Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make CDT/Eclipse work with C++11 threads?

I tried to test an example of C++11 threads in Eclipse. But I got this message when running the program:

terminate called after throwing an instance of 'std::system_error' what(): Operation not permitted'

My system: ubuntu + gcc 4.7

Program:

#include <iostream>
#include <thread>

void worker()
{
    std::cout << "hello from worker" << std::endl;
}

int main(int argc, char **argv)
{
    std::thread t(worker);
    t.join();
}

...and yes, I put -std=c++11 and -pthread inside C/C++ Build -> Settings -> Tool Settings -> Cross G++ Compiler -> Miscellaneous -> Other Flags.

Any comments?

like image 326
melmi Avatar asked May 01 '12 09:05

melmi


2 Answers

The problem was solved by the comment of Jonathan Wakely.

I added -pthread to C/C++ Build -> Settings -> Tool Settings -> Cross G++ **Linker** -> Miscellaneous -> Other Flags and the program worked correctly.

Thank you Jonathan.

like image 54
melmi Avatar answered Oct 24 '22 15:10

melmi


To work C++11 std::thread in Eclipse, one needs to give -pthread option while compiling. However that's not enough. In my Ubuntu 14.04, with Eclipse Kepler and g++4.9 below makes it work:

  1. Right click on Project and select 'Properties'
  2. Go to 'C/C++ Build' > 'Settings' > (tab) 'Tool Settings'
  3. First select 'Cross G++ Compiler' > 'Miscellaneous' > 'Other flags';
    and add -pthread after -std=c++11
  4. Second select 'Cross G++ Linker' > 'Libraries';
    and add pthread (which is equivalent to command line -lpthread)

Finally re-compile the project; the error should go.

Also remember that if you use, std::thread then its object must be join() somewhere. Else you may get below runtime error:

terminate called without an active exception

like image 40
iammilind Avatar answered Oct 24 '22 16:10

iammilind