Code injection at the end of the processing of each CMakeLists.txt file

Hi,

We have a bit of a weird use-case where we occasionally need to inject code at the end of the processing of each CMakeLists.txt file. This extra CMake code is very bespoke and most of it we do not have any control over; it effectively needs to call a function on every CMake target that was created in the directory (this needs to happen in the same directory as it applies post-build steps to the targets and this can only be done in same directory scope that created the target).

We have a solution to this, but I am assuming that it is not particularly robust and not at-all designed for this purpose. We currently have a script which is injected when building the project via CMAKE_PROJECT_TOP_LEVEL_INCLUDES, this script:

  1. Creates a custom target which we use custom properties on to keep track of directories that have been seen.
  2. Uses variable_watch(CMAKE_CURRENT_LIST_DIR some_function_) to call a function whenever the directory is changed. This function looks at a property of the custom target to see if the directory has been processed already. If it has, do nothing. Otherwise:
  3. Use cmake_language(DEFER CALL some_macro_) to invoke a macro at the end of the processing of the current list that does ā€œthe thingsā€.

My questions are:

  1. Is there a better way to achieve this that we have not realised? Otherwise…
  2. Is the behavior we are currently using something we can continue to depend upon? Otherwise…
  3. Would the CMake developers be open to adding/accepting a feature that would help us achieve this…

Thanks!

I’m not aware of a clean way of achieving what you want, unfortunately. The proposed features in issue 22466 are aimed at use cases exactly like yours and others, but I’m not aware of anyone working on it.

1 Like

The feature requested in the issue you linked to does look like it could also resolve our use-case.

Thanks for taking the time to respond. Much appreciated.