2

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
DevAndreas
  • 21
  • 2
  • 1
    Yes, you can use path dependencies https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#specifying-path-dependencies – Zeppi Nov 02 '21 at 15:46
  • 1
    @Zeppi Thx for ur fast answer. Could you make an explicit example on how to use it in my project structure? – DevAndreas Nov 02 '21 at 15:58

1 Answers1

0

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.

Caesar
  • 6,733
  • 4
  • 38
  • 44