question: macro or function?

stevend8 wrote on Friday, August 06, 2010:

Why is portSAVE_CONTEXT() implemented as a macro, and not as a function?

I am going to use a PIC18F4550 but I was thinking: if I use a function instead of a macro, I can save a little bit RAM (pic18f4550 doesnt have much RAM), what do you think?

woops_ wrote on Friday, August 06, 2010:

Saving and restoring must usually be inline code to get the stack frame right. Function calls include hidden code.

richard_damon wrote on Friday, August 06, 2010:

If portSAVE_CONTEXT was a function, then when it returned it would have to “unsave” the context to get to the return address, in one sense, portYIELD does that, save context, swap context, restore new context, and all works just fine. It is some what tricky programming (if it is possible) to make a function that you can call that returns to you and in the process saves the processor state on the stack, and even if you could write it, changing the stack in this manner in arbitrary places could give the compiler problems. This is one reason why the rules for how you right your ISRs can be very precise and tricky, as the save context macro needs to know the conditions it is being used to make things work.

Another issue is that it really wouldn’t save that much program memory, as there are normally only a few calls to this macro. As I mentioned, portYEILD does, and in some port, the interrupt handlers will call it. (on others the interrupt handlers call portYIELD to save the context).

stevend8 wrote on Saturday, August 07, 2010:

ok, now i see, thank you all!