Node:A few directives, Next:Macros, Previous:Preprocessor directives, Up:Preprocessor directives
A few directives
All preprocessor directives
, or commands, are preceded by a hash
mark (#
). One example you have already seen in previous chapters
is the #include
directive:
#include <stdio.h>
This directive tells the preprocessor to include the file
stdio.h
; in other words, to treat it as though it were part of
the program text.
A file to be included may itself contain #include
directives,
thus encompassing other files. When this happens, the included
files are said to be nested.
Here are a few other directives:
#if ... #endif
- The
#if
directive is followed by an expression on the same line. The lines of code between#if
and#endif
will be compiled only if the expression is true. This is called conditional compilation. #else
- This is part of an
#if
preprocessor statement and works in the same way with#if
that the regular Celse
does with the regularif
. #line constant filename
- This causes the compiler to act as though the next line is line number
constant and is part of the file filename.
Mainly used for debugging.
#error
- This forces the compiler to abort. Also intended for debugging.
Below is an example of conditional compilation.
The following code displays 23
to the screen.
#include <stdio.h> #define CHOICE 500 int my_int = 0; #if (CHOICE == 500) void set_my_int() { my_int = 23; } #else void set_my_int() { my_int = 17; } #endif int main () { set_my_int(); printf("%d\n", my_int); return 0; }