Linux Kernel: BUILD_BUG_ON_ZERO() / BUILD_BUG_ON_NULL()
之前在 trace Linux Kernel source codes 時發現了兩個很特別的 macros:BUILD_BUG_ON_ZERO() 和 BUILD_BUG_ON_NULL() (定義在:include/linux/kernel.h) 它們的定義如下: 1 2 3 4 5 6 /* 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(struct { int:-!!(e); })) #define BUILD_BUG_ON_NULL(e) ((void *)sizeof(struct { int:-!!(e); })) 其中 e 是我們所傳入的判斷式,若判斷式為 true,則會造成 compile error。如此我們便可透過這個 macro 來判斷是否某些錯誤/不應發生的情況 (判斷式) 是否會發生,若會發生則可在 compile-time 的時候就顯示錯誤訊息。 ...