What are "extern char condition tricks"?
I was reading the GCC documentation on C and C++ function attributes. In the description of the error
and warning
attributes, the documentation casually mentions the following "trick":
error ("message")
warning ("message")
If the
error
orwarning
attribute is used on a function declaration and a call to such a function is not eliminated through dead code elimination or other optimizations, an error or warning (respectively) that includes message is diagnosed. This is useful for compile-time checking, especially together with__builtin_constant_p
and inline functions where checking the inline function arguments is not possible throughextern char [(condition) ? 1 : -1];
tricks.While it is possible to leave the function undefined and thus invoke a link failure (to define the function with a message in
.gnu.warning*
section), when using these attributes the problem is diagnosed earlier and with exact location of the call even in presence of inline functions or when not emitting debugging information.
There's no further explanation. Perhaps it's obvious to programmers immersed in the environment, but it's not at all obvious to me, and I could not find any explanation online. What is this technique and when might I use it?
I believe the premise is to have a compile time assert functionality. Suppose that you wrote
extern char a[(condition) ? 1 : -1];
If condition
is true
, nothing happens and the line compiles to nothing. The extern
makes sure that a
doesn't use any memory. However, if condition
is false
, a
is declared as an array of negative length, and you get a compile time error.
You probably wrap it in a macro and have something similar to static_assert
#define STATIC_ASSERT(condition) extern char a[(condition) ? 1 : -1]