Как установить nasm на windows 10

Последнее обновление: 12.10.2023

NASM является кроссплатформенным ассемблером, который доступен в том числе и на Windows. Рассмотрим, как использовать NASM на Windows.

Установка

Для работы с NASM нам надо установить непосредственно сам ассемблер. Для этого на официальном сайте перейдем на страницу https://www.nasm.us/pub/nasm/releasebuilds/2.16.01/win64/,
где находятся файлы ассемблера NASM версии 2.16.01 для 64-разрядной версии Windows:

Установка NASM на Windows

Здесь нам доступен ассемблер в виде двух пакетов. Один пакет установщика (nasm-2.16.01-installer-x64.exe), а второй — архив (nasm-2.16.01-win64.zip).
Загрузим zip-архив.
. Например, загрузим zip-архив и после загрузки распакуем его. В папке распакованного архива мы можем найти два файла

ассемблер NASM на Windows

Это прежде всего сам ассемблер — файл nasm.exe и дизассемблер — файл ndisasm.exe

Чтобы не прописывать весь путь к ассемблеру, занесем его в переменные среды. Для этого можно в окне поиска в Windows ввести «изменение переменных среды текущего пользователя»:

изменение переменных среды текущего пользователя в Windows

Нам откроется окно Переменныех среды:

Добавление GCC в переменные среды на Windows

И добавим путь к ассемблеру. Например, в моем случае архив ассемблера распакован в папку C:\nasm-2.16.01, соответственно я указываю
в переменной Path среды эту папку:

ассемблер NASM на Windows

Если все настроено правильно, то мы можем запустить командную строку и с помощью команды nasm -v узнать текущую версию ассемблера:

C:\Users\eugen>nasm -v
NASM version 2.16.01 compiled on Dec 21 2022

C:\Users\eugen>

Начало работы с NASM

Определим в файловой системе каталог для файлов с исходным кодом и создадим в нем следующий файл hello.asm:

global _start       ; делаем метку метку _start видимой извне

section .text       ; объявление секции кода
_start:             ; метка _start - точка входа в программу
    mov rax, 22     ; произвольный код возврата - 22 
    ret             ; выход из программы

Рассмотрим поэтапно данный код. Вначале идет директива global:

global _start

Данная директива делает видимой извне определенную метку программы. В данном случае метку _start, которая является точкой входа в программу. Благодаря этому компоновщик при компоновке программы в исполняемый файл сможет увидеть данную метку.

Затем идет секция кода программы, которая и определяет выполняемые программой действия. Для определения секции применяется директива
section, после которой указывается имя секции. Причем секция кода программы должна называться .text.

section .text 

Далее собственно идет код программы. И он начинается с определения метки _start, на которую собственно и проецируется
программа. Сама по себе метка представляет произвольное название, после которого идет двоеточие. После двоеточия могут идти инструкции программы или определения данных.

Метка _start выступает в качестве точки входа в программу. Название подобной метки произвольное, но обычно это или _start или _main

Наша программа не производит какой-то феноменальной работы. Все что она делает — это помещает в регистр rax число 22 и завершается. Для помещения числа в регистр применяется инструкция
mov:

mov rax, 22

Инструкция mov помещает в первый операнд — регистр rax значение из второго операнда — число 22.

Затем идет вызов инструкции ret, которая завершает программу

ret

Кроме директив и инструкций, которые определяют действия программы, также следует отметить комментарии. Комментарии начинаются с точки с запятой ;. Комментарии не учитываются при компиляции,
никак не влияют на объект или работоспособность программы и нужны лишь в качестве текстового описания отдельных строк или блоков программы.

global _start  ; делаем метку метку _start видимой извне - это текст комментария

Компиляция

Для компиляции откроем командную строку, перейдем в ней к папке с исходным кодом (где располагается файл hello.asm) и выполним следующую команду

nasm -f win64 hello.asm -o hello.o

Здесь с помощью опции -f указывается формат файла, в который мы хотим скомпилировать код.
Для 64-разрядной ОС Windows это — win64. После этого указывается файл, который мы хотим скомпилировать — наш файл hello.asm.
Затем опция -o hello.o указывает на имя скомпилированного файла. В результате выполнения этой команды будет создан объектный файл hello.o

Однако файл hello.o — это объектный файл, а не исполняемый. Он содержит машинный код, который понимает компьютер, но чтобы его можно было запускать как обычную
программу, его надо скомпоновать в исполняемый файл. И для этого нужна программа компоновщика (он же линковщик/линкер или linker).
Недостатком NASM является то, что он не предоставляет встроенного компоновщика. И нам надо использовать внешнюю программу компоновки. Где ее взять?
Далее я рассмотрю два варианта — использование компоновщика из пакета GCC и использование компоновщика компилятора Visual C/C++, который идет вместе с Visual Studio. Оба варианта равноценны.

Компоновка с помощью GCC

Вначале нам надо установить пакет GCC. Пакет компиляторов GCC для Windows не имеет какого-то одного единого разработчика, разные организации могут выпускать свои сборки. Для Windows одной из наиболее популярных версий GCC является пакет средств для разработки от
некоммерческого проекта MSYS2. Следует отметить, что для MSYS2 требуется 64-битная версия Windows 7 и выше (то есть Vista, XP и более ранние версии не подходят)

