A Technique for substituting substrings with parameters in Macros

Flenser

Senior Member
The preprocessor substtitues macro parameters to replace whole words in the body of the macro. It does not substitute the parameter to replace substrings in the body of the macros.

e.g This code does not work:
Code:
#macro LCDconfig(lcdname, i2cSlaveAddress)
SYMBOL i2caddresslcdname = i2cSlaveAddress
#endmacro

LCDconfig(LCD1, $4E)
LCDconfig(LCD1, $4C)

The parameter is not substituted into the SYMBOL name by the preprocessor so the two calls to the macro generate SYMBOL statements with duplicate names and the compiler reports the 2nd, duplicate, SYMBOL name as a syntax error:
Code:
SYMBOL i2caddresslcdname = $4E
SYMBOL i2caddresslcdname = $4C

SYMBOL i2caddresslcdname = $4C
                        ^
Syntax error on line 6 at/before position 24
Error: syntax error

However, by a fortunate coincidence it turns out that the period(.) character is treated as a word seperator by the preprocessor but is treated by the compilers as a valid charater in both SYMBOL and LABEL name.

It is valid syntax to have a period character in your SYMBOL and LABEL name.
e.g. When I want to work with the high & low bytes of a word variable I will define my variable names like this:
Code:
SYMBOL mywordvariable     = W0
SYMBOL mywordvariable.MSB = B1
SYMBOL mywordvariable.LSB = B0

So this code using a period charater in the SYMBOL name works to replace the substring "lcdname" with the value of that parameter:
Code:
#macro LCDconfig(lcdname, i2cSlaveAddress)
SYMBOL i2caddress.lcdname = i2cSlaveAddress
#endmacro

LCDconfig(LCD1, $4E)
LCDconfig(LCD2, $4C)

and the two calls to the macro generate these two SYMBOL statements with unique names:
Code:
SYMBOL i2caddress.LCD1 = $4E
SYMBOL i2caddress.LCD2 = $4C

With a period character used in the string the preprocessor substring replacement works for a substring at the start of, in the middle of, or at the end of the string.

As the substring substitution is done by the preprocessor, it works for both SYMBOL & LABEL names.

I tested this feature using the preprocessor Version 1.0.5 that is included with PE6 and using a period in the SYMBOL names is accepted by all the v3.4 compilers that are included with PE6 .

Using a period in the SYMBOL names is also accepted by all the by all the v4 compilers that were released later, although these are no longer listed on the picaxe.com site.

For examples of this technique being used in the names of constant and variable SYMBOLs, the names of LABELs, and in the GOTO and GOSUB statements that reference those LABELs, see the MACRO LCD_begin() in the include file for this library: LCD LIbrary LCD_LIB-PCF8574-I2C-Multi

DISCLAIMER: This technique relies on an undocumented feature of the preprocessor so this behaviour could change in a future version and you make use of this technique at your own risk.
 
Back
Top