可以使用静态链接使用库构建共享库吗? [英] Possible to build a shared library with static link used library?
问题描述
我可以使用带有静态链接的 gcc 构建可执行文件:
I can build a executable with gcc with static link:
gcc -static xxx.c -o xxx
gcc -static xxx.c -o xxx
所以我可以在没有任何外部依赖库的情况下运行 xxx.
So I can run xxx without any external dependent library.
但是如果我想构建没有外部依赖库的共享库怎么办?我的意思是我想要共享库静态链接其外部引用.
But what if I want to build shared library without externel dependent library? which I mean I want the shared library statically linked its externel reference in.
推荐答案
这将起作用:
# Generate position independent code (PIC)
gcc -fPIC -c -o xxx.o xxx.c
# Build a shared object and link with static libraries
ld -shared -static -o xxx.so xxx.o
# Same thing but with static libc
ld -shared -static -o xxx.so xxx.o -lc
澄清:如果将 -static 标志提供给 gcc,则将其传递给链接器 (ld) 并告诉它使用库的静态版本 (.a)(使用 -l 标志指定),而不是动态版本 (.so).
A clarification: the -static flag, if given to gcc, is passed on to the linker (ld) and tells it to work with the static version (.a) of a library (specified with the -l flag), rather than the dynamic version (.so).
另一件事:在我的系统 (Debian) 上,最后一个示例给出了 libc.a ... recompile with -fPIC 错误.很确定这意味着我系统上的 libc.a 不是用 -fPIC 编译的.apt-cache search libc pic 确实给出了一些结果.
Another thing: On my system (Debian) the last example gives a libc.a ... recompile with -fPIC error. Pretty sure that means that the libc.a I have on my system wasn't compiled with -fPIC. An apt-cache search libc pic did give some results however.
另请参阅:程序库 HOWTO,SO:结合.so库,ld(1), gcc(1)
这篇关于可以使用静态链接使用库构建共享库吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!