Thursday, July 29, 2010

erlang: Simple Debug macro

When testing things I need some quick way to debug "a la" printf() style. Old habits :)

Here's is the simple debug macro I use:
-ifdef(debug).
-define(DEBUG(Format, Args),
  io:format("~s.~w: DEBUG: " ++ Format, [ ?MODULE, ?LINE | Args])).
-else.
-define(DEBUG(Format, Args), true).
-endif.
Write it down in a "debug.hrl" file, then you only need to add this line in any file header:
-include("debug.hrl").
This simple macro gives you the module name and the line number. This saves me a lot of time.

Then you need to define the "debug" atom to let your macro do what you want. The compile:file/2 handles options for this, the syntax is {d, debug}


You can also use some simple helper module to compile multiples files using simple regexp:
Here's the code:
-module(utils_compile).

-export([c/1, c/2, d/1, d/2]).

c(FilePattern) ->
 c(FilePattern, "../ebin").

c(FilePattern, OutDir) ->
 filelib:fold_files(".", FilePattern ++ ".erl$", false, 
 fun(X, _Acc) -> 
  io:format("Compiling ~p~n", [ X ]), 
  compile:file(X, [{outdir, OutDir}, report]) end, []).

d(FilePattern) ->
 d(FilePattern, "../ebin").

d(FilePattern, OutDir) ->
 filelib:fold_files(".", FilePattern ++ ".erl$", false, 
 fun(X, _Acc) -> 
  io:format("Compiling (debug) ~p~n", [ X ]), 
  compile:file(X, [{outdir, OutDir}, {d, debug}, report]) end, []).

No comments:

Sticky