How to keep a specific symbol in binary file?

I have a static lib ( my_static_lib ) which I link to an executable binary file. Some of the symbols, but not all, are used in my binary.

A second library, dynamically loaded( my_shared_lib ), is expecting to receive some symbols from my_static_lib through symbol injection from the binary. But those symbols are not used by my_binary, so they are stripped off the final bin file.

So, at runtime, my_shared_lib complains that it cannot find __my_stripped_symbols__ and crashes.

Is there a way to force the linker to keep __my_stripped_symbols__ ? I would prefer something that can be cleanly written in a Makefile.am (autotools)

(-binary file makefile)
-L$(top_builddir)/static_lib -lmy_static_lib --magic-flag-to-keep-stripped-symbol

I do not want to link my_static_lib with my_shared_lib because it will generate strange conflicts in other parts of a rather complex group of executables/shared libraries.


When you link my_static_lib to your application, you want to use the --whole-archive option. It's documented in the ld options docs.

If you're linking with gcc, it looks something like this:

-L$(top_builddir)/static_lib -Wl,-whole-archive -lmy_static_lib -Wl,-no-whole-archive

That will make sure the entire library is kept, and not just the specific functions that your executable uses.

You also need to make sure that the symbols get exported. If the symbols from your static library aren't being exported already, you make need a combination of -fvisibility=hidden and use __attribute__ ((visibility("default"))) to mark up the ones you want exported. You can read a little more about it in the gcc docs

链接地址: http://www.djcxy.com/p/53302.html

上一篇: 链接器选项列出使用的库

下一篇: 如何在二进制文件中保留特定的符号?