0

I would like to make a makefile for compiling c programs for the arduino. I am somewhat familiar with make but have never used it with avr-gcc. What is the simplest way I could put the commands below in a makefile?

$ avr-gcc -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o led.o led.c
$ avr-gcc -mmcu=atmega328p led.o -o led
$ avr-objcopy -O ihex -R .eeprom led led.hex
$ avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyACM0 -b 115200 -U flash:w:led.hex
connorwstein
  • 305
  • 2
  • 13

1 Answers1

2

The simple-as-a-meataxe way is just to wrap the commands in a recipe:

.PHONY: all
all:
    avr-gcc -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o led.o led.c
    avr-gcc -mmcu=atmega328p led.o -o led
    avr-objcopy -O ihex -R .eeprom led led.hex
    avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyACM0 -b 115200 -U flash:w:led.hex

Just type make, and it will run. It works, but it's just a dumb script. A better way is by wrapping each command in a rule, with correct names and prerequisites:

# I still don't know what this one does. ("flashing"?)
.PHONY: flash
flash: led.hex
    avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyACM0 -b 115200 -U flash:w:led.hex

led.o: led.c
    avr-gcc -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o led.o led.c

led: led.o
    avr-gcc -mmcu=atmega328p led.o -o led

led.hex: led
    avr-objcopy -O ihex -R .eeprom led led.hex

That will prevent a lot of unnecessary work, such as rebuilding led and led.o when they're already up to date. We can improve it further by making some of these rules into pattern rules, so that later if you want to add servo.c to the project you won't have to write new versions of everything:

# Can other things "flash"? Or be "flashed"? The word has several definitions.
.PHONY: flash
flash: led.hex
    avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyACM0 -b 115200 -U flash:w:led.hex

%.o: %.c
    avr-gcc -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o $@ $<

%: %.o
    avr-gcc -mmcu=atmega328p $< -o $@

%.hex: %
    avr-objcopy -O ihex -R .eeprom $< $@

Further improvements are possible, but a lot depends on how you intend to use this makefile and in which directions you intend to expand the project.

Beta
  • 96,650
  • 16
  • 149
  • 150