如何查找UNIX的编译时间

How to find UNIX time of compilation

本文关键字:UNIX 编译 时间 查找 何查找      更新时间:2023-10-16

我希望能够获得编译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