How to encode the executable location in a Linux rpath?
-
01-07-2021 - |
Question
I have an executable that implicitly loads several .so libraries, all of them built by me. For deployment, or at least testing/debugging, I'd like to have them all in the same directory:
my_executable
libmylib1.so
libmylib2.so
To get the executable to load the libraries implicitly, I'd like to set an rpath (DT_RUNPATH) for the executable's directory. With OS X, I'd do this like so:
clang -dynamiclib -o libmylib1.dylib -install_name @rpath/libmylib1.dylib src1.c src2.c
clang -dynamiclib -o libmylib2.dylib -install_name @rpath/libmylib2.dylib src3.c src4.c
clang -o my_executable -L. -llibmylib1.so -llibmylib2.so -Wl,-rpath,@loader_path/. main.c
Notice the @loader_path/.
that forms the executable's rpath in OS X. With Linux, the closest I can come to this is
gcc -dynamiclib -o libmylib1.so src1.c src2.c
gcc -dynamiclib -o libmylib2.so src3.c src4.c
gcc -o my_executable -L. -llibmylib1.so -llibmylib2.so -Wl,-rpath=. main.c
The problem here is that on Linux the rpath follows the current working directory, not the executable's directory. Is there any way of accomplishing the same thing on Linux?
Solution
You need to use the literal string $ORIGIN
as the runpath, that is understood as the executable's location by the dynamic loader.
OTHER TIPS
A common solution is to create a shell script wrapper that figures out what directory the executable is in and sets LD_LIBRARY_PATH appropriately before execing the actual executable.