What Is Conditional Compilation?
Under normal circumstances, every line of code in the C language source program must be compiled. But sometimes because of the optimization of the program code, I hope to compile only a part of it. At this time, you need to add conditions to the program, so that the compiler will only compile the code that meets the conditions, and will not meet the conditions of the code Discard, this is conditional compile. [1]
- The preprocessor provides the function of conditional compilation. Conditional compilation allows you to compile only the program segments that meet the conditions in the source file, making the target program shorter, thereby reducing the memory overhead and improving the efficiency of the program. You can compile different program parts according to different conditions, resulting in different Object code file. This is useful for program porting and debugging. [2]
- In C language, to conditionally compile the code segments in a program, conditional compilation commands are used. Conditional compilation mainly has the following formats: [1]
- There are three source files as shown in Figure 16-2, which has the problem of repeatedly including the same source file. Please modify the program, do not delete the code, use conditional compilation to avoid repeated inclusion, so that each source file can be compiled. [5]
- analysis:
- The main () function in the source file ac needs to call the subl () function in bc and the sub2 () function in cc. Therefore, the file ac contains bc and cc. The sub3 () function in the source file bc calls the sub2 () function in cc, so bc also contains cc. In this way, the problem of duplicate inclusion is caused, that is, the file ac contains cc twice, and the content of ac is equivalent to this:
- The content of cc appears twice, and there are two definitions of the sub2 () function, resulting in compilation errors.
- To solve this problem, you need to use conditional compilation, put the content of cc under the conditional compilation control, that is, modify the content of cc to
// cc #ifndef FILE_C #define FILE_C void sub () { ... } #endif
- This can prevent the content of cc from being included repeatedly. [5]