How can I get my C code to automatically print out its Git version hash?

AndyL picture AndyL · Nov 10, 2009 · Viewed 48.8k times · Source

Is there an easy way to write C code that can access its Git version hash?

I wrote software in C to collect scientific data in a laboratory setting. My code records the data it collects in a .yaml file for later analysis. My experiments change from day-to-day and I often have to modify the code. To keep track of revisions, I use a git repository.

I would like to be able to include the Git revision hash as a comment in my .yaml data files. That way, I could look at the .yaml file and know exactly what code was used to generate the data shown in that file. Is there an easy way to do this automatically?

Answer

ndyer picture ndyer · Sep 11, 2012

If you are using a make-based build, you can put this in the Makefile:

GIT_VERSION := "$(shell git describe --abbrev=4 --dirty --always --tags)"

(See man git describe for what the switches do)

then add this to your CFLAGS:

-DVERSION=\"$(GIT_VERSION)\"

Then you can just reference the version directly in the program as though it was a #define:

printf("Version: %s\n", VERSION);

By default this just prints an abbreviated git commit id, but optionally you can tag particular releases with something like:

git tag -a v1.1 -m "Release v1.1"

then it will print out:

Version: v1.1-2-g766d

which means, 2 commits past v1.1, with a git commit id beginning with "766d".

If there are uncommitted changes in your tree, it will append "-dirty".

There is no dependency scanning so you have to do an explicit make clean to force the version to be updated. This can be solved however.

The advantages are that it is simple and doesn't require any extra build dependencies like perl or awk. I have used this approach with GNU automake and with Android NDK builds.