如何编译c程序,使其不依赖任何库? [英] How to compile c program so that it doesn't depend on any library?

查看:199
本文介绍了如何编译c程序,使其不依赖任何库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如何静态链接所有内容?

解决方案

链接 -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讨论:



在与gcc静态链接时,如何仅包含已用符号?


使用GCC查找无法访问的功能(死码)


$ b Update2:如果您满足于仅使用系统调用,则可以使用 gcc -freestanding -nostartfiles -static 真的得到小的可执行文件。



试试这个文件(small.c):

  #include< unistd.h> 

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

编译使用: gcc -freestanding -nostartfiles -static -o small small.c&&剥离小。这会在我的系统上生成一个〜5K的可执行文件(它仍然有几个应该可分离的部分)。如果您想进一步查看指南。


It seems even a 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.

这篇关于如何编译c程序,使其不依赖任何库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