Search code examples
macrosrustrust-macros

Is it possible to have one crate with both procedural macros and logic?


When you want to share a library that uses a procedural macro, is the dual crate approach foo/foo_derive inevitable?

I would like to provide a crate that has the logic and the macros. The first thing I tried was:

my_proc_macro
├── Cargo.toml
├── src/lib.rs
└── my_crate
    ├── Cargo.toml
    └── src/lib.rs

In the my_proc_macro crate, I tried to pub use my_crate::*; but it is forbidden to do so: the compiler refused to build this.

Is it possible to do this the other way around? I mean: import the procedural macro crate into the library and then reexport the macro?


Solution

  • It's actually quite straight-forward to re-export macros. Simply use

    #[macro_use]
    extern crate my_proc_macro;
    

    in the root of my_crate.

    The serde crate can be used this way when enabling the feature serde_derive.

    In the 2018 edition, you can also explicitly re-export proc macros using use declarations.