Search code examples
linkerg++rpath

How can I set an executable's rpath and check its value after building it?


I'm building the following file:

int main()
{
  return 0;
}

with the following flags:

g++ -o main -Wl,-rpath,'$ORIGIN' main.cpp

but the rpath flag is doing nothing. When I execute the following commands:

objdump -x main | grep -i rpath
readelf -a main | grep -i rpath

I obtain nothing (RPATH is not defined).

What I'm doing wrong?

EDIT

I have tried to do the above with a different binary using the following cmake flags:

set(CMAKE_SKIP_BUILD_RPATH FALSE)
set(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE)
set(CMAKE_INSTALL_RPATH "\$ORIGIN")
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)

I have moved the executable to a different machine, and placed a dynamic library that it needs to 'dlopen' in the same folder. It has worked (and I'm 100% sure this is because rpath, since before applying the above cmake flags the executable didn't worked).

Still, using the above two commands to check rpath (objdump and readelf) I still don't see anything.


Solution

  • If I didnt miss something here, you are not linking any libs in your build command.

    Lets say you want to link libusb.so shared library, which is located in libusb sub-folder of your current folder where is main.cpp. I will not take any details here, about soname, linkname of lib etc, just to make clear about rpath.

    rpath will provide runtime linker path to library, not for linktime, cause even shared library need to be present(accessible) in compile/link time. So, to provide your application loader with possibility to look for needed library in start time, relatively to your app folder, there is $ORIGIN variable, you can see it with readelf but only if you link some library with $ORIGIN in rpath. Here is example based on your question:

    g++ main.cpp -o main -L./libusb -Wl,-rpath,'$ORIGIN/libusb' -lusb 
    

    As you see, you need to provide -L directory for compile/link time search, and rpath for runtime linker. Now you will be able to examin all needed libs for your app using readelf and location for search.