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
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.
This guide contains the following chapters:
gcc, the Ada compiler.
gnatbind, the GNAT binding
utility.
gnatlink, a
program that provides for linking using the GNAT run-time library to
construct a program. gnatlink can also incorporate foreign language
object units into the executable.
gnatmake, a
utility that automatically determines the set of sources
needed by an Ada compilation unit, and executes the necessary compilations
binding and link.
gnatchop, a utility that allows you to preprocess a file that
contains Ada source code, and split it into one or more new files, one
for each compilation unit.
gnatxref and gnatfind, two tools that provide an easy
way to navigate through sources.
gnatkr
file name krunching utility, used to handle shortened
file names on operating systems with a limit on the length of names.
gnatprep, a
preprocessor utility that allows a single source file to be used to
generate multiple or parameterized source files, by means of macro
substitution.
gnatls, a
utility that displays information about compiled units, including dependences
on the corresponding sources files, and consistency of compilations.
gnatclean, a utility
to delete files that are produced by the compiler, binder and linker.
gnatstub,
a utility that generates empty but compilable bodies for library units.
gnathtml.
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.
For further information about related tools, refer to the following documents:
Following are examples of the typographical and graphic conventions used in this guide:
Functions, utility program names, standard names,
and classes.
and then shown this way.
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.
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.
Three steps are needed to create an executable file from an Ada source file:
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.
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.
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
Greetings
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.
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.
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).
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.
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:
Start with default project in directory
Create new project with wizard
Open existing project
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.
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.
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.
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.
This section illustrates basic debugging techniques (setting breakpoints, examining/modifying variables, single stepping).
Start GPS and select Open existing project; browse to
specify the project file sample.prj that you had created in the
earlier example.
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.
Add Example as a new main unit for the project:
Project, then Edit Project Properties.
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
OK
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.
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.
Select Debug, then Initialize, then example
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));
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.
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.
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.
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.
Toggle the breakpoint icon at line 10.
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.
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.
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
Buffers
Files
Tools
Edit
Search
Mule
Glide
Help
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
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.
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:
Files => Split Window;
this will produce two windows each of which holds the original buffer
(these are not copies, but rather different views of the same buffer contents)
Buffers menu
To exit from Glide, choose Files => Exit.
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.
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:
VT16#0B#
HT16#09#
CR16#0D#
LF16#0A#
FF16#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.
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).
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.
GNAT also supports several other 8-bit coding schemes:
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.
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:
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.
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.
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.
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.
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).
[ " 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.
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.
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.
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.
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:
Source_File_Name pragma for the given unit,
then this is always used, and any general pattern rules are ignored.
Source_File_Name pragma that applies to
the unit, then the resulting file name will be used if the file exists. If
more than one pattern matches, the latest one will be tried first, and the
first attempt resulting in a reference to a file that exists will be used.
Source_File_Name pragma that applies to the unit
for which the corresponding file exists, then the standard GNAT default
naming rules are used.
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);
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.
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:
with's a unit X, the object file
depends on the file containing the spec of unit X. This includes
files that are with'ed implicitly either because they are parents
of with'ed child units or they are run-time units required by the
language constructs used in a particular unit.
Inline applies and inlining is activated with the
-gnatn switch, the object file depends on the file containing the
body of this subprogram as well as on the file containing the spec. Note
that for inlining to actually occur as a result of the use of this switch,
it is necessary to compile in optimizing mode.
The use of -gnatN activates a more extensive inlining optimization that is performed by the front end of the compiler. This inlining does not require that the code generation be optimized. Like -gnatn, the use of this switch generates additional dependencies. Note that -gnatN automatically implies -gnatn so it is not necessary to specify both options.
These rules are applied transitively: if unit A with's
unit B, whose elaboration calls an inlined procedure in package
C, the object file for unit A will depend on the body of
C, in file c.adb.
The set of dependent files described by these rules includes all the files on which the unit is semantically dependent, as described in the Ada 95 Language Reference Manual. However, it is a superset of what the ARM describes, because it includes generic, inline, and subunit dependencies.
An object file must be recreated by recompiling the corresponding source
file if any of the source files on which it depends are modified. For
example, if the make utility is used to control compilation,
the rule for an Ada object file must mention all the source files on
which the object file depends, according to the above definition.
The determination of the necessary
recompilations is done automatically when one uses gnatmake.
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.
gcc command for the compilation
Pure).
with'ed units, including presence of
Elaborate or Elaborate_All pragmas.
Linker_Options pragmas used in the unit
Body_Version or Version
attributes in the unit.
gnatxref and gnatfind to
provide cross-reference information.
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.
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.
This section describes how to develop a mixed-language program, specifically one that comprises units in both Ada and 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;
gcc -c file1.c
gcc -c file2.c
gnatmake -c my_main.adb
gnatbind my_main.ali
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;
gcc -c main.c
gnatmake -c unit1.adb
gnatmake -c unit2.adb
gnatbind -n unit1.ali unit2.ali
gnatlink unit2.ali main.o -o exec_file
This procedure yields a binary executable called exec_file.
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:
AdaNote 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.
AssemblerAsmCOBOLCDefaultExternalCPPFortranIntrinsic type Distance is new Long_Float;
type Time is new Long_Float;
type Velocity is new Long_Float;
function "/" (D : Distance; T : Time)
return Velocity;
pragma Import (Intrinsic, "/");
This common idiom is often programmed with a generic definition and an explicit body. The pragma makes it simpler to introduce such declarations. It incurs no overhead in compilation time or code size, because it is implemented as a single machine instruction.
StdcallDLLWin32StubbedProgram_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.
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.
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:
extern "C" syntax.
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.
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:
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++
$ 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
$ 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.
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;
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.
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.
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:
with'ed, the unit seen by the compiler corresponds
to the version of the unit most recently compiled into the library.
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:
with'ed, the unit seen by the compiler corresponds
to the source version of the unit that is currently accessible to the
compiler.
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.
gccThis 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.
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.
gccThe 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.
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.
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.
Inline_Always.
See also -gnatn and -gnatN.
Pragma Assert and pragma Debug to be
activated.
k = krunch).
inline is specified. This inlining is performed
by the GCC back-end.
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.
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.
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.
Inline. This applies only to
inlining within a unit. For details on control of inlining
see See Subprogram Inlining Control.
gnatmake flag (see Switches for gnatmake).
gcc driver. Normally used only for
debugging purposes or if you need to be sure what version of the
compiler you are executing.
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:
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:
| 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.
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.
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).
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
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:
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.
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.
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.
accept statement
select
return statement along some execution path in a function
with clauses
Bit_Order usage that does not have any effect
Standard.Duration used to resolve universal fixed expression
with'ed by application unit
for loop that is known to be null or might be null
The following switches are available to control the handling of warning messages:
.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.
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.
with of an internal GNAT
implementation unit.
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.
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.
Base where typ'Base is the same
as typ.
Pack when all components are placed by a record
representation clause.
if statements, while statements and exit statements.
gcc back end.
To suppress these back end warnings as well, use the switch -w
in addition to -gnatws.
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.
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:
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.
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.
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.
in mode parameters
Arguments for parameters of mode in are validity checked in function
and procedure calls at the point of call.
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.
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.
return statements in functions is validity
checked.
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.
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:
-- starting on a column that is a multiple of
the alignment level.
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.
--” that starts the column must either start in column one,
or else at least one blank must precede this sequence.
--” at the start of the comment.
--” that
starts the comment, with the following exceptions.
--” characters, possibly preceded
by blanks is permitted.
--x” where x is a special character
is permitted.
This allows proper processing of the output generated by specialized tools
including gnatprep (where “--!” is used) and the SPARK
annotation
language (where “--#” is used). For the purposes of this rule, a
special character is defined as being in one of the ASCII ranges
16#21#..16#2F# or 16#3A#..16#3F#.
Note that this usage is not permitted
in GNAT implementation units (i.e. when -gnatg is used).
--” is permitted as long as at
least one blank follows the initial “--”. Together with the preceding
rule, this allows the construction of box comments, as shown in the following
example:
---------------------------
-- This is a box comment --
-- with two text lines. --
---------------------------
end statements ending subprograms and on
exit statements exiting named loops, are required to be present.
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.
digits used as attribute names to which this check
does not apply).
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; |
Integer and ASCII.NUL).
=> must be surrounded by spaces.
<> must be preceded by a space or a left parenthesis.
** must be surrounded by spaces.
There is no restriction on the layout of the ** binary operator.
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.
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:
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.
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.
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.
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.
gcc for Syntax Checkings 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).
gcc for Semantic Checkingc 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).
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.
123459p8fnwSee Foreign Language Representation, for full details on the
implementation of these character sets.
huse8bUTF-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.
For the source file naming rules, See File Naming Rules.
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.
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:
Debug unit in the compiler source
file debug.adb.
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]at end procedure-name;(if expr then expr else expr)x?y:z construction in C.
^(source)?(source)?^(source) #/ y #mod y #* y #rem yfree expr [storage_pool = xxx]free statement.
freeze typename [actions]reference itype! (arg, arg, arg) : label && expr && expr ... && expr[constraint_error]Constraint_Error exception.
'reference!(source-expression)[numerator/denominator]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).
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.
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.
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.
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.
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.
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.
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=fileA 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-c--! ”.
-Dsymbol=valueif,
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-uFALSE
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]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.
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:
gcc command line, in the order given.
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).
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.
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.
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:
with's, all its subunits, and the bodies of any generics it
instantiates must be available (reachable by the search-paths mechanism
described above), or you will receive a fatal error message.
The following are some typical Ada compilation command line examples:
$ gcc -c xyz.adb$ gcc -c -O2 -gnata xyz-def.adbAssert/Debug statements
enabled.
$ gcc -c -gnatc abc-def.adbgnatbindThis chapter describes the GNAT binder, gnatbind, which is used
to bind compiled GNAT objects. The gnatbind program performs
four separate functions:
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.
gnatlink utility used to link the Ada application.
gnatbindThe 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:
gcc -c hello.adb to compile the main program.
gcc -c p.ads to compile package P.
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).
The following switches are available with gnatbind; details will
be presented in subsequent sections.
GNAT.Traceback and
GNAT.Traceback.Symbolic for more information.
Note that on x86 ports, you must not use -fomit-frame-pointer
gcc option.
gnatbind was
invoked, and do not look for ALI files in the directory containing the
ALI file named in the gnatbind command line.
gnatmake flag (see Switches for gnatmake).
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).
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.
You may obtain this listing of switches by running gnatbind with
no arguments.
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.
gnatmake because in this
case the checking against sources has already been performed by
gnatmake in the course of compilation (i.e. before binding).
The following switches provide control over the generation of error messages from the binder:
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.
GNAT were used for compilation
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.
The following switches provide additional control over the elaboration order. For full details see See Elaboration Order Handling in GNAT.
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.
The following switches allow additional control over the output generated by the binder.
gnatbind option.
gnatbind
option.
gnatbind.
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.
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:
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:
adainitadainit 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.
adafinaladafinal 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.
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:
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.
gnatbindThe 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:
gnatbind
command line, in the order given.
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).
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.
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.
gnatbind UsageThis section contains a number of examples of using the GNAT binding
utility gnatbind.
gnatbind helloHello (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.adbHello (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 -xMain (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.cgnatbind -n math dbase -C -o ada-control.cMath 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.
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.
gnatlinkThe 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.
gnatlinkThe following switches are available with the gnatlink utility:
gnatlink that the binder has generated C code rather than
Ada code.
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.
gnatbind option, in this case the filenames
are b_mainprog.c and b_mainprog.o.
gnatlink try.ali creates
an executable called try.
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'. 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".
gnatlinkUnder Windows systems, it is possible to specify the program stack size from
gnatlink using either:
$ gnatlink hello -Xlinker --stack=0x10000,0x1000
This sets the stack reserve size to 0x10000 bytes and the stack commit size to 0x1000 bytes.
$ gnatlink hello -Wl,--stack=0x1000000
This sets the stack reserve size to 0x1000000 bytes. Note that with -Wl option it is not possible to set the stack commit size because the coma is a separator for this option.
gnatlinkUnder Windows systems, it is possible to specify the program heap size from
gnatlink using either:
$ gnatlink hello -Xlinker --heap=0x10000,0x1000
This sets the heap reserve size to 0x10000 bytes and the heap commit size to 0x1000 bytes.
$ gnatlink hello -Wl,--heap=0x1000000
This sets the heap reserve size to 0x1000000 bytes. Note that with -Wl option it is not possible to set the heap commit size because the coma is a separator for this option.
gnatmakeThe 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.
gnatmakeThe 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.
gnatmakeYou may specify any of the following switches to gnatmake:
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'. 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'. 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.
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.
gnatmake will attempt binding and linking
unless all objects are up to date and the executable is more recent than
the objects.
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.
This switch cannot be used when using a project file.
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.
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.
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.
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.
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.
This switch cannot be used when invoking gnatmake with several
file_names.
gnatmake are displayed.
This switch is recommended when Integrated Preprocessing is used.
gnatmake
decides are necessary.
external(name) when parsing the project file.
See Switches Related to Project Files.
gcc switchesgcc (e.g. -O, -gnato, etc.)
Source and library search path switches:
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.
gnatmake was invoked.
The selected path is handled like a normal RTS path.
gnatmakeThe 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.
gcc. They will be passed on to
all compile steps performed by gnatmake.
gnatbind. They will be passed on to
all bind steps performed by gnatmake.
gnatlink. They will be passed on to
all link steps performed by gnatmake.
gnatmake,
regardless of any previous occurrence of -cargs, -bargs
or -largs.
This section contains some additional useful notes on the operation
of the gnatmake command.
gnatmake finds no ALI files, it recompiles the main program
and all other units required by the main program.
This means that gnatmake
can be used for the initial compile, as well as during subsequent steps of
the development cycle.
gnatmake file.adb, where file.adb
is a subunit or body of a generic unit, gnatmake recompiles
file.adb (because it finds no ALI) and stops, issuing a
warning.
gnatmake the switch -I
is used to specify both source and
library file paths. Use -aI
instead if you just want to specify
source paths only and -aO
if you want to specify library paths
only.
gnatmake examines both an ALI file and its corresponding object file
for consistency. If an ALI is more recent than its corresponding object,
or if the object file is missing, the corresponding source will be recompiled.
Note that gnatmake expects an ALI and the corresponding object file
to be in the same directory.
gnatmake will ignore any files whose ALI file is write-protected.
This may conveniently be used to exclude standard libraries from
consideration and in particular it means that the use of the
-f switch will not recompile these files
unless -a is also specified.
gnatmake has been designed to make the use of Ada libraries
particularly convenient. Assume you have an Ada library organized
as follows: obj-dir contains the objects and ALI files for
of your Ada compilation units,
whereas include-dir contains the
specs of these units, but no bodies. Then to compile a unit
stored in main.adb, which uses this Ada library you would just type
$ gnatmake -aIinclude-dir -aLobj-dir main
gnatmake along with the
-m (minimal recompilation)
switch provides a mechanism for avoiding unnecessary rcompilations. Using
this switch,
you can update the comments/format of your
source files without having to recompile everything. Note, however, that
adding or deleting lines in a source files may render its debugging
info obsolete. If the file in question is a spec, the impact is rather
limited, as that debugging info will only be useful during the
elaboration phase of your program. For bodies the impact can be more
significant. In all events, your debugger will warn you if a source file
is more recent than the corresponding object, and alert you to the fact
that the debugging information may be out of date.
gnatmake WorksGenerally 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.
gnatmake Usagegnatmake hello.adbHello) and bind and link the
resulting object files to generate an executable file hello.
gnatmake main1 main2 main3Main1), 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 -lMain_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.
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.
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.
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.
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.
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:
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.
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:
step or next
commands show
the PC bouncing back and forth in the code. This may result from any of
the following optimizations:
goto, a return, or
a break in a C switch statement.
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.
A call to a subprogram in the current unit is inlined if all the following conditions are met:
gcc
cannot support in inlined subprograms.
pragma Inline applies to the subprogram or it is
small and automatic inlining (optimization level -O3) is
specified.
Calls to subprograms in with'ed units are normally not inlined.
To achieve this level of inlining, the following conditions must all be
true:
gcc cannot
support in inlined subprograms.
pragma Inline for the subprogram.
gcc command line
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.
gnatelimThis section describes gnatelim, a tool which detects unused subprograms and helps the compiler to create a smaller executable for your program.
gnatelimWhen 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.
gnatelimgnatelim 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:
gnatelim outputs to the standard error
stream the number of program units left to be processed. This option turns
this trace off.
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.
gnatmake.
gnatelim not to look for
sources in the current directory.
gnatelim to use specific gcc compiler instead of one
available on the path.
gnatelim to use specific gnatmake instead of one
available on the path.
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.
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.
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.
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.
$ gnatmake -c main_prog
$ gnatbind main_prog
Eliminate pragmas
$ gnatelim main_prog >[>] gnat.adc
$ gnatmake -f main_prog
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.
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.
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.
gnatchopThe 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
gnatchopgnatchop recognizes the following switches:
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.
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.
gnatchop to generate a brief help summary to the standard
output file showing usage information.
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.
gnatchop is used as part of a standard build process.
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.
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.
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.
gnatchop Usagegnatchop -w hello_s.ada prerelease/filesgnatchop archivegnatchop 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
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
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.
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.
gnatnameThe 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.
gnatnameThe 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.
gnatnameSwitches for gnatname must precede any specified Naming Pattern.
You may specify any of the following switches to gnatname:
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".
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.
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.
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:
gnatls, gnatxref,
gnatfind); you can apply these settings either globally or to individual
compilation units.
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.
This section illustrates some of the typical uses of project files and explains their basic structure and behavior.
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.
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.
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.
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.
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.
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.
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).
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.
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).
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.
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.
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
ADA_PROJECT_PATH is the same as
the syntax of ADA_INCLUDE_PATH and ADA_OBJECTS_PATH: a list of
directory names separated by colons (semicolons on Windows).
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.
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.
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).
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:
case
end
for
is
others
package
renames
type
use
when
with
Comments in project files have the same syntax as in Ada, two consecutives hyphens through the end of the line.
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:
Naming
Builder
Compiler
Binder
Linker
Finder
Cross_Reference
Eliminate
gnatls
gnatstub
IDE
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.
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:
"comm/my_proj.gpr"
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:
File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
Empty_List := ();
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
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.
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.
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:
project for an attribute of the current project
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");
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.
case ConstructionsA 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).
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).
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.
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.
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.
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).