简体   繁体   中英

CMake: add packages to rpath

I have a dynamic library libhelloworld.so built with CMake that I've installed in /usr/local/lib64 . I'm linking against the library in a CMakeLists.txt file that builds an executable:

find_package(HelloWorld REQUIRED)
target_link_libraries(helloexecutable HelloWorld::HelloWorld)

CMake builds the executable just fine, but when I run it I get the following error:

error while loading shared libraries: libhelloworld.so: cannot open shared object file: No such file or directory

I was able to resolve the issue by setting the rpath

set(CMAKE_INSTALL_RPATH "/usr/local/lib64")

but this is not portable.

So I have two questions: 1) shouldn't CMake automatically set the rpath for linked dynamic libraries? and 2) if Cmake can automatically set the rpath how do I tell it to do so, and if it can't, what's a more portable way of setting the rpath?

The observed behavior is described in the CMake wiki (thanks, Tsyvarev!)

By default if you don't change any RPATH related settings, CMake will link the executables and shared libraries with full RPATH to all used libraries in the build tree. When installing, it will clear the RPATH of these targets so they are installed with an empty RPATH.

This means you need to tell CMake to add the automatically determined parts of the RPATH which point to directories outside the build tree to the install RPATH

SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)

In other words, 1) yes, CMake automatically sets the rpath, but only for the build tree by default. 2) CMake can set the rpath for the installed executable as well, it just has to be told to do so, as shown above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM