【Linux】编译C语言文件(-o -lpthread)

    科技2024-04-11  77

    在gcc中使用-o编译

    对于一个一般的程序,直接使用gcc <C语言文件名> -o <编译后生成的文件名>即可,例如以下程序:

    // cpu.c

    #include <stdio.h> #include <unistd.h> #include <stdlib.h> int main(int argc,int *argv[]){ if(argc != 2){ fprintf(stderr,"need parameter\n"); exit(1); } char *str = argv[1]; for(int i = 0;i < 4;i++){ printf("%s\n",str); sleep(1); } return 0; }

    编译命令:gcc cpu.c -o cpu (这个警告不重要)之后就会生成可执行文件cpu,我们可以使用./cpu运行它。

    额外参数 -lpthread

    对于含有<pthread.h>的程序,例如下面的:

    // threads.c

    #include <stdio.h> #include <stdlib.h> #include <pthread.h> volatile int counter = 0; int loops; void *worker(void *arg) { int i; for (i = 0; i < loops; i++) { counter++; } return NULL; } int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "usage: threads <value>\n"); exit(1); } loops = atoi(argv[1]); pthread_t p1, p2; printf("Initial value : %d\n", counter); pthread_create(&p1, NULL, worker, NULL); pthread_create(&p2, NULL, worker, NULL); pthread_join(p1, NULL); pthread_join(p2, NULL); printf("Final value : %d\n", counter); return 0; }

    在编译的时候需要加上额外的参数-lpthread,因为该头文件在Linux默认Import Library中没有,需要使用库libpthread.a进行编译链接。

    命令gcc threads.c -o threads -lpthread

    然后会生成可执行文件threads,使用./threads运行即可。

    Processed: 0.019, SQL: 8