Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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."


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...