cargo build: Compile Your Rust Package and Its Dependencies
Think of `cargo build` as your project's general contractor. It reads the `Cargo.toml` blueprint to compile your package and all its dependencies. A common footgun is forgetting it only builds libraries and binaries by default; use `--tests` for test targets.
WHY IT EXISTS Manually compiling a project with dependencies is tedious. You have to find and download dependencies, pass the right files to the compiler in the correct order, and manage different build configurations (like for tests or examples). cargo build was created to automate this entire process based on a single manifest file, Cargo.toml.
THE MENTAL MODEL cargo build is a project manager, not just a compiler wrapper. It reads your Cargo.toml file as a set of instructions. Based on these instructions, it resolves the full dependency graph, downloads any missing crates, and then orchestrates the Rust compiler (rustc) to build everything in the correct order, placing the final output in the target/ directory.
HOW IT WORKS When you run cargo build, Cargo first identifies the package(s) to build. By default, this is the package in the current directory. It then selects which parts of that package—called targets—to compile. By default, it only builds the library and binary targets. You can override this with flags like --tests to build test targets or --example <name> for a specific example. Finally, it resolves features, activating default features unless told otherwise, and invokes rustc for each compilation unit.
WHEN TO USE IT Use cargo build during your main development loop to check for compilation errors. Use it to produce a debug executable for local testing. In a multi-package project (a workspace), use cargo build --workspace to ensure all packages compile correctly. Use target-selection flags like --bin my_app to speed up compilation by only building the specific part of the project you're working on.
WHEN NOT TO USE IT cargo build only compiles code; it doesn't run it. To compile and immediately execute your code, use other commands. For a binary, use cargo run. For tests, use cargo test. For benchmarks, use cargo bench. These commands will build the necessary code first and then execute it. For production-ready, optimized binaries, you should use cargo build --release.
ONE CANONICAL EXAMPLE Imagine your project has a library and two separate binaries, server and cli. To compile only the cli binary and none of the other targets, saving significant time, you would run: cargo build --bin cli. Cargo will still compile any dependencies the cli binary needs, but it will skip compiling the server binary and the library if it's not a dependency.
Read the original → doc.rust-lang.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.