[英]How to concat macros in C
I have a macro that displays the month from __DATE__
as a numeric value string literal: 我有一个宏,它以数字字符串文字形式显示
__DATE__
的月份:
#define MONTH (\
__DATE__[2] == 'n' ? (__DATE__[1] == 'a' ? "01" : "06") \
: __DATE__[2] == 'b' ? "02" \
: __DATE__[2] == 'r' ? (__DATE__[0] == 'M' ? "03" : "04") \
: __DATE__[2] == 'y' ? "05" \
: __DATE__[2] == 'l' ? "07" \
: __DATE__[2] == 'g' ? "08" \
: __DATE__[2] == 'p' ? "09" \
: __DATE__[2] == 't' ? "10" \
: __DATE__[2] == 'v' ? "11" \
: "12")
This works fine and produces the month I'm looking for. 这可以正常工作并产生我要寻找的月份。
printf("%s", MONTH);
. 。 However, I'm trying to add this to a larger group of macros and am having trouble:
但是,我试图将其添加到更大的一组宏中,并且遇到了麻烦:
#define MYMONTH "M" MONTH
should produce the string: M11
right now. 现在应该产生字符串:
M11
。 But instead, it produces the following compiler error: 但相反,它会产生以下编译器错误:
error: called object is not a function or function pointer
#define MYMONTH "M" MONTH
I know you can combine string literals with a macro by appending them: 我知道您可以通过附加字符串文字和宏来组合它们:
#define COMMA ","
#define EXCLA "!"
#define MYSTR "Hello" COMMA " world" EXCLA
But why won't it work when there is logic involved? 但是,当涉及逻辑时,为什么它不起作用?
Macros are just a string copy done in preprocessing. 宏只是在预处理中完成的字符串复制。
If we copy your MONTH
macro into MYMONTH
we get: 如果我们将您的
MONTH
宏复制到MYMONTH
得到:
#define MYMONTH "M" (\
__DATE__[2] == 'n' ? (__DATE__[1] == 'a' ? "01" : "06") \
: __DATE__[2] == 'b' ? "02" \
: __DATE__[2] == 'r' ? (__DATE__[0] == 'M' ? "03" : "04") \
: __DATE__[2] == 'y' ? "05" \
: __DATE__[2] == 'l' ? "07" \
: __DATE__[2] == 'g' ? "08" \
: __DATE__[2] == 'p' ? "09" \
: __DATE__[2] == 't' ? "10" \
: __DATE__[2] == 'v' ? "11" \
: "12")
Which to the compiler looks like you are trying "M"(<some string here>)
对编译器来说,您正在尝试使用
"M"(<some string here>)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.