How to get executable's full target triple as a compile-time constant without using a build script?

自古美人都是妖i 提交于 2020-02-04 00:56:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!