Instead of creating C code inside cmake scripts it's better to use command configure_file (https://cmake.org/cmake/help/latest/command/configure_file.h...). The command creates a source file based on a template file.
The generation of the .h file from the .h.in file does happen at compile-time. (Well, at build time, right before the compiler is invoked.)