C: Multi-File Programming
Multi-file programming is like team collaboration — declarations are contracts (header files), implementations are the work (source files), extern is a cross-department reference, and Makefile is the project schedule.
1. Why Multi-File
A single .c file is enough for small programs, but real projects have large codebases that need to be split by functionality into multiple files:
- Clear logic with well-defined responsibilities
- Faster compilation — changing one file only recompiles that file
- Code reuse — common modules can be shared across projects
- Team collaboration — different people own different modules
2. Writing Header Files
Header files (.h) contain declarations, and source files (.c) contain definitions. This is the most fundamental modularization rule in C.
(1) Header File Content
// Preprocessor directive
#ifndef MATH_UTILS_H
// Preprocessor directive
#define MATH_UTILS_H
// Function definition
int add(int a, int b);
// Function definition
int subtract(int a, int b);
// Function definition
double average(int *arr, int n);
// Preprocessor directive
#endif
(2) Source File Content
// Preprocessor directive
#include "math_utils.h"
// Function definition
int add(int a, int b) {
// Return result
return a + b;
}
// Function definition
int subtract(int a, int b) {
// Return result
return a - b;
}
// Function definition
double average(int *arr, int n) {
// Conditional check
if (n <= 0) return 0.0;
// Variable declaration
int sum = 0;
// For loop
for (int i = 0; i < n; i++) sum += arr[i];
// Return result
return (double)sum / n;
}
(3) Main Program
#include <stdio.h>
#include "math_utils.h"
int main(void) {
printf("3 + 5 = %d\n", add(3, 5));
printf("10 - 4 = %d\n", subtract(10, 4));
int scores[] = {80, 90, 75, 88};
printf("Average: %.1f\n", average(scores, 4));
return 0;
}
3. extern for Cross-File References
A global variable defined in one .c file can be accessed from other files using extern.
(1) Definition (in some .c file)
// Variable declaration
int g_count = 0;
(2) Declaration (in a header or another .c file)
extern int g_count;
extern tells the compiler "this variable is defined elsewhere — this is only a declaration," so no new space is allocated.
▶ Example
Project structure:
project/
├── counter.h
├── counter.c
└── main.c
counter.h:
// Preprocessor directive
#ifndef COUNTER_H
// Preprocessor directive
#define COUNTER_H
extern int g_count;
// Function definition
void increment(void);
// Function definition
int get_count(void);
// Preprocessor directive
#endif
counter.c:
#include "counter.h"
int g_count = 0;
void increment(void) {
g_count++;
}
int get_count(void) {
return g_count;
}
main.c:
// Preprocessor directive
#include <stdio.h>
// Preprocessor directive
#include "counter.h"
// Function definition
int main(void) {
increment();
increment();
increment();
// I/O operation
printf("count = %d\n", get_count());
// I/O operation
printf("g_count = %d\n", g_count);
// Return result
return 0;
}
count = 3
g_count = 3
extern declaration. extern int g_count = 0; may become a definition on some compilers, causing duplicate definition errors.
4. Multi-File Compilation Commands
(1) Compile Individually, Then Link
gcc -c counter.c -o counter.o
gcc -c main.c -o main.o
gcc counter.o main.o -o myapp
The -c flag compiles without linking, producing .o object files. All .o files are then linked into the final executable.
(2) Compile All at Once
gcc counter.c main.c -o myapp
Simple, but changing any file requires recompiling everything — not suitable for large projects.
main.c, you only need gcc -c main.c and then link, without recompiling counter.c.
5. Makefile Basics
Makefile automates compilation rules and only recompiles files that have been modified.
CC = gcc
CFLAGS = -Wall -g
myapp: main.o counter.o
$(CC) $(CFLAGS) main.o counter.o -o myapp
main.o: main.c counter.h
$(CC) $(CFLAGS) -c main.c -o main.o
counter.o: counter.c counter.h
$(CC) $(CFLAGS) -c counter.c -o counter.o
clean:
rm -f *.o myapp
Usage:
make
make clean
Makefile rule format:
target: dependencies
command
- Target: the file to generate
- Dependencies: files the target depends on — if any dependency is newer than the target, the command is re-executed
- Command: how to generate the target from the dependencies
6. Preventing Duplicate Inclusion
A header file may be included by multiple source files, and the same source file may indirectly include it multiple times. Without protection, duplicate declarations cause errors.
(1) Approach 1: Include Guard
// Preprocessor directive
#ifndef MYHEADER_H
// Preprocessor directive
#define MYHEADER_H
// Function definition
void my_func(void);
// Preprocessor directive
#endif
On first inclusion, MYHEADER_H is undefined, so the content is processed and the macro is defined. On subsequent inclusions, #ifndef evaluates to false and the entire content is skipped.
(2) Approach 2: #pragma once
// Preprocessor directive
#pragma once
// Function definition
void my_func(void);
Concise and supported by most compilers, but not part of the standard — theoretically less portable than include guards.
#pragma once is more concise; include guards are more standard. Pick one and use it consistently.
7. Header File Organization Principles
- Each
.cfile should have a corresponding.hfile with the same name .hfiles should only contain declarations, not definitions- The first line of a
.cfile should include its own.h(to verify declarations match definitions) - Headers must include duplicate-inclusion protection
externglobal variable declarations go in.h; definitions go in a specific.cfile
▶ Example 3: Static vs External Functions
▶ Try it Yourself// helpers.c
#include <stdio.h>
#include "helpers.h"
int global_counter = 0; // definition
static void secret_log() {
printf(" [secret internal log]\n");
}
void public_greet(const char *name) {
global_counter++;
printf("Hello, %s! (call #%d)\n", name, global_counter);
secret_log(); // only visible inside helpers.c
}
// main.c
#include "helpers.h"
int main() {
public_greet("Alice");
public_greet("Bob");
return 0;
}
编译:
gcc -c main.c helpers.c && gcc main.o helpers.o -o greet && ./greet输出:TEXTHello, Alice! (call #1) [secret internal log] Hello, Bob! (call #2) [secret internal log]
▶ Example 4: Traditional Include Guards
▶ Try it Yourself// math_tools.c
#include "math_tools.h"
double add(double a, double b) { // definition
return a + b;
}
double multiply(double a, double b) { // definition
return a * b;
}
// app.c
#include <stdio.h>
#include "math_tools.h" // includes the declaration only
int main() {
// Use the functions — definitions live in math_tools.c
printf("2.5 + 3.5 = %.1f\n", add(2.5, 3.5));
printf("2.5 * 3.5 = %.1f\n", multiply(2.5, 3.5));
return 0;
}
编译:
gcc -c math_tools.c -o math_tools.o && gcc -c app.c -o app.o && gcc math_tools.o app.o -o app && ./app输出:TEXT2.5 + 3.5 = 6.0 2.5 * 3.5 = 8.75
❓ FAQ
int global_count;. In every other .c file that needs it, declare with extern int global_count; — this tells the compiler the definition is elsewhere and the linker will resolve it. Declarations go in the shared header; the definition stays in one .c file.extern int count;); actual definitions belong in one .c file.#include <file.h> searches the compiler's standard include paths. #include "file.h" searches the current source file's directory first, then falls back to system paths. Use <> for system and third-party headers; use "" for your own project headers.📖 Summary
- Header files (.h) hold declarations, source files (.c) hold definitions — this separation is the foundation of modularization
externdeclares cross-file global variables and functions, telling the compiler "defined elsewhere"- Multi-file compilation should use "compile individually with -c, then link" — only recompile modified files
- Makefile automates compilation dependencies, avoiding the need to type long commands manually
- Prevent duplicate inclusion with include guards or
#pragma once
📝 Exercises
- Create a 3-file project:
string_utils.h,string_utils.c, andmain.c. Implement a string reversal function and a character-count function, then call and test them in main - Write a Makefile for exercise 1 that supports
maketo compile andmake cleanto clean up - Intentionally omit duplicate-inclusion protection in a header file, then
#includethe same header twice in main.c and observe the compilation error