A unit
consists of types (including classes), constants, variables, and routines
(functions and procedures). Each unit is defined in its own unit (.pas) file.
A unit file begins with a unit heading, which is followed by the interface, implementation, initialization, and finalization sections. The initialization and finalization sections are optional. A skeleton unit file looks like this:
unit
Unit1;
interface
uses { List of units goes here }
{ Interface section goes here }
implementation
uses { List of units goes here }
{ Implementation section goes here }
initialization
{ Initialization section goes here }
finalization
{ Finalization section goes here }
end.
The unit must conclude with the word end followed by a period.
Program structure and syntax:
Overview
Unit structure and syntax: Overview
Unit references and
the uses clause
Multiple and indirect
unit references
Program structure and syntax: Overview
单元一般由类型(包括类)、常量、变量以及例程(函数和过程)组成。每个单元都在其各自相应的单元(.pas)文件中定义。
单元文件以单元首部开始,接下来是接口节、实现节、初始化节和实现节。其中,初始化节和结束节是可选的。下面是单元文件的框架:
unit
Unit1;
interface
uses { 当前单元使用到的单元列于此处
}
{ 接口节
}
implementation
uses { 当前单元使用到的单元列于此处
}
{ 实现节
}
initialization
{ 初始化节
}
finalization
{ 结束节
}
end.
单元必需以保留字end结束,并且在end之后还必需一个句点(.)。
编者注
上面的单元框架中,在接口节和实现节中先后两次出现uses子句,其作用是不相同的。如果在单元的接口节中需要使用其他单元(例如从其他单元中继承类),则被使用的单元名必需列在接口节的uses子句中;如果在实现节中使用其他单元(如常量、例程),则被使用的单元名既可以列在接口节的uses子句中,也可以列在实现节的uses子句中。需要注意的是,被使用的单元,其单元名在这两处uses子句中只能出现一次,否则编译器将不认可。作为良好的习惯,能够列在实现节uses子句中的单元名,最好不要列在接口节中。这样做的好处在于,即便有可能出现单元之间相互引用的情况,也不会因为二者都被对方单元列在了接口节的uses子句中而使编译通不过。严格地说,Object Pascal编译器不允许单元之间完全相互引用,因为Object Pascal严格遵循“先声明、后使用”的编译规则(极端情况例外,详见本参考帮助主题“指针类型”中编者注)。