我如何始终包含来自静态库的符号? [英] how do I always include symbols from a static library?

查看:55
本文介绍了我如何始终包含来自静态库的符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个静态库libx.a.如何从该库中创建一些符号(不是全部),使其始终以 的形式出现在与该库链接的任何二进制文件中?原因是我需要这些符号可以通过dlopen + dlsym使用.我知道--whole-archive链接器开关,但是它会强制将库归档文件中的所有目标文件链接到生成的二进制文件中,这不是我想要的...

Suppose I have a static library libx.a. How to I make some symbols (not all) from this library to be always present in any binary I link with my library? Reason is that I need these symbols to be available via dlopen+dlsym. I'm aware of --whole-archive linker switch, but it forces all object files from library archive to linked into resulting binary, and that is not what I want...

到目前为止的观察(CentOS 5.4,32位)(更新:此段是错误的;我无法重现此行为)

Observations so far (CentOS 5.4, 32bit) (upd: this paragraph is wrong; I could not reproduce this behaviour)

ld main.o libx.a

会很高兴地删除所有未引用的符号,而

will happily strip all non-referenced symbols, while

ld main.o -L. -lx

将链接整个库.我想这取决于所用binutils的版本,但是较新的链接器将能够从静态库中挑选单个对象.

will link whole library in. I guess this depends on version of binutils used, however, and newer linkers will be able to cherry-pick individual objects from a static library.

另一个问题是如何在Windows下实现相同的效果?

Another question is how can I achieve the same effect under Windows?

先谢谢了.任何提示将不胜感激.

Thanks in advance. Any hints will be greatly appreciated.

推荐答案

假设您有一个项目,该项目在同一文件夹中包含以下三个C文件;

Imagine you have a project which consists of the following three C files in the same folder;

// ---- jam.h
 int jam_badger(int);

// ---- jam.c
 #include "jam.h"
 int jam_badger(int a)
 {
   return a + 1;
 }

 // ---- main.c
 #include "jam.h"
 int main()
 {
   return jam_badger(2);
 }

然后使用boost-build bjam文件进行构建;

And you build it with a boost-build bjam file like this;

lib jam : jam.c <link>static ;

lib jam_badger : jam ;

exe demo : jam_badger main.c ;

您将收到这样的错误.

undefined reference to `jam_badger'

(我在这里使用bjam是因为该文件更易于阅读,但是您可以使用任何您想使用的东西)

(I have used bjam here because the file is easier to read, but you could use anything you want)

删除"static"会生成一个有效的二进制文件,就像将static添加到另一个库一样,或者只是使用一个库(而不是笨拙地包装在另一个库中)

Removing the 'static' produces a working binary, as does adding static to the other library, or just using the one library (rather than the silly wrapping on inside the other)

发生这种情况的原因是因为ld足够聪明,只能选择实际使用的归档部分,在这种情况下,它们都不是.

The reason this happens is because ld is clever enough to only select the parts of the archive which are actually used, which in this case is none of them.

解决方案是用-Wl,-whole-archive和-Wl,-no-whole-archive包围静态档案,像这样;

The solution is to surround the static archives with -Wl,--whole-archive and -Wl,--no-whole-archive, like so;

g++ -o "libjam_candle_badger.so" -Wl,--whole-archive libjam_badger.a Wl,--no-whole-archive

不太确定如何获得boost-build的帮助,但是您明白了.

Not quite sure how to get boost-build to do this for you, but you get the idea.

这篇关于我如何始终包含来自静态库的符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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