c - Linux 中对 pthread_create 的 undefined reference

标签 c linux multithreading pthreads

我从 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

这对我来说没有任何意义,因为 header 包含 pthread.h,它应该具有 pthread_create 函数。有什么想法吗?

最佳答案

对于 Linux,正确的命令是:

gcc -pthread -o term term.c

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

gcc -lpthread ...

将无法链接。

关于c - Linux 中对 pthread_create 的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1662909/

相关文章:

c - snprintf() ,溢出的可能性?

c - 打印小写字母、大写字母和数字个数

linux - 使用 awk 命令一次更改多个文件的文件类型

linux - 如何准确显示命令输出的 10 行

c# - 使用 Invoke 方法从外部线程关闭窗体

c - 3D vector 加速欧氏距离

c - 如何使用赋值(=)和相等(==)操作数创建语法?

python - 如何使用 Autokey 移动应用程序窗口?

java - java-me 支持线程吗?

c# - 为什么 WCF 服务能够处理来自不同进程的调用比来自线程的调用更多