7

I have some troubles trying to compile a program with multi-threading from the standard template library. It return me a obscure error when i try to compile the following program :

#include <iostream>
#include <thread>

void foo()
{
    std::cout << "Thread 1\n";
}

int main(int argc, char** argv)
{
    std::thread tr(foo);
    std::cout << "Main thread\n";
    tr.join();

    return 0;
}

I don't understand the error :

/tmp/ccE8EtL1.o : In the function « std::thread::thread<void (&)()>(void (&)()) » :
 file.cpp:(.text._ZNSt6threadC2IRFvvEJEEEOT_DpOT0_[_ZNSt6threadC5IRFvvEJEEEOT_DpOT0_]+0x21) : undefined reference to « pthread_create »
  collect2: error : ld has return 1 execution status code

I compile it with :

g++ -std=c++14 file.cpp -o test -Wall

Can anyone help me please ?

Harry333Cover
  • 379
  • 3
  • 11

1 Answers1

15

Pass -pthread to the compiler. This flag combines what is necessary to compile and link the pthread library (-lpthread is not always enough). See this question.

Community
  • 1
  • 1
BoBTFish
  • 19,167
  • 3
  • 49
  • 76
  • Thank you, it was the solution \o/ – Harry333Cover Feb 04 '17 at 23:03
  • For completeness: [g++ - Why do I have to pass “-pthread” option while using std::thread?](https://stackoverflow.com/questions/46994982/g-why-do-i-have-to-pass-pthread-option-while-using-stdthread) – Evandro Coan Apr 24 '21 at 05:25