获取没有宏的编译时间日期和时间
使用 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
会被重新生成,你的program
会在每次make
时重新链接(所以生成的程序确实会改变,但大多数代码 - 通过 $(OBJECTS)
make variable- 将保持不变).
The timestamp.o
would then be regenerated and your program
would 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
不会改变,但您会在某处记录构建时间戳.顺便说一句,您还可以记录二进制程序的一些校验和(例如 $(shell md5sum program)
在 make
语法中).
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.
相关文章