在 #define 宏中转义 # 符号?
在不深入细节的情况下,我想使用一个 #define
宏来扩展为 #include
但“#”符号使预处理器感到困惑(因为它认为我想要引用一个论点。)
例如,我想做这样的事情:
#define MACRO(name) #include "name##foo"
并这样使用它:
MACRO(Test)
这将扩展为:
#include "Testfoo"
不起眼的 # 符号导致预处理器呕吐。 MinGW 给了我以下错误:
'#'后面没有宏参数
我想我需要转义 # 符号,但如果这是可能的,我不会这样做。
是的,宏确实是邪恶的......
Without going into the gory details I want to use a #define
macro that will expand to a #include
but the '#' sign is confusing the preprocessor (as it thinks I want to quote an argument.)
For example, I want to do something like this:
#define MACRO(name) #include "name##foo"
And use it thus:
MACRO(Test)
Which will expand to:
#include "Testfoo"
The humble # sign is causing the preprocessor to barf. MinGW gives me the following error:
'#' is not followed by a macro parameter
I guess I need to escape the # sign but I don't if this is even possible.
Yes, macros are indeed evil...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
可以将哈希令牌插入到预处理的令牌流中。 您可以按如下方式执行此操作:
- 扩展为:
但是,标准明确排除了对此类行是否存在预处理指令 [cpp.rescan] 的任何进一步分析:
It is possible to insert a hash token into the preprocessed token stream. You can do it as follows:
—expands to:
However, the standard explicitly rules out any further analysis of such line for the existence of preprocessing directives [cpp.rescan]:
问题实际上并不在于预处理器的输出中出现 # 符号。
显然,您希望预处理器重新解析您的文件,以处理新创建的 #include 指令作为宏扩展的一部分。 事实并非如此。 如果一行以 # 开头,则它是预处理器的指令并被解释。 如果一行不以 # 开头,则它仅受预处理器转换(包括宏替换)的影响。 这是每行一次的测试。
不以#开头。 因此它不被解释为预处理器指令; 相反,它受宏替换规则的约束。
The problem isn't actually getting a # symbol in the output of your preprocessor.
Apparently you want the preprocessor to reparse your file, to deal with newly created #include directives as part of macro expansion. It doesn't work that way. If a line starts with #, it's an instruction for the preprocessor and interpreted. If a line doesn't start with #, it's only subject to preprocessor transformation including macro substitution. This is a once-per-line test.
does not start with #. Therefore it is not interpreted as a preprocessor directive; instead it's subject to macro replacement rules.
据我记得你不能在定义中使用另一个预处理器指令。
As far as I remember you cannot use another preprocessor directive in define.
这是因为# 在宏中使用时具有特殊含义。
在您的情况下,# 后面没有正确的标记。
因此,在您的情况下,我们需要进行一定程度的间接处理:
This is because the # has special meaning when used in a macro.
In your situation the # is not followed by a proper token.
So in your situation we need to go through a level of indirection:
你不能那样做。 预处理器指令在宏扩展之前被识别; 如果宏扩展为看起来像预处理器指令的内容,则该指令将不会被识别。 您能做的最好的事情就是为文件名创建一个宏:
You can't do that. Preprocessor directives are recognized before macro expansion; if the macro expands into something that looks like a preprocessor directive, that directive will not be recognized. The best you can do is create a macro for the file name:
这可能有效(它适用于不带参数的常规
#define
宏,但我还没有使用带参数的宏对其进行测试)。This might work (it works for regular
#define
macros with no parameters, but I haven't tested it with macros with parameters).