profile 与发布配置

上一节练习答案要点

上一节练习给 feat-demo 补 to_json:Record 实现 Serialize、to_json 被 #[cfg(feature = "json")] 守住、main 用 cfg! 分叉。沙箱无 serde,用手写转义模拟;本地换成 serde_json::to_string(r).unwrap()。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// 上一节练习答案:补全 to_json(沙箱无 serde,用手写转义模拟 serde_json 的输出)
mod mylib {
    pub struct Record {
        pub name: String,
        pub score: u32,
    }
    pub fn summary(r: &Record) -> String {
        format!("{}:{} 分", r.name, r.score)
    }
    fn escape(s: &str) -> String {
        let mut out = String::new();
        for c in s.chars() {
            match c {
                '"' => out.push_str("\\\""),
                '\\' => out.push_str("\\\\"),
                '\n' => out.push_str("\\n"),
                c => out.push(c),
            }
        }
        out
    }
    // 真实项目里这段被 #[cfg(feature = "json")] 守住,内部是 serde_json::to_string(r).unwrap()
    pub fn to_json(r: &Record) -> String {
        format!("{{\"name\":\"{}\",\"score\":{}}}", escape(&r.name), r.score)
    }
}

fn main() {
    let r = mylib::Record { name: "小明".to_string(), score: 92 };
    println!("核心功能:{}", mylib::summary(&r));
    // 真实项目里写 cfg!(feature = "json") 分叉;沙箱没有 Cargo feature,恒为 false
    if cfg!(feature = "json") {
        println!("可选功能:{}", mylib::to_json(&r));
    } else {
        println!("可选功能:{}", mylib::to_json(&r));
        println!("(沙箱里 cfg!(feature = \"json\") 为 false;本地默认构建为 true,输出相同)");
    }
    let tricky = mylib::Record { name: "a\"b\\c".to_string(), score: 60 };
    println!("转义验证:{}", mylib::to_json(&tricky));
}

输出:

1
2
3
4
核心功能:小明:92 分
可选功能:{"name":"小明","score":92}
(沙箱里 cfg!(feature = "json") 为 false;本地默认构建为 true,输出相同)
转义验证:{"name":"a\"b\\c","score":60}

思考题要点:

  1. 旧写法把依赖名暴露成隐含 feature,下游可直接 features = ["serde"] 绕过 json;dep:serde 把“启用依赖”与“功能名”分开。
  2. 带 json:feature 取并集,B 的构建里 to_json 也存在——但 B 不该依赖它,A 一旦关掉就编译不过。feature 只能叠加、任意组合必须能编译,永远不要假设某 feature 关着。
  3. 多半是 dev-dependencies 打开的 feature 只在测试构建生效,业务代码却用了它守住的 API。排查:cargo tree -e features -i <包名>;修法:把需要的 feature 移到正常依赖,或用 #[cfg(...)] 守住。

本节收尾第 14 章:讲同一份代码怎么编出快慢、大小、可调试性不同的产物。

学习目标

读完本节,你会:说清四个内置 profile 的默认值与继承;理解各开关管什么、代价是什么;用 inherits 定义自定义 profile、用按包覆盖加速开发构建;按场景选发布配方;补齐 crates.io 元数据、跑 --dry-run、按语义化版本升版本号。

核心概念

profile:一组编译开关的预设

同一份代码要编出不同产物:开发时编译快、能断点、溢出就报错;发布时运行快、体积小。差异靠一组编译开关,profile 就是这组开关的预设。Cargo 内置四个:cargo build/run/check 用 dev,--release 用 release,cargo test 用 test(继承 dev),cargo bench 用 bench(继承 release),cargo install 默认 release。用 [profile.<名字>] 改开关。两条规则:Cargo 只看工作空间根清单里的 profile,依赖包里写的被忽略;每个 profile 产物单独放 target/<名字>/。

dev 与 release 的默认差异

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
开关                dev(开发)              release(发布)
opt-level           0(不优化)              3(全优化)
debug               true(完整调试信息)     false(无调试信息)
debug-assertions    true                     false
overflow-checks     true(溢出 panic)       false(溢出回绕)
lto                 false                    false
codegen-units       256(增量构建时)        16
panic               unwind                   unwind
incremental         true                     false
strip               none                     none

