7

I am trying to compile some C++ code that uses threads:

#include <iostream>
#include <thread>
void hello()
{
    std::cout<<"Hello Concurrent World\n";
}

int _main(int argc, _TCHAR* argv[])
{
    std::thread t(hello);
    t.join();
    return 0;
}

I get errors when compiling:

c:\temp\app1\app1\app1.cpp(6): fatal error C1083: Cannot open 
include file: 'thread': No such file or directory


~/Documents/C++ $ g++ -o thread1 thread1.cpp -D_REENTRANT -lpthread
In file included from /usr/include/c++/4.5/thread:35:0,
                 from thread1.cpp:2:
/usr/include/c++/4.5/bits/c++0x_warning.h:31:2: error: #error This file 
requires compiler and library support for the upcoming ISO C++ standard, 
C++0x. This support is currently experimental, and must be enabled with 
the -std=c++0x or -std=gnu++0x compiler options.

How do I fix these errors?

Eric Leschinski
  • 135,913
  • 89
  • 401
  • 325
q0987
  • 33,230
  • 67
  • 231
  • 369
  • Duplicate of http://stackoverflow.com/questions/2519607/c0x-stdthread-error-thread-not-member-of-std – q0987 Dec 15 '11 at 01:26

3 Answers3

9

<thread> and standard threading support is a new feature (defined in the C++11 standard). As for g++, you have to enable it adding -std=c++0x to the command line, as explained in the error message.

Also, you are using a nonstandard (Microsoft-specific) main, use the "classic" main and normal char:

// thread1.cpp
#include <iostream>
#include <thread>

void hello()
{
    std::cout<<"Hello Concurrent World\n";
}

int main(int argc, char * argv[])
{
    std::thread t(hello);
    t.join();

    return 0;
}

Notice that not all C++11 features are available in current compilers; as far as g++ is concerned, you can find the status of their implementation here.

Matteo Italia
  • 119,648
  • 17
  • 200
  • 293
  • @AlphaBravo: not exactly, there are [some guarantees](http://stackoverflow.com/a/6374525/214671); besides, in this specific case there's only one thread using it, so it's safe. – Matteo Italia Sep 29 '16 at 17:08
3

Yes, the header file <thread> is only standard in the C++11 newest standard (finalized this year only).

With GCC, you'll need the very latest 4.6 version, and even with it, not everything is supported of the C++11 standard. See this table

Basile Starynkevitch
  • 216,767
  • 17
  • 275
  • 509
2

As far as MSVC goes, the C++11 <thread> header isn't supported in VS2010 - you'll need to pull down a Developer Preview of Visual Studio 11 (http://msdn.microsoft.com/en-us/vstudio/hh127353) to try it out today.

See http://blogs.msdn.com/b/vcblog/archive/2011/09/12/10209291.aspx for details on what is new in C++ for Visual Studio 11.

Also, my PDF of the book (which is in pre-release at the moment) has the following definition of main():

int main()
{
    std::thread t(hello);
    t.join();
}

which avoids the problems you're running into with _TCHAR being undefined in GCC.

Michael Burr
  • 321,763
  • 49
  • 514
  • 739