如何定义和使用编译时宏?
how to define and use a compile time macro?
我正在尝试了解有关编译设置宏的更多信息。
Erlangcompile documentation表明可以定义一个宏:
{d,Macro} {d,Macro,Value}
Defines a macro Macro to have the value Value.
Macro is of type atom, and Value can be any term.
The default Value is true.
我正在尝试使用指令设置宏:
-module(my_mod).
-compile([debug_info, {d, debug_level, 1}]).
...
如何在我的代码中使用这个宏?例如我试过这个:
my_func() ->
if
debug_level == 1 -> io:format("Warning ...");
true -> io:format("Error ...")
end.
但总是输出'Error ...'。
我哪里错了?
您可以使用 -define
:
在代码中设置宏
-define(debug_level, 1).
如果你想从编译命令行覆盖它,你可以用-ifndef
:
包裹它
-ifndef(debug_level).
-define(debug_level, 1).
-endif.
这样,如果你用
编译
erlc -Ddebug_level=2 file.erl
例如,宏将具有值 2 而不是默认值 1。
要访问宏的值,请在其前面加上 ?
:
my_func() ->
if
?debug_level == 1 -> io:format("Warning ...");
true -> io:format("Error ...")
end.
请注意,由于 ?debug_level
是一个常量,您将从 if
表达式中获得有关永远无法匹配的子句的编译器警告。
我正在尝试了解有关编译设置宏的更多信息。
Erlangcompile documentation表明可以定义一个宏:
{d,Macro} {d,Macro,Value}
Defines a macro Macro to have the value Value. Macro is of type atom, and Value can be any term. The default Value is true.
我正在尝试使用指令设置宏:
-module(my_mod).
-compile([debug_info, {d, debug_level, 1}]).
...
如何在我的代码中使用这个宏?例如我试过这个:
my_func() ->
if
debug_level == 1 -> io:format("Warning ...");
true -> io:format("Error ...")
end.
但总是输出'Error ...'。
我哪里错了?
您可以使用 -define
:
-define(debug_level, 1).
如果你想从编译命令行覆盖它,你可以用-ifndef
:
-ifndef(debug_level).
-define(debug_level, 1).
-endif.
这样,如果你用
编译erlc -Ddebug_level=2 file.erl
例如,宏将具有值 2 而不是默认值 1。
要访问宏的值,请在其前面加上 ?
:
my_func() ->
if
?debug_level == 1 -> io:format("Warning ...");
true -> io:format("Error ...")
end.
请注意,由于 ?debug_level
是一个常量,您将从 if
表达式中获得有关永远无法匹配的子句的编译器警告。