The C Preprocessor

It is a program that processes our source program before it is passed to the compiler. The preprocessor commands are known as directives and begin with a pound symbol(#). In the coming sections, we will learn about the following:

Macro Expansion

A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the constant contents of the macro. It is made to make the program more readable. For example :

#define UPPER 10 main( ) { int i ; for ( i = 1 ; i <= UPPER ; i++ ) printf ( "\n%d", i ) ; }
In this example, instead of writing 10 in the for loop, we use the macro UPPER, which is replaced by its defined value during preprocessing.

File Inclusion

The file inclusion directive causes one file to be included in another, i.e. it causes the entire contents of filename to be inserted into the source code at that point in the program. The syntax of the command is :

#include "filename" #include <filename>
Following are the examples:
#include "myFile.c" #include <myFile.c>
The first statement looks for the file in the current directory as well as the specified list of directories as mentioned in the include search path that might have been set up.
The next statement looks for the file in the specified list of directories only.

Conditional Compilation

We can make the compiler skip over a part of a source code. This can be done by inserting the preprocessing commands like #ifdef and #endif that have the general form:

#ifdef macroname statement 1 ; statement 2 ; statement 3 ; #endif
If macroname has been defined, the block of code will be processed as usual, otherwise not.
It can be used to "comment out" obsolete lines of code.

Miscellaneous Directives

In this section, we will read about two more directives, which are not used very frequently:

#undef directive

When we need to cause a defined name to be 'undefined', we use this directive. The syntax is:

#undef macro template
For example
#undef PENTIUM
This will cause the definition of PENTIUM to be removed from the system.

#pragma directive

The pragma directive specifies machine- or operating-specific compiler features. There are many types of pragma directive and they vary from one compiler to the other. If a compiler does not recognize a particular pragma, then it simply ignores that pragma statement without showing any error or warning message and executes the whole program as if the pragma statement was never present.
Some available pragma directives are listed below :