Search code examples
gcccmakeposixclion

Using CMakeLists causes error while compiling fine in commandline


I am compiling my code, in which I use posix threads in C.

I am using CLion and its CMakeLists.txt:

cmake_minimum_required(VERSION 3.7)
project(Test)

set(CMAKE_C_STANDARD 99)
add_definitions(-lpthread)

set(SOURCE_FILES main.c)

add_executable(Test ${SOURCE_FILES})

I am getting errors (eg: undefined reference tosem_init'`).

The proposed suggestion for solution is adding -lpthread compiler flag, but I already added it.

I compiled the same code from commandline:

gcc main.c -lpthread

It compiles without any problem.

What can be a possible problem/solution for this?


Solution

  • Remove add_definitions(-lpthread) entirely since pthread is not a definition, but a library dependency.

    Add after add_executable():

    target_link_libraries(Test pthread)
    

    Also, if you want to see what commands CMake is using without having to examine its files, you can use it on the command line with cmake -DCMAKE_VERBOSE_MAKEFILE=ON ....

    Btw, always prefer all the target_* commands, like target_compile_definitions() instead of older style add_definitions(). This keeps your project properties and dependencies clean and minimizes interference between different targets.

    If after the above changes your code still does not compile, then it is highly likely the code itself is wrong (nothing to do with CMake).