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?
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?
This answer is outdated as of Rust 1.1.0-stable.
You need to add
#![macro_escape]
at the top ofmacros.rs
and include it usingmod macros;
as mentioned in the Macros Guide.For future reference,
Adding
#![macro_use]
to the top of your file containing macros will cause all macros to be pulled into main.rs.For example, let's assume this file is called node.rs:
Your main.rs would look sometime like the following:
Finally let's say you have a file called toad.rs that also requires these macros:
Notice that once files are pulled into main.rs with
mod
, the rest of your files have access to them through theuse
keyword.Macros within the same crate
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:
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 viause crate_name::macro_name;
.Note: macros always live at the top-level of a crate; so even if
foo
would be inside amod bar {}
, theuser
crate would still have to writeuse util::foo;
and notuse util::bar::foo;
.(Before Rust 2018, you had to import macro from other crates by adding the attribute
#[macro_use]
to theextern crate util;
statement. That would import all macros fromutil
. Alternatively,#[macro_use(cat, dog)]
could be used to only import the macroscat
anddog
. This syntax should not be necessary anymore.)More information is available in The Rust Programming Language.