如何使用mingw编译C STD ::线程代码

How to compile C++ std::thread code with MinGW?

本文关键字:线程 代码 STD 何使用 mingw 编译      更新时间:2023-10-16

我想用mingw编译我的C 11项目(最近移至C 11(。而且我有关于C 11代码的编译错误,例如" std ::未找到线程"。

我使用了GCC 5.3.0(2015年12月(的最后一个mingW。a结尾,我只想在编译我的大项目之前编译这个示例:

#include <iostream>
#include <thread>
#include <chrono>
void foo()
{
    // simulate expensive operation
    std::this_thread::sleep_for(std::chrono::seconds(1));
}
void bar()
{
    // simulate expensive operation
    std::this_thread::sleep_for(std::chrono::seconds(1));
}
int main()
{
    std::cout << "starting first helper...n";
    std::thread helper1(foo);
    std::cout << "starting second helper...n";
    std::thread helper2(bar);
    std::cout << "waiting for helpers to finish..." << std::endl;
    helper1.join();
    helper2.join();
    std::cout << "done!n";
}

(来源:http://en.cppreference.com/w/cpp/thread/thread/join(

我尝试了" g -std = c 11 main.cpp"answers" g main.cpp -std = c 0x",但我始终有以下错误:

main.cpp: In function 'void foo()':
main.cpp:8:10: error: 'std::this_thread' has not been declared
     std::this_thread::sleep_for(std::chrono::seconds(1));
          ^
main.cpp: In function 'void bar()':
main.cpp:14:10: error: 'std::this_thread' has not been declared
     std::this_thread::sleep_for(std::chrono::seconds(1));
          ^
main.cpp: In function 'int main()':
main.cpp:20:5: error: 'thread' is not a member of 'std'
     std::thread helper1(foo);
     ^
main.cpp:23:5: error: 'thread' is not a member of 'std'
     std::thread helper2(bar);
     ^
main.cpp:26:5: error: 'helper1' was not declared in this scope
     helper1.join();
     ^
main.cpp:27:5: error: 'helper2' was not declared in this scope
     helper2.join();
     ^

mingw大多没有glibc的端口,该端口支持pthreading或gthreading,例如gcc中。

为了解决此问题,第一个解决方案可以安装线程标头库。另一种解决方案可以与GCC编译器一起使用。