如何将构建日期自动获取到我的代码可见的常量中? [英] How can I automate getting the date of build into a constant visible to my code?

查看:19
本文介绍了如何将构建日期自动获取到我的代码可见的常量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的代码中定义一个常量来保存可执行文件的构建日期.我很自然地希望自动化这个过程.

我知道我可以使用 Perl 等编写预构建脚本来写出包含日期的 .inc 文件.我更喜欢使用环境变量或构建变量的更轻量级的解决方案.msbuild 是否提供任何有帮助的变量?有谁知道这个问题的更简洁的解决方案?

解决方案

您可以从 PE 头 可执行文件:

使用图像帮助;function LinkerTimeStamp(const FileName: string): TDateTime;超载;无功LI: TLoadedImage;开始Win32Check(MapAndLoad(PChar(FileName), nil, @LI, False, True));结果:= LI.FileHeader.FileHeader.TimeDateStamp/SecsPerDay + UnixDateDelta;UnMapAndLoad(@LI);结尾;

对于当前模块的加载图像,以下似乎有效:

function LinkerTimestamp: TDateTime;超载;开始结果:= PImageNtHeaders(HInstance + Cardinal(PImageDosHeader(HInstance)^._lfanew))^.FileHeader.TimeDateStamp/SecsPerDay + UnixDateDelta;结尾;

早期版本的 Delphi 没有正确更新它,但它已在 Delphi 2010 左右修复.对于早期版本,我使用 IDE 插件在成功编译后自动更新.>

注意:该值存储为 UTC,因此为了显示目的,您可能需要将其转换为适当的时区.

I would like to define in my code a constant holding the date on which the executable was built. I would naturally like to automate that process.

I know that I can write a pre-build script using, for example, Perl, to write out a .inc file containing the date. I would prefer a more lightweight solution using, perhaps, environment variables or build variables. Does msbuild provide any variables that would help? Does anyone know a neater solution to the problem?

解决方案

You can read the linker timestamp from the PE header of the executable:

uses
  ImageHlp;

function LinkerTimeStamp(const FileName: string): TDateTime; overload;
var
  LI: TLoadedImage;
begin
  Win32Check(MapAndLoad(PChar(FileName), nil, @LI, False, True));
  Result := LI.FileHeader.FileHeader.TimeDateStamp / SecsPerDay + UnixDateDelta;
  UnMapAndLoad(@LI);
end;

For the loaded image of the current module, the following seems to work:

function LinkerTimestamp: TDateTime; overload;
begin
  Result := PImageNtHeaders(HInstance + Cardinal(PImageDosHeader(HInstance)^._lfanew))^.FileHeader.TimeDateStamp / SecsPerDay + UnixDateDelta;
end;

Earlier versions of Delphi didn't update it correctly but it has been fixed around Delphi 2010 or so. For the earlier versions, I used an IDE plugin to update it automatically after a successful compile.

Note: The value is stored as UTC so for display purposes you may need to convert it to an appropriate timezone.

这篇关于如何将构建日期自动获取到我的代码可见的常量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