burning423 发表于 2007-11-08 12:37

gcc -S test.c编译出的程序的一个问题

最近在学linux的汇编程序,我把一个最简单的C程序:

int
main(void)
{
    return 0;
}
通过gcc -S test.c编译出的程序是:

.file   "test.c"
      .text
.globl main
      .type   main, @function
main:
      leal    4(%esp), %ecx
      andl    $-16, %esp
      pushl   -4(%ecx)
      pushl   %ebp
      movl    %esp, %ebp
      pushl   %ecx
      movl    $0, %eax
      popl    %ecx
      popl    %ebp
      leal    -4(%ecx), %esp
      ret
      .size   main, .-main
      .ident"GCC: (GNU) 4.1.2 20070925 (Red Hat 4.1.2-27)"
      .section      .note.GNU-stack,"",@progbits


跟其他程序编译出来的比较了下,发现:
      leal    4(%esp), %ecx
      andl    $-16, %esp
      pushl   -4(%ecx)
      pushl   %ebp
      movl    %esp, %ebp
      pushl   %ecx
这几句在每个汇编是都会有.问下,这些是linux下特有的吗?这些代码都有些什么作用?在哪方面的文档中对这些有说明的?

skywarship 发表于 2007-11-08 19:48

可能是和操作系统有关

下面的程序
int main() {
    return 0;
}

int f() {
    int i=0;
    i++;
    return 0;
}

在WinXP下编译(GCC 3.4.2)的结果是
    .file    "a.c"
    .def    ___main;    .scl    2;    .type    32;    .endef
    .text
.globl _main
    .def    _main;    .scl    2;    .type    32;    .endef
_main:
    pushl    %ebp
    movl    %esp, %ebp
    subl    $8, %esp
    andl    $-16, %esp
    movl    $0, %eax
    addl    $15, %eax
    addl    $15, %eax
    shrl    $4, %eax
    sall    $4, %eax
    movl    %eax, -4(%ebp)
    movl    -4(%ebp), %eax
    call    __alloca
    call    ___main
    movl    $0, %eax
    leave
    ret
.globl _f
    .def    _f;    .scl    2;    .type    32;    .endef
_f:
    pushl    %ebp
    movl    %esp, %ebp
    subl    $4, %esp
    movl    $0, -4(%ebp)
    leal    -4(%ebp), %eax
    incl    (%eax)
    movl    $0, %eax
    leave
    ret


同样的程序在Debian下编译(GCC 4.2.2)的结果是
    .file    "a.c"
    .text
.globl main
    .type    main, @function
main:
    leal    4(%esp), %ecx
    andl    $-16, %esp
    pushl    -4(%ecx)
    pushl    %ebp
    movl    %esp, %ebp
    pushl    %ecx
    movl    $0, %eax
    popl    %ecx
    popl    %ebp
    leal    -4(%ecx), %esp
    ret
    .size    main, .-main
.globl f
    .type    f, @function
f:
    pushl    %ebp
    movl    %esp, %ebp
    subl    $16, %esp
    movl    $0, -4(%ebp)
    addl    $1, -4(%ebp)
    movl    $0, %eax
    leave
    ret
    .size    f, .-f
    .ident    "GCC: (GNU) 4.2.1 (Debian 4.2.1-5)"
    .section    .note.GNU-stack,"",@progbits


至于它们之间的区别,可能和运行库的实现有关,正在研究中

prolj 发表于 2007-11-09 08:24

庆祝新版开张,发本汇编的书http://linux.chinaunix.net/bbs/thread-885941-1-10.html
看一眼这个

burning423 发表于 2007-11-09 18:17

呵呵。。好的。我也再看看。谢谢
页: [1]
查看完整版本: gcc -S test.c编译出的程序的一个问题