【发布时间】:2014-10-22 02:24:25
【问题描述】:
我正在尝试了解静态链接、加载 GCC 的过程:
我有以下玩具程序
#include "stdio.h"
int main() {
fprintf(stdout, "Hello World \n");
return 0 ;
}
我可以编译并运行文件如下:
gcc -static -std=gnu99 -Wall -Wno-unused -g test.c -o test;
但是一旦我尝试将编译和链接过程分开如下:
gcc -static -std=gnu99 -Wall -Wno-unused -g test.c -c;
ld -o test -T link.lds test.o
link.lds 在哪里
SECTIONS
{
. = 0x10000;
.text : { *(.text) }
. = 0x8000000;
.data : { *(.data) }
.bss : { *(.bss) }
}
我收到错误“未定义对 stdouttest.o 的引用:在函数‘main’中:
test.c:(.text+0x7): undefined reference to `stdout'
test.c:(.text+0x1e): undefined reference to `fwrite'
如果我尝试将标志 -lc 添加到 ld,它会告诉我找不到它。我试过用 -lc 运行 gcc 和/或 -static-libgcc 但我有同样的问题。
我做错了什么?
【问题讨论】:
-
我用 gcc-4.4.7 运行
gcc -static -std=gnu99 -Wall -Wno-unused -g test.c -c && gcc test.o -o test没有问题 -
这可以正常工作。但我特别关注将它与加载器(ld)一起使用
-
然后你会链接到
-lc,添加其他员工,如crt1.o、crtn.o、crtbegin.o、crtend.o等,它们与你的gcc相伴。你可以运行gcc -v test.o来检查gcc是如何完成这项工作的。 -
我设法做到了这一点: gcc -static test.c -lc -static-libgcc -c ; ld test.o -o test -lc --entry main --section-start=.txt=0x30000 --section-start=.bss=0x400000 --section-start=.data=0x500000 但是现在我得到了./test : 找不到二进制文件。它说当我将文件指定为静态时,该文件是动态链接的。关于复制 ld 输出,它依赖于 /tmp/...o 中的目标文件,当我重新运行 ld 命令时,该文件不存在 这是为什么我不重用 -v 的输出
-
避免使用
test作为可执行文件名,因为它是一个内置的shell。将-v添加到您的gcc命令以了解正在发生的事情,例如编译gcc -v -static -std=gnu99 -Wall -Wno-unused -g test.c -o mytest