简体   繁体   English

C上的预处理器

[英]Preprocessor on C

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? 我的问题是,如果我不在DEBUG_MODE ,编译器在编译时会做什么?

编译器将不执行任何操作,因为未定义DEBUG_MODE时将不执行任何操作。

#ifdef and #endif control conditional compilation. #ifdef#endif控制条件编译。 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. 这发生在程序的初次传递过程中,在编译器甚至开始考虑文件专门包含C代码之前进行了愚蠢的文本替换。 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. 如果当时未定义要测试的预处理器定义,则文本甚至不会被分类为C标记。

You can see this for yourself: just invoke your compiler with whatever flag it uses to stop after preprocessing - eg gcc -E x.cc - and at that point in the output there will just be an empty line or two. 您可以亲眼看到这一点:只需使用编译器在预处理后用于停止的任何标志(例如gcc -E x.cc来调用编译器,然后在输出中只有一两行是空的。 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则不会编译其下的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM