开发者

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

开发者 https://www.devze.com 2023-03-28 17:20 出处:网络
It seems even a开发者_StackOverflow社区 hello world program depends on several libraries: libc.so.6 => /lib64/libc.so.6 (0x00000034f4000000)

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

精彩评论

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

关注公众号