gcc -static的作用

刚发现,这是一个神奇的命令!
比如,现在有个简单的程序。该程序依赖于动态库libpthread.so

#include <stdio.h>
#include <pthread.h>
/* this function is run by the second thread */
void *thread_exe(void x_void_ptr)
{
/
increment x to 100 */
int *x_ptr = (int *)x_void_ptr;
while(++(x_ptr) < 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;
/
create a second thread which executes thread_exe(&y) /
if(pthread_create(&inc_x_thread, NULL, thread_exe, &x)) {
fprintf(stderr, “Error creating thread\n”);
return 1;
}
/
increment y to 100 in the first thread /
while(++y < 100);
printf(“y increment finished\n”);
/
wait for the second thread to finish /
if(pthread_join(inc_x_thread, NULL)) {
fprintf(stderr, “Error joining thread\n”);
return 2;
}
/
show the results - x is now 100 thanks to the second thread /
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 test_main.c -static -o test_main -lpthread
结果,你会发现test_main文件很大!
chenxf@chenxf-PC:~/temp/test_main$ ll
-rwxrwxr-x 1 chenxf chenxf 1131418 6月 23 14:45 test_main

-rw-rw-r-- 1 chenxf chenxf 1081 6月 23 14:38 test_main.c
*
这是因为,test_main是静态的程序,它已经把各种依赖的函数,比如pthread_create()函数,以及所有pthread_create()依赖的任何东西,都包含进来了。跑test_main不需要依赖任何库了!

不加-static的情况

而如果你不加-static,结果就不同了。
gcc test_main.c -o test_main -lpthread
文件要小很多!
chenxf@chenxf-PC:~/temp/test_main$ ll
-rwxrwxr-x 1 chenxf chenxf 8891 6月 23 14:39 test_main

-rw-rw-r-- 1 chenxf chenxf 1081 6月 23 14:38 test_main.c
*

总结

当gcc -static 用于编译一个程序时,会使此程序静态编译(把动态库的函数和所依赖的任何的东西,都编译进本程序),编译好后,文件会非常大,但是,运行时就不需要依赖任何动态库。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值