std::thread is not a member of namespace std using

2019-01-09 14:15发布

问题:

I'm trying to compile a simple c++ program that uses std::thread on eclipse kepler / mingw 4.8.1 and win32. I hope to move development to linux at some point after many years on windows development.

#include "test.h"
#include <thread>
#include <algorithm>


int main()
{
    Test::CreateInstance();

    std::thread(
        [&]()
        {
            Test::I()->Output2();
        }
    );

    Test::DestroyInstance();
    return 0;
}

Ignoring the purpose of test (it's a singleton that just produces some output that I will expand upon, once I get the std::thread working!)

The g++ compiler settings I've set in Eclipse are:

-c -fmessage-length=0  -std=c++0x -Wc++0x-compat

And the preprocessor symbol I have defined is:

__GXX_EXPERIMENTAL_CXX0X__

Building complains that std::thread is not a member of std:

    10:30:13 **** Incremental Build of configuration Debug for project test ****
Info: Internal Builder is used for build
g++ -D__GXX_EXPERIMENTAL_CXX0X__ -O0 -g3 -Wall -c -fmessage-length=0 -std=c++0x -Wc++0x-compat -o main.o "..\\main.cpp" 
..\main.cpp: In function 'int main()':
..\main.cpp:11:2: error: 'thread' is not a member of 'std'
  std::thread(
  ^

Can someone suggest what I might be missing to get this compiling correctly?

回答1:

Plain MinGW cannot support std::thread. You will need to use a MinGW-w64 toolchain (such as those shipped with Qt 5) that has "posix" threading enabled, so that libstdc++ exposes the <thread>, <mutex> and <future> functionality.

You can find an installer here, but you can also try just replacing the whole mingw toolchain root folder with one of these packages. You can choose 32- or 64-bit, remember to select threads-posix if you want to play with std::thread and friends. No special compiler options other than the ones you already have are needed. I do suggest using -std=c++11 if you don't need GCC 4.6 compatibility.



回答2:

I had the same problem, though I worked with Cygwin compiler instead. What I did was to define the symbol __cplusplus with the value 201103L for the preprocessor. Also I'd used the flag -std=c++11 for the compiler. This settings have to be made for All configurations (Debug & Release).

Another thing that you may check is that you have properly installed the compiler, verify your compiler instalation as explained by rubenvb.



回答3:

See here for a native implementation that can be added to any C++11 version of MinGW: https://github.com/meganz/mingw-std-threads It is a header-only library, so you just need to include the headers in your project and you will get C++11 threads and synchronization primitives.