29 de diciembre de 2014

Automatically store git hash inside C source

Sometimes we need to know what exact revision is a software. This doesn't work

#define VERSION 1.2

Just because it won't be updated by anyone.

On the other hand if using git, we could insert part of the revision hash automatically
  • With a batch file
  • Running the batch file from makefile in every build to avoid any manual task
Here is how

Edit makefile to insert code in build-pre section


Create the batch file version.bat to generate version.h with the hash constant inside



The automatic generated file will be something like this

#define VERSION "877bd1"

Wherever we need to use this version hash, this file must be included

#include "version.h"

Important

Add version.h to .gitignore to avoid modifying hash while build

Final Note

The git sha-1 hash will only acknowledge for changes in current project, if the code depends on other, the proper sha-1 code must be included (or a combination).

Reference and related info
This stackoverflow question