在工程中经常会使用svn的版本号作为开发版本的迭代的版本信息。如果使用手动配置文件的方式,开发人员可能会经常忘记更新配置文件,这回导致svn版本和软件配置文件的版本信息不一致的问题。所以为了解决这个问题,我们可以将svn版本号信息编译到软件的可执行文件中。那么就需要在编译前通过脚本生成版本头文件(version.h),然后代码中引用该头文件,获取版本宏内容。
经过查阅和实践,我总结了在VS和QT(QMake)中使用的方式,为了跨平台支持,这里使用了python脚本来生成version.h头文件。
1. VS设置预生成事件
在Windows下,我们使用Vs来管理和编译自己的工程。所以可以通过Vs的预生成事件来执行python脚本:
在预生成事件的命令行中输入你需要执行的脚本,类似在cmd命令行中需要做的相关操作:
cd /d $(SolutionDir)\version
python version.py
那么在命令行中加入这些后,在编译前编译器就会先执行这个命令。我们用的时python去读取svn的信息,这里又是执行的命令模式去获取,所以要确保svn支持windows命令模式,如果不支持,需要修复安装:
安装时,选择如上的选项进行安装。然后进入cmd命令模式,在自己的svn工程下执行是svn info,看是否可以顺利输出svn的相关信息。
2. Qmake设置预生成事件
linux下我们使用的是qtcreater,所以在.pro中加入如下即可:
versionTarget.target = …/…/version.h
versionTarget.depends = FORCE
versionTarget.commands = cd …/…/; python version.py -p $$TARGETPRE_TARGETDEPS += …/…/version.h
QMAKE_EXTRA_TARGETS += versionTarget
编译时,qt会先执行这部分,生成我们需要的头文件,然后再进行编译。
最后附上生成version.h的脚本:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
if __name__ == '__main__':
curDir = os.path.dirname(os.path.abspath(__file__))
print curDir
versionFile = open(curDir + '/version.h', 'w')
print versionFile
versionFile.write('#ifndef VERSION_H' + '\n')
versionFile.write('#define VERSION_H' + '\n\n')
versionInfo = os.popen('svn info')
varInfo = versionInfo.read()
if varInfo is not '':
infoList = varInfo.splitlines()
for strInfo in infoList:
if strInfo.find('Revision') >= 0:
strVersion = re.findall("\d+", strInfo)
versionFile.write('#define SVN_VERSION ' + str(strVersion[0]) + '\n\n')
else:
versionFile.write('#define SVN_VERSION 9999' + '\n\n')
versionFile.write('#endif')