[fpc-devel] New preprocessor directive

Michael Van Canneyt michael at freepascal.org
Sun May 17 10:50:19 CEST 2015


Hello,

As you probably know, it is possible to include source filename, line number, date etc. in your source
with the following directives:
{$I %FILENAME%}
{$I %LINE%}
{$i %DATE%}

At my request, Florian added

{$I %CURRENTROUTINE%}

to the list of possibilities, which means you can do nifty things as:

program testcr;

{$mode objfpc}

Type
   TMyClass = Class(TObject)
   Public
     Procedure MyMethod;
   end;

Var
   Indent : Integer;

Procedure MethodEnter(Const AMethod : String);
begin
   Writeln(StringOfChar(' ',Indent),'Entering ',AMethod);
   Inc(Indent,2);
end;

Procedure MethodExit(Const AMethod : String);
begin
   Dec(Indent,2);
   if Indent<0 then Indent:=0;
   Writeln(StringOfChar(' ',Indent),'Exiting ',AMethod);
end;

Procedure Debug(Const AMsg : String);

begin
  Writeln(StringOfChar(' ',Indent),AMsg);
end;

Procedure DoSomething;

   Procedure DoNested;

   begin
     MethodEnter({$I %CURRENTROUTINE%});
     Debug('Nested handling in '+{$I %CURRENTROUTINE%});
     MethodExit({$I %CURRENTROUTINE%});
   end;

begin
   MethodEnter({$I %CURRENTROUTINE%});
   Debug('Doing something in '+{$I %CURRENTROUTINE%}+' at line '+{$I %LINE%});
   DoNested;
   MethodExit({$I %CURRENTROUTINE%});
end;

Procedure TMyClass.MyMethod;

   Procedure DoNested;

   begin
     MethodEnter({$I %CURRENTROUTINE%});
     Debug('Nested handling in '+{$I %CURRENTROUTINE%});
     MethodExit({$I %CURRENTROUTINE%});
   end;

begin
   MethodEnter({$I %CURRENTROUTINE%});
   Debug('Doing some things in '+{$I %CURRENTROUTINE%}+' at line '+{$I %LINE%});
   DoNested;
   MethodExit({$I %CURRENTROUTINE%});
end;


Var
   T : TMyClass;

begin
   MethodEnter({$I %CURRENTROUTINE%});
   DoSomething;
   T:=TMyClass.Create;
   try
     T.MyMethod;
   finally
     T.Free;
   end;
   MethodExit({$I %CURRENTROUTINE%});
end.

Which produces something like

Entering $main
   Entering DoSomething
     Doing something in DoSomething at line 44
     Entering DoNested
       Nested handling in DoNested
     Exiting DoNested
   Exiting DoSomething
   Entering MyMethod
     Doing some things in MyMethod at line 61
     Entering DoNested
       Nested handling in DoNested
     Exiting DoNested
   Exiting MyMethod
Exiting $main

Kudos to Florian.

Michael.



More information about the fpc-devel mailing list