## Rust测试项目 ### 基础使用 项目依赖在 Cargo.toml 各种轮子库 [crates.io](https://crates.io) 各种轮子库文档 [docs.rs](https://docs.rs/) **创建项目** > cargo new <项目名> 加 --lib 参数创建库项目,加 --vcs none 不初始化本地git仓库 默认是 --bin 和初始化 .git **下载依赖和构建项目** > cargo build 加 --release 参数开启优化,并将编译结果输出到 target/release 目录 默认是 --debug 和输出到 target/debug 目录 **运行** 如果未构建则先构建 > cargo run **测试** > cargo test **为项目构建文档** > cargo doc **将库发布到crates.io** > cargo publish 更多cargo工具链说明参考 [Cargo 中文文档](https://cargo.budshome.com/index.html) ### 加国内镜像 > vim ~/.cargo/config ``` [source.crates-io] registry = "https://github.com/rust-lang/crates.io-index" replace-with = 'ustc' [source.ustc] registry = "git://mirrors.ustc.edu.cn/crates.io-index" ``` ### 交叉编译 以MAC OS X作为上位机为例 **安装musl相关交叉编译工具链** > brew install FiloSottile/musl-cross/musl-cross 要下载很多内容,耐心等待 可以加 --with-arm --with-arm-hf --with-i486 等选择平台,默认是带 --with-x86_64,也可以通过 --without-x86_64 取消 安装位置在 /usr/local/Cellar/musl-cross 关于在mac下基于muslc交叉编译linux、win目标的rust(或涉及到cgo的golang)程序的官方文档见: [filippo.io](https://blog.filippo.io/easy-windows-and-linux-cross-compilers-for-macos/) **安装交叉编译目标环境rust包** 查看已安装或支持的目标平台 > rustup target list 如果未安装想要的,通过类似如下命令安装 > rustup target add x86_64-unknown-linux-musl 或 > rustup target add armv7-unknown-linux-musleabi 等等 编辑 ~/.cargo/config,追加与目标平台相应的配置,linker的程序名字到musl-cross安装目录bin子目录里找 ``` [target.x86_64-unknown-linux-musl] linker = "x86_64-linux-musl-gcc" ``` 或 ``` [target.armv7-unknown-linux-musleabi] linker = "arm-linux-musleabi-ld" ``` 等等 export CROSS_COMPILE=x86_64-linux-musl- **交叉编译** 执行编译命令时带上目标平台参数即可 > cargo build --release --target=x86_64-unknown-linux-musl 如遇 openssl 相关编译错误,参考:https://github.com/richfelker/musl-cross-make/issues/65 CI工具中做rust交叉编译也可以考虑用现成的或自定义docker镜像,如: https://github.com/clux/muslrust