《通过例子学Rust》第11章 crate

crate(中文有 "包,包装箱" 之意)是 Rust 的编译单元。当调用 rustc some_file.rs 时,some_file.rs 被当作 crate 文件 。如果 some_file.rs 里面含有 mod 声明,那么模块文件的内容将在编译之前被插入 crate 文件的相应声明处。换句话说,模块不会单独被编译,只有 crate 才会被编译。

crate 可以编译成二进制可执行文件(binary)或库文件(library)。默认情况下,rustc 将从 crate 产生二进制可执行文件。这种行为可以通过 rustc 的选项 --crate-type 重载。

11.1 库

让我们创建一个库,然后看看如何把它链接到另一个 crate。

复制代码
// 11.1节 库

pub fn public_function() {
    println!("called rary's 'public_function()'");
}

fn private_function() {
    println!("called rary's 'private_function()'");
}

pub fn indirect_access() {
    print!("called rary's 'indirect_access()', that\n> ");
    private_function();
}

// 编译库  rustc --crate-type=lib rary.rs

PS F:\rustproject\rustbyexample\chapter11\example11_1> rustc --crate-type=lib rary.rs
PS F:\rustproject\rustbyexample\chapter11\example11_1> ls lib*
library.rlib

默认情况下,库会使用 crate 文件的名字,前面加上 "lib" 前缀,但这个默认名称可以使用 crate_name 属性 覆盖。

11.2 使用库

要将一个 crate 链接到上节新建的库,可以使用 rustc 的 --extern 选项。然后将所有的物件导入到与库名相同的模块下。此模块的操作通常与任何其他模块相同。

复制代码
// 11.2节 使用库
fn main() {
    rary::public_function();

    // 报错! `private_function` 是私有的
    //rary::private_function();
    rary::indirect_access();
 
    println!("Hello Rust"); 
}
 
// rustc main.rs --extern rary=library.rlib --edition=2024
// ./main

编译运行:

复制代码
# library.rlib 是已编译好的库的路径,这里假设它在同一目录下:
PS F:\rustproject\rustbyexample\chapter11\example11_1> rustc main.rs --extern rary=library.rlib
PS F:\rustproject\rustbyexample\chapter11\example11_1> ./main
called rary's 'public_function()'
called rary's 'indirect_access()', that
> called rary's 'private_function()'
Hello Rust
PS F:\rustproject\rustbyexample\chapter11\example11_1>
相关推荐
niyongsheng7 小时前
3D 装箱算法工程化:数据结构、放置启发式与支撑规则
数据结构·算法·rust
Hello.Reader8 小时前
tsrs 技术解析用 Rust 移植 TypeScript 7,类型检查还能怎样提速?
开发语言·rust·typescript
王仔小奶10 小时前
Rust 正在接管金融圈?深度拆解一份高薪 FinTech 岗位 JD
开发语言·金融·rust
你为她披上外套时我正站在窗外12 小时前
subtitler v2.10 发布:3 个社区 PR、一个一天修掉的 issue,和关于 uuencode 的真相
rust
Thneonl12 小时前
熔断不是开关是状态机:Claude Code 路由内核的 3 条红线
人工智能·rust
Thneonl12 小时前
一个 Claude Code 本地代理,凭啥配了 3 个观测出口?
人工智能·rust
西风测评14 小时前
终端粘贴原理:bracketed paste、4095 字节行限制与 UTF-8 分片
rust
geovindu17 小时前
rust: Read-Write Lock Pattern
开发语言·后端·设计模式·rust·读写锁模式·同步型模式
怪我冷i17 小时前
Rust智能指针Rc<T> 使用总结
开发语言·后端·rust
Kapaseker17 小时前
删掉 1.1 万行 C 代码,Rust 正式接手 Android Binder
android·rust