Course contentsShow
← C
Lesson 146 of 1,2192. Variables and TypesFree lesson

The `extern` keyword for multi-file code

The extern keyword for multi-file code

What you'll learn: How to share a single global variable across multiple different C files using the extern keyword.

The problem of sharing

As your programs grow, you will start splitting your code into multiple .c files to keep things organized. However, C has a strict rule: you cannot define the same variable name in two different files. If you try to create int score = 0; in player.c and also in ui.c, the compiler will get confused and throw a "multiple definition" error.

But what if both files need to access the exact same score? You need a way to tell one file that the variable exists somewhere else.

The "I'm just visiting" keyword

The extern keyword is like a "referral." It tells the compiler: "Don't create a new box for this variable here. Just know that a variable with this name and type already exists in another file, and I'd like to use it."

Think of it like a library book.

  • One file defines the variable (buys the book and puts it on the shelf).
  • Other files declare it as extern (gets a library card to look at that specific book).

How it looks in code

Imagine we have a game. We define our global variable in main.c, and we want to modify it inside a function in game_logic.c.

File 1: main.c

#include <stdio.h>

// This is the actual definition. The memory is allocated here.
int global_score = 100;

int main() {
    printf("Score before: %d\n", global_score);
    update_score(); // Function defined in the other file
    printf("Score after: %d\n", global_score);
    return 0;
}

File 2: game_logic.c

// We use extern to say: "Find global_score in another file."
// Do NOT assign a value here (like = 5); just state the type and name.
extern int global_score;

void update_score() {
    global_score = global_score + 50; 
}

Why use it?

Without extern, each file is an island. By using extern, you create a bridge. It allows different parts of your program to stay in sync. Just remember: you can declare extern as many times as you want in different files, but you must define the variable (without extern) exactly once in only one file.

Key takeaway

Use extern to tell a file that a global variable is defined somewhere else, allowing multiple files to share the same piece of data.