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
The #ifdef
and #ifndef
directives let you include or skip parts of the code depending on whether a macro is defined.
This is called conditional compilation, and it's useful for debugging or creating different versions of a program.
Example
#define DEBUG
int main() {
#ifdef DEBUG
printf("Debug mode is ON\n");
#endif
return 0;
}
Try it Yourself »
If DEBUG
is defined, the message will be printed. If it's not defined, that part of the code is skipped.
Create Your own Header Files
In the next chapter, you will learn how to create your own header files and organize your code across multiple files using "modular programming".