预处理,IFDEF

时间:2013-01-22 04:17:27

标签: erlang

当调试gen_server模块时,我想记录更多详细信息状态。

init()->
    put(?COMPLETED_COMMANDS,[]),
-ifdef(DEBUG).
    put(?DETAIL_STATUS,[]),
-endif.
    ok.

编译器出现以下错误。

src/benvolio_command_cache.erl:34: syntax error before: ','
src/benvolio_command_cache.erl:36: syntax error before: '.'
src/benvolio_command_cache.erl:33: variable 'DEBUG' is unbound
src/benvolio_command_cache.erl:33: function ifdef/1 undefined

如何在*.erl文件的功能中添加debuging代码行?

2 个答案:

答案 0 :(得分:5)

宏指令不能在函数内部使用。见8.5 Flow Control in Macros

答案 1 :(得分:0)

根据9. Preprocessor中的Erlang Reference Manual User's Guide (Version 11.1)章(2020年9月22日),

  • 不能在函数中定义;尽管在9.2 Defining and Using Macros中间接指出:

    宏定义可以放在模块的属性和函数声明中的任何位置,但是定义必须先于宏使用。

  • 宏指令不能在函数内部使用(请参见9.5 Flow Control in Macros


关于您要实现的目标,9.5 Flow Control in Macros中有一个示例可以回答您的问题:

示例:

-module(m).
...

-ifdef(debug).
-define(LOG(X), io:format("{~p,~p}: ~p~n", [?MODULE,?LINE,X])).
-else.
-define(LOG(X), true).
-endif.

...

当需要跟踪输出时,将在模块时定义debug m已编译:

% erlc -Ddebug m.erl

1> c(m, {d, debug}).
{ok,m}
然后将

?LOG(Arg)扩展为对io:format/2的调用并提供 为用户提供一些简单的跟踪输出。

为此,在没有debug宏的情况下编译模块时,?LOG(Arg)将扩展为true


请参见compile optionscompile:file/2c/\[2,3\]erlc的命令行标志。