Mar 27

主函数main的返回值 不指定

felix021 @ 2010-3-27 15:47 [IT » 程序设计] 评论(3) , 引用(0) , 阅读(7186) | Via 本站原创 | |
注:以下测试都是在Ubuntu 9.10 + Gcc 4.4下测试。

1.c
int main(){}
$ gcc -S 1.c
        .file   "1.c"
        .text
.globl main
        .type   main, @function
main:
        pushl   %ebp
        movl    %esp, %ebp
        popl    %ebp
        ret
        .size   main, .-main
        .ident  "GCC: (Ubuntu 4.4.1-4ubuntu9) 4.4.1"
        .section        .note.GNU-stack,"",@progbits


2.c
int main(){ return 0; }
$ gcc -S 2.c
        .file   "2.c"
        .text
.globl main
        .type   main, @function
main:
        pushl   %ebp
        movl    %esp, %ebp
        movl    $0, %eax
        popl    %ebp
        ret
        .size   main, .-main
        .ident  "GCC: (Ubuntu 4.4.1-4ubuntu9) 4.4.1"
        .section        .note.GNU-stack,"",@progbits

说明如果没有return语句,那么返回值应该是不确定的。

3.c
int main() {__asm__("movl    $0, %eax"); }

增加一个程序test.c
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int s = system("./1.exe");
    printf("return: %x\n", s);  //16进制输出
    return 0;
}


分别运行1.c 2.c 3.c编译后的可执行程序,可以发现,1.exe的返回值是不确定的,但末2位都是0; 2.exe的返回值总是0; 3.exe的返回值总是0 。如果修改2.c的return 0为return 1或2,又或者修改3.c里面的 $0 为 $1 或者 $2 ,可以发现返回值就变成了 100 和 200。这说明在x86下,主函数结束后会将返回值存放在EAX这个寄存器中。



欢迎扫码关注:




转载请注明出自 ,如是转载文则注明原出处,谢谢:)
RSS订阅地址: https://www.felix021.com/blog/feed.php
slyar Email Homepage
2010-4-14 23:11
话说,我用gcc真的可以编译成功,我附了图...
ivan
2010-3-31 09:35
return 0; -> exit(EXIT_SUCCESS);呢?
felix021 回复于 2010-3-31 15:45
本质上是一样的
Sandy
2010-3-28 13:24
晕,不仅是主函数,x86汇编任何PROC的返回值都保存在EAX中,如果是复杂结构的话EAX是指向此结构的地址。

另外如果main中没有return貌似编译器会给warning吧。

PS:你也4.4了?编译的时候加了-std=gnu++0x没有?呵呵
felix021 回复于 2010-3-28 13:26
我知道都是用eax返回的,只是这里只测试main。ubuntu从9.04应该就是用4.4了吧。
分页: 1/1 第一页 1 最后页
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称   密码   *非必须
网址   电邮   [注册]