preprocessor directives in c
The C Preprocessor is not part of the compiler, but is a separate step in the compilation process. In simplistic terms, a C Preprocessor is just a text substitution tool and they instruct compiler to do required pre-processing before actual compilation. We’ll refer to the C Preprocessor as the CPP.
All preprocessor commands begin with a pound symbol (#). It must be the first nonblank character, and for readability, a preprocessor directive should begin in first column. Following section lists down all important preprocessor directives:
|Substitutes a preprocessor macro
|Inserts a particular header from another file
|Undefines a preprocessor macro
|Returns true if this macro is defined
|Returns true if this macro is not defined
|Tests if a compile time condition is true
|The alternative for #if
|#else an #if in one statement
|Ends preprocessor conditional
|Prints error message on stderr
|Issues special commands to the compiler, using a standardized method
Analyze the following examples to understand various directives.
#define MAX_ARRAY_LENGTH 20
This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use#define for constants to increase readability.
#include <stdio.h> #include "myheader.h"
These directives tell the CPP to get stdio.h from System Libraries and add the text to the current source file. The next line tells CPP to get myheader.h from the local directory and add the content to the current source file.
#undef FILE_SIZE #define FILE_SIZE 42
This tells the CPP to undefine existing FILE_SIZE and define it as 42.
#ifndef MESSAGE #define MESSAGE "You wish!" #endif
This tells the CPP to define MESSAGE only if MESSAGE isn’t already defined.
#ifdef DEBUG /* Your debugging statements here */ #endif
This tells the CPP to do the process the statements enclosed if DEBUG is defined. This is useful if you pass the -DDEBUG flag to gcc compiler at the time of compilation. This will define DEBUG, so you can turn debugging on and off on the fly during compilation.
ANSI C defines a number of macros. Although each one is available for your use in programming, the predefined macros should not be directly modified.
|The current date as a character literal in “MMM DD YYYY” format
|The current time as a character literal in “HH:MM:SS” format
|This contains the current filename as a string literal.
|This contains the current line number as a decimal constant.
|Defined as 1 when the compiler complies with the ANSI standard.