In this recipe, we will revisit the previous example, and will again generate print_info.c from the template print_info.c.in. However, this time, we will imagine that the CMake function configure_file() has not been invented yet, and will emulate it with a Python script. The goal of this recipe is to learn how we can generate source code at configure time by using a now familiar example. Of course, we will probably favor configure_file() for a real project, but when faced with the challenge of generating sources using Python at configure time, we will know how to do it.
We should point out that this recipe has a serious limitation and cannot emulate configure_file() fully. The approach that we will present here cannot generate an automatic dependency which would regenerate print_info.c at build time. In other words, if you remove the generated print_info.c after the configure step, this file will not be regenerated and the build step will fail. To properly mimic the behavior of configure_file() we would require add_custom_command() and add_custom_target(), which we will use in the subsequent Recipe 3, Generating source code at build time using Python, where we will overcome this limitation.
In this recipe, we will use a relatively simple Python script which we will detail below. This script will read in print_info.c.in and replace the placeholders in the file with parameters passed to the Python script from CMake. For more sophisticated templating, we recommend external tools, such as Jinja (see http://jinja.pocoo.org).