我想知道 gcc 上的 -static 选项是做什么的。我在编译某个应用程序时需要此选项,但是当我这样做时,我收到以下错误:
gcc -static -O3 -o prog prog.c
/usr/bin/ld: cannot find -lc
collect2: ld returned 1 exit status
需要安装什么?
海湾合作委员会版本:
[user@localhost dir]$ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/libexec/gcc/x86_64-redhat-linux/4.6.1/lto-wrapper
Target: x86_64-redhat-linux
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla --enable-bootstrap --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-linker-build-id --enable-languages=c,c++,objc,obj-c++,java,fortran,ada,go,lto --enable-plugin --enable-java-awt=gtk --disable-dssi --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-1.5.0.0/jre --enable-libgcj-multifile --enable-java-maintainer-mode --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --disable-libjava-multilib --with-ppl --with-cloog --with-tune=generic --with-arch_32=i686 --build=x86_64-redhat-linux
Thread model: posix
gcc version 4.6.1 20110908 (Red Hat 4.6.1-9) (GCC)
-static
选项静态链接程序,换句话说,它不需要在运行时依赖动态库来运行。
要实现静态链接,需要系统上存在库的存档 (
.a
) 版本。所以/usr/lib/libc.a
、/usr/lib/crt1.o
等等
在现代 Linux 系统上(当您使用红帽时):当二进制文件链接在一起时 1) 通过
.o
和 .a
文件将代码放入可执行文件中,或者 2) 放入对动态库的引用 ( .so
)由 /lib/ld-linux.so
(或 /lib64/ld-linux=x86-64.so
)解析的文件,这些文件始终位于众所周知的位置。
对于您的特定系统,如果程序专门希望创建自身的静态版本,那么您需要安装开发工具的静态版本。 您至少需要
glibc-static
包。 您可能还需要 libstdc++-static
套餐。
-static
标志强制链接器仅接受静态库而不接受任何共享库。
如果你想使用
-static
,你必须确保安装了静态版本的C库,这可能很难找到(大多数系统不再有静态C库)。 或者你必须取消-static
的效果。 然而,在该示例中,这将违背 -static
的目的,因为唯一链接的库是(隐式)C 库。
在支持动态链接的系统上,这会覆盖 -pie 并阻止与共享库的链接。在其他系统上,此选项无效。