当前位置:课程学习>>第二章>>实践活动



实践主题

初学者编写大型的汇编程序有一定的困难,可以从阅读他人写好的程序开始熟悉和掌握汇编指令及程序设计技巧。C语言的各种编译器通常带有生成汇编指令选项,或在debug模式下有时会进入汇编代码。尝试按手册指导打开生成汇编选项,观察C语言编译器生成的汇编代码,或汇编代码片断。

(1)下述代码保存为 hello.c

#include

#include

int main()

{

     int a = 225;

     printf("Hello World! %d", a);

}

(2)在命令行下执行

gcc -S hello.c -o hello.s

会得到 hello.s 文件内容如下。

     .file "hello.c"

     .text

     .def __main; .scl 2; .type 32; .endef

      .section .rdata,"dr"

.LC0:

     .ascii "Hello World! %d\0"

     .text

     .globl main

     .def main; .scl 2; .type 32; .endef

     .seh_proc main

main:

pushq %rbp

.seh_pushreg %rbp

movq %rsp, %rbp

.seh_setframe %rbp, 0

subq $48, %rsp

.seh_stackalloc 48

.seh_endprologue

call __main

movl $225, -4(%rbp)

movl -4(%rbp), %eax

movl %eax, %edx

leaq .LC0(%rip), %rcx

call printf

movl $0, %eax

addq $48, %rsp

popq %rbp

ret

.seh_endproc

.ident "GCC: (x86_64-posix-seh, Built by strawberryperl.com project) 8.3.0"

.def printf; .scl 2; .type 32; .endef

(3)在命令行下执行

gcc hello.c -o hello.exe

会得到 hello.exe

执行 hello.exe 运行结果为

Hello World! 225

hello.s可以视为hello.c到hello.exe的中间步骤。

上述代码在本章示例代码 由C生成汇编.ZIP 中。


进入拓展资源