内联汇编的基本结构

1
2
3
4
5
6
asm asm-qualifiers ( AssemblerTemplate 
: OutputOperands
[ : InputOperands
[ : Clobbers ] ])


AssemblerTemplate 汇编程序模板
OutputOperands 输出操作数
InputOperands 输入操作数
Clobbers

示例代码

1
2
3
4
5
6
7
int src = 1;
int dst;
asm ("mov %1, %0\n\t"
"add $1, %0"
: "=r" (dst)
: "r" (src));
printf("%d\n", dst);

此段代码复制 srcdst ,并将 1 添加到 dst

可以将多个汇编程序指令放在一个 asm 字符串中,由系统汇编代码中通常使用的字符分隔。在大多数地方都有效的组合是换行符,加上一个制表符(写为“ \n\t”)

约束符号

“=”:Means that this operand is written to by this instruction: the previous value is discarded and replaced by new data.

”r”:Means that this operand is both read and written by the instruction. 标识既可读又可写入的操作数

如果在约束中指定 ‘ = ‘ 或 ‘ + ‘,则将其放在约束字符串的第一个字符中。

“a”:ax寄存器,函数返回

“r”:任意寄存器

“m”:内存

image-20240412231300895

image-20240412231241954