How to insert a Git commit hash into your build on Eclipse CDT

last updated: Nov 20, 2024

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.

  1. Select Project->Properties
  2. Navigate to C/C++ Build -> Settings
  3. Under Tool Settings, select Preprocessor for the compiler in use and add the following symbol:
    GIT_HASH=$(shell git rev-parse HEAD)
Screenshot of adding defined symbol

Add a defined symbol to the preprocessor tool settings

  1. 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;
}
Prev in section:
NXPs MCUXpresso is not configured…