w1coding.comAll tutorials

Assembly Macros

Assembly lessons
  1. Environment Setup
  2. Introduction
  3. Syntax
  4. Datamovement
  5. Operators
  6. Control
  7. Loops
  8. Interupts
  9. Functions
  10. Memory
  11. System
  12. Debugging
  13. Macros
  14. Execution
  15. Floating
  16. Interupts
  17. Optimization
  18. Linking
  19. Inline
  20. Registers
  21. Bootloader
  22. Macros
  23. Stack
  24. Call
  25. Technique
  26. Responsive

Macros in Assembly

Macros are reusable blocks of code that are substituted during assembly. They simplify repetitive tasks and improve code readability.

Defining a Macro

Macros are defined using the %macro directive, and invoked like regular instructions.

Syntax

%macro macro_name num_params
    ; Macro body
%endmacro
    

Example: Simple Macro

This macro writes a string to the screen using a system call.

%macro write_string 2
    mov rax, 1          ; System call: write
    mov rdi, 1          ; File descriptor: stdout
    mov rsi, %1         ; String address
    mov rdx, %2         ; String length
    syscall
%endmacro

section .data
    msg db 'Hello, Macro!', 0xA
    len equ $ - msg

section .text
    global _start

_start:
    write_string msg, len  ; Call the macro
    mov rax, 60            ; System call: exit
    xor rdi, rdi           ; Exit code: 0
    syscall
    

Example: Reusable Arithmetic Macro

This macro adds two numbers and stores the result in a register.

%macro add_two_numbers 3
    mov %1, %2      ; Move the first number to the target register
    add %1, %3      ; Add the second number
%endmacro

section .text
    global _start

_start:
    add_two_numbers rax, 5, 10 ; Adds 5 and 10, stores the result in rax
    mov rax, 60                ; System call: exit
    xor rdi, rdi               ; Exit code: 0
    syscall
    

Benefits of Macros

  • Reduces code duplication.
  • Improves readability.
  • Makes code easier to maintain.