Linux 在构建期间将静态库链接到共享库?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14889941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Link a static library to a shared one during build?
提问by Elmi
I have a problem building a shared library with GCC/Linux. Currently this shared library is created with GCC/libtool option "-shared" and everything is fine.
我在使用 GCC/Linux 构建共享库时遇到问题。目前这个共享库是用 GCC/libtool 选项“-shared”创建的,一切都很好。
Now there are two additional, static libraries (.a-files) that have to be added to this shared one since they provide some functionality that is required by the shared one. Adding these static libraries with option "-l" does not help, afterwards they are not part of the .so file.
现在有两个额外的静态库(.a 文件)必须添加到这个共享库中,因为它们提供了共享库所需的一些功能。使用选项“-l”添加这些静态库无济于事,之后它们不是 .so 文件的一部分。
So how can I force GCC/libtool to really add the code of these static libraries to the shared library?
那么如何强制 GCC/libtool 真正将这些静态库的代码添加到共享库中呢?
Thanks!
谢谢!
采纳答案by Dmitry Yudakov
You need --whole-archive
linker option in this case to command the linker to include whole static libs' content into the shared lib.
--whole-archive
在这种情况下,您需要链接器选项来命令链接器将整个静态库的内容包含到共享库中。
g++ -shared sample.o -o libSample.so -Wl,-whole-archive -lmylib1.a -lmylib2.a -Wl,-no-whole-archive
From man ld
:
来自man ld
:
For each archive mentioned on the command line after the --whole-archiveoption, 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-archiveafter 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.
对于--whole-archive选项后命令行中提到的每个存档,将存档中的每个目标文件都包含在链接中,而不是在存档中搜索所需的目标文件。这通常用于将存档文件转换为共享库,强制将每个对象都包含在生成的共享库中。此选项可以多次使用。
从 gcc 使用此选项时有两个注意事项:首先,gcc 不知道此选项,因此您必须使用 -Wl,-whole-archive。其次,不要忘记在您的档案列表之后使用-Wl,-no-whole-archive,因为 gcc 会将其自己的档案列表添加到您的链接中,您可能不希望此标志也影响这些。
回答by robert
You only need the --whole-archiveparameter to forcethe linker to include the library, but it should be able to infer its own needs from unmatched symbols.
您只需要--whole-archive参数来强制链接器包含库,但它应该能够从不匹配的符号中推断出自己的需求。
Ensure that any static libraries on the command-line come after their dependent object-files e.g.:
确保命令行上的任何静态库都在其依赖对象文件之后,例如:
g++ -Wl,-E -g -pipe -O2 -pipe -fPIC myobjectfile.o mystaticlibrary.a -shared -o mylib.so