9.2  Defining and Using Macros

9.2 Defining and Using Macros

A macro is defined as follows:

-define(Const, Replacement).
-define(Func(Var1,...,VarN), Replacement).

A macro definition can be placed anywhere among the attributes and function declarations of a module, but the definition must come before any usage of the macro.

If a macro is used in several modules, it is recommended that the macro definition is placed in an include file.

A macro is used as follows:

?Const
?Func(Arg1,...,ArgN)

Macros are expanded during compilation. A simple macro ?Const is replaced with Replacement.

Example:

-define(TIMEOUT, 200).
...
call(Request) ->
    server:call(refserver, Request, ?TIMEOUT).

This is expanded to:

call(Request) ->
    server:call(refserver, Request, 200).

A macro ?Func(Arg1,…,ArgN) is replaced with Replacement, where all occurrences of a variable Var from the macro definition are replaced with the corresponding argument Arg.

Example:

-define(MACRO1(X, Y), {a, X, b, Y}).
...
bar(X) ->
    ?MACRO1(a, b),
    ?MACRO1(X, 123)

This is expanded to:

bar(X) ->
    {a,a,b,b},
    {a,X,b,123}.

It is good programming practice, but not mandatory, to ensure that a macro definition is a valid Erlang syntactic form.

To view the result of macro expansion, a module can be compiled with the 'P' option. compile:file(File, ['P']). This produces a listing of the parsed code after preprocessing and parse transforms, in the file File.P.