Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 36 ยท Units and Object Pascal

Initialization and Finalization

See how Delphi and Free Pascal run unit setup and cleanup code, in which order units start and stop, and which pitfalls to avoid in initialization sections.

Some units need to prepare something before the program runs: open a log file, build a lookup table, register a class. They also need to clean up when the program ends. Pascal gives every unit two optional sections for this: initialization and finalization.

You rarely need them in small programs, but they are all over real Delphi code. The forms you design register themselves in initialization sections, and the memory manager reports leaks from a finalization section. Knowing exactly when they run explains a whole family of mysterious start-up bugs.

The two sections

They go at the end of the unit, after implementation:

PASCAL
unit Logger;

interface

procedure Log(const Msg: string);

implementation

uses
  System.SysUtils;

var
  LogFile: TextFile;

procedure Log(const Msg: string);
begin
  WriteLn(LogFile, FormatDateTime('hh:nn:ss ', Now), Msg);
end;

initialization
  AssignFile(LogFile, 'app.log');
  Rewrite(LogFile);
  Log('Logger started');

finalization
  Log('Logger stopped');
  CloseFile(LogFile);

end.

The code under initialization runs once, before the main program's begin. The code under finalization runs once, when the program ends normally. Neither section can have parameters, and neither is a routine you call yourself.

Both sections are optional, and most units have neither. Put finalization after initialization (an empty initialization line is fine). For a very short setup you can write begin ... end. instead of initialization, but that older form is discouraged.

The order rules

There are only two rules, and they follow from the uses clauses:

  1. A unit is initialized after every unit it uses.
  2. Finalization runs in the exact reverse of the initialization order.

So if Main uses Reports, and Reports uses Logger, the startup order is Logger, then Reports, then Main. At shutdown it is Main, Reports, Logger: Logger lives longest, so it is still available while the others shut down.

flowchart LR
  L["Logger"] --> R["Reports"] --> M["Main program"]

Dependencies start first and stop last.

Units that do not depend on each other have no guaranteed order between them. It usually follows the uses order, but do not rely on it. If one unit truly needs another to be ready, add it to uses so the dependency is explicit.

The runnable stand-in below sorts units by their dependencies with a depth-first search, starts them in that order, and stops them in reverse. Each "unit" prints a line when it starts and stops.

C Stand-in: dependency-ordered start and reverse stop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Notice that Logger starts first (everyone needs it) and stops last. Try changing the list so Format also uses Logger: the order stays valid because the search always finishes a unit's dependencies before the unit itself.

What belongs in initialization

Good uses:

  • registering something with a central registry (classes, plug-ins, file format handlers),
  • creating a singleton object and freeing it in finalization,
  • setting up a table that is expensive to compute.
PASCAL
unit Settings;

interface

type
  TSettings = class
    // ...
  end;

function AppSettings: TSettings;

implementation

var
  FSettings: TSettings;

function AppSettings: TSettings;
begin
  if FSettings = nil then
    FSettings := TSettings.Create;
  Result := FSettings;
end;

initialization

finalization
  FSettings.Free;   // Free is safe on nil

end.

This shows an alternative: create the object lazily the first time it is needed, but still release it in finalization.

What to avoid

  • Slow work. Everything in initialization runs before your program shows its first window or prints its first line. Ten units that each take half a second add up to a visibly slow start.
  • Showing dialogs or touching forms. The UI is not ready yet, and on a server there may be no UI at all.
  • Depending on units you did not name in uses. Order between unrelated units is not defined.
  • Raising exceptions. An exception in initialization stops the program before it has really begun, often with a confusing message. Check conditions and fail clearly instead.
  • Doing important work in finalization that must succeed. If the program crashes, finalization does not run. Save user data when it changes, not only at shutdown.

In Delphi, finalization and the memory manager

Delphi's default memory manager, FastMM, can report objects you forgot to free. Setting ReportMemoryLeaksOnShutdown := True; in your main program makes it print a leak report when it shuts down, which happens last of all. That is another reason finalization order matters: your units free their objects first, then the memory manager checks what is left. See debugging and compiler tools for more.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Unit A uses unit B. Which unit is initialized first?

    Dependencies are initialized before the units that use them, so B starts before A.
  2. 2. In what order do finalization sections run?

    Finalization mirrors initialization in reverse, so a unit's dependencies are still alive while it shuts down.
  3. 3. Which of these is a poor use of an initialization section?

    Slow work delays startup before the program does anything visible, and network failures there are hard to report.
  4. 4. Why should you save user data when it changes instead of only in finalization?

    A crash or forced termination skips finalization, so anything you saved only there is lost.

Summary

  • initialization runs once before the main program; finalization runs once at normal exit.
  • A unit starts after the units it uses and stops before them (reverse order).
  • Order between unrelated units is not guaranteed: declare real dependencies in uses.
  • Keep initialization fast, quiet and free of exceptions.
  • Do not count on finalization for data that must not be lost.

Next: Generics and Anonymous Methods