Difference between revisions of "Unit/ru"

From Free Pascal wiki
Jump to navigationJump to search
Line 48: Line 48:
 
         // здесь может быть размещен код,  
 
         // здесь может быть размещен код,  
 
         // который выполняется при загрузке модуля
 
         // который выполняется при загрузке модуля
 
 
finalization
 
finalization
 
// код, выполняемый по окончании программы
 
// код, выполняемый по окончании программы

Revision as of 22:22, 31 August 2020

Deutsch (de) English (en) español (es) suomi (fi) français (fr) português (pt) русский (ru)


Back to Зарезервированным словам.


A unit is a source code file (or the binary compiled from that file) which was written using the Pascal programming language, and that is designed to be a single module in an application or an object module. Unit is a reserved word.

A Unit - это файл исходного кода (или двоичный, скомпилированный из этого файла), который был написан с использованием языка программирования Pascal и разработан как отдельный модуль в Приложении или Объектном модуле. Слово Unit - это зарезервированное слово.

Назначение

Модуль может использоваться там, где функциональность должна быть предоставлена прикладной программе или другим модулям. Он позволяет писать код, который выполняет эту функцию один раз и может использоваться во многих местах. Это может снизить вероятность ошибок и увеличить повторное использование кода.

Двоичный модуль может использоваться, когда автор модуля желает предоставить определенные функции для использования в программе языка Паскаль, но не желает предоставлять исходный код, который выполняет эти функции.

Модули также использовались в более старых версиях Паскаля, когда на компьютерах с ограниченными ресурсами было необходимо иметь возможность загружать подпрограммы по мере необходимости, а не хранить каждую подпрограмму исполняемой программы в памяти все время.

Модуль, которому требуется доступ, например, процедуры и типы данных в другом модуле, должен указывать те модули, к которым он должен получить доступ, в разделе uses (но связывание выполняется без необходимости писать make-файл, как в C).

Модуль также можно использовать для объявления серии глобальных констант или переменных для использования всем приложением без фактического содержания исполняемого кода. Это похоже на ключевое слово common в языке программирования Fortran.

Формат

Модуль задается с помощью ключевого слова unit, за которым следует идентификатор модуля. Идентификатор модуля (в следующем примере имя модуля - «minimalunit») должен соответствовать имени файла, в котором он записан. Минимальный рабочий пример (который ничего не делает):

unit minimalunit;
interface
        // здесь функционал, которые модуль публикует открыто
implementation
        // здесь идет реализация предлагаемого функционала и, 
        // возможно, внутреннего функционала (видимого только внутри модуля)
end.

где часть после раздела interface соответствует public-части других языков и раздел implementation делает это для private.

Более продвинутая базовая структура:

unit advancedunit;
interface

implementation

initialization
        // здесь может быть размещен код, 
        // который выполняется при загрузке модуля
finalization
	// код, выполняемый по окончании программы

end.

Необязательные разделы initialization и finalization могут следовать за кодом, который выполняется в начале/конце программы.

Detailed unit example

A step-by-step example:

unit randomunit;
// this unit does something

// public  - - - - - - - - - - - - - - - - - - - - - - - - -
interface

type
	// the type TRandomNumber gets globally known
	// since it is included somewhere (uses-statement)
	TRandomNumber = integer;

// of course the const- and var-blocks are possible, too

// a list of procedure/function signatures makes
// them useable from outside of the unit
function getRandomNumber(): TRandomNumber;

// an implementation of a function/procedure
// must not be in the interface-part

// private - - - - - - - - - - - - - - - - - - - - - - - - -
implementation

var
	// var in private-part
	// => only modifiable inside from this unit
	chosenRandomNumber: TRandomNumber;

function getRandomNumber(): TRandomNumber;
begin
	// return value
	getRandomNumber := chosenRandomNumber;
end;

// initialization is the part executed
// when the unit is loaded/included
initialization
begin
	// choose our random number
	chosenRandomNumber := 3;
	// chosen by fair-dice-roll
	// guaranteed to be random 
end;

// finalization is worked off at program end
finalization
begin
	// this unit says 'bye' at program halt
	writeln('bye');
end;
end.

To include a unit just use the uses-statement.

program chooseNextCandidate;
uses
	// include a unit
	randomunit;

begin
	writeln('next candidate: no. ' + getRandomNumber());
end.

When compiling, FPC checks this program for unit dependencies. It has to be able to find the unit "randomunit".

The simplest way to satisfy this is to have a unit whose name matches the file name it is written in (appending .pas is OK and encouraged). The unit file may be in the same directory where the program source is in or in the unit path FPC looks for units.

Unit precedence

When multiple units are described in a use clause, conflicts can occur with identifiers (procedures, types, functions etc.) that have the same name in multiple units. In FreePascal, the last unit “wins” and provides the code for the unit.

If you want to achieve a different behavior, you can explicitly prepend unitname.identifier to specify the unit you want to use, or reorder the units. The former is often the clearest option.

unit interestCalculations;

interface

type
  basisType = currency;

implementation

end.

Specifying the unit of declaration explicitly:

program interestCalculator;

uses
   interestCalculations;

type
   // we already loaded a declaration of "basisType"
   // from the interestCalculations unit, but we're
   // re-declaring it here again ("shadowing")
   basisType = extended;

var
   // last declaration wins: originalCapital is an extended
   originalCapital: basisType;
   // specify a scope to use the declaration valid there
   monthlyMargin: interestCalculations.basisType;

begin
end.

Note, the interestCalculations unit will still perform its own calculations with its own basisType (here currency). You can only alter (“shadow”) declarations in the current scope (and descending).

See also