I'm working with C++ in Visual Studio 2015 and using Git as source control. I'm writing a multi-platform application and would like my application to include the Git branch and the commit it was built from.
On platforms other than Visual Studio I put the following lines in my makefile:
GIT_CUR_COMMIT := $(shell git rev-parse --verify HEAD)
GIT_CUR_BRANCH := $(shell git rev-parse --abbrev-ref HEAD)
DEPS += -DGIT_COMMIT=\"$(GIT_CUR_COMMIT)\" -DGIT_BRANCH=\"$(GIT_CUR_BRANCH)\"
And then in my application I have code to read these preprocessor variables and expose them programmatically:
std::string getGitCommit()
{
#ifdef GIT_COMMIT
return GIT_COMMIT;
#endif
return "unavailable";
}
std::string getGitBranch()
{
#ifdef GIT_BRANCH
return GIT_BRANCH;
#endif
return "unavailable";
}
But in Visual Studio there are no makefiles. How can I define these two variables (GIT_CUR_COMMIT
and GIT_CUR_BRANCH
) at compile time and achieve the same behavior?
Probably - you can do it exactly same way in VS - But I feel the following procedure would be a lot easier to implement
In the project properties select the "Build Events" / "Pre-Build Event"
Add following commands to the Command Line
echo | set /p dummyName=#define GIT_CUR_COMMIT > gitparams.h
git rev-parse --verify HEAD >> gitparams.h
echo | set /p dummyName=#define GIT_BRANCH >> gitparams.h
git rev-parse --abbrev-ref HEAD >> gitparams.h
This should generate the following header file (gitparams.h) each time you compile your project
#define GIT_CUR_COMMIT 8a6b3f147fababda57ddd39262df5aa83bc853c4
#define GIT_BRANCH master
Make sure you add it to .gitignore
And in your code you can use
#include "gitparams.h"
#define ADD_QUOTES_HELPER(s) #s
#define ADD_QUOTES(s) ADD_QUOTES_HELPER(s)
std::string getGitCommit()
{
#ifdef GIT_CURR_COMMIT
return ADD_QUOTES(GIT_CURR_COMMIT);
#endif
return "unavailable";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With