Site Tools


c-header-guard

Table of Contents

C header guard

Header guard is a C/C++ pattern that prevents multiple inclusion of the same header file by wrapping declarations in preprocessor conditionals. The pattern uses #ifndef, #define, and #endif to ensure declarations are processed only once, even if the header is included multiple times.

Modern alternative: #pragma once.

Use header guards to protect against duplicate declarations and multiple definition errors.

Example

This example shows header guards preventing redefinition when a header is included multiple times.

// compile: gcc -o headerguard headerguard.c
// run: ./headerguard
// description: header guards prevent duplicate inclusion

// math_util.h
#ifndef MATH_UTIL_H
#define MATH_UTIL_H

int multiply(int a, int b) {
    return a * b;
}

#endif // MATH_UTIL_H

// main.c
#include <stdio.h>
#include "math_util.h"
#include "math_util.h"  // safe: guard prevents redefinition

int main() {
    printf("5 * 3 = %d\n", multiply(5, 3));
    return 0;
}
c-header-guard.md · Last modified: