0

I'm building a simple timer in C++ on Ubuntu 18, which runs for a number of milliseconds and calls a callback when it is done. But when I'm trying to launch the new thread, I get an= strange error from the compiler which states :

CMakeFiles/SourceCode.dir/main.cpp.o: In function `std::thread::thread<void (Timer::*)(), Timer*&>(void (Timer::*&&)(), Timer*&)':
/usr/include/c++/7/thread:122: undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status
CMakeFiles/SourceCode.dir/build.make:128: recipe for target 'SourceCode' failed
make[3]: *** [SourceCode] Error 1
CMakeFiles/Makefile2:72: recipe for target 'CMakeFiles/SourceCode.dir/all' failed
make[2]: *** [CMakeFiles/SourceCode.dir/all] Error 2
CMakeFiles/Makefile2:84: recipe for target 'CMakeFiles/SourceCode.dir/rule' failed
make[1]: *** [CMakeFiles/SourceCode.dir/rule] Error 2
Makefile:118: recipe for target 'SourceCode' failed
make: *** [SourceCode] Error 2

I'm using CLion, I went online and tried looking for solutions, but I've found nothing which works up to now. Here is how I start the timer in a new thread:

void Timer::startTimer() {

    std::thread t1(&Timer::checkTimer, this);
}

Here is how I run my timer :

void Timer::checkTimer() {

    auto now = std::chrono::system_clock::now().time_since_epoch();
    auto milisecondsDuration = std::chrono::milliseconds(duration);
    auto futureDuration = now + milisecondsDuration;

    while (std::chrono::system_clock::now().time_since_epoch() < futureDuration)
    {
        if(endTimer)
        {
            std::terminate();
        }
        std::this_thread::sleep_for (std::chrono::milliseconds(1));
        cout << "Running\n";
    }
    completedListener.timerCompleted(entityId, cause);
}

Please can someone help me out? I'm new to C++ and I'm having a hard time figuring out the cause of the problem.

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
John Code
  • 655
  • 7
  • 24
  • Most likely you need to compile and link with the `-pthread` option. See [this Answer](https://stackoverflow.com/a/8649908). – Hasturkun Nov 04 '18 at 16:07
  • It’s not “strange”: it tells you exactly what happens: you want to use `pthread_create`, but no library you link with provides it. Just because you can access a declaration in a header doesn’t make the library (the implementation) available. You’ll see what library to link with in pthreads documentation on your system. – Kuba hasn't forgotten Monica Nov 04 '18 at 18:49

0 Answers0