【问题标题】:How do I compile a cpp file with the thread class? [duplicate]如何使用线程类编译 cpp 文件? [复制]
【发布时间】:2018-10-18 20:55:39
【问题描述】:

我正在学习使用线程,所以我尝试使用线程类运行代码,以便我可以同时运行函数。但是,尝试在终端中编译它,它说线程及其对象 t1 未声明。

 threading.cpp:16:5: error: 'thread' was not declared in this scope
     thread t1(task1, "Hello");
     ^~~~~~
 threading.cpp:21:5: error: 't1' was not declared in this scope
     t1.join();

我以为 g++ 不支持它,但我还在它的论点中加入了支持 c++11 的参数

  g++ -std=c++11 threading.cpp

知道我应该如何处理这个错误吗?

(操作系统:windows,gcc 版本 6.3.0)

代码如下(来自网站的示例):

#include <string>
#include <iostream>
#include <thread>

using namespace std;

// The function we want to execute on the new thread.
void task1(string msg)
{
    cout << "task1 says: " << msg;
}

int main()
{
    // Constructs the new thread and runs it. Does not block execution.
    thread t1(task1, "Hello");

    // Do other things...

    // Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
    t1.join();
}

【问题讨论】:

  • 请将命令和错误发布为文本而不是图像。对于可以看到图像的人,这会使您的问题无法回答。
  • g++ 编译 c++ 代码,而gcc 编译 c 代码。
  • @πάνταῥεῖ 比这更复杂。
  • 所以你的问题真的是'为什么我不能编译这个 c++11 线程代码?'
  • 你有什么版本的g++?您可以通过运行g++ -v 来获取它

标签: c++ multithreading c++11 mingw


【解决方案1】:

知道我应该如何处理这个错误吗?

您的代码compiles and runs fine with a recent version of GCC (coliru.com)。对于旧版本(例如 GCC 6)和 -std=c++11 也是如此。您的问题一定出在其他地方:

  • 也许您使用的是非常旧的编译器?
  • 也许您的 C++ 标准库头文件没有安装?
  • 也许您的 C++ 标准库头文件位于意外的位置?如果您使用的是编译器或标准库的自定义安装版本,则可能会发生这种情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-31
    • 1970-01-01
    • 2017-04-28
    • 1970-01-01
    • 2020-08-23
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多