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

无人久伴 提交于 2019-12-04 14:41:34
user786653

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!