Reuse macro in the same Rust crate across several files

macro_rules! allow unused_macros unused_imports mod pub

As you develop your project you probably start out with a single main.rs file and as the project growth you move some of the functions to other files. How can you move macros to other files?

This is what we had in src/main.rs before splitting up the code.

macro_rules! prt {
    ($var: expr) => {
        println!("{:?}", $var);
    };
}

fn main() {
    let x = 23;
    prt!(x);
}

We have a very simple macro in this example.

Moving the code:

We moved the macro_rules! definition in a file called src/macros.rs. The name of the file does not matter, but this seem to make sense. The definition did not have to change.

We added

pub(crate) use prt;

This will make the macro public to the current crate.

Finally we put the following line at the top of the file.

#![allow(unused_macros, unused_imports)]

This is probably only important if you don't want to use all the macros. Probably this is only relevant to me while I am writing examples to show Rust. In real-world code you probably would get rid of the macros you don't use or you'd create a separate crate that exports macros and then you'd import only the ones you need. Note the exlamation mark at the beginning!

The full file:

examples/reuse-macro-in-the-same-crate/src/macros.rs

#![allow(unused_macros, unused_imports)]

macro_rules! prt {
    ($var: expr) => {
        println!("{:?}", $var);
    };
}
pub(crate) use prt;

In the meantime in the src/main.rs file we added two lines:

mod macros;
use macros::prt;

The first one tells Rust that we know about the module called macros. The second line imports the macro into our namespace.

The full file:

examples/reuse-macro-in-the-same-crate/src/main.rs

mod macros;
use macros::prt;

fn main() {
    let x = 23;
    prt!(x);
}

See also this answer.

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo