Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 380
Kornel Avatar asked Feb 24 '18 21:02

Kornel


2 Answers

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.

like image 199
Ishan Jain Avatar answered Oct 15 '22 23:10

Ishan Jain


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);
}
like image 25
dtolnay Avatar answered Oct 15 '22 23:10

dtolnay