Re: [PATCH] debug: fix BUILD_BUG_ON() for non-constant expressions

From: Linus Torvalds
Date: Sun Aug 17 2008 - 12:57:18 EST




On Sun, 17 Aug 2008, Ingo Molnar wrote:
> +/*
> + * Force a compilation error if condition is true [array index becomes
> + * negative], and a linker error if condition is not constant [non-defined
> + * variable is used as an array index]:
> + *
> + * ( The linker trick relies on gcc optimizing out a multiplication with
> + * constant zero - which should be reasonable enough. )
> + */
> +extern unsigned int __BUILD_BUG_ON_non_constant;
> +
> +#define BUILD_BUG_ON(condition) \
> +do { \
> + (void)sizeof(char[1 - 2*!!(condition)]); \
> + if (!__builtin_constant_p(condition)) \
> + __BUILD_BUG_ON_non_constant++; \
> +} while (0)

Gag me now.

Why not just do

#define __BBO(c) sizeof(const char[1 - 2*!!(c)])
#define __BBONC(c) __BBO(!__builtin_constant_p(c))
#define BUILD_BUG_ON_ZERO(c) (__BBO(c) - __BBONC(c))
#define BUILD_BUG_ON(c) (void)BUILD_BUG_ON_ZERO(c)

and be done with it?

The rules are trivial:

- __BBO() causes a warning if 'c' is a constant non-zero, returns a
(size_t) 1 otherwise

- __BBONC() causes a warning if 'c' is not a constant, returns a
(size_t) 1 otherwise

And then BUILD_BUG_ON[_ZERO] are totally _trivial_ on top of those.

Yeah, yeah, I didn't test this, but it looks a hell of a lot simpler, and
gives the warning about non-constant issues at compile time with line
numbers rather than at link-time.

Linus
--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/