【问题标题】:how to define and use a compile time macro?如何定义和使用编译时宏?
【发布时间】:2015-10-23 05:19:41
【问题描述】:

我正在尝试了解有关编译设置宏的更多信息。

Erlang compile 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.

但总是输出“错误...”。

我哪里出错了?

【问题讨论】:

    标签: erlang


    【解决方案1】:

    您可以使用-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 表达式中收到关于永远无法匹配的子句的编译器警告。

    【讨论】:

    • 似乎无法将宏定义为-compile() 指令的一部分。
    • 不知道为什么要用-compile 定义一个,而使用-define 可以更清晰、更灵活地定义一个?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    相关资源
    最近更新 更多