C Preprocessor Directives
C Preprocessor Directives
Preprocessor directives are lines that start with #. The preprocessor handles them before the code is compiled, for example to include a header file, or to replace a name with a value.
Example
Use #define and #ifdef:
#include <stdio.h>
#define DEBUG
#define VERSION 2
int main() {
#ifdef DEBUG
printf("Debug mode, version %d\n", VERSION);
#endif
return 0;
}
A list of all the preprocessor directives can be found in the table below:
| Directive | Description |
|---|---|
| #include | Copies the contents of a header file into the program |
| #define | Defines a macro: a name that is replaced with a value or with code |
| #undef | Removes a macro that was defined with #define |
| #ifdef | Includes the code below it, if a macro is defined |
| #ifndef | Includes the code below it, if a macro is not defined |
| #if | Includes the code below it, if a condition is true |
| #elif | Checks another condition, if the conditions above it were false |
| #else | Includes the code below it, if the conditions above it were false |
| #endif | Ends an #if, #ifdef or #ifndef block |
| #error | Stops the compiling with an error message |
| #pragma | Gives a special instruction to the compiler. What it does depends on the compiler |
| #line | Changes the line number and the file name that the compiler reports |
Note: #pragma once is often used instead of an include guard. Most compilers support it, but it is not part of the C standard.
Preprocessor Operators
| Operator | Description |
|---|---|
| defined | Checks if a macro is defined. Used with #if, for example #if defined(DEBUG) |
| # | Turns a macro parameter into a string. With #define STR(x) #x, STR(hello) becomes "hello" |
| ## | Joins two names into one. With #define JOIN(a, b) a##b, JOIN(my, Var) becomes myVar |
Predefined Macros
The compiler defines these macros for you:
| Macro | Description |
|---|---|
| __FILE__ | The name of the current source file, as a string |
| __LINE__ | The current line number, as an int |
| __DATE__ | The date when the file was compiled, as a string like "Nov 10 2026" |
| __TIME__ | The time when the file was compiled, as a string like "14:30:05" |
| __STDC__ | The value 1, if the compiler follows the C standard |
| __STDC_VERSION__ | The C version, for example 199901L for C99, 201112L for C11 and 201710L for C17 |
Note: __func__ (the name of the current function) is not a macro, but you can use it in the same way.
Example
Print the line number and the name of the function:
#include <stdio.h>
int main() {
printf("Line: %d\n", __LINE__);
printf("Function: %s\n", __func__);
return 0;
}
Related Pages
Read more about the preprocessor in our C Macros Tutorial and C Organize Code Tutorial.