汇编: Linux中汇编程序的编译

NASM在Linux系统上创建汇编程序

编写汇编程序

  • Code

        ;; 可执行文件名: helloworld.asm
        ;; 程序版本: 0.01
        ;; 创建日期: 2019/1/02
        ;; 最后修改日期: 2019/1/02
        ;; 作者: ieeqc
        ;; 描述:
        ;; - 汇编语言helloworld程序实现
        ;; 
        ;; 编译指令
        ;; - nasm -f elf64 -g -F stabs helloworld.asm
        ;; - ld -o helloworld helloworld.o
    
        SECTION .data               ; 包含已经初始化的数据段
        
    EatMsg: db "Hello World!", 10   ; 10 代表 ASCII回车等同于c语言"\n"
    EatLen: equ $-EatMsg            ; 计算EatMsg的串长度
        
        SECTION .bss                ; 包含未初始化的数据段
        SECTION .text               ; 包含代码段
    
        global _start               ; 连接器根据此寻找程序入口点
        
    _start:
        nop                         ; 方便gdb调试
        mov eax, 4                  ; 系统调用编号: sys_write
        mov ebx, 1                  ; 指定文件描述符为1, 标准输出
        mov ecx, EatMsg             ; 传递打印信息
        mov edx, EatLen             ; 传递打印信息的长度
        int 80H                     ; 中断执行系统调用
        mov eax, 1                  ; 系统调用编号: Exit
        mov ebx, 0                  ; 返回一个0代表运行成功
        int 80H                     ; 中断执行系统调用
    
    

使用NASM编译程序

NASM与ld不兼容

  • 创建程序

    nasm -f elf -g -F stabs helloworld.asm
    
    ld -o helloworld helloworld.o
    
    • 可能出现错误: ld: i386 architecture of input file 'helloworld.o' is incompatible with i386:x86-64 output
    • 原因:
      • nasm编译器默认输出32位程序, 在而ld默认输出64位,不兼容

正确创建方法

  • 64位

    nasm -f elf64 -g -F stabs helloworld.asm -o helloworld.o
    
    ld -o helloworld helloworld.o
    
  • 32位

    nasm -f elf -g -F stabs helloworld.asm -o helloworld.o
    
    ld -m elf_i386 -o helloworld helloworld.o
    
posted @ 2021-03-14 12:03  南方与南  阅读(522)  评论(0)    收藏  举报