Skip to content
LumenaryAcademy
Foundations 50 min

First steps in Ada

Why the US Department of Defense commissioned a language, where Ada flies today, and how a source file becomes a running program.

Code tested · 3AI-draftedAwaiting review by a computer scientist

Your guides: Chloe · The Designer, Margaret · The Profiler, Gideon · The Language Lawyer

MotivationH

Why learn Ada?

Most programming languages are designed to make code quick to write. Ada was designed to make code hard to get wrong, and easy to read years later by someone who did not write it. That sounds like a small difference in emphasis; in practice it changes almost everything about the language.

In Ada you say what your numbers mean. A temperature in a reactor, a train's speed and a count of passengers are three different types, each with its own range, and the compiler refuses to add a speed to a temperature by accident. If a value ever falls outside its declared range while the program runs, Ada raises an exception at that moment instead of letting a wrong number travel silently through the system. Interfaces between parts of a program are written down separately from their implementations, and the compiler checks that every part honours them. Concurrency is part of the language rather than a library bolted on. And since Ada 2012, a subprogram can state its preconditions and postconditions in code, where tools can check them while testing or, with SPARK, prove them before the program ever runs.

This is why Ada is chosen for software that must not fail: the flight controls of an airliner, the signalling of a railway, the guidance of a launcher. You may never write such software. But learning Ada teaches habits that pay off in any language: modelling the problem with precise types, separating interface from implementation, and treating the compiler as a careful colleague rather than an obstacle. Ada is also more pleasant than its reputation suggests. Its syntax reads almost like English, its error messages are good, and the modern toolchain (the GNAT compiler and the Alire package manager) installs in minutes.

History & global context

From the Department of Defense to Ada 2022

In the early 1970s the United States Department of Defense (DoD) was spending a great deal on software for embedded systems, computers built into aircraft, ships, weapons and communications equipment, and that software was written in hundreds of different languages and dialects. Every new project brought its own compilers, tools and specialists, and almost nothing could be reused. In 1975 the DoD set up the High Order Language Working Group to find one language for all of it.

The group did something unusual: before choosing or designing anything, it wrote down what the language had to do, in a series of requirement documents that grew more precise with each round and were named Strawman, Woodenman, Tinman, Ironman and finally Steelman (1978). No existing language met them, so the DoD held an international design competition. Four teams were funded to develop their designs under colour code names (Red, Green, Blue and Yellow); after a final round between Red and Green, the Green design won in 1979. It came from a team at CII Honeywell Bull in France led by Jean Ichbiah, and it was named Ada after Augusta Ada King, Countess of Lovelace, who in the 1840s wrote what is often called the first published computer program, for Charles Babbage's Analytical Engine. The military standard that defined it was numbered MIL-STD-1815, after the year of her birth.

The first reference manual appeared in 1980. After public review it became the ANSI standard in 1983, which is why the first version is called Ada 83, and an ISO standard in 1987. Since then the language has been revised roughly once a decade, each time keeping old programs working:

VersionStandardMajor additions
Ada 83ANSI 1983, ISO 1987strong typing, packages, generics, exceptions, tasks
Ada 95ISO/IEC 8652:1995object orientation with tagged types, protected objects, child packages
Ada 2005amendment, 2007interfaces, the containers library, the Ravenscar profile for real-time systems
Ada 2012ISO/IEC 8652:2012contracts (Pre, Post, invariants, predicates), expression functions, for … of loops
Ada 2022ISO/IEC 8652:2023'Image for every type, delta and bracket aggregates, declare expressions, parallel constructs, big numbers

Ada 95, designed by a team led by Tucker Taft, is often cited as the first object-oriented language to have an ISO standard. For a decade (1987 to 1997) the DoD required Ada for new systems; when the requirement was dropped, Ada stayed where its strengths mattered most.

Today Ada is found in avionics on many commercial and military aircraft, in railway signalling and train-control systems, in air-traffic management, in satellites and launch vehicles, in defence systems, and in medical and industrial equipment. Its formally verifiable subset, SPARK, has spread further, including to companies writing security-critical firmware; AdaCore's SPARK page links to their case studies. The free compiler, GNAT, began at New York University in the early 1990s and is part of GCC, the GNU Compiler Collection; the company AdaCore, founded by its authors, maintains it with the community.

The design goals that run through every version are worth keeping in mind as you learn: reliability and maintainability (programs are read far more often than written, so readability beats brevity), programming as a human activity (the language should help people avoid and find their mistakes), and efficiency (safety checks should be cheap, and a compiler should be able to remove those it can prove unnecessary).

ComputationC

Installing GNAT and running a first program

Installing the toolchain

The Ada community recommends Alire, whose command is alr. Download it for your system from alire.ada.dev, put alr on your path, and ask it for a toolchain:

bash
alr toolchain --select        # choose a native GNAT and gprbuild; the defaults are fine
alr init --bin hello          # create a new executable project called hello
cd hello
alr run                       # build it and run it

