使用简单Makefile,则可直接添加宏定义:
CPPFLAGS+=-DGIT_SHA1="$(shell git log --format='[sha1]:%h [author]:%cn [time]:%ci [commit]:%s [branch]:%d' -1)"
使用CMake,在CMakeList.txt中添加:
exec_program(
"git"
${CMAKE_CURRENT_SOURCE_DIR}
ARGS "log --format='[sha1]:%h [author]:%cn [time]:%ci [commit]:%s [branch]:%d' -1"
OUTPUT_VARIABLE VERSION_SHA1 )
add_definitions( -DGIT_SHA1="${VERSION_SHA1}" )
CMake也可通过使用https://github.com/rpavlik/cmake-modules里的扩展GetGitRevisionDescription。
然后在代码中根据宏GIT_SHA1来进行相应的打印输出,方便追踪对应的版本信息。
ps: 如果不使用宏,也可替换源文件方法,或者CMakefile中使用configure_file来进行管理xxx.cpp.in文件编译。