Reading history

Internal vs External Linkage in C: static and extern

8 min read 1 views

Learn how C shares names between files: external linkage with extern, internal linkage with static, and a 3-file example to build with gcc.

Real C programs are split across many files. Linkage decides whether a name in one file can refer to the same variable or function in another. External linkage shares a name across the whole program. Internal linkage, made with static, keeps a name private to one file.

In this lesson you will learn

  • What a translation unit is, and why linkage matters
  • The three kinds of linkage: external, internal and none
  • How extern and static control them
  • How to split a program into a header and source files correctly
  • The linker errors you will meet, and what causes each one

Files, Translation Units and the Linker

The compiler handles one .c file at a time, after the preprocessor has pasted in its headers. That combined text is called a translation unit. Each one becomes an object file. Then the linker joins the object files into one program.

When main.c calls add_visitor() but the function is written in counter.c, the compiler cannot see the body. It trusts a declaration and leaves a note for the linker to fill in the address. Linkage decides which of these notes the linker is allowed to connect across files.

The Three Kinds of Linkage

LinkageWho can use the nameHow you get it
ExternalAny file in the programDefault for functions and for variables declared outside any function
InternalOnly the file where it is definedAdd static to a function or a file-level variable
NoneOnly inside its own blockLocal variables and function parameters

static means two different things

Written at file level, static is about who can see the name: only this file. Written inside a function, it is about how long the variable lives: it survives from one call to the next. A static local is still invisible outside its block, so it has no linkage at all. One keyword, two unrelated jobs. See Storage Classes in C.

A Three-File Example

This small visitor counter is split the way real projects are: a header that declares the public parts, and source files that define them.

/* counter.h - the public face of the counter module */
#ifndef COUNTER_H
#define COUNTER_H

extern int visitors_today;      /* declared here, defined in counter.c */

void add_visitor(void);
int  visitor_total(void);

#endif

