开发者

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

It seems even a开发者_StackOverflow社区 hello world program depends on several libraries:

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

How can I static link all stuff ?


Link with -static. "On systems that support dynamic linking, this prevents linking with the shared libraries."

Edit: Yes this will increase the size of your executable. You can go two routes, either do what Marco van de Voort recommends (-nostdlib, bake your own standard library or find a minimal one).

Another route is to try and get GCC to remove as much as it can.

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

Reduces a small test from ~800K to ~700K on my machine, so the reduction isn't really that big.

Previous SO discussions:
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")

Update2: If you are content with using just system calls, you can use gcc -ffreestanding -nostartfiles -static to get really small executable files.

Try this file (small.c):

#include <unistd.h>

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

Compile using: gcc -ffreestanding -nostartfiles -static -o small small.c && strip small. This produces a ~5K executable on my system (which still has a few sections that ought to be stripable). If you want to go further look at this guide.


Or use -nostdlib and implement your own libraries and startup code.

The various "assembler on *nix" sites can give you an idea how to do it.

If you just want your binary to be small, start by using 32-bit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