Sub topic 7
Building, running, and checking with Cargo
This chapter covers the three commands you will run most often in a Rust project: cargo check, cargo build, and cargo run. It explains what each one does, where its output goes, and how to read the messages it prints. It assumes you have installed Rust with rustup, can run cargo --version in a terminal, and have created the hello_cargo project with cargo new. Debug and release builds, dependencies, and tests each get their own chapter, so they appear here only where they affect the commands.
The three commands and what each produces
Cargo does not compile code itself. It reads Cargo.toml, works out which crates to compile and in what order, and calls the compiler, rustc, for each one. The three commands differ in how far along that pipeline they go.
| Command | Runs `rustc` | Produces a binary | Runs your program | Typical use |
|---|---|---|---|---|
| `cargo check` | Yes, but stops after analysis | No | No | Fast feedback while editing |
| `cargo build` | Yes, through code generation and linking | Yes | No | Getting an executable to run yourself or ship |
| `cargo run` | Yes, same as build | Yes | Yes | Building and trying the program in one step |
Code generation and linking are the slow part of compiling. Parsing, name resolution, type checking, and borrow checking are comparatively quick. Because cargo check stops before code generation, it is often several times faster than cargo build on a large project. It still reports every error the compiler would find.
Running a project with cargo run
From the project directory, run:
cargo runOn a fresh hello_cargo project the output looks like this. Exact wording varies a little between Cargo versions.
Compiling hello_cargo v0.1.0 (/home/you/hello_cargo)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.45s
Running `target/debug/hello_cargo`
Hello, world!The lines before Hello, world! come from Cargo and go to standard error. The program's own output goes to standard output. This split matters when you redirect output. In cargo run > out.txt, only Hello, world! lands in out.txt, and the Cargo messages still show in the terminal.
Run it a second time and the Compiling line disappears. Cargo sees that no source file has changed since the last build, so it skips compilation and launches the existing binary. This is the incremental behavior you should expect from every Cargo command.
Passing arguments to your program
Cargo has its own flags, and your program has its own arguments. A bare -- separates them. Everything after it goes to your program.
Replace src/main.rs with this:
use std::env;
fn main() {
let args: Vec<String> = env::args().skip(1).collect();
if args.is_empty() {
println!("No arguments given.");
} else {
for (i, arg) in args.iter().enumerate() {
println!("argument {}: {}", i + 1, arg);
}
}
}Then run it:
cargo run -- alpha "two words"argument 1: alpha
argument 2: two wordsWithout the --, Cargo would try to interpret alpha as one of its own arguments and fail. Flags meant for Cargo go before the --. For example, cargo run --quiet -- alpha hides Cargo's status lines. -q is the short form of --quiet.
Building without running
cargo buildThis compiles the project and writes the executable to target/debug/. On Linux and macOS the file is target/debug/hello_cargo. On Windows it is target\debug\hello_cargo.exe. You can run it directly, without Cargo:
./target/debug/hello_cargoBuilding without running is useful when you want to hand the executable to another tool, such as a debugger. It is also useful when you want to confirm that the project compiles before a long-running program starts.
What is inside target
Cargo puts all of its generated files in the target directory at the project root, and never in src. After one build, target/debug holds:
- The executable, named after the package.
deps/, which holds the compiled pieces Cargo built for this project and its dependencies.incremental/, which holds data that letsrustcrecompile only what changed.build/and.fingerprint/, which hold build-script output and the records Cargo uses to decide whether something is out of date.
You never edit these files. Generated files do not belong in version control, and cargo new creates a .gitignore that excludes target. If the directory grows large or you suspect stale output, delete it with:
cargo cleanThe next build then starts from scratch.
Checking without building
cargo check Checking hello_cargo v0.1.0 (/home/you/hello_cargo)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.12sThe status word is Checking instead of Compiling, and no executable appears in target/debug. Cargo does write metadata files there so later checks stay fast.
Use cargo check in the loop of edit, check, fix. Reserve cargo build and cargo run for when you want to execute the program. Many editors run cargo check in the background to underline errors as you type.
Reading compiler output
Cargo passes the compiler's messages through unchanged, so learning to read them pays off in every command. Put this in src/main.rs:
fn main() {
let count: i32 = "three";
let unused = 5;
println!("{count}");
}Run cargo check. The output is similar to this, trimmed for space:
error[E0308]: mismatched types
--> src/main.rs:2:22
|
2 | let count: i32 = "three";
| --- ^^^^^^^ expected `i32`, found `&str`
| |
| expected due to this
warning: unused variable: `unused`
--> src/main.rs:3:9
|
3 | let unused = 5;
| ^^^^^^ help: if this is intentional, prefix it with an underscore: `_unused`
error: could not compile `hello_cargo` (bin "hello_cargo") due to 1 previous error; 1 warning emittedA few things to notice:
- Error codes.
E0308can be looked up withrustc --explain E0308, which prints a longer explanation with examples. - Locations.
src/main.rs:2:22is file, line, and column. Most terminals and editors let you click it. - Errors versus warnings. An error stops the build and no binary is produced. A warning does not stop it. The program still compiles and runs, but the warning usually points at something worth fixing.
- The summary line. It tells you how many errors and warnings there were. Fix the first error first, because later ones are sometimes consequences of it.
Fix the code by changing "three" to 3 and deleting the unused line. Then cargo check finishes cleanly.
Choosing what to build
A package can contain more than one target. A package with src/main.rs has one binary. You can add more binaries by placing files in src/bin/, for example src/bin/tool.rs. Each file becomes its own executable named after the file.
When there is more than one binary, cargo run needs to know which one you want:
cargo run --bin toolcargo build and cargo check build all targets by default. Select one with --bin NAME. In a package that has both src/lib.rs and src/main.rs, --lib selects the library. Library crates are covered in a later chapter.
Common errors and what they mean
The table lists the failures you are most likely to hit at this stage.
| Message or symptom | Likely cause | Fix |
|---|---|---|
| `could not find Cargo.toml in ... or any parent directory` | You are not inside a Cargo project | `cd` into the project directory, or create a project with `cargo new` |
| `error: linker 'cc' not found` | No C linker is installed | Install one, such as `build-essential` on Debian and Ubuntu, Xcode command line tools on macOS, or the Visual Studio C++ build tools on Windows |
| `error: a bin target must be available for cargo run` | The package has no `src/main.rs` and no binary target, for example a library-only project | Add a `main.rs`, or use `cargo test` or `cargo check` instead |
| `error: 'cargo run' could not determine which binary to run` | More than one binary exists | Pass `--bin NAME`, or set `default-run` in `Cargo.toml` |
| `Blocking waiting for file lock on build directory` | Another Cargo process is using the same `target` directory | Wait for it to finish, or stop the other process |
| Unexpected stale behavior after switching branches or toolchains | Cached build state in `target` | Run `cargo clean` and rebuild |
Debug builds are the default
Every command above used the dev profile, which is what Cargo uses unless you ask otherwise. It compiles quickly and includes debugging information, but it does not optimize the code, so the resulting program runs more slowly than it could. That is the right trade for development. Pass --release to cargo build or cargo run to get an optimized build, which is written to target/release instead. The next chapters explain the difference in detail.
A practical workflow
For day-to-day work, this loop covers most needs:
- Edit the code.
- Run
cargo checkuntil it reports no errors. - Run
cargo runto see the program behave. - Repeat.
Run cargo build when you need the executable itself. Run cargo clean only when you have a specific reason, because it discards all cached work.
Exercise
In a project with a src/main.rs that prints its command-line arguments, you run cargo run --quiet -- --verbose file.txt. Which of the two flags, --quiet and --verbose, is interpreted by Cargo, and which is received by your program? Also, after this command succeeds, which command would show you a compile error without producing a new executable?
Show answer
--quiet appears before the -- separator, so Cargo interprets it and hides its own status lines. --verbose appears after the --, so Cargo passes it to your program as an argument, along with file.txt. To see compile errors without producing a new executable, run cargo check, which type-checks the code and stops before code generation and linking.
Exercise
You run cargo run twice in a row without changing any files. The first run prints a Compiling line and the second does not. Why, and where is the executable that both runs launch?
Show answer
Cargo records which sources and settings produced the existing build. On the second run nothing has changed, so it skips compilation and launches the existing binary. That binary is at target/debug/hello_cargo (or target\debug\hello_cargo.exe on Windows), because the default profile is the debug one.