Reputation: 2935
I have two files. The first, a.pas
, contains:
uses b;
function f(x: integer): integer;
begin
f := x+1;
end;
begin
writeln(g(10));
end.
The file b.pas
contains:
unit b;
interface
function g(x: integer): integer;
implementation
function g(x: integer): integer;
begin
g := f(x)*2;
end;
end.
Is it possible to somehow reference the function f
defined in a.pas
? I thought about using the forward
keyword like this: (b.pas
)
unit b;
interface
function g(x: integer): integer;
implementation
function f(x: integer): integer; forward;
function g(x: integer): integer;
begin
g := f(x)*2;
end;
end.
But it doesn't work. It gives a "Forward declaration not solved" error.
I also thought about using the external
keyword but, in order to use the external f
function, b.pas
requires a.pas
to be already compiled (but a.pas
require b.pas
as well).
The only way to do this seems to be moving f
(interface and implementation) to a new helper.pas
file, and modifying b.pas
like this:
unit b;
interface
function g(x: integer): integer;
implementation
uses helper;
function g(x: integer): integer;
begin
g := f(x)*2;
end;
end.
I would prefer not having a helper.pas
file. But maybe it's just impossible?
Upvotes: 0
Views: 360
Reputation: 1141
With the current source code layout it is not possible. If you do not want to make a.pas a unit (why?), you can rewrite function g to have a function parameter:
{$ifdef FPC}
{$mode delphi}
{$endif}
type
tintfunc = function(x: integer): integer;
function g(x: integer; f: tintfunc): integer;
begin
g := 2*f(x);
end;
function f(x: integer): integer;
begin
f := x+1;
end;
begin
writeln(g(3,f));
end.
There are other methods (including global function pointers), but function parameters are IMO the most clean/safe way to implement it.
Upvotes: 1