user4757345 user4757345 - 3 months ago 8
C Question

cannot open shared object file: No such file or directory error while there is file

I try to create shared library and compile my

main.c
with this library

I follow this web site : http://www.yolinux.com/TUTORIALS/LibraryArchives-StaticAndDynamic.html

I give these commands :

gcc -fPIC -c *.c
gcc -shared -Wl,-rpath,/opt/lib -Wl,-soname,libctest.so.1 -o libctest.so.1.0 *.o
sudo mv libctest.so.1.0 /opt/lib
sudo ln -sf /opt/lib/libctest.so.1.0 /opt/lib/libctest.so
sudo ln -sf /opt/lib/libctest.so.1.0 /opt/lib/libctest.so.1
gcc -Wall -L/opt/lib main.c -lctest -o prog


Commands gave no error. When I execute binary file
./prog
it gives
./prog: error while loading shared libraries: libctest.so.1: cannot open shared object file: No such file or directory


but
libctest.so.1
is in
/opt/lib


lrwxrwxrwx 1 root root 24 Aug 18 17:06 libctest.so -> /opt/lib/libctest.so.1.0
lrwxrwxrwx 1 root root 24 Aug 18 17:06 libctest.so.1 -> /opt/lib/libctest.so.1.0
-rwxr-xr-x 1 user user 7064 Aug 18 17:05 libctest.so.1.0


Also
ldd prog
is

linux-vdso.so.1 (0x00007ffe0f559000)
libctest.so.1 => not found
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fcd27fc6000)
/lib64/ld-linux-x86-64.so.2 (0x00007fcd28371000)


so what is wrong ?

Thanks.

I used
debian 8.5
and
gcc 4.9.2

Answer

GCC's ld command has an --rpath option that may solve your problems:

-rpath=dir
       Add a directory to the runtime library search path.

You should add the location of your compiled library to GCC's command line when you compile prog, via the -wl option:

-Wl,option
       Pass option as an option to the linker. If option contains commas,
       it is split into multiple options at the commas.

So your search path already includes /opt/lib because of the original creation of the library:

-Wl,-rpath,/opt/lib

For the second compile, add the location of libctest.so.1.0 as another rpath, and it should be found without your needing to move files around:

gcc -Wall -L/opt/lib main.c -lctest -Wl,-rpath,/you/dir/name -o prog

I think your original effort is failing as the linker has included a hard path to your original outout dir, and then you moved the library from under it.