如何在模块文件中使用宏? [英] How do I use a macro across module files?
问题描述
我在同一板条箱中的单独文件中有两个模块,其中板条箱已启用macro_rules
.我想使用在另一个模块中一个模块中定义的宏.
I have two modules in separate files within the same crate, where the crate has macro_rules
enabled. I want to use the macros defined in one module in another module.
// macros.rs
#[macro_export] // or not? is ineffectual for this, afaik
macro_rules! my_macro(...)
// something.rs
use macros;
// use macros::my_macro; <-- unresolved import (for obvious reasons)
my_macro!() // <-- how?
我目前遇到了编译器错误"macro undefined: 'my_macro'
" ...,这很有意义;宏系统先于模块系统运行.我该如何解决?
I currently hit the compiler error "macro undefined: 'my_macro'
"... which makes sense; the macro system runs before the module system. How do I work around that?
推荐答案
同一箱子中的宏
#[macro_use]
mod foo {
macro_rules! bar {
() => ()
}
}
bar!(); // works
如果要在同一包装箱中使用宏,则定义宏的模块需要属性#[macro_use]
.
If you want to use the macro in the same crate, the module your macro is defined in needs the attribute #[macro_use]
.
宏只能在定义后 使用.这意味着这行不通:
Macros can only be used after they have been defined. This means that this does not work:
bar!(); // ERROR: cannot find macro `bar!` in this scope
#[macro_use]
mod foo {
macro_rules! bar {
() => ()
}
}
板条箱中的宏
要使用其他板条箱中的macro_rules!
宏,宏本身需要属性#[macro_export]
.然后,导入箱可以通过use crate_name::macro_name;
导入宏.
Macros across crates
To use your macro_rules!
macro from other crates, the macro itself needs the attribute #[macro_export]
. The importing crate can then import the macro via use crate_name::macro_name;
.
// --- Crate `util` ---
#[macro_export]
macro_rules! foo {
() => ()
}
// --- Crate `user` ---
use util::foo;
foo!();
注意:宏始终位于板条箱的顶层;因此即使foo
放在mod bar {}
内,user
板条箱仍必须写use util::foo;
和 not use util::bar::foo;
.
Note: macros always live at the top-level of a crate; so even if foo
would be inside a mod bar {}
, the user
crate would still have to write use util::foo;
and not use util::bar::foo;
.
(在Rust 2018之前,您必须通过在extern crate util;
语句中添加属性#[macro_use]
从其他包装箱中导入宏.这将从util
中导入所有宏.或者,#[macro_use(cat, dog)]
仅可用于导入宏cat
和dog
.不再需要使用此语法.)
(Before Rust 2018, you had to import macro from other crates by adding the attribute #[macro_use]
to the extern crate util;
statement. That would import all macros from util
. Alternatively, #[macro_use(cat, dog)]
could be used to only import the macros cat
and dog
. This syntax should not be necessary anymore.)
更多信息,请参见 Rust编程语言 .
More information is available in The Rust Programming Language.
这篇关于如何在模块文件中使用宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!