开发者

Compile a shared library statically

开发者 https://www.devze.com 2022-12-30 09:50 出处:网络
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 sta

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?


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


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


You can get this sort of thing working by using libtool, see the libtool manual on Inter library dependencies for an example of how that works


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

I'm not sure why, though. *NIX platforms' handling of shared libraries is a work of genius, and severely cuts down on compiled program size. If you're worried about not being able to run code on a different computer due to missing libraries, then you can always take the path of most closed-source programs compiled for Linux libraries: just compile them with -Wl,--rpath -Wl,. options to GCC and distribute the library alongside the binary.

0

精彩评论

暂无评论...
验证码 换一张
取 消