3

I have just installed gcc 4.8.2 on Centos (I am using devtoolset-2). I wrote a very simple program using thread. It compiles fine but crashes when executed?

 #include <thread>
 #include <iostream>

 void test() 
 { 
   std::cout << "test\n"; 
 }

 void main()
 {
      std::thread t(test);
      t.join();
      return 0;
 }

I compile with:

 scl enable devtoolset-2 bash
 c++ -o test test.cpp -std=c++11

I am terribly surprised. I must do something wrong, not using the write libc++ etc? Do you have any idea how I could debug this. Thank you! I compile it on Mac (Maverick) which obviously doesn't use gcc and it works fine.

alk
  • 69,737
  • 10
  • 105
  • 255
user18490
  • 3,546
  • 4
  • 33
  • 52
  • 4
    Try adding the command line option `-pthread` -- and of course also `-Wall`. – nosid Jun 29 '14 at 15:01
  • That worked thank you so much, I didn't know on Linux you still needed to use pthread with thread? Thank you very much. – user18490 Jun 29 '14 at 15:05
  • 1
    `main()` shall return `int`. – alk Jun 29 '14 at 15:16
  • 2
    @nosid: Why not add your proposal as the answer? – alk Jun 29 '14 at 15:20
  • I voted up the question despite of not checking the GCC docs for thread options, because it shows a nice basic test case, complete unlike most questions of this nature. – Rob11311 Jun 29 '14 at 15:29
  • Thanks Rob, I didn't think about checking the docs indeed, but your comment is helpful and I will do it next time. – user18490 Jun 29 '14 at 16:10

1 Answers1

3

On Linux, you should use the command line option -pthread with GCC and Clang for compiling and linking. In your case, the command line should look as follows:

g++ -std=c++11 -Wall -Wextra -pthread test.cpp -o test

See the following links for more information:

Community
  • 1
  • 1
nosid
  • 48,932
  • 13
  • 112
  • 139