Итак, загрузим программу установки MSYS2 с официального сайта MSYS2:

Установка MSYS для разработки под С

После загрузки запустим программу установки:

Установка пакета mingw-w64 и msys2 на Windows

На первом шаге установки будет предложено установить каталог для установки. По умолчанию это каталог C:\msys64:

Установка компиляторов Си MSYS2 на Windows

Оставим каталог установки по умолчанию (при желании можно изменить). На следующем шаге устанавливаются настройки для ярлыка для меню Пуск, и затем собственно будет произведена установка.
После завершения установки нам отобразить финальное окно, в котором нажмем на кнопку Завершить

Установка компиляторов MSYS2 на Windows

После завершения установки запустится консольное приложение MSYS2.exe. Если по каким-то причинам оно не запустилось,
то в папке установки C:/msys64 надо найти файл usrt_64.exe:

компиляторы MSYS2.exe на Windows

Теперь нам надо установить собственно набор компиляторов GCC. Для этого введем в этом приложении следующую команду:

pacman -S mingw-w64-ucrt-x86_64-gcc

Для управления пакетами MSYS2 использует пакетный менеджер Packman. И данная команда говорит пакетному менелжеру packman установить пакет mingw-w64-ucrt-x86_64-gcc,
который представляет набор компиляторов GCC (название устанавливаемого пакета указывается после параметра -S).

Установка компиляторов MSYS2 на Windows

Если после завершения установки мы откроем каталог установки и зайдем в нем в папку C:\msys64\ucrt64\bin,
то найдем там файл компоновщика ld

GNU ассемблер на Windows

Для упрощения запуска компоновщика мы можем добавить путь к нему в Переменные среды:

Определение пути к компилятору GCC в переменных среды на Windows

Чтобы убедиться, что нам доступен компоновщик GCC — программа ld, введем следующую команду:

ld --version

В этом случае нам должна отобразиться версия компоновщика

c:\asm>ld --version
GNU ld (GNU Binutils) 2.40
Copyright (C) 2023 Free Software Foundation, Inc.
This program is free software; you may redistribute it under the terms of
the GNU General Public License version 3 or (at your option) a later version.
This program has absolutely no warranty.

c:\asm>

Теперь скомпонуем файл hello.o в исполняемый файл hello.exe с помощью следующей команды:

ld hello.o -o hello.exe

Мы можем запустить этот файл, введя в консоли его название и нажав на Enter. Но наша программа ничего не выводит на консоль, поэтому после запуска программы мы ничего не увидим. Тем не менее
наша программа устанавливает регистр RAX. А значение этого регистра при завершении программы рассматривается в Windows как статусный код возврата, который сигнализирует, как завершилась программа (успешно или не успешно).
И мы можем этот статусный код получить, если после выполнения программы введем команду

echo %ERRORLEVEL%

И нам должно отобразится число 22 — значение регистра RAX. Полный консольный вывод:

c:\asm>nasm -f win64 hello.asm -o hello.o

c:\asm>ld hello.o -o hello.exe

c:\asm>hello.exe

c:\asm>echo %ERRORLEVEL%
22

c:\asm>

Установка компоновщика link.exe

Компоновщик от GCC — не единственный компоновщик, который можно использовать для компоновки программы на Windows. Еще один вариант представляет компоновщик
link.exe из пакета инструментов разработки для C/C++ для Visual Studio. Условным плюсом этого компоновщика может быть то, что его
разработчик — Microsoft, поэтому можно ожидать более лучшей интеграции с Windows. Поэтому также рассмотрим и этот способ.

Сперва нам надо установить для Visual Studio инструменты разработки для C/C++. Установщик для среды Visual Studio можно загрузить по следующему адресу:
Microsoft Visual Studio 2022. После загрузки программы установщика Visual Studio запустим ее и в окне устанавливаемых
опций выберем пункт Разработка классических приложений на C++:

Установка MASM 64 в Windows

И нажмем на кнопку установки.

В зависимости от конкретной подверсии и номера сборки Visual Studio точное расположение файлов может варьироваться. Например, в моем случае это папка
C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.37.32822\bin\Hostx64\x64\. И в этой папке можно найти программу компоновщика link.exe.
Причем при обновлениях Visual Studio этот расположение может измениться, так как при обновлении меняется и версия Visual Studio. Поэтому к конкретным путям можно не цепляться. Вместо этого
мы можем перейти к меню Пуск и в списке программ найти пункт Visual Studio и подпункт
x64 Native Tools Command Prompt for VS 2022

Build Tools for Visual Studio 2022 и MASM64 в Windows

Нам должна открыться консоль. Введем в нее link, и нам отобразится версия ассемблера и некоторая дополнительная информация:

**********************************************************************
** Visual Studio 2022 Developer Command Prompt v17.7.4
** Copyright (c) 2022 Microsoft Corporation
**********************************************************************
[vcvarsall.bat] Environment initialized for: 'x64'

