undefined reference to `pthread_create'错误
- 问题描述
- 问题原因及解决
问题描述
在使用linux编译创建多线程时会出现undefined reference to `pthread_create’错误
命令行编译错误结果如下
[email protected]DESKTOP-EIC0724:~$ gcc -pthread pthread_create.c
/tmp/cc3e3bXk.o: In function `main':
pthread_creat.c:(.text+0x90): undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status
问题原因及解决
首先看一下男人:
[email protected]:~$ man pthread_create
NAME
pthread_create - create a new thread
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.
在最后一句Compile and link with -pthread意思是编译需要附加-pthread
也就是说pthread不是Linux下的默认的库,在链接的时候,无法找到phread库中函数的入口地址,于是链接会失败。所以在gcc编译的时候,附加要加 -lpthread 参数即可解决。
注意: ubuntu必须把-pthread放在后面
我在连接的时候首先就把-pthread加上,但是还是出现这种错误,而其他非Ubuntu的Linux发行版不会出现此类错误,具体做法参考如下.
[email protected]DESKTOP-EIC0724:~$ gcc pthread_create.c -o pthread_create -pthread