Example macro_rules! that depends on target

I want a define a macro magic where:

on target=wasm32, magic!(...) maps to wasm32_macro!(...)

and otherwise, magic!(...) maps to default_macro!(...)

Is there a simple way to do this via macro_rules! (or other techniques, besides using procedural macros?)

You can use the #[cfg(...)] attribute to only include items if a condition is met, and use ... as ... to rename items.

#[cfg(target_arch = "wasm32")]
use wasm32_macro as magic;

#[cfg(not(target_arch = "wasm32"))]
use default_macro as magic;

You can also put the #[cfg(...)] directly on the definition of the macros if you prefer.

#[cfg(target_arch = "wasm32")]
macro_rules! magic { ... }

#[cfg(not(target_arch = "wasm32"))]
macro_rules! magic { ... }

This solution solves the problem in a way I did not expect.

Initially, I thought there would be some way where inside of macro_rules! magic { .. }, there would be some special parameter that allowed us to query what target we are compiling for.

However, your solution seems to take a different approach. The magic macro is "dumb", and the "dispatch" is done via #cfg[(target...)], so the magic macro has no logic for handling which target we are on, but the cfg preprocessor (not sure if correct name) ensures the magic is bound to the right target-specific-macro.

Is this correct?

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.