共享库与依赖关系的动态链接 [英] Dynamic Linking of Shared Libraries with Dependencies

查看:361
本文介绍了共享库与依赖关系的动态链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有动态链接具有依赖关系的共享库的方法?

Is there a way to dynamically link shared libraries that have dependencies?

例如,我有两个库libA.so和libB.so。 libB.so调用在libA.so中定义的函数。

For example, I have two libraries, libA.so and libB.so. libB.so calls functions defined in libA.so.

在我的主程序中,我希望用dlopen加载这两个库。但是,如果我尝试:

In my main program, I wish to load the two libraries with dlopen. However, if I try:

dlopen(libA.so);
dlopen(libB.so);

然后第二个dlopen会失败,因为libB有无法识别的符号。

Then the second dlopen will fail as libB has unrecognized symbols.

我可以想到几个解决方法,例如将所有的目标文件构建到一个共享库中,或者让libB.so在libA.so上调用dlopen,但这是额外的工作。

I can think of a few workarounds such as building all the object files into a single shared library, or to have libB.so call dlopen on libA.so, but that's extra work.

我想我的想法这种工作方式就像在内核模块的情况下,你可以使用EXPORT_SYMBOL()允许其他模块调用以前加载的模块中定义的函数。

I guess the way I'm imagining this to work is like in the case of kernel modules where you can use "EXPORT_SYMBOL()" to allow other modules to call functions defined in a previously loaded module.

可以使用共享库进行类似的操作吗?

Can something similar be done with shared libraries? Or will I have to use my workarounds?

推荐答案

我经历过类似的情况,这对我有用(使用gcc工具链):

I experienced a similar situation, this is what worked for me (using a gcc toolchain):

当您创建共享对象 libB.so 时,您无条件地链接库 libA.so ,命令应如下所示:

When you create the shared object libB.so, you unconditionally link the library libA.so, the command should look like this:

gcc -shared -Wl,--no-as-needed -lA -o libB.so b.o

然后可以检查 libA.so 确实成为动态链接器的依赖关系:

You can then check that libA.so indeed became a dependency for the dynamic linker:

$ ldd libB.so
    linux-gate.so.1 =>  (0xb77ba000)
    libA.so => not found
    libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xb75f7000)
    /lib/ld-linux.so.2 (0xb77bb000)

在您的主程序中,只需 dlopen() libB.so ,其他库应由动态链接器自动链接。

In your main program it should be sufficient to only dlopen() the library libB.so, and the other library should get linked automatically by the dynamic linker.

这篇关于共享库与依赖关系的动态链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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