Does binary have to be single file?

Sometimes binary files becomes long (assumed), with several sturcts. For example,

// src/bin/some_bin.rs
struct SomeConfig {
    pub common_config: CommonConfig,
    ...
}

struct CommonConfig...
struct ...

fn main() {
    ...
}
// src/bin/some_other_bin.rs
struct SomeOtherConfig {
    pub common_config: CommonConfig,
    ...
}

struct CommonConfig...
struct ...

fn main() {
    ...
}

and SomeConfig and SomeOtherConfig may share some other structs.

Questions:

  1. Can one split some_bin.rs and some_other_bin.rs into several files in this case?

  2. Since SomeConfig is bound to some_bin.rs and SomeOtherConfig is bound to some_other_bin.rs, I think they should not be put into the library (lib.rs or other mod files)?

  3. Also, some_bin.rs and some_other_bin.rs may share some structs but are not in library level, then where should these shared ones be placed?

  4. Is workspace a good choice for this case? I haven't use workspace before, but it's more like sub-crates to me.

Thanks.

You can use a mod statement in the binary to load another file, or you can put the file in the library part of your project.

However, a workspace is likely a better choice, since it allows an entire project per binary.

2 Likes

https://doc.rust-lang.org/book/ch07-02-defining-modules-to-control-scope-and-privacy.html

This specific case you may want to use a lib.rs to define a shared library of code that gets compiled once and linked into each binary. The usage is just:

// src/lib.rs
pub struct CommonConfig...
pub struct ...

// src/bin/some_bin.rs
use my_crate_name::CommonConfig;

struct SomeConfig {
    pub common_config: CommonConfig,
    ...
}

fn main() {
    ...
}

// src/bin/some_other_bin.rs
// likewise...

Note that the common code needs to be pub, and that you need to import via the crate name, not crate or the like, just as if it was a separate crate.

This is a slightly less well supported setup, especially if the binary name is the same as the crate name, that can confuse cargo (or rather, the msvc toolchain it runs on windows), but it works well enough and saves a small amount of complexity.

Definitely look into workspaces, though, they are an extremely good tool to have as your projects get bigger.

1 Like

I used to go this way. But as I mentioned in the original post the CommonConfig may not be in the library level and very specific to binary/application level so I moved them...

Workspaces seems to be good for complex project structures.

Sorry, I missed that!

No worry :smile:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.