Problem with RPATH

Given a top level file:


cmake_minimum_required(VERSION 3.16)

project(SmtpMime
  VERSION 2.0
  LANGUAGES C CXX)

option(BUILD_TESTS "builds tests" ON)
option(BUILD_DEMOS "builds demos" ON)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_AUTOUIC OFF)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC OFF)

find_package(QT NAMES Qt6 COMPONENTS Core Network Test REQUIRED)
find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core Network Test REQUIRED)

set(LIBRARY_TARGET_NAME ${PROJECT_NAME})

message(USING Qt${QT_VERSION_MAJOR})

set(CMAKE_SKIP_BUILD_RPATH FALSE)
set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
set(CMAKE_INSTALL_RPATH $ORIGIN)

add_subdirectory(src)

if (BUILD_TESTS)
  add_subdirectory(test)
endif()

if (BUILD_DEMOS)
  add_subdirectory(demos)
endif()

the target library (SmtpMime) is built with RPATH set to $ORIGIN, but unfortunately so are the demo and test executables which is less desirable (they don’t work).

How can I change this so that the library (in src sub-dir) gets built with RPATH set to $ORIGIN, but the executables with RPATH set such they pick up the library they are linked with. The CMake file for test has:

add_executable(test
  main.cpp
  connectiontest.cpp)

target_link_libraries(test PRIVATE
  Qt${QT_VERSION_MAJOR}::Core
  Qt${QT_VERSION_MAJOR}::Test
  ${LIBRARY_TARGET_NAME})

Set INSTALL_RPATH on the target test with set_target_properties.

https://cmake.org/cmake/help/latest/command/set_target_properties.html
https://cmake.org/cmake/help/latest/manual/cmake-properties.7.html#target-properties