9.2 Defining and Using Macros

A macro is defined as follows:

  1. -define(Const, Replacement).
  2. -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:

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

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


  1. -define(TIMEOUT, 200).
  2. ...
  3. call(Request) ->
  4. server:call(refserver, Request, ?TIMEOUT).

This is expanded to:

  1. call(Request) ->
  2. 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.


  1. -define(MACRO1(X, Y), {a, X, b, Y}).
  2. ...
  3. bar(X) ->
  4. ?MACRO1(a, b),
  5. ?MACRO1(X, 123)

This is expanded to:

  1. bar(X) ->
  2. {a,a,b,b},
  3. {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.