如果使用前缀,则无法让 Cmake 将 rpath 烘焙到可执行文件中

Cannot get Cmake to bake rpath into executable if prefix used

我有一个生成可执行文件和共享库的 cmake 安装程序我使用的是非标准安装前缀,想将 RPATH 烘焙到可执行文件中。阅读之前的一堆问题以及 kitware wiki 将我引向了这个:

顶部CMakeLists.txt:

cmake_minimum_required( VERSION 3.14 )
project( cmakeprogram VERSION 1.0 )

add_executable( program program.cxx )

set( CMAKE_RPATH "${CMAKE_INSTALL_PREFIX}/lib" )
set( CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib" )
set( CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE )
add_subdirectory( lib )
target_include_directories( auxlib PUBLIC "${CMAKE_CURRECT_SOURCE_DIR}" )
target_link_libraries( program PUBLIC auxlib )

install( TARGETS program DESTINATION . )

图书馆:

cmake_minimum_required( VERSION 3.14 )
project( auxlib )

set( CMAKE_RPATH "${CMAKE_INSTALL_PREFIX}/lib" )
set( CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib" )
set( CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE )
add_library( auxlib SHARED
             aux.cxx aux.h )
target_include_directories( auxlib PUBLIC "${CMAKE_CURRECT_SOURCE_DIR}" )
install( TARGETS auxlib DESTINATION lib )

运行 ldd on the program (SuSe linux if it matters) in the build & isntall location respectively gives:

build
        libauxlib.so => /stuff/build-publiclib/lib/libauxlib.so (0x00002ad64984c000)
prefix
        libauxlib.so => not found

是的,我读过 https://gitlab.kitware.com/cmake/community/-/wikis/doc/cmake/RPATH-handling 但是 1. 这似乎是关于 cmake 2.whatever 和 2. 仍然没有找到正确的解决方案。

从文章中看不是很明显,但是变量 CMAKE_INSTALL_RPATHCMAKE_INSTALL_RPATH_USE_LINK_PATH 应该在 创建目标之前设置:

cmake_minimum_required( VERSION 3.14 )
project( cmakeprogram VERSION 1.0 )

# All further targets on installation will have given RPATH.
set( CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib" )

add_executable( program program.cxx )

add_subdirectory( lib )

有趣的是,甚至 CMAKE_INSTALL_RPATH 变量的文档也具有误导性:

This is used to initialize the target property INSTALL_RPATH for all targets.

但是 INSTALL_RPATH 的描述正确指定了情况:

This property is initialized by the value of the variable CMAKE_INSTALL_RPATH if it is set when a target is created.

实际上,在 CMake 中,从变量初始化大多数目标属性遵循上面加粗的子句。