how can I link a shared object in C?

2019-07-17 12:37发布

问题:

I made a simple program that uses a shared object, opening it with dlopen(). I also compiled and linked the shared object like below:

gcc -o libmylib.so libmylib.c -shared -fPIC -Wall

gcc -o program program.c -L. -lmylib -ldl -Wall

When I tried to run the program for the first time it said something like

cannot open libmylib.so: no such file or directory

so I searched the internet and found that I have to copy my shared object to /lib/i386-linux-gnu/ in order for the program to run. So I did so, and it worked, but then I tried to do it in other ways and therefore I removed libmylib.so from the /lib/i3686-linux-gnu/ directory. Now when I'm trying to run the program it shown no errors but keeps saying Segmentation fault. It is clear that the shared object is nowhere to be found, but how can I link it without copying anything?

I am using Ubuntu 11.10

回答1:

When you compiled the program, you linked it properly; using -L. -lmylib. However, if it's not a standard system library, the execution environment needs to know where to look for it. One way you can do this is by using the environment variable LD_LIBRARY_PATH, like so:

LD_LIBRARY_PATH=. ./program

or

export LD_LIBRARY_PATH=.
./program


回答2:

Read more about shared libraries and their search paths, and the ld command.

An alternative could be to register the "runtime" path used for searching library. You could use gcc -Wl,-rpath . -o program program.c -L. -lmylib -ldl -Wall

If your program is dlopen-ing at run time some *.so file, you'll better pass the absolute file name to dlopen (or something like "./foo.so"). The realpath function could help you.

There is even a command chrpath (which I just discovered) to use on an existing executable to change its run path.

There are security reasons (similar to those for PATH) to avoid putting the current directory in the run time path or the LD_LIBRARY_PATH.