Summary - Compiler basics
- C course
- Expert
- Lesson 18/47
- 5 min
Combine lexer, parser and AST to write a calculator language.
Summary - Compiler basics
This group covered the five stages of a small compiler: the lexer splits the source into tokens, the parser builds a tree from tokens, the AST carries the code structure, codegen emits instructions and the symbol table stores identifiers.
Each stage takes the previous one's output. The lexer, parser and codegen stay modular with separate functions. This is the core skeleton for writing a compiler in C. You'll now write a mini task that combines the five stages and shows each output on screen.
Practice Print compiler stages
Define void print_stage(const char *stage, const char *output) with body printf("%s -> %s\n", stage, output);. In main call it for five stages: ("lexer", "tokens"), ("parser", "ast"), ("ast", "tree"), ("codegen", "asm"), ("symbol_table", "names").
Starter code
#include <stdio.h>
// Define print_stage function
// Print five stages: lexer, parser, ast, codegen, symbol_table
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
void print_stage(const char *stage, const char *output) {
printf("%s -> %s\n", stage, output);
}
int main(void) {
print_stage("lexer", "tokens");
print_stage("parser", "ast");
print_stage("ast", "tree");
print_stage("codegen", "asm");
print_stage("symbol_table", "names");
return 0;
}Expected output
lexer -> tokens parser -> ast ast -> tree codegen -> asm symbol_table -> names
Compiler basics done
Congratulations! You've finished the compiler basics. You can now lay out a tool that splits source into tokens, builds a tree and emits instructions. You know the order of the five stages and each one's output.
The next group moves to security: buffer overflow, stack canary, ASLR, format string and safe functions. You'll see the common mistakes C programs make and the modern compiler protections. What you learned here is needed both to write safe code and to understand compiler output.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the order of compiler stages?
- parser → lexer → codegen
- lexer → parser → codegen Correct answer
- codegen → lexer → parser
- parser → codegen → lexer
Explanation: First the lexer, then the parser, finally codegen.
2 Match five stages to their output
| Term | Meaning |
|---|---|
lexer |
tokens |
parser |
tree |
ast |
structure |
codegen |
instructions |
symbol_table |
names |