获取没有宏的编译时日期和时间 [英] getting compile-time date and time without macros

查看:89
本文介绍了获取没有宏的编译时日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用c ++

我以自动的时间表来编译我的代码,并且需要使用代码本身在代码中编译的时间.目前,我只是使用__DATE____TIME__宏来获取编译时的日期和时间.但是,这会导致二进制文件更改,即使未对源代码进行任何更改(宏会在编译时膨胀)也不是一件好事(我不希望安装程序认为二进制文件在没有更改的情况下也已更改)到源头).

I compile my code on an automated schedule and need to use the time at which the code was compiled in the code itself. Currently I'm just using the __DATE__, __TIME__ macros to get the compile- time date and time. However, this causes the binaries to change even if no changes have been made to the source (macros will inflate at compile time) which is not good (i don't want the setup to think that the binary changed if there have been no changes to the source).

是否可以在不使用任何会导致源代码更改的方法的情况下获得编译时间?

Is it possible to get the compile-time without using any means that would cause the source to change?

谢谢

推荐答案

标准的__DATE____TIME__宏可以执行您所观察到的操作,并返回时间相关的字符串.

The standard __DATE__ and __TIME__ macros do what you observe, return a time dependent string.

这取决于系统(可能还有编译器),尤其取决于构建系统(例如GNU make ).

It depends upon the system (and perhaps the compiler) and notably the build system (like GNU make for example).

一个可能的想法可能是链接一个单独的时间戳文件,类似于(使用make语法)

A possible idea could be to link in a seperate timestamp file, something like (in make syntax)

timestamp.c:
        date +'const char timestamp[]="%c";' > $@

program: $(OBJECTS) timestamp.c
        $(LINKER.cc) $^ -o $@ $(LIBES)
        rm -f timestamp.c

然后将重新生成timestamp.o,并且将在每个make处重新链接您的program(因此,生成的程序的确会发生变化,但是大部分代码-thru $(OBJECTS) make variable-将保持不变)

The timestamp.owould then be regenerated and your programwould be relinked at every make (so the generated program will indeed change, but most of the code -thru $(OBJECTS) make variable- will stay unchanged).

或者,您可以例如链接时在某些数据库或文本日志文件中记录链接时间,例如

Alternatively, you could e.g. log inside some database or textual log file the time of linking, e.g.

program: $(OBJECTS)
      $(LINKER.cc) $^ -o $@ $(LIBES)
      date +'$@ built at %c' >> /var/log/build.log

(您可以使用logger而不是date来将其记录到系统日志中)

(you might use logger instead of date to get that logged in the syslog)

然后生成的program不会更改,但是您将在某个地方记录构建时间戳.顺便说一句,您还可以记录二进制程序的某些校验和(例如make语法中的$(shell md5sum program)).

Then the generated program won't change, but you'll have logged somewhere a build timestamp. BTW you could log also some checksum (e.g. $(shell md5sum program) in make syntax) of your binary program.

这篇关于获取没有宏的编译时日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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