【Linux】编译C语言文件(-o -lpthread)
生活随笔
收集整理的這篇文章主要介紹了
【Linux】编译C语言文件(-o -lpthread)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在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運行即可。
總結
以上是生活随笔為你收集整理的【Linux】编译C语言文件(-o -lpthread)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 成都欢乐谷比较安全的项目
- 下一篇: 【Linux】Ubuntu下进行C语言编