Search code examples
cc-preprocessorepoch

Getting Epoch Time at Compile Time


Context: I'm writing a sort of non-trivial client-server UDP multicast program that I'm deploying on some wireless nodes. The means of deployment is a script I wrote that broadcast pings the network that these nodes sit on, gets a list of the nodes (based on IP addresses), deploys my package, and installs it. It has come to my attention that sometimes not all the nodes are detected at the time of deployment, and the most current package I'm developing is not installed. Ultimately, it can be the case in which the server running on one node is older than a client who wishes to communicate with the server. Because the server gets packets, and allocates memory depending on entries in this packet, if the structure changes, the server usually crashes in a segfault. As a solution, I'm thinking about implementing version numbers in the packets that get sent between client and server such that if the server/client reads a packet in which the version number isn't the same (or is garbage because of restructuring of packets), this packet gets ignored, and a log is updated, or an emergency packet is sent to the original sender.

So, I'm trying to come up with the best way of getting this "version number" at compile time that can sit in a header as a #define. I've looked up the __time__ preprocessor macro, but this is in the form of a string. Is there a way to get the epoch time during compile time so that I can bitmask it into an unsigned int (which should only roll over after 136 years, if I'm thinking about this correctly)?

Sorry if I'm being unclear.


Solution

  • It depends on your build system, but if you're using gmake, you can do something like:

    CXX_TIME = -DBUILDTIME=$(shell python -c "import time; print( int( time.time() ) )" )
    

    Add this into your other compiler options, and then use the macro BUILDTIME in your code.

    (This supposes that you've got Python installed in your path. If not, you can either install it, or do something similar with a tool you have installed.)