Machine generated code as part of cargo build


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, 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?



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.

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

mod pre_gen;
use pre_gen::*;

even though pre-compilation your directory looks like this


because afterwards it’ll look like this


and then will be compiled.

1 Like


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

1 Like