jz87
jz87

Reputation: 9627

How do you import macros in submodules in Rust?

I have the following directory structure

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?

Upvotes: 34

Views: 17679

Answers (3)

Shepmaster
Shepmaster

Reputation: 432059

I figured out my original problem. It turns out there are 2 Cargo roots? I have both a lib.rs and a main.rs. It turns out the correct place to put the #[macro_use] was in lib.rs.

Upvotes: 6

Lukas Kalbertodt
Lukas Kalbertodt

Reputation: 88986

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.

Upvotes: 11

John Anthony
John Anthony

Reputation: 257

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.

Upvotes: 24

Related Questions