【问题标题】:How can I create a static executable with rustc using glibc instead of musl?如何使用 glibc 而不是 musl 创建带有 rustc 的静态可执行文件?
【发布时间】:2019-10-23 15:54:17
【问题描述】:

我用 C、Go 和 Rust 编写了简单的代码。

foo.c

#include <stdio.h>

int main()
{
    printf("hello\n");
    return 0;
}

foo.go

package main

import "fmt"

func main() {
    fmt.Println("hello");
}

foo.rs

fn main() {
    println!("hello");
}

然后我把它们都建好了。

$ gcc -static -o cfoo foo.c
$ go build -o gofoo foo.go
$ rustc -o rustfoo foo.rs

它们运行良好。

$ ./cfoo; ./gofoo; ./rustfoo
hello
hello
hello

Rust 可执行文件的二进制文件与其他两个相比太小,所以我怀疑它不是静态可执行文件。

$ ls -l cfoo gofoo rustfoo
-rwxr-xr-x 1 lone lone  755744 Oct 23 21:17 cfoo
-rwxr-xr-x 1 lone lone 1906945 Oct 23 21:17 gofoo
-rwxr-xr-x 1 lone lone  253528 Oct 23 21:17 rustfoo

我确认 Rust 不会生成静态可执行文件。

$ ldd cfoo gofoo rustfoo
cfoo:
    not a dynamic executable
gofoo:
    not a dynamic executable
rustfoo:
    linux-vdso.so.1 (0x00007ffe6dfb7000)
    libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007fd8d9b75000)
    librt.so.1 => /lib/x86_64-linux-gnu/librt.so.1 (0x00007fd8d9b6b000)
    libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fd8d9b4a000)
    libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fd8d9b30000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fd8d996f000)
    /lib64/ld-linux-x86-64.so.2 (0x00007fd8d9bbb000)

有没有办法为 Rust 生成静态可执行文件?

我检查了其他类似的答案,他们谈论使用 musl。有没有办法用 glibc 生成静态可执行文件?如果我必须使用另一种方式,您能否提供一步一步的命令来生成带有rustc 的静态可执行文件?

【问题讨论】:

标签: rust runtime static-linking libc


【解决方案1】:

自从最初回答这个问题后,情况似乎已经发生了变化。

首先,您需要确保您的系统上有一个可用的静态链接 glibc。我使用的是 RHEL 系统,所以我这样做了:

sudo yum install glibc-static

我相信 Ubuntu / Debian 等价物是:

sudo apt-get install libc6-dev

之后,在编译程序时将选项 -C target-feature=+crt-static 传递给 rustc:

$ rustc -o rustfoo -C target-feature=+crt-static main.rs
$ ldd rustfoo
        not a dynamic executable

当然很少有人手动运行 rustc。您可以使用 RUSTFLAGS 环境变量指示 cargo 将此选项传递给 rustc,如下所示:

RUSTFLAGS="-C target-feature=+crt-static" cargo build --target x86_64-unknown-linux-gnu

您必须添加 --target 选项的原因是,即使您正在为主机平台构建,如果您不这样做,那么在构建编译时代码时将应用通过 RUSTFLAGS 提供的选项,例如proc 宏等可能导致编译失败。如果您明确指定目标平台,则 RUSTFLAGS 仅在为目标平台编译代码时应用。另见this bug report

如果您希望它始终像这样静态构建,而不需要环境变量,那么您可以在您的项目顶级目录中创建一个文件.cargo/config.toml,并将以下内容放入其中:

[build]
rustflags = ["-C", "target-feature=+crt-static"]
target = "x86_64-unknown-linux-gnu"

参考资料:

【讨论】:

  • 太棒了!目前它在 proc-macro crates 上存在问题。解决方法是始终指定目标RUSTFLAGS="-C target-feature=+crt-static" cargo build --target x86_64-unknown-linux-gnu --release。更多关于 github 上的问题:github.com/rust-lang/rust/issues/78210
  • 好消息@michalhosna。我已更新答案以包含该信息。
【解决方案2】:

【讨论】:

    猜你喜欢
    • 2021-03-17
    • 2015-06-24
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 2012-04-19
    相关资源
    最近更新 更多