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

Internal vs external linkage basics

Internal vs external linkage basics

What you'll learn: You'll understand how to control whether a variable or function is private to one file or shared across your entire project.

The "Scope" of the Project

Up until now, you’ve likely worked with local variables that live inside functions. But when you move to "Advanced C," your projects will span multiple .c files. Linkage is the set of rules that determines if an identifier (a variable or function name) can be seen by other files during the linking phase of compilation.

Think of your project like a large apartment building. Each .c file is an individual apartment.

  • External Linkage is like a package addressed to the building lobby; anyone in any apartment can access it.
  • Internal Linkage is like a conversation happening inside a specific apartment; the neighbors next door have no idea it’s happening.

External Linkage: The Global Default

By default, any variable or function you declare outside of a function (at the file level) has external linkage. This means if you define int global_score = 100; in game.c, you can access that exact same memory location in ui.c by using the extern keyword. It is a truly global entity.

Internal Linkage: The static Keyword

Sometimes, you want a global variable that is "global" only to the file it sits in. You might have a helper function called validate() that is specific to your math logic and shouldn't clash with a validate() function in your networking logic.

To achieve this, we use the static keyword at the file level. This restricts the name to internal linkage. It tells the compiler: "Keep this name private to this file. Do not let the linker see it."

// math_utils.c

static int local_counter = 0; // Internal linkage: Only visible in this file
int total_operations = 0;      // External linkage: Visible to the whole project

static void reset(void) {      // Internal linkage: Private helper function
    local_counter = 0;
}

void add_numbers(int a, int b) { // External linkage: Can be called from anywhere
    local_counter++;
    total_operations++;
    // ... logic ...
}

Why differentiate?

Using internal linkage (static) is a best practice for encapsulation. It prevents "name collisions"—where two files accidentally use the same name for different things—and ensures that your file’s internal logic stays hidden from the rest of the program.

Key takeaway

External linkage (default) makes names visible to the entire program, while internal linkage (using static) keeps names private to a single file.