Skip to main content

Macro expansion and file inclusion

Short answer

Macro expansion is the preprocessor replacing a #define name with its body text before compilation (e.g., #define PI 3.1416). File inclusion inserts the contents of another file via #include; <file.h> searches system directories, "file.h" searches current directory first.

What do you mean by macro expansion and file inclusion in C? Explain with example.

Macro expansion

A macro is a name defined with #define that stands for a piece of text. Before compilation the preprocessor replaces every use of the macro by its text. This is called macro expansion. A macro can be a simple constant (#define PI 3.1416) or take arguments (#define SQUARE(x) ((x) * (x))), so SQUARE(r) expands to ((r) * (r)).

File inclusion

The #include directive inserts the contents of another file into the program at that place before compilation. #include <stdio.h> searches the standard system directories; #include "mymath.h" searches the current folder first. It is used for header files and for the programmer's own reusable code.

Example

File mymath.h:

int cube(int n) { return n * n * n; }

Main program:

#include <stdio.h>
#include "mymath.h"
#define PI 3.1416
#define SQUARE(x) ((x) * (x))
int main(void)
{
    float r = 2.0f;
    printf("Area = %.2f\n", PI * SQUARE(r));
    printf("Cube of 3 = %d\n", cube(3));
    return 0;
}

Output:

Area = 12.57
Cube of 3 = 27

Here PI and SQUARE(r) are expanded as macros, and mymath.h is included into the program.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 3 questions →