Sunday, April 3, 2022

[SOLVED] How CMake automatically detects header dependencies

Issue

I wonder how CMake automatically detects that main.cpp depends on header.h

// header.h
int f() {
  return 0;
}
// main.cpp
#include "header.h"

int main() {
  return f();
}
# CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(Cppref)

add_executable(main main.cpp)

Solution

When I run cmake . -B build it creates the following make target in ./build/CMakeFiles/main.dir/build.make

CMakeFiles/main.dir/main.cpp.o: CMakeFiles/main.dir/compiler_depend.ts
    @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green --progress-dir=/home/nikolay/Cpp/Train/Cppref/build/CMakeFiles --progress-num=$(CMAKE_PROGRESS_1) "Building CXX object CMakeFiles/main.dir/main.cpp.o"
    /usr/bin/c++ $(CXX_DEFINES) $(CXX_INCLUDES) $(CXX_FLAGS) -MD -MT CMakeFiles/main.dir/main.cpp.o -MF CMakeFiles/main.dir/main.cpp.o.d -o CMakeFiles/main.dir/main.cpp.o -c /home/nikolay/Cpp/Train/Cppref/main.cpp

Pay attention to the -MD compiler option, as it is used to dump dependencies visible to the preprocessor.

So after the first build it will create ./build/CMakeFiles/main.dir/main.cpp.o.d with the following content

CMakeFiles/main.dir/main.cpp.o: /home/nikolay/Cpp/Train/Cppref/main.cpp \
  /home/nikolay/Cpp/Train/Cppref/header.h

So whenever you change header.h, the target main.o will be rebuilt.



Answered By - Nikolay
Answer Checked By - Timothy Miller (WPSolving Admin)