【问题标题】:How to compile c program so that it doesn't depend on any library?如何编译c程序使其不依赖任何库?
【发布时间】:2011-08-15 12:19:26
【问题描述】:

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

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

如何静态链接所有内容?

【问题讨论】:

  • 为什么这对你很重要?任何地方的任何 Linux 系统都将有一个可用的 C 库和动态链接器。它们是 ABI 的一部分。
  • @Henning Makholm,在哪里描述了“linux ABI”?我的意思是 ABI,它说 libc.so.6ld-linux-x86-64.so.2 是其中的一部分。你见过没有 rootfs 的嵌入式 linux 吗?
  • @osgx:它主要是非正式的(非正式的 ABI 仍然是 ABI,只是更难确定它是什么),但我认为它在 FHS 中的某个地方写下来了。

标签: c linux gcc static-linking


【解决方案1】:

链接到-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 讨论:
Garbage from other linking units
How do I include only used symbols when statically linking with gcc?
Using GCC to find unreachable functions ("dead code")

更新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 &amp;&amp; strip small。这会在我的系统上生成约 5K 的可执行文件(其中仍有一些部分应该是可剥离的)。如果您想进一步了解this 指南。

【讨论】:

【解决方案2】:

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

各种“*nix 上的汇编器”网站可以让您了解如何操作。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 2020-02-14
    • 2012-08-01
    • 1970-01-01
    • 2021-12-17
    • 2015-03-26
    相关资源
    最近更新 更多