# Can CMake patch RPATH in existing binaries?

**URL:** https://discourse.cmake.org/t/can-cmake-patch-rpath-in-existing-binaries/9424
**Category:** Usage
**Created:** [November 14, 2023, 8:11am UTC](https://discourse.cmake.org/t/can-cmake-patch-rpath-in-existing-binaries/9424 "2023-11-14T08:11:09Z")
**Posts on this page:** 4
**Page:** 1

<div class="post-metadata">

### Author: ![KUGA2](https://discourse.cmake.org/user_avatar/discourse.cmake.org/kuga2/32/4968_2.png) [@KUGA2](https://discourse.cmake.org/u/KUGA2)
#### Post date: [November 14, 2023, 8:11am UTC](https://discourse.cmake.org/t/can-cmake-patch-rpath-in-existing-binaries/9424/1 "2023-11-14T08:11:09Z")

</div>

CMake can patch RPATH within `install(TARGETS ...)`. Can we also do this manually like:

```auto
set_rpath("libsepp.so" "\$ORIGIN")

```

Reason: I want to patch libs that are IMPORTED. I cannot install them.

PS: I have found internal commands, but there is no documentation so I do not really know how to do it: [https://gitlab.kitware.com/cmake/cmake/-/issues/16825](https://gitlab.kitware.com/cmake/cmake/-/issues/16825)

---

<div class="post-metadata">

### Author: ![ben.boeckel](https://discourse.cmake.org/letter_avatar_proxy/v4/letter/b/ea5d25/32.png) [@ben.boeckel](https://discourse.cmake.org/u/ben.boeckel)
#### Post date: [November 18, 2023, 9:48pm UTC](https://discourse.cmake.org/t/can-cmake-patch-rpath-in-existing-binaries/9424/2 "2023-11-18T21:48:03Z")

</div>

The best you can do is install them and, as part of the install (`install(CODE)` or `install(SCRIPT)`), use a tool like `patchelf` or `chrpath` to edit the installed copy as needed. If you need the dependency itself to be fixed, please contact upstream or the vendor that built that copy.

---

<div class="post-metadata">

### Author: ![Grinlex](https://discourse.cmake.org/user_avatar/discourse.cmake.org/grinlex/32/5601_2.png) [@Grinlex](https://discourse.cmake.org/u/Grinlex)
#### Post date: [December 14, 2025, 8:55am UTC](https://discourse.cmake.org/t/can-cmake-patch-rpath-in-existing-binaries/9424/3 "2025-12-14T08:55:02Z")

</div>

```cmake
file(READ_ELF ${MOD} RUNPATH _old_rpath)
if("${_old_rpath}" STREQUAL "")
    file(READ_ELF ${MOD} RPATH _old_rpath)
endif()
string(REPLACE ";" ":" _old_rpath "${_old_rpath}")
file(RPATH_CHANGE FILE "${MOD}" OLD_RPATH "${_old_rpath}" NEW_RPATH "\$ORIGIN")

```

---

<div class="post-metadata">

### Author: ![craig.scott](https://discourse.cmake.org/user_avatar/discourse.cmake.org/craig.scott/32/20_2.png) [@craig.scott](https://discourse.cmake.org/u/craig.scott)
#### Post date: [December 14, 2025, 7:17pm UTC](https://discourse.cmake.org/t/can-cmake-patch-rpath-in-existing-binaries/9424/4 "2025-12-14T19:17:46Z")

</div>

I think you’d need to first check that the new RPATH is not longer than the old RPATH before changing it. Also, do note that `file(READ_ELF)` is an undocumented, internal part of CMake. It could change or disappear at any time.
