Preprocessor
View SourceFile Inclusion
A file can be included as follows:
-include(File).-include_lib(File).File, a string, is to point out a file. The contents of this file are includedas is, at the position of the directive.
Include files are typically used for record and macro definitions that areshared by several modules. It is recommended to use the file name extension.hrl for include files.
File can start with a path component$VAR, for some stringVAR. If that isthe case, the value of the environment variableVAR as returned byos:getenv(VAR) is substituted for$VAR. Ifos:getenv(VAR) returnsfalse,$VAR is left as is.
If the filenameFile is absolute (possibly after variable substitution), theinclude file with that name is included. Otherwise, the specified file issearched for in the following directories, and in this order:
- The current working directory
- The directory where the module is being compiled
- The directories given by the
includeoption
For details, seeerlc in ERTS andcompile in Compiler.
Examples:
-include("my_records.hrl").-include("incdir/my_records.hrl").-include("/home/user/proj/my_records.hrl").-include("$PROJ_ROOT/my_records.hrl").include_lib is similar toinclude, but is not to point out an absolute file.Instead, the first path component (possibly after variable substitution) isassumed to be the name of an application.
Example:
-include_lib("kernel/include/file.hrl").The code server usescode:lib_dir(kernel) to find the directory of the current(latest) version of Kernel, and then the subdirectoryinclude is searched forthe filefile.hrl.
Defining and Using Macros
A macro is defined as follows:
-define(Const,Replacement).-define(Func(Var1,...,VarN),Replacement).A macro definition can be placed anywhere among the attributes and functiondeclarations of a module, but the definition must come before any usage of themacro.
If a macro is used in several modules, it is recommended that the macrodefinition is placed in an include file.
A macro is used as follows:
?Const?Func(Arg1,...,ArgN)Macros are expanded during compilation. A simple macro?Const is replaced withReplacement.
Example:
-define(TIMEOUT,200)....call(Request)->server:call(refserver,Request,?TIMEOUT).This is expanded to:
call(Request)->server:call(refserver,Request,200).A macro?Func(Arg1,...,ArgN) is replaced withReplacement, where alloccurrences of a variableVar from the macro definition are replaced with thecorresponding argumentArg.
Example:
-define(MACRO1(X,Y),{a,X,b,Y})....bar(X)->?MACRO1(a,b),?MACRO1(X,123)This is expanded to:
bar(X)->{a,a,b,b},{a,X,b,123}.It is good programming practice, but not mandatory, to ensure that a macrodefinition is a valid Erlang syntactic form.
To view the result of macro expansion, a module can be compiled with the'P'option.compile:file(File, ['P']). This produces a listing of the parsed codeafter preprocessing and parse transforms, in the fileFile.P.
Predefined Macros
The following macros are predefined:
?MODULE- The name of the current module, as an atom.?MODULE_STRING- The name of the current module, as a string.?FILE- The file name of the current module, as a string.?LINE- The current line number, as an integer.?MACHINE- The machine name,'BEAM'.?FUNCTION_NAME- The name of the current function, as an atom.?FUNCTION_ARITY- The arity (number of arguments) for the currentfunction, as an integer.?OTP_RELEASE- The OTP release for the runtime system that isrunning the compiler, as an integer. For example, when compiling usingErlang/OTP 27, the macro returns27.Note
To find out the release at run-time, call
erlang:system_info(otp_release). Notethat it returns the release as a string. For example, when therelease is Erlang/OTP 27, the string"27"will be returned.Change
The
?OTP_RELEASEmacro was introduced in Erlang/OTP 21.?FEATURE_AVAILABLE(Feature)- Expands totrueif thefeatureFeatureis available. The featuremight or might not be enabled.Change
The
?FEATURE_AVAILABLE()macro was introduced in Erlang/OTP 25.?FEATURE_ENABLED(Feature)- Expands totrueif thefeatureFeatureis enabled.Change
The
?FEATURE_ENABLED()macro was introduced in Erlang/OTP 25.
Macros Overloading
It is possible to overload macros, except for predefined macros. An overloadedmacro has more than one definition, each with a different number of arguments.
Change
Support for overloading of macros was added in Erlang 5.7.5/OTP R13B04.
A macro?Func(Arg1,...,ArgN) with a (possibly empty) list of arguments resultsin an error message if there is at least one definition ofFunc witharguments, but none with N arguments.
Assuming these definitions:
-define(F0(),c).-define(F1(A),A).-define(C,m:f).the following does not work:
f0()->?F0.% No, an empty list of arguments expected.f1(A)->?F1(A,A).% No, exactly one argument expected.On the other hand,
f() -> ?C().is expanded to
f()->m:f().Removing a macro definition
A definition of macro can be removed as follows:
-undef(Macro).Conditional Compilation
The following macro directives support conditional compilation:
-ifdef(Macro).- Evaluate the following lines only ifMacroisdefined.-ifndef(Macro).- Evaluate the following lines only ifMacrois notdefined.-else.- Only allowed after theifdef,ifndef,if, andelifdirectives. The lines followingelseare evaluated if the precedingdirective evaluated to false.-if(Condition).- Evaluates the following lines only ifConditionevaluates to true.-elif(Condition).- Only allowed after anifor anotherelifdirective. If the precedingiforelifdirective does not evaluate totrue, and theConditionevaluates to true, the lines following theelifare evaluated instead.-endif.- Specifies the end of a series of control flow directives.
Note
Macro directives cannot be used inside functions.
Syntactically, theCondition inif andelif must be aguard expression. Other constructs (such asacase expression) result in a compilation error.
As opposed to the standard guard expressions, an expression in anif andelif also supports calling the psuedo-functiondefined(Name), which testswhether theName argument is the name of a previously defined macro.defined(Name) evaluates totrue if the macro is defined andfalseotherwise. An attempt to call other functions results in a compilation error.
Example:
-module(m)....-ifdef(debug).-define(LOG(X),io:format("{~p,~p}:~p~n",[?MODULE,?LINE,X])).-else.-define(LOG(X),true).-endif....When trace output is desired,debug is to be defined when the modulem iscompiled:
% erlc -Ddebug m.erlor1>c(m,{d,debug}).{ok,m}?LOG(Arg) is then expanded to a call toio:format/2 and provide the userwith some simple trace output.
Example:
-module(m)...-if(?OTP_RELEASE>=25).%% Code that will work in OTP 25 or higher-elif(?OTP_RELEASE>=26).%% Code that will work in OTP 26 or higher-else.%% Code that will work in OTP 24 or lower.-endif....This code uses theOTP_RELEASE macro to conditionally select code depending onrelease.
Example:
-module(m)...-if(?OTP_RELEASE>=26andalsodefined(debug)).%% Debugging code that requires OTP 26 or later.-else.%% Non-debug code that works in any release.-endif....This code uses theOTP_RELEASE macro anddefined(debug) to compile debugcode only for OTP 26 or later.
The -feature() directive
The directive-feature(FeatureName, enable | disable) can be used to enable ordisable thefeatureFeatureName. This isthe preferred way of enabling (disabling) features, although it is possible todo it with options to the compiler as well.
Note that the-feature(..) directive may only appear before any syntax isused. In practice this means it should appear before any-export(..) or recorddefinitions.
-error() and -warning() directives
The directive-error(Term) causes a compilation error.
Example:
-module(t).-export([version/0]).-ifdef(VERSION).version()->?VERSION.-else.-error("Macro VERSION must be defined.").version()->"".-endif.The error message will look like this:
% erlc t.erlt.erl:7: -error("Macro VERSION must be defined.").The directive-warning(Term) causes a compilation warning.
Example:
-module(t).-export([version/0]).-ifndef(VERSION).-warning("Macro VERSION not defined -- using default version.").-define(VERSION,"0").-endif.version()->?VERSION.The warning message will look like this:
% erlc t.erlt.erl:5: Warning: -warning("Macro VERSION not defined -- using default version.").Change
The-error() and-warning() directives were added in Erlang/OTP 19.
Stringifying Macro Arguments
The construction??Arg, whereArg is a macro argument, is expanded to astring containing the tokens of the argument. This is similar to the#argstringifying construction in C.
Example:
-define(TESTCALL(Call),io:format("Call~s:~w~n",[??Call,Call])).?TESTCALL(myfunction(1,2)),?TESTCALL(you:function(2,1)).results in
io:format("Call~s:~w~n",["myfunction ( 1 , 2 )",myfunction(1,2)]),io:format("Call~s:~w~n",["you : function ( 2 , 1 )",you:function(2,1)]).That is, a trace output, with both the function called and the resulting value.