[英]How can I build multiple binaries with Cargo?
I'd like to make a project with a daemon
and a client
, connecting through a unix socket.我想用一个
daemon
和一个client
制作一个项目,通过 unix socket 连接。
A client
and a daemon
requires two binaries, so how do I tell Cargo
to build two targets from two different sources?一个
client
和一个daemon
需要两个二进制文件,那么我如何告诉Cargo
从两个不同的来源构建两个目标呢?
To add a bit of fantasy, I'd like to have a library
for the main part of the daemon
, and just have a binary to wrap around it and communicate through sockets.为了增加一点幻想,我想为
daemon
的主要部分提供一个library
,并且只需要一个二进制文件来包装它并通过套接字进行通信。
So, we have this kind of tree architecture:所以,我们有这种树结构:
├── Cargo.toml
├── target
| └── debug
| ├── daemon
│ └── client
└── src
├── daemon
│ ├── bin
│ │ └── main.rs
│ └── lib
│ └── lib.rs
└── client
└── bin
└── main.rs
I could make one executable which manages both concerns, but that's not what I want to do, unless it's very good practice.我可以制作一个管理这两个问题的可执行文件,但这不是我想要做的,除非这是非常好的做法。
You can specify multiple binaries using [[bin]]
, as mentioned here :您可以使用指定多个二进制文件
[[bin]]
提到这里:
[[bin]]
name = "daemon"
path = "src/daemon/bin/main.rs"
[[bin]]
name = "client"
path = "src/client/bin/main.rs"
Tip: If you instead put these files in src/bin/daemon.rs
and src/bin/client.rs
, you'll get two executables named daemon
and client
as Cargo compiles all files in src/bin
into executables with the same name automatically.提示:如果您将这些文件放在
src/bin/daemon.rs
和src/bin/client.rs
,您将获得两个名为daemon
和client
可执行文件,因为 Cargo 会将src/bin
所有文件编译为具有相同名称的可执行文件自动。 You need to specify names and paths like in the snippet above only if you don't follow this convention.仅当您不遵循此约定时,才需要像上面的代码片段一样指定名称和路径。
Another way is to use the workspace feature .另一种方法是使用工作区功能。 This will provide more flexibility due to the fact that we can have more than one library.
由于我们可以拥有多个库,这将提供更大的灵活性。 Example project structure:
示例项目结构:
.
├── Cargo.toml
├── cli
│ ├── Cargo.toml
│ └── src
│ └── main.rs
├── core
│ ├── Cargo.toml
│ └── src
│ └── lib.rs
├── daemon
│ ├── Cargo.toml
│ └── src
│ └── main.rs
├── gui
│ ├── Cargo.toml
│ └── src
│ └── main.rs
└── rpc
├── Cargo.toml
└── src
└── lib.rs
Contents of the root Cargo.toml
:根
Cargo.toml
:
[workspace]
members = ["cli", "core", "daemon", "gui", "rpc"]
Another format could be to replicate what the Crates.io source code has done, if you have a massive project, something like:另一种格式可能是复制Crates.io 源代码所做的事情,如果您有一个庞大的项目,例如:
Main Library in src, with a Bin folder with your executables. src 中的主库,带有包含可执行文件的 Bin 文件夹。 Then make calls to your main library crate from your executables.
然后从您的可执行文件调用您的主库 crate。
That way you library is centralized so easier to find things as it's cached.这样,您的库是集中的,因此在缓存时更容易查找内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.