Defining Macros

A macro definition is one or more assembly statements that define:

To define a macro, use the .macro directive.

Note: If you use a local label in a macro, the scope of the label is limited to the expansion of the macro. (Local labels begin with the @ character.)

The .macro directive is part of the first line of a macro definition. Every macro definition ends with the .endm directive. The following listing shows the full syntax.

Listing: Macro Definition Syntax: .macro Directive
name: .macro [ parameter ] [ ,parameter ] ... 
macro_body 
.endm 

The following table explains the syntax elements.

Table 1. Syntax Elements: .macro Directive
Element Description
name Label that invokes the macro.
parameter Operand the assembler passes to the macro for us in the macro body.
macro_body One or more assembly language statements. Invoking the macro tell the assembler to substitutes these statements.

The body of a simple macro consists of just one or two statements for the assembler to execute. Then, in response to the .endm directive, the assembler resumes program execution at the statement immediately after the macro call.

But not all macros are so simple. For example, a macro can contain a conditional assembly block, The conditional test could lead to the .mexit directive stopping execution early, before it reaches the .endm directive.

The following listing shows the definition of macro addto, which includes a .mexit directive.

Listing: Conditional Macro Definition
//define a macro 
addto .macro dest,val 
 .if val==0 
no-op 
.mexit // execution goes to the statement 
 // immediately after the .endm directive 
.elseif val==1 
// use compact instruction 
add #1, dest 
.mexit // execution goes to the statement 
 // immediately after the .endm directive 
.endif 
// if val is not equal to either 0 or 1, 
// add dest and val 
add val, dest 
// end macro definition 
.endm 

The following listing shows the assembly-language code that calls the addto macro.

Listing: Assembly Code that Calls addto Macro
// specify an executable code section 
.text 
xor d0,d0 
// call the addto macro 
addto d0,0 
addto d0,1 
addto d0,2 
addto d0,3 

The following listing shows the expanded addto macro calls.

Listing: Expanded addto Macro Calls
xor d0,d0 
nop 
add d0 
add d0,2 
add d0,3