【问题标题】:How do you import macros in submodules in Rust?如何在 Rust 的子模块中导入宏?
【发布时间】:2016-08-26 23:32:16
【问题描述】:

我有以下目录结构

  • /main.rs
  • /lib.rs
  • /tutorial/mod.rs
  • /tutorial/foo.rs

foo.rs 中,我需要使用来自glium 库的宏implement_vertex!。如果我把#[macro_use] extern crate glium; 放在foo.rs 的前面,我会得到一个error: an `extern crate` loading macros must be at the crate root。我也收到了error: macro undefined: 'implement_vertex!'

还有一个 lib.rs 是教程模块的 crate 根。我需要把#[macro_use] 放在那里。如果我同时拥有 main.rslib.rs,这会创建 2 个板条箱根吗?

在子模块中导入宏的正确方法是什么?

【问题讨论】:

  • 没有实际代码,这个只能盲猜解决。我们需要的只是结构、导入位置和使用位置。
  • 如何编译(cargo build)?您是否修改了您的Cargo.tomlmod tutorial; 行在哪个文件中? mod foo; 行在哪个文件中?如果没有这些信息,我们只能猜测您的模块树的外观,如@DK。已经说过了。

标签: rust


【解决方案1】:

顺序很重要的编译阶段尽早处理宏。你和我一样,可能变得很好,并且习惯了 Rust,不需要关心你的 use 和 crate 语句的顺序。

根据需要将 #[macro_use] extern crate glium; 语句移至 lib.rs 和/或 main.rs 文件的顶部。

【讨论】:

    【解决方案2】:

    像编译器告诉你的那样做:

    an `extern crate` loading macros must be at the crate root

    #[macro_use] extern crate glium; 放在 crate 根目录中,在您的情况下为 main.rs。确保extern crate 语句位于mod 语句之前,否则模块将无法访问导入的宏。

    然后您可以在子模块中使用宏。

    【讨论】:

    • 是的,这是我尝试的第一件事。它没有用。我仍然收到错误:宏未定义:'implement_vertex!'
    • 确保extern crate 语句位于mod 语句之前,否则模组将无法访问导入的宏。
    • 我得到了同样的错误,但tests/common.rs。那么test 目录的src/main.rssrc/lib.rs 有什么相似之处?
    • @VijaySali 通常,tests/ 中的每个.rs 文件都被编译为自己的小二进制包,并以您的主库作为依赖项。所以你必须在每个文件的顶部添加#[macro_use] extern crate glium;。如果您通过[[test]]Cargo.toml 中手动添加测试,那么这些就是您的板条箱根。
    • @VijaySali:正如 Lukas 在上面的评论中解释的那样,解决方案是将extern crate stuff; 添加到您的每个tests/<each-file>.rs。另外,请注意,如果您想在每个测试文件中定义一组通用函数,则不要将该通用文件定义为tests/common.rs,因为这将被视为另一个测试文件,而不是 Cargo。改为定义 tests/common/mod.rs。然后您可以将extern crate common 添加到您的测试文件中。
    【解决方案3】:

    我发现了我原来的问题。原来有 2 个 Cargo 根?我有lib.rsmain.rs。事实证明,放置#[macro_use] 的正确位置是lib.rs

    【讨论】:

    • 谢谢 - 这也帮助我尝试导入 riker-testkit 将此评论放在这里供其他人使用:将其放入您的 lib.rs:` #[macro_use] \n extern crate riker_testkit; `
    猜你喜欢
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 2020-12-06
    • 2016-10-31
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多