Can you include a macro from a sub-module?

Is there any way to something like this?:

mod utils {
    macro_rules! say_hi {
        () => {
            println!("Hi!! :waving:")
        };
    }
}

mod program {
    pub(crate) fn do_program_stuff() {
        use crate::utils;
        println!("Doing program stuff");
        utils::say_hi!();
    }
}

fn main() {
    program::do_program_stuff();
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0433]: failed to resolve: could not find `say_hi` in `utils`
  --> src/main.rs:13:16
   |
13 |         utils::say_hi!();
   |                ^^^^^^ could not find `say_hi` in `utils`

warning: unused macro definition
 --> src/main.rs:2:5
  |
2 | /     macro_rules! say_hi {
3 | |         () => {
4 | |             println!("Hi!! :waving:")
5 | |         };
6 | |     }
  | |_____^
  |
  = note: `#[warn(unused_macros)]` on by default

error: aborting due to previous error

For more information about this error, try `rustc --explain E0433`.
error: could not compile `playground`.

To learn more, run the command again with --verbose.

I did find out that this works:

mod utils {
    #[macro_export]
    macro_rules! say_hi {
        () => {
            println!("Hi!! :waving:")
        };
    }
}

mod program {
    pub(crate) fn do_program_stuff() {
        println!("Doing program stuff");
        crate::say_hi!();
    }
}

fn main() {
    program::do_program_stuff();
}

But I want to know if there is a way to export it without having to put all of the macros in the root of the crate.

1 Like

macros are always exported to crate root, so no

3 Likes

OK, thanks.

I'll just put all my macros in a macros module then and #[macro_use] them in the crate root. That makes them globally accessible from anywhere in the crate.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.