在类似函数的宏中添加预处理器指令是否是错误的? [英] Is it wrong to add preprocessor directives in a function-like macro?
问题描述
我知道我的问题类似于这一个或这一个,但我发现它不是真的相同,更多,第二个没有答案接受,我决定询问是否添加预处理器指令,当一个函数的宏被调用时是正确的
I know that my question is similar to this one or this one, but I find that it is not really the same and, more, the second one has not an answer accepted, I decided to ask if it is correct to add preprocessor directives when a function-like macro is called?
在我的例子中,我有一个类似函数的宏:
In my case I have a function-like macro:
#define FUNC_MACRO(a, b) // do something with the variables
来执行某些操作其他宏定义:
and somewhere in the code I call it with specific difference if some other macro is defined:
// ...
FUNC_MACRO(aVal
#ifdef ANOTHER_MACRO
+ offset
#endif // ANOTHER_MACRO
, bVal);
// ...
我在我的机器上测试了(linux,用gcc 4.8)并且它工作确定(有和没有预处理器指令,并且有和没有ANOTHER_MACRO定义),但是这是安全吗?
I tested on my machine (linux, with gcc 4.8) and it worked ok (with and without the preprocessor directives, and with and without ANOTHER_MACRO defined), but is it safe to do so?
我读了16.3 / 9段
I read the 16.3/9 paragraph from the answer of the first similar question, but is it true for my case too?
推荐答案
C语言将此定义为undefined在中的行为6.10.3宏替换,¶11
The C language leaves this as undefined behavior in 6.10.3 Macro replacement, ¶11:
如果列表中有预处理令牌
If there are sequences of preprocessing tokens within the list of arguments that would otherwise act as preprocessing directives, the behavior is undefined.
因此,这是错误的。
GCC和其他流行的编译没有抓住它,这可能是为什么许多用户的语言不知道。我遇到这个,当我的一些代码在PCC上编译失败(并及时修复了我的代码中的错误)。
GCC and perhaps other popular compiles don't catch it, which is probably why many users of the language are not aware. I encountered this when some of my code failed to compile on PCC (and promptly fixed the bug in my code).
更新:PJTraill在评论中询问一个案件在宏扩展中包含预处理器指令是误导或无意义的。这是一个明显的:
Update: PJTraill asked in the comments for a case where it would be "misleading or meaningless" to have preprocessor directives inside a macro expansion. Here's an obvious one:
foo(a, b,
#ifdef BAR
c);
#else
d);
#endif
我不确定它是否会对语言指定在宏扩展内的平衡预处理条件是可以的,但我认为你也会遇到问题,它们应该被处理的顺序含糊。
I'm not sure whether it would have been plausible for the language to specify that balanced preprocessor conditionals inside the macro expansion are okay, but I think you'd run into problems there too with ambiguities in the order in which they should be processed.
这篇关于在类似函数的宏中添加预处理器指令是否是错误的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!