C:\Program Files\Microsoft Visual Studio\2022\Community>link
Microsoft (R) Incremental Linker Version 14.37.32824.0
Copyright (C) Microsoft Corporation.  All rights reserved.

 usage: LINK [options] [files] [@commandfile]

   options:

      /ALIGN:#
      /ALLOWBIND[:NO]
      /ALLOWISOLATION[:NO]
      /APPCONTAINER[:NO]
      /ASSEMBLYDEBUG[:DISABLE]
      /ASSEMBLYLINKRESOURCE:filename
      /ASSEMBLYMODULE:filename
      /ASSEMBLYRESOURCE:filename[,[name][,PRIVATE]]
      /BASE:{address[,size]|@filename,key}
      /CLRIMAGETYPE:{IJW|PURE|SAFE|SAFE32BITPREFERRED}
      /CLRLOADEROPTIMIZATION:{MD|MDH|NONE|SD}
      /CLRSUPPORTLASTERROR[:{NO|SYSTEMDLL}]
      /CLRTHREADATTRIBUTE:{MTA|NONE|STA}
      /CLRUNMANAGEDCODECHECK[:NO]
      /DEBUG[:{FASTLINK|FULL|NONE}]
    ............................

В частности, можно увидеть, что версия компоновщика — 14.37.32824.0 и все опции, которые можно передать программе при компоновке. Стоит отметить, что запуск этой этой утилиты фактически представляет запуск файла C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvars64.bat —
он по сути вызывает другой файл — vcvarsall.bat, который собственно и настраивает окружение для выполнения ассемблера.

Используем этот компоновщик. Для этого откроем программу x64 Native Tools Command Prompt for VS 2022 и перейдем в ней к папке, где располагается объектный файл
hello.o. Затем выполним следующую команду

link hello.o /entry:_start /subsystem:console /out:hello2.exe

В данном случае компоновщику передаем ряд параметров:

  • собственно объектный файл hello.o, который будет компилироваться в исполняемое приложение

  • Параметр /entry:_start указывает компоновщику на точку входа в программу —
    это наша метка «_start».

  • Параметр /subsystem:console указывает компоновщику, что создается консольное (не графическое) приложение.

  • Параметр /out:hello2.exe устанавливает имя генерируемого файла приложение — оно будет называться «hello2.exe».

В результате будет создан файл hello2.exe, который мы также можем запускать:

c:\asm>link hello.o /entry:_start /subsystem:console /out:hello2.exe
Microsoft (R) Incremental Linker Version 14.37.32824.0
Copyright (C) Microsoft Corporation.  All rights reserved.


c:\asm>hello2.exe

c:\asm>echo %ERRORLEVEL%
22

c:\asm>

Создание первой программы на Windows

Теперь создадим более осмысленную программу, которая выводит на экран строку,kernel32.lib и для этого изменим файл hello.asm следующим образом:

global _start       ; делаем метку метку _start видимой извне

extern WriteFile        ; подключем функцию WriteFile
extern GetStdHandle     ; подключем функцию GetStdHandle

section .data   ; секция данных
message: db "Hello METANIT.COM!",10  ; строка для вывода на консоль

section .text       ; объявление секции кода
_start:             ; метка _start - точка входа в программу
    sub  rsp, 40   ; Для параметров функций WriteFile и GetStdHandle резервируем 40 байт (5 параметров по 8 байт)
    mov  rcx, -11  ; Аргумент для GetStdHandle - STD_OUTPUT
    call GetStdHandle ; вызываем функцию GetStdHandle
    mov  rcx, rax     ; Первый параметр WriteFile - в регистр RCX помещаем дескриптор файла - консоли
    mov  rdx, message    ; Второй параметр WriteFile - загружаем указатель на строку в регистр RDX
    mov  r8d, 18      ; Третий параметр WriteFile - длина строки для записи в регистре R8D 
    xor  r9, r9       ; Четвертый параметр WriteFile - адрес для получения записанных байтов
    mov  qword [rsp + 32], 0  ; Пятый параметр WriteFile
    call WriteFile ; вызываем функцию WriteFile
    add  rsp, 40
    ret             ; выход из программы

Разберем эту программу. Для вывода строки на консоль нам надо использовать нативные функции GetStdHandle и WriteFile.
И чтобы воспользоваться этими функциями подключаем их с помощью директивы extern

extern WriteFile
extern GetStdHandle

Далее идет определение секции данных — секции .data:

section .data   ; секция данных
message: db "Hello METANIT.COM!",10  ; строка для вывода на консоль

В секции .data определена метка message, на которую проецируется строка. По сути message — это переменная, которая представляет строку.
После метки указывается тип данных. Строка в ассемблере — это просто набор байтов, поэтому имеет тип db. Затем в кавычках определяется собственно выводимая строка — "Hello METANIT.COM!",10. Обратите внимание на 10 после строки — это код символа перевода строки. То есть при выводе мы ожидаем, что будет происходить перевод на другую строку.

Затем идет секция кода — секция .text и метка _start — точка входа в программу

section .text       ; объявление секции кода
_start:             ; метка _start - точка входа в программу

В программе для вызова функций первым делом необходимо настроить стек. В частности, резервируем в стеке 40 байт для параметров функций GetStdHandle и WriteFile и при этом учитываем выравнивание
стека по 16-байтной границе. Указатель на верхушку стека хранится в регистре
rsp. Поэтому вычитаем с помощью инструкции sub из значения в регистре rsp 40 байт

sub rsp, 40

Почему 40? Прежде всего при вызове функций WinAPI (как в данном случае функций GetStdHandle и WriteFile) необходимо зарезервировать в стеке как минимум 32 байта — так называемое
«shadow storage» (теневое хранилище). Далее нам надо учитывать количество параметров функции. Пеовые 4 параметра функций передаются через регистры, а параметры начиная с 5-го передаются через стек.
Соответственно для 5-го и последующих параметров надо выделить в стеке область. Для каждого параметра вне зависимости от его размера выделяется 8 байт. Функция WriteFile как раз принимает 5 параметров, поэтому для нее надо выделить дополнительные 8 байт в стеке.
Поэтому получаем 32 байта + 8 байт (5-й параметр WriteLine) = 40 байт. Количество параметров смотрим по функции с наибольшим количеством параметров. Третий момент — нам надо учитывать, что перед вызовом функций WinAPI стек имел выравнивание по 16 байтовой границе, то есть значение в RSP
должно быть кратно 16. По умолчанию при вызове функции в стек помещается адрес возврата функии размером 8 байт. Поэтому наши 40 байт + 8 байт (адрес возврата из функции) дадут 48 байт — число кратное 16.

Вначале нам надо использовать встроенную функцию GetStdHandle(), которая позволяет получить дескриптор на устройство ввода-вывода. Она имеет следующее определение на C:

HANDLE WINAPI GetStdHandle(
  _In_ DWORD nStdHandle
);

Функция GetStdHandle() получает числовой код устройства, с которым мы хотим взаимодействовать. В нашем случае нам надо получить устройство стандартного вывода (для вывода строки), которым по умолчанию является консоль. Для обращения к консоли надо передать число -11, которое надо поместить в
регистр rcx:

 mov  rcx, -11  ; Аргумент для GetStdHandle - STD_OUTPUT

После установки параметра этой функции вызываем ее с помощью инструкции call:

call GetStdHandle

В результате выполнения функция GetStdHandle возвращает дескриптор — объект, через который мы можем взаимодействовать с консолью. Этот дескриптор помещается в регистр
rax. Получив этот дескриптор, используем его для вывода на консоль строки с помощью функции WriteFile. Для справки ее определение на С++

BOOL WriteFile(
  [in]                HANDLE       hFile,
  [in]                LPCVOID      lpBuffer,
  [in]                DWORD        nNumberOfBytesToWrite,
  [out, optional]     LPDWORD      lpNumberOfBytesWritten,
  [in, out, optional] LPOVERLAPPED lpOverlapped
);

Вызов функции GetStdHandle помещает в регистр rax дескриптор консоли. И для вывода строкии на консоль с помощью функции WriteFile нам надо поместить
этот дескриптор в регистр rcx

mov rcx, rax

Затем также с помощью инструкции mov загружаем в регистр rdx адрес выводимой строки

mov rdx, message

Далее в регистр r8d помещаем длину выводимой строки в байтах — в данном случае это 18 байт:

mov  r8d, 18

Поскольку у нас строка с символами ASCII, и каждый символ эквивалентен 1 байту, то получаем, что в строке message с учетом последнего символа с числовым кодом 10 будет 18 байт.

Затем в регистре r9 устанавливаем адрес четвертого параметра функции WriteFile:

xor  r9, r9

В данном случае нам не нужно количество считанных байтов, и с помощью инструкции xor обнуляем значение регистра r9.

Последний — пятый параметр функции WriteFile должен иметь значение NULL, по сути 0. Поэтому устанавливаем для него значение 0, смещаясь в стеке вперед на 32 байта (4 параметра * 8):

mov qword [rsp + 32], 0

Инструкция mov помещает значение в определенное место. Здесь в качестве значения служит число 0. А место определяется выражением
qword [rsp + 32]. qword указывает, что этот операнд описывает адрес размером в четыре слова, что означает 8 байтов (слово имеет длину 2 байта). То есть число 0 представляет 8-байтное значение и помещается по адресу rsp + 32.

И далее собственно вызываем функцию WriteFile:

call WriteFile

Этот вызов должен привести к выводу строки на консоль. После этого восстанавливаем значение верхушки стека. Для этого с помощью инструкции add прибавляем
к значению в регстре rsp ранее отнятые 40 байт:

add rsp, 40

И с помощью инструкции ret выходим из программы.

Компиляция

Поскольку теперь программа использует внешние функции WinApi — GetStdHandle и WriteFile, которые определены во внешней библиотеке kernel32.lib, то при компоновке
нам надо подключить эту библиотеку. В зависимости от используемого компоновщика/линкера этот процесс может немного отличаться. Например, при использовании компоновщика ld
из комплекта инструментов GCC все подключаемые библиотеки передаются с помощью опции -l:

ld hello.o -o hello.exe -l kernel32

Здесь последний параметр -l kernel32 как раз указывает, какую библиотеку надо подлючить, при чем название библиотеки указывается без расширения файла.

При использовании компоновщика link.exe от Microsoft подключаемая библиотека просто передается вместе с компонуемыми файлами:

link hello.o kernel32.lib /entry:_start /subsystem:console /out:hello2.exe

Итак, повторно скомпилируем файл и скомпонуем одним из компоновщиков. Затем запустим полученный исполняемый файл, и консоль должна вывести нам строку.
Полный процесс при использовании компоновщика ld из комплекта GCC:

