rustc 命令详解与参数实测(Ubuntu 22.04)

在 Ubuntu 22.04(rustc 1.99.1 / cargo 1.99.1,rustup minimal profile + gcc 链接器,rsproxy 镜像安装)逐项实测 rust 工具链全流程:rustc -vV 与版本信息、hello.rs 单文件编译(-O/-o/--edition/--crate-type/--emit)、E0425 真实错误回显与 --error-format=json、--explain 错误码、cargo new/run/build(debug 与 release 体积对比)/check/test/fmt、cargo add 真实拉取 rand 并排障(thread_rng 移除、RngExt trait)、Cargo.lock 语义、rustup show/check/component 管理,含 minimal profile 缺组件排障与工具链对照。

Linux命令RustLinux系统UbuntuUbuntu 22.04命令行2026/10/17

rustc 命令详解与参数实测(Ubuntu 22.04)

目标:全面掌握 rustc 与 cargo 工具链的每一个常用命令与参数——rustc 版本信息(--version/-vV 看 LLVM 后端)、单文件编译(-O 开优化、-o 改名、--edition 选版本、--crate-type=lib 产 rlib、--emit=asm 出汇编)、错误体系(E0425 真实回显、--error-format=json 机器可读、--explain 错误码)、cargo 工程(new/run/build 与 debug、release 体积对比/check/test/fmt/clean)、依赖管理(cargo add 真实拉取 rand 并踩平 0.10 API 变更、Cargo.lock、update/remove)、工具链管理(rustup show/check/component add),全部命令与回显已在 Ubuntu 22.04(rustc 1.99.1)实测通过。

一、环境信息

本文所有命令均在以下环境实测,回显逐字照抄:

  • 操作系统:Ubuntu 22.04.5 LTS(x86_64)
  • rustc:1.99.1(2026-10-13),LLVM 后端 23.1.1
  • 安装方式:rustup minimal profile(rustup 1.29.1),组件最小集 + 系统 gcc 11.4 作链接器
  • 执行身份:root;演示目录 /opt/rustdemo(单文件)与 /opt/rustdemo(cargo 工程)

rustup 安装(经 rsproxy 镜像站取工具链分发文件,minimal profile 只装 rustc、cargo、rust-std 三个最小组件):

apt install -y curl build-essential   # curl 下载脚本,build-essential 提供 gcc 链接器
export RUSTUP_DIST_SERVER=https://rsproxy.cn
export RUSTUP_UPDATE_ROOT=https://rsproxy.cn/rustup
curl --proto '=https' --tlsv1.2 -sSf https://rsproxy.cn/rustup-init.sh | sh -s -- -y --profile minimal
source $HOME/.cargo/env

版本验证:

$ rustc --version
rustc 1.99.1 (58cf8f9c3 2026-10-13)
exit=0

$ cargo --version
cargo 1.99.1 (5f94df478 2026-08-27)

$ rustup toolchain list
stable-x86_64-unknown-linux-gnu (active, default)

$ which rustc && ls $HOME/.rustup/toolchains/
/root/.cargo/bin/rustc
stable-x86_64-unknown-linux-gnu

💡 说明: $HOME/.cargo/bin/rustc 是 rustup 的代理(shim),按 $HOME/.rustup/toolchains/ 里的默认工具链转发到真实二进制;build-essential 必装——链接阶段调 cc,缺 gcc 会在最后一步报 linker 'cc' not found。

二、命令概览

命令作用本文小节
rustc --version / -vV版本与构建元信息三
rustc hello.rs编译单个源文件三
rustc -O / -o 名 / --edition=2021优化/输出/语言版本三
rustc --crate-type=lib / --emit=asm产 rlib / 出中间产物三
rustc --error-format=json / --explain E0425机器可读错误 / 错误码解释四
cargo new <名字>新建工程五
cargo run / build [--release] / check运行/构建/快速检查五
cargo test / fmt --check / clean测试/格式/清理五
cargo add <crate> / update / remove依赖管理六
rustup show / check / component add工具链与组件管理七

三、rustc 单文件编译

-vV(双 v)打印构建元信息:commit 哈希、host 三元组、LLVM 版本:

$ rustc -vV(详细版本:host/LLVM 后端)
rustc 1.99.1 (58cf8f9c3 2026-10-13)
binary: rustc
commit-hash: 58cf8f9c35b355199727627d07ae34a4e2846d67
commit-date: 2026-10-13
host: x86_64-unknown-linux-gnu
release: 1.99.1
LLVM version: 23.1.1

最小程序三种编译姿势:

$ cat hello.rs
fn main() {
    println!("hello, rust");
}

$ rustc hello.rs(默认产出同名二进制)
exit=0

$ ls -l hello
-rwxr-xr-x 1 root root 4537856 Oct 17 03:12 hello

$ ./hello
hello, rust

$ rustc -O hello.rs -o hello-opt(-O 开优化,-o 改名)
-rwxr-xr-x 1 root root 4537048 Oct 17 03:12 hello-opt
hello, rust

$ rustc --edition=2021 hello.rs -o hello-2021(--edition 指定版本)
hello, rust

--crate-type=lib 编成 rlib 库(注意 dead_code 警告——库形态下 main 不再是入口):

$ rustc --crate-type=lib hello.rs(编译成 rlib 库)
warning: function `main` is never used
 --> hello.rs:1:4
  |
1 | fn main() {
  |    ^^^^
  |
  = note: `#[warn(dead_code)]` (part of `#[warn(unused)]`) on by default

warning: 1 warning emitted

exit=0

$ ls -l libhello.rlib
-rw-r--r-- 1 root root 6944 Oct 17 03:12 libhello.rlib

$ rustc --emit=asm hello.rs -o hello.s(导出汇编中间产物)
-rw-r--r-- 1 root root 8603 Oct 17 03:12 hello.s

💡 说明: hello 级二进制约 4.5 MB——std 标准库默认静态链接(含调试符号);-O 与 release 一样开优化但保留默认符号,真要瘦身看 cargo build --release 的对比(第五节:4.4 MB → 444 KB)。--edition 缺省按 2015,新代码建议显式 2021/2024。

四、错误体系:E0425 / --error-format=json / --explain

故意写未定义变量,看完整诊断回显(错误码 + 定位 + 修复建议):

$ cat bad.rs
fn main() {
    let x = 1;
    println!("{}", y);
}

$ rustc bad.rs
error[E0425]: cannot find value `y` in this scope
 --> bad.rs:3:20
  |
3 |     println!("{}", y);
  |                    ^
  |
help: a local variable with a similar name exists
  |
3 -     println!("{}", y);
3 +     println!("{}", x);
  |

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0425`.
exit=1

--error-format=json 输出结构化诊断(给编辑器/CI 用,截取前 1 条的头部):

$ rustc --error-format=json bad.rs(机器可读错误,截取)
{"$message_type":"diagnostic","message":"cannot find value `y` in this scope","code":{"code":"E0425",...},"level":"error","spans":[{"file_name":"bad.rs","line_start":3,"column_start":20,...}],"children":[{"message":"a local variable with a similar name exists","level":"help",...}],"rendered":"error[E0425]: ..."}

--explain 直接吐错误码官方讲解(含错误示例与改正写法):

$ rustc --explain E0425(错误码官方解释,截取)
An unresolved name was used.

Erroneous code examples:

something_that_doesnt_exist::foo; // error: unresolved name something_that_doesnt_exist::foo


> 💡 说明: rustc 的诊断是三段式——`error[错误码]` 定位、`help:` 给修复建议(甚至直接给出 diff)、`--explain` 补背景;编译失败退出码固定为 1,链接期 panic 类错误是 101。

## 五、cargo 工程:new / run / build / test

```text
$ cargo new rustdemo
    Creating binary (application) `rustdemo` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
exit=0

$ cat rustdemo/Cargo.toml
[package]
name = "rustdemo"
version = "0.1.0"
edition = "2024"

[dependencies]

$ cat rustdemo/src/main.rs
fn main() {
    println!("Hello, world!");
}

cargo new 生成的是 edition 2024 的标准骨架(含 git 仓库与 #[cfg(test)] 测试模块)。构建三档:

$ cargo run(首次编译并运行)
   Compiling rustdemo v0.1.0 (/opt/rustdemo)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.10s
     Running `target/debug/rustdemo`
Hello, world!
exit=0

$ cargo build(debug 构建)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
exit=0

$ ls -l target/debug/rustdemo
-rwxr-xr-x 2 root root 4545688 Oct 17 03:12 target/debug/rustdemo

$ cargo build --release(release 构建,开优化)
   Compiling rustdemo v0.1.0 (/opt/rustdemo)
    Finished `release` profile [optimized] target(s) in 0.05s
exit=0

$ ls -l target/release/rustdemo
-rwxr-xr-x 2 root root 444760 Oct 17 03:12 target/release/rustdemo

实测体积对比:debug 4.5 MB vs release 444 KB(约 10 倍)——release 剔除 debuginfo 且开优化。cargo check 只做类型检查不产码,是写码循环里最快的反馈:

$ cargo check(只查类型不产码,最快)
    Checking rustdemo v0.1.0 (/opt/rustdemo)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.02s
exit=0

cargo test 跑全部 #[test] 函数:

$ cargo test(真实用例回显,截取尾部)
     Running unittests src/main.rs (target/debug/deps/rustdemo-6dd8dc5b6cf4b1a9)

running 1 test
test tests::it_works ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

cargo fmt --check 需要 rustfmt 组件,minimal profile 默认不装,实测先报错再补装:

$ cargo fmt --check
error: 'cargo-fmt' is not installed for the toolchain 'stable-x86_64-unknown-linux-gnu'.
help: run `rustup component add rustfmt` to install it
exit=1

$ rustup component add rustfmt(minimal profile 默认缺该组件)
info: downloading component rustfmt
exit=0

$ cargo fmt --check(装组件后通过,无输出)
exit=0

清理产物:

$ cargo clean(清空 target)
     Removed 140 files, 49.2MiB total
exit=0

六、依赖管理:cargo add 与 rand 0.10 排障实录

cargo add 真实拉取 rand(crates.io sparse index):

$ cargo add rand
    Updating crates.io index
      Adding rand v0.10.3 to dependencies
             Features:
             + alloc
             + std
             + std_rng
             ...
    Updating crates.io index
     Locking 8 packages to highest Rust 1.99.1 compatible versions
      Adding cfg-if v1.0.5
      Adding chacha20 v0.10.2
      Adding cpufeatures v0.3.1
      Adding getrandom v0.4.3
      Adding libc v0.2.191
      Adding r-efi v6.0.0
      Adding rand v0.10.3
      Adding rand_core v0.10.1
exit=0

$ cat Cargo.toml(依赖已写入)
[package]
name = "rustdemo"
version = "0.1.0"
edition = "2024"

[dependencies]
rand = "0.10.3"

按 0.8 时代教程写 rand::thread_rng(),实测编译失败——rand 0.10 已移除该函数:

$ cargo run(首次尝试,旧 API)
   Compiling rand v0.10.3
   Compiling rustdemo v0.1.0 (/opt/rustdemo)
error[E0425]: cannot find function `thread_rng` in crate `rand`
 --> src/main.rs:4:19
  |
4 |     let n = rand::thread_rng().gen_range(1..=100);
  |                   ^^^^^^^^^^ not found in `rand`

warning: unused import: `rand::Rng`
 --> src/main.rs:1:5
  |
  = note: `#[warn(unused_imports)]` (part of `#[warn(unused)]`) on by default

error: could not compile `rustdemo` (bin "rustdemo") due to 1 previous error; 1 warning emitted
exit=101

改用 0.9+ 更名后的 rand::rng().random_range(...),第二次报错暴露 trait 归属变化——random_range 在 0.10 移进了 RngExt trait,编译器直接给出修法:

error[E0599]: no method named `random_range` found for struct `ThreadRng` in the current scope
   --> src/main.rs:4:25
    |
  4 |     let n = rand::rng().random_range(1..=100);
    |                         ^^^^^^^^^^^^
    |
   ::: /root/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/rand-0.10.3/src/rng.rs:163:8
    |
163 |     fn random_range<T, R>(&mut self, range: R) -> T
    |        ------------ the method is available for `ThreadRng` here
    |
    = help: items from traits can only be used if the trait is in scope
help: trait `RngExt` which provides `random_range` is implemented but not in scope; perhaps you want to import it
    |
  1 + use rand::RngExt;
    |

error: could not compile `rustdemo` (bin "rustdemo") due to 1 previous error; 1 warning emitted

按编译器提示 use rand::RngExt; 后编译运行成功:

$ cat src/main.rs
use rand::RngExt;

fn main() {
    let n = rand::rng().random_range(1..=100);
    println!("lucky number = {n}");
}

$ cargo run
   Compiling rand v0.10.3
   Compiling rustdemo v0.1.0 (/opt/rustdemo)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.00s
     Running `target/debug/rustdemo`
lucky number = 55
exit=0

$ cargo run(第二次:编译缓存命中,直接运行)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
     Running `target/debug/rustdemo`
lucky number = 51

Cargo.lock 锁定精确版本与校验和(lockfileVersion 4):

$ head -22 Cargo.lock(锁文件记录精确版本与哈希)
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4

[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"

[[package]]
name = "chacha20"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
dependencies = [
 "cfg-if",
 "cpufeatures",
 "rand_core",
]

update 与 remove:

$ cargo update(按 semver 更新依赖)
    Updating crates.io index
     Locking 0 packages to highest Rust 1.99.1 compatible versions
exit=0

$ cargo remove rand(移除依赖)
    Removing rand from dependencies
exit=0

💡 说明: 这轮排障是 Rust 生态的典型工作流——E0425(函数没了)→ E0599(方法在别的 trait 里)→ 按编译器 help 补 use rand::RngExt; 即修复,全程无需查文档。rand 0.9 起 thread_rng() 更名 rng()、0.10 起 random_range 归入 RngExt,老教程代码要过两道坎。Cargo.lock 是二进制工程必须提交的文件(可复现构建),库工程则通常不提交。

七、工具链管理:rustup

$ rustup show(活动工具链与默认设置)
Default host: x86_64-unknown-linux-gnu
rustup home:  /root/.rustup

installed toolchains
--------------------
stable-x86_64-unknown-linux-gnu (active, default)

active toolchain
----------------
name: stable-x86_64-unknown-linux-gnu
active because: it's the default toolchain
installed targets:
  x86_64-unknown-linux-gnu

$ rustup component list --installed
cargo-x86_64-unknown-linux-gnu
rust-std-x86_64-unknown-linux-gnu
rustc-x86_64-unknown-linux-gnu

$ rustup target list --installed
x86_64-unknown-linux-gnu

$ rustup check(检查工具链与 rustup 自身更新)
stable-x86_64-unknown-linux-gnu - up to date: 1.99.1 (58cf8f9c3 2026-10-13)
rustup - up to date : 1.29.1

$ rustup --version
rustup 1.29.1 (d95a37b6a 2026-08-13)
info: This is the version for the rustup toolchain manager, not the rustc compiler.
info: the currently active `rustc` version is `rustc 1.99.1 (58cf8f9c3 2026-10-13)`

💡 说明: minimal profile 实测只装 3 个组件(rustc、cargo、rust-std),clippy/rustfmt/llvm-tools 等按需 rustup component add;rustup --version 会特意提示它只是管理器版本,别和 rustc 混淆。交叉编译目标用 rustup target add x86_64-unknown-linux-musl 追加,纯 Rust 代码 + musl 可得全静态二进制。

cargo 子命令一览(cargo --list,截取):

$ cargo --list(子命令总表,截取前 26 行)
Installed Commands:
    add                  Add dependencies to a Cargo.toml manifest file
    b                    alias: build
    bench                Execute all benchmarks of a local package
    build                Compile a local package and all of its dependencies
    c                    alias: check
    check                Check a local package and all of its dependencies for errors
    clean                Remove artifacts that cargo has generated in the past
    clippy               Checks a package to catch common mistakes and improve your Rust code.
    config               Inspect configuration values
    d                    alias: doc
    doc                  Build a package's documentation
    fetch                Fetch dependencies of a package from the network
    fix                  Automatically fix lint warnings reported by rustc
    fmt                  Formats all bin and lib files of the current crate using rustfmt.
    generate-lockfile    Generate the lockfile for a package
    ...

八、常见问题与排查

1. linker 'cc' not found:只装了 rustup 没装系统工具链。apt install build-essential 提供 gcc 链接器(本文环境即此配置),纯 Rust 代码无需 gcc 编译、只要链接器。

2. error: 'cargo-fmt' is not installed for the toolchain ...:minimal profile 不带 rustfmt/clippy 组件。rustup component add rustfmt(clippy 同理)。

3. E0425: cannot find function ... in crate xxx:依赖大版本升级后 API 被移除(如 rand 0.10 移除 thread_rng)。看报错 crate 名与版本号,对照该版本官方文档换新 API。

4. E0599: no method named ... found for struct ...:方法存在但在未引入的 trait 里(Rust 的 trait 必须显式 use 才能用)。编译器 help 通常直接给出该补的 use 行。

5. E0432: unresolved import / E0433: cannot find module or crate:Cargo.toml 里没有该依赖(忘了 add,或 add 后没保存)。cargo add <crate> 解决。

6. debug 与 release 行为差异:debug 有整型溢出 panic、release 回绕;性能基准必须用 cargo build --release(实测同代码体积差 10 倍,优化差距更大)。

7. cargo update 后 Locking 0 packages:依赖都已是 semver 允许的最新版,正常;跨大版本升级(0.8 → 0.10)要用 cargo add rand@0.10 或 cargo update --precise。

8. 编译退出码区分:编译错误 = 1,编译期内部 abort/panic 类(如 error: could not compile 后的 rustc panic)= 101,脚本按退出码分支别按文本匹配。

九、与同类工具链对照

能力cargogonpmpython3
版本cargo --versiongo versionnpm -vpython3 -V
新工程cargo newgo mod initnpm init -y手写/脚手架
运行cargo rungo run .node .python3 main.py
构建cargo build [--release]go build打包链—
测试cargo test(内置)go test(内置)框架外置unittest/pytest
加依赖cargo addgo getnpm installpip install
锁文件Cargo.lockgo.sumpackage-lock.json手工冻结
格式化cargo fmtgofmtprettier 外置black 外置
文档cargo docgo doc—pydoc
错误码体系E0xxx + --explain精确行列——

cargo 与 go 一样把测试/格式/文档全部内置;错误诊断(错误码 + help diff + --explain)是 rustc 公认的体验标杆;与 npm 相比锁文件与校验和由工具链强制维护,供应链可复现性开箱即得。