C语言到汇编-准备工作

2020-04-08  本文已影响0人  故事观察日记

看完了王爽的《汇编语言》,接下来学习C语言,教材用K&R的《C程序设计语言》。

首先是第1章的入门程序打印“hello,world”,C语言代码如下:

#include <stdio.h> 
main()
{
  printf("hello, world\n");
} 

将这段代码保存在hello.c文件中,可用如下命令对其编译,获得对应的汇编代码:

gcc -S hello.c

gcc是linux系统中C语言的编译指令,如果要在windows系统中使用gcc,可以下载MinGW:
参考:https://jingyan.baidu.com/article/0320e2c11564ca1b87507b8f.html
安装配置好GCC后,使用gcc --help命令可查看参数“-S”的说明。

-S  Compile only; do not assemble or link
参数-S 只编译;不汇编也不连接

编译器 gcc 在执行编译工作的时候,总共需要4步:

1、预处理,生成 .i 的文件[预处理器cpp]
2、将预处理后的文件转换成汇编语言,生成文件 .s [编译器egcs]
3、有汇编变为目标代码(机器代码)生成 .o 的文件[汇编器as]
4、连接目标代码,生成可执行程序 [链接器ld]

所以指令“gcc -S hello.c”就是只执行到第2步,获得的hello.s文件就是对应的汇编程序。不过这样生成的汇编程序是ATT汇编,格式与王爽书中使用的Intel汇编有些不同。可用如下指令生成格式熟悉的Intel汇编:

gcc -S -masm=intel hello.c

参数“-masm”的说明可在官方文档中找到:
官方文档:https://gcc.gnu.org/onlinedocs
详细页面:https://gcc.gnu.org/onlinedocs/gcc-3.4.6/gcc/i386-and-x86_002d64-Options.html#i386-and-x86_002d64-Options

-masm=dialect
Output asm instructions using selected dialect. Supported choices are `intel' or `att' (the default one).
使用选定的方言输出asm指令。支持的选择是`intel'或`att'(默认值)。

成功获得hello.s文件后,用文本编辑器打开,代码如下:

    .file   "hello.c"
    .intel_syntax
    .def    ___main;    .scl    2;  .type   32; .endef
    .section .rdata,"dr"
LC0:
    .ascii "hello,world\12\0"
    .text
.globl _main
    .def    _main;  .scl    2;  .type   32; .endef
_main:
    push    ebp
    mov ebp, esp
    sub esp, 8
    and esp, -16
    mov eax, 0
    add eax, 15
    add eax, 15
    shr eax, 4
    sal eax, 4
    mov DWORD PTR [ebp-4], eax
    mov eax, DWORD PTR [ebp-4]
    call    __alloca
    call    ___main
    mov DWORD PTR [esp], OFFSET FLAT:LC0
    call    _printf
    leave
    ret
    .def    _printf;    .scl    2;  .type   32; .endef

看到了熟悉的汇编代码,不过也有一些不熟悉的。准备工作就先到这里,下次再具体学习这些代码的含义。

上一篇 下一篇

猜你喜欢

热点阅读