Skip to content
Tutorials Center
My learning

Topics

Lesson 90 of 135 ยท Advanced C

Multi-File Programs and Linkage

Split a C program into headers and source files - what goes where, extern and static linkage, include guards, opaque types, the one-definition rule and linker errors.

Every example so far has lived in one file, which is perfect for learning and hopeless for real software. The Linux kernel has tens of thousands of .c files; even a small command-line tool usually has a handful. Splitting a program lets several people work on it at once, lets the build recompile only what changed, and, most importantly, lets each part hide its internals behind a small, documented interface.

C's tools for this are simple but precise: header files declare what a module offers, source files define it, and two pieces of linkage, extern and static, decide which names are visible across files. This lesson shows a complete multi-file project, explains the rules the compiler and linker apply, and decodes the linker errors you'll inevitably meet. It builds on Declarations, Prototypes and Headers, Scope and Storage Classes and How C Works.

Our editor compiles one file, so the multi-file project itself is shown as read-only code with the commands to build it on your machine. The runnable examples squeeze each idea into a single file so you can try it here.

A project in three files

Here is a tiny temperature-statistics module and a program that uses it. The header is the module's public face:

C
/* temp_stats.h - public interface of the temperature statistics module */
#ifndef TEMP_STATS_H
#define TEMP_STATS_H

#include <stddef.h>     /* size_t: include what the header itself needs */

struct temp_summary {
    double min;
    double max;
    double mean;
};

/* Summarize n readings (n > 0). Returns 0 on success, -1 if n is 0. */
int temp_summarize(const double readings[], size_t n, struct temp_summary *out);

/* Convert Celsius to Fahrenheit. */
double temp_to_fahrenheit(double celsius);

/* Number of summaries computed so far (for diagnostics). */
int temp_summary_count(void);

#endif /* TEMP_STATS_H */

The source file defines everything the header promised, plus private helpers nobody else needs to know about:

C
/* temp_stats.c - implementation */
#include "temp_stats.h"     /* first: proves the header is self-contained */

static int summaries_done = 0;          /* private to this file */

static double clamp_to_absolute_zero(double celsius)   /* private helper */
{
    return celsius < -273.15 ? -273.15 : celsius;
}

int temp_summarize(const double readings[], size_t n, struct temp_summary *out)
{
    if (n == 0) {
        return -1;
    }
    double sum = 0.0;
    out->min = out->max = clamp_to_absolute_zero(readings[0]);
    for (size_t i = 0; i < n; i++) {
        double t = clamp_to_absolute_zero(readings[i]);
        if (t < out->min) { out->min = t; }
        if (t > out->max) { out->max = t; }
        sum += t;
    }
    out->mean = sum / (double)n;
    summaries_done++;
    return 0;
}

double temp_to_fahrenheit(double celsius)
{
    return celsius * 9.0 / 5.0 + 32.0;
}

int temp_summary_count(void)
{
    return summaries_done;
}

And the program that uses the module includes the header and nothing else from it:

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

int main(void)
{
    const double week[] = { 18.5, 21.0, 23.4, 19.8, 25.1, 22.7, 20.3 };
    struct temp_summary s;

    if (temp_summarize(week, sizeof week / sizeof week[0], &s) != 0) {
        fprintf(stderr, "no readings\n");
        return 1;
    }
    printf("min %.1f C, max %.1f C, mean %.1f C (%.1f F)\n",
           s.min, s.max, s.mean, temp_to_fahrenheit(s.mean));
    printf("summaries computed: %d\n", temp_summary_count());
    return 0;
}

Build it by compiling each .c file separately into an object file, then linking them:

Terminal
gcc -std=c17 -Wall -Wextra -c temp_stats.c -o temp_stats.o
gcc -std=c17 -Wall -Wextra -c main.c -o main.o
gcc temp_stats.o main.o -o weather
./weather

Or in one go with gcc -std=c17 -Wall -Wextra main.c temp_stats.c -o weather, which does the same steps behind the scenes. Notice that you never compile the header: it's pulled into each .c file by #include. Each .c file plus everything it includes is called a translation unit, and the compiler sees exactly one translation unit at a time. Here is the same program squeezed into one file, with comments marking where each part would live:

C The three files in one

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It prints min 18.5 C, max 25.1 C, mean 21.5 C (70.8 F) and summaries computed: 1. The key point: main calls temp_summarize before its definition appears, and it compiles because the prototype from the "header" came first. That's exactly the situation in a real multi-file program, where the definition is in a different file that the compiler never sees while compiling main.c.

