lex*_*xer 3 c linux gcc static-linking
似乎一个hello world程序依赖于几个库:
libc.so.6 => /lib64/libc.so.6 (0x00000034f4000000)
/lib64/ld-linux-x86-64.so.2 (0x00000034f3c00000)
Run Code Online (Sandbox Code Playgroud)
我如何静态链接所有东西?
链接-static."在支持动态链接的系统上,这可以防止与共享库的链接."
编辑:是的,这将增加可执行文件的大小.您可以选择两条路线,或者执行Marco van de Voort建议的路线(-nostdlib烘烤您自己的标准库或找到最小的库).
另一种方法是尝试让GCC尽可能地删除.
gcc -Wl,--gc-sections -Os -fdata-sections -ffunction-sections -ffunction-sections -static test.c -o test
strip test
Run Code Online (Sandbox Code Playgroud)
在我的机器上将小测试从~800K减少到~700K,因此减少的幅度并不大.
以前的SO讨论:
来自其他链接单元的垃圾
如何在与gcc静态链接时仅包含使用过的符号?
使用GCC查找无法访问的函数("死代码")
Update2:如果您满足于仅使用系统调用,则可以使用gcc -ffreestanding -nostartfiles -static获取非常小的可执行文件.
试试这个文件(small.c):
#include <unistd.h>
void _start() {
char msg[] = "Hello!\n";
write(1, msg, sizeof(msg));
_exit(0);
}
Run Code Online (Sandbox Code Playgroud)
编译使用:gcc -ffreestanding -nostartfiles -static -o small small.c && strip small.这会在我的系统上生成一个~5K的可执行文件(它仍然有一些应该是可剥离的部分).如果您想进一步了解本指南.