我正在尝试使用rust-http库,并希望将其用作小项目的基础。
我不知道如何使用通过rustpkg install <remote_url>
无法安装的东西。事实上,我今天才发现rustpkg
现在已经过时了。
如果我通过git clone
克隆该库并运行适当的make
命令来构建它,我该如何在其他地方使用它?也就是说,我如何实际使用extern crate http
?
使用 cargo new
命令创建项目。
编辑生成的 Cargo.toml
文件,添加依赖项:
[dependencies]
old-http = "0.1.0-pre"
在您的代码中访问crate:
Rust 2021和2018
use old_http::SomeType;
Rust 2015
extern crate old_http;
use old_http::SomeType;
使用cargo build
来构建项目。
Cargo会管理版本,需要时构建依赖项,并向编译器传递正确的参数以链接所有依赖关系。
阅读Rust编程语言中关于使用Cargo的详细信息。Cargo book中的指定依赖项详细介绍了可以添加哪些种类的依赖项。
extern crate
结合 macro_use
仍然很有用:https://doc.rust-lang.org/reference/macros-by-example.html?highlight=macro_use#the-macro_use-attribute - hkBstuse ...
语法导入。我已经好几年没有需要使用 #[macro_use]
了。 - Shepmastermacro_use
的参考文档中加入一些关于这个的内容可能会有用吧? - hkBstrustc -L ../rust-http/target/debug your-source-file.rs
进行编译。 - nalply这段话与您的帖子无关,但与您的标题有关。而且与货物有关。
最佳实践:
foo
的外部crate。use ::foo;
foo
的模块(属于您的代码/包)use crate::foo;
use foo;
,但这可能会导致混淆。构建完成后,您可以在代码中使用常规的extern crate http;
。唯一的技巧是您需要向rustc
传递适当的-L
标志,以告诉它在哪里找到libhttp
。
如果您的项目中有一个子模块在rust-http
目录中,并且如果它构建到其根目录(我实际上不知道rust-http
中的make
将结果库放置在何处),那么您可以使用rustc -L rust-http pkg.rs
构建自己的项目。通过该-L
标志,您的pkg.rs
中的extern crate http;
行将能够在rust-http
子文件夹中找到libhttp
。
rustc -L rust-rand
无法正常工作。 - Dee我遇到了类似的问题。最终我在我的Cargo.toml中这样做。
[dependencies]
shell = { git = "https://github.com/google/rust-shell" }
然后在我的 main.rs 中,我能够添加这个并且成功编译。请注意,在我的情况下,这个 cargo 包是一个宏。通常你不希望在 extern 调用之前加上 #[macro_use]。
#[macro_use] extern crate shell;
extern mod
最近已更名为extern crate
。 - barjak