Macros

Macros are a way of extending the assembler. Macros are effectively extra commands or instructions. Used sparingly they can really enhance you code. As an example, inside the Astrum editor is some code that takes a keypress and decides what to do with it. It uses a list of keys and labels:

     defb 8
     defw LEFT
     defb 9
     defw RIGHT
     defb 11
     defw UP
It would be nicer if each keypress and label were on one line. We can do this with a macro:
     MACRO KEY_HANDLER key,label
     defb key
     defw label
     ENDM
Now we can write:
     KEY_HANDLER 8,LEFT
     KEY_HANDLER 9,RIGHT
     KEY_HANDLER 11,UP

Macros can call other macros but they must have been declared previously.

You can declare and use labels inside a macro but you cannot reference them from outside a macro. In general you cannot declare a label more than once but labels used in a macro are hidden so you do not have to worry about choosing unique label names from one macro to another.

You could do:

       MACRO VDUN ch,n
       ld b,n
loop   ld a,ch
       rst 16
       djnz loop
       ENDM

Of course just because you can do something doesn't mean you should! If a macro is more than a few lines long it might be worth considering its worth.

Do not choose macro names that would be recognised as something else and do not use argument names that could be confused with a register name. You can't use a macro to modify an existing instruction or directive.