I'm building with g++ from the command line in OS X, and not using XCode. When I built my executable I had to include the linker flag to the library where the dynamic library was stored, but when I went to run the executable the dynamic library was not found, and I got the error dyld: Library not loaded: (foo)
.
There were a few questions on here already about dynamic libraries related to specific software packages and how to get dynamic libraries built into XCode projects, but nothing generic explaining how Mac OS X looks for dynamic libraries in general and how to get a new .dylib into the search path for the executable.
Could someone fill in that gap. How does Mac OS X look for dynamic libraries when one is built with an executable and how would I put a link to my dynamic library in the right place so the executable will run?
I'm on OSX 10.9 - Mavericks.
A good place to start would be the Apple documentation on Dynamic Library Programming Topics and especially Run-Path Dependent Libraries.
"When the dynamic loader (dyld) loads the executable, it looks for run-path dependent libraries in the run-path search paths in the order in which they were specified at link time."
The first think is to check the libraries dependencies for you binary using otool:
otool -L /path/to/binary
Then, you have different solutions depending on how you want to distribute your library.
You can specify the absolute path of the library in the binary. It should be done with a tool, CMake for instance. Otherwise, you can use
install_name_tool to change the path to a library by hand.
Most of the time, you want to deploy your binary and put the dylibs in a separated folder. Those libraries are loaded relatively to where the binary is. For example:
@loader_path/../Frameworks/Sparkle.framework/Versions/A/Sparkle
For more info about paths, I suggest you read this blog.