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
externshares a variable between files. - How
statickeeps 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
| Declaration | Definition | |
|---|---|---|
| Meaning | "This name exists, with this type" | "Create it here" |
| Memory | None | Allocated |
| How many times | Any number of times (in a header) | Exactly once in the whole program |
| Variable example | extern int visits; | int visits = 0; |
| Function example | void 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
int visits = 0;in counter.c is the only definition. The memory forvisitslives there.extern int visits;in counter.h is a declaration. Because site.c includes the header, site.c may usevisitsdirectly.add_visit()is called 3 times, sovisitsbecomes 3.visits += 10;in site.c changes the same variable (there is only one), so it becomes 13.static int callsis private to counter.c. Writingcalls++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
makedo 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_VALUEandcreatedarestatic: other files can't use them and their names can't clash with names in other files. Another file could have its ownsquare().- 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
staticunless 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.
staticat file level = private to that file (internal linkage).- Compile each file with
gcc -c, then link the .o files, or do both withgcc a.c b.c. - "undefined reference" = no definition; "multiple definition" = defined twice.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
int visits = 0; in the header | "multiple definition" when two files include it | Header: extern int visits;, one .c file: the definition |
extern int visits = 0; in a header | An initializer makes it a definition | No 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 file | Linker can't find it | Remove static, or add a public wrapper |
| Too many global variables | Hard-to-find bugs; any file can change them | Prefer static globals with access functions |
Multiple Source Files Practice Questions
- What is the difference between a declaration and a definition?
- What does the
externkeyword do? - What does
staticmean for a global variable or function? - What causes the error "undefined reference to x"?
- Write the commands to compile a.c and b.c separately and link them.
Show answers
- A declaration introduces a name and type without memory; a definition creates it (allocates memory / gives the function body). Definitions happen once.
- It declares a variable or function that is defined in another file, without allocating memory.
- It gives internal linkage: the name is visible only inside that source file.
- The linker found a use of x but no definition (the file defining it wasn't compiled/linked, or it was static).
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)
-
extern int x;is a:A) Definition B) Declaration C) Macro D) Function
-
A global variable declared
staticis visible:A) In every file B) Only inside its own file C) Only in main D) Nowhere
-
Which gcc option compiles without linking?
A)
-oB)-EC)-cD)-g -
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
-
Functions in C are by default:
A) static B) extern C) inline D) private
Show answers
- B: a declaration.
- B: only inside its own file.
- C:
-c. - B: a "multiple definition" linker error.
- B: extern.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| extern | Declares a name defined in another file |
|---|---|
| Definition | Creates memory, exactly once |
| static (file level) | Internal linkage: private to the file |
| Functions | extern by default |
| gcc -c | Compile to .o without linking |
| undefined reference | No definition found by the linker |
| multiple definition | Defined 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.