c - 将 libgcc 链接到 -nostdlib 编译

标签 c gcc libgcc

我正在尝试生成一个不依赖于 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/

相关文章:

ffmpeg - 使用 Android NDK r17 : undefined reference to '__mulodi4' 构建 C 库 (FFmpeg)

c - 将 char 转换为整数并返回值的函数 [C]

gcc - fatal error : gnu/stubs-soft. h:无此类文件或目录

c - gcc 编译的 main() 中无用序言的动机,禁用它?

c - 静态和内联

c - 如何创建结构体并通过 pthread_create() 传递给新线程

printf() 中可以有 '+' 运算符吗?

iphone - 为什么这个 C 风格的代码比这个 obj-C 风格的代码慢 10 倍?

gcc - 裸机 mod (%) 在带有 libgcc 的 ARMv6 上挂起