c++ std:thread编译出错记录

本文详细介绍了如何在C++11中正确使用线程库。首先,需要确保编译器支持C++11标准,并通过指定编译选项来启用。其次,为使程序能够成功运行,还需链接到操作系统提供的线程库,如Linux下的libpthread。文章通过一个简单的示例程序,展示了从编译到执行过程中可能遇到的问题及解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://coderwall.com/p/rzkw6q


Consider the following code, which uses the C++11 (used to be known as C++0x) thread library:

#include <iostream>
#include <thread>

using namespace std;

void hello_world()
{
  cout << "Hello from thread!\n";
}

int main()
{
  thread t(hello_world);
  t.join();
  return 0;
}

How can we get this to work? If we compile it with:

g++ bare.cpp -o bare

We'll get something like:

/usr/include/c++/4.5/bits/c++0x_warning.h:31:2: error: #error This file requires compiler and library support for the upcoming ISO C++ standard, C++0x. This support is currently experimental, and must be enabled with the -std=c++0x or -std=gnu++0x compiler options.

... and maybe something about the thread type used in the code:

error: ‘thread’ was not declared in this scope

So we add the std=c++0x ...

g++ bare.cpp -std=c++0x -o bare

No errors during compilation, but when we try to execute bare...

$ ./bare
terminate called after throwing an instance of 'std::system_error'
  what():  
Aborted

... oops. We have to link this against the operating system's implementation of threads. In linux, this is the libpthread library. The winning command is:

g++ bare.cpp -std=c++0x -lpthread -o bare

and then:

$ ./bare
Hello from thread!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值