**dev 优化迭代时间,release 优化产物。**两个陷阱:release 默认不开 LTO、不 strip;overflow-checks 默认关闭,溢出开发时 panic、发布时回绕(示例 1)。

逐个开关:管什么、代价是什么

  • opt-level:0 不优化,1 基本,2 多数,3 全部;"s"/"z" 偏体积(z 关向量化)。越高编译越慢、调试变量越容易被优化没;3 不必然比 2 快。
  • debug:调试信息量。false 无,"line-tables-only" 只有行号,true 完整。只影响体积与可调试性。
  • debug-assertions:控制 cfg(debug_assertions) 与 debug_assert!。放开发期贵检查;不能放副作用,release 下消失。
  • overflow-checks:溢出 panic 还是回绕。金额、长度、索引计算值得在 release 也打开,或用 checked_add 写死。
  • lto:链接时优化。false 仅本 crate 薄 LTO;"thin" 跨 crate、代价小;true 全量跨 crate,收益最大、链接最慢。常配 codegen-units = 1。
  • codegen-units:拆几个单元并行编译。越多编译越快、优化越受限;1 优化机会最多。
  • panic:"unwind"(默认)展开栈、catch_unwind 能接住;"abort" 直接终止进程,产物更小但 panic 即退出。测试、基准、构建脚本、过程宏始终 unwind。
  • strip:"debuginfo" 只剥调试信息,"symbols"/true 连符号剥(回溯只剩地址)。
  • incremental:增量编译,dev 默认开;发布构建关着。

自定义 profile 与按包覆盖

自定义 profile 必须写 inherits,只写与父不同的开关:

1
2
3
4
[profile.release-lto]
inherits = "release"
lto = true
codegen-units = 1

cargo build --profile release-lto 构建,产物在 target/release-lto/。

按包覆盖解决“开发构建慢”:自己的代码快速重编,依赖不优化却慢得没法调试:

1
2
[profile.dev.package."*"]
opt-level = 2

"*" 指所有依赖,也可写具体包名。优先级:具体包名 > "*" > build-override > profile 本体 > 默认值;覆盖不能改 panic、lto、rpath。细节:泛型在实例化它的 crate 里生成,拉高依赖的 opt-level 未必让泛型变快;先试 1(允许跨 crate 共享单态化,2/3 会关掉)。

三个常用发布配方

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# 极速:用编译时间换运行速度(服务端、计算密集)
[profile.release]
lto = true
codegen-units = 1

# 小体积:分发给用户的命令行工具(panic 直接退出、回溯无符号)
[profile.release]
opt-level = "z"
lto = true
codegen-units = 1
panic = "abort"
strip = true

# 可调试的 release:几乎不增体积,给回溯留文件名行号(线上服务值得开)
[profile.release]
debug = "line-tables-only"

CI 与发版用 --locked 保可复现(锁文件过期直接报错);--frozen 再禁止网络。

发布配置:从产物到 crates.io

发布二进制产物在 target/release/<名字>;cargo install --path . 装到 ~/.cargo/bin。发布库重点在元数据与版本纪律:

  • 元数据:强制要求 description 与 license(如 "MIT OR Apache-2.0");建议补 repository、readme、keywords。内部包写 publish = false。
  • 预演:先 cargo publish --dry-run(校验、打包、解包验证,不上传),cargo package --list 看打包文件。.crate 上限 10MB。
  • 不可撤销:同版本不能覆盖、代码不能删除。发错只能发新版,并用 cargo yank 撤回坏版本。
  • 版本号:1.0 后破坏性升主版本、新功能升次版本、修复升修订号;0.x 阶段破坏性升次版本,功能与修复升修订号。建议打 tag。
  • 锁文件:二进制提交 Cargo.lock 并在 CI 用 --locked;库通常不提交。

可运行代码

在线沙箱按 release 构建(断言与溢出检查关闭),正好把可观察差异跑出来;Cargo.toml 部分用模拟并附本地复现。

示例 1:debug_assertions 与溢出检查

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
use std::hint::black_box;

fn main() {
    println!("debug_assertions 开启?{}", cfg!(debug_assertions));
    // debug_assert! 只在 debug-assertions 开启时求值;assert! 永远求值
    let mut counter = 0;
    debug_assert!({ counter += 1; true });
    println!("debug_assert! 的副作用执行次数:{}(release 构建为 0)", counter);
    assert!(1 + 1 == 2);
    println!("assert! 永远执行,这行能打印说明它通过了");

    // 溢出:dev 默认 overflow-checks=true 会 panic;release 默认关闭、按二进制回绕
    let a = black_box(200u8);
    let b = black_box(100u8);
    println!("wrapping_add:200 + 100 = {}(明确回绕,两种构建一致)", a.wrapping_add(b));
    println!("checked_add:{:?}(溢出返回 None,两种构建一致)", a.checked_add(b));
    println!("saturating_add:{}(钳到最大值 255)", a.saturating_add(b));
    // 裸的 a + b 在 release 得到 44,在 dev 直接 panic——不要依赖它写业务逻辑
    println!("release 下裸加法的结果(此处用 wrapping 模拟,免得 dev 构建直接 panic):{}", a.wrapping_add(b));
    println!("结论:要确定性就用 checked/wrapping/saturating,别让 profile 决定语义");
}

输出:

1
2
3
4
5
6
7
8
debug_assertions 开启?false
debug_assert! 的副作用执行次数:0(release 构建为 0)
assert! 永远执行,这行能打印说明它通过了
wrapping_add:200 + 100 = 44(明确回绕,两种构建一致)
checked_add:None(溢出返回 None,两种构建一致)
saturating_add:255(钳到最大值 255)
release 下裸加法的结果(此处用 wrapping 模拟,免得 dev 构建直接 panic):44
结论:要确定性就用 checked/wrapping/saturating,别让 profile 决定语义

本地复现:cargo run(dev)第一行变 true、计数变 1;换成裸 a + b,dev 直接 panic、release 输出 44。溢出有业务含义处用 checked_*。

示例 2:profile 的继承与覆盖

把默认值、继承、自定义、按包覆盖写成数据打印。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#[derive(Clone, Debug)]
struct Profile {
    opt_level: &'static str,
    debug: &'static str,
    debug_assertions: bool,
    overflow_checks: bool,
    lto: &'static str,
    codegen_units: u32,
    panic: &'static str,
    strip: &'static str,
}

fn dev() -> Profile {
    Profile { opt_level: "0", debug: "full", debug_assertions: true,
              overflow_checks: true, lto: "false", codegen_units: 256,
              panic: "unwind", strip: "none" }
}
fn release() -> Profile {
    Profile { opt_level: "3", debug: "none", debug_assertions: false,
              overflow_checks: false, lto: "false", codegen_units: 16,
              panic: "unwind", strip: "none" }
}

fn show(name: &str, p: &Profile) {
    println!("[profile.{}] opt-level={} debug={} debug-assertions={} overflow-checks={}",
             name, p.opt_level, p.debug, p.debug_assertions, p.overflow_checks);
    println!("              lto={} codegen-units={} panic={} strip={}",
             p.lto, p.codegen_units, p.panic, p.strip);
}

fn main() {
    show("dev", &dev());
    show("release", &release());
    // test 继承 dev、bench 继承 release:只改一处,其余沿用父 profile
    let test = dev();
    show("test(继承 dev)", &test);
    // 自定义 profile 必须写 inherits;这里模拟 release-lto
    let mut lto = release();
    lto.lto = "fat";
    lto.codegen_units = 1;
    show("release-lto(继承 release)", &lto);
    // 按包覆盖:dev 里把依赖优化到 2,自己的代码仍是 0
    let mut dep = dev();
    dep.opt_level = "2";
    println!("dev 下依赖包(package.\"*\" 覆盖):opt-level={},自己的包仍是 0", dep.opt_level);
    println!("产物目录:target/dev、target/release、target/release-lto 各一份");
}

输出:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
[profile.dev] opt-level=0 debug=full debug-assertions=true overflow-checks=true
              lto=false codegen-units=256 panic=unwind strip=none
[profile.release] opt-level=3 debug=none debug-assertions=false overflow-checks=false
              lto=false codegen-units=16 panic=unwind strip=none
[profile.test(继承 dev)] opt-level=0 debug=full debug-assertions=true overflow-checks=true
              lto=false codegen-units=256 panic=unwind strip=none
[profile.release-lto(继承 release)] opt-level=3 debug=none debug-assertions=false overflow-checks=false
              lto=fat codegen-units=1 panic=unwind strip=none
dev 下依赖包(package."*" 覆盖):opt-level=2,自己的包仍是 0
产物目录:target/dev、target/release、target/release-lto 各一份

