使用c ++函数中的汇编程序编译循环

Dze*_*rek 1 c c++ assembly

我一直对汇编程序感兴趣,但到目前为止,我没有真正的机会以最好的方式面对它.现在,当我有一些时间的时候,我开始使用汇编程序在c ++中编写一些小程序,但这只是小程序,即定义x,将其存储在某处等等,等等.我想在汇编程序中实现foor循环,但我无法实现它,所以我想问一下这里有没有人做过这件事,很高兴在这里分享.一些功能的例子是

for(i=0;i<10;i++) { std::cout<< "A"; }

任何人都知道如何在汇编程序中实现它?

edit2:ISA x86

Ker*_* SB 6

以下是此代码的GCC 未优化输出1:

void some_function(void);

int main()
{
  for (int i = 0; i < 137; ++i) { some_function(); }
}
Run Code Online (Sandbox Code Playgroud)


    movl    $0, 12(%esp)            // i = 0; i is stored at %esp + 12
    jmp .L2
.L3:
    call    some_function           // some_function()
    addl    $1, 12(%esp)            // ++i
.L2:
    cmpl    $136, 12(%esp)          // compare i to 136 ...
    jle .L3                         //   ... and repeat loop less-or-equal

    movl    $0, %eax                // return 0
    leave                           //  --"--
Run Code Online (Sandbox Code Playgroud)

通过优化-O3,加法+比较变为减法:

    pushl   %ebx          // save %ebx
    movl    $137, %ebx    // set %ebx to 137

    // some unrelated parts

.L2:
    call    some_function // some_function()
    subl    $1, %ebx      // subtract 1 from %ebx
    jne .L2               // if not equal to 0, repeat loop
Run Code Online (Sandbox Code Playgroud)

1 可以通过使用-S标志调用GCC来检查生成的程序集.


oua*_*uah 5

尝试for使用a gotoif语句在C++中重写循环,您将拥有程序集版本的基础知识.