env::var("TARGET") always returns `x86_64-unknown-linux-gnu` in `build.rs`

Hi everyone,

I'm running into a strange issue with my build.rs script, and it's driving me crazy. No matter which target I specify, the following code always prints x86_64-unknown-linux-gnu and linux:

println!("cargo:warning=Target : {}", env::var("TARGET").unwrap());
println!("cargo:warning=Target OS : {}", env::var("CARGO_CFG_TARGET_OS").unwrap());

For example, when I run:

cargo +stable build --target wasm32-unknown-unknown
cargo +esp build --target xtensa-esp32s3-espidf

I still get x86_64-unknown-linux-gnu as the TARGET and linux as CARGO_CFG_TARGET_OS.

According to the Cargo documentation on environment variables for build scripts (Environment Variables - The Cargo Book), TARGET should be the target triple that is being compiled for.

Did I miss something? Is there a specific flag or setting needed to get build.rs to detect the correct target? Or is this expected behavior? (I don't think because it seems to disturb bindgen too).

Thanks for any help!

Is this perhaps the build script of a build dependency rather than of a runtime dependency?

1 Like

The mistake was that I placed the dependency in build-dependencies instead of dependencies, which caused the wrong target to be used. Everything is fine now. I sincerely apologize for taking up your time. Thank you!