How to squeeze code for more Flash and RAM?

You have a couple of options: first is to look for redundant code and move it to a single call to get rid of the duplication; the second is to remove functionality.

Take a good look at your .map file and see if there are functions that you can get rid of or rewrite. Also make sure that library calls which are being used are really needed.

Certain things like division and multiplications can bring in a lot of code but using shifts and a better use of constants can make the code smaller. Also have a look at things like string constants and printfs. For example each printf will eat up your rom but you might be able to have a couple of shared format strings instead of repeating that string constant over and over again.

For memory see if you can get rid of globals and use autos in a function instead. Also avoid as many variables in the main function as possible, as these eat up memory just like globals do.


It's always worth looking at listing file (assembler) output to look for things which your particular compiler is particularly bad at.

For example, you may find that local variables are very expensive, and if the application is simple enough to be worth the risk, moving a few loop counters into static variables might save a lot of code.

Or array indexing might be very expensive but pointer operations much cheaper. Or vice versa.

But looking at the assembly language is the first step.


Compiler optimisations, for example, -Os in GCC gives the best balance between speed and code size. Avoid -O3, as it may increase code size.

Tags:

Embedded