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;
}
1

4 Answers

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)

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

2

I had fixed the same Issue (undefined reference to Pthread_create) So the issue is not your Code but the argument which be have missed while generating object file in G++ compiler

void threadFun()
{ cout<<"\n"<<" "<<"INSIDE THREAD"<<"\n";
}
int main()
{ thread t1(threadFun); t1.join(); return 0;
}

Here is the issue:

This is how I fixed it:

1

you can take a look at this example:

#include #include #include

using namespace std;

// The function we want to execute on the new thread. void task1(string msg) { cout << "task1 says: " << msg; }

int main() { // Constructs the new thread and runs it. Does not block execution. thread t1(task1, "Hello");

// Do other things...

// Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution. t1.join(); }

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like