博客
关于我
gcc -static 命令
阅读量:489 次
发布时间:2019-03-07

本文共 1867 字,大约阅读时间需要 6 分钟。

好的,以下是优化后的文章:


刚发现这是一个神奇的命令!比如,我们有一个简单的程序,这个程序依赖动态库 libpthread.so。想象一下,现在有一个程序,它依靠第二个线程来完成某些任务。那我们可以通过观察这个程序,看看它是如何运行的。

首先,让我们看看这个程序的代码:

#include 
#include
void *thread_exe(void *x_void_ptr) { /* 这个函数由第二个线程执行 */ int *x_ptr = (int *)x_void_ptr; while (++(*x_ptr) < 100); // 增加到 100 printf("x increment finished\n"); return NULL;}int testFunc(int param) { printf(" testFunc %i\n", param); pthread_t inc_x_thread; int x = 0, y = 0; /* 创建一个线程运行 thread_exe(&y) */ if (pthread_create(&inc_x_thread, NULL, thread_exe, &y)) { fprintf(stderr, "Error creating thread\n"); return 1; } /* 在第一个线程中,增加 y 的值 */ while (++y < 100) { printf("y increment finished\n"); } /* 等待第二个线程完成 */ if (pthread_join(inc_x_thread, NULL)) { fprintf(stderr, "Error joining thread\n"); return 2; } /* 展示结果 */ printf("x: %d, y: %d\n", x, y); return 0;}int main(int argc, char *argv) { int a = 100; testFunc(a); return 1;}

static 编译的情况

编译时使用 gcc -static 会让程序静态编译。这意味着所有依赖的函数和相关内容都会被编译到程序中。比如:

gcc test_main.c -static -o test_main -lpthread

运行后,你会发现生成的程序文件非常大!这是因为静态编译会将所有相关的函数(例如 pthread_create() 和其所有依赖)都编译进去,程序不再依赖外部动态库。为了验证这一点,我们可以使用 nm 工具检查文件主аних:

nm test_main

截取部分结果:

0000000000404fb0 T __pthread_cleanup_push0000000000404fb0 T _pthread_cleanup_push...

可以看到,和 pthread 相关的各种函数都被包含进来了。


不加 -static 的情况

如果不使用 -static 加编译:

gcc test_main.c -o test_main -lpthread

生成的程序文件会变得小很多!使用 nm 检查时,只会看到少量的函数:

0000000000601060 B __bss_start...U printf@@GLIBC_2.2.5U pthread_create@@GLIBC_2.2.5U pthread_join@@GLIBC_2.2.5

这些符号表示这些函数是从动态库中导入的。


总结

当使用 gcc -static 编译程序时,会将所有依赖的动态库函数以及它们的支持内容编制入程序,生成的大文件体量较大,但运行时无需外部动态库支持。相反,如果不加 -static,程序依赖动态库,文件会小许多,但运行时需要这些库。静态编译的好处是最大程度地减少依赖,缺点则是文件体量较大。

如果对编译过程不太熟悉,或者想进一步了解如何优化程序性能,可以继续探索更多的编译选项。比如,了解哪些选项会影响程序的调试体验,或者怎样平衡 compilation speed 计划和程序的大小等。


转载地址:http://lwedz.baihongyu.com/

你可能感兴趣的文章
Python趣味编程:用代码创造无限可能
查看>>
Python UI自动化测试三方库扩展详解
查看>>
Python UI自动化测试与Web UI自动化测试框架详解
查看>>
python谷歌翻译,2021年9月10日亲测可用,一次可以翻译十万,强烈star
查看>>
Python UI自动化测试数据驱动实战
查看>>
Python UI自动化测试集成UnitTest
查看>>
Python UI自动化测试集成UnitTest
查看>>
python unicode-escape
查看>>
Python unittest mock:是否可以在测试时模拟方法默认参数的值?
查看>>
Python unittest单元测试框架 TestSuite测试套件
查看>>
PYTHON调离线语音合成并实时播放
查看>>
python unittest高级特性!
查看>>
Python unittest:如何将标准输出消息临时重定向到缓冲区并测试其内容?
查看>>
Python urllib/Requests下载文件失败,但浏览器下载失败
查看>>
Python urllib2 文件上传问题
查看>>
Python urllib2.open 连接由对等错误重置
查看>>
python urllib2详解及实例
查看>>
Python url请求提示certificate verify failed unable to get local issuer certificate
查看>>
Python UTC 日期时间对象的 ISO 格式不包括 Z(祖鲁语或零偏移)
查看>>
python valueerror object2_python遇到错误记录
查看>>