GCC 12 AVR array subscript 0 is outside array bounds

1 minute read

Where I describe a new error caused by a bug in GCC 12 as it relates to the AVR microcontrollers.

Sources:

Description

While debugging a setup script, I ran across this error on my Linux system, however, it didn’t show up on my macOS or Windows computers.

$ make flash
avr-gcc -Os -mcall-prologues -g3 -std=gnu99 -Wall -Werror -Wundef -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums  -ffunction-sections -fdata-sections  -DF_CPU=16000000UL   -DBAUD=9600UL -DSOFT_RESET=0 -I.  -I../../Library -mmcu=atmega328p -c -o main.o main.c
main.c: In function 'main':
main.c:33:9: error: array subscript 0 is outside array bounds of 'volatile uint8_t[0]' {aka 'volatile unsigned char[]'} [-Werror=array-bounds]
   33 |   PORTB &= ~_BV(PORTB5);
      |         ^~
cc1: all warnings being treated as errors
make: *** [<builtin>: main.o] Error 1
$

It does seem rather odd as 0 is certainly not “outside array bounds”, therefor I had no idea as to how to remediate it.

A little investigation shows the error is caused by a change in GCC 12. I can’t describe why it happens or why the fix works, however this bug report does.

In a nutshell, one has to add “–param=min-pagesize=0” to their CFLAGS in the Makefile as in:

CFLAGS = -Os -mcall-prologues -g3 -std=gnu99 -Wall -Werror -Wundef --param=min-pagesize=0

If the version of GCC is less than 12, this will break GCC as this is a new parameter. Once I did, the warning went away, the error went away (due to Werror) and everything was fine again.

The addition to the Makefile at line 46 is this:

# If GCC is < 12.x
CFLAGS = -Os -mcall-prologues -g3 -std=gnu99 -Wall -Werror -Wundef
# If GCC 12+ Add --param=min-pagesize=0 to solve subscript error on AVR uC
# "array subscript 0 is outside array bounds"
# https://gcc.gnu.org/bugzilla//show_bug.cgi?id=105523
# CFLAGS = -Os -mcall-prologues -g3 -std=gnu99 -Wall -Werror -Wundef --param=min-pagesize=0 

Comment/uncomment based on the version of GCC you are running.

Comments powered by Talkyard.