I'm compiling C source which calls a shared library, and have only the library header on the build machine, not the .so file (different cpu architecture). How do I make the code find and load /usr/lib/libx.so at runtime?
3 Answers
REVISED from original suggestion of LD_LIBRARY_PATH.
Assuming you are on a linux system, shared libraries may be loaded before execution starts via the LD_PRELOAD environment variable:
$ LD_PRELOAD="/usr/lib/libx.so" your_app However, linking with -Wl,--unresolved-symbols=ignore-in-object-files is probably not a good practice. I'd recommend using dlsym to load arbitrary symbols from a dynamic library. For example,
#include <stdlib.h> #include <stdio.h> #include <dlfcn.h> int main () { void *handle; void (*foo_fp) (void); // function signature from dynamic library // Dynamically load libfoo.so, searching it from LD_LIBRARY_PATH handle = dlopen ("libfoo.so", RTLD_LAZY); // Load function 'foo' from libfoo.so foo_fp = dlsym(handle, "foo"); // Calls 'foo' from libfoo.so foo_fp(); return 0; } To compile this:
gcc -o main main.c -ldl To execute:
export LD_LIBRARY_PATH=<location of libfoo.so> ./main 8 Comments
LD_PRELOAD=/usr/lib/libx.so; ./appUsing the library header file we can create a dummy libx.so using a valid x.c file with blank implementations.
We can use this libx.so file to link to our executable while building it. Once the executable is built we can replace the dummy libx.so file with the real libx.so file and it will work properly.
I have tested this approach with gcc and found it to work. I wonder if there is a straightforward way to do this.
This might be helpful to follow the steps https://www.cprogramming.com/tutorial/shared-libraries-linux-gcc.html.
dlopenit will search/liband/usr/lib(in that order) automatically.