Compile-time version strings in CMake
mattkeeter.com
mattkeeter.com
Personally I tend to go the route wmu mentions in their comment: add a file named MyProject.h.in, to expose CMake variables in a generated header file. I use the C preprocessor's stringification [0] to transform version numbers into strings. My approach (really just CMake basics) doesn't expose any git specifics though - it's more basic than what the blog describes.
The MyProject.h.in file looks like:
#define MyProject_VERSION_MAJOR @MyProject_VERSION_MAJOR@
#define MyProject_VERSION_MINOR @MyProject_VERSION_MINOR@
#define EXPAND_AND_STRINGIFY(s) STRINGIFY(s)
#define STRINGIFY(s) #s
#define MyProject_VERSION_MAJOR_STR EXPAND_AND_STRINGIFY(MyProject_VERSION_MAJOR)
#define MyProject_VERSION_MINOR_STR EXPAND_AND_STRINGIFY(MyProject_VERSION_MINOR)
#define MyProject_VERSION_STR MyProject_VERSION_MAJOR_STR "." MyProject_VERSION_MINOR_STR
Getting CMake to process this file is simple enough: we just add configure_file(MyProjectConfig.h.in MyProjectConfig.h) to the CMakeLists.txt file.[0] https://gcc.gnu.org/onlinedocs/gcc-4.8.5/cpp/Stringification...
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.)
The usual technique is to have some script check the git version, then output two files: the version.cpp file, and a "witness" file which changes every run. The script should be careful to not perturb the mod date of version.cpp unless it has changed.
This is coupled with Ninja's "restat" option. Without that option, Ninja will observe that version.cpp will be recreated and schedule all of its dependents (such as linking). With that option, Ninja will behave more like Make, check if the file was actually modified.
See CMake's (weirdly-placed) docs on this: https://cmake.org/cmake/help/v3.4/policy/CMP0058.html
Here's fish shell's version gen script: https://github.com/fish-shell/fish-shell/blob/master/build_t...
package managers, for example, should know the git sha
But in general, git doesn't look kindly on gratuitous modifications to source files. Those modifications can never occur in the actual files in the repository, since you can't hash something that contains its own hash (unless the hash is broken). And having the file in the working directory not match the file in the repository makes life difficult in various ways (diffs, etc).