问题
I have a project struct of a lib like this:
lib_ode/
src/
main/
c/
ode.c
incluce/
ode.h
test/
c/
test_ode.c
include/
target/
.objs/
test/
In this struct I had compile my project with those 4 commands:
(creating lib object)
gcc -fPIC -O3 -DNDEBUG -g -Wall -Isrc/main/include -c -o "target/.objs/ode.o" src/main/c/ode.c
(creating lib)
gcc -shared target/.objs/ode.o -lm -o "target/libode.so"
(creating test object)
gcc -fPIC -O3 -DNDEBUG -g -Wall -Isrc/main/include -c -Isrc/test/include -o target/.objs/test.o src/test/c/test_ode.c
(creating test)
gcc -L./target -lode target/.objs/test.o -o target/test/test.out
Then I tryed to run target/test/test.out and got this error.
target/test/test.out: error while loading shared libraries: libode.so: cannot open shared object file: No such file or directory
In my understand, -L option includes a folder for link, and after the second command I can find a file at target/libode.so.
So what am I doing wrong?
回答1:
You have created an executable dynamically linked against a library in an arbitrary directory. At runtime, the dynamic linker cannot find the library (it doesn't exist in any of the standard search paths) and so gives you the error.
To run the program, you could set the LD_LIBRARY_PATH
environment variable:
LD_LIBRARY_PATH="`pwd`/target" target/test/test.out
You could also trying linking with -rpath
(I've not tried this):
gcc -L./target -Wl,-rpath,./target -lode target/.objs/test.o -o target/test/test.out
(The above should "hardcode" the additional dynamic library search path in the executable. If you later move the library you will get an error again. I'm not sure if the path stored in the executable will be relative or absolute; if it's relative, you'll need to keep the executable and library at the same path relative to each other).
来源:https://stackoverflow.com/questions/44115894/dynamic-linker-gives-cannot-open-shared-object-file-no-such-file-or-directory