There are two answers to this question: part of the answer is to compile-time binding ( gcc -lfoo -L/usr/lib ... which in turn calls ld ) and looking for a run-time linker.
When you compile your program, the compiler checks the syntax, and then the linker ensures that the characters necessary for execution exist (for example, variables / methods / etc), among other things. LD_LIBRARY_PATH , as noted, has a side effect of changing the behavior of gcc / ld , as well as the way that the runtime linker behaves by changing the search path.
When you run your program, the runtime linker actually extracts the shared libraries (on disk or from memory, if possible) and loads into common characters / code / etc. Again, LD_LIBRARY_PATH affects this search path implicitly (sometimes this is not very good, as already mentioned).
The correct fix for this without using LD_LIBRARY_PATH for most Linux systems is to add the path that contains your shared libraries to /etc/ld.so.conf (or on some distributions, create a file in /etc/ld.so.conf.d/ using the path in it) and run ldconfig ( /sbin/ldconfig as root) to update the runtime linker binding cache.
Debian example:
jewart@dorfl:~$ cat /etc/ld.so.conf.d/usrlocal.conf /usr/local/lib
Then, when the program executes, the runtime linker will look in these directories for the libraries that your binary was associated with.
If you want to know what libraries the runtime 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 the binary libraries are associated with, you can use ldd as such, which will tell you which library your runtime linker will be selected in:
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)