I have a source file. When I compile the code, I want the executable file to remember when it was built. I am wondering if it is possible. For example:
int main(){
time_t t = ??? // Time when this line is compiled
//print out value of t in certain format.
return t
}
You can use the
__TIME__and__DATE__macros to get the time the preprocessor ran at. It’s a string, so yo need to convert it to atime_tfrom there.A quick example I put together:
I was a little worried about how this interacted with different locales, so I had a quick look in a recent C standard and found the following passage:
asctimeis quite clear that:But
%bofstrptime()says:So you need to be aware that this is making an assumption about what the locale will be set to at run time.
(You could in theory write a
constexprfunction or two to do that at compile time in C++11, but that’s non-trivial to say the least!)