"extern char condition tricks" 是什么?

What are "extern char condition tricks"?

我正在阅读 the GCC documentation on C and C++ function attributes。在 errorwarning 属性的描述中,文档随便提到了以下“技巧”:

error ("message")
warning ("message")

If the error or warning 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 through extern 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.

没有进一步的解释。也许对于沉浸在环境中的程序员来说很明显,但对我来说却一点都不明显,我在网上找不到任何解释。这是什么技术,我什么时候可以使用它?

相信前提是要有编译时断言功能。假设你写了

extern char a[(condition) ? 1 : -1];

如果 conditiontrue,什么也不会发生,该行编译为空。 extern 确保 a 不使用任何内存。然而,如果 conditionfalsea 被声明为一个负长度的数组,你会得到一个编译时错误。

您可能将其包装在一个宏中并具有类似于 static_assert

的内容
#define STATIC_ASSERT(condition) extern char a[(condition) ? 1 : -1]