Gcc linker search path order

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 -o 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?

On your system does gcc generate 64 bit image code by default? -m64
sets 64 bit. Most systems default to 32 bit - the ones I have anyway.

Suppose you have

gcc -o ./foo.so foo.c -L/path/to/mylib -fPIC

gcc reads thru objects and library lists from left to right during linking. It uses implicit libraries only after the list is exhausted. So the only reason I can see from what you gave is that gcc thinks it needs to link 32bit. I do not get why you are not getting errors.

Does the runtime linker/loader know about /home/richj/product/zlib/lib/?

Regards,
Alister

That would be:

export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/home/richj/product/zlib/lib

LD_LIBRARY_PATH was generally meant for runtime not compile time - that is up to you with -L. Using an oddball version of a generally standard library is the path to future problems. I would link against the archive (.a) rather than the .so -- if you plan to move it to other boxes.

If, in fact, the problem is that the loader's lookup process is finding the default system library, an alternative to modifying the environment, and to using -L and -l, is to provide an absolute path to the library. If a dependency contains a slash, the loader will not perform a lookup.

Regards,
Alister