Search code examples
c++compilationlinkerg++shared-libraries

Run-time linking to dynamic libraries not on LD_LIBRARY_PATH


I'm trying to link a project of mine to a particular set of custom-compiled libraries placed on the project's base directory [proj_dir]/lib - not on any of the system's /lib, /usr/lib or /usr/local/lib - to avoid conficts with the installed stock versions of those same libraries.

I'm able to compile the project by passing the library path with the -L flag, but I get error while loading shared libraries libXXX.so: cannot open shared object file: No such file or directory when I run the compiled binary, and ldd tells me it can't find those particular libs.

On the other hand, I am able to run it without issue if I pass LD_LIBRARY_PATH=[proj_dir]/lib to the executable. Still, is there a way to link those libraries implicitly, without having to manually set the LD_LIBRARY_PATH at runtime?


Solution

  • You can either

    1. Write a wrapper script to always include LD_LIBRARY_PATH before calling the actual program (more flexible).
    2. Add -Wl,-rpath=<directory> to your linker options to add a directory to the runtime library search path. So assuming you have a libfoo.so and your program and DSO are located in the same directory, your compilation command could look like this: gcc -o myprogam main.c -L. -lfoo -Wl,-rpath='$ORIGIN'.

    Update: As correctly noted by Maxim, setting -rpath=. is dangerous and should be avoided.

    For -Wl,, see the gcc manpage and for -rpath see the ld manpage.