Learn C
#include "preprocessor/include_guards.h"

Include Guards in C

#concept

Headers get included multiple times through diamond include chains (a.h includes b.h and c.h, both including common.h) — without guards, common.h's contents paste twice and redefinition errors follow. Include guards (#ifndef FILE_H / #define FILE_H ... #endif, or #pragma once) make repetition harmless.

Every header you write needs one, named after its path (MATH_UTILS_H). #pragma once is shorter and universally supported in practice, though not technically standard — classic guards work everywhere including ancient toolchains.

#how it works
1

Diamond includes duplicate

Two paths to one header paste its contents twice — structs and typedefs then redefine and fail.

2

Classic guard pattern

#ifndef MATH_H / #define MATH_H ...contents... #endif — second inclusion finds MATH_H defined and contributes nothing.

3

Name guards uniquely

PROJECT_MODULE_H mirrors the file path — generic names like COMMON_H collide across projects.

4

#pragma once alternative

One line, same effect, supported by GCC/Clang/MSVC — choose it for new code unless exotic compilers matter.

#example
// math.h:
// #ifndef MATH_H
// #define MATH_H
// int square(int x);
// #endif
// main.c includes math.h twice (directly + via util.h):
// -> second paste contributes nothing; compiles cleanly
Output
(builds with no redefinition errors)
1First inclusion defines MATH_H and contributes the declarations.
2Second inclusion (through another header) sees MATH_H defined and pastes nothing.
3No duplicates reach the compiler — the diamond collapses silently.
#use cases
Guarding every header in every project without exception
Diagnosing redefinition errors as missing guards
Unique guard names preventing cross-project collisions
Choosing #pragma once for brevity on mainstream toolchains

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.