🎓 A1Learner
🔍

Rust Target-Specific Dependencies

A target-specific dependency is a library attached to one target only. The rest of the program never sees a target-only library.

One library, one system family

This table adds flaglib only when the program is built for a Unix system:

[target.'cfg(unix)'.dependencies]
flaglib = { path = "../flaglib" }

Name the exact target instead

A target triple names one exact platform. This library is added only for 64-bit Windows:

[target.x86_64-pc-windows-msvc.dependencies]
winlib = { path = "../winlib" }

Match the table in your code

The cfg in the code must agree with the cfg in the table. On other systems, this line is not compiled at all:

#[cfg(unix)]
println!("flags: {}", flaglib::flags());

Check another target without building

cargo tree accepts a target too. On a Linux machine, this prints the Windows library list: winlib is there, and flaglib is gone:

cargo tree --target x86_64-pc-windows-msvc

Example

// Cargo.toml
// [target.'cfg(unix)'.dependencies]
// flaglib = { path = "../flaglib", features = ["red"] }
// [target.'cfg(windows)'.dependencies]
// winlib = { path = "../winlib" }
fn main() {
    #[cfg(unix)]
    println!("on unix, flaglib says: {}", flaglib::flags());

    #[cfg(windows)]
    println!("on windows: {}", winlib::name());
}

Key points

  • Target: one platform a program can be built for, named by a triple like x86_64-unknown-linux-gnu
  • Use a [target.<triple>.dependencies] table to add a library for one exact target only
  • Use a [target.'cfg(...)'.dependencies] table to add a library for a whole family, like cfg(unix) or cfg(windows)
  • The same cfg test must guard the code that uses the library, or the other targets fail to build
  • Use cargo tree --target <triple> to inspect another target's library list without building for it

In this example, the manifest asks for flaglib on Unix systems and winlib on Windows. The code matches each library with the same cfg test. On Linux, only the Unix line is compiled, and it prints red. The Windows line is left out of the program completely. It is not skipped at run time. It was never in the binary.

Note

Rust calls these target-specific dependencies.

They sit in the lockfile for every build.

But Cargo builds each one only for the targets that ask for it.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

Your program needs the winlib library on Windows only. Where does it belong?