本地复现:加 [profile.release-lto] 后构建看链接耗时;再加按包覆盖,对比改一行重编的时间。

示例 3:panic 的 unwind 与 abort

默认 unwind 时 panic 可被接住;abort 时第一次 panic 就终止进程。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
use std::panic;

fn divide(a: i32, b: i32) -> i32 {
    if b == 0 { panic!("除数不能为零"); }
    a / b
}

fn main() {
    // panic = "unwind"(默认):panic 沿调用栈展开,catch_unwind 能接住,进程继续
    let ok = panic::catch_unwind(|| divide(10, 2));
    println!("10 / 2 = {:?}", ok);
    let bad = panic::catch_unwind(|| divide(10, 0));
    println!("10 / 0 被接住?{}(unwind 才能接住)", bad.is_err());
    println!("接住之后程序继续运行——这行就是证据");
    println!();
    println!("若 profile 里写 panic = \"abort\":第一次 panic 就终止进程,catch_unwind 永远接不住");
    println!("abort 的好处:产物更小、无展开表;代价:任何 panic 都是整进程退出");
    println!("注意:测试、基准、构建脚本、过程宏忽略 panic 设置,始终按 unwind 构建");
    println!("选择原则:库不要替下游决定;二进制要小体积且能接受崩溃退出时才用 abort");
}

输出(标准输出;panic 报错行走标准错误,在线运行器会附在后面):

1
2
3
4
5
6
7
8
10 / 2 = Ok(5)
10 / 0 被接住?true(unwind 才能接住)
接住之后程序继续运行——这行就是证据

若 profile 里写 panic = "abort":第一次 panic 就终止进程,catch_unwind 永远接不住
abort 的好处:产物更小、无展开表;代价:任何 panic 都是整进程退出
注意:测试、基准、构建脚本、过程宏忽略 panic 设置,始终按 unwind 构建
选择原则:库不要替下游决定;二进制要小体积且能接受崩溃退出时才用 abort

本地复现:加 panic = "abort" 后 cargo run --release,程序在除零处直接终止;cargo test 不受影响。可预期的失败用 Result,不用 panic。

示例 4:版本号怎么升、发布前查什么

把语义化版本升级规则与元数据自检写成函数。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#[derive(Clone, Copy, Debug, PartialEq)]
struct Version(u32, u32, u32);

#[derive(Clone, Copy, Debug)]
enum Change { Breaking, Feature, Fix }

fn bump(v: Version, c: Change) -> Version {
    match (v.0, c) {
        // 1.0 之后:破坏性升主版本、新功能升次版本、修复升修订号
        (_, Change::Breaking) if v.0 >= 1 => Version(v.0 + 1, 0, 0),
        (_, Change::Feature) if v.0 >= 1 => Version(v.0, v.1 + 1, 0),
        (_, Change::Fix) if v.0 >= 1 => Version(v.0, v.1, v.2 + 1),
        // 0.x 阶段:次版本当主版本看(破坏性升次版本),功能与修复都升修订号
        (_, Change::Breaking) => Version(0, v.1 + 1, 0),
        _ => Version(0, v.1, v.2 + 1),
    }
}

fn fmt(v: Version) -> String { format!("{}.{}.{}", v.0, v.1, v.2) }

fn main() {
    let cases = [
        (Version(1, 2, 3), Change::Breaking),
        (Version(1, 2, 3), Change::Feature),
        (Version(1, 2, 3), Change::Fix),
        (Version(0, 2, 3), Change::Breaking),
        (Version(0, 2, 3), Change::Feature),
        (Version(0, 0, 3), Change::Fix),
    ];
    for (v, c) in cases {
        println!("{} + {:?} -> {}", fmt(v), c, fmt(bump(v, c)));
    }
    println!();
    // 发布前元数据自检:crates.io 强制要求 description 与 license(或 license-file)
    let meta = [("description", true), ("license", true), ("repository", true),
                ("readme", false), ("keywords", false)];
    let mut ready = true;
    for (k, present) in meta {
        let required = k == "description" || k == "license";
        if required && !present { ready = false; }
        println!("{}:{}{}", k, if present { "已填" } else { "未填" },
                 if required { "(必填)" } else { "(建议)" });
    }
    println!("可以 cargo publish --dry-run 了?{}", ready);
}

