Ubuntu20 Rust实现静态编译文件

1,166 阅读1分钟

Ubuntu20 Rust实现静态编译文件

Linux 环境

Linux 下 rust 默认使用 gcc 作为链接器,编译后的文件在运行时需要glibc 运行库和其他的一些库。

这就导致在某个Linux版本下编译的执行文件,无法在另一个Linux版本上顺利运行。而且,如果你的程序还使用了OpenSSL动态库,那这样的问题会更加突出。

解决方案

我们可以通过静态编译生成新的可执行文件即可换一台linux也能执行你编译的文件

#更新
apt-get update
# 安装rustup
curl https://sh.rustup.rs -sSf | sh
# 设置环境变量
source "$HOME/.cargo/env"
# 下载x86_64-unknown-linux-musl库
rustup target add x86_64-unknown-linux-musl
rustup toolchain add nightly-x86_64-unknown-linux-gnu
rustup target add x86_64-unknown-linux-musl --toolchain=nightly
#下载musl-tools(核心)很多教程都没有教这个,如果不下载这个编译就可能过不去
sudo apt install musl-tools -y

restup下载速度慢

restup或者rust下载速度慢,我们可以设置更换成国内源或者设置代理

更换国内源

vim ~/.cargo/config.toml

#以下是填写内容
[source.crates-io]
registry = "https://github.com/rust-lang/crates.io-index"
replace-with = 'ustc'
[source.ustc]
# registry = "https://mirrors.ustc.edu.cn/crates.io-index"
registry = "https://mirrors.tuna.tsinghua.edu.cn/git/crates.io-index.git"
[http]
check-revoke = false

在这里插入图片描述

设置代理

vim ~/.cargo/config.toml

#以下是填写内容
[http]
proxy="ip地址:你的端口"

在这里插入图片描述

实验

# 用Cargo创建一个可执行项目
cargo new --bin hello
cd hello
cargo build --release --target=x86_64-unknown-linux-musl
#进入到可执行文件
cd ~/hello/target/x86_64-unknown-linux-musl/release
# 通过ldd查看是否有动态链接库
ldd hello

在这里插入图片描述 在这里插入图片描述 在这里插入图片描述