Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import macros in Rust?

Tags:

macros

rust

glium

I'm struggling with how to import macros from an external crate. In my main.rs I'm importing the Glium crate:

#![macro_use]
extern crate glium;

pub use glium::*;

// where my actual main function will be done from
mod part01drawtriangle;

fn main() {
    part01drawtriangle::main();
}

In my other file, where my main function is coming from, I call one of the macros from that crate:

pub fn main() {
    implement_vertex!(Vertex, position);
}

When building, I get the error message:

error: macro undefined: 'implement_vertex!'
like image 414
Adityo Pratomo Avatar asked Jul 27 '16 12:07

Adityo Pratomo


2 Answers

According to the Rust Edition Guide:

In Rust 2018, you can import specific macros from external crates via use statements, rather than the old #[macro_use] attribute.

// in a `bar` crate's lib.rs:
#[macro_export]
macro_rules! baz {
    () => ()
}

// in your crate:
use bar::baz;

// Rather than:
//
// #[macro_use]
// extern crate bar;

This only works for macros defined in external crates. For macros defined locally, #[macro_use] mod foo; is still required, as it was in Rust 2015.

like image 53
Nickolay Avatar answered Nov 16 '22 12:11

Nickolay


#[macro_use], not #![macro_use].

#[..] applies an attribute to the thing after it (in this case, the extern crate). #![..] applies an attribute to the containing thing (in this case, the root module).

like image 21
DK. Avatar answered Nov 16 '22 13:11

DK.