2

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
  • Add your lib directory to LD_LIBRARY_PATH. Commented Oct 26, 2016 at 16:02
  • If you use dlopen it will search /lib and /usr/lib (in that order) automatically. Commented Oct 26, 2016 at 16:09
  • Would I call dlsym as well, or use the original symbol names and build with -Wl,--unresolved-symbols=ignore-in-object-files? Commented Oct 26, 2016 at 16:33

3 Answers 3

3

Create a 'dummy' libx.so file that exports the needed symbols.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Does not work; probably since it was built without -l*
Can you clarify how you built the executable? This reference may help you as well: cprogramming.com/tutorial/shared-libraries-linux-gcc.html
gcc -o app src.c -Wl,--unresolved-symbols=ignore-in-object-files
Try: LD_PRELOAD=/usr/lib/libx.so; ./app
The dlopen() idea should be a separate answer. I believe dlopen() by itself has the same effect as LD_PRELOAD. I definitely don't want to call dlsym() for each shared lib routine.
|
1

Using 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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.