Yarin Miran
Yarin Miran

Reputation: 3381

Global variables in Delphi

I have a console application written in Delphi. I saw that I can have global variables by assigning them to unit scopes, but in a console application I don't use units (from what I've understood it's forms-only).

Upvotes: 1

Views: 17676

Answers (2)

Toon Krijthe
Toon Krijthe

Reputation: 53366

Nope, a unit is not equivalent to a form.

A unit is a module which contains part of your program. Each form is a separate unit but a unit does not have to contain a form.

Each unit has an interface section and a implementation section. The declarations in the interface section are visible to all units that use the unit:

unit A;

interface

  type
    TMyClass = class
    end;


implementation

end.


unit B;

interface

uses
  A;  // I can now see and use TMyClass.

You can declare global variables by declaring them in a unit:

unit A;

interface

  var
    GVar1 : Integer;

implementation

  var 
    GVar2 : Integer;

end.

GVar1 is visible and can be modified by all units using unit A. GVar2 is only visisble by the code of unit A because it is defined in the implementation section.

I strongly advice against using globals in the interface section because you have no control over them (because anybody can change them). If you really need a global, you better define it in the implementations section and provide access functions.

By the way, you can see a unit as a kind of a class (with a single instance). It even has a way to construct and destruct:

unit A;

interface

  type
    TMyClass = class
    end;


implementation

initialization
  // Initialize the unit
finalization
  // Free resources etc. You can olny have a finalization if you have an initialization.
end.

Upvotes: 13

Michał Niklas
Michał Niklas

Reputation: 54292

If you want global variable declare it in interface section of your unit.

PS Console aplication can use units.

PPS Take some time and read Delphi documentation, it explains Delphi language pretty well.

Upvotes: 1

Related Questions