Sub topic 2
Incremental Compilation and What Invalidates It
Assume you know basic Rust ownership, Cargo commands, and Cargo.toml. This chapter focuses on changes that force work to be repeated.
Incremental compilation and invalidation
Incremental compilation stores intermediate results in the target directory. When you edit a small function, rustc can reuse unchanged results instead of compiling the entire crate again.
A change can invalidate more work when it affects:
- A public type or function signature used by other modules.
- A Cargo feature, dependency version, or build configuration.
- A
build.rsscript or one of its inputs. - A procedural macro invocation.
- Compiler flags, the Rust toolchain, or the target platform.
Keep incremental compilation enabled in development. Avoid deleting target during normal iteration. Use cargo check when you only need type checking and borrow checking; it skips producing a runnable binary and usually avoids much of the linking cost.
Trim dependencies and features
Every dependency can add parsing, type checking, code generation, build scripts, or linking work. Features can pull in additional modules and transitive dependencies.
Prefer the smallest feature set that satisfies your project:
[dependencies]
serde = { version = "1", default-features = false, features = ["derive"] }Use cargo tree -e features to find enabled features and unexpected dependency paths. Remove unused direct dependencies, then measure again. A dependency that saves runtime code but adds a large compile-time cost may be a poor development choice.
Proc macros and build scripts
Procedural macros are Rust programs that run during compilation. Derive-heavy crates can therefore add noticeable compile time. Build scripts (build.rs) also run before compilation and may rerun when their inputs change.
Declare inputs explicitly with cargo:rerun-if-changed=... so unrelated file edits do not rerun the script. Keep generated work small and avoid doing network or expensive discovery operations in a build script.
> callout tip > Measure before removing macros. A macro may reduce application code and improve correctness even when it adds compile time.
Switching to a faster linker
For native Linux builds, lld or mold can shorten the final link step. Install the linker separately, then configure Cargo:
# .cargo/config.toml
[target.x86_64-unknown-linux-gnu]
linker = "clang"
rustflags = ["-C", "link-arg=-fuse-ld=lld"]This setting is target-specific. Confirm that the linker is installed and matches your target before applying it in CI.
Exercise
Why can changing a public function signature rebuild more code than changing its function body?
Show answer
Dependents may need to be recompiled because their type checking and generated code rely on the public interface.