在 Linux 中对 pthread_create 的未定义引用 [英] Undefined reference to pthread_create in Linux

查看:83
本文介绍了在 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!
", 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
", t);
      rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
      if (rc){
         printf("ERROR; return code from pthread_create() is %d
", rc);
         exit(-1);
      }
   }
   pthread_exit(NULL);
}

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

But when I compile it on my machine (running Ubuntu Linux 9.04) I get the following error:

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 函数.知道出了什么问题吗?

This doesn't make any sense to me, because the header includes pthread.h, which should have the pthread_create function. Any ideas what's going wrong?

推荐答案

对于 Linux,正确的命令是:

For Linux the correct command is:

gcc -pthread -o term term.c

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

In general, libraries should follow sources and objects on command line, and -lpthread is not an "option", it's a library specification. On a system with only libpthread.a installed,

gcc -lpthread ...

将无法链接.

这篇关于在 Linux 中对 pthread_create 的未定义引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