问题
I have a C library in an archive file, clib.a
. I've written a C++ wrapper for it, cpp.o
, and would like to use this as a static library:
ar cTrvs cppwrap.a clib.a cpp.o
Code which links to this won't be able to use the stuff from clib.a
directly unless the correct header is included. However, if someone coincidentally creates an appropriate prototype -- e.g. void myCoincidentallyNamedGlobalFunction()
-- I'm concerned which definition of myCoincidentallyNamedGlobalFunction
will apply.
Since the symbols from clib.a
only need to be accessed in cpp.o
, and not anything linked to cppwrap.a
, is there a way to completely hide them so that there is no possible collision (so even including the clib header would fail)?
回答1:
You can manually remove unneeded symbols on the final combined library:
$ objcopy -N foo cppwrap.a
(remove symbol)
Or, if you need the symbols but want to make sure that external users can't get to them:
$ objcopy -L bar cppwrap.a
(localize symbol)
Or, if a symbol in clib.a
must be visible by something in cpp.o
but you don't want it to be used by anyone else:
$ objcopy -W baz cppwrap.a
(weaken symbol)
In this case, collisions with symbols from other object files/libraries will defer to their usage, even though the symbol will still be visible. To obscure things further or to reduce chances of even a deferential collision, you can also use:
$ objcopy --redefine-sym old=new cppwrap.a
An anonymous namespace may help in some cases, but not if there's functionality that your wrapper needs but is trying to hide from external users.
来源:https://stackoverflow.com/questions/23678896/limiting-the-scope-of-global-symbols-from-linked-objects