A Unit can also contain an initialization section and a finalization section.
These two blocks of code run automatically when the program starts and exits respectively.
initialization: Executes when the program launches and the unit is loaded into memory, before the main program code. Multiple units run their initialization sections sequentially in the order they are referenced.
finalization: Executes right before the program shuts down normally and the process terminates; its execution order is the reverse of initialization.
Functions
Initialization: Register classes, open global files / database connections, initialize global variables, register components;
Finalization: Free allocated memory, close handles, save configurations, unregister occupied resources to prevent memory leaks.
Let’s modify the unit PAS file from the previous lesson: MyUnit.pas
unit MyUnit;
{$ifdef FPC}
{$mode objfpc}{$H+}{$J-}
{$endif}
interface
procedure MyProcedure(const A: Integer);
function MyFunction(const S: string): string;
implementation
procedure MyProcedure(const A: Integer);
begin
WriteLn('A + 10 is: ', A + 10);
end;
function MyFunction(const S: string): string;
begin
Result := S + 'strings are automatically managed';
end;
// Initialization section: Runs automatically when the program loads this unit
initialization
WriteLn('Hello world!');
// Finalization section: Runs automatically before normal program exit
finalization
WriteLn('Goodbye world!');
end.Code language: JavaScript (javascript)
Only the above two segments are added at the bottom

Execution Result

The final “Goodbye world” will only execute after you press Enter (when the program is about to terminate).
Initialization and finalization