2018年5月15日 星期二

STM32F10x code size optimization




I have been using ARM embedded gcc with STM32F103 for a long time. recentlly, I found the binary size is much smaller compiled by Keil than gcc. It's huge different, lets say 10k bytes with Keil and 40k bytes with gcc. After some research there's solution.

1. Optimization level to code size

CFLAGS += -Os

2.Remove debug

#CFLAGS += -g

3.Add garbage collection flag

CFLAGS += -Wl,--gc-sections 

4. Using nano-newlib instead of newlib

CFLAGS += --specs=nano.specs

5.Other flags

CFLAGS += -fno-common -mfloat-abi=soft -fsingle-precision-constant -fomit-frame-pointer -ffunction-sections -fdata-sections

6.Below are the results, the red text is code size in bytes

CFLAGS += -Os

arm-none-eabi-size main.elf
   text    data     bss     dec     hex filename
  99652    2332    4560 106544   1a030 main.elf

CFLAGS += -Os
CFLAGS += -Wl,--gc-sections

arm-none-eabi-size main.elf
   text    data     bss     dec     hex filename
  88712    2260    3748   94720   17200 main.elf

CFLAGS += -Os
CFLAGS += -Wl,--gc-sections
CFLAGS += --specs=nano.specs

arm-none-eabi-size main.elf
   text    data     bss     dec     hex filename
  31716    1156    1620   34492    86bc main.elf

CFLAGS += -Os
CFLAGS += -Wl,--gc-sections
CFLAGS += --specs=nano.specs
CFLAGS += -fno-common -mfloat-abi=soft -fsingle-precision-constant -fomit-frame-pointer -ffunction-sections -fdata-sections

arm-none-eabi-size main.elf
   text    data     bss     dec     hex filename
  22572    1136    1612   25320    62e8 main.elf