这是一个Minimal, Reproducible Example ,展示了你经历过的同样问题.我创建了一个C库,导出了一个简单的加法函数.我还创建了一个Cargo项目来使用这个功能.
dynlink/
├── executable
│ ├── build.rs
│ ├── Cargo.lock
│ ├── Cargo.toml
│ └── src
│ └── main.rs
└── library
├── awesome_math.c
└── libawesome_math.so
awesome_math.c
#include <stdint.h>
uint8_t from_the_library(uint8_t a, uint8_t b) {
return a + b;
}
该图书馆被编译为gcc -g -shared awesome_math.c -o libawesome_math.so
本.
src/main.rs
extern {
fn from_the_library(a: u8, b: u8) -> u8;
}
fn main() {
unsafe {
println!("Adding: {}", from_the_library(1, 2));
}
}
build.rs
fn main() {
println!("cargo:rustc-link-lib=dylib=awesome_math");
println!("cargo:rustc-link-search=native=/home/shep/rust/dynlink/library");
}
Cargo.toml
[package]
name = "executable"
version = "0.1.0"
edition = "2021"
[profile.dev]
rpath = true
进一步调查后,我让Rust编译器打印出它将要使用的链接器参数:
cargo rustc -- --print link-args
这本书印出了一大堆东西,但一条重要的线索是:
"-Wl,-rpath,$ORIGIN/../../../../../../.rustup/toolchains/nightly-aarch64-unknown-linux-gnu/lib/rustlib/aarch64-unknown-linux-gnu/lib"
这是指向链接器的指令,用于将特定值添加到完成的二进制文件的rpath中.缺少对我们正在链接的动态库的任何引用.回想起来,这可能是有道理的,因为编译器如何知道我们希望将其包含在rpath中?
解决方法是向链接器添加另一个指令.有一些有趣的选项(比如$ORIGIN
),但为了简单起见,我们将只使用绝对路径:
cargo rustc -- -C link-args="-Wl,-rpath,/home/shep/rust/dynlink/library/"
生成的二进制文件以ldd
为单位打印正确的内容,并在不设置LD_LIBRARY_PATH
的情况下运行:
$ ldd ./target/debug/executable | grep awesome
libawesome_math.so => /home/shep/rust/dynlink/library/libawesome_math.so (0x0000ffffb1e56000)
$ ./target/debug/executable
Adding: 3
说到相对性,我们可以使用$ORIGIN
:
cargo rustc -- -C link-args='-Wl,-rpath,$ORIGIN/../../../library/'
小心地为shell正确转义$ORIGIN
,记住路径是相对于executable的,而不是当前工作目录.
另见: