0
\$\begingroup\$

I write code for Atmega8 in Atmel studio and the size of code is overflow the flash size of microcontroller. Could anyone help on How to Optimize code for Size? or have experience in reduce code size in flash? Thanks a lot.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ That would require analysis of your code to see where it could be "optimized" for space and is way outside the scope of an answer here.. First step is to go through your code and look for blocks that are repeated or similar and separate them into subroutines. If it's just too big..you may be expecting too much from a little single micro. \$\endgroup\$
    – Trevor_G
    Commented Jun 1, 2017 at 13:12

1 Answer 1

5
\$\begingroup\$

Did you set the optimization flag as -Os (optimize for size)? Other tips:

In Atmel Studio:

  • check "Prepare functions for garbage collection (-ffunction-sections)"
  • check "Prepare data for garbage collection (-fdata-sections)"
  • check "Pack Structure members together (-fpack-struct)"
  • check "Garbage collect unused sections (-WI, --gc-sections)"

Also

  • don't use printf or similar bloated stuff
  • utilize code reuse when possible (easier with C++ class derivation, method overriding etc)
  • check lst & map files for other hints
\$\endgroup\$
3
  • 2
    \$\begingroup\$ + Don't use floating point maths. \$\endgroup\$
    – Jeroen3
    Commented Jun 1, 2017 at 13:26
  • 1
    \$\begingroup\$ The -flto option can squeeze the code by 20%. Don't use a bootloader, so you can use all the flash memory for code. Avoid using a large library for a simple task. The tip by @Jeroen3 to remove all floating point is very good. Set parts of the code between #ifdef and #endif to be able to turn on and off debug messages. When sending messages, keep the messages very short. In some cases it can help to use the EEPROM more. Sometimes changing a 'byte' into an 'int' reduces the code, when the byte was converted to integers a lot. Use local variables, the compiler might only use registers for them. \$\endgroup\$
    – Jot
    Commented Jun 1, 2017 at 14:37
  • \$\begingroup\$ @Jot: Thanksss Jot..good guide :) plz put it in answer list \$\endgroup\$
    – Ali
    Commented Jun 1, 2017 at 20:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.