Compiling multiple .c files
What you'll learn: How to tell the C compiler to stitch together different source files into a single running program.
Why split things up?
As your programs grow, putting thousands of lines of code into a single main.c file becomes a nightmare to navigate. In the previous lessons, we learned how to use header files to share declarations. Now, we need to handle the actual "meat" of the code—the source files.
Think of a computer program like a Lego set. Instead of molding the entire spaceship out of one giant piece of plastic, Lego gives you individual bricks. If one brick is flawed, you only replace that brick, not the whole ship. In C, your .c files are those bricks.
The compilation process
When you have multiple files, like main.c and math_utils.c, you can't just compile one and hope for the best. You must tell the compiler about every source file involved in the project.
Suppose we have two files:
math_utils.c: Contains the logic for a function calledadd().main.c: Contains themain()function that callsadd().
To turn these into a program, the compiler performs a two-step dance. First, it translates each .c file into an "object file" (machine code snippets). Then, a tool called the linker stitches those snippets together into one final executable file.
The command line
If you are using a tool like GCC, you compile multiple files by listing them all in one command, separated by spaces:
gcc main.c math_utils.c -o my_program
Here is what is happening conceptually in your code:
// File: math_utils.c
// This file holds the actual logic
int add(int a, int b) {
return a + b;
}
// File: main.c
// This file uses the logic from elsewhere
#include <stdio.h>
#include "math_utils.h" // The header connects the two
int main() {
int result = add(5, 3);
printf("The sum is: %d\n", result);
return 0;
}
When you run the gcc command, the compiler looks at main.c, sees that it needs an add function, finds that function inside math_utils.c, and glues them together. If you forgot to include math_utils.c in the command, the linker would get confused and throw an "undefined reference" error because it couldn't find the instructions for add.
Key takeaway
To build a modular program, list every .c file in your project during the compilation command so the linker can join them into one executable.