C语言 错误:粘贴“。” 并且“红色”没有给出有效的预处理标记
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13216423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
error: pasting "." and "red" does not give a valid preprocessing token
提问by Hyman
I'm implementing The X macro, but I have a problem with a simple macro expansion. This macro (see below) is used into several macros usage examples, by including in thisarticle.
The compiler gives an error message, but I can see valid C code by using -Eflag with the GCC compiler.
我正在实施 X 宏,但我在简单的宏扩展方面遇到了问题。这个宏(见下文)被用于几个宏使用示例,包括在this文章中。编译器给出了一条错误消息,但我可以通过-E在 GCC 编译器中使用标志来查看有效的 C 代码。
The macro X-list is defined as the following:
宏 X-list 定义如下:
#define LIST \
X(red, "red") \
X(blue, "blue") \
X(yellow, "yellow")
And then:
进而:
#define X(a, b) foo.##a = -1;
LIST;
#undef X
But the gcc given the following errors messages:
但是 gcc 给出了以下错误消息:
lixo.c:42:1: error: pasting "." and "red" does not give a valid preprocessing token
lixo.c:42:1: error: pasting "." and "blue" does not give a valid preprocessing token
lixo.c:42:1: error: pasting "." and "yellow" does not give a valid preprocessing token
Like I said, I can seen valid C code by using -Eswitch on gcc:
就像我说的,我可以通过-E在 gcc 上使用switch来查看有效的 C 代码:
lixo.c:42:1: error: pasting "." and "red" does not give a valid preprocessing token
lixo.c:42:1: error: pasting "." and "blue" does not give a valid preprocessing token
lixo.c:42:1: error: pasting "." and "yellow" does not give a valid preprocessing token
foo.red = -1; foo.blue = -1; foo.yellow = -1;;
What's a valid preprocessing token? Can someone explain this?
什么是有效的预处理令牌?有人可以解释一下吗?
(before you say "why not just an either initialize or memset()?" it's not my real code.)
(在你说“为什么不只是初始化或memset()?”之前,这不是我真正的代码。)
回答by Pubby
.separates tokens and so you can't use ##as .redis not a valid token. You would only use ##if you were concatenating two tokens into a single one.
.分隔令牌,因此您不能使用##as.red不是有效令牌。仅##当您将两个令牌连接成一个时才会使用。
This works:
这有效:
#define X(a, b) foo.a = -1;
What's a valid proprocessing token? Can someone explain this?
什么是有效的处理令牌?有人可以解释一下吗?
It is what gets parsed/lexed. foo.barwould be parsed as 3 tokens (two identifiers and an operator): foo . barIf you use ##you would get only 2 tokens (one identifier and one invalid token): foo .bar
这就是解析/词法分析的内容。foo.bar将被解析为 3 个令牌(两个标识符和一个运算符):foo . bar如果您使用,##您将只得到 2 个令牌(一个标识符和一个无效令牌):foo .bar

