8

I'm trying to compile my program using CLion under Linux (Ubuntu) OS.

My CMake file:

# cmake_minimum_required(VERSION 3.5)
  project(untitled2 C)

  set(CMAKE_C_STANDARD 99)
  set(CMAKE_CXX_FLAGS -pthread)
  add_executable(untitled2 main.c)

My pragram using threads so I've added set(CMAKE_CXX_FLAGS -pthread) that required to compile my program. I got a compilation error: "undefined reference to pthread_create"

I can compile the program via the terminal using the following:

gcc main.c -o main -pthread

I think that my issue is with the CMake file. Can someone please help my with that matter ?

Thank you!

Ido Segal
  • 430
  • 2
  • 7
  • 20
  • You need to pass `-pthread` to the *linker* as well (or explicitly link with `-lpthread`). You might also want to read about [the CMake `FindThreads` funciton](https://cmake.org/cmake/help/latest/module/FindThreads.html) (though it's offline at the moment, will come back soon according to their page). – Some programmer dude Dec 15 '18 at 17:49
  • 1
    Oh by the way, `CXX` anything is for C++, not C. – Some programmer dude Dec 15 '18 at 17:49
  • Thank you for your response. I Changed CXX to C and the compilation completed successfully! – Ido Segal Dec 15 '18 at 17:52
  • How do you set the **C** standard to be used (even if it's added automatically by CLion)? There's a very simple pattern regarding languages and related variables in your `CMakeLists.txt`. – Some programmer dude Dec 15 '18 at 17:55
  • 3
    Possible duplicate of [cmake and libpthread](https://stackoverflow.com/questions/1620918/cmake-and-libpthread) – Tsyvarev Dec 15 '18 at 19:22

3 Answers3

9

You have to change set(CMAKE_CXX_FLAGS -pthread) in set(CMAKE_C_FLAGS -pthread), because CXX stay for C++. Hope this will help you.

7

I might still not be the best option but using a call to
find_package(Threads REQUIRED)
in combination with
target_link_libraries(mytarget PRIVATE Threads::Threads)
is the more modern way of getting to your goal because you should perform your actions on a target (instead of using 'magic' variables that could influence other parts of the project or even contain spelling issues).

See: https://codingnest.com/basic-cmake-part-2/

codewing
  • 674
  • 8
  • 25
1

Adding this to CMakeLists works fine for me:

set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
target_link_libraries(myprog Threads::Threads )