I am compiling a simple C program on m2 mac that depends on a shared library using clang on macOS. I am setting the rpath correctly using the -Wl,-rpath,@executable_path/../saga flag. I've verified this by inspecting the executable using otool, which shows the correct rpath.
However, when I try to run the program, the dynamic linker (dyld) does not find the library in the specified path. The program only works when I set the DYLD_LIBRARY_PATH environment variable to the location where the library (libdynamiclib.dylib) is present.
Why is dyld not using the rpath that I've set? Am I setting the rpath incorrectly?
Here's the command I'm using to compile the program:
clang -I../saga -L../saga -ldynamiclib -Wl,-rpath,@executable_path/../saga -o main main.c
Rpath only matters for lookups that are actually using @rpath
, but it looks like your library isn't. Its install name is just libdynamiclib.dylib
, but it needs to be @rpath/libdynamiclib.dylib
.
Run this, then recompile your main binary:
install_name_tool -id '@rpath/libdynamiclib.dylib' ../saga/libdynamiclib.dylib
codesign -s - -f -o linker-signed ../saga/libdynamiclib.dylib
(The second command is just to update the default linker-generated signature, if you have your own codesigning process, then obviously just use that instead.)
And if you want a deep dive on how install names work, see this post of mine.