Patch external crates' build.rs before compiling them

I would like to use a library, which is using build.rs and seems its code compiles by using -O2 flag, but I want to reduce its size by passing -Os flag to its gcc.
Is it possible to patch/hook the build.rs of a crate before starting compile process (without forking or cloning original project. exactly same as running patch command before building them)?

I suggest you read trough this section: https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#overriding-dependencies.

In essence, just check out the crates source somewhere in your local filesystem, and modify the build.rs there. Then override the crates.io or git dependency with a [patch] section.

1 Like

Thank you for your clear answer.
In this case, I would like to use quickjs library, which uses libquickjs-sys, Is it possible to patch libquickjs-sys crate, which is an indirect dependency?

By the way, I suggest using binutils nm or cargo-bloat to analyze your final binary. This way you know what is really taking all that space in your binary. If you are targeting wasm, I bet there is an alternative tool.

Patching transitive dependencies should not be an issue at all. If it is, just import the crate directly.

1 Like

Thank you, I will try to patch indirect dependency by using nested override dependencies.
I am writing a tool for embedded devices, which is the final size important, the project requires an embedded scriptable language such as lua or js which can run users script and It should not require user code compilation.
I have chosen js because of its syntax.

@ruabmbua: I have read the references you have mentioned, I had forgotten to say I am looking for a method that doesn't require fork or cloning original project. Exactly same as running Linux's patch command before building them.

I looked int the sys crate. Seems like the Makefile already contains some logic for -Os. You can try to set CFLAGS, or a similar environment variable. Makefile will use these environment variables.

1 Like