Simple C++ Thread Program Can't Be Compiled

The following is my 1st multi-threaded program. But while it was compiled, there is a linking error. The part of the error message:

std::thread::thread<void (&)(int), int&>(void (&)(int), int&):
test.cpp (.text._ZNSt6threadC2IRFviEJRiEEEOT_DpOT0_[_ZNSt6threadC5IRFviEJRiEEEOT_DpOT0_]+0x33): undefined reference pthread_create
collect2: error ld return 1

#include<thread>

void f(int i) {}

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

Solution 1:

You need to compile with -pthread as a compile option.

I got your code to compile with this (though I added the -Wall function to give me all warning notices):

g++ -pthread -out foo.exe foo.cpp

(where foo.cpp was the input filename I used containing your code)

Solution 2:

Even if your program uses c++11's threading feature, you need to specify '-pthread' to successfully compile your program.


Please read below thread for more info https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=763369