configure_file in add_custom_command?

In a CMakeLists.txt of a project of mine, I had a configure_file that converted MyHeader.h.in to MyHeader.h while doing transformations of CMake variables - and that worked great.

My problem now is that I ended up generating MyHeader.h.initself by an add_custom_command, so at build time - while configure_file runs at configure time. So, I need to convert the configure_file to something else that can transform CMake variables in the source file at build time.

I found this: Implementing build time configure_file functionality (#25534) · Issue · cmake/cmake :

In the COMMAND for the add_custom_command() call, you can use one of the various cmake -E copy... commands to do a simple file copy if you don’t need to do any variable substitution as part of the copying

Great - but what do I do, if I do need to do variable substitution as part of the copying? Can I use configure_file directly as an argument of the cmake command? Or maybe should I save the configure_file call to a separate .cmake script file, and then call cmake on this script from add_custom_command?

Are you in control of the build-time process generating the header? If so, the easiest solution would be to inject the CMake variables you need into that process, and generate the header file directly with the variables already substituted (i.e. generate directly MyHeader.h instead of generating MyHeader.h.in).

If that is not an option, you will have to move the configure_file process to build time, as you indicated in your last sentence. However, that has one major thing you need to solve: you need to make sure that the CMake which you will launch at build time actually has the variables you wish to configure. You may want to look at the load_cache() command, or you may end up having to configure_file() the script to get the variable values from your configure time into the build-time script.