Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I have to run cmake twice for compile the project

I got the following error with the first running of the command

cmake .

But if I run the command again, the compilation succeed. That is, I have to run cmake twice for make the project compiled. Why is it so? How could I fix it?

Error message:

CMakeFiles/exec.dir/Timer.cpp.o: In function `std::thread::thread<Timer::Timer()::{lambda()#1}>(Timer::Timer()::{lambda()#1}&&)':
/usr/include/c++/7/thread:122: undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status
CMakeFiles/exe.dir/build.make:146: recipe for target 'exe' failed
make[2]: *** [exe] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/exe.dir/all' failed
make[1]: *** [CMakeFiles/exe.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2

CMakeLists.txt:

cmake_minimum_required(VERSION 3.10)

set(CMAKE_BUILD_TYPE Debug)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread -g -std=c++14 -std=c++11 -std=c++17 ")

project(myproject)

set(SOURCE_FILES main.cpp Timer.cpp TimerEntity.cpp)
add_executable(exe ${SOURCE_FILES})
like image 969
GccGUY Avatar asked Nov 05 '25 05:11

GccGUY


1 Answers

It is not usually noted, but appending compiler flags via

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} <...>")

should be placed after the project() call.

Exactly project() call sets the initial value of CMAKE_CXX_FLAGS variable.

Normally, project() call is issued just after the cmake_minimum_required():

cmake_minimum_required(VERSION 3.10)
project(437_Hw1)

...

Details

In your current code, when you call cmake the first time, your first setting set(CMAKE_CXX_FLAGS ...) is replaced by the value of the following project() call and stored in the CACHE.

When you call cmake the second time, CMAKE_CXX_FLAGS variable is already set (it is loaded from the cache). So, set(CMAKE_CXX_FLAGS ...) sets the variable to correct value. Moreover, following project() doesn't change CMAKE_CXX_FLAGS variable because it finds it already in the cache.

like image 91
Tsyvarev Avatar answered Nov 08 '25 13:11

Tsyvarev