Understanding .o and .obj files
What you'll learn: How your source code is transformed into intermediate "object files" before becoming a finished program.
The Half-Baked Program
When you write C code, you are creating a recipe. However, computers cannot "read" recipes; they only understand electricity and binary instructions. Between your text file (main.c) and your final app (main.exe), there is a crucial middle step: the Object File.
Depending on your operating system, these files end in .o (macOS/Linux) or .obj (Windows). Think of an object file as a "half-baked" version of your code. It has been translated into machine language that the CPU understands, but it isn’t a functional program yet because it hasn't been connected to other necessary pieces.
Why do they exist?
Imagine you are building a car. You don't forge the entire vehicle from a single block of steel. Instead, you build the engine, the doors, and the wheels separately.
In C, object files allow for Modular Compilation:
- You compile
engine.cintoengine.o. - You compile
wheels.cintowheels.o. - If you decide to change the color of the wheels, you only have to re-compile the wheels. You don't have to waste time re-building the engine.
What is inside them?
An object file contains "Machine Code" (binary) and a "Symbol Table." The symbol table is like a directory that says, "I have a function called 'StartEngine' located at this specific spot."
However, if main.o tries to call a function located in math.o, the object file just leaves a blank space with a sticky note saying, "I'll need someone to plug in the math logic here later."
// When you compile this to 'hello.o', the computer
// translates the logic to binary but leaves a "gap"
// for the printf function, which lives elsewhere.
#include <stdio.h>
int main() {
printf("Hello, World!");
return 0;
}
The Linker's Job
You cannot "run" a .o file. If you try to double-click it, nothing happens. To make a program, a tool called the Linker takes all your various .o files, stitches them together, fills in the "sticky note" gaps, and produces the final executable file.
Key takeaway
Object files (.o/.obj) are pieces of machine-readable code that act as the bridge between your human-written text and the final executable program.