假设我想创建一个动态库 dynamic.so
,但我的代码引用了其他静态库 static.a
中存在的函数。当然,如果我使用 g++
和 -shared
选项进行编译和链接,dynamic.so
将期望引用的函数在其他一些中实现我必须在运行时将其与dynamic.so
链接在一起的动态库。换句话说,只要我执行-l static
(取模语法),它就会很高兴。
但由于另一个库实际上是静态库,所以我不能这样做。假设我也无法在主程序编译时链接静态库,但我被迫只使用动态库。所以我真正想要的是将编译后的代码包含在 dynamic.so
中的 static.a
引用的函数中。
相关问题的这个答案建议使用 --whole-archive
选项来包含 dynamic.so
中的 >static.a。然而,就我而言,static.a
很大。我真的不需要所有这些,我只需要一个函数定义。
另一个问题的答案解释了在编译时链接到静态库意味着仅包含实际引用的代码在二进制文件中。好吧,这正是我想要为我的单一函数参考做的事情!我真的不想把整个静态档案放在那里。
但我怎样才能做到这一点呢?如何在 dynamic.so
中仅包含 static.a
所需的部分?
Let's say I want to create a dynamic library dynamic.so
, but my code references a function that exists in some other, static library static.a
. Naturally, if I compile and link with g++
and the -shared
option, dynamic.so
will expect the referenced function to be implemented in some other dynamic library that I would have to link at runtime together with dynamic.so
. In other words, it will be happy as long as I do -l static
(modulo syntax).
But since that other library is actually a static one, I cannot do that. Let's assume I can not link the static library at compile time of my main program either, but I'm forced to only use dynamic libraries. So what I really want is to include the compiled code off the referenced function from static.a
in dynamic.so
.
This answer to a related question suggests using the --whole-archive
option to include static.a
in dynamic.so
. However, in my case, static.a
is huge. And I really don't need all of it, I only need that one function definition.
This answer to another question explains that linking to a static library at compile time means that only the code that is actually referenced gets included in the binary. Well, this is exactly what I would like to do for my single function reference! I don't really want the whole static archive in there.
But how can I achieve that? How can I include just the required parts of static.a
in dynamic.so
?
发布评论
评论(1)
您不需要
--whole-archive
:只需像这样链接dynamic.so
即可:这将从
libstatic 中拉入链接器需要的任何内容。 .a.
请参阅此说明了解原因。一个问题可能是您的
libstatic.a
是在没有-fPIC
的情况下编译的。在 32 位 x86/Linux 上,这仍然有效(尽管如果多个进程正在使用您的库,则不会为您节省太多 RAM)。在x86_64
上,无法将非 fPIC 代码链接到共享库,因此您必须使用-fPIC
重新构建它。You don't need
--whole-archive
: just link yourdynamic.so
like this:This will pull into dynamic.so anything the linker needs from
libstatic.a.
See this explanation to understand why that is.One problem might be that your
libstatic.a
is compiled without-fPIC
. On 32-bitx86/Linux
, that would still work (though your library will not be saving you much RAM if multiple processes are using it). Onx86_64
, linking non-fPIC code into a shared library can't work, so you'll have to rebuild it with-fPIC
.