This is a reference implementation for the book Writing a C Compiler, a hands-on guide to writing your own compiler for a substantial subset of the C programming language.
This implementation is a work in progress, so please fork with caution!
You’ll need:
- Rust ≥ 1.79.0 (latest stable recommended)
- Cargo, installed with Rustup
- A C toolchain (GCC or Clang) to assemble and link the output programs
- (Optional) llvm-tools-preview if you plan to emit LLVM IR or link through llc
If you’re new to Rust, install the toolchain using rustup:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | shConfirm installation:
rustc --version
cargo --version- Ch 1–3: Lexer, parser, expression handling
- Ch 4–5: Statement parsing, functions
- Ch 6–7: Locals, stack management
- Ch 8–10: Control flow, conditionals, loops
- Ch 11–12: Pointers, arrays, structs
- Ch 13+: Codegen optimizations, calling conventions, ABI compliance
This puts the executable at target/release/fcc
git clone https://github.com/princemuel/fcc.git # check out the repo
cd fcc
cargo build --releaseFor a faster iteration
cargo run -- path/to/source.cFCC uses Rust’s built-in test framework for unit and integration tests. There are a handful of unit tests, can be run with this command
cargo testFor compiler verification against the official Writing a C Compiler Test Suite
git clone https://github.com/nlsandler/writing-a-c-compiler-tests.git
cd writing-a-c-compiler-tests./test_compiler --check-setup # make sure you meet all the system requirements./test_compiler ~/path/to/fcc/target/release -- --chapter 4Assume we have this source file at ~/hello.c
int puts(char *c);
int main(void) {
puts("Hello, world!");
}To compile and run it
$ target/release/fcc ~/hello.c -o ~/hello
$ ~/hello
Hello, world!cargo run -- examples/return_42.cIf you use the LLVM backend
cargo run --release --backend=llvm examples/hello.cTo emit LLVM IR (if enabled) instead of machine code
cargo run -- --emit-llvm examples/fib.cMIT License © 2025
Based on the book Writing a C Compiler by Nora Sandler.