宏观替代

时间:2011-03-26 09:02:28

标签: objective-c c

# include <stdio.h>
# define ONE 1
# define TWO 2
# define ONE TWO
# define TWO ONE
int main ( void )
{
  printf("ONE = %d, TWO = %d\n", ONE, TWO );
  return 0;
}

当我们这样写的时候会发生什么?在第4行#define ONE TWO,预处理器是否会立即将其替换为1 2

3 个答案:

答案 0 :(得分:1)

如果您使用的是xcode 3,则可以右键单击该文件并选择PreProcess

您将在末尾附近获得一个包含此代码的大文件

int main ( void )
{
 printf("ONE = %d, TWO = %d\n", ONE, TWO );
 return 0;
}

编辑:我认为在这种情况下它没用。出于某种原因,预处理没有错误和警告,但代码不会改变。但是如果你编写有用的代码,你可以查看预处理的代码。


如果你尝试编译它,你会得到一堆警告和错误。

test.c:4:1: warning: "ONE" redefined
test.c:2:1: warning: this is the location of the previous definition
test.c:5:1: warning: "TWO" redefined
test.c:3:1: warning: this is the location of the previous definition
test.c: In function ‘main’:
test.c:8: error: ‘ONE’ undeclared (first use in this function)
test.c:8: error: (Each undeclared identifier is reported only once
test.c:8: error: for each function it appears in.)
test.c:8: error: ‘TWO’ undeclared (first use in this function)

答案 1 :(得分:0)

将调用哪个宏的冲突.....由于ONE为1而ONE为TWO ....这就是链接错误。

答案 2 :(得分:0)

  

在第4行#define ONE TWO,预处理器是否会立即将其替换为1 2

没有。在这种情况下,define指令的相关形式是:

  

#define标识符替换列表换行

......并且identifier没有发生替换。此外,以下适用:

  

当前定义为类似对象宏的标识符不应由另一个#define预处理指令重新定义,除非第二个定义是类似于对象的宏定义且两个替换列表相同。

...这使您的重新定义非法。

如果您需要重新定义宏,则必须先使用#undef取消定义。

相关问题