Skip to content
StudyFame

Multi-File Programs in C

Real programs are not one giant file. A game might have player.c, enemy.c and score.c, each doing one job. Splitting code this way makes it easier to read, test and reuse, and lets several people work at once.

In this lesson you will split a program into several files, share a global variable between files with extern, keep things private with static, and learn the compile-then-link process with gcc -c.

What You Will Learn

  • Why programs are split into multiple source files.
  • The difference between a declaration and a definition.
  • How extern shares a variable between files.
  • How static keeps a variable or function private to one file.
  • How separate compilation and linking work.
  • The errors you get when something is missing or defined twice.

Multi-File Programs in C Explained

Exam definition: A multi-file program consists of several source files that are compiled separately into object files and then linked into one executable. The extern keyword declares a variable or function that is defined in another file, without creating storage for it. A global variable or function declared static has internal linkage: it is visible only inside the file where it is defined.

Memory trick: A global variable is a shared water tank on the roof. Only one file builds the tank (the definition: int visits = 0;). Every other file just runs a pipe to it (extern int visits;). static puts a lock on the tank so only its own building can use it.

Declaration vs definition

DeclarationDefinition
Meaning"This name exists, with this type""Create it here"
MemoryNoneAllocated
How many timesAny number of times (in a header)Exactly once in the whole program
Variable exampleextern int visits;int visits = 0;
Function examplevoid add_visit(void);void add_visit(void) { ... }

Syntax of extern and static

/* data.c : definitions (memory is created here, once) */
int total = 0;               /* global, visible to other files   */
static int secret = 42;      /* global, but private to data.c    */
static void helper(void) {}  /* function private to data.c       */

/* data.h : declarations shared with other files */
extern int total;            /* "total is defined somewhere else" */
void update(void);           /* functions are extern by default   */

Example 1: Sharing a Global Variable with extern

counter.h

#ifndef COUNTER_H
#define COUNTER_H

extern int visits;        /* declaration: defined in counter.c */

void add_visit(void);
int total_visits(void);

#endif

counter.c

#include "counter.h"

int visits = 0;           /* definition: memory is created here */
static int calls = 0;     /* private: no other file can see it  */

void add_visit(void)
{
    visits++;
    calls++;
}

int total_visits(void)
{
    return visits;
}

site.c

#include <stdio.h>
#include "counter.h"

int main(void)
{
    add_visit();
    add_visit();
    add_visit();
    printf("visits (through function) = %d\n", total_visits());

    visits += 10;          /* direct access, thanks to extern */
    printf("visits (direct, extern)   = %d\n", visits);
    return 0;
}
gcc site.c counter.c -o site
./site

Output

visits (through function) = 3
visits (direct, extern)   = 13

Code Explanation

  1. int visits = 0; in counter.c is the only definition. The memory for visits lives there.
  2. extern int visits; in counter.h is a declaration. Because site.c includes the header, site.c may use visits directly.
  3. add_visit() is called 3 times, so visits becomes 3.
  4. visits += 10; in site.c changes the same variable (there is only one), so it becomes 13.
  5. static int calls is private to counter.c. Writing calls++ in site.c would give an "undeclared" or "undefined reference" error.

How Separate Compilation and Linking Work

Each .c file is compiled on its own into an object file (.o). The linker then connects every name used in one file with its definition in another:

gcc -c counter.c        -> counter.o   (contains visits, add_visit, total_visits)
gcc -c site.c           -> site.o      (uses visits, add_visit, total_visits)
gcc site.o counter.o -o site           (linker joins them)

site.o says: "I need visits"   ──►  counter.o says: "visits is here"
  • If you change only site.c, you recompile only site.c and link again. In big projects this saves a lot of time; tools like make do it automatically.
  • Missing definition → linker error: undefined reference to 'visits'.
  • Two definitions (int visits = 0; in two files) → linker error: multiple definition of 'visits'.

Example 2: Hiding Helpers with static

#ifndef SHAPES_H
#define SHAPES_H

double area_circle(double r);
double area_square(double side);
int shapes_created(void);

#endif
#include "shapes.h"

static const double PI_VALUE = 3.14159;   /* private constant */
static int created = 0;                   /* private counter  */

static double square(double x)            /* private helper   */
{
    return x * x;
}

double area_circle(double r)
{
    created++;
    return PI_VALUE * square(r);
}

double area_square(double side)
{
    created++;
    return square(side);
}

int shapes_created(void)
{
    return created;
}
#include <stdio.h>
#include "shapes.h"

