Compile a shared library statically

I have a shared library with some home functions that I compile into my other programs, but I need to link the final program with all the libraries that I used to compile the static library. Here is an example:

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

In my main program, to use the foo function, I need to compile it with the -lbar flag. Is there a way that I can collect statically in the library so that it includes all the necessary code from other libraries, and I can compile my final program without the need to use the -lbar flag?

+6
c ++ c static linker shared-libraries
source share
4 answers

Shared objects (.so) are not libraries, they are objects. You cannot extract some of them and paste it into other libraries.

What can you do if you create a shared object that references another, but another will be needed at runtime. Just add -lbar when connecting libfoo.

If you can create libbar, you can obviously create a library that is a combination of libfoo and libbar. IIRC, you can also make the linker build a library that is libfoo and a necessary part of libbar by associating .a with .o, intended to go into 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 
+5
source share

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 to the static library):

 gcc -static main.c -L. -lyour -o statically_linked 
+3
source share

You can get this working using libtool , see the libtool tutorial for cross-library dependencies for an example of how this works

+2
source share

Basically, if you have statically linked libraries of system libraries that your static library depends on, you can statically refer to all the code from them.

I'm not sure why. * Processing NIX platforms for shared libraries is an ingenious work and greatly reduces the size of compiled programs. If you are concerned that you cannot run the code on another computer due to the lack of libraries, you can always choose the path for most closed source programs compiled for Linux libraries: just compile them with the -Wl,--rpath -Wl,. options -Wl,--rpath -Wl,. for GCC and distribute the library with the binary.

+1
source share

All Articles