Build script with multiple files?

Is there a way to specify an alternative to build.rs which includes modules spread across multiple files like a normal crate? The Cargo reference mentions that the build script is expected to be a file, so I'm guessing not, but maybe there's a workaround I'm not familiar with.

I think it would work -- cargo just invokes rustc, and that only cares that it can find modules relative to the primary input file. You can even use a starting path other than build.rs if you specify that in Cargo.toml.

Ah I didn't realize that rustc itself was that smart. I figured, just like gcc or a compiler like that, it would expect all source files to be fed to it by a tool like Cargo.

You can think of mod declarations somewhat like C #include in that regard.

1 Like

Gotcha, makes sense.

You can specify the root file using the package.build entry in Cargo.toml,then put its submodules in the same folder.

Example:

Cargo.toml

[package]
name = "foo"
version = "0.1.0"
build="build/main.rs"

Crate folder:

build/main.rs
build/submodule1.rs
build/submodule2.rs
src/lib.rs
Cargo.toml

build/main.rs:

mod submodule1;
mod submodule2;

fn main(){}

If you want to see a crate with a multi-file build script you can look here.

4 Likes

Yep, makes sense! Thanks for the complete example!

1 Like

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