如何用MinGW编译C std :: thread代码?

我想用MinGW编译我的c 11项目(最近移到c 11).而且我有关于c 11代码的编译错误,例如“找不到std :: thread”.

我在gcc 5.3.0中使用了最新的MinGW(2015年12月).最后,我只想在编译我的大项目之前先编译此示例:

#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”和“ 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端口,该端口像在GCC中一样支持pthreading或gthreading.

为了解决这个问题,第一个解决方案是安装library of thread headers.
另一个解决方案可以与GCC编译器一起使用.

上一篇:c-stoi和std :: to_string在mingw 4.7.1


下一篇:c – 使用MinGW的g在Windows XP中编译Qt程序