繁体   English   中英

如何编译 c 程序使其不依赖任何库?

[英]How to compile c program so that it doesn't depend on any library?

似乎一个 hello world 程序也依赖于几个库:

libc.so.6 => /lib64/libc.so.6 (0x00000034f4000000)
/lib64/ld-linux-x86-64.so.2 (0x00000034f3c00000)

我怎样才能 static 链接所有的东西?

-static链接。 “在支持动态链接的系统上,这会阻止与共享库的链接。”

编辑:是的,这将增加您的可执行文件的大小。 你可以 go 两条路线,要么按照 Marco van de Voort 的建议( -nostdlib ,烘焙你自己的标准库或找到一个最小的)。

另一种方法是尝试让 GCC 尽可能多地删除。

gcc  -Wl,--gc-sections -Os -fdata-sections -ffunction-sections -ffunction-sections -static test.c -o test
strip test

将我机器上的小测试从 ~800K 减少到 ~700K,因此减少量并不是那么大。

以前的 SO 讨论:
来自其他链接单元的垃圾
与 gcc 静态链接时,如何仅包含使用的符号?
使用 GCC 查找无法访问的函数(“死代码”)

更新 2:如果您满足于仅使用系统调用,则可以使用gcc -ffreestanding -nostartfiles -static来获取非常小的可执行文件。

试试这个文件(small.c):

#include <unistd.h>

void _start() {
    char msg[] = "Hello!\n";
    write(1, msg, sizeof(msg));
    _exit(0);
}

编译使用: gcc -ffreestanding -nostartfiles -static -o small small.c && strip small 这会在我的系统上生成约 5K 的可执行文件(其中仍有一些部分应该是可剥离的)。 如果您想 go 进一步查看指南。

或者使用-nostdlib并实现您自己的库和启动代码。

各种“*nix 上的汇编程序”站点可以让您了解如何执行此操作。

如果您只想让您的二进制文件变小,请从使用 32 位开始。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM