执行cargo test时,在加载build.rs中的共享库时出现错误

编程语言 2026-07-09

在我的 build.rs 中,我正在链接一个共享库 .so,使用 cmake-package crate。这个共享库是使用 cmake 构建的。运行 cargo test 时,出现如下错误信息。

错误信息如下:

error while loading shared libraries: libxyz.so.1.0.0: cannot open shared object file: No such file or directory

error: test failed, to rerun pass `-p abc --bin abc`

Caused by:
process didn't exit successfully: `/some/path/to/the/test/executable` (exit status: 127)

除了手动设置环境变量以包含共享库所在目录之外,是否还有其他方法可以使用 LD_LIBRARY_PATH=/path/to/library 呢?

解决方案

你可以通过在你的 build.rs 中使用 cargo:rustc-link-argcargo:rustc-link-search 指令,将库的搜索路径直接嵌入到二进制文件中,从而避免手动设置LD_LIBRARY_PATH。

你可以将 println!("cargo:rustc-link-search=native=/path/to/library"); 添加到你的build.rs,以便链接器在编译时就知道在哪里查找.so文件。对于在运行时无需环境变量进行发现,你也可以通过使用 println!("cargo:rustc-link-arg=-Wl,-rpath,/path/to/library"); 来设置 RPATHRUNPATH

https://blog.krzyzanowskim.com/2018/12/05/rpath-what/ 是一个了解rpath更多信息的好资源。

此外,Mac上的 man otool 和Linux上的 man ldd 也有一些有用的资源。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章