getting compile-time date and time without macros(获取没有宏的编译时间日期和时间)
问题描述
使用 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.
这篇关于获取没有宏的编译时间日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:获取没有宏的编译时间日期和时间


基础教程推荐
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01