Disambiguate the conditional compilation based on `#[cfg(...)]` macro

Suppose I am building an application that I want to deploy on different environments, e.g. LOCAL, DEV, SIT, UAT, PREPROD, PROD.

I would want conditional compilation on the codes based on what environment it is in, e.g. maybe in SIT it does not authenticate the user.

I am prepared to build different binaries for different environments.

What is the best practice for doing this?

  1. Via Cargo's custom profiles? It seems like setting RUSTFLAGS in custom profile is a nightly feature - I would want to stay on stable.

This seems like the sort of thing features are for. Just define a separate feature for enabling each conditional part of the code, and when you build for a given environment, pass the relevant features to --features.

Hi, thank you for your response.

Yes, it does indeed disambiguate the different environments but is not a clean solution.

This is because, fundamentally, cargo features are meant as a mechanism for users of library crates to determine what codes they want to include from the upstream crate into theirs.

A #[cfg(PROD)] or so would make a much cleaner solution for binary crate and my question is: how can one achieve this?

You can specify it in your project’s .cargo/config.toml file:

[build]
rustflags = ["--cfg", "PROD"]

I don't think this requires unstable rust.

3 Likes

Hi @alice

I think this is a good answer, totally incorporable into the CICD pipeline and serves my intention of wanting to write codes like:

#[cfg(PROD)]
fn authenticate(user: &User) {
    authenticate_user_seriously(user);
}

#[cfg(SIT)]
fn authenticate(user: &User) {
    let_user_pass(user);
}

Sorry for reviving an old question because I am revisiting it after some time, just curious if there is any other way to 'pass' rustflags (e.g. --cfg PROD) at build time via the cargo CLI? Looks like currently, the only way is to go through the .cargo/config.toml.

does setting the RUSTFLAGS environment variable not work for you?

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.