在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
運行即可。