使用内联汇编来交换两个整数变量

问题描述 投票:0回答:2

(编者注:这是一个调试问题,关于这个尝试实现的错误(几乎所有内容),因此不是How to write a short block of inline gnu extended assembly to swap the values of two integer variables?的副本但是如果你想要一个有效的例子,请参阅Q&A和https://stackoverflow.com/tags/inline-assembly/info。)


我正在尝试使用gnu扩展程序集交换两个整数变量,这就是我现在所拥有的:

int main()
{
    int a = 2;
    int b = 1;
    printf("a is %d, b is %d\n", a, b);
    // TODO (student): swap a and b using inline assembly
    printf("a is %d, b is %d\n", a, b);
    asm ("mov ebx, b;"
        "mov ecx, b;"
        "mov c, ecx;"
        "mov d, ebx;"
    );

我收到错误消息:asmPractice.c:17:错误:mov的内存引用太多。

我该如何解决这个问题?

c gcc gnu inline-assembly
2个回答
2
投票

使用扩展的内联汇编语法,这是一个单行:

volatile int a = 1;
volatile int b = 2;

asm("" : "=r" (a), "=r" (b) : "0" (b), "1" (a) : );
//      ^^^^^^^^^^^^^^^^^^   ^^^^^^^^^^^^^^^^^
//           input               output

printf("a is %d, b is %d\n", a, b);

0
投票

不知道是否重要。但是在我记忆中,你需要在注册之前加上%,以便让口译员理解你对注册的看法。像mov %esp, %ebp

尝试但不是100%肯定会解决它。 qazxsw poi指的是这篇文章


0
投票

在注册前尝试加倍%。

© www.soinside.com 2019 - 2024. All rights reserved.