Workspace Setup and proc-macro Crate

I'm starting to experiment with macros, and wanted to try building an attribute proc-macro. I added proc-macro = true to my .toml file, but I got the following error:

error: cannot export macro_rules! macros from a `proc-macro` crate type currently

I did some digging online to understand this error a little better, and found a helpful answer about this on StackOverflow.

it sounds like proc macros are essentially extensions for the compiler, and not the implementing project code, so the macro source is something that's actually separate from my implementing crate. My project is set up as a Rust workspace, so I was going to create a new create specifically for my procedural macros, then have any other crates in that workspace depend on that crate as necessary.

Is this generally a good approach to breaking up my project structure when developing procedural macros?

You need two crates, a "backend" crate that defines the procedural macros and the procedural macros only, and a "frontend" crate that re-exports the procedural macros and defines everything else (functions, types, traits, #[macro_export] macro_rules! macros).

I detailed this pattern in this post: Proc macros - using third party crate

1 Like

Ah, so that's how it's done. That makes a lot of sense as well since the procedural macros are an extension of the compiler, and if other constructs depend on it, then the code that builds the macro needs to be built ahead of time in order to be used (as an extension of the compiler). So, procedural macros go into their own build target (the backend), and everything directly utilizing it into the frontend.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.