The header only declares things. extern int visitors_today; says “this variable exists somewhere; do not create it here”. The guard (#ifndef COUNTER_H) stops the header from being pasted twice into one file.

counter.c: Public and Private Parts

/* counter.c - one module, with public and private parts */
#include "counter.h"

int visitors_today = 0;          /* external linkage: other files may use it */

static int all_time_total = 0;   /* internal linkage: private to this file */

static void log_change(void) {   /* internal linkage: helper nobody else sees */
    all_time_total++;
}

void add_visitor(void) {         /* external linkage: part of the public API */
    visitors_today++;
    log_change();
}

int visitor_total(void) {
    return all_time_total;
}
  • visitors_today, add_visitor and visitor_total have external linkage. Any file that includes the header can use them.
  • all_time_total and log_change are static, so they have internal linkage. No other file can read or change them, even by guessing their names.

report.c: A Private Name That Does Not Clash

/* report.c - a second module with its own private helper of the same name */
#include <stdio.h>
#include "counter.h"

static void log_change(void) {   /* no clash: each file has its own static log_change */
    printf("[report] printing summary\n");
}

void print_report(void) {
    log_change();
    printf("Visitors today: %d\n", visitors_today);
    printf("All-time total: %d\n", visitor_total());
}

This file also defines a function called log_change. Because both copies are static, each file has its own private version and the linker never confuses them. Without static, the build would fail with a “multiple definition” error.

main.c and the Build

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

void print_report(void);         /* defined in report.c (external linkage) */

int main(void) {
    for (int i = 0; i < 3; i++) {
        int greeting_number = i + 1;   /* no linkage: a plain local variable */
        add_visitor();
        printf("Welcome, visitor %d\n", greeting_number);
    }
    visitors_today = 0;          /* allowed: visitors_today has external linkage */
    add_visitor();
    print_report();
    return 0;
}
gcc -std=c11 -Wall -Wextra main.c counter.c report.c -o shop && ./shop

Output

Welcome, visitor 1
Welcome, visitor 2
Welcome, visitor 3
[report] printing summary
Visitors today: 1
All-time total: 4

main.c can reset visitors_today because it has external linkage. It has no way to touch all_time_total, so the all-time count of 4 stays correct. That is the point of internal linkage: other files can only change your module’s data through the functions you choose to make public. greeting_number is a local variable with no linkage at all.

Proof That static Really Hides a Name

What if another file tries to reach the private counter with extern?

/* peek.c */
extern int all_time_total;      /* tries to reach counter.c's static variable */
int peek(void) { return all_time_total; }

The file compiles, because extern is only a promise. The linker then looks for an external all_time_total, finds none, and stops:

undefined reference to `all_time_total'

Declare Many Times, Define Once

For anything with external linkage, follow one rule: exactly one definition in the whole program, and as many declarations as you like.

CodeWhat it isWhere it goes
extern int visitors_today;Declaration: “it exists somewhere”Header file
int visitors_today = 0;Definition: creates the variableExactly one .c file
void add_visitor(void);Function declaration (prototype)Header file
void add_visitor(void) { ... }Function definitionExactly one .c file

Functions are extern by default, so writing extern before a function prototype is allowed but unnecessary. More in Function Declaration vs Definition.

Linker Errors and What They Mean

MessageUsual causeFix
undefined reference to `name'Declared but never defined, the defining file was not compiled in, or the definition is staticAdd the definition, add the .c file to the gcc command, or remove static
multiple definition of `name'Two files define the same external name, often because a header contains a definitionKeep only extern declarations in headers; define once; or make helpers static
conflicting types for 'name' (compiler)The header and the source file disagree about the typeInclude the header in the file that defines the name, so the compiler can check both

Common Mistakes

  1. Defining a variable in a header. int count = 0; in a header creates a copy in every file that includes it, which leads to “multiple definition” errors. Use extern int count; in the header.
  2. Putting static variables in a header. Every file gets its own separate copy, so changes in one file are invisible in another. This bug compiles cleanly.
  3. Making everything global. Global variables with external linkage can be changed from anywhere, which makes bugs hard to trace. Start with static and make a name public only when another file needs it.
  4. Forgetting to compile all the files. gcc main.c alone cannot find functions defined in counter.c.
  5. Not including your own header in its source file. If counter.c includes counter.h, the compiler can catch type mismatches between declaration and definition.

Practice Exercises

Exercise 1. What linkage does each name have? (a) static int hits; at file level, (b) double rate; at file level, (c) int i; inside main, (d) static int calls; inside a function.

Show answer

(a) internal, (b) external, (c) none, (d) none (it is a static local: it keeps its value between calls, but no other code can name it).

Exercise 2. A header contains int score = 0; and is included by a.c and b.c. What happens when you link them, and how do you fix it?

Show answer

The linker reports “multiple definition of `score'”. Change the header to extern int score; and put int score = 0; in exactly one .c file.

Exercise 3. Two files each need a helper called trim() that nobody else should call. How do you avoid a clash?

Show answer

Declare each one static: static void trim(char *s) { ... }. Each file then has its own private copy.

Frequently Asked Questions

What is the difference between scope and linkage?

Scope is where a name is visible inside one file. Linkage is whether the same name in different files refers to the same object. A file-level static variable has file scope and internal linkage.

Do I need extern for functions?

No. Functions have external linkage by default. A plain prototype in a header is enough.

Does extern allocate memory?

No. extern int x; without an initialiser only declares the variable. Memory is created by the one definition, such as int x = 0;.

Can a static function be called from another file?

Not by name. Another file can still call it through a function pointer if you hand one out, but it cannot link to it directly.

Summary

  • Each .c file is compiled alone; the linker joins them using linkage.
  • External linkage (the default for functions and file-level variables) shares a name across files.
  • static at file level gives internal linkage: private to that file.
  • Locals and parameters have no linkage.
  • Declare in headers with extern; define exactly once in a .c file.
Lessons are also marked complete when you click Next.