SoFunction
Updated on 2025-04-09

Detailed explanation of GCC inline assembly tutorial under ARM system

In operating system-level programming, sometimes, C language cannot fully use hardware functions, so some assembly code is needed to implement functions. There are two ways to make C and assembly language work together. One is to write two files separately in two languages, and link them into one file when linking; the other is to embed assembly code in C language. The following is a brief introduction to how to embed assembly code in GCC.

GCC specifies the syntax of inline assembly, and GCC inline assembly on different hardware platforms is almost the same:

asm(
 Assembly command list
 :Output operator list
 :List of input operators
 :List of changed resources
};

Inserting assembly code in GCC requires starting with the asm keyword, and the middle four parts are separated by ":". If the assembly you embedded has no input or output, or changes resources, the next three items can be omitted.

Here is an example to illustrate this syntax:

void test(void)
 {
  int tmp;
  // some code
  __asm__(
   " mov r1,%0\n\t"
   : 
   : "r" (tmp)
   : "r1"
  );
 }

The above code means that the value of the tmp variable is assigned to the r1 register, %0 represents the first value that appears in the input operator list and the output operator list, %1, %2 and so on. Since our own assembly code changes the value of r1, we need to notify the GCC compiler that the value of r1 has been changed by us. In the "r" (tmp) expression, tmp represents the variable input into the assembly in C language, and "r" means tmp will be passed through a register. There are several symbols that can be used:

Table 1 Excerpt from GCC4 inline assembly operators

Operator meaning
r General registers R0~R15
m A valid memory address
l Immediate number in data processing instructions
X The modified operator can only be used as output

The above code is to pass the value of C language into the assembly code, and you can also pass the result output from the assembly code to the C code:

void test(void)
  {
   int tmp;
   __asm__(
    "mov %0, #1\n\t"
    : "=r" (tmp)
    :
   ); 
  }

This code means that the immediate number 1 is assigned to the variable tmp. Unlike the above, the input operator list is moved to the output operator list, and there is an equal sign before "r". This equal sign is called a constraint modifier. Here is a list of meanings of several modifiers:

Table 2 Inline assembly modifiers in GCC4

Modifier illustrate
none The modified operator is read-only
= The modified operator is written only
+ The modified operator has readable and writeable properties
& The modified operator can only be used as output

Summarize

The above is a detailed explanation of the GCC inline assembly tutorial under the ARM system introduced to you by the editor. I hope it will be helpful to you!