Yan Zhu
Yan Zhu

Reputation: 4356

Recording the time when you compile a source

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 
 } 

Upvotes: 3

Views: 1585

Answers (4)

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 a time_t from there.

A quick example I put together:

#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;
}

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:

__DATE__ The date of translation of the preprocessing translation unit: 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 shall be supplied.

asctime is quite clear that:

... The abbreviations for the months are "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", and "Dec" ...

But %b of strptime() says:

%b or %B or %h

The month name according to the current locale, in abbreviated form or the full name.

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 constexpr function or two to do that at compile time in C++11, but that's non-trivial to say the least!)

Upvotes: 11

webgenius
webgenius

Reputation: 904

Read the last date and time modified properties of your executable in your code.

Upvotes: 0

Andrius Naruševičius
Andrius Naruševičius

Reputation: 8578

It is not perfectly addressing your problem, but in visual studio you can add a post built events. Add some console command like creating a new file or updating an existing one to see when it was last built successfully. I am doing this to copy my report files to the directory that I need them in. I just build my project and they all go there :)

Upvotes: 2

NPE
NPE

Reputation: 500883

You can record the time as string through the __DATE__ and __TIME__ predefined macros.

If you want a time_t, you'll have to convert it at runtime.

Upvotes: 5

Related Questions