Preprocessor
Preprocessor
Preprocessor: An instruction that takes action before compilation. It may expand source code, include/exclude source code, or optimise code in a particular way.
Preprocessor directives: Lines which start with #
, which will be processed by the preprocessor.
4 Types of Preprocessor Directives
File Inclusion Tells the compiler to include a file using the
#include
directive.standard / header file: files provided by the (standard) library. Contains pre-defined functions like
printf()
. These files are included with<>
. Example:#include <stdio.h>
user-defined file: header files defined/written by the user. It's a good practice to divide up functions into separate files and include only when needed. These files are included with
""
. Example:#include "mylibrary.h"
Macro Associates a name with a piece of code. During preprocessing, the compiler will replace all encounters of the name with the corresponding code. Macros are defined with the
#define
directive.Macros can take arguments and can be used like functions.
Sample Code
Conditional Compilation Tells C to compile a specific portion of the program or to skip compilation of some specific part of the program based on conditions, enclosed with
#ifdef
, and#endif
.You can also use
#if
,#elif
and#else
for conditional compilation.Others
#undef
: used to undefine existing macros.#pragma
: a subset of special commands for the compiler. Some pragma directives are unique to certain compilers. Examples:
Last updated