This is a solution for CMake projects that works for Windows and Linux, without the need for any other programs (e.g. script languages) to be installed.
The git hash is written to a .h file by a script, which is a bash script when compiling on Linux or a Windows batch script when compiling on Windows. An if-clause in CMakeLists.txt is used to execute the script corresponding to the platform the code is compiled on.
Save the following 2 scripts in the same directory as CMakeLists.txt:
get_git_hash.sh:
#!/bin/bash
hash=$(git describe --dirty --always --tags)
echo "#ifndef GITHASH_H" > include/my_project/githash.h
echo "#define GITHASH_H" >> include/my_project/githash.h
echo "const std::string kGitHash = \"$hash\";" >> include/my_project/githash.h
echo "#endif // GITHASH_H" >> include/my_project/githash.h
get_git_hash.cmd:
@echo off
FOR /F "tokens=* USEBACKQ" %%F IN (`git describe --dirty --always --tags`) DO (
SET var=%%F
)
ECHO #ifndef GITHASH_H > include/my_project/githash.h
ECHO #define GITHASH_H >> include/my_project/githash.h
ECHO const std::string kGitHash = "%var%"; >> include/my_project/githash.h
ECHO #endif // GITHASH_H >> include/my_project/githash.h
In CMakeLists.txt add the following lines at the beginning to define the custom target "write_git_hash"
if(WIN32)
add_custom_target( write_git_hash
get_git_hash.cmd
COMMENT "Call batch script for writing git hash"
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
)
else()
add_custom_target( write_git_hash
./get_git_hash.sh
COMMENT "Call shell script for writing git hash"
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
)
endif()
Make sure to add the "include" folder to your project
project(my_project)
include_directories(include)
After you define the executable, add "write_git_hash" as a dependency
add_executable(my_project src/my_cpp_file.cpp)
add_dependencies(my_project write_git_hash)
This will trigger the generation of the githash.h when building the project.
Include the githash.h file in your C++ file with #include <my_project/githash.h>
.
You should now be able to print the git hash to the terminal with
std::cout << "Software version: " << kGitHash << std::endl;
or do with it whatever you like.