如何仅使用rustc而不使用商品链接动态Rust库? [英] How to link a dynamic Rust library using only rustc and not cargo?

查看:274
本文介绍了如何仅使用rustc而不使用商品链接动态Rust库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的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.so链接到rustc main.rs命令?

推荐答案

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

You need to match ABIs. When you use an extern "C" block, you need to declare your functions using the same ABI.

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

Name your dynamic library using the platform's conventions. Use .dylib on macOS, .lib on Windows, and .so on Linux. rustc will do this for you automatically if you don't provide a -o option.

一旦构建了动态库,就需要将其添加到编译器的链接器选项中. rustc --help列出了各种编译器选项. -L将目录添加到搜索路径,并-l链接到特定库.

Once you have built your dynamic library, you need to add it to the compiler's linker options. rustc --help has a list of the various compiler options. -L adds a directory to the search path and -l links to a specific library.

lib.rs

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

main.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来表明它确实是动态链接的:

As I'm on macOS, I used otool to show that it's indeed dynamically linked:

$ 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)

另请参阅:

  • Linking Rust application with a dynamic library not in the runtime linker search path
  • How do I specify the linker path in Rust?

为完整起见,这是板条箱的常规"链接:

For completeness, here's "normal" linking of crates:

lib.rs

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

main.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)

这篇关于如何仅使用rustc而不使用商品链接动态Rust库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