deadbeef deadbeef - 1 year ago 80
Linux Question

g++ link an .a file and its dependencies into a static .so

I have a libSomelib.a that can be linked to an executable by the following command:

g++ -L. -lsomeLib -lpcrecpp -lpcre -lpthread main.cpp -o main

But how could I link a shared object from it, that contains all depentencies?

I want to achieve the following with my new

g++ -L. -lsomeLib main.cpp -o main

I have tried the following:

g++ -shared -L. -lsomeLib -lpcrecpp -lpcre -lpthread -o

This gives me an .so file with no symbols.

PS: I'm completely beginer of compilers.

Answer Source

There are a few issues at play here:

  1. Linkers only use object files from an archive that resolve unresolved symbols. This is why the order of archives in the command line is important. Correct order is object files, followed by static libraries, followed by shared libraries. E.g. g++ -o main -pthread main.cpp -L. -lsomeLib -lpcrecpp -lpcre.
  2. When you build the shared library that archive does not resolve any symbols, hence the linker ignores it completely. See 1.
  3. Object files for a shared library must be compiled as position independent code (-fPIC compiler flag). Archives are normally built without this flag.
  4. Use -pthread flag both when compiling and linking multi-threaded applications, not -lpthread.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download