I'm trying to learn how to build and use dynamic library in a c++ program. Everything is fine and my program run well when I launch it from Terminal (I'm on a mac OS X El Capitan). Surprisingly that's not the case when I try to launch it by clicking on the executable. I get a dyld: Library not loaded: liblibrary.so
, Reason: image not found
error.
All my files are in a same repertory. I build them with commands :
g++ -c -fPIC A.cpp
g++ -c -fPIC B.cpp
g++ -shared -fPIC A.o B.o -o library.so
g++ main.cpp library.so -o Program
Thank's in advance for your help.
I tried the following solutions :
LD_LIBRARY_PATH
and DYLD_LIBRARY_PATH
library.so
or library.dylib
g++ main.cpp library.so -Wl,-rpath,. -o Program
and g++ main.cpp library.so -Wl,-rpath,$HOME/my_dir -o Program
Finally, I found the solution. Actually, dynamic library creation is different for macOS. What I tried since the beginning is only working for Linux.
So the Mac solution is:
g++ -dynamiclib -install_name "absolute_path/library.dylib" A.o B.o -o library.dylib
where:
-dynamiclib
is the Mac equivalent for -shared
.-install_name "absolute_path/library.dylib"
create an alias of library.dylib
for the linker which is necessary to use library.dylib
. After that, the traditional command:
g++ main.cpp library.dylib -o Program
creates the executable if main.cpp
and library.dylib
are in the same directory.
The program can then be used everywhere in the system as long as library.dylib
stays in the same place.
Following the comment of @Ssswift, relative path linking can be achieved with the command:
g++ -dynamiclib -install_name "@executable_path/library.dylib" A.o B.o -o library.dylib
The library can then follow the executable.
Thanks for your help.