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

In my program, I hold the git version number and the date of the build in a separate file, called version.c, which looks like this:

#include "version.h"
const char * build_date = "2009-11-10 11:09";
const char * build_git_sha = "6b54ea36e92d4907aba8b3fade7f2d58a921b6cd";

There is also a header file, which looks like this:

#ifndef VERSION_H
#define VERSION_H
extern const char * build_date; /* 2009-11-10 11:09 */
extern const char * build_git_sha; /* 6b54ea36e92d4907aba8b3fade7f2d58a921b6cd */
#endif /* VERSION_H */

Both the header file and the C file are generated by a Perl script which looks like this:

my $git_sha = `git rev-parse HEAD`;
$git_sha =~ s/\s+//g;
# This contains all the build variables.
my %build;
$build{date} = make_date_time ();
$build{git_sha} = $git_sha;

hash_to_c_file ("version.c", \%build, "build_");

Here hash_to_c_file does all the work of creating version.c and version.h and make_date_time makes a string as shown.

In the main program, I have a routine

#include "version.h"

// The name of this program.
const char * program_name = "magikruiser";
// The version of this program.
const char * version = "0.010";

/* Print an ID stamp for the program. */

static void _program_id_stamp (FILE * output)
{
    fprintf (output, "%s / %s / %s / %s\n",
             program_name, version,
             build_date, build_git_sha);
}

I'm not that knowledgeable about git, so I'd welcome comments if there is a better way to do this.


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.