一段c语言宏的代码

ArcJson 发布于 2012/04/14 13:47
阅读 372
收藏 0
Hey, since the last disgusting code hack thing worked out so well on G+, here's a new challenge..

Improve on this new disgusting hack:

#define is_enabled(x) (__stringify(CONFIG_##x)[0]=='1')

which basically is a C language "is the config variable 'x' defined" question (the "__stringify()" thing is the normal two-level macro expansion using the '#' operator, so that it expands the macro argument and then turns it into a string). And gcc does seem to do the proper compile-time optimizations that turn the above into a simple constant.

The intent is to be able to write

if (is_enabled(PROC)) {
...

in C code, without having to make ugly  #ifdef sections with all the odd line breaks etc that entails. The kernel config rules are that the CONFIG_XYZ macro exists and has the value '1' for enabled features (you can ignore the module case for now - that's just the same thing, except the preprocessor name is CONFIG_XYZ_MODULE)

Is there a better trick for this? Bonus points if somebody comes up with a single macro that works for both C code  and in pre-processor expressions.

--

Edit: so for people who can't be bothered with reading all the comments, +comex . found a solution that works. There's a few tweaking variations of in it there, but  +comex . original approach works fine:

#define is_set(macro) is_set_(macro)
#define macrotest_1 ,
#define is_set_(value) is_set__(macrotest_##value)
#define is_set_ (comma) is_set__(comma 1, 0)
#define is_set___(_, v, ...) v

Thanks.
这是linus 在G+上的一段话。
文章的意思我大概看懂了,可是宏就看的不是很懂,自己试了一下,也没编译没通过,求解释。
加载中
0
中山野鬼
中山野鬼
哪段看不懂?上面貌似不全。
返回顶部
顶部