Rerun custom command if project was reconfigured

I want a custom command to be considered out of date if the project was reconfigured. My current solution is to touch a specific file in the build tree and make the command depend on it, but I get a warning that byproducts have to be listed explicitly.
What is the correct way to do this?

You might be able to depend on CMakeCache.txt instead?

That only re-runs it if cache variables were changed.

That file is unconditionally written when CMake runs. I don’t know if that’s guaranteed, but it is the behavior of today.

Another option might be to delete an output file whenever CMake is run, and include rules for regenerating it as part of your custom command(s). e.g.

set(marker ${CMAKE_CURRENT_BINARY_DIR}/.rebuilt)
add_custom_command(
  OUTPUT ${marker}
  COMMAND
    ${CMAKE_COMMAND} -E touch ${marker}
)
add_custom_command(
  OUTPUT ${build_file}
  COMMAND
    ${command_to_generate_build_file}
  DEPENDS ${marker}
)
file(REMOVE ${marker})

Untested, but that should ensure that ${command_to_generate_build_file} gets rerun for sure anytime the project is reconfigured, because the build will have to re-create the .rebuilt file it depends on. And there are no undeclared byproducts to worry about, so that shouldn’t be an issue.

I double-checked. The timestamp on the file is not updated and the target doesn’t re-run.

I ended up using a file generated using the configure_file command. It seems that such files are recognized as byproducts of cmake itself.

They are, but note that you may have the same troubles since, according to the configure_file() docs…:

The generated file is modified and its timestamp updated on subsequent
cmake runs only if its content is changed.

Surprisingly enough I’m seeing the same thing, with CMake 3.19.7 on Linux x86_64. When build is already configured and nothing has changed, a subsequent cmake -B build -S . leaves the build/CMakeCache.txt timestamp untouched. (But there really has to be nothing changed.)

…Of course, if nothing’s changed, it’s difficult to see what kind of imperative there would be to force re-running of a custom command. Unless it’s being used for un-accounted-for side effects, in which case it would arguably be useful to instead account for those explicitly as dependencies in the build config. :wink:

I figured out a way to put the info that I really care about into the configured file.