Created with Highcharts 5.0.7Insert Temperature RecordChart context menuClick and drag in the plot area to zoom in10001100120013001400150016001700180019002000250300350400450Powered by the 2 Degrees InstituteVisit 2 Degrees InstituteShow last 800,000 years
Carbon Dioxide (CO2 ppm)
Global CO2 Levels

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


.build-pre:
# Add your pre 'build' code here...
version.bat
$(info ************ RUNNING CUSTOM CODE FROM MAKEFILE ************)
view raw makefile hosted with ❤ by GitHub

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


@REM ---------------------------------------
@REM This creates a .h with a macro VERSION
@REM with part of the current git commit hash
@REM
@REM It should be called from Makefile
@REM ---------------------------------------
@ECHO OFF
del version.h
@ECHO ON
@REM Shows description in build console
git describe --always --abbrev=6 --dirty
@ECHO OFF
echo | set /p uglyName=#define VERSION >> version.h
git describe --always --abbrev=6 --dirty >> tmpFile
@set /p var= < tmpFile
echo | set /p uglyName=""%var%"" >> version.h
del tmpFile
view raw version.bat hosted with ❤ by GitHub

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