Conditional compilation is achieved through precompiled directives, the main methods are:
1, #if, #elif, #else, #endif
#if conditions 1
Code Snippet 1
#elif Conditions 2
Code Snippet 2
...
#elif condition N
Code Snippet N
#else
Code Snippet N+1
#endif
#if的含义是, if the constant expression after # if is true, compile the code that it controls, such as when condition 1 is set up in code Snippet 1, Condition 1 does not set up again to see if the condition 2 is set up, if the condition 2 is set up the code segment 2, otherwise, and so on to judge other conditions, The final code snippet N+1 is compiled if the condition 1-n is not force-coded.
2, #ifdef, #else, #endif or #ifndef, #else, #endif
#ifdef: Indicates "If this macro is defined"
#ifndef: Indicates "If this macro is not defined"
#ifdef Windows//If there is a macro defined for Windows, execute Code Snippet 1, otherwise execute code snippet 2
Code Snippet 1
#else
Code Snippet 2
#endif
#ifndef Windows//If you do not have a macro defined for Windows, execute Code Snippet 1, otherwise execute code snippet 2
Code Snippet 1
#else
Code Snippet 2
#endif
3, through the macro function defined (macro_name)
The parameter is a macro name (no need to add ""), if the macro_name is defined and returns True, otherwise false, the function can write more complex conditional compilation instructions such as
#if defined (Macro1) | | (!defined (MACRO2) && defined (MACRO3))
...
#else
...
#endif
Directive Purpose # NULL instruction, no effect #include contains a source code file #define define a macro #undef cancel a defined macro #if If the given condition is true, compile the following code #ifdef If the macro is already defined, compile the following code #ifndef If the macro is not defined, compile the following code #elif If the previous # if given condition is not true and the current condition is true, compile the code below, which is actually else If the shorthand #endif End an # if ... #else条件编译块 #error Stop compiling and display an error message
Conditional compilation of C language