Yan*_*Zhu 3 c c++ time compilation
我有一个源文件.当我编译代码时,我希望可执行文件在构建时记住.我想知道是否有可能.例如:
int main(){
time_t t = ??? // Time when this line is compiled
//print out value of t in certain format.
return t
}
Run Code Online (Sandbox Code Playgroud)
Fle*_*exo 11
您可以使用__TIME__和__DATE__宏来获取预处理器运行的时间.这是一个字符串,所以你需要将它time_t从那里转换为a.
我放在一起的一个简单例子:
#include <time.h>
#include <iostream>
#include <cassert>
time_t build_time() {
static const char *built = __DATE__" "__TIME__;
struct tm t;
const char *ret = strptime(built, "%b %d %Y %H:%M:%S", &t);
assert(ret);
return mktime(&t);
}
int main() {
std::cout << build_time() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
我有点担心这与不同的语言环境有什么关系,所以我快速查看了最近的C标准并找到了以下段落:
__DATE__预处理翻译单元的翻译日期:"Mmm dd yyyy"形式的字符串文字,其中月份的名称与asctime函数生成的相同,dd的第一个字符是空格字符该值小于10.如果没有翻译日期,则应提供实施定义的有效日期.
asctime 很明显:
......月份的缩写是"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct"," 11月"和"12月"......
但%b中strptime()说:
%b或%B或%h
根据当前区域设置的月份名称,缩写形式或全名.
所以你需要知道这是在运行时设置区域设置的假设.
(理论上你可以编写一个constexpr或两个函数来在C++ 11的编译时执行此操作,但至少可以说这是非常重要的!)
| 归档时间: |
|
| 查看次数: |
1123 次 |
| 最近记录: |