Use macro inside proc_macro crate


I have a crate with proc-macro = true inside Cargo.toml, because it exposes a procedural macro.

There is also a normal macro that is only used inside this crate.

How can I use this macro in one module of this crate if it is defined in another module of this crate?

Because if I write

macro_rules! internal_macro {...}

I get

error: cannot export macro_rules! macros from a `proc-macro` crate type currently

You can use the #[macro_use] attribute to import a macro from another module. The #[macro_export] attribute is just if you want to export it as part of the crate's public API.

// src/

mod macros;

internal_macro! { ... }
// src/

macro_rules! internal_macro { ... }
1 Like

Sorry, I forget that #[macro_use] belongs above mod modname instead of above use modname.
Thank you

Also, FWIW, I recommend people stop using #[macro_use] and that they use, instead, the more future-compatible and other-items-in-the-language-consistent mechanism of re-exporting a macro_rules! macro:

//! `src/`

macro_rules! internal_macro { … }
pub(crate) use internal_macro;

and then you can use crate::macros::internal_macro! anywhere in the crate :wink:


I'm mostly wondering how I missed the existence of this, managing the macro namespace can be a bit of a nightmare due to the way they're resolved. The use of pub use might improve on that if it means I can then import and use the macro anywhere in the crate (or dependent crates) like any other regular old item.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.