Inline assembler
Inline assembler can be used for inserting assembler instructions directly into a C or C++ function.
The asm extended keyword and its aliases __asm and __asm__ all insert assembler instructions. However, when you compile C source code, the asm keyword is not available when the option ‑‑strict is used. The __asm and __asm__ keywords are always available.
The syntax is:
asm ("string");The string can be a valid assembler instruction or a data definition assembler directive, but not a comment. You can write several consecutive inline assembler instructions, for example:
asm("label:nop\n"
"jmp label");where \n (new line) separates each new assembler instruction. Note that you can define and use local labels in inline assembler instructions.
The following example demonstrates the use of the asm keyword. This example also shows the risks of using inline assembler.
extern volatile __saddr char UART1_SR;
#pragma required=UART1_SR
static __near char sFlag;
void Foo(void)
{
while (!sFlag)
{
asm("MOV A, S:UART1_SR");
asm("MOV sFlag, A");
}
}The inline assembler instruction will simply be inserted at the given location in the program flow. The consequences or side-effects the insertion might have on the surrounding code are not taken into consideration. If, for example, registers or memory locations are altered, they might have to be restored within the sequence of inline assembler instructions for the rest of the code to work properly.
Inline assembler sequences have no well-defined interface with the surrounding code generated from your C or C++ code. This makes the inline assembler code fragile, and might also become a maintenance problem if you upgrade the compiler in the future. There are also several limitations to using inline assembler:
The compiler’s various optimizations will disregard any effects of the inline sequences, which will not be optimized at all
In general, assembler directives will cause errors or have no meaning. However, data definition directives will work as expected.
Alignment cannot be controlled; this means, for example, that
DC16directives might be misalignedLabels cannot be declared.
Inline assembler is therefore often best avoided. If no suitable intrinsic function is available, we recommend that you use modules written in assembler language instead of inline assembler, because the function call to an assembler routine normally causes less performance reduction.