Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

23.5 Building and Running Projects

As discussed in Section 23.2.2, cargo build compiles your package’s crates, and cargo run compiles and then executes the default binary crate. Both default to debug mode unless --release is specified.

23.5.1 Build Cache and Incremental Compilation

Cargo employs several caching mechanisms to speed up builds:

  • Dependency Caching: Once a specific version of a dependency package (and its contained crates) is compiled, Cargo caches the result. Subsequent builds reuse the cached artifact as long as the dependency package version and features remain unchanged in Cargo.lock. This avoids recompiling external packages repeatedly.
  • Incremental Compilation: When you modify your own package’s source code, Cargo attempts to recompile only the changed parts of your crates and their dependents, rather than the entire package.
    • Incremental compilation is enabled by default for debug builds (cargo build). This significantly speeds up compilation during typical development cycles by reusing intermediate artifacts from previous compilations for unchanged code sections.
    • For release builds (cargo build --release), incremental compilation is disabled by default. While it could potentially speed up release build times in some scenarios, it is often disabled because:
      • It can sometimes interfere with the more aggressive optimizations performed during release builds, potentially leading to slightly less optimal runtime performance or larger binary sizes.
      • The primary goal of a release build is the quality of the final artifact, and disabling incremental compilation ensures the compiler has the fullest scope for optimization without being constrained by previous partial compilation states.
    • You can explicitly control incremental compilation in Cargo.toml profiles if needed (e.g., [profile.dev] incremental = true), but the defaults are generally sensible.

These mechanisms significantly reduce build times during typical development workflows.

23.5.2 Cross-Compilation

Cargo can compile the crates within your package for different target architectures (e.g., ARM for Raspberry Pi from an x86 machine) using the --target flag. You first need to add the target via rustup:

# Add the ARMv7 Linux target
rustup target add armv7-unknown-linux-gnueabihf

# Build the package for that target
cargo build --target armv7-unknown-linux-gnueabihf

Cross-compilation might require setting up appropriate linkers for the target system.