如何找到当前 Rust 编译器的默认 LLVM 目标三元组?



我想覆盖一个构建脚本,这意味着添加一个如下所示的配置部分:

[target.x86_64-unknown-linux-gnu.foo]
rustc-link-search = ["/path/to/foo"]
rustc-link-lib = ["foo"]
root = "/path/to/foo"
key = "value"

但我使用的是Mac,所以x86_64-unknown-linux-gnu不是正确的目标三元组。

我如何发现当前使用的是哪个目标三重防锈剂或货物?

rustc --print cfg打印一个似乎与三元组不对应的值列表(特别是其中没有unknown(。

rustc --print target-list显示所有可用目标;我只想要默认值。

基于@konstin答案:

$ rustc -vV | sed -n 's|host: ||p'

它会给你一些类似的东西:

x86_64-unknown-linux-gnu

cargo使用rustc -vV来检测默认的目标三元组(源(。我们可以做同样的事情:

use std::process::Command;
use anyhow::{format_err, Context, Result};
use std::str;
fn get_target() -> Result<String> {
let output = Command::new("rustc")
.arg("-vV")
.output()
.context("Failed to run rustc to get the host target")?;
let output = str::from_utf8(&output.stdout).context("`rustc -vV` didn't return utf8 output")?;
let field = "host: ";
let host = output
.lines()
.find(|l| l.starts_with(field))
.map(|l| &l[field.len()..])
.ok_or_else(|| {
format_err!(
"`rustc -vV` didn't have a line for `{}`, got:n{}",
field.trim(),
output
)
})?
.to_string();
Ok(host)
}
fn main() -> Result<()> {
let host = get_target()?;
println!("target triple: {}", host);
Ok(())
}

我写了很多跨平台的shell脚本或Python程序,需要检查我当前的Rust默认目标三元组。不过,我不喜欢手动转换字符串值。

为了更容易获得默认的目标三元组,我将konstin的答案打包到一个命令行工具中。

你可以安装它与:

cargo install default-target

然后你只需运行就可以使用该程序

default-target

它会将你当前的目标值返回三倍。类似x86_64-apple-darwinx86_64-unknown-linux-gnu的东西。

您可以在crates.io、docs.rs和GitHub上找到有关机箱的更多详细信息。

您可以使用current_platform机箱:

use current_platform::CURRENT_PLATFORM;
fn main() {
println!("Running on {}", CURRENT_PLATFORM);
}

这将在桌面Linux上打印Running on x86_64-unknown-linux-gnu

与所有其他答案不同,这是零成本:平台是在编译时确定的,因此没有运行时开销。相比之下,对rustc的调用是昂贵的:如果Rust是通过rustup.rs安装的,则任何rustc命令都需要大约100ms。

使用最新的rustc编译器:

$ rustc -Z unstable-options --print target-spec-json | grep llvm-target

什么对我有效(受罗德里戈回答的启发(

RUSTC_BOOTSTRAP=1 rustc -Z unstable-options --print target-spec-json | python3 -c 'import json,sys;obj=json.load(sys.stdin);print(obj["llvm-target"])'

RUSTC_BOOTSTRAP=1跳过通常只允许在夜间分支上使用某些功能的检查。我还使用了一个合适的json解析器,而不是grep。

它可能不是特别优雅,但我发现它很有效:

rustup show | grep default | grep -Po "^[^-]+-KS+"

最新更新