Creating relocatable Linux executables by setting RPATH with $ORIGIN

Lots of modern C/C++ projects leverage Autotools to create GNU building system e.g. generate make files based on the platform. Executable files (binaries) are generated during the make/compile process, and can be executed locally on the machine where the compilation is performed. However, if the same executable were moved onto a different machine, or simply a different folder on the same machine, the “library not found” error might be encountered while running the executable.

What is RPATH and $ORIGIN

$ORIGIN is a special variable that indicate actual executable filename. It is resolved to where the executable is at run-time, and can be quite useful when setting RPATH.

How to check the value of RPATH/RUNPATH

$ objdump -x path/to/executable | grep RPATH

or

$ readelf -d path/to/executable | head -20

or

$ chrpath -l path/to/executable

RUNPATH, introduced after RPATH to make it easier to testing libraries (without needing to rebuild them every time), is gaining wider adoptions these days and making the latter obsolete. There’s another post covering more details on this topic. So don’t be surprised if an executable has RUNPATH instead of RPATH set.

Below screenshot provides an example of readelf output with RUNPATH and $ORIGIN:

“readelf” output with RUNPATH and $ORIGIN

Why and How to set RPATH

There are 2 different stages RPATH could be set:

During compilation time

$ ./configure LDFLAGS=-Wl,-rpath=$ORIGIN/path/to/library

will tell the linker to build and run the executable under the specified library path, usually used to override the default library paths.

After compilation before execution

$ chrpath -r “\$\ORIGIN/path/to/library” <executable>

Above command could fail if no rpath was set previously for the executable.

Try below command with patchelf utility, which won’t complain about an unset rpath, and will get RUNPATH set to achieve similar target.

$ patchelf — set-rpath ‘$ORIGIN/path/to/library’ <executable>

Conclusion

--

--

OpenSource & Automation make me excited. Release engineering @MongoDB

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Luke Chen

OpenSource & Automation make me excited. Release engineering @MongoDB