Windows下搭建RUST编译环境

前言

  1. rust在windows上有两种链接形式

一种是兼容windows ABI库需要vs studio。安装完3个G起步
一种是兼容gnu ABI库安装形式是gnu toolchain,这种rustup自动下载100多M安装包就行

  1. 这两种安装形式的区别是:

msvc toolchain支持windows下用msvc编译的库文件,比如windows提供的系统库,与windows其他软件兼容较好,所以是推荐安装
gnu toolchain主要支持gnu ABI格式,比如一些广泛使用的gcc编译的开源库

  1. 一般rust开发的程序只调用rust库或开源跨平台库用gnu toolchain就可以了

安装Rust编译环境

  1. 可以设置一些环境变量来改变默认安装的位置,建议添加到系统变量
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
设置变量 CARGO_HOME 指定cargo的安装目录,默认路径 $HOME/.cargo 或者 %USERPROFILE%/.cargo
设置变量 RUSTUP_HOME 指定rustup的安装目录,默认路径 $HOME/.rustup 或者 %USERPROFILE%/.rustup

set CARGO_HOME=C:\Soft\Rust\cargo_home
set RUSTUP_HOME=C:\Soft\Rust\rustup_home
set PATH=%PATH%;%CARGO_HOME%\bin


# rustup默认直接从官网下载会很慢容易失败。推荐设置以下环境变量使用科大镜像加速安装:
set RUSTUP_DIST_SERVER=https://mirrors.ustc.edu.cn/rust-static
set RUSTUP_UPDATE_ROOT=https://mirrors.ustc.edu.cn/rust-static/rustup


# cargo默认从https://crates.io下载依赖包也一样,可修改添加配置文件:$HOME/.cargo/config
[source.crates-io]
registry = "https://github.com/rust-lang/crates.io-index"

# 指定镜像为中科大源
replace-with = 'ustc'
[source.ustc]
registry = "http://mirrors.ustc.edu.cn/crates.io-index/"
  1. 点击下载Windows的Rust安装包 后双击安装包开始安装
  1. 垃圾Rust居然诱导安装Visual Studio,显示如下下时选择:3
1
2
3
1) Quick install via the Visual Studio Community installer
2) Manually install the prerequisites (for enterprise and advanced users).
3) Don't install the prerequisites (if you're targetting the GNU ABI)
  1. 显示如下下时选择:2
1
2
3
1) Proceed with installation (default)     确认并安装(默认)
2) Customize installation 自定义安装
3) Cancel installation 取消安装
  1. 然后首先会出现让你输入Default host triple,此时手动在命令行输入:x86_64-pc-windows-gnu

  2. 后续直接都默认按回车,再次出现上面选择1,2,3的时候,选择1开始安装

  3. 安装完成后也可安装默认Toolchain rustup toolchain install stable

Rust的使用

  1. 项目及包管理工具 cargo 的使用,只能安装库
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 项目管理
cargo init hello // 在当前的目录中创建项目hello
cargo new hello // 初始化新的目录hello创建项目
cargo build // 构建项目,可选参数 --release
cargo run // 同时编译并运行生成的可执行文件
cargo check // 快速检查代码确保其可以编译,但并不产生可执行文件
cargo clean // 清理构建期间生成的任何二进制文件
cargo add gtk4 // 添加依赖库到本项目
cargo update // 更新本项目所有依赖
cargo update -p gtk4 // 只更新gtk4

# 依赖包管理
cargo search gtk4 // 网络上搜索指定库
cargo install gtk4 // 安装指定库到本地,默认在 $HOME/.cargo/bin
cargo uninstall gtk4 // 卸载本地的指定库
  1. 工具链管理器 rustup 的使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
rustup check			// 检查有无更新
rustup update // 更新工具链和rustup
rustup show // 显示已安装的工具链或配置文件
rustup which rustc // 查看编译器或包管理器的完整路径
rustup self uninstall // 卸载Rust

# 修改或查询已安装的工具链
rustup default stable-gnu // 设置默认的工具链
rustup toolchain list // 列出已装的工具链
rustup toolchain install stable-msvc // 安装指定的工具链
rustup toolchain uninstall stable-msvc // 移除指定的工具链

# 修改工具链支持的平台
rustup target list // 列出已装和可用平台
rustup target add aarch64-linux-android // 将平台添加到工具链
rustup target remove aarch64-linux-android // 从工具链中删除平台
  1. 编译器 rustc 的使用
1
2
3
4
5
6
7
# 编译源码test.rs并添加库搜索目录./lib,链接库libadd.so
rustc test.rs -o filename -L ./lib -l add

# Rust源码文件test.rs
fn main() {
println!("Hello World!");
}