如何从 Rust 可执行文件中导出符号? [英] How to export a symbol from a Rust executable?

查看:47
本文介绍了如何从 Rust 可执行文件中导出符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 Rust 可执行文件中导出符号:

I'm trying to export a symbol from a Rust executable:

#[allow(non_upper_case_globals)]
#[no_mangle]
pub static exported_symbol: [u8; 1] = *b"\0";

fn main() {
    println!("Hello, world!");
}

exported_symbol 似乎没有被生成的二进制文件导出:

exported_symbol doesn't appear to be exported by the resulting binary:

$ cargo build
$ nm ./target/debug/test_export| grep exported_symbol

另一方面,如果我用相同的源构建一个库,符号确实会被导出:

On the other hand, if I build a library with the same source, the symbol does get exported:

$ rustc --crate-type cdylib src/main.rs
$ nm libmain.so| grep exported_symbol
0000000000016c10 R exported_symbol

我在 Linux x86-64 上使用 Rust 1.18.0.

I'm using Rust 1.18.0 on Linux x86-64.

推荐答案

我建议在 .cargo/config 文件中使用这个而不是上面的:

I'd recommend this in the .cargo/config file instead of the above:

[build]
rustflags = ["-C", "link-args=-rdynamic"]

-rdynamic 更便携.特别是,它适用于 Linux 和 MacOS.

-rdynamic is more portable. In particular, it works both on Linux and MacOS.

此外,在当前的 Rust/LLVM 版本中,除非实际使用符号,否则链接器很可能会删除它.

Also, in current Rust/LLVM versions, unless a symbol is actually used, the linker is very likely to remove it.

为了避免这种情况,应该调用引用导出函数的虚拟函数(在任何时间点,例如在 main 函数中).

In order to avoid this, a dummy function referencing the exported functions should be called (at any point in time, such as in the main function).

这种函数的一个例子可能是:

An example of such a function could be:

pub fn init() {
    let funcs: &[*const extern "C" fn()] = &[
        exported_function_1 as _,
        exported_function_2 as _,
        exported_function_3 as _      
    ];
    std::mem::forget(funcs);
}

当然,导出的函数应该具有 #[no_mangle] 属性:

And of course, the exported functions should have the #[no_mangle] property:

#[no_mangle]
pub extern "C" fn exported_function_1() {
  // ...
}

这篇关于如何从 Rust 可执行文件中导出符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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