how to link static library into dynamic library in gcc

Under gcc (g++), I have compiled a static .a (call it some_static_lib.a) library. I want to link (is that the right phrase?) this .a file into another dynamic library (call it libsomeDyn.so) that I'm building. Though the .so compiles, I don't see content of .a under .so using nm command:

/usr/bin/g++ -fPIC -g -O2 -Wall -Werror -pipe -march=pentium3 -mtune=prescott -MD -D_FILE_OFFSET_BITS=64 -DLINUX -D_GNU_SOURCE -D_THREAD_SAFE -I../../../../../../../../ -I../../../../../../../..//libraries -Wl,-rpath,/usr/lib -o libsomeDyn.so some.o another.o some_static_lib.a -shared -Wl -x -Wl,-soname,libsomeDyn.so

I do not see functions under some_static_lib.a under libsomeDyn.so. What am I doing wrong?


Solution 1:

Static libraries have special rules when it comes to linking. An object from the static library will only be added to the binary if the object provides an unresolved symbol.

On Linux, you can change that behavior with the --whole-archive linker option:

g++ -Wl,--whole-archive some_static_lib.a -Wl,--no-whole-archive

Solution 2:

For every one that comes across that problem like me (and has not understand the answer properly): here is a short howto generate a dynamic library (libmylib.so) from a static one (mylib.a):

1.) create a mylib.c file that only imports the mylib.h file

2.) compile this mylib.c to mylib.o with

gcc -c -fPIC mylib.c -o mylib.o

3.) generate a dynamic library with the following command:

gcc --whole-archive -shared -Wl,-soname,libmylib.so -o libmylib.so mylib.o mylib.a 

That worked at least for me, turning a static library (compiled with -fPIC) to a dynamic library. I'm not sure wether this will work for other libraries too.