Skip to content

Automatically disable cast checks when building with optimization

Michael Catanzaro requested to merge mcatanzaro/cast-checks into main

Cast checks are slow. We seem to have some rough consensus that they are important for debug builds, but not for release builds. Problem is, very few apps define G_DISABLE_CAST_CHECKS for release builds. Worse, it's undocumented, so there's no way apps could even be expected to know about it.

We can get the right default is almost all situations by making this depend on the __OPTIMIZE__ preprocessor definition. This is a GCC-specific thing, although Clang supports it too. If the compiler does not define __OPTIMIZE__, then this commit does no harm: you can still use G_DISABLE_CAST_CHECKS as before. When checking __OPTIMIZE__, we are supposed to ensure our code has the same behavior as it would if we do not, which will be true except in case the check fails (which is programmer error).

Downside: this will not automatically do the right thing with -Og, because __OPTIMIZE__ is always defined to 1. We don't want to disable cast checks automatically if using -O0 or -Og. There's no way to automatically fix this, but we can create an escape hatch by allowing you to define G_DISABLE_CAST_CHECKS=0 to force-enable cast checks. In practice, I don't think this matters much because -Og kinda failed: GCC's man page says it should be a superior debugging experience to -O0, but it optimizes variables away so it's definitely not.

Another downside: this is bad if you really do want cast checks in release builds. The same solution applies: define G_DISABLE_CAST_CHECKS=0 and you'll get your cast checks.

Edited by Michael Catanzaro

Merge request reports