两次定义C预处理程序宏会发生什么? [英] What happens when a C preprocessor macro is defined twice?
问题描述
我两次定义一个宏,如下所示:
I define a macro twice as follows:
#define a 2
#define a 3
我认为代码中 a
的任何出现都是替换为 2
,当遇到 #define 3
时,不再有 a
s在代码中可用,以替换为 3
,因此 2
具有优先权
I thought any occurrence of a
in the code would be replaced by 2
, and when #define a 3
is encountered there are no more a
s are available in the code to be replaced by 3
, so the 2
would take precedence.
但是当我执行它时, a
被3代替了,为什么?
But when I executed it a
was replaced by 3, why?
推荐答案
如果您两次定义宏,则编译器至少应发出警告,即使不是错误。
If you define a macro twice like that, the compiler should at least give you warning, if not an error. It is an error.
§6.10.3/ 2:当前定义为类对象宏的标识符不应由另一个<$ c $重新定义。 c> #define 预处理指令,除非第二个定义是类似对象的宏定义并且两个替换列表相同。
§6.10.3/2 : An identifier currently defined as an object-like macro shall not be redefined by another
#define
preprocessing directive unless the second definition is an object-like macro definition and the two replacement lists are identical.
您可以通过显式删除先前的定义来重新定义宏:
You can redefine a macro by explicitly removing the previous definition:
#define a 2
/* In this part of the code, a will be replaced with 2 */
...
#undef a
#define a 3
/* From here on, a will be replaced with 3 */
...
读取文件时会使用宏定义激活宏替换指向文件中的 except (在大多数预处理指令中)。
Macro replacement happens as the file is read, using the macro definitions active at that point in the file, except inside (most) preprocessing directives.
§6.10/ 7:预处理指令中的预处理令牌除非另有说明,否则不进行宏扩展。
§6.10/7: The preprocessing tokens within a preprocessing directive are not subject to macro expansion unless otherwise stated.
§6.10.3.5/ 1:宏定义n持续(独立于块结构)直到遇到相应的 #undef
指令,或者(如果没有遇到)直到预处理转换单元的末尾。
§6.10.3.5/1: A macro definition lasts (independent of block structure) until a corresponding #undef
directive is encountered or (if none is encountered) until the end of the preprocessing translation unit.
这篇关于两次定义C预处理程序宏会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!