一起来认识Linux中的 BUILD_BUG_ON 宏

简介: 一起来认识Linux中的 BUILD_BUG_ON 宏

该宏在Linux内核中实现的,可以在编译的时候检查传入参数的合法性,而assert是在运行到断言的时候才会知道参数的合法性。

原型
include/linux/kernel.h
/ Force a compilation error if condition is true /

define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))

/ Force a compilation error if condition is true, but also produce a
result (of value 0 and type size_t), so the expression can be used
e.g. in a structure initializer (or where-ever else comma expressions
aren't permitted).
/

define BUILD_BUG_ON_ZERO(e) (sizeof(char[1 - 2 * !!(e)]) - 1)

表达式sizeof(char[1 - 2!!(condition)])的作用,首先对条件表达式进行两次取反,这可以保证执行 1 - 2!!(condition) 的结果只有两种值:条件为0时结果为1或者不为0则结果为-1,显然char[-1]将会导致编译器报错。注意:两次取反的目的是为了将表达式的值转换为逻辑值。
BUILD_BUG_ON:只有条件condition为0时可编译,但不返回值,否则编译器报错。
BUILD_BUG_ON_ZERO:只有条件e为0时返回0,否则编译器报错。

当我们调试完代码后,建议关闭这个宏,可以使用另一个宏定义来使能/关闭BUILD_BUG_ON 宏。

相关文章
|
2月前
|
Shell Linux 开发工具
在Linux中,当你需要给命令绑定⼀个宏或者按键的时候,应该怎么做呢?
在Linux中,当你需要给命令绑定⼀个宏或者按键的时候,应该怎么做呢?
|
3月前
|
Linux
Linux EXPORT_SYMBOL宏详解
Linux EXPORT_SYMBOL宏详解
31 4
|
4月前
|
Linux 编译器 C语言
Linux 中 EXPORT_SYMBOL宏详解
Linux 中 EXPORT_SYMBOL宏详解
|
5月前
|
Linux 编译器 C语言
|
Linux
Linux container_of宏详细剖析
Linux container_of宏详细剖析
115 0
Linux container_of宏详细剖析
|
存储 Linux C语言
Linux 内核常见的宏(1):offsetof 和 container_of分析
Linux 内核常见的宏(1):offsetof 和 container_of分析
193 0
Linux 内核常见的宏(1):offsetof 和 container_of分析
|
Linux C语言
介绍几种LINUX编程中非常实用的调试程序宏变量
介绍几种LINUX编程中非常实用的调试程序宏变量
|
Linux 容器
Linux内核中的常用宏container_of
/* linux-2.6.38.8/include/linux/compiler-gcc4.h */ #define __compiler_offsetof(a,b) __builtin_offsetof(a,b) /* linux-2.
929 0