Saturday, March 1, 2014

Dynamic Compilation

From the Erlang shell you can use:

> c(modulename).

To compile and load a module. From an actual source code perspective:

> compile:file("filename.erl").

So for an example I have the contents of test1.erl:

-module(test1).
-export([dostuff/0]).

dostuff() -> compile.file("test2.erl"),
                  test2:printMessage().

Contents of test2.erl:

-module(test2).
-export([printMessage/0]).

printMessage() -> io:fwrite("Hello World!~n", []).

Next step is to open the Erlang shell and load in test1.erl:

> c(test1).

If you open a terminal in the same directory, you'll notice the contents are:

test1.erl
test1.beam
test2.erl

But there is no test2.beam because it hasn't been compiled/run yet. Now from the Erlang shell where the compile was run do the following:

> test1:dostuff().
Hello World!
ok

If you list the directories it shows:

test1.erl
test1.beam
test2.erl
test2.beam

The test2.erl file was compiled and loaded from source. Pretty cool that we can dynamically load code as needed.

No comments:

Post a Comment