23.5 Building and Running Projects

As discussed in Section 23.2.2, cargo build compiles your project, and cargo run compiles and then executes it. 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 is compiled, Cargo caches the result. Subsequent builds reuse the cached artifact as long as the dependency version and features remain unchanged in Cargo.lock. This avoids recompiling external crates repeatedly.
  • Incremental Compilation: When you modify your own crate’s source code, Cargo attempts to recompile only the changed parts and their dependents, rather than the entire crate. This is most effective in debug mode but also applies to release builds.

These mechanisms significantly reduce build times during typical development workflows.

23.5.2 Cross-Compilation

Cargo can compile code 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 project for that target
cargo build --target armv7-unknown-linux-gnueabihf

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