pthread_create函数编译时报错:undefined reference to 'pthread_create'
錯誤:
pthread_create函數編譯時報錯:undefined reference to 'pthread_create'
pthread_create()和pthread_atfork()函數使用時應注意的問題:
源代碼:
#include <pthread.h>
void pmsg(void* p)
{
??? char *msg;
??? msg = (char*)p;
??? printf("%s ", msg);
}
int main(int argc, char *argv)
{
??? pthread_t t1, t2;
??? pthread_attr_t a1, a2;
??? char *msg1 = "Hello";
??? char *msg2 = "World";
??? pthread_attr_init(&a1);
??? pthread_attr_init(&a2);
??? pthread_create(&t1, &a1, (void*)&pmsg, (void*)msg1);
??? pthread_create(&t2, &a2, (void*)&pmsg, (void*)msg2);
??? return 0;
}
運行結果:
gcc thread.c -o thread
/tmp/ccFCkO8u.o: In function `main':
/tmp/ccFCkO8u.o(.text+0x6a): undefined reference to `pthread_create'
/tmp/ccFCkO8u.o(.text+0x82): undefined reference to `pthread_create'
collect2: ld returned 1 exit status
原因分析:
由于pthread 庫不是?Linux?系統默認的庫,連接時需要使用靜態庫 libpthread.a,所以在使用pthread_create()創建線程,以及調用 pthread_atfork()函數建立fork處理程序時,在編譯中要加 -lpthread參數。
解決辦法:
例如:在加了頭文件#include <pthread.h>之后執行 pthread.c文件,需要使用如下命令:
??? gcc thread.c -o thread?-lpthread
這種情況類似于<math.h>的使用,需在編譯時加 -m 參數。
總結
以上是生活随笔為你收集整理的pthread_create函数编译时报错:undefined reference to 'pthread_create'的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 秋冬季节吃什么水果好
- 下一篇: LINK : fatal error L