我正在阅读 Alfred V. Aho 的书“编译器:原理、技术和工具(第 2 版)”。本书中有一个例子(例1.7)要求分析C宏定义中x
的作用域:
#define a (x+1)
从这个例子,
We cannot resolve x statically, that is, in terms of the program text.
In fact, in order to interpret x, we must use the usual dynamic-scope rule. We examine all the function calls that are currently active, and we take the most recently called function that has a declaration of x. It is to this declaration that the use of x refers.
读到这里我变得很困惑——据我所知,宏替换发生在编译开始之前的预处理阶段。但是如果我做对了,这本书说它会在程序执行时发生。谁能澄清一下?
最佳答案
宏本身没有作用域的概念,至少与 C 语言的概念不同。无论符号 a
出现在源代码中 #define
之后(以及可能的 #undef
之前),它都被替换为 (x + 1)
。
但是文中讲了x
的作用域,宏替换中的符号。这是由通常的 C 规则解释的。如果在 a
被替换的范围内没有符号 x
,这是一个编译错误。
宏不是独立的。它使用宏外部的符号,如果您愿意的话,可以是某种全局变量,但其含义会根据调用宏的源文本中的位置而改变。我认为引用的文字想说的是,除非我们知道宏 a
是在哪里被调用的,否则我们无法知道它的作用。
关于c - 什么时候在 C 中发生宏替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23752109/