Tool to transform code before compilation
- Can be used for more than C code - Xresources, perl
- Not recommended for generic macro usage (use something
like m4 instead.
- Lines beginning with # are commands to the
preprocessor.
Inclusion of header files
- Inserts an external file into the current file:
#include filename
- Surround system header files with <>
(looks in include path first)
- Surround your header files with "" (looks in
current directory first)
- Use -I option to set search path
Macro definition and expansion
Conditional compilation
#ifdef NAME and #ifndef NAME
will only insert contained code if NAME is or isn't
defined (respectively). End with #endif
Example:
#define FOO
#ifdef FOO
... this gets included ...
#endif
#ifndef FOO
... this does NOT get included ...
#endif
#if allows more complicated expressions with a C-like syntax
(combine terms with &&, ||, and ! and also
use integer operations)
The defined() function returns 1 iff a variable is defined.
These two lines are identical:
#ifdef FOO
#if defined(FOO)
Can use #else and #elif EXPRESSION with
#if EXPRESSION
Can do simple macro arithmatic, eg:
#define X 5
#if X == 4
...
#elif X == 5
...
#else
...
#endif
To omit code, use:
#if 0
... code to be omitted
#endif
Rather than commenting it out. This eliminates problems with
nested comments.
Demo
Uses the files foo,
bar, and
blah.
/lib/cpp -P foo
/lib/cpp -P -DINCLUDE_BAR foo
/lib/cpp -P -DINCLUDE_BLAH foo
![[BACK]](images/back.gif)
Prepared by
Erik Nygren (nygren@mit.edu)
and
Mike Whitson (mwhitson@mit.edu)