Course contentsShow
← C
Lesson 789 of 1,21911. The Preprocessor and BuildFree lesson

The 'duplicate definition' error

The 'duplicate definition' error

What you'll learn: Why including the same header file multiple times causes the compiler to complain and how it leads to "redefinition" conflicts.

The "Double Recipe" Problem

Imagine you are baking a cake and follow a recipe book. If the book accidentally prints the instructions for the frosting twice, you don't bake two frostings; you just get confused. In C, the compiler is much less forgiving.

When you use #include "player.h", the preprocessor literally copies and pastes the entire content of that file into your code. If you accidentally include it twice—perhaps because main.c includes player.h and also includes game.h, which itself includes player.h—the compiler sees the same code twice in a row.

When definitions collide

In C, you can declare something (like a function signature) as many times as you want. However, you can only define something (like a struct or a global variable) exactly once.

If your header file defines a custom data type, like this:

/* player.h */
struct Player {
    int health;
    int score;
};

If this file is included twice, the compiler sees:

/* Result after preprocessing */
struct Player {
    int health;
    int score;
};

struct Player {
    int health;
    int score;
};

The compiler will stop immediately and throw an error: redefinition of 'struct Player'. Even though the two definitions are identical, C assumes you are trying to create a brand new type with the same name, which isn't allowed.

Why this happens in real projects

As your programs grow, you will create a web of files. You might have a constants.h file that everyone needs. If physics.c includes constants.h, and graphics.c includes constants.h, and then main.c includes both physics.h and graphics.h, the contents of constants.h will be pasted into your main file multiple times.

Without a way to tell the compiler "I've already seen this," your build will fail, even if your code logic is perfect. This is the primary reason why managing how headers are read is a vital skill in C programming.

Key takeaway

A "duplicate definition" error happens when the preprocessor pastes the same header content into a single file more than once, violating C’s rule that structures and variables can only be defined one time.