2.3 Macros

Macros are very much like symbols in their syntax, the difference is that macros have a value whereas a symbol simply is defined or is not defined. If you want macro support, you need to specify the -Sm command-line switch, otherwise your macro will be regarded as a symbol.

Defining a macro in your program is done in the same way as defining a symbol; in a {$define} preprocessor statement2:

 {$define ident:=expr}
If the compiler encounters ident in the rest of the source file, it will be replaced immediately by expr. This replacement works recursive, meaning that when the compiler expanded one of your macros, it will look at the resulting expression again to see if another replacement can be made. You need to be careful with this, because an infinite loop can occur in this manner.

Here are two examples which illustrate the use of macros:

 {$define sum:=a:=a+b;}
 ...
 sum          { will be expanded to 'a:=a+b;'
                remark the absence of the semicolon}
 ...
 {$define b:=100}
 sum          { Will be expanded recursively to a:=a+100; }
 ...
The previous example could go wrong:
 {$define sum:=a:=a+b;}
 ...
 sum          { will be expanded to 'a:=a+b;'
                remark the absence of the semicolon}
 ...
 {$define b=sum} { DON'T do this !!!}
 sum          { Will be infinitely recursively expanded \dots }
 ...
On my system, the last example results in a heap error, causing the compiler to exit with a run-time error 203.

Remark:Macros defined in the interface part of a unit are not available outside that unit! They can just be used as a notational convenience, or in conditional compiles. By default the compiler predefines three macros, containing the version number, the release number and the patch number. They are listed in table (2.1).



Table 2.1: Predefined macros


Symbol Contains


FPC_VERSION The version number of the compiler.
FPC_RELEASE The release number of the compiler.
FPC_PATCH The patch number of the compiler.



Remark:Don’t forget that macros support isn’t on by default. You need to compile with the -Sm command-line switch.