输出:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
1.2.3 + Breaking -> 2.0.0
1.2.3 + Feature -> 1.3.0
1.2.3 + Fix -> 1.2.4
0.2.3 + Breaking -> 0.3.0
0.2.3 + Feature -> 0.2.4
0.0.3 + Fix -> 0.0.4

description:已填(必填)
license:已填(必填)
repository:已填(建议)
readme:未填(建议)
keywords:未填(建议)
可以 cargo publish --dry-run 了?true

这与插入符严丝合缝:下游写 "0.2" 只接受 0.2.x,0.x 破坏性变更升次版本(0.2.3 → 0.3.0)不会被误升级。纪律:先判断变更类型,再升版本,最后预演。

常见坑

  • 拿 dev 产物测性能。opt-level = 0 慢十倍不奇怪;性能结论在 release 下测。
  • 以为 --release 就是极致。默认不开 LTO、codegen-units = 16;极速加 lto = true + codegen-units = 1。
  • 溢出随构建变化。dev panic、release 回绕;金额、长度、索引计算用 checked_*。
  • debug_assert! 写副作用。release 下消失,只放纯检查。
  • 在依赖里写 profile。只认根清单,依赖的被忽略。
  • 自定义 profile 漏 inherits。必须声明继承谁;产物在 target/<名字>/。
  • 指望覆盖改 panic/lto。覆盖不支持;泛型重的依赖拉高 opt-level 未必变快,先试 1。
  • strip = true 后回溯没符号。排障用 "debuginfo" 或 debug = "line-tables-only"。
  • panic = "abort" 后测试不受影响。测试、基准、构建脚本、过程宏始终 unwind。
  • 发布不预演。先 --dry-run + package --list;发布不可覆盖,发错只能 yank 加新版。
  • CI 不加 --locked。锁文件不一致时普通构建会悄悄升级依赖。改了 profile“没变化”时,先确认改的是根清单、命令带对 --profile。

动手练习

本地实测(只用标准库,不真发布):

  1. cargo new profile-demo,main.rs 写循环求和。对比 cargo run 与 --release 的时间(time)与产物大小。
  2. 加 release-lto 与 release-small(配置见下方提示),记录大小与编译耗时;给后者故意除零,观察进程直接终止。
  3. 把示例 1 搬进来:裸 a + b 在 dev 看 panic、release 看回绕,再改 checked_add 确认一致。补 description 与 license = "MIT",跑 --dry-run 与 package --list(不要真 publish)。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// Cargo.toml(补全两个自定义 profile 与发布元数据)
[package]
name = "profile-demo"
version = "0.1.0"
edition = "2024"
description = "profile 与发布配置练习"
license = "MIT"

[profile.release-lto]
inherits = "release"
# 提示:lto = true,codegen-units = 1,strip = true

[profile.release-small]
inherits = "release"
# 提示:opt-level = "z",panic = "abort",strip = true

期望观察:release-lto 链接最慢、产物最小;release-small 触发 panic 直接退出;--dry-run 生成 .crate 包。

思考题:

  1. 工具要体积小、崩溃时还能拿到带行号的回溯。opt-level、strip、debug、panic 各选什么?
  2. 解析库 dev 下很慢,按包覆盖拉到 opt-level = 2 还是慢,可能是什么原因?
  3. 库的 0.3.1 修了 bug、同时给公开函数加了必填参数。下一版发什么版本号?下游写 "0.3" 会受影响吗?

小结与预告

核心就四句话:profile 是编译开关的预设,dev 优化迭代速度、release 优化产物,test 继承 dev、bench 继承 release,只有根清单的 profile 生效;每个开关都有代价——优化三件套用编译时间换速度,debug 与 strip 在体积与可调试性间取舍,断言与溢出检查决定两种构建是否同行为,abort 用可恢复性换体积;自定义 profile 靠 inherits 叠加、按包覆盖只加速依赖,配方按场景选,CI 加 --locked;发布先补齐 description 与 license、跑 --dry-run、按语义化版本升版本号,因为发布不可覆盖、发错只能 yank 加新版。

下一节 15.1:单元测试与断言。下一章讲怎么证明代码是对的,先从 #[test] 讲起。


配套练习:在学习站动手练这一节

本文代码基于 Rust 1.8x / Edition 2024 验证。

JerryHome · 记录技术与生活