Embed timestamp in object code at compile time with C++

你。 提交于 2019-12-18 18:33:49

问题


I want to perform a printf() to display when the currently executing code was last compiled. Does C/C++ provide a macro that gives you that resolves to a timestamp during compilation?


回答1:


You could use __DATE__ and __TIME__.




回答2:


16.8 Predefined macro names [cpp.predefined]
1 The following macro names shall be defined by the implementation:
__LINE__ The line number of the current source line (a decimal constant).
__FILE__ The presumed name of the source file (a character string literal).
__DATE__ The date of translation of the source file (a character string literal of the form "Mmm dd yyyy", where the names of the months are the same as those generated by the asctime function, and the first character of dd is a space character if the value is less than 10). If the date of translation is not available, an implementation-defined valid date is supplied.
__TIME__ The time of translation of the source file (a character string literal of the form "hh:mm:ss" as in the time generated by the asctime function). If the time of translation is not available, an implementation-defined valid time is supplied.
__STDC__ Whether __STDC__ is predefined and if so, what its value is, are implementation-defined.
__cplusplus The name __cplusplus is defined to the value 199711L when compiling a C++ translation unit.

You want __TIME__ and possibly __DATE__.




回答3:


Use the macros __DATE__ and __TIME__




回答4:


If you are using gcc preprocessor then you will find what you are looking for in the __TIME__ and __DATE__ macros

Quotes from GNU C pre-processor documentation:

__DATE__

This macro expands to a string constant that describes the date on which the preprocessor is being run. The string constant contains eleven characters and looks like "Feb 12 1996". If the day of the month is less than 10, it is padded with a space on the left.

...

__TIME__

This macro expands to a string constant that describes the time at which the preprocessor is being run. The string constant contains eight characters and looks like "23:59:01".




回答5:


Use a script, or create an application, to generate a C++ source file containing the build date and time. Add this file to the build setup. The other parts of the program can reference the data in this file.

This technique is also useful for embedding a version number into the program. The build process can control the version number.




回答6:


It looks like compilers are expected to provide a __TIMESTAMP__ macro, which ought to work for your purposes.




回答7:


I am using this to send a message to DbgView:

    OutputDebugStringA(("ATTACHED VERSION: "+ string(__DATE__) + " " + string(__TIME__)).c_str());


来源:https://stackoverflow.com/questions/2526933/embed-timestamp-in-object-code-at-compile-time-with-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!