How to Rust macro in another project?

Viewed 75

Hi is it possible to use a custom declarative macro across multiple projects? If yes, how?

The project tree structure looks like this: (the macro is defined in proj1)

.
├── proj1
│   ├── Cargo.toml
│   └── src
│       └── main.rs
├── proj2
│   ├── Cargo.toml
│   └── src
│       └── main.rs
└── proj3
    ├── Cargo.toml
    └── src
        └── main.rs
1 Answers

proj1 would need to be a hybrid bin/lib crate for you to be able to use a macro from it. This would mean moving your macro to a proj1/src/lib.rs. However, I suggest you move common functionality to a different crate, let's call it lib1. The rest has already been described in detail, so here is a quick demo only:

cargo new --lib lib1
cargo new proj2
echo 'lib1 = { path = "../lib1" }' >>proj2/Cargo.toml
echo '#[macro_export] macro_rules! mahcro { () => { println!("Hello macro.") } }' >lib1/src/lib.rs
echo 'use lib1::mahcro; fn main() { mahcro!() }' >proj2/src/main.rs
cargo run --manifest-path proj2/Cargo.toml

By the way, workspaces are really useful in this kind of setup, I recommend you read up on them.

Related