如何使用线程类编译 cpp 文件?
How do I compile a cpp file with the thread class?
我正在学习使用线程,所以我正在尝试使用线程类运行代码,以便我可以同时运行函数。但是,尝试在终端中编译它,它说线程及其对象 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
知道我应该对这个错误做什么吗?
(操作系统:视窗,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();
}
知道我应该如何处理此错误吗?
您的代码在最新版本的 GCC (coliru.com( 中编译并运行良好。旧版本(例如 GCC 6(和-std=c++11
.您的问题一定在其他地方:
- 也许您正在使用一个非常旧的编译器?
- 也许您的C++标准库标头未安装?
- 也许您的C++标准库标题位于意想不到的地方?如果您使用的是自定义安装版本的编译器或标准库,则可能会发生这种情况。
相关文章:
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 命名空间中具有.h和.cpp文件的类
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 有充分的理由在h文件中使用include保护而不是cpp文件吗
- 如何在cpp文件之间切换窗口?在Qt中
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 我有两个类需要在同一 cpp 文件中相互引用,但第一个类无法识别第二个类类型的对象
- .h 和.cpp文件分离时出错,但仅使用 .h 文件时没有错误.我做错了什么?
- 库标题在标题中不可见,但在 cmake build 下.cpp文件中完全可见.为什么?
- C++ 链接到单独的.cpp文件说"multiple definitions"
- 在 cpp 文件中隐藏采用模板参数引用的方法
- 如何使用 samtools C API 构建一个简单的主.cpp文件
- 包含在.cpp文件中包含在 .h 文件时包含
- C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?
- 在头文件和 cpp 文件中使用一次 #pragma 时出现结构重定义错误
- 如何使用线程类编译 cpp 文件?
- 使用 Powershell 命令将 cpp 文件的文件夹编译为 GNU 的 g++
- 我应该将外部标头放在 .h 文件还是.cpp文件中?
- 从另一个 cpp 文件更改结构内、映射键内的变量