Plugins - Pascal. Custom modules in pascal Working with standard modules in pascal examples

Modules in Pascal in relation to the main part of the program they resemble subroutines (procedures and functions). But by definition, they are independent programs whose resources can be used in other programs. In addition, the modules are described outside the calling application, but in a separate file, so a module is a separately compiled program. The compiled module file (this is exactly what is needed for use) will have the extension provided by the programming environment (for example, .tpu, .ppu, .pcu).

Modules are created, as a rule, to ensure code compactness, which large projects have to worry about. It is also worth noting that the use of modules, in a sense, removes the limitation on memory segmentation, since the code for each module is located in a separate segment.

The module structure looks like this:

Unit<имя модуля>;
Interface
<интерфейсная часть>
Implementation
<исполняемая часть>
Begin
<инициализация>
End.

Unit name

Module name following the keyword Unit, must match the name of the file (without .pas) in which its code is located. Also, using the name, the module is connected to another module, or to the main program. To do this, you need to specify a service word Uses, and list the list of plug-ins separated by commas:

Uses<список имен модулей>;

Interface part

The interface part describes the headers of objects that other modules and programs will have access to. These are constants, types, variables and subroutines. For example, this is what the interface part of the Search module may look like, containing algorithms for searching elements in an array.

1
2
3
4
5
6

unit Search;
Interface

var s: string ;

To declare this module, you need to specify its name in the program:

After which it will be possible to use all the objects described in the interface part.

Implementation

This section begins with the word Implementation(implementation). This is where you need to describe the subroutines declared in the interface part. At the same time, it is allowed not to indicate formal parameters in their headers, otherwise they must completely coincide with those in the interface part. In addition, the interface part can contain objects that are local (inaccessible to the calling program) for the module.

Initiating part

The initiating part begins its work before the execution of the main program begins. It (between Begin and End), as a rule, describes operators intended for various kinds of auxiliary work. This part may be missing or may not have any code. In the first case, you need to specify End with a dot, in the second, leave empty space inside Begin and End.

Compiling modules

You can only use compiled modules in the program that have the extension provided by your application development environment. Let's look at the three most popular of them:

Turbo Pascal

The result of compiling the module in Turbo Pascal will be a file with the extension .tpu (Turbo Pascal Unit), storing its code.

Free Pascal

After compiling the module in Free Pascal, two files are created with different resolutions: .ppu And .o. The first contains the interface part of the module, and the second (necessary for composing the program) contains part of the implementations.

Pascal ABC.NET

Pascal ABC.Net does not generate machine language code during module compilation. If compilation is successful, the code is saved in a file with permission .pcu.

There are three compilation modes for the Turbo Pascal and Free Pascal programming environments: Compile, Make and Build. In Compile mode, all modules used in the program must be compiled in advance. The application in Make compilation mode checks all connected modules for the presence of files with the appropriate resolution for the programming environment (.tpu or .o). If any of them is not found, then a file is searched with the name of the unfound module and the extension .pas. The most reliable mode is Build. Searching and compiling files (with the .pas extension) in this mode occurs even when modular files already exist.

Example

Let's create a small module containing procedures for binary and linear search of elements in an array. Module code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

