# What is the right way to use RPATH on UNIX?

**URL:** https://discourse.cmake.org/t/what-is-the-right-way-to-use-rpath-on-unix/13335
**Category:** Code
**Created:** [January 6, 2025, 9:44pm UTC](https://discourse.cmake.org/t/what-is-the-right-way-to-use-rpath-on-unix/13335 "2025-01-06T21:44:46Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![ClausKlein](https://discourse.cmake.org/user_avatar/discourse.cmake.org/clausklein/32/352_2.png) [@ClausKlein](https://discourse.cmake.org/u/ClausKlein)
#### Post date: [January 6, 2025, 9:44pm UTC](https://discourse.cmake.org/t/what-is-the-right-way-to-use-rpath-on-unix/13335/1 "2025-01-06T21:44:46Z")

</div>

I found this cmake snipped:

```cmake
# - 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:

```cmake
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})

```

---

<div class="post-metadata">

### Author: ![AnthonyD973](https://discourse.cmake.org/user_avatar/discourse.cmake.org/anthonyd973/32/3130_2.png) [@AnthonyD973](https://discourse.cmake.org/u/AnthonyD973)
#### Post date: [January 7, 2025, 11:27pm UTC](https://discourse.cmake.org/t/what-is-the-right-way-to-use-rpath-on-unix/13335/2 "2025-01-07T23:27:15Z")

</div>

[Here](https://github.com/adentinger/CMakeBestPractices/blob/b150317500d7886a2998ebaf8561250ea9d1085f/prj2/lib2/CMakeLists.txt#L152) 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](https://discourse.cmake.org/t/setting-rpath-and-not-runpath-for-executable/10011/3) it’s up to the linker to choose between using `RPATH` vs `RUNPATH`.
