宏的定义:
#define BUILD_BUG_ON_INVALID(e) ((void)(sizeof((__force long)(e))))
我测试宏如下:
#include <stdio.h>
#define BUILD_BUG_ON_INVALID(e) ((void)(sizeof(( long)(e))))
#define true 1
int main() {
BUILD_BUG_ON_INVALID(true);
return 0;
}
我用以下命令编译它:
gcc -Wall -Wextra -c test.c
但没有警告(true=0 和 true=1)
gcc的版本是11.4.0
来自内核头(
include/linux/build_bug.h
):
/*
* BUILD_BUG_ON_INVALID() permits the compiler to check the validity of the
* expression but avoids the generation of any code, even if that expression
* has side-effects.
*/
#define BUILD_BUG_ON_INVALID(e) ((void)(sizeof((__force long)(e))))
此宏并不意味着在运行时检查任何内容。该宏的唯一目的是检查传递给它的表达式的有效性,而不实际添加任何代码。
通常这样使用(摘自
drivers/gpu/drm/i915/i915_memcpy.c
):
#if IS_ENABLED(CONFIG_DRM_I915_DEBUG)
#define CI_BUG_ON(expr) BUG_ON(expr)
#else
#define CI_BUG_ON(expr) BUILD_BUG_ON_INVALID(expr)
#endif
如果配置被禁用,我们仍然希望编译器检查
expr
是否有效,这样在启用配置时就不会导致编译错误。