Preprocessor directives in C are commands that are processed before the actual
compilation of the program begins. They are used to perform actions such as file
inclusion, macro substitution, conditional compilation, and more. Preprocessor
directives are not part of the C language itself but are handled by the
preprocessor before the code is compiled.
Preprocessor directives are identified by the # symbol and are typically placed at
the beginning of a program or before the main code block.
1. File Inclusion (#include)
The #include directive is used to include header files in a C program. Header files
typically contain declarations of functions, macros, and data types that can be
shared across multiple source files.
There are two types of file inclusion:
Standard Library Header Files: These are predefined by the C library and
are included using angle brackets (<>).
User-defined Header Files: These are created by the programmer and are
included using double quotes ("").
Example: Including Standard Header File
#include <stdio.h> // Including standard library header file
int main() {
printf("Hello, World!\n");
return 0;
}
Example: Including User-defined Header File
#include "myheader.h" // Including user-defined header file
int main() {
, // Code using functions or variables declared in myheader.h
return 0;
}
2. Macro Definition (#define)
The #define directive is used to define macros, which are symbolic constants or
expressions that are substituted by their value during preprocessing. Macros can
be used to define constants, small functions, or complex expressions.
Constant Definition Example:
#include <stdio.h>
#define PI 3.14 // Defining a constant PI
int main() {
printf("Value of PI: %.2f\n", PI);
return 0;
}
Macro Function Example:
#include <stdio.h>
#define SQUARE(x) ((x) * (x)) // Defining a macro for square of a number
int main() {
int num = 5;
printf("Square of %d: %d\n", num, SQUARE(num));
return 0;
}
In the above example, the macro SQUARE(x) is substituted by the expression (x) *
(x) at compile time.