Skip to content

Instantly share code, notes, and snippets.

@TapioT
Last active March 23, 2023 00:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TapioT/9ac8e546904447e66a96a91b6f3b1d79 to your computer and use it in GitHub Desktop.
Save TapioT/9ac8e546904447e66a96a91b6f3b1d79 to your computer and use it in GitHub Desktop.
How to compile Rust to ARMv7 (Raspberry Pi) and musl

Why run musl-linked code in a Raspberry Pi? Containers are a nice way to package all dependencies for a program. The most popular container is Alpine Linux, since it is very small, especially compared with other distros. One reason for its size is that it uses the musl library instead of glibc. A consequence of this is that all programs must be compiled to use musl, so there are two tasks:

  1. Compile to the target architecture
  2. Compile to the target architecture so that the result uses musl

I had a lot of false starts in compiling Rust programs to Raspberry Pi, so below is what finally worked.

Start with the musl-cross-make project from https://github.com/richfelker/musl-cross-make. I checked that latest versions from "patches" directory and found the following:

  • binutils-2.32
  • gcc-9.2.0
  • linux-4.4.10

So I edited these versions to config.mak. I also edited OUTPUT to be /usr/local, and built and installed. Next, the .cargo/config file should have this:

[target.armv7-unknown-linux-musleabihf]
linker = "arm-linux-musleabihf-gcc"

I could put the CPU model to the Cargo config file, but that does not sound like a good idea. RPi 3B uses Cortex-A53 and RPi 4B uses Cortex-A72. Both have VFPv4 with NEON FPUs. The whole story is in https://en.wikipedia.org/wiki/Raspberry_Pi#Hardware

To make the compilate work, I need a couple of flags, like this:

TARGET_CFLAGS='-mfpu=neon-vfpv4 -mmusl -mcpu=cortex-a72' cargo build --target armv7-unknown-linux-musleabihf --release

All allowable flags are in https://gcc.gnu.org/onlinedocs/gcc/ARM-Options.html

For aarch64, the magic incantation is

TARGET_CFLAGS='-mmusl -mcpu=cortex-a72' cargo build --target aarch64-unknown-linux-musl --release

The armv7 target must have the FPU flag.

The aarch64 target must not have the FPU flag.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment