Linux下undefined reference to ‘pthread_create’问题解决

以你之姓@ 2022-06-09 09:19 359阅读 0赞

接触了Linux系统编程中的线程编程模块,可gcc sample.c(习惯把书上的sample代码写进sample.c文件中)出现“undefined reference to ‘pthread_create’”,所有关于线程的函数都会有此错误,导致无法编译通过。

问题的原因:pthread不是Linux下的默认的库,也就是在链接的时候,无法找到phread库中哥函数的入口地址,于是链接会失败。

解决:在gcc编译的时候,附加要加 -lpthread参数即可解决。

  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <unistd.h>
  4. pthread_t ntid;
  5. void printids(const char * s)
  6. {
  7. pid_t pid;
  8. pthread_t tid;
  9. pid = getpid();
  10. tid = pthread_self();
  11. printf("%s pid %u tid %u (0x%x)\n",s,(unsigned int)pid,
  12. (unsigned int)tid,(unsigned int)tid);
  13. }
  14. void * thr_fn(void * arg)
  15. {
  16. printids("new thread:");
  17. return ((void *)0);
  18. }
  19. int main(void)
  20. {
  21. int err;
  22. err = pthread_create(&ntid,NULL,thr_fn,NULL);
  23. if(err != 0)
  24. printf("pthread_create error \n");
  25. printids("main thread:");
  26. sleep(1);
  27. return 0;
  28. }

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)

本文完 2012-07-15

捣乱小子 http://www.daoluan.net/

由于是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

发表评论

表情:
评论列表 (有 0 条评论,359人围观)

还没有评论,来说两句吧...

相关阅读