我想用 Rust 创建一个静态库,然后在 C 程序中使用它。该库预计是 self-contained(即它的所有依赖项都是独立的)。
最初,
crate-type = ["staticlib"]
是在Cargo.toml
中加入的。但是这种方法似乎只在简单的情况下有效,在这种情况下,Rust 代码只包含基本功能而没有外部包装箱。
对于更复杂的 Rust 代码,上述方法可能无法构建 self-contained 库。在这种情况下,可以构建库,但不能被 C 程序使用。
我还了解到可以通过键入来构建一个 独立的 库
RUSTFLAGS='-C target-feature=+crt-static' cargo build --release --target=x86_64-unknown-linux-gnu
但是libaray搭建失败
error: linking with `cc` failed: exit status: 1
|
= note: LC_ALL="C" PATH="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
/usr/bin/ld: /lib/x86_64-linux-gnu/ld-linux-x86-64.so.2: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status> note: some `extern` functions couldn't be found; some native libraries may need to be installed or have their path specified
= note: some `extern` functions couldn't be found; some native libraries may need to be installed or have their path specified
= note: use the `-l` flag to specify native libraries to link
= note: use the `cargo:rustc-link-lib` directive to specify the native libraries to link with Cargo (see https://doc.rust-lang.org/cargo/reference/build-scripts.html#cargorustc-link-libkindname)>
我还阅读了官方说明的构建部分,从中我了解到本地库应该链接到 Rust cargo build,看起来像
RUSTFLAGS='-C target-feature=+crt-static -L /path/to/nativelibrary' cargo build --release --target=x86_64-unknown-linux-gnu
假设我的 Rust 代码使用了几十个外部 crate,每个 crate 也可能有自己的依赖,我真的不知道该填什么
/path/to/nativelibrary
.
问题:
/path/to/nativelibrary
的方式是不可避免的,如何找到链接哪些原生库?到目前为止,我找到了三种可能的方法,无趣。