rust-lang/cargo · error · anyhow::Error

extra arguments to `{}` can only be passed to one target, co

Error message

extra arguments to `{}` can only be passed to one target, consider filtering
the package by passing, e.g., `--lib` or `--bin NAME` to specify a single target

What it means

Thrown when extra rustc/rustdoc arguments (supplied via target_rustc_args / target_rustdoc_args, e.g. `cargo rustc -- <ARGS>` or `cargo rustdoc -- <ARGS>`) are present but the resolved build has more than one root unit. Cargo can only forward raw compiler flags to a single target, so it requires the selection to be narrowed. Guarded at src/ops/cargo_compile/mod.rs:580-588.

Source

Thrown at src/ops/cargo_compile/mod.rs:582

                platform: target_data.short_name(&unit.kind).to_owned(),
                index,
                features: unit
                    .features
                    .iter()
                    .map(|s| s.as_str().to_owned())
                    .collect(),
                requested: root_unit_indexes.contains(&index),
                dependencies,
            });
        }
        let elapsed = ws.gctx().invocation_instant().elapsed().as_secs_f64();
        logger.log(LogMessage::UnitGraphFinished { elapsed });
    }

    let mut extra_compiler_args = HashMap::default();
    if let Some(args) = extra_args {
        if root_units.len() != 1 {
            anyhow::bail!(
                "extra arguments to `{}` can only be passed to one \
                 target, consider filtering\nthe package by passing, \
                 e.g., `--lib` or `--bin NAME` to specify a single target",
                extra_args_name
            );
        }
        extra_compiler_args.insert(root_units[0].clone(), args);
    }

    for unit in root_units
        .iter()
        .filter(|unit| unit.mode.is_doc() || unit.mode.is_doc_test())
        .filter(|unit| rustdoc_document_private_items || unit.target.is_bin())
    {
        // Add `--document-private-items` rustdoc flag if requested or if
        // the target is a binary. Binary crates get their private items
        // documented by default.
        let mut args = vec!["--document-private-items".into()];

View on GitHub (pinned to 0e07a15537)

Solutions

  1. Add a single-target filter: `--lib`, `--bin NAME`, `--example NAME`, `--test NAME`, or `--bench NAME`.
  2. Scope to one package with `-p <pkg>` plus one of the above target filters.
  3. Drop the extra rustc args if you actually meant to build all targets.

Example fix

# before
cargo rustc -- --cfg my_flag        # multiple root units -> error

# after
cargo rustc --lib -- --cfg my_flag   # single target, ok
Defensive patterns

Strategy: validation

Validate before calling

// When forwarding rustc/rustdoc args, ensure exactly one target is selected.
fn single_target_filter(spec: &Packages, lib: bool, bin: Option<&str>) -> bool {
    lib || bin.is_some()
}
// CLI: if extra args present, require --lib or --bin NAME before invoking compile.

Type guard

fn has_single_target_filter(opts: &ops::CompileOptions) -> bool {
    use cargo::core::compiler::CompileMode;
    opts.build_config.mode != CompileMode::Every
        && (opts.spec.len() == 1 /* simplified */)
}

Try / catch

if let Err(e) = ops::compile(ws, &opts) {
    if e.to_string().contains("extra arguments") {
        eprintln!("pass --lib or --bin NAME to select a single target");
    }
    return Err(e);
}

Prevention

When it happens

Trigger: Calling `cargo rustc -- --cfg foo` (or `cargo rustdoc --`) when the default package selection yields multiple root units (e.g. a workspace default with several crates, or a package with lib+bin+tests). The check `root_units.len() != 1` triggers the bail.

Common situations: Running `cargo rustc -- -Zunstable-options` in a multi-crate workspace without -p/--lib/--bin. Forgetting to add a target filter when scripting rustc flags. A package that builds lib and bin by default.

Related errors


AI-assisted analysis of rust-lang/cargo@0e07a15537 (2026-08-06). Data as JSON: /data/errors/9eff207533697de0.json. Report an issue: GitHub.