linux:gcc编译error:“collect2: ld returned 1 exit status” (Undefined reference )

在linux环境下编译一个工程,不管怎样编译,总是出现以下错误:

-bash-4.1$ gcc test.c consumers_producers.c
/tmp/ccQzS4PV.o: In function `main':
test.c:(.text+0x92): undefined reference to `pthread_create'
test.c:(.text+0xf2): undefined reference to `pthread_create'
test.c:(.text+0x123): undefined reference to `pthread_join'
collect2: ld returned 1 exit status

Undefined reference to 错误:

这类错误是在链接过程中出现的,可能有两种原因∶
一是使用者自己定义的函数或者全局变量所在源代码文件,没有被编译、链接,或者干脆还没有定义,这 需要使用者根据实际情况修改源程序,给出全局变量或者函数的定义体;
二是未定义的符号是一个标准的库函数,在源程序中使用了该库函数,而链接过程中还没有 给定相应的函数库的名称,或者是该档案库的目录名称有问题

出现此种错误,表示你的代码应该是没有问题的
经过作者我多番查找,才找出了原因,如下:

SYNOPSIS
       #include <pthread.h>

       int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);

       Compile and link with -pthread.

最重要的是这句话:

故在使用gcc编译的时候应该是:gcc xxx -pthread
一定要加上“-lpthread”,这样才可以编译通过
在上面的例子中:

应该是: gcc test.c consumers_producers.c -pthread

猜你喜欢

转载自blog.csdn.net/dangzhangjing97/article/details/80169103
今日推荐