刚发现,这是一个神奇的命令!
比如,现在有个简单的程序。该程序依赖于动态库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 用于编译一个程序时,会使此程序静态编译(把动态库的函数和所依赖的任何的东西,都编译进本程序),编译好后,文件会非常大,但是,运行时就不需要依赖任何动态库。