Setting LD_LIBRARY_PATH

Suppose I have a binary that links against a shared library that OpenCSW provides, but can't find it during run time. Is it OK if I set LD_LIBRARY_PATH? What's the best way to do it, e.g. what about setting it in a system-wide profile?

asked: 2012-04-12 by: automaciej


Ben Walton answers:

LD_LIBRARY_PATH should be used only in the rarest of occasions and if you need to ask when those occasions are...you probably shouldn't be using it. :)

As there is no safe way to use LD_LIBRARY_PATH generally (eg: as part of your profile's environment), you need to rely on each binary having a library path of its own. This is best (if at all) done using a wrapper script for each binary. For details on the working of LD_LIBRARY_PATH see ld.so.1(1). However, as information can also be stored in each elf object that allows the runtime linker to safely find the right libraries in the preferred locations this it is preferred to use this method instead of using LD_LIBRARY_PATH at all.

The two settings (usually the same) are RUNPATH and RPATH. Using the -R/path/to/libdir flag during build will see these set. For example, to ensure your binary has /opt/csw/lib in it's RPATH (with precedence to system paths), you could pass -R/opt/csw/lib as part of the LD_OPTIONS (or LDFLAGS) environment setting when you run the configure script.

To inspect the RPATH value in a binary, you can use the tool named dump. You can see the RPATH and RUNPATH of the git binary like this:

$ dump -Lv /opt/csw/bin/git | grep 'R.*PATH'
[12]    RUNPATH         /opt/csw/lib/$ISALIST:/opt/csw/lib:/opt/csw/lib:/opt/csw/lib:/opt/csw/lib
[13]    RPATH           /opt/csw/lib/$ISALIST:/opt/csw/lib:/opt/csw/lib:/opt/csw/lib:/opt/csw/lib

The $ISALIST that you see in the first item is something that the runtime linker will fill in for you. It allows for finding hardware optimized versions of the library in subdirectories of /opt/csw/lib (/opt/csw/lib/sparcv9 for 64-bit libraries as an example). There is some redundancy in the value of the git binary but that will not negatively impact the functionality, just the efficiency of the linking process at load time.