Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using another macro in a macro_rules without requiring `extern crate` in rust

Tags:

macros

rust

Is there a way to "re-export" #[macro_use] extern crate similar to pub use so that users of a macro using macros do not have to manually add these dependent extern crates?

The rest of the question is an example to illustrate.

In src/lib.rs, note that the id macro is using the lazy_static macro:

#[macro_export]
macro_rules! id {
    () => {
        lazy_static! {
            static ref NUMBER : std::sync::atomic::AtomicUsize =
                std::sync::atomic::AtomicUsize::new(0);
        }
        return NUMBER.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
    }
}

In examples/example.rs, we need an extern crate line for each macro, even though we're just using the id macro directly:

#[macro_use]
extern crate id_macro;
#[macro_use]
extern crate lazy_static;

fn new_id() -> usize {
    id!();
}

fn main() {
    println!("id {}", new_id()); // prints "id 0"
    println!("id {}", new_id()); // prints "id 1"
}

In the example, it would be great if the user of id_macro could use id! without knowing about lazy_static. Is there a way to "re-export" extern crate similar to pub use to make the following lines go away from the example?

#[macro_use]
extern crate lazy_static;
like image 338
Johannes Hoff Avatar asked Jan 28 '26 17:01

Johannes Hoff


1 Answers

There is an unstable macro_reexport attribute.

However, Rust is working on making macros (2.0) behave like normal items that support pub use, so this attribute won't be stable and will become obsolete.

like image 51
Kornel Avatar answered Feb 01 '26 11:02

Kornel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!