The extern keyword for variables
What you'll learn: How to share a single global variable across multiple source files without causing linker errors.
The problem of "Multiple Definition"
In C, variables have a specific "home." When you declare int global_score = 0; at the top of a file, you are telling the compiler to reserve a spot in memory for that integer.
In a multi-file project, you might want main.c to track the score, but player.c needs to update it. If you simply write int global_score; at the top of both files, the compiler gets confused. When the linker tries to stitch your files together into a final program, it sees two different variables with the same name and throws a "multiple definition" error. It doesn't know which "home" is the real one.
The extern solution
The extern keyword acts like a signpost. It tells the compiler: "This variable exists somewhere else in the project. Don't create a new box for it; just trust me that it’s already been defined in another file."
Think of it like a shared office phone. The definition is the physical phone plugged into the wall in Room A. The extern declaration is a sticky note in Room B that says, "If you need the phone, it's located in Room A."
How to implement it
You define the variable once in a .c file, and you declare it as extern in a header file (.h) that every other file can include.
// --- global_data.c ---
// This is the actual definition (allocates memory)
int global_score = 100;
// --- global_data.h ---
// This is a declaration (does NOT allocate memory)
// It tells other files that global_score exists elsewhere
extern int global_score;
// --- main.c ---
#include <stdio.h>
#include "global_data.h"
int main() {
// We can access and change the variable defined in global_data.c
global_score += 50;
printf("Current Score: %d", global_score);
return 0;
}
By using extern, you maintain a single point of truth. Only one file allocates the memory, while every other file just points to that same memory address. This allows your different program modules to communicate through shared data without breaking the build process.
Key takeaway
Use extern in header files to let multiple .c files reference a single global variable defined in one location.