print git hash in qt as macro created at compile time

c++, git, makefile, qt

Solution

Ok so its seems I found out solution after some time. Just add this to defines in Qt .pro file.

DEFINES += GIT_CURRENT_SHA1="\\\"$(shell git -C \""$$_PRO_FILE_PWD_"\" describe)\\\""

This define will be refreshed when building generated Makefile. No need to run qmake every time.

Usage simple:

label->setText(QString("Version: %1").arg(GIT_CURRENT_SHA1));

But there is problem that those files using value from GIT_CURRENT_SHA1 macro will not be automatically rebuilt when git hash changes.

Problem

I need to get information about git commit (to print it and use in my about dialog) used during compile time (make, not qmake). Its ok to use git describe command for this. I need the solution to be multiplatform(Windows Linux at least), I managed to successfuly get git hash at qnake run on Windows and Linux. This command is executed at qmake run and works well: ``` DEFINES += GIT_CURRENT_SHA1=$(shell git describe) ``` However I need to have git describe executed at compile time, because qmake is not run every time I compile and thus there will be old commit hash. If I add this code to Makefile generated by qmake it works fine, but of course vanishes after qmake run: ``` VARIABLE = $(shell cd ../../project/ ; git describe) DEFINES = -DGIT_CURRENT_SHA1=$(VARIABLE) ``` And there is problem how to get to correct path due to shadow build which is not inside git repository directory. I need to cd to project and then run git describe from there. So there are two subquestions: - how to add code to Makefile from Qt .pro file - how to pass the correct path to git describe command Or does anybody know of something better? Thanks Update 1 Ok I found out how to insert shell code into Makefile define variable, there need to be quotes around it: ``` DEFINES += GIT_CURRENT_SHA1="$(shell cd ../../project/ ; git describe)" ``` But the problem is how to pass the project path into it(due to shadow build etc) Update 2 Ok found out also how to do that.. ``` DEFINES += GIT_CURRENT_SHA1="$(shell git -C \""$$_PRO_FILE_PWD_"\" describe)" ``` But there is big problem - how to force rebuild files which uses GIT_CURRENT_SHA1 macro ?? I am thinking about some extra header file which I would have to generate every time and include it where I need it.

Original source