III.11.4 Local Symbols
Local symbols are symbols, which are only known within a macro body, but not outside the macro. Symbols that are defined for the whole program, will subsequently be called "global symbols" for better understanding. We are already familiar with a special case of local symbols: formal macro parameters. They appear in the macro definition only. Since they are substituted during macro expansion, we don't have further problems with them. But what happens with symbols that are defined in a macro body?
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.
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.