You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CMake如何自动检测头文件依赖?——基于main.cpp与header.h的依赖检测示例

How CMake Detects Header File Dependencies (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 about main.cpp (since it's explicitly listed in add_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 make or ninja), 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 .d file (e.g., main.cpp.d), and it contains a list of all headers that main.cpp includes. For your code, this file will explicitly list header.h as a dependency of main.cpp.

  • CMake Updates Build Rules: CMake automatically parses these generated dependency files and updates the build system rules. From this point on, if header.h is modified, the build system knows it needs to recompile main.cpp—because the dependency file tells it that main.cpp relies on header.h.

  • No Explicit Header Listing Needed: You don't have to add header.h to add_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 16:12:36