Alire downloads the GNAT compiler and gprbuild, the project builder, into its own directory, so they do not interfere with anything else on your machine. On Debian or Ubuntu you can instead install the distribution's packages with sudo apt install gnat gprbuild; on Windows and macOS, Alire is the simplest route. For editing, the free GNAT Studio IDE and Visual Studio Code with AdaCore's Ada and SPARK extension both understand Ada projects. Lesson 5 shows what an Alire project looks like inside; until then we work with single files.

Hello, Ada

Save this as main.adb:

ada
with Ada.Text_IO;

procedure Main is
begin
   Ada.Text_IO.Put_Line ("Hello, Ada!");
end Main;

Compile and run it:

bash
gnatmake main.adb
./main
text
Hello, Ada!

Line by line:

  • with Ada.Text_IO; is a context clause. It says this unit depends on the standard package Ada.Text_IO, which handles text input and output. Nothing is pasted in, as with C's #include: the compiler reads the package's specification and checks every use of it.
  • procedure Main is begins the main program. In Ada the main program is simply a procedure with no parameters; its name is your choice, and the file is named after it in lower case (main.adb; the b stands for body).
  • Between is and begin comes the declarative part, where you declare variables, constants, types and nested subprograms. Here it is empty.
  • Between begin and end come the statements. Ada.Text_IO.Put_Line prints a string followed by a line break. Strings are in double quotes; each statement ends with a semicolon.
  • end Main; closes the procedure. Repeating the name is optional but customary, and the compiler checks that it matches.

gnatmake does three jobs in a row. It compiles each unit that is out of date, producing an object file (main.o) and an Ada library information file (main.ali) that records what the unit depends on. It binds: the binder, gnatbind, checks that every unit was compiled consistently and works out the order in which packages must be initialised. Then it links everything into the executable main. The binding step is a mark of Ada's character: the toolchain refuses to build a program from parts compiled against different versions of an interface.

The shape of every Ada program

Ada is not case-sensitive: Put_Line, PUT_LINE and put_line are the same name. The convention, which the style checker enforces if you ask it to, is Mixed_Case_With_Underscores for names and lower case for reserved words such as procedure, begin and loop. Comments start with -- and run to the end of the line. Indentation of three spaces is the traditional GNAT style.

Writing Ada.Text_IO. before every call gets tiresome. A use clause makes the package's names directly visible:

ada
with Ada.Text_IO; use Ada.Text_IO;

Professionals use use freely for the standard input/output packages and more carefully elsewhere, because a fully qualified name such as Sensors.Read tells the reader exactly where a subprogram comes from.

Worked examplesH

Declarations, loops and output

A program with some work to do shows the separation between declarations and statements. This one prints triangle numbers, the running totals 1, 1 + 2, 1 + 2 + 3, and so on, in two aligned columns:

ada
with Ada.Text_IO;         use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure Main is
   Rows  : constant := 8;    -- a named number: no type, known at compile time
   Total : Integer := 0;