c:\asm>nasm -f win64 hello.asm -o hello.o

c:\asm>ld hello.o -o hello.exe -l kernel32

c:\asm>hello.exe
Hello METANIT.COM!
c:\asm>

Полный процесс при использовании компоновщика link от Microsoft (компоновка выполняется в программе x64 Native Tools Command Prompt for VS 2022):

c:\asm>nasm -f win64 hello.asm -o hello.o

c:\asm>link hello.o kernel32.lib /entry:_start /subsystem:console /out:hello2.exe
Microsoft (R) Incremental Linker Version 14.37.32824.0
Copyright (C) Microsoft Corporation.  All rights reserved.


c:\asm>hello2.exe
Hello METANIT.COM!
c:\asm>

Introduction

As a beginner in assembly language programming, you’re likely to come across the term NASM, which stands for Netwide Assembler. NASM is a popular assembler that can be used to write assembly code for various platforms, including Windows. In this article, we’ll show you how to install NASM in Windows 10 without using DosBox or VM.

What is NASM?

NASM is a free and open-source assembler that can be used to write assembly code for various platforms, including Windows, Linux, and macOS. It’s a popular choice among assembly language programmers due to its ease of use and flexibility. NASM can be used to write assembly code for various architectures, including x86, x64, and ARM.

Why Install NASM in Windows 10?

Installing NASM in Windows 10 can be beneficial for several reasons:

  • Learning Assembly: NASM is a popular choice among assembly language programmers, and installing it in Windows 10 can help you learn assembly language programming.
  • Writing Assembly Code: NASM can be used to write assembly code for various platforms, including Windows, Linux, and macOS.
  • Cross-Platform Compatibility: NASM can be used to write assembly code that’s compatible with various platforms, including Windows, Linux, and macOS.

System Requirements

Before installing NASM in Windows 10, make sure your system meets the following requirements:

  • Windows 10: NASM can be installed on Windows 10.
  • 64-bit or 32-bit: NASM can be installed on both 64-bit and 32-bit versions of Windows 10.
  • Administrative Privileges: You’ll need administrative privileges to install NASM in Windows 10.

Installing NASM in Windows 10

Installing NASM in Windows 10 is a straightforward process that can be completed in a few steps:

Step 1: Download NASM

To install NASM in Windows 10, you’ll need to download the NASM installer from the official NASM website. Follow these steps to download NASM:

  1. Open a Web Browser: Open a web browser, such as Google Chrome or Mozilla Firefox.
  2. Visit the NASM Website: Visit the official NASM website at https://www.nasm.us/.
  3. Click on the Download Button: Click on the download button to download the NASM installer.
  4. Select the Correct Version: Select the correct version of NASM for your system architecture (32-bit or 64-bit).

Step 2: Run the Installer

Once you’ve downloaded the NASM installer, follow these steps to run the installer:

  1. Open the Installer: Open the NASM installer file that you downloaded.
  2. Follow the Installation Instructions: Follow the installation instructions to install NASM in Windows 10.
  3. Choose the Installation Location: Choose the installation location for NASM.
  4. Choose the Components to Install: Choose the components to install, such as the NASM assembler and the NASM debugger.

Step 3: Configure the Environment Variables

After installing NASM in Windows 10, you need to configure the environment variables to use NASM. Follow these steps to configure the environment variables:

  1. Open the System Properties: Open the system properties by pressing the Windows key + Pause/Break.
  2. Click on the Advanced Tab: Click on the advanced tab.
  3. Click on the Environment Variables Button: Click on the environment variables button.
  4. Add a New Variable: Add a new variable for the NASM assembler and the NASM debugger.
  5. Set the Variable Value: Set the variable value to the path of the NASM assembler and the NASM debugger.

Step 4: Verify the Installation

After configuring the environment variables, you can verify the installation of NASM in Windows 10 by following these steps:

  1. Open a Command Prompt: Open a command prompt.
  2. Type the NASM Command: Type the NASM command to verify the installation.
  3. Check the Output: Check the output to ensure that NASM is installed correctly.

Using NASM with CodeBlocks

Once you’ve installed NASM in Windows 10, you can use it with CodeBlocks to write assembly code. Follow these steps to use NASM with CodeBlocks:

  1. Open CodeBlocks: Open CodeBlocks.
  2. Create a New Project: Create a new project in CodeBlocks.
  3. Choose the Project Type: Choose the project type as assembly code.
  4. Choose the Compiler: Choose the compiler as NASM.
  5. Configure the Compiler Options: Configure the compiler options to use NASM.

Conclusion

Installing NASM in Windows 10 is a straightforward process that can be completed in a few steps. By following the steps outlined in this article, you can install NASM in Windows 10 and use it with CodeBlocks to write assembly code. Remember to configure the environment variables to use NASM, and verify the installation by typing the NASM command in a command prompt.

Frequently Asked Questions

Q: What is NASM?

A: NASM is a free and open-source assembler that can be used to write assembly code for various platforms, including Windows, Linux, and macOS.

Q: Why install NASM in Windows 10?

A: Installing NASM in Windows 10 can be beneficial for several reasons, including learning assembly language programming, writing assembly code, and cross-platform compatibility.

