0

Firstly, I recognize that this may not be possible, as macros are only expanded once. However, I'm hoping there is some standard way of getting similar behavior, or suggestions for other methods to pursue.

I'm looking for a way to do a compile-time check on our build that would raise an error in the event of incompatibility. The following will, of course, not work, but is the easiest way in my mind to get the idea across:

version.h:

#define CODE_VERSION 2
#define VERSION(x)    #if (CODE_VERSION > (x) ) \
                          #error "Incompatible version detected!" \
                      #endif

main.c:

#include "version.h"
VERSION(1)
// ...and so on

If the output from the preprocessor was fed back into the preprocessor, this ought to cause an error to appear during compilation.

So, what is the proper way to achieve this (or similar) behavior? For the curious, the thought behind of this is to avoid manual analysis during reviews of a reasonably large codebase to comply with an audit process (as automatic auditing is so much less burdensome).

Nate
  • 12,499
  • 5
  • 45
  • 60
  • 1
    I fail to understand what you are trying to achieve. Usually, you change version.h and main.c together, so that they remain compatible with each other. Perhaps what you need is a good version control system? – Juliano Jan 17 '11 at 15:43
  • 1
    This is a) across hundreds of files, and b) is actually NOT version related - I just figured that it was an easily-approachable equivalent, without having to explain the details of what I'm actually checking. Version control has no bearing on the problem. – Nate Jan 17 '11 at 15:46

3 Answers3

4

boost static assert? As this is tagged C and C++, boost is perhaps not an option but refer to : BOOST_STATIC_ASSERT without boost for alternative.

Community
  • 1
  • 1
AProgrammer
  • 51,233
  • 8
  • 91
  • 143
4

A solution available for C could be to define in your main.c the version it needs before including version.h:

  • main.c:

    #define NEEDED_VERSION 1
    #include "version.h"
    
  • version.h:

    #define CODE_VERSION 2
    #ifndef NEEDED_VERSION
      #error please declare what version you need
    #elif NEEDED_VERSION > CODE_VERSION
      #error
    #endif
    
peoro
  • 25,562
  • 20
  • 98
  • 150
1

One way to make compile-time assertions without using any C++0x features is described in "Compile Time Assertions in C" by Jon Jagger. The C Programming wikibook has a section on compile-time assertions.

You end up with something like

main.c:

#include "version.h"
#include <static_assert.h>

static_assert( (CODE_VERSION <= 1), "Incompatible version detected!" )

p.s.: I'm almost certain that "use test-driven development (TDD) and a decent version control system" is a better way to avoid accidentally including old versions of source code.

David Cary
  • 5,250
  • 6
  • 53
  • 66