+ -
当前位置:首页 → 问答吧 → FB8上无法编译多线程代码(已自已解决)

FB8上无法编译多线程代码(已自已解决)

时间:2010-08-06

来源:互联网

本帖最后由 cgmeco 于 2010-08-07 01:04 编辑
  1. #include <stdio.h>
  2. #include <pthread.h>

  3. void thread1(void)
  4. {
  5.         int i=0;
  6.         for(i=0;i<6;i++){
  7.                 printf("This is a pthread1.\n");
  8.                 if(i==2)
  9.                         pthread_exit(0);
  10.                 sleep(1);
  11.                 }
  12. }

  13. void thread2(void)
  14. {
  15.         int i;
  16.         for(i=0;i<3;i++)
  17.                 printf("This is a pthread2.\n");
  18.         pthread_exit(0);
  19. }

  20. int main(void)
  21. {
  22.         pthread_t id1,id2;
  23.         int i,ret;
  24.         ret=pthread_create(&id1,NULL,(void *) thread1,NULL);
  25.         if(ret!=0){
  26.                 printf ("Create pthread error!\n");
  27.         exit (1);
  28.         }
  29.         ret=pthread_create(&id2,NULL,(void *) thread2,NULL);
  30.         if(ret!=0){
  31.                 printf ("Create pthread error!\n");
  32.                 exit (1);
  33.         }
  34.         pthread_join(id1,NULL);
  35.         pthread_join(id2,NULL);
  36.         exit (0);
  37. }
复制代码
在FB8上编译时,出现以下错误,
  1. [workstation@fse ~/programer/cprgm]$ gcc thread.c
  2. thread.c: In function 'main':
  3. thread.c:30: warning: incompatible implicit declaration of built-in function 'exit'
  4. thread.c:35: warning: incompatible implicit declaration of built-in function 'exit'
  5. thread.c:39: warning: incompatible implicit declaration of built-in function 'exit'
  6. /var/tmp//ccsujMHW.o(.text+0xc1): In function `main':
  7. : undefined reference to `pthread_create'
  8. /var/tmp//ccsujMHW.o(.text+0x106): In function `main':
  9. : undefined reference to `pthread_create'
复制代码
实在想不通,为什么会出现无法引用的问题,难道我的GCC安装不完全!求高手指导!

作者: cgmeco   发布时间: 2010-08-06

在网上google才发现,由于涉及多线程的程序编译,在编译时需要链接pthread库。

所以上面的代码在编译时要做如下操作:
  1. gcc -o thread -lpthread thread.c
复制代码

作者: cgmeco   发布时间: 2010-08-07