Laurent Zuijdwijk

@laurent.zuijdwijk

Cross Compiling Rust for the Raspberry Pi on Linux

Lets build a simple “Hello Pi” program in Rust and compile it for the Raspberry Pi running a Linux version. I am using a Raspberry Pi 3 and Raspbian. Why do we want to compile this on a PC? Assuming you do development of your application on a PC, it would be much faster to compile and test it on a PC as well and ship only the binary to the RPi.

We will need rustup in order to use different versions of Rust and to select compile targets. It is a toolchain installer.

curl https://sh.rustup.rs -sSf | sh

If you have a previously installed Rust, then rustup will ask you to remove it, so that rustup can manage the different Rust versions. Go ahead and install the default Rust version for your environment.

To compile for the Raspberry Pi we will need to install the right toolchain for the ARM platform. Model 2 and 3 support ARMv7, while model 1 supports ARMv6. The RPi has a floating point processor, so we want the gnueabihf (hf is hard float I believe), as opposed to the gnueabi. This article will focus on models 2&3.

Add the toolchain for Rust:

$ rustup target add armv7-unknown-linux-gnueabihf

and the right C compiler:

$ sudo apt-get install gcc-4.7-multilib-arm-linux-gnueabihf

We need to add our build target to ~/.cargo/config by adding the following lines, so that rust knows which linker to use.

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

Creating our project

Installing Rust will have installed cargo, the Rust package manager. We can use it to create a new project.

$ cargo new hello-rpi --bin
$ cd hello-rpi

We can still run our project locally on AMD64, by running cargo run. To build our project for the RPi we use.

$ cargo build --target=armv7-unknown-linux-gnueabihf

Let’s see if we have successfully created an arm binary

$ file target/armv7-unknown-linux-gnueabihf/debug/hello-rpi
target/armv7-unknown-linux-gnueabihf/debug/hello-rpi: ELF 32-bit LSB  shared object, ARM, EABI5 version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.32, 

Success! When we transfer hello-rpi to our Raspberry Pi, we will be able to run it and get a fantastic “hello world!” on the command line! Now that we can compile, we can start developing something more interesting.

Part 2 coming soon…

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMI family. We are now accepting submissions and happy to discuss advertising & sponsorship opportunities.
If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!
Topics of interest

More Related Stories