Command Line Arguments in Ada

Our program demonstrates how to handle command-line arguments. Here’s the full source code:

with Ada.Text_IO;
with Ada.Command_Line;

procedure Command_Line_Arguments is
   use Ada.Text_IO;
   use Ada.Command_Line;

   Args_With_Prog : constant String := Command_Name;
   Args_Without_Prog : constant String := Command_Line(1 .. Argument_Count);
   Arg : constant String := Argument(3);
begin
   Put_Line("Args with program: " & Args_With_Prog);
   Put_Line("Args without program: " & Args_Without_Prog);
   Put_Line("Third argument: " & Arg);
end Command_Line_Arguments;

In Ada, we use the Ada.Command_Line package to access command-line arguments. The Command_Name function provides the name of the program (equivalent to os.Args[0] in the original example), while Argument_Count gives the number of arguments, and Argument(N) returns the Nth argument.

To build and run the program:

$ gnatmake command_line_arguments.adb
$ ./command_line_arguments a b c d
Args with program: ./command_line_arguments
Args without program: a b c d
Third argument: c

Note that Ada’s array indexing starts at 1, not 0, so Argument(3) gives us the third argument after the program name.

This example shows basic command-line argument handling. For more advanced needs, Ada provides additional facilities through various libraries.

Next, we might explore more sophisticated command-line processing using Ada’s GNAT.Command_Line package, which offers functionality similar to flag-based argument parsing in other languages.