Cargo, crates and the build
In C++, the language standard says nothing about how code is built. Every project chooses a build system, a package manager, a directory layout and a way to find headers and libraries, and connecting two projects means reconciling their choices. Rust settled all of this from the start. One tool, Cargo, builds every Rust project, and every library is published the same way. This is the biggest day-to-day productivity difference you will notice.
This chapter covers:
- crates, the unit of compilation, and why there are no headers,
Cargo.tomlcompared withCMakeLists.txt,- dependencies, versions and the lock file,
- features, the replacement for
#ifdefand CMake options, - build profiles and optimization settings,
- what gets linked, and how,
- workspaces for large codebases.
Crates: the unit of compilation
In C++ the compiler sees one translation unit at a time: a .cpp file
with all its headers pasted in. The linker stitches the object files together
afterwards, and headers exist so each translation unit can know the
declarations of the others.
In Rust the compiler sees a whole crate at a time. A crate is a tree of modules (source files) compiled together into one library or executable. Since the compiler sees every file of the crate at once, there is nothing to declare in advance:
- no header files and no forward declarations,
- no include guards or
#pragma once, - functions and types can be used before they are defined, in any order,
- no One Definition Rule to violate, because each item is defined in exactly one place.
When crate game depends on crate math, the compiler reads math's
compiled metadata (an .rlib file), which contains its public API, generic
function bodies and inlinable code. That metadata plays the role of headers,
but it is generated by the compiler, so it can never disagree with the
implementation.
| C++ | Rust |
|---|---|
Translation unit (.cpp + headers) | Crate (a tree of .rs modules) |
| Header file | Nothing; the compiler reads dependency metadata |
Static library .a/.lib | Library crate (.rlib) |
| Executable target | Binary crate |
| CMake project | Cargo package |
| vcpkg / Conan package | Crate on crates.io |
A package is a directory with a Cargo.toml. It contains at most one
library crate (src/lib.rs) and any number of binary crates (src/main.rs,
src/bin/*.rs), plus tests, examples and benchmarks.
Cargo.toml
CMakeLists.txt
cmake_minimum_required(VERSION 3.20)
project(viewer VERSION 0.1.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
find_package(glfw3 3.3 REQUIRED)
find_package(glm REQUIRED)
option(VIEWER_HOT_RELOAD "Hot reload" OFF)
add_executable(viewer src/main.cpp
src/renderer.cpp)
target_link_libraries(viewer glfw glm::glm)
if(VIEWER_HOT_RELOAD)
target_compile_definitions(viewer
PRIVATE HOT_RELOAD=1)
endif()
Cargo.toml
[package]
name = "viewer"
version = "0.1.0"
edition = "2024"
[dependencies]
winit = "0.30"
glam = "0.30"
[features]
hot-reload = []
There is no list of source files: Cargo finds src/main.rs and the compiler
follows mod declarations from there. The edition selects a language
edition (2015, 2018, 2021, 2024), similar to -std=c++17, except that crates of
different editions link together freely. An edition can change syntax and
defaults, but never the ABI or the standard library.
Dependencies and versions
Dependencies come from crates.io by default, but can also come from Git or a local path:
[dependencies]
glam = "0.30" # crates.io, semver-compatible with 0.30.x
serde = { version = "1", features = ["derive"] }
ash = { version = "0.38", default-features = false, features = ["loaded"] }
my-math = { path = "../my-math" } # a local crate
imgui-backend = { git = "https://github.com/example/imgui-backend", rev = "4f2a1c9" }
[dev-dependencies] # only for tests, examples and benchmarks
criterion = "0.5"
[build-dependencies] # only for build.rs
cc = "1"
Version requirements follow semantic versioning: "0.30"
means "any 0.30.x", and "1.4" means "1.4.0 or newer, but below 2.0". The
first build resolves exact versions and records them in Cargo.lock. Commit
Cargo.lock for applications so every build uses identical dependencies;
cargo update moves to newer compatible versions deliberately.
Cargo downloads, builds and links dependencies from source with your compiler
and your flags. There are no prebuilt binaries to mismatch: no "this library
was built with a different _ITERATOR_DEBUG_LEVEL", no runtime library
conflicts, no missing .lib for your compiler version.
If two of your dependencies need incompatible versions of a crate (say rand
0.8 and rand 0.9), Cargo builds and links both. Symbols are mangled with a
hash of the crate's identity, so there is no clash. Types from the two
versions are distinct types, so you cannot accidentally pass one to the other.
In C++ the same situation is an ODR violation that the linker may or may not
catch.
Features: conditional compilation
Features are named, additive switches declared by a crate, used where C++ uses preprocessor definitions and CMake options:
[features]
default = ["png"]
png = ["dep:png"] # enabling "png" pulls in the optional dependency
hot-reload = []
vulkan = ["dep:ash"]
[dependencies]
png = { version = "0.17", optional = true }
ash = { version = "0.38", optional = true }
In code, #[cfg(...)] includes or removes an item, like #if but on whole
syntax items rather than text:
#[cfg(feature = "hot-reload")] fn watch_shaders() { println!("watching shader directory"); } #[cfg(not(feature = "hot-reload"))] fn watch_shaders() {} #[cfg(target_os = "windows")] const PLATFORM: &str = "windows"; #[cfg(not(target_os = "windows"))] const PLATFORM: &str = "not windows"; fn main() { watch_shaders(); if cfg!(debug_assertions) { // a boolean, for ordinary `if`s println!("debug build on {PLATFORM}"); } }
cargo build --features hot-reload enables a feature, and
--no-default-features turns off the defaults. Features are meant to be
additive: enabling one must not break code that does not use it, because if
two crates in your build enable different features of a shared dependency,
Cargo compiles that dependency once with the union of both.
Build profiles
Cargo has a dev profile (cargo build) and a release profile
(cargo build --release). You can tune them, and you can tune them per
dependency, which is invaluable for games:
[profile.dev]
opt-level = 1 # light optimization for your own code: still debuggable
[profile.dev.package."*"]
opt-level = 3 # fully optimize all dependencies, even in dev builds
[profile.release]
lto = "thin" # link-time optimization across crates
codegen-units = 1 # better optimization, slower build
debug = "line-tables-only" # keep symbols for profilers and crash reports
panic = "abort" # no unwinding tables; a panic kills the process
[profile.profiling] # a custom profile: cargo build --profile profiling
inherits = "release"
debug = true
| CMake / compiler flag | Cargo setting |
|---|---|
-O0 / -O2 / -O3 | opt-level = 0 / 2 / 3 |
-Os / -Oz | opt-level = "s" / "z" |
-g | debug = true |
-flto=thin | lto = "thin" |
-DNDEBUG | debug-assertions = false (the default in release) |
-fno-exceptions | panic = "abort" (roughly) |
-march=native | RUSTFLAGS="-C target-cpu=native" or .cargo/config.toml |
debug_assertions controls debug_assert! and integer overflow checks.
assert! is always on, like an assert that survives NDEBUG.
What ends up in the binary
By default, Rust links all Rust code statically. A Rust executable contains
your code, every dependency and the parts of the standard library you use. It
links dynamically only to the platform's C runtime and system libraries
(libc, kernel32.dll, and so on), plus whatever C libraries you link
explicitly.
Library crates can be built in other shapes by setting crate-type:
[lib]
crate-type = ["rlib", "cdylib", "staticlib"]
crate-type | Produces | Use it for |
|---|---|---|
rlib (default) | Rust library with metadata | Other Rust crates |
staticlib | .a / .lib with a C ABI | Linking Rust into a C or C++ program |
cdylib | .so / .dll / .dylib with a C ABI | Plugins, loading from C/C++, WebAssembly |
dylib | Rust-ABI shared library | Rarely; see hot reloading |
Generic functions are compiled into the crate that uses them, with the
concrete types filled in, exactly as templates are instantiated in each
translation unit that uses them. Non-generic functions are compiled once, in
their own crate, unless marked #[inline].
build.rs: the custom command
A build.rs file at the package root is a Rust program that Cargo compiles and
runs before compiling your crate. It plays the role of CMake custom commands:
compiling C code, generating bindings, compiling shaders, emitting link flags.
// build.rs
fn main() {
// Rebuild only when the shader changes.
println!("cargo::rerun-if-changed=shaders/triangle.wgsl");
// Link a system library.
println!("cargo::rustc-link-lib=dylib=vulkan");
// Compile a C file into the crate with the `cc` build dependency.
cc::Build::new().file("native/stb_image.c").compile("stb_image");
}
The FFI chapter and the assets
chapter use build.rs in earnest.
Workspaces
A large project is a workspace: several packages that share one
Cargo.lock, one target/ directory and common settings. It is the
equivalent of a top-level CMakeLists.txt with add_subdirectory.
engine/
├── Cargo.toml # [workspace]
├── crates/
│ ├── engine-math/
│ ├── engine-render/
│ ├── engine-ecs/
│ └── engine-assets/
└── apps/
├── editor/
└── game/
# engine/Cargo.toml
[workspace]
members = ["crates/*", "apps/*"]
resolver = "3"
[workspace.package]
edition = "2024"
version = "0.1.0"
[workspace.dependencies] # pick versions once, use them everywhere
glam = "0.30"
ash = "0.38"
# engine/crates/engine-render/Cargo.toml
[package]
name = "engine-render"
edition.workspace = true
version.workspace = true
[dependencies]
glam.workspace = true
ash.workspace = true
engine-math = { path = "../engine-math" }
Splitting a project into crates matters more than splitting C++ into libraries, because the crate is the unit of parallel and incremental compilation. A single huge crate compiles serially at the front end; a graph of mid-sized crates builds in parallel. The modules chapter discusses how to draw those boundaries.
Rust compile times are comparable to template-heavy C++. The levers you have:
- Split the engine into crates along stable boundaries (math, ECS, renderer, assets), so a change rebuilds only what depends on it.
- Use
cargo checkwhile editing; it skips code generation. - Optimize dependencies in dev builds (shown above) so you can run debug builds at playable frame rates.
- On Linux, use a faster linker (
moldorlld); linking is often the slowest step of an incremental build. - Share build caches across machines with
sccache, the Rust analogue ofccache.
Summary
| C++ | Rust |
|---|---|
| CMake, Meson, Bazel, MSBuild… | Cargo |
| vcpkg, Conan, git submodules | crates.io and Cargo |
| Headers + translation units | Crates; no headers |
#ifdef / CMake options | Features and #[cfg] |
| Build types (Debug/Release/RelWithDebInfo) | Profiles, tunable per dependency |
| Custom commands | build.rs |
add_subdirectory | Workspaces |
Exercises
- Create a workspace with a library crate
geom(aVec2struct with anaddfunction) and a binary crate that uses it. Run it withcargo run -p <name>. - Add a feature
doubletogeomthat makesaddprint a message. Build the binary with and without--features geom/double. - Run
cargo treein a project with a few dependencies and find a crate that appears more than once. Why is it there twice?