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

Using Macros in Assembly

Macros in assembly are a powerful way to reuse code without manually duplicating it. They allow you to define common patterns or sequences of instructions that can be inserted wherever needed in the code.

Basic Macro Syntax

In assembly, macros are defined with the %macro directive and invoked with the % symbol:

%macro print_message 2
    mov eax, 4            ; sys_write
    mov ebx, 1            ; file descriptor (stdout)
    mov ecx, %1           ; message
    mov edx, %2           ; length
    int 0x80              ; make the system call
%endmacro
    

Example Usage of Macro

This example uses a macro to print messages:

section .data
    msg1 db 'Hello, world!', 0xA
    msg1_len equ $ - msg1

section .text
    global _start

_start:
    print_message msg1, msg1_len  ; Use the print_message macro
    ; Exit system call
    mov eax, 1            ; sys_exit
    xor ebx, ebx          ; Return code 0
    int 0x80
    

Advantages of Using Macros

  • Code Reusability: Macros help to avoid code duplication.
  • Readability: Complex code sequences can be abstracted into simpler, more readable macro calls.
  • Performance: Macros are expanded at compile-time, meaning no runtime overhead.

Key Notes

  • Macros are expanded by the assembler at the point of use, so they don’t incur runtime performance costs.
  • While macros help with code reusability, overusing them can lead to less readable code.