gpt4 book ai didi

c - 将 libgcc 链接到 -nostdlib 编译

转载 作者:行者123 更新时间:2023-12-02 01:50:00 25 4
gpt4 key购买 nike

我正在尝试生成一个不依赖于 libc(或任何其他)的可执行文件。首先,我这样做了:

// test.c
void _start()
{
// write(1, "hello!\n", 7);
asm ("int $0x80"::"a"(4), "b"(1), "c"("hello!\n"), "d"(7));

// exit(0);
asm ("int $0x80"::"a"(1), "b"(0));
}

gcc -m32 -nostdlib test.c -o test 编译:

hello

到目前为止一切顺利。后来我尝试使用一些更“高级”的 C,比如 long long。在 32 位平台上(我的情况)这需要 libgcc:

// test.c
void _start()
{
volatile long long int a = 10;
volatile long long int b = 5;
volatile int c = a/b; // Implemented as a call to '__divdi3'
}

编译失败,undefined reference to '__divdi3'。似乎是正确的,因为我实际上并没有告诉它链接。但是添加标志 -static-libgcc 并不能解决问题!为什么?

请注意,我无法动态链接到 libgcc。以下必须成立:

$ ldd test
not a dynamic executable

我正在使用 gcc 4.8.2 从 64 位 Ubuntu 14.04 编译(没什么特别的)。

最佳答案

最终我自己找到了解决方案。似乎 gcc 无法找到该库,也没有费心去提示它。我运行了以下命令:

$ locate libgcc.a
/usr/lib/gcc/x86_64-linux-gnu/4.8/libgcc.a
/usr/lib/gcc/x86_64-linux-gnu/4.8/32/libgcc.a
/usr/lib/gcc/x86_64-linux-gnu/4.8/x32/libgcc.a

然后我没有将 -static-libgcc 提供给编译器,而是将标志更改为:

gcc -m32 -nostdlib test.c -o test -L/usr/lib/gcc/x86_64-linux-gnu/4.8/32 -lgcc

它编译并运行得很好!


-L 是多余的。以下也适用:

gcc -m32 -nostdlib test.c -o test -lgcc

关于c - 将 libgcc 链接到 -nostdlib 编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23410221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com