I’d like to implement an “assert” that prevents compilation, rather than failing at runtime, in the error case.
I currently have one defined like this, which works great, but which increases the size of the binaries.
#define MY_COMPILER_ASSERT(EXPRESSION) switch (0) {case 0: case (EXPRESSION):;}
Sample code (which fails to compile).
#define DEFINE_A 1
#define DEFINE_B 1
MY_COMPILER_ASSERT(DEFINE_A == DEFINE_B);
How can I implement this so that it does not generate any code (in order to minimize the size of the binaries generated)?
A compile-time assert in pure standard C is possible, and a little bit of preprocessor trickery makes its usage look just as clean as the runtime usage of
assert().The key trick is to find a construct that can be evaluated at compile time and can cause an error for some values. One answer is the declaration of an array cannot have a negative size. Using a typedef prevents the allocation of space on success, and preserves the error on failure.
The error message itself will cryptically refer to declaration of a negative size (GCC says “size of array foo is negative”), so you should pick a name for the array type that hints that this error really is an assertion check.
A further issue to handle is that it is only possible to
typedefa particular type name once in any compilation unit. So, the macro has to arrange for each usage to get a unique type name to declare.My usual solution has been to require that the macro have two parameters. The first is the condition to assert is true, and the second is part of the type name declared behind the scenes. The answer by plinth hints at using token pasting and the
__LINE__predefined macro to form a unique name possibly without needing an extra argument.Unfortunately, if the assertion check is in an included file, it can still collide with a check at the same line number in a second included file, or at that line number in the main source file. We could paper over that by using the macro
__FILE__, but it is defined to be a string constant and there is no preprocessor trick that can turn a string constant back into part of an identifier name; not to mention that legal file names can contain characters that are not legal parts of an identifier.So, I would propose the following code fragment:
A typical usage might be something like:
In GCC, an assertion failure would look like: