问题描述
现在我有一个包含三个成员的 Cargo 工作区.
Right now I have a Cargo workspace with three members.
[workspace]
members = [
"foo",
"bar",
"baz",
]
如果我在根目录中运行 cargo run
,我会收到这个错误:
If I run cargo run
in the root directory, I get this error:
错误:清单路径 /home/lukas/dev/mahboi/Cargo.toml
是一个虚拟清单,但此命令需要针对此工作区中的实际包运行
这是有道理的.我可以运行 cargo run -p foo
并且它可以工作.但问题是:foo
是唯一可执行的 crate,我会经常执行它,所以如果我能运行 cargo run
并执行它会很好.
That makes sense. I can run cargo run -p foo
and it works. But the thing is: foo
is the only crate that is executable and I will execute it very often, so it would be nice if I could just run cargo run
and execute it.
我尝试使用 default-members
键,但这没有帮助:
I tried to use the default-members
key, but this didn't help:
default-members = ["foo"]
是否有另一种方法告诉 Cargo cargo run
应该执行 foo
crate(相当于在 中运行
子目录)?我也会接受使 root crate 非虚拟的答案(即添加一个 cargo run
foo/[package]
键).
Is there another way to tell Cargo that cargo run
should execute the foo
crate (equivalent to running cargo run
in the foo/
subdirectory)? I would also accept answers that make the root crate non virtual (i.e. add a [package]
key).
推荐答案
Single Binary
这个 从 Rust 1.30 开始可用.这是我测试过的完整文件集:
Single Binary
This is available as of Rust 1.30. Here is the complete set of files I tested with:
Cargo.toml
[workspace]
members = [
"foo",
"bar",
"baz",
]
foo/Cargo.toml
[package]
name = "foo"
version = "0.1.0"
authors = ["An Devloper <[email protected]>"]
[dependencies]
foo/src/main.rs
fn main() {
println!("Hello, world!");
}
bar/Cargo.toml
[package]
name = "bar"
version = "0.1.0"
authors = ["An Devloper <[email protected]>"]
[dependencies]
bar/src/lib.rs
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
baz/Cargo.toml
[package]
name = "baz"
version = "0.1.0"
authors = ["An Devloper <[email protected]>"]
[dependencies]
baz/src/lib.rs
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
$ tree .
.
├── Cargo.lock
├── Cargo.toml
├── bar
│ ├── Cargo.toml
│ └── src
│ └── lib.rs
├── baz
│ ├── Cargo.toml
│ └── src
│ └── lib.rs
├── foo
│ ├── Cargo.toml
│ └── src
│ └── main.rs
├── src
│ └── lib.rs
└── target
└── ...
$ cargo run
Compiling baz v0.1.0 (file:///private/tmp/example/baz)
Compiling bar v0.1.0 (file:///private/tmp/example/bar)
Compiling foo v0.1.0 (file:///private/tmp/example/foo)
Finished dev [unoptimized + debuginfo] target(s) in 0.39s
Running `target/debug/foo`
Hello, world!
多个二进制文件
从 Rust 1.37.0 开始,您可以使用 Cargo 的默认运行"功能来指定使用哪个.
Multiple Binaries
As of Rust 1.37.0 you can use Cargo's "default-run" feature to specify which one to use.
foo/Cargo.toml
[package]
name = "foo"
version = "0.0.1"
authors = ["An Devloper <[email protected]>"]
default-run = "foo"
这篇关于如何指定默认情况下在 Cargo 工作区的根目录中运行的 crate `cargo run`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!