Sunday, July 24, 2022

[SOLVED] Cannot get Cmake to bake rpath into executable if prefix used

Issue

I have a cmake setup that makes an executable and a shared library I'm using a non-standard install prefix and want to bake the RPATH into the executable. Reading a bunch of previous questions as well as the kitware wiki leads me to this:

Top 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 . )

Library:

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 )

Running 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

Yes, I have read https://gitlab.kitware.com/cmake/community/-/wikis/doc/cmake/RPATH-handling but 1. that seems to be about cmake 2.whatever and 2. still doesn't get me the correct solution.


Solution

It is not so obvious from the article, but variables CMAKE_INSTALL_RPATH and CMAKE_INSTALL_RPATH_USE_LINK_PATH should be set before creation of the target:

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 )

Funny thing that even documentation of CMAKE_INSTALL_RPATH variable is misleading:

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

But description of the INSTALL_RPATH correctly specifies the situation:

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

Actually, in CMake initialization of the most target properties from variables follows the clause bolded above.



Answered By - Tsyvarev
Answer Checked By - Mildred Charles (WPSolving Admin)