Skip to content
Advertisement

How to include dependencies information when creating shared libraries in linux?

I’m writing a shared library based on libpthread.so. To build it, I use the following command:

gcc -fPIC -shared -lpthread -o libfoo.so foo.c

But when linking files that use libfoo.so, I have to specify the option -lpthread -lfoo not just -lfoo. In addition, ldd libfoo.so doesn’t show anything about libpthread.so.

So, is there any way so that I can avoid ‘-lpthread’?

Advertisement

Answer

Extending @Someprogrammerdude ‘s comment:

Your command line is in the wrong order, you need to put the libraries you want to link with last: gcc -fPIC -shared -o libfoo.so foo.c -lpthread

I would say, doing this is a bad thing. Shared libs linking other shared libs are not okay, because:

  • The program finally using them may also use your libpthread, but it may need a different version. As the linker symbols are global (inside the process), linking the multiple versions of the same library can cause the most terrible, worst binary debuggable bugs. Consider that it is pseudorandomly, which version of a given global variable / api call will be used.
  • But, it is not a problem to use a different version of the same library for which it was compiled for. The reason is that the libraries can be binary compatible to eachother, and it can be decided very easily by a relative newer glibc feature (it uses special linker symbols to decide about compatibility).

Particularly in the glibc (whose part is libpthread) is the long binary compatibility very important, so it doesn’t really matter, with with libpthread you compiled your binary, it will work everywhere in the foreseeble future. And, if not, it will cause linker errors and not mystical bugs.

Thus, the optimal solution is:

  1. entirely let out libpthread from the linking of the shared lib (you don’t need it to compile, you need only its symbols on running it)
  2. yes, you have to give both -lfoo and -lpthread if you compile a binary using your libfoo.

(2) is not a very big problem – there are various tools (like gnu autoconf) which can generate the libs of the required compiler/linker flags automatically.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement