Windows环境下Rust的tch crate编译失败原因求助
问题描述
尝试在Rust中使用tch crate时,编译阶段出现链接错误:
Creating library C:\Users\sefto\Documents\rust-projects\tch-test\target\debug\deps\tch_test.lib and object C:\Users\sefto\Documents\rust-projects\tch-test\target\debug\deps\tch_test.exp libtorch_sys-457a9014c45a8ec4.rlib(torch_api.o) : error LNK2001: unresolved external symbol __imp___tls_index_?init@?1??lazy_init_num_threads@internal@at@@YAXXZ@4_NA libtorch_sys-457a9014c45a8ec4.rlib(torch_api.o) : error LNK2001: unresolved external symbol __imp___tls_offset_?init@?1??lazy_init_num_threads@internal@at@@YAXXZ@4_NA C:\Users\sefto\Documents\rust-projects\tch-test\target\debug\deps\tch_test.exe : fatal error LNK1120: 2 unresolved externals
操作流程:
- 创建项目并添加依赖:
cargo new tch-test cd tch-test cargo add tch
- 修改
main.rs内容:
use tch::*; fn main() { println!("Hello, world!"); }
- 执行
cargo run触发错误。
已尝试操作:按照tch-rs官方文档安装libtorch并添加到PATH,也尝试让cargo自动安装libtorch,问题仍存在。
解决方案
1. 匹配编译器与工具链版本
Windows下tch-rs依赖MSVC编译器,确保安装Visual Studio 2019及以上版本,且Rust使用MSVC工具链:
- 检查当前工具链:
rustup show - 切换到MSVC工具链(如果当前不是):
rustup install stable-x86_64-pc-windows-msvc rustup default stable-x86_64-pc-windows-msvc
2. 手动指定兼容的libtorch版本
自动安装的libtorch可能存在架构或版本不匹配问题:
- 下载与Rust工具链架构(x86_64)一致的MSVC版libtorch
- 设置环境变量:
set LIBTORCH=C:\path\to\your\libtorch set PATH=%LIBTORCH%\lib;%PATH% - 或者在项目根目录创建
.cargo\config.toml,写入:[env] LIBTORCH = "C:/path/to/your/libtorch"
3. 清理缓存后重新编译
清除旧编译产物和缓存,避免依赖冲突:
cargo clean
之后重新执行cargo run。
4. 锁定tch crate到稳定版本
在Cargo.toml中指定已知兼容的tch版本,例如:
[dependencies] tch = "0.13.0"
5. 临时禁用多线程特性(workaround)
若上述方法无效,可尝试关闭多线程相关特性(会限制功能,仅作临时解决):
[dependencies] tch = { version = "*", default-features = false, features = ["cpu"] }
内容的提问来源于stack exchange,提问作者Sefton de Pledge
相关产品推荐
相关产品推荐

