rust - 如何仅使用 rustc 而不是 cargo 链接动态 Rust 库?

标签 rust linker dynamic-linking ffi

我的 main.rs 看起来像

// #[link(name = "lib")]
extern "C" {
    fn hello();
}

fn main() {
    unsafe {
        hello();
    }
}

lib.rs:

#[no_mangle]
pub fn hello() {
    println!("Hello, World!");
}

我使用rustc --crate-type=cdylib lib.rs -o lib.so编译了lib.rs

如何将 lib.so 链接到 rustc main.rs 命令?

最佳答案

您需要匹配 ABI。当您使用 extern "C" block 时,您需要使用相同的 ABI 声明您的函数。

使用平台的约定命名您的动态库。在 macOS 上使用 .dylib,在 Windows 上使用 .lib,在 Linux 上使用 .so。如果您不提供 -o 选项,rustc 将自动为您执行此操作。

构建动态库后,您需要将其添加到编译器的链接器选项中。 rustc --help 有各种编译器选项的列表。 -L 将目录添加到搜索路径,-l 链接到特定库。

lib.rs

#[no_mangle]
pub extern "C" fn hello() {
    println!("Hello, World!");
}

ma​​in.rs

extern "C" {
    fn hello();
}

fn main() {
    unsafe {
        hello();
    }
}

编译并执行:

$ rustc --crate-type=cdylib lib.rs
$ rustc main.rs -L . -l lib
$ ./main
Hello, World!

因为我在 macOS 上,所以我使用 otool 来证明它确实是动态链接的:

$ otool -L main
main:
    liblib.dylib (compatibility version 0.0.0, current version 0.0.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.250.1)
    /usr/lib/libresolv.9.dylib (compatibility version 1.0.0, current version 1.0.0)

另见:


为了完整起见,这里是 crate 的“正常”链接:

lib.rs

pub fn hello() {
    println!("Hello, World!");
}

ma​​in.rs

fn main() {
    lib::hello();
}
$ rustc --crate-type=rlib lib.rs
$ rustc main.rs --extern lib=liblib.rlib
$ ./main
Hello, World!
$ otool -L main
main:
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.250.1)
    /usr/lib/libresolv.9.dylib (compatibility version 1.0.0, current version 1.0.0)

关于rust - 如何仅使用 rustc 而不是 cargo 链接动态 Rust 库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55537573/

相关文章:

rust - 理解 Rust `tt` 宏中的 `macro_rules!`

rust - 错误: The requirement is only added

GCC -rdynamic 不适用于静态库

rust - 这个展开的东西是什么 : sometimes it's unwrap sometimes it's unwrap_or

python - 通过 FFI 调用 Rust 函数时发生访问冲突

c - 在这种情况下,如何链接库函数?

c++ - Boost Mountain Lion 链接

linker - --unresolved-symbols=ignore-in-shared-libs 和 --allow-shlib-undefined 标志有什么区别

c++ - 在 Linux 上计时共享库加载时间

rust - 与 Rust 中的 native 库链接时将符号公开给动态链接器