在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!\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函数。 任何想法出了什么问题?

目前为止这个问题的答案都是不正确的
对于Linux,正确的命令是:

 gcc -pthread -o term term.c 

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

 gcc -lpthread ... 

将无法链接。

对于Linux使用:

 gcc -pthread -o term term.c 

-pthread指示编译器在pthread库中链接,并为线程configuration编译。

使用-lpthread选项只会导致pthread库被链接 – 预定义的macros不会被定义。

底线:你应该使用-pthread选项。

在日食

属性 – > c / c ++编译 – >设置 – > GCC C ++链接器 – >库顶部添加“pthread”

实际上,下面列出了几个用于pthreads代码的编译命令示例,如果您继续阅读以下教程:

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

在这里输入图像描述

您需要使用gcc选项-lpthread

你只需要在属性中添加“pthread”=> C / C ++ build => GCC C ++ Linker => Libraries =>顶部“Libraries(-l)”。 而已

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

在Anjuta,转到生成菜单,然后configuration项目。 在configuration选项框中,添加:

 LDFLAGS='-lpthread' 

希望它能帮助别人

有时,如果您使用多个库,请检查库依赖关系。 (例如-lpthread -lSDL … <==> … -lSDL -lpthread)