How do I return a value from the main function in MIPS?

拜拜、爱过 提交于 2019-11-28 10:36:59

问题


Say I want to write the following C program in MIPS:

int main () {
  return 5;
}

When I try the following MIPS code in MARS:

main:   ADDI $v0, $zero, 5     # $v0 = 5
        JR $ra                 # return from main()

I get a 'invalid program counter' error. This is apparently because you cannot jump out of the main function in MARS. So I tried rewriting it like so:

main:   ADDI $v0, $zero, 5     # $v0 = 5
        li $v0, 10             # load 10(exit) for syscall
        syscall                # exit

After executing this, the $v0 register contains the value 10, not 5. Which is understandable since I had to overwrite the $v0 register in order for syscall to work. My question, then, is where would I save the value 5 in order for it to be returned to the caller of this application correctly?


回答1:


Use syscall 17:

exit2 (terminate with value)
----------------------------
$v0 = 17
$a0 = termination result

Note that "If the MIPS program is run under control of the MARS graphical interface (GUI), the exit code in $a0 is ignored."



来源:https://stackoverflow.com/questions/18727971/how-do-i-return-a-value-from-the-main-function-in-mips

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!