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 參數。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章