C Preprocessor Directives
C Preprocessor Directives are special instructions that begin with the # symbol and are processed before compilation. They are used to include files, define macros, control conditional compilation, generate errors, and give compiler-specific instructions. Preprocessor directives do not end with a semicolon.
- Macro Definition Directives
Used to define and manipulate macros that replace code or values before compilation. Examples: #define, #undef, #, ##
#include <stdio.h>
#define PI 3.14
#define SQUARE(x) ((x) * (x))
#define STR(x) #x
#define JOIN(a,b) a##b
int main() {
int r = 3;
int xy = 10;
printf("PI = %.2f\n", PI);
printf("Square of %d = %d\n", r, SQUARE(r));
printf("Stringized: %s\n", STR(Hello_C));
printf("Token pasted value = %d\n", JOIN(x, y));
#undef PI
printf("Macro PI undefined successfully\n");
return 0;
}
- File Inclusion Directives
Used to include header files and external source files into a program. Examples: #include
#include <stdio.h>
int main() {
printf("Header file included successfully\n");
return 0;
}
- Conditional Compilation Directives
Used to compile or exclude portions of code based on conditions or macro definitions. Examples: #if, #ifdef, #ifndef, #elif, #else, #endif, #error
#include <stdio.h>
#define VALUE 10
int main() {
#if VALUE > 10
printf("VALUE is greater than 10\n");
#elif VALUE == 10
printf("VALUE is equal to 10\n");
#else
printf("VALUE is less than 10\n");
#endif
#ifdef VALUE
printf("VALUE is defined\n");
#endif
#ifndef MAX
printf("MAX is not defined\n");
#endif
#if VALUE < 5
#error "VALUE is too small"
#endif
return 0;
}
- Miscellaneous / Compiler Control Directives
Used to control compiler behavior and debugging information. Examples: #pragma, #line, predefined macros like __FILE__, __LINE__
#include <stdio.h>
#pragma message("Compiling C Preprocessor Example")
int main() {
#line 200 "custom_file.c"
printf("File Name : %s\n", __FILE__);
printf("Line No : %d\n", __LINE__);
printf("Date : %s\n", __DATE__);
printf("Time : %s\n", __TIME__);
return 0;
}