What are some refactoring methods to reduce size of compiled code?

后端 未结 7 1451
夕颜
夕颜 2021-01-30 18:47

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 funct

7条回答
  •  不思量自难忘°
    2021-01-30 19:19

    • 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.

提交回复
热议问题