d4nf
d4nf

Reputation: 43

How do I make CMake re-run a add_custom_command when a dependent file gets modified?

I want to have my custom commands rerun every time a file from a list I supply gets modified.

My example: my project has the following files:

cmake_minimum_required(VERSION 3.17)

project(dummy)
set(DummyFiles dep1.txt, dep2.txt)

add_executable(test_dummy main.cpp)

add_custom_command(TARGET test_dummy
COMMENT "ran custom command on file change"
DEPENDS ${DummyFiles}
)

My expectation is that after I have already configured that project, every time I modify dep1.txt or dep2.txt and reconfigure, CMake will print out the COMMENT section above. It however doesn't.

Any help would be appreciated.

Upvotes: 4

Views: 1777

Answers (1)

Tsyvarev
Tsyvarev

Reputation: 65928

There are two flows of command add_custom_command: "Generating Files" and "Build Events".

The option DEPENDS is available only for the first flow - "Generating Files", which requires OUTPUT as the first option.

You use TARGET as the first option to the command, which denotes "Build Events" command flow. This command flow doesn't support DEPENDS option (there is no such option in the synopsis for this command flow).

I want to have my custom commands rerun every time a file from a list I supply gets modified.

For that you need to use the first flow of the add_custom_command with OUTPUT option.

You may use dummy file as OUTPUT, so build system could be able to compare the timestamp of this file with the timestamps of the files from DEPENDS section. Whenever the timestamp of OUTPUT would be found older than the timestamp of one of DEPENDS, the command will be re-run.

set(DummyFiles dep1.txt dep2.txt)

add_custom_command(OUTPUT dummy.txt
  COMMENT "ran custom command on file change"
  DEPENDS ${DummyFiles}
)

# Need to create a custom target for custom command to work
add_custom_target(my_target ALL
  # Use absolute path for the DEPENDS file.
  # Relative paths are interpreted relative to the source directory.
  DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/dummy.txt
)

Upvotes: 8

Related Questions