Conditionally Define Crate-Level Attribute If Not Release

I've been trying to figure out a way to allow dead_code for non-release builds. So far, I've got this:

#![allow(dead_code)] // disable it at the crate-level

This is great for non-release builds, but how do I disable it for --release builds? Is there a way to do this?

Compilation profiles don't really give you that level of control, they're just a set of optimization settings. You can't detect optimization settings very easily in code.

What you might look at is build config. You could maybe arrange a build alias or to pass in a rustc-cfg flag that you can test against with #cgf(...). I have never used it, so I can't say if there's a combination that works.

A better option is probably to use debug_assertions as a standin-for non-release builds, so you can do this:

#![cfg_attr(debug_assertions, allow(dead_code))]
#![cfg_attr(not(debug_assertions), deny(dead_code))]

You could also use debug here, but neither is perfect.


Ah-hah, cfg_attr() was exactly what I was looking for. I was using debug_assertions in some of my attempts since that seems to be a common indicator between dev/prod. I couldn't figure out how to use that to conditionally enable things, and it looks like cfg_attr() is what does just that. I was also hoping that there'd be a way to also undefined certain flags, and it appears that there is a way with deny().


Deny doesn't really undefine cfg flags, what it does is convert a lint that would warn into a lint that errors. You can do allow, warn or deny on lints to choose the behavior.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.