liveBook · Manning

Compiler

As explained in Rust in Action: Systems programming concepts and techniques

A compiler is a program that translates source code into executable or lower-level code while checking it against the language's rules.

A compiler turns source code into machine code and handles the bookkeeping needed to make it runnable by the operating system and CPU. Rust’s compiler is called rustc. section 2.1.1

Compilation does more than produce an executable:

  • The compiler checks Rust’s rules before a program can run. Its strictness can catch problems during development rather than leaving them to cause a crash for users. section 1.8.3
  • It optimizes a program’s size and speed. Rust also uses static method dispatch by default, giving the compiler opportunities to reduce call costs. section 1.7.1

Compile one file

Save a Rust program with a main() function as ok.rs. In a shell, run rustc ok.rs, then run the executable it creates. A successful compilation prints nothing; running this example prints OK. section 2.1.1

$ rustc ok.rs 
$ ./ok           #1
OK
#1 For Windows, include the .exe filename extension (for example, ok.exe).

The commands show the distinction between compiling a file and running the executable produced from it. section 2.1.1

For a whole Rust crate, cargo manages the project, while rustc manages compilation. Running cargo run compiles and runs a project; cargo run --release produces an optimized release build. section 1.13 section 1.5

How Rust in Action: Systems programming concepts and techniques covers it

How deep it goes
Explains the compiler’s job and walks through single-file compilation, without detailing its internal stages.
Examples
Demonstrates rustc ok.rs followed by running ./ok, and contrasts Cargo development and release runs.
What it assumes
Starts with a small program containing main() and supplies the file-saving and shell commands needed to compile it.
What you can do after
Apply it via rustc to compile a single Rust file and run its executable.
How it connects
Connects compilation to machine code, operating systems, CPUs, optimization, static dispatch, and Cargo.

Also explained in

Compare how 9 books explain compiler →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust in Action: Systems programming concepts and techniques. The section links point to the parts of the book it draws on.