Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hard code a dynamic library path on Linux

I would like to hard code the path to a library in my executable, in Linux. On OS X this is achieved by providing the full path after the -o argument when building the library. For example, I build a library like this on OS X:

cc foo.c --shared -o /home/sander/libfoo.so

When I build an executable called 'bar' that links with this library, and I use otool -L on the executable, I get this output:

bar:
    /home/sander/libfoo.so (compatibility version 0.0.0, current version 0.0.0)

I can now run this executable from anywhere, and it is always able to find the library.

I am looking for equivalent functionality on Linux with gcc. I'd rather not use rpath since that doesn't link to a specific library + path.

like image 255
Sander Mertens Avatar asked May 09 '15 19:05

Sander Mertens


1 Answers

Just compile it this way, so don't use -llib but specify it as object to compile:

cd /full/path/to/lib
gcc -shared -fpic -o liblib.so lib.c             # make the lib
gcc -c -o prog.o prog.c                          # compile program
gcc -o prog prog.o "/full/path/to/lib/liblib.so" # link everything together

EDIT: I initially wrote that on OS X it would not matter whether an absolute or relative path is specified after the -o option. That is not true. It does affect the library's "name" in the Mach-O LC_ID_DYLIB load command. Thanks @Sander Mertens for letting me know.

like image 198
Johannes Weiss Avatar answered Sep 23 '22 18:09

Johannes Weiss