Rust Sysroots for Easier Embedded Projects

Rust now has usable support for Rust sysroots. This makes it must easier and useful to use cargo to build your embedded projects. You should be able to even use stable rust once 1.9 is out, but you will have to use a nightly for now.

Build libcore for your target

Use the instructions in my last blog post here to build a libcore for the target platform.

Make a sysroot directory structure:

The directory naming and structure in your sysroot is important. Put the libraries you built in the previous step in:

my-sysroot/lib/rustlib/$target_name/lib/libcore.rlib

Replace $target_name with your desired target, in my case this is thumbv7em-none-eabi so I have:

my-sysroot/lib/rustlib/thumbv7em-none-eabi/lib/libcore.rlib

(you can name my-sysroot whatever you want)

Set RUSTFLAGS to specify the desired target and sysroot

You have two options for specifying the sysroot. You can either use the RUSTFLAGS environment variable:

RUSTFLAGS=”–sysroot=my-sysroot” cargo build –target thumbv7em-none-eabi

or you can specify these in the .cargo/config file:

[build]
target = “thumbv7em-none-eabi”
rustflags = [“–sysroot”, “my-sysroot”]

Build

and then just do:

cargo build

To build your cargo library against your desired target and sysroot.

I usually have a few more flags. Something like:

[build]
target = “thumbv7em-none-eabi”
rustflags = [“-C”, “opt-level=2”, “-Z”, “no-landing-pads”, “–emit”, “obj”, “–sysroot”, “my-sysroot”]

and then build with a:

cargo build –verbose

The --emit obj causes cargo to emit an object file as an artifact of the build which you can link into an existing C embedded project. The --verbose shows the arguments passed to rustc under the hood which is useful to verify that cargo is calling rustc as you expect.

Conversation
  • Brad says:

    I’ve seen the term used in many places but never defined. In Rust, what is a sysroot?

  • Comments are closed.