问题
I'm writing a Cargo helper command that needs to know the default target triple used by Rust/Cargo (which I presume is the same as host's target triple). Ideally it should be a compile-time constant.
There's ARCH constant, but it's not a full triple. For example, it doesn't distinguish between soft float and hard float ARM ABIs.
env!("TARGET")
would be ideal, but it's set only for build scripts, and not the lib/bin targets. I could pass it on to the lib with build.rs
and dynamic source code generation (writing the value to an .rs
file in OUT_DIR
), but it seems like a heavy hack just to get one string that the compiler has to know anyway.
Is there a more straightforward way to get the current target triple in lib/bin target built with Cargo?
回答1:
Build scripts print some additional output to a file so you can not be sure that build script only printed output of $TARGET
.
Instead, try something like this in build.rs:
fn main() {
println!(
"cargo:rustc-env=TARGET={}",
std::env::var("TARGET").unwrap()
);
}
This will fetch the value of the $TARGET
environment variable in the build script and set it so it will be accessible when the program is started.
In my main.rs:
const TARGET: &str = env!("TARGET");
Now I can access the target triplet in my program. If you are using this technique, you'll only read the value of theTARGET
environment variable and nothing else.
回答2:
I don't think this is exposed other than through a build script. A concise way to get the target triple without "dynamic source code generation" would be, in build.rs
:
fn main() {
print!("{}", std::env::var("TARGET").unwrap());
}
and in src/main.rs
:
const TARGET: &str = include_str!(concat!(env!("OUT_DIR"), "/../output"));
fn main() {
println!("target = {:?}", TARGET);
}
来源:https://stackoverflow.com/questions/48967583/how-to-get-executables-full-target-triple-as-a-compile-time-constant-without-us