Jump to content

Erlang Programming/Macros

From Wikibooks, open books for an open world

Macros

[edit | edit source]

Macros are a tool to perform text transformation in the source code before it is compiled. In Erlang, a macro is defined as this:

-define(LIKERT_SCALE, lists:seq(1, 5)). 

Usually macros are written in all caps, to differentiate them from ordinary variables.

In order to use the macro, it is necessary to prepend a question mark to its name:

A = ?LIKERT_SCALE.

The code makes A = [1,2,3,4,5].

Some handy predefined macros include:

 ?MODULE  (module name)
 ?LINE    (line number)
 ?FILE    (filename as a string)
 % ===========================================
 % Example code
 % ===========================================
 -module(test_macros).
 -define(LIKERT_SCALE, lists:seq(1, 5)).
 -compile(export_all).
 
 start() ->
   io:format("likert scale:  ~w \n", [?LIKERT_SCALE]),
   io:format("module name:   ~w \n", [?MODULE]),
   io:format("line number:   ~w \n", [?LINE]),
   io:format("filename:      ~s \n", [?FILE]),
   ok.
 % ===========================================
 % Example output
 % ===========================================
 %
 % 6> c(test_macros).
 % {ok,test_macros}
 % 7> test_macros:start().
 % likert scale:  [1,2,3,4,5] 
 % module name:   test_macros 
 % line number:   10 
 % filename:      ./test_macros.erl
 % ok

Besides defining macros with -define, it is possible to conditionally compile code, depending on macro values. For this, one uses -idfdef, -ifndef, -else, -endif.

 -define(IMPORTANT_MACRO).
 
 -ifdef(?IMPORTANT_MACRO).
 f() -> "It is defined!"
 -else.
 f() -> "I do not see it defined anywhere!"
 -endif.

In this example, the first version of f() will be compiled.