【问题标题】:note: 'std::thread' is defined in header '<thread>'; did you forget to '#include <thread>'?注意:“std::thread”在标题“<thread>”中定义;你忘了'#include <thread>'吗?
【发布时间】:2019-11-17 02:27:58
【问题描述】:

我尝试在 c++ 中编译一个简单的 c++ 代码,但是当我尝试在 windows 中使用 g++ 编译它时不断返回错误。

我用

g++ -std=c++0x -pthread main.cpp

错误信息是:

std::thread' is defined in header '<thread>'; did you forget to '#include <thread>'?

这没有意义,因为代码只是

#include<thread>

void f(int i) {}

int main() {
        std::thread t(f, 1);
        t.join();
        return 0;
}

我相信这段代码在linux下可以工作,我想知道为什么它不能在windows下工作。

【问题讨论】:

  • &lt;thread&gt; 是 C++11 或更高版本的标头。您是在告诉 g++ 使用旧版本的语言。
  • 您还应该检查您使用的 g++ 的任何 Windows 端口是否支持 C++11 线程。 -pthread 选项在 Windows 上也有点奇怪......或者你的 G++ 是否使用 Windows 端口的 pthreads 而不是本机 Win32 线程?

标签: c++ multithreading c++11 g++


【解决方案1】:

要使用std::thread,您必须将代码编译为 C++11、C++14 或 C++17。

您正在将-std=c++0x 传递给 gcc。 c++0x 是用于 gcc C++11 实现的预发布版本的名称,根据您的编译器版本,可能不完整。

将您的 gcc 命令行更改为 -std=c++11 并且事情很可能会更好。如果没有,您可能需要获取更新版本的编译器。

【讨论】:

    【解决方案2】:

    Windows 有自己的非 POSIX 标准的线程 API。您需要了解的是(如何获取和)如何为您的编译器链接线程库。听起来您正在使用MinGW?我使用 MSVC,它会自动与 Windows 线程库链接。不幸的是,我不知道如何为 MinGW 执行此操作,因此这不是最佳答案,但这里有一个链接可能会让您入门:

    Does MinGW-w64 support std::thread out of the box when using the Win32 threading model?

    【讨论】:

      猜你喜欢
      • 2012-05-23
      • 1970-01-01
      • 2020-12-21
      • 2011-11-16
      • 1970-01-01
      • 2020-12-15
      • 2012-04-24
      • 1970-01-01
      相关资源
      最近更新 更多