Linking dependency
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 i开发者_如何转开发t 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?
While you are linking against libB
only, the linker looks for libA
, but cannot find it, because it isn't in a findable path for the linker/loader. You have to set LD_LIBRARY_PATH
(and/or LD_RUN_PATH
) during the linking stage, or otherwise link libB
with -rpath /some/lib
.
Just pretend for a minute that libB
is itself an executable, let's call it foo
. You couldn't just say ./foo
at the command line because libA
wouldn't be found (check ldd foo
to examine the loader paths). Instead, you need
LD_LIBRARY_PATH=/some/lib ./foo
or you need to compile with rpath
. (In g++
, you'd say g++ -Wl,-rpath,/some/lib ...
to pass the option to the linker.) The same load-time resolution process applies to dynamic libraries themselves.
精彩评论