【发布时间】:2014-11-27 11:20:01
【问题描述】:
我正在尝试使用 GCC 的动态和静态链接来编译一个非常简单(就像 hello world 一样简单)的 C 程序。我想知道一般情况下如何做到这一点,所以我的最小测试示例只是尝试将 libc 链接为静态和动态的 libm。
我至少遇到过以下关于同一主题的其他问题:
GCC: static linking only some libraries
Static link of shared library function in gcc
其中的一些答案提出了一些建议,例如使用 -Wl,-Bstatic 和 -Wl,-Bdynamic 来指定哪些库分别是静态和动态的。还建议简单地指定要链接的静态库的完整路径。
我已经尝试了其中的几个建议及其变体。我不明白它给我的错误信息。我知道 PIE 是什么,但我不明白它与我正在尝试做的事情有什么关系。
以下是一些失败的尝试:
$ gcc test.c /usr/lib64/libc.a
linux-gnu/4.7.3/../../../../x86_64-pc-linux-gnu/bin/ld: dynamic STT_GNU_IFUNC symbol `strcmp' with pointer equality in `/usr/lib64/libc.a(strcmp.o)' can not be used when making an executable; recompile with -fPIE and relink with -pie
urned 1 exit status
$ gcc test.c -Wl,-Bdynamic -lm -Wl,-Bstatic -lc
/usr/lib/gcc/x86_64-pc-linux-gnu/4.7.3/../../../../x86_64-pc-linux-gnu/bin/ld: cannot find -lgcc_s
/usr/lib/gcc/x86_64-pc-linux-gnu/4.7.3/../../../../x86_64-pc-linux-gnu/bin/ld: cannot find -lgcc_s
collect2: error: ld returned 1 exit status
$ gcc -Wl,-Bdynamic -lm -Wl,-Bstatic -lc test.c
/usr/lib/gcc/x86_64-pc-linux-gnu/4.7.3/../../../../x86_64-pc-linux-gnu/bin/ld: cannot find -lgcc_s
/usr/lib/gcc/x86_64-pc-linux-gnu/4.7.3/../../../../x86_64-pc-linux-gnu/bin/ld: cannot find -lgcc_s
collect2: error: ld returned 1 exit status
$ gcc -Wl,-Bstatic -lc -Wl,-Bdynamic -lm test.c
/usr/lib/gcc/x86_64-pc-linux-gnu/4.7.3/../../../../x86_64-pc-linux-gnu/bin/ld: dynamic STT_GNU_IFUNC symbol `strcmp' with pointer equality in `/usr/lib/gcc/x86_64-pc-linux-gnu/4.7.3/../../../../lib64/libc.a(strcmp.o)' can not be used when making an executable; recompile with -fPIE and relink with -pie
collect2: error: ld returned 1 exit status
只编译不带参数,使用 -static 工作正常,但我需要 部分 静态编译:
$ gcc test.c -lm
$ gcc -static test.c -lm
但是,以下也失败了:
$ gcc test.c /usr/lib64/libc.a /usr/lib64/libm.a
我在这篇文章中遇到了类似的错误:
C++ Statically linked shared library
但是答案似乎不适用于我的问题。
我要编译的程序很简单(如 test.c):
#include <stdio.h>
#include <math.h>
int main(int argc, char **argv)
{
int i = 0;
for(i = 0; i < 65535; i++) {
printf("%f\n", sinf(i));
printf("%f\n", cosf(i));
printf("%f\n", tanf(i));
printf("%f\n", sqrtf(i));
}
return 0;
}
编辑:请注意,程序必须足够复杂才能实际需要 libm,否则如果真的不需要 libm,链接尝试可能会产生误报。在我最初的 test.c 示例中,我只使用了 sinf() 到一个常量值,这使得编译器完全优化了 sinf() 调用。
我正在使用:
$ gcc --version
gcc (Gentoo 4.7.3-r1 p1.4, pie-0.5.5) 4.7.3
【问题讨论】:
-
您是否尝试按照 gcc 的建议进行操作(查看失败消息)?
-
-fPIE 和 -pie 对我来说毫无意义,无论如何我都不想编译为 PIE。
标签: c gcc compilation static-linking