318 Chapter 13 The Preprocessor
want to make certain it is included only once in a program, you can define a unique
identifier that can be tested later. Consider the sequence of statements:
#ifndef _MYSTDIO_H
#define _MYSTDIO_H
...
#endif /* _MYSTDIO_H */
Suppose you typed this into a file called mystdio.h. If you included this file in your pro-
gram with a statement like this:
#include "mystdio.h"
the #ifndefinside the file would test whether _MYSTDIO_Hwere defined. Because it
wouldn’t be, the lines between the #ifndefand the matching #endifwould be includ-
ed in the program. Presumably, this would contain all of the statements that you want
included in your program from this header file. Notice that the very next line in the
header file defines _MYSTDIO_H.If an attempt were made to again include the file in the
program,_MYSTDIO_Hwould be defined, so the statements that followed (up to the
#endif, which presumably is placed at the very end of your header file) would not be
included in the program, thus avoiding multiple inclusion of the file in the program.
This method as shown is used in the system header files to avoid their multiple inclu-
sion in your programs.Take a look at some and see!
The #ifand #elifPreprocessor Statements
The #ifpreprocessor statement offers a more general way of controlling conditional
compilation.The #ifstatement can be used to test whether a constant expression evalu-
ates to nonzero. If the result of the expression is nonzero, subsequent lines up to a #else,
#elif, or #endifare processed; otherwise, they are skipped. As an example of how this
might be used, assume you define the name OS,which is set to 1 if the operating system
is Macintosh OS, to 2 if the operating system is Windows, to 3 if the operating system is
Linux, and so on.You could write a sequence of statements to conditionally compile
statements based upon the value of OSas follows:
#if OS == 1 /* Mac OS */
...
#elif OS == 2 /* Windows */
...
#elif OS == 3 /* Linux */
...
#else
...
#endif
With most compilers, you can assign a value to the name OSon the command line using
the -Doption discussed earlier.The command line
gcc -D OS=2 program.c