user357269
user357269

Reputation: 1913

CMake setting to Ninja rebuild when header change?

Apparently, Ninja has to be configured to treat headers as dependencies: https://ninja-build.org/manual.html#ref_headers.

How do I tell CMake to generate this into my build.ninja?

Upvotes: 1

Views: 3903

Answers (2)

Florian
Florian

Reputation: 43030

If I look into my build.ninja files generated with CMake for e.g. GCC I do have the necessary dependency file entries automatically generated (see 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

And the dependency checking works as expected. Just touch or change one of the header dependencies and ninja will automatically rebuild the necessary sources.

Upvotes: 1

Torbjörn
Torbjörn

Reputation: 5800

There is the file property OBJECT_DEPENDS, which can be used to specify the dependency on other files of any objects created from a specific file.

From 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).

To set this property on a given source file, use:

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"

Upvotes: 1

Related Questions