0

I decided to make some threads research in C++. Everything was great, Visual Studio compiled it easily. But when I decided to compile all of that stuff by using Ubuntu terminal for Windows - I ran into mistake below. I tried to compile like:

  1. g++ -o thread ThreadTest.cpp
  2. g++ --std=c++17 -o thread ThreadTest.cpp

Have already tried to use #include <pthread.h> , but it cannot be found in Visual Studio. I'm also using lambda, there are all includes from my code:

#include <chrono>
#include <functional>
#include <iostream>
#include <thread>
#include <vector>

And this is what I take when I'm trying to compile it by Ubuntu:

In function `std::thread::thread<main::{lambda()#1}>(main::{lambda()#1}&&)':
ThreadTest.cpp:(.text+0x8b7): undefined reference to `pthread_create'
/tmp/cc0NzGGt.o: In function `std::thread::thread<void (&)(std::vector<int, std::allocator<int> >, std::vector<std::function<void (int)>, std::allocator<std::function<void (int)> > >), std::vector<int, std::allocator<int> >&, std::vector<std::function<void (int)>, std::allocator<std::function<void (int)> > >&>(void (&)(std::vector<int, std::allocator<int> >, std::vector<std::function<void (int)>, std::allocator<std::function<void (int)> > >), std::vector<int, std::allocator<int> >&, std::vector<std::function<void (int)>, std::allocator<std::function<void (int)> > >&)':
ThreadTest.cpp:(.text._ZNSt6threadC2IRFvSt6vectorIiSaIiEES1_ISt8functionIFviEESaIS6_EEEJRS3_RS8_EEEOT_DpOT0_[_ZNSt6threadC5IRFvSt6vectorIiSaIiEES1_ISt8functionIFviEESaIS6_EEEJRS3_RS8_EEEOT_DpOT0_]+0x39): undefined reference to `pthread_create'
/tmp/cc0NzGGt.o: In function `std::thread::thread<int (&)(int, int), std::reference_wrapper<int>, std::reference_wrapper<int> >(int (&)(int, int), std::reference_wrapper<int>&&, std::reference_wrapper<int>&&)':
ThreadTest.cpp:(.text._ZNSt6threadC2IRFiiiEJSt17reference_wrapperIiES4_EEEOT_DpOT0_[_ZNSt6threadC5IRFiiiEJSt17reference_wrapperIiES4_EEEOT_DpOT0_]+0x39): undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status
GlKosh
  • 67
  • 6

1 Answers1

1

In order to use threads you have to ensure that you're linking the proper library. To do so, just add -lpthread as in:

g++ -o thread ThreadTest.cpp -lpthread

Alex Baum
  • 166
  • 9
  • I never understood why it's separate, unlike the rest of the C++ std lib. Why is it separate? – Mooing Duck Jun 26 '20 at 22:16
  • @MooingDuck, as I suspected the main reason is that pthread is not part of the standard C++/C library, but rather a part of the POSIX standard, see [this second answer in](https://stackoverflow.com/questions/25036467/g-why-dont-you-have-to-link-iostream-binaries-but-for-pthread-you-do). This changes in new versions of C++ – Alex Baum Jun 26 '20 at 22:26