我从网上下载了以下演示: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
函数。有什么想法吗,出了什么问题?
到目前为止,这个问题的两个答案都是*错误的。<br>。 对于Linux来说,正确的命令是。
gcc -pthread -o term term.c
一般来说,库应该在命令行上跟随源和对象,-lpthread
不是一个"选项",它是一个库规范。在一个只安装了libpthread.a
的系统上。
gcc -lpthread ...
将无法链接。
实际上,它给出了几个用于pthreads代码的编译命令的例子,如下表所示,如果你继续阅读下面的教程。
https://computing.llnl.gov/tutorials/pthreads/#Compiling
![在此输入图片描述][1] 。