Section 2.4 - Compilation Units

Now that we know about program units, packages, and the difference between declarations and bodies, we can talk about compilation units.

A compilation unit contains either the declaration or the body of a program unit, preceded by the necessary context clause (`with' or `use' clauses). Thus a compilation unit can be a package declaration, a package body, a subprogram declaration, or a subprogram body along with its context clause.

An Ada compiler only compiles collections of one or more compilation units. That's why it's important to understand compilation units - to compile something, it must be a part of a legal compilation unit.

Here's a simplified BNF syntax for a compilation unit (the real definition is in chapter 10 of the LRM):

  1. compilation_unit ::= context_clause library_item
  2. context_clause ::= {context_item}
  3. context_item ::= with_clause | use_clause
  4. with_clause ::= "with" library_unit_name { "," library_unit_name} ";"
  5. use_clause ::= "use" library_unit_name { "," library_unit_name} ";"
  6. library_item ::= package_declaration | package_body | subprogram_declaration | subprogram_body

Note that compilation units start with "with" and "use" clauses, followed by a program unit declaration or body. We've already seen two compilation units - the simplified package declaration for Text_IO and the procedure body Hello.

Although most Ada compilers permit multiple compilation units in a single file, it's usually better to put separate compilation units in separate files. One Ada compiler (GNAT) requires different compilation units to be in different files.

Informally, when people say `show me X's package declaration' they really mean `show me the compilation unit that includes the package declaration of package X'.


Quiz:


Which of the following cannot be part of a compilation unit after the context clause?
  1. A package declaration
  2. A procedure declaration
  3. A procedure body
  4. A type definition

You may also:

PREVIOUS Go back to the previous section

NEXT     Skip to the next section

OUTLINE  Go up to the outline of lesson 2

David A. Wheeler (wheeler@ida.org)