Rust Code Compilation: Rustc vs Cargo | m1ss1On

m1ss1On
2 min readJul 10, 2024

--

We store our Rust code in files with .rs extension. There are two methods to compile this files. Rustc and Cargo.

The Rust code we will compile ↷

fn main {
println!("Hello, world!");
}

1) Compile with “Rustc”;

➙ It is the official compiler for Rust.
➙ It compiles Rust source code directly into executable binaries.
➙ It is a lower-level tool and is not usually used directly.
➙ It provides more control over the compilation process.

Let’s go to the directory where our main.rs ile is located and start compiling.

On Windows devices, our executable file will have an .exe extension.

~/m1ss1on/project/src>  rustc main.rs   // Compilation

~/m1ss1on/project/src> ./main // We run our compiled file.
Hello, world!

2) Compile with “Cargo”;

➙ Rust’s package manager and build system.
➙ It facilitates project management, dependency management and build operations.
➙ It has functions like creating new projects, running tests and creating documentation.
➙ It uses rustc in the background, but offers a more user-friendly interface.
➙ It is used more frequently by Rust developers on a daily basis.

In summary,rustc is the basic compiler, while cargo is a more comprehensive project management tool and is the preferred tool for most Rust developers.

Now let’s create a new cargo project using the cargo new <project name> command;

~/m1ss1on/project/src> cargo new medium
Creating binary (application) `medium` package
Adding `medium` as member of workspace at `/m1ss1on/project/medium`
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

The Cargo.toml file is the configuration file of your Rust projects. This file defines the basic information and dependencies of your project.

[package]
name = "medium"
version = "0.1.0"
edition = "2021"

[dependencies]

Commands we can use after creating the project;
cargo build: They compile the project.
cargo run: Compiles and runs the project.

~/m1ss1on/project/src> cargo run
Compiling medium v0.1.0 (/m1ss1on/project/medium)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.09s
Running `target/debug/medium`
Hello, world!

My Github

Sources:

--

--