【发布时间】:2016-03-17 02:10:55
【问题描述】:
所以我正在尝试实现一个“通用打印宏”:
#include <stdio.h>
#include <float.h>
#define CHECK(x) printf(#x " =" \
_Generic((x), float: double: "%f",\
int: "%d",\
default: "Cannot print this with CHECK(x)")\
, x)
int main(void){
CHECK(FLT_RADIX);
return 0;
}
这给了我错误:
main.c:11:2: error: expected ')'
CHECK(FLT_RADIX);
^
main.c:5:3: note: expanded from macro 'CHECK'
_Generic((x), float: double: "%f",\
^
main.c:11:2: note: to match this '('
main.c:4:24: note: expanded from macro 'CHECK'
#define CHECK(x) printf(#x " =" \
^
1 error generated.
运行clang main.c -E后,输出为:
int main(void){
printf("FLT_RADIX" " =" _Generic((2), float: double: "%f", int: "%d", default: "Cannot print this with CHECK(x)") , 2);
return 0;
}
那么如何让_Generic()在翻译过程中展开呢?
顺便说一句:我不匹配哪个)?
【问题讨论】:
-
我认为您不能像这样将
float:和double:术语组合在一起 - 这是错误消息的来源。也许你应该在default:子句中使用静态断言,这样如果代码不起作用,代码就不会编译。 -
另一种可能的解决方案是
#define CHECK(X) (printf("%s", #x " ="), printf(_Generic(.......(保持原样,修复下面 Jonathan Leffler 指出的问题) -
@JonathanLeffler:实际上有两个错误。你提到的那个会在正文后面出现(见错误标记)。
-
几个很好的例子(太长了,不能在这里发布)可以在:
http://www.robertgamble.net/2012/01/c11-generic-selections.html -
"我正在尝试实现一个"通用打印宏":" --> 这可能会有所帮助 Formatted print without the need to specify type matching specifiers using _Generic
标签: c clang c-preprocessor