What is the right way to use RPATH on UNIX?

I found this cmake snipped:

# - A workaround to correctly resolve installed runtime dependencies on unix for now
# Include this module in the main CMakeLists.txt before adding targets to make use

include(GNUInstallDirs)

set(CMAKE_SKIP_INSTALL_RPATH OFF)

if(APPLE)
  set(CMAKE_MACOSX_RPATH ON)
  list(APPEND CMAKE_INSTALL_RPATH @loader_path/../${CMAKE_INSTALL_LIBDIR})
else()
  list(APPEND CMAKE_INSTALL_RPATH $ORIGIN/../${CMAKE_INSTALL_LIBDIR})
endif()

and this too:

include(GNUInstallDirs)

if(APPLE)
    set(_base @loader_path)
else()
    set(_base $ORIGIN)
endif()
file(RELATIVE_PATH _relDir ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}
     ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR})
set(CMAKE_INSTALL_RPATH ${_base} ${_base}/${_relDir})

Here is an example of mine, with explanatory comments. Disclaimer: haven’t used this in production at this time, but it seems to be working fine on Linux and MacOS.

Note that there is also RUNPATH, which is used only if RPATH and LD_LIBRARY_PATH don’t contain the sought library. According to here it’s up to the linker to choose between using RPATH vs RUNPATH.