Search code examples
rustrust-cargo

Cargo project with library + multiple binaries, with binaries consisting of multiple files?


The Cargo book describes how to have a library and multiple executable in a single Cargo project.

I'd like to have an executable consist of multiple source files that are specific to that executable and not in the library.

For example

  • src/lib1.rs, src/lib2.rs, src/lib3.rs in the library itself,
  • src/bin/exe1.rs + another source file specific to exe1 for the exe1 executable.

Where would I place this last source file so that it's not compiled into the library but compiled into the executable?


Solution

  • The Cargo-supported way to have multiple source files for a single binary in a package is to give it a directory with main.rs. The documentation on “Package Layout” gives this example (I have removed irrelevant elements):

    src/
    ├── lib.rs
    └── bin/
        ├── named-executable.rs
        ├── another-executable.rs
        └── multi-file-executable/
            ├── main.rs
            └── some_module.rs
    

    You want the multi-file-executable case here. Name the directory whatever you want the binary to be named. Your main.rs will then contain mod some_module; in just the same way as if this project had been a simple src/main.rs project.