我从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函数。知道哪里出了问题吗?


当前回答

在eclipse中

属性->c/c++构建->设置->GCC c++连接器->库在顶部添加“pthread”

其他回答

如果你正在使用cmake,你可以使用:

add_compile_options(-pthread)

Or

SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread")

像这样编译:gcc demo.c -o demo -pthread

在eclipse中

属性->c/c++构建->设置->GCC c++连接器->库在顶部添加“pthread”

你需要在gcc中使用-lpthread选项。

实际上,如果你继续阅读下面的教程,它给出了几个用于pthreads代码的编译命令示例,如下表所示:

https://computing.llnl.gov/tutorials/pthreads/#Compiling