如何在构建 C 混合 Rust 静态库时找出要链接的本机库

问题描述 投票:0回答:0

我想用 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
.

问题:

  1. 有没有更自动化的方法来生成一个完全独立库?
  2. 如果设置
    /path/to/nativelibrary
    的方式是不可避免的,如何找到链接哪些原生库?

更新

到目前为止,我找到了三种可能的方法,无趣。

  • cargo clean && cargo build -vv 2>/dev/null | grep 'rustc-link-lib'
    可以帮助找出需要哪些本地库(见这里)。

  • crate

    pkg-config
    可以帮助探测特定的库,一旦你知道它们的名字(see here)。

  • crate

    cross
    可能有助于构建真正的静态二进制文件(see here),但我没有成功。

c rust static-libraries static-linking
© www.soinside.com 2019 - 2024. All rights reserved.