I'm trying to compile a dylib on MacOS using CMake. My library is dynamically linked to some other libraries and I want to ship them with my library. For this I need to make sure that when I load my library, the dependent libraries are loaded from the same folder regardless its location. I believe that it has something to do with rpath, but I'm not an expert here. Can you please suggest a way to achieve this using CMake? (I guess one needs to provide some linker options via -Wl,-rpath or similar
Thanks in advance!
Here's what I have done in my CMake scripts for the shared libraries to be loaded from the same directory as my binaries (executables and other libraries):
SET(CMAKE_BUILD_WITH_INSTALL_RPATH true) SET(CMAKE_INSTALL_RPATH "$ORIGIN/")
(tested with CMake 3.0+)
How it works (my understanding): the second line tells CMake to add the $ORIGIN special string to the binaries search folder (This special $ORIGIN string is "replaced" by the OS, at execution time, with the folder containing the executing binary. So, a needed library that is next to the binary containing this string will be correctly found).
However, setting this variable in CMake only impacts the install-time binaries (those that are deployed with make install, for instance): CMake does not change the search path in binaries created at the build stage, but only when it installs them.
Since I am not using the CMake install feature, and I only want to supply my application in a freely-relocatable folder, I have used the first call, that tells CMake to use the install-time search paths at build time, too.
So, with these two calls, calling make (or building with XCode, I guess) on the CMake-generated makefiles will create binaries with the search folder correctly set to $ORIGIN.
Please do this before defining any other target. You can also customize these settings for individual targets by using set_target_property with the BUILD_WITH_INSTALL_RPATH and INSTALL_RPATH properties.
I have only tested this under Linux, but if MacOS X behaves in the same way, this should be OK.
Hope this helps