Compiling assembler files with avr-gcc without C runtime

Written down so that I’ll remember this the next time I’m trying to do this: If you want to compile assembler files with avr-gcc to be used with your C files, just compile them like your .c files.

avr-gcc -c -mmcu=atmega328p -o foo.o foo.S

If you want to run your assembler code standalone, without the C runtime support (crt*.o), you’ll need to tell the linker that the entry point is inside your program instead of the C initialization routines. The command-line option -e for avr-ld is what you’re looking for. Consider the following assembler program:

    #include <avr/io.h>

    .section text

    .org 0
    .global init
init:
    rjmp main

    .org 0x020
    .global main
main:
    ; on Arduino, this will light up the on-board LED
    ldi 16, 0xFF
    out _SFR_IO_ADDR(DDRB), 16
    out _SFR_IO_ADDR(PORTB), 16

loop:
    rjmp loop

To start the execution from init, compile and link it like this:

avr-gcc -c -mmcu=atmega328p -o foo.o foo.S
avr-ld -e init -o foo.elf foo.o
avr-objcopy -O ihex foo.hex foo.elf

Also, check out avr-libc’s manual on assembler programs.


Comments or questions? Send me an e-mail.


Want to get these articles to your inbox? Subscribe to the newsletter: