Tiny C Compiler (subset of C17).
Warning
This project is experimental and not intended for production use.
Note
Currently only emits gas_x86-64_linux assembly. Other backends may be added in the future.
-
int
- Function definitions and declarations (supports types listed above)
-
int main(void) { ... }
- Local variables
- Global variables
- Lexical block scoping
- Shadowing
- Internal and external linkage (
externandstatic) - Static/automatic storage duration (local/file-scope variables and
staticlocals)
-
return - Expression statements
-
if/else -
goto/labeled statements - Compound statements (
{ ... }) -
for/do/while -
break/continue -
switch -
default/caselabels - Empty statements (
;)
- Integer constants
- Variables
- Unary operators:
-,!,~,++(postfix and prefix),--(postfix and prefix) - Binary operators:
+,-,*,/,% - Binary bitwise operators:
&,|,^ - Binary shift operators:
<<,>> - Binary logical operators:
&&,|| - Comparison operators:
<,<=,>,>=,==,!= - Assignment operators:
=,+=,-=,*=,/=,%=,&=,|=,^=,<<=,>>= - Conditional (ternary) operator:
? : - Function calls
- Constant Folding
- Unreachable Code Elimination
- Copy Propagation
- Dead Store Elimination
- Register Allocation
- Register Coalescing
Compiler is tested using an external test suite: nlsandler/writing-a-c-compiler-tests/.
Clone the repository and build the project:
git clone https://github.com/hmunye/cc2.git
cd cc2
cargo build --releaseDisplay help and available flags:
./target/release/cc2 --helpOptionally, install globally:
cargo install --path .
cc2 --help# 1. Preprocess separately using `GCC` or `cpp`:
gcc -E hello_world.c -o hello_world.i
# or
cpp hello_world.c -o hello_world.i
# 2. Compile the preprocessed file to assembly:
./target/release/cc2 hello_world.i
# 3a. Use `GCC` to assemble and link to an executable:
gcc hello_world.s -o hello_world
# 3b. Or manually invoke assembler and linker:
as hello_world.s -o hello_world.o # assemble to object file
ld hello_world.o -o hello_world # link to produce executable
# -----------------------------
# Shortcut: Use the -p flag
# -----------------------------
#
# The `-p` flag preprocesses and compiles in a single step.
# This is just a convenience; no separate preprocessed file is needed.
./target/release/cc2 -p hello_world.c
# Assemble and link as usual:
gcc hello_world.s -o hello_worldThis project is licensed under the MIT License.