C++ threads in Eclipse Kepler and Ubuntu 16.04

I began testing a simple threads example. But, I had a little problems:

  • The pre-compiler said: “thread could not be resolved”.
  • The compiler said “… undefined reference to ‘pthread_create’ …”.

Here is the solution.

First, I began testing a simple thread example in C++.  The code is the follow:

#include <string>
#include <iostream>
#include <thread>

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");

 // Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.

 return 0;

The first problem was the pre-processor. It didn’t recognize the “thread” class and the IDE Eclipse Kepler showed an error on the line:

thread t1(task1, "Hello");

I found the solution in page, and I followed the instructions:

Go to Project -> Properties -> C/C++ General -> Preprocessor include paths, etc -> Providers -> CDT GCC Builtin Compiler Settings and append -std=c++11 to the compiler specs

Modify the project preferences

Add “-std=c++11” flag

This answer solved that problem. But, when I “Build Project”, the console showed an error like the following:

... undefined reference to 'pthread_create' ...

I found several solutions in the Internet, but none solved my problem. When I was desperate this page appears and it solved the problem.  I updated the solution to Eclipse Kepler.

Add libraries to GCC C++ Linker

Add libraries to GCC C++ Linker

I “Clean Project” and “Build Project” again, and the console showed the follow:

Building target: BasicThread
Invoking: GCC C++ Linker
g++ -o "BasicThread" ./src/thread.o -lpthread
Finished building target: BasicThread

You can look at the final flag on compiler invocation. It solved the problem.


Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *