Cargo管理多个程序的三种方法

1. 自动发现(autobins)

在使用cargo new的新项目中,autobins参数默认是打开的。autobin的作用是: 存放在src/bin下的所有文件都是一个独立的应用程序,可以单独编译和运行。

1. 项目文件概览

如下示例项目,有三个目标程序: hello, test1, tuple

autobin
├── Cargo.lock
├── Cargo.toml
└── src
    ├── bin
    │   ├── test1.rs
    │   └── tuple.rs
    └── main.rs

2 directories, 5 files

Cargo.toml内容为默认:

[package]
name = "hello"
version = "1.0.0"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

2. 编译单个程序

cargo build --bin [目标程序]

3. 编译所有程序

cargo build --bins

4.运行单个程序

cargo run --bin [目标程序]

5. 清理项目

cargo clean

2. Cargo.toml文件[bin]配置

手动指定bin程序,需要关闭autobins选项。

1. 项目文件概览

toml
├── Cargo.lock
├── Cargo.toml
└── src
    ├── hello
    │   └── hello.rs
    └── tuple
        └── tuple.rs

3 directories, 4 files

Cargo.toml内容:

[package]
name = "toml"
version = "1.0.0"
autobins = false

[[bin]]
name = "hello"
path = "src/hello/hello.rs"

[[bin]]
name= "tuple"
path = "src/tuple/tuple.rs"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

编译,运行及清理同1. 自动发现(autobins)

3. 工作空间workspace

一个工作空间是由多个package组成的集合,它们共享同一个Cargo.lock文件、输出目录和一些设置。
工作空间的几个关键点在于:

  • 所有的 package 共享同一个 Cargo.lock 文件,该文件位于工作空间的根目录中
  • 所有的 package 共享同一个输出目录,该目录默认的名称是 target ,位于工作空间根目录下
  • 只有工作空间根目录的 Cargo.toml 才能包含 [patch], [replace] 和 [profile.*],而成员的 Cargo.toml 中的相应部分将被自动忽略

1. 项目文件概览

worksapce
├── Cargo.lock
├── Cargo.toml
├── all
│   ├── test1
│   │   ├── Cargo.toml
│   │   └── src
│   │       └── main.rs
│   └── test2
│       ├── Cargo.toml
│       └── src
│           └── main.rs
├── hello
│   ├── Cargo.toml
│   └── src
│       └── main.rs
└── tuple
    ├── Cargo.toml
    └── src
        └── main.rs

9 directories, 10 files

顶层Cargo.toml内容:

[workspace]
members = ["hello", "tuple", "all/*"]
default-members = ["hello"]
exclude = ["all/test2"]
  • members: 指定package路径,支持通配符*?
  • default-members: 当没有指定编译参数时,默认编译的package
  • exclude:排除的package

2. 编译单个程序

cargo build -p [目标程序]

3. 编译所有程序

cargo build --workspace

4.运行单个程序

cargo run -p [目标程序]

5. 清理项目

cargo clean

Related Posts