Mac 通过homebrew安装nasm(Mac上的汇编环境,附常见错误解决办法)

相比于大家熟悉的C、C++、Java高级编程语言,语言汇编一种低级编程语言(机器码是最低级的)。所谓低级,更接近机器底层,比如机器码直接交给CPU执行,汇编指令修改CPU某个寄存器的值。所谓高级,抽象、封装程度高,比如C、C++源程序都需要编译汇编成汇编指令,然后再将汇编代码翻译为可执行的机器码,Java源程序,需要翻译成字节码class文件,再交给Java虚拟机JVM运行。通俗的解释就是越方便人的越高级,越难懂的就低级
本篇博客将演示在Mac系统上通过homebrew安装nasm,汇编编写工具。
请先安装好homebrew工具,参考我的另外一篇博客 Mac OS安装homebrew工具(详细版)

1、安装nasm

命令:brew install nasm

进入Mac自带的终端,输入命令+回车即可。
在这里插入图片描述

2、查看nasm版本信息

命令:nasm -v

看到nasm的版本信息即表示nasm安装成功。
在这里插入图片描述

3、编写hello world

在桌面新建一个helloword.asm的文件,用记事本打开。(会vim的,直接在终端写就行,不懂当我没说)

section .data
    ;(数据段)放置变量
    ;字符串常量
    string DB 'Hello World!'
    ;字符串长度,$表示string_len的偏移地址-string的偏移地址,就是string长度
    string_len DB $ - string

section .bss
    ;bss段(也是存放变量,不过不知道与data有何区别)

section .text
    ;(代码段)放置代码

;定义入口函数
global _MAIN

_MAIN:
	;rax、rdi、rsi、rdx分别存放系统调用号、类型(输出)、字符串地址、字符串长度
    MOV rax,0x2000004
    MOV rdi,1
    MOV rsi,string
    MOV rdx,string_len
    syscall
    ;退出,rax、rdi分别存放系统调用号、类型(退出)
    mov rax,0x2000001
    mov rdi,0
    syscall

注意一下nasm汇编的格式。

4、汇编hello world

①、终端进入helloworld所在的目录

在这里插入图片描述

②、汇编helloworld
命令:nasm -f macho64 -o helloworld.o helloworld.asm

在这里插入图片描述

③、链接动态库
命令:ld -macosx_version_min 10.14 -o helloworld -e _MAIN helloworld.o -lSystem

在这里插入图片描述

④、执行helloworld
命令:./helloworld

在这里插入图片描述

5 \color{red}5、报错处理:

①、报错helloworld.asm:18: error: instruction not supported in 32-bit mode

在这里插入图片描述
\color{red}解决方法: 修改为64位模式
因为helloworld编写时,使用了raxrsi等64位的寄存器。
在这里插入图片描述

②、报错ld: warning: No version-min specified on command line

在这里插入图片描述
\color{red}解决方法: 指定command line版本
在这里插入图片描述

③、报错ld: dynamic main executables must link with libSystem.dylib for inferred architecture x86_64

在这里插入图片描述
\color{red}解决方法: 加上-lSystem参数,指定系统dylib
在这里插入图片描述

④、报错Undefined symbols for architecture x86_64: "_main", referenced from: implicit entry/start for main executable

在这里插入图片描述
\color{red}解决方法: _main写错了,修改为_MAIN
在这里插入图片描述
以上就是Mac安装Nasm的主要内容以及常见错误处理,如果你还遇到了其它问题,可以在评论下方留言。

发布了976 篇原创文章 · 获赞 230 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/qq_41855420/article/details/103744106
mac
今日推荐