9.2.1 Creating Macro Procedures

To define a macro procedure without parameters, place the desired statements between the MACRO and ENDM directives:

name MACRO
statements
ENDM

For example, suppose you want a program to beep when it encounters certain errors. A beep macro can be defined as follows:

beep MACRO

mov ah, 2 ;; Select DOS Print Char function

mov dl, 7 ;; Select ASCII 7 (bell)

int 21h ;; Call DOS

ENDM

Summary: Macro comments must start with two semicolons instead of one.

The double semicolons mark the beginning of macro comments. Macro comments appear in a listing file only at the macro's initial definition, not at the point where it is called and expanded. Listings are usually easier to read if the comments aren't always expanded. Regular comments (those with a single semicolon) are listed in macro expansions. Appendix C discusses listing files and shows examples of how macros are expanded in listings.

Once a macro is defined, you can call it anywhere in the program by using the macro's name as a statement. The following example calls the beep macro two times if an error flag has been set.

.IF error ; If error flag is true

beep ; execute macro two times

beep

.ENDIF

The instructions in the macro take the place of the macro call when the program is assembled. This would be the resulting code (from the listing file):

.IF error

0017 80 3E 0000 R 00 * cmp error, 000h

001C 74 0C * je @C0001

beep

001E B4 02 1 mov ah, 2

0020 B2 07 1 mov dl, 7

0022 CD 21 1 int 21h

beep

0024 B4 02 1 mov ah, 2

0026 B2 07 1 mov dl, 7

0028 CD 21 1 int 21h

.ENDIF

002A *@C0001:

Contrast this with the results of defining beep as a procedure using the PROC directive and then calling it using the CALL instruction. The instructions of the procedure occur only once in the executable file, but you would also have the additional overhead of the CALL and RET instructions.

Summary: Macros are usually faster than run-time procedures.

In some cases the same task can be done with either a macro or a procedure. Macros are potentially faster because they have less overhead, but they generate the same code multiple times rather than just once.