简体   繁体   中英

c / c++ compile-time “compatibility” check

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).

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.

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 

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!" )

ps: 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM