1

I created a macro and 'exported' it in 'lib.rs' file like this:


pub mod utils {
  macro_rules! my_macro {
    () => {};
  }
  
  pub(crate) use my_macro;

}

The code above is working fine and I can use my_macro in all modules, But the problem is I can't use (import) it in 'tests' directory to test it. like so:

use my_crate::utils::my_macro;

The compiler gives me an error: 'macro my_macro is private'. So what should I do?

E_net4
  • 27,810
  • 13
  • 101
  • 139
  • what is you project file structure? is your `tests` directory in the crate root? if not, replacing `pub(crate)` with `pub` may fix it – Jeremy Meadows Jun 17 '22 at 14:55
  • @Jeremy Meadows tests directory is next to 'src' directory. replacing `pub(crate)` with pub gives me another error: 'my_macro is only public within the crate, and cannot be re-exported outside ' –  Jun 17 '22 at 14:57
  • 1
    Also relevant: https://stackoverflow.com/questions/26731243/how-do-i-use-a-macro-across-module-files The key thing here is that the tests in the "tests" directory are not in the same crate as the library. – E_net4 Jun 17 '22 at 15:14
  • Does this answer your question? [How do I use a macro across module files?](https://stackoverflow.com/questions/26731243/how-do-i-use-a-macro-across-module-files) – Chayim Friedman Jun 18 '22 at 23:57

1 Answers1

1

You should use [#macro_export] to export the macro from one crate to another. Like this.

#[macro_export]
pub mod utils {
  macro_rules! my_macro {
    () => {};
  }  
  pub(crate) use my_macro;
}
cargo_run
  • 79
  • 6