Include static lib in dynamic lib

最后都变了- 提交于 2019-12-13 15:02:50

问题


I have the following problem :

  • several object files a1.o, a2.o, a3.o, ...
  • an archive libxxxx.a. The archive libxxxx.a only contains object files : b1.o, b2.o etc...

I would like to create a shared library (.so) from all the object files.

Problem : If I use :

g++ -shared libxxxx.a a1.o a2.o ... -o libnew.so

g++ does understand that I want to link with the static library libxxxx.a and does not include all the symbols of the archive.

A simple workaround is to first expand the archive using ar -x and then create the lib but it's not really "elegant".

There must be a simple command to force g++ to include the whole archive in the .so but I can't find it.

Thanks for your help.


回答1:


From man ld:

--whole-archive
For each archive mentioned on the command line after the --whole-archive option, include every object file in the archive in the link, rather than searching the archive for the required object files. This is normally used to turn an archive file into a shared library, forcing every object to be included in the resulting shared library. This option may be used more than once.

Two notes when using this option from gcc: First, gcc doesn't know about this option, so you have to use -Wl,-whole-archive. Second, don't forget to use -Wl,-no-whole-archive after your list of archives, because gcc will add its own list of archives to your link and you may not want this flag to affect those as well.

Example:

g++ -shared -o yourlib a.o. b.o. c.o -Wl,-whole-archive libstatic.a -Wl,-no-whole-archive

Note also that in your example you first put static library, then the object files - in this case the symbols used in the object files and defined in static library will not be found unless you use --whole-archive linker option. If you want to include just the needed symbols from the static library, you need to put it after the object files.

g++ -o your_app a.o b.o c.o -lyour_static_lib


来源:https://stackoverflow.com/questions/3752902/include-static-lib-in-dynamic-lib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!