使用 GCC 编译内联程序集时出错,"shl"

error compiling inline assembly with gcc, "shl"

本文关键字:出错 shl 程序集 GCC 编译 使用      更新时间:2023-10-16

这是我尝试转换为gcc风格的asm内联汇编代码的实际代码。

#include<iostream>
using namespace std;
int reverse(int num);
int main(){
    int num;
    cout << "enter number: ";
    cin >> num;
    cout << endl;
    cout << reverse(num);
    return 0;
}
int reverse(int num){
    if(num == 0 || num == 1){
        return num;
    }
    __asm
    {
        xor eax, eax
        xor ecx, ecx     
        mov ebx, num    
        clc             ; clear carry
not_found:
        inc ecx
        shl ebx, 1
        jnc not_found

        rcr eax, 1
        mov edx, ecx
again:
        shl ebx, 1
        rcr eax, 1
        inc ecx
        cmp ecx, 32
        jne again
        dec edx     
again2:     
        shr eax, 1
        dec edx
        cmp edx, 0
        jne again2
    }
}
由于我无法使用 gcc 编译

上述代码,我尝试将其转换为一些可以通过 gcc 编译器成功编译的东西,但到目前为止我无法产生任何有意义的结果。

根据 OP 注释中的代码,下面是一个修改后的示例,它使用内联程序集移动了一位:

#include<iostream>
using namespace std;
int reverse(int num);
int main()
{
    int num;
    cout << "enter number: ";
    cin >> num;
    cout << endl;
    cout << reverse(num) << endl;
    return 0;
}
int reverse(int num)
{
    if (num == 0 || num == 1)
    {
        return num;
    }
    int temp = 0;
    asm( "shll $1, %0 nt" : "=r"(temp) : "0"(num));
    return temp;
}

请注意,如果您使用 r 约束要求操作数,gcc将操作数放入寄存器中,因此实际上没有理由自己mov它们(至少在这个小示例中(。此外,我在输入约束中使用了0来指示它应该与输出相同的寄存器,因为这就是shl的工作方式。

仍然不确定num == 1条件,但大概这是因为我们不知道完整函数的实际功能。