Summary: Static (compile-time) assert mechanism
                 Project: Freeciv
            Submitted by: jtn
            Submitted on: Sat Jul 16 23:35:33 2011
                Category: general
                Priority: 5 - Normal
                  Status: In Progress
                 Privacy: Public
             Assigned to: jtn
        Originator Email: 
             Open/Closed: Open
         Discussion Lock: Any
         Planned Release: 2.4.0



For maintainability, it's occasionally useful to be able to make the build
fail if certain conditions are not true, usually relating to build-time
tweakables or system limits.

Bug #18087 is a case in point; MAP_MAX_SIZE relies on MAX_DBV_LENGTH having a
certain minimum value, and this is currently commented, but it would be better
if the build failed hard when someone increased MAP_MAX_SIZE without noticing
the comment, rather than them having to debug some subtle failure. (OK, in
this case you run into a run-time assertion failure pretty quickly, but in
some other case you might not happen to tickle that code path in your

This isn't a standard facility in the C language (yet), but there are a
number of well-known techniques for doing this in C, each with their
advantages and drawbacks (particularly generation of warnings, which matters
to us because we run with -Werror).

Googling found some surveys of available techniques here
<http://www.pixelbeat.org/programming/gcc/static_assert.html>, here
<http://www.jaggersoft.com/pubs/CVu11_3.html> (old!), and here
for example.

I'm leaning toward this one:

#define FC_STATIC_ASSERT(cond, tag) enum { static_assert_ ## tag = 1 /
(!!(cond)) }


which, if it fails, throws the following error on my system:

In file included from ../packets.h:29,
                 from ../game.h:33,
                 from aisupport.c:26:
../map.h:571: error: division by zero
../map.h:571: error: enumerator value for
‘static_assert_map_too_big_for_bitvector’ is not an integer constant

Ugly, but effective.

(It's a shame this idiom doesn't map onto the
static_assert(constant-expression, "error message") pattern that's apparently
coming in a future C standard, but I haven't found a satisfactory technique
that does.)


Reply to this item at:


  Message sent via/by Gna!

Freeciv-dev mailing list

Reply via email to