【问题标题】:Why does Rust export its whole standard library when building a DLL?为什么 Rust 在构建 DLL 时会导出其整个标准库?
【发布时间】:2015-02-21 22:16:30
【问题描述】:

我目前正在尝试使用 Rust 编写一个动态库,该库将从现有程序中加载。我需要导出一些具有特定名称和调用约定的函数。一切正常,但只要我use 标准库中的任何内容:

  • DLL 大小膨胀到超过 3MiB(不是很漂亮,但我可以忍受)
  • 整个标准库从 DLL 中导出。以下是所有导出的列表:http://pastebin.com/LsG1u96C(5100 个函数)

我是否缺少一些编译器开关? 我使用rustc 编译以下代码,没有任何选项:

#![crate_type = "dylib"]
#![feature(std_misc)]

use std::ffi::CString;

#[link(name = "user32")]
#[allow(non_snake_case)]
extern "stdcall" {
    fn MessageBoxA(hWnd: u32, lpText: *const i8, lpCaption: *const i8, uType: u32) -> u32;
}

#[no_mangle]
#[allow(non_snake_case)]
pub unsafe extern "stdcall" fn _AddLuaState(lua_state_ptr: u32)
{
    let info_str = format!("Lua State Created: {}!", lua_state_ptr);
    let info_cstring = CString::new(info_str).unwrap();
    let caption = CString::new("Hello from my Rust Library!").unwrap();
    MessageBoxA(0, info_cstring.as_ptr(), caption.as_ptr(), 0);
}

_AddLuaState@4 是唯一应该导出的函数。

这是在带有rustc 1.0.0-nightly (522d09dfe 2015-02-19) (x86) 的 Windows 8.1 机器上

更新:看起来当使用rustc -C prefer-dynamic 编译动态链接文件时,DLL 大小缩小到 60kiB,并且只有 3 个额外的导出 (http://pastebin.com/G0AYZrpF),这些看起来都很合理。但我还是更喜欢静态链接库。

【问题讨论】:

  • 用优化编译(rustc -Ocargo build --release)有什么效果吗?请注意,cargo 将发布/非发布二进制文件放在不同的目录中。
  • 使用优化编译只会将库缩小几个 kiB,但没有其他效果,cargo 发布版本也是如此。但是用-C prefer-dynamic编译有效果,请看我更新的帖子。
  • -C lto-C link-args=--gc-sections 做什么?我自己也不知道,只是把它扔在那里。
  • 链接时间优化仅适用于静态库,但我可以使用rustc -C link-args=-Wl,--gc-sections ldbg.rs 编译它。不幸的是,这里也没有效果。

标签: windows dll rust ffi


【解决方案1】:

最近添加了新的 crate 类型“cdylib”,它可能更适合您的用例。将源文件的第一行替换为:

#![crate_type = "cdylib"]

当使用 Cargo 包管理器而不是直接调用 rustc 时,更新 Cargo.toml 以包含以下行:

[lib]
crate-type = ["cdylib"]

更多详情请查看Rust pull request #33553

在我的测试中,它将以下简单的"Hello World" DLL 的大小从 650k (dylib) 减小到了 8k (cdylib)。导出符号的数量也大大减少。

#[no_mangle]
pub extern fn hello_rust() -> *const u8 {
    "Hello, world!\0".as_ptr()
}

【讨论】:

    猜你喜欢
    • 2016-06-04
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    • 2018-11-10
    • 2021-09-20
    • 2013-08-31
    相关资源
    最近更新 更多