Example 1:
The following simple macro is intended to read a character from the 8051 UART, and to return it in A:RECEIVE MACRO UARTIN: JNB RI,UARTIN MOV A,SBUF CLR RI ENDMThis will work only once! If the macro RECEIVE is called multiple times, the label UARTIN will be multiply defined.
This can be solved by simply declaring the symbol UARTIN local.
For this, the LOCAL statement has been introduced. After the keyword
LOCAL, a list of local symbols can be specified, separated by commas.
These symbols will only be valid inside the macro that contains the LOCAL
statement. LOCAL statements may only be placed directly after the MACRO
or REPT statement, preceding the first body line. They may contain any
number of local symbols. The macro body may be preceded by an arbitrary
number of LOCAL statements.
Local symbols must be valid symbols, unique within the macro, and different
from the formal parameters (if any). Keywords cannot be used as local symbol
names. If a local symbol has the same name as a global symbol, the local
scope takes precedance during substitution.
When a macro is expanded, its local symbols are always substituted: the
formal parameters are replaced by the macro arguments, and the local symbols
that have been declared in a LOCAL statement are replaced by unique, global
symbol names, which the assembler generates during every expansion. These
have always the format ??xxxx, where xxxx is a unique symbol number.
Example 2:
After a redesign of our previous macro RECEIVE using local symbols, it is looking as follows:RECEIVE MACRO LOCAL UARTIN UARTIN: JNB RI,UARTIN MOV A,SBUF CLR RI ENDMEnhanced as shown above, the macro will work correctly, as often as desired. When RECEIVE is called for the first time, the local symbol UARTIN will be replaced by ??0000,??0000: JNB RI,??0000 MOV A,SBUF CLR RIwhen it is called for the second time, UARTIN will be replaced by ??0001, and so on:??0001: JNB RI,??0001 MOV A,SBUF CLR RI
However, it is recommended not to define global symbols in the format ??xxxx, to avoid name conflicts with substituted local symbols from expanded macros.