LinuxCommandLibrary

cargo-clean

Remove compiled artifacts

TLDR

Remove the entire target directory

$ cargo clean
copy

Remove documentation artifacts (the target/doc directory)
$ cargo clean --doc
copy

Remove release artifacts (the target/release directory)
$ cargo clean [[-r|--release]]
copy

Remove artifacts in the directory of the given profile (in this case, target/debug)
$ cargo clean --profile [dev]
copy

SYNOPSIS

cargo clean [OPTIONS]

PARAMETERS

--package SPEC...
    Clean only the specified packages (accepts package ID specifiers)

-p SPEC...
    Alias for --package

--doc
    Remove only target/doc directory (requires -p, --workspace, or --all)

--release
    Remove only target/release directory (requires -p, --workspace, or --all)

--workspace
    Clean all packages in the workspace

--all
    Alias for --workspace (deprecated)

-v
    Verbose output (-vv for very verbose, -vvv for max)

--verbose
    Equivalent to -v

-q, --quiet
    Suppress cargo log messages

--color WHEN
    WHEN is auto, always, or never

-j N, --jobs N
    Number of parallel jobs (defaults to CPU count)

--frozen
    Do not update lock files

--locked
    Require up-to-date lock file

--offline
    Operate without network access

-Z FLAGS
    Unstable nightly flags

DESCRIPTION

The cargo clean command is a key tool in the Cargo build system for Rust projects. It removes the contents of the target/ directory, where Cargo stores compiled binaries, intermediate artifacts, downloaded dependencies, and generated documentation. This is essential for freeing disk space, resolving corrupted builds, or ensuring a clean slate before distribution.

By default, cargo clean deletes everything in target/, forcing subsequent builds to compile from scratch. This can be time-consuming for large projects but guarantees reproducibility. Selective cleaning is possible with flags like --release (only release builds) or --doc (only docs). For workspaces, --workspace cleans all packages.

It's commonly used in CI/CD pipelines, after dependency updates, or when switching Rust versions. Note that it preserves the Cargo.lock file and project source code.

CAVEATS

Deletes build artifacts irreversibly; large projects rebuild slowly afterward. Does not remove Cargo.lock, .git, or source files. Selective flags like --release require package/workspace spec.

EXAMPLES

cargo clean
Removes entire target/.

cargo clean -p mypkg --release
Cleans release build for mypkg.

cargo clean --workspace --doc
Cleans docs in workspace.

WHEN TO USE

After toolchain changes, disk space issues, or mysterious linker errors. Pair with cargo build for fresh builds.

HISTORY

Introduced with Cargo in Rust 0.9 (2014). Evolved alongside Rust editions; workspace and selective cleaning added in Cargo 0.20+ (2017). Now integral to Rust 1.0+ toolchain for reproducible builds.

SEE ALSO

cargo(1), cargo-build(1), rustc(1), rustup(8)

Copied to clipboard