Ada Easy · Lesson 1 · On the house

Packages: spec and body

Split interface from implementation with package specs (.ads) and bodies (.adb). Lesson 1 is free — on the house.

Lessons · Ada Easy · Lesson 1 of 10 · On the house

Packages: spec and body

Split interface from implementation with package specs (.ads) and bodies (.adb).

Illustration for Ada
Lesson 1 is on the house.

A package groups types and subprograms. The spec (counter.ads) declares what clients see; the body (counter.adb) implements it.

Clients with Counter; and call Counter.Increment. Only the spec matters to them, so bodies can change without recompiling clients.

Variables declared in the body are hidden state, initialized once when the package is elaborated.

Packages can also be declared inside a subprogram's declarative part, as in this single-file example.

GNAT expects name.ads/name.adb file pairs; gnatmake main.adb compiles dependencies automatically.

package

with Ada.Text_IO; use Ada.Text_IO;

procedure Pkg_Demo is
   package Counter is
      procedure Increment (By : Positive := 1);
      function Value return Natural;
   end Counter;

   package body Counter is
      Count : Natural := 0;   -- hidden state
      procedure Increment (By : Positive := 1) is
      begin
         Count := Count + By;
      end Increment;
      function Value return Natural is (Count);
   end Counter;
begin
   Counter.Increment;
   Counter.Increment (By => 4);
   Put_Line (Counter.Value'Image);
end Pkg_Demo;
Match this when you type.

Quiz

Which part do clients depend on?

Quiz

Where should hidden state live?

Quiz

What file extension does GNAT use for specs?

Quiz

What does Counter.Value print?

Check

Match the still for: Packages: spec and body.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.