Macros and module attributes
A macro is a piece of source with a name, replaced by the compiler before it reads the code. An attribute is a line that tells the compiler something about the module. Both are text-level tools of Erlang: the runtime never sees a macro, and an attribute becomes part of the module only where the compiler chooses to store it. This lesson writes one of each and shows the parenthesis mistake that every macro author meets.
Define a macro
-define(Name, Value) defines a macro, and ?Name uses it. The compiler replaces the use with the value before it parses the expression, which is why a macro can hold a constant, a pattern or a whole clause. -undef(Name) removes one. This module defines a constant and uses the built-in macros the compiler provides:
macros.erl
-module(macros). -export([main/0]). -vsn("1.2.3"). -author("Ada"). -define(MAX, 10). -define(SQUARE(X), ((X) * (X))). -define(BAD_DOUBLE(X), X + X). main() -> io:format("max: ~p~n", [?MAX]), io:format("square: ~p~n", [?SQUARE(5)]), io:format("module: ~p~n", [?MODULE]), io:format("vsn: ~p~n", [proplists:get_value(vsn, ?MODULE:module_info(attributes))]), io:format("good: ~p~n", [?SQUARE(1 + 2)]), io:format("bad: ~p~n", [?BAD_DOUBLE(2) * 3]).
erlc macros.erl
erl -noshell -eval 'macros:main(), halt().'
max: 10 square: 25 module: macros vsn: "1.2.3" good: 9 bad: 8
?MODULE is the module name as an atom and ?MODULE_STRING the same name as a string; the compiler also provides ?LINE and ?FILE. The two attributes -vsn and -author are stored in the module's attribute list, which module_info(attributes) returns as a property list.
A macro with arguments
?SQUARE(1 + 2) is 9 because the definition wraps the argument
in parentheses: ((X) * (X)) becomes
((1 + 2) * (1 + 2)). The macro
?BAD_DOUBLE(X) has no parentheses, so
?BAD_DOUBLE(2) * 3 expands to
2 + 2 * 3 and prints 8 instead of 12. That is the rule for a
macro author:
wrap every use of an argument in parentheses, and wrap the whole body in parentheses as
well. A macro is text substitution, not a function call, and the operator around the use
binds to whatever the body leaves uncovered.
Compile-time switches
-ifdef(Name), -ifndef(Name), -else and -endif include a part of the source only when a macro is defined. erlc -DDEBUG defines DEBUG for the build, so one source has a debug build and a release build. This module logs only in the debug build:
debug.erl
-module(debug). -export([main/0]). -ifdef(DEBUG). -define(LOG(Value), io:format("debug: ~p~n", [Value])). -else. -define(LOG(Value), ok). -endif. main() -> ?LOG(1), io:format("done~n").
erlc debug.erl
erl -noshell -eval 'debug:main(), halt().'
done
The same source built with the flag prints the log line first:
erlc -DDEBUG debug.erl
erl -noshell -eval 'debug:main(), halt().'
debug: 1 done
The branch is chosen when the file compiles; the macro is a piece of text either way. -ifdef is also how a header guards itself against a second inclusion, with the name of the header as the macro: -ifndef(PERSON_HRL). and -define(PERSON_HRL, true). around the content.
Include a header
A header file holds the macros and the records two modules share. -include("defs.hrl") reads the file from the folder of the module and inserts it at that point, so both modules see the same definition. The file defs.hrl here defines one macro and one record:
defs.hrl
-define(APP, demo). -record(point, {x = 0, y = 0}).
include.erl
-module(include). -export([main/0]). -include("defs.hrl"). main() -> io:format("app: ~p~n", [?APP]), io:format("x: ~p~n", [(#point{x = 2})#point.x]).
erlc include.erl
erl -noshell -eval 'include:main(), halt().'
app: demo x: 2
-include_lib("app/include/file.hrl") searches an installed OTP application instead of the module's folder, and it is the form a library header takes. The Alpine OTP package this course runs on has no include folders, which the records in depth lesson explains, so the page uses a header of its own.
Module attributes
An attribute starts with a dash at column one and ends with a full stop. Some are read by the compiler and stored:
- -module(Name) names the module and must match the file.
- -export([f/1]) and -import(Module, [f/1]) open and borrow functions.
- -behaviour(gen_server) asks the compiler to warn when a callback of the behaviour is missing; the GenServer lesson uses it.
- -record, -define and -include are the compile-time forms of this lesson.
- -vsn, -author and -doc carry metadata: -vsn and -author are attributes a program can read, -doc is read by edoc and by the shell's h/1.
- -compile(...) passes an option to the compiler, and -on_load(f/0) names a function to run when the module loads.
-vsn and -author answer the property list the program printed at the top of this page, and module_info(exports) lists the export table. The documentation and edoc lesson turns the doc attributes into HTML, and Typespecs adds -spec and -type to the same list.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does the compiler do with a macro?
Answer
Replaces the use with its text before parsing
A macro is text substitution at compile time; the runtime never sees it.
-
What does this module print?
-module(q4). -export([main/0]). -vsn("9.9"). main() -> io:format("~p~n", [proplists:get_value(vsn, ?MODULE:module_info(attributes))]).Answer
"9.9"-vsnis stored in the attribute list, and the property is the string"9.9". -
Why does
-define(SQUARE(X), ((X) * (X)))wrap the argument?Answer
Without the parentheses an operator around the use would bind inside
A macro is text, so
?SQUARE(1 + 2)would become1 + 2 * 1 + 2without the parentheses. -
What does
erlc -DDEBUG debug.erldo?Answer
Defines the macro
DEBUGfor the buildThe
-Dflag defines a macro, so every-ifdef(DEBUG)branch is compiled in. -
Which attribute makes another module callable without its name?
Answer
-import-import(Module, [f/1])lets the module callf(...)without the remote prefix. -
What does
module_info(attributes)return?Answer
A property list of the stored attributes, such as
vsnandauthorThe attribute list is stored in the beam and read back as a property list.
-
What does
-include("defs.hrl")do?Answer
Inserts the header file at that point at compile time
The include is a compile-time text insertion, so every module that includes it shares the definitions.
-
What does this module print?
-module(q1). -export([main/0]). -define(MAX, 10). -define(SQUARE(X), ((X) * (X))). main() -> io:format("~p~n", [?SQUARE(?MAX)]).Answer
100The inner macro becomes 10 and the outer one squares it, so the answer is 100.
-
What does this module print?
-module(q2). -export([main/0]). -define(BAD_DOUBLE(X), X + X). main() -> io:format("~p~n", [?BAD_DOUBLE(2) * 3]).Answer
8The macro expands to
2 + 2 * 3, and multiplication runs first, so the value is 8. -
What does this module print?
-module(q3). -export([main/0]). -ifdef(DEBUG). -define(TAG, debug). -else. -define(TAG, release). -endif. main() -> io:format("~p~n", [?TAG]).Answer
releaseThe build defines no
DEBUG, so the-elsebranch suppliesrelease.
The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Автор статьи: Arthur Isaev