Friday, September 2, 2016

Set Shared Library Path during Compilation without Using LD_LIBRARY_PATH

When you are linking a shared library that is not in the default shared library path, usually specified in /etc/ld.so.conf, plus /lib and /usr/lib, you need to set the environment variable LD_LIBRARY_PATH to point to the directory that contains user-created shared libraries. Here is how to save the path of the custom shared library path within the executable during compilation, so that one can execute the binary without setting LD_LIBRARY_PATH. For Mac OS X, the variable name is DYLD_LIBRARY_PATH.

For Linux,
$ gcc main.c -g /user/custom/shared/library/path -Wl,-rpath=/user/custom/shared/library/path

For Mac OS X,
$ gcc main.c -g /user/custom/shared/library/path -Wl,-rpath /user/custom/shared/library/path

The last option -Wl,-rpath will set the executable's rpath, so that it will look for the shared library in the specified folder. With this option, you won't need to set LD_LIBRARY_PATH or DYLD_LIBRARY_PATH.

1 comment: