How do you add an rpath to an executable in cmake on build (not install) on OSX?

MacOS

Question or issue on macOS:

So, if you already have a binary, you can add an rpath to it on OSX using the ‘install_name_tool’, as so:

install_name_tool -add_rpath @executable_path/blah

xcode does this automatically when you’re building an application bundle.

I know that in cmake you can use this to set the install_name of the shared library:

set_target_properties(nshared PROPERTIES BUILD_WITH_INSTALL_RPATH 1 INSTALL_NAME_DIR "@rpath")

My question is, what’s the equivalent of this to add an rpath to a binary?

(for the ‘why would you do that?’ amongst you, go look at the otool -l on any of the apps in your Applications/ folder and you’ll see plenty of apps with entries like:

Load command 15
          cmd LC_RPATH
      cmdsize 36
         path @executable_path/../../Frameworks/

This is standard practice. I’m just trying to do it in cmake)

How to solve this problem?

You can use a POST_BUILD command to add an LC_RPATH load command to the built executable:

add_custom_command(TARGET executable 
    POST_BUILD COMMAND 
    ${CMAKE_INSTALL_NAME_TOOL} -add_rpath "@executable_path/../../Frameworks/"
    $)

The variable CMAKE_INSTALL_NAME_TOOL contains the path to the install_name_tool executable under Darwin.

Hope this helps!