Shared library on OS X (rpath issue?)
May 11, 2015 at 10:11am UTC
I'm learning about shared libraries in C++ but I'm struggling to run a program when the shared library .so file isn't in the same directory as the executable. As a minimal example, I have the file "print_hw.cpp" in ./shared/:
1 2 3 4 5
#include <iostream>
void print_hw() {
std::cout << "Hello world!" << std::endl;
}
Which I compile with:
1 2
g++ -c -fPIC -o print_hw.o print_hw.cpp
g++ -shared -o libprint_hw.so print_hw.o
Then in ./ I have "main.cpp":
1 2 3 4 5 6 7
void print_hw();
int main() {
print_hw();
return 0;
}
I then compile this with:
g++ -L./shared -Wl,-rpath,./shared -o test main.cpp -lprint_hw
This all compiles fine, but when I run "./test" I get:
dyld: Library not loaded: libprint_hw.dylib
Referenced from: ..././test
Reason: image not found
unless I put libprint_hw.so in the same directory as the executable, when it works.
I've been following the guide on Cprogramming.com
http://www.cprogramming.com/tutorial/shared-libraries-linux-gcc.html which is intended for C and Linux - am I missing something to make this work on OS X?
Thanks for any help.
May 11, 2015 at 5:23pm UTC
Well I think I figured this out, and I believe it's an OS X thing. If I compile my shared library with:
g++ -dynamiclib -o libprint_hw.dylib -install_name @loader_path/shared/libprint_hw.dylib print_hw.cpp
and then compile my program with:
g++ -o test -Lshared -lprint_hw main.cpp
it all works. This blog post was useful in working this out:
https://mikeash.com/pyblog/friday-qa-2009-11-06-linking-and-install-names.html
Hopefully this might help someone else in future!
Topic archived. No new replies allowed.