Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to link static library into dynamic library in gcc

Tags:

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?

like image 628
bob Avatar asked Apr 15 '10 23:04

bob


People also ask

Can static library link to dynamic library?

Yes for instance when you call windows functions from within your static lib they are normally from some dynamic library so there should be no difference.

Can a DLL link to static library?

When your DLL refers to an external content (like function or variable), it is resolved at linking time - together with all dependencies. But that's all. If your static library has a function named print_sample_string() , but your DLL does not use it, it won't be attached to DLL image.

How static library is linked?

Static libraries are either merged with other static libraries and object files during building/linking to form a single executable or loaded at run-time into the address space of their corresponding executable at a static memory offset determined at compile-time/link-time.


2 Answers

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 
like image 52
R Samuel Klatchko Avatar answered Sep 18 '22 15:09

R Samuel Klatchko


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.

like image 38
Andreas Morgenstern Avatar answered Sep 20 '22 15:09

Andreas Morgenstern