Conditional Compilation
Conditional Compilation in C directives is a type of directive that helps to compile a specific portion of the program or to skip the compilation of some specific part of the program based on some conditions. There are the following preprocessor directives that are used to insert conditional code:
- #if Directive
- #ifdef Directive
- #ifndef Directive
- #else Directive
- #elif Directive
- #endif Directive
#endif directive is used to close off the #if, #ifdef, and #ifndef opening directives which means the preprocessing of these directives is completed.
Syntax
#ifdef macro_name
// Code to be executed if macro_name is defined
#ifndef macro_name
// Code to be executed if macro_name is not defined
#if constant_expr
// Code to be executed if constant_expression is true
#elif another_constant_expr
// Code to be excuted if another_constant_expression is true
#else
// Code to be excuted if none of the above conditions are true
#endif
If the macro with the name ‘macro_name‘ is defined, then the block of statements will execute normally, but if it is not defined, the compiler will simply skip this block of statements.
Example
The below example demonstrates the use of #include #if, #elif, #else, and #endif preprocessor directives.
C
//program to demonstrates the use of #if, #elif, #else, // and #endif preprocessor directives. #include <stdio.h> // defining PI #define PI 3.14159 int main() { #ifdef PI printf ( "PI is defined\n" ); #elif defined(SQUARE) printf ( "Square is defined\n" ); #else #error "Neither PI nor SQUARE is defined" #endif #ifndef SQUARE printf ( "Square is not defined" ); #else cout << "Square is defined" << endl; #endif return 0; } |
PI is defined Square is not defined
C Preprocessors
Preprocessors are programs that process the source code before compilation. Several steps are involved between writing a program and executing a program in C. Let us have a look at these steps before we actually start learning about Preprocessors.
You can see the intermediate steps in the above diagram. The source code written by programmers is first stored in a file, let the name be “program.c“. This file is then processed by preprocessors and an expanded source code file is generated named “program.i”. This expanded file is compiled by the compiler and an object code file is generated named “program.obj”. Finally, the linker links this object code file to the object code of the library functions to generate the executable file “program.exe”.