【发布时间】:2016-04-30 22:05:20
【问题描述】:
这是我使用puts()的C程序:
#include <stdio.h>
int main(void){
puts("testing");
}
使用gcc -S -o sample.s sample.c编译成Assembly后,我得到了:
.file "sample.c"
.section .rodata
.LC0:
.string "testing"
.text
.globl main
.type main, @function
main:
pushl %ebp
movl %esp, %ebp
andl $-16, %esp
subl $16, %esp
movl $.LC0, (%esp)
call puts
leave
ret
.size main, .-main
.ident "GCC: (GNU) 4.4.5 20110214 (Red Hat 4.4.5-6)"
.section .note.GNU-stack,"",@progbits
我也是这样做的,这次我使用 printf() 而不是 puts,这就是我得到的:
.file "sample.c"
.section .rodata
.LC0:
.string "testing"
.text
.globl main
.type main, @function
main:
pushl %ebp
movl %esp, %ebp
andl $-16, %esp
subl $16, %esp
movl $.LC0, %eax //this is the difference
movl %eax, (%esp)
call printf
leave
ret
.size main, .-main
.ident "GCC: (GNU) 4.4.5 20110214 (Red Hat 4.4.5-6)"
.section .note.GNU-stack,"",@progbits
这是我不明白的,printf() 函数mov $.LC0 到%eax,然后mov %eax 到(%esp) 而puts() 函数mov %.LC0 直接到(%esp)。
我不知道这是为什么。
【问题讨论】:
-
这可能是因为
printf是一个可变参数函数,它们的调用方式与具有固定参数数量的函数不同。 -
有趣的是,在 os x 上使用 clang,两个程序都编译成同一个程序集。
-
还有为什么GCC在linux上编译位置依赖代码?
-
编译时开启优化。如果没有优化,GCC 会生成糟糕的代码,这些代码会做很多不必要的事情。
-
汇编输出在低于最大优化级别时无关紧要,您会看到编译器使代码比需要的更冗长,以便在调试器或人工阅读中更容易理解