macos BUILD_RPATH not used the first time CMake is run

I’m embedding a Python interpreter in a C++ application. The embedding relies on some code generated with SWIG. The library generated by SWIG needs to be linked into the C++ executable. I’ve set OUTPUT_DIR option of swig_add_library to tell CMake’s SWIG module where the library needs to be placed in the build so that it can be loaded from the SWIG generated .py file. It needs to be in the same directory as the SWIG generated Python files which in my case is not the lib directory.

the SWIG generated library is linked into executables using “@rpath/”, and the executable crashes because the SWIG OUTPUT_DIR is not in the RPATH (verified with otool -l).

dyld[75999]: Library not loaded: @rpath/

I think I need to add the OUTPUT_DIR used with swig_add_library into the executable’s RPATH, and I should be able to do that with BUILD_RPATH target property and set CMAKE_SKIP_BUILD_RPATH OFF. However, the BUILD_RPATH property is being ignored the first “cmake && make” (verified with otool -l). However, It is picked up in the second “cmake && make”. For instance, eg I can touch CMakeCache.txt && make and my BUILD_RPATH shows up in the executable.

cmake version 3.22.3

Any help on getting this working?

The main issue is that BUILD_RPATH is only picked up if “cmake && make” 2 times. Why would that happen?

I turns out this had nothing to do with BUILD_RPATH (which did nothing) and was instead related to my use of an IMPORTED library used to present the SWIG generated library to other targets that needed to link to it. Another person reported a similar issue here
following the hints there, with the addition that the IMPORTED library must be SHARED (I had used UNKNOWN) resolved things.