链接依赖
从 /some/lib 中的共享库 libA.so 开始。 我构建的库(libB.so)依赖于 libA.so 中的功能。因此,在创建 libB.so 时,我在 g++ 命令行上包含 -L/some/lib -lA 。 libB.so 也将驻留在 /some/lib 中。
现在,我正在构建一个将使用 libB.so 的可执行文件。我向 g++ 链接器提供了预期的 -L/some/lib 和 -lB 。但我收到错误,因为它找不到“libA.so”。如果我将“-lA”添加到链接器行,程序就会链接。
我不明白为什么它找不到“libA.so”。我当然不明白为什么在链接器行中包含“-lA”可以让它找到它。它似乎已经知道它需要 libA.so,并且 libA.so 与 libB.so 位于同一路径中。
有人可以解释一下吗?我不喜欢必须在每个想要链接 libB.so 的可执行文件中显式放置“-lA”的想法。我还做错了什么吗?
Start with shared library libA.so that is in /some/lib.
I build library (libB.so) that depends on a capability in libA.so. So, when creating libB.so, I include -L/some/lib -lA on the g++ command line.
libB.so will also reside in /some/lib.
Now, I'm building an executable that will use libB.so. I provide the expected -L/some/lib and -lB to the g++ linker. But I get an error because it can't find "libA.so". If I add "-lA" to the linker line, the program links.
I don't understand why it doesn't find "libA.so". I certainly don't understand why including "-lA" on the linker line lets it find it. It appears to already know that it needs libA.so, and libA.so is in the same path as libB.so.
Can someone explain this? I don't like the idea of having to explicitly put "-lA" in every executable that wants to link libB.so. Did I do something else wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您仅链接
libB
时,链接器会查找libA
,但找不到它,因为它不在链接器/加载器的可找到路径中。您必须在链接阶段设置LD_LIBRARY_PATH
(和/或LD_RUN_PATH
),或者使用-rpath /some/链接
。libB
库假设
libB
本身就是一个可执行文件,我们称之为foo
。您不能只在命令行中输入./foo
,因为找不到libA
(检查ldd foo
以检查加载器路径) )。相反,您需要使用 rpath 进行编译。 (在
g++
中,您可以说g++ -Wl,-rpath,/some/lib ...
将选项传递给链接器。)相同的加载时间解析过程适用于动态库本身。While you are linking against
libB
only, the linker looks forlibA
, but cannot find it, because it isn't in a findable path for the linker/loader. You have to setLD_LIBRARY_PATH
(and/orLD_RUN_PATH
) during the linking stage, or otherwise linklibB
with-rpath /some/lib
.Just pretend for a minute that
libB
is itself an executable, let's call itfoo
. You couldn't just say./foo
at the command line becauselibA
wouldn't be found (checkldd foo
to examine the loader paths). Instead, you needor you need to compile with
rpath
. (Ing++
, you'd sayg++ -Wl,-rpath,/some/lib ...
to pass the option to the linker.) The same load-time resolution process applies to dynamic libraries themselves.