Sharing variables across files with extern
What you'll learn: How to use the extern keyword to let multiple C files access and modify the same global variable.
The problem of separate files
Imagine you are building a house. You have two blueprints: one for the kitchen and one for the living room. If both rooms need to use the same thermostat, you can't just put a brand-new thermostat in both blueprints. If you did, you’d end up with two separate devices that don't talk to each other.
In C, if you define int score = 0; in file1.c and then define int score = 0; again in file2.c, the compiler will get confused and throw a "multiple definition" error. However, if you don't define it in the second file, that file won't know the variable exists. To solve this, we use extern.
How extern works
The extern keyword tells the compiler: "Hey, this variable exists somewhere else in the project. Don't create a new one; just look for the existing one when you link everything together."
- Definition: You create the variable once (usually in a
.cfile) without theexternkeyword. This allocates memory. - Declaration: You tell other files about it using
extern. This does not allocate memory; it’s just a pointer to the original.
Seeing it in action
Here is how you share a global variable between two files:
// --- global_data.c ---
int global_score = 100; // The actual definition (memory is allocated here)
// --- main.c ---
#include <stdio.h>
extern int global_score; // Declaration: "Look for this in another file!"
int main() {
printf("The score is: %d\n", global_score);
global_score = 200; // Modifying the shared variable
return 0;
}
In this example, main.c doesn't "own" the global_score, but it has permission to use it. Because both files are pointing to the same spot in your computer's memory, any changes made in main.c will be reflected everywhere else the variable is used.
Why use it?
Using extern is the primary way to manage "Global State." While you should use global variables sparingly to avoid messy code, extern is essential for sharing configuration settings, game states, or hardware flags across a large program with dozens of different files.
Key takeaway
Use extern to declare a variable in one file that is physically defined in another, allowing multiple files to share the same piece of data.