How to Optimize Embedded C Code for Size Efficiently
To optimize embedded C code for size, use
compiler size optimization flags, avoid unnecessary library functions, and prefer static inline functions over macros or large functions. Also, minimize global variables and use const data to store fixed values in read-only memory.Syntax
Use compiler flags and code patterns to reduce code size:
-Os: Compiler flag to optimize for size.static inline: Defines small functions that the compiler can embed directly to avoid function call overhead.const: Marks data as read-only, allowing storage in flash memory instead of RAM.
c
static inline int add(int a, int b) { return a + b; } const char greeting[] = "Hello"; int main() { int result = add(3, 4); return 0; }
Example
This example shows how to use static inline functions and const data to reduce code size. The compiler flag -Os should be used during compilation to optimize for size.
c
#include <stdio.h> static inline int multiply(int x, int y) { return x * y; } const char message[] = "Size optimized code!"; int main() { int val = multiply(5, 6); printf("%s\nResult: %d\n", message, val); return 0; }
Output
Size optimized code!
Result: 30
Common Pitfalls
Common mistakes when optimizing for size include:
- Using large library functions unnecessarily instead of smaller custom code.
- Overusing macros which can increase code size due to repeated expansions.
- Not using
constfor fixed data, causing it to occupy RAM instead of flash. - Ignoring compiler optimization flags or using
-O2which favors speed over size.
c
/* Wrong: macro causes code bloat */ #define SQUARE(x) ((x) * (x)) /* Better: static inline function */ static inline int square(int x) { return x * x; }
Quick Reference
Summary tips to optimize embedded C code size:
- Compile with
-Osflag to optimize for size. - Use
static inlinefunctions instead of macros or large functions. - Mark fixed data as
constto store in flash memory. - Avoid unnecessary library calls; write minimal custom code.
- Minimize global variables and large stack allocations.
Key Takeaways
Use compiler flag -Os to optimize code size automatically.
Prefer static inline functions over macros to reduce code bloat.
Mark constant data with const to store it in read-only memory.
Avoid large library functions when smaller custom code suffices.
Minimize global variables and large stack usage to save memory.