1

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).

1
  • 1
    OK. Your understanding is wrong. But what's your question? Commented Jan 12, 2009 at 7:16

2 Answers 2

13

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.
Sign up to request clarification or add additional context in comments.

2 Comments

Regarding your observation about "units as classes," I think that's exactly how Delphi units are implemented in .Net.
I think it's more logical to think of a unit as a namespace, at least in a non dotnet version of Delphi.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.