且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何自动化将生成日期定义为我的代码可见的常量?

更新时间:2023-01-29 15:52:36

您可以从 PE标题

 使用
ImageHlp;

函数LinkerTimeStamp(const FileName:string):TDateTime;超载;
var
LI:TLoadedImage;
begin
Win32Check(MapAndLoad(PChar(FileName),nil,@LI,False,True));
结果:= LI.FileHeader.FileHeader.TimeDateStamp / SecsPerDay + UnixDateDelta;
UnMapAndLoad(@LI);
结束

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

 函数LinkerTimestamp:TDateTime;超载; 
begin
结果:= PImageNtHeaders(HInstance + Cardinal(PIMageDosHeader(HInstance)^ ._ lfanew))^。FileHeader.TimeDateStamp / SecsPerDay + UnixDateDelta;
结束

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

注意:该值存储为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.