-
Notifications
You must be signed in to change notification settings - Fork 13.9k
Description
Code
fn main() {
println!("version {}", env!("CARGO_PACKAGE_VERSION"));
}Current output
error: environment variable `CARGO_PACKAGE_VERSION` not defined at compile time
--> src/main.rs:2:28
|
2 | println!("version {}", env!("CARGO_PACKAGE_VERSION"));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= help: Cargo sets build script variables at run time. Use `std::env::var("CARGO_PACKAGE_VERSION")` insteadDesired output
error: environment variable `CARGO_PACKAGE_VERSION` not defined at compile time
--> src/main.rs:2:28
|
2 | println!("version {}", env!("CARGO_PACKAGE_VERSION"));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= help: this is not a variable Cargo exposes to crates; did you mean "CARGO_PKG_VERSION"?Rationale and extra context
Cargo exposes environment variables to programs it's compiling in two different ways:
- When compiling regular Rust code, the environment variables are exposed directly to the compiler (accessible via the
env!macro); - When compiling a build script, the environment variable is exposed to the build script at runtime (accessible via
std::env::var).
Currently, if an attempt is made to use an environment variable that doesn't exist, rustc assumes that the program was trying to use the former method of receiving variables but cargo was trying to use the latter, and the suggestion is made on that basis. However, this suggestion is only valid when the user is actually compiling a build script.
There's another situation in which the environment variable might not exist: the user might not be compiling a build script, and instead might simply have got the name wrong. In this situation, the suggested fix is extremely wrong (because it leads to code that will compile, but malfunction at runtime, and misses the actual source of the problem). The suggestion I've suggested above is the "ideal", but even just removing the suggestion when not compiling a build script would be an improvement.
Other cases
Rust Version
Tested on the Rust playground:
version: 1.93.0-nightly (2025-11-02 b15a874aafe7eab9ea3a)Anything else?
@rustbot label D-incorrect