LD_LIBRARY_PATH does not work in ld.

  • It seems man ld(1) says that LD_LIBRARY_PATH is used for search-path of shared libraries. But it seems LD_LIBRARY_PATH does not work in ld.
  • In fact the explanation in man page doesn't mean like that. If a linked shared library uses another one, LD_LIBRARY_PATH is used. Do not confuse these difference :) "-rpath-link" option can be used for the same purpose. "-rpath-link" has higher priority.

Example

  • main.c uses libtest1.so
  • libtest1.so uses libtest2.so

1. In case there is dependency from libtest1 to libtest2.


$ gcc -shared -fPIC test2.c -o libtest2.so
$ gcc -shared -fPIC test1.c -o libtest1.so -ltest2 -L.
$ ldd libtest1.so
linux-vdso.so.1 => (0x00007fff4bfff000)
libtest2.so => /home/user/hoge/libtest2.so (0x00007f96de0f3000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f96ddd42000)
/lib64/ld-linux-x86-64.so.2 (0x00007f96de4f9000)
$ gcc -c main.c -o main.o
$ gcc main.o -ltest1 -L .
/usr/bin/ld: warning: libtest2.so, needed by /home/user/hoge/libtest1.so, not found (try using -rpath or -rpath-link)
/home/user/hoge/libtest1.so: undefined reference to `func_in_litest2'
$ export LD_LIBRARY_PATH=`pwd`
$ gcc main.o -ltest1 -L .
$

2. In case there is no dependency information written in libtest1.so. It is required to specify -ltest2 explicitly.


$ gcc -shared -fPIC test2.c -o libtest2.so
$ gcc -shared -fPIC test1.c -o libtest1.so
$ ldd libtest1.so
linux-vdso.so.1 => (0x00007fff4bfff000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f96ddd42000)
/lib64/ld-linux-x86-64.so.2 (0x00007f96de4f9000)
$ gcc -c main.c -o main.o
$ export LD_LIBRARY_PATH=`pwd`
$ gcc main.o -ltest1 -L .
./libtest1.so: undefined reference to `func_in_libtest2'
$ gcc main.o -ltest1 -ltest2 -L.
$

  • When gcc is used for link, LIBRARY_PATH (not LD_LIBRARY_PATH) can be used instead of "-L" option.


$ gcc -shared -fPIC test.c -o libtest.so
$ export LIBRARY_PATH=`pwd`
$ gcc main.c -ltest