Erlang - Header Files


Advertisements


Header files are like include files in any other programming language. It is useful for splitting modules into different files and then accessing these header files into separate programs. To see header files in action, let’s look at one of our earlier examples of records.

Let’s first create a file called user.hrl and add the following code −

-record(person, {name = "", id}).

Now in our main program file, let’s add the following code −

Example

-module(helloworld). 
-export([start/0]). 
-include("user.hrl"). 

start() -> 
   P = #person{name = "John",id = 1}, 
   io:fwrite("~p~n",[P#person.id]), 
   io:fwrite("~p~n",[P#person.name]).

As you can see from the above program, we are actually just including the user.hrl file which automatically inserts the –record code in it.

If you execute the above program, you will get the following output.

Output

1
“John”

You can also do the same thing with macros, you can define the macro inside the header file and reference it in the main file. Let’ see an example of this −

Let’s first create a file called user.hrl and add the following code −

-define(macro1(X,Y),{X+Y}).

Now in our main program file, let’s add the following code −

Example

-module(helloworld). 
-export([start/0]). 
-include("user.hrl"). 

start() -> 
   io:fwrite("~w",[?macro1(1,2)]).

If you execute the above program, you will get the following output −

Output

{3}


Advertisements
E-Books Store