AVR Makefile

After one has written the C program, one needs to compile it into a format which conforms to the microcontroller's understanding. In the case of an AVR microcontroller, it is the Intel HEX format. The avr-gcc is a set of utilities which comes bundled with every package of Linux (for Windows systems, download WinAVR) and is used to compile the C code into Intel HEX code.

A makefile is nothing but a set of instructions which eases the task of typing in the compile commands every time one needs to compile. To compile using a makefile, one just needs to type make and everything's done.

Makefile


# Makefile for generating Intel HEX files for the AVR MCU using avr-gcc and binutils
# By	-	Nandan Banerjee
#			December 24, 2011
#
# Change the MCU_TARGET to the AVR microcontroller you wish to generate the HEX file for.
# Change the PRG to the name of the C program file which you want to build.
# Set the optimizations in the OPTIMIZE macro.
# Comment the FILES_GENERATED macro if you want to keep the files generated.

PRG 			= main
OBJ 			= $(PRG).o
MCU_TARGET		= atmega32
OPTIMIZE       	= -Os
CC				= avr-gcc
CFLAGS			= -g $(OPTIMIZE) -mmcu=$(MCU_TARGET) 
OBJCOPY        	= avr-objcopy
OBJDUMP        	= avr-objdump
FILES_GENERATED	= $(PRG).elf $(PRG).bin $(OBJ) $(PRG).lst $(PRG).srec

all: $(PRG).elf $(PRG).lst text clean

$(PRG).elf: $(OBJ)
	$(CC) $(CFLAGS) -o $@ $^

$(OBJ): $(PRG).c
	$(CC) $(CFLAGS) -c $<

$(PRG).lst: $(PRG).elf
	$(OBJDUMP) -h -S $< > $@

text: hex bin srec

hex:  $(PRG).hex
bin:  $(PRG).bin
srec: $(PRG).srec

$(PRG).hex: $(PRG).elf
	$(OBJCOPY) -j .text -j .data -O ihex $< $@

$(PRG).srec: $(PRG).elf
	$(OBJCOPY) -j .text -j .data -O srec $< $@

$(PRG).bin: $(PRG).elf
	$(OBJCOPY) -j .text -j .data -O binary $< $@

clean:
	rm -rf $(FILES_GENERATED)