How to compile and run an optimized Rust program with overflow checking enabled

Kornel picture Kornel · Dec 2, 2015 · Viewed 8.8k times · Source

I'm writing a program that's quite compute heavy, and it's annoyingly slow to run in debug mode.

My program is also plagued by integer overflows, because I'm reading data from u8 arrays and u8 type spreads to unexpected places via type inference, and Rust prefers to overflow rather than to promote integers to larger types.

Building in release mode disables overflow checks:

cargo run --release

How can I build Rust executable with optimizations and runtime overflow checks enabled as well?

Answer

Shepmaster picture Shepmaster · Dec 3, 2015

You can compile in release mode with overflow checks enabled:

[profile.release]
overflow-checks = true

This passes -C overflow-checks=true to the compiler. In earlier versions of Rust, overflow-checks was part of the debug-assertions switch, so you may need to use that in certain cases.

Other times, the easiest thing might be to build in test or dev mode with optimizations:

[profile.dev]
opt-level = 3