Hey guys,
I have a console application written in delphi. I saw that I can have global variables by assigning then to units scopes. but in console application I don't use units. (From what I've understood it's forms-only).
Hey guys,
I have a console application written in delphi. I saw that I can have global variables by assigning then to units scopes. but in console application I don't use units. (From what I've understood it's forms-only).
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.
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.