C++程序带版本信息

主程序携带版本信息

思路是通过cmake获取版本控制信息,生成version.h版本信息文件,在项目中include生成的头文件带到程序中

# 项目信息这里指定,版本变更就改这里的version
project(example_project
    VERSION 1.2.2
    LANGUAGES CXX)

include(FindSubversion)

if(SUBVERSION_FOUND)
    Subversion_WC_INFO(${PROJECT_SOURCE_DIR} SVN IGNORE_SVN_FAILURE)
endif()

# 如果能获取到svn信息就重新指定version,添加svnrevision信息
if(SVN_WC_REVISION)
    PROJECT(example_project)
        VERSION ${PROJECT_VERSION}.${SVN_WC_REVISION}
        LANGUAGES CXX)
else()
    # 没有就找git信息
    find_package(Git)
    if(GIT_FOUND)
        execute_process(
            COMMAND ${GIT_EXECUTABLE} log -1 --pretty=format:%H
            OUTPUT_VARIABLE COMMIT_HASH
            OUTPUT_STRIP_TRAILING_WHITESPACE)
    endif()
endif()

# 生成version.h
configure_file(${PROJECT_SOURCE_DIR}/version.h.in ${PROJECT_SOURCE_DIR}/version.h)

version.h.in为生成配置的模板

#pragma once
#define PROJECT_NAME "@[email protected]"
#define PROJECT_VER "@[email protected]"
#define PROJECT_VER_MAJOR "@[email protected]"
#define PROJECT_VER_MINOR "@[email protected]"
#define PROJECT_VER_PATCH "@[email protected]"
#define PROJECT_VER_TEWAK "@[email protected]"
#define PROJECT_VER_HASH "@[email protected]"

至于怎么判断是否有git的hash信息可以用PROJECT_VER_HASH[0]!=0判断

依赖库携带版本信息

因为程序会用到依赖动态库,所以希望显示版本信息的时候除了主程序的版本还要显示当前使用的动态库版本信息
思路为在动态库中加个版本符号(全局静态变量),在主程序里直接读这个变量获取

依赖库的cmake获取版本生成version.h的内容和主程序的一样
需要在接口头文件中声明版本变量

extern char LIBDEP_VER[];
extern char LIBDEP_VER_MAJOR[];
extern char LIBDEP_VER_MINOR[];
extern char LIBDEP_VER_PATCH[];
extern char LIBDEP_VER_TWEAK[];
extern char LIBDEP_VER_HASH[];

version.h.in配置中赋值

#pragma once
char LIBDEP_VER[] = "@[email protected]";
char LIBDEP_VER_MAJOR[] = "@[email protected]";
char LIBDEP_VER_MINOR[] = "@[email protected]";
char LIBDEP_VER_PATCH[] = "@[email protected]";
char LIBDEP_VER_TWEAK[] = "@[email protected]";
char LIBDEP_VER_HASH[] = "@[email protected]";

@

Show Comments