Share module between binaries in the same package


I have the following package src structure:

├── bin
│   └──

And in I have:

mod utils;

Now I need to use in bin/ (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/ cannot use anything in its parent directory as bin/ is basically its root?


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

pub mod utils;
use your_crate_name::utils;
// bin/
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 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/ defines a crate, src/ defines a crate, etc.

1 Like

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