Preprocessor
TheĀ C PreprocessorĀ is is just a text substitution tool to allow extra pre-processing before the actual compilation.
- The above are Preprocessor directives - commands that allow transformations of the source code before it is compiled.
For C++
C++ has many tools such as inline functions that may be better suited compared to a preprocessor definition such as a macro.
Example
Seen in Lecture 7 of CS247. Consider an example: Linear Algebra modules.
main.cc
includes vec.h
main.cc
includes matrix.h
, includes vec.h
- Without the
#ifndef
guard, there are two definitions ofstruct vec
inmain.cc
, which is not allowed
To fix this issue of multiple definitions, use āinclude guardsā:
#ifndef VARIABLE
: The code between#ifndef
and#endif
will only be seen by the compiler ifVARIABLE
is not defined.#define VARIABLE
defines a preprocessor variable.
Include Guard
Works because once File.h
is included once, the variable becomes defined, so in all future includes
the block is omitted.
This doesn't fix all issues
There is an issue with circular dependencies. Consider the following example:
The issue is that each class needs to know the other exists before it can be created.
Solution: Break circular dependencies chain using Forward Declaration.
Preprocessor Directives
All preprocessor commands begin with a hash symbol (#
).
Directive | Description |
---|---|
#define | Substitutes a preprocessor macro. |
#include | Inserts a particular header from another file. |
#undef | Undefines a preprocessor macro. |
ifdef | Returns true if this macro is defined. |
#ifndef | Returns true if this macro is not defined. |
#if | Tests if a compile time condition is true. |
#else | The alternative for #if . |
#elif | #else and #if in one statement. |
#endif | Ends preprocessor conditional. |
#error | Prints error message on stderr. |
#pragma | Issues special commands to the compiler, using a standardized method. |