4.2.1. Embedded assembler syntax

An embedded assembly function definition is marked by the __asm (C and C++) or asm (C++) function qualifiers, and can be used on:

Functions declared with __asm or asm can have arguments, and return a type. They are called from C and C++ in the same way as normal C and C++ functions. The syntax of an embedded assembly function is:


__asm return-type function-name(parameter-list)
{
    // ARM/Thumb assembler code
    instruction[;instruction]
    ...
    instruction
}

The initial state of the embedded assembler (ARM or Thumb) is determined by the initial state of the compiler, as specified on the command line. That is:

You can change the state of the embedded assembler by using explicit ARM, THUMB, or CODE16 directives in the embedded assembler function. The directives have effect until the next such directive is encountered. That is, a directive will set ARM or Thumb state for all subsequent __asm functions until it is over-ridden.

Note

Argument names are permitted in the parameter list, but they cannot be used in the body of the embedded assembly function. For example, the following function uses integer i in the body of the function, but this is not valid in assembly:


__asm int f(int i) {
    ADD i, i, #1 // error
}

You can use, for example, r0 instead of i.

Embedded assembler example

Example 4.4 is equivalent to Example 4.1, but modified to show how to use the string copy routine as an embedded assembler routine.

Example 4.4. String copy with embedded assembler


#include <stdio.h>
__asm void my_strcpy(const char *src, const char *dst) {
loop
      LDRB  r3, [r0], #1
      STRB  r3, [r1], #1
      CMP   r3, #0
      BNE   loop
      MOV   pc, lr
}
void main()
{
    const char *a = "Hello world!";
    char b[20];
    my_strcpy (a, b);
    printf("Original string: '%s'\n", a);
    printf("Copied   string: '%s'\n", b);
}
Copyright © 2005 ARM Limited. All rights reserved.ARM DUI 0282B
Non-Confidential