Consider Built-in Functions Before In-line Assembly

Last modified by Microchip on 2024/01/22 16:45

Although C has a wide range of operators, it can sometimes lack functionality dedicated to embedded programming and it certainly will not provide device-specific operations or code sequences.

When faced with a requirement for an operation that is not handled by the C language, the temptation is to immediately dust off your device datasheet and program in assembly code. Before you venture down this path, first check to make sure that there is not already a compiler built-in function provided that can perform the task you require.

All three Microchip MPLAB® XC compilers provide built-in functions and these offer several benefits over hand-written assembly code.

Built-in functions differ from ordinary C functions, in that the assembly code they generate directly implements the desired task. Since there is no call, return, or parameter passing, they are very efficient and yet provide the same code abstraction provided by functions and make understanding source code easier. Optimizations are typically enabled for the output of built-in functions (unlike in-line assembly code) and register usage of built-in functions is taken into consideration by the compiler. This ensures that the code works with the surrounding compiler-generated code—a common failure of handwritten in-line assembly code.

Examples of the tasks performed by built-in functions include in-line delays, software breakpoints, enabling and disabling interrupts, bit operations, arithmetic operations, program memory access, and peripheral unlock sequences.

Check the appendix in your compiler’s user guide to find out what built-in functions are available.