Introduction to inline assembly and inline assembly
Use three instances to multiply variable a and variable B. The obtained value is included in result.
Simple instance
AsmIndicates that inline assembly is used,VolatileIndicates that inline assembly is not optimized to avoid accidental deletion.
#include<stdio.h>int a = 10;int b = 20;int result;int main(){ __asm__ __volatile__( "movl a, %eax\n\t" "movl b, %ebx\n\t" "imull %ebx, %eax\n\t" "movl %eax, result\n\t" ); printf("the answer is %d\n", result); return 0;}
In a simple example, inline assembly can only use global variables in the C language. Second, registers and variables in the C language cannot communicate with each other.
Extended asm
To solve the limitations of the above instances, the extended asm is provided.
__asm__("asm statements" : outputs : inputs : registers-modified);
The outputs and inputs formats are as follows:
"constraints" (variable)
Constraints |
Description |
"M", "v", "o" |
Memory Unit |
"R" |
Any register |
"Q" |
Registers eax, ebx, ecx, and edx |
"I", "h" |
Direct operand |
"E" and "F" |
Floating Point Number |
"G" |
Arbitrary |
"A", "B", "c", and "d" |
Registers eax, ebx, ecx, and edx |
"S" and "D" |
Register esi and edi |
"I" |
Constant (0 to 31) |
Instance
#include<stdio.h>int main(){ int data1 = 10; int data2 = 20; int result; __asm__ __volatile__( "imull %%ebx, %%eax\n\t" "movl %%ecx, %%eax" : "=a"(result) : "d"(data1), "c"(data2) ); printf("the answer is %d\n", result); return 0;}
In extended asm, the reference Register uses "%". "=" to indicate the number of write operations. Here it refers to writing the value of the eax register to the result.
Use placeholders
Registers can be numbered starting from 0, for example, % 0 and % 1. This number is called a placeholder.
#include<stdio.h>int main(){ int data1 = 10; int data2 = 20; int result; __asm__ __volatile__( "imull %1, %2\n\t" "movl %2, %0" : "=r"(result) : "r"(data1), "r"(data2) ); printf("the answer is %d\n", result); return 0;}