线程编译问题(undefined reference to `pthread_create’)

不管现实多么惨不忍睹,都要持之以恒地相信,这只是黎明前短暂的黑暗而已。不要惶恐眼前的难关迈不过去,不要担心此刻的付出没有回报,别再花时间等待天降好运。真诚做人,努力做事!你想要的,岁月都会给你。线程编译问题(undefined reference to `pthread_create’),希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

[cpp] 
view plain
copy

  1. #include <stdio.h>  
  2. #include <pthread.h>  
  3. #include <stdlib.h>  
  4.   
  5. void  
  6. printids(const char *s)  
  7. {  
  8.   
  9.         pid_t pid;  
  10.         pthread_t tid;  
  11.   
  12.         pid = getpid();  
  13.         tid = pthread_self();  
  14.         printf(“%s pid = [%u] tid = [%u] [0x%x]\n”,  
  15.                 s, (unsigned int)pid, (unsigned int)tid, (unsigned int)tid);  
  16.   
  17. }  
  18.   
  19. void *  
  20. thr_fn(void *arg)  
  21. {  
  22.   
  23.         printids(“new thread:”);  
  24.         return ((void *)0);  
  25.   
  26. }  
  27. int  
  28. main()  
  29. {  
  30.   
  31.         pthread_t ntid;  
  32.         int err;  
  33.   
  34.         err = pthread_create(&ntid, NULL, thr_fn, NULL);  
  35.         if(err != 0)  
  36.                 printf(“不能创建线程[%s]\n”,strerror(err));  
  37.         printids(“main thread:”);  
  38.         sleep(3);  
  39.         exit(0);  
  40. }  

[root@localhost pthread]# gcc test.c -o test

/tmp/ccq2Mbxs.o: In function `main’:
test.c:(.text+0x89): undefined reference to `pthread_create’
collect2: ld 返回 1
[root@localhost pthread]#
问题原因:
   pthread 库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a,所以在使用pthread_create()创建线程,以及调用 pthread_atfork()函数建立fork处理程序时,需要链接该库。

问题解决:
    在编译中要加 -lpthread参数
    gcc test.c -o test -lpthread

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/163102.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!