gcc/ld: what is to -Wl,-rpath in dynamic linking what -l is to -L in static linking?

With /my/dir/path/foo.a and /my/dir/path/bar.a:

To statically link using gcc/g++, one uses -L to specify the directory containing the static libraries and -l to specify the name of the library. In this case one would write gcc -L/my/dir/path -lfoo -lbar ....

With /my/dir/path/foo.so and /my/dir/path/bar.so:

To dynamically link using gcc/g++, one uses -Wl,-rpath,/my/dir/path. How are the names of the libraries specified? Is the command gcc -L/my/dir/path -Wl,-rpath,/my/dir/path -lfoo -lbar ... correct? Or should it be gcc -L/my/dir/path -Wl,-rpath,/my/dir/path -Wl,-lfoo -Wl,-lbar ...? In other words, do the library names need to be passed on to the linker through -Wl,-l?

1 Answer

The -l argument works well for both static and shared libraries but expects the filename of specified library to be in a specific format. Namely, -lfoo tells the linker to look for a file named libfoo.a or libfoo.so. If you want to links against a library whose filename don't have this 'lib' prefix (i. e. foo.so), you can use a semicolon and specify a filename: -l:foo.so.

So, to dynamically link against /my/dir/path/foo.so and /my/dir/path/bar.so you need to issue the following command:

g++ -L/my/dir/path/ -l:foo.so -l:bar.so

As for -rpath, it has the -rpath=<path> format, so in order to pass it to the linked you need the issue the following:

g++ -L/my/dir/path/ -Wl,-rpath=/my/dir/path/ -l:foo.so -l:bar.so

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like