如何强制将静态库中的符号包含在共享库构建中? [英] How to force symbols from a static library to be included in a shared library build?

查看:209
本文介绍了如何强制将静态库中的符号包含在共享库构建中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试构建一个共享对象库,该对象库将由程序使用dlopen()打开。此库将使用由静态单独库提供的功能。



在链接行中包含适当的标志以在链接动态库时引入静态库(例如,我对libfoo.a有-lfoo),链接器不会发出抱怨。但是,当主程序在动态库上调用dlopen()时,调用失败,并引用静态库中的符号的未定义符号消息。



运行nm确实在动态库中未定义符号,并且主程序没有包含它,所以如何强制链接器将此符号拉入?该符号本身位于未初始化的数据部分(nm输出中的符号类型B)。

解决方案 - 整个存档链接器选项应该这样做。你可以使用它作为例如

  gcc -o libmyshared.so foo.o -lanothersharedlib -Wl, - 整个归档-lmystaticlib 

您遇到的情况是,默认情况下,链接器将在静态中搜索符号存档您生成的二进制文件需要,如果需要的话,它将包含符号所在的整体。如果您的共享库不需要任何符号,它们将不会包含在共享库中。

请记住,成为共享库的代码需要使用特殊选项进行编译,例如 -fpic ,因为您在共享库中包含静态库,所以需要使用相同的选项编译静态库。


I'm trying to build a shared object library that will be opened by a program using dlopen(). This library will use functionality provided by a separate library that is static.

I have included the appropriate flag on the link line to pull in the static library when linking the dynamic one (e.g. I have -lfoo for libfoo.a), and the linker doesn't complain. However, when the main program calls dlopen() on the dynamic library, the call fails with an "undefined symbol" message referencing a symbol from the static library.

Running nm does indicate that the symbol in question is undefined in the dynamic library, and the main program doesn't contain it, so how can I force the linker to pull this symbol in? The symbol itself is in the uninitialized data section (symbol type "B" in the nm output).

解决方案

The --whole-archive linker option should do this. You'd use it as e.g.

gcc -o libmyshared.so foo.o -lanothersharedlib -Wl,--whole-archive -lmystaticlib

What you're experiencing is that by default, the linker will search for symbols in a static archive that the binary you produce needs, and if it needs one, it'll include the whole .o that the symbol resides in. If your shared library doesn't need any of the symbols, they will not be included in your shared lib.

Remember that code that becomes a shared library needs to be compiled with special options, such as -fpic , as you're including a static library in your shared library, the static library needs to be compiled with the same options.

这篇关于如何强制将静态库中的符号包含在共享库构建中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