During the build process of C or C++ programs, dynamic library search paths can be embedded directly into the resulting executable. This mechanism is known as RUNPATH, and it allows the runtime linker to determine additional locations where shared libraries should be loaded from. It is commonly used for relocatable builds, custom library layouts, and deployment scenarios without system-wide installation. This tutorial explains how to add the RUNPATH to binary file using gcc or g++ compiler.
The gcc is used for demonstration, but the same options apply when using g++ for C++ programs.
1. Single RUNPATH entry
A single runtime search path can be injected using the linker option -rpath.
gcc -Wl,-rpath,/opt/mylibs main.c -o test
After compilation, the RUNPATH value can be verified using the readelf command:
readelf -d ./test | grep RUNPATH
Example output:
0x000000000000001d (RUNPATH) Library runpath: [/opt/mylibs]
2. Multiple RUNPATH entries
More than one entry can be included either by separating paths with a colon or by repeating the linker option -rpath.
gcc -Wl,-rpath,/opt/mylibs:/opt/otherlibs main.c -o test
gcc -Wl,-rpath,/opt/mylibs -Wl,-rpath,/opt/otherlibs main.c -o test
Output example:
0x000000000000001d (RUNPATH) Library runpath: [/opt/mylibs:/opt/otherlibs]
3. RUNPATH with runtime variables
Special linker token $ORIGIN allow paths to be defined relative to the executable location. This is useful for portable directory structures. Relative to executable directory:
gcc -Wl,-rpath,'$ORIGIN' main.c -o test
Output example:
0x000000000000001d (RUNPATH) Library runpath: [$ORIGIN]
Relative subdirectory (e.g., lib directory):
gcc -Wl,-rpath,'$ORIGIN/lib' main.c -o test
Leave a Comment
Cancel reply