当我定义具有相同名称的宏时会发生什么

What happens when I define macros with the same name

当我在一个源文件中有多个同名的 #define 时会发生什么:

例如:

#define Dummy 1
#define Dummy 2

我不打算使用它,但在生产代码中看到了类似的东西。这是否包含在标准中?

这个:

#define Dummy 1
#define Dummy 2

等同于:

#define Dummy 2

但是你可能会收到(我不确定标准是怎么说的)第二个 #define

之类的警告,例如 'Dummy': macro redefinition

换句话说:最后的 #define 获胜。

如果你想把事情做好,你应该使用#undef:

#define Dummy 1
#undef Dummy
#define Dummy 2    // no warning this time

顺便说一句:在某些情况下,更改宏的定义是完全可以的。

它违反了约束,因此需要符合标准的编译器才能发出诊断。

C11, 6.10.3 Macro replacement 状态:

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. [..]

如前所述,如果替换相同,则不会违反约束。所以

#define X 1
#define X 2

需要诊断;而

#define X 1
#define X 1

没问题。类似的约束适用于 function-like 宏 (C11, 6.10.3, 2)。

C 标准中的示例#6.10.3.5p8

EXAMPLE 6 To demonstrate the redefinition rules, the following sequence is valid.

      #define      OBJ_LIKE      (1-1)
      #define      OBJ_LIKE      /* white space */ (1-1) /* other */
      #define      FUNC_LIKE(a)   ( a )
      #define      FUNC_LIKE( a )( /* note the white space */ \
                                   a /* other stuff on this line
                                       */ ) 

But the following redefinitions are invalid:

      #define      OBJ_LIKE    (0)     // different token sequence
      #define      OBJ_LIKE    (1 - 1) // different white space
      #define      FUNC_LIKE(b) ( a ) // different parameter usage
      #define      FUNC_LIKE(b) ( b ) // different parameter spelling

[强调我的]

因此,这

#define Dummy 1
#define Dummy 2

无效。