Linux下undefined reference to ‘pthread_create’問題解決 zz


接觸了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; 
}

root@daoluan:/code/pthreadid# gcc sample.c
/tmp/cc1WztL9.o: In function `main’:
sample.c:(.text+0×83): undefined reference to `pthread_create’
collect2: ld returned 1 exit status

root@daoluan:/code/pthreadid# gcc -lpthread sample.c
root@daoluan:/code/pthreadid# ./a.out
main thread: pid 7059 tid 3078141632 (0xb778b6c0)
new thread: pid 7059 tid 3078138736 (0xb778ab70)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM