Reducing Compiled Code Size Dramatically by Factoring-Out a void Pointer

644 Views Asked by At

I've recently been developing some embedded software in C for a microcontroller, which only has 2kB of Flash memory. Coming to the end of programming, I've been hitting the code limit. Up until now, I've been increasing the level of compiler optimisation when this happens, retesting and then carrying on happily. However, I recently reached the limit of optimisation and with the addition of the last bit of functionality, ran out of memory again. As a result, I had to get the George Foreman out on my source code and drain some fat.

I messed around with reducing some layers of abstraction here and there, which helped matters slightly but not enough. The next thing I saw was that I had the function prototype

void process_event(Event event, void *data);

which takes as its parameters the event to process and a void pointer that can be used to pass additional data to the call. If I didn't need any extra data, I passed NULL. This function was written very early on in the development and I realised that I never used data, so I factored it out. This one change gave me the compiled code size saving I needed (~100 bytes), and I'm wondering why, especially considering I generally passed NULL when process_event was called?

1

There are 1 best solutions below

0
On BEST ANSWER

About 100 bytes would probably be in line with the fact that your call site has to pass an extra argument every time the function is called - this will at least involve a clear of a register, and, depending on your chip, storing it on the stack before the call.

It is also possible that this simple reduction of one instruction per call could result in more code being removed, depending exactly on how jumps are implemented, as you might find that some code is now in the range of a jump instruction using a short relative offset rather than a long one. A similar saving could be made when trying to load up constants.