Cargo指定自定义构建目标失败,加载目标规范报错求助
解决Rust自定义目标文件加载错误:expected value at line 1 column 1
问题重现
我在开发简易Rust OS时,按照教程创建了自定义目标文件x86_64-simple_os.json,配置了.cargo/config.toml和Cargo.toml,并指定使用nightly工具链,但执行cargo build --target x86_64-simple_os.json时出现以下错误:
$ cargo build --target x86_64-simple_os.json error: failed to run `rustc` to learn about target-specific information Caused by: process didn't exit successfully: `C:\Users\12081\.rustup\toolchains\nightly-x86_64-pc-windows-msvc\bin\rustc.exe - --crate-name ___ --print=file-names --target '\\?\C:\Users\12081\OSTutorial\simple_os\x86_64-simple_os.json' --crate-type bin --crate-type rlib --crate-type dylib --crate-type cdylib --crate-type staticlib --crate-type proc-macro --print=sysroot --print=split-debuginfo --print=crate-name --print=cfg` (exit code: 1) --- stderr error: Error loading target specification: expected value at line 1 column 1. Run `rustc --print target-list` for a list of built-in targets
我的配置文件
目标文件 x86_64-simple_os.json
{ "llvm-target": "x86_64-unknown-none", "data-layout": "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128", "arch": "x86_64", "target-endian": "little", "target-pointer-width": "64", "target-c-int-width": "32", "os": "none", "executables": true, "linker-flavor": "ld.lld", "linker": "rust-lld", "panic-strategy": "abort", "disable-redzone": true, "features": "-mmx,-sse,+soft-float" }
.cargo/config.toml
[unstable] build-std = ["core", "compiler_builtins"] [build] target = "x86_64-simple_os.json"
Cargo.toml
[package] name = "simple_os" version = "0.1.0" edition = "2021" [profile.dev] panic = "abort" [profile.release] panic = "abort" [dependencies]
rust-toolchain 文件
内容为:nightly
解决方案
这个错误的核心是rustc无法正确解析自定义目标JSON文件,常见修复步骤如下:
移除JSON文件的UTF-8 BOM编码
Windows下默认新建的UTF-8文件会带BOM(字节顺序标记),但rustc的JSON解析器不支持该格式。用编辑器(比如VS Code)打开x86_64-simple_os.json,点击右下角编码选项,选择「通过编码保存」,再选「UTF-8」(不要选UTF-8 with BOM)。验证JSON格式正确性
检查文件是否存在语法错误,比如多余逗号、未闭合括号。可以用rustfmt格式化文件:rustfmt x86_64-simple_os.json若格式错误会直接抛出提示。
确认文件路径与命令有效性
- 确保
x86_64-simple_os.json放在项目根目录(和Cargo.toml同一层级)。 - 路径无空格时直接执行命令即可;若有空格,用引号包裹路径。
- 确保
清理缓存重新构建
清除Cargo缓存避免旧数据干扰:cargo clean cargo build --target x86_64-simple_os.json检查rust-toolchain文件
确保文件内容仅为nightly,无多余换行、空格或注释,保证rustup能正确识别工具链版本。
内容的提问来源于stack exchange,提问作者Duncan McPherson
相关产品推荐
相关产品推荐

