How do I specify parameters to pass to `rustc` when building using dfx?

I want to use the cfg! macro to conditionally inject values depending on whether I’m running on dev or mainnet.

I imagine using cfg would be the best way to do this as environment variables are not available for the wasm32-unknown-unknown target as far as I’m able to figure out trying out the std::env::var module.

What’s the easiest way to execute conditional code depending on what environment canisters are being run on? Thoughts?

2 Likes

You should be able to use the env! macro, which is evaluated at compile time. The DFX_NETWORK environment variable will always be set, typically to either local or ic.

2 Likes

Thank you. Will try this and report findings.

1 Like

If you would like to create a cfg that corresponds to this environment variable, you can use a build script that prints cargo:rustc-cfg=mainnet (or cargo:rustc-cfg=network=ic, or similar) if the environment variable is set to ic.

https://doc.rust-lang.org/cargo/reference/build-scripts.html

2 Likes

NYC< Thanks We Will Try Thisss

Adding to this answer, using the env! macro will not work as that will lead to a compiler error as shown below

image

You will need to use the option_env! macro for this to work. Like this

image