---
title: "Rust 笔记"
date: 2021-08-29T15:02:13+08:00
lastmod: 2021-08-29T15:02:13+08:00
keywords: []
tags: []
categories: ["dev/ops"]
---

## 安装 rust
- 安装 rustup，参考官网
    ```bash
    export RUST_UPDATE_ROOT=https://mirrors.tuna.tsinghua.edu.cn/rustup
    export RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustup
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
    # 按照提示，一直 default 即可
    ```

- 配置 rustup、toolchain 和 target 更新源
    ```bash
    cat >> /etc/profile.d/rustup.sh <<-EOF
        export RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustup
    EOF
    ```

- 配置 crate 源
    ```bash
    cat >> ~/.cargo/config <<-EOF
    [source.crates-io]
    replace-with = 'tuna'

    [source.tuna]
    registry = "https://mirrors.tuna.tsinghua.edu.cn/git/crates.io-index.git"
    EOF
    ```

## 交叉编译
### 树梅派 Alpine armv7/armhf
- 下载交叉编译工具
    ```bash
    curl -LO https://musl.cc/armv7l-linux-musleabihf-cross.tgz
    tar zxf armv7l-linux-musleabihf-cross.tgz -C /opt/
    export PATH=/opt/armv7l-linux-musleabihf-cross/bin/:$PATH
    ```

- 配置 target
    ```bash
    rustup target add armv7-unknown-linux-musleabihf
    cat >> ~/.cargo/config <<-EOF
    [target.armv7-unknown-linux-musleabihf]
    linker = "armv7l-linux-musleabihf-ld"
    EOF
    ```

- 编译
    ```bash
    # 操作系统如果是 armv7，则需指定该 cflag 来禁用 fpu
    export CFLAGS='-mfpu=neon'

    export CC=armv7l-linux-musleabihf-gcc
    cargo build --target armv7-unknown-linux-musleabihf --release
    armv7l-linux-musleabihf-strip target/armv7-unknown-linux-musleabihf/release/{目标二进制文件}
    ```

### 树梅派 Alpine aarch64
- 下载交叉编译工具
    ```bash
    curl -LO https://musl.cc/aarch64-linux-musl-cross.tgz
    tar zxf aarch64-linux-musl-cross.tgz -C /opt/
    export PATH=/opt/aarch64-linux-musl-cross/bin/:$PATH
    ```

- 配置 target
    ```bash
    rustup target add aarch64-unknown-linux-musl
    cat >> ~/.cargo/config <<-EOF
    [target.aarch64-unknown-linux-musl]
    linker = "aarch64-linux-musl-ld"
    EOF
    ```

- 编译
    ```bash
    export CC=aarch64-linux-musl-gcc
    cargo build --target aarch64-unknown-linux-musl --release
    aarch64-linux-musl-strip target/aarch64-unknown-linux-musl/release/{目标二进制文件}
    ```

