8.1) Preprocessor Directives in C

Preprocessor directives are commands that instruct the compiler to perform specific actions before the actual compilation process begins. They help you customize the compilation process and include or exclude certain code sections based on conditions.

#include Directive

The #include directive is used to include external files in your code, allowing you to reuse code from other files.

Example: Using #include Directive

Suppose you have a header file named myheader.h:

// myheader.h
#ifndef MYHEADER_H
#define MYHEADER_H

void printMessage();

#endif

And a source file named main.c:

#include <stdio.h>
#include "myheader.h"

int main() {
    printf("Hello from main!\n");
    printMessage();

    return 0;
}

Output:

Hello from main!
Message from header file.

In this example, the #include directive includes the content of the myheader.h file in the main.c file, allowing the printMessage() function to be used.

#define Directive

The #define directive defines constants or macros that are replaced with their values during preprocessing.

Example: Using #define Directive

#include <stdio.h>

#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

In this example, the #define directive defines PI as a constant, which is then used to calculate the area of a circle.

Conditional Compilation with #ifdef and #ifndef

Conditional compilation allows you to include or exclude code based on conditions.

Example: Conditional Compilation

Suppose you have a file named config.h:

// config.h
#define DEBUG_ENABLED

And a source file named main.c:

#include <stdio.h>
#include "config.h"

int main() {
#ifdef DEBUG_ENABLED
    printf("Debug mode enabled.\n");
#endif

    printf("Regular operation.\n");

    return 0;
}

Output:

Debug mode enabled.
Regular operation.

In this example, the code within the #ifdef DEBUG_ENABLED block is included because the DEBUG_ENABLED macro is defined in the config.h file.

Preprocessor directives are powerful tools that allow you to control the compilation process and create flexible and customizable code. They help you avoid code duplication, define constants, and enable conditional compilation based on specific conditions.

Leave a Reply