Linux 中对 pthread_create 的未定义引用

新手上路,请多包涵

我从 https://computing.llnl.gov/tutorials/pthreads/ 从网上获取了以下演示

#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS     5

void *PrintHello(void *threadid)
{
   long tid;
   tid = (long)threadid;
   printf("Hello World! It's me, thread #%ld!\n", tid);
   pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
   pthread_t threads[NUM_THREADS];
   int rc;
   long t;
   for(t=0; t<NUM_THREADS; t++){
      printf("In main: creating thread %ld\n", t);
      rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
      if (rc){
         printf("ERROR; return code from pthread_create() is %d\n", rc);
         exit(-1);
      }
   }
   pthread_exit(NULL);
}

但是当我在我的机器上编译它(运行 Ubuntu Linux 9.04)我得到以下错误:

 corey@ubuntu:~/demo$ gcc -o term term.c
term.c: In function ‘main’:
term.c:23: warning: incompatible implicit declaration of built-in function ‘exit’
/tmp/cc8BMzwx.o: In function `main':
term.c:(.text+0x82): undefined reference to `pthread_create'
collect2: ld returned 1 exit status

这对我来说没有任何意义,因为标题包括 pthread.h ,它应该具有 pthread_create 功能。任何想法出了什么问题?

原文由 Ralph 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 833
1 个回答

对于 Linux,正确的命令是:

 gcc -pthread -o term term.c

通常,库应该遵循命令行上的源和对象,而 -lpthread 不是“选项”,它是库规范。在仅安装了 libpthread.a 的系统上,

 gcc -lpthread ...

将无法链接。

原文由 Employed Russian 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题