为什么我的编译器不能识别#include <thread> (c++)?
Why doesn't my compiler recognize #include <thread> (c++)?
我将此作为多线程示例的简化版本来编写以感受一下,但 运行 在编译时遇到了一些问题。我的编译器说 thread
不是 std
的成员,并提示我将 #include <thread>
添加到我的代码中,即使我已经这样做了。到目前为止我一直找不到任何类似的问题,但我怀疑这是我编译它的方式的问题,因为我的代码与示例代码非常相似。
#include <iostream>
#include <thread>
void doWork () {
std::cout << "Working...\n";
}
int main () {
std::thread worker(doWork);
work.join();
std::cout << "Finished\n";
return 0;
}
我的编译器是 MinGW g++ 9.2.0
我用 g++ main.cpp -o main
编译,它给了我这些错误:
main.cpp: In function 'int main()':
main.cpp:9:7: error: 'thread' is not a member of 'std'
9 | std::thread worker(doWork);
| ^~~~~~
main.cpp:3:1: note: 'std::thread' is defined in header '<thread>'; did you forget to '#include <thread>'?
2 | #include <thread>
+++ |+#include <thread>
3 |
main.cpp:11:2: error: 'work' was not declared in this scope
11 | work.join();
| ^~~~
MinGW-w64 默认带有原生 (Win32) 而不是 POSIX 线程支持,不幸的是目前没有 Win32 gthreads 实现(libstdc++ 的线程子系统),因此 GCC 中没有线程功能。
您需要从 x86_64-w64-mingw32-g++-win32
切换到 x86_64-w64-mingw32-g++-posix
包才能让 std::thread
在 MinGW-w64 中工作。
问题 mingw-w64 threads: posix vs win32 更详细地讨论了这个问题。
我将此作为多线程示例的简化版本来编写以感受一下,但 运行 在编译时遇到了一些问题。我的编译器说 thread
不是 std
的成员,并提示我将 #include <thread>
添加到我的代码中,即使我已经这样做了。到目前为止我一直找不到任何类似的问题,但我怀疑这是我编译它的方式的问题,因为我的代码与示例代码非常相似。
#include <iostream>
#include <thread>
void doWork () {
std::cout << "Working...\n";
}
int main () {
std::thread worker(doWork);
work.join();
std::cout << "Finished\n";
return 0;
}
我的编译器是 MinGW g++ 9.2.0
我用 g++ main.cpp -o main
编译,它给了我这些错误:
main.cpp: In function 'int main()':
main.cpp:9:7: error: 'thread' is not a member of 'std'
9 | std::thread worker(doWork);
| ^~~~~~
main.cpp:3:1: note: 'std::thread' is defined in header '<thread>'; did you forget to '#include <thread>'?
2 | #include <thread>
+++ |+#include <thread>
3 |
main.cpp:11:2: error: 'work' was not declared in this scope
11 | work.join();
| ^~~~
MinGW-w64 默认带有原生 (Win32) 而不是 POSIX 线程支持,不幸的是目前没有 Win32 gthreads 实现(libstdc++ 的线程子系统),因此 GCC 中没有线程功能。
您需要从 x86_64-w64-mingw32-g++-win32
切换到 x86_64-w64-mingw32-g++-posix
包才能让 std::thread
在 MinGW-w64 中工作。
问题 mingw-w64 threads: posix vs win32 更详细地讨论了这个问题。