Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How CMake automatically detects header dependencies

Tags:

cmake

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)
like image 577
Kolansburg Avatar asked Jun 21 '26 07:06

Kolansburg


1 Answers

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.

like image 175
Kolansburg Avatar answered Jul 03 '26 22:07

Kolansburg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!