unit Search;
Interface
type arr = array [ 1 ..5 ] of integer ;
var s: string ;
procedure binary_search(x: integer ; Ar: arr; var s: string ) ;
procedure line_search(x: integer ; Ar: arr; var s: string ) ;
Implementation
var a, b, c, i: integer ;
procedure binary_search(x: integer ; Ar: arr; var s: string ) ;
begin
a:= 1 ; b:= 5 ; s:= 'NO' ;
while a<= b do
begin
c:= a+ (b— a) div 2 ;
if(x b:= c— 1
else if (x>Ar[ c] ) then
a:= c+ 1
else
begin s:= 'YES' ; break ; end ;
end ;
end ;
procedure line_search(x: integer ; Ar: arr; var s: string ) ;
begin
s:= 'NO' ;
for i:= 1 to 5 do
begin
if (Ar[ i] = x) then
begin
s:= 'YES' ; break ;
end ;
end ;
end ;
end.

All this code should be in a separate file. Now let's write the main program into which we will connect our Search module.

Module (UNIT-module, unit) is an autonomously (separately) compiled program unit that contains components of the description section (labels, constants, types, variables, procedures, functions), and may also contain operators of the initializing part.
The module itself is not an executable program, but is intended to be used by other programs and modules.

Module structure

The module has the following structure:
UNIT< module name >
INTERFACE
< interface section >
IMPLEMENTATION
< implementation section >
BEGIN
< initialization section >
END.

Module title consists of a reserved word Unit(module) and the module name.

The name of the module is selected according to general rules and must match the name of the disk file containing the source code of the module.
The extension in the module name (. pas ) is not specified, it is set by default.

The module name is used to link it to the main program using a clause Uses .
Offer Uses M.B. placed after the module title or after the words

Interface And Implementation .

Interface part Interface(interface, articulation, connection) and contains references to other modules and declarations (descriptions) of global objects, i.e. labels, constants, types, variables, and headers of procedures and functions that are available to the main program and other modules (i.e. visible from outside).

Implementation section – starts with a keyword Implementation(execution) and contains a description of objects local to the module, i.e. labels, constants, types, variables that are not accessible to the main program and other modules (i.e. not visible from the outside) and a complete description of procedures and functions. In this case, in the header of the subroutines there is a list of formal parameters. omitted, but if it is given, it must exactly correspond to the description in the interface part.

Initialization section – enclosed in verbal brackets BEGIN END.
and contains statements that will be executed before control is transferred to the main program. This might be data (variable) initialization operators For example, assignment and input operators, as well as procedures for linking and opening files. Operators section m.b. empty BEGIN END or simply be absent END .
There is a period at the end of the module.

Compiling and Using Modules

The system's RAM has a segment structure (one segment is equal to 64K = 65535 bytes). Program code m.b. no more than one segment, the data volume cannot exceed one segment (unless dynamic memory is used) and one segment for the stack. The stack size is set by the directive ($M<>). The minimum stack size is 1K, the default maximum one segment is 16K. The values ​​of local variables are pushed onto the stack when calling a subroutine, and popped from the stack when exiting.
The module code is placed in a separate segment, because it is translated independently from the main program, and the number of modules used by the program depends only on the available OP. This allows you to create large programs.
The compiler creates module code with the same name, but with the extension tpu (turbo pascal unit).
To use a module by the main program or other modules, its name (without extension) is placed in the sentence list Uses
If the module is compact and often m.b. used by application programs, it can be placed in the library of standard modules TURBO.TPL (Turbo-Pasacal-library ) using the utility TPUMOVER.
But this should be done only in case of emergency because... the library is loaded into the OP and reduces the space for the program.
When compiling a file with the source text of a module, a file of the same name appears with the extension tpu and is placed in the directory specified by the option

OPTIONS/DIRECTORIES/UNIT DIRECTORIES

or in the current directory if this option is not available.
When compiling the main program, the modules used must be in the directory specified by the option
OPTIONS/DIRECTORIES/EXE & TPU DIRECTORIES

or in the current directory if this option is missing
For getting EXE task file in option

COMPILE/DESTINATION/DISK(MEMORI)
install DISK .
There are three module compilation modes:
- COMPILE
- BUILD
- MAKE

Modes are set by menu COMPILE

1. Mode COMPILE(called Alt-F9 ) . In this case, the program is compiled and the modules used must be compiled. pre-compiled and stored in appropriate directories.
2. Mode BUILD(called - F9) . In this case, previously compiled modules are ignored, and modules with the extension are searched for pas and are recompiled.
3. Mode MAKE(called F9) . In this case, only modules that had changes in the text are recompiled.

Example 16.1.

In file inp.txt there are three arrays of real numbers

2.1 3.1 -2.4 5.6 5.4 -6.7 3.5 -3.6

Evaluate function

where Max_a, Max_b, Max_c, Sa, Sb, Sc, ka, kb, kc - the maximum element, sum and number of positive elements of the corresponding arrays a, b, and c.
Output the result to a file out. txt and on the screen.

Module text

Unit UNMAS;
Interface
Const n=10;
Type vec=array of real;
Var z:vec;
i:integer;
f1,f2:text;

Procedure SK1(z:vec; num:byte; Var s:real; Var k:byte);
Function MAX(z:vec; num:byte):real;

Implementation
Procedure Vv(s:char; num:byte;Var z:vec);
Begin
Writeln("Array ",s);
For i:=1 to num do
Begin
Read(f1,z[i]); Write(z[i]:4:1," ":3);
End;
Readln(f1); Writeln;
End;

Procedure SK1(z:vec;num:byte; Var s:real; Var k:byte);
Begin
s:=0; k:=0;
for i:=1 to num do if z[i]>0 then
Begin
s:=s+z[i];
k:=k+1
End;
End;
Function MAX(z:vec;num:byte):real;
Var m:real;
Begin
m:=z;
for i:=1 to num do if z[i]>m then m:=z[i];
MAX:=m
End;

Begin
Assign(f1,"inp.txt"); Reset(f1);
Assign(f2,"out.txt"); Rewrite(f2)
End.

Program text

Program lr7_16;
Uses CRT,UNMAS;
Var
a,b,c:vec;
y,sa,sb,sc:real;
ka,kb,kc:byte;
Begin
clrscr;
Vv("a",8,a);
Vv("b",9,b);
Vv("c",n,c);
SK1(a,8,sa,ka);
SK1(b,9,sb,kb);
SK1(c,n,sc,kc);
y:=(MAX(a,8)+MAX(b,9)+MAX(c,n))+(sa+sb+sc+ka+kb+kc);
Writeln("Result:":20);
Write("Array a: ");
Writeln("sa=",sa:5:1," ka=",ka);
Write("Array b: ");
Writeln("sb=",sb:5:1," kb=",kb);
Write("Array c: ");
Writeln("sc=",sc:5:1," kc=",kc);
Writeln(" ":10,"y=",y:10);
Readln;
Writeln(f2,"ђҐ§г"мв в:");
Writeln(f2," ":10,"y=",y:10);
Close(f1);
Close(f2)
End.

Program results

Array a
-2.1 3.1 -2.4 5.6 5.4 -6.7 3.5 -3.6
Array b
2.3 -4.3 2.1 2.5 -3.7 -5.6 4.6 3.5 -7.5
Array c
-2.1 4.3 -2.3 7.6 4.5 -8.9 5.7 -4.5 6.8 -5.8
Result:
Array a: sa= 17.6 ka=4
Array b: sb= 15.0 kb=5
Array c: sc= 28.9 kc=5
y= 9.330E+01

Plug-ins.

1. Basic provisions

Plug-in module– a file containing source text in Pascal language, having a certain structure, intended for use both in the main program and in other plug-ins. Usage is to include a module in the uses section by specifying its name.

2. General structure of the plug-in module

Unit<имя модуля>; Interface Implementation End.

Structurally, the plug-in module can be divided into three sections: 1) Interface section - interface (must be declared, can be empty) 2) Implementations section - implementation (must be declared, can be empty) 3) Module body - begin-end. (may be missing)

