Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting compile-time date and time without macros

using c++

I compile my code on an automated schedule and need to use the time at which the code was compiled in the code itself. Currently I'm just using the __DATE__, __TIME__ macros to get the compile- time date and time. However, this causes the binaries to change even if no changes have been made to the source (macros will inflate at compile time) which is not good (i don't want the setup to think that the binary changed if there have been no changes to the source).

Is it possible to get the compile-time without using any means that would cause the source to change?

Thanks

like image 282
Habeeb Ahmed Avatar asked Oct 22 '22 05:10

Habeeb Ahmed


1 Answers

The standard __DATE__ and __TIME__ macros do what you observe, return a time dependent string.

It depends upon the system (and perhaps the compiler) and notably the build system (like GNU make for example).

A possible idea could be to link in a seperate timestamp file, something like (in make syntax)

timestamp.c:
        date +'const char timestamp[]="%c";' > $@

program: $(OBJECTS) timestamp.c
        $(LINKER.cc) $^ -o $@ $(LIBES)
        rm -f timestamp.c

The timestamp.owould then be regenerated and your programwould be relinked at every make (so the generated program will indeed change, but most of the code -thru $(OBJECTS) make variable- will stay unchanged).


Alternatively, you could e.g. log inside some database or textual log file the time of linking, e.g.

program: $(OBJECTS)
      $(LINKER.cc) $^ -o $@ $(LIBES)
      date +'$@ built at %c' >> /var/log/build.log

(you might use logger instead of date to get that logged in the syslog)

Then the generated program won't change, but you'll have logged somewhere a build timestamp. BTW you could log also some checksum (e.g. $(shell md5sum program) in make syntax) of your binary program.

like image 98
Basile Starynkevitch Avatar answered Oct 24 '22 02:10

Basile Starynkevitch