header 更改时 CMake 设置为 Ninja 重建?

CMake setting to Ninja rebuild when header change?

显然,Ninja 必须配置为将 headers 视为依赖项:https://ninja-build.org/manual.html#ref_headers.

如何告诉 CMake 将其生成到我的 build.ninja 中?

有文件属性OBJECT_DEPENDS,可用于指定从特定文件创建的任何对象对其他文件的依赖性。

来自the docs

Additional files on which a compiled object file depends.

Specifies a ;-list of full-paths to files on which any object files compiled from this source file depend. On Makefile Generators and the Ninja generator an object file will be recompiled if any of the named files is newer than it. Visual Studio Generators and the Xcode generator cannot implement such compilation dependencies.

This property need not be used to specify the dependency of a source file on a generated header file that it includes. Although the property was originally introduced for this purpose, it is no longer necessary. If the generated header file is created by a custom command in the same target as the source file, the automatic dependency scanning process will recognize the dependency. If the generated header file is created by another target, an inter-target dependency should be created with the add_dependencies() command (if one does not already exist due to linking relationships).

要在给定的源文件上设置此 属性,请使用:

set_property(SOURCE first.cpp second.cpp
             APPEND PROPERTY OBJECT_DEPENDS "${PROJECT_SOURCE_DIR}/inc/header1.h;${PROJECT_SOURCE_DIR}/inc/header2;${PROJECT_SOURCE_DIR}/inc/global_deps.h"

如果我查看使用 CMake 生成的 build.ninja 文件,例如GCC 我确实有自动生成的必要依赖文件条目(参见 DEP_FILE):

#=============================================================================
# Object build statements for EXECUTABLE target MyExe

build CMakeFiles/MyExe.dir/foo.cc.obj: CXX_COMPILER ../foo.cc
  DEP_FILE = CMakeFiles/MyExe.dir/foo.cc.obj.d
  FLAGS = -fdiagnostics-color=always -Wconversion
  OBJECT_DIR = CMakeFiles\MyExe.dir
  OBJECT_FILE_DIR = CMakeFiles\MyExe.dir

依赖性检查按预期工作。只需 touch 或更改 header 依赖项之一,ninja 将自动重建必要的源。