简体   繁体   English

在Rust FFI中混合静态和动态库

[英]Mixing static and dynamic libraries in Rust FFI

My executable Rust crate uses a native library libfoo.a which depends on a shared library libbar.so , but does not expose it at all. 我的可执行文件Rust crate使用本机库libfoo.a ,它依赖于共享库libbar.so ,但根本不暴露它。

My Rust FFI uses the methods from libfoo, so I defined a link attribute on my extern code:: 我的Rust FFI使用libfoo中的方法,所以我在我的extern代码上定义了一个link属性::

#[link(name="foo", kind="static")]
extern "C"{
    pub fn do_foo();
}

and my build.rs included from Cargo.toml using build="build.rs" 和我的build.rs包含来自Cargo.toml使用build="build.rs"

fn main() {
    let libs = &[(Some("../libs/foo/1.0/"), "static=foo"), // use ../libs/foo/1.0/libfoo.a
                 (None, "bar")]; // use libbar.so using LD_LIBRARY_PATH
    for &(ref m_path, ref lib) in libs {
        if let &Some(static_path) = m_path {
            println!("cargo:rustc-link-search={}", &static_path);
        }
        println!("cargo:rustc-link-lib={}", &lib);
    }
}

which outputs 哪个输出

cargo:rustc-link-search=../libs/foo/1.0/
cargo:rustc-link-lib=static=foo
cargo:rustc-link-lib=bar

Theoretically, I expect Rust to link against libfoo.a and libbar.so . 从理论上讲,我希望Rust能够链接到libfoo.alibbar.so The problem is that rustc does not even try to acknowledge libbar . 问题是rustc甚至没有尝试承认libbar

cargo build --debug ends with cargo build --debug结束

/home/author/src/foo/foo.c:21: undefined reference to 'bar_do_stuff'
collect2: error: ld returned 1 exit status

When I inspect the linker command, there is an -L ../libs/foo/1.0 argument, as well as -l foo , but there is no trace of -l bar ! 当我检查链接器命令时,有一个-L ../libs/foo/1.0参数,以及-l foo ,但是没有-l bar跟踪!

If I manually add the -l bar to cc , it builds (and runs) just fine. 如果我手动将-l bar添加到cc ,它就可以构建(并运行)。

Could you let me know what I am missing? 你能让我知道我错过了什么吗? Should I create an FFI binding for libbar even though I don't use it in Rust and it is not exposed from libfoo's API? 我是否应该为libbar创建一个FFI绑定,即使我没有在Rust中使用它并且它没有从libfoo的API中公开?

The issue is a conflict between the #[link] attribute in the FFI definition and the output of the build.rs build script. 问题是FFI定义中的#[link]属性与build.rs构建脚本的输出之间存在冲突。

It would seem that the #[link] attribute is instructing rustc to ignore the cargo:rustc-link-* instructions. 似乎#[link]属性指示rustc忽略cargo:rustc-link-*指令。

The fix was as simple as removing the #[link] attribute. 修复就像删除#[link]属性一样简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM