1.获取编译时间戳
string(TIMESTAMP COMPILE_TIME %Y%m%d_%H%M%S)
set(build_time ${COMPILE_TIME})
2.获取git 分支、commit号
#git号
set(GIT_HASH "")
get_git_hash(GIT_HASH)
#git分支
set(GIT_BRANCH "")
get_git_branch(GIT_BRANCH)
# get git hash
macro(get_git_hash _git_hash)
find_package(Git QUIET)
if(GIT_FOUND)
execute_process(
COMMAND ${GIT_EXECUTABLE} log -1 --pretty=format:%h
OUTPUT_VARIABLE ${_git_hash}
OUTPUT_STRIP_TRAILING_WHITESPACE
ERROR_QUIET
WORKING_DIRECTORY
${CPP_PATH}
)
endif()
endmacro()
# get git branch
macro(get_git_branch _git_branch)
find_package(Git QUIET)
if(GIT_FOUND)
execute_process(
COMMAND ${GIT_EXECUTABLE} symbolic-ref --short -q HEAD
OUTPUT_VARIABLE ${_git_branch}
OUTPUT_STRIP_TRAILING_WHITESPACE
ERROR_QUIET
WORKING_DIRECTORY
${CPP_PATH}
)
endif()
endmacro()
3.上述版本参数写到版本头文件
VersionConfigPath:你的配置文件路径,自己设定
VersionConfig.h.in:配置文件母版,自己创建,输入的参数会替换里面的字段生成VersionConfig.h文件
VersionConfig.h:生成出来配置文件,自动生成,给源码include
configure_file(
"${VersionConfigPath}/VersionConfig.h.in"
"${VersionConfigPath}/VersionConfig.h"
)
//VersionConfig.h.in
#define V_BUILD_TIME "@build_time@"
#define V_GIT_INFO "@GIT_BRANCH@_@GIT_HASH@"
//VersionConfig.h
#define V_BUILD_TIME "20210324_145645"
#define V_GIT_INFO "master_81076d98"
4源文件使用版本头文件
#include "VersionConfig.h"
...
printf("version=%s\n",V_BUILD_TIME);