天天看點

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

繼續閱讀