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

标签 rust static-linking

我正在尝试使用 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]

注意动态链接解释器/lib64/ld-linux-x86-64.so.2。静态可执行文件有 statically linked 代替。 (在我的例子中,损坏的节头大小,尽管如果我能说服 Rust 复制那个,我会感到惊喜。)

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

最佳答案

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

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

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

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

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

另见:

关于rust - 如何生成静态链接的可执行文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31770604/

相关文章:

clang - 如何在 gentoo(glibc 配置文件)和 clang 上静态构建 musl-libc?

rust - 包含具有不同要求和冲突的参数的 Clap arg 组

python - 通过 FFI 调用 Rust 函数时发生访问冲突

rust - 在 Rust 中计算两个 f64 向量的点积的最快方法是什么?

rust - 捕获无法复制的移动值

rust - 为什么这个闭包的生命周期会根据看似无关的类型而改变?

gcc - "Undefined reference "到静态库中定义的函数

opencv - 如何在 Qt 项目中静态链接 OpenCV

ffmpeg - 如何正确地将 ffmpeg 链接到静态构建 "g++ -static"?

c++ - 链接时不同静态库中的相同目标文件