Multiple modules
- C course
- Intermediate
- Lesson 63/116
- 5 min
Learn to combine multiple modules in one project.
Multiple modules
A big C project splits into modules. Each module has a .h and a .c file. For example vector.h/vector.c and matrix.h/matrix.c. main.c includes both headers and calls functions.
Compile: gcc -c vector.c and gcc -c matrix.c produce separate .o files, then gcc -o app main.o vector.o matrix.o links them. A Makefile automates these steps. Modular layout cuts compile time; only the changed module recompiles. This is the standard structure of real-world C projects.
Module design
A good module carries one responsibility. The vector module only does vector ops; matrix does matrix ops. The header exposes the public API; the .c hides implementation detail. static makes internal helpers invisible outside the file.
Dependencies between modules should be one-directional when possible. For example matrix may depend on vector, but not the other way. Circular dependency is a design smell; split modules. This discipline makes maintenance easier in big projects.
Practice Simulate a two-module program
Simulate two modules in one file: write int vec_add(int a, int b) { return a + b; } and int vec_mul(int a, int b) { return a * b; }. In int main(void) add printf("%d \n", vec_add(2, 3)); and printf("%d\n", vec_mul(4, 5));. Don't forget <stdio.h>.
Starter code
#include <stdio.h>
// Write vec_add and vec_mul
int main(void) {
// Call vec_add(2, 3) and vec_mul(4, 5) and print
return 0;
}Sample solution
#include <stdio.h>
int vec_add(int a, int b) {
return a + b;
}
int vec_mul(int a, int b) {
return a * b;
}
int main(void) {
printf("%d \n", vec_add(2, 3));
printf("%d\n", vec_mul(4, 5));
return 0;
}Expected output
5 20
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match module files
| Term | Meaning |
|---|---|
vector.h |
Vector declarations |
vector.c |
Vector definitions |
vector.o |
Compiled object |
main.c |
Program entry |
2 What does gcc -c do?
- Produces an executable
- Performs linking
- Includes headers
- Only compiles, makes .o Correct answer
Explanation: -c compiles only, no linking; leaves a .o file.
3 Complete the link command
gcc -o app main.o vector.o ____.o
gcc -o app main.o vector.o matrix.o
Explanation: Adding matrix.o links all modules.