文档声明:
以下资料均属于本人在学习过程中产出的学习笔记,如果错误或者遗漏之处,请多多指正。并且该文档在后期会随着学习的深入不断补充完善。感谢各位的参考查看。
笔记资料仅供学习交流使用,转载请标明出处,谢谢配合。
如果存在相关知识点的遗漏,可以在评论区留言,看到后将在第一时间更新。
作者: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