Concept of conditional compilation
• In many cases, we want some of the code in the program to compile only if certain conditions are met, otherwise it does not participate in compilation (only the code that participates in the compilation will eventually be executed), which is conditional compilation.
first, basic usage
#if conditions 1
..... code1 ...
#elif Conditions 2
..... code2 ...
#else
..... code3 ...
#endif
1> If condition 1 is set up, then the compiler will have # if and #elif之间的code1代码编译进去 (note: is compiled into, not execution, very often used if-else is not the same)?2> if the condition 1 is not established, the condition 2 is established, then the compiler will put the # Elif and #else之间的code2代码编译进去 3> if the conditions 1, 2 are not set, then the compiler will #else and #endif之间的code3编译进去 4> notice, conditional compilation, after the end of the last side to add a #endif, Otherwise the consequences are serious (think about the consequences yourself) 5> #if and #elif后面的条件一般是判断宏定义而不是判断变量, because conditional compilation is a judgment done before compiling, and the macro definition is defined before compilation, and the variable is generated at run time, meaning that it is used.
Two , give an example
#include <stdio.h>
2
3 #define MAX 11
4
5 int Main ()
6 {
7 #if MAX = = 0
8 printf ("Max is 0");
9 #elif MAX > 0
printf ("Max is greater than 0");
#else
printf ("Max is less than 0");
#endif
return 0;
15}
• A macro max is defined in line 3rd, but in development this max may be defined in other header files and is now written to the main function for illustrative purposes only. Note the conditional compilation statements for lines 7th through 13th. Because Max is 11, the #elif condition is set, and the 10th line of code will be compiled, in fact, after the pre-processing of the compiled code:
int main ()
4 {
5 printf ("Max is greater than 0");
6 return 0;
7}
Third, Other uses
• 1. Use of #if defined () and # if!defined ()• #if and #elif后面的条件不仅仅可以用来判断宏的值, you can also determine whether a macro has been defined.
such as
#if defined (MAX)
.... Code ...
#endif
• If you have already defined Max as a macro, compile code into it. It does not control the value of Max, as long as Max is defined, the condition is set.
conditions can also be reversed:
#if!defined (MAX)
.... Code ...
#endif
• If Max is not defined previously, the code is compiled in.
2. Use of #ifdef和 #ifndef• The use of #ifdef的使用和 # if defined () is basically consistent
#ifdef MAX
.... Code ...
#endif
• If you have already defined Max as a macro, compile code into it. * #ifndef又和 The use of # if!defined () is basically consistent
#ifndef MAX
.... Code ...
#endif
• If Max is not defined previously, the code is compiled in.
preprocessing directives (conditional compilation)