What goes in a header

A header should contain only things that are safe to see in every file that includes it, and nothing that creates storage or code twice:

Put in headers Keep in .c files
Function prototypes Function definitions (bodies)
struct, union and enum type definitions that callers need Private types used only inside the module
typedefs static helper functions
Macros and #define constants Global variable definitions (int count = 0;)
extern declarations of global variables Static file-scope variables
static inline functions (inline Functions)

Two habits make headers robust. First, a header should include what it uses: temp_stats.h includes <stddef.h> for size_t, so a user can include it first without a mysterious error. Including your own header first in its .c file proves this. Second, every header gets an include guard.

Include guards

Headers include other headers, so the same header often reaches one translation unit twice. Declaring a function twice is harmless, but defining a function twice is an error, and so is defining a struct twice in C17 and earlier. The guard (#ifndef X / #define X / ... / #endif) makes the second inclusion expand to nothing. Here a header's text is pasted twice, exactly what the preprocessor would produce if two headers both included it:

C An include guard at work

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Delete the two #ifndef lines and their #endifs and the compiler reports redefinition of 'point_sum'. (The repeated identical struct alone is accepted under our C23 compiler, since C23 allows compatible redefinitions of a tag, but older standards reject it, and function definitions may never be repeated.) Most compilers also support #pragma once at the top of a header, which does the same thing in one line; it isn't in the C standard, but GCC, Clang and MSVC all accept it. The details are in Conditional Compilation.

Linkage: extern and static

Every name at file scope (outside any function) has a linkage that decides whether other translation units can refer to it:

  • External linkage (the default for functions and global variables): the name refers to the same thing in every file of the program. The linker matches uses in one object file with the definition in another.
  • Internal linkage (static at file scope): the name is private to its translation unit. Another file can use the same name for something else without any clash.
  • No linkage: local variables and parameters, which exist only inside their block.

For functions, a prototype is all another file needs; extern is implied and usually omitted. For variables, you need a way to declare a variable without defining it, and that's what extern does:

C
/* config.h */
extern int verbosity;              /* declaration: "it exists somewhere" */

/* config.c */
#include "config.h"
int verbosity = 1;                 /* the one definition: allocates storage */

/* any other .c file */
#include "config.h"
void log_detail(const char *msg) { if (verbosity > 1) { puts(msg); } }

This TryIt shows the same rules within one file: extern declarations may appear many times, but there's one definition; static names are private:

C extern declarations and static privacy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The first detail message is suppressed, the second is printed after verbosity is raised, and 2 message(s) printed comes last. In a real project, printed and level_name couldn't be touched from main.c at all, and another file could have its own static int printed without conflict.

Warning: static means different things in different places. At file scope it means "internal linkage, private to this file". Inside a function, static int calls = 0; means "keep this variable alive between calls" (static storage duration). Same keyword, two jobs; see Scope and Storage Classes.

Mark every function and global that isn't part of the module's interface as static. It prevents name clashes between modules, documents intent, and lets the compiler optimize more aggressively (it can inline or delete a static function knowing no other file calls it). -Wmissing-prototypes makes GCC warn about non-static functions that have no prototype in a header, which catches forgotten statics.

Opaque types: hiding a struct's insides

The strongest form of encapsulation in C is the opaque type. The header declares a struct without its members (an incomplete type) and offers functions that work through pointers to it. Users can hold and pass struct counter * values but can't read or change the fields, because the compiler doesn't know what they are. FILE from <stdio.h> is the most famous example.

In this single-file version, main comes before the struct's definition, so it sees the type exactly as a user of the header would: incomplete.

C An opaque counter type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Attempts 4 and 5 hit the limit and the value stays 3. Replace that comment line with the code visits->value = 100; and GCC refuses with invalid use of undefined type 'struct counter'. Because users never see the layout, the module can add, remove or reorder fields later without breaking (or even recompiling) code that uses it. The costs are a heap allocation per object and a function call for every access.

The one-definition rule and linker errors

The linker's job is to match every use of an external name with exactly one definition. Zero or two definitions are both errors, and the messages come from the linker (ld), not the compiler, which confuses beginners because the code in each file looks fine.

Undefined reference: something was declared and used, but no object file defines it. Usually you forgot to compile or link a .c file, misspelled a name, or forgot a library like -lm. This TryIt fails to link on purpose:

C An undefined reference (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The compiler is perfectly happy, because the prototype is valid. Then the linker reports undefined reference to 'circle_area' (GCC quotes it with a backtick) and ld returned 1 exit status. Add a definition below main and it links.

Multiple definition: two object files both define the same external name. The classic cause is a variable definition in a header:

C
/* settings.h - WRONG */
int max_users = 100;        /* a definition: every .c that includes this gets one */
TEXT
/usr/bin/ld: b.o:(.data+0x0): multiple definition of `max_users'; a.o:(.data+0x0): first defined here
collect2: error: ld returned 1 exit status

The fix is the extern pattern: declare in the header, define in exactly one .c file. (Before GCC 10, an uninitialized int max_users; in a header often linked anyway because of "common" symbols; GCC 10 and later default to -fno-common, which makes it an error too. Don't rely on the old behavior.) A function defined in a header has the same problem unless it's static inline.

Mismatched declarations are the sneakiest problem, because the linker matches names only, not types. If a.c defines long total(int n) and b.c declares int total(int n) by hand, everything links and then behaves unpredictably (undefined behavior). The cure is the rule you've already seen: declare each function in one header, and include that header in both the file that defines it and every file that uses it, so the compiler checks them against each other.

Organizing a real project

A typical small C project looks like this:

TEXT
weather/
โ”œโ”€โ”€ Makefile
โ”œโ”€โ”€ include/
โ”‚   โ””โ”€โ”€ temp_stats.h      public headers
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ main.c
โ”‚   โ”œโ”€โ”€ temp_stats.c
โ”‚   โ”œโ”€โ”€ csv_reader.c
โ”‚   โ””โ”€โ”€ csv_reader.h      private header, used only inside src/
โ””โ”€โ”€ tests/
    โ””โ”€โ”€ test_temp_stats.c
Terminal
gcc -std=c17 -Wall -Wextra -Iinclude src/*.c -o weather

-Iinclude adds a directory to the search path for #include "..." and <...>. Quoted includes search the current file's directory first, then the -I paths; angle-bracket includes are meant for system and library headers. Compiling every file on every change gets slow quickly, which is exactly what a Makefile fixes:

MAKE
CC     = gcc
CFLAGS = -std=c17 -Wall -Wextra -Iinclude

weather: src/main.o src/temp_stats.o src/csv_reader.o
	$(CC) $^ -o $@

src/%.o: src/%.c include/temp_stats.h
	$(CC) $(CFLAGS) -c $< -o $@

With this file, make rebuilds only the object files whose source or header changed, then relinks. The next lesson explains every line and introduces CMake.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where should int request_count = 0; go if three source files need the variable?

    There must be exactly one definition. The header's extern declaration lets the other files refer to it. Putting the definition in the header causes a multiple-definition link error; static copies would be three separate variables.
  2. 2. What does static mean on a function defined at file scope?

    At file scope, static gives a name internal linkage. Other translation units can't call it, and they can reuse the name.
  3. 3. A program compiles, but linking fails with: undefined reference to 'parse_line'. What is the most likely cause?

    The declaration was enough for the compiler, but the linker found no object file containing the definition. Add the file to the build, or fix the spelling.
  4. 4. What problem do include guards solve?

    When a header reaches a file twice (often through other headers), the guard makes the second copy expand to nothing, so types aren't defined twice.
  5. 5. With an opaque type (struct counter; in the header), what can code outside counter.c do?

    An incomplete type can be used through pointers only. Its size and members are unknown outside the file that completes it.

Summary

  • A module is a header (.h, the interface) plus a source file (.c, the implementation); each .c file with its includes is one translation unit, compiled separately and then linked.
  • Headers hold prototypes, shared types, macros, extern declarations and static inline functions; they never define variables or ordinary functions.
  • Include your own header first in its .c file, make headers include what they use, and protect every header with an include guard.
  • Functions and globals have external linkage by default; static at file scope makes them private. Mark everything outside the interface static.
  • Share a global variable with extern in the header and one definition in a .c file.
  • Opaque types (incomplete structs used through pointers) hide a module's data layout completely.
  • "Undefined reference" means a missing definition; "multiple definition" means two; mismatched hand-written declarations link silently, so always share prototypes through headers.

Next: Build Tools: Make and CMake, which turn the compile-and-link steps into a fast, repeatable build.