Turn-key PCB assembly services in prototype quantities or low-volume to mid-volume production runs

Function calls and stacking of parameters in embedded systems

Usually when you write C programs for microcontrollers you use functions that can be called any time in main program or in another function. Compiler compiles these functions as subroutines. These functions can be called from main function or from other functions – this is called nesting (nested subroutines).

C program subroutine

If you see the listings of compiled program you will see that subroutines are called by using call or rcall keyword. The argument of this instruction is an subroutine address which will be executed on the next processor cycle. Call instruction also writes return address from function to the stack to continue program after returning from function.

The next instruction begins execution at the start of the subroutine and returning from function is done after ret instruction which also restores an address of program counter in hardware level. Stack is also used to store all arguments of function – it usually depends on compiler hos it is done.

But in general compiler generates code which:

  • Push all arguments to stack;

  • Call the function;

  • Allocate storage for all local variables in the stack;

  • Perform the function;

  • Deallocate local variables from stack;

  • Return from function;

  • Deallocate the space used by arguments.

All these operations may depend on compiler and platform used. For instance AVR-GCC compiler is using registers for arguments and return values and if there are too many (over 9) of them then other are passed to stack. Read the FAQ. But it is recommended not to use too many parameters in functions if you want to use code efficiently.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.