Machine generated code as part of cargo build

#1

I want to have a step of the build process generate some rust code then compile it as part of the current crate being built.
I tried using build.rs, which wwill generate the file of code I want, but it is not then compiled by rustc.
Of course I can have a pre-compilation step, but can I make it part of cargo build?

0 Likes

#2

The Rust file designated by the build command (relative to the package root) will be compiled and invoked before anything else is compiled in the package, allowing your Rust code to depend on the built or generated artifacts.

https://doc.rust-lang.org/cargo/reference/build-scripts.html

So therefore you could output your code to a file (Which we’ll call pre_gen.rs) and depend on it in your main code:

mod pre_gen;
use pre_gen::*;

even though pre-compilation your directory looks like this

src
-> main.rs

because afterwards it’ll look like this

src
-> main.rs
-> pre_gen.rs

and then will be compiled.

1 Like

#3

Duh! Silly me!
I had the correct approach but I had forgotten to include the generated file in my lib.rs

1 Like