Course contentsShow
← C
Lesson 380 of 1,2195. FunctionsFree lesson

Header Guards: `#ifndef` and `#define`

Header Guards: #ifndef and #define

What you'll learn: How to prevent compiler errors caused by including the same header file multiple times in a single program.

The Double-Include Problem

Imagine you are baking a cake. You have a recipe for frosting, and you have a recipe for the sponge. Both recipes require you to "Define what sugar is." If you read both recipes, you don't need to be told what sugar is twice; you already know.

In C, if you #include the same header file twice—even indirectly—the compiler sees the same function prototypes and variables defined twice. This leads to a "redefinition error," and your program won't compile. As your projects grow and files include other files, these circular overlaps become almost impossible to avoid manually.

The Shield: Header Guards

A Header Guard is a special wrapper made of preprocessor directives that acts like a velvet rope at a club. It checks if the file has already been invited to the party. If it has, the compiler skips it.

We use three directives to build this shield:

  1. #ifndef: "If Not Defined." It checks if a specific unique name (a macro) exists.
  2. #define: If the name doesn't exist, this line creates it.
  3. #endif: This marks the end of the guarded section.

How to Write Them

You should wrap the entire contents of your .h file in these guards. By convention, the unique name is usually the filename in uppercase, with underscores instead of dots.

/* math_utils.h */

// 1. Check: Has "MATH_UTILS_H" been defined yet?
#ifndef MATH_UTILS_H
// 2. If not, define it immediately!
#define MATH_UTILS_H

// Now, all your actual code goes here:
int add(int a, int b);
int subtract(int a, int b);

// 3. Close the guard
#endif 

The first time the compiler hits this file, MATH_UTILS_H isn't defined, so it enters the file and defines it. If the compiler encounters this file again in the same run, the #ifndef check fails (because the name now exists), and the compiler skips straight to the #endif, preventing any duplicate definitions.

Key takeaway

Header guards ensure your header file is only processed once per compilation, preventing "redefinition" errors in complex projects.