×
>
<

Aptitude

Pre-Processors in C

What is a Pre-Processor in C ?

In C programming, a pre-processor is a program or a part of the compiler that processes the source code before actual compilation. It handles directives beginning with a hash symbol (#) and performs various tasks such as including header files, macro substitution, conditional compilation, and file inclusion.

The primary purpose of a pre-processor is to prepare the source code for compilation by the actual compiler. It doesn't understand the syntax of the C language but acts on instructions provided through preprocessor directives. Some common preprocessor directives include:

Types ?
  • #include: It is used to include contents of another file (usually header files) in the source code.
  • #define: It is used to define constants or macros which are replaced by specified expressions throughout the code.
  • #ifdef, #ifndef, #endif: These directives are used for conditional compilation. Code enclosed between #ifdef and #endif is included in the compilation process only if the specified identifier is defined.
  • #undef: It is used to undefine a defined macro.
  • #if, #elif, #else: These directives are used for conditional compilation based on expressions.
  • #pragma: It provides additional instructions to the compiler, typically to control optimization or to give other non-standard directives.
Example for #include:
            
#include <stdio.h>

int main()
{
    printf("Hello, world!\n");
    return 0;
}
            
        
Output
            
Hello, world!
            
        
Example for #define:
            
#define PI 3.14159

int main()
{
    float radius = 5.0;
    float area = PI * radius * radius;
    printf("Area of circle: %f\n", area);
    return 0;
}
            
        
Output
            
Area of circle: 78.539749
            
        
Example for #ifdef, #ifndef, #endif:
            
#define DEBUG

int main()
{
#ifdef DEBUG
    printf("Debugging is enabled.\n");
#else
    printf("Debugging is disabled.\n");
#endif

    return 0;
}
            
        
Output
            
Debugging is enabled.
            
        
Example for #undef:
            
#define MESSAGE "Hello, world!"
#undef MESSAGE

int main()
{
    printf("%s\n", MESSAGE); // This line will cause a compilation error.
    return 0;
}
            
        
Output
            
Compilation error: 'MESSAGE' undeclared.
            
        
Example for #if, #elif, #else:
            
#define VERSION 2

int main()
{
#if VERSION == 1
    printf("This is version 1.\n");
#elif VERSION == 2
    printf("This is version 2.\n");
#else
    printf("Unknown version.\n");
#endif

    return 0;
}
            
        
Output
            
This is version 2.
            
        
Example for #pragma:
            
#include <stdio.h>

int main()
{
#pragma message("Compiling main function...")
    printf("Hello, world!\n");
    return 0;
}
            
        
Output
            
Hello, world!