Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile a shared library statically

I've got a shared library with some homemade functions, which I compile into my other programs, but I have to link the end program with all the libraries I have used to compile the static library. Here is an example:

I have function foo in the library which requires a function from another library libbar.so.

In my main program to use function foo I have to compile it with the -lbar flag. Is there a way I can compile my library statically so it includes all the required code from the other libraries, and I can compile my end program without needing the -lbar flag?

like image 263
Simon Walker Avatar asked May 11 '10 15:05

Simon Walker


People also ask

Can shared library be statically linked?

You can't statically link a shared library (or dynamically link a static one).

What is static and shared library?

Static libraries take longer to execute, because loading into the memory happens every time while executing. While Shared libraries are faster because shared library code is already in the memory.

Is a shared library a dynamic library?

Dynamic and shared libraries are usually the same. But in your case, it looks as if you are doing something special. In the shared library case, you specify the shared library at compile-time. When the app is started, the operating system will load the shared library before the application starts.


2 Answers

Shared objects (.so) aren't libraries, they are objects. You can't extract part of them and insert it in other libraries.

What you can do if build a shared object which references the other -- but the other will be needed at run time. Just add the -lbar when linking libfoo.

If you are able to build libbar, you can obviously make a library which is the combination of libfoo and libbar. IIRC, you can also make the linker build a library which is libfoo and the needed part of libbar by linking a .a with the .o meant to go in libbar. Example:

gcc -fPIC -c lib1.c     # define foofn(), reference barfn1()
gcc -fPIC -c lib2a.c    # define barfn1(), reference barfn2()
gcc -fPIC -c lib2b.c    # define barfn2()
gcc -fPIC -c lib2c.c    # define barfn3()
gcc -c main.c           # reference foofn()
ar -cru libbar.a lib2*.o
gcc -shared -o libfoo.so lib1.o -L. -lbar
nm libfoo.so | grep barfn2()    # ok, not here
gcc -o prog main.o -L. -lfoo
env LD_LIBRARY_PATH=. ./prog    # works, so foofn(), barfn1() and barfn2() are found
like image 106
AProgrammer Avatar answered Oct 03 '22 00:10

AProgrammer


Step 1 (Create object file):

gcc -c your.c -o your.o

Step 2 (Create static library):

ar rcs libyour.a your.o

Step 3 (Link against static library):

gcc -static main.c -L. -lyour -o statically_linked
like image 28
Taylor Leese Avatar answered Oct 03 '22 02:10

Taylor Leese