How to link to a shared library without lib* prefi

2019-01-22 15:31发布

问题:

I have to link my code to a shared library without the lib prefix. (say, foo.so) The first problem is -l option does not find the file. So I tried directly including this file to the last compilation like this:

gcc a a.o /PATH/TO/FOO/foo.so

But in this case, a is hard linked to foo.so as an absolute path as seen in "ldd a":

/PATH/TO/FOO/foo.so

In the final deployment both files would end up being in the same folder, so this should be normal link, not the absolute path. How can I do this?

回答1:

This works for me: -l:mylib.so

thanks to



回答2:

Assuming an ELF platform, if you can rebuild foo.so:
- the best fix is to simply name it libfoo.so
- the next best fix is to set SONAME on it:

  gcc -Wl,-soname,foo.so -o foo.so foo.o

when you later link with:

  gcc -o a.out a.o /path/to/foo.so

only the SONAME will be recorded as a dependency, not a full /path/to/foo.so.

If you can't rebuild foo.so, then do this:

  rm -f foo.so && ln -s /path/to/foo.so foo.so &&
  gcc -o a.out a.o ./foo.so && rm -f foo.so


回答3:

-Wl,-rpath,. --> to use current directory for searching lib files. (even if not found in compilation, ok at run-time) instead of -llibrary --> use library.so.

This seems to work correctly. Hope anyone finds this useful.