CMake如何自动检测头文件依赖?——基于main.cpp与header.h的依赖检测示例
Great question! Let's break down exactly how CMake figures out that your main.cpp depends on header.h, using your code as an example.
First, let's recap your code for clarity:
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)
Now, here's the step-by-step process of how CMake tracks that dependency:
Initial Configuration: When you run
cmake .to set up your build system, CMake only knows aboutmain.cpp(since it's explicitly listed inadd_executable). It doesn't scan the source code for includes yet—instead, it relies on your compiler to provide that information.Compiler-Generated Dependency Files: When you build the project (e.g., with
makeorninja), CMake tells your compiler (like GCC, Clang, or MSVC) to generate a dependency file alongside the object file. For GCC/Clang, this is usually a.dfile (e.g.,main.cpp.d), and it contains a list of all headers thatmain.cppincludes. For your code, this file will explicitly listheader.has a dependency ofmain.cpp.CMake Updates Build Rules: CMake automatically parses these generated dependency files and updates the build system rules. From this point on, if
header.his modified, the build system knows it needs to recompilemain.cpp—because the dependency file tells it thatmain.cpprelies onheader.h.No Explicit Header Listing Needed: You don't have to add
header.htoadd_executable(though you can, if you want IDEs to show the header in your project files). CMake will still detect the dependency automatically thanks to the compiler-generated files.
A quick note: This behavior is enabled by default in CMake for most modern compilers. You don't need any special flags or commands to make it work—it's part of the standard workflow when using add_executable or add_library.
内容的提问来源于stack exchange,提问作者Kolansburg

