- How to structure a modular C program across multiple source files
- Where to use
externfor shared state andstaticfor private state - How
autolocals andregisterhints fit into real functions - Why modular design and storage-class choices go hand-in-hand
- How the linker ties shared globals together across modules
Why Combine All Four Storage Classes?
Textbook examples usually show one storage class at a time — a static counter here, an extern variable there. Real programs use them all together. A well-designed module needs shared state (that other modules can see), private state (that they cannot), fast-changing locals (that live only for a call), and — sometimes — hot loop variables where a register hint or careful allocation matters.
This tutorial builds a tiny two-module project: a statistics module that accumulates totals and counts, and a sequence module that generates unique IDs. A main file drives both. Each module picks the right storage class for each variable. The result is a realistic, modular C design that shows all four storage classes cooperating instead of competing.
💡 In one line: extern shares, static hides, auto scopes, register hints. Good modular design uses each for exactly what it's good at.
Role of Each Storage Class
| Storage Class | Where Used Here | Why |
|---|---|---|
extern | Shared counters in shared_state.h, defined in stats.c | Both modules read and write the same totals |
static | Private helpers and file-scope state inside stats.c and sequence.c | Module internals stay invisible to other modules |
auto | Ordinary locals in every function (default) | Short-lived temporaries — allocated on the stack |
register | Hot loop index inside a batch-update loop | A hint to the compiler in the tight inner loop |
Complete Multi-File C Project
Four files: one header for shared state, one for the statistics module, one for the sequence module, and a main file. Save them in the same directory, then compile together.
File 1: shared_state.h — the extern declarations
#ifndef SHARED_STATE_H
#define SHARED_STATE_H
/* extern: defined once in stats.c, visible to every module */
extern long long g_total;
extern int g_calls;
/* Statistics module API */
void stats_add(int value);
void stats_report(void);
/* Sequence module API */
int sequence_next(void);
int sequence_next_batch(int count);
#endif /* SHARED_STATE_H */
File 2: stats.c — owns the shared state and keeps some private
#include <stdio.h>
#include "shared_state.h"
/* THE definitions — the only place these globals are created */
long long g_total = 0;
int g_calls = 0;
/* static file-scope: module-private, invisible outside stats.c */
static int stats_peak = 0;
/* static helper: also invisible outside this file */
static int update_peak(int value) {
if (value > stats_peak) {
stats_peak = value;
}
return stats_peak;
}
void stats_add(int value) {
auto int local_copy = value; /* auto: lives only for this call */
g_total += local_copy; /* extern global: shared */
g_calls++; /* extern global: shared */
update_peak(local_copy); /* private helper via static */
}
void stats_report(void) {
printf("[stats] calls=%d total=%lld peak=%d\n",
g_calls, g_total, stats_peak);
}
File 3: sequence.c — static IDs plus a register-hinted loop
#include <stdio.h>
#include "shared_state.h"
/* static local: private counter, persists across calls */
int sequence_next(void) {
static int id = 0;
id++;
return id;
}
/* register hint on the hot inner-loop index */
int sequence_next_batch(int count) {
register int i;
int last = 0;
for (i = 0; i < count; i++) {
last = sequence_next();
}
return last; /* return the final ID of the batch */
}
File 4: main.c — drives both modules
#include <stdio.h>
#include "shared_state.h"
int main(void) {
int i;
int last_id;
printf("=== Phase 1: feed values into stats ===\n");
for (i = 0; i < 4; i++) {
stats_add((i + 1) * 10); /* auto loop var i */
}
stats_report();
printf("\n=== Phase 2: generate a batch of unique IDs ===\n");
last_id = sequence_next_batch(3);
printf("[sequence] last ID in batch = %d\n", last_id);
printf("\n=== Phase 3: one more stats update, then final report ===\n");
stats_add(50);
stats_report();
printf("\n=== Final check: shared state seen from main ===\n");
printf("g_total = %lld, g_calls = %d\n", g_total, g_calls);
return 0;
}
Compile and run
gcc main.c stats.c sequence.c -o modular_demo
./modular_demo
Program Output
=== Phase 1: feed values into stats ===
[stats] calls=4 total=100 peak=40
=== Phase 2: generate a batch of unique IDs ===
[sequence] last ID in batch = 3
=== Phase 3: one more stats update, then final report ===
[stats] calls=5 total=150 peak=50
=== Final check: shared state seen from main ===
g_total = 150, g_calls = 5
Every number here tells a story about a storage class. calls and total come from extern globals defined in stats.c — and the final block proves main.c sees exactly the same values. peak comes from a static file-scope variable that no other file can touch. The loop variable i is a plain auto local. And sequence_next_batch's inner-loop index is register-hinted.
Step-by-Step Explanation
Let's see how each storage class plays its role, and why this split matters.
1. extern for genuinely shared state:
/* shared_state.h */
extern long long g_total;
extern int g_calls;
These declarations are included by every module. They tell the compiler "somebody else owns these" — no memory is allocated. The definitions live in stats.c, and the linker binds every reference to those single addresses. stats_add() increments g_calls; main() prints g_calls; both observe the same object.
2. static for module-private state:
static int stats_peak = 0;
static int update_peak(int value) { ... }
Both stats_peak and update_peak are invisible outside stats.c. That's exactly what a module wants: internals hidden, public API exposed. If another file tried to reference stats_peak, the compiler would reject it — no extern declaration exists, so the name is unknown. This is the standard C technique for encapsulation in a language without classes.
3. static local for a persistent private counter:
int sequence_next(void) {
static int id = 0;
id++;
return id;
}
The generator's counter must survive between calls, but nobody outside the function should touch it. A static local is the exact fit: lifetime = whole program, scope = this function only. Notice that sequence_next_batch calls sequence_next repeatedly, and the counter keeps climbing (1, 2, 3) across three separate calls. Nothing had to reset it.
4. auto for short-lived locals:
auto int local_copy = value;
for (int i = 0; i < 4; i++) { ... }
Writing auto explicitly is optional — every unmarked local is automatic by default. But it's included here for teaching purposes. local_copy is created fresh on each call to stats_add() and destroyed when the call returns. That's the right behaviour for a temporary: no baggage, no stale value, no accidental sharing.
5. register as a hint in a hot loop:
register int i;
for (i = 0; i < count; i++) { ... }
On modern compilers this makes no measurable difference — the optimizer allocates i to a register on its own. But it's a reasonable signal of intent, and on small embedded CPUs with simplistic compilers it still matters. The key lesson from the earlier timing tutorial applies here: register is a hint, not a guarantee, and shouldn't be relied on for performance.
6. The linker sees the big picture:
When you build with gcc main.c stats.c sequence.c -o modular_demo, three separate object files are produced and linked. The linker matches the extern declarations in shared_state.h — which are seen in main.o, stats.o, and sequence.o — to the one real definition in stats.o. If you accidentally added a second definition of g_total somewhere, the build would fail with a multiple-definition error. That's a good failure — the toolchain catches the bug for you.
🎯 Remember this: Modular C isn't about any single storage class — it's about choosing the right one for each piece of state. Share what must be shared (extern), hide what should be private (static), scope short-lived work (auto), and hint the compiler only where it might help (register).
Frequently Asked Questions
1. Why not just put everything in one .c file?
For small programs, that's fine. The moment code grows beyond a few hundred lines — or when multiple people work on it — modular files reduce conflicts and make the structure obvious. Each module gets a clear responsibility, a header that documents its public API, and a source file that holds its private state. Storage classes are the language tools that make this split clean.
2. Should every module use extern globals?
No — that leads to spaghetti code. Most state should be passed as function arguments or bundled into a context struct. Use extern sparingly, for a small number of genuinely cross-cutting values (configuration, shared counters, logging handles). If you find yourself needing many shared globals, that's a signal to reconsider the module boundaries.
3. How is static used here different from static global?
Both have static storage duration. The static int stats_peak at file scope has internal linkage — visible throughout stats.c, invisible to other files. The static int id inside sequence_next has block scope — visible only inside that function. Both are useful; which one you pick depends on whether the state needs to be shared among functions within the same file.
4. Is register deprecated in modern C?
Not formally deprecated, but practically inert on modern desktop compilers. GCC and Clang treat it mostly as a no-op under optimization. It's still sometimes used in embedded code targeting compilers with minimal optimization, and it remains legal in the language. The general advice: don't rely on it, but it won't hurt.
5. How do I unit-test a module that uses extern globals?
Shared globals make unit testing harder because tests can affect each other through the shared state. Options: (a) provide a reset function that clears the globals between tests, (b) refactor to pass a context struct so each test creates its own instance, (c) use link-time substitution (link your test against a stub of the module that doesn't use the global). Option (b) is the cleanest long-term.
6. Does the header need include guards?
Absolutely. Without #ifndef SHARED_STATE_H / #define / #endif, a file that includes the header twice would see duplicate declarations — harmless for extern, but problematic for struct definitions, typedefs, and macros. The include guard makes the header safe to include from any file, any number of times. All production C headers use them.
💡 Tip: As your project grows, keep the module's public API small. Every extern global and every public function is a promise to keep the interface stable. Private helpers marked static let you refactor freely without touching other modules.