macros defined in linux kernel.h file

On stack overflow I ran into a question What is ":-!!" in C code?

> #define BUILD_BUG_ON_ZERO(e) (sizeof(struct { int:-!!(e); }))
> #define BUILD_BUG_ON_NULL(e) ((void *)sizeof(struct { int:-!!(e); }))

out of curiosity I want to know how can I use these kind of macros ?

int main()
{
    BUILD_BUG_ON_ZERO(0);
    return 0;
}

In the above code it gives an error that type name is not allowed.

EDIT : the code compiles on linux using gcc but fails on visual studio


Read the best answer carefully:

The macro is somewhat misnamed; it should be something more like BUILD_BUG_OR_ZERO , rather than ...ON_ZERO

So it fails to compile when the parameter is nonzero:

int main()
{
    BUILD_BUG_ON_ZERO(1);
    return 0;
}

http://ideone.com/TI97r3


As for a practical usage:

int main()
{
    BUILD_BUG_ON_ZERO(sizeof(int) != 4); // we need int to be 4 bytes, stop compilation otherwise
    return 0;
}

As for C++: this is a C construct that does not compile in C++ at all.

In C++11 you can use a static_assert instead.

链接地址: http://www.djcxy.com/p/73570.html

上一篇: 在C中静态声明

下一篇: 在linux kernel.h文件中定义的宏