Sub topic 8
Dev, build and target-specific dependencies
What you need first
This chapter assumes you can already:
- Create a project with
cargo new. - Add a crate to the
[dependencies]table, by hand or withcargo add. - Read a SemVer requirement such as
"1". - Run
cargo buildandcargo test.
Everything under [dependencies] is compiled into your final program. Some crates are not needed there. A test helper has no place in a release binary. A C compiler wrapper that runs before your code is built is not part of the program either. Some crates only make sense on one operating system. Cargo has separate tables for these cases.
The three kinds of dependency tables
| Table | Used by | Compiled for | Passed on to crates that depend on yours |
|---|---|---|---|
| `[dependencies]` | Your library or binary code | The target platform | Yes |
| `[dev-dependencies]` | Tests, examples and benchmarks | The target platform | No |
| `[build-dependencies]` | The `build.rs` build script | The host machine | No |
The target is the platform your program will run on. The host is the machine running the compiler. They are usually the same, but they differ when you cross-compile, for example when you build for a Raspberry Pi from a laptop.
Dev-dependencies
A dev-dependency is a crate you need only while developing. Typical examples are assertion helpers, mocking libraries, benchmark harnesses and test-data generators.
Add one with --dev:
cargo add --dev pretty_assertionsCargo writes a new table in Cargo.toml:
[dev-dependencies]
pretty_assertions = "1"The requirement syntax is the same as in [dependencies]. You can also use features, default-features, path, git and package.
Here is a library that uses the crate in its unit tests. Put it in src/lib.rs:
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn adds_two_numbers() {
assert_eq!(add(2, 2), 4);
}
}pretty_assertions::assert_eq! prints a colored diff when two values differ. It replaces the standard macro of the same name inside the test module.
Cargo compiles dev-dependencies only for these targets:
cargo testcargo bench- Examples, which are built by
cargo testand bycargo build --examples cargo check --testsandcargo check --all-targets
A plain cargo build or cargo run skips them. This keeps compile times shorter and the release binary smaller.
If you import a dev-dependency from normal code, cargo build fails with an "unresolved import" error. That is the signal that the crate belongs in [dependencies].
Dev-dependencies are not inherited
Suppose crate app depends on your crate mylib. Cargo builds mylib with its normal dependencies. It ignores mylib's dev-dependencies. Your test helpers do not appear in the dependency tree of your users, and they do not affect version resolution for them.
Same crate in two tables
You can list one crate in both [dependencies] and [dev-dependencies]. This is useful when tests need extra features:
[dependencies]
serde = "1"
[dev-dependencies]
serde = { version = "1", features = ["derive"] }When you run cargo test, the features from both entries are combined. When you run cargo build, only the normal entry applies. With the modern feature resolver (see the callout later in this chapter), a dev-dependency's features do not leak into non-test builds.
Build-dependencies
A build script is a Rust file named build.rs in the package root. Cargo compiles and runs it before it compiles your package. Build scripts commonly:
- Compile bundled C code.
- Generate Rust source files.
- Detect system libraries.
The build script is its own small program, so it has its own dependency table. Your package code cannot use these crates.
Add one with --build:
cargo add --build cc[build-dependencies]
cc = "1"The cc crate drives the system C compiler. This example needs a C compiler installed (gcc, clang or MSVC), and unsafe extern blocks need Rust 1.82 or newer.
build.rs:
fn main() {
cc::Build::new().file("src/answer.c").compile("answer");
println!("cargo::rerun-if-changed=src/answer.c");
}src/answer.c:
int answer(void) {
return 42;
}src/main.rs:
unsafe extern "C" {
fn answer() -> i32;
}
fn main() {
let value = unsafe { answer() };
println!("{value}");
}Running cargo run prints 42. The cargo::rerun-if-changed line tells Cargo to rerun the script only when the C file changes. Without it, Cargo reruns the script whenever any file in the package changes. The cargo:: form needs Rust 1.77 or newer. Older toolchains use cargo:.
Build scripts and procedural macros run on the host, so Cargo compiles their dependencies for the host. When you cross-compile, cc is built for your laptop and main.rs is built for the other target.
Target-specific dependencies
Some crates only compile or only make sense on certain platforms. Put them in a table whose name includes the platform:
[target.'cfg(windows)'.dependencies]
winapi = { version = "0.3", features = ["winuser"] }
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[target.x86_64-pc-windows-gnu.dependencies]
winapi = "0.3"
[target.'cfg(target_os = "linux")'.dev-dependencies]
procfs = "0.17"There are two ways to name the platform:
- A full target triple, such as
x86_64-pc-windows-gnu. This matches exactly one target. - A
cfg(...)expression, such ascfg(windows),cfg(unix),cfg(target_os = "linux")orcfg(target_arch = "aarch64"). You can combine them withall(...),any(...)andnot(...).
Put single quotes around a cfg(...) key in TOML. The key contains parentheses, spaces and double quotes, so it must be quoted.
The same tables exist for each kind of dependency: [target.<platform>.dependencies], [target.<platform>.dev-dependencies] and [target.<platform>.build-dependencies].
You can also create the entry from the command line:
cargo add --target 'cfg(windows)' winapi --features winuserPair the dependency with matching conditional code in Rust:
#[cfg(unix)]
fn os_name() -> &'static str {
"a Unix-like system"
}
#[cfg(windows)]
fn os_name() -> &'static str {
"Windows"
}
fn main() {
println!("running on {}", os_name());
}On Windows, Cargo does not build libc. On Linux, it does not build winapi.
What cfg can and cannot express
The cfg in a [target.…] table describes the platform. It cannot depend on Cargo features, on whether you build in release mode, or on cfg(test). If a dependency should exist only when a feature is enabled, declare it with optional = true and tie it to a feature. Features are covered in an earlier chapter.
Cargo.lock still contains everything
Cargo.lock records the resolved versions of all platforms' dependencies, including crates you are not building right now. The lock file therefore does not change between your Windows and Linux machines. Cargo downloads and compiles only the crates needed for the current target.
Inspecting dependency kinds with cargo tree
cargo tree can filter by edge kind with -e (short for --edges):
cargo tree -e normal
cargo tree -e dev
cargo tree -e build
cargo tree -e no-dev
cargo tree --target all-e normalshows only normal dependencies.-e devand-e buildadd the dev and build edges.-e no-devshows everything except dev-dependencies.--target allshows dependencies for every platform, not just the current one.
By default cargo tree shows normal, build and dev edges for the current target. Use -e no-dev to see roughly what a release build contains.
Common mistakes
| Symptom | Cause | Fix |
|---|---|---|
| `cargo build` says a crate is an unresolved import, but `cargo test` works | The crate is in `[dev-dependencies]` but used in normal code | Move it to `[dependencies]` |
| `build.rs` cannot find a crate | The crate is only in `[dependencies]` | Add it to `[build-dependencies]` |
| Your program cannot use a crate that `build.rs` uses | Build-dependencies are not visible to package code | Also add it to `[dependencies]` if you need it in both places |
| The `Cargo.toml` fails to parse | A `cfg(...)` table key is unquoted | Wrap the key in single quotes |
| A Windows-only crate is missing on Windows | The platform is spelled wrong in the `cfg` | Use `cfg(windows)`, or `cfg(target_os = "windows")` |
| The release binary is large | A test-only crate sits in `[dependencies]` | Move it to `[dev-dependencies]` |
Removing dependencies
cargo remove takes the same flags as cargo add, so it removes from the right table:
cargo remove --dev pretty_assertions
cargo remove --build cc
cargo remove --target 'cfg(windows)' winapiWithout a flag, cargo remove foo looks only in [dependencies].
Putting it together
A package that uses all three kinds might have this manifest:
[package]
name = "demo"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = { version = "1", features = ["derive"] }
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[dev-dependencies]
pretty_assertions = "1"
[build-dependencies]
cc = "1"Each table answers one question: where is this crate needed, and on which platforms? Ask it before you add a crate. Put the crate in the narrowest table that fits.
Exercise
Your crate has tempfile under [dev-dependencies]. A teammate adds use tempfile::tempdir; to src/main.rs and runs cargo test, which passes. cargo build --release then fails. Why, and what are two valid ways to fix it?
Show answer
cargo test compiles dev-dependencies, so the import resolves. cargo build --release does not, so the import is unresolved. Fix 1: move tempfile to [dependencies] if the program really needs it at runtime. Fix 2: keep it a dev-dependency and move the use of tempfile into test code, such as a #[cfg(test)] module or a file under tests/.
Exercise
Write the Cargo.toml entry that adds libc version 0.2 only on Unix-like systems, then give the cargo add command that produces it.
Show answer
Entry: [target.'cfg(unix)'.dependencies] followed by libc = "0.2". Command: cargo add --target 'cfg(unix)' libc.
Exercise
Which command shows the dependencies of your package for all platforms, leaving out dev-dependencies?
Show answer
cargo tree -e no-dev --target all