Hector
Hector

Reputation: 1220

Preprocessor macro to remove code if compiled after a certain date

I would like three lines of code not to be included if compiled after a certain date. The reason being is they provide backwards compatibility. To support a staggered release between client and embedding it is required to be there now.

Once the next software release comes along this support is to be dropped to force customers to upgrade the embedded software. Since this is a few months away there is risk of these lines being forgotten.

So ideally I would like a

#if __DATE__ > MyDate
    code here
#endif

or something equivalent. Is there any way of doing this?

*The code is compiled with GCC

Upvotes: 4

Views: 303

Answers (4)

Bathsheba
Bathsheba

Reputation: 234825

This solution is specifically for Windows platform and is something I use in production.

I exploit the environment variable %DATE%, and in a batch file used to launch my IDE, I have VA_CURRENT_DATE=%DATE:~6,4%%DATE:~3,2%%DATE:~0,2% (which transforms to an ISO8601 date for my specific locale).

Then in my preprocessor definitions for my project I define VA_BUILD_DATE to VA_CURRENT_DATE

Then I have some code like:

long day = VA_BUILD_DATE;
long year = day / 10000;
day -= year * 10000;
long month = day / 100;
day -= month * 100;

Upvotes: 5

Eric Z
Eric Z

Reputation: 14525

Now I am running the risk of not answering your question directly. But I'd take the risk and suggest you NOT to do so. How many times does a project get released on time? The date is, too prone to change. And you never know that.

Why not use the version of your project instead?

// Only defined in old projects that you want this legacy code in.
#ifdef OLD__VERSION
    code here
#endif

Upvotes: 2

zwol
zwol

Reputation: 140786

You can't do this with __DATE__, because it expands to a string constant, and string constants can't be used in #if. Also, setting a fixed date is a bad idea, because you may need to do bug-fix releases to the older version that should preserve the backward compatibility.

(Do you really need to drop backward compatibility? If it's only three lines of code, consider just keeping them around forever. Your customers will not thank you for "forcing them to upgrade.")

The good way to do this sort of thing is via your version control system. You should be maintaining a branch for each release anyway, so write your code like this:

#ifdef BACKWARD_COMPAT_VERSION_1_0
    compatibility code here
#endif

and then change the Makefile on the release branch, only, to include -DBACKWARD_COMPAT_VERSION_1_0 in your CFLAGS.

Upvotes: 3

trojanfoe
trojanfoe

Reputation: 122421

Unfortunately this won't work as __DATE__ produces a string in the form "Sep 5 2013", which is useless for comparison.

Ideally the compiler should support a constant like __DATEFLAT__ which produces an integer like 20130905, which would be ideal for such as task. However this doesn't exist.

Upvotes: 1

Related Questions