【问题标题】:How to call Rust code outside of the libraries directory when compiling code using rustc?使用 rustc 编译代码时如何在库目录之外调用 Rust 代码?
【发布时间】:2019-09-30 23:30:41
【问题描述】:

我正在尝试使用这种布局编写一个 Rust 库:

.
├── Cargo.lock
├── Cargo.toml
├── examples
│   └── main.rs
├── src
│   ├── client.rs
│   └── lib.rs
└── target
    └── rls
        └── debug
            ├── build
            ├── deps

client.rs 拥有所有代码并且客户端结构是公开的

lib.rs 包含pub mod client;

examples/main.rs

extern crate fistrs;

use fistrs::client::FistClient;

fn main() {
    let mut client = FistClient::new("localhost", "5575");
    client.connect();
}

但是当我运行这个rustc examples/main.rs时出现错误

 --> examples/main.rs:1:1
  |
1 | extern crate fistrs;
  | ^^^^^^^^^^^^^^^^^^^^ can't find crate

这是我的Cargo.toml

[package]
name = "fistrs"
version = "0.1.0"
authors = ["palash25 <npalash25@gmail.com>"]
edition = "2018"

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

[dependencies]

【问题讨论】:

  • 很难回答您的问题,因为它不包含minimal reproducible example。您需要提供 Cargo.toml 以及库的内容。请从库中删除不会导致错误的所有内容;当您完全完成此操作后,您的库很可能会变成一行!您可以使用Rust-specific MRE tips 来减少您在此处发布的原始代码。谢谢!
  • 我不明白你的问题标题和正文之间的联系,你能解释一下吗?
  • @PaulStenne 请注意,我更改了标题以使其更清晰 - 现在是更好还是更糟?
  • @Shepmaster 哦。呃。没有把握?我也不太了解第一个标题之间的意图。也许这是一个自动完成问题?
  • @PaulStenne 我对问题的解释表明 OP 已经创建了一个库板条箱并希望在 Cargo 示例中使用该库。但是,他们遇到了一个错误,所以他们想弄清楚如何使用src 目录“外部”的库(这是我的逻辑飞跃)。我更改了标题以匹配正文中的内容:他们不能在示例中使用它。

标签: rust


【解决方案1】:

惯用答案

当我运行这个rustc examples/main.rs

不要那样做。请改用cargo run --example maincargo build --example main

另见:

字面意思

在构建示例时,涉及到两个 crate:

  1. 图书馆箱子
  2. 示例板条箱

您需要构建库 crate,然后在构建示例 crate 时通知编译器该 crate。这是一项非常乏味的工作,通常没有人愿意做。它看起来像:

$ rustc --edition=2018 --crate-type=rlib --crate-name library_example src/lib.rs -o libmy_library.rlib
$ rustc --edition=2018 --extern library_example=libmy_library.rlib examples/main.rs

另见:

【讨论】:

    猜你喜欢
    • 2022-06-19
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 2021-10-11
    相关资源
    最近更新 更多