Reducing microcontroller code size isn’t ease task, but what if you want resulting code to fit your available memory?
Minimizing microcontroller code size can be done in two ways:
Firs is using compilers optimization feature by code size. This optimization is very dangerous. Your optimized code may not work as supposed to because compiler may eliminate some code like empty loops or adding zeros.
For example compilers like to remove for(int i=0;i by leaving one or several iterations. So don’t think that your optimized code will work as un-optimized.
There are other things you can do to minimize microcontroller code size. One of them is avoiding usage of standard libraries routines. Because these libraries are general and handles all standard possible execution cases. By including them in your design you include a bunch of code you dont need. If it is possible it is better to write your own routines or modify existing ones to fit your needs.
Also try to use needed variable sizes. If you need unsigned integers use uint type if you need byte size avoid using int which usually is more than 8 bits (16 or 32). This may significantly reduce your code as there are fewer instructions needed to execute smaller variable types. Sometimes you can use goto statements to remove complicated conditional structures. Just remember – Embedded system development is different than writing PC software. Don’t think general – think narrow when working with concrete hardware as resources of microcontrollers are limited.