The code for this recipe is available at https://github.com/dev-cafe/cmake-cookbook/tree/v1.0/chapter-06/recipe-04, including C and Fortran examples. The recipe is valid with CMake version 3.5 (and higher), and has been tested on GNU/Linux, macOS, and Windows.
Code versions matter, not only for reproducibility but also to document API capabilities or simplify support requests and bug reporting. The source code is typically under some version control, and additional semantic version numbers (see e.g. https://semver.org) can be attached using Git tags, for example. However, not only does the source code need to be versioned, but the executable needs to record the project version so that it can be printed to the code output or user interface.
In this example, we will define the version number inside of the CMake sources...