Search code examples
rustrust-cargo

How to use shared module between two binaries in a Cargo package?


My project has a client and a server binary. So my Cargo.toml looks something like

[[bin]]
name = "server"
path = "src/server/mod.rs"

[[bin]]
name = "client"
path = "src/client.rs"

My file structure looks something like:

.
├── client.rs
├── server
│   ├── something.rs
│   └── mod.rs
└── shared
    ├── mod.rs
    └── something2.rs

What I want to do is use anything from shared in server/mod.rs. To do that I tried to have a mod shared and use crate::shared in the server/mod.rs but I got the error "no 'shared' in the root" (It is only looking in shared/). I don't have a main.rs where I could properly declare the modules.

So another thing I tried was using server.rs instead of server/mod.rs. This worked partially, as I now can declare mod shared. However, I cannot access anything in server/something.rs anymore. Is there any way to get the server.rs see the contents of server/ or is there a way to make server/mod.rs see the contents of a neighboring module without having a top level main.rs?


Solution

  • You can use the #[path] attribute:

    #[path = "../shared/mod.rs"]
    mod shared;
    

    But the proper way is to have a library, in addition to client and server, and make both depend on it.