链接至-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
在我的机器上将一个小测试从约 800K 减少到约 700K,因此减少量并不是那么大。
以前的SO讨论:
来自其他链接单元的垃圾 https://stackoverflow.com/questions/4815177/garbage-from-other-linking-units
与 gcc 静态链接时如何仅包含使用过的符号? https://stackoverflow.com/questions/5307348/how-do-i-include-only-used-symbols-when-statically-linking-with-gcc
使用 GCC 查找无法访问的函数(“死代码”) https://stackoverflow.com/questions/4195494/using-gcc-to-find-unreachable-functions-dead-code
Update2:如果您满足于仅使用系统调用,则可以使用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 的可执行文件(其中仍然有一些应该可剥离的部分)。如果你想进一步查看this http://www.muppetlabs.com/~breadbox/software/tiny/teensy.html guide.