1

I try to compile a simple c++ code in c++, but keep returning errors when I try to compile it with g++ in windows.

I use

g++ -std=c++0x -pthread main.cpp

The error messages are:

std::thread' is defined in header '<thread>'; did you forget to '#include <thread>'?

Which doesn't make sense because the code is just

#include<thread>

void f(int i) {}

int main() {
        std::thread t(f, 1);
        t.join();
        return 0;
}

I believe this code works in linux, I wonder why it can't work under windows.

Alex
  • 9,891
  • 11
  • 53
  • 87
HAO LEE
  • 153
  • 3
  • 13
  • 4
    `` is a header for C++11 or newer. You're telling g++ to use an older version of the language. – Shawn Jul 07 '19 at 07:54
  • 1
    You should also check to see if whatever Windows port of g++ you're using supports C++11 threads. The `-pthread` option is kind of odd on Windows too... or does your G++ use a Windows port of pthreads instead of native Win32 threads? – Shawn Jul 07 '19 at 07:57

2 Answers2

5

To use std::thread you must be compiling your code as C++11, C++14 or C++17.

You are passing -std=c++0x to gcc. c++0x was the name used for pre-release versions of the gcc C++11 impletation and, depending on your compiler version, may be incomplete.

Change your gcc command line to -std=c++11 and things most likely work better. If not, you may need to get a newer version of the compiler.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
0

Windows has its own threading API that is not POSIX standard. What you need to find out is (how to acquire and) how to link the threading library for your compiler. It sounds like you're using MinGW? I use MSVC and it automatically links with the Windows threading libraries. Unfortunately I don't know how to do this for MinGW, so this isn't the best answer, but here is a link that might get you started:

Does MinGW-w64 support std::thread out of the box when using the Win32 threading model?

Humphrey Winnebago
  • 1,512
  • 8
  • 15