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

来源:互联网 发布:花返网络股份有限公司 编辑:程序博客网 时间:2024/06/10 05:30
[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


转自:http://blog.csdn.net/silentpebble/article/details/6906117

0 0
原创粉丝点击