简体   繁体   中英

How to Rust macro in another project?

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

proj1 would need to be a hybrid bin/lib crate for you to be able to use a macro from it. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM