《通过例子学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>
相关推荐
techdashen1 天前
每次 `cargo build` 背后,有人在默默撑着这一切
rust
Binarydog_Lee1 天前
Rust 核心机制:所有权、借用与生命周期
开发语言·rust
卜夋1 天前
Rust 学习笔记 - Day 6: 引用与借用
后端·rust
zandy10111 天前
衡石科技|HENGSHI CLI登场,以Rust架构驱动BI自动驾驶
开发语言·科技·rust
沛沛rh451 天前
用 Rust 实现用户态调试器:mini-debugger项目原理剖析与工程复盘
开发语言·c++·后端·架构·rust·系统架构
BugShare1 天前
一个用 Rust 编写的、速度极快的 Python 包和项目管理器
开发语言·python·rust
Binarydog_Lee1 天前
Rust 生命周期机制详解:彻底理解 ‘static
rust
techdashen1 天前
Rust 正式成立 Types Team:类型系统终于有了专属团队
开发语言·后端·rust