目录

Erlang - 宏( Macros)

宏通常用于内联代码替换。 在Erlang中,宏通过以下语句定义。

  • -define(Constant, Replacement).
  • -define(Func(Var1, Var2,.., Var), Replacement).

以下是使用第一种语法的宏示例 -

例子 (Example)

-module(helloworld). 
-export([start/0]). 
-define(a,1). 
start() -> 
   io:fwrite("~w",[?a]).

从上面的程序中你可以看到使用'?'扩展宏 符号。 常量由宏中定义的值替换。

上述计划的输出将是 -

输出 (Output)

1

使用函数类的宏的示例如下 -

例子 (Example)

-module(helloworld). 
-export([start/0]). 
-define(macro1(X,Y),{X+Y}). 
start() ->
   io:fwrite("~w",[?macro1(1,2)]).

上述计划的输出将是 -

输出 (Output)

{3}

以下附加语句可用于宏 -

  • undef(Macro) - 取消定义宏; 在此之后你无法调用宏。

  • ifdef(Macro) - 仅在定义了宏时才评估以下行。

  • ifndef(Macro) - 仅当未定义宏时才评估以下行。

  • else - 在ifdef或ifndef语句之后允许。 如果条件为false,则评估其他语句。

  • endif - 标记ifdef或ifndef语句的结尾。

使用上述语句时,应以正确的方式使用它,如以下程序所示。

-ifdef(<FlagName>).
-define(...).
-else.
-define(...).
-endif.
↑回到顶部↑
WIKI教程 @2018