示例说明:
本示例主要是自动生成与日期时间关联的软件版本号,格式如:250211.1758
缺点:只在构建时才会生成版本号。
一、手动编写.sh或.bat脚本文件;
二、在.pro中添加代码调用此脚本文件;
三、编译时调用脚本,并生成指定的.h文件;
四、在其它代码文件中include上述.h文件;
详细步骤:
1、编写.sh或.bat脚本文件
以下为update_version.sh
内容(提供给Linux使用):
#!/bin/bash
# 获取当前时间戳作为版本号的一部分
timestamp=$(date +%y%m%d.%H%M)
# 写入版本号到version.h
echo "#ifndef MYVERSION_H" > version.h
echo "#define MYVERSION_H" >> version.h
echo "" >> version.h
echo "#include \"QString\"" >> version.h
echo "" >> version.h
echo "const QString MYSOFT_VERSION = \"$timestamp\";" >> version.h
echo "" >> version.h
echo "#endif // MYVERSION_H" >> version.h
以下为update_version.bat
内容(提供给Windows使用):
@echo off
:: 使用PowerShell获取当前时间戳
for /f "delims=" %%i in ('powershell -NoProfile -Command "Get-Date -Format 'yyMMdd.HHmm'"') do set timestamp=%%i
:: 写入版本号到version.h
echo #ifndef MYVERSION_H > version.h
echo #define MYVERSION_H >> version.h
echo. >> version.h
echo #include "QString" >> version.h
echo. >> version.h
echo const QString MYSOFT_VERSION = "%timestamp%"; >> version.h
echo. >> version.h
echo #endif // MYVERSION_H >> version.h
2、在.pro中添加代码调用此脚本文件
代码如下:
win32 {
system("cmd /c update_version.bat")
} else {
system("sh update_version.sh")
}
HEADERS += version.h
3、编译时调用脚本,并生成指定的.h文件
上述操作完成后,执行构建或重新构建时,会生成version.h
文件。
4、在其它代码文件中include上述.h文件
#include "version.h"
QString SoftVersion = "1.0." + MYSOFT_VERSION;//软件版本号
版本号替代方案
使用宏变量__DATA__
和__TIME__
来获取软件的日期和时间。
这种方法只要.exe发生编译,就会改变日期和时间值。
版本号获取代码如下:
QString getVersionString() {
const char *date = __DATE__;
const char *time = __TIME__;
// 提取月份并转换为数字
char monthStr[4] = {date[0], date[1], date[2], '\0'};
int month = 0;
if (std::strcmp(monthStr, "Jan") == 0) month = 1;
else if (std::strcmp(monthStr, "Feb") == 0) month = 2;
else if (std::strcmp(monthStr, "Mar") == 0) month = 3;
else if (std::strcmp(monthStr, "Apr") == 0) month = 4;
else if (std::strcmp(monthStr, "May") == 0) month = 5;
else if (std::strcmp(monthStr, "Jun") == 0) month = 6;
else if (std::strcmp(monthStr, "Jul") == 0) month = 7;
else if (std::strcmp(monthStr, "Aug") == 0) month = 8;
else if (std::strcmp(monthStr, "Sep") == 0) month = 9;
else if (std::strcmp(monthStr, "Oct") == 0) month = 10;
else if (std::strcmp(monthStr, "Nov") == 0) month = 11;
else if (std::strcmp(monthStr, "Dec") == 0) month = 12;
// 处理日期,确保两位
char dayPart[3];
if (date[4] == ' ') {
dayPart[0] = '0';
dayPart[1] = date[5];
} else {
dayPart[0] = date[4];
dayPart[1] = date[5];
}
dayPart[2] = '\0';
int day = std::atoi(dayPart);
// 提取年份后两位
char yearLastTwo[3] = {date[9], date[10], '\0'};
// 处理时间,提取小时和分钟
char hour[3] = {time[0], time[1], '\0'};
char minute[3] = {time[3], time[4], '\0'};
// 组合成版本号字符串
return QString("%1%2%3.%4%5")
.arg(yearLastTwo)
.arg(month, 2, 10, QChar('0'))
.arg(day, 2, 10, QChar('0'))
.arg(hour, minute);
}