Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you import macros in submodules in Rust?

Tags:

rust

I have the following directory structure

  • /main.rs
  • /lib.rs
  • /tutorial/mod.rs
  • /tutorial/foo.rs

In foo.rs I need to use a macro from the glium library, implement_vertex!. If I put #[macro_use] extern crate glium; at the head of foo.rs, I get a error: an `extern crate` loading macros must be at the crate root. I also get a error: macro undefined: 'implement_vertex!'

There is also a lib.rs that is the crate root of the tutorial modules. I needed to put #[macro_use] there. Does this create 2 crate roots if I have both main.rs and lib.rs?

What is the correct way to import macros in a submodule?

like image 572
jz87 Avatar asked Aug 26 '16 23:08

jz87


People also ask

Can you use macros in Rust?

Rust has excellent support for macros. Macros enable you to write code that writes other code, which is known as metaprogramming. Macros provide functionality similar to functions but without the runtime cost. There is some compile-time cost, however, since macros are expanded during compile time.

How do I export macros in Rust?

macro_rules! macros can be exported from the current crate using #[macro_export] .


2 Answers

Macros are handled early enough in the compilation stage that order matters. You, like I, probably were getting nice and used to Rust magicking away the need to care about the order of your use and crate statements.

Move your #[macro_use] extern crate glium; statement to the top of your lib.rs and/or main.rs file as needed.

like image 166
John Anthony Avatar answered Sep 22 '22 14:09

John Anthony


Do it just like the compiler told you:

an `extern crate` loading macros must be at the crate root

Put the #[macro_use] extern crate glium; in the crate root, which is main.rs in your case. Make sure the extern crate statement is before your mod statements, otherwise the modules won't be able to access the imported macros.

You can then use the macro in your submodule.

like image 36
Lukas Kalbertodt Avatar answered Sep 20 '22 14:09

Lukas Kalbertodt