gpt4 book ai didi

rust - 使用 rustc 编译代码时如何调用库目录之外的 Rust 代码?

转载 作者:行者123 更新时间:2023-11-29 08:04:31 25 4
gpt4 key购买 nike

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

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

client.rs 包含所有代码,并且客户端结构是公共(public)的

lib.rs 包含 pub mod 客户端;

示例/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 <<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fa948a9b969b8992c8cfba9d979b9396d4999597" rel="noreferrer noopener nofollow">[email protected]</a>>"]
edition = "2018"

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

[dependencies]

最佳答案

惯用的答案

when I run this rustc examples/main.rs

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

另请参阅:

字面答案

当您构建示例时,涉及两个 crate:

  1. 图书馆箱子
  2. 示例 crate

您需要构建库 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

另请参阅:

关于rust - 使用 rustc 编译代码时如何调用库目录之外的 Rust 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58170395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com