Macro Design · 19 min · free with an account

Proc-Macro Boundaries

Lesson preview · about 30%

Separate host-time generation from target code.

Core idea

A procedural macro is compiled for and runs on the build host, then emits tokens for the target crate.

Start with the idea

A procedural macro is compiled for and runs on the build host, then emits tokens for the target crate. It cannot depend on target runtime state and should emit spans that point errors back to useful input.

Procedural macros run as host tools during compilation. They receive token input from the crate being built and return token output that the compiler later checks for the target. If you cross-compile from a Mac to a phone, the macro runs on the Mac; generated program code targets the phone. This is why host dependencies and target dependencies can have different requirements, and why a restricted on-device compiler may not support arbitrary proc-macro crates. Keep the generated program independent of accidental host-only paths or environment details.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Macros & Systems Rust