Share module between binaries in the same package

Hi,

I have the following package src structure:

src
├── bin
│   └── foo.rs
├── main.rs
└── utils.rs

And in main.rs I have:

mod utils;

Now I need to use utils.rs in bin/foo.rs (another binary) as well, what is the proper way to do that? I was not able to find such example.

Further, is it true that bin/foo.rs cannot use anything in its parent directory as bin/ is basically its root?

Thanks.

If you wish to share something between several binaries, you need to put it in a lib.rs.

// lib.rs
pub mod utils;
// main.rs
use your_crate_name::utils;
// bin/foo.rs
use your_crate_name::utils;

The your_crate_name thing here is whatever you named your crate in your Cargo.toml.

Thanks for your answer. I have a couple of questions:

  1. Sometimes not all binaries share all shared modules. Will all modules listed in lib.rs always linked into every binary?

  2. In my Cargo.toml, I have package name, but not crate name. By your_crate_name, did you mean the package name, or something else?

My understanding is that src/ and src/bin are two different crates in the same package. But I might be wrong.

Yes, I'm referring to the package key in your Cargo.toml. I haven't heard of the package/crate distinction before.

As for the linking, if you turn on lto, unused code paths should be removed. You can also turn your project into a workspace if you wish to have several library crates.

1 Like

Got it. Thanks for helpful info. Btw, here is where I learned about package and crate.

Folks tend to use them interchangeably. A Cargo.toml defines a package, which can have one or many crates. (this is why the first line of your Cargo.toml is [package]. A crate is "a thing you pass to rustc", so like, src/main.rs defines a crate, src/lib.rs defines a crate, etc.

1 Like

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