C 上的预处理器
我在代码中添加了这个:
#ifdef DEBUG_MODE
printf("i=%d\n",i);
fflush(stdout);
#endif
我的问题是,如果我不在 DEBUG_MODE
中,编译器在编译它时会做什么?
I added this in my code:
#ifdef DEBUG_MODE
printf("i=%d\n",i);
fflush(stdout);
#endif
and my question is, if I'm not in DEBUG_MODE
what the compiler does when compiling this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编译器不会执行任何操作,因为当未定义 DEBUG_MODE 时,编译器将不会执行任何操作。
The compiler will do nothing, because there will be nothing there when DEBUG_MODE is not defined.
#ifdef
和#endif
控制条件编译。这种情况发生在程序的初始传递期间,在编译器甚至开始考虑文件专门包含 C 代码之前就进行了愚蠢的文本替换。在这种情况下,如果没有定义符号,则仅留下空白。如果当时未定义测试的预处理器定义,则文本永远不会被词法分析为 C 标记。您可以亲自看到这一点:只需使用编译器在预处理后用于停止的任何标志来调用编译器 - 例如
gcc -E x.cc
- 此时输出中将只有一个空行或两个。这也是理解宏的一个非常重要的技术,当你无法猜测为什么某些程序没有按你期望的方式工作时,这是一件好事 - 编译器说某些类或函数不存在,而你已经包含了它的标头 - 查看预处理的输出以了解编译器真正处理的内容。#ifdef
and#endif
control conditional compilation. This happens during an initial pass over the program, making dumb textual substitutions before the compiler even begins to consider the file to contain C code specifically. In this case, without the symbol defined only whitespace is left. The text is never even lexed into C tokens if the preprocessor define tested for isn't defined at that point.You can see this for yourself: just invoke your compiler with whatever flag it uses to stop after preprocessing - e.g.
gcc -E x.cc
- and at that point in the output there will just be an empty line or two. This is also a very important technique for understanding macros, and a good thing to do when you just can't guess why some program's not working the way you expect - the compiler says some class or function doesn't exist and you've included its header - look at the preprocessed output to know what your compiler is really dealing with.如果
DEBUG_MODE
没有定义,则其下的代码将不会被编译。if
DEBUG_MODE
is not defined, the code under it will not be compiled.