2.1. Interface section.

Interface section– plug-in area, starting with the interface keyword and ending with the implementation keyword, which can contain: - a list of plug-ins; - constants;- custom data types; - variables; as in the program, the above sections (declarations of constants, variables, etc., with the exception of the uses section) in this section can be arranged in any sequence and in any quantity. Note 3: If prototypes of procedures/functions are declared in this section, then their implementations must be guaranteed to be present in the implementation section. Main purpose: defines public data/functionality for use from a program or module that uses this module.

Example of an interface section:

Interface (plug-ins) Uses AnotherUnit; (constants) Const PI=3.14159265;

E=2.71828182; (custom data types) Type TMyType=array[-3..7] of real; (variables) Var temp:TMyType; (procedures and functions) Procedure Fill(var x:TMyType); Function Find(const x:TMyType; const Value:real):Boolean; Implementation

2.2. Implementations section. Implementations section Main purpose:– the area of ​​the plug-in module, starting with the keyword implementation and ending with the body of the module (if there is one) or the keyword end with a dot indicating the end of the module, in which implementations of procedures and functions declared in the interface section are located, which may contain: - a list of plug-ins modules; - constants;- constants;

- custom data types;

- variables;

- procedures and functions necessary to implement the procedures/functions declared in the interface section.

implementation of procedures and functions described in the interface section.

