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


当前回答

我相信在CMake中添加pthread的正确方法如下

find_package (Threads REQUIRED)

target_link_libraries(helloworld
    ${CMAKE_THREAD_LIBS_INIT}
)

其他回答

我相信在CMake中添加pthread的正确方法如下

find_package (Threads REQUIRED)

target_link_libraries(helloworld
    ${CMAKE_THREAD_LIBS_INIT}
)

你只需要在properties中添加“pthread”=>C/ c++ build=>GCC c++ Linker=>Libraries=>顶部部分“Libraries(-l)”。 这是它

在Anjuta中,转到Build菜单,然后配置项目。 在“配置选项”框中添加:

LDFLAGS='-lpthread'

希望它也能帮助到别人…

从Linux终端运行,对我来说有用的是使用以下命令进行编译(假设我想编译的c文件名为test.c):

gcc -o test test.c -pthread

希望它能帮助到一些人!

在eclipse中

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