[Learning notes] [C Language] Conditional compilation, learning notes Compilation
1. Concept of Conditional compilation
In many cases, we hope that some of the code of the program can be compiled only when certain conditions are met. Otherwise, it will not be involved in compilation (only the Code involved in compilation can be executed eventually ), this is Conditional compilation.
2. Basic usage
# If condition 1
... Code1...
# Elif condition 2
... Code2...
# Else
... Code3...
# Endif
1> if condition 1 is true, the compiler will compile the code1 code between # if and # elif (Note: It is compiled, not executed, normally, if-else is different.) condition 2> if condition 1 is not true and condition 2 is true, the compiler will compile the code2 code between # elif and # else.
3> if conditions 1 and 2 are not true, the compiler will compile code3 between # else and # endif.
4> Note: After the condition compilation is complete, add a # endif at the end. Otherwise, the consequences will be very serious (think about the consequences yourself)
5> # if and # The conditions after elif are generally macro definitions rather than variables, because Conditional compilation is performed before compilation and macro definitions are defined before compilation, variables are generated at runtime and used only.
3. Other usage
1> # if defined () and # if! Usage of defined ()
# If and # conditions after elif can be used not only to determine the macro value, but also to determine whether a macro has been defined.
For example:
# If defined (MAX)
... Code...
# Endif
If you have defined the MAX macro, compile the code. It does not care about the value of MAX. As long as MAX is defined, the condition is true.
The condition can also be reversed:
# If! Defined (MAX)
... Code...
# Endif
If the MAX macro has not been defined before, compile the code.
2> # Use of ifdef and # ifndef
# The use of ifdef is basically the same as that of # if defined ()
# Ifdef MAX
... Code...
# Endif
If you have defined the MAX macro, compile the code.
* # Ifndef and # if! The usage of defined () is basically the same
# Ifndef MAX
... Code...
# Endif
If the MAX macro has not been defined before, compile the code.
4. Code
1 # include <stdio. h> 2 3 // if you have written # if, you must add # endif 4 5 // # define A 5 6 7 int main () at the end () 8 {9 # ifndef A10 // # ifdef A11 // # if! Defined (A) 12 printf ("Haha \ n"); 13 # endif14 15 // int a = 10; 16/* 17 if (a = 10) 18 {19 printf ("a is 10 \ n"); 20} 21 else if (a = 5) 22 {23 printf ("a is 5 \ n "); 24} 25 else26 {27 printf ("a other value \ n"); 28} */29/* 30 31 # if (A = 10) 32 printf ("a is 10 \ n"); 33 # elif (A = 5) 34 printf ("a is 5 \ n "); 35 # else36 printf ("a other value \ n"); 37 # endif38 39 */40 41 return 0; 42}