0
0
Cprogramming~5 mins

Include guards

Choose your learning style9 modes available
Introduction

Include guards stop a file from being included more than once. This helps avoid errors when the same code is added multiple times.

When you write a header file that might be included in many places.
When you want to prevent duplicate definitions of functions or variables.
When your project has many files including the same header.
When you want to keep your code safe from multiple inclusions causing errors.
Syntax
C
#ifndef HEADER_NAME_H
#define HEADER_NAME_H

// Your code here

#endif // HEADER_NAME_H
Use a unique name for HEADER_NAME_H, usually based on the file name in uppercase.
The #ifndef checks if the name is not defined, then defines it to prevent repeats.
Examples
This example shows a simple include guard for a header file named my_header.h.
C
#ifndef MY_HEADER_H
#define MY_HEADER_H

void greet();

#endif // MY_HEADER_H
Here, the guard protects a config file that defines a constant.
C
#ifndef CONFIG_H
#define CONFIG_H

#define MAX_SIZE 100

#endif // CONFIG_H
Sample Program

This program uses an include guard in the same file for demonstration. The greet function prints a message. The guard ensures greet is defined only once.

C
#include <stdio.h>

#ifndef GREET_H
#define GREET_H

void greet() {
    printf("Hello!\n");
}

#endif // GREET_H

int main() {
    greet();
    return 0;
}
OutputSuccess
Important Notes

Include guards are a simple way to avoid errors from including the same file multiple times.

Always use a unique and descriptive name for the guard to avoid conflicts.

Summary

Include guards prevent multiple inclusion of the same header file.

They use #ifndef, #define, and #endif directives.

Include guards help keep your code safe and error-free.