What happens if we include header file for two times in a C program?

In C programming, header files contain declarations of predefined functions, constants, and macros. When a header file is included multiple times in a program, the preprocessor automatically handles this situation to prevent compilation errors.

What Happens with Duplicate Includes?

When a header file is included twice or more times in a C program, the C preprocessor uses include guards (or header guards) to ensure that the contents of the header file are processed only once during compilation. Most standard C library headers like stdio.h, stdlib.h, etc., have built-in protection mechanisms.

How Include Guards Work

Standard header files use preprocessor directives to prevent multiple inclusions −

#ifndef _STDIO_H_
#define _STDIO_H_
/* Header content here */
#endif

Example 1: Multiple stdio.h Inclusions

The following example demonstrates including stdio.h twice −

#include <stdio.h>
#include <stdio.h>  /* Second inclusion ignored */

int main() {
    int a, b, c;
    float avg;
    
    printf("Enter three numbers: ");
    scanf("%d %d %d", &a, &b, &c);
    
    avg = (float)(a + b + c) / 3;
    printf("Average: %.2f<br>", avg);
    
    return 0;
}
Enter three numbers: 10 20 30
Average: 20.00

Example 2: Multiple Header Inclusions

This example shows multiple header files included twice −

#include <stdio.h>
#include <stdio.h>   /* Duplicate stdio.h */
#include <stdlib.h>
#include <stdlib.h>  /* Duplicate stdlib.h */

int main() {
    int a, b, sum;
    
    printf("Enter two numbers: ");
    scanf("%d %d", &a, &b);
    
    sum = a + b;
    printf("Sum: %d<br>", sum);
    
    return 0;
}
Enter two numbers: 15 25
Sum: 40

Key Points

  • The preprocessor automatically ignores duplicate header inclusions using include guards.
  • This prevents redefinition errors and compilation issues.
  • The same mechanism works for user-defined header files when properly implemented.
  • No performance impact occurs since duplicates are eliminated at preprocessing stage.

Conclusion

Including header files multiple times in C is safe and handled automatically by the preprocessor. The include guard mechanism ensures that header content is processed only once, preventing compilation errors and maintaining code reliability.

Updated on: 2026-03-15T13:12:13+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements