Linking multiple object files
What you'll learn: How the linker combines separate machine-code files into a single, functional program.
The Assembly Line
In C, large programs are rarely written in one massive file. Instead, we split code into several .c files. When you compile these, the compiler doesn't immediately create a program you can run. Instead, it turns each source file into an object file (ending in .o or .obj).
Think of object files like pieces of a Lego set. The "engine" is in one box, and the "wheels" are in another. They are manufactured separately, but they aren't a "car" until someone snaps them together. That "someone" is the Linker.
Connecting the Dots
When you call a function in main.c that is actually defined in physics.c, the compiler leaves a placeholder. It essentially says, "I don't know where the calculate_gravity function is yet, but I trust the linker to find it later."
If you try to run the compiler on just one file, it will complain about "undefined references." Linking is the final step of the build process that resolves these references by stitching the addresses of functions and variables across all your object files.
// main.c
void greet(); // Promise: This exists somewhere!
int main() {
greet();
return 0;
}
// functions.c
#include <stdio.h>
void greet() {
printf("Hello from another file!");
}
How to Link
To turn these into a program, you tell the compiler to compile both files and link them together. Using a tool like GCC, it looks like this:
gcc main.c functions.c -o my_program
Behind the scenes, the computer creates main.o and functions.o. The linker then looks at main.o, sees the request for greet(), finds the actual code for greet() inside functions.o, and patches the two together into the final my_program executable.
If you forgot to include functions.c, the linker would throw an error because it found a "call" but no "destination."
Key takeaway
Linking is the "glue" phase that combines separate object files into one executable by resolving function calls and variable references between them.