There are two answers to this question, part of the answer lies in the compile-time linking (i.e gcc -lfoo -L/usr/lib
... which in turn calls ld
), and run-time linker lookups.
When you compile your program, the compiler checks syntax, and then the linker ensures that the symbols required for execution exist (i.e variables / methods / etc), among other things. LD_LIBRARY_PATH
, as has been noted, has the side-effect of altering the way gcc
/ld
behave as well as the way the the run-time linker behaves by modifying the search path.
When you run your program, the run-time linker actually fetches the shared libraries (on disk or from memory if possible), and loads in the shared symbols / code / etc. Again, LD_LIBRARY_PATH
affects this search path implicitly (sometimes not a good thing, as has been mentioned.)
The correct fix for this without using LD_LIBRARY_PATH
on most Linux systems is to add the path that contains your shared libraries to /etc/ld.so.conf
(or in some distributions, create a file in /etc/ld.so.conf.d/
with the path in it) and run ldconfig
(/sbin/ldconfig
as root) to update the runtime linker bindings cache.
Example on Debian:
jewart@dorfl:~$ cat /etc/ld.so.conf.d/usrlocal.conf
/usr/local/lib
Then when the program is executed, the run-time linker will look in those directories for libraries that your binary has been linked against.
If you want to know what libraries the run-time linker knows about, you can use:
jewart@dorfl:~$ ldconfig -v
/usr/lib:
libbfd-2.18.0.20080103.so -> libbfd-2.18.0.20080103.so
libkdb5.so.4 -> libkdb5.so.4.0
libXext.so.6 -> libXext.so.6.4.0
And, if you want to know what libraries a binary is linked against, you can use ldd
like such, which will tell you which library your runtime linker is going to choose:
jewart@dorfl:~$ ldd /bin/ls
linux-vdso.so.1 => (0x00007fffda1ff000)
librt.so.1 => /lib/librt.so.1 (0x00007f5d2149b000)
libselinux.so.1 => /lib/libselinux.so.1 (0x00007f5d2127f000)
libacl.so.1 => /lib/libacl.so.1 (0x00007f5d21077000)
libc.so.6 => /lib/libc.so.6 (0x00007f5d20d23000)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…