begin
   Put_Line ("  n  triangle");
   for N in 1 .. Rows loop
      Total := Total + N;
      Put (N, Width => 3);
      Put (Total, Width => 10);
      New_Line;
   end loop;
   Put_Line ("The last triangle number is" & Integer'Image (Total) & ".");
end Main;

It prints:

text
  n  triangle
  1         1
  2         3
  3         6
  4        10
  5        15
  6        21
  7        28
  8        36
The last triangle number is 36.

Several things here are typically Ada:

  • Declarations come first, each with a type: Total : Integer := 0; reads "Total is an Integer, initially 0". Assignment is :=; a single = is only ever a comparison.
  • Rows : constant := 8; is a named number, a constant with no particular type that the compiler knows exactly. constant Integer := 8 would also work; named numbers are handy for values like sizes and limits.
  • The loop variable N is declared by the for loop itself, exists only inside it, and cannot be assigned to. 1 .. Rows is a range, a word you will meet everywhere in Ada.
  • Ada.Integer_Text_IO.Put prints an integer, and its Width parameter pads it on the left. Width => 3 is named parameter association: you may name the parameter you are giving a value to, which makes calls self-describing.
  • & joins strings. Ada never converts a number to a string implicitly, so Integer'Image (Total) does it explicitly.

The Image attribute

An attribute is a property of a type or object, written with an apostrophe: Integer'Image, Integer'First, Integer'Last. 'Image turns a value into its text form. Since Ada 2022 you can apply it directly to an object, Total'Image, and to values of any type, not only numbers. GNAT 14 compiles Ada 2012 by default, so programs that use Ada 2022 features in this course begin with pragma Ada_2022;, a directive to the compiler. (In an Alire project you would put the switch -gnat2022 in the project file instead.)

ada
pragma Ada_2022;
with Ada.Text_IO; use Ada.Text_IO;

procedure Main is
   Cities     : constant Integer := 3;
   Rain_Today : constant Integer := -2;   -- a change since yesterday, in mm
   Ratio      : constant Float := 2.0 / 3.0;
begin
   Put_Line ("[" & Cities'Image & "]");
   Put_Line ("[" & Rain_Today'Image & "]");
   Put_Line ("[" & Ratio'Image & "]");
   Put_Line ("[" & Boolean'Image (Cities > 2) & "]");
end Main;

It prints:

text
[ 3]
[-2]
[ 6.66667E-01]
[TRUE]

Two surprises deserve a word. 'Image of a non-negative number starts with a space, where a minus sign would go, so that columns of positive and negative numbers line up; it is a deliberate rule of the standard, and the reason the triangle program needed no space before Integer'Image (Total). And 'Image of a floating-point number uses scientific notation, 6.66667E-01 meaning 6.66667 × 10⁻¹. For human-friendly numbers you use the Put procedures of the text input/output packages, which take Fore, Aft and Exp parameters for the digits before and after the point and the exponent; the next lesson uses them.

A first meeting with the type checker

Ada does not mix types silently. This program does not compile:

ada
with Ada.Text_IO; use Ada.Text_IO;

procedure Main is
   Count : Integer := 10;
   Mean  : Float;
begin
   Mean := Count / 4;
   Put_Line (Float'Image (Mean));
end Main;

GNAT 14 reports:

text
main.adb:7:18: error: expected type "Standard.Float"
main.adb:7:18: error: found type "Standard.Integer"

Line 7, column 18 is the division. Count / 4 is an integer division whose result is the integer 2, and Ada will not quietly turn it into a Float, let alone guess that you meant 2.5. You must convert explicitly, and decide where: Mean := Float (Count) / 4.0; gives 2.5. Beginners from other languages find this fussy for about a week. After that, most find it a relief: every conversion in an Ada program is visible, so none is accidental.

ExplanationH

How Ada programmers work

Professional Ada code is written for its readers. Names are full words (Passenger_Count, not pc), subprogram calls often use named parameters, and the end of every construct repeats what it ends (end loop, end if, end Main). It is more typing than in C, and a good editor does most of it; the payoff is code that a reviewer or auditor can read without guessing.

Three compiler switches are worth knowing from the start. With gnatmake you type them on the command line; in a project they live in the project file:

  • -gnatwa turns on most of GNAT's optional warnings, such as variables that are assigned but never read, or conditions that are always true.
  • -gnata enables the run-time checking of assertions and contracts, which Lesson 7 is about.
  • -gnaty checks layout and naming style, so that a whole team's code looks the same.

GNAT's error messages are worth reading closely. Each starts with file:line:column, says what was expected and what was found, and often suggests a fix. The compiler catches far more than a C compiler would, and Ada programmers rely on that: a common saying is that once an Ada program compiles, it is much closer to working than in most languages. That is true but not magic. It holds because you told the compiler more about your intent, through types and contracts, so it could check more.

Finally, Ada programs are built from packages, and real projects split each package into a specification file (.ads) and a body file (.adb), built with gprbuild and managed with Alire. In this course every complete program is a single file containing procedure Main, with any packages declared inside it, so that you can compile it with one command. Lesson 5 shows how the same code is laid out in a real project.

Common misconceptionsH

Common misunderstandings

Misconception

"Ada is a dead military language." The DoD stopped requiring Ada in 1997, but the language kept evolving: Ada 2012 and Ada 2022 are modern standards, GNAT is part of GCC, Alire's catalogue grows every year, and Ada and SPARK are chosen for new projects in aviation, rail, space and security. It is a specialist language, not a dead one.

Misconception

"Run-time checks make Ada slow." Range and index checks cost little, and the compiler removes those it can prove unnecessary; in a tight loop over an array's own index range, for example, there is nothing left to check. Ada compiles to native code through the same back end as GCC's C compiler. Where checks must go entirely, they can be switched off, or better, proved unnecessary with SPARK.

Misconception

"Ada is just Pascal with more keywords." Ada borrowed Pascal's readable, block-structured syntax, and the two look alike at first glance. But Ada added packages with separate specifications, generics, exceptions, tasks, and later object orientation and contracts, and it is defined by an international standard with a conformance test suite. Its scope is much closer to that of C++ or Rust.

Misconception

"= assigns." In Ada, := assigns and = only compares. Writing if X := 3 then is a syntax error, so the classic C bug of assigning inside a condition cannot happen.

Exercises

Exercises

All outputs below were checked by compiling and running the code with GNAT 14.

1. First steps in Ada

Warm-upHuman

Whose design won the US Department of Defense's competition and became Ada?

Choose one

2. First steps in Ada

Warm-upComputational

What does Put_Line ("[" & Integer'Image (42) & "]"); print? Type the whole line, brackets included.

3. First steps in Ada

CoreComputational

What does Put_Line (Integer'Image (-7) & Integer'Image (7)); print?

4. First steps in Ada

CoreComputational

In the triangle-number program, Rows is changed to 10. What number does the last line report?

5. First steps in Ada

CoreHuman

Which steps does gnatmake main.adb carry out?

Choose one

6. First steps in Ada

CoreComputational

Count is an Integer equal to 10 and Mean is a Float. Which assignment compiles and sets Mean to 2.5?

Choose one

7. First steps in Ada

Warm-upHuman

After with Ada.Text_IO; use Ada.Text_IO;, does the statement PUT_LINE ("shout"); compile?

Choose one

Further reading and resources