The code for this recipe is available at https://github.com/dev-cafe/cmake-cookbook/tree/v1.0/chapter-05/recipe-04 and has a C++ example. The recipe is valid with CMake version 3.5 (and higher) and has been tested on GNU/Linux, macOS, and Windows.
As we discussed in the previous recipe, add_custom_command has some limitations that can be circumvented by using add_custom_target. This CMake command will introduce new targets in the build system. These targets, in turn, execute commands that do not return an output, in contrast to add_custom_command. The commands add_custom_target and add_custom_command can be combined. With this, the custom target can be specified in a directory different than the one where its dependents are, and this can be very helpful when designing a modular CMake infrastructure for your project...