Sunday, February 28, 2016

Conditional Compilation pre-processors

There are other C pre-processors like #if, #elif, #else, #endif etc which are used for conditional compilation. If we want to skip over a part of code during compilation, we can use these pre-processors. This is mostly useful when we write code which depends on the operating system. Suppose, some code we have written is not applicable for Windows and only applicable for Linux machines, we can skip the code, when compiling from Windows machine using this pre-processors. The general form of #ifdefis

  1. #ifdef macroname
  2. Statement block;
  3. #endif
The '#ifdef' stands for 'if defined'. It means that if the macro name is already defined somewhere, then the statement block will be included in the source for compilation, otherwise it will be skipped. The #ifdefis accompanied by an #endif statement, which marks the end of statement block. We can use #ifndef, which is applicable when we want to compile part of program if the corresponding macro name is not defined. Like nested if...else , #ifdef also can be combined with #elif and #else. We can use them as given in the below example.

Conditional Compilation Example in C

  1. #ifdef SYSTEM==LINUX
  2. statement block 1;
  3. #elif SYSTEM==WINDOWS
  4. statement block 2;
  5. #else
  6. statement block 3;
  7. #endif

Predefined Macros

Apart from the above mentioned macros, ANCI has a set of predefined macros which can be used for functionalities that's used commonly in application programs. They are explained below.
MacroDescription
__DATE__Gives current date in MMM DD YYYY format
__TIME__Gives current time in HH:MM:SS format
__FILE__Gives the current file name
__LINE__Gives the current line number of source code
__STDC__Gives 1 when the compilation follows ANSI standard

No comments: