天天看點

Linux下undefined reference to 'pthread_create'解決方法

接觸了Linux系統程式設計中的線程程式設計子產品,可gcc sample.c(習慣把書上的sample代碼寫進sample.c檔案中)出現“undefined reference to ‘pthread_create’”,所有關于線程的函數都會有此錯誤,導緻無法編譯通過。

問題的原因:pthread不是Linux下的預設的庫,也就是在連結的時候,無法找到phread庫中哥函數的入口位址,于是連結會失敗。

解決:在gcc編譯的時候,附加要加 -lpthread參數即可解決。

#include <stdio.h> 
#include <pthread.h> 
#include <unistd.h> 
pthread_t ntid; 
void printids(const char * s) 
{ 
    pid_t pid; 
    pthread_t tid; 
    pid = getpid(); 
    tid = pthread_self(); 
    printf("%s pid %u tid %u (0x%x)\n",s,(unsigned int)pid, 
            (unsigned int)tid,(unsigned int)tid); 
} 
void * thr_fn(void * arg) 
{ 
    printids("new thread:"); 
    return ((void *)0); 
} 
int main(void) 
{ 
    int err; 
    err = pthread_create(&ntid,NULL,thr_fn,NULL); 
    if(err != 0) 
        printf("pthread_create error \n"); 
    printids("main thread:"); 
    sleep(1); 
    return 0; 
}
           
由于是Linux新手,是以現在才開始接觸線程程式設計,照着GUN/Linux程式設計指南中的一個例子輸入編譯,結果出現如下錯誤: undefined reference to 'pthread_create' undefined reference to 'pthread_join' 問題原因:    pthread 庫不是 Linux 系統預設的庫,連接配接時需要使用靜态庫 libpthread.a,是以在使用pthread_create()建立線程,以及調用 pthread_atfork()函數建立fork處理程式時,需要連結該庫。 問題解決:     在編譯中要加 -lpthread參數     gcc thread.c -o thread -lpthread     thread.c為你些的源檔案,不要忘了加上頭檔案#include<pthread.h>

繼續閱讀