Preprocessor Directives
C Preprocessor
In a C program, all lines that start with # are processed by the preprocessor, a special program invoked by the compiler.
In simple terms:
The preprocessor takes a C program and produces another C program where all preprocessor directives (
#lines) are handled and removed.
Types of Preprocessor Directives
There are four main types of preprocessor directives:
-
Macros
-
File Inclusion
-
Conditional Compilation
-
Other Directives
Important Preprocessor Directives
All preprocessor commands:
-
Begin with
# -
Must be the first non-blank character on a line
-
Typically start in the first column for readability
List of Common Directives
| Sr. No | Directive | Description |
|---|---|---|
| 1 | #define | Substitutes a preprocessor macro |
| 2 | #include | Inserts a header file |
| 3 | #undef | Undefines a macro |
| 4 | #ifdef | True if macro is defined |
| 5 | #ifndef | True if macro is not defined |
| 6 | #if | Tests a compile-time condition |
| 7 | #else | Alternative for #if |
| 8 | #elif | Combination of #else and #if |
| 9 | #endif | Ends conditional block |
| 10 | #error | Prints error message |
| 11 | #pragma | Issues compiler-specific instructions |
Important Facts About the Preprocessor
1️⃣ File Inclusion (#include)
When using #include, the contents of the included file are copied into the current file after preprocessing.
Using Angle Brackets
-
Searches in standard system directories
Using Double Quotes
-
Searches in the current directory first
-
Then in system directories
2️⃣ Macros (#define)
When using #define, the preprocessor replaces matching tokens with the defined value.
Example: Constant Macro
Output:
⚠️ Note: The word max inside double quotes ("") is not replaced.
Example: Function-like Macro
3️⃣ Conditional Compilation
Preprocessors support conditional compilation using #if, #ifdef, #ifndef, etc.
Example:
Platform-Specific Compilation Example
-
__unix__→ Defined on Unix systems -
_WIN32→ Defined on Windows systems
Most Windows compilers define _WIN32.
Some define WIN32.
You can define macros manually during compilation:
4️⃣ Header File Multiple Inclusion Problem
If a header file is included multiple times, it may cause:
-
Redefinition errors
-
Duplicate declarations
Solution: Use Include Guards
5️⃣ Standard Predefined Macros
C provides some built-in macros:
| Macro | Description |
|---|---|
__FILE__ | Current file name |
__DATE__ | Compilation date |
__TIME__ | Compilation time |
__LINE__ | Current line number |
Example:
Comments
Post a Comment