Macros are expanded during compilation. A simple macro ?Const will be replaced with Replacement.
This snippet defines a macro called DEBUG that is replaced with a call to print a string if debug is set at compile time. The macro is then used in the following code thus:
?DEBUG("Creating ~p for N = ~p~n", [First, N]),
This statement is expanded and replaced with the appropriate contents if debug is set. Therefore you get to see debug messages only if debug is set.
A question mark means to try and expand what follows as a macro call. There is nothing prohibiting using the macro name (atom or variable) as a normal atom or variable. So in [the above] example you could use DEBUG as a normal variable just as long as you don't prefix it with ?. Confusing, most definitely, but not illegal.
Erlang macros are really similar to C's '#define' statements, mainly used to define short functions and constants. They are simple expressions represented by text that will be replaced before the code is compiled for the VM. Such macros are mainly useful to avoid having magic values floating around your modules. A macro is defined as a module attribute of the form: -define(MACRO, some_value). and is used as ?MACRO inside any function defined in the module. A 'function' macro could be written as -define(sub(X,Y), X-Y). and used like ?sub(23,47), later replaced by 23-47 by the compiler. Some people will use more complex macros, but the basic syntax stays the same.
发布评论
评论(3)
Erlang 使用问号来标识宏。例如,考虑下面的代码:
正如文档所说,
此代码段定义了一个名为
DEBUG
的宏,如果在编译时设置了debug
,则该宏将替换为打印字符串的调用。然后在以下代码中使用该宏:如果设置了
debug
,则该语句将被扩展并替换为适当的内容。因此,仅当设置了debug
时,您才能看到调试消息。更新
感谢@rvirding:
Erlang uses question mark to identify macros. For e.g. consider the below code:
As the documentation says,
This snippet defines a macro called
DEBUG
that is replaced with a call to print a string ifdebug
is set at compile time. The macro is then used in the following code thus:This statement is expanded and replaced with the appropriate contents if
debug
is set. Therefore you get to see debug messages only ifdebug
is set.Update
Thanks to @rvirding:
根据本文档,我相信这是引用宏的语法。
来自学习一些 Erlang:
Based on this documentation, I believe it's the syntax for referring to a macro.
And from Learn You Some Erlang:
?表示宏。
Erlang 也有预定义的宏。示例:?模块。您可以在 https://www.erlang.org 中找到完整列表/doc/reference_manual/macros.html#predefined-macros
? indicates Macros.
Erlang has predefined macros as well. Example: ?MODULE. You can find the complete list in https://www.erlang.org/doc/reference_manual/macros.html#predefined-macros