Static Asserts in Microchip XC8

A project log for Microhacks

A collection of small ideas

ted-yapoTed Yapo 07/24/2020 at 14:500 Comments

XC8 seems to ignore negative array sizes in typedefs, a common trick for realizing static assert functionality in C. To get around this, the following code defines an unused file-scope function that declares an automatic array with negative size if the assertion fails, which XC8 properly complains about. If the assertion passes, the function gets defined, but is never called, and gets optimized out.

I disable the unused function warning to clean up the output a bit.

// disable unused function definition warnings
#pragma warning disable 967

#define _STATIC_ASSERT_H2(a, b) a ## b
#define _STATIC_ASSERT_H1(c, l) static void _STATIC_ASSERT_H2(_STATIC_ASSERT_LINE_, l) (){int a[1-2*(!(c))];}
// this will throw a negative array size when the assertion
//   fails at compile time; check line it was expanded from
#define STATIC_ASSERT(cond) _STATIC_ASSERT_H1(cond, __LINE__ )


 this is mostly here so I can search for it later.