Course contentsShow
← C
Lesson 925 of 1,21913. Advanced CFree lesson

Common linkage errors and 'multiple definition'

Common linkage errors and 'multiple definition'

What you'll learn: How to prevent the "multiple definition" error by understanding why including variable definitions in header files causes linker conflicts.

The "Too Many Cooks" Problem

Imagine you are writing a recipe for a cake. If you give the recipe to three different chefs and tell each of them to bring the exact same physical mixing bowl, they will eventually collide in the kitchen. In C, the linker is the head chef trying to assemble your program. If two different source files (.c files) both claim to "own" the same global variable, the linker gets confused and quits with a multiple definition error.

This usually happens because a programmer defines a variable in a header file (.h) and then #includes that header in multiple .c files. Remember: #include literally copies and pastes the code. If global_score is defined in game.h, and both player.c and enemy.c include it, they both end up trying to create their own version of that variable.

The Right Way: Declare, Don't Define

To fix this, we use the extern keyword. This tells the compiler: "This variable exists somewhere else, so don't create it here. Just trust me."

You declare the variable in the header using extern (the "promise"), and you define it in exactly one .c file (the "reality").

/* --- settings.h --- */
#ifndef SETTINGS_H
#define SETTINGS_H

// This is a DECLARATION. It says "someone has a volume variable."
extern int global_volume; 

#endif

/* --- settings.c --- */
#include "settings.h"

// This is the DEFINITION. It actually reserves the memory.
int global_volume = 10; 

/* --- main.c --- */
#include "settings.h"
#include <stdio.h>

int main() {
    // We can use it here because of the 'extern' in the header.
    printf("Volume is: %d", global_volume);
    return 0;
}

Why Header Guards Don't Help

A common misconception is that #ifndef header guards prevent this error. Header guards only prevent a header from being included twice in the same .c file. They do nothing to stop two different .c files from each compiling their own copy of a variable. The linker sees these two separate object files, notices they both have a variable named global_volume, and throws the error because it doesn't know which one is the "real" one.

Key takeaway

Define variables in .c files and use extern in headers to share them, ensuring only one memory location exists for the linker to find.