int main(void)
{
    printf("Circle r=2 : %.2f\n", area_circle(2));
    printf("Square s=5 : %.2f\n", area_square(5));
    printf("Shapes made: %d\n", shapes_created());
    return 0;
}

Output

Circle r=2 : 12.57
Square s=5 : 25.00
Shapes made: 2
  • square(), PI_VALUE and created are static: other files can't use them and their names can't clash with names in other files. Another file could have its own square().
  • geometry.c reads the counter only through shapes_created(). This is called encapsulation: data is protected, and only chosen functions are public.
  • Rule of thumb: make every global variable and helper function static unless another file really needs it.

Important Points to Remember

  • Define a global variable in one .c file; declare it with extern in a header.
  • extern = declaration only, no memory.
  • Functions are extern by default; a prototype is enough to use them from another file.
  • static at file level = private to that file (internal linkage).
  • Compile each file with gcc -c, then link the .o files, or do both with gcc a.c b.c.
  • "undefined reference" = no definition; "multiple definition" = defined twice.

Common Mistakes Beginners Make

MistakeWhat happensFix
int visits = 0; in the header"multiple definition" when two files include itHeader: extern int visits;, one .c file: the definition
extern int visits = 0; in a headerAn initializer makes it a definitionNo initializer with extern in headers
Forgetting to compile counter.c"undefined reference to add_visit"gcc site.c counter.c
Using a static function from another fileLinker can't find itRemove static, or add a public wrapper
Too many global variablesHard-to-find bugs; any file can change themPrefer static globals with access functions

Multiple Source Files Practice Questions

  1. What is the difference between a declaration and a definition?
  2. What does the extern keyword do?
  3. What does static mean for a global variable or function?
  4. What causes the error "undefined reference to x"?
  5. Write the commands to compile a.c and b.c separately and link them.
Show answers
  1. A declaration introduces a name and type without memory; a definition creates it (allocates memory / gives the function body). Definitions happen once.
  2. It declares a variable or function that is defined in another file, without allocating memory.
  3. It gives internal linkage: the name is visible only inside that source file.
  4. The linker found a use of x but no definition (the file defining it wasn't compiled/linked, or it was static).
  5. gcc -c a.c, gcc -c b.c, gcc a.o b.o -o app.

Coding Exercise

Create scores.h / scores.c with a global int score_count (shared with extern) and a private static int score_sum. Provide add_score(int) and average_score(void). In record.c, add the scores 70, 85 and 90, then print the count (directly) and the average.

Show solution
#ifndef SCORES_H
#define SCORES_H

extern int score_count;

void add_score(int s);
double average_score(void);

#endif
#include "scores.h"

int score_count = 0;
static int score_sum = 0;

void add_score(int s)
{
    score_sum += s;
    score_count++;
}

double average_score(void)
{
    return score_count ? (double)score_sum / score_count : 0.0;
}
#include <stdio.h>
#include "scores.h"

int main(void)
{
    add_score(70);
    add_score(85);
    add_score(90);
    printf("Scores added : %d\n", score_count);
    printf("Average score: %.2f\n", average_score());
    return 0;
}
Scores added : 3
Average score: 81.67

Quick Quiz: Multiple Source Files (MCQ)

  1. extern int x; is a:

    A) Definition   B) Declaration   C) Macro   D) Function

  2. A global variable declared static is visible:

    A) In every file   B) Only inside its own file   C) Only in main   D) Nowhere

  3. Which gcc option compiles without linking?

    A) -o   B) -E   C) -c   D) -g

  4. Defining the same global variable in two files causes:

    A) No problem   B) "multiple definition" error   C) A warning only   D) A run-time crash

  5. Functions in C are by default:

    A) static   B) extern   C) inline   D) private

Show answers
  1. B: a declaration.
  2. B: only inside its own file.
  3. C: -c.
  4. B: a "multiple definition" linker error.
  5. B: extern.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

externDeclares a name defined in another file
DefinitionCreates memory, exactly once
static (file level)Internal linkage: private to the file
Functionsextern by default
gcc -cCompile to .o without linking
undefined referenceNo definition found by the linker
multiple definitionDefined in two files

Frequently asked questions

What is the extern keyword in C?
It declares a variable or function defined in another file, so the current file can use it; no memory is allocated.
What is the difference between extern and static globals?
extern shares a global across files; static keeps it private to one file.
Why split a program into multiple files?
For organisation, reuse and teamwork, and so only changed files need recompiling.

Remember

  • One file builds the tank, others connect a pipe (extern).
  • static = lock it inside the file.

Next Topic

Next lesson: Bit Manipulation in C. You will use bitwise operators to set, clear, toggle and check individual bits.