GNAT User's Guide for Native Platforms / Unix and Windows


Next: , Previous: (dir), Up: (dir)

GNAT User's Guide

GNAT User's Guide for Native Platforms / Unix and Windows

GNAT, The GNU Ada 95 Compiler
GCC version 3.4.6

Ada Core Technologies, Inc.

--- The Detailed Node Listing ---

About This Guide

Getting Started with GNAT

The GNAT Compilation Model

Foreign Language Representation

Compiling Ada Programs With gcc

Switches for gcc

Binding Ada Programs With gnatbind

Switches for gnatbind

Linking Using gnatlink

The GNAT Make Program gnatmake

Improving Performance

Performance Considerations

Reducing the Size of Ada Executables with gnatelim

Renaming Files Using gnatchop

Configuration Pragmas

Handling Arbitrary File Naming Conventions Using gnatname

GNAT Project Manager

The Cross-Referencing Tools gnatxref and gnatfind

The GNAT Pretty-Printer gnatpp

File Name Krunching Using gnatkr

Preprocessing Using gnatprep

The GNAT Library Browser gnatls

Cleaning Up Using gnatclean

GNAT and Libraries

Using the GNU make Utility

Finding Memory Problems

The gnatmem Tool

The GNAT Debug Pool Facility

Creating Sample Bodies Using gnatstub

Other Utility Programs

Running and Debugging Ada Programs

Platform-Specific Information for the Run-Time Libraries

Example of Binder Output File

Elaboration Order Handling in GNAT

Inline Assembler

Compatibility and Porting Guide

Microsoft Windows Topics


Next: , Previous: Top, Up: Top

About This Guide

This guide describes the use of GNAT, a compiler and software development toolset for the full Ada 95 programming language. It describes the features of the compiler and tools, and details how to use them to build Ada 95 applications.


Next: , Up: About This Guide

What This Guide Contains

This guide contains the following chapters:


Next: , Previous: What This Guide Contains, Up: About This Guide

What You Should Know before Reading This Guide

This user's guide assumes that you are familiar with Ada 95 language, as described in the International Standard ANSI/ISO/IEC-8652:1995, January 1995.


Next: , Previous: What You Should Know before Reading This Guide, Up: About This Guide

Related Information

For further information about related tools, refer to the following documents:


Previous: Related Information, Up: About This Guide

Conventions

Following are examples of the typographical and graphic conventions used in this guide:

Commands that are entered by the user are preceded in this manual by the characters “ (dollar sign followed by space). If your system uses this sequence as a prompt, then the commands will appear exactly as you see them in the manual. If your system uses some other prompt, then the command will appear with the $ replaced by whatever prompt character you are using.

Full file names are shown with the “/” character as the directory separator; e.g., parent-dir/subdir/myfile.adb. If you are using GNAT on a Windows platform, please note that the “\” character should be used instead.


Next: , Previous: About This Guide, Up: Top

1 Getting Started with GNAT

This chapter describes some simple ways of using GNAT to build executable Ada programs. Running GNAT, through Using the gnatmake Utility, show how to use the command line environment. Introduction to Glide and GVD, provides a brief introduction to the visually-oriented IDE for GNAT. Supplementing Glide on some platforms is GPS, the GNAT Programming System, which offers a richer graphical “look and feel”, enhanced configurability, support for development in other programming language, comprehensive browsing features, and many other capabilities. For information on GPS please refer to Using the GNAT Programming System.


Next: , Up: Getting Started with GNAT

1.1 Running GNAT

Three steps are needed to create an executable file from an Ada source file:

  1. The source file(s) must be compiled.
  2. The file(s) must be bound using the GNAT binder.
  3. All appropriate object files must be linked to produce an executable.

All three steps are most commonly handled by using the gnatmake utility program that, given the name of the main program, automatically performs the necessary compilation, binding and linking steps.


Next: , Previous: Running GNAT, Up: Getting Started with GNAT

1.2 Running a Simple Ada Program

Any text editor may be used to prepare an Ada program. If Glide is used, the optional Ada mode may be helpful in laying out the program. The program text is a normal text file. We will suppose in our initial example that you have used your editor to prepare the following standard format text file:

     

with Ada.Text_IO; use Ada.Text_IO; procedure Hello is begin Put_Line ("Hello WORLD!"); end Hello;

This file should be named hello.adb. With the normal default file naming conventions, GNAT requires that each file contain a single compilation unit whose file name is the unit name, with periods replaced by hyphens; the extension is ads for a spec and adb for a body. You can override this default file naming convention by use of the special pragma Source_File_Name (see Using Other File Names). Alternatively, if you want to rename your files according to this default convention, which is probably more convenient if you will be using GNAT for all your compilations, then the gnatchop utility can be used to generate correctly-named source files (see Renaming Files Using gnatchop).

You can compile the program using the following command ($ is used as the command prompt in the examples in this document):

     $ gcc -c hello.adb

gcc is the command used to run the compiler. This compiler is capable of compiling programs in several languages, including Ada 95 and C. It assumes that you have given it an Ada program if the file extension is either .ads or .adb, and it will then call the GNAT compiler to compile the specified file.

The -c switch is required. It tells gcc to only do a compilation. (For C programs, gcc can also do linking, but this capability is not used directly for Ada programs, so the -c switch must always be present.)

This compile command generates a file hello.o, which is the object file corresponding to your Ada program. It also generates an “Ada Library Information” file hello.ali, which contains additional information used to check that an Ada program is consistent. To build an executable file, use gnatbind to bind the program and gnatlink to link it. The argument to both gnatbind and gnatlink is the name of the ALI file, but the default extension of .ali can be omitted. This means that in the most common case, the argument is simply the name of the main program:

     $ gnatbind hello
     $ gnatlink hello

A simpler method of carrying out these steps is to use gnatmake, a master program that invokes all the required compilation, binding and linking tools in the correct order. In particular, gnatmake automatically recompiles any sources that have been modified since they were last compiled, or sources that depend on such modified sources, so that “version skew” is avoided.

     $ gnatmake hello.adb

The result is an executable program called hello, which can be run by entering:

     $ hello

assuming that the current directory is on the search path for executable programs.

and, if all has gone well, you will see

     Hello WORLD!

appear in response to this command.


Next: , Previous: Running a Simple Ada Program, Up: Getting Started with GNAT

1.3 Running a Program with Multiple Units

Consider a slightly more complicated example that has three files: a main program, and the spec and body of a package:

     

package Greetings is procedure Hello; procedure Goodbye; end Greetings; with Ada.Text_IO; use Ada.Text_IO; package body Greetings is procedure Hello is begin Put_Line ("Hello WORLD!"); end Hello; procedure Goodbye is begin Put_Line ("Goodbye WORLD!"); end Goodbye; end Greetings;

with Greetings; procedure Gmain is begin Greetings.Hello; Greetings.Goodbye; end Gmain;

Following the one-unit-per-file rule, place this program in the following three separate files:

greetings.ads
spec of package Greetings
greetings.adb
body of package Greetings
gmain.adb
body of main program

To build an executable version of this program, we could use four separate steps to compile, bind, and link the program, as follows:

     $ gcc -c gmain.adb
     $ gcc -c greetings.adb
     $ gnatbind gmain
     $ gnatlink gmain

Note that there is no required order of compilation when using GNAT. In particular it is perfectly fine to compile the main program first. Also, it is not necessary to compile package specs in the case where there is an accompanying body; you only need to compile the body. If you want to submit these files to the compiler for semantic checking and not code generation, then use the -gnatc switch:

     $ gcc -c greetings.ads -gnatc

Although the compilation can be done in separate steps as in the above example, in practice it is almost always more convenient to use the gnatmake tool. All you need to know in this case is the name of the main program's source file. The effect of the above four commands can be achieved with a single one:

     $ gnatmake gmain.adb

In the next section we discuss the advantages of using gnatmake in more detail.


Next: , Previous: Running a Program with Multiple Units, Up: Getting Started with GNAT

1.4 Using the gnatmake Utility

If you work on a program by compiling single components at a time using gcc, you typically keep track of the units you modify. In order to build a consistent system, you compile not only these units, but also any units that depend on the units you have modified. For example, in the preceding case, if you edit gmain.adb, you only need to recompile that file. But if you edit greetings.ads, you must recompile both greetings.adb and gmain.adb, because both files contain units that depend on greetings.ads.

gnatbind will warn you if you forget one of these compilation steps, so that it is impossible to generate an inconsistent program as a result of forgetting to do a compilation. Nevertheless it is tedious and error-prone to keep track of dependencies among units. One approach to handle the dependency-bookkeeping is to use a makefile. However, makefiles present maintenance problems of their own: if the dependencies change as you change the program, you must make sure that the makefile is kept up-to-date manually, which is also an error-prone process.

The gnatmake utility takes care of these details automatically. Invoke it using either one of the following forms:

     $ gnatmake gmain.adb
     $ gnatmake gmain

The argument is the name of the file containing the main program; you may omit the extension. gnatmake examines the environment, automatically recompiles any files that need recompiling, and binds and links the resulting set of object files, generating the executable file, gmain. In a large program, it can be extremely helpful to use gnatmake, because working out by hand what needs to be recompiled can be difficult.

Note that gnatmake takes into account all the Ada 95 rules that establish dependencies among units. These include dependencies that result from inlining subprogram bodies, and from generic instantiation. Unlike some other Ada make tools, gnatmake does not rely on the dependencies that were found by the compiler on a previous compilation, which may possibly be wrong when sources change. gnatmake determines the exact set of dependencies from scratch each time it is run.


Next: , Previous: Using the gnatmake Utility, Up: Getting Started with GNAT

1.5 Introduction to GPS

Although the command line interface (gnatmake, etc.) alone is sufficient, a graphical Interactive Development Environment can make it easier for you to compose, navigate, and debug programs. This section describes the main features of GPS (“GNAT Programming System”), the GNAT graphical IDE. You will see how to use GPS to build and debug an executable, and you will also learn some of the basics of the GNAT “project” facility.

GPS enables you to do much more than is presented here; e.g., you can produce a call graph, interface to a third-party Version Control System, and inspect the generated assembly language for a program. Indeed, GPS also supports languages other than Ada. Such additional information, and an explanation of all of the GPS menu items. may be found in the on-line help, which includes a user's guide and a tutorial (these are also accessible from the GNAT startup menu).


Next: , Up: Introduction to GPS

1.5.1 Building a New Program with GPS

GPS invokes the GNAT compilation tools using information contained in a project (also known as a project file): a collection of properties such as source directories, identities of main subprograms, tool switches, etc., and their associated values. (See GNAT Project Manager, for details.) In order to run GPS, you will need to either create a new project or else open an existing one.

This section will explain how you can use GPS to create a project, to associate Ada source files with a project, and to build and run programs.

  1. Creating a project

    Invoke GPS, either from the command line or the platform's IDE. After it starts, GPS will display a “Welcome” screen with three radio buttons:

    Select Create new project with wizard and press OK. A new window will appear. In the text box labeled with Enter the name of the project to create, type sample as the project name. In the next box, browse to choose the directory in which you would like to create the project file. After selecting an appropriate directory, press Forward.

    A window will appear with the title Version Control System Configuration. Simply press Forward.

    A window will appear with the title Please select the source directories for this project. The directory that you specified for the project file will be selected by default as the one to use for sources; simply press Forward.

    A window will appear with the title Please select the build directory for this project. The directory that you specified for the project file will be selected by default for object files and executables; simply press Forward.

    A window will appear with the title Please select the main units for this project. You will supply this information later, after creating the source file. Simply press Forward for now.

    A window will appear with the title Please select the switches to build the project. Press Apply. This will create a project file named sample.prj in the directory that you had specified.

  2. Creating and saving the source file

    After you create the new project, a GPS window will appear, which is partitioned into two main sections:

    Select File on the menu bar, and then the New command. The Workspace area will become white, and you can now enter the source program explicitly. Type the following text

              with Ada.Text_IO; use Ada.Text_IO;
              procedure Hello is
              begin
                Put_Line("Hello from GPS!");
              end Hello;
         

    Select File, then Save As, and enter the source file name hello.adb. The file will be saved in the same directory you specified as the location of the default project file.

  3. Updating the project file

    You need to add the new source file to the project. To do this, select the Project menu and then Edit project properties. Click the Main files tab on the left, and then the Add button. Choose hello.adb from the list, and press Open. The project settings window will reflect this action. Click OK.

  4. Building and running the program

    In the main GPS window, now choose the Build menu, then Make, and select hello.adb. The Messages window will display the resulting invocations of gcc, gnatbind, and gnatlink (reflecting the default switch settings from the project file that you created) and then a “successful compilation/build” message.

    To run the program, choose the Build menu, then Run, and select hello. An Arguments Selection window will appear. There are no command line arguments, so just click OK.

    The Messages window will now display the program's output (the string Hello from GPS), and at the bottom of the GPS window a status update is displayed (Run: hello). Close the GPS window (or select File, then Exit) to terminate this GPS session.


Previous: Building a New Program with GPS, Up: Introduction to GPS

1.5.2 Simple Debugging with GPS

