Compile a shared library statically

谁都会走 提交于 2019-12-03 12:44:45

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!