Search code examples
ld

How does `ld` find secondary dependencies for shared objects?


I have a situation where we link to some shared library libfoo.so, that in turn depends on libbar.so. In case we link an executable that depends on libfoo.so directly we compile it by giving the flags:

-L<location of libbar.so> -lfoo

This however picks up a libbar.so in the system path instead of the location specified on the command line with the incorrect set of symbols resulting in undefined references. If we change the command to:

-L<location of libbar.so> -lfoo -lbar

The right libbar.so is found by ld. Is this to be expected? How can we tell ld to find a secondary dependency in some location without explicitly linking to it?


Solution

  • If you do not specify -lbar, the indirect dependent libbar is added implicitly. In this case the compile time linking search mechanism for this library is different (it is then similar how the runtime linker ld.so would search the library at runtime). Have a look at the -rpath-link option in the ld manual. There you can see that searching in -L directorys for this case is only done on SunOs systems. The best way to specify a compile time linking search path for indirect dependencies ist to use the -rpath-link option, because this has the highest search priority.