如何生成静态链接的可执行文件? [英] How to generate statically linked executables?

查看:87
本文介绍了如何生成静态链接的可执行文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create a static executable with Rust. I am not trying to statically link a particular library, I am trying to create a executable which does not use dynamic linking at all. I have the following (otherwise working) test:

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

注意动态链接的解释器/lib64/ld-linux-x86-64.so.2.静态可执行文件具有 静态链接.(在我的例子中,损坏的部分标题大小,尽管如果我能说服 Rust 复制那个,我会很高兴.)

Note the dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2. Static executables have statically linked instead. (And in my case corrupted section header size, although I would be pleasantly astonished if I can convince Rust to replicate that.)

我需要将哪些选项传递给 rustc 以使其生成实际的静态可执行文件(具体而言:即使 file 同意的文件也是静态链接的).

What options do I need to pass to rustc to get it to generate a actual static executable (for concreteness: one which even file agrees is statically linked).

推荐答案

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

Since Rust 1.19, you can statically link the C runtime (CRT) to avoid this very common situation on Windows:

程序无法启动,因为您的文件中缺少 VCRUNTIME140.dll电脑.尝试重新安装程序以解决此问题.

The program can't start because VCRUNTIME140.dll is missing from your computer. Try reinstalling the program to fix this problem.

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

Add this to your .cargo/config file, using the appropriate target triple for your platform:

[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]

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

An alternative to editing .cargo/config is to pass -C target-feature=+crt-static to rustc by hand.

另见:

拉取请求

货物配置文档

这篇关于如何生成静态链接的可执行文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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