C Preprocessor and Macros
Preprocessor and Macros
In C, the preprocessor runs before the actual compilation begins. It handles things like including files and defining macros.
Preprocessor commands begin with a #
symbol and are called directives.
#include - Include Header Files
You have already seen the #include
directive many times - It tells the compiler to include a file.
It is used to add libraries or custom header files:
Example
#include <stdio.h>
#include "myfile.h"
Use angle brackets < >
for standard libraries and double quotes " "
for your own files.
Tip: The most commonly used libraries can be found in our C Reference Documentation.
#define - Create a Macro
A macro is a name that represents a value (like PI), or a piece of code,
defined using the #define
directive.
In the example below, PI
is replaced with 3.14
before the program is compiled.
This means that every time PI
appears in the
code, it will be replaced with 3.14
:
Macros can also take parameters, like a function:
Example
#define SQUARE(x) ((x) * (x))
int main() {
printf("Square of 4: %d\n", SQUARE(4));
return 0;
}
Try it Yourself »
Macros with parameters work like shortcuts, but be careful with parentheses to avoid mistakes.
#ifdef and #ifndef - Conditional Compilation
You can use #ifdef
and #ifndef
to compile parts of the code only if certain macros are (or are not) defined:
Example
#define DEBUG
int main() {
#ifdef DEBUG
printf("Debug mode is ON\n");
#endif
return 0;
}
Try it Yourself »
This is useful for debugging or building different versions of the same program.