我希望能够获得编译c++程序的UNIX时间(从epoch开始的秒数)。
我应该如何使用预处理器声明来做到这一点?
我认为一旦我计算出了UNIX编译时间,其他的一切都可以以此为基础。
用sscanf
、__DATE__
和/或__TIME__
填充tm
结构体的编译时间。
使用mktime
将对象转换为unix时间,得到一个time_t
。
tm compile_time;
...
sscanf(__DATE__, "%s %d %d", month, &compile_time.tm_mday, &compile_time.tm_year);
...
time_t timestamp = mktime(&compile_time);
请注意,您必须将月份名称转换为整数(0-11)。
c++提供了许多预定义的宏,包括__TIME__
__LINE__ This contain the current line number of the program when it is being compiled.
__FILE__ This contain the current file name of the program when it is being compiled.
__DATE__ This contains a string of the form month/day/year that is the date of the translation of the source file into object code.
__TIME__ This contains a string of the form hour:minute:second that is the time at which the program was compiled.
让我们看看上面所有宏的例子:
#include <iostream>
using namespace std;
int main ()
{
cout << "Value of __LINE__ : " << __LINE__ << endl;
cout << "Value of __FILE__ : " << __FILE__ << endl;
cout << "Value of __DATE__ : " << __DATE__ << endl;
cout << "Value of __TIME__ : " << __TIME__ << endl;
return 0;
}
如果我们编译并运行上面的代码,将产生以下结果:
Value of __LINE__ : 6
Value of __FILE__ : test.cpp
Value of __DATE__ : Mai 17 2014
Value of __TIME__ : 18:52:48