Sub topic 2
Adding clap to your project
This chapter covers adding clap 4 to a Cargo project: which dependency lines to write, what each Cargo feature turns on, and how to check that the setup works. It assumes you can create and build a Cargo project and read a Cargo.toml file. Basic Rust (structs, Option, Result) is enough for the code.
Two crates, one dependency line
clap is a library, called a crate in Rust, that turns command-line text into Rust values. Most of its behavior is optional and controlled by Cargo features. A feature is a named switch in a crate's Cargo.toml that compiles extra code only when you ask for it.
The derive API is the style this tutorial uses first. In it you describe your CLI as a struct and clap generates the parsing code. It lives behind the derive feature. When you turn that feature on, clap pulls in a second crate, clap_derive, which contains the procedural macros (code that runs at compile time and writes Rust code for you). You never name clap_derive yourself. You only enable the feature on clap.
Creating the project
Start from a fresh binary project and let Cargo edit the manifest for you.
cargo new mycli
cd mycli
cargo add clap --features derive,envcargo add writes the dependency into Cargo.toml with the latest 4.x version. You can also edit the file by hand. This is the form the rest of the tutorial assumes:
[package]
name = "mycli"
version = "0.1.0"
edition = "2021"
description = "A small command-line tool built with clap"
[dependencies]
clap = { version = "4", features = ["derive", "env"] }
clap_complete = "4"Some details in this file matter later:
version = "4"means "any 4.x release". Cargo uses the newest compatible one and records the exact version inCargo.lock. CommitCargo.lockfor binary projects so every build uses the same clap.descriptionandversionin[package]feed the generated--helpand--versionoutput. The#[command(version, about)]attribute reads them at compile time.clap_completeis a separate crate for shell completion scripts. You don't need it until the completions chapter. Adding it now is harmless, but a project that doesn't generate completions can leave it out.
What each feature does
clap enables a set of default features. You add to them by listing more features.
| Feature | On by default | What it gives you |
|---|---|---|
| `std` | yes | Standard library support. |
| `help` | yes | The `--help` and `-h` output. |
| `usage` | yes | The "Usage:" line in help and error messages. |
| `error-context` | yes | Detail in error messages, such as the offending argument and value. |
| `suggestions` | yes | "Did you mean `--verbose`?" hints for typos. |
| `color` | yes | Colored help and error output when the terminal supports it. |
| `derive` | no | `#[derive(Parser)]`, `Subcommand`, `ValueEnum`, and the `#[arg(...)]` and `#[command(...)]` attributes. |
| `env` | no | The `env = "NAME"` argument attribute, which reads a value from an environment variable. |
| `cargo` | no | The `command!()` and `crate_version!()` macros for the builder API. |
| `wrap_help` | no | Wraps help text to the terminal width. |
| `unicode` | no | Better width calculation for non-ASCII help text. |
| `string` | no | Lets the builder API take owned `String` values for names and help text. |
For the derive API you need derive. You add env only if you use #[arg(env = "...")], which a later chapter covers. The other optional features are conveniences:
clap = { version = "4", features = ["derive", "env", "wrap_help"] }The cargo feature is not needed for #[command(version, about)]. The derive macros read the package metadata themselves. The feature only matters when you use the builder API's command!() macro.
Verify the setup
Replace src/main.rs with a small program that uses the derive macro, the env-free attributes, and the Cargo metadata:
use clap::Parser;
/// A starting point for a clap project.
#[derive(Parser, Debug)]
#[command(version, about)]
struct Cli {
/// Name to greet
#[arg(long, default_value = "world")]
name: String,
}
fn main() {
let cli = Cli::parse();
println!("Hello, {}!", cli.name);
}Run it three ways:
cargo run -- --name Ada
cargo run -- --version
cargo run -- --helpThe -- separates Cargo's own options from the arguments passed to your program. You should see output like this:
Hello, Ada!
mycli 0.1.0
A small command-line tool built with clap
Usage: mycli [OPTIONS]
Options:
--name <NAME> Name to greet [default: world]
-h, --help Print help
-V, --version Print versionThe program name, version, and description all came from Cargo.toml. If your [package] table has no description, the about line is simply absent.
Checking which features are active
Features combine across your whole dependency tree. If another crate you depend on enables a clap feature, it is on for you too. To see what is actually enabled, run:
cargo tree -i clap -e featuresThis prints the clap features and which crate requested each one. It is the quickest way to answer "why is this feature on?".
Common errors
Two setup mistakes cause most first-time failures.
- Missing
derive. If you writeuse clap::Parser;and#[derive(Parser)]but did not enablederive, the compiler typically reports that it cannot find the derive macroParserin this scope. The fix is to addfeatures = ["derive"]to the clap dependency. TheParsertrait is always available, which is why theuseline itself compiles. - Missing
env. If you write#[arg(env = "APP_TOKEN")]without theenvfeature, compilation fails with an error that theenvmethod does not exist onArg. Add"env"to the feature list.
A third problem shows up later. If clap and clap_complete are on different major versions, you get type errors about mismatched Command types, because each crate sees its own copy of clap's types. Keep both on 4.
Choosing a version requirement
"4" is a good default for an application. For a library that exposes clap types in its public API, consider a lower bound such as "4.4" if you need a feature added in that release, so downstream users get a clear resolution error instead of a confusing compile failure. clap also declares a minimum supported Rust version, so an old toolchain may fail to build a new 4.x release. Check the crate's rust-version field on crates.io if your build uses an older compiler.
Exercise
You add clap = "4" to Cargo.toml and write #[derive(Parser)] on a struct. The build fails with "cannot find derive macro Parser in this scope". What change fixes it, and which two package fields in Cargo.toml feed the output of --version and the description line of --help when you use #[command(version, about)]?
Show answer
Enable the derive feature: clap = { version = "4", features = ["derive"] }, or run cargo add clap --features derive. --version uses version and the help description uses description from the [package] table.
Exercise
Which command shows which crate enabled each active clap feature, and why might a feature be on even though you did not list it?
Show answer
cargo tree -i clap -e features. Cargo unifies features across the dependency tree, so another crate that depends on clap can enable a feature for the whole build.