c++ - 强制编译器忽略程序中的某些行

标签 c++ preprocessor-directive

假设我有 10,000 行 C++ 代码。 200 行代码用于测试目的(例如,检查程序并显示错误消息)。

在 C++ 中有没有一种方法可以忽略或考虑某些代码行(可能带有 preprocessor 关键字)?

最佳答案

简答:

使用 ma​​cros#ifdef 检查。例如:

#ifdef MY_CONTROL_MACRO
...
#endif

只有在您已经定义了 MY_CONTROL_MACRO 宏时,才会编译此范围内的代码。


更多内容:

  1. 要定义这样的宏,你可以

    • #define MY_CONTROL_MACRO 添加到您的代码中。或者,
    • 对于 VS,将 MY_CONTROL_MACRO 添加到 Project > Properties > C/C++ > Preprocessor > Preprocessor Definitions。或者,
    • 对于 GCC,使用选项 -DMY_CONTROL_MACRO 编译您的代码。
  2. 您可以查看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.

  3. 你也可以使用高级的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/

相关文章:

clang++ - 将预处理器定义传递给 clang++

c++ - 我如何优化这个 S 曲线函数?

c++ - Qt删除指针方法

c++ - 使用 Python 而不是 XML 在 C++ 中加载资源?

c++ - 为什么即使我没有#include <algorithm> 仍然可以使用 std::max 和 std::min ?

c# - #if(DEBUG) 和 log4net 行号源/运行时不匹配

c++ - '*' token 模板化链表之前的预期构造函数、析构函数或类型转换

c++ - 自动更改 C++11 中的含义;请删除它这是什么意思?

c# - 如何使用#if 来决定在 C# 中为哪个平台编译

JSHint:不包括预处理器指令。不完全是