C/C++ linux 多线程编程报错 :undefined reference to `pthread_create‘

41 篇文章 6 订阅
7 篇文章 0 订阅

文档声明:
以下资料均属于本人在学习过程中产出的学习笔记,如果错误或者遗漏之处,请多多指正。并且该文档在后期会随着学习的深入不断补充完善。感谢各位的参考查看。


笔记资料仅供学习交流使用,转载请标明出处,谢谢配合。
如果存在相关知识点的遗漏,可以在评论区留言,看到后将在第一时间更新。
作者:Aliven888

  最近在做 linux 环境下编程时发现,在使用 C++ 11 中的线程类时,出现了下面的错误,这里做个笔记记录下。

demo 代码:

#include <stdio.h>
#include <iostream>
#include <thread>
using namespace std;

void printfB()
{
	std::cout  << " hello wordl " << endl;
}

int main(int argc, char *argv[])
{
	std::thread thd(printfB);
	thd.join();
	return 0;
}

编译脚本 :

g++ -o main -g testDemo.cpp

编译错误 :

aliven@Aliven:~$ g++ -o main -g testDemo.cpp 
/usr/bin/ld: /tmp/cci68K7i.o: in function `std::thread::thread<void (*)(), , void>(void (*&&)())':
/usr/include/c++/9/thread:126: undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status

问题分析: pthread不是linux下的默认的库,也就是在链接的时候,无法找到phread库中哥函数的入口地址,于是链接会失败。

解决方案: 编译命令后,附加 -lpthread 参数。

修改后的编译脚本:

g++ -std=c++11 testDemo.cpp -o main -lpthread

编译后执行:

aliven@Aliven:~$ ./main 
> hello wordl 
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值