如何生成静态链接的可执行文件?

Dav*_*d X 31 static-linking rust

我正在尝试使用Rust创建一个静态可执行文件.我不是试图静态链接特定的库,我试图创建一个根本不使用动态链接的可执行文件.我有以下(否则工作)测试:

$ cat hello.rs
fn main()
    {
    print!("Hello, world!\n");
    }
$ rustc hello.rs -o hello
$ file hello
hello: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV),
 dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, [etc]
Run Code Online (Sandbox Code Playgroud)

请注意dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2.statically linked相反,静态可执行文件.(就我而言corrupted section header size,如果我能说服Rust复制那个,我会感到非常惊讶.)

我需要传递什么选项rustc才能使它生成一个实际的静态可执行文件(具体来说:一个甚至file同意静态链接的选项).

Ste*_*nik 21

除默认情况下,Rust静态链接除glibc(和libgcc,iirc)之外的所有内容.

如果要获得100%静态链接的二进制文件,可以使用MUSL和1.1.https://github.com/rust-lang/rust/pull/24777是最初的支持,我们希望将来更容易使用.

  • 它现在通过 rustup 分发,因此您可以“rustup target add x86_64-unknown-linux-musl”,然后“cargo build --target=x86_64-unknown-linux-musl” (3认同)
  • 在2019年,``musl''是否仍然是获得100%静态链接二进制文件的唯一方法?我们现在可以用glibc获得100%静态链接的二进制文件吗? (2认同)
  • @SteveKlabnik 这应该是它自己的答案!谢谢。 (2认同)

ark*_*kod 15

从Rust 1.19开始,您可以静态链接C运行时(CRT)以避免在Windows上出现这种非常常见的情况:

程序无法启动,因为您的计算机缺少VCRUNTIME140.dll.尝试重新安装该程序以解决此问题.

.cargo/config使用适合您平台的目标三元组将其添加到您的文件中:

[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]
Run Code Online (Sandbox Code Playgroud)

编辑的另一种方法.cargo/config-C target-feature=+crt-static手工传递给rustc.

也可以看看:

  • 自 1.48 起,此编译器选项现在也可用于“linux-gnu”目标。https://github.com/rust-lang/rust/blob/master/RELEASES.md#version-1480-2020-11-19 (2认同)
  • 使用“cargo build”时如何做到这一点? (2认同)