polytopia
polytopia

Reputation: 429

How can I write a C #if directive that branches based on the current date

What I want is something functionally like this:

#if TODAY<OCTOBER_31_2017
#define OK 0
#elif TODAY==OCTOBER_31_2017     
#define OK 1
#else     
#define OK 2
#endif

So I want "OK" to have the relevant compile-time value, depending on today's date.

Is there any way to do it?

Upvotes: 2

Views: 33

Answers (1)

Petr Skocik
Petr Skocik

Reputation: 60117

Assuming a compiler that accepts the -D option and a POSIX shell/environment invoking it, you can do:

cc -DOCTOBER_31_2017=$(date -d 'Oct 31 2017' +%s) \
   -DTODAY=$(date -d now +%s) \
    yourfile.c

and your preprocessor code should work.

( date +%s prints dates as a UNIX timestamps (seconds since 1970-01-01 00:00:00 UTC), which should allow you to compare them with the C preprocessor's integer arithmetic. )

Upvotes: 1

Related Questions