A Unit is a module in Pascal that contains code, procedures, variables, and type declarations. It is used to provide the functionality to an application program or other units. With units, programmers can write the code once and have the functionality used in many places. This allows for greater modularity and code reusability.
unit
keyword followed by the identifier. The name of the file in which the unit is written should match the identifier (LoadBalncer in this case).interface
keyword, where declarations of all the functions and procedures are written.implementation
keyword, where the implementation logic and definition of functions are written.unit LoadBalancer
interface
// everything that the unit offers publicly
implementation
// implementation of the offered functions and
// private definitions (only known in the unit)
end.
Let us first make a unit. We will build a unit that calculates the perimeters of different shapes.
unit CalculatePerimeter;
interface
// function declarations
function RectanglePerimeter( length, width: real): real;
function CirclePerimeter(radius: real) : real;
implementation
//function definitions
function RectanglePerimeter( length, width: real): real;
begin
RectanglePerimeter := 2 * (length + width);
end;
function CirclePerimeter(radius: real) : real;
const
PI = 3.14159;
begin
CirclePerimeter := 2 * PI * radius;
end;
Then we will create a simple program that uses this unit with the uses
keyword, as we see here:
program PerimeterCalculator
uses CalculatePerimeter
var
l, w, r, pR, pC: real;
begin
clrscr;
l := 8;
w := 4;
pR := RectanglePerimeter(l, w);
r:= 7.0;
pC:= CirclePerimeter(r);
When more than one unit is mentioned in the uses
clause, conflicts can occur with the functions, identifiers, and types with the same names in different units. In FreePascal, the conflict is resolved by accepting the code of the last unit used.
If we want to access some other unit’s code, we can reorder the arrangement of the unit in the uses
clause, or we can use the notation, unitname.identifier.
Free Resources