When implementing procedures and functions described in the interface section, their headers can be described in abbreviated form. Exception - PascalABC: when using header variables in the implementation text, a compilation error occurs.

Example 1 (headings in abbreviated form): Unit DemoUnit; Interface (procedure prototype) Procedure Swap(var a,b:integer); Implementation Procedure Swap; Var Temp:integer; Begin Temp:=a; Main purpose: initialization of module variables, allocation of resources necessary for its operation, etc.

Example of a module containing a body:

Unit DemoUnit; Interface Const N=50; Var Roots:array of real; Implementation Uses Math; Var I:integer; (module body) Begin For i:=1 to N do Roots[i]:=sqrt(i); End.

Example of a module without a body: (see example of a module for headers in full form).

- constants; The program code located in the body of the module is executed once - when the module is loaded, before the execution of the main program code begins. - variables; In the case when several modules that have initialization sections are connected in the uses section, the code of these sections is executed in the order in which the modules are connected.

2.4. Additional sections in the module structure.

The Free Pascal, Pascal ABC, Pascal ABC.Net compilers allow, in addition to those listed above, two more sections: - an initialization section - a finalization section. 2.4.1. Initialization section. Initialization section – the plug-in area placed after the end of the implementations section, starting with the initialization keyword and ending with the finalization section, if there is one, or the end keyword followed by a dot. The purpose is similar to the module body. 2.4.2. Finalization section. Main purpose: Finalization section

– a plug-in area placed at the end of the initialization section, if there is one, or at the end of the implementations section, and ends with the end keyword followed by a dot.

- constants; releasing resources allocated for module operation. - variables; unit DemoUnit; interface var a:array of ^integer;(array of pointers) implementation (memory allocation and initialization with values) procedure AllocateArray; var i:integer; begin for i:=1 to 20 do begin New(a[i]);

a[i]^:=i;

end; end; (deallocating memory) procedure DeallocateArray; var i:integer; begin for i:=1 to 20 do Dispose(a[i]); end; initialization AllocateArray;(initialization - start of work - allocate memory) finalization DeallocateArray; (finalization - end of work - free up memory) end.

The program code placed in the listed sections is executed once. The code of the initialization sections is before the start of execution of the main program code, the code of the finalization sections is after.

The result of compiling a plug-in into Turbo Pascal is a *.tpu file (Turbo Pascal Compiled Unit), which is a machine representation of the data and code located in it.

3.2. Compiling in Free Pascal.

The result of compiling a plug-in module in Free Pascal is two files: *.ppu - a file containing the interface part of the module, and a *.o file - an object file containing part of the implementations. Moreover, the latter is necessary for composing the application.

3.3. Compilation in Pascal ABC.Net.

Unlike the environments listed above, Pascal ABC.Net does not generate machine language code during module compilation. The compiler of this environment completes its work after performing a semantic analysis, saving the semantic tree of the module in an intermediate format - *.pcu - a file that, to a first approximation, can be considered the result of compilation with the indicated limitations.

3.4. Speeding up program compilation.

At the application linking stage, the linker assembles an executable module, taking object modules as input. Thus, having already compiled plug-ins, compiling programs using them is faster, since they have already been processed. This is true for Turbo and Free Pascal. However, in Pascal ABC.Net, compilation speed is achieved only due to the fact that there is no need to perform syntactic and semantic analysis. Conclusion: compiled versions of executable modules are not compatible between different compilers.

Code for the task: “Plug-ins”

Textual

Program listing

Unit u1; interface procedure PrintFirst; procedure PrintFirstSecond; implementation uses u2; (<--- Раньше было в Interface } procedure PrintFirst; begin writeln("Print first"); end; procedure PrintFirstSecond; begin writeln("Print first"); PrintSecond; end; end.

Modules in Pascal, in relation to the main part of the program, resemble subroutines (procedures and functions). But by definition, they are independent programs whose resources can be used in other programs. In addition, the modules are described outside the calling application, but in a separate file, so a module is a separately compiled program. The compiled module file (this is exactly what is needed for use) will have the extension provided by the programming environment (for example, .tpu, .ppu, .pcu).

Modules are created, as a rule, to ensure code compactness, which large projects have to worry about. It is also worth noting that the use of modules, in a sense, removes the limitation on memory segmentation, since the code for each module is located in a separate segment.

The module structure looks like this:

Unit<имя модуля>; Interface<интерфейсная часть>Implementation<исполняемая часть>Begin<инициализация>End.

Unit name

The module name following the Unit keyword must match the name of the file (without .pas) in which its code is located. Also, using the name, the module is connected to another module, or to the main program. To do this, you need to specify the service word Uses, and list the list of plug-ins separated by commas:

Uses<список имен модулей>;

Interface part

The interface part describes the headers of objects that other modules and programs will have access to. These are constants, types, variables and subroutines. For example, this is what the interface part of the Search module may look like, containing algorithms for searching elements in an array.

Unit Search; Interface type arr = array of integer; var s: string; procedure binary_search(x: integer; Ar: arr; var s: string); procedure line_search(x: integer; Ar: arr; var s: string);

To declare this module, you need to specify its name in the program:

After which it will be possible to use all the objects described in the interface part.

Implementation

This section begins with the word Implementation. This is where you need to describe the subroutines declared in the interface part. At the same time, it is allowed not to indicate formal parameters in their headers, otherwise they must completely coincide with those in the interface part. In addition, the interface part can contain objects that are local (inaccessible to the calling program) for the module.
Initiating part

The initiating part begins its work before the execution of the main program begins. It (between Begin and End), as a rule, describes operators intended for various kinds of auxiliary work. This part may be missing or may not contain any code. In the first case, you need to specify End with a dot, in the second, leave empty space inside Begin and End .

Compiling modules

You can only use compiled modules in the program that have the extension provided by your application development environment. Let's look at the three most popular of them:

compiling modules in Turbo Pascal

The result of compiling the module into Turbo Pascal, there will be a file with the extension .tpu (Turbo Pascal Unit), storing its code.

compiling modules in Free Pascal

After compiling the module in the environment Free Pascal, two files are created with different resolutions: .ppu And .o. The first contains the interface part of the module, and the second (necessary for composing the program) contains part of the implementations.

compiling modules in Pascal ABC.NET

Pascal ABC.Net does not generate machine language code during module compilation. If compilation is successful, the code is saved in a file with permission.pcu.

There are three compilation modes for the Turbo Pascal and Free Pascal programming environments: Compile, Make and Build. In Compile mode, all modules used in the program must be compiled in advance. The application in Make compilation mode checks all connected modules for the presence of files with the appropriate resolution for the programming environment (.tpu or .o). If any of them is not found, then a file is searched with the name of the unfound module and the extension .pas. The most reliable mode is Build. Searching and compiling files (with the .pas extension) in this mode occurs even when modular files already exist.

Example: let's create a small module containing procedures for binary and linear search of elements in an array. Module code:

Unit Search; Interface type arr = array of integer;<=b do begin c:=a+(b-a) div 2; if (xvar s: string;

procedure binary_search(x: integer; Ar: arr; var s: string);

procedure line_search(x: integer; Ar: arr; var s: string); Implementation var a, b, c, i: integer;

procedure binary_search(x: integer; Ar: arr; var s: string); begin a:=1; b:=5; s:="NO";