Richard Johnson
Richard Johnson

Reputation: 612

gcc change the search order for libraries

I have a build where I wish to link against and load a specific version of a library and a different version of the same library is installed on the system. I'm using a -L option to point to the version that I wish to link against but gcc still seems to choose the installed version. Is there a way to force gcc to search the directory specified with the -L option before it searches the standard locations?

I'm running Centos 6.5 with gcc 4.4.7. Here are the relevant libs and directories zlib-devel is not installed

/lib64/libz.so.1.2.3
/lib64/libz.so.1 -> libz.so.1.2.3

/home/richj/product/zlib/lib/libz.so.1.2.8
/home/richj/product/zlib/lib/libz.so -> libz.so.1.2.8
/home/richj/product/zlib/lib/libz.so.1 -> libz.so.1.2.8
/home/richj/product/zlib/include/zlib.h

/home/richj/product/foo/libfoo.so
/home/richj/product/foo/foo.h

/home/richj/product/bar/bar.c

Main in bar.c calls foo in libfoo.so and foo calls inflateInit in libz Here are the compile commands for libfoo.so and bar. Both the library and the program compile and run without error.

/usr/bin/gcc -c -fPIC -Wall -g -I../zlib/include foo.c
/usr/bin/gcc -shared -o libfoo.so foo.o

/usr/bin/gcc -Wall -g -I../foo -L../foo -lfoo -L../zlib/lib -lz bar.c bar

$ldd bar
    linux-vdso.so.1 => (0x00007fffd67ff000)
    libfoo.so => ../foo/libfoo.so
    libz.so.1 => /lib64/libz.so.1
    libc.so.6 => /lib64/libc.so.6
    /lib64/ld-linux-x86-64.so.2

So the question is why is it not linking against and loading the version of zlib that I point to in the compile command?

Upvotes: 1

Views: 472

Answers (1)

Sean Perry
Sean Perry

Reputation: 3886

Passing -L/path/to/libs to gcc helps the compiler know where to look. This information is not baked into the compiled output unless you request it to be. Otherwise the binary would potentially only work on the system it was compiled on.

All you need to do is add -Wl,rpath,/path/to/library to the linking command. This will set the rpath in the program so that when the shared library loaders starts looking for the libraries needed it will know that there is an extra place to look.

As an aside, if this location is a place that you install libraries in and expect many programs to use you can also add a file in /etc/ld.so.conf.d which contains just the full path to the directory containing the libraries. This will allow all programs using the shared library loader to work without embedding the rpath in each and every one of them.

Upvotes: 2

Related Questions