This section illustrates basic debugging techniques (setting breakpoints, examining/modifying variables, single stepping).

  1. Opening a project

    Start GPS and select Open existing project; browse to specify the project file sample.prj that you had created in the earlier example.

  2. Creating a source file

    Select File, then New, and type in the following program:

              with Ada.Text_IO; use Ada.Text_IO;
              procedure Example is
                 Line : String (1..80);
                 N    : Natural;
              begin
                 Put_Line("Type a line of text at each prompt; an empty line to exit");
                 loop
                    Put(": ");
                    Get_Line (Line, N);
                    Put_Line (Line (1..N) );
                    exit when N=0;
                 end loop;
              end Example;
         

    Select File, then Save as, and enter the file name example.adb.

  3. Updating the project file

    Add Example as a new main unit for the project:

    1. Select Project, then Edit Project Properties.
    2. Select the Main files tab, click Add, then select the file example.adb from the list, and click Open. You will see the file name appear in the list of main units
    3. Click OK
  4. Building/running the executable

    To build the executable select Build, then Make, and then choose example.adb.

    Run the program to see its effect (in the Messages area). Each line that you enter is displayed; an empty line will cause the loop to exit and the program to terminate.

  5. Debugging the program

    Note that the -g switches to gcc and gnatlink, which are required for debugging, are on by default when you create a new project. Thus unless you intentionally remove these settings, you will be able to debug any program that you develop using GPS.

    1. Initializing

      Select Debug, then Initialize, then example

    2. Setting a breakpoint

      After performing the initialization step, you will observe a small icon to the right of each line number. This serves as a toggle for breakpoints; clicking the icon will set a breakpoint at the corresponding line (the icon will change to a red circle with an “x”), and clicking it again will remove the breakpoint / reset the icon.

      For purposes of this example, set a breakpoint at line 10 (the statement Put_Line (Line (1..N));

    3. Starting program execution

      Select Debug, then Run. When the Program Arguments window appears, click OK. A console window will appear; enter some line of text, e.g. abcde, at the prompt. The program will pause execution when it gets to the breakpoint, and the corresponding line is highlighted.

    4. Examining a variable

      Move the mouse over one of the occurrences of the variable N. You will see the value (5) displayed, in “tool tip” fashion. Right click on N, select Debug, then select Display N. You will see information about N appear in the Debugger Data pane, showing the value as 5.

    5. Assigning a new value to a variable

      Right click on the N in the Debugger Data pane, and select Set value of N. When the input window appears, enter the value 4 and click OK. This value does not automatically appear in the Debugger Data pane; to see it, right click again on the N in the Debugger Data pane and select Update value. The new value, 4, will appear in red.

    6. Single stepping

      Select Debug, then Next. This will cause the next statement to be executed, in this case the call of Put_Line with the string slice. Notice in the console window that the displayed string is simply abcd and not abcde which you had entered. This is because the upper bound of the slice is now 4 rather than 5.

    7. Removing a breakpoint

      Toggle the breakpoint icon at line 10.

    8. Resuming execution from a breakpoint

      Select Debug, then Continue. The program will reach the next iteration of the loop, and wait for input after displaying the prompt. This time, just hit the Enter key. The value of N will be 0, and the program will terminate. The console window will disappear.


Previous: Introduction to GPS, Up: Getting Started with GNAT

1.6 Introduction to Glide and GVD

This section describes the main features of Glide, a GNAT graphical IDE, and also shows how to use the basic commands in GVD, the GNU Visual Debugger. These tools may be present in addition to, or in place of, GPS on some platforms. Additional information on Glide and GVD may be found in the on-line help for these tools.


Next: , Up: Introduction to Glide and GVD

1.6.1 Building a New Program with Glide

The simplest way to invoke Glide is to enter glide at the command prompt. It will generally be useful to issue this as a background command, thus allowing you to continue using your command window for other purposes while Glide is running:

     $ glide&

Glide will start up with an initial screen displaying the top-level menu items as well as some other information. The menu selections are as follows

For this introductory example, you will need to create a new Ada source file. First, select the Files menu. This will pop open a menu with around a dozen or so items. To create a file, select the Open file... choice. Depending on the platform, you may see a pop-up window where you can browse to an appropriate directory and then enter the file name, or else simply see a line at the bottom of the Glide window where you can likewise enter the file name. Note that in Glide, when you attempt to open a non-existent file, the effect is to create a file with that name. For this example enter hello.adb as the name of the file.

A new buffer will now appear, occupying the entire Glide window, with the file name at the top. The menu selections are slightly different from the ones you saw on the opening screen; there is an Entities item, and in place of Glide there is now an Ada item. Glide uses the file extension to identify the source language, so adb indicates an Ada source file.

You will enter some of the source program lines explicitly, and use the syntax-oriented template mechanism to enter other lines. First, type the following text:

     with Ada.Text_IO; use Ada.Text_IO;
     procedure Hello is
     begin

Observe that Glide uses different colors to distinguish reserved words from identifiers. Also, after the procedure Hello is line, the cursor is automatically indented in anticipation of declarations. When you enter begin, Glide recognizes that there are no declarations and thus places begin flush left. But after the begin line the cursor is again indented, where the statement(s) will be placed.

The main part of the program will be a for loop. Instead of entering the text explicitly, however, use a statement template. Select the Ada item on the top menu bar, move the mouse to the Statements item, and you will see a large selection of alternatives. Choose for loop. You will be prompted (at the bottom of the buffer) for a loop name; simply press the <Enter> key since a loop name is not needed. You should see the beginning of a for loop appear in the source program window. You will now be prompted for the name of the loop variable; enter a line with the identifier ind (lower case). Note that, by default, Glide capitalizes the name (you can override such behavior if you wish, although this is outside the scope of this introduction). Next, Glide prompts you for the loop range; enter a line containing 1..5 and you will see this also appear in the source program, together with the remaining elements of the for loop syntax.

Next enter the statement (with an intentional error, a missing semicolon) that will form the body of the loop:

     Put_Line("Hello, World" & Integer'Image(I))

Finally, type end Hello; as the last line in the program. Now save the file: choose the File menu item, and then the Save buffer selection. You will see a message at the bottom of the buffer confirming that the file has been saved.

You are now ready to attempt to build the program. Select the Ada item from the top menu bar. Although we could choose simply to compile the file, we will instead attempt to do a build (which invokes gnatmake) since, if the compile is successful, we want to build an executable. Thus select Ada build. This will fail because of the compilation error, and you will notice that the Glide window has been split: the top window contains the source file, and the bottom window contains the output from the GNAT tools. Glide allows you to navigate from a compilation error to the source file position corresponding to the error: click the middle mouse button (or simultaneously press the left and right buttons, on a two-button mouse) on the diagnostic line in the tool window. The focus will shift to the source window, and the cursor will be positioned on the character at which the error was detected.

Correct the error: type in a semicolon to terminate the statement. Although you can again save the file explicitly, you can also simply invoke Ada => Build and you will be prompted to save the file. This time the build will succeed; the tool output window shows you the options that are supplied by default. The GNAT tools' output (e.g. object and ALI files, executable) will go in the directory from which Glide was launched.

To execute the program, choose Ada and then Run. You should see the program's output displayed in the bottom window:

     Hello, world 1
     Hello, world 2
     Hello, world 3
     Hello, world 4
     Hello, world 5


Next: , Previous: Building a New Program with Glide, Up: Introduction to Glide and GVD

1.6.2 Simple Debugging with GVD

This section describes how to set breakpoints, examine/modify variables, and step through execution.

In order to enable debugging, you need to pass the -g switch to both the compiler and to gnatlink. If you are using the command line, passing -g to gnatmake will have this effect. You can then launch GVD, e.g. on the hello program, by issuing the command:

     $ gvd hello

If you are using Glide, then -g is passed to the relevant tools by default when you do a build. Start the debugger by selecting the Ada menu item, and then Debug.

GVD comes up in a multi-part window. One pane shows the names of files comprising your executable; another pane shows the source code of the current unit (initially your main subprogram), another pane shows the debugger output and user interactions, and the fourth pane (the data canvas at the top of the window) displays data objects that you have selected.

To the left of the source file pane, you will notice green dots adjacent to some lines. These are lines for which object code exists and where breakpoints can thus be set. You set/reset a breakpoint by clicking the green dot. When a breakpoint is set, the dot is replaced by an X in a red circle. Clicking the circle toggles the breakpoint off, and the red circle is replaced by the green dot.

For this example, set a breakpoint at the statement where Put_Line is invoked.

Start program execution by selecting the Run button on the top menu bar. (The Start button will also start your program, but it will cause program execution to break at the entry to your main subprogram.) Evidence of reaching the breakpoint will appear: the source file line will be highlighted, and the debugger interactions pane will display a relevant message.

You can examine the values of variables in several ways. Move the mouse over an occurrence of Ind in the for loop, and you will see the value (now 1) displayed. Alternatively, right-click on Ind and select Display Ind; a box showing the variable's name and value will appear in the data canvas.

Although a loop index is a constant with respect to Ada semantics, you can change its value in the debugger. Right-click in the box for Ind, and select the Set Value of Ind item. Enter 2 as the new value, and press OK. The box for Ind shows the update.

Press the Step button on the top menu bar; this will step through one line of program text (the invocation of Put_Line), and you can observe the effect of having modified Ind since the value displayed is 2.

Remove the breakpoint, and resume execution by selecting the Cont button. You will see the remaining output lines displayed in the debugger interaction window, along with a message confirming normal program termination.


Previous: Simple Debugging with GVD, Up: Introduction to Glide and GVD

1.6.3 Other Glide Features

You may have observed that some of the menu selections contain abbreviations; e.g., (C-x C-f) for Open file... in the Files menu. These are shortcut keys that you can use instead of selecting menu items. The <C> stands for <Ctrl>; thus (C-x C-f) means <Ctrl-x> followed by <Ctrl-f>, and this sequence can be used instead of selecting Files and then Open file....

To abort a Glide command, type <Ctrl-g>.

If you want Glide to start with an existing source file, you can either launch Glide as above and then open the file via Files => Open file..., or else simply pass the name of the source file on the command line:

     $ glide hello.adb&

While you are using Glide, a number of buffers exist. You create some explicitly; e.g., when you open/create a file. Others arise as an effect of the commands that you issue; e.g., the buffer containing the output of the tools invoked during a build. If a buffer is hidden, you can bring it into a visible window by first opening the Buffers menu and then selecting the desired entry.

If a buffer occupies only part of the Glide screen and you want to expand it to fill the entire screen, then click in the buffer and then select Files => One Window.

If a window is occupied by one buffer and you want to split the window to bring up a second buffer, perform the following steps:

To exit from Glide, choose Files => Exit.


Next: , Previous: Getting Started with GNAT, Up: Top

2 The GNAT Compilation Model

This chapter describes the compilation model used by GNAT. Although similar to that used by other languages, such as C and C++, this model is substantially different from the traditional Ada compilation models, which are based on a library. The model is initially described without reference to the library-based model. If you have not previously used an Ada compiler, you need only read the first part of this chapter. The last section describes and discusses the differences between the GNAT model and the traditional Ada compiler models. If you have used other Ada compilers, this section will help you to understand those differences, and the advantages of the GNAT model.


Next: , Up: The GNAT Compilation Model

2.1 Source Representation

Ada source programs are represented in standard text files, using Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar 7-bit ASCII set, plus additional characters used for representing foreign languages (see Foreign Language Representation for support of non-USA character sets). The format effector characters are represented using their standard ASCII encodings, as follows:

VT
Vertical tab, 16#0B#
HT
Horizontal tab, 16#09#
CR
Carriage return, 16#0D#
LF
Line feed, 16#0A#
FF
Form feed, 16#0C#

Source files are in standard text file format. In addition, GNAT will recognize a wide variety of stream formats, in which the end of physical physical lines is marked by any of the following sequences: LF, CR, CR-LF, or LF-CR. This is useful in accommodating files that are imported from other operating systems.

The end of a source file is normally represented by the physical end of file. However, the control character 16#1A# (SUB) is also recognized as signalling the end of the source file. Again, this is provided for compatibility with other operating systems where this code is used to represent the end of file.

Each file contains a single Ada compilation unit, including any pragmas associated with the unit. For example, this means you must place a package declaration (a package spec) and the corresponding body in separate files. An Ada compilation (which is a sequence of compilation units) is represented using a sequence of files. Similarly, you will place each subunit or child unit in a separate file.


Next: , Previous: Source Representation, Up: The GNAT Compilation Model

2.2 Foreign Language Representation

GNAT supports the standard character sets defined in Ada 95 as well as several other non-standard character sets for use in localized versions of the compiler (see Character Set Control).


Next: , Up: Foreign Language Representation

2.2.1 Latin-1

The basic character set is Latin-1. This character set is defined by ISO standard 8859, part 1. The lower half (character codes 16#00# ... 16#7F#) is identical to standard ASCII coding, but the upper half is used to represent additional characters. These include extended letters used by European languages, such as French accents, the vowels with umlauts used in German, and the extra letter A-ring used in Swedish.

For a complete list of Latin-1 codes and their encodings, see the source file of library unit Ada.Characters.Latin_1 in file a-chlat1.ads. You may use any of these extended characters freely in character or string literals. In addition, the extended characters that represent letters can be used in identifiers.


Next: , Previous: Latin-1, Up: Foreign Language Representation

2.2.2 Other 8-Bit Codes

GNAT also supports several other 8-bit coding schemes:

ISO 8859-2 (Latin-2)
Latin-2 letters allowed in identifiers, with uppercase and lowercase equivalence.
ISO 8859-3 (Latin-3)
Latin-3 letters allowed in identifiers, with uppercase and lowercase equivalence.
ISO 8859-4 (Latin-4)
Latin-4 letters allowed in identifiers, with uppercase and lowercase equivalence.
ISO 8859-5 (Cyrillic)
ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and lowercase equivalence.
ISO 8859-15 (Latin-9)
ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and lowercase equivalence
IBM PC (code page 437)
This code page is the normal default for PCs in the U.S. It corresponds to the original IBM PC character set. This set has some, but not all, of the extended Latin-1 letters, but these letters do not have the same encoding as Latin-1. In this mode, these letters are allowed in identifiers with uppercase and lowercase equivalence.
IBM PC (code page 850)
This code page is a modification of 437 extended to include all the Latin-1 letters, but still not with the usual Latin-1 encoding. In this mode, all these letters are allowed in identifiers with uppercase and lowercase equivalence.
Full Upper 8-bit
Any character in the range 80-FF allowed in identifiers, and all are considered distinct. In other words, there are no uppercase and lowercase equivalences in this range. This is useful in conjunction with certain encoding schemes used for some foreign character sets (e.g. the typical method of representing Chinese characters on the PC).
No Upper-Half
No upper-half characters in the range 80-FF are allowed in identifiers. This gives Ada 83 compatibility for identifier names.

For precise data on the encodings permitted, and the uppercase and lowercase equivalences that are recognized, see the file csets.adb in the GNAT compiler sources. You will need to obtain a full source release of GNAT to obtain this file.


Previous: Other 8-Bit Codes, Up: Foreign Language Representation

2.2.3 Wide Character Encodings

GNAT allows wide character codes to appear in character and string literals, and also optionally in identifiers, by means of the following possible encoding schemes:

Hex Coding
In this encoding, a wide character is represented by the following five character sequence:
          ESC a b c d
     

Where a, b, c, d are the four hexadecimal characters (using uppercase letters) of the wide character code. For example, ESC A345 is used to represent the wide character with code 16#A345#. This scheme is compatible with use of the full Wide_Character set.

Upper-Half Coding
The wide character with encoding 16#abcd# where the upper bit is on (in other words, “a” is in the range 8-F) is represented as two bytes, 16#ab# and 16#cd#. The second byte cannot be a format control character, but is not required to be in the upper half. This method can be also used for shift-JIS or EUC, where the internal coding matches the external coding.
Shift JIS Coding
A wide character is represented by a two-character sequence, 16#ab# and 16#cd#, with the restrictions described for upper-half encoding as described above. The internal character code is the corresponding JIS character according to the standard algorithm for Shift-JIS conversion. Only characters defined in the JIS code set table can be used with this encoding method.
EUC Coding
A wide character is represented by a two-character sequence 16#ab# and 16#cd#, with both characters being in the upper half. The internal character code is the corresponding JIS character according to the EUC encoding algorithm. Only characters defined in the JIS code set table can be used with this encoding method.
UTF-8 Coding
A wide character is represented using UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO 10646-1/Am.2. Depending on the character value, the representation is a one, two, or three byte sequence:
          16#0000#-16#007f#: 2#0xxxxxxx#
          16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
          16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
          
     

where the xxx bits correspond to the left-padded bits of the 16-bit character value. Note that all lower half ASCII characters are represented as ASCII bytes and all upper half characters and other wide characters are represented as sequences of upper-half (The full UTF-8 scheme allows for encoding 31-bit characters as 6-byte sequences, but in this implementation, all UTF-8 sequences of four or more bytes length will be treated as illegal).

Brackets Coding
In this encoding, a wide character is represented by the following eight character sequence:
          [ " a b c d " ]
     

Where a, b, c, d are the four hexadecimal characters (using uppercase letters) of the wide character code. For example, [“A345”] is used to represent the wide character with code 16#A345#. It is also possible (though not required) to use the Brackets coding for upper half characters. For example, the code 16#A3# can be represented as [``A3''].

This scheme is compatible with use of the full Wide_Character set, and is also the method used for wide character encoding in the standard ACVC (Ada Compiler Validation Capability) test suite distributions.

Note: Some of these coding schemes do not permit the full use of the Ada 95 character set. For example, neither Shift JIS, nor EUC allow the use of the upper half of the Latin-1 set.


Next: , Previous: Foreign Language Representation, Up: The GNAT Compilation Model

2.3 File Naming Rules

The default file name is determined by the name of the unit that the file contains. The name is formed by taking the full expanded name of the unit and replacing the separating dots with hyphens and using lowercase for all letters.

An exception arises if the file name generated by the above rules starts with one of the characters a,g,i, or s, and the second character is a minus. In this case, the character tilde is used in place of the minus. The reason for this special rule is to avoid clashes with the standard names for child units of the packages System, Ada, Interfaces, and GNAT, which use the prefixes s- a- i- and g- respectively.

The file extension is .ads for a spec and .adb for a body. The following list shows some examples of these rules.

main.ads
Main (spec)
main.adb
Main (body)
arith_functions.ads
Arith_Functions (package spec)
arith_functions.adb
Arith_Functions (package body)
func-spec.ads
Func.Spec (child package spec)
func-spec.adb
Func.Spec (child package body)
main-sub.adb
Sub (subunit of Main)
a~bad.adb
A.Bad (child package body)

Following these rules can result in excessively long file names if corresponding unit names are long (for example, if child units or subunits are heavily nested). An option is available to shorten such long file names (called file name “krunching”). This may be particularly useful when programs being developed with GNAT are to be used on operating systems with limited file name lengths. See Using gnatkr.

Of course, no file shortening algorithm can guarantee uniqueness over all possible unit names; if file name krunching is used, it is your responsibility to ensure no name clashes occur. Alternatively you can specify the exact file names that you want used, as described in the next section. Finally, if your Ada programs are migrating from a compiler with a different naming convention, you can use the gnatchop utility to produce source files that follow the GNAT naming conventions. (For details see Renaming Files Using gnatchop.)

Note: in the case of Windows NT/XP or OpenVMS operating systems, case is not significant. So for example on Windows XP if the canonical name is main-sub.adb, you can use the file name Main-Sub.adb instead. However, case is significant for other operating systems, so for example, if you want to use other than canonically cased file names on a Unix system, you need to follow the procedures described in the next section.


Next: , Previous: File Naming Rules, Up: The GNAT Compilation Model

2.4 Using Other File Names

In the previous section, we have described the default rules used by GNAT to determine the file name in which a given unit resides. It is often convenient to follow these default rules, and if you follow them, the compiler knows without being explicitly told where to find all the files it needs.

However, in some cases, particularly when a program is imported from another Ada compiler environment, it may be more convenient for the programmer to specify which file names contain which units. GNAT allows arbitrary file names to be used by means of the Source_File_Name pragma. The form of this pragma is as shown in the following examples:

     

pragma Source_File_Name (My_Utilities.Stacks, Spec_File_Name => "myutilst_a.ada"); pragma Source_File_name (My_Utilities.Stacks, Body_File_Name => "myutilst.ada");

As shown in this example, the first argument for the pragma is the unit name (in this example a child unit). The second argument has the form of a named association. The identifier indicates whether the file name is for a spec or a body; the file name itself is given by a string literal.

The source file name pragma is a configuration pragma, which means that normally it will be placed in the gnat.adc file used to hold configuration pragmas that apply to a complete compilation environment. For more details on how the gnat.adc file is created and used see Handling of Configuration Pragmas GNAT allows completely arbitrary file names to be specified using the source file name pragma. However, if the file name specified has an extension other than .ads or .adb it is necessary to use a special syntax when compiling the file. The name in this case must be preceded by the special sequence -x followed by a space and the name of the language, here ada, as in:

     $ gcc -c -x ada peculiar_file_name.sim

gnatmake handles non-standard file names in the usual manner (the non-standard file name for the main program is simply used as the argument to gnatmake). Note that if the extension is also non-standard, then it must be included in the gnatmake command, it may not be omitted.


Next: , Previous: Using Other File Names, Up: The GNAT Compilation Model

2.5 Alternative File Naming Schemes

In the previous section, we described the use of the Source_File_Name pragma to allow arbitrary names to be assigned to individual source files. However, this approach requires one pragma for each file, and especially in large systems can result in very long gnat.adc files, and also create a maintenance problem.

GNAT also provides a facility for specifying systematic file naming schemes other than the standard default naming scheme previously described. An alternative scheme for naming is specified by the use of Source_File_Name pragmas having the following format:

     pragma Source_File_Name (
        Spec_File_Name  => FILE_NAME_PATTERN
      [,Casing          => CASING_SPEC]
      [,Dot_Replacement => STRING_LITERAL]);
     
     pragma Source_File_Name (
        Body_File_Name  => FILE_NAME_PATTERN
      [,Casing          => CASING_SPEC]
      [,Dot_Replacement => STRING_LITERAL]);
     
     pragma Source_File_Name (
        Subunit_File_Name  => FILE_NAME_PATTERN
      [,Casing             => CASING_SPEC]
      [,Dot_Replacement    => STRING_LITERAL]);
     
     FILE_NAME_PATTERN ::= STRING_LITERAL
     CASING_SPEC ::= Lowercase | Uppercase | Mixedcase

The FILE_NAME_PATTERN string shows how the file name is constructed. It contains a single asterisk character, and the unit name is substituted systematically for this asterisk. The optional parameter Casing indicates whether the unit name is to be all upper-case letters, all lower-case letters, or mixed-case. If no Casing parameter is used, then the default is all lower-case.

The optional Dot_Replacement string is used to replace any periods that occur in subunit or child unit names. If no Dot_Replacement argument is used then separating dots appear unchanged in the resulting file name. Although the above syntax indicates that the Casing argument must appear before the Dot_Replacement argument, but it is also permissible to write these arguments in the opposite order.

As indicated, it is possible to specify different naming schemes for bodies, specs, and subunits. Quite often the rule for subunits is the same as the rule for bodies, in which case, there is no need to give a separate Subunit_File_Name rule, and in this case the Body_File_name rule is used for subunits as well.

The separate rule for subunits can also be used to implement the rather unusual case of a compilation environment (e.g. a single directory) which contains a subunit and a child unit with the same unit name. Although both units cannot appear in the same partition, the Ada Reference Manual allows (but does not require) the possibility of the two units coexisting in the same environment.

The file name translation works in the following steps:

As an example of the use of this mechanism, consider a commonly used scheme in which file names are all lower case, with separating periods copied unchanged to the resulting file name, and specs end with .1.ada, and bodies end with .2.ada. GNAT will follow this scheme if the following two pragmas appear:

     pragma Source_File_Name
       (Spec_File_Name => "*.1.ada");
     pragma Source_File_Name
       (Body_File_Name => "*.2.ada");

The default GNAT scheme is actually implemented by providing the following default pragmas internally:

     pragma Source_File_Name
       (Spec_File_Name => "*.ads", Dot_Replacement => "-");
     pragma Source_File_Name
       (Body_File_Name => "*.adb", Dot_Replacement => "-");

Our final example implements a scheme typically used with one of the Ada 83 compilers, where the separator character for subunits was “__” (two underscores), specs were identified by adding _.ADA, bodies by adding .ADA, and subunits by adding .SEP. All file names were upper case. Child units were not present of course since this was an Ada 83 compiler, but it seems reasonable to extend this scheme to use the same double underscore separator for child units.

     pragma Source_File_Name
       (Spec_File_Name => "*_.ADA",
        Dot_Replacement => "__",
        Casing = Uppercase);
     pragma Source_File_Name
       (Body_File_Name => "*.ADA",
        Dot_Replacement => "__",
        Casing = Uppercase);
     pragma Source_File_Name
       (Subunit_File_Name => "*.SEP",
        Dot_Replacement => "__",
        Casing = Uppercase);


Next: , Previous: Alternative File Naming Schemes, Up: The GNAT Compilation Model

2.6 Generating Object Files

An Ada program consists of a set of source files, and the first step in compiling the program is to generate the corresponding object files. These are generated by compiling a subset of these source files. The files you need to compile are the following:

The preceding rules describe the set of files that must be compiled to generate the object files for a program. Each object file has the same name as the corresponding source file, except that the extension is .o as usual.

You may wish to compile other files for the purpose of checking their syntactic and semantic correctness. For example, in the case where a package has a separate spec and body, you would not normally compile the spec. However, it is convenient in practice to compile the spec to make sure it is error-free before compiling clients of this spec, because such compilations will fail if there is an error in the spec.

GNAT provides an option for compiling such files purely for the purposes of checking correctness; such compilations are not required as part of the process of building a program. To compile a file in this checking mode, use the -gnatc switch.


Next: , Previous: Generating Object Files, Up: The GNAT Compilation Model

2.7 Source Dependencies

A given object file clearly depends on the source file which is compiled to produce it. Here we are using depends in the sense of a typical make utility; in other words, an object file depends on a source file if changes to the source file require the object file to be recompiled. In addition to this basic dependency, a given object may depend on additional source files as follows:


Next: , Previous: Source Dependencies, Up: The GNAT Compilation Model

2.8 The Ada Library Information Files

Each compilation actually generates two output files. The first of these is the normal object file that has a .o extension. The second is a text file containing full dependency information. It has the same name as the source file, but an .ali extension. This file is known as the Ada Library Information (ALI) file. The following information is contained in the ALI file.

For a full detailed description of the format of the ALI file, see the source of the body of unit Lib.Writ, contained in file lib-writ.adb in the GNAT compiler sources.


Next: , Previous: The Ada Library Information Files, Up: The GNAT Compilation Model

2.9 Binding an Ada Program

When using languages such as C and C++, once the source files have been compiled the only remaining step in building an executable program is linking the object modules together. This means that it is possible to link an inconsistent version of a program, in which two units have included different versions of the same header.

The rules of Ada do not permit such an inconsistent program to be built. For example, if two clients have different versions of the same package, it is illegal to build a program containing these two clients. These rules are enforced by the GNAT binder, which also determines an elaboration order consistent with the Ada rules.

The GNAT binder is run after all the object files for a program have been created. It is given the name of the main program unit, and from this it determines the set of units required by the program, by reading the corresponding ALI files. It generates error messages if the program is inconsistent or if no valid order of elaboration exists.

If no errors are detected, the binder produces a main program, in Ada by default, that contains calls to the elaboration procedures of those compilation unit that require them, followed by a call to the main program. This Ada program is compiled to generate the object file for the main program. The name of the Ada file is b~xxx.adb (with the corresponding spec b~xxx.ads) where xxx is the name of the main program unit.

Finally, the linker is used to build the resulting executable program, using the object from the main program from the bind step as well as the object files for the Ada units of the program.


Next: , Previous: Binding an Ada Program, Up: The GNAT Compilation Model

2.10 Mixed Language Programming

This section describes how to develop a mixed-language program, specifically one that comprises units in both Ada and C.


Next: , Up: Mixed Language Programming

2.10.1 Interfacing to C

Interfacing Ada with a foreign language such as C involves using compiler directives to import and/or export entity definitions in each language—using extern statements in C, for instance, and the Import, Export, and Convention pragmas in Ada. For a full treatment of these topics, read Appendix B, section 1 of the Ada 95 Language Reference Manual.

There are two ways to build a program using GNAT that contains some Ada sources and some foreign language sources, depending on whether or not the main subprogram is written in Ada. Here is a source example with the main subprogram in Ada:

     /* file1.c */
     #include <stdio.h>
     
     void print_num (int num)
     {
       printf ("num is %d.\n", num);
       return;
     }
     
     /* file2.c */
     
     /* num_from_Ada is declared in my_main.adb */
     extern int num_from_Ada;
     
     int get_num (void)
     {
       return num_from_Ada;
     }
     --  my_main.adb
     procedure My_Main is
     
        --  Declare then export an Integer entity called num_from_Ada
        My_Num : Integer := 10;
        pragma Export (C, My_Num, "num_from_Ada");
     
        --  Declare an Ada function spec for Get_Num, then use
        --  C function get_num for the implementation.
        function Get_Num return Integer;
        pragma Import (C, Get_Num, "get_num");
     
        --  Declare an Ada procedure spec for Print_Num, then use
        --  C function print_num for the implementation.
        procedure Print_Num (Num : Integer);
        pragma Import (C, Print_Num, "print_num");
     
     begin
        Print_Num (Get_Num);
     end My_Main;
  1. To build this example, first compile the foreign language files to generate object files:
              gcc -c file1.c
              gcc -c file2.c
         
  2. Then, compile the Ada units to produce a set of object files and ALI files:
              gnatmake -c my_main.adb
         
  3. Run the Ada binder on the Ada main program:
              gnatbind my_main.ali
         
  4. Link the Ada main program, the Ada objects and the other language objects:
              gnatlink my_main.ali file1.o file2.o
         

The last three steps can be grouped in a single command:

     gnatmake my_main.adb -largs file1.o file2.o

If the main program is in a language other than Ada, then you may have more than one entry point into the Ada subsystem. You must use a special binder option to generate callable routines that initialize and finalize the Ada units (see Binding with Non-Ada Main Programs). Calls to the initialization and finalization routines must be inserted in the main program, or some other appropriate point in the code. The call to initialize the Ada units must occur before the first Ada subprogram is called, and the call to finalize the Ada units must occur after the last Ada subprogram returns. The binder will place the initialization and finalization subprograms into the b~xxx.adb file where they can be accessed by your C sources. To illustrate, we have the following example:

     /* main.c */
     extern void adainit (void);
     extern void adafinal (void);
     extern int add (int, int);
     extern int sub (int, int);
     
     int main (int argc, char *argv[])
     {
       int a = 21, b = 7;
     
       adainit();
     
       /* Should print "21 + 7 = 28" */
       printf ("%d + %d = %d\n", a, b, add (a, b));
       /* Should print "21 - 7 = 14" */
       printf ("%d - %d = %d\n", a, b, sub (a, b));
     
       adafinal();
     }
     --  unit1.ads
     package Unit1 is
        function Add (A, B : Integer) return Integer;
        pragma Export (C, Add, "add");
     end Unit1;
     
     --  unit1.adb
     package body Unit1 is
        function Add (A, B : Integer) return Integer is
        begin
           return A + B;
        end Add;
     end Unit1;
     
     --  unit2.ads
     package Unit2 is
        function Sub (A, B : Integer) return Integer;
        pragma Export (C, Sub, "sub");
     end Unit2;
     
     --  unit2.adb
     package body Unit2 is
        function Sub (A, B : Integer) return Integer is
        begin
           return A - B;
        end Sub;
     end Unit2;
  1. The build procedure for this application is similar to the last example's. First, compile the foreign language files to generate object files:
              gcc -c main.c
         
  2. Next, compile the Ada units to produce a set of object files and ALI files:
              gnatmake -c unit1.adb
              gnatmake -c unit2.adb
         
  3. Run the Ada binder on every generated ALI file. Make sure to use the -n option to specify a foreign main program:
              gnatbind -n unit1.ali unit2.ali
         
  4. Link the Ada main program, the Ada objects and the foreign language objects. You need only list the last ALI file here:
              gnatlink unit2.ali main.o -o exec_file
         

    This procedure yields a binary executable called exec_file.


Previous: Interfacing to C, Up: Mixed Language Programming

2.10.2 Calling Conventions

GNAT follows standard calling sequence conventions and will thus interface to any other language that also follows these conventions. The following Convention identifiers are recognized by GNAT:

Ada
This indicates that the standard Ada calling sequence will be used and all Ada data items may be passed without any limitations in the case where GNAT is used to generate both the caller and callee. It is also possible to mix GNAT generated code and code generated by another Ada compiler. In this case, the data types should be restricted to simple cases, including primitive types. Whether complex data types can be passed depends on the situation. Probably it is safe to pass simple arrays, such as arrays of integers or floats. Records may or may not work, depending on whether both compilers lay them out identically. Complex structures involving variant records, access parameters, tasks, or protected types, are unlikely to be able to be passed.

Note that in the case of GNAT running on a platform that supports DEC Ada 83, a higher degree of compatibility can be guaranteed, and in particular records are layed out in an identical manner in the two compilers. Note also that if output from two different compilers is mixed, the program is responsible for dealing with elaboration issues. Probably the safest approach is to write the main program in the version of Ada other than GNAT, so that it takes care of its own elaboration requirements, and then call the GNAT-generated adainit procedure to ensure elaboration of the GNAT components. Consult the documentation of the other Ada compiler for further details on elaboration.

However, it is not possible to mix the tasking run time of GNAT and DEC Ada 83, All the tasking operations must either be entirely within GNAT compiled sections of the program, or entirely within DEC Ada 83 compiled sections of the program.


Assembler
Specifies assembler as the convention. In practice this has the same effect as convention Ada (but is not equivalent in the sense of being considered the same convention).


Asm
Equivalent to Assembler.


COBOL
Data will be passed according to the conventions described in section B.4 of the Ada 95 Reference Manual.


C
Data will be passed according to the conventions described in section B.3 of the Ada 95 Reference Manual.


Default
Equivalent to C.


External
Equivalent to C.


CPP
This stands for C++. For most purposes this is identical to C. See the separate description of the specialized GNAT pragmas relating to C++ interfacing for further details.


Fortran
Data will be passed according to the conventions described in section B.5 of the Ada 95 Reference Manual.
Intrinsic
This applies to an intrinsic operation, as defined in the Ada 95 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram, this means that the body of the subprogram is provided by the compiler itself, usually by means of an efficient code sequence, and that the user does not supply an explicit body for it. In an application program, the pragma can only be applied to the following two sets of names, which the GNAT compiler recognizes.
Stdcall
This is relevant only to NT/Win95 implementations of GNAT, and specifies that the Stdcall calling sequence will be used, as defined by the NT API.


DLL
This is equivalent to Stdcall.


Win32
This is equivalent to Stdcall.


Stubbed
This is a special convention that indicates that the compiler should provide a stub body that raises Program_Error.

GNAT additionally provides a useful pragma Convention_Identifier that can be used to parametrize conventions and allow additional synonyms to be specified. For example if you have legacy code in which the convention identifier Fortran77 was used for Fortran, you can use the configuration pragma:

     pragma Convention_Identifier (Fortran77, Fortran);

And from now on the identifier Fortran77 may be used as a convention identifier (for example in an Import pragma) with the same meaning as Fortran.


Next: , Previous: Mixed Language Programming, Up: The GNAT Compilation Model

2.11 Building Mixed Ada & C++ Programs

A programmer inexperienced with mixed-language development may find that building an application containing both Ada and C++ code can be a challenge. As a matter of fact, interfacing with C++ has not been standardized in the Ada 95 Reference Manual due to the immaturity of – and lack of standards for – C++ at the time. This section gives a few hints that should make this task easier. The first section addresses the differences regarding interfacing with C. The second section looks into the delicate problem of linking the complete application from its Ada and C++ parts. The last section gives some hints on how the GNAT run time can be adapted in order to allow inter-language dispatching with a new C++ compiler.


Next: , Up: Building Mixed Ada & C++ Programs

2.11.1 Interfacing to C++

GNAT supports interfacing with C++ compilers generating code that is compatible with the standard Application Binary Interface of the given platform.

Interfacing can be done at 3 levels: simple data, subprograms, and classes. In the first two cases, GNAT offers a specific Convention CPP that behaves exactly like Convention C. Usually, C++ mangles the names of subprograms, and currently, GNAT does not provide any help to solve the demangling problem. This problem can be addressed in two ways:

Interfacing at the class level can be achieved by using the GNAT specific pragmas such as CPP_Class and CPP_Virtual. See the GNAT Reference Manual for additional information.


Next: , Previous: Interfacing to C++, Up: Building Mixed Ada & C++ Programs

2.11.2 Linking a Mixed C++ & Ada Program

Usually the linker of the C++ development system must be used to link mixed applications because most C++ systems will resolve elaboration issues (such as calling constructors on global class instances) transparently during the link phase. GNAT has been adapted to ease the use of a foreign linker for the last phase. Three cases can be considered:

  1. Using GNAT and G++ (GNU C++ compiler) from the same GCC installation: The C++ linker can simply be called by using the C++ specific driver called c++. Note that this setup is not very common because it may involve recompiling the whole GCC tree from sources, which makes it harder to upgrade the compilation system for one language without destabilizing the other.
              $ c++ -c file1.C
              $ c++ -c file2.C
              $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
         
  2. Using GNAT and G++ from two different GCC installations: If both compilers are on the PATH, the previous method may be used. It is important to note that environment variables such as C_INCLUDE_PATH, GCC_EXEC_PREFIX, BINUTILS_ROOT, and GCC_ROOT will affect both compilers at the same time and may make one of the two compilers operate improperly if set during invocation of the wrong compiler. It is also very important that the linker uses the proper libgcc.a GCC library – that is, the one from the C++ compiler installation. The implicit link command as suggested in the gnatmake command from the former example can be replaced by an explicit link command with the full-verbosity option in order to verify which library is used:
              $ gnatbind ada_unit
              $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
         

    If there is a problem due to interfering environment variables, it can be worked around by using an intermediate script. The following example shows the proper script to use when GNAT has not been installed at its default location and g++ has been installed at its default location:

              $ cat ./my_script
              #!/bin/sh
              unset BINUTILS_ROOT
              unset GCC_ROOT
              c++ $*
              $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
         
  3. Using a non-GNU C++ compiler: The commands previously described can be used to insure that the C++ linker is used. Nonetheless, you need to add the path to libgcc explicitly, since some libraries needed by GNAT are located in this directory:
              $ cat ./my_script
              #!/bin/sh
              CC $* `gcc -print-libgcc-file-name`
              $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
         

    Where CC is the name of the non-GNU C++ compiler.


Next: , Previous: Linking a Mixed C++ & Ada Program, Up: Building Mixed Ada & C++ Programs

2.11.3 A Simple Example

The following example, provided as part of the GNAT examples, shows how to achieve procedural interfacing between Ada and C++ in both directions. The C++ class A has two methods. The first method is exported to Ada by the means of an extern C wrapper function. The second method calls an Ada subprogram. On the Ada side, The C++ calls are modelled by a limited record with a layout comparable to the C++ class. The Ada subprogram, in turn, calls the C++ method. So, starting from the C++ main program, the process passes back and forth between the two languages.

Here are the compilation commands:

     $ gnatmake -c simple_cpp_interface
     $ c++ -c cpp_main.C
     $ c++ -c ex7.C
     $ gnatbind -n simple_cpp_interface
     $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
           -lstdc++ ex7.o cpp_main.o

Here are the corresponding sources:

     
     //cpp_main.C
     
     #include "ex7.h"
     
     extern "C" {
       void adainit (void);
       void adafinal (void);
       void method1 (A *t);
     }
     
     void method1 (A *t)
     {
       t->method1 ();
     }
     
     int main ()
     {
       A obj;
       adainit ();
       obj.method2 (3030);
       adafinal ();
     }
     
     //ex7.h
     
     class Origin {
      public:
       int o_value;
     };
     class A : public Origin {
      public:
       void method1 (void);
       virtual void method2 (int v);
       A();
       int   a_value;
     };
     
     //ex7.C
     
     #include "ex7.h"
     #include <stdio.h>
     
     extern "C" { void ada_method2 (A *t, int v);}
     
     void A::method1 (void)
     {
       a_value = 2020;
       printf ("in A::method1, a_value = %d \n",a_value);
     
     }
     
     void A::method2 (int v)
     {
        ada_method2 (this, v);
        printf ("in A::method2, a_value = %d \n",a_value);
     
     }
     
     A::A(void)
     {
        a_value = 1010;
       printf ("in A::A, a_value = %d \n",a_value);
     }
     
     -- Ada sources
     package body Simple_Cpp_Interface is
     
        procedure Ada_Method2 (This : in out A; V : Integer) is
        begin
           Method1 (This);
           This.A_Value := V;
        end Ada_Method2;
     
     end Simple_Cpp_Interface;
     
     package Simple_Cpp_Interface is
        type A is limited
           record
              O_Value : Integer;
              A_Value : Integer;
           end record;
        pragma Convention (C, A);
     
        procedure Method1 (This : in out A);
        pragma Import (C, Method1);
     
        procedure Ada_Method2 (This : in out A; V : Integer);
        pragma Export (C, Ada_Method2);
     
     end Simple_Cpp_Interface;


Previous: A Simple Example, Up: Building Mixed Ada & C++ Programs

2.11.4 Adapting the Run Time to a New C++ Compiler

GNAT offers the capability to derive Ada 95 tagged types directly from preexisting C++ classes and . See “Interfacing with C++” in the GNAT Reference Manual. The mechanism used by GNAT for achieving such a goal has been made user configurable through a GNAT library unit Interfaces.CPP. The default version of this file is adapted to the GNU C++ compiler. Internal knowledge of the virtual table layout used by the new C++ compiler is needed to configure properly this unit. The Interface of this unit is known by the compiler and cannot be changed except for the value of the constants defining the characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size, CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source of this unit for more details.


Next: , Previous: Building Mixed Ada & C++ Programs, Up: The GNAT Compilation Model

2.12 Comparison between GNAT and C/C++ Compilation Models

The GNAT model of compilation is close to the C and C++ models. You can think of Ada specs as corresponding to header files in C. As in C, you don't need to compile specs; they are compiled when they are used. The Ada with is similar in effect to the #include of a C header.

One notable difference is that, in Ada, you may compile specs separately to check them for semantic and syntactic accuracy. This is not always possible with C headers because they are fragments of programs that have less specific syntactic or semantic rules.

The other major difference is the requirement for running the binder, which performs two important functions. First, it checks for consistency. In C or C++, the only defense against assembling inconsistent programs lies outside the compiler, in a makefile, for example. The binder satisfies the Ada requirement that it be impossible to construct an inconsistent program when the compiler is used in normal mode.

The other important function of the binder is to deal with elaboration issues. There are also elaboration issues in C++ that are handled automatically. This automatic handling has the advantage of being simpler to use, but the C++ programmer has no control over elaboration. Where gnatbind might complain there was no valid order of elaboration, a C++ compiler would simply construct a program that malfunctioned at run time.


Previous: Comparison between GNAT and C/C++ Compilation Models, Up: The GNAT Compilation Model

2.13 Comparison between GNAT and Conventional Ada Library Models

This section is intended to be useful to Ada programmers who have previously used an Ada compiler implementing the traditional Ada library model, as described in the Ada 95 Language Reference Manual. If you have not used such a system, please go on to the next section.

In GNAT, there is no library in the normal sense. Instead, the set of source files themselves acts as the library. Compiling Ada programs does not generate any centralized information, but rather an object file and a ALI file, which are of interest only to the binder and linker. In a traditional system, the compiler reads information not only from the source file being compiled, but also from the centralized library. This means that the effect of a compilation depends on what has been previously compiled. In particular:

In GNAT, compiling one unit never affects the compilation of any other units because the compiler reads only source files. Only changes to source files can affect the results of a compilation. In particular:

The most important result of these differences is that order of compilation is never significant in GNAT. There is no situation in which one is required to do one compilation before another. What shows up as order of compilation requirements in the traditional Ada library becomes, in GNAT, simple source dependencies; in other words, there is only a set of rules saying what source files must be present when a file is compiled.


Next: , Previous: The GNAT Compilation Model, Up: Top

3 Compiling Using gcc

This chapter discusses how to compile Ada programs using the gcc command. It also describes the set of switches that can be used to control the behavior of the compiler.


Next: , Up: Compiling Using gcc

3.1 Compiling Programs

The first step in creating an executable program is to compile the units of the program using the gcc command. You must compile the following files:

You need not compile the following files

because they are compiled as part of compiling related units. GNAT package specs when the corresponding body is compiled, and subunits when the parent is compiled.

If you attempt to compile any of these files, you will get one of the following error messages (where fff is the name of the file you compiled):

     cannot generate code for file fff (package spec)
     to check package spec, use -gnatc
     
     cannot generate code for file fff (missing subunits)
     to check parent unit, use -gnatc
     
     cannot generate code for file fff (subprogram spec)
     to check subprogram spec, use -gnatc
     
     cannot generate code for file fff (subunit)
     to check subunit, use -gnatc

As indicated by the above error messages, if you want to submit one of these files to the compiler to check for correct semantics without generating code, then use the -gnatc switch.

The basic command for compiling a file containing an Ada unit is

     $ gcc -c [switches] file name

where file name is the name of the Ada file (usually having an extension .ads for a spec or .adb for a body). You specify the -c switch to tell gcc to compile, but not link, the file. The result of a successful compilation is an object file, which has the same name as the source file but an extension of .o and an Ada Library Information (ALI) file, which also has the same name as the source file, but with .ali as the extension. GNAT creates these two output files in the current directory, but you may specify a source file in any directory using an absolute or relative path specification containing the directory information.

gcc is actually a driver program that looks at the extensions of the file arguments and loads the appropriate compiler. For example, the GNU C compiler is cc1, and the Ada compiler is gnat1. These programs are in directories known to the driver program (in some configurations via environment variables you set), but need not be in your path. The gcc driver also calls the assembler and any other utilities needed to complete the generation of the required object files.

It is possible to supply several file names on the same gcc command. This causes gcc to call the appropriate compiler for each file. For example, the following command lists three separate files to be compiled:

     $ gcc -c x.adb y.adb z.c

calls gnat1 (the Ada compiler) twice to compile x.adb and y.adb, and cc1 (the C compiler) once to compile z.c. The compiler generates three object files x.o, y.o and z.o and the two ALI files x.ali and y.ali from the Ada compilations. Any switches apply to all the files listed, except for -gnatx switches, which apply only to Ada compilations.


Next: , Previous: Compiling Programs, Up: Compiling Using gcc

3.2 Switches for gcc

The gcc command accepts switches that control the compilation process. These switches are fully described in this section. First we briefly list all the switches, in alphabetical order, then we describe the switches in more detail in functionally grouped sections.

-b target
Compile your program to run on target, which is the name of a system configuration. You must have a GNAT cross-compiler built if target is not the same as your host system.
-Bdir
Load compiler executables (for example, gnat1, the Ada compiler) from dir instead of the default location. Only use this switch when multiple versions of the GNAT compiler are available. See the gcc manual page for further details. You would normally use the -b or -V switch instead.
-c
Compile. Always use this switch when compiling Ada programs.

Note: for some other languages when using gcc, notably in the case of C and C++, it is possible to use use gcc without a -c switch to compile and link in one step. In the case of GNAT, you cannot use this approach, because the binder must be run and gcc cannot be used to run the GNAT binder.

-fno-inline
Suppresses all back-end inlining, even if other optimization or inlining switches are set. This includes suppression of inlining that results from the use of the pragma Inline_Always. See also -gnatn and -gnatN.
-fstack-check
Activates stack checking. See Stack Overflow Checking, for details of the use of this option.
-g
Generate debugging information. This information is stored in the object file and copied from there to the final executable file by the linker, where it can be read by the debugger. You must use the -g switch if you plan on using the debugger.
-gnat83
Enforce Ada 83 restrictions.
-gnata
Assertions enabled. Pragma Assert and pragma Debug to be activated.
-gnatA
Avoid processing gnat.adc. If a gnat.adc file is present, it will be ignored.
-gnatb
Generate brief messages to stderr even if verbose mode set.
-gnatc
Check syntax and semantics only (no code generation attempted).
-gnatd
Specify debug options for the compiler. The string of characters after the -gnatd specify the specific debug options. The possible characters are 0-9, a-z, A-Z, optionally preceded by a dot. See compiler source file debug.adb for details of the implemented debug options. Certain debug options are relevant to applications programmers, and these are documented at appropriate points in this users guide.
-gnatD
Output expanded source files for source level debugging. This switch also suppress generation of cross-reference information (see -gnatx).
-gnatec=path
Specify a configuration pragma file (the equal sign is optional) (see The Configuration Pragmas Files).
-gnateDsymbol[=value]
Defines a symbol, associated with value, for preprocessing. (see Integrated Preprocessing)
-gnatef
Display full source path name in brief error messages.
-gnatem=path
Specify a mapping file (the equal sign is optional) (see Units to Sources Mapping Files).
-gnatep=file
Specify a preprocessing data file (the equal sign is optional) (see Integrated Preprocessing).
-gnatE
Full dynamic elaboration checks.
-gnatf
Full errors. Multiple errors per line, all undefined references, do not attempt to suppress cascaded errors.
-gnatF
Externals names are folded to all uppercase.
-gnatg
Internal GNAT implementation mode. This should not be used for applications programs, it is intended only for use by the compiler and its run-time library. For documentation, see the GNAT sources. Note that -gnatg implies -gnatwu so that warnings are generated on unreferenced entities, and all warnings are treated as errors.
-gnatG
List generated expanded code in source form.
-gnath
Output usage information. The output is written to stdout.
-gnatic
Identifier character set (c=1/2/3/4/8/9/p/f/n/w).
-gnatk=n
Limit file names to n (1-999) characters (k = krunch).
-gnatl
Output full source listing with embedded error messages.
-gnatL
Use the longjmp/setjmp method for exception handling
-gnatm=n
Limit number of detected error or warning messages to n where n is in the range 1..999_999. The default setting if no switch is given is 9999. Compilation is terminated if this limit is exceeded.
-gnatn
Activate inlining for subprograms for which pragma inline is specified. This inlining is performed by the GCC back-end.
-gnatN
Activate front end inlining for subprograms for which pragma Inline is specified. This inlining is performed by the front end and will be visible in the -gnatG output. In some cases, this has proved more effective than the back end inlining resulting from the use of -gnatn. Note that -gnatN automatically implies -gnatn so it is not necessary to specify both options. There are a few cases that the back-end inlining catches that cannot be dealt with in the front-end.
-gnato
Enable numeric overflow checking (which is not normally enabled by default). Not that division by zero is a separate check that is not controlled by this switch (division by zero checking is on by default).
-gnatp
Suppress all checks.
-gnatP
Enable polling. This is required on some systems (notably Windows NT) to obtain asynchronous abort and asynchronous transfer of control capability. See the description of pragma Polling in the GNAT Reference Manual for full details.
-gnatq
Don't quit; try semantics, even if parse errors.
-gnatQ
Don't quit; generate ALI and tree files even if illegalities.
-gnatR[0/1/2/3[s]]
Output representation information for declared types and objects.
-gnats
Syntax check only.
-gnatS
Print package Standard.
-gnatt
Generate tree output file.
-gnatTnnn
All compiler tables start at nnn times usual starting size.
-gnatu
List units for this compilation.
-gnatU
Tag all error messages with the unique string “error:”
-gnatv
Verbose mode. Full error output with source lines to stdout.
-gnatV
Control level of validity checking. See separate section describing this feature.
-gnatwxxx
Warning mode where xxx is a string of option letters that denotes the exact warnings that are enabled or disabled. (see Warning Message Control)
-gnatWe
Wide character encoding method (e=n/h/u/s/e/8).
-gnatx
Suppress generation of cross-reference information.
-gnaty
Enable built-in style checks. (see Style Checking)
-gnatzm
Distribution stub generation and compilation (m=r/c for receiver/caller stubs).
-gnatZ
Use the zero cost method for exception handling
-Idir
Direct GNAT to search the dir directory for source files needed by the current compilation (see Search Paths and the Run-Time Library (RTL)).
-I-
Except for the source file named in the command line, do not look for source files in the directory containing the source file named in the command line (see Search Paths and the Run-Time Library (RTL)).
-mbig-switch
This standard gcc switch causes the compiler to use larger offsets in its jump table representation for case statements. This may result in less efficient code, but is sometimes necessary (for example on HP-UX targets) in order to compile large and/or nested case statements.
-o file
This switch is used in gcc to redirect the generated object file and its associated ALI file. Beware of this switch with GNAT, because it may cause the object file and ALI file to have different names which in turn may confuse the binder and the linker.
-nostdinc
Inhibit the search of the default location for the GNAT Run Time Library (RTL) source files.
-nostdlib
Inhibit the search of the default location for the GNAT Run Time Library (RTL) ALI files.
-O[n]
n controls the optimization level.
n = 0
No optimization, the default setting if no -O appears
n = 1
Normal optimization, the default if you specify -O without an operand.
n = 2
Extensive optimization
n = 3
Extensive optimization with automatic inlining of subprograms not specified by pragma Inline. This applies only to inlining within a unit. For details on control of inlining see See Subprogram Inlining Control.

-pass-exit-codes
Catch exit codes from the compiler and use the most meaningful as exit status.
--RTS=rts-path
Specifies the default location of the runtime library. Same meaning as the equivalent gnatmake flag (see Switches for gnatmake).
-S
Used in place of -c to cause the assembler source file to be generated, using .s as the extension, instead of the object file. This may be useful if you need to examine the generated assembly code.
-v
Show commands generated by the gcc driver. Normally used only for debugging purposes or if you need to be sure what version of the compiler you are executing.
-V ver
Execute ver version of the compiler. This is the gcc version, not the GNAT version.

You may combine a sequence of GNAT switches into a single switch. For example, the combined switch

     -gnatofi3

is equivalent to specifying the following sequence of switches:

     -gnato -gnatf -gnati3

The following restrictions apply to the combination of switches in this manner:


Next: , Up: Switches for gcc

3.2.1 Output and Error Message Control

The standard default format for error messages is called “brief format”. Brief format messages are written to stderr (the standard error file) and have the following form:

     e.adb:3:04: Incorrect spelling of keyword "function"
     e.adb:4:20: ";" should be "is"

The first integer after the file name is the line number in the file, and the second integer is the column number within the line. glide can parse the error messages and point to the referenced character. The following switches provide control over the error message format:

-gnatv
The v stands for verbose. The effect of this setting is to write long-format error messages to stdout (the standard output file. The same program compiled with the -gnatv switch would generate:
          

3. funcion X (Q : Integer) | >>> Incorrect spelling of keyword "function" 4. return Integer; | >>> ";" should be "is"

The vertical bar indicates the location of the error, and the `>>>' prefix can be used to search for error messages. When this switch is used the only source lines output are those with errors.

-gnatl
The l stands for list. This switch causes a full listing of the file to be generated. The output might look as follows:
          

1. procedure E is 2. V : Integer; 3. funcion X (Q : Integer) | >>> Incorrect spelling of keyword "function" 4. return Integer; | >>> ";" should be "is" 5. begin 6. return Q + Q; 7. end; 8. begin 9. V := X + X; 10.end E;

When you specify the -gnatv or -gnatl switches and standard output is redirected, a brief summary is written to stderr (standard error) giving the number of error messages and warning messages generated.

-gnatU
This switch forces all error messages to be preceded by the unique string “error:”. This means that error messages take a few more characters in space, but allows easy searching for and identification of error messages.
-gnatb
The b stands for brief. This switch causes GNAT to generate the brief format error messages to stderr (the standard error file) as well as the verbose format message or full listing (which as usual is written to stdout (the standard output file).
-gnatmn
The m stands for maximum. n is a decimal integer in the range of 1 to 999 and limits the number of error messages to be generated. For example, using -gnatm2 might yield
          e.adb:3:04: Incorrect spelling of keyword "function"
          e.adb:5:35: missing ".."
          fatal error: maximum errors reached
          compilation abandoned
     

-gnatf
The f stands for full. Normally, the compiler suppresses error messages that are likely to be redundant. This switch causes all error messages to be generated. In particular, in the case of references to undefined variables. If a given variable is referenced several times, the normal format of messages is
          e.adb:7:07: "V" is undefined (more references follow)
     

where the parenthetical comment warns that there are additional references to the variable V. Compiling the same program with the -gnatf switch yields

          e.adb:7:07: "V" is undefined
          e.adb:8:07: "V" is undefined
          e.adb:8:12: "V" is undefined
          e.adb:8:16: "V" is undefined
          e.adb:9:07: "V" is undefined
          e.adb:9:12: "V" is undefined
     

The -gnatf switch also generates additional information for some error messages. Some examples are:


-gnatq
The q stands for quit (really “don't quit”). In normal operation mode, the compiler first parses the program and determines if there are any syntax errors. If there are, appropriate error messages are generated and compilation is immediately terminated. This switch tells GNAT to continue with semantic analysis even if syntax errors have been found. This may enable the detection of more errors in a single run. On the other hand, the semantic analyzer is more likely to encounter some internal fatal error when given a syntactically invalid tree.
-gnatQ
In normal operation mode, the ALI file is not generated if any illegalities are detected in the program. The use of -gnatQ forces generation of the ALI file. This file is marked as being in error, so it cannot be used for binding purposes, but it does contain reasonably complete cross-reference information, and thus may be useful for use by tools (e.g. semantic browsing tools or integrated development environments) that are driven from the ALI file. This switch implies -gnatq, since the semantic phase must be run to get a meaningful ALI file.

In addition, if -gnatt is also specified, then the tree file is generated even if there are illegalities. It may be useful in this case to also specify -gnatq to ensure that full semantic processing occurs. The resulting tree file can be processed by ASIS, for the purpose of providing partial information about illegal units, but if the error causes the tree to be badly malformed, then ASIS may crash during the analysis.

When -gnatQ is used and the generated ALI file is marked as being in error, gnatmake will attempt to recompile the source when it finds such an ALI file, including with switch -gnatc.

Note that -gnatQ has no effect if -gnats is specified, since ALI files are never generated if -gnats is set.


Next: , Previous: Output and Error Message Control, Up: Switches for gcc

3.2.2 Warning Message Control

In addition to error messages, which correspond to illegalities as defined in the Ada 95 Reference Manual, the compiler detects two kinds of warning situations.

First, the compiler considers some constructs suspicious and generates a warning message to alert you to a possible error. Second, if the compiler detects a situation that is sure to raise an exception at run time, it generates a warning message. The following shows an example of warning messages:

     e.adb:4:24: warning: creation of object may raise Storage_Error
     e.adb:10:17: warning: static value out of range
     e.adb:10:17: warning: "Constraint_Error" will be raised at run time

GNAT considers a large number of situations as appropriate for the generation of warning messages. As always, warnings are not definite indications of errors. For example, if you do an out-of-range assignment with the deliberate intention of raising a Constraint_Error exception, then the warning that may be issued does not indicate an error. Some of the situations for which GNAT issues warnings (at least some of the time) are given in the following list. This list is not complete, and new warnings are often added to subsequent versions of GNAT. The list is intended to give a general idea of the kinds of warnings that are generated.

The following switches are available to control the handling of warning messages:

-gnatwa
Activate all optional errors. This switch activates most optional warning messages, see remaining list in this section for details on optional warning messages that can be individually controlled. The warnings that are not turned on by this switch are -gnatwd (implicit dereferencing), -gnatwh (hiding), and -gnatwl (elaboration warnings). All other optional warnings are turned on.
-gnatwA
Suppress all optional errors. This switch suppresses all optional warning messages, see remaining list in this section for details on optional warning messages that can be individually controlled.
-gnatwc
Activate warnings on conditionals. This switch activates warnings for conditional expressions used in tests that are known to be True or False at compile time. The default is that such warnings are not generated. Note that this warning does not get issued for the use of boolean variables or constants whose values are known at compile time, since this is a standard technique for conditional compilation in Ada, and this would generate too many “false positive” warnings. This warning can also be turned on using -gnatwa.
-gnatwC
Suppress warnings on conditionals. This switch suppresses warnings for conditional expressions used in tests that are known to be True or False at compile time.
-gnatwd
Activate warnings on implicit dereferencing. If this switch is set, then the use of a prefix of an access type in an indexed component, slice, or selected component without an explicit .all will generate a warning. With this warning enabled, access checks occur only at points where an explicit .all appears in the source code (assuming no warnings are generated as a result of this switch). The default is that such warnings are not generated. Note that -gnatwa does not affect the setting of this warning option.
-gnatwD
Suppress warnings on implicit dereferencing. This switch suppresses warnings for implicit dereferences in indexed components, slices, and selected components.
-gnatwe
Treat warnings as errors. This switch causes warning messages to be treated as errors. The warning string still appears, but the warning messages are counted as errors, and prevent the generation of an object file.
-gnatwf
Activate warnings on unreferenced formals. This switch causes a warning to be generated if a formal parameter is not referenced in the body of the subprogram. This warning can also be turned on using -gnatwa or -gnatwu.
-gnatwF
Suppress warnings on unreferenced formals. This switch suppresses warnings for unreferenced formal parameters. Note that the combination -gnatwu followed by -gnatwF has the effect of warning on unreferenced entities other than subprogram formals.
-gnatwg
Activate warnings on unrecognized pragmas. This switch causes a warning to be generated if an unrecognized pragma is encountered. Apart from issuing this warning, the pragma is ignored and has no effect. This warning can also be turned on using -gnatwa. The default is that such warnings are issued (satisfying the Ada Reference Manual requirement that such warnings appear).
-gnatwG
Suppress warnings on unrecognized pragmas. This switch suppresses warnings for unrecognized pragmas.
-gnatwh
Activate warnings on hiding. This switch activates warnings on hiding declarations. A declaration is considered hiding if it is for a non-overloadable entity, and it declares an entity with the same name as some other entity that is directly or use-visible. The default is that such warnings are not generated. Note that -gnatwa does not affect the setting of this warning option.
-gnatwH
Suppress warnings on hiding. This switch suppresses warnings on hiding declarations.
-gnatwi
Activate warnings on implementation units. This switch activates warnings for a with of an internal GNAT implementation unit, defined as any unit from the Ada, Interfaces, GNAT, or System hierarchies that is not documented in either the Ada Reference Manual or the GNAT Programmer's Reference Manual. Such units are intended only for internal implementation purposes and should not be with'ed by user programs. The default is that such warnings are generated This warning can also be turned on using -gnatwa.
-gnatwI
Disable warnings on implementation units. This switch disables warnings for a with of an internal GNAT implementation unit.
-gnatwj
Activate warnings on obsolescent features (Annex J). If this warning option is activated, then warnings are generated for calls to subprograms marked with pragma Obsolescent and for use of features in Annex J of the Ada Reference Manual. In the case of Annex J, not all features are flagged. In particular use of the renamed packages (like Text_IO) and use of package ASCII are not flagged, since these are very common and would generate many annoying positive warnings. The default is that such warnings are not generated.
-gnatwJ
Suppress warnings on obsolescent features (Annex J). This switch disables warnings on use of obsolescent features.
-gnatwk
Activate warnings on variables that could be constants. This switch activates warnings for variables that are initialized but never modified, and then could be declared constants.
-gnatwK
Suppress warnings on variables that could be constants. This switch disables warnings on variables that could be declared constants.
-gnatwl
Activate warnings for missing elaboration pragmas. This switch activates warnings on missing pragma Elaborate_All statements. See the section in this guide on elaboration checking for details on when such pragma should be used. Warnings are also generated if you are using the static mode of elaboration, and a pragma Elaborate is encountered. The default is that such warnings are not generated. This warning is not automatically turned on by the use of -gnatwa.
-gnatwL
Suppress warnings for missing elaboration pragmas. This switch suppresses warnings on missing pragma Elaborate_All statements. See the section in this guide on elaboration checking for details on when such pragma should be used.
-gnatwm
Activate warnings on modified but unreferenced variables. This switch activates warnings for variables that are assigned (using an initialization value or with one or more assignment statements) but whose value is never read. The warning is suppressed for volatile variables and also for variables that are renamings of other variables or for which an address clause is given. This warning can also be turned on using -gnatwa.
-gnatwM
Disable warnings on modified but unreferenced variables. This switch disables warnings for variables that are assigned or initialized, but never read.
-gnatwn
Set normal warnings mode. This switch sets normal warning mode, in which enabled warnings are issued and treated as warnings rather than errors. This is the default mode. the switch -gnatwn can be used to cancel the effect of an explicit -gnatws or -gnatwe. It also cancels the effect of the implicit -gnatwe that is activated by the use of -gnatg.
-gnatwo
Activate warnings on address clause overlays. This switch activates warnings for possibly unintended initialization effects of defining address clauses that cause one variable to overlap another. The default is that such warnings are generated. This warning can also be turned on using -gnatwa.
-gnatwO
Suppress warnings on address clause overlays. This switch suppresses warnings on possibly unintended initialization effects of defining address clauses that cause one variable to overlap another.
-gnatwp
Activate warnings on ineffective pragma Inlines. This switch activates warnings for failure of front end inlining (activated by -gnatN) to inline a particular call. There are many reasons for not being able to inline a call, including most commonly that the call is too complex to inline. This warning can also be turned on using -gnatwa.
-gnatwP
Suppress warnings on ineffective pragma Inlines. This switch suppresses warnings on ineffective pragma Inlines. If the inlining mechanism cannot inline a call, it will simply ignore the request silently.
-gnatwr
Activate warnings on redundant constructs. This switch activates warnings for redundant constructs. The following is the current list of constructs regarded as redundant: This warning can also be turned on using -gnatwa.
-gnatwR
Suppress warnings on redundant constructs. This switch suppresses warnings for redundant constructs.
-gnatws
Suppress all warnings. This switch completely suppresses the output of all warning messages from the GNAT front end. Note that it does not suppress warnings from the gcc back end. To suppress these back end warnings as well, use the switch -w in addition to -gnatws.
-gnatwu
Activate warnings on unused entities. This switch activates warnings to be generated for entities that are declared but not referenced, and for units that are with'ed and not referenced. In the case of packages, a warning is also generated if no entities in the package are referenced. This means that if the package is referenced but the only references are in use clauses or renames declarations, a warning is still generated. A warning is also generated for a generic package that is with'ed but never instantiated. In the case where a package or subprogram body is compiled, and there is a with on the corresponding spec that is only referenced in the body, a warning is also generated, noting that the with can be moved to the body. The default is that such warnings are not generated. This switch also activates warnings on unreferenced formals (it is includes the effect of -gnatwf). This warning can also be turned on using -gnatwa.
-gnatwU
Suppress warnings on unused entities. This switch suppresses warnings for unused entities and packages. It also turns off warnings on unreferenced formals (and thus includes the effect of -gnatwF).
-gnatwv
Activate warnings on unassigned variables. This switch activates warnings for access to variables which may not be properly initialized. The default is that such warnings are generated.
-gnatwV
Suppress warnings on unassigned variables. This switch suppresses warnings for access to variables which may not be properly initialized.
-gnatwx
Activate warnings on Export/Import pragmas. This switch activates warnings on Export/Import pragmas when the compiler detects a possible conflict between the Ada and foreign language calling sequences. For example, the use of default parameters in a convention C procedure is dubious because the C compiler cannot supply the proper default, so a warning is issued. The default is that such warnings are generated.
-gnatwX
Suppress warnings on Export/Import pragmas. This switch suppresses warnings on Export/Import pragmas. The sense of this is that you are telling the compiler that you know what you are doing in writing the pragma, and it should not complain at you.
-gnatwz
Activate warnings on unchecked conversions. This switch activates warnings for unchecked conversions where the types are known at compile time to have different sizes. The default is that such warnings are generated.
-gnatwZ
Suppress warnings on unchecked conversions. This switch suppresses warnings for unchecked conversions where the types are known at compile time to have different sizes.
-Wuninitialized
The warnings controlled by the -gnatw switch are generated by the front end of the compiler. In some cases, the gcc back end can provide additional warnings. One such useful warning is provided by -Wuninitialized. This must be used in conjunction with tunrning on optimization mode. This causes the flow analysis circuits of the back end optimizer to output additional warnings about uninitialized variables.
-w
This switch suppresses warnings from the gcc back end. It may be used in conjunction with -gnatws to ensure that all warnings are suppressed during the entire compilation process.

A string of warning parameters can be used in the same parameter. For example:

     -gnatwaLe

will turn on all optional warnings except for elaboration pragma warnings, and also specify that warnings should be treated as errors. When no switch -gnatw is used, this is equivalent to:

-gnatwB
-gnatwC
-gnatwK
-gnatwD
-gnatwL
-gnatwH
-gnatwi
-gnatwP
-gnatwn
-gnatwo
-gnatwz
-gnatwx


Next: , Previous: Warning Message Control, Up: Switches for gcc

3.2.3 Debugging and Assertion Control

-gnata
The pragmas Assert and Debug normally have no effect and are ignored. This switch, where `a' stands for assert, causes Assert and Debug pragmas to be activated.

The pragmas have the form:

          

pragma Assert (Boolean-expression [, static-string-expression]) pragma Debug (procedure call)

The Assert pragma causes Boolean-expression to be tested. If the result is True, the pragma has no effect (other than possible side effects from evaluating the expression). If the result is False, the exception Assert_Failure declared in the package System.Assertions is raised (passing static-string-expression, if present, as the message associated with the exception). If no string expression is given the default is a string giving the file name and line number of the pragma.

The Debug pragma causes procedure to be called. Note that pragma Debug may appear within a declaration sequence, allowing debugging procedures to be called between declarations.


Next: , Previous: Stack Overflow Checking, Up: Switches for gcc

3.2.4 Validity Checking

The Ada 95 Reference Manual has specific requirements for checking for invalid values. In particular, RM 13.9.1 requires that the evaluation of invalid values (for example from unchecked conversions), not result in erroneous execution. In GNAT, the result of such an evaluation in normal default mode is to either use the value unmodified, or to raise Constraint_Error in those cases where use of the unmodified value would cause erroneous execution. The cases where unmodified values might lead to erroneous execution are case statements (where a wild jump might result from an invalid value), and subscripts on the left hand side (where memory corruption could occur as a result of an invalid value).

The -gnatVx switch allows more control over the validity checking mode. The x argument is a string of letters that indicate validity checks that are performed or not performed in addition to the default checks described above.

-gnatVa
All validity checks. All validity checks are turned on. That is, -gnatVa is equivalent to gnatVcdfimorst.
-gnatVc
Validity checks for copies. The right hand side of assignments, and the initializing values of object declarations are validity checked.
-gnatVd
Default (RM) validity checks. Some validity checks are done by default following normal Ada semantics (RM 13.9.1 (9-11)). A check is done in case statements that the expression is within the range of the subtype. If it is not, Constraint_Error is raised. For assignments to array components, a check is done that the expression used as index is within the range. If it is not, Constraint_Error is raised. Both these validity checks may be turned off using switch -gnatVD. They are turned on by default. If -gnatVD is specified, a subsequent switch -gnatVd will leave the checks turned on. Switch -gnatVD should be used only if you are sure that all such expressions have valid values. If you use this switch and invalid values are present, then the program is erroneous, and wild jumps or memory overwriting may occur.
-gnatVf
Validity checks for floating-point values. In the absence of this switch, validity checking occurs only for discrete values. If -gnatVf is specified, then validity checking also applies for floating-point values, and NaN's and infinities are considered invalid, as well as out of range values for constrained types. Note that this means that standard IEEE infinity mode is not allowed. The exact contexts in which floating-point values are checked depends on the setting of other options. For example, -gnatVif or -gnatVfi (the order does not matter) specifies that floating-point parameters of mode in should be validity checked.
-gnatVi
Validity checks for in mode parameters Arguments for parameters of mode in are validity checked in function and procedure calls at the point of call.
-gnatVm
Validity checks for in out mode parameters. Arguments for parameters of mode in out are validity checked in procedure calls at the point of call. The 'm' here stands for modify, since this concerns parameters that can be modified by the call. Note that there is no specific option to test out parameters, but any reference within the subprogram will be tested in the usual manner, and if an invalid value is copied back, any reference to it will be subject to validity checking.
-gnatVn
No validity checks. This switch turns off all validity checking, including the default checking for case statements and left hand side subscripts. Note that the use of the switch -gnatp suppresses all run-time checks, including validity checks, and thus implies -gnatVn. When this switch is used, it cancels any other -gnatV previously issued.
-gnatVo
Validity checks for operator and attribute operands. Arguments for predefined operators and attributes are validity checked. This includes all operators in package Standard, the shift operators defined as intrinsic in package Interfaces and operands for attributes such as Pos. Checks are also made on individual component values for composite comparisons.
-gnatVp
Validity checks for parameters. This controls the treatment of parameters within a subprogram (as opposed to -gnatVi and -gnatVm which control validity testing of parameters on a call. If either of these call options is used, then normally an assumption is made within a subprogram that the input arguments have been validity checking at the point of call, and do not need checking again within a subprogram). If -gnatVp is set, then this assumption is not made, and parameters are not assumed to be valid, so their validity will be checked (or rechecked) within the subprogram.
-gnatVr
Validity checks for function returns. The expression in return statements in functions is validity checked.
-gnatVs
Validity checks for subscripts. All subscripts expressions are checked for validity, whether they appear on the right side or left side (in default mode only left side subscripts are validity checked).
-gnatVt
Validity checks for tests. Expressions used as conditions in if, while or exit statements are checked, as well as guard expressions in entry calls.

The -gnatV switch may be followed by a string of letters to turn on a series of validity checking options. For example, -gnatVcr specifies that in addition to the default validity checking, copies and function return expressions are to be validity checked. In order to make it easier to specify the desired combination of effects, the upper case letters CDFIMORST may be used to turn off the corresponding lower case option. Thus -gnatVaM turns on all validity checking options except for checking of in out procedure arguments.

The specification of additional validity checking generates extra code (and in the case of -gnatVa the code expansion can be substantial. However, these additional checks can be very useful in detecting uninitialized variables, incorrect use of unchecked conversion, and other errors leading to invalid values. The use of pragma Initialize_Scalars is useful in conjunction with the extra validity checking, since this ensures that wherever possible uninitialized variables have invalid values.

See also the pragma Validity_Checks which allows modification of the validity checking mode at the program source level, and also allows for temporary disabling of validity checks.


Next: , Previous: Validity Checking, Up: Switches for gcc

3.2.5 Style Checking

The -gnatyx switch causes the compiler to enforce specified style rules. A limited set of style rules has been used in writing the GNAT sources themselves. This switch allows user programs to activate all or some of these checks. If the source program fails a specified style check, an appropriate warning message is given, preceded by the character sequence “(style)”. The string x is a sequence of letters or digits indicating the particular style checks to be performed. The following checks are defined:

1-9
Specify indentation level. If a digit from 1-9 appears in the string after -gnaty then proper indentation is checked, with the digit indicating the indentation level required. The general style of required indentation is as specified by the examples in the Ada Reference Manual. Full line comments must be aligned with the -- starting on a column that is a multiple of the alignment level.
a
Check attribute casing. If the letter a appears in the string after -gnaty then attribute names, including the case of keywords such as digits used as attributes names, must be written in mixed case, that is, the initial letter and any letter following an underscore must be uppercase. All other letters must be lowercase.
b
Blanks not allowed at statement end. If the letter b appears in the string after -gnaty then trailing blanks are not allowed at the end of statements. The purpose of this rule, together with h (no horizontal tabs), is to enforce a canonical format for the use of blanks to separate source tokens.
c
Check comments. If the letter c appears in the string after -gnaty then comments must meet the following set of rules:
e
Check end/exit labels. If the letter e appears in the string after -gnaty then optional labels on end statements ending subprograms and on exit statements exiting named loops, are required to be present.
f
No form feeds or vertical tabs. If the letter f appears in the string after -gnaty then neither form feeds nor vertical tab characters are not permitted in the source text.
h
No horizontal tabs. If the letter h appears in the string after -gnaty then horizontal tab characters are not permitted in the source text. Together with the b (no blanks at end of line) check, this enforces a canonical form for the use of blanks to separate source tokens.
i
Check if-then layout. If the letter i appears in the string after -gnaty, then the keyword then must appear either on the same line as corresponding if, or on a line on its own, lined up under the if with at least one non-blank line in between containing all or part of the condition to be tested.
k
Check keyword casing. If the letter k appears in the string after -gnaty then all keywords must be in lower case (with the exception of keywords such as digits used as attribute names to which this check does not apply).
l
Check layout. If the letter l appears in the string after -gnaty then layout of statement and declaration constructs must follow the recommendations in the Ada Reference Manual, as indicated by the form of the syntax rules. For example an else keyword must be lined up with the corresponding if keyword.

There are two respects in which the style rule enforced by this check option are more liberal than those in the Ada Reference Manual. First in the case of record declarations, it is permissible to put the record keyword on the same line as the type keyword, and then the end in end record must line up under type. For example, either of the following two layouts is acceptable:

          

type q is record a : integer; b : integer; end record; type q is record a : integer; b : integer; end record;

Second, in the case of a block statement, a permitted alternative is to put the block label on the same line as the declare or begin keyword, and then line the end keyword up under the block label. For example both the following are permitted:

          

Block : declare A : Integer := 3; begin Proc (A, A); end Block; Block : declare A : Integer := 3; begin Proc (A, A); end Block;

The same alternative format is allowed for loops. For example, both of the following are permitted:

          

Clear : while J < 10 loop A (J) := 0; end loop Clear; Clear : while J < 10 loop A (J) := 0; end loop Clear;

m
Check maximum line length. If the letter m appears in the string after -gnaty then the length of source lines must not exceed 79 characters, including any trailing blanks. The value of 79 allows convenient display on an 80 character wide device or window, allowing for possible special treatment of 80 character lines. Note that this count is of raw characters in the source text. This means that a tab character counts as one character in this count and a wide character sequence counts as several characters (however many are needed in the encoding).
Mnnn
Set maximum line length. If the sequence Mnnn, where nnn is a decimal number, appears in the string after -gnaty then the length of lines must not exceed the given value.
n
Check casing of entities in Standard. If the letter n appears in the string after -gnaty then any identifier from Standard must be cased to match the presentation in the Ada Reference Manual (for example, Integer and ASCII.NUL).
o
Check order of subprogram bodies. If the letter o appears in the string after -gnaty then all subprogram bodies in a given scope (e.g. a package body) must be in alphabetical order. The ordering rule uses normal Ada rules for comparing strings, ignoring casing of letters, except that if there is a trailing numeric suffix, then the value of this suffix is used in the ordering (e.g. Junk2 comes before Junk10).
p
Check pragma casing. If the letter p appears in the string after -gnaty then pragma names must be written in mixed case, that is, the initial letter and any letter following an underscore must be uppercase. All other letters must be lowercase.
r
Check references. If the letter r appears in the string after -gnaty then all identifier references must be cased in the same way as the corresponding declaration. No specific casing style is imposed on identifiers. The only requirement is for consistency of references with declarations.
s
Check separate specs. If the letter s appears in the string after -gnaty then separate declarations (“specs”) are required for subprograms (a body is not allowed to serve as its own declaration). The only exception is that parameterless library level procedures are not required to have a separate declaration. This exception covers the most frequent form of main program procedures.
t
Check token spacing. If the letter t appears in the string after -gnaty then the following token spacing rules are enforced:

In the above rules, appearing in column one is always permitted, that is, counts as meeting either a requirement for a required preceding space, or as meeting a requirement for no preceding space.

Appearing at the end of a line is also always permitted, that is, counts as meeting either a requirement for a following space, or as meeting a requirement for no following space.

If any of these style rules is violated, a message is generated giving details on the violation. The initial characters of such messages are always “(style)”. Note that these messages are treated as warning messages, so they normally do not prevent the generation of an object file. The -gnatwe switch can be used to treat warning messages, including style messages, as fatal errors.

The switch -gnaty on its own (that is not followed by any letters or digits), is equivalent to gnaty3abcefhiklmprst, that is all checking options enabled with the exception of -gnatyo, with an indentation level of 3. This is the standard checking option that is used for the GNAT sources.


Next: , Previous: Debugging and Assertion Control, Up: Switches for gcc

3.2.6 Run-Time Checks

If you compile with the default options, GNAT will insert many run-time checks into the compiled code, including code that performs range checking against constraints, but not arithmetic overflow checking for integer operations (including division by zero) or checks for access before elaboration on subprogram calls. All other run-time checks, as required by the Ada 95 Reference Manual, are generated by default. The following gcc switches refine this default behavior:

-gnatp
Suppress all run-time checks as though pragma Suppress (all_checks) had been present in the source. Validity checks are also suppressed (in other words -gnatp also implies -gnatVn. Use this switch to improve the performance of the code at the expense of safety in the presence of invalid data or program bugs.
-gnato
Enables overflow checking for integer operations. This causes GNAT to generate slower and larger executable programs by adding code to check for overflow (resulting in raising Constraint_Error as required by standard Ada semantics). These overflow checks correspond to situations in which the true value of the result of an operation may be outside the base range of the result type. The following example shows the distinction:
          X1 : Integer := Integer'Last;
          X2 : Integer range 1 .. 5 := 5;
          X3 : Integer := Integer'Last;
          X4 : Integer range 1 .. 5 := 5;
          F  : Float := 2.0E+20;
          ...
          X1 := X1 + 1;
          X2 := X2 + 1;
          X3 := Integer (F);
          X4 := Integer (F);
     

Here the first addition results in a value that is outside the base range of Integer, and hence requires an overflow check for detection of the constraint error. Thus the first assignment to X1 raises a Constraint_Error exception only if -gnato is set.

The second increment operation results in a violation of the explicit range constraint, and such range checks are always performed (unless specifically suppressed with a pragma suppress or the use of -gnatp).

The two conversions of F both result in values that are outside the base range of type Integer and thus will raise Constraint_Error exceptions only if -gnato is used. The fact that the result of the second conversion is assigned to variable X4 with a restricted range is irrelevant, since the problem is in the conversion, not the assignment.

Basically the rule is that in the default mode (-gnato not used), the generated code assures that all integer variables stay within their declared ranges, or within the base range if there is no declared range. This prevents any serious problems like indexes out of range for array operations.

What is not checked in default mode is an overflow that results in an in-range, but incorrect value. In the above example, the assignments to X1, X2, X3 all give results that are within the range of the target variable, but the result is wrong in the sense that it is too large to be represented correctly. Typically the assignment to X1 will result in wrap around to the largest negative number. The conversions of F will result in some Integer value and if that integer value is out of the X4 range then the subsequent assignment would generate an exception.

Note that the -gnato switch does not affect the code generated for any floating-point operations; it applies only to integer semantics). For floating-point, GNAT has the Machine_Overflows attribute set to False and the normal mode of operation is to generate IEEE NaN and infinite values on overflow or invalid operations (such as dividing 0.0 by 0.0).

The reason that we distinguish overflow checking from other kinds of range constraint checking is that a failure of an overflow check can generate an incorrect value, but cannot cause erroneous behavior. This is unlike the situation with a constraint check on an array subscript, where failure to perform the check can result in random memory description, or the range check on a case statement, where failure to perform the check can cause a wild jump.

Note again that -gnato is off by default, so overflow checking is not performed in default mode. This means that out of the box, with the default settings, GNAT does not do all the checks expected from the language description in the Ada Reference Manual. If you want all constraint checks to be performed, as described in this Manual, then you must explicitly use the -gnato switch either on the gnatmake or gcc command.

-gnatE
Enables dynamic checks for access-before-elaboration on subprogram calls and generic instantiations. For full details of the effect and use of this switch, See Compiling Using gcc.

The setting of these switches only controls the default setting of the checks. You may modify them using either Suppress (to remove checks) or Unsuppress (to add back suppressed checks) pragmas in the program source.


Next: , Previous: Run-Time Checks, Up: Switches for gcc

3.2.7 Stack Overflow Checking

For most operating systems, gcc does not perform stack overflow checking by default. This means that if the main environment task or some other task exceeds the available stack space, then unpredictable behavior will occur.

To activate stack checking, compile all units with the gcc option -fstack-check. For example:

     gcc -c -fstack-check package1.adb

Units compiled with this option will generate extra instructions to check that any use of the stack (for procedure calls or for declaring local variables in declare blocks) do not exceed the available stack space. If the space is exceeded, then a Storage_Error exception is raised.

For declared tasks, the stack size is always controlled by the size given in an applicable Storage_Size pragma (or is set to the default size if no pragma is used.

For the environment task, the stack size depends on system defaults and is unknown to the compiler. The stack may even dynamically grow on some systems, precluding the normal Ada semantics for stack overflow. In the worst case, unbounded stack usage, causes unbounded stack expansion resulting in the system running out of virtual memory.

The stack checking may still work correctly if a fixed size stack is allocated, but this cannot be guaranteed. To ensure that a clean exception is signalled for stack overflow, set the environment variable GNAT_STACK_LIMIT to indicate the maximum stack area that can be used, as in:

     SET GNAT_STACK_LIMIT 1600

The limit is given in kilobytes, so the above declaration would set the stack limit of the environment task to 1.6 megabytes. Note that the only purpose of this usage is to limit the amount of stack used by the environment task. If it is necessary to increase the amount of stack for the environment task, then this is an operating systems issue, and must be addressed with the appropriate operating systems commands.


Next: , Previous: Style Checking, Up: Switches for gcc

3.2.8 Using gcc for Syntax Checking

-gnats
The s stands for “syntax”.

Run GNAT in syntax checking only mode. For example, the command

          $ gcc -c -gnats x.adb
     

compiles file x.adb in syntax-check-only mode. You can check a series of files in a single command , and can use wild cards to specify such a group of files. Note that you must specify the -c (compile only) flag in addition to the -gnats flag. . You may use other switches in conjunction with -gnats. In particular, -gnatl and -gnatv are useful to control the format of any generated error messages.

When the source file is empty or contains only empty lines and/or comments, the output is a warning:

          $ gcc -c -gnats -x ada toto.txt
          toto.txt:1:01: warning: empty file, contains no compilation units
          $
     

Otherwise, the output is simply the error messages, if any. No object file or ALI file is generated by a syntax-only compilation. Also, no units other than the one specified are accessed. For example, if a unit X with's a unit Y, compiling unit X in syntax check only mode does not access the source file containing unit Y.

Normally, GNAT allows only a single unit in a source file. However, this restriction does not apply in syntax-check-only mode, and it is possible to check a file containing multiple compilation units concatenated together. This is primarily used by the gnatchop utility (see Renaming Files Using gnatchop).


Next: , Previous: Using gcc for Syntax Checking, Up: Switches for gcc

3.2.9 Using gcc for Semantic Checking

-gnatc
The c stands for “check”. Causes the compiler to operate in semantic check mode, with full checking for all illegalities specified in the Ada 95 Reference Manual, but without generation of any object code (no object file is generated).

Because dependent files must be accessed, you must follow the GNAT semantic restrictions on file structuring to operate in this mode:

The output consists of error messages as appropriate. No object file is generated. An ALI file is generated for use in the context of cross-reference tools, but this file is marked as not being suitable for binding (since no object file is generated). The checking corresponds exactly to the notion of legality in the Ada 95 Reference Manual.

Any unit can be compiled in semantics-checking-only mode, including units that would not normally be compiled (subunits, and specifications where a separate body is present).


Next: , Previous: Using gcc for Semantic Checking, Up: Switches for gcc

3.2.10 Compiling Ada 83 Programs

-gnat83
Although GNAT is primarily an Ada 95 compiler, it accepts this switch to specify that an Ada 83 program is to be compiled in Ada 83 mode. If you specify this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics where this can be done easily. It is not possible to guarantee this switch does a perfect job; for example, some subtle tests, such as are found in earlier ACVC tests (and that have been removed from the ACATS suite for Ada 95), might not compile correctly. Nevertheless, this switch may be useful in some circumstances, for example where, due to contractual reasons, legacy code needs to be maintained using only Ada 83 features.

With few exceptions (most notably the need to use <> on unconstrained generic formal parameters, the use of the new Ada 95 reserved words, and the use of packages with optional bodies), it is not necessary to use the -gnat83 switch when compiling Ada 83 programs, because, with rare exceptions, Ada 95 is upwardly compatible with Ada 83. This means that a correct Ada 83 program is usually also a correct Ada 95 program. For further information, please refer to Compatibility and Porting Guide.


Next: , Previous: Compiling Ada 83 Programs, Up: Switches for gcc

3.2.11 Character Set Control

-gnatic
Normally GNAT recognizes the Latin-1 character set in source program identifiers, as described in the Ada 95 Reference Manual. This switch causes GNAT to recognize alternate character sets in identifiers. c is a single character indicating the character set, as follows:
1
ISO 8859-1 (Latin-1) identifiers
2
ISO 8859-2 (Latin-2) letters allowed in identifiers
3
ISO 8859-3 (Latin-3) letters allowed in identifiers
4
ISO 8859-4 (Latin-4) letters allowed in identifiers
5
ISO 8859-5 (Cyrillic) letters allowed in identifiers
9
ISO 8859-15 (Latin-9) letters allowed in identifiers
p
IBM PC letters (code page 437) allowed in identifiers
8
IBM PC letters (code page 850) allowed in identifiers
f
Full upper-half codes allowed in identifiers
n
No upper-half codes allowed in identifiers
w
Wide-character codes (that is, codes greater than 255) allowed in identifiers

See Foreign Language Representation, for full details on the implementation of these character sets.

-gnatWe
Specify the method of encoding for wide characters. e is one of the following:
h
Hex encoding (brackets coding also recognized)
u
Upper half encoding (brackets encoding also recognized)
s
Shift/JIS encoding (brackets encoding also recognized)
e
EUC encoding (brackets encoding also recognized)
8
UTF-8 encoding (brackets encoding also recognized)
b
Brackets encoding only (default value)
For full details on the these encoding methods see See Wide Character Encodings. Note that brackets coding is always accepted, even if one of the other options is specified, so for example -gnatW8 specifies that both brackets and UTF-8 encodings will be recognized. The units that are with'ed directly or indirectly will be scanned using the specified representation scheme, and so if one of the non-brackets scheme is used, it must be used consistently throughout the program. However, since brackets encoding is always recognized, it may be conveniently used in standard libraries, allowing these libraries to be used with any of the available coding schemes. scheme. If no -gnatW? parameter is present, then the default representation is Brackets encoding only.

Note that the wide character representation that is specified (explicitly or by default) for the main program also acts as the default encoding used for Wide_Text_IO files if not specifically overridden by a WCEM form parameter.


Next: , Previous: Character Set Control, Up: Switches for gcc

3.2.12 File Naming Control

-gnatkn
Activates file name “krunching”. n, a decimal integer in the range 1-999, indicates the maximum allowable length of a file name (not including the .ads or .adb extension). The default is not to enable file name krunching.

For the source file naming rules, See File Naming Rules.


Next: , Previous: File Naming Control, Up: Switches for gcc

3.2.13 Subprogram Inlining Control

-gnatn
The n here is intended to suggest the first syllable of the word “inline”. GNAT recognizes and processes Inline pragmas. However, for the inlining to actually occur, optimization must be enabled. To enable inlining of subprograms specified by pragma Inline, you must also specify this switch. In the absence of this switch, GNAT does not attempt inlining and does not need to access the bodies of subprograms for which pragma Inline is specified if they are not in the current unit.

If you specify this switch the compiler will access these bodies, creating an extra source dependency for the resulting object file, and where possible, the call will be inlined. For further details on when inlining is possible see See Inlining of Subprograms.

-gnatN
The front end inlining activated by this switch is generally more extensive, and quite often more effective than the standard -gnatn inlining mode. It will also generate additional dependencies. Note that -gnatN automatically implies -gnatn so it is not necessary to specify both options.


Next: , Previous: Subprogram Inlining Control, Up: Switches for gcc

3.2.14 Auxiliary Output Control

-gnatt
Causes GNAT to write the internal tree for a unit to a file (with the extension .adt. This not normally required, but is used by separate analysis tools. Typically these tools do the necessary compilations automatically, so you should not have to specify this switch in normal operation.
-gnatu
Print a list of units required by this compilation on stdout. The listing includes all units on which the unit being compiled depends either directly or indirectly.
-pass-exit-codes
If this switch is not used, the exit code returned by gcc when compiling multiple files indicates whether all source files have been successfully used to generate object files or not.

When -pass-exit-codes is used, gcc exits with an extended exit status and allows an integrated development environment to better react to a compilation failure. Those exit status are:

5
There was an error in at least one source file.
3
At least one source file did not generate an object file.
2
The compiler died unexpectedly (internal error for example).
0
An object file has been generated for every source file.


Next: , Previous: Auxiliary Output Control, Up: Switches for gcc

3.2.15 Debugging Control

-gnatdx
Activate internal debugging switches. x is a letter or digit, or string of letters or digits, which specifies the type of debugging outputs desired. Normally these are used only for internal development or system debugging purposes. You can find full documentation for these switches in the body of the Debug unit in the compiler source file debug.adb.
-gnatG
This switch causes the compiler to generate auxiliary output containing a pseudo-source listing of the generated expanded code. Like most Ada compilers, GNAT works by first transforming the high level Ada code into lower level constructs. For example, tasking operations are transformed into calls to the tasking run-time routines. A unique capability of GNAT is to list this expanded code in a form very close to normal Ada source. This is very useful in understanding the implications of various Ada usage on the efficiency of the generated code. There are many cases in Ada (e.g. the use of controlled types), where simple Ada statements can generate a lot of run-time code. By using -gnatG you can identify these cases, and consider whether it may be desirable to modify the coding approach to improve efficiency.

The format of the output is very similar to standard Ada source, and is easily understood by an Ada programmer. The following special syntactic additions correspond to low level features used in the generated code that do not have any exact analogies in pure Ada source form. The following is a partial list of these special constructions. See the specification of package Sprint in file sprint.ads for a full list.

new xxx [storage_pool = yyy]
Shows the storage pool being used for an allocator.
at end procedure-name;
Shows the finalization (cleanup) procedure for a scope.
(if expr then expr else expr)
Conditional expression equivalent to the x?y:z construction in C.
target^(source)
A conversion with floating-point truncation instead of rounding.
target?(source)
A conversion that bypasses normal Ada semantic checking. In particular enumeration types and fixed-point types are treated simply as integers.
target?^(source)
Combines the above two cases.
x #/ y
x #mod y
x #* y
x #rem y
A division or multiplication of fixed-point values which are treated as integers without any kind of scaling.
free expr [storage_pool = xxx]
Shows the storage pool associated with a free statement.
freeze typename [actions]
Shows the point at which typename is frozen, with possible associated actions to be performed at the freeze point.
reference itype
Reference (and hence definition) to internal type itype.
function-name! (arg, arg, arg)
Intrinsic function call.
labelname : label
Declaration of label labelname.
expr && expr && expr ... && expr
A multiple concatenation (same effect as expr & expr & expr, but handled more efficiently).
[constraint_error]
Raise the Constraint_Error exception.
expression'reference
A pointer to the result of evaluating expression.
target-type!(source-expression)
An unchecked conversion of source-expression to target-type.
[numerator/denominator]
Used to represent internal real literals (that) have no exact representation in base 2-16 (for example, the result of compile time evaluation of the expression 1.0/27.0).

-gnatD
This switch is used in conjunction with -gnatG to cause the expanded source, as described above to be written to files with names xxx.dg, where xxx is the normal file name, for example, if the source file name is hello.adb, then a file hello.adb.dg will be written. The debugging information generated by the gcc -g switch will refer to the generated xxx.dg file. This allows you to do source level debugging using the generated code which is sometimes useful for complex code, for example to find out exactly which part of a complex construction raised an exception. This switch also suppress generation of cross-reference information (see -gnatx).
-gnatR[0|1|2|3[s]]
This switch controls output from the compiler of a listing showing representation information for declared types and objects. For -gnatR0, no information is output (equivalent to omitting the -gnatR switch). For -gnatR1 (which is the default, so -gnatR with no parameter has the same effect), size and alignment information is listed for declared array and record types. For -gnatR2, size and alignment information is listed for all expression information for values that are computed at run time for variant records. These symbolic expressions have a mostly obvious format with #n being used to represent the value of the n'th discriminant. See source files repinfo.ads/adb in the GNAT sources for full details on the format of -gnatR3 output. If the switch is followed by an s (e.g. -gnatR2s), then the output is to a file with the name file.rep where file is the name of the corresponding source file.
-gnatS
The use of the switch -gnatS for an Ada compilation will cause the compiler to output a representation of package Standard in a form very close to standard Ada. It is not quite possible to do this and remain entirely Standard (since new numeric base types cannot be created in standard Ada), but the output is easily readable to any Ada programmer, and is useful to determine the characteristics of target dependent types in package Standard.
-gnatx
Normally the compiler generates full cross-referencing information in the ALI file. This information is used by a number of tools, including gnatfind and gnatxref. The -gnatx switch suppresses this information. This saves some space and may slightly speed up compilation, but means that these tools cannot be used.


Next: , Previous: Debugging Control, Up: Switches for gcc

3.2.16 Exception Handling Control

GNAT uses two methods for handling exceptions at run-time. The longjmp/setjmp method saves the context when entering a frame with an exception handler. Then when an exception is raised, the context can be restored immediately, without the need for tracing stack frames. This method provides very fast exception propagation, but introduces significant overhead for the use of exception handlers, even if no exception is raised.

The other approach is called “zero cost” exception handling. With this method, the compiler builds static tables to describe the exception ranges. No dynamic code is required when entering a frame containing an exception handler. When an exception is raised, the tables are used to control a back trace of the subprogram invocation stack to locate the required exception handler. This method has considerably poorer performance for the propagation of exceptions, but there is no overhead for exception handlers if no exception is raised.

The following switches can be used to control which of the two exception handling methods is used.

-gnatL
This switch causes the longjmp/setjmp approach to be used for exception handling. If this is the default mechanism for the target (see below), then this has no effect. If the default mechanism for the target is zero cost exceptions, then this switch can be used to modify this default, but it must be used for all units in the partition, including all run-time library units. One way to achieve this is to use the -a and -f switches for gnatmake. This option is rarely used. One case in which it may be advantageous is if you have an application where exception raising is common and the overall performance of the application is improved by favoring exception propagation.
-gnatZ
This switch causes the zero cost approach to be sed for exception handling. If this is the default mechanism for the target (see below), then this has no effect. If the default mechanism for the target is longjmp/setjmp exceptions, then this switch can be used to modify this default, but it must be used for all units in the partition, including all run-time library units. One way to achieve this is to use the -a and -f switches for gnatmake. This option can only be used if the zero cost approach is available for the target in use (see below).

The longjmp/setjmp approach is available on all targets, but the zero cost approach is only available on selected targets. To determine whether zero cost exceptions can be used for a particular target, look at the private part of the file system.ads. Either GCC_ZCX_Support or Front_End_ZCX_Support must be True to use the zero cost approach. If both of these switches are set to False, this means that zero cost exception handling is not yet available for that target. The switch ZCX_By_Default indicates the default approach. If this switch is set to True, then the zero cost approach is used by default.


Next: , Previous: Exception Handling Control, Up: Switches for gcc

3.2.17 Units to Sources Mapping Files

-gnatempath
A mapping file is a way to communicate to the compiler two mappings: from unit names to file names (without any directory information) and from file names to path names (with full directory information). These mappings are used by the compiler to short-circuit the path search.

The use of mapping files is not required for correct operation of the compiler, but mapping files can improve efficiency, particularly when sources are read over a slow network connection. In normal operation, you need not be concerned with the format or use of mapping files, and the -gnatem switch is not a switch that you would use explicitly. it is intended only for use by automatic tools such as gnatmake running under the project file facility. The description here of the format of mapping files is provided for completeness and for possible use by other tools.

A mapping file is a sequence of sets of three lines. In each set, the first line is the unit name, in lower case, with “%s” appended for specifications and “%b” appended for bodies; the second line is the file name; and the third line is the path name.

Example:

             main%b
             main.2.ada
             /gnat/project1/sources/main.2.ada
     

When the switch -gnatem is specified, the compiler will create in memory the two mappings from the specified file. If there is any problem (non existent file, truncated file or duplicate entries), no mapping will be created.

Several -gnatem switches may be specified; however, only the last one on the command line will be taken into account.

When using a project file, gnatmake create a temporary mapping file and communicates it to the compiler using this switch.


Previous: Units to Sources Mapping Files, Up: Switches for gcc

3.2.18 Integrated Preprocessing

GNAT sources may be preprocessed immediately before compilation; the actual text of the source is not the text of the source file, but is derived from it through a process called preprocessing. Integrated preprocessing is specified through switches -gnatep and/or -gnateD. -gnatep indicates, through a text file, the preprocessing data to be used. -gnateD specifies or modifies the values of preprocessing symbol.

It is recommended that gnatmake switch -s should be used when Integrated Preprocessing is used. The reason is that preprocessing with another Preprocessing Data file without changing the sources will not trigger recompilation without this switch.

Note that gnatmake switch -m will almost always trigger recompilation for sources that are preprocessed, because gnatmake cannot compute the checksum of the source after preprocessing.

The actual preprocessing function is described in details in section Preprocessing Using gnatprep. This section only describes how integrated preprocessing is triggered and parameterized.

-gnatep=file
This switch indicates to the compiler the file name (without directory information) of the preprocessor data file to use. The preprocessor data file should be found in the source directories.

A preprocessing data file is a text file with significant lines indicating how should be preprocessed either a specific source or all sources not mentioned in other lines. A significant line is a non empty, non comment line. Comments are similar to Ada comments.

Each significant line starts with either a literal string or the character '*'. A literal string is the file name (without directory information) of the source to preprocess. A character '*' indicates the preprocessing for all the sources that are not specified explicitly on other lines (order of the lines is not significant). It is an error to have two lines with the same file name or two lines starting with the character '*'.

After the file name or the character '*', another optional literal string indicating the file name of the definition file to be used for preprocessing. (see Form of Definitions File. The definition files are found by the compiler in one of the source directories. In some cases, when compiling a source in a directory other than the current directory, if the definition file is in the current directory, it may be necessary to add the current directory as a source directory through switch -I., otherwise the compiler would not find the definition file.

Then, optionally, switches similar to those of gnatprep may be found. Those switches are:

-b
Causes both preprocessor lines and the lines deleted by preprocessing to be replaced by blank lines, preserving the line number. This switch is always implied; however, if specified after -c it cancels the effect of -c.
-c
Causes both preprocessor lines and the lines deleted by preprocessing to be retained as comments marked with the special string “--! ”.
-Dsymbol=value
Define or redefine a symbol, associated with value. A symbol is an Ada identifier, or an Ada reserved word, with the exception of if, else, elsif, end, and, or and then. value is either a literal string, an Ada identifier or any Ada reserved word. A symbol declared with this switch replaces a symbol with the same name defined in a definition file.
-s
Causes a sorted list of symbol names and values to be listed on the standard output file.
-u
Causes undefined symbols to be treated as having the value FALSE in the context of a preprocessor test. In the absence of this option, an undefined symbol in a #if or #elsif test will be treated as an error.

Examples of valid lines in a preprocessor data file:

            "toto.adb"  "prep.def" -u
            --  preprocess "toto.adb", using definition file "prep.def",
            --  undefined symbol are False.
          
            * -c -DVERSION=V101
            --  preprocess all other sources without a definition file;
            --  suppressed lined are commented; symbol VERSION has the value V101.
          
            "titi.adb" "prep2.def" -s
            --  preprocess "titi.adb", using definition file "prep2.def";
            --  list all symbols with their values.
     

-gnateDsymbol[=value]
Define or redefine a preprocessing symbol, associated with value. If no value is given on the command line, then the value of the symbol is True. A symbol is an identifier, following normal Ada (case-insensitive) rules for its syntax, and value is any sequence (including an empty sequence) of characters from the set (letters, digits, period, underline). Ada reserved words may be used as symbols, with the exceptions of if, else, elsif, end, and, or and then.

A symbol declared with this switch on the command line replaces a symbol with the same name either in a definition file or specified with a switch -D in the preprocessor data file.

This switch is similar to switch -D of gnatprep.


Next: , Previous: Switches for gcc, Up: Compiling Using gcc

3.3 Search Paths and the Run-Time Library (RTL)

With the GNAT source-based library system, the compiler must be able to find source files for units that are needed by the unit being compiled. Search paths are used to guide this process.

The compiler compiles one source file whose name must be given explicitly on the command line. In other words, no searching is done for this file. To find all other source files that are needed (the most common being the specs of units), the compiler examines the following directories, in the following order:

  1. The directory containing the source file of the main unit being compiled (the file name on the command line).
  2. Each directory named by an -I switch given on the gcc command line, in the order given.
  3. Each of the directories listed in the value of the ADA_INCLUDE_PATH environment variable. Construct this value exactly as the PATH environment variable: a list of directory names separated by colons (semicolons when working with the NT version).
  4. Each of the directories listed in the text file whose name is given by the ADA_PRJ_INCLUDE_FILE environment variable.

    ADA_PRJ_INCLUDE_FILE is normally set by gnatmake or by the gnat driver when project files are used. It should not normally be set by other means.

  5. The content of the ada_source_path file which is part of the GNAT installation tree and is used to store standard libraries such as the GNAT Run Time Library (RTL) source files. Installing an Ada Library

Specifying the switch -I- inhibits the use of the directory containing the source file named in the command line. You can still have this directory on your search path, but in this case it must be explicitly requested with a -I switch.

Specifying the switch -nostdinc inhibits the search of the default location for the GNAT Run Time Library (RTL) source files.

The compiler outputs its object files and ALI files in the current working directory. Caution: The object file can be redirected with the -o switch; however, gcc and gnat1 have not been coordinated on this so the ALI file will not go to the right place. Therefore, you should avoid using the -o switch.

The packages Ada, System, and Interfaces and their children make up the GNAT RTL, together with the simple System.IO package used in the "Hello World" example. The sources for these units are needed by the compiler and are kept together in one directory. Not all of the bodies are needed, but all of the sources are kept together anyway. In a normal installation, you need not specify these directory names when compiling or binding. Either the environment variables or the built-in defaults cause these files to be found.

In addition to the language-defined hierarchies (System, Ada and Interfaces), the GNAT distribution provides a fourth hierarchy, consisting of child units of GNAT. This is a collection of generally useful types, subprograms, etc. See the GNAT Reference Manual for further details.

Besides simplifying access to the RTL, a major use of search paths is in compiling sources from multiple directories. This can make development environments much more flexible.


Next: , Previous: Search Paths and the Run-Time Library (RTL), Up: Compiling Using gcc

3.4 Order of Compilation Issues

If, in our earlier example, there was a spec for the hello procedure, it would be contained in the file hello.ads; yet this file would not have to be explicitly compiled. This is the result of the model we chose to implement library management. Some of the consequences of this model are as follows:


Previous: Order of Compilation Issues, Up: Compiling Using gcc

3.5 Examples

The following are some typical Ada compilation command line examples:

$ gcc -c xyz.adb
Compile body in file xyz.adb with all default options.
$ gcc -c -O2 -gnata xyz-def.adb
Compile the child unit package in file xyz-def.adb with extensive optimizations, and pragma Assert/Debug statements enabled.
$ gcc -c -gnatc abc-def.adb
Compile the subunit in file abc-def.adb in semantic-checking-only mode.


Next: , Previous: Compiling Using gcc, Up: Top

4 Binding Using gnatbind

This chapter describes the GNAT binder, gnatbind, which is used to bind compiled GNAT objects. The gnatbind program performs four separate functions:

  1. Checks that a program is consistent, in accordance with the rules in Chapter 10 of the Ada 95 Reference Manual. In particular, error messages are generated if a program uses inconsistent versions of a given unit.
  2. Checks that an acceptable order of elaboration exists for the program and issues an error message if it cannot find an order of elaboration that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
  3. Generates a main program incorporating the given elaboration order. This program is a small Ada package (body and spec) that must be subsequently compiled using the GNAT compiler. The necessary compilation step is usually performed automatically by gnatlink. The two most important functions of this program are to call the elaboration routines of units in an appropriate order and to call the main program.
  4. Determines the set of object files required by the given main program. This information is output in the forms of comments in the generated program, to be read by the gnatlink utility used to link the Ada application.


Next: , Up: Binding Using gnatbind

4.1 Running gnatbind

The form of the gnatbind command is

     $ gnatbind [switches] mainprog[.ali] [switches]

where mainprog.adb is the Ada file containing the main program unit body. If no switches are specified, gnatbind constructs an Ada package in two files whose names are b~mainprog.ads, and b~mainprog.adb. For example, if given the parameter hello.ali, for a main program contained in file hello.adb, the binder output files would be b~hello.ads and b~hello.adb.

When doing consistency checking, the binder takes into consideration any source files it can locate. For example, if the binder determines that the given main program requires the package Pack, whose .ALI file is pack.ali and whose corresponding source spec file is pack.ads, it attempts to locate the source file pack.ads (using the same search path conventions as previously described for the gcc command). If it can locate this source file, it checks that the time stamps or source checksums of the source and its references to in ALI files match. In other words, any ALI files that mentions this spec must have resulted from compiling this version of the source file (or in the case where the source checksums match, a version close enough that the difference does not matter).

The effect of this consistency checking, which includes source files, is that the binder ensures that the program is consistent with the latest version of the source files that can be located at bind time. Editing a source file without compiling files that depend on the source file cause error messages to be generated by the binder.

For example, suppose you have a main program hello.adb and a package P, from file p.ads and you perform the following steps:

  1. Enter gcc -c hello.adb to compile the main program.
  2. Enter gcc -c p.ads to compile package P.
  3. Edit file p.ads.
  4. Enter gnatbind hello.

At this point, the file p.ali contains an out-of-date time stamp because the file p.ads has been edited. The attempt at binding fails, and the binder generates the following error messages:

     error: "hello.adb" must be recompiled ("p.ads" has been modified)
     error: "p.ads" has been modified and must be recompiled

Now both files must be recompiled as indicated, and then the bind can succeed, generating a main program. You need not normally be concerned with the contents of this file, but for reference purposes a sample binder output file is given in Example of Binder Output File.

In most normal usage, the default mode of gnatbind which is to generate the main package in Ada, as described in the previous section. In particular, this means that any Ada programmer can read and understand the generated main program. It can also be debugged just like any other Ada code provided the -g switch is used for gnatbind and gnatlink.

However for some purposes it may be convenient to generate the main program in C rather than Ada. This may for example be helpful when you are generating a mixed language program with the main program in C. The GNAT compiler itself is an example. The use of the -C switch for both gnatbind and gnatlink will cause the program to be generated in C (and compiled using the gnu C compiler).


Next: , Previous: Running gnatbind, Up: Binding Using gnatbind

4.2 Switches for gnatbind

The following switches are available with gnatbind; details will be presented in subsequent sections.

-aO
Specify directory to be searched for ALI files.
-aI
Specify directory to be searched for source file.
-A
Generate binder program in Ada (default)
-b
Generate brief messages to stderr even if verbose mode set.
-c
Check only, no generation of binder output file.
-C
Generate binder program in C
-e
Output complete list of elaboration-order dependencies.
-E
Store tracebacks in exception occurrences when the target supports it. This is the default with the zero cost exception mechanism. See also the packages GNAT.Traceback and GNAT.Traceback.Symbolic for more information. Note that on x86 ports, you must not use -fomit-frame-pointer gcc option.
-F
Force the checks of elaboration flags. gnatbind does not normally generate checks of elaboration flags for the main executable, except when a Stand-Alone Library is used. However, there are cases when this cannot be detected by gnatbind. An example is importing an interface of a Stand-Alone Library through a pragma Import and only specifying through a linker switch this Stand-Alone Library. This switch is used to guarantee that elaboration flag checks are generated.
-h
Output usage (help) information
-I
Specify directory to be searched for source and ALI files.
-I-
Do not look for sources in the current directory where gnatbind was invoked, and do not look for ALI files in the directory containing the ALI file named in the gnatbind command line.
-l
Output chosen elaboration order.
-Lxxx
Binds the units for library building. In this case the adainit and adafinal procedures (See see Binding with Non-Ada Main Programs) are renamed to xxxinit and xxxfinal. Implies -n. (see GNAT and Libraries, for more details.)
-Mxyz
Rename generated main program from main to xyz
-mn
Limit number of detected errors to n, where n is in the range 1..999_999. The default value if no switch is given is 9999. Binding is terminated if the limit is exceeded. Furthermore, under Windows, the sources pointed to by the libraries path set in the registry are not searched for.
-n
No main program.
-nostdinc
Do not look for sources in the system default directory.
-nostdlib
Do not look for library files in the system default directory.
--RTS=rts-path
Specifies the default location of the runtime library. Same meaning as the equivalent gnatmake flag (see Switches for gnatmake).
-o file
Name the output file file (default is b~xxx.adb). Note that if this option is used, then linking must be done manually, gnatlink cannot be used.
-O
Output object list.
-p
Pessimistic (worst-case) elaboration order
-s
Require all source files to be present.
-Sxxx
Specifies the value to be used when detecting uninitialized scalar objects with pragma Initialize_Scalars. The xxx string specified with the switch may be either

In addition, you can specify -Sev to indicate that the value is to be set at run time. In this case, the program will look for an environment variable of the form GNAT_INIT_SCALARS=xx, where xx is one of in/lo/hi/xx with the same meanings as above. If no environment variable is found, or if it does not have a valid value, then the default is in (invalid values).

-static
Link against a static GNAT run time.
-shared
Link against a shared GNAT run time when available.
-t
Tolerate time stamp and other consistency errors
-Tn
Set the time slice value to n milliseconds. If the system supports the specification of a specific time slice value, then the indicated value is used. If the system does not support specific time slice values, but does support some general notion of round-robin scheduling, then any non-zero value will activate round-robin scheduling.

A value of zero is treated specially. It turns off time slicing, and in addition, indicates to the tasking run time that the semantics should match as closely as possible the Annex D requirements of the Ada RM, and in particular sets the default scheduling policy to FIFO_Within_Priorities.

-v
Verbose mode. Write error messages, header, summary output to stdout.
-wx
Warning mode (x=s/e for suppress/treat as error)
-x
Exclude source files (check object consistency only).
-z
No main subprogram.

You may obtain this listing of switches by running gnatbind with no arguments.


Next: , Up: Switches for gnatbind

4.2.1 Consistency-Checking Modes

As described earlier, by default gnatbind checks that object files are consistent with one another and are consistent with any source files it can locate. The following switches control binder access to sources.

-s
Require source files to be present. In this mode, the binder must be able to locate all source files that are referenced, in order to check their consistency. In normal mode, if a source file cannot be located it is simply ignored. If you specify this switch, a missing source file is an error.
-x
Exclude source files. In this mode, the binder only checks that ALI files are consistent with one another. Source files are not accessed. The binder runs faster in this mode, and there is still a guarantee that the resulting program is self-consistent. If a source file has been edited since it was last compiled, and you specify this switch, the binder will not detect that the object file is out of date with respect to the source file. Note that this is the mode that is automatically used by gnatmake because in this case the checking against sources has already been performed by gnatmake in the course of compilation (i.e. before binding).


Next: , Previous: Consistency-Checking Modes, Up: Switches for gnatbind

4.2.2 Binder Error Message Control

The following switches provide control over the generation of error messages from the binder:

-v
Verbose mode. In the normal mode, brief error messages are generated to stderr. If this switch is present, a header is written to stdout and any error messages are directed to stdout. All that is written to stderr is a brief summary message.
-b
Generate brief error messages to stderr even if verbose mode is specified. This is relevant only when used with the -v switch.
-mn
Limits the number of error messages to n, a decimal integer in the range 1-999. The binder terminates immediately if this limit is reached.
-Mxxx
Renames the generated main program from main to xxx. This is useful in the case of some cross-building environments, where the actual main program is separate from the one generated by gnatbind.
-ws
Suppress all warning messages.
-we
Treat any warning messages as fatal errors.
-t
The binder performs a number of consistency checks including:

Normally failure of such checks, in accordance with the consistency requirements of the Ada Reference Manual, causes error messages to be generated which abort the binder and prevent the output of a binder file and subsequent link to obtain an executable.

The -t switch converts these error messages into warnings, so that binding and linking can continue to completion even in the presence of such errors. The result may be a failed link (due to missing symbols), or a non-functional executable which has undefined semantics. This means that -t should be used only in unusual situations, with extreme care.


Next: , Previous: Binder Error Message Control, Up: Switches for gnatbind

4.2.3 Elaboration Control

The following switches provide additional control over the elaboration order. For full details see See Elaboration Order Handling in GNAT.

-p
Normally the binder attempts to choose an elaboration order that is likely to minimize the likelihood of an elaboration order error resulting in raising a Program_Error exception. This switch reverses the action of the binder, and requests that it deliberately choose an order that is likely to maximize the likelihood of an elaboration error. This is useful in ensuring portability and avoiding dependence on accidental fortuitous elaboration ordering.

Normally it only makes sense to use the -p switch if dynamic elaboration checking is used (-gnatE switch used for compilation). This is because in the default static elaboration mode, all necessary Elaborate_All pragmas are implicitly inserted. These implicit pragmas are still respected by the binder in -p mode, so a safe elaboration order is assured.


Next: , Previous: Elaboration Control, Up: Switches for gnatbind

4.2.4 Output Control

The following switches allow additional control over the output generated by the binder.

-A
Generate binder program in Ada (default). The binder program is named b~mainprog.adb by default. This can be changed with -o gnatbind option.
-c
Check only. Do not generate the binder output file. In this mode the binder performs all error checks but does not generate an output file.
-C
Generate binder program in C. The binder program is named b_mainprog.c. This can be changed with -o gnatbind option.
-e
Output complete list of elaboration-order dependencies, showing the reason for each dependency. This output can be rather extensive but may be useful in diagnosing problems with elaboration order. The output is written to stdout.
-h
Output usage information. The output is written to stdout.
-K
Output linker options to stdout. Includes library search paths, contents of pragmas Ident and Linker_Options, and libraries added by gnatbind.
-l
Output chosen elaboration order. The output is written to stdout.
-O
Output full names of all the object files that must be linked to provide the Ada component of the program. The output is written to stdout. This list includes the files explicitly supplied and referenced by the user as well as implicitly referenced run-time unit files. The latter are omitted if the corresponding units reside in shared libraries. The directory names for the run-time units depend on the system configuration.
-o file
Set name of output file to file instead of the normal b~mainprog.adb default. Note that file denote the Ada binder generated body filename. In C mode you would normally give file an extension of .c because it will be a C source program. Note that if this option is used, then linking must be done manually. It is not possible to use gnatlink in this case, since it cannot locate the binder file.
-r
Generate list of pragma Restrictions that could be applied to the current unit. This is useful for code audit purposes, and also may be used to improve code generation in some cases.


Next: , Previous: Output Control, Up: Switches for gnatbind

4.2.5 Binding with Non-Ada Main Programs

In our description so far we have assumed that the main program is in Ada, and that the task of the binder is to generate a corresponding function main that invokes this Ada main program. GNAT also supports the building of executable programs where the main program is not in Ada, but some of the called routines are written in Ada and compiled using GNAT (see Mixed Language Programming). The following switch is used in this situation:

-n
No main program. The main program is not in Ada.

In this case, most of the functions of the binder are still required, but instead of generating a main program, the binder generates a file containing the following callable routines:

adainit
You must call this routine to initialize the Ada part of the program by calling the necessary elaboration routines. A call to adainit is required before the first call to an Ada subprogram.

Note that it is assumed that the basic execution environment must be setup to be appropriate for Ada execution at the point where the first Ada subprogram is called. In particular, if the Ada code will do any floating-point operations, then the FPU must be setup in an appropriate manner. For the case of the x86, for example, full precision mode is required. The procedure GNAT.Float_Control.Reset may be used to ensure that the FPU is in the right state.

adafinal
You must call this routine to perform any library-level finalization required by the Ada subprograms. A call to adafinal is required after the last call to an Ada subprogram, and before the program terminates.

If the -n switch is given, more than one ALI file may appear on the command line for gnatbind. The normal closure calculation is performed for each of the specified units. Calculating the closure means finding out the set of units involved by tracing with references. The reason it is necessary to be able to specify more than one ALI file is that a given program may invoke two or more quite separate groups of Ada units.

The binder takes the name of its output file from the last specified ALI file, unless overridden by the use of the -o file. The output is an Ada unit in source form that can be compiled with GNAT unless the -C switch is used in which case the output is a C source file, which must be compiled using the C compiler. This compilation occurs automatically as part of the gnatlink processing.

Currently the GNAT run time requires a FPU using 80 bits mode precision. Under targets where this is not the default it is required to call GNAT.Float_Control.Reset before using floating point numbers (this include float computation, float input and output) in the Ada code. A side effect is that this could be the wrong mode for the foreign code where floating point computation could be broken after this call.


Previous: Binding with Non-Ada Main Programs, Up: Switches for gnatbind

4.2.6 Binding Programs with No Main Subprogram

It is possible to have an Ada program which does not have a main subprogram. This program will call the elaboration routines of all the packages, then the finalization routines.

The following switch is used to bind programs organized in this manner:

-z
Normally the binder checks that the unit name given on the command line corresponds to a suitable main subprogram. When this switch is used, a list of ALI files can be given, and the execution of the program consists of elaboration of these units in an appropriate order.


Next: , Previous: Switches for gnatbind, Up: Binding Using gnatbind

4.3 Command-Line Access

The package Ada.Command_Line provides access to the command-line arguments and program name. In order for this interface to operate correctly, the two variables

     int gnat_argc;
     char **gnat_argv;

are declared in one of the GNAT library routines. These variables must be set from the actual argc and argv values passed to the main program. With no n present, gnatbind generates the C main program to automatically set these variables. If the n switch is used, there is no automatic way to set these variables. If they are not set, the procedures in Ada.Command_Line will not be available, and any attempt to use them will raise Constraint_Error. If command line access is required, your main program must set gnat_argc and gnat_argv from the argc and argv values passed to it.


Next: , Previous: Command-Line Access, Up: Binding Using gnatbind

4.4 Search Paths for gnatbind

The binder takes the name of an ALI file as its argument and needs to locate source files as well as other ALI files to verify object consistency.

For source files, it follows exactly the same search rules as gcc (see Search Paths and the Run-Time Library (RTL)). For ALI files the directories searched are:

  1. The directory containing the ALI file named in the command line, unless the switch -I- is specified.
  2. All directories specified by -I switches on the gnatbind command line, in the order given.
  3. Each of the directories listed in the value of the ADA_OBJECTS_PATH environment variable. Construct this value exactly as the PATH environment variable: a list of directory names separated by colons (semicolons when working with the NT version of GNAT).
  4. Each of the directories listed in the text file whose name is given by the ADA_PRJ_OBJECTS_FILE environment variable.

    ADA_PRJ_OBJECTS_FILE is normally set by gnatmake or by the gnat driver when project files are used. It should not normally be set by other means.

  5. The content of the ada_object_path file which is part of the GNAT installation tree and is used to store standard libraries such as the GNAT Run Time Library (RTL) unless the switch -nostdlib is specified. Installing an Ada Library

In the binder the switch -I is used to specify both source and library file paths. Use -aI instead if you want to specify source paths only, and -aO if you want to specify library paths only. This means that for the binder -Idir is equivalent to -aIdir -aOdir. The binder generates the bind file (a C language source file) in the current working directory.

The packages Ada, System, and Interfaces and their children make up the GNAT Run-Time Library, together with the package GNAT and its children, which contain a set of useful additional library functions provided by GNAT. The sources for these units are needed by the compiler and are kept together in one directory. The ALI files and object files generated by compiling the RTL are needed by the binder and the linker and are kept together in one directory, typically different from the directory containing the sources. In a normal installation, you need not specify these directory names when compiling or binding. Either the environment variables or the built-in defaults cause these files to be found.

Besides simplifying access to the RTL, a major use of search paths is in compiling sources from multiple directories. This can make development environments much more flexible.


Previous: Search Paths for gnatbind, Up: Binding Using gnatbind

4.5 Examples of gnatbind Usage

This section contains a number of examples of using the GNAT binding utility gnatbind.

gnatbind hello
The main program Hello (source program in hello.adb) is bound using the standard switch settings. The generated main program is b~hello.adb. This is the normal, default use of the binder.
gnatbind hello -o mainprog.adb
The main program Hello (source program in hello.adb) is bound using the standard switch settings. The generated main program is mainprog.adb with the associated spec in mainprog.ads. Note that you must specify the body here not the spec, in the case where the output is in Ada. Note that if this option is used, then linking must be done manually, since gnatlink will not be able to find the generated file.
gnatbind main -C -o mainprog.c -x
The main program Main (source program in main.adb) is bound, excluding source files from the consistency checking, generating the file mainprog.c.
gnatbind -x main_program -C -o mainprog.c
This command is exactly the same as the previous example. Switches may appear anywhere in the command line, and single letter switches may be combined into a single switch.
gnatbind -n math dbase -C -o ada-control.c
The main program is in a language other than Ada, but calls to subprograms in packages Math and Dbase appear. This call to gnatbind generates the file ada-control.c containing the adainit and adafinal routines to be called before and after accessing the Ada units.


Next: , Previous: Binding Using gnatbind, Up: Top

5 Linking Using gnatlink

This chapter discusses gnatlink, a tool that links an Ada program and builds an executable file. This utility invokes the system linker (via the gcc command) with a correct list of object files and library references. gnatlink automatically determines the list of files and references for the Ada part of a program. It uses the binder file generated by the gnatbind to determine this list.


Next: , Up: Linking Using gnatlink

5.1 Running gnatlink

The form of the gnatlink command is

     $ gnatlink [switches] mainprog[.ali]
                [non-Ada objects] [linker options]

The arguments of gnatlink (switches, main ALI file, non-Ada objects or linker options) may be in any order, provided that no non-Ada object may be mistaken for a main ALI file. Any file name F without the .ali extension will be taken as the main ALI file if a file exists whose name is the concatenation of F and .ali.

mainprog.ali references the ALI file of the main program. The .ali extension of this file can be omitted. From this reference, gnatlink locates the corresponding binder file b~mainprog.adb and, using the information in this file along with the list of non-Ada objects and linker options, constructs a linker command file to create the executable.

The arguments other than the gnatlink switches and the main ALI file are passed to the linker uninterpreted. They typically include the names of object files for units written in other languages than Ada and any library references required to resolve references in any of these foreign language units, or in Import pragmas in any Ada units.

linker options is an optional list of linker specific switches. The default linker called by gnatlink is gcc which in turn calls the appropriate system linker. Standard options for the linker such as -lmy_lib or -Ldir can be added as is. For options that are not recognized by gcc as linker options, use the gcc switches -Xlinker or -Wl,. Refer to the GCC documentation for details. Here is an example showing how to generate a linker map:

     $ gnatlink my_prog -Wl,-Map,MAPFILE

Using linker options it is possible to set the program stack and heap size. See Setting Stack Size from gnatlink, and Setting Heap Size from gnatlink.

gnatlink determines the list of objects required by the Ada program and prepends them to the list of objects passed to the linker. gnatlink also gathers any arguments set by the use of pragma Linker_Options and adds them to the list of arguments presented to the linker.


Next: , Previous: Running gnatlink, Up: Linking Using gnatlink

5.2 Switches for gnatlink

The following switches are available with the gnatlink utility:

-A
The binder has generated code in Ada. This is the default.
-C
If instead of generating a file in Ada, the binder has generated one in C, then the linker needs to know about it. Use this switch to signal to gnatlink that the binder has generated C code rather than Ada code.
-f
On some targets, the command line length is limited, and gnatlink will generate a separate file for the linker if the list of object files is too long. The -f switch forces this file to be generated even if the limit is not exceeded. This is useful in some cases to deal with special situations where the command line length is exceeded.
-g
The option to include debugging information causes the Ada bind file (in other words, b~mainprog.adb) to be compiled with -g. In addition, the binder does not delete the b~mainprog.adb, b~mainprog.o and b~mainprog.ali files. Without -g, the binder removes these files by default. The same procedure apply if a C bind file was generated using -C gnatbind option, in this case the filenames are b_mainprog.c and b_mainprog.o.
-n
Do not compile the file generated by the binder. This may be used when a link is rerun with different options, but there is no need to recompile the binder file.
-v
Causes additional information to be output, including a full list of the included object files. This switch option is most useful when you want to see what set of object files are being used in the link step.
-v -v
Very verbose mode. Requests that the compiler operate in verbose mode when it compiles the binder file, and that the system linker run in verbose mode.
-o exec-name
exec-name specifies an alternate name for the generated executable program. If this switch is omitted, the executable has the same name as the main unit. For example, gnatlink try.ali creates an executable called try.
-b target
Compile your program to run on target, which is the name of a system configuration. You must have a GNAT cross-compiler built if target is not the same as your host system.
-Bdir
Load compiler executables (for example, gnat1, the Ada compiler) from dir instead of the default location. Only use this switch when multiple versions of the GNAT compiler are available. See the gcc manual page for further details. You would normally use the -b or -V switch instead.
--GCC=compiler_name
Program used for compiling the binder file. The default is `gcc'. You need to use quotes around compiler_name if compiler_name contains spaces or other separator characters. As an example --GCC="foo -x -y" will instruct gnatlink to use foo -x -y as your compiler. Note that switch -c is always inserted after your command name. Thus in the above example the compiler command that will be used by gnatlink will be foo -c -x -y. If several --GCC=compiler_name are used, only the last compiler_name is taken into account. However, all the additional switches are also taken into account. Thus, --GCC="foo -x -y" --GCC="bar -z -t" is equivalent to --GCC="bar -x -y -z -t".
--LINK=name
name is the name of the linker to be invoked. This is especially useful in mixed language programs since languages such as C++ require their own linker to be used. When this switch is omitted, the default name for the linker is (gcc). When this switch is used, the specified linker is called instead of (gcc) with exactly the same parameters that would have been passed to (gcc) so if the desired linker requires different parameters it is necessary to use a wrapper script that massages the parameters before invoking the real linker. It may be useful to control the exact invocation by using the verbose switch.


Next: , Previous: Switches for gnatlink, Up: Linking Using gnatlink

5.3 Setting Stack Size from gnatlink

Under Windows systems, it is possible to specify the program stack size from gnatlink using either:


Previous: Setting Stack Size from gnatlink, Up: Linking Using gnatlink

5.4 Setting Heap Size from gnatlink

Under Windows systems, it is possible to specify the program heap size from gnatlink using either:


Next: , Previous: Linking Using gnatlink, Up: Top

6 The GNAT Make Program gnatmake

A typical development cycle when working on an Ada program consists of the following steps:
  1. Edit some sources to fix bugs.
  2. Add enhancements.
  3. Compile all sources affected.
  4. Rebind and relink.
  5. Test.

The third step can be tricky, because not only do the modified files have to be compiled, but any files depending on these files must also be recompiled. The dependency rules in Ada can be quite complex, especially in the presence of overloading, use clauses, generics and inlined subprograms.

gnatmake automatically takes care of the third and fourth steps of this process. It determines which sources need to be compiled, compiles them, and binds and links the resulting object files.

Unlike some other Ada make programs, the dependencies are always accurately recomputed from the new sources. The source based approach of the GNAT compilation model makes this possible. This means that if changes to the source program cause corresponding changes in dependencies, they will always be tracked exactly correctly by gnatmake.


Next: , Up: The GNAT Make Program gnatmake

6.1 Running gnatmake

The usual form of the gnatmake command is

     $ gnatmake [switches] file_name
           [file_names] [mode_switches]

The only required argument is one file_name, which specifies a compilation unit that is a main program. Several file_names can be specified: this will result in several executables being built. If switches are present, they can be placed before the first file_name, between file_names or after the last file_name. If mode_switches are present, they must always be placed after the last file_name and all switches.

If you are using standard file extensions (.adb and .ads), then the extension may be omitted from the file_name arguments. However, if you are using non-standard extensions, then it is required that the extension be given. A relative or absolute directory path can be specified in a file_name, in which case, the input source file will be searched for in the specified directory only. Otherwise, the input source file will first be searched in the directory where gnatmake was invoked and if it is not found, it will be search on the source path of the compiler as described in Search Paths and the Run-Time Library (RTL).

All gnatmake output (except when you specify -M) is to stderr. The output produced by the -M switch is send to stdout.


Next: , Previous: Running gnatmake, Up: The GNAT Make Program gnatmake

6.2 Switches for gnatmake

You may specify any of the following switches to gnatmake:

--GCC=compiler_name
Program used for compiling. The default is `gcc'. You need to use quotes around compiler_name if compiler_name contains spaces or other separator characters. As an example --GCC="foo -x -y" will instruct gnatmake to use foo -x -y as your compiler. Note that switch -c is always inserted after your command name. Thus in the above example the compiler command that will be used by gnatmake will be foo -c -x -y. If several --GCC=compiler_name are used, only the last compiler_name is taken into account. However, all the additional switches are also taken into account. Thus, --GCC="foo -x -y" --GCC="bar -z -t" is equivalent to --GCC="bar -x -y -z -t".
--GNATBIND=binder_name
Program used for binding. The default is `gnatbind'. You need to use quotes around binder_name if binder_name contains spaces or other separator characters. As an example --GNATBIND="bar -x -y" will instruct gnatmake to use bar -x -y as your binder. Binder switches that are normally appended by gnatmake to `gnatbind' are now appended to the end of bar -x -y.
--GNATLINK=linker_name
Program used for linking. The default is `gnatlink'. You need to use quotes around linker_name if linker_name contains spaces or other separator characters. As an example --GNATLINK="lan -x -y" will instruct gnatmake to use lan -x -y as your linker. Linker switches that are normally appended by gnatmake to `gnatlink' are now appended to the end of lan -x -y.
-a
Consider all files in the make process, even the GNAT internal system files (for example, the predefined Ada library files), as well as any locked files. Locked files are files whose ALI file is write-protected. By default, gnatmake does not check these files, because the assumption is that the GNAT internal files are properly up to date, and also that any write protected ALI files have been properly installed. Note that if there is an installation problem, such that one of these files is not up to date, it will be properly caught by the binder. You may have to specify this switch if you are working on GNAT itself. The switch -a is also useful in conjunction with -f if you need to recompile an entire application, including run-time files, using special configuration pragmas, such as a Normalize_Scalars pragma.

By default gnatmake -a compiles all GNAT internal files with gcc -c -gnatpg rather than gcc -c.

-b
Bind only. Can be combined with -c to do compilation and binding, but no link. Can be combined with -l to do binding and linking. When not combined with -c all the units in the closure of the main program must have been previously compiled and must be up to date. The root unit specified by file_name may be given without extension, with the source extension or, if no GNAT Project File is specified, with the ALI file extension.
-c
Compile only. Do not perform binding, except when -b is also specified. Do not perform linking, except if both -b and -l are also specified. If the root unit specified by file_name is not a main unit, this is the default. Otherwise gnatmake will attempt binding and linking unless all objects are up to date and the executable is more recent than the objects.
-C
Use a temporary mapping file. A mapping file is a way to communicate to the compiler two mappings: from unit names to file names (without any directory information) and from file names to path names (with full directory information). These mappings are used by the compiler to short-circuit the path search. When gnatmake is invoked with this switch, it will create a temporary mapping file, initially populated by the project manager, if -P is used, otherwise initially empty. Each invocation of the compiler will add the newly accessed sources to the mapping file. This will improve the source search during the next invocation of the compiler.
-C=file
Use a specific mapping file. The file, specified as a path name (absolute or relative) by this switch, should already exist, otherwise the switch is ineffective. The specified mapping file will be communicated to the compiler. This switch is not compatible with a project file (-Pfile) or with multiple compiling processes (-jnnn, when nnn is greater than 1).
-D dir
Put all object files and ALI file in directory dir. If the -D switch is not used, all object files and ALI files go in the current working directory.

This switch cannot be used when using a project file.

-f
Force recompilations. Recompile all sources, even though some object files may be up to date, but don't recompile predefined or GNAT internal files or locked files (files with a write-protected ALI file), unless the -a switch is also specified.
-F
When using project files, if some errors or warnings are detected during parsing and verbose mode is not in effect (no use of switch -v), then error lines start with the full path name of the project file, rather than its simple file name.
-i
In normal mode, gnatmake compiles all object files and ALI files into the current directory. If the -i switch is used, then instead object files and ALI files that already exist are overwritten in place. This means that once a large project is organized into separate directories in the desired manner, then gnatmake will automatically maintain and update this organization. If no ALI files are found on the Ada object path (Search Paths and the Run-Time Library (RTL)), the new object and ALI files are created in the directory containing the source being compiled. If another organization is desired, where objects and sources are kept in different directories, a useful technique is to create dummy ALI files in the desired directories. When detecting such a dummy file, gnatmake will be forced to recompile the corresponding source file, and it will be put the resulting object and ALI files in the directory where it found the dummy file.
-jn
Use n processes to carry out the (re)compilations. On a multiprocessor machine compilations will occur in parallel. In the event of compilation errors, messages from various compilations might get interspersed (but gnatmake will give you the full ordered list of failing compiles at the end). If this is problematic, rerun the make process with n set to 1 to get a clean list of messages.
-k
Keep going. Continue as much as possible after a compilation error. To ease the programmer's task in case of compilation errors, the list of sources for which the compile fails is given when gnatmake terminates.

If gnatmake is invoked with several file_names and with this switch, if there are compilation errors when building an executable, gnatmake will not attempt to build the following executables.

-l
Link only. Can be combined with -b to binding and linking. Linking will not be performed if combined with -c but not with -b. When not combined with -b all the units in the closure of the main program must have been previously compiled and must be up to date, and the main program need to have been bound. The root unit specified by file_name may be given without extension, with the source extension or, if no GNAT Project File is specified, with the ALI file extension.
-m
Specifies that the minimum necessary amount of recompilations be performed. In this mode gnatmake ignores time stamp differences when the only modifications to a source file consist in adding/removing comments, empty lines, spaces or tabs. This means that if you have changed the comments in a source file or have simply reformatted it, using this switch will tell gnatmake not to recompile files that depend on it (provided other sources on which these files depend have undergone no semantic modifications). Note that the debugging information may be out of date with respect to the sources if the -m switch causes a compilation to be switched, so the use of this switch represents a trade-off between compilation time and accurate debugging information.
-M
Check if all objects are up to date. If they are, output the object dependences to stdout in a form that can be directly exploited in a Makefile. By default, each source file is prefixed with its (relative or absolute) directory name. This name is whatever you specified in the various -aI and -I switches. If you use gnatmake -M -q (see below), only the source file names, without relative paths, are output. If you just specify the -M switch, dependencies of the GNAT internal system files are omitted. This is typically what you want. If you also specify the -a switch, dependencies of the GNAT internal files are also listed. Note that dependencies of the objects in external Ada libraries (see switch -aLdir in the following list) are never reported.
-n
Don't compile, bind, or link. Checks if all objects are up to date. If they are not, the full name of the first file that needs to be recompiled is printed. Repeated use of this option, followed by compiling the indicated source file, will eventually result in recompiling all required units.
-o exec_name
Output executable name. The name of the final executable program will be exec_name. If the -o switch is omitted the default name for the executable will be the name of the input file in appropriate form for an executable file on the host system.

This switch cannot be used when invoking gnatmake with several file_names.

-Pproject
Use project file project. Only one such switch can be used. See gnatmake and Project Files.
-q
Quiet. When this flag is not set, the commands carried out by gnatmake are displayed.
-s
Recompile if compiler switches have changed since last compilation. All compiler switches but -I and -o are taken into account in the following way: orders between different “first letter” switches are ignored, but orders between same switches are taken into account. For example, -O -O2 is different than -O2 -O, but -g -O is equivalent to -O -g.

This switch is recommended when Integrated Preprocessing is used.

-u
Unique. Recompile at most the main files. It implies -c. Combined with -f, it is equivalent to calling the compiler directly. Note that using -u with a project file and no main has a special meaning (see Project Files and Main Subprograms).
-U
When used without a project file or with one or several mains on the command line, is equivalent to -u. When used with a project file and no main on the command line, all sources of all project files are checked and compiled if not up to date, and libraries are rebuilt, if necessary.
-v
Verbose. Displays the reason for all recompilations gnatmake decides are necessary.
-vPx
Indicates the verbosity of the parsing of GNAT project files. See Switches Related to Project Files.
-Xname=value
Indicates that external variable name has the value value. The Project Manager will use this value for occurrences of external(name) when parsing the project file. See Switches Related to Project Files.
-z
No main subprogram. Bind and link the program even if the unit name given on the command line is a package name. The resulting executable will execute the elaboration routines of the package and its closure, then the finalization routines.
-g
Enable debugging. This switch is simply passed to the compiler and to the linker.
gcc switches
Any uppercase switch (other than -A, -L or -S) or any switch that is more than one character is passed to gcc (e.g. -O, -gnato, etc.)

Source and library search path switches:

-aIdir
When looking for source files also look in directory dir. The order in which source files search is undertaken is described in Search Paths and the Run-Time Library (RTL).
-aLdir
Consider dir as being an externally provided Ada library. Instructs gnatmake to skip compilation units whose .ALI files have been located in directory dir. This allows you to have missing bodies for the units in dir and to ignore out of date bodies for the same units. You still need to specify the location of the specs for these units by using the switches -aIdir or -Idir. Note: this switch is provided for compatibility with previous versions of gnatmake. The easier method of causing standard libraries to be excluded from consideration is to write-protect the corresponding ALI files.
-aOdir
When searching for library and object files, look in directory dir. The order in which library files are searched is described in Search Paths for gnatbind.
-Adir
Equivalent to -aLdir -aIdir.
-Idir
Equivalent to -aOdir -aIdir.
-I-
Do not look for source files in the directory containing the source file named in the command line. Do not look for ALI or object files in the directory where gnatmake was invoked.
-Ldir
Add directory dir to the list of directories in which the linker will search for libraries. This is equivalent to -largs -Ldir. Furthermore, under Windows, the sources pointed to by the libraries path set in the registry are not searched for.
-nostdinc
Do not look for source files in the system default directory.
-nostdlib
Do not look for library files in the system default directory.
--RTS=rts-path
Specifies the default location of the runtime library. GNAT looks for the runtime in the following directories, and stops as soon as a valid runtime is found (adainclude or ada_source_path, and adalib or ada_object_path present):

The selected path is handled like a normal RTS path.


Next: , Previous: Switches for gnatmake, Up: The GNAT Make Program gnatmake

6.3 Mode Switches for gnatmake

The mode switches (referred to as mode_switches) allow the inclusion of switches that are to be passed to the compiler itself, the binder or the linker. The effect of a mode switch is to cause all subsequent switches up to the end of the switch list, or up to the next mode switch, to be interpreted as switches to be passed on to the designated component of GNAT.

-cargs switches
Compiler switches. Here switches is a list of switches that are valid switches for gcc. They will be passed on to all compile steps performed by gnatmake.
-bargs switches
Binder switches. Here switches is a list of switches that are valid switches for gnatbind. They will be passed on to all bind steps performed by gnatmake.
-largs switches
Linker switches. Here switches is a list of switches that are valid switches for gnatlink. They will be passed on to all link steps performed by gnatmake.
-margs switches
Make switches. The switches are directly interpreted by gnatmake, regardless of any previous occurrence of -cargs, -bargs or -largs.


Next: , Previous: Mode Switches for gnatmake, Up: The GNAT Make Program gnatmake

6.4 Notes on the Command Line

This section contains some additional useful notes on the operation of the gnatmake command.


Next: , Previous: Notes on the Command Line, Up: The GNAT Make Program gnatmake

6.5 How gnatmake Works

Generally gnatmake automatically performs all necessary recompilations and you don't need to worry about how it works. However, it may be useful to have some basic understanding of the gnatmake approach and in particular to understand how it uses the results of previous compilations without incorrectly depending on them.

First a definition: an object file is considered up to date if the corresponding ALI file exists and its time stamp predates that of the object file and if all the source files listed in the dependency section of this ALI file have time stamps matching those in the ALI file. This means that neither the source file itself nor any files that it depends on have been modified, and hence there is no need to recompile this file.

gnatmake works by first checking if the specified main unit is up to date. If so, no compilations are required for the main unit. If not, gnatmake compiles the main program to build a new ALI file that reflects the latest sources. Then the ALI file of the main unit is examined to find all the source files on which the main program depends, and gnatmake recursively applies the above procedure on all these files.

This process ensures that gnatmake only trusts the dependencies in an existing ALI file if they are known to be correct. Otherwise it always recompiles to determine a new, guaranteed accurate set of dependencies. As a result the program is compiled “upside down” from what may be more familiar as the required order of compilation in some other Ada systems. In particular, clients are compiled before the units on which they depend. The ability of GNAT to compile in any order is critical in allowing an order of compilation to be chosen that guarantees that gnatmake will recompute a correct set of new dependencies if necessary.

When invoking gnatmake with several file_names, if a unit is imported by several of the executables, it will be recompiled at most once.

Note: when using non-standard naming conventions (See Using Other File Names), changing through a configuration pragmas file the version of a source and invoking gnatmake to recompile may have no effect, if the previous version of the source is still accessible by gnatmake. It may be necessary to use the switch -f.


Previous: How gnatmake Works, Up: The GNAT Make Program gnatmake

6.6 Examples of gnatmake Usage

gnatmake hello.adb
Compile all files necessary to bind and link the main program hello.adb (containing unit Hello) and bind and link the resulting object files to generate an executable file hello.
gnatmake main1 main2 main3
Compile all files necessary to bind and link the main programs main1.adb (containing unit Main1), main2.adb (containing unit Main2) and main3.adb (containing unit Main3) and bind and link the resulting object files to generate three executable files main1, main2 and main3.
gnatmake -q Main_Unit -cargs -O2 -bargs -l
Compile all files necessary to bind and link the main program unit Main_Unit (from file main_unit.adb). All compilations will be done with optimization level 2 and the order of elaboration will be listed by the binder. gnatmake will operate in quiet mode, not displaying commands it is executing.


Next: , Previous: The GNAT Make Program gnatmake, Up: Top

7 Improving Performance

This chapter presents several topics related to program performance. It first describes some of the tradeoffs that need to be considered and some of the techniques for making your program run faster. It then documents the gnatelim tool, which can reduce the size of program executables.


Next: , Up: Improving Performance

7.1 Performance Considerations

The GNAT system provides a number of options that allow a trade-off between

The defaults (if no options are selected) aim at improving the speed of compilation and minimizing dependences, at the expense of performance of the generated code:

These options are suitable for most program development purposes. This chapter describes how you can modify these choices, and also provides some guidelines on debugging optimized code.


Next: , Up: Performance Considerations

7.1.1 Controlling Run-Time Checks

By default, GNAT generates all run-time checks, except arithmetic overflow checking for integer operations and checks for access before elaboration on subprogram calls. The latter are not required in default mode, because all necessary checking is done at compile time. Two gnat switches, -gnatp and -gnato allow this default to be modified. See Run-Time Checks.

Our experience is that the default is suitable for most development purposes.

We treat integer overflow specially because these are quite expensive and in our experience are not as important as other run-time checks in the development process. Note that division by zero is not considered an overflow check, and divide by zero checks are generated where required by default.

Elaboration checks are off by default, and also not needed by default, since GNAT uses a static elaboration analysis approach that avoids the need for run-time checking. This manual contains a full chapter discussing the issue of elaboration checks, and if the default is not satisfactory for your use, you should read this chapter.

For validity checks, the minimal checks required by the Ada Reference Manual (for case statements and assignments to array elements) are on by default. These can be suppressed by use of the -gnatVn switch. Note that in Ada 83, there were no validity checks, so if the Ada 83 mode is acceptable (or when comparing GNAT performance with an Ada 83 compiler), it may be reasonable to routinely use -gnatVn. Validity checks are also suppressed entirely if -gnatp is used.

Note that the setting of the switches controls the default setting of the checks. They may be modified using either pragma Suppress (to remove checks) or pragma Unsuppress (to add back suppressed checks) in the program source.


Next: , Previous: Controlling Run-Time Checks, Up: Performance Considerations

7.1.2 Use of Restrictions

The use of pragma Restrictions allows you to control which features are permitted in your program. Apart from the obvious point that if you avoid relatively expensive features like finalization (enforceable by the use of pragma Restrictions (No_Finalization), the use of this pragma does not affect the generated code in most cases.

One notable exception to this rule is that the possibility of task abort results in some distributed overhead, particularly if finalization or exception handlers are used. The reason is that certain sections of code have to be marked as non-abortable.

If you use neither the abort statement, nor asynchronous transfer of control (select .. then abort), then this distributed overhead is removed, which may have a general positive effect in improving overall performance. Especially code involving frequent use of tasking constructs and controlled types will show much improved performance. The relevant restrictions pragmas are

        pragma Restrictions (No_Abort_Statements);
        pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);

It is recommended that these restriction pragmas be used if possible. Note that this also means that you can write code without worrying about the possibility of an immediate abort at any point.


Next: , Previous: Use of Restrictions, Up: Performance Considerations

7.1.3 Optimization Levels

The default is optimization off. This results in the fastest compile times, but GNAT makes absolutely no attempt to optimize, and the generated programs are considerably larger and slower than when optimization is enabled. You can use the -On switch, where n is an integer from 0 to 3, to gcc to control the optimization level:

-O0
No optimization (the default); generates unoptimized code but has the fastest compilation time.
-O1
Medium level optimization; optimizes reasonably well but does not degrade compilation time significantly.
-O2
Full optimization; generates highly optimized code and has the slowest compilation time.
-O3
Full optimization as in -O2, and also attempts automatic inlining of small subprograms within a unit (see Inlining of Subprograms).

Higher optimization levels perform more global transformations on the program and apply more expensive analysis algorithms in order to generate faster and more compact code. The price in compilation time, and the resulting improvement in execution time, both depend on the particular application and the hardware environment. You should experiment to find the best level for your application.

Since the precise set of optimizations done at each level will vary from release to release (and sometime from target to target), it is best to think of the optimization settings in general terms. The Using GNU GCC manual contains details about the -O settings and a number of -f options that individually enable or disable specific optimizations.

Unlike some other compilation systems, gcc has been tested extensively at all optimization levels. There are some bugs which appear only with optimization turned on, but there have also been bugs which show up only in unoptimized code. Selecting a lower level of optimization does not improve the reliability of the code generator, which in practice is highly reliable at all optimization levels.

Note regarding the use of -O3: The use of this optimization level is generally discouraged with GNAT, since it often results in larger executables which run more slowly. See further discussion of this point in see Inlining of Subprograms.


Next: , Previous: Optimization Levels, Up: Performance Considerations

7.1.4 Debugging Optimized Code

Although it is possible to do a reasonable amount of debugging at non-zero optimization levels, the higher the level the more likely that source-level constructs will have been eliminated by optimization. For example, if a loop is strength-reduced, the loop control variable may be completely eliminated and thus cannot be displayed in the debugger. This can only happen at -O2 or -O3. Explicit temporary variables that you code might be eliminated at level -O1 or higher.

The use of the -g switch, which is needed for source-level debugging, affects the size of the program executable on disk, and indeed the debugging information can be quite large. However, it has no effect on the generated code (and thus does not degrade performance)

Since the compiler generates debugging tables for a compilation unit before it performs optimizations, the optimizing transformations may invalidate some of the debugging data. You therefore need to anticipate certain anomalous situations that may arise while debugging optimized code. These are the most common cases:

  1. The “hopping Program Counter”: Repeated step or next commands show the PC bouncing back and forth in the code. This may result from any of the following optimizations:
  2. The “big leap”: More commonly known as cross-jumping, in which two identical pieces of code are merged and the program counter suddenly jumps to a statement that is not supposed to be executed, simply because it (and the code following) translates to the same thing as the code that was supposed to be executed. This effect is typically seen in sequences that end in a jump, such as a goto, a return, or a break in a C switch statement.
  3. The “roving variable”: The symptom is an unexpected value in a variable. There are various reasons for this effect:

    In general, when an unexpected value appears for a local variable or parameter you should first ascertain if that value was actually computed by your program, as opposed to being incorrectly reported by the debugger. Record fields or array elements in an object designated by an access value are generally less of a problem, once you have ascertained that the access value is sensible. Typically, this means checking variables in the preceding code and in the calling subprogram to verify that the value observed is explainable from other values (one must apply the procedure recursively to those other values); or re-running the code and stopping a little earlier (perhaps before the call) and stepping to better see how the variable obtained the value in question; or continuing to step from the point of the strange value to see if code motion had simply moved the variable's assignments later.

In light of such anomalies, a recommended technique is to use -O0 early in the software development cycle, when extensive debugging capabilities are most needed, and then move to -O1 and later -O2 as the debugger becomes less critical. Whether to use the -g switch in the release version is a release management issue. Note that if you use -g you can then use the strip program on the resulting executable, which removes both debugging information and global symbols.


Previous: Debugging Optimized Code, Up: Performance Considerations

7.1.5 Inlining of Subprograms

A call to a subprogram in the current unit is inlined if all the following conditions are met:

Calls to subprograms in with'ed units are normally not inlined. To achieve this level of inlining, the following conditions must all be true:

Note that specifying the -gnatn switch causes additional compilation dependencies. Consider the following:

     

package R is procedure Q; pragma Inline (Q); end R; package body R is ... end R; with R; procedure Main is begin ... R.Q; end Main;

With the default behavior (no -gnatn switch specified), the compilation of the Main procedure depends only on its own source, main.adb, and the spec of the package in file r.ads. This means that editing the body of R does not require recompiling Main.

On the other hand, the call R.Q is not inlined under these circumstances. If the -gnatn switch is present when Main is compiled, the call will be inlined if the body of Q is small enough, but now Main depends on the body of R in r.adb as well as on the spec. This means that if this body is edited, the main program must be recompiled. Note that this extra dependency occurs whether or not the call is in fact inlined by gcc.

The use of front end inlining with -gnatN generates similar additional dependencies.

Note: The -fno-inline switch can be used to prevent all inlining. This switch overrides all other conditions and ensures that no inlining occurs. The extra dependences resulting from -gnatn will still be active, even if this switch is used to suppress the resulting inlining actions.

Note regarding the use of -O3: There is no difference in inlining behavior between -O2 and -O3 for subprograms with an explicit pragma Inline assuming the use of -gnatn or -gnatN (the switches that activate inlining). If you have used pragma Inline in appropriate cases, then it is usually much better to use -O2 and -gnatn and avoid the use of -O3 which in this case only has the effect of inlining subprograms you did not think should be inlined. We often find that the use of -O3 slows down code by performing excessive inlining, leading to increased instruction cache pressure from the increased code size. So the bottom line here is that you should not automatically assume that -O3 is better than -O2, and indeed you should use -O3 only if tests show that it actually improves performance.


Previous: Performance Considerations, Up: Improving Performance

7.2 Reducing the Size of Ada Executables with gnatelim

This section describes gnatelim, a tool which detects unused subprograms and helps the compiler to create a smaller executable for your program.


Next: , Up: Reducing the Size of Ada Executables with gnatelim

7.2.1 About gnatelim

When a program shares a set of Ada packages with other programs, it may happen that this program uses only a fraction of the subprograms defined in these packages. The code created for these unused subprograms increases the size of the executable.

gnatelim tracks unused subprograms in an Ada program and outputs a list of GNAT-specific pragmas Eliminate marking all the subprograms that are declared but never called. By placing the list of Eliminate pragmas in the GNAT configuration file gnat.adc and recompiling your program, you may decrease the size of its executable, because the compiler will not generate the code for 'eliminated' subprograms. See GNAT Reference Manual for more information about this pragma.

gnatelim needs as its input data the name of the main subprogram and a bind file for a main subprogram.

To create a bind file for gnatelim, run gnatbind for the main subprogram. gnatelim can work with both Ada and C bind files; when both are present, it uses the Ada bind file. The following commands will build the program and create the bind file:

     $ gnatmake -c Main_Prog
     $ gnatbind main_prog

Note that gnatelim needs neither object nor ALI files.


Next: , Previous: About gnatelim, Up: Reducing the Size of Ada Executables with gnatelim

7.2.2 Running gnatelim

gnatelim has the following command-line interface:

     $ gnatelim [options] name

name should be a name of a source file that contains the main subprogram of a program (partition).

gnatelim has the following switches:

-q
Quiet mode: by default gnatelim outputs to the standard error stream the number of program units left to be processed. This option turns this trace off.
-v
Verbose mode: gnatelim version information is printed as Ada comments to the standard output stream. Also, in addition to the number of program units left gnatelim will output the name of the current unit being processed.
-a
Also look for subprograms from the GNAT run time that can be eliminated. Note that when gnat.adc is produced using this switch, the entire program must be recompiled with switch -a to gnatmake.
-Idir
When looking for source files also look in directory dir. Specifying -I- instructs gnatelim not to look for sources in the current directory.
-bbind_file
Specifies bind_file as the bind file to process. If not set, the name of the bind file is computed from the full expanded Ada name of a main subprogram.
-Cconfig_file
Specifies a file config_file that contains configuration pragmas. The file must be specified with full path.
--GCC=compiler_name
Instructs gnatelim to use specific gcc compiler instead of one available on the path.
--GNATMAKE=gnatmake_name
Instructs gnatelim to use specific gnatmake instead of one available on the path.
-dx
Activate internal debugging switches. x is a letter or digit, or string of letters or digits, which specifies the type of debugging mode desired. Normally these are used only for internal development or system debugging purposes. You can find full documentation for these switches in the spec of the Gnatelim unit in the compiler source file gnatelim.ads.

gnatelim sends its output to the standard output stream, and all the tracing and debug information is sent to the standard error stream. In order to produce a proper GNAT configuration file gnat.adc, redirection must be used:

     $ gnatelim main_prog.adb > gnat.adc

or

     $ gnatelim main_prog.adb >> gnat.adc

in order to append the gnatelim output to the existing contents of gnat.adc.


Next: , Previous: Running gnatelim, Up: Reducing the Size of Ada Executables with gnatelim

7.2.3 Correcting the List of Eliminate Pragmas

In some rare cases gnatelim may try to eliminate subprograms that are actually called in the program. In this case, the compiler will generate an error message of the form:

     file.adb:106:07: cannot call eliminated subprogram "My_Prog"

You will need to manually remove the wrong Eliminate pragmas from the gnat.adc file. You should recompile your program from scratch after that, because you need a consistent gnat.adc file during the entire compilation.


Next: , Previous: Correcting the List of Eliminate Pragmas, Up: Reducing the Size of Ada Executables with gnatelim

7.2.4 Making Your Executables Smaller

In order to get a smaller executable for your program you now have to recompile the program completely with the new gnat.adc file created by gnatelim in your current directory:

     $ gnatmake -f main_prog

(Use the -f option for gnatmake to recompile everything with the set of pragmas Eliminate that you have obtained with gnatelim).

Be aware that the set of Eliminate pragmas is specific to each program. It is not recommended to merge sets of Eliminate pragmas created for different programs in one gnat.adc file.


Previous: Making Your Executables Smaller, Up: Reducing the Size of Ada Executables with gnatelim

7.2.5 Summary of the gnatelim Usage Cycle

Here is a quick summary of the steps to be taken in order to reduce the size of your executables with gnatelim. You may use other GNAT options to control the optimization level, to produce the debugging information, to set search path, etc.

  1. Produce a bind file
              $ gnatmake -c main_prog
              $ gnatbind main_prog
         
  2. Generate a list of Eliminate pragmas
              $ gnatelim main_prog >[>] gnat.adc
         
  3. Recompile the application
              $ gnatmake -f main_prog
         


Next: , Previous: Improving Performance, Up: Top

8 Renaming Files Using gnatchop

This chapter discusses how to handle files with multiple units by using the gnatchop utility. This utility is also useful in renaming files to meet the standard GNAT default file naming conventions.


Next: , Up: Renaming Files Using gnatchop

8.1 Handling Files with Multiple Units

The basic compilation model of GNAT requires that a file submitted to the compiler have only one unit and there be a strict correspondence between the file name and the unit name.

The gnatchop utility allows both of these rules to be relaxed, allowing GNAT to process files which contain multiple compilation units and files with arbitrary file names. gnatchop reads the specified file and generates one or more output files, containing one unit per file. The unit and the file name correspond, as required by GNAT.

If you want to permanently restructure a set of “foreign” files so that they match the GNAT rules, and do the remaining development using the GNAT structure, you can simply use gnatchop once, generate the new set of files and work with them from that point on.

Alternatively, if you want to keep your files in the “foreign” format, perhaps to maintain compatibility with some other Ada compilation system, you can set up a procedure where you use gnatchop each time you compile, regarding the source files that it writes as temporary files that you throw away.


Next: , Previous: Handling Files with Multiple Units, Up: Renaming Files Using gnatchop

8.2 Operating gnatchop in Compilation Mode

The basic function of gnatchop is to take a file with multiple units and split it into separate files. The boundary between files is reasonably clear, except for the issue of comments and pragmas. In default mode, the rule is that any pragmas between units belong to the previous unit, except that configuration pragmas always belong to the following unit. Any comments belong to the following unit. These rules almost always result in the right choice of the split point without needing to mark it explicitly and most users will find this default to be what they want. In this default mode it is incorrect to submit a file containing only configuration pragmas, or one that ends in configuration pragmas, to gnatchop.

However, using a special option to activate “compilation mode”, gnatchop can perform another function, which is to provide exactly the semantics required by the RM for handling of configuration pragmas in a compilation. In the absence of configuration pragmas (at the main file level), this option has no effect, but it causes such configuration pragmas to be handled in a quite different manner.

First, in compilation mode, if gnatchop is given a file that consists of only configuration pragmas, then this file is appended to the gnat.adc file in the current directory. This behavior provides the required behavior described in the RM for the actions to be taken on submitting such a file to the compiler, namely that these pragmas should apply to all subsequent compilations in the same compilation environment. Using GNAT, the current directory, possibly containing a gnat.adc file is the representation of a compilation environment. For more information on the gnat.adc file, see the section on handling of configuration pragmas see Handling of Configuration Pragmas.

Second, in compilation mode, if gnatchop is given a file that starts with configuration pragmas, and contains one or more units, then these configuration pragmas are prepended to each of the chopped files. This behavior provides the required behavior described in the RM for the actions to be taken on compiling such a file, namely that the pragmas apply to all units in the compilation, but not to subsequently compiled units.

Finally, if configuration pragmas appear between units, they are appended to the previous unit. This results in the previous unit being illegal, since the compiler does not accept configuration pragmas that follow a unit. This provides the required RM behavior that forbids configuration pragmas other than those preceding the first compilation unit of a compilation.

For most purposes, gnatchop will be used in default mode. The compilation mode described above is used only if you need exactly accurate behavior with respect to compilations, and you have files that contain multiple units and configuration pragmas. In this circumstance the use of gnatchop with the compilation mode switch provides the required behavior, and is for example the mode in which GNAT processes the ACVC tests.


Next: , Previous: Operating gnatchop in Compilation Mode, Up: Renaming Files Using gnatchop

8.3 Command Line for gnatchop

The gnatchop command has the form:

     $ gnatchop switches file name [file name file name ...]
           [directory]

The only required argument is the file name of the file to be chopped. There are no restrictions on the form of this file name. The file itself contains one or more Ada units, in normal GNAT format, concatenated together. As shown, more than one file may be presented to be chopped.

When run in default mode, gnatchop generates one output file in the current directory for each unit in each of the files.

directory, if specified, gives the name of the directory to which the output files will be written. If it is not specified, all files are written to the current directory.

For example, given a file called hellofiles containing

     

procedure hello; with Text_IO; use Text_IO; procedure hello is begin Put_Line ("Hello"); end hello;

the command

     $ gnatchop hellofiles

generates two files in the current directory, one called hello.ads containing the single line that is the procedure spec, and the other called hello.adb containing the remaining text. The original file is not affected. The generated files can be compiled in the normal manner.

When gnatchop is invoked on a file that is empty or that contains only empty lines and/or comments, gnatchop will not fail, but will not produce any new sources.

For example, given a file called toto.txt containing

     

-- Just a comment

the command

     $ gnatchop toto.txt

will not produce any new file and will result in the following warnings:

     toto.txt:1:01: warning: empty file, contains no compilation units
     no compilation units found
     no source files written


Next: , Previous: Command Line for gnatchop, Up: Renaming Files Using gnatchop

8.4 Switches for gnatchop

gnatchop recognizes the following switches:

-c
Causes gnatchop to operate in compilation mode, in which configuration pragmas are handled according to strict RM rules. See previous section for a full description of this mode.
-gnatxxx
This passes the given -gnatxxx switch to gnat which is used to parse the given file. Not all xxx options make sense, but for example, the use of -gnati2 allows gnatchop to process a source file that uses Latin-2 coding for identifiers.
-h
Causes gnatchop to generate a brief help summary to the standard output file showing usage information.
-kmm
Limit generated file names to the specified number mm of characters. This is useful if the resulting set of files is required to be interoperable with systems which limit the length of file names. No space is allowed between the -k and the numeric value. The numeric value may be omitted in which case a default of -k8, suitable for use with DOS-like file systems, is used. If no -k switch is present then there is no limit on the length of file names.
-p
Causes the file modification time stamp of the input file to be preserved and used for the time stamp of the output file(s). This may be useful for preserving coherency of time stamps in an environment where gnatchop is used as part of a standard build process.
-q
Causes output of informational messages indicating the set of generated files to be suppressed. Warnings and error messages are unaffected.
-r
Generate Source_Reference pragmas. Use this switch if the output files are regarded as temporary and development is to be done in terms of the original unchopped file. This switch causes Source_Reference pragmas to be inserted into each of the generated files to refers back to the original file name and line number. The result is that all error messages refer back to the original unchopped file. In addition, the debugging information placed into the object file (when the -g switch of gcc or gnatmake is specified) also refers back to this original file so that tools like profilers and debuggers will give information in terms of the original unchopped file.

If the original file to be chopped itself contains a Source_Reference pragma referencing a third file, then gnatchop respects this pragma, and the generated Source_Reference pragmas in the chopped file refer to the original file, with appropriate line numbers. This is particularly useful when gnatchop is used in conjunction with gnatprep to compile files that contain preprocessing statements and multiple units.

-v
Causes gnatchop to operate in verbose mode. The version number and copyright notice are output, as well as exact copies of the gnat1 commands spawned to obtain the chop control information.
-w
Overwrite existing file names. Normally gnatchop regards it as a fatal error if there is already a file with the same name as a file it would otherwise output, in other words if the files to be chopped contain duplicated units. This switch bypasses this check, and causes all but the last instance of such duplicated units to be skipped.
--GCC=xxxx
Specify the path of the GNAT parser to be used. When this switch is used, no attempt is made to add the prefix to the GNAT parser executable.


Previous: Switches for gnatchop, Up: Renaming Files Using gnatchop

8.5 Examples of gnatchop Usage

gnatchop -w hello_s.ada prerelease/files
Chops the source file hello_s.ada. The output files will be placed in the directory prerelease/files, overwriting any files with matching names in that directory (no files in the current directory are modified).
gnatchop archive
Chops the source file archive into the current directory. One useful application of gnatchop is in sending sets of sources around, for example in email messages. The required sources are simply concatenated (for example, using a Unix cat command), and then gnatchop is used at the other end to reconstitute the original file names.
gnatchop file1 file2 file3 direc
Chops all units in files file1, file2, file3, placing the resulting files in the directory direc. Note that if any units occur more than once anywhere within this set of files, an error message is generated, and no files are written. To override this check, use the -w switch, in which case the last occurrence in the last file will be the one that is output, and earlier duplicate occurrences for a given unit will be skipped.


Next: , Previous: Renaming Files Using gnatchop, Up: Top

9 Configuration Pragmas

In Ada 95, configuration pragmas include those pragmas described as such in the Ada 95 Reference Manual, as well as implementation-dependent pragmas that are configuration pragmas. See the individual descriptions of pragmas in the GNAT Reference Manual for details on these additional GNAT-specific configuration pragmas. Most notably, the pragma Source_File_Name, which allows specifying non-default names for source files, is a configuration pragma. The following is a complete list of configuration pragmas recognized by GNAT:

        Ada_83
        Ada_95
        C_Pass_By_Copy
        Component_Alignment
        Discard_Names
        Elaboration_Checks
        Eliminate
        Extend_System
        Extensions_Allowed
        External_Name_Casing
        Float_Representation
        Initialize_Scalars
        License
        Locking_Policy
        Long_Float
        Normalize_Scalars
        Polling
        Propagate_Exceptions
        Queuing_Policy
        Ravenscar
        Restricted_Run_Time
        Restrictions
        Reviewable
        Source_File_Name
        Style_Checks
        Suppress
        Task_Dispatching_Policy
        Universal_Data
        Unsuppress
        Use_VADS_Size
        Warnings
        Validity_Checks


Next: , Up: Configuration Pragmas

9.1 Handling of Configuration Pragmas

Configuration pragmas may either appear at the start of a compilation unit, in which case they apply only to that unit, or they may apply to all compilations performed in a given compilation environment.

GNAT also provides the gnatchop utility to provide an automatic way to handle configuration pragmas following the semantics for compilations (that is, files with multiple units), described in the RM. See section see Operating gnatchop in Compilation Mode for details. However, for most purposes, it will be more convenient to edit the gnat.adc file that contains configuration pragmas directly, as described in the following section.


Previous: Handling of Configuration Pragmas, Up: Configuration Pragmas

9.2 The Configuration Pragmas Files

In GNAT a compilation environment is defined by the current directory at the time that a compile command is given. This current directory is searched for a file whose name is gnat.adc. If this file is present, it is expected to contain one or more configuration pragmas that will be applied to the current compilation. However, if the switch -gnatA is used, gnat.adc is not considered.

Configuration pragmas may be entered into the gnat.adc file either by running gnatchop on a source file that consists only of configuration pragmas, or more conveniently by direct editing of the gnat.adc file, which is a standard format source file.

In addition to gnat.adc, one additional file containing configuration pragmas may be applied to the current compilation using the switch -gnatecpath. path must designate an existing file that contains only configuration pragmas. These configuration pragmas are in addition to those found in gnat.adc (provided gnat.adc is present and switch -gnatA is not used).

It is allowed to specify several switches -gnatec, however only the last one on the command line will be taken into account.

If you are using project file, a separate mechanism is provided using project attributes, see Specifying Configuration Pragmas for more details.


Next: , Previous: Configuration Pragmas, Up: Top

10 Handling Arbitrary File Naming Conventions Using gnatname


Next: , Up: Handling Arbitrary File Naming Conventions Using gnatname

10.1 Arbitrary File Naming Conventions

The GNAT compiler must be able to know the source file name of a compilation unit. When using the standard GNAT default file naming conventions (.ads for specs, .adb for bodies), the GNAT compiler does not need additional information.

When the source file names do not follow the standard GNAT default file naming conventions, the GNAT compiler must be given additional information through a configuration pragmas file (see Configuration Pragmas) or a project file. When the non standard file naming conventions are well-defined, a small number of pragmas Source_File_Name specifying a naming pattern (see Alternative File Naming Schemes) may be sufficient. However, if the file naming conventions are irregular or arbitrary, a number of pragma Source_File_Name for individual compilation units must be defined. To help maintain the correspondence between compilation unit names and source file names within the compiler, GNAT provides a tool gnatname to generate the required pragmas for a set of files.


Next: , Previous: Arbitrary File Naming Conventions, Up: Handling Arbitrary File Naming Conventions Using gnatname

10.2 Running gnatname

The usual form of the gnatname command is

     $ gnatname [switches] naming_pattern [naming_patterns]

All of the arguments are optional. If invoked without any argument, gnatname will display its usage.

When used with at least one naming pattern, gnatname will attempt to find all the compilation units in files that follow at least one of the naming patterns. To find these compilation units, gnatname will use the GNAT compiler in syntax-check-only mode on all regular files.

One or several Naming Patterns may be given as arguments to gnatname. Each Naming Pattern is enclosed between double quotes. A Naming Pattern is a regular expression similar to the wildcard patterns used in file names by the Unix shells or the DOS prompt.

Examples of Naming Patterns are

        "*.[12].ada"
        "*.ad[sb]*"
        "body_*"    "spec_*"

For a more complete description of the syntax of Naming Patterns, see the second kind of regular expressions described in g-regexp.ads (the “Glob” regular expressions).

When invoked with no switches, gnatname will create a configuration pragmas file gnat.adc in the current working directory, with pragmas Source_File_Name for each file that contains a valid Ada unit.


Next: , Previous: Running gnatname, Up: Handling Arbitrary File Naming Conventions Using gnatname

10.3 Switches for gnatname

Switches for gnatname must precede any specified Naming Pattern.

You may specify any of the following switches to gnatname:

-cfile
Create a configuration pragmas file file (instead of the default gnat.adc). There may be zero, one or more space between -c and file. file may include directory information. file must be writable. There may be only one switch -c. When a switch -c is specified, no switch -P may be specified (see below).
-ddir
Look for source files in directory dir. There may be zero, one or more spaces between -d and dir. When a switch -d is specified, the current working directory will not be searched for source files, unless it is explicitly specified with a -d or -D switch. Several switches -d may be specified. If dir is a relative path, it is relative to the directory of the configuration pragmas file specified with switch -c, or to the directory of the project file specified with switch -P or, if neither switch -c nor switch -P are specified, it is relative to the current working directory. The directory specified with switch -d must exist and be readable.
-Dfile
Look for source files in all directories listed in text file file. There may be zero, one or more spaces between -D and file. file must be an existing, readable text file. Each non empty line in file must be a directory. Specifying switch -D is equivalent to specifying as many switches -d as there are non empty lines in file.
-fpattern
Foreign patterns. Using this switch, it is possible to add sources of languages other than Ada to the list of sources of a project file. It is only useful if a -P switch is used. For example,
          gnatname -Pprj -f"*.c" "*.ada"
     

will look for Ada units in all files with the .ada extension, and will add to the list of file for project prj.gpr the C files with extension ".c".

-h
Output usage (help) information. The output is written to stdout.
-Pproj
Create or update project file proj. There may be zero, one or more space between -P and proj. proj may include directory information. proj must be writable. There may be only one switch -P. When a switch -P is specified, no switch -c may be specified.
-v
Verbose mode. Output detailed explanation of behavior to stdout. This includes name of the file written, the name of the directories to search and, for each file in those directories whose name matches at least one of the Naming Patterns, an indication of whether the file contains a unit, and if so the name of the unit.
-v -v
Very Verbose mode. In addition to the output produced in verbose mode, for each file in the searched directories whose name matches none of the Naming Patterns, an indication is given that there is no match.
-xpattern
Excluded patterns. Using this switch, it is possible to exclude some files that would match the name patterns. For example,
          gnatname -x "*_nt.ada" "*.ada"
     

will look for Ada units in all files with the .ada extension, except those whose names end with _nt.ada.


Previous: Switches for gnatname, Up: Handling Arbitrary File Naming Conventions Using gnatname

10.4 Examples of gnatname Usage

     $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"

In this example, the directory /home/me must already exist and be writable. In addition, the directory /home/me/sources (specified by -d sources) must exist and be readable.

Note the optional spaces after -c and -d.

     $ gnatname -P/home/me/proj -x "*_nt_body.ada"
       -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"

Note that several switches -d may be used, even in conjunction with one or several switches -D. Several Naming Patterns and one excluded pattern are used in this example.


Next: , Previous: Handling Arbitrary File Naming Conventions Using gnatname, Up: Top

11 GNAT Project Manager


Next: , Up: GNAT Project Manager

11.1 Introduction

This chapter describes GNAT's Project Manager, a facility that allows you to manage complex builds involving a number of source files, directories, and compilation options for different system configurations. In particular, project files allow you to specify:


Up: Introduction

11.1.1 Project Files

Project files are written in a syntax close to that of Ada, using familiar notions such as packages, context clauses, declarations, default values, assignments, and inheritance. Finally, project files can be built hierarchically from other project files, simplifying complex system integration and project reuse.

A project is a specific set of values for various compilation properties. The settings for a given project are described by means of a project file, which is a text file written in an Ada-like syntax. Property values in project files are either strings or lists of strings. Properties that are not explicitly set receive default values. A project file may interrogate the values of external variables (user-defined command-line switches or environment variables), and it may specify property settings conditionally, based on the value of such variables.

In simple cases, a project's source files depend only on other source files in the same project, or on the predefined libraries. (Dependence is used in the Ada technical sense; as in one Ada unit withing another.) However, the Project Manager also allows more sophisticated arrangements, where the source files in one project depend on source files in other projects:

More generally, the Project Manager lets you structure large development efforts into hierarchical subsystems, where build decisions are delegated to the subsystem level, and thus different compilation environments (switch settings) used for different subsystems.

The Project Manager is invoked through the -Pprojectfile switch to gnatmake or to the gnat front driver. There may be zero, one or more spaces between -P and projectfile. If you want to define (on the command line) an external variable that is queried by the project file, you must use the -Xvbl=value switch. The Project Manager parses and interprets the project file, and drives the invoked tool based on the project settings.

The Project Manager supports a wide range of development strategies, for systems of all sizes. Here are some typical practices that are easily handled:

The destination of an executable can be controlled inside a project file using the -o switch. In the absence of such a switch either inside the project file or on the command line, any executable files generated by gnatmake are placed in the directory Exec_Dir specified in the project file. If no Exec_Dir is specified, they will be placed in the object directory of the project.

You can use project files to achieve some of the effects of a source versioning system (for example, defining separate projects for the different sets of sources that comprise different releases) but the Project Manager is independent of any source configuration management tools that might be used by the developers.

The next section introduces the main features of GNAT's project facility through a sequence of examples; subsequent sections will present the syntax and semantics in more detail. A more formal description of the project facility appears in the GNAT Reference Manual.


Next: , Previous: Introduction, Up: GNAT Project Manager

11.2 Examples of Project Files

This section illustrates some of the typical uses of project files and explains their basic structure and behavior.


Next: , Up: Examples of Project Files

11.2.1 Common Sources with Different Switches and Directories

Suppose that the Ada source files pack.ads, pack.adb, and proc.adb are in the /common directory. The file proc.adb contains an Ada main subprogram Proc that withs package Pack. We want to compile these source files under two sets of switches:

The GNAT project files shown below, respectively debug.gpr and release.gpr in the /common directory, achieve these effects.

Schematically:

     /common
       debug.gpr
       release.gpr
       pack.ads
       pack.adb
       proc.adb
     /common/debug
       proc.ali, proc.o
       pack.ali, pack.o
     /common/release
       proc.ali, proc.o
       pack.ali, pack.o

Here are the corresponding project files:

     project Debug is
       for Object_Dir use "debug";
       for Main use ("proc");
     
       package Builder is
         for Default_Switches ("Ada")
             use ("-g");
         for Executable ("proc.adb") use "proc1";
       end Builder;
     
       package Compiler is
         for Default_Switches ("Ada")
            use ("-fstack-check",
                 "-gnata",
                 "-gnato",
                 "-gnatE");
       end Compiler;
     end Debug;
     project Release is
       for Object_Dir use "release";
       for Exec_Dir use ".";
       for Main use ("proc");
     
       package Compiler is
         for Default_Switches ("Ada")
             use ("-O2");
       end Compiler;
     end Release;

The name of the project defined by debug.gpr is "Debug" (case insensitive), and analogously the project defined by release.gpr is "Release". For consistency the file should have the same name as the project, and the project file's extension should be "gpr". These conventions are not required, but a warning is issued if they are not followed.

If the current directory is /temp, then the command

     gnatmake -P/common/debug.gpr

generates object and ALI files in /common/debug, as well as the proc1 executable, using the switch settings defined in the project file.

Likewise, the command

     gnatmake -P/common/release.gpr

generates object and ALI files in /common/release, and the proc executable in /common, using the switch settings from the project file.


Next: , Up: Common Sources with Different Switches and Directories
Source Files

If a project file does not explicitly specify a set of source directories or a set of source files, then by default the project's source files are the Ada source files in the project file directory. Thus pack.ads, pack.adb, and proc.adb are the source files for both projects.


Next: , Previous: Source Files, Up: Common Sources with Different Switches and Directories
Specifying the Object Directory

Several project properties are modeled by Ada-style attributes; a property is defined by supplying the equivalent of an Ada attribute definition clause in the project file. A project's object directory is another such a property; the corresponding attribute is Object_Dir, and its value is also a string expression, specified either as absolute or relative. In the later case, it is relative to the project file directory. Thus the compiler's output is directed to /common/debug (for the Debug project) and to /common/release (for the Release project). If Object_Dir is not specified, then the default is the project file directory itself.


Next: , Previous: Specifying the Object Directory, Up: Common Sources with Different Switches and Directories
Specifying the Exec Directory

A project's exec directory is another property; the corresponding attribute is Exec_Dir, and its value is also a string expression, either specified as relative or absolute. If Exec_Dir is not specified, then the default is the object directory (which may also be the project file directory if attribute Object_Dir is not specified). Thus the executable is placed in /common/debug for the Debug project (attribute Exec_Dir not specified) and in /common for the Release project.


Next: , Previous: Specifying the Exec Directory, Up: Common Sources with Different Switches and Directories
Project File Packages

A GNAT tool that is integrated with the Project Manager is modeled by a corresponding package in the project file. In the example above, The Debug project defines the packages Builder (for gnatmake) and Compiler; the Release project defines only the Compiler package.

The Ada-like package syntax is not to be taken literally. Although packages in project files bear a surface resemblance to packages in Ada source code, the notation is simply a way to convey a grouping of properties for a named entity. Indeed, the package names permitted in project files are restricted to a predefined set, corresponding to the project-aware tools, and the contents of packages are limited to a small set of constructs. The packages in the example above contain attribute definitions.


Next: , Previous: Project File Packages, Up: Common Sources with Different Switches and Directories
Specifying Switch Settings

Switch settings for a project-aware tool can be specified through attributes in the package that corresponds to the tool. The example above illustrates one of the relevant attributes, Default_Switches, which is defined in packages in both project files. Unlike simple attributes like Source_Dirs, Default_Switches is known as an associative array. When you define this attribute, you must supply an “index” (a literal string), and the effect of the attribute definition is to set the value of the array at the specified index. For the Default_Switches attribute, the index is a programming language (in our case, Ada), and the value specified (after use) must be a list of string expressions.

The attributes permitted in project files are restricted to a predefined set. Some may appear at project level, others in packages. For any attribute that is an associative array, the index must always be a literal string, but the restrictions on this string (e.g., a file name or a language name) depend on the individual attribute. Also depending on the attribute, its specified value will need to be either a string or a string list.

In the Debug project, we set the switches for two tools, gnatmake and the compiler, and thus we include the two corresponding packages; each package defines the Default_Switches attribute with index "Ada". Note that the package corresponding to gnatmake is named Builder. The Release project is similar, but only includes the Compiler package.

In project Debug above, the switches starting with -gnat that are specified in package Compiler could have been placed in package Builder, since gnatmake transmits all such switches to the compiler.


Next: , Previous: Specifying Switch Settings, Up: Common Sources with Different Switches and Directories
Main Subprograms

One of the specifiable properties of a project is a list of files that contain main subprograms. This property is captured in the Main attribute, whose value is a list of strings. If a project defines the Main attribute, it is not necessary to identify the main subprogram(s) when invoking gnatmake (see gnatmake and Project Files).


Next: , Previous: Main Subprograms, Up: Common Sources with Different Switches and Directories
Executable File Names

By default, the executable file name corresponding to a main source is deducted from the main source file name. Through the attributes Executable and Executable_Suffix of package Builder, it is possible to change this default. In project Debug above, the executable file name for main source proc.adb is proc1. Attribute Executable_Suffix, when specified, may change the suffix of the the executable files, when no attribute Executable applies: its value replace the platform-specific executable suffix. Attributes Executable and Executable_Suffix are the only ways to specify a non default executable file name when several mains are built at once in a single gnatmake command.


Next: , Previous: Executable File Names, Up: Common Sources with Different Switches and Directories
Source File Naming Conventions

Since the project files above do not specify any source file naming conventions, the GNAT defaults are used. The mechanism for defining source file naming conventions – a package named Naming – is described below (see Naming Schemes).


Previous: Source File Naming Conventions, Up: Common Sources with Different Switches and Directories
Source Language(s)

Since the project files do not specify a Languages attribute, by default the GNAT tools assume that the language of the project file is Ada. More generally, a project can comprise source files in Ada, C, and/or other languages.


Next: , Previous: Common Sources with Different Switches and Directories, Up: Examples of Project Files

11.2.2 Using External Variables

Instead of supplying different project files for debug and release, we can define a single project file that queries an external variable (set either on the command line or via an environment variable) in order to conditionally define the appropriate settings. Again, assume that the source files pack.ads, pack.adb, and proc.adb are located in directory /common. The following project file, build.gpr, queries the external variable named STYLE and defines an object directory and switch settings based on whether the value is "deb" (debug) or "rel" (release), and where the default is "deb".

     project Build is
       for Main use ("proc");
     
       type Style_Type is ("deb", "rel");
       Style : Style_Type := external ("STYLE", "deb");
     
       case Style is
         when "deb" =>
           for Object_Dir use "debug";
     
         when "rel" =>
           for Object_Dir use "release";
           for Exec_Dir use ".";
       end case;
     
       package Builder is
     
         case Style is
           when "deb" =>
             for Default_Switches ("Ada")
                 use ("-g");
             for Executable ("proc") use "proc1";
         end case;
     
       end Builder;
     
       package Compiler is
     
         case Style is
           when "deb" =>
             for Default_Switches ("Ada")
                 use ("-gnata",
                      "-gnato",
                      "-gnatE");
     
           when "rel" =>
             for Default_Switches ("Ada")
                 use ("-O2");
         end case;
     
       end Compiler;
     
     end Build;

Style_Type is an example of a string type, which is the project file analog of an Ada enumeration type but whose components are string literals rather than identifiers. Style is declared as a variable of this type.

The form external("STYLE", "deb") is known as an external reference; its first argument is the name of an external variable, and the second argument is a default value to be used if the external variable doesn't exist. You can define an external variable on the command line via the -X switch, or you can use an environment variable as an external variable.

Each case construct is expanded by the Project Manager based on the value of Style. Thus the command

     gnatmake -P/common/build.gpr -XSTYLE=deb

is equivalent to the gnatmake invocation using the project file debug.gpr in the earlier example. So is the command

     gnatmake -P/common/build.gpr

since "deb" is the default for STYLE.

Analogously,

     gnatmake -P/common/build.gpr -XSTYLE=rel

is equivalent to the gnatmake invocation using the project file release.gpr in the earlier example.


Next: , Previous: Using External Variables, Up: Examples of Project Files

11.2.3 Importing Other Projects

A compilation unit in a source file in one project may depend on compilation units in source files in other projects. To compile this unit under control of a project file, the dependent project must import the projects containing the needed source files. This effect is obtained using syntax similar to an Ada with clause, but where withed entities are strings that denote project files.

As an example, suppose that the two projects GUI_Proj and Comm_Proj are defined in the project files gui_proj.gpr and comm_proj.gpr in directories /gui and /comm, respectively. Suppose that the source files for GUI_Proj are gui.ads and gui.adb, and that the source files for Comm_Proj are comm.ads and comm.adb, where each set of files is located in its respective project file directory. Schematically:

     /gui
       gui_proj.gpr
       gui.ads
       gui.adb
     
     /comm
       comm_proj.gpr
       comm.ads
       comm.adb

We want to develop an application in directory /app that with the packages GUI and Comm, using the properties of the corresponding project files (e.g. the switch settings and object directory). Skeletal code for a main procedure might be something like the following:

     with GUI, Comm;
     procedure App_Main is
        ...
     begin
        ...
     end App_Main;

Here is a project file, app_proj.gpr, that achieves the desired effect:

     with "/gui/gui_proj", "/comm/comm_proj";
     project App_Proj is
        for Main use ("app_main");
     end App_Proj;

Building an executable is achieved through the command:

     gnatmake -P/app/app_proj

which will generate the app_main executable in the directory where app_proj.gpr resides.

If an imported project file uses the standard extension (gpr) then (as illustrated above) the with clause can omit the extension.

Our example specified an absolute path for each imported project file. Alternatively, the directory name of an imported object can be omitted if either

Thus, if we define ADA_PROJECT_PATH to include /gui and /comm, then our project file app_proj.gpr can be written as follows:

     with "gui_proj", "comm_proj";
     project App_Proj is
        for Main use ("app_main");
     end App_Proj;

Importing other projects can create ambiguities. For example, the same unit might be present in different imported projects, or it might be present in both the importing project and in an imported project. Both of these conditions are errors. Note that in the current version of the Project Manager, it is illegal to have an ambiguous unit even if the unit is never referenced by the importing project. This restriction may be relaxed in a future release.


Previous: Importing Other Projects, Up: Examples of Project Files

11.2.4 Extending a Project

In large software systems it is common to have multiple implementations of a common interface; in Ada terms, multiple versions of a package body for the same specification. For example, one implementation might be safe for use in tasking programs, while another might only be used in sequential applications. This can be modeled in GNAT using the concept of project extension. If one project (the “child”) extends another project (the “parent”) then by default all source files of the parent project are inherited by the child, but the child project can override any of the parent's source files with new versions, and can also add new files. This facility is the project analog of a type extension in Object-Oriented Programming. Project hierarchies are permitted (a child project may be the parent of yet another project), and a project that inherits one project can also import other projects.

As an example, suppose that directory /seq contains the project file seq_proj.gpr as well as the source files pack.ads, pack.adb, and proc.adb:

     /seq
       pack.ads
       pack.adb
       proc.adb
       seq_proj.gpr

Note that the project file can simply be empty (that is, no attribute or package is defined):

     project Seq_Proj is
     end Seq_Proj;

implying that its source files are all the Ada source files in the project directory.

Suppose we want to supply an alternate version of pack.adb, in directory /tasking, but use the existing versions of pack.ads and proc.adb. We can define a project Tasking_Proj that inherits Seq_Proj:

     /tasking
       pack.adb
       tasking_proj.gpr
     
     project Tasking_Proj extends "/seq/seq_proj" is
     end Tasking_Proj;

The version of pack.adb used in a build depends on which project file is specified.

Note that we could have obtained the desired behavior using project import rather than project inheritance; a base project would contain the sources for pack.ads and proc.adb, a sequential project would import base and add pack.adb, and likewise a tasking project would import base and add a different version of pack.adb. The choice depends on whether other sources in the original project need to be overridden. If they do, then project extension is necessary, otherwise, importing is sufficient.

In a project file that extends another project file, it is possible to indicate that an inherited source is not part of the sources of the extending project. This is necessary sometimes when a package spec has been overloaded and no longer requires a body: in this case, it is necessary to indicate that the inherited body is not part of the sources of the project, otherwise there will be a compilation error when compiling the spec.

For that purpose, the attribute Locally_Removed_Files is used. Its value is a string list: a list of file names.

     project B extends "a" is
        for Source_Files use ("pkg.ads");
        --  New spec of Pkg does not need a completion
        for Locally_Removed_Files use ("pkg.adb");
     end B;

Attribute Locally_Removed_Files may also be used to check if a source is still needed: if it is possible to build using gnatmake when such a source is put in attribute Locally_Removed_Files of a project P, then it is possible to remove the source completely from a system that includes project P.


Next: , Previous: Examples of Project Files, Up: GNAT Project Manager

11.3 Project File Syntax

This section describes the structure of project files.

A project may be an independent project, entirely defined by a single project file. Any Ada source file in an independent project depends only on the predefined library and other Ada source files in the same project.

A project may also depend on other projects, in either or both of the following ways:

The dependence relation is a directed acyclic graph (the subgraph reflecting the “extends” relation is a tree).

A project's immediate sources are the source files directly defined by that project, either implicitly by residing in the project file's directory, or explicitly through any of the source-related attributes described below. More generally, a project proj's sources are the immediate sources of proj together with the immediate sources (unless overridden) of any project on which proj depends (either directly or indirectly).


Next: , Up: Project File Syntax

11.3.1 Basic Syntax

As seen in the earlier examples, project files have an Ada-like syntax. The minimal project file is:

     project Empty is
     
     end Empty;

The identifier Empty is the name of the project. This project name must be present after the reserved word end at the end of the project file, followed by a semi-colon.

Any name in a project file, such as the project name or a variable name, has the same syntax as an Ada identifier.

The reserved words of project files are the Ada reserved words plus extends, external, and project. Note that the only Ada reserved words currently used in project file syntax are:

Comments in project files have the same syntax as in Ada, two consecutives hyphens through the end of the line.


Next: , Previous: Basic Syntax, Up: Project File Syntax

11.3.2 Packages

A project file may contain packages. The name of a package must be one of the identifiers from the following list. A package with a given name may only appear once in a project file. Package names are case insensitive. The following package names are legal:

In its simplest form, a package may be empty:

     project Simple is
       package Builder is
       end Builder;
     end Simple;

A package may contain attribute declarations, variable declarations and case constructions, as will be described below.

When there is ambiguity between a project name and a package name, the name always designates the project. To avoid possible confusion, it is always a good idea to avoid naming a project with one of the names allowed for packages or any name that starts with gnat.


Next: , Previous: Packages, Up: Project File Syntax

11.3.3 Expressions

An expression is either a string expression or a string list expression.

A string expression is either a simple string expression or a compound string expression.

A simple string expression is one of the following:

A compound string expression is a concatenation of string expressions, using the operator "&"

            Path & "/" & File_Name & ".ads"

A string list expression is either a simple string list expression or a compound string list expression.

A simple string list expression is one of the following:

A compound string list expression is the concatenation (using "&") of a simple string list expression and an expression. Note that each term in a compound string list expression, except the first, may be either a string expression or a string list expression.

        File_Name_List := () & File_Name; --  One string in this list
        Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
        --  Two strings
        Big_List := File_Name_List & Extended_File_Name_List;
        --  Concatenation of two string lists: three strings
        Illegal_List := "gnat.adc" & Extended_File_Name_List;
        --  Illegal: must start with a string list


Next: , Previous: Expressions, Up: Project File Syntax

11.3.4 String Types

A string type declaration introduces a discrete set of string literals. If a string variable is declared to have this type, its value is restricted to the given set of literals.

Here is an example of a string type declaration:

        type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");

Variables of a string type are called typed variables; all other variables are called untyped variables. Typed variables are particularly useful in case constructions, to support conditional attribute declarations. (see case Constructions).

The string literals in the list are case sensitive and must all be different. They may include any graphic characters allowed in Ada, including spaces.

A string type may only be declared at the project level, not inside a package.

A string type may be referenced by its name if it has been declared in the same project file, or by an expanded name whose prefix is the name of the project in which it is declared.


Next: , Previous: String Types, Up: Project File Syntax

11.3.5 Variables

A variable may be declared at the project file level, or within a package. Here are some examples of variable declarations:

        This_OS : OS := external ("OS"); --  a typed variable declaration
        That_OS := "GNU/Linux";          --  an untyped variable declaration

The syntax of a typed variable declaration is identical to the Ada syntax for an object declaration. By contrast, the syntax of an untyped variable declaration is identical to an Ada assignment statement. In fact, variable declarations in project files have some of the characteristics of an assignment, in that successive declarations for the same variable are allowed. Untyped variable declarations do establish the expected kind of the variable (string or string list), and successive declarations for it must respect the initial kind.

A string variable declaration (typed or untyped) declares a variable whose value is a string. This variable may be used as a string expression.

        File_Name       := "readme.txt";
        Saved_File_Name := File_Name & ".saved";

A string list variable declaration declares a variable whose value is a list of strings. The list may contain any number (zero or more) of strings.

        Empty_List := ();
        List_With_One_Element := ("-gnaty");
        List_With_Two_Elements := List_With_One_Element & "-gnatg";
        Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
                      "pack2.ada", "util_.ada", "util.ada");

The same typed variable may not be declared more than once at project level, and it may not be declared more than once in any package; it is in effect a constant.

The same untyped variable may be declared several times. Declarations are elaborated in the order in which they appear, so the new value replaces the old one, and any subsequent reference to the variable uses the new value. However, as noted above, if a variable has been declared as a string, all subsequent declarations must give it a string value. Similarly, if a variable has been declared as a string list, all subsequent declarations must give it a string list value.

A variable reference may take several forms:

A context may be one of the following:

A variable reference may be used in an expression.


Next: , Previous: Variables, Up: Project File Syntax

11.3.6 Attributes

A project (and its packages) may have attributes that define the project's properties. Some attributes have values that are strings; others have values that are string lists.

There are two categories of attributes: simple attributes and associative arrays (see Associative Array Attributes).

Legal project attribute names, and attribute names for each legal package are listed below. Attributes names are case-insensitive.

The following attributes are defined on projects (all are simple attributes):

Attribute Name Value
Source_Files string list
Source_Dirs string list
Source_List_File string
Object_Dir string
Exec_Dir string
Locally_Removed_Files string list
Main string list
Languages string list
Main_Language string
Library_Dir string
Library_Name string
Library_Kind string
Library_Version string
Library_Interface string
Library_Auto_Init string
Library_Options string list
Library_GCC string

The following attributes are defined for package Naming (see Naming Schemes):

Attribute Name Category Index Value
Spec_Suffix associative array language name string
Body_Suffix associative array language name string
Separate_Suffix simple attribute n/a string
Casing simple attribute n/a string
Dot_Replacement simple attribute n/a string
Spec associative array Ada unit name string
Body associative array Ada unit name string
Specification_Exceptions associative array language name string list
Implementation_Exceptions associative array language name string list

The following attributes are defined for packages Builder, Compiler, Binder, Linker, Cross_Reference, and Finder (see Switches and Project Files).

Attribute Name Category Index Value
Default_Switches associative array language name string list
Switches associative array file name string list

In addition, package Compiler has a single string attribute Local_Configuration_Pragmas and package Builder has a single string attribute Global_Configuration_Pragmas.

Each simple attribute has a default value: the empty string (for string-valued attributes) and the empty list (for string list-valued attributes).

An attribute declaration defines a new value for an attribute.

Examples of simple attribute declarations:

        for Object_Dir use "objects";
        for Source_Dirs use ("units", "test/drivers");

The syntax of a simple attribute declaration is similar to that of an attribute definition clause in Ada.

Attributes references may be appear in expressions. The general form for such a reference is <entity>'<attribute>: Associative array attributes are functions. Associative array attribute references must have an argument that is a string literal.

Examples are:

       project'Object_Dir
       Naming'Dot_Replacement
       Imported_Project'Source_Dirs
       Imported_Project.Naming'Casing
       Builder'Default_Switches("Ada")

The prefix of an attribute may be:

Example:

        project Prj is
          for Source_Dirs use project'Source_Dirs & "units";
          for Source_Dirs use project'Source_Dirs & "test/drivers"
        end Prj;

In the first attribute declaration, initially the attribute Source_Dirs has the default value: an empty string list. After this declaration, Source_Dirs is a string list of one element: "units". After the second attribute declaration Source_Dirs is a string list of two elements: "units" and "test/drivers".

Note: this example is for illustration only. In practice, the project file would contain only one attribute declaration:

        for Source_Dirs use ("units", "test/drivers");


Next: , Previous: Attributes, Up: Project File Syntax

11.3.7 Associative Array Attributes

Some attributes are defined as associative arrays. An associative array may be regarded as a function that takes a string as a parameter and delivers a string or string list value as its result.

Here are some examples of single associative array attribute associations:

        for Body ("main") use "Main.ada";
        for Switches ("main.ada")
            use ("-v",
                 "-gnatv");
        for Switches ("main.ada")
                 use Builder'Switches ("main.ada")
                   & "-g";

Like untyped variables and simple attributes, associative array attributes may be declared several times. Each declaration supplies a new value for the attribute, and replaces the previous setting.

An associative array attribute may be declared as a full associative array declaration, with the value of the same attribute in an imported or extended project.

        package Builder is
           for Default_Switches use Default.Builder'Default_Switches;
        end Builder;

In this example, Default must be either an project imported by the current project, or the project that the current project extends. If the attribute is in a package (in this case, in package Builder), the same package needs to be specified.

A full associative array declaration replaces any other declaration for the attribute, including other full associative array declaration. Single associative array associations may be declare after a full associative declaration, modifying the value for a single association of the attribute.


Previous: Associative Array Attributes, Up: Project File Syntax

11.3.8 case Constructions

A case construction is used in a project file to effect conditional behavior. Here is a typical example:

     project MyProj is
        type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
     
        OS : OS_Type := external ("OS", "GNU/Linux");
     
        package Compiler is
          case OS is
            when "GNU/Linux" | "Unix" =>
              for Default_Switches ("Ada")
                  use ("-gnath");
            when "NT" =>
              for Default_Switches ("Ada")
                  use ("-gnatP");
            when others =>
          end case;
        end Compiler;
     end MyProj;

The syntax of a case construction is based on the Ada case statement (although there is no null construction for empty alternatives).

The case expression must a typed string variable. Each alternative comprises the reserved word when, either a list of literal strings separated by the "|" character or the reserved word others, and the "=>" token. Each literal string must belong to the string type that is the type of the case variable. An others alternative, if present, must occur last.

After each =>, there are zero or more constructions. The only constructions allowed in a case construction are other case constructions and attribute declarations. String type declarations, variable declarations and package declarations are not allowed.

The value of the case variable is often given by an external reference (see External References in Project Files).


Next: , Previous: Project File Syntax, Up: GNAT Project Manager

11.4 Objects and Sources in Project Files

Each project has exactly one object directory and one or more source directories. The source directories must contain at least one source file, unless the project file explicitly specifies that no source files are present (see Source File Names).


Next: , Up: Objects and Sources in Project Files

11.4.1 Object Directory

The object directory for a project is the directory containing the compiler's output (such as ALI files and object files) for the project's immediate sources.

The object directory is given by the value of the attribute Object_Dir in the project file.

        for Object_Dir use "objects";

The attribute Object_Dir has a string value, the path name of the object directory. The path name may be absolute or relative to the directory of the project file. This directory must already exist, and be readable and writable.

By default, when the attribute Object_Dir is not given an explicit value or when its value is the empty string, the object directory is the same as the directory containing the project file.


Next: , Previous: Object Directory, Up: Objects and Sources in Project Files

11.4.2 Exec Directory

The exec directory for a project is the directory containing the executables for the project's main subprograms.

The exec directory is given by the value of the attribute Exec_Dir in the project file.

        for Exec_Dir use "executables";

The attribute Exec_Dir has a string value, the path name of the exec directory. The path name may be absolute or relative to the directory of the project file. This directory must already exist, and be writable.

By default, when the attribute Exec_Dir is not given an explicit value or when its value is the empty string, the exec directory is the same as the object directory of the project file.


Next: , Previous: Exec Directory, Up: Objects and Sources in Project Files

11.4.3 Source Directories

The source directories of a project are specified by the project file attribute Source_Dirs.

This attribute's value is a string list. If the attribute is not given an explicit value, then there is only one source directory, the one where the project file resides.

A Source_Dirs attribute that is explicitly defined to be the empty list, as in

         for Source_Dirs use ();

indicates that the project contains no source files.

Otherwise, each string in the string list designates one or more source directories.

        for Source_Dirs use ("sources", "test/drivers");

If a string in the list ends with "/**", then the directory whose path name precedes the two asterisks, as well as all its subdirectories (recursively), are source directories.

        for Source_Dirs use ("/system/sources/**");

Here the directory /system/sources and all of its subdirectories (recursively) are source directories.

To specify that the source directories are the directory of the project file and all of its subdirectories, you can declare Source_Dirs as follows:

        for Source_Dirs use ("./**");

Each of the source directories must exist and be readable.


Previous: Source Directories, Up: Objects and Sources in Project Files

11.4.4 Source File Names

In a project that contains source files, their names may be specified by the attributes Source_Files (a string list) or Source_List_File (a string). Source file names never include any directory information.

If the attribute Source_Files is given an explicit value, then each element of the list is a source file name.

        for Source_Files use ("main.adb");
        for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");

If the attribute Source_Files is not given an explicit value, but the attribute Source_List_File is given a string value, then the source file names are contained in the text file whose path name (absolute or relative to the directory of the project file) is the value of the attribute Source_List_File.

Each line in the file that is not empty or is not a comment contains a source file name.

        for Source_List_File use "source_list.txt";

By default, if neither the attribute Source_Files nor the attribute Source_List_File is given an explicit value, then each file in the source directories that conforms to the project's naming scheme (see Naming Schemes) is an immediate source of the project.

A warning is issued if both attributes Source_Files and Source_List_File are given explicit values. In this case, the attribute Source_Files prevails.

Each source file name must be the name of one existing source file in one of the source directories.

A Source_Files attribute whose value is an empty list indicates that there are no source files in the project.

If the order of the source directories is known statically, that is if "/**" is not used in the string list Source_Dirs, then there may be several files with the same source file name. In this case, only the file in the first directory is considered as an immediate source of the project file. If the order of the source directories is not known statically, it is an error to have several files with the same source file name.

Projects can be specified to have no Ada source files: the value of (Source_Dirs or Source_Files may be an empty list, or the "Ada" may be absent from Languages:

        for Source_Dirs use ();
        for Source_Files use ();
        for Languages use ("C", "C++");

Otherwise, a project must contain at least one immediate source.

Projects with no source files are useful as template packages (see Packages in Project Files) for other projects; in particular to define a package Naming (see Naming Schemes).


Next: , Previous: Objects and Sources in Project Files, Up: