Preprocessor directives (#define, #include, etc.)

Lesson 8.1: Preprocessor Directives


In this lesson, you'll learn about preprocessor directives, special instructions that the C preprocessor handles before your code is compiled. They provide a way to control the compilation process, manage conditional code, and create reusable macros.


What is the Preprocessor?


A separate program that runs before your C compiler.

Processes your source code, looking for special lines starting with the # symbol.

Makes changes to your code based on these directives, and then hands off the modified code to the compiler.

Common Preprocessor Directives


#include (File Inclusion):


Tells the preprocessor to insert the contents of another file (usually a header file) into your source code.

Used to include standard library headers (e.g., #include <stdio.h>) or your own header files.

Syntax:

#include <filename>: Searches for the file in standard system directories.

#include "filename": Searches for the file in the current directory first.

#define (Macro Definition):


Creates symbolic constants or macros.

A macro can be a simple value replacement or a more complex piece of code.

Syntax:

#define identifier replacement (Constant)

#define identifier(parameters) replacement (Function-like macro)

Example:

C

#define PI 3.14159 // Constant

#define SQUARE(x) ((x) * (x)) // Function-like macro


#ifdef, #ifndef, #else, #endif (Conditional Compilation):


Allow you to include or exclude sections of code based on certain conditions (whether a macro is defined or not).


Useful for managing platform-specific code or debug output.


Example:


C

#ifdef DEBUG

    printf("Debug information\n");

#endif


Other Directives


#undef: Undefines a macro.

#error: Generates an error message during preprocessing.

#pragma: Provides additional instructions to the compiler (e.g., disabling warnings).

#line: Changes the line numbering reported in error messages.

Important Notes


No Semicolons: Preprocessor directives do not end with semicolons.

Processing Order: Directives are processed in the order they appear in your source code.

Scope: Macros defined with #define have file scope and can be used anywhere in the file after their definition.

Example: Using Preprocessor Directives


C

#include <stdio.h>

#define MAX_VALUE 100

#define DEBUG


int main() {

    int number;


    #ifdef DEBUG

        printf("Enter a number (0-%d): ", MAX_VALUE);

    #else

        printf("Enter a number: "); 

    #endif

        

    scanf("%d", &number);

    

    #ifdef DEBUG

        printf("You entered: %d\n", number);

    #endif

    return 0;

}


In this example, the #ifdef DEBUG directives control whether debug messages are printed or not.

Course Syllabus