天天看點

unix環境進階程式設計-undefined reference to 'pthread_create'

筆者一直在學習unix環境進階程式設計。第十一章為線程程式設計。第一個程式就是列印線程ID。程式如下:

[cpp] view plaincopy

  1. #include "apue.h"  
  2. #include <pthread.h>  
  3. pthread_t ntid;  
  4. void printids(const char* s)  
  5. {  
  6.         pid_t     pid;  
  7.         pthread_t tid;  
  8.         pid=getpid();//得到目前程序id  
  9.         tid=pthread_self();//得到目前線程id  
  10.         printf("%s pid %u tid %u (0x%x)\n",s,(unsigned int)pid,(unsigned int) tid,(unsigned int )tid);  
  11. }  
  12. void* thr_fn(void* arg)  
  13. {  
  14.         printids("new thread: ");  
  15.         return((void*) 0);  
  16. }  
  17. int main(void)  
  18. {  
  19.         int err;  
  20.         err=pthread_create(&ntid,NULL,thr_fn,NULL);  
  21.         if(err!=0)  
  22.                 err_quit("can't create thread:%s\n",strerror(err));  
  23.                 printids("main thread :");  
  24.                 sleep(1);  
  25.                 exit(0);  
  26. }  

編譯指令:gcc -o pro_11.1 pro_11-1.c

就會報錯:錯誤如下:

[cpp] view plaincopy

  1. /tmp/ccAmLjR7.o: In function `main':  
  2. pro_11-1.c:(.text+0x307): undefined reference to `pthread_create'  
  3. collect2: ld ·µ»Ø 1  

經過網上查詢原因是:

    pthread 庫不是 Linux 系統預設的庫,連接配接時需要使用靜态庫 libpthread.a,是以在使用pthread_create()建立線程,以及調用 pthread_atfork()函數建立fork處理程式時,需要連結該庫。

問題解決:

    在編譯中要加 -lpthread參數

我用如下編譯指令:

[cpp] view plaincopy

  1. gcc -o pro_11.1 pro_11-1.c -lpthread  

程式輸出結果:

[cpp] view plaincopy

  1. main thread : pid 6123 tid 3086358208 (0xb7f616c0)  
  2. new thread:  pid 6123 tid 3086355344 (0xb7f60b90)  

版權聲明:本文為CSDN部落客「weixin_34038293」的原創文章,遵循CC 4.0 BY-SA版權協定,轉載請附上原文出處連結及本聲明。

原文連結:https://blog.csdn.net/weixin_34038293/article/details/92557661