Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't calling a function with identical signatures in different units result in compiler error?

Tags:

delphi

lazarus

Why doesn't this code result in a compiler error? I would have expected error for example 'ambiguous call to "CallMe"'. Is this a bug in the compiler or in the language? This can worked around by using the unit name and a dot in front of the function call but this not shield user code and library code against name collisions. You think that your code did something but it did something else and that's bad.

uses
  Unit2, Unit3;

{$R *.lfm}
{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage(IntToStr(CallMe(5)));
end;

unit Unit2;
{$mode objfpc}{$H+}
interface
uses
  Classes, SysUtils;
function CallMe(A: Integer) : Integer;
implementation
function CallMe(A: Integer) : Integer;
begin
  Result := A * 2;
end;
end.

unit Unit3;
{$mode objfpc}{$H+}
interface
uses
  Classes, SysUtils;
function CallMe(A: Integer) : Integer;
implementation
function CallMe(A: Integer) : Integer;
begin
  Result := A * -1;
end;
end.
like image 460
Allan Ojala Avatar asked Sep 16 '15 09:09

Allan Ojala


1 Answers

From documentation:

If two units declare a variable, constant, type, procedure, or function with the same name, the compiler uses the one from the unit listed last in the uses clause. (To access the identifier from the other unit, you would have to add a qualifier: UnitName.Identifier.)

like image 163
LU RD Avatar answered Oct 12 '22 04:10

LU RD