2016年9月28日 星期三

Injecting Git branch and Git commit hash as macro to binaries compiled by gcc with CMake in Linux

Solution

Simply adding some code to only 2 files: CMakeList.txt and main.cpp.

1. CMakeList.txt

# git commit hash macro
execute_process(
  COMMAND git log -1 --format=%h
  WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
  OUTPUT_VARIABLE GIT_COMMIT_HASH
  OUTPUT_STRIP_TRAILING_WHITESPACE
)
add_definitions("-DGIT_COMMIT_HASH=\"${GIT_COMMIT_HASH}\"")

2. main.cpp

inline void LogGitCommitHash() {
#ifndef GIT_COMMIT_HASH
#define GIT_COMMIT_HASH "0000000" // 0000000 means uninitialized
#endif
    std::cout << "GIT_COMMIT_HASH[" << GIT_COMMIT_HASH << "]"; // 4f34ee8
}

Explanation

In CMakeList.txt, the CMake commandexecute_process() is used to call command git log -1 --format=%h that give you the short and unique abbreviation for your SHA-1 values in string like 4f34ee8. This string is assigned to CMake variable called GIT_COMMIT_HASH. The CMake command add_definitions() defines the macro GIT_COMMIT_HASH to the value of 4f34ee8 just before gcc compilation. The hash value is used to replace the macro in C++ code by preprocessor, and hence exists in the object file main.o and in the compiled binaries a.out.

Side Note

Another way to achieve is to use CMake command called configure_file(), but I don't like to use it because the file does not exist before CMake is run.

沒有留言:

張貼留言

2023 Promox on Morefine N6000 16GB 512GB

2023 Promox on Morefine N6000 16GB 512GB Software Etcher 100MB (not but can be rufus-4.3.exe 1.4MB) Proxmox VE 7.4 ISO Installer (1st ISO re...