Program Structure: Programs, Units and Packages

3.1 Program File (.dpr)

program MyApp;

uses
  Vcl.Forms,
  MainForm in 'MainForm.pas' {Form1},
  DataModule in 'DataModule.pas' {DM: TDataModule};

{$R *.res}

begin
  Application.Initialize;
  Application.MainFormOnTaskbar := True;
  Application.CreateForm(TDM, DM);
  Application.CreateForm(TForm1, Form1);
  Application.Run;
end.

3.2 Unit Structure

unit Geometry;                         // unit name = file name (Geometry.pas)

interface                              // PUBLIC section: what other units can see

uses
  System.SysUtils, System.Math;        // units needed by the interface

type
  TPoint2D = record
    X, Y: Double;
  end;

function Distance(const A, B: TPoint2D): Double;

const
  Epsilon = 1E-9;

implementation                         // PRIVATE section: implementation details

uses
  System.Classes;                      // units needed only by the implementation (avoids circular references)

function Distance(const A, B: TPoint2D): Double;
begin
  Result := Sqrt(Sqr(A.X - B.X) + Sqr(A.Y - B.Y));
end;

initialization                         // optional: runs when the program starts (in uses order)
  // setup code

finalization                           // optional: runs at shutdown (reverse order)
  // cleanup code

end.

3.3 Unit Scope Names and Namespaces

Modern RTL/VCL units use dotted names: System.SysUtils, System.Classes, Vcl.Forms, FMX.Forms, Data.DB, FireDAC.Comp.Client, Winapi.Windows.

Unit scope names (Project Options) allow short names like SysUtils. Prefer fully qualified names in new code.

Circular references: units can use each other only if at least one of the uses clauses is in the implementation section.

3.4 Lexical Elements

Case-insensitive language (Count = count). Statements end with ;. Blocks use begin ... end.

Comments: // line, { block }, (* block *). Compiler directives look like {$IFDEF ...}.

Identifiers: letters, digits, _. Reserved words can be used with the & prefix (&type).

String literals use single quotes: 'It''s' (a doubled quote escapes it). Character codes: #13#10.

Multiline strings (Delphi 12+): triple quotes:

const
  SQL = '''
    SELECT *
    FROM Customers
    WHERE City = :City
    ''';