Johannes Hoff
Johannes Hoff

Reputation: 3901

Using another macro in a macro_rules without requiring `extern crate` in 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;

Upvotes: 3

Views: 1116

Answers (1)

Kornel
Kornel

Reputation: 100110

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.

Upvotes: 3

Related Questions