Phase 0 · Module 2 of 4
From source to program: what the compiler actually does
GCC and Clang: compile, assemble, link · 12 min read
Typing gcc hello.c and getting a program feels like one step, but it is four, and knowing them explains half the error messages you will ever see in C. Let's run each step by hand.
// hello.c
#include <stdio.h>
#define GREETING "Hello, C"
int main(void) {
printf("%s!\n", GREETING);
return 0;
}1. Preprocess
$ gcc -E hello.c -o hello.i
$ tail -4 hello.i
int main(void) {
printf("%s!\n", "Hello, C");
return 0;
}The preprocessor handles every line starting with #. It pasted in the whole of stdio.h (hello.i is over 800 lines) and replaced GREETING with its text. The compiler proper never sees your macros, only the result.
2. Compile to assembly
$ gcc -S hello.c -o hello.s
$ grep call hello.s
call printf@PLTNow your C is assembly for your CPU. printf is just a name to call; the compiler doesn't know where it lives yet. (With optimisation on, compilers often swap a simple printf for puts, so don't be surprised to see that instead.)
3. Assemble into an object file
$ gcc -c hello.c -o hello.o
$ nm hello.o
0000000000000000 T main
U printfhello.o contains machine code. nm lists its symbols: main is defined here (T), and printf is undefined (U), an IOU to be paid by someone else.
4. Link
$ gcc hello.o -o hello
$ ./hello
Hello, C!The linker combines your object file with the C library, finds printf, and fixes up the call. Error messages like "undefined reference to ..." come from this step: something was declared and used, but never defined anywhere the linker could see.
Your everyday command
$ gcc -Wall -Wextra -std=c17 -g -o hello hello.c-Wall and -Wextra turn on warnings (treat them as errors in your head), -std=c17 picks the language standard, and -g adds debug information for GDB. You'll put this in a Makefile in the next module.
Try it
- Misspell printf as prinf and build. Which step fails, and what exactly does the message say?
- Delete the #include line and build with -Wall. What does the compiler warn about, and why does it still link?
In the full course you go from here through pointers and memory, data structures, processes and signals, to POSIX threads and network sockets, and finish by building a multi-threaded TCP key-value server.