Knowing the specific code that was used to build a particular binary is very useful when it comes to debugging unexpected behavior. Although version numbers can help for significant releases, they’re less useful when iterating quickly.
Inserting the current Git commit hash into your binary in Eclipse CDT is easy to do. It can then be used in debug output to precisely identify the code used in the build.
Note: This example uses Eclipse 2022-09 on Linux, but the process for other versions should be similar.
- Select
Project->Properties
- Navigate to
C/C++ Build -> Settings
- Under
Tool Settings
, selectPreprocessor
for the compiler in use and add the following symbol:
GIT_HASH=$(shell git rev-parse HEAD)
- Use macros to insert the hash as a string literal in your code:
#include <iostream>
using namespace std;
#define STR(x) #x
#define TOSTR(x) STR(x)
int main() {
cout << "Git hash: " << TOSTR(GIT_HASH) << endl;
return 0;
}