Passing build variables from command line/environment

Let's say one has a shell variable one wishes to be passed to the compiler -- how would one go about accomplishing this?

I have a C++ project which defaults a path to a directory relative to the build directory. In the C++ case I solve this using the preprocessor and do something akin to -DDEFAULT_PATH=$(pwd).

I'm thinking about porting this project to Rust and while I'm probably going to remove the default path feature completely, this problem made me randomly curious about the Rust case.

Apart from the obvious solutions of using sed or generating a source file from scratch prior to calling cargo build, is there an idiomatic way to get rust/cargo to do it as part of the build process?

Is this one of the things one would typically use build.rs for?

Your Rust code can use env!("DEFAULT_PATH") directly, without needing build.rs.

Cargo/rustc doesn't take -D directly, but setting an env var any other way should work, e.g. DEFAULT_PATH=$(pwd) cargo build.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.