building a shared object library: ldd does not show specified name

3k views Asked by At

I'm trying to build a shared object library on Debian

cat /etc/issue
Debian GNU/Linux 9 \n \l

I build the library and object as normal (wrap.c serves as a wrapper to create all object files)

gcc -c -fPIC -W -Wall -O2 -funroll-loops wrap.c
gcc -shared -Wl,-soname,libtest.so -o libtest.so *.o
mv libtest.so /usr/local/lib/ && mv test-header.h /usr/local/include/

I then create a test.c to pull in the library and compile successfully as follows:

gcc test.c -ltest

However, running the program ./a.out returns the following error:

./a.out: error while loading shared libraries: libtest.so: cannot open shared object file: No such file or directory

Inspecting the .so, I see:

$ ldd /path/to/libtest.so
    linux-vdso.so.1 (0x00007ffdb71c5000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f1c22fba000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f1c23560000)

I don't even see libtest.so => none, which at least would tell me it can't find the library.

I'm not really sure what's going on here.

I am to successfully create a .dylib on macOS with the same process (with gcc -dynamiclib -o libtest.dylib *.o), and I can successfully call the library in an executable. I'm not sure what's different on Debian.

1

There are 1 answers

2
Mike Kinghan On BEST ANSWER

The shared library libtest.so that you have placed in /usr/local/lib will be located by linker in the command

gcc test.c -ltest

because /usr/local/lib is one the linker's default search paths.

However, it will not be located there by the runtime loader when you attempt to run ./a.out because the runtime loader does not search directories directly other than those listed in the value of the variable LD_LIBRARY_PATH, if any, in the current environment. By default it searchs the libraries registered in the ldconfig cache, and that cache is updated to register newly appeared libraries only by running ldconfig (as root).

So to run your program you have two options:-

For success in your current shell, run:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib; ./a.out

For lasting success, run:

sudo ldconfig

Then your program will run in any shell.

BTW, ldd /path/to/libtest.so tells you, of course, the shared library dependencies of libtest.so. That's not going to tell you why running ./a.out fails to find /path/to/libtest.so itself. To see the shared library dependencies of a.out, run ldd a.out