Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

c++ - Force the compiler to ignore some lines in the program

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)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...