I am working on a C++ project using CMake where I build an executable foo that uses a shared library libbar (that is being added via ExternalProject_add).
The executable build/src/foo in the build directory works perfectly fine. However, if I run make install, the installed executable /bin/foo gives me the following error.
./foo: error while loading shared libraries: libbar.so.11: cannot open shared object file: No such file or directory
I know I am not the only one with this problem (see e.g. here), and I am also aware of the handling of rpath by CMake, see here. As I understand, the install step strips the rpath variable, which explains that the library file cannot be found.
I checked this by running ldd foo in the directory /build/src/ resulting in
libbar.so => /PATH/TO/LIBBAR/libbar.so
When I run the same command in the directory /build/bin/, I get
libbar.so => not found
Now my question. How can I avoid in general that the executable "forgets" the location of the shared library during installation? I basically want the installed executable to have the same paths in rpath as the one in the build directory.
What I have tried so far
I read that you can avoid the stripping of the path via
SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
However, that does not work at all. I have no idea why not, as it is the precise solution suggested here and in the documentation.
I can set the path manually of course via
SET(CMAKE_INSTALL_RPATH "$LIBBAR_PATH}/lib")
and that does work, but this solution is too specific to libbar and does e.g. not work, if I import this project in another code that also uses libbar via my project.
EDIT
I should add that this problem does not appear on all machines. I get it on Linux machines, where it also says
-- Set runtime path of "/PATH/TO/foo" to ""
during the installation. I do not get that line on my Mac, where I don't have that problem at all.
EDIT 2
I just saw that my problem is even mentioned explicitly on the documentation under Common questions. They also say that adding set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) is the solution. But it simply does not work for me, what am I doing wrong here?
EDIT 3
Could it be that the CMAKE_INSTALL_RPATH_USE_LINK_PATH = True solution does not work here, because I am adding libbar via ExternalProject? The documentation states that
CMAKE_INSTALL_RPATH_USE_LINK_PATH is a boolean that if set to true will append directories in the linker search path and outside the project to the INSTALL_RPATH. This is used to initialize the target property INSTALL_RPATH_USE_LINK_PATH for all targets.