Reputation: 16805
When I'm dynamically linking on a Unix/Linux based system, where will it try to find the library files when I execute the program, and how do I change this? I am using the GNU/G++ compiler.
Upvotes: 0
Views: 362
Reputation: 59416
The system the program runs on defines where to search for the dynamic libraries. The program itself just names the libraries (without path).
On Linux systems there is a system-wide default where to search and you can override this by setting the environment variable LD_LIBRARY_PATH
to a colon-separated list of paths to the libraries:
$ LD_LIBRARY_PATH=/path/to/my/libs/:/another/path/to/libs/of/mine/
$ export LD_LIBRARY_PATH
$ ./path/to/my/executable
or shorter:
$ LD_LIBRARY_PATH=/path/to/my/libs/:/another/path/to/libs/of/mine/ ./path/to/my/executable
The system default is configured using ldconfig
and typically based on the files found at /etc/ld.so.conf
(pointing to /etc/ld.so.conf.d
) and /etc/ld.so.cache
.
Which dynamic libraries a given executable is going to need can be examined using ldd
:
$ ldd /bin/ls
linux-vdso.so.1 => (0x00007fffc83ff000)
libselinux.so.1 => /lib/x86_64-linux-gnu/libselinux.so.1 (0x00007fbe1306b000)
librt.so.1 => /lib/x86_64-linux-gnu/librt.so.1 (0x00007fbe12e63000)
libacl.so.1 => /lib/x86_64-linux-gnu/libacl.so.1 (0x00007fbe12c5a000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fbe1289b000)
libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007fbe12697000)
/lib64/ld-linux-x86-64.so.2 (0x00007fbe132ae000)
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fbe12479000)
libattr.so.1 => /lib/x86_64-linux-gnu/libattr.so.1 (0x00007fbe12274000)
You can also use the output of strace
when starting the executable to see where the system looks for libraries:
$ strace ls 2>&1 | grep '^open.*\.so'
open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libselinux.so.1", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/librt.so.1", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libacl.so.1", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libdl.so.2", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libpthread.so.0", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libattr.so.1", O_RDONLY|O_CLOEXEC) = 3
Upvotes: 2