Q: What are the system requirements for installing NASM in Windows 10?

A: The system requirements for installing NASM in Windows 10 include Windows 10, 64-bit or 32-bit, and administrative privileges.

Q: How do I install NASM in Windows 10?

A: To install NASM in Windows 10, follow the steps outlined in this article, including downloading the NASM installer, running the installer, configuring the environment variables, and verifying the installation.

Q: Can I use NASM with CodeBlocks?

Q: What is NASM?

A: NASM (Netwide Assembler) is a free and open-source assembler that can be used to write assembly code for various platforms, including Windows, Linux, and macOS.

Q: Why install NASM in Windows 10?

A: Installing NASM in Windows 10 can be beneficial for several reasons, including:

  • Learning Assembly: NASM is a popular choice among assembly language programmers, and installing it in Windows 10 can help you learn assembly language programming.
  • Writing Assembly Code: NASM can be used to write assembly code for various platforms, including Windows, Linux, and macOS.
  • Cross-Platform Compatibility: NASM can be used to write assembly code that’s compatible with various platforms, including Windows, Linux, and macOS.

Q: What are the system requirements for installing NASM in Windows 10?

A: The system requirements for installing NASM in Windows 10 include:

  • Windows 10: NASM can be installed on Windows 10.
  • 64-bit or 32-bit: NASM can be installed on both 64-bit and 32-bit versions of Windows 10.
  • Administrative Privileges: You’ll need administrative privileges to install NASM in Windows 10.

Q: How do I install NASM in Windows 10?

A: To install NASM in Windows 10, follow these steps:

  1. Download the NASM Installer: Download the NASM installer from the official NASM website.
  2. Run the Installer: Run the NASM installer and follow the installation instructions.
  3. Configure the Environment Variables: Configure the environment variables to use NASM.
  4. Verify the Installation: Verify the installation by typing the NASM command in a command prompt.

Q: Can I use NASM with CodeBlocks?

A: Yes, you can use NASM with CodeBlocks to write assembly code. Follow these steps to configure CodeBlocks to use NASM:

  1. Open CodeBlocks: Open CodeBlocks.
  2. Create a New Project: Create a new project in CodeBlocks.
  3. Choose the Project Type: Choose the project type as assembly code.
  4. Choose the Compiler: Choose the compiler as NASM.
  5. Configure the Compiler Options: Configure the compiler options to use NASM.

Q: What are the benefits of using NASM with CodeBlocks?

A: The benefits of using NASM with CodeBlocks include:

  • Easy Assembly Code Writing: NASM makes it easy to write assembly code.
  • Cross-Platform Compatibility: NASM can be used to write assembly code that’s compatible with various platforms, including Windows, Linux, and macOS.
  • Debugging and Testing: NASM provides a debugger and testing tools to help you debug and test your assembly code.

Q: Can I use NASM with other IDEs?

A: Yes, you can use NASM with other IDEs, including:

  • Visual Studio: You can use NASM with Visual Studio to write assembly code.
  • Eclipse: You can use NASM with Eclipse to write assembly code.
  • NetBeans: You can use NASM with NetBeans to write assembly code.

Q: What are the limitations of using NASM?

A: The limitations of using NASM include:

  • Platform-Specific Code: NASM can only be used to write platform-specific code.
  • Limited Support: NASM may not have the same level of support as other assemblers.
  • Complexity: NASM can be complex to use, especially for beginners.

Q: Can I use NASM for other purposes?

A: Yes, you can use NASM for other purposes, including:

  • Embedded Systems: NASM can be used to write assembly code for embedded systems.
  • Firmware Development: NASM can be used to write firmware for various devices.
  • Operating System Development: NASM can be used to write operating system code.

Conclusion

Installing NASM in Windows 10 is a straightforward process that can be completed in a few steps. By following the steps outlined in this article, you can install NASM in Windows 10 and use it with CodeBlocks to write assembly code. Remember to configure the environment variables to use NASM, and verify the installation by typing the NASM command in a command prompt.

How do I install NASM on Windows?

To install NASM, do the following:

  1. Double-click on the “My Computer” icon on your desktop.
  2. Right-click on your CD-Rom icon, and select “Explore”
  3. Navigate to the installnasm folder.
  4. Double-click on the file nasmsetup.exe.

Where does NASM install to?

On July 1, 2020, the official NASM git repository moved to github.

How do I use NASM software?

Install the codeblocks by running the setup.exe file you downloaded. Extract and install nasm into the codeblocks folder, e.g., C:Program FilesCodeBlocksMinGWbin. Check whether the installation is working or not by the source code below for a test run.

How do I know if NASM is installed?

Check The netwide assembler (NASM) website for the latest version.

Installing NASM

  1. Open a Linux terminal.
  2. Type whereis nasm and press ENTER.
  3. If it is already installed, then a line like, nasm: /usr/bin/nasm appears. Otherwise, you will see just nasm:, then you need to install NASM.

What is Nasm Ubuntu?

Ubuntu Manpage: nasm – the Netwide Assembler, a portable 80×86 assembler. options. syntax. directives. format-specific directives.

Can Nasm run on Windows?

NASM stands for the net assembler. if you want to type edit and execute an assembly language program you need to install NASM on Windows 10 using DosBox. in this tutorial you will be guided about how to install NASM on Windows 10 using dosbox. … NASM can be used to write 16 bit, 32-bit and 64-bit programs.

Is NASM accredited?

The NASM® CPT online personal training certification is proudly accredited by the National Commission for Certifying Agencies (NCCA). The NCCA is a nationally recognized third party agency that accredits certification programs which are able to meet and comply with its standards.

What does Nasm stand for?

Education and Performance

For more than 30 years, the National Academy of Sports Medicine ™ (NASM) has set the standard in certification, continuing education, solutions and tools for health and fitness, sports performance and sports medicine professionals.

Does Nasm work on Mac?

Most tutorials for nasm are written with Linux in mind, so you’ll usually need to make a few adjustments to get things working on macOS. NASM Hello World for x86 and x86_64 Intel Mac OS is a great place to start, and the NASM Tutorial a great place to go from there (see section ‘Using NASM on macOS’).

Is Nasm recognized in Australia?

GILBERT, Ariz. –(BUSINESS WIRE)–The National Academy of Sports Medicine (NASM), a world leader in fitness and nutrition certifications, is expanding its global presence through a new collaboration with Clean Health, a leading registered training provider in Australia.

What is RESB in NASM?

3.2.2 RESB and Friends: Declaring Uninitialized Data. RESB, RESW, RESD, RESQ, REST, RESO, RESY and RESZ are designed to be used in the BSS section of a module: they declare uninitialized storage space. Each takes a single operand, which is the number of bytes, words, doublewords or whatever to reserve.

What is Nasm shell?

The National Association of Shell Marketers, Inc. (NASM) is a brand-specific trade association which represents the interests of those companies which have wholesale supply contracts with Shell Oil, its licensees or its branded marketers.

What is QEMU Nasm?

QEMU is the PC emulator and the NASM is the assembler( converting . asm files to . bin files), which converts assembly language into raw machine code executable files.

What are assembler directives?

Directives are instructions used by the assembler to help automate the assembly process and to improve program readability. Examples of common assembler directives are ORG (origin), EQU (equate), and DS. B (define space for a byte). … The assembler directives listed below are the most common ones used for Code Warrior.

How do I get Winget?

There are several ways to install the winget tool:

  1. The winget tool is included in the flight or preview version of Windows App Installer. …
  2. Participate in the Windows Insider flight ring.
  3. Install the Windows Desktop App Installer package located on the Releases page for the winget repository.

How do I download Masm?

You will have to download two files: DOS Box Installer – Download the file from here. 8086 Assembler – Download the file from here.

After downloading the files,

  1. Install DOS Box on your computer.
  2. Extract the second file (8086. rar) to C drive.
  3. Now open DOS Box and type the following commands:

Do personal trainers make good money?

Yes, making good money as a personal trainer is very viable. Even entry-level personal trainers can make upwards of $25 an hour, and easily up to $100 an hour if they are experienced. … Private personal trainers can make even more per hour, charging up top $100 an hour.

Which is better ace or NASM?

NASM is considered more of a corrective exercise certification, whereas ACE is more of a general CPT certification. NASM progresses clients using their OPT training model, while ACE uses its IFT training model. … The pass rate for the ACE test is 65%, while the pass rate for the NASM test is 64%.

Can you take the NASM exam without taking the course?

For students unable to take their test in-person due to COVID-19, NASM is offering an exclusive opportunity to take your NASM-CPT final exam online through a live remote proctor. … This opportunity is available to both new students, and those already enrolled in a CPT course.

How do I update Nasm?

  1. Step 1: Complete Your CEUs & CPR/AED Certification. NASM-CPTs are required to earn 2.0 Continuing Education Units (20 contact hours) every two years in order to recertify. …
  2. Step 2: Upload Documentation to the Recertification Portal. …
  3. Step 3: Pay Your Recertification Fee.

What do you mean by an assembler?

An assembler is a program that takes basic computer instructions and converts them into a pattern of bits that the computer’s processor can use to perform its basic operations. Some people call these instructions assembler language and others use the term assembly language.

Footstep 2: Install a Compiler and Assembler

Table of Contents

  • Step 2: Install a Compiler and Assembler

    • 2.1: Install a GCC compiler

    • 2.2: Download Netwide Assembler (NASM)

    • Part 3: Set the path to the assembler

      • Verify the programs execute in CMD

      • Errors

      • Set path in Windows System

Objective: Install MinGW and NASM to compile an .asm file and then create an .exe executable.

2.1: Install a GCC compiler

We will use MinGW to compile our associates projects

  1. Observe the installer on MinGW’southward site or download information technology from this site straight.

  2. Note the default the installation directory and and then press Proceed.

    Circumspection

    • MinGW might non piece of work correctly if you install it in some other directory other than the default.

    • And so, we recommend using the default installation directory.

    image1

  3. The installer will download and install MinGW.

  4. Verify that the installer downloaded and installed all selected items.

    image2

  5. Select mingw32-base-bin and apply changes.

    • From the menu: Installation Apply Changes

    • The installer might have a while depending on your internet connexion.

    image3

    image4

  6. Press the Close push when the packages finish downloading.

    image5

  7. Verify that ming32-base-bin installed.

    image6

  8. Y’all tin now close the installer window.

two.2: Download Netwide Assembler (NASM)

We volition utilise the Netwide Assembler (NASM) for this class. You tin can read more than information about NSAM from https://en.wikipedia.org/wiki/Netwide_Assembler.

  1. Find the installer on NASM’due south site or download the Windows 10 x64 version from this site directly.

  2. Execute the installer as an administrator

    Annotation

    You will need to execute the installer as Administrator if your logged in user cannot write to C:\MinGW\bin .

    image7

  3. Install to C:\MinGW\bin

    Annotation

    It is easiest to fix upwardly if you install information technology to the same directory as the GCC compiler. Otherwise, y’all have to add the systems paths for both applications.

    image8

Part 3: Set the path to the assembler

Windows needs to know where to find gcc.exe and nasm.exe, which it will do past setting the path=C:\MinGW\bin;%path%

Starting time, we’ll verify that Windows recognizes gcc and nasm using the command line. Then, nosotros’ll set the path every bit role of the system path.

Verify the programs execute in CMD

Note

This path is set Simply for this CMD instance. You have to run the command once again when yous close the CMD window. Or, yous can specify the absolute path to the file.

You lot can add information technology permanently the Arrangement Environs Variables.

  1. Open up Command Prompt (CMD)

  2. Set the temporary path by executing: path=C:\MinGW\bin;%path%

  3. Verify the path prepare correctly

  4. Type: repeat %path%

    image9

  5. Type: gcc --version Verify that it displays the file version.

    image10

  6. Type: nasm --version Verify that information technology displays the file version.

    image11

Errors

If you lot get a not recognized error, then the path is not gear up correctly or you installed MinGW or NASM in a dissimilar directory.

image12

  1. Attempt executing information technology using the full path: C:\MinGW\bin\gcc --version

  2. Verify the installation path: dir C:\MinGW\bin

Set path in Windows System

Tip

  • Set up the path to your assembler and compiler in the Windows path then that all applications can find it.

  • Otherwise, yous have to specify the total path to the applications.

  1. Open up the Advanced System Properties in Windows. There are several ways:

    1. Re-create and paste i of these commands to Windows Explorer or Outset Card

      • Advanced System Settings
        -OR-

      • C:\Windows\System32\SystemPropertiesAdvanced.exe

    2. Navigate from the command panel: Control Panel > System and Security > System

      image21

  2. Click on the Environment Variables button

    image22

  3. Select Path under User variables and then click on the Edit button

    image23

  4. Click on New and then add a variable for the bin binder of NASM and GCC: C:\MinGW\bin

    Note

    Y’all must add both paths if you installed NASM in a different folder.

    image24

  5. Printing OK on all windows

  6. Close and reopen the CMD windows to get a new prompt.

  7. Verify that the NASM and GCC display the versions correctly before continuing.

    image25

Chenxiao Ma | December 27, 2016

I was trying to build a compiler
as a course project in a Compiler Technology course.
I decided to use x86 as my destination code architecture.
However there are 2 more steps to take before the x86 code can be executed.
Here is a what I have tried and I hope it will help you.

The assembly code has to be «assembled» first, with a program called assembler.
The assembler will produce a program called object file. Each source assembly
file will be assembled to an object file.
All the object files are then «linked» by a program called linker.
lld might be used on macOS and mingw is used on Windows.

There are many assemblers available, including GAS, NASM and MASM.
GAS is used by GNU GCC,
NASM is cross-platform and MASM is exclusive to Windows.
I am using a Mac so I have no choice but to use NASM.
Then because of the requirements of the assignment,
I have to migrate it to Windows too.

First I will talk about how I set up NASM and got Xcode to run
and debug my assembly code.
Then I will talk about how to set up NASM on Windows
and use it to assemble x86 code to object files on Windows.
In the end I will also tell you
how to use mingw to make executable files on Windows.

macOS

First we install NASM with Homebrew

Then go to Build Rules in the Project Settings in Xcode, click the plus button,
and set the rules as below

project-setting

/usr/local/bin/nasm -f macho ${INPUT_FILE_PATH} -o ${SCRIPT_OUTPUT_FILE_0}

Then we write a really simple program.
In test.asm we declare an assembly function,
which simply returns an integer 2017.
In main.cpp we declare the main function, call test
and print out the return value.

; test.asm

global _test

section .text

_test:
    mov dword eax, 2017
    ret
// main.cpp

#include

extern "C" int test();

int main(int, const char**) {
    int out = test();
    std::cout << out;
    return 0;
}

Now we are all set.
If you want to run it, just hit command + R.
If you want to debug it, you can set a breakpoint
and use control + F7 to jump into the assembly function.

Windows

NASM can be downloaded from its official website.
I didn’t use the installer and just used the executable in the zip file.
Move the executable to the same folder as your assembly file
and type the following command into cmd.

cd C:\\Assembly
nasm -f win32 test.asm -o test.o
g++ -c main.cpp
mingw32-g++ test.o main.o
a.exe

Now if you see 2017 printed on the command line, you have succeeded!

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Смонтировать образ iso windows 2008
  • Создать zip средствами windows
  • Steady state для windows 7
  • Как изменить обои на ноутбуке windows 10
  • Вырезать защитник windows 10 навсегда