有哪些重构方法可以减少编译代码的大小? [英] What are some refactoring methods to reduce size of compiled code?

查看:26
本文介绍了有哪些重构方法可以减少编译代码的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I have a legacy firmware application that requires new functionality. The size of the application was already near the limited flash capacity of the device and the few new functions and variables pushed it over the edge. Turning on compiler optimization does the trick, but the customer is wary of doing so because they have caused failures in the past. So, what are some common things to look for when refactoring C code to produce smaller output?

解决方案

  • Use generation functions instead of data tables where possible
  • Disable inline functions
  • Turn frequently used macros into functions
  • Reduce resolution for variables larger than the native machine size (ie, 8 bit micro, try to get rid of 16 and 32 bit variables - doubles and quadruples some code sequences)
  • If the micro has a smaller instruction set (Arm thumb) enable it in the compiler
  • If the memory is segmented (ie, paged or nonlinear) then
    • Rearrange code so that fewer global calls (larger call instructions) need to be used
    • Rearrange code and variable usage to eliminate global memory calls
    • Re-evaluate global memory usage - if it can be placed on the stack then so much the better
  • Make sure you're compiling with debug turned off - on some processors it makes a big difference
  • Compress data that can't be generated on the fly - then decompress into ram at startup for fast access
  • Delve into the compiler options - it may be that every call is automatically global, but you might be able to safely disable that on a file by file basis to reduce size (sometimes significantly)

If you still need more space than with compile with optimizations turned on, then look at the generated assembly versus unoptimized code. Then re-write the code where the biggest changes took place so that the compiler generates the same optimizations based on tricky C re-writes with optimization turned off.

For instance, you may have several 'if' statements that make similar comparisons:

if(A && B && (C || D)){}
if(A && !B && (C || D)){}
if(!A && B && (C || D)){}

Then creating anew variable and making some comparisons in advance will save the compiler from duplicating code:

E = (C || D);

if(A && B && E){}
if(A && !B && E){}
if(!A && B && E){}

This is one of the optimizations the compiler does for you automatically if you turn it on. There are many, many others, and you might consider reading a bit of compiler theory if you want to learn how to do this by hand in the C code.

这篇关于有哪些重构方法可以减少编译代码的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