std::thread works in cygwin but not in MinGw

2019-09-11 02:40发布

问题:

So I decided to give c++ a try today. I downloaded MinGw and the g++ compiler that comes with it. I decided to test the following code:

#include <iostream>
#include <thread>

int foo()
{
    std::cout << "foo" << std::endl;
}

int main()
{
    std::thread t1(foo);
    t1.join();
    std::cout << "done" << std::endl;
    return 0;
}

I then tried to compile it on the command line using the following line:

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

Which works for hello world. This time however, it gave me this error:

error: 'thread' is not a member of 'std'

I tried the exact same code using the g++ provided by cygwin, and it works. So why doesn't it work in MinGw? Is it outdated or something? I want to compile stuff using c++11 and c++14 like on the cygwin terminal, but outside of the cygwin environment.

回答1:

MinGW-w64 (or rather GCC on windows) needs to be compiled with posix thread support if you want to use std::thread, presumably you downloaded a build with native windows threads.

Check out the mingw-builds folders targeting 64 bit or 32 bit and pick a version with posix threads. You'll also need to choose the exception handling method, if you don't have a reason to choose otherwise then stick with the GCC defaults of seh for 64 bit and dwarf for 32.



回答2:

I tested this in linux (cross-compiling).

This compiles ok,

i686-w64-mingw32-g++-posix -std=c++11 threads.cpp -lwinpthread

this does not

i686-w64-mingw32-g++-win32 -std=c++11 threads.cpp -lwinpthread

The difference between the compilers is --enable-threads=win32 vs. --enable-threads=posix option used when the compilers were built. g++ -v should show what was used.