假设我有 10,000 行 C++ 代码。 200 行代码用于测试目的(例如,检查程序并显示错误消息)。
在 C++ 中有没有一种方法可以忽略或考虑某些代码行(可能带有 preprocessor 关键字)?
最佳答案
简答:
使用 macros 和 #ifdef
检查。例如:
#ifdef MY_CONTROL_MACRO
...
#endif
只有在您已经定义了 MY_CONTROL_MACRO
宏时,才会编译此范围内的代码。
更多内容:
要定义这样的宏,你可以
- 将
#define MY_CONTROL_MACRO
添加到您的代码中。或者, - 对于 VS,将
MY_CONTROL_MACRO
添加到Project > Properties > C/C++ > Preprocessor > Preprocessor Definitions
。或者, - 对于 GCC,使用选项
-DMY_CONTROL_MACRO
编译您的代码。
- 将
您可以查看here了解更多信息。
This block is called a conditional group. controlled text will be included in the output of the preprocessor if and only if MACRO is defined. We say that the conditional succeeds if MACRO is defined, fails if it is not.
The controlled text inside of a conditional can include preprocessing directives. They are executed only if the conditional succeeds. You can nest conditional groups inside other conditional groups, but they must be completely nested. In other words, ‘#endif’ always matches the nearest ‘#ifdef’ (or ‘#ifndef’, or ‘#if’). Also, you cannot start a conditional group in one file and end it in another.
你也可以使用高级的
ifdef-else-endif
风格:#ifdef MY_CONTROL_MACRO ... // this part will be valid if MY_CONTROL_MACRO is defined #else ... // this part will be valid if MY_CONTROL_MACRO is NOT defined #endif
关于c++ - 强制编译器忽略程序中的某些行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21256252/