cmake编译时候加入git的版本号和分支名字

# 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
          ${CMAKE_CURRENT_SOURCE_DIR}
        )
    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
          ${CMAKE_CURRENT_SOURCE_DIR}
        )
    endif()
endmacro()

# 获取当前的GIT_HASH
set(GIT_HASH "unknown")
get_git_hash(GIT_HASH)
add_definitions(-DMY_GIT_VERSION="${GIT_HASH}")

# 获取当前的分支
set(GIT_BRANCH "unknown")
get_git_branch(GIT_BRANCH)
add_definitions(-DMY_GIT_BRANCH="${GIT_BRANCH}")
#define STRING(R) #R
#define AS_STRING(R) STRING(R)
std::cout<<"git version:"<

AS_STRING(GIT_VERSION)这句只会展开成GIT_VERSION,而不会再往下一层把GIT_VERSION也展开成一个具体的数值,因此,我们定义一个STRING(GIT_VERSION)的宏做中间转换,就能正常把AS_STRING(GIT_VERSION)展开STRING(GIT_VERSION),最终展开成具体的git 版本号。

你可能感兴趣的:(c++)