undefined reference to 'pthread_create'

因为明天要学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>

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值