我对这个 C 预处理器语句的含义有点迷失,
因此,首先,这是代码,将实际名称切换为通用名称以减少混淆。
/* Get the list of Hotkey commands */
#define A_COMMANDS_MACRO(a, b, c, d) a = b ,
enum {
#include "commandsFile.def"
} ;
#undef A_COMMANDS_MACRO
这是我一直在查看的一些源代码的片段,并考虑使用 fork 作为熟悉 C 编程语言的复杂性的一种方式。因此,在我未经训练的眼睛看来,这似乎没有任何作用。在我看来,定义某件事然后立即取消定义似乎会相互抵消。
显然,我意识到我错了。但为什么我错了呢?
So, to start off, here's the code, with actual names switched for generic ones to limit confusion.
/* Get the list of Hotkey commands */
#define A_COMMANDS_MACRO(a, b, c, d) a = b ,
enum {
#include "commandsFile.def"
} ;
#undef A_COMMANDS_MACRO
This is a snippet from some source code I have been looking over and considering forking as a way to familiarize myself with the intricacies of the C programming language. So, to my untrained eye, this appears to do nothing. To my brain, defining something and then immediately undefining it would seem to cancel each other out.
Obviously, I realize that I'm wrong. But why am I wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
“commandsFile.def”文件可能在内部某处使用“A_COMMANDS_MACRO”宏。
请记住,“#include”本质上是将包含的文件粘贴到包含文件中,因此在处理“commandsFile.def”时,#define 仍然有效。
The "commandsFile.def" file probably uses the "A_COMMANDS_MACRO" macro somewhere internally.
Remember that "#include" essentially pastes the included file into the including one, so the #define is still in effect when "commandsFile.def" is processed.
你在那里看到的通常被称为X-MACRO。该技术包括通过
#define
定义宏,然后通过#include
包含使用它们的文件。作为一个非常简单的示例,您可以有一个标头(例如 myheader.h),以以下形式声明 2 个函数:
然后,在您的代码中:
#undef
s 有时也在包含的文件中。有关更多信息,请查看此维基百科链接。
What you see there is usually called X-MACRO. The technique consists in defining macros via
#define
, and then including a file that makes use of them with#include
.As a very simple example, you could have a header (say myheader.h) that declared 2 functions in the form of:
And then, in your code:
The
#undef
s are sometimes in the included file as well.For more information, take a look at this Wikipedia link.
commandsFile.def
应包含许多行:以便代码创建一个包含可用命令及其代码的枚举。
当这个 .def 文件被用其他语言编写的程序使用时,它可能很有用,这样它就不会实现文本解析,而是使用 C 预处理器来执行此操作。
The
commandsFile.def
should contain many lines:So that the code would create an enum with available commands and their codes.
It could be useful when this .def file is used by a program written in other language, so that instead of implementing text parsing, it uses C preprocessor to do this.