Search code examples
delphiundeclared-identifier

Accessing other unit constant in Delphi


I have a simple project in Delphi:

program Project1;

uses
  Forms,
  Unit2 in 'Unit2.pas',
  Unit1 in 'Unit1.pas' {Form1};

{$R *.res}

begin
  Application.Initialize;
  Application.CreateForm(TForm1, Form1);
  Application.Run;
end.

Unit1:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Edit1: TEdit;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

uses Unit2;

{$R *.dfm}

function encodeData(var Data:array of Byte; var Size: Integer): Integer;
var
  i: Intger
begin
  ...
  for i := 1 to Size do
  begin
    Data[i] := Data[i] + unit2.SomeArray[i]
  end;
  ...
  Result := 0;
  Exit;
  end
...

The second unit:

unit Unit2;

interface

implementation

const
  SomeArray:Array [0..65000] of LongWord = (
  ...
  );

end.

When I'm trying to build this project I get errors like this:

[Error] Unit1.pas(41): Undeclared identifier: 'SomeArray'

What's wrong with this code? I checked Delphi wiki and other questions and didn't find solution for this issue...


Solution

  • You need to define SomeArray in the interface section of the unit. Currently, you have it in the implementation section, which is purposely hidden from other units. Only things defined/declared in the interface are visible to other units.

    In the documentation you linked, it's described:

    The implementation section of a unit begins with the reserved word implementation and continues until the beginning of the initialization section or, if there is no initialization section, until the end of the unit. The implementation section defines procedures and functions that are declared in the interface section. Within the implementation section, these procedures and functions may be defined and called in any order. You can omit parameter lists from public procedure and function headings when you define them in the implementation section; but if you include a parameter list, it must match the declaration in the interface section exactly.

    In addition to definitions of public procedures and functions, the implementation section can declare constants, types (including classes), variables, procedures, and functions that are private to the unit. That is, unlike the interface section, entities declared in the implementation section are inaccessible to other units.

    (Emphasis mine)