undefined reference to 'pthread_create'

来源:互联网 发布:编程的希望纪录片 编辑:程序博客网 时间:2024/05/17 22:41

因为明天要学Linux 多线程所以就先预习了一下。

看着参考资料写完创建线程函数时,进行编译,擦,报告undefined reference to 'pthread_create'错误

我也引入了需要的头文件。

#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
void printfids(const char *s)
{
pid_t pid;
pthread_t tid;
pid=getpid();
tid=pthread_self();
printf("%s pid %u tid %u %u (0x%x) \n ",s,(unsigned int ) pid,
(unsigned int )tid,( unsigned int )pid);

}
void *thfun(void *arg)
{
printfids("new thread :");
return ((void *)0);
}

int main(int argc ,char *argv[])
{
int ret;
pthread_t pthid;
ret=pthread_create(&pthid,NULL,thfun,NULL);
//If attr is NULL, the default attributes shall be used.
//第二个参数ifNULL,则创建默认属性的进程。
if(ret!=0)
perror("can't creat thread ");
printfids("main thread :");
sleep(1);
exit(0);
}
gcc 编译结果报告undefined reference to 'pthread_create'错误

左看看右看看,没有错啊,搞了半个小时没有出来,于是就百了一下。

问题原因:

pthread 库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a,所以在使用pthread_create()创建线程,需要链接该库。

在编译中要加 -lpthread参数
gcc thread.c -o thread -lpthread
thread.c为你写的源文件,不要忘了加上头文件#include<pthread.h>

 

原创粉丝点击