强制编译器忽略程序中的一些行 [英] Force the compiler to ignore some lines in the program

查看:136
本文介绍了强制编译器忽略程序中的一些行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



在C ++中有一种方法可以忽略或考虑某些行(也许使用预处理器关键字)?

解决方案

简答:



使用 $ c> #ifdef 检查。例如:

  #ifdef MY_CONTROL_MACRO 
...
#endif

此范围内的代码只有在您已经定义 MY_CONTROL_MACRO






更多资料:




  1. 要定义此类宏,您可以




    • 添加 #define MY_CONTROL_MACRO 到您的代码。或

    • 对于VS,将 MY_CONTROL_MACRO 添加到 Project&属性> C / C ++>预处理器>预处理器定义。或者,

    • 对于GCC,使用选项 -DMY_CONTROL_MACRO 编译代码。


  2. 您可以查看此处了解更多信息。


    此块称为条件组。当且仅当MACRO被定义时,控制文本将被包括在预处理器的输出中。我们说如果MACRO被定义,条件成功,如果不定义,则失败。



    条件中的受控文本可以包括预处理指令。它们只有在条件成功时才执行。您可以将条件组嵌套在其他条件组中,但它们必须完全嵌套。换句话说,'#endif'总是匹配最近的'#ifdef'(或'#ifndef'或'#if')。



  3. 您也可以使用高级<
    ... //如果定义了MY_CONTROL_MACRO,此部分将有效
    #else
    ... //如果MY_CONTROL_MACRO未定义,则此部分将有效
    #endif



Suppose that I have 10,000 lines of C++ code. 200 lines of this code are for testing purpose (for example, check the program and show an error message).

Is there an way in C++ to ignore or consider some lines of the code (maybe with preprocessor keywords)?

解决方案

Short answer:

Use macros and #ifdef checking. For example:

#ifdef MY_CONTROL_MACRO
...
#endif

the code within this scope will only be compiled if you already defined the MY_CONTROL_MACRO macro.


More stuff:

  1. To define such a macro, you can

    • Add #define MY_CONTROL_MACRO to your code. Or,
    • For VS, add MY_CONTROL_MACRO to Project > Properties > C/C++ > Preprocessor > Preprocessor Definitions. Or,
    • For GCC, compile your code with option -DMY_CONTROL_MACRO.
  2. You can check out here for more info.

    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. You can also use the advanced ifdef-else-endif style:

    #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
    

这篇关于强制编译器忽略程序中的一些行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