3.1. The built-in avr-unknown-gnu-atmega328 target

The Rust nightly compiler contains a built-in target, avr-unknown-gnu-atmega328, that generates code for the AVR ATmega328 using the GNU AVR-GCC toolchain for linking support.

Targeting custom microcontrollers by adapting 'avr-unkonwn-gnu-atmega328'

See the section [./005.1-the-target-specification-json-file.md](5.1. The Target Specification JSON File) for more information about how Rust target specification JSON files work.

To generate a Rust target specification JSON file from the builtin:

rustc --print target-spec-json -Z unstable-options --target avr-unknown-gnu-atmega328 > my-custom-avr-unknown-gnu-atmega328.json

This prints the target specification JSON file my-custom-avr-unknown-gnu-atmega328.json:

{
  "arch": "avr",
  "cpu": "atmega328",
  "data-layout": "e-P1-p:16:8-i8:8-i16:8-i32:8-i64:8-f32:8-f64:8-n8-a:8",
  "eh-frame-header": false,
  "env": "",
  "exe-suffix": ".elf",
  "executables": true,
  "is-builtin": true,
  "late-link-args": {
    "gcc": [
      "-lgcc"
    ]
  },
  "linker": "avr-gcc",
  "linker-flavor": "gcc",
  "linker-is-gnu": true,
  "llvm-target": "avr-unknown-unknown",
  "os": "unknown",
  "pre-link-args": {
    "gcc": [
      "-mmcu=atmega328",
      "-Wl,--as-needed"
    ]
  },
  "target-c-int-width": "16",
  "target-endian": "little",
  "target-pointer-width": "16",
  "vendor": "unknown"
}

To adapt this file to target a different microcontroller:

  • Replace the top-level "cpu": "atmega328" with "cpu": "YOUR-AVR-VARIANT-NAME"
  • Replace "-mmcu=atmega328" with "-mmcu=YOUR-AVR-VARIANT-NAME"

The file can then be passed to Rust via the rustc --target <JSON FILE PATH> instead of rustc --target avr-unknown-gnu-atmega328, which will tailor the generated code to your desired microcontroller.

It is also possible to customize link parameters if desired by modifying the JSON file.

Compiling for AVR without the GNU toolchain

At the moment, the only builtin AVR target avr-unknown-gnu-atmega328 always requires AVR-GCC, AVR-libc and AVR-binutils from the GNU project.

The LLVM LLD linker has some limited support for AVR which in the future could be leveraged to allow compiling AVR Rust binaries without the dependency on the GNU toolchain. Some work on compiler-builtins and others would also be required. At the moment, the GNU toolchain is a hard dependency. no t