1 \input texinfo @c -*-texinfo-*-
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
6 @c GNAT DOCUMENTATION o
10 @c Copyright (C) 1992-2002 Ada Core Technologies, Inc. o
12 @c GNAT is free software; you can redistribute it and/or modify it under o
13 @c terms of the GNU General Public License as published by the Free Soft- o
14 @c ware Foundation; either version 2, or (at your option) any later ver- o
15 @c sion. GNAT is distributed in the hope that it will be useful, but WITH- o
16 @c OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY o
17 @c or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License o
18 @c for more details. You should have received a copy of the GNU General o
19 @c Public License distributed with GNAT; see file COPYING. If not, write o
20 @c to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, o
21 @c MA 02111-1307, USA. o
23 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
25 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
27 @c GNAT_UG Style Guide
29 @c 1. Always put a @noindent on the line before the first paragraph
30 @c after any of these commands:
42 @c 2. DO NOT use @example. Use @smallexample instead.
44 @c 3. Each @chapter, @section, @subsection, @subsubsection, etc.
45 @c command must be preceded by two empty lines
47 @c 4. The @item command must be on a line of its own if it is in an
48 @c @itemize or @enumerate command.
50 @c 5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
53 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
57 @setfilename gnat_ug_unx.info
58 @settitle GNAT User's Guide for Unix Platforms
61 @include gcc-common.texi
63 @setchapternewpage odd
68 Copyright @copyright{} 1995-2003, Free Software Foundation
70 Permission is granted to copy, distribute and/or modify this document
71 under the terms of the GNU Free Documentation License, Version 1.2
72 or any later version published by the Free Software Foundation;
73 with the Invariant Sections being ``GNU Free Documentation License'', with the
74 Front-Cover Texts being
75 ``GNAT User's Guide for Unix Platforms'',
76 and with no Back-Cover Texts.
77 A copy of the license is included in the section entitled ``GNU
78 Free Documentation License''.
85 @title GNAT User's Guide
86 @center @titlefont{for Unix Platforms}
89 @subtitle GNAT, The GNU Ada 95 Compiler
90 @subtitle GNAT Version for GCC @value{version-GCC}
92 @author Ada Core Technologies, Inc.
95 @vskip 0pt plus 1filll
102 @node Top, About This Guide, (dir), (dir)
103 @top GNAT User's Guide
107 GNAT User's Guide for Unix Platforms
110 GNAT, The GNU Ada 95 Compiler
112 GNAT Version for GCC @value{version-GCC}
114 Ada Core Technologies, Inc.
120 * Getting Started with GNAT::
121 * The GNAT Compilation Model::
122 * Compiling Using gcc::
123 * Binding Using gnatbind::
124 * Linking Using gnatlink::
125 * The GNAT Make Program gnatmake::
126 * Renaming Files Using gnatchop::
127 * Configuration Pragmas::
128 * Handling Arbitrary File Naming Conventions Using gnatname::
129 * GNAT Project Manager::
130 * Elaboration Order Handling in GNAT::
131 * The Cross-Referencing Tools gnatxref and gnatfind::
132 * File Name Krunching Using gnatkr::
133 * Preprocessing Using gnatprep::
134 * The GNAT Library Browser gnatls::
135 * GNAT and Libraries::
136 * Using the GNU make Utility::
137 * Finding Memory Problems with gnatmem::
138 * Finding Memory Problems with GNAT Debug Pool::
139 * Creating Sample Bodies Using gnatstub::
140 * Reducing the Size of Ada Executables with gnatelim::
141 * Other Utility Programs::
142 * Running and Debugging Ada Programs::
144 * Performance Considerations::
145 * GNU Free Documentation License::
148 --- The Detailed Node Listing ---
152 * What This Guide Contains::
153 * What You Should Know before Reading This Guide::
154 * Related Information::
158 Getting Started with GNAT
161 * Running a Simple Ada Program::
162 * Running a Program with Multiple Units::
163 * Using the gnatmake Utility::
165 The GNAT Compilation Model
167 * Source Representation::
168 * Foreign Language Representation::
169 * File Naming Rules::
170 * Using Other File Names::
171 * Alternative File Naming Schemes::
172 * Generating Object Files::
173 * Source Dependencies::
174 * The Ada Library Information Files::
175 * Binding an Ada Program::
176 * Mixed Language Programming::
177 * Building Mixed Ada & C++ Programs::
178 * Comparison between GNAT and C/C++ Compilation Models::
179 * Comparison between GNAT and Conventional Ada Library Models::
181 Foreign Language Representation
184 * Other 8-Bit Codes::
185 * Wide Character Encodings::
187 Compiling Ada Programs With gcc
189 * Compiling Programs::
191 * Search Paths and the Run-Time Library (RTL)::
192 * Order of Compilation Issues::
197 * Output and Error Message Control::
198 * Debugging and Assertion Control::
200 * Stack Overflow Checking::
202 * Validity Checking::
204 * Using gcc for Syntax Checking::
205 * Using gcc for Semantic Checking::
206 * Compiling Ada 83 Programs::
207 * Character Set Control::
208 * File Naming Control::
209 * Subprogram Inlining Control::
210 * Auxiliary Output Control::
211 * Debugging Control::
212 * Units to Sources Mapping Files::
214 Binding Ada Programs With gnatbind
217 * Generating the Binder Program in C::
218 * Consistency-Checking Modes::
219 * Binder Error Message Control::
220 * Elaboration Control::
222 * Binding with Non-Ada Main Programs::
223 * Binding Programs with No Main Subprogram::
224 * Summary of Binder Switches::
225 * Command-Line Access::
226 * Search Paths for gnatbind::
227 * Examples of gnatbind Usage::
229 Linking Using gnatlink
232 * Switches for gnatlink::
233 * Setting Stack Size from gnatlink::
234 * Setting Heap Size from gnatlink::
236 The GNAT Make Program gnatmake
239 * Switches for gnatmake::
240 * Mode Switches for gnatmake::
241 * Notes on the Command Line::
242 * How gnatmake Works::
243 * Examples of gnatmake Usage::
245 Renaming Files Using gnatchop
247 * Handling Files with Multiple Units::
248 * Operating gnatchop in Compilation Mode::
249 * Command Line for gnatchop::
250 * Switches for gnatchop::
251 * Examples of gnatchop Usage::
253 Configuration Pragmas
255 * Handling of Configuration Pragmas::
256 * The Configuration Pragmas Files::
258 Handling Arbitrary File Naming Conventions Using gnatname
260 * Arbitrary File Naming Conventions::
262 * Switches for gnatname::
263 * Examples of gnatname Usage::
268 * Examples of Project Files::
269 * Project File Syntax::
270 * Objects and Sources in Project Files::
271 * Importing Projects::
272 * Project Extension::
273 * External References in Project Files::
274 * Packages in Project Files::
275 * Variables from Imported Projects::
278 * Switches Related to Project Files::
279 * Tools Supporting Project Files::
280 * An Extended Example::
281 * Project File Complete Syntax::
283 Elaboration Order Handling in GNAT
285 * Elaboration Code in Ada 95::
286 * Checking the Elaboration Order in Ada 95::
287 * Controlling the Elaboration Order in Ada 95::
288 * Controlling Elaboration in GNAT - Internal Calls::
289 * Controlling Elaboration in GNAT - External Calls::
290 * Default Behavior in GNAT - Ensuring Safety::
291 * Elaboration Issues for Library Tasks::
292 * Mixing Elaboration Models::
293 * What to Do If the Default Elaboration Behavior Fails::
294 * Elaboration for Access-to-Subprogram Values::
295 * Summary of Procedures for Elaboration Control::
296 * Other Elaboration Order Considerations::
298 The Cross-Referencing Tools gnatxref and gnatfind
300 * gnatxref Switches::
301 * gnatfind Switches::
302 * Project Files for gnatxref and gnatfind::
303 * Regular Expressions in gnatfind and gnatxref::
304 * Examples of gnatxref Usage::
305 * Examples of gnatfind Usage::
307 File Name Krunching Using gnatkr
312 * Examples of gnatkr Usage::
314 Preprocessing Using gnatprep
317 * Switches for gnatprep::
318 * Form of Definitions File::
319 * Form of Input Text for gnatprep::
322 The GNAT Library Browser gnatls
325 * Switches for gnatls::
326 * Examples of gnatls Usage::
331 * Creating an Ada Library::
332 * Installing an Ada Library::
333 * Using an Ada Library::
334 * Creating an Ada Library to be Used in a Non-Ada Context::
335 * Rebuilding the GNAT Run-Time Library::
337 Using the GNU make Utility
339 * Using gnatmake in a Makefile::
340 * Automatically Creating a List of Directories::
341 * Generating the Command Line Switches::
342 * Overcoming Command Line Length Limits::
344 Finding Memory Problems with gnatmem
346 * Running gnatmem (GDB Mode)::
347 * Running gnatmem (GMEM Mode)::
348 * Switches for gnatmem::
349 * Examples of gnatmem Usage::
350 * GDB and GMEM Modes::
351 * Implementation Note::
354 Finding Memory Problems with GNAT Debug Pool
356 Creating Sample Bodies Using gnatstub
359 * Switches for gnatstub::
361 Reducing the Size of Ada Executables with gnatelim
366 * Preparing Tree and Bind Files for gnatelim::
368 * Correcting the List of Eliminate Pragmas::
369 * Making Your Executables Smaller::
370 * Summary of the gnatelim Usage Cycle::
372 Other Utility Programs
374 * Using Other Utility Programs with GNAT::
375 * The gnatpsta Utility Program::
376 * The External Symbol Naming Scheme of GNAT::
377 * Ada Mode for Glide::
378 * Converting Ada Files to html with gnathtml::
381 Running and Debugging Ada Programs
383 * The GNAT Debugger GDB::
385 * Introduction to GDB Commands::
386 * Using Ada Expressions::
387 * Calling User-Defined Subprograms::
388 * Using the Next Command in a Function::
391 * Debugging Generic Units::
392 * GNAT Abnormal Termination or Failure to Terminate::
393 * Naming Conventions for GNAT Source Files::
394 * Getting Internal Debugging Information::
399 * Basic Assembler Syntax::
400 * A Simple Example of Inline Assembler::
401 * Output Variables in Inline Assembler::
402 * Input Variables in Inline Assembler::
403 * Inlining Inline Assembler Code::
404 * Other Asm Functionality::
405 * A Complete Example::
409 Performance Considerations
411 * Controlling Run-Time Checks::
412 * Optimization Levels::
413 * Debugging Optimized Code::
414 * Inlining of Subprograms::
420 @node About This Guide
421 @unnumbered About This Guide
424 This guide describes the use of GNAT, a compiler and software development
425 toolset for the full Ada 95 programming language.
426 It describes the features of the compiler and tools, and details
427 how to use them to build Ada 95 applications.
430 * What This Guide Contains::
431 * What You Should Know before Reading This Guide::
432 * Related Information::
436 @node What This Guide Contains
437 @unnumberedsec What This Guide Contains
440 This guide contains the following chapters:
443 @ref{Getting Started with GNAT}, describes how to get started compiling
444 and running Ada programs with the GNAT Ada programming environment.
446 @ref{The GNAT Compilation Model}, describes the compilation model used
449 @ref{Compiling Using gcc}, describes how to compile
450 Ada programs with @code{gcc}, the Ada compiler.
452 @ref{Binding Using gnatbind}, describes how to
453 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
456 @ref{Linking Using gnatlink},
457 describes @code{gnatlink}, a
458 program that provides for linking using the GNAT run-time library to
459 construct a program. @code{gnatlink} can also incorporate foreign language
460 object units into the executable.
462 @ref{The GNAT Make Program gnatmake}, describes @code{gnatmake}, a
463 utility that automatically determines the set of sources
464 needed by an Ada compilation unit, and executes the necessary compilations
467 @ref{Renaming Files Using gnatchop}, describes
468 @code{gnatchop}, a utility that allows you to preprocess a file that
469 contains Ada source code, and split it into one or more new files, one
470 for each compilation unit.
472 @ref{Configuration Pragmas}, describes the configuration pragmas handled by GNAT.
474 @ref{Handling Arbitrary File Naming Conventions Using gnatname}, shows how to override
475 the default GNAT file naming conventions, either for an individual unit or globally.
477 @ref{GNAT Project Manager}, describes how to use project files to organize large projects.
479 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps you deal with
480 elaboration order issues.
482 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
483 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
484 way to navigate through sources.
486 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
487 file name krunching utility, used to handle shortened
488 file names on operating systems with a limit on the length of names.
490 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
491 preprocessor utility that allows a single source file to be used to
492 generate multiple or parameterized source files, by means of macro
495 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
496 utility that displays information about compiled units, including dependences
497 on the corresponding sources files, and consistency of compilations.
499 @ref{GNAT and Libraries}, describes the process of creating and using
500 Libraries with GNAT. It also describes how to recompile the GNAT run-time
504 @ref{Using the GNU make Utility}, describes some techniques for using
505 the GNAT toolset in Makefiles.
508 @ref{Finding Memory Problems with gnatmem}, describes @code{gnatmem}, a
509 utility that monitors dynamic allocation and deallocation activity in a
510 program, and displays information about incorrect deallocations and sources
511 of possible memory leaks.
513 @ref{Finding Memory Problems with GNAT Debug Pool}, describes how to
514 use the GNAT-specific Debug Pool in order to detect as early as possible
515 the use of incorrect memory references.
518 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
519 a utility that generates empty but compilable bodies for library units.
522 @ref{Reducing the Size of Ada Executables with gnatelim}, describes
523 @code{gnatelim}, a tool which detects unused subprograms and helps
524 the compiler to create a smaller executable for the program.
527 @ref{Other Utility Programs}, discusses several other GNAT utilities,
528 including @code{gnatpsta}.
531 @ref{Running and Debugging Ada Programs}, describes how to run and debug
535 @ref{Inline Assembler}, shows how to use the inline assembly facility in an Ada program.
539 @ref{Performance Considerations}, reviews the trade offs between using
540 defaults or options in program development.
543 @node What You Should Know before Reading This Guide
544 @unnumberedsec What You Should Know before Reading This Guide
546 @cindex Ada 95 Language Reference Manual
548 This user's guide assumes that you are familiar with Ada 95 language, as
549 described in the International Standard ANSI/ISO/IEC-8652:1995, Jan
552 @node Related Information
553 @unnumberedsec Related Information
556 For further information about related tools, refer to the following
561 @cite{GNAT Reference Manual}, which contains all reference
562 material for the GNAT implementation of Ada 95.
565 @cite{Ada 95 Language Reference Manual}, which contains all reference
566 material for the Ada 95 programming language.
569 @cite{Debugging with GDB}
570 contains all details on the use of the GNU source-level debugger.
573 @cite{GNU Emacs Manual}
574 contains full information on the extensible editor and programming
580 @unnumberedsec Conventions
582 @cindex Typographical conventions
585 Following are examples of the typographical and graphic conventions used
590 @code{Functions}, @code{utility program names}, @code{standard names},
597 @file{File Names}, @file{button names}, and @file{field names}.
606 [optional information or parameters]
609 Examples are described by text
611 and then shown this way.
616 Commands that are entered by the user are preceded in this manual by the
617 characters @w{"@code{$ }"} (dollar sign followed by space). If your system
618 uses this sequence as a prompt, then the commands will appear exactly as
619 you see them in the manual. If your system uses some other prompt, then
620 the command will appear with the @code{$} replaced by whatever prompt
621 character you are using.
624 @node Getting Started with GNAT
625 @chapter Getting Started with GNAT
628 This chapter describes some simple ways of using GNAT to build
629 executable Ada programs.
633 * Running a Simple Ada Program::
635 * Running a Program with Multiple Units::
637 * Using the gnatmake Utility::
638 * Introduction to Glide and GVD::
642 @section Running GNAT
645 Three steps are needed to create an executable file from an Ada source
650 The source file(s) must be compiled.
652 The file(s) must be bound using the GNAT binder.
654 All appropriate object files must be linked to produce an executable.
658 All three steps are most commonly handled by using the @code{gnatmake}
659 utility program that, given the name of the main program, automatically
660 performs the necessary compilation, binding and linking steps.
662 @node Running a Simple Ada Program
663 @section Running a Simple Ada Program
666 Any text editor may be used to prepare an Ada program. If @code{Glide} is
667 used, the optional Ada mode may be helpful in laying out the program. The
668 program text is a normal text file. We will suppose in our initial
669 example that you have used your editor to prepare the following
670 standard format text file:
675 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
676 @b{procedure} Hello @b{is}
678 Put_Line ("Hello WORLD!");
685 This file should be named @file{hello.adb}.
686 With the normal default file naming conventions, GNAT requires
688 contain a single compilation unit whose file name is the
690 with periods replaced by hyphens; the
691 extension is @file{ads} for a
692 spec and @file{adb} for a body.
693 You can override this default file naming convention by use of the
694 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
695 Alternatively, if you want to rename your files according to this default
696 convention, which is probably more convenient if you will be using GNAT
697 for all your compilations, then the @code{gnatchop} utility
698 can be used to generate correctly-named source files
699 (@pxref{Renaming Files Using gnatchop}).
701 You can compile the program using the following command (@code{$} is used
702 as the command prompt in the examples in this document):
710 @code{gcc} is the command used to run the compiler. This compiler is
711 capable of compiling programs in several languages, including Ada 95 and
712 C. It assumes that you have given it an Ada program if the file extension is
713 either @file{.ads} or @file{.adb}, and it will then call the GNAT compiler to compile
716 The @option{-c} switch is required. It tells @command{gcc} to only do a
717 compilation. (For C programs, @command{gcc} can also do linking, but this
718 capability is not used directly for Ada programs, so the @option{-c}
719 switch must always be present.)
721 This compile command generates a file
722 @file{hello.o}, which is the object
723 file corresponding to your Ada program. It also generates an "Ada Library Information" file
725 which contains additional information used to check
726 that an Ada program is consistent.
727 To build an executable file,
728 use @code{gnatbind} to bind the program
729 and @code{gnatlink} to link it. The
730 argument to both @code{gnatbind} and @code{gnatlink} is the name of the
731 @file{ali} file, but the default extension of @file{.ali} can
732 be omitted. This means that in the most common case, the argument
733 is simply the name of the main program:
742 A simpler method of carrying out these steps is to use
744 a master program that invokes all the required
745 compilation, binding and linking tools in the correct order. In particular,
746 @command{gnatmake} automatically recompiles any sources that have been modified
747 since they were last compiled, or sources that depend
748 on such modified sources, so that "version skew" is avoided.
749 @cindex Version skew (avoided by @command{gnatmake})
757 The result is an executable program called @file{hello}, which can be
760 @c The following should be removed (BMB 2001-01-23)
770 assuming that the current directory is on the search path for executable programs.
773 and, if all has gone well, you will see
780 appear in response to this command.
785 @node Running a Program with Multiple Units
786 @section Running a Program with Multiple Units
789 Consider a slightly more complicated example that has three files: a
790 main program, and the spec and body of a package:
795 @b{package} Greetings @b{is}
797 @b{procedure} Goodbye;
800 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
801 @b{package} @b{body} Greetings @b{is}
802 @b{procedure} Hello @b{is}
804 Put_Line ("Hello WORLD!");
807 @b{procedure} Goodbye @b{is}
809 Put_Line ("Goodbye WORLD!");
816 @b{procedure} Gmain @b{is}
826 Following the one-unit-per-file rule, place this program in the
827 following three separate files:
831 spec of package @code{Greetings}
834 body of package @code{Greetings}
841 To build an executable version of
842 this program, we could use four separate steps to compile, bind, and link
843 the program, as follows:
847 $ gcc -c greetings.adb
854 Note that there is no required order of compilation when using GNAT.
855 In particular it is perfectly fine to compile the main program first.
856 Also, it is not necessary to compile package specs in the case where
857 there is an accompanying body; you only need to compile the body. If you want
858 to submit these files to the compiler for semantic checking and not code generation,
860 @option{-gnatc} switch:
863 $ gcc -c greetings.ads -gnatc
868 Although the compilation can be done in separate steps as in the
869 above example, in practice it is almost always more convenient
870 to use the @code{gnatmake} tool. All you need to know in this case
871 is the name of the main program's source file. The effect of the above four
872 commands can be achieved with a single one:
880 In the next section we discuss the advantages of using @code{gnatmake} in
883 @node Using the gnatmake Utility
884 @section Using the @command{gnatmake} Utility
887 If you work on a program by compiling single components at a time using
888 @code{gcc}, you typically keep track of the units you modify. In order to
889 build a consistent system, you compile not only these units, but also any
890 units that depend on the units you have modified.
891 For example, in the preceding case,
892 if you edit @file{gmain.adb}, you only need to recompile that file. But if
893 you edit @file{greetings.ads}, you must recompile both
894 @file{greetings.adb} and @file{gmain.adb}, because both files contain
895 units that depend on @file{greetings.ads}.
897 @code{gnatbind} will warn you if you forget one of these compilation
898 steps, so that it is impossible to generate an inconsistent program as a
899 result of forgetting to do a compilation. Nevertheless it is tedious and
900 error-prone to keep track of dependencies among units.
901 One approach to handle the dependency-bookkeeping is to use a
902 makefile. However, makefiles present maintenance problems of their own:
903 if the dependencies change as you change the program, you must make
904 sure that the makefile is kept up-to-date manually, which is also an
907 The @code{gnatmake} utility takes care of these details automatically.
908 Invoke it using either one of the following forms:
917 The argument is the name of the file containing the main program;
918 you may omit the extension. @code{gnatmake}
919 examines the environment, automatically recompiles any files that need
920 recompiling, and binds and links the resulting set of object files,
921 generating the executable file, @file{gmain}.
922 In a large program, it
923 can be extremely helpful to use @code{gnatmake}, because working out by hand
924 what needs to be recompiled can be difficult.
926 Note that @code{gnatmake}
927 takes into account all the Ada 95 rules that
928 establish dependencies among units. These include dependencies that result
929 from inlining subprogram bodies, and from
930 generic instantiation. Unlike some other
931 Ada make tools, @code{gnatmake} does not rely on the dependencies that were
932 found by the compiler on a previous compilation, which may possibly
933 be wrong when sources change. @code{gnatmake} determines the exact set of
934 dependencies from scratch each time it is run.
937 @node Introduction to Glide and GVD
938 @section Introduction to Glide and GVD
942 Although it is possible to develop programs using only the command line interface (@command{gnatmake}, etc.) a graphical Interactive Development Environment can make it easier for you to compose, navigate, and debug programs. This section describes the main features of Glide, the GNAT graphical IDE, and also shows how to use the basic commands in GVD, the GNU Visual Debugger. Additional information may be found in the on-line help for these tools.
945 * Building a New Program with Glide::
946 * Simple Debugging with GVD::
947 * Other Glide Features::
950 @node Building a New Program with Glide
951 @subsection Building a New Program with Glide
953 The simplest way to invoke Glide is to enter @command{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:
960 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
973 For this introductory example, you will need to create a new Ada source file. First, select the @code{Files} menu. This will pop open a menu with around a dozen or so items. To create a file, select the @code{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 @file{hello.adb} as the name of the file.
975 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 @code{Entities} item, and in place of @code{Glide} there is now an @code{Ada} item. Glide uses the file extension to identify the source language, so @file{adb} indicates an Ada source file.
977 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:
979 with Ada.Text_IO; use Ada.Text_IO;
985 Observe that Glide uses different colors to distinguish reserved words from identifiers. Also, after the @code{procedure Hello is} line, the cursor is automatically indented in anticipation of declarations. When you enter @code{begin}, Glide recognizes that there are no declarations and thus places @code{begin} flush left. But after the @code{begin} line the cursor is again indented, where the statement(s) will be placed.
987 The main part of the program will be a @code{for} loop. Instead of entering the text explicitly, however, use a statement template. Select the @code{Ada} item on the top menu bar, move the mouse to the @code{Statements} item, and you will see a large selection of alternatives. Choose @code{for loop}. You will be prompted (at the bottom of the buffer) for a loop name; simply press the @key{Enter} key since a loop name is not needed. You should see the beginning of a @code{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 @code{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 @code{1..5} and you will see this also appear in the source program, together with the remaining elements of the @code{for} loop syntax.
989 Next enter the statement (with an intentional error, a missing semicolon) that will form the body of the loop:
991 Put_Line("Hello, World" & Integer'Image(I))
995 Finally, type @code{end Hello;} as the last line in the program. Now save the file: choose the @code{File} menu item, and then the @code{Save buffer} selection. You will see a message at the bottom of the buffer confirming that the file has been saved.
997 You are now ready to attempt to build the program. Select the @code{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 @command{gnatmake}) since, if the compile is successful, we want to build an executable. Thus select @code{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.
999 Correct the error: type in a semicolon to terminate the statement. Although you can again save the file explicitly, you can also simply invoke @code{Ada} @result{} @code{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.
1001 To execute the program, choose @code{Ada} and then @code{Run}. You should see the program's output displayed in the bottom window:
1011 @node Simple Debugging with GVD
1012 @subsection Simple Debugging with GVD
1015 This section describes how to set breakpoints, examine/modify variables, and step through execution.
1017 In order to enable debugging, you need to pass the @option{-g} switch to both the compiler and to @command{gnatlink}. If you are using the command line, passing @option{-g} to @command{gnatmake} will have this effect. You can then launch GVD, e.g. on the @code{hello} program, by issuing the command:
1024 If you are using Glide, then @option{-g} is passed to the relevant tools by default when you do a build. Start the debugger by selecting the @code{Ada} menu item, and then @code{Debug}.
1026 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.
1028 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 @code{X} in a red circle. Clicking the circle toggles the breakpoint off, and the red circle is replaced by the green dot.
1030 For this example, set a breakpoint at the statement where @code{Put_Line} is invoked.
1032 Start program execution by selecting the @code{Run} button on the top menu bar. (The @code{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.
1034 You can examine the values of variables in several ways. Move the mouse over an occurrence of @code{Ind} in the @code{for} loop, and you will see the value (now @code{1}) displayed. Alternatively, right-click on @code{Ind} and select @code{Display Ind}; a box showing the variable's name and value will appear in the data canvas.
1036 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 @code{Ind}, and select the @code{Set Value of Ind} item. Enter @code{2} as the new value, and press @command{OK}. The box for @code{Ind} shows the update.
1038 Press the @code{Step} button on the top menu bar; this will step through one line of program text (the invocation of @code{Put_Line}), and you can observe the effect of having modified @code{Ind} since the value displayed is @code{2}.
1040 Remove the breakpoint, and resume execution by selecting the @code{Cont} button. You will see the remaining output lines displayed in the debugger interaction window, along with a message confirming normal program termination.
1043 @node Other Glide Features
1044 @subsection Other Glide Features
1047 You may have observed that some of the menu selections contain abbreviations; e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu. These are @emph{shortcut keys} that you can use instead of selecting menu items. The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead of selecting @code{Files} and then @code{Open file...}.
1049 To abort a Glide command, type @key{Ctrl-g}.
1051 If you want Glide to start with an existing source file, you can either launch Glide as above and then open the file via @code{Files} @result{} @code{Open file...}, or else simply pass the name of the source file on the command line:
1058 While you are using Glide, a number of @emph{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 @code{Buffers} menu and then selecting the desired entry.
1060 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 @code{Files} @result{} @code{One Window}.
1062 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:
1064 @item Select @code{Files} @result{} @code{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)
1065 @item With the focus in one of the windows, select the desired buffer from the @code{Buffers} menu
1069 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1071 @node The GNAT Compilation Model
1072 @chapter The GNAT Compilation Model
1073 @cindex GNAT compilation model
1074 @cindex Compilation model
1077 * Source Representation::
1078 * Foreign Language Representation::
1079 * File Naming Rules::
1080 * Using Other File Names::
1081 * Alternative File Naming Schemes::
1082 * Generating Object Files::
1083 * Source Dependencies::
1084 * The Ada Library Information Files::
1085 * Binding an Ada Program::
1086 * Mixed Language Programming::
1087 * Building Mixed Ada & C++ Programs::
1088 * Comparison between GNAT and C/C++ Compilation Models::
1089 * Comparison between GNAT and Conventional Ada Library Models::
1093 This chapter describes the compilation model used by GNAT. Although
1094 similar to that used by other languages, such as C and C++, this model
1095 is substantially different from the traditional Ada compilation models,
1096 which are based on a library. The model is initially described without
1097 reference to the library-based model. If you have not previously used an
1098 Ada compiler, you need only read the first part of this chapter. The
1099 last section describes and discusses the differences between the GNAT
1100 model and the traditional Ada compiler models. If you have used other
1101 Ada compilers, this section will help you to understand those
1102 differences, and the advantages of the GNAT model.
1104 @node Source Representation
1105 @section Source Representation
1109 Ada source programs are represented in standard text files, using
1110 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1111 7-bit ASCII set, plus additional characters used for
1112 representing foreign languages (@pxref{Foreign Language Representation}
1113 for support of non-USA character sets). The format effector characters
1114 are represented using their standard ASCII encodings, as follows:
1119 Vertical tab, @code{16#0B#}
1123 Horizontal tab, @code{16#09#}
1127 Carriage return, @code{16#0D#}
1131 Line feed, @code{16#0A#}
1135 Form feed, @code{16#0C#}
1139 Source files are in standard text file format. In addition, GNAT will
1140 recognize a wide variety of stream formats, in which the end of physical
1141 physical lines is marked by any of the following sequences:
1142 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1143 in accommodating files that are imported from other operating systems.
1145 @cindex End of source file
1146 @cindex Source file, end
1148 The end of a source file is normally represented by the physical end of
1149 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1150 recognized as signalling the end of the source file. Again, this is
1151 provided for compatibility with other operating systems where this
1152 code is used to represent the end of file.
1154 Each file contains a single Ada compilation unit, including any pragmas
1155 associated with the unit. For example, this means you must place a
1156 package declaration (a package @dfn{spec}) and the corresponding body in
1157 separate files. An Ada @dfn{compilation} (which is a sequence of
1158 compilation units) is represented using a sequence of files. Similarly,
1159 you will place each subunit or child unit in a separate file.
1161 @node Foreign Language Representation
1162 @section Foreign Language Representation
1165 GNAT supports the standard character sets defined in Ada 95 as well as
1166 several other non-standard character sets for use in localized versions
1167 of the compiler (@pxref{Character Set Control}).
1170 * Other 8-Bit Codes::
1171 * Wide Character Encodings::
1179 The basic character set is Latin-1. This character set is defined by ISO
1180 standard 8859, part 1. The lower half (character codes @code{16#00#}
1181 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half is
1182 used to represent additional characters. These include extended letters
1183 used by European languages, such as French accents, the vowels with umlauts
1184 used in German, and the extra letter A-ring used in Swedish.
1186 @findex Ada.Characters.Latin_1
1187 For a complete list of Latin-1 codes and their encodings, see the source
1188 file of library unit @code{Ada.Characters.Latin_1} in file
1189 @file{a-chlat1.ads}.
1190 You may use any of these extended characters freely in character or
1191 string literals. In addition, the extended characters that represent
1192 letters can be used in identifiers.
1194 @node Other 8-Bit Codes
1195 @subsection Other 8-Bit Codes
1198 GNAT also supports several other 8-bit coding schemes:
1203 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1208 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1213 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1219 Latin-4 letters (Cyrillic) allowed in identifiers, with uppercase and lowercase
1222 @item IBM PC (code page 437)
1223 @cindex code page 437
1224 This code page is the normal default for PCs in the U.S. It corresponds
1225 to the original IBM PC character set. This set has some, but not all, of
1226 the extended Latin-1 letters, but these letters do not have the same
1227 encoding as Latin-1. In this mode, these letters are allowed in
1228 identifiers with uppercase and lowercase equivalence.
1230 @item IBM PC (code page 850)
1231 @cindex code page 850
1232 This code page is a modification of 437 extended to include all the
1233 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1234 mode, all these letters are allowed in identifiers with uppercase and
1235 lowercase equivalence.
1237 @item Full Upper 8-bit
1238 Any character in the range 80-FF allowed in identifiers, and all are
1239 considered distinct. In other words, there are no uppercase and lowercase
1240 equivalences in this range. This is useful in conjunction with
1241 certain encoding schemes used for some foreign character sets (e.g.
1242 the typical method of representing Chinese characters on the PC).
1245 No upper-half characters in the range 80-FF are allowed in identifiers.
1246 This gives Ada 83 compatibility for identifier names.
1250 For precise data on the encodings permitted, and the uppercase and lowercase
1251 equivalences that are recognized, see the file @file{csets.adb} in
1252 the GNAT compiler sources. You will need to obtain a full source release
1253 of GNAT to obtain this file.
1255 @node Wide Character Encodings
1256 @subsection Wide Character Encodings
1259 GNAT allows wide character codes to appear in character and string
1260 literals, and also optionally in identifiers, by means of the following
1261 possible encoding schemes:
1266 In this encoding, a wide character is represented by the following five
1274 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1275 characters (using uppercase letters) of the wide character code. For
1276 example, ESC A345 is used to represent the wide character with code
1278 This scheme is compatible with use of the full Wide_Character set.
1280 @item Upper-Half Coding
1281 @cindex Upper-Half Coding
1282 The wide character with encoding @code{16#abcd#} where the upper bit is on (in
1283 other words, "a" is in the range 8-F) is represented as two bytes,
1284 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1285 character, but is not required to be in the upper half. This method can
1286 be also used for shift-JIS or EUC, where the internal coding matches the
1289 @item Shift JIS Coding
1290 @cindex Shift JIS Coding
1291 A wide character is represented by a two-character sequence,
1293 @code{16#cd#}, with the restrictions described for upper-half encoding as
1294 described above. The internal character code is the corresponding JIS
1295 character according to the standard algorithm for Shift-JIS
1296 conversion. Only characters defined in the JIS code set table can be
1297 used with this encoding method.
1301 A wide character is represented by a two-character sequence
1303 @code{16#cd#}, with both characters being in the upper half. The internal
1304 character code is the corresponding JIS character according to the EUC
1305 encoding algorithm. Only characters defined in the JIS code set table
1306 can be used with this encoding method.
1309 A wide character is represented using
1310 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1311 10646-1/Am.2. Depending on the character value, the representation
1312 is a one, two, or three byte sequence:
1317 16#0000#-16#007f#: 2#0xxxxxxx#
1318 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
1319 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1324 where the xxx bits correspond to the left-padded bits of the
1325 16-bit character value. Note that all lower half ASCII characters
1326 are represented as ASCII bytes and all upper half characters and
1327 other wide characters are represented as sequences of upper-half
1328 (The full UTF-8 scheme allows for encoding 31-bit characters as
1329 6-byte sequences, but in this implementation, all UTF-8 sequences
1330 of four or more bytes length will be treated as illegal).
1331 @item Brackets Coding
1332 In this encoding, a wide character is represented by the following eight
1340 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1341 characters (using uppercase letters) of the wide character code. For
1342 example, ["A345"] is used to represent the wide character with code
1343 @code{16#A345#}. It is also possible (though not required) to use the
1344 Brackets coding for upper half characters. For example, the code
1345 @code{16#A3#} can be represented as @code{["A3"]}.
1347 This scheme is compatible with use of the full Wide_Character set,
1348 and is also the method used for wide character encoding in the standard
1349 ACVC (Ada Compiler Validation Capability) test suite distributions.
1354 Note: Some of these coding schemes do not permit the full use of the
1355 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
1356 use of the upper half of the Latin-1 set.
1358 @node File Naming Rules
1359 @section File Naming Rules
1362 The default file name is determined by the name of the unit that the
1363 file contains. The name is formed by taking the full expanded name of
1364 the unit and replacing the separating dots with hyphens and using
1365 lowercase for all letters.
1367 An exception arises if the file name generated by the above rules starts
1368 with one of the characters
1370 and the second character is a
1371 minus. In this case, the character tilde is used in place
1372 of the minus. The reason for this special rule is to avoid clashes with
1373 the standard names for child units of the packages System, Ada,
1374 Interfaces, and GNAT, which use the prefixes
1378 The file extension is @file{.ads} for a spec and
1379 @file{.adb} for a body. The following list shows some
1380 examples of these rules.
1387 @item arith_functions.ads
1388 Arith_Functions (package spec)
1389 @item arith_functions.adb
1390 Arith_Functions (package body)
1392 Func.Spec (child package spec)
1394 Func.Spec (child package body)
1396 Sub (subunit of Main)
1398 A.Bad (child package body)
1402 Following these rules can result in excessively long
1403 file names if corresponding
1404 unit names are long (for example, if child units or subunits are
1405 heavily nested). An option is available to shorten such long file names
1406 (called file name "krunching"). This may be particularly useful when
1407 programs being developed with GNAT are to be used on operating systems
1408 with limited file name lengths. @xref{Using gnatkr}.
1410 Of course, no file shortening algorithm can guarantee uniqueness over
1411 all possible unit names; if file name krunching is used, it is your
1412 responsibility to ensure no name clashes occur. Alternatively you
1413 can specify the exact file names that you want used, as described
1414 in the next section. Finally, if your Ada programs are migrating from a
1415 compiler with a different naming convention, you can use the gnatchop
1416 utility to produce source files that follow the GNAT naming conventions.
1417 (For details @pxref{Renaming Files Using gnatchop}.)
1419 @node Using Other File Names
1420 @section Using Other File Names
1424 In the previous section, we have described the default rules used by
1425 GNAT to determine the file name in which a given unit resides. It is
1426 often convenient to follow these default rules, and if you follow them,
1427 the compiler knows without being explicitly told where to find all
1430 However, in some cases, particularly when a program is imported from
1431 another Ada compiler environment, it may be more convenient for the
1432 programmer to specify which file names contain which units. GNAT allows
1433 arbitrary file names to be used by means of the Source_File_Name pragma.
1434 The form of this pragma is as shown in the following examples:
1435 @cindex Source_File_Name pragma
1440 @b{pragma} Source_File_Name (My_Utilities.Stacks,
1441 Spec_File_Name => "myutilst_a.ada");
1442 @b{pragma} Source_File_name (My_Utilities.Stacks,
1443 Body_File_Name => "myutilst.ada");
1449 As shown in this example, the first argument for the pragma is the unit
1450 name (in this example a child unit). The second argument has the form
1451 of a named association. The identifier
1452 indicates whether the file name is for a spec or a body;
1453 the file name itself is given by a string literal.
1455 The source file name pragma is a configuration pragma, which means that
1456 normally it will be placed in the @file{gnat.adc}
1457 file used to hold configuration
1458 pragmas that apply to a complete compilation environment.
1459 For more details on how the @file{gnat.adc} file is created and used
1460 @pxref{Handling of Configuration Pragmas}
1461 @cindex @file{gnat.adc}
1463 GNAT allows completely arbitrary file names to be specified using the
1464 source file name pragma. However, if the file name specified has an
1465 extension other than @file{.ads} or @file{.adb} it is necessary to use a special
1466 syntax when compiling the file. The name in this case must be preceded
1467 by the special sequence @code{-x} followed by a space and the name of the
1468 language, here @code{ada}, as in:
1471 $ gcc -c -x ada peculiar_file_name.sim
1475 @code{gnatmake} handles non-standard file names in the usual manner (the
1476 non-standard file name for the main program is simply used as the
1477 argument to gnatmake). Note that if the extension is also non-standard,
1478 then it must be included in the gnatmake command, it may not be omitted.
1480 @node Alternative File Naming Schemes
1481 @section Alternative File Naming Schemes
1482 @cindex File naming schemes, alternative
1485 In the previous section, we described the use of the @code{Source_File_Name}
1486 pragma to allow arbitrary names to be assigned to individual source files.
1487 However, this approach requires one pragma for each file, and especially in
1488 large systems can result in very long @file{gnat.adc} files, and also create
1489 a maintenance problem.
1491 GNAT also provides a facility for specifying systematic file naming schemes
1492 other than the standard default naming scheme previously described. An
1493 alternative scheme for naming is specified by the use of
1494 @code{Source_File_Name} pragmas having the following format:
1495 @cindex Source_File_Name pragma
1498 pragma Source_File_Name (
1499 Spec_File_Name => FILE_NAME_PATTERN
1500 [,Casing => CASING_SPEC]
1501 [,Dot_Replacement => STRING_LITERAL]);
1503 pragma Source_File_Name (
1504 Body_File_Name => FILE_NAME_PATTERN
1505 [,Casing => CASING_SPEC]
1506 [,Dot_Replacement => STRING_LITERAL]);
1508 pragma Source_File_Name (
1509 Subunit_File_Name => FILE_NAME_PATTERN
1510 [,Casing => CASING_SPEC]
1511 [,Dot_Replacement => STRING_LITERAL]);
1513 FILE_NAME_PATTERN ::= STRING_LITERAL
1514 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1519 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1520 It contains a single asterisk character, and the unit name is substituted
1521 systematically for this asterisk. The optional parameter
1522 @code{Casing} indicates
1523 whether the unit name is to be all upper-case letters, all lower-case letters,
1524 or mixed-case. If no
1525 @code{Casing} parameter is used, then the default is all
1528 The optional @code{Dot_Replacement} string is used to replace any periods
1529 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1530 argument is used then separating dots appear unchanged in the resulting
1532 Although the above syntax indicates that the
1533 @code{Casing} argument must appear
1534 before the @code{Dot_Replacement} argument, but it
1535 is also permissible to write these arguments in the opposite order.
1537 As indicated, it is possible to specify different naming schemes for
1538 bodies, specs, and subunits. Quite often the rule for subunits is the
1539 same as the rule for bodies, in which case, there is no need to give
1540 a separate @code{Subunit_File_Name} rule, and in this case the
1541 @code{Body_File_name} rule is used for subunits as well.
1543 The separate rule for subunits can also be used to implement the rather
1544 unusual case of a compilation environment (e.g. a single directory) which
1545 contains a subunit and a child unit with the same unit name. Although
1546 both units cannot appear in the same partition, the Ada Reference Manual
1547 allows (but does not require) the possibility of the two units coexisting
1548 in the same environment.
1550 The file name translation works in the following steps:
1555 If there is a specific @code{Source_File_Name} pragma for the given unit,
1556 then this is always used, and any general pattern rules are ignored.
1559 If there is a pattern type @code{Source_File_Name} pragma that applies to
1560 the unit, then the resulting file name will be used if the file exists. If
1561 more than one pattern matches, the latest one will be tried first, and the
1562 first attempt resulting in a reference to a file that exists will be used.
1565 If no pattern type @code{Source_File_Name} pragma that applies to the unit
1566 for which the corresponding file exists, then the standard GNAT default
1567 naming rules are used.
1572 As an example of the use of this mechanism, consider a commonly used scheme
1573 in which file names are all lower case, with separating periods copied
1574 unchanged to the resulting file name, and specs end with ".1.ada", and
1575 bodies end with ".2.ada". GNAT will follow this scheme if the following
1579 pragma Source_File_Name
1580 (Spec_File_Name => "*.1.ada");
1581 pragma Source_File_Name
1582 (Body_File_Name => "*.2.ada");
1586 The default GNAT scheme is actually implemented by providing the following
1587 default pragmas internally:
1590 pragma Source_File_Name
1591 (Spec_File_Name => "*.ads", Dot_Replacement => "-");
1592 pragma Source_File_Name
1593 (Body_File_Name => "*.adb", Dot_Replacement => "-");
1597 Our final example implements a scheme typically used with one of the
1598 Ada 83 compilers, where the separator character for subunits was "__"
1599 (two underscores), specs were identified by adding @file{_.ADA}, bodies
1600 by adding @file{.ADA}, and subunits by
1601 adding @file{.SEP}. All file names were
1602 upper case. Child units were not present of course since this was an
1603 Ada 83 compiler, but it seems reasonable to extend this scheme to use
1604 the same double underscore separator for child units.
1607 pragma Source_File_Name
1608 (Spec_File_Name => "*_.ADA",
1609 Dot_Replacement => "__",
1610 Casing = Uppercase);
1611 pragma Source_File_Name
1612 (Body_File_Name => "*.ADA",
1613 Dot_Replacement => "__",
1614 Casing = Uppercase);
1615 pragma Source_File_Name
1616 (Subunit_File_Name => "*.SEP",
1617 Dot_Replacement => "__",
1618 Casing = Uppercase);
1621 @node Generating Object Files
1622 @section Generating Object Files
1625 An Ada program consists of a set of source files, and the first step in
1626 compiling the program is to generate the corresponding object files.
1627 These are generated by compiling a subset of these source files.
1628 The files you need to compile are the following:
1632 If a package spec has no body, compile the package spec to produce the
1633 object file for the package.
1636 If a package has both a spec and a body, compile the body to produce the
1637 object file for the package. The source file for the package spec need
1638 not be compiled in this case because there is only one object file, which
1639 contains the code for both the spec and body of the package.
1642 For a subprogram, compile the subprogram body to produce the object file
1643 for the subprogram. The spec, if one is present, is as usual in a
1644 separate file, and need not be compiled.
1648 In the case of subunits, only compile the parent unit. A single object
1649 file is generated for the entire subunit tree, which includes all the
1653 Compile child units independently of their parent units
1654 (though, of course, the spec of all the ancestor unit must be present in order
1655 to compile a child unit).
1659 Compile generic units in the same manner as any other units. The object
1660 files in this case are small dummy files that contain at most the
1661 flag used for elaboration checking. This is because GNAT always handles generic
1662 instantiation by means of macro expansion. However, it is still necessary to
1663 compile generic units, for dependency checking and elaboration purposes.
1667 The preceding rules describe the set of files that must be compiled to
1668 generate the object files for a program. Each object file has the same
1669 name as the corresponding source file, except that the extension is
1672 You may wish to compile other files for the purpose of checking their
1673 syntactic and semantic correctness. For example, in the case where a
1674 package has a separate spec and body, you would not normally compile the
1675 spec. However, it is convenient in practice to compile the spec to make
1676 sure it is error-free before compiling clients of this spec, because such
1677 compilations will fail if there is an error in the spec.
1679 GNAT provides an option for compiling such files purely for the
1680 purposes of checking correctness; such compilations are not required as
1681 part of the process of building a program. To compile a file in this
1682 checking mode, use the @option{-gnatc} switch.
1684 @node Source Dependencies
1685 @section Source Dependencies
1688 A given object file clearly depends on the source file which is compiled
1689 to produce it. Here we are using @dfn{depends} in the sense of a typical
1690 @code{make} utility; in other words, an object file depends on a source
1691 file if changes to the source file require the object file to be
1693 In addition to this basic dependency, a given object may depend on
1694 additional source files as follows:
1698 If a file being compiled @code{with}'s a unit @var{X}, the object file
1699 depends on the file containing the spec of unit @var{X}. This includes
1700 files that are @code{with}'ed implicitly either because they are parents
1701 of @code{with}'ed child units or they are run-time units required by the
1702 language constructs used in a particular unit.
1705 If a file being compiled instantiates a library level generic unit, the
1706 object file depends on both the spec and body files for this generic
1710 If a file being compiled instantiates a generic unit defined within a
1711 package, the object file depends on the body file for the package as
1712 well as the spec file.
1716 @cindex @option{-gnatn} switch
1717 If a file being compiled contains a call to a subprogram for which
1718 pragma @code{Inline} applies and inlining is activated with the
1719 @option{-gnatn} switch, the object file depends on the file containing the
1720 body of this subprogram as well as on the file containing the spec. Note
1721 that for inlining to actually occur as a result of the use of this switch,
1722 it is necessary to compile in optimizing mode.
1724 @cindex @option{-gnatN} switch
1725 The use of @option{-gnatN} activates a more extensive inlining optimization
1726 that is performed by the front end of the compiler. This inlining does
1727 not require that the code generation be optimized. Like @option{-gnatn},
1728 the use of this switch generates additional dependencies.
1731 If an object file O depends on the proper body of a subunit through inlining
1732 or instantiation, it depends on the parent unit of the subunit. This means that
1733 any modification of the parent unit or one of its subunits affects the
1737 The object file for a parent unit depends on all its subunit body files.
1740 The previous two rules meant that for purposes of computing dependencies and
1741 recompilation, a body and all its subunits are treated as an indivisible whole.
1744 These rules are applied transitively: if unit @code{A} @code{with}'s
1745 unit @code{B}, whose elaboration calls an inlined procedure in package
1746 @code{C}, the object file for unit @code{A} will depend on the body of
1747 @code{C}, in file @file{c.adb}.
1749 The set of dependent files described by these rules includes all the
1750 files on which the unit is semantically dependent, as described in the
1751 Ada 95 Language Reference Manual. However, it is a superset of what the
1752 ARM describes, because it includes generic, inline, and subunit dependencies.
1754 An object file must be recreated by recompiling the corresponding source
1755 file if any of the source files on which it depends are modified. For
1756 example, if the @code{make} utility is used to control compilation,
1757 the rule for an Ada object file must mention all the source files on
1758 which the object file depends, according to the above definition.
1759 The determination of the necessary
1760 recompilations is done automatically when one uses @code{gnatmake}.
1763 @node The Ada Library Information Files
1764 @section The Ada Library Information Files
1765 @cindex Ada Library Information files
1766 @cindex @file{ali} files
1769 Each compilation actually generates two output files. The first of these
1770 is the normal object file that has a @file{.o} extension. The second is a
1771 text file containing full dependency information. It has the same
1772 name as the source file, but an @file{.ali} extension.
1773 This file is known as the Ada Library Information (@file{ali}) file.
1774 The following information is contained in the @file{ali} file.
1778 Version information (indicates which version of GNAT was used to compile
1779 the unit(s) in question)
1782 Main program information (including priority and time slice settings,
1783 as well as the wide character encoding used during compilation).
1786 List of arguments used in the @code{gcc} command for the compilation
1789 Attributes of the unit, including configuration pragmas used, an indication
1790 of whether the compilation was successful, exception model used etc.
1793 A list of relevant restrictions applying to the unit (used for consistency)
1797 Categorization information (e.g. use of pragma @code{Pure}).
1800 Information on all @code{with}'ed units, including presence of
1801 @code{Elaborate} or @code{Elaborate_All} pragmas.
1804 Information from any @code{Linker_Options} pragmas used in the unit
1807 Information on the use of @code{Body_Version} or @code{Version}
1808 attributes in the unit.
1811 Dependency information. This is a list of files, together with
1812 time stamp and checksum information. These are files on which
1813 the unit depends in the sense that recompilation is required
1814 if any of these units are modified.
1817 Cross-reference data. Contains information on all entities referenced
1818 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
1819 provide cross-reference information.
1824 For a full detailed description of the format of the @file{ali} file,
1825 see the source of the body of unit @code{Lib.Writ}, contained in file
1826 @file{lib-writ.adb} in the GNAT compiler sources.
1828 @node Binding an Ada Program
1829 @section Binding an Ada Program
1832 When using languages such as C and C++, once the source files have been
1833 compiled the only remaining step in building an executable program
1834 is linking the object modules together. This means that it is possible to
1835 link an inconsistent version of a program, in which two units have
1836 included different versions of the same header.
1838 The rules of Ada do not permit such an inconsistent program to be built.
1839 For example, if two clients have different versions of the same package,
1840 it is illegal to build a program containing these two clients.
1841 These rules are enforced by the GNAT binder, which also determines an
1842 elaboration order consistent with the Ada rules.
1844 The GNAT binder is run after all the object files for a program have
1845 been created. It is given the name of the main program unit, and from
1846 this it determines the set of units required by the program, by reading the
1847 corresponding ALI files. It generates error messages if the program is
1848 inconsistent or if no valid order of elaboration exists.
1850 If no errors are detected, the binder produces a main program, in Ada by
1851 default, that contains calls to the elaboration procedures of those
1852 compilation unit that require them, followed by
1853 a call to the main program. This Ada program is compiled to generate the
1854 object file for the main program. The name of
1855 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
1856 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
1859 Finally, the linker is used to build the resulting executable program,
1860 using the object from the main program from the bind step as well as the
1861 object files for the Ada units of the program.
1863 @node Mixed Language Programming
1864 @section Mixed Language Programming
1865 @cindex Mixed Language Programming
1868 * Interfacing to C::
1869 * Calling Conventions::
1872 @node Interfacing to C
1873 @subsection Interfacing to C
1875 There are two ways to
1876 build a program that contains some Ada files and some other language
1877 files depending on whether the main program is in Ada or not.
1878 If the main program is in Ada, you should proceed as follows:
1882 Compile the other language files to generate object files. For instance:
1889 Compile the Ada units to produce a set of object files and ALI
1890 files. For instance:
1892 gnatmake -c my_main.adb
1896 Run the Ada binder on the Ada main program. For instance:
1898 gnatbind my_main.ali
1902 Link the Ada main program, the Ada objects and the other language
1903 objects. For instance:
1905 gnatlink my_main.ali file1.o file2.o
1909 The three last steps can be grouped in a single command:
1911 gnatmake my_main.adb -largs file1.o file2.o
1914 @cindex Binder output file
1916 If the main program is in some language other than Ada, you may
1917 have more than one entry point in the Ada subsystem. You must use a
1918 special option of the binder to generate callable routines to initialize
1919 and finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
1920 Calls to the initialization and finalization routines must be inserted in
1921 the main program, or some other appropriate point in the code. The call to
1922 initialize the Ada units must occur before the first Ada subprogram is
1923 called, and the call to finalize the Ada units must occur after the last
1924 Ada subprogram returns. You use the same procedure for building the
1925 program as described previously. In this case, however, the binder
1926 only places the initialization and finalization subprograms into file
1927 @file{b~@var{xxx}.adb} instead of the main program.
1928 So, if the main program is not in Ada, you should proceed as follows:
1932 Compile the other language files to generate object files. For instance:
1939 Compile the Ada units to produce a set of object files and ALI
1940 files. For instance:
1942 gnatmake -c entry_point1.adb
1943 gnatmake -c entry_point2.adb
1947 Run the Ada binder on the Ada main program. For instance:
1949 gnatbind -n entry_point1.ali entry_point2.ali
1953 Link the Ada main program, the Ada objects and the other language
1954 objects. You only need to give the last entry point here. For instance:
1956 gnatlink entry_point2.ali file1.o file2.o
1960 @node Calling Conventions
1961 @subsection Calling Conventions
1962 @cindex Foreign Languages
1963 @cindex Calling Conventions
1964 GNAT follows standard calling sequence conventions and will thus interface
1965 to any other language that also follows these conventions. The following
1966 Convention identifiers are recognized by GNAT:
1969 @cindex Interfacing to Ada
1970 @cindex Other Ada compilers
1971 @cindex Convention Ada
1973 Ada. This indicates that the standard Ada calling sequence will be
1974 used and all Ada data items may be passed without any limitations in the
1975 case where GNAT is used to generate both the caller and callee. It is also
1976 possible to mix GNAT generated code and code generated by another Ada
1977 compiler. In this case, the data types should be restricted to simple
1978 cases, including primitive types. Whether complex data types can be passed
1979 depends on the situation. Probably it is safe to pass simple arrays, such
1980 as arrays of integers or floats. Records may or may not work, depending
1981 on whether both compilers lay them out identically. Complex structures
1982 involving variant records, access parameters, tasks, or protected types,
1983 are unlikely to be able to be passed.
1985 Note that in the case of GNAT running
1986 on a platform that supports DEC Ada 83, a higher degree of compatibility
1987 can be guaranteed, and in particular records are layed out in an identical
1988 manner in the two compilers. Note also that if output from two different
1989 compilers is mixed, the program is responsible for dealing with elaboration
1990 issues. Probably the safest approach is to write the main program in the
1991 version of Ada other than GNAT, so that it takes care of its own elaboration
1992 requirements, and then call the GNAT-generated adainit procedure to ensure
1993 elaboration of the GNAT components. Consult the documentation of the other
1994 Ada compiler for further details on elaboration.
1996 However, it is not possible to mix the tasking run time of GNAT and
1997 DEC Ada 83, All the tasking operations must either be entirely within
1998 GNAT compiled sections of the program, or entirely within DEC Ada 83
1999 compiled sections of the program.
2001 @cindex Interfacing to Assembly
2002 @cindex Convention Assembler
2004 Assembler. Specifies assembler as the convention. In practice this has the
2005 same effect as convention Ada (but is not equivalent in the sense of being
2006 considered the same convention).
2008 @cindex Convention Asm
2011 Asm. Equivalent to Assembler.
2013 @cindex Convention Asm
2016 Asm. Equivalent to Assembly.
2018 @cindex Interfacing to COBOL
2019 @cindex Convention COBOL
2022 COBOL. Data will be passed according to the conventions described
2023 in section B.4 of the Ada 95 Reference Manual.
2026 @cindex Interfacing to C
2027 @cindex Convention C
2029 C. Data will be passed according to the conventions described
2030 in section B.3 of the Ada 95 Reference Manual.
2032 @cindex Convention Default
2035 Default. Equivalent to C.
2037 @cindex Convention External
2040 External. Equivalent to C.
2043 @cindex Interfacing to C++
2044 @cindex Convention C++
2046 CPP. This stands for C++. For most purposes this is identical to C.
2047 See the separate description of the specialized GNAT pragmas relating to
2048 C++ interfacing for further details.
2051 @cindex Interfacing to Fortran
2052 @cindex Convention Fortran
2054 Fortran. Data will be passed according to the conventions described
2055 in section B.5 of the Ada 95 Reference Manual.
2058 Intrinsic. This applies to an intrinsic operation, as defined in the Ada 95
2059 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
2060 this means that the body of the subprogram is provided by the compiler itself,
2061 usually by means of an efficient code sequence, and that the user does not
2062 supply an explicit body for it. In an application program, the pragma can only
2063 be applied to the following two sets of names, which the GNAT compiler
2067 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
2068 Arithmetic. The corresponding subprogram declaration must have
2069 two formal parameters. The
2070 first one must be a signed integer type or a modular type with a binary
2071 modulus, and the second parameter must be of type Natural.
2072 The return type must be the same as the type of the first argument. The size
2073 of this type can only be 8, 16, 32, or 64.
2074 @item binary arithmetic operators: "+", "-", "*", "/"
2075 The corresponding operator declaration must have parameters and result type
2076 that have the same root numeric type (for example, all three are long_float
2077 types). This simplifies the definition of operations that use type checking
2078 to perform dimensional checks:
2080 type Distance is new Long_Float;
2081 type Time is new Long_Float;
2082 type Velocity is new Long_Float;
2083 function "/" (D : Distance; T : Time)
2085 pragma Import (Intrinsic, "/");
2088 This common idiom is often programmed with a generic definition and an explicit
2089 body. The pragma makes it simpler to introduce such declarations. It incurs
2090 no overhead in compilation time or code size, because it is implemented as a
2091 single machine instruction.
2096 @cindex Convention Stdcall
2098 Stdcall. This is relevant only to NT/Win95 implementations of GNAT,
2099 and specifies that the Stdcall calling sequence will be used, as defined
2103 @cindex Convention DLL
2105 DLL. This is equivalent to Stdcall.
2108 @cindex Convention Win32
2110 Win32. This is equivalent to Stdcall.
2113 @cindex Convention Stubbed
2115 Stubbed. This is a special convention that indicates that the compiler
2116 should provide a stub body that raises @code{Program_Error}.
2120 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2121 that can be used to parametrize conventions and allow additional synonyms
2122 to be specified. For example if you have legacy code in which the convention
2123 identifier Fortran77 was used for Fortran, you can use the configuration
2127 pragma Convention_Identifier (Fortran77, Fortran);
2131 And from now on the identifier Fortran77 may be used as a convention
2132 identifier (for example in an @code{Import} pragma) with the same
2135 @node Building Mixed Ada & C++ Programs
2136 @section Building Mixed Ada & C++ Programs
2139 Building a mixed application containing both Ada and C++ code may be a
2140 challenge for the unaware programmer. As a matter of fact, this
2141 interfacing has not been standardized in the Ada 95 reference manual due
2142 to the immaturity and lack of standard of C++ at the time. This
2143 section gives a few hints that should make this task easier. In
2144 particular the first section addresses the differences with
2145 interfacing with C. The second section looks into the delicate problem
2146 of linking the complete application from its Ada and C++ parts. The last
2147 section give some hints on how the GNAT run time can be adapted in order
2148 to allow inter-language dispatching with a new C++ compiler.
2151 * Interfacing to C++::
2152 * Linking a Mixed C++ & Ada Program::
2153 * A Simple Example::
2154 * Adapting the Run Time to a New C++ Compiler::
2157 @node Interfacing to C++
2158 @subsection Interfacing to C++
2161 GNAT supports interfacing with C++ compilers generating code that is
2162 compatible with the standard Application Binary Interface of the given
2166 Interfacing can be done at 3 levels: simple data, subprograms and
2167 classes. In the first 2 cases, GNAT offer a specific @var{Convention
2168 CPP} that behaves exactly like @var{Convention C}. Usually C++ mangle
2169 names of subprograms and currently GNAT does not provide any help to
2170 solve the demangling problem. This problem can be addressed in 2 ways:
2173 by modifying the C++ code in order to force a C convention using
2174 the @var{extern "C"} syntax.
2177 by figuring out the mangled name and use it as the Link_Name argument of
2182 Interfacing at the class level can be achieved by using the GNAT specific
2183 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
2184 Reference Manual for additional information.
2186 @node Linking a Mixed C++ & Ada Program
2187 @subsection Linking a Mixed C++ & Ada Program
2190 Usually the linker of the C++ development system must be used to link
2191 mixed applications because most C++ systems will resolve elaboration
2192 issues (such as calling constructors on global class instances)
2193 transparently during the link phase. GNAT has been adapted to ease the
2194 use of a foreign linker for the last phase. Three cases can be
2199 Using GNAT and G++ (GNU C++ compiler) from the same GCC
2200 installation. The c++ linker can simply be called by using the c++
2201 specific driver called @code{c++}. Note that this setup is not
2202 very common because it may request recompiling the whole GCC
2203 tree from sources and it does not allow to upgrade easily to a new
2204 version of one compiler for one of the two languages without taking the
2205 risk of destabilizing the other.
2210 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
2214 Using GNAT and G++ from 2 different GCC installations. If both compilers
2215 are on the PATH, the same method can be used. It is important to be
2216 aware that environment variables such as C_INCLUDE_PATH,
2217 GCC_EXEC_PREFIX, BINUTILS_ROOT or GCC_ROOT will affect both compilers at
2218 the same time and thus may make one of the 2 compilers operate
2219 improperly if they are set for the other. In particular it is important
2220 that the link command has access to the proper gcc library @file{libgcc.a},
2221 that is to say the one that is part of the C++ compiler
2222 installation. The implicit link command as suggested in the gnatmake
2223 command from the former example can be replaced by an explicit link
2224 command with full verbosity in order to verify which library is used:
2227 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
2229 If there is a problem due to interfering environment variables, it can
2230 be workaround by using an intermediate script. The following example
2231 shows the proper script to use when GNAT has not been installed at its
2232 default location and g++ has been installed at its default location:
2235 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
2244 Using a non GNU C++ compiler. The same set of command as previously
2245 described can be used to insure that the c++ linker is
2246 used. Nonetheless, you need to add the path to libgcc explicitely, since some
2247 libraries needed by GNAT are located in this directory:
2251 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2254 CC $* `gcc -print-libgcc-file-name`
2258 Where CC is the name of the non GNU C++ compiler.
2262 @node A Simple Example
2263 @subsection A Simple Example
2265 The following example, provided as part of the GNAT examples, show how
2266 to achieve procedural interfacing between Ada and C++ in both
2267 directions. The C++ class A has 2 methods. The first method is exported
2268 to Ada by the means of an extern C wrapper function. The second method
2269 calls an Ada subprogram. On the Ada side, The C++ calls is modelized by
2270 a limited record with a layout comparable to the C++ class. The Ada
2271 subprogram, in turn, calls the c++ method. So from the C++ main program
2272 the code goes back and forth between the 2 languages.
2275 Here are the compilation commands
2276 for native configurations:
2278 $ gnatmake -c simple_cpp_interface
2281 $ gnatbind -n simple_cpp_interface
2282 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
2283 -lstdc++ ex7.o cpp_main.o
2286 Here are the corresponding sources:
2294 void adainit (void);
2295 void adafinal (void);
2296 void method1 (A *t);
2318 class A : public Origin @{
2320 void method1 (void);
2321 virtual void method2 (int v);
2331 extern "C" @{ void ada_method2 (A *t, int v);@}
2333 void A::method1 (void)
2336 printf ("in A::method1, a_value = %d \n",a_value);
2340 void A::method2 (int v)
2342 ada_method2 (this, v);
2343 printf ("in A::method2, a_value = %d \n",a_value);
2350 printf ("in A::A, a_value = %d \n",a_value);
2354 @b{package} @b{body} Simple_Cpp_Interface @b{is}
2356 @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
2360 @b{end} Ada_Method2;
2362 @b{end} Simple_Cpp_Interface;
2364 @b{package} Simple_Cpp_Interface @b{is}
2365 @b{type} A @b{is} @b{limited}
2370 @b{pragma} Convention (C, A);
2372 @b{procedure} Method1 (This : @b{in} @b{out} A);
2373 @b{pragma} Import (C, Method1);
2375 @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
2376 @b{pragma} Export (C, Ada_Method2);
2378 @b{end} Simple_Cpp_Interface;
2381 @node Adapting the Run Time to a New C++ Compiler
2382 @subsection Adapting the Run Time to a New C++ Compiler
2384 GNAT offers the capability to derive Ada 95 tagged types directly from
2385 preexisting C++ classes and . See "Interfacing with C++" in the GNAT
2386 reference manual. The mechanism used by GNAT for achieving such a goal
2387 has been made user configurable through a GNAT library unit
2388 @code{Interfaces.CPP}. The default version of this file is adapted to
2389 the GNU c++ compiler. Internal knowledge of the virtual
2390 table layout used by the new C++ compiler is needed to configure
2391 properly this unit. The Interface of this unit is known by the compiler
2392 and cannot be changed except for the value of the constants defining the
2393 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
2394 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
2395 of this unit for more details.
2397 @node Comparison between GNAT and C/C++ Compilation Models
2398 @section Comparison between GNAT and C/C++ Compilation Models
2401 The GNAT model of compilation is close to the C and C++ models. You can
2402 think of Ada specs as corresponding to header files in C. As in C, you
2403 don't need to compile specs; they are compiled when they are used. The
2404 Ada @code{with} is similar in effect to the @code{#include} of a C
2407 One notable difference is that, in Ada, you may compile specs separately
2408 to check them for semantic and syntactic accuracy. This is not always
2409 possible with C headers because they are fragments of programs that have
2410 less specific syntactic or semantic rules.
2412 The other major difference is the requirement for running the binder,
2413 which performs two important functions. First, it checks for
2414 consistency. In C or C++, the only defense against assembling
2415 inconsistent programs lies outside the compiler, in a makefile, for
2416 example. The binder satisfies the Ada requirement that it be impossible
2417 to construct an inconsistent program when the compiler is used in normal
2420 @cindex Elaboration order control
2421 The other important function of the binder is to deal with elaboration
2422 issues. There are also elaboration issues in C++ that are handled
2423 automatically. This automatic handling has the advantage of being
2424 simpler to use, but the C++ programmer has no control over elaboration.
2425 Where @code{gnatbind} might complain there was no valid order of
2426 elaboration, a C++ compiler would simply construct a program that
2427 malfunctioned at run time.
2429 @node Comparison between GNAT and Conventional Ada Library Models
2430 @section Comparison between GNAT and Conventional Ada Library Models
2433 This section is intended to be useful to Ada programmers who have
2434 previously used an Ada compiler implementing the traditional Ada library
2435 model, as described in the Ada 95 Language Reference Manual. If you
2436 have not used such a system, please go on to the next section.
2438 @cindex GNAT library
2439 In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
2440 source files themselves acts as the library. Compiling Ada programs does
2441 not generate any centralized information, but rather an object file and
2442 a ALI file, which are of interest only to the binder and linker.
2443 In a traditional system, the compiler reads information not only from
2444 the source file being compiled, but also from the centralized library.
2445 This means that the effect of a compilation depends on what has been
2446 previously compiled. In particular:
2450 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
2451 to the version of the unit most recently compiled into the library.
2454 Inlining is effective only if the necessary body has already been
2455 compiled into the library.
2458 Compiling a unit may obsolete other units in the library.
2462 In GNAT, compiling one unit never affects the compilation of any other
2463 units because the compiler reads only source files. Only changes to source
2464 files can affect the results of a compilation. In particular:
2468 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
2469 to the source version of the unit that is currently accessible to the
2474 Inlining requires the appropriate source files for the package or
2475 subprogram bodies to be available to the compiler. Inlining is always
2476 effective, independent of the order in which units are complied.
2479 Compiling a unit never affects any other compilations. The editing of
2480 sources may cause previous compilations to be out of date if they
2481 depended on the source file being modified.
2485 The most important result of these differences is that order of compilation
2486 is never significant in GNAT. There is no situation in which one is
2487 required to do one compilation before another. What shows up as order of
2488 compilation requirements in the traditional Ada library becomes, in
2489 GNAT, simple source dependencies; in other words, there is only a set
2490 of rules saying what source files must be present when a file is
2493 @node Compiling Using gcc
2494 @chapter Compiling Using @code{gcc}
2497 This chapter discusses how to compile Ada programs using the @code{gcc}
2498 command. It also describes the set of switches
2499 that can be used to control the behavior of the compiler.
2501 * Compiling Programs::
2502 * Switches for gcc::
2503 * Search Paths and the Run-Time Library (RTL)::
2504 * Order of Compilation Issues::
2508 @node Compiling Programs
2509 @section Compiling Programs
2512 The first step in creating an executable program is to compile the units
2513 of the program using the @code{gcc} command. You must compile the
2518 the body file (@file{.adb}) for a library level subprogram or generic
2522 the spec file (@file{.ads}) for a library level package or generic
2523 package that has no body
2526 the body file (@file{.adb}) for a library level package
2527 or generic package that has a body
2532 You need @emph{not} compile the following files
2537 the spec of a library unit which has a body
2544 because they are compiled as part of compiling related units. GNAT
2546 when the corresponding body is compiled, and subunits when the parent is
2548 @cindex No code generated
2549 If you attempt to compile any of these files, you will get one of the
2550 following error messages (where fff is the name of the file you compiled):
2553 No code generated for file @var{fff} (@var{package spec})
2554 No code generated for file @var{fff} (@var{subunit})
2558 The basic command for compiling a file containing an Ada unit is
2561 $ gcc -c [@var{switches}] @file{file name}
2565 where @var{file name} is the name of the Ada file (usually
2567 @file{.ads} for a spec or @file{.adb} for a body).
2569 @code{-c} switch to tell @code{gcc} to compile, but not link, the file.
2570 The result of a successful compilation is an object file, which has the
2571 same name as the source file but an extension of @file{.o} and an Ada
2572 Library Information (ALI) file, which also has the same name as the
2573 source file, but with @file{.ali} as the extension. GNAT creates these
2574 two output files in the current directory, but you may specify a source
2575 file in any directory using an absolute or relative path specification
2576 containing the directory information.
2579 @code{gcc} is actually a driver program that looks at the extensions of
2580 the file arguments and loads the appropriate compiler. For example, the
2581 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
2582 These programs are in directories known to the driver program (in some
2583 configurations via environment variables you set), but need not be in
2584 your path. The @code{gcc} driver also calls the assembler and any other
2585 utilities needed to complete the generation of the required object
2588 It is possible to supply several file names on the same @code{gcc}
2589 command. This causes @code{gcc} to call the appropriate compiler for
2590 each file. For example, the following command lists three separate
2591 files to be compiled:
2594 $ gcc -c x.adb y.adb z.c
2598 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
2599 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
2600 The compiler generates three object files @file{x.o}, @file{y.o} and
2601 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
2602 Ada compilations. Any switches apply to all the files listed,
2604 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
2606 @node Switches for gcc
2607 @section Switches for @code{gcc}
2610 The @code{gcc} command accepts switches that control the
2611 compilation process. These switches are fully described in this section.
2612 First we briefly list all the switches, in alphabetical order, then we
2613 describe the switches in more detail in functionally grouped sections.
2616 * Output and Error Message Control::
2617 * Debugging and Assertion Control::
2619 * Stack Overflow Checking::
2620 * Run-Time Control::
2621 * Validity Checking::
2623 * Using gcc for Syntax Checking::
2624 * Using gcc for Semantic Checking::
2625 * Compiling Ada 83 Programs::
2626 * Character Set Control::
2627 * File Naming Control::
2628 * Subprogram Inlining Control::
2629 * Auxiliary Output Control::
2630 * Debugging Control::
2631 * Units to Sources Mapping Files::
2635 @cindex @code{-b} (@code{gcc})
2636 @item -b @var{target}
2637 Compile your program to run on @var{target}, which is the name of a
2638 system configuration. You must have a GNAT cross-compiler built if
2639 @var{target} is not the same as your host system.
2642 @cindex @code{-B} (@code{gcc})
2643 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
2644 from @var{dir} instead of the default location. Only use this switch
2645 when multiple versions of the GNAT compiler are available. See the
2646 @code{gcc} manual page for further details. You would normally use the
2647 @code{-b} or @code{-V} switch instead.
2650 @cindex @code{-c} (@code{gcc})
2651 Compile. Always use this switch when compiling Ada programs.
2653 Note: for some other languages when using @code{gcc}, notably in
2654 the case of C and C++, it is possible to use
2655 use @code{gcc} without a @code{-c} switch to
2656 compile and link in one step. In the case of GNAT, you
2657 cannot use this approach, because the binder must be run
2658 and @code{gcc} cannot be used to run the GNAT binder.
2661 @cindex @code{-g} (@code{gcc})
2662 Generate debugging information. This information is stored in the object
2663 file and copied from there to the final executable file by the linker,
2664 where it can be read by the debugger. You must use the
2665 @code{-g} switch if you plan on using the debugger.
2668 @cindex @code{-I} (@code{gcc})
2670 Direct GNAT to search the @var{dir} directory for source files needed by
2671 the current compilation
2672 (@pxref{Search Paths and the Run-Time Library (RTL)}).
2675 @cindex @code{-I-} (@code{gcc})
2677 Except for the source file named in the command line, do not look for source files
2678 in the directory containing the source file named in the command line
2679 (@pxref{Search Paths and the Run-Time Library (RTL)}).
2682 @cindex @code{-o} (@code{gcc})
2683 This switch is used in @code{gcc} to redirect the generated object file
2684 and its associated ALI file. Beware of this switch with GNAT, because it may
2685 cause the object file and ALI file to have different names which in turn
2686 may confuse the binder and the linker.
2689 @cindex @code{-O} (@code{gcc})
2690 @var{n} controls the optimization level.
2694 No optimization, the default setting if no @code{-O} appears
2697 Normal optimization, the default if you specify @code{-O} without
2701 Extensive optimization
2704 Extensive optimization with automatic inlining. This applies only to
2705 inlining within a unit. For details on control of inter-unit inlining
2706 see @xref{Subprogram Inlining Control}.
2710 @item --RTS=@var{rts-path}
2711 @cindex @code{--RTS} (@code{gcc})
2712 Specifies the default location of the runtime library. Same meaning as the
2713 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
2716 @cindex @code{-S} (@code{gcc})
2717 Used in place of @code{-c} to
2718 cause the assembler source file to be
2719 generated, using @file{.s} as the extension,
2720 instead of the object file.
2721 This may be useful if you need to examine the generated assembly code.
2724 @cindex @code{-v} (@code{gcc})
2725 Show commands generated by the @code{gcc} driver. Normally used only for
2726 debugging purposes or if you need to be sure what version of the
2727 compiler you are executing.
2730 @cindex @code{-V} (@code{gcc})
2731 Execute @var{ver} version of the compiler. This is the @code{gcc}
2732 version, not the GNAT version.
2735 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
2739 Avoid processing @file{gnat.adc}. If a gnat.adc file is present, it will be ignored.
2742 Generate brief messages to @file{stderr} even if verbose mode set.
2745 Check syntax and semantics only (no code generation attempted).
2748 Compress debug information and external symbol name table entries.
2751 Output expanded source files for source level debugging. This switch
2752 also suppress generation of cross-reference information (see -gnatx).
2754 @item -gnatec@var{path}
2755 Specify a configuration pragma file. (see @ref{The Configuration Pragmas Files})
2757 @item -gnatem@var{path}
2758 Specify a mapping file. (see @ref{Units to Sources Mapping Files})
2761 Full dynamic elaboration checks.
2764 Full errors. Multiple errors per line, all undefined references.
2767 Externals names are folded to all uppercase.
2770 Internal GNAT implementation mode. This should not be used for
2771 applications programs, it is intended only for use by the compiler
2772 and its run-time library. For documentation, see the GNAT sources.
2775 List generated expanded code in source form.
2778 Identifier character set
2779 (@var{c}=1/2/3/4/8/9/p/f/n/w).
2782 Output usage information. The output is written to @file{stdout}.
2785 Limit file names to @var{n} (1-999) characters (@code{k} = krunch).
2788 Output full source listing with embedded error messages.
2791 Limit number of detected errors to @var{n} (1-999).
2794 Activate inlining across unit boundaries for subprograms for which
2795 pragma @code{inline} is specified.
2798 Activate front end inlining.
2801 Suppresses all inlining, even if other optimization or inlining switches
2805 Activates stack checking. See separate section on stack checking for
2806 details of the use of this option.
2809 Enable numeric overflow checking (which is not normally enabled by
2810 default). Not that division by zero is a separate check that is not
2811 controlled by this switch (division by zero checking is on by default).
2814 Suppress all checks.
2817 Don't quit; try semantics, even if parse errors.
2820 Don't quit; generate @file{ali} and tree files even if illegalities.
2823 Enable polling. This is required on some systems (notably Windows NT) to
2824 obtain asynchronous abort and asynchronous transfer of control capability.
2825 See the description of pragma Polling in the GNAT Reference Manual for
2828 @item -gnatR[0/1/2/3][s]
2829 Output representation information for declared types and objects.
2835 Tree output file to be generated.
2838 Set time slice to specified number of microseconds
2841 List units for this compilation.
2844 Tag all error messages with the unique string "error:"
2847 Verbose mode. Full error output with source lines to @file{stdout}.
2850 Control level of validity checking. See separate section describing
2853 @item -gnatwxxx@var{xxx}
2855 @var{xxx} is a string of options describing the exact warnings that
2856 are enabled or disabled. See separate section on warning control.
2859 Wide character encoding method
2860 (@var{e}=n/h/u/s/e/8).
2863 Suppress generation of cross-reference information.
2866 Enable built-in style checks. See separate section describing this feature.
2869 Distribution stub generation and compilation
2870 (@var{m}=r/c for receiver/caller stubs).
2873 Enforce Ada 83 restrictions.
2875 @item -pass-exit-codes
2876 Catch exit codes from the compiler and use the most meaningful as
2880 You may combine a sequence of GNAT switches into a single switch. For
2881 example, the combined switch
2883 @cindex Combining GNAT switches
2889 is equivalent to specifying the following sequence of switches:
2892 -gnato -gnatf -gnati3
2896 The following restrictions apply to the combination of switches
2901 The switch @option{-gnatc} if combined with other switches must come
2902 first in the string.
2905 The switch @option{-gnats} if combined with other switches must come
2906 first in the string.
2909 Once a "y" appears in the string (that is a use of the @option{-gnaty}
2910 switch), then all further characters in the switch are interpreted
2911 as style modifiers (see description of @option{-gnaty}).
2914 Once a "d" appears in the string (that is a use of the @option{-gnatd}
2915 switch), then all further characters in the switch are interpreted
2916 as debug flags (see description of @option{-gnatd}).
2919 Once a "w" appears in the string (that is a use of the @option{-gnatw}
2920 switch), then all further characters in the switch are interpreted
2921 as warning mode modifiers (see description of @option{-gnatw}).
2924 Once a "V" appears in the string (that is a use of the @option{-gnatV}
2925 switch), then all further characters in the switch are interpreted
2926 as validity checking options (see description of @option{-gnatV}).
2930 @node Output and Error Message Control
2931 @subsection Output and Error Message Control
2935 The standard default format for error messages is called "brief format."
2936 Brief format messages are written to @file{stderr} (the standard error
2937 file) and have the following form:
2943 e.adb:3:04: Incorrect spelling of keyword "function"
2944 e.adb:4:20: ";" should be "is"
2948 The first integer after the file name is the line number in the file,
2949 and the second integer is the column number within the line.
2950 @code{glide} can parse the error messages
2951 and point to the referenced character.
2952 The following switches provide control over the error message
2957 @cindex @option{-gnatv} (@code{gcc})
2959 The v stands for verbose.
2960 The effect of this setting is to write long-format error
2961 messages to @file{stdout} (the standard output file.
2962 The same program compiled with the
2963 @option{-gnatv} switch would generate:
2968 3. funcion X (Q : Integer)
2970 >>> Incorrect spelling of keyword "function"
2973 >>> ";" should be "is"
2979 The vertical bar indicates the location of the error, and the @samp{>>>}
2980 prefix can be used to search for error messages. When this switch is
2981 used the only source lines output are those with errors.
2984 @cindex @option{-gnatl} (@code{gcc})
2985 The @code{l} stands for list.
2986 This switch causes a full listing of
2987 the file to be generated. The output might look as follows:
2994 3. funcion X (Q : Integer)
2996 >>> Incorrect spelling of keyword "function"
2999 >>> ";" should be "is"
3012 When you specify the @option{-gnatv} or @option{-gnatl} switches and
3013 standard output is redirected, a brief summary is written to
3014 @file{stderr} (standard error) giving the number of error messages and
3015 warning messages generated.
3018 @cindex @option{-gnatU} (@code{gcc})
3019 This switch forces all error messages to be preceded by the unique
3020 string "error:". This means that error messages take a few more
3021 characters in space, but allows easy searching for and identification
3025 @cindex @option{-gnatb} (@code{gcc})
3026 The @code{b} stands for brief.
3027 This switch causes GNAT to generate the
3028 brief format error messages to @file{stderr} (the standard error
3029 file) as well as the verbose
3030 format message or full listing (which as usual is written to
3031 @file{stdout} (the standard output file).
3034 @cindex @option{-gnatm} (@code{gcc})
3035 The @code{m} stands for maximum.
3036 @var{n} is a decimal integer in the
3037 range of 1 to 999 and limits the number of error messages to be
3038 generated. For example, using @option{-gnatm2} might yield
3044 e.adb:3:04: Incorrect spelling of keyword "function"
3045 e.adb:5:35: missing ".."
3046 fatal error: maximum errors reached
3047 compilation abandoned
3051 @cindex @option{-gnatf} (@code{gcc})
3052 @cindex Error messages, suppressing
3053 The @code{f} stands for full.
3054 Normally, the compiler suppresses error messages that are likely to be
3055 redundant. This switch causes all error
3056 messages to be generated. In particular, in the case of
3057 references to undefined variables. If a given variable is referenced
3058 several times, the normal format of messages is
3063 e.adb:7:07: "V" is undefined (more references follow)
3067 where the parenthetical comment warns that there are additional
3068 references to the variable @code{V}. Compiling the same program with the
3069 @option{-gnatf} switch yields
3072 e.adb:7:07: "V" is undefined
3073 e.adb:8:07: "V" is undefined
3074 e.adb:8:12: "V" is undefined
3075 e.adb:8:16: "V" is undefined
3076 e.adb:9:07: "V" is undefined
3077 e.adb:9:12: "V" is undefined
3081 @cindex @option{-gnatq} (@code{gcc})
3082 The @code{q} stands for quit (really "don't quit").
3083 In normal operation mode, the compiler first parses the program and
3084 determines if there are any syntax errors. If there are, appropriate
3085 error messages are generated and compilation is immediately terminated.
3087 GNAT to continue with semantic analysis even if syntax errors have been
3088 found. This may enable the detection of more errors in a single run. On
3089 the other hand, the semantic analyzer is more likely to encounter some
3090 internal fatal error when given a syntactically invalid tree.
3093 In normal operation mode, the @file{ali} file is not generated if any
3094 illegalities are detected in the program. The use of @option{-gnatQ} forces
3095 generation of the @file{ali} file. This file is marked as being in
3096 error, so it cannot be used for binding purposes, but it does contain
3097 reasonably complete cross-reference information, and thus may be useful
3098 for use by tools (e.g. semantic browsing tools or integrated development
3099 environments) that are driven from the @file{ali} file.
3101 In addition, if @option{-gnatt} is also specified, then the tree file is
3102 generated even if there are illegalities. It may be useful in this case
3103 to also specify @option{-gnatq} to ensure that full semantic processing
3104 occurs. The resulting tree file can be processed by ASIS, for the purpose
3105 of providing partial information about illegal units, but if the error
3106 causes the tree to be badly malformed, then ASIS may crash during the
3112 In addition to error messages, which correspond to illegalities as defined
3113 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
3116 @cindex Warning messages
3117 First, the compiler considers some constructs suspicious and generates a
3118 warning message to alert you to a possible error. Second, if the
3119 compiler detects a situation that is sure to raise an exception at
3120 run time, it generates a warning message. The following shows an example
3121 of warning messages:
3126 e.adb:4:24: warning: creation of object may raise Storage_Error
3127 e.adb:10:17: warning: static value out of range
3128 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
3133 GNAT considers a large number of situations as appropriate
3134 for the generation of warning messages. As always, warnings are not
3135 definite indications of errors. For example, if you do an out-of-range
3136 assignment with the deliberate intention of raising a
3137 @code{Constraint_Error} exception, then the warning that may be
3138 issued does not indicate an error. Some of the situations for which GNAT
3139 issues warnings (at least some of the time) are given in the following
3140 list, which is not necessarily complete.
3144 Possible infinitely recursive calls
3147 Out-of-range values being assigned
3150 Possible order of elaboration problems
3156 Fixed-point type declarations with a null range
3159 Variables that are never assigned a value
3162 Variables that are referenced before being initialized
3165 Task entries with no corresponding accept statement
3168 Duplicate accepts for the same task entry in a select
3171 Objects that take too much storage
3174 Unchecked conversion between types of differing sizes
3177 Missing return statements along some execution paths in a function
3180 Incorrect (unrecognized) pragmas
3183 Incorrect external names
3186 Allocation from empty storage pool
3189 Potentially blocking operations in protected types
3192 Suspicious parenthesization of expressions
3195 Mismatching bounds in an aggregate
3198 Attempt to return local value by reference
3201 Unrecognized pragmas
3204 Premature instantiation of a generic body
3207 Attempt to pack aliased components
3210 Out of bounds array subscripts
3213 Wrong length on string assignment
3216 Violations of style rules if style checking is enabled
3222 Bit_Order usage that does not have any effect
3225 Compile time biased rounding of floating-point constant
3228 Standard.Duration used to resolve universal fixed expression
3231 Dereference of possibly null value
3234 Declaration that is likely to cause storage error
3237 Internal GNAT unit with'ed by application unit
3240 Values known to be out of range at compile time
3243 Unreferenced labels and variables
3246 Address overlays that could clobber memory
3249 Unexpected initialization when address clause present
3252 Bad alignment for address clause
3255 Useless type conversions
3258 Redundant assignment statements
3261 Accidental hiding of name by child unit
3267 Access before elaboration detected at compile time
3270 A range in a @code{for} loop that is known to be null or might be null
3275 The following switches are available to control the handling of
3279 @item -gnatwa (activate all optional errors)
3280 @cindex @option{-gnatwa} (@code{gcc})
3281 This switch activates most optional warning messages, see remaining list
3282 in this section for details on optional warning messages that can be
3283 individually controlled. The warnings that are not turned on by this
3284 switch are @option{-gnatwb} (biased rounding),
3285 @option{-gnatwd} (implicit dereferencing),
3286 and @option{-gnatwh} (hiding). All other optional warnings are
3289 @item -gnatwA (suppress all optional errors)
3290 @cindex @option{-gnatwA} (@code{gcc})
3291 This switch suppresses all optional warning messages, see remaining list
3292 in this section for details on optional warning messages that can be
3293 individually controlled.
3295 @item -gnatwb (activate warnings on biased rounding)
3296 @cindex @option{-gnatwb} (@code{gcc})
3297 @cindex Rounding, biased
3298 @cindex Biased rounding
3299 If a static floating-point expression has a value that is exactly half
3300 way between two adjacent machine numbers, then the rules of Ada
3301 (Ada Reference Manual, section 4.9(38)) require that this rounding
3302 be done away from zero, even if the normal unbiased rounding rules
3303 at run time would require rounding towards zero. This warning message
3304 alerts you to such instances where compile-time rounding and run-time
3305 rounding are not equivalent. If it is important to get proper run-time
3306 rounding, then you can force this by making one of the operands into
3307 a variable. The default is that such warnings are not generated.
3308 Note that @option{-gnatwa} does not affect the setting of
3309 this warning option.
3311 @item -gnatwB (suppress warnings on biased rounding)
3312 @cindex @option{-gnatwB} (@code{gcc})
3313 This switch disables warnings on biased rounding.
3315 @item -gnatwc (activate warnings on conditionals)
3316 @cindex @option{-gnatwc} (@code{gcc})
3317 @cindex Conditionals, constant
3318 This switch activates warnings for conditional expressions used in
3319 tests that are known to be True or False at compile time. The default
3320 is that such warnings are not generated.
3321 This warning can also be turned on using @option{-gnatwa}.
3323 @item -gnatwC (suppress warnings on conditionals)
3324 @cindex @option{-gnatwC} (@code{gcc})
3325 This switch suppresses warnings for conditional expressions used in
3326 tests that are known to be True or False at compile time.
3328 @item -gnatwd (activate warnings on implicit dereferencing)
3329 @cindex @option{-gnatwd} (@code{gcc})
3330 If this switch is set, then the use of a prefix of an access type
3331 in an indexed component, slice, or selected component without an
3332 explicit @code{.all} will generate a warning. With this warning
3333 enabled, access checks occur only at points where an explicit
3334 @code{.all} appears in the source code (assuming no warnings are
3335 generated as a result of this switch). The default is that such
3336 warnings are not generated.
3337 Note that @option{-gnatwa} does not affect the setting of
3338 this warning option.
3340 @item -gnatwD (suppress warnings on implicit dereferencing)
3341 @cindex @option{-gnatwD} (@code{gcc})
3342 @cindex Implicit dereferencing
3343 @cindex Dereferencing, implicit
3344 This switch suppresses warnings for implicit deferences in
3345 indexed components, slices, and selected components.
3347 @item -gnatwe (treat warnings as errors)
3348 @cindex @option{-gnatwe} (@code{gcc})
3349 @cindex Warnings, treat as error
3350 This switch causes warning messages to be treated as errors.
3351 The warning string still appears, but the warning messages are counted
3352 as errors, and prevent the generation of an object file.
3354 @item -gnatwf (activate warnings on unreferenced formals)
3355 @cindex @option{-gnatwf} (@code{gcc})
3356 @cindex Formals, unreferenced
3357 This switch causes a warning to be generated if a formal parameter
3358 is not referenced in the body of the subprogram. This warning can
3359 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
3361 @item -gnatwF (suppress warnings on unreferenced formals)
3362 @cindex @option{-gnatwF} (@code{gcc})
3363 This switch suppresses warnings for unreferenced formal
3364 parameters. Note that the
3365 combination @option{-gnatwu} followed by @option{-gnatwF} has the
3366 effect of warning on unreferenced entities other than subprogram
3369 @item -gnatwh (activate warnings on hiding)
3370 @cindex @option{-gnatwh} (@code{gcc})
3371 @cindex Hiding of Declarations
3372 This switch activates warnings on hiding declarations.
3373 A declaration is considered hiding
3374 if it is for a non-overloadable entity, and it declares an entity with the
3375 same name as some other entity that is directly or use-visible. The default
3376 is that such warnings are not generated.
3377 Note that @option{-gnatwa} does not affect the setting of this warning option.
3379 @item -gnatwH (suppress warnings on hiding)
3380 @cindex @option{-gnatwH} (@code{gcc})
3381 This switch suppresses warnings on hiding declarations.
3383 @item -gnatwi (activate warnings on implementation units).
3384 @cindex @option{-gnatwi} (@code{gcc})
3385 This switch activates warnings for a @code{with} of an internal GNAT
3386 implementation unit, defined as any unit from the @code{Ada},
3387 @code{Interfaces}, @code{GNAT},
3389 hierarchies that is not
3390 documented in either the Ada Reference Manual or the GNAT
3391 Programmer's Reference Manual. Such units are intended only
3392 for internal implementation purposes and should not be @code{with}'ed
3393 by user programs. The default is that such warnings are generated
3394 This warning can also be turned on using @option{-gnatwa}.
3396 @item -gnatwI (disable warnings on implementation units).
3397 @cindex @option{-gnatwI} (@code{gcc})
3398 This switch disables warnings for a @code{with} of an internal GNAT
3399 implementation unit.
3401 @item -gnatwl (activate warnings on elaboration pragmas)
3402 @cindex @option{-gnatwl} (@code{gcc})
3403 @cindex Elaboration, warnings
3404 This switch activates warnings on missing pragma Elaborate_All statements.
3405 See the section in this guide on elaboration checking for details on
3406 when such pragma should be used. The default is that such warnings
3408 This warning can also be turned on using @option{-gnatwa}.
3410 @item -gnatwL (suppress warnings on elaboration pragmas)
3411 @cindex @option{-gnatwL} (@code{gcc})
3412 This switch suppresses warnings on missing pragma Elaborate_All statements.
3413 See the section in this guide on elaboration checking for details on
3414 when such pragma should be used.
3416 @item -gnatwo (activate warnings on address clause overlays)
3417 @cindex @option{-gnatwo} (@code{gcc})
3418 @cindex Address Clauses, warnings
3419 This switch activates warnings for possibly unintended initialization
3420 effects of defining address clauses that cause one variable to overlap
3421 another. The default is that such warnings are generated.
3422 This warning can also be turned on using @option{-gnatwa}.
3424 @item -gnatwO (suppress warnings on address clause overlays)
3425 @cindex @option{-gnatwO} (@code{gcc})
3426 This switch suppresses warnings on possibly unintended initialization
3427 effects of defining address clauses that cause one variable to overlap
3430 @item -gnatwp (activate warnings on ineffective pragma Inlines)
3431 @cindex @option{-gnatwp} (@code{gcc})
3432 @cindex Inlining, warnings
3433 This switch activates warnings for failure of front end inlining
3434 (activated by @option{-gnatN}) to inline a particular call. There are
3435 many reasons for not being able to inline a call, including most
3436 commonly that the call is too complex to inline.
3437 This warning can also be turned on using @option{-gnatwa}.
3439 @item -gnatwP (suppress warnings on ineffective pragma Inlines)
3440 @cindex @option{-gnatwP} (@code{gcc})
3441 This switch suppresses warnings on ineffective pragma Inlines. If the
3442 inlining mechanism cannot inline a call, it will simply ignore the
3445 @item -gnatwr (activate warnings on redundant constructs)
3446 @cindex @option{-gnatwr} (@code{gcc})
3447 This switch activates warnings for redundant constructs. The following
3448 is the current list of constructs regarded as redundant:
3449 This warning can also be turned on using @option{-gnatwa}.
3453 Assignment of an item to itself.
3455 Type conversion that converts an expression to its own type.
3457 Use of the attribute @code{Base} where @code{typ'Base} is the same
3460 Use of pragma @code{Pack} when all components are placed by a record
3461 representation clause.
3464 @item -gnatwR (suppress warnings on redundant constructs)
3465 @cindex @option{-gnatwR} (@code{gcc})
3466 This switch suppresses warnings for redundant constructs.
3468 @item -gnatws (suppress all warnings)
3469 @cindex @option{-gnatws} (@code{gcc})
3470 This switch completely suppresses the
3471 output of all warning messages from the GNAT front end.
3472 Note that it does not suppress warnings from the @code{gcc} back end.
3473 To suppress these back end warnings as well, use the switch @code{-w}
3474 in addition to @option{-gnatws}.
3476 @item -gnatwu (activate warnings on unused entities)
3477 @cindex @option{-gnatwu} (@code{gcc})
3478 This switch activates warnings to be generated for entities that
3479 are defined but not referenced, and for units that are @code{with}'ed
3481 referenced. In the case of packages, a warning is also generated if
3482 no entities in the package are referenced. This means that if the package
3483 is referenced but the only references are in @code{use}
3484 clauses or @code{renames}
3485 declarations, a warning is still generated. A warning is also generated
3486 for a generic package that is @code{with}'ed but never instantiated.
3487 In the case where a package or subprogram body is compiled, and there
3488 is a @code{with} on the corresponding spec
3489 that is only referenced in the body,
3490 a warning is also generated, noting that the
3491 @code{with} can be moved to the body. The default is that
3492 such warnings are not generated.
3493 This switch also activates warnings on unreferenced formals
3494 (it is includes the effect of @option{-gnatwf}).
3495 This warning can also be turned on using @option{-gnatwa}.
3497 @item -gnatwU (suppress warnings on unused entities)
3498 @cindex @option{-gnatwU} (@code{gcc})
3499 This switch suppresses warnings for unused entities and packages.
3500 It also turns off warnings on unreferenced formals (and thus includes
3501 the effect of @option{-gnatwF}).
3504 A string of warning parameters can be used in the same parameter. For example:
3511 Would turn on all optional warnings except for elaboration pragma warnings,
3512 and also specify that warnings should be treated as errors.
3516 This switch suppresses warnings from the @code{gcc} backend. It may be
3517 used in conjunction with @option{-gnatws} to ensure that all warnings
3518 are suppressed during the entire compilation process.
3522 @node Debugging and Assertion Control
3523 @subsection Debugging and Assertion Control
3527 @cindex @option{-gnata} (@code{gcc})
3533 The pragmas @code{Assert} and @code{Debug} normally have no effect and
3534 are ignored. This switch, where @samp{a} stands for assert, causes
3535 @code{Assert} and @code{Debug} pragmas to be activated.
3537 The pragmas have the form:
3542 @b{pragma} Assert (@var{Boolean-expression} [,
3543 @var{static-string-expression}])
3544 @b{pragma} Debug (@var{procedure call})
3550 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
3551 If the result is @code{True}, the pragma has no effect (other than
3552 possible side effects from evaluating the expression). If the result is
3553 @code{False}, the exception @code{Assert_Failure} declared in the package
3554 @code{System.Assertions} is
3555 raised (passing @var{static-string-expression}, if present, as the
3556 message associated with the exception). If no string expression is
3557 given the default is a string giving the file name and line number
3560 The @code{Debug} pragma causes @var{procedure} to be called. Note that
3561 @code{pragma Debug} may appear within a declaration sequence, allowing
3562 debugging procedures to be called between declarations.
3566 @node Validity Checking
3567 @subsection Validity Checking
3568 @findex Validity Checking
3571 The Ada 95 Reference Manual has specific requirements for checking
3572 for invalid values. In particular, RM 13.9.1 requires that the
3573 evaluation of invalid values (for example from unchecked conversions),
3574 not result in erroneous execution. In GNAT, the result of such an
3575 evaluation in normal default mode is to either use the value
3576 unmodified, or to raise Constraint_Error in those cases where use
3577 of the unmodified value would cause erroneous execution. The cases
3578 where unmodified values might lead to erroneous execution are case
3579 statements (where a wild jump might result from an invalid value),
3580 and subscripts on the left hand side (where memory corruption could
3581 occur as a result of an invalid value).
3583 The @option{-gnatVx} switch allows more control over the validity checking
3584 mode. The @code{x} argument here is a string of letters which control which
3585 validity checks are performed in addition to the default checks described
3590 @option{-gnatVc} Validity checks for copies
3592 The right hand side of assignments, and the initializing values of
3593 object declarations are validity checked.
3596 @option{-gnatVd} Default (RM) validity checks
3598 Some validity checks are done by default following normal Ada semantics
3600 A check is done in case statements that the expression is within the range
3601 of the subtype. If it is not, Constraint_Error is raised.
3602 For assignments to array components, a check is done that the expression used
3603 as index is within the range. If it is not, Constraint_Error is raised.
3604 Both these validity checks may be turned off using switch @option{-gnatVD}.
3605 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
3606 switch @option{-gnatVd} will leave the checks turned on.
3607 Switch @option{-gnatVD} should be used only if you are sure that all such
3608 expressions have valid values. If you use this switch and invalid values
3609 are present, then the program is erroneous, and wild jumps or memory
3610 overwriting may occur.
3613 @option{-gnatVi} Validity checks for @code{in} mode parameters
3615 Arguments for parameters of mode @code{in} are validity checked in function
3616 and procedure calls at the point of call.
3619 @option{-gnatVm} Validity checks for @code{in out} mode parameters
3621 Arguments for parameters of mode @code{in out} are validity checked in
3622 procedure calls at the point of call. The @code{'m'} here stands for
3623 modify, since this concerns parameters that can be modified by the call.
3624 Note that there is no specific option to test @code{out} parameters,
3625 but any reference within the subprogram will be tested in the usual
3626 manner, and if an invalid value is copied back, any reference to it
3627 will be subject to validity checking.
3630 @option{-gnatVo} Validity checks for operator and attribute operands
3632 Arguments for predefined operators and attributes are validity checked.
3633 This includes all operators in package @code{Standard},
3634 the shift operators defined as intrinsic in package @code{Interfaces}
3635 and operands for attributes such as @code{Pos}.
3638 @option{-gnatVr} Validity checks for function returns
3640 The expression in @code{return} statements in functions is validity
3644 @option{-gnatVs} Validity checks for subscripts
3646 All subscripts expressions are checked for validity, whether they appear
3647 on the right side or left side (in default mode only left side subscripts
3648 are validity checked).
3651 @option{-gnatVt} Validity checks for tests
3653 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
3654 statements are checked, as well as guard expressions in entry calls.
3657 @option{-gnatVf} Validity checks for floating-point values
3659 In the absence of this switch, validity checking occurs only for discrete
3660 values. If @option{-gnatVf} is specified, then validity checking also applies
3661 for floating-point values, and NaN's and infinities are considered invalid,
3662 as well as out of range values for constrained types. Note that this means
3663 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
3664 in which floating-point values are checked depends on the setting of other
3665 options. For example @option{-gnatVif} or @option{-gnatVfi} (the order does
3666 not matter) specifies that floating-point parameters of mode @code{in} should
3667 be validity checked.
3670 @option{-gnatVa} All validity checks
3672 All the above validity checks are turned on. That is @option{-gnatVa} is
3673 equivalent to @code{gnatVcdfimorst}.
3676 @option{-gnatVn} No validity checks
3678 This switch turns off all validity checking, including the default checking
3679 for case statements and left hand side subscripts. Note that the use of
3680 the switch @option{-gnatp} supresses all run-time checks, including
3681 validity checks, and thus implies @option{-gnatVn}.
3685 The @option{-gnatV} switch may be followed by a string of letters to turn on
3686 a series of validity checking options. For example, @option{-gnatVcr} specifies
3687 that in addition to the default validity checking, copies and function
3688 return expressions be validity checked. In order to make it easier to specify
3689 a set of options, the upper case letters @code{CDFIMORST} may be used to turn
3690 off the corresponding lower case option, so for example @option{-gnatVaM} turns
3691 on all validity checking options except for checking of @code{in out}
3692 procedure arguments.
3694 The specification of additional validity checking generates extra code (and
3695 in the case of @option{-gnatva} the code expansion can be substantial. However,
3696 these additional checks can be very useful in smoking out cases of
3697 uninitialized variables, incorrect use of unchecked conversion, and other
3698 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
3699 is useful in conjunction with the extra validity checking, since this
3700 ensures that wherever possible uninitialized variables have invalid values.
3702 See also the pragma @code{Validity_Checks} which allows modification of
3703 the validity checking mode at the program source level, and also allows for
3704 temporary disabling of validity checks.
3706 @node Style Checking
3707 @subsection Style Checking
3708 @findex Style checking
3711 The -gnaty@var{x} switch causes the compiler to
3712 enforce specified style rules. A limited set of style rules has been used
3713 in writing the GNAT sources themselves. This switch allows user programs
3714 to activate all or some of these checks. If the source program fails a
3715 specified style check, an appropriate warning message is given, preceded by
3716 the character sequence "(style)".
3717 The string @var{x} is a sequence of letters or digits
3718 indicating the particular style
3719 checks to be performed. The following checks are defined:
3722 @item 1-9 (specify indentation level)
3723 If a digit from 1-9 appears in the string after @option{-gnaty} then proper
3724 indentation is checked, with the digit indicating the indentation level
3725 required. The general style of required indentation is as specified by
3726 the examples in the Ada Reference Manual. Full line comments must be
3727 aligned with the @code{--} starting on a column that is a multiple of
3728 the alignment level.
3730 @item a (check attribute casing)
3731 If the letter a appears in the string after @option{-gnaty} then
3732 attribute names, including the case of keywords such as @code{digits}
3733 used as attributes names, must be written in mixed case, that is, the
3734 initial letter and any letter following an underscore must be uppercase.
3735 All other letters must be lowercase.
3737 @item b (blanks not allowed at statement end)
3738 If the letter b appears in the string after @option{-gnaty} then
3739 trailing blanks are not allowed at the end of statements. The purpose of this
3740 rule, together with h (no horizontal tabs), is to enforce a canonical format
3741 for the use of blanks to separate source tokens.
3743 @item c (check comments)
3744 If the letter c appears in the string after @option{-gnaty} then
3745 comments must meet the following set of rules:
3750 The "--" that starts the column must either start in column one, or else
3751 at least one blank must precede this sequence.
3754 Comments that follow other tokens on a line must have at least one blank
3755 following the "--" at the start of the comment.
3758 Full line comments must have two blanks following the "--" that starts
3759 the comment, with the following exceptions.
3762 A line consisting only of the "--" characters, possibly preceded by blanks
3766 A comment starting with "--x" where x is a special character is permitted.
3767 This alows proper processing of the output generated by specialized tools
3768 including @code{gnatprep} (where --! is used) and the SPARK annnotation
3769 language (where --# is used). For the purposes of this rule, a special
3770 character is defined as being in one of the ASCII ranges
3771 16#21#..16#2F# or 16#3A#..16#3F#.
3774 A line consisting entirely of minus signs, possibly preceded by blanks, is
3775 permitted. This allows the construction of box comments where lines of minus
3776 signs are used to form the top and bottom of the box.
3779 If a comment starts and ends with "--" is permitted as long as at least
3780 one blank follows the initial "--". Together with the preceding rule,
3781 this allows the construction of box comments, as shown in the following
3784 ---------------------------
3785 -- This is a box comment --
3786 -- with two text lines. --
3787 ---------------------------
3791 @item e (check end/exit labels)
3792 If the letter e appears in the string after @option{-gnaty} then
3793 optional labels on @code{end} statements ending subprograms and on
3794 @code{exit} statements exiting named loops, are required to be present.
3796 @item f (no form feeds or vertical tabs)
3797 If the letter f appears in the string after @option{-gnaty} then
3798 neither form feeds nor vertical tab characters are not permitted
3801 @item h (no horizontal tabs)
3802 If the letter h appears in the string after @option{-gnaty} then
3803 horizontal tab characters are not permitted in the source text.
3804 Together with the b (no blanks at end of line) check, this
3805 enforces a canonical form for the use of blanks to separate
3808 @item i (check if-then layout)
3809 If the letter i appears in the string after @option{-gnaty},
3810 then the keyword @code{then} must appear either on the same
3811 line as corresponding @code{if}, or on a line on its own, lined
3812 up under the @code{if} with at least one non-blank line in between
3813 containing all or part of the condition to be tested.
3815 @item k (check keyword casing)
3816 If the letter k appears in the string after @option{-gnaty} then
3817 all keywords must be in lower case (with the exception of keywords
3818 such as @code{digits} used as attribute names to which this check
3821 @item l (check layout)
3822 If the letter l appears in the string after @option{-gnaty} then
3823 layout of statement and declaration constructs must follow the
3824 recommendations in the Ada Reference Manual, as indicated by the
3825 form of the syntax rules. For example an @code{else} keyword must
3826 be lined up with the corresponding @code{if} keyword.
3828 There are two respects in which the style rule enforced by this check
3829 option are more liberal than those in the Ada Reference Manual. First
3830 in the case of record declarations, it is permissible to put the
3831 @code{record} keyword on the same line as the @code{type} keyword, and
3832 then the @code{end} in @code{end record} must line up under @code{type}.
3833 For example, either of the following two layouts is acceptable:
3838 @b{type} q @b{is record}
3853 Second, in the case of a block statement, a permitted alternative
3854 is to put the block label on the same line as the @code{declare} or
3855 @code{begin} keyword, and then line the @code{end} keyword up under
3856 the block label. For example both the following are permitted:
3878 The same alternative format is allowed for loops. For example, both of
3879 the following are permitted:
3884 Clear : @b{while} J < 10 @b{loop}
3889 @b{while} J < 10 @b{loop}
3896 @item m (check maximum line length)
3897 If the letter m appears in the string after @option{-gnaty}
3898 then the length of source lines must not exceed 79 characters, including
3899 any trailing blanks. The value of 79 allows convenient display on an
3900 80 character wide device or window, allowing for possible special
3901 treatment of 80 character lines.
3903 @item Mnnn (set maximum line length)
3904 If the sequence Mnnn, where nnn is a decimal number, appears in
3905 the string after @option{-gnaty} then the length of lines must not exceed the
3908 @item n (check casing of entities in Standard)
3909 If the letter n appears in the string
3910 after @option{-gnaty} then any identifier from Standard must be cased
3911 to match the presentation in the Ada Reference Manual (for example,
3912 @code{Integer} and @code{ASCII.NUL}).
3914 @item o (check order of subprogram bodies)
3915 If the letter o appears in the string
3916 after @option{-gnaty} then all subprogram bodies in a given scope
3917 (e.g. a package body) must be in alphabetical order. The ordering
3918 rule uses normal Ada rules for comparing strings, ignoring casing
3919 of letters, except that if there is a trailing numeric suffix, then
3920 the value of this suffix is used in the ordering (e.g. Junk2 comes
3923 @item p (check pragma casing)
3924 If the letter p appears in the string after @option{-gnaty} then
3925 pragma names must be written in mixed case, that is, the
3926 initial letter and any letter following an underscore must be uppercase.
3927 All other letters must be lowercase.
3929 @item r (check references)
3930 If the letter r appears in the string after @option{-gnaty}
3931 then all identifier references must be cased in the same way as the
3932 corresponding declaration. No specific casing style is imposed on
3933 identifiers. The only requirement is for consistency of references
3936 @item s (check separate specs)
3937 If the letter s appears in the string after @option{-gnaty} then
3938 separate declarations ("specs") are required for subprograms (a
3939 body is not allowed to serve as its own declaration). The only
3940 exception is that parameterless library level procedures are
3941 not required to have a separate declaration. This exception covers
3942 the most frequent form of main program procedures.
3944 @item t (check token spacing)
3945 If the letter t appears in the string after @option{-gnaty} then
3946 the following token spacing rules are enforced:
3951 The keywords @code{abs} and @code{not} must be followed by a space.
3954 The token @code{=>} must be surrounded by spaces.
3957 The token @code{<>} must be preceded by a space or a left parenthesis.
3960 Binary operators other than @code{**} must be surrounded by spaces.
3961 There is no restriction on the layout of the @code{**} binary operator.
3964 Colon must be surrounded by spaces.
3967 Colon-equal (assignment) must be surrounded by spaces.
3970 Comma must be the first non-blank character on the line, or be
3971 immediately preceded by a non-blank character, and must be followed
3975 If the token preceding a left paren ends with a letter or digit, then
3976 a space must separate the two tokens.
3979 A right parenthesis must either be the first non-blank character on
3980 a line, or it must be preceded by a non-blank character.
3983 A semicolon must not be preceded by a space, and must not be followed by
3984 a non-blank character.
3987 A unary plus or minus may not be followed by a space.
3990 A vertical bar must be surrounded by spaces.
3994 In the above rules, appearing in column one is always permitted, that is,
3995 counts as meeting either a requirement for a required preceding space,
3996 or as meeting a requirement for no preceding space.
3998 Appearing at the end of a line is also always permitted, that is, counts
3999 as meeting either a requirement for a following space, or as meeting
4000 a requirement for no following space.
4005 If any of these style rules is violated, a message is generated giving
4006 details on the violation. The initial characters of such messages are
4007 always "(style)". Note that these messages are treated as warning
4008 messages, so they normally do not prevent the generation of an object
4009 file. The @option{-gnatwe} switch can be used to treat warning messages,
4010 including style messages, as fatal errors.
4014 @option{-gnaty} on its own (that is not followed by any letters or digits),
4015 is equivalent to @code{gnaty3abcefhiklmprst}, that is all checking
4016 options are enabled with
4017 the exception of -gnatyo,
4018 with an indentation level of 3. This is the standard
4019 checking option that is used for the GNAT sources.
4021 @node Run-Time Checks
4022 @subsection Run-Time Checks
4023 @cindex Division by zero
4024 @cindex Access before elaboration
4025 @cindex Checks, division by zero
4026 @cindex Checks, access before elaboration
4029 If you compile with the default options, GNAT will insert many run-time
4030 checks into the compiled code, including code that performs range
4031 checking against constraints, but not arithmetic overflow checking for
4032 integer operations (including division by zero) or checks for access
4033 before elaboration on subprogram calls. All other run-time checks, as
4034 required by the Ada 95 Reference Manual, are generated by default.
4035 The following @code{gcc} switches refine this default behavior:
4039 @cindex @option{-gnatp} (@code{gcc})
4040 @cindex Suppressing checks
4041 @cindex Checks, suppressing
4043 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
4044 had been present in the source. Validity checks are also suppressed (in
4045 other words @option{-gnatp} also implies @option{-gnatVn}.
4046 Use this switch to improve the performance
4047 of the code at the expense of safety in the presence of invalid data or
4051 @cindex @option{-gnato} (@code{gcc})
4052 @cindex Overflow checks
4053 @cindex Check, overflow
4054 Enables overflow checking for integer operations.
4055 This causes GNAT to generate slower and larger executable
4056 programs by adding code to check for overflow (resulting in raising
4057 @code{Constraint_Error} as required by standard Ada
4058 semantics). These overflow checks correspond to situations in which
4059 the true value of the result of an operation may be outside the base
4060 range of the result type. The following example shows the distinction:
4063 X1 : Integer := Integer'Last;
4064 X2 : Integer range 1 .. 5 := 5;
4066 X1 := X1 + 1; -- @option{-gnato} required to catch the Constraint_Error
4067 X2 := X2 + 1; -- range check, @option{-gnato} has no effect here
4071 Here the first addition results in a value that is outside the base range
4072 of Integer, and hence requires an overflow check for detection of the
4073 constraint error. The second increment operation results in a violation
4074 of the explicit range constraint, and such range checks are always
4075 performed. Basically the compiler can assume that in the absence of
4076 the @option{-gnato} switch that any value of type @code{xxx} is
4077 in range of the base type of @code{xxx}.
4079 @findex Machine_Overflows
4080 Note that the @option{-gnato} switch does not affect the code generated
4081 for any floating-point operations; it applies only to integer
4083 For floating-point, GNAT has the @code{Machine_Overflows}
4084 attribute set to @code{False} and the normal mode of operation is to
4085 generate IEEE NaN and infinite values on overflow or invalid operations
4086 (such as dividing 0.0 by 0.0).
4088 The reason that we distinguish overflow checking from other kinds of
4089 range constraint checking is that a failure of an overflow check can
4090 generate an incorrect value, but cannot cause erroneous behavior. This
4091 is unlike the situation with a constraint check on an array subscript,
4092 where failure to perform the check can result in random memory description,
4093 or the range check on a case statement, where failure to perform the check
4094 can cause a wild jump.
4096 Note again that @option{-gnato} is off by default, so overflow checking is
4097 not performed in default mode. This means that out of the box, with the
4098 default settings, GNAT does not do all the checks expected from the
4099 language description in the Ada Reference Manual. If you want all constraint
4100 checks to be performed, as described in this Manual, then you must
4101 explicitly use the -gnato switch either on the @code{gnatmake} or
4105 @cindex @option{-gnatE} (@code{gcc})
4106 @cindex Elaboration checks
4107 @cindex Check, elaboration
4108 Enables dynamic checks for access-before-elaboration
4109 on subprogram calls and generic instantiations.
4110 For full details of the effect and use of this switch,
4111 @xref{Compiling Using gcc}.
4116 The setting of these switches only controls the default setting of the
4117 checks. You may modify them using either @code{Suppress} (to remove
4118 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
4121 @node Stack Overflow Checking
4122 @subsection Stack Overflow Checking
4123 @cindex Stack Overflow Checking
4124 @cindex -fstack-check
4127 For most operating systems, @code{gcc} does not perform stack overflow
4128 checking by default. This means that if the main environment task or
4129 some other task exceeds the available stack space, then unpredictable
4130 behavior will occur.
4132 To activate stack checking, compile all units with the gcc option
4133 @code{-fstack-check}. For example:
4136 gcc -c -fstack-check package1.adb
4140 Units compiled with this option will generate extra instructions to check
4141 that any use of the stack (for procedure calls or for declaring local
4142 variables in declare blocks) do not exceed the available stack space.
4143 If the space is exceeded, then a @code{Storage_Error} exception is raised.
4145 For declared tasks, the stack size is always controlled by the size
4146 given in an applicable @code{Storage_Size} pragma (or is set to
4147 the default size if no pragma is used.
4149 For the environment task, the stack size depends on
4150 system defaults and is unknown to the compiler. The stack
4151 may even dynamically grow on some systems, precluding the
4152 normal Ada semantics for stack overflow. In the worst case,
4153 unbounded stack usage, causes unbounded stack expansion
4154 resulting in the system running out of virtual memory.
4156 The stack checking may still work correctly if a fixed
4157 size stack is allocated, but this cannot be guaranteed.
4158 To ensure that a clean exception is signalled for stack
4159 overflow, set the environment variable
4160 @code{GNAT_STACK_LIMIT} to indicate the maximum
4161 stack area that can be used, as in:
4162 @cindex GNAT_STACK_LIMIT
4165 SET GNAT_STACK_LIMIT 1600
4169 The limit is given in kilobytes, so the above declaration would
4170 set the stack limit of the environment task to 1.6 megabytes.
4171 Note that the only purpose of this usage is to limit the amount
4172 of stack used by the environment task. If it is necessary to
4173 increase the amount of stack for the environment task, then this
4174 is an operating systems issue, and must be addressed with the
4175 appropriate operating systems commands.
4177 @node Run-Time Control
4178 @subsection Run-Time Control
4182 @cindex @option{-gnatT} (@code{gcc})
4183 @cindex Time Slicing
4186 The @code{gnatT} switch can be used to specify the time-slicing value
4187 to be used for task switching between equal priority tasks. The value
4188 @code{nnn} is given in microseconds as a decimal integer.
4190 Setting the time-slicing value is only effective if the underlying thread
4191 control system can accommodate time slicing. Check the documentation of
4192 your operating system for details. Note that the time-slicing value can
4193 also be set by use of pragma @code{Time_Slice} or by use of the
4194 @code{t} switch in the gnatbind step. The pragma overrides a command
4195 line argument if both are present, and the @code{t} switch for gnatbind
4196 overrides both the pragma and the @code{gcc} command line switch.
4199 @node Using gcc for Syntax Checking
4200 @subsection Using @code{gcc} for Syntax Checking
4203 @cindex @option{-gnats} (@code{gcc})
4206 The @code{s} stands for syntax.
4208 Run GNAT in syntax checking only mode. For
4209 example, the command
4212 $ gcc -c -gnats x.adb
4216 compiles file @file{x.adb} in syntax-check-only mode. You can check a
4217 series of files in a single command
4218 , and can use wild cards to specify such a group of files.
4219 Note that you must specify the @code{-c} (compile
4220 only) flag in addition to the @option{-gnats} flag.
4223 You may use other switches in conjunction with @option{-gnats}. In
4224 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
4225 format of any generated error messages.
4227 The output is simply the error messages, if any. No object file or ALI
4228 file is generated by a syntax-only compilation. Also, no units other
4229 than the one specified are accessed. For example, if a unit @code{X}
4230 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
4231 check only mode does not access the source file containing unit
4234 @cindex Multiple units, syntax checking
4235 Normally, GNAT allows only a single unit in a source file. However, this
4236 restriction does not apply in syntax-check-only mode, and it is possible
4237 to check a file containing multiple compilation units concatenated
4238 together. This is primarily used by the @code{gnatchop} utility
4239 (@pxref{Renaming Files Using gnatchop}).
4242 @node Using gcc for Semantic Checking
4243 @subsection Using @code{gcc} for Semantic Checking
4246 @cindex @option{-gnatc} (@code{gcc})
4249 The @code{c} stands for check.
4250 Causes the compiler to operate in semantic check mode,
4251 with full checking for all illegalities specified in the
4252 Ada 95 Reference Manual, but without generation of any object code
4253 (no object file is generated).
4255 Because dependent files must be accessed, you must follow the GNAT
4256 semantic restrictions on file structuring to operate in this mode:
4260 The needed source files must be accessible
4261 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4264 Each file must contain only one compilation unit.
4267 The file name and unit name must match (@pxref{File Naming Rules}).
4270 The output consists of error messages as appropriate. No object file is
4271 generated. An @file{ALI} file is generated for use in the context of
4272 cross-reference tools, but this file is marked as not being suitable
4273 for binding (since no object file is generated).
4274 The checking corresponds exactly to the notion of
4275 legality in the Ada 95 Reference Manual.
4277 Any unit can be compiled in semantics-checking-only mode, including
4278 units that would not normally be compiled (subunits,
4279 and specifications where a separate body is present).
4282 @node Compiling Ada 83 Programs
4283 @subsection Compiling Ada 83 Programs
4285 @cindex Ada 83 compatibility
4287 @cindex @option{-gnat83} (@code{gcc})
4288 @cindex ACVC, Ada 83 tests
4291 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
4292 specify that an Ada 83 program is to be compiled in Ada83 mode. If you specify
4293 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
4294 where this can be done easily.
4295 It is not possible to guarantee this switch does a perfect
4296 job; for example, some subtle tests, such as are
4297 found in earlier ACVC tests (that have been removed from the ACVC suite for Ada
4298 95), may not compile correctly. However, for most purposes, using
4299 this switch should help to ensure that programs that compile correctly
4300 under the @option{-gnat83} switch can be ported easily to an Ada 83
4301 compiler. This is the main use of the switch.
4303 With few exceptions (most notably the need to use @code{<>} on
4304 @cindex Generic formal parameters
4305 unconstrained generic formal parameters, the use of the new Ada 95
4306 keywords, and the use of packages
4307 with optional bodies), it is not necessary to use the
4308 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
4309 exceptions, Ada 95 is upwardly compatible with Ada 83. This
4310 means that a correct Ada 83 program is usually also a correct Ada 95
4315 @node Character Set Control
4316 @subsection Character Set Control
4319 @cindex @code{-gnati} (@code{gcc})
4322 Normally GNAT recognizes the Latin-1 character set in source program
4323 identifiers, as described in the Ada 95 Reference Manual.
4325 GNAT to recognize alternate character sets in identifiers. @var{c} is a
4326 single character indicating the character set, as follows:
4333 Latin-2 letters allowed in identifiers
4336 Latin-3 letters allowed in identifiers
4339 Latin-4 letters allowed in identifiers
4342 Latin-5 (Cyrillic) letters allowed in identifiers
4345 Latin-9 letters allowed in identifiers
4348 IBM PC letters (code page 437) allowed in identifiers
4351 IBM PC letters (code page 850) allowed in identifiers
4354 Full upper-half codes allowed in identifiers
4357 No upper-half codes allowed in identifiers
4360 Wide-character codes (that is, codes greater than 255)
4361 allowed in identifiers
4364 @xref{Foreign Language Representation}, for full details on the
4365 implementation of these character sets.
4368 @cindex @code{-gnatW} (@code{gcc})
4369 Specify the method of encoding for wide characters.
4370 @var{e} is one of the following:
4375 Hex encoding (brackets coding also recognized)
4378 Upper half encoding (brackets encoding also recognized)
4381 Shift/JIS encoding (brackets encoding also recognized)
4384 EUC encoding (brackets encoding also recognized)
4387 UTF-8 encoding (brackets encoding also recognized)
4390 Brackets encoding only (default value)
4392 For full details on the these encoding
4393 methods see @xref{Wide Character Encodings}.
4394 Note that brackets coding is always accepted, even if one of the other
4395 options is specified, so for example @option{-gnatW8} specifies that both
4396 brackets and @code{UTF-8} encodings will be recognized. The units that are
4397 with'ed directly or indirectly will be scanned using the specified
4398 representation scheme, and so if one of the non-brackets scheme is
4399 used, it must be used consistently throughout the program. However,
4400 since brackets encoding is always recognized, it may be conveniently
4401 used in standard libraries, allowing these libraries to be used with
4402 any of the available coding schemes.
4403 scheme. If no @option{-gnatW?} parameter is present, then the default
4404 representation is Brackets encoding only.
4406 Note that the wide character representation that is specified (explicitly
4407 or by default) for the main program also acts as the default encoding used
4408 for Wide_Text_IO files if not specifically overridden by a WCEM form
4412 @node File Naming Control
4413 @subsection File Naming Control
4417 @cindex @option{-gnatk} (@code{gcc})
4418 Activates file name "krunching". @var{n}, a decimal integer in the range
4419 1-999, indicates the maximum allowable length of a file name (not
4420 including the @file{.ads} or @file{.adb} extension). The default is not
4421 to enable file name krunching.
4423 For the source file naming rules, @xref{File Naming Rules}.
4426 @node Subprogram Inlining Control
4427 @subsection Subprogram Inlining Control
4431 @cindex @option{-gnatn} (@code{gcc})
4432 The @code{n} here is intended to suggest the first syllable of the
4434 GNAT recognizes and processes @code{Inline} pragmas. However, for the
4435 inlining to actually occur, optimization must be enabled. To enable
4436 inlining across unit boundaries, this is, inlining a call in one unit of
4437 a subprogram declared in a @code{with}'ed unit, you must also specify
4439 In the absence of this switch, GNAT does not attempt
4440 inlining across units and does not need to access the bodies of
4441 subprograms for which @code{pragma Inline} is specified if they are not
4442 in the current unit.
4444 If you specify this switch the compiler will access these bodies,
4445 creating an extra source dependency for the resulting object file, and
4446 where possible, the call will be inlined.
4447 For further details on when inlining is possible
4448 see @xref{Inlining of Subprograms}.
4451 @cindex @option{-gnatN} (@code{gcc})
4452 The front end inlining activated by this switch is generally more extensive,
4453 and quite often more effective than the standard @option{-gnatn} inlining mode.
4454 It will also generate additional dependencies.
4458 @node Auxiliary Output Control
4459 @subsection Auxiliary Output Control
4463 @cindex @option{-gnatt} (@code{gcc})
4464 @cindex Writing internal trees
4465 @cindex Internal trees, writing to file
4466 Causes GNAT to write the internal tree for a unit to a file (with the
4467 extension @file{.adt}.
4468 This not normally required, but is used by separate analysis tools.
4470 these tools do the necessary compilations automatically, so you should
4471 not have to specify this switch in normal operation.
4474 @cindex @option{-gnatu} (@code{gcc})
4475 Print a list of units required by this compilation on @file{stdout}.
4476 The listing includes all units on which the unit being compiled depends
4477 either directly or indirectly.
4479 @item -pass-exit-codes
4480 @cindex @code{-pass-exit-codes} (@code{gcc})
4481 If this switch is not used, the exit code returned by @code{gcc} when
4482 compiling multiple files indicates whether all source files have
4483 been successfully used to generate object files or not.
4485 When @code{-pass-exit-codes} is used, @code{gcc} exits with an extended
4486 exit status and allows an integrated development environment to better
4487 react to a compilation failure. Those exit status are:
4491 There was an error in at least one source file.
4493 At least one source file did not generate an object file.
4495 The compiler died unexpectedly (internal error for example).
4497 An object file has been generated for every source file.
4501 @node Debugging Control
4502 @subsection Debugging Control
4505 @cindex Debugging options
4507 Activate internal debugging switches. @var{x} is a letter or digit, or
4508 string of letters or digits, which specifies the type of debugging
4509 outputs desired. Normally these are used only for internal development
4510 or system debugging purposes. You can find full documentation for these
4511 switches in the body of the @code{Debug} unit in the compiler source
4512 file @file{debug.adb}.
4515 @cindex @option{-gnatG} (@code{gcc})
4516 This switch causes the compiler to generate auxiliary output containing
4517 a pseudo-source listing of the generated expanded code. Like most Ada
4518 compilers, GNAT works by first transforming the high level Ada code into
4519 lower level constructs. For example, tasking operations are transformed
4520 into calls to the tasking run-time routines. A unique capability of GNAT
4521 is to list this expanded code in a form very close to normal Ada source.
4522 This is very useful in understanding the implications of various Ada
4523 usage on the efficiency of the generated code. There are many cases in
4524 Ada (e.g. the use of controlled types), where simple Ada statements can
4525 generate a lot of run-time code. By using @option{-gnatG} you can identify
4526 these cases, and consider whether it may be desirable to modify the coding
4527 approach to improve efficiency.
4529 The format of the output is very similar to standard Ada source, and is
4530 easily understood by an Ada programmer. The following special syntactic
4531 additions correspond to low level features used in the generated code that
4532 do not have any exact analogies in pure Ada source form. The following
4533 is a partial list of these special constructions. See the specification
4534 of package @code{Sprint} in file @file{sprint.ads} for a full list.
4537 @item new @var{xxx} [storage_pool = @var{yyy}]
4538 Shows the storage pool being used for an allocator.
4540 @item at end @var{procedure-name};
4541 Shows the finalization (cleanup) procedure for a scope.
4543 @item (if @var{expr} then @var{expr} else @var{expr})
4544 Conditional expression equivalent to the @code{x?y:z} construction in C.
4546 @item @var{target}^(@var{source})
4547 A conversion with floating-point truncation instead of rounding.
4549 @item @var{target}?(@var{source})
4550 A conversion that bypasses normal Ada semantic checking. In particular
4551 enumeration types and fixed-point types are treated simply as integers.
4553 @item @var{target}?^(@var{source})
4554 Combines the above two cases.
4556 @item @var{x} #/ @var{y}
4557 @itemx @var{x} #mod @var{y}
4558 @itemx @var{x} #* @var{y}
4559 @itemx @var{x} #rem @var{y}
4560 A division or multiplication of fixed-point values which are treated as
4561 integers without any kind of scaling.
4563 @item free @var{expr} [storage_pool = @var{xxx}]
4564 Shows the storage pool associated with a @code{free} statement.
4566 @item freeze @var{typename} [@var{actions}]
4567 Shows the point at which @var{typename} is frozen, with possible
4568 associated actions to be performed at the freeze point.
4570 @item reference @var{itype}
4571 Reference (and hence definition) to internal type @var{itype}.
4573 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
4574 Intrinsic function call.
4576 @item @var{labelname} : label
4577 Declaration of label @var{labelname}.
4579 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
4580 A multiple concatenation (same effect as @var{expr} & @var{expr} &
4581 @var{expr}, but handled more efficiently).
4583 @item [constraint_error]
4584 Raise the @code{Constraint_Error} exception.
4586 @item @var{expression}'reference
4587 A pointer to the result of evaluating @var{expression}.
4589 @item @var{target-type}!(@var{source-expression})
4590 An unchecked conversion of @var{source-expression} to @var{target-type}.
4592 @item [@var{numerator}/@var{denominator}]
4593 Used to represent internal real literals (that) have no exact
4594 representation in base 2-16 (for example, the result of compile time
4595 evaluation of the expression 1.0/27.0).
4598 @cindex @option{-gnatD} (@code{gcc})
4599 This switch is used in conjunction with @option{-gnatG} to cause the expanded
4600 source, as described above to be written to files with names
4601 @file{xxx.dg}, where @file{xxx} is the normal file name,
4602 for example, if the source file name is @file{hello.adb},
4603 then a file @file{hello.adb.dg} will be written.
4604 The debugging information generated
4605 by the @code{gcc} @code{-g} switch will refer to the generated
4606 @file{xxx.dg} file. This allows you to do source level debugging using
4607 the generated code which is sometimes useful for complex code, for example
4608 to find out exactly which part of a complex construction raised an
4609 exception. This switch also suppress generation of cross-reference
4610 information (see -gnatx).
4613 @cindex @option{-gnatE} (@code{gcc})
4614 In the generated debugging information, and also in the case of long external
4615 names, the compiler uses a compression mechanism if the name is very long.
4616 This compression method uses a checksum, and avoids trouble on some operating
4617 systems which have difficulty with very long names. The @option{-gnatC} switch
4618 forces this compression approach to be used on all external names and names
4619 in the debugging information tables. This reduces the size of the generated
4620 executable, at the expense of making the naming scheme more complex. The
4621 compression only affects the qualification of the name. Thus a name in
4625 Very_Long_Package.Very_Long_Inner_Package.Var
4629 would normally appear in these tables as:
4632 very_long_package__very_long_inner_package__var
4636 but if the @option{-gnatC} switch is used, then the name appears as
4643 Here b7e0c705 is a compressed encoding of the qualification prefix.
4644 The GNAT Ada aware version of GDB understands these encoded prefixes, so if this
4645 debugger is used, the encoding is largely hidden from the user of the compiler.
4649 @item -gnatR[0|1|2|3][s]
4650 @cindex @option{-gnatR} (@code{gcc})
4651 This switch controls output from the compiler of a listing showing
4652 representation information for declared types and objects. For
4653 @option{-gnatR0}, no information is output (equivalent to omitting
4654 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
4655 so @option{-gnatR} with no parameter has the same effect), size and alignment
4656 information is listed for declared array and record types. For
4657 @option{-gnatR2}, size and alignment information is listed for all
4658 expression information for values that are computed at run time for
4659 variant records. These symbolic expressions have a mostly obvious
4660 format with #n being used to represent the value of the n'th
4661 discriminant. See source files @file{repinfo.ads/adb} in the
4662 @code{GNAT} sources for full detalis on the format of @option{-gnatR3}
4663 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
4664 the output is to a file with the name @file{file.rep} where
4665 file is the name of the corresponding source file.
4668 @cindex @option{-gnatx} (@code{gcc})
4669 Normally the compiler generates full cross-referencing information in
4670 the @file{ALI} file. This information is used by a number of tools,
4671 including @code{gnatfind} and @code{gnatxref}. The -gnatx switch
4672 suppresses this information. This saves some space and may slightly
4673 speed up compilation, but means that these tools cannot be used.
4676 @node Units to Sources Mapping Files
4677 @subsection Units to Sources Mapping Files
4681 @item -gnatem@var{path}
4682 @cindex @option{-gnatem} (@code{gcc})
4683 A mapping file is a way to communicate to the compiler two mappings:
4684 from unit names to file names (without any directory information) and from
4685 file names to path names (with full directory information). These mappings
4686 are used by the compiler to short-circuit the path search.
4688 A mapping file is a sequence of sets of three lines. In each set,
4689 the first line is the unit name, in lower case, with "%s" appended for
4690 specifications and "%b" appended for bodies; the second line is the file
4691 name; and the third line is the path name.
4697 /gnat/project1/sources/main.2.ada
4700 When the switch @option{-gnatem} is specified, the compiler will create
4701 in memory the two mappings from the specified file. If there is any problem
4702 (non existent file, truncated file or duplicate entries), no mapping
4705 Several @option{-gnatem} switches may be specified; however, only the last
4706 one on the command line will be taken into account.
4708 When using a project file, @code{gnatmake} create a temporary mapping file
4709 and communicates it to the compiler using this switch.
4713 @node Search Paths and the Run-Time Library (RTL)
4714 @section Search Paths and the Run-Time Library (RTL)
4717 With the GNAT source-based library system, the compiler must be able to
4718 find source files for units that are needed by the unit being compiled.
4719 Search paths are used to guide this process.
4721 The compiler compiles one source file whose name must be given
4722 explicitly on the command line. In other words, no searching is done
4723 for this file. To find all other source files that are needed (the most
4724 common being the specs of units), the compiler examines the following
4725 directories, in the following order:
4729 The directory containing the source file of the main unit being compiled
4730 (the file name on the command line).
4733 Each directory named by an @code{-I} switch given on the @code{gcc}
4734 command line, in the order given.
4737 @findex ADA_INCLUDE_PATH
4738 Each of the directories listed in the value of the
4739 @code{ADA_INCLUDE_PATH} environment variable.
4740 Construct this value
4741 exactly as the @code{PATH} environment variable: a list of directory
4742 names separated by colons (semicolons when working with the NT version).
4744 The content of the "ada_source_path" file which is part of the GNAT
4745 installation tree and is used to store standard libraries such as the
4746 GNAT Run Time Library (RTL) source files.
4747 @ref{Installing an Ada Library}
4751 Specifying the switch @code{-I-}
4752 inhibits the use of the directory
4753 containing the source file named in the command line. You can still
4754 have this directory on your search path, but in this case it must be
4755 explicitly requested with a @code{-I} switch.
4757 Specifying the switch @code{-nostdinc}
4758 inhibits the search of the default location for the GNAT Run Time
4759 Library (RTL) source files.
4761 The compiler outputs its object files and ALI files in the current
4763 Caution: The object file can be redirected with the @code{-o} switch;
4764 however, @code{gcc} and @code{gnat1} have not been coordinated on this
4765 so the ALI file will not go to the right place. Therefore, you should
4766 avoid using the @code{-o} switch.
4769 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
4770 children make up the GNAT RTL, together with the simple @code{System.IO}
4771 package used in the "Hello World" example. The sources for these units
4772 are needed by the compiler and are kept together in one directory. Not
4773 all of the bodies are needed, but all of the sources are kept together
4774 anyway. In a normal installation, you need not specify these directory
4775 names when compiling or binding. Either the environment variables or
4776 the built-in defaults cause these files to be found.
4778 In addition to the language-defined hierarchies (System, Ada and
4779 Interfaces), the GNAT distribution provides a fourth hierarchy,
4780 consisting of child units of GNAT. This is a collection of generally
4781 useful routines. See the GNAT Reference Manual for further details.
4783 Besides simplifying access to the RTL, a major use of search paths is
4784 in compiling sources from multiple directories. This can make
4785 development environments much more flexible.
4787 @node Order of Compilation Issues
4788 @section Order of Compilation Issues
4791 If, in our earlier example, there was a spec for the @code{hello}
4792 procedure, it would be contained in the file @file{hello.ads}; yet this
4793 file would not have to be explicitly compiled. This is the result of the
4794 model we chose to implement library management. Some of the consequences
4795 of this model are as follows:
4799 There is no point in compiling specs (except for package
4800 specs with no bodies) because these are compiled as needed by clients. If
4801 you attempt a useless compilation, you will receive an error message.
4802 It is also useless to compile subunits because they are compiled as needed
4806 There are no order of compilation requirements: performing a
4807 compilation never obsoletes anything. The only way you can obsolete
4808 something and require recompilations is to modify one of the
4809 source files on which it depends.
4812 There is no library as such, apart from the ALI files
4813 (@pxref{The Ada Library Information Files}, for information on the format of these
4814 files). For now we find it convenient to create separate ALI files, but
4815 eventually the information therein may be incorporated into the object
4819 When you compile a unit, the source files for the specs of all units
4820 that it @code{with}'s, all its subunits, and the bodies of any generics it
4821 instantiates must be available (reachable by the search-paths mechanism
4822 described above), or you will receive a fatal error message.
4829 The following are some typical Ada compilation command line examples:
4832 @item $ gcc -c xyz.adb
4833 Compile body in file @file{xyz.adb} with all default options.
4835 @item $ gcc -c -O2 -gnata xyz-def.adb
4837 Compile the child unit package in file @file{xyz-def.adb} with extensive
4838 optimizations, and pragma @code{Assert}/@code{Debug} statements
4841 @item $ gcc -c -gnatc abc-def.adb
4842 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
4846 @node Binding Using gnatbind
4847 @chapter Binding Using @code{gnatbind}
4851 * Running gnatbind::
4852 * Generating the Binder Program in C::
4853 * Consistency-Checking Modes::
4854 * Binder Error Message Control::
4855 * Elaboration Control::
4857 * Binding with Non-Ada Main Programs::
4858 * Binding Programs with No Main Subprogram::
4859 * Summary of Binder Switches::
4860 * Command-Line Access::
4861 * Search Paths for gnatbind::
4862 * Examples of gnatbind Usage::
4866 This chapter describes the GNAT binder, @code{gnatbind}, which is used
4867 to bind compiled GNAT objects. The @code{gnatbind} program performs
4868 four separate functions:
4872 Checks that a program is consistent, in accordance with the rules in
4873 Chapter 10 of the Ada 95 Reference Manual. In particular, error
4874 messages are generated if a program uses inconsistent versions of a
4878 Checks that an acceptable order of elaboration exists for the program
4879 and issues an error message if it cannot find an order of elaboration
4880 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
4883 Generates a main program incorporating the given elaboration order.
4884 This program is a small Ada package (body and spec) that
4885 must be subsequently compiled
4886 using the GNAT compiler. The necessary compilation step is usually
4887 performed automatically by @code{gnatlink}. The two most important
4888 functions of this program
4889 are to call the elaboration routines of units in an appropriate order
4890 and to call the main program.
4893 Determines the set of object files required by the given main program.
4894 This information is output in the forms of comments in the generated program,
4895 to be read by the @code{gnatlink} utility used to link the Ada application.
4898 @node Running gnatbind
4899 @section Running @code{gnatbind}
4902 The form of the @code{gnatbind} command is
4905 $ gnatbind [@var{switches}] @var{mainprog}[.ali] [@var{switches}]
4909 where @var{mainprog}.adb is the Ada file containing the main program
4910 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
4911 package in two files which names are
4912 @file{b~@var{ada_main}.ads}, and @file{b~@var{ada_main}.adb}.
4913 For example, if given the
4914 parameter @samp{hello.ali}, for a main program contained in file
4915 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
4916 and @file{b~hello.adb}.
4918 When doing consistency checking, the binder takes into consideration
4919 any source files it can locate. For example, if the binder determines
4920 that the given main program requires the package @code{Pack}, whose
4922 file is @file{pack.ali} and whose corresponding source spec file is
4923 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
4924 (using the same search path conventions as previously described for the
4925 @code{gcc} command). If it can locate this source file, it checks that
4927 or source checksums of the source and its references to in @file{ali} files
4928 match. In other words, any @file{ali} files that mentions this spec must have
4929 resulted from compiling this version of the source file (or in the case
4930 where the source checksums match, a version close enough that the
4931 difference does not matter).
4933 @cindex Source files, use by binder
4934 The effect of this consistency checking, which includes source files, is
4935 that the binder ensures that the program is consistent with the latest
4936 version of the source files that can be located at bind time. Editing a
4937 source file without compiling files that depend on the source file cause
4938 error messages to be generated by the binder.
4940 For example, suppose you have a main program @file{hello.adb} and a
4941 package @code{P}, from file @file{p.ads} and you perform the following
4946 Enter @code{gcc -c hello.adb} to compile the main program.
4949 Enter @code{gcc -c p.ads} to compile package @code{P}.
4952 Edit file @file{p.ads}.
4955 Enter @code{gnatbind hello}.
4958 At this point, the file @file{p.ali} contains an out-of-date time stamp
4959 because the file @file{p.ads} has been edited. The attempt at binding
4960 fails, and the binder generates the following error messages:
4963 error: "hello.adb" must be recompiled ("p.ads" has been modified)
4964 error: "p.ads" has been modified and must be recompiled
4968 Now both files must be recompiled as indicated, and then the bind can
4969 succeed, generating a main program. You need not normally be concerned
4970 with the contents of this file, but it is similar to the following which
4971 is the binder file generated for a simple "hello world" program.
4977 -- The package is called Ada_Main unless this name is actually used
4978 -- as a unit name in the partition, in which case some other unique
4984 Elab_Final_Code : Integer;
4985 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
4987 -- The main program saves the parameters (argument count,
4988 -- argument values, environment pointer) in global variables
4989 -- for later access by other units including
4990 -- Ada.Command_Line.
4992 gnat_argc : Integer;
4993 gnat_argv : System.Address;
4994 gnat_envp : System.Address;
4996 -- The actual variables are stored in a library routine. This
4997 -- is useful for some shared library situations, where there
4998 -- are problems if variables are not in the library.
5000 pragma Import (C, gnat_argc);
5001 pragma Import (C, gnat_argv);
5002 pragma Import (C, gnat_envp);
5004 -- The exit status is similarly an external location
5006 gnat_exit_status : Integer;
5007 pragma Import (C, gnat_exit_status);
5009 GNAT_Version : constant String :=
5010 "GNAT Version: 3.15w (20010315)";
5011 pragma Export (C, GNAT_Version, "__gnat_version");
5013 -- This is the generated adafinal routine that performs
5014 -- finalization at the end of execution. In the case where
5015 -- Ada is the main program, this main program makes a call
5016 -- to adafinal at program termination.
5019 pragma Export (C, adafinal, "adafinal");
5021 -- This is the generated adainit routine that performs
5022 -- initialization at the start of execution. In the case
5023 -- where Ada is the main program, this main program makes
5024 -- a call to adainit at program startup.
5027 pragma Export (C, adainit, "adainit");
5029 -- This routine is called at the start of execution. It is
5030 -- a dummy routine that is used by the debugger to breakpoint
5031 -- at the start of execution.
5033 procedure Break_Start;
5034 pragma Import (C, Break_Start, "__gnat_break_start");
5036 -- This is the actual generated main program (it would be
5037 -- suppressed if the no main program switch were used). As
5038 -- required by standard system conventions, this program has
5039 -- the external name main.
5043 argv : System.Address;
5044 envp : System.Address)
5046 pragma Export (C, main, "main");
5048 -- The following set of constants give the version
5049 -- identification values for every unit in the bound
5050 -- partition. This identification is computed from all
5051 -- dependent semantic units, and corresponds to the
5052 -- string that would be returned by use of the
5053 -- Body_Version or Version attributes.
5055 type Version_32 is mod 2 ** 32;
5056 u00001 : constant Version_32 := 16#7880BEB3#;
5057 u00002 : constant Version_32 := 16#0D24CBD0#;
5058 u00003 : constant Version_32 := 16#3283DBEB#;
5059 u00004 : constant Version_32 := 16#2359F9ED#;
5060 u00005 : constant Version_32 := 16#664FB847#;
5061 u00006 : constant Version_32 := 16#68E803DF#;
5062 u00007 : constant Version_32 := 16#5572E604#;
5063 u00008 : constant Version_32 := 16#46B173D8#;
5064 u00009 : constant Version_32 := 16#156A40CF#;
5065 u00010 : constant Version_32 := 16#033DABE0#;
5066 u00011 : constant Version_32 := 16#6AB38FEA#;
5067 u00012 : constant Version_32 := 16#22B6217D#;
5068 u00013 : constant Version_32 := 16#68A22947#;
5069 u00014 : constant Version_32 := 16#18CC4A56#;
5070 u00015 : constant Version_32 := 16#08258E1B#;
5071 u00016 : constant Version_32 := 16#367D5222#;
5072 u00017 : constant Version_32 := 16#20C9ECA4#;
5073 u00018 : constant Version_32 := 16#50D32CB6#;
5074 u00019 : constant Version_32 := 16#39A8BB77#;
5075 u00020 : constant Version_32 := 16#5CF8FA2B#;
5076 u00021 : constant Version_32 := 16#2F1EB794#;
5077 u00022 : constant Version_32 := 16#31AB6444#;
5078 u00023 : constant Version_32 := 16#1574B6E9#;
5079 u00024 : constant Version_32 := 16#5109C189#;
5080 u00025 : constant Version_32 := 16#56D770CD#;
5081 u00026 : constant Version_32 := 16#02F9DE3D#;
5082 u00027 : constant Version_32 := 16#08AB6B2C#;
5083 u00028 : constant Version_32 := 16#3FA37670#;
5084 u00029 : constant Version_32 := 16#476457A0#;
5085 u00030 : constant Version_32 := 16#731E1B6E#;
5086 u00031 : constant Version_32 := 16#23C2E789#;
5087 u00032 : constant Version_32 := 16#0F1BD6A1#;
5088 u00033 : constant Version_32 := 16#7C25DE96#;
5089 u00034 : constant Version_32 := 16#39ADFFA2#;
5090 u00035 : constant Version_32 := 16#571DE3E7#;
5091 u00036 : constant Version_32 := 16#5EB646AB#;
5092 u00037 : constant Version_32 := 16#4249379B#;
5093 u00038 : constant Version_32 := 16#0357E00A#;
5094 u00039 : constant Version_32 := 16#3784FB72#;
5095 u00040 : constant Version_32 := 16#2E723019#;
5096 u00041 : constant Version_32 := 16#623358EA#;
5097 u00042 : constant Version_32 := 16#107F9465#;
5098 u00043 : constant Version_32 := 16#6843F68A#;
5099 u00044 : constant Version_32 := 16#63305874#;
5100 u00045 : constant Version_32 := 16#31E56CE1#;
5101 u00046 : constant Version_32 := 16#02917970#;
5102 u00047 : constant Version_32 := 16#6CCBA70E#;
5103 u00048 : constant Version_32 := 16#41CD4204#;
5104 u00049 : constant Version_32 := 16#572E3F58#;
5105 u00050 : constant Version_32 := 16#20729FF5#;
5106 u00051 : constant Version_32 := 16#1D4F93E8#;
5107 u00052 : constant Version_32 := 16#30B2EC3D#;
5108 u00053 : constant Version_32 := 16#34054F96#;
5109 u00054 : constant Version_32 := 16#5A199860#;
5110 u00055 : constant Version_32 := 16#0E7F912B#;
5111 u00056 : constant Version_32 := 16#5760634A#;
5112 u00057 : constant Version_32 := 16#5D851835#;
5114 -- The following Export pragmas export the version numbers
5115 -- with symbolic names ending in B (for body) or S
5116 -- (for spec) so that they can be located in a link. The
5117 -- information provided here is sufficient to track down
5118 -- the exact versions of units used in a given build.
5120 pragma Export (C, u00001, "helloB");
5121 pragma Export (C, u00002, "system__standard_libraryB");
5122 pragma Export (C, u00003, "system__standard_libraryS");
5123 pragma Export (C, u00004, "adaS");
5124 pragma Export (C, u00005, "ada__text_ioB");
5125 pragma Export (C, u00006, "ada__text_ioS");
5126 pragma Export (C, u00007, "ada__exceptionsB");
5127 pragma Export (C, u00008, "ada__exceptionsS");
5128 pragma Export (C, u00009, "gnatS");
5129 pragma Export (C, u00010, "gnat__heap_sort_aB");
5130 pragma Export (C, u00011, "gnat__heap_sort_aS");
5131 pragma Export (C, u00012, "systemS");
5132 pragma Export (C, u00013, "system__exception_tableB");
5133 pragma Export (C, u00014, "system__exception_tableS");
5134 pragma Export (C, u00015, "gnat__htableB");
5135 pragma Export (C, u00016, "gnat__htableS");
5136 pragma Export (C, u00017, "system__exceptionsS");
5137 pragma Export (C, u00018, "system__machine_state_operationsB");
5138 pragma Export (C, u00019, "system__machine_state_operationsS");
5139 pragma Export (C, u00020, "system__machine_codeS");
5140 pragma Export (C, u00021, "system__storage_elementsB");
5141 pragma Export (C, u00022, "system__storage_elementsS");
5142 pragma Export (C, u00023, "system__secondary_stackB");
5143 pragma Export (C, u00024, "system__secondary_stackS");
5144 pragma Export (C, u00025, "system__parametersB");
5145 pragma Export (C, u00026, "system__parametersS");
5146 pragma Export (C, u00027, "system__soft_linksB");
5147 pragma Export (C, u00028, "system__soft_linksS");
5148 pragma Export (C, u00029, "system__stack_checkingB");
5149 pragma Export (C, u00030, "system__stack_checkingS");
5150 pragma Export (C, u00031, "system__tracebackB");
5151 pragma Export (C, u00032, "system__tracebackS");
5152 pragma Export (C, u00033, "ada__streamsS");
5153 pragma Export (C, u00034, "ada__tagsB");
5154 pragma Export (C, u00035, "ada__tagsS");
5155 pragma Export (C, u00036, "system__string_opsB");
5156 pragma Export (C, u00037, "system__string_opsS");
5157 pragma Export (C, u00038, "interfacesS");
5158 pragma Export (C, u00039, "interfaces__c_streamsB");
5159 pragma Export (C, u00040, "interfaces__c_streamsS");
5160 pragma Export (C, u00041, "system__file_ioB");
5161 pragma Export (C, u00042, "system__file_ioS");
5162 pragma Export (C, u00043, "ada__finalizationB");
5163 pragma Export (C, u00044, "ada__finalizationS");
5164 pragma Export (C, u00045, "system__finalization_rootB");
5165 pragma Export (C, u00046, "system__finalization_rootS");
5166 pragma Export (C, u00047, "system__finalization_implementationB");
5167 pragma Export (C, u00048, "system__finalization_implementationS");
5168 pragma Export (C, u00049, "system__string_ops_concat_3B");
5169 pragma Export (C, u00050, "system__string_ops_concat_3S");
5170 pragma Export (C, u00051, "system__stream_attributesB");
5171 pragma Export (C, u00052, "system__stream_attributesS");
5172 pragma Export (C, u00053, "ada__io_exceptionsS");
5173 pragma Export (C, u00054, "system__unsigned_typesS");
5174 pragma Export (C, u00055, "system__file_control_blockS");
5175 pragma Export (C, u00056, "ada__finalization__list_controllerB");
5176 pragma Export (C, u00057, "ada__finalization__list_controllerS");
5178 -- BEGIN ELABORATION ORDER
5181 -- gnat.heap_sort_a (spec)
5182 -- gnat.heap_sort_a (body)
5183 -- gnat.htable (spec)
5184 -- gnat.htable (body)
5185 -- interfaces (spec)
5187 -- system.machine_code (spec)
5188 -- system.parameters (spec)
5189 -- system.parameters (body)
5190 -- interfaces.c_streams (spec)
5191 -- interfaces.c_streams (body)
5192 -- system.standard_library (spec)
5193 -- ada.exceptions (spec)
5194 -- system.exception_table (spec)
5195 -- system.exception_table (body)
5196 -- ada.io_exceptions (spec)
5197 -- system.exceptions (spec)
5198 -- system.storage_elements (spec)
5199 -- system.storage_elements (body)
5200 -- system.machine_state_operations (spec)
5201 -- system.machine_state_operations (body)
5202 -- system.secondary_stack (spec)
5203 -- system.stack_checking (spec)
5204 -- system.soft_links (spec)
5205 -- system.soft_links (body)
5206 -- system.stack_checking (body)
5207 -- system.secondary_stack (body)
5208 -- system.standard_library (body)
5209 -- system.string_ops (spec)
5210 -- system.string_ops (body)
5213 -- ada.streams (spec)
5214 -- system.finalization_root (spec)
5215 -- system.finalization_root (body)
5216 -- system.string_ops_concat_3 (spec)
5217 -- system.string_ops_concat_3 (body)
5218 -- system.traceback (spec)
5219 -- system.traceback (body)
5220 -- ada.exceptions (body)
5221 -- system.unsigned_types (spec)
5222 -- system.stream_attributes (spec)
5223 -- system.stream_attributes (body)
5224 -- system.finalization_implementation (spec)
5225 -- system.finalization_implementation (body)
5226 -- ada.finalization (spec)
5227 -- ada.finalization (body)
5228 -- ada.finalization.list_controller (spec)
5229 -- ada.finalization.list_controller (body)
5230 -- system.file_control_block (spec)
5231 -- system.file_io (spec)
5232 -- system.file_io (body)
5233 -- ada.text_io (spec)
5234 -- ada.text_io (body)
5236 -- END ELABORATION ORDER
5240 -- The following source file name pragmas allow the generated file
5241 -- names to be unique for different main programs. They are needed
5242 -- since the package name will always be Ada_Main.
5244 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
5245 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
5247 -- Generated package body for Ada_Main starts here
5249 package body ada_main is
5251 -- The actual finalization is performed by calling the
5252 -- library routine in System.Standard_Library.Adafinal
5254 procedure Do_Finalize;
5255 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
5262 procedure adainit is
5264 -- These booleans are set to True once the associated unit has
5265 -- been elaborated. It is also used to avoid elaborating the
5268 E040 : Boolean; pragma Import (Ada, E040, "interfaces__c_streams_E");
5269 E008 : Boolean; pragma Import (Ada, E008, "ada__exceptions_E");
5270 E014 : Boolean; pragma Import (Ada, E014, "system__exception_table_E");
5271 E053 : Boolean; pragma Import (Ada, E053, "ada__io_exceptions_E");
5272 E017 : Boolean; pragma Import (Ada, E017, "system__exceptions_E");
5273 E024 : Boolean; pragma Import (Ada, E024, "system__secondary_stack_E");
5274 E030 : Boolean; pragma Import (Ada, E030, "system__stack_checking_E");
5275 E028 : Boolean; pragma Import (Ada, E028, "system__soft_links_E");
5276 E035 : Boolean; pragma Import (Ada, E035, "ada__tags_E");
5277 E033 : Boolean; pragma Import (Ada, E033, "ada__streams_E");
5278 E046 : Boolean; pragma Import (Ada, E046, "system__finalization_root_E");
5279 E048 : Boolean; pragma Import (Ada, E048, "system__finalization_implementation_E");
5280 E044 : Boolean; pragma Import (Ada, E044, "ada__finalization_E");
5281 E057 : Boolean; pragma Import (Ada, E057, "ada__finalization__list_controller_E");
5282 E055 : Boolean; pragma Import (Ada, E055, "system__file_control_block_E");
5283 E042 : Boolean; pragma Import (Ada, E042, "system__file_io_E");
5284 E006 : Boolean; pragma Import (Ada, E006, "ada__text_io_E");
5286 -- Set_Globals is a library routine that stores away the
5287 -- value of the indicated set of global values in global
5288 -- variables within the library.
5290 procedure Set_Globals
5291 (Main_Priority : Integer;
5292 Time_Slice_Value : Integer;
5293 WC_Encoding : Character;
5294 Locking_Policy : Character;
5295 Queuing_Policy : Character;
5296 Task_Dispatching_Policy : Character;
5297 Adafinal : System.Address;
5298 Unreserve_All_Interrupts : Integer;
5299 Exception_Tracebacks : Integer);
5300 @findex __gnat_set_globals
5301 pragma Import (C, Set_Globals, "__gnat_set_globals");
5303 -- SDP_Table_Build is a library routine used to build the
5304 -- exception tables. See unit Ada.Exceptions in files
5305 -- a-except.ads/adb for full details of how zero cost
5306 -- exception handling works. This procedure, the call to
5307 -- it, and the two following tables are all omitted if the
5308 -- build is in longjmp/setjump exception mode.
5310 @findex SDP_Table_Build
5311 @findex Zero Cost Exceptions
5312 procedure SDP_Table_Build
5313 (SDP_Addresses : System.Address;
5314 SDP_Count : Natural;
5315 Elab_Addresses : System.Address;
5316 Elab_Addr_Count : Natural);
5317 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
5319 -- Table of Unit_Exception_Table addresses. Used for zero
5320 -- cost exception handling to build the top level table.
5322 ST : aliased constant array (1 .. 23) of System.Address := (
5324 Ada.Text_Io'UET_Address,
5325 Ada.Exceptions'UET_Address,
5326 Gnat.Heap_Sort_A'UET_Address,
5327 System.Exception_Table'UET_Address,
5328 System.Machine_State_Operations'UET_Address,
5329 System.Secondary_Stack'UET_Address,
5330 System.Parameters'UET_Address,
5331 System.Soft_Links'UET_Address,
5332 System.Stack_Checking'UET_Address,
5333 System.Traceback'UET_Address,
5334 Ada.Streams'UET_Address,
5335 Ada.Tags'UET_Address,
5336 System.String_Ops'UET_Address,
5337 Interfaces.C_Streams'UET_Address,
5338 System.File_Io'UET_Address,
5339 Ada.Finalization'UET_Address,
5340 System.Finalization_Root'UET_Address,
5341 System.Finalization_Implementation'UET_Address,
5342 System.String_Ops_Concat_3'UET_Address,
5343 System.Stream_Attributes'UET_Address,
5344 System.File_Control_Block'UET_Address,
5345 Ada.Finalization.List_Controller'UET_Address);
5347 -- Table of addresses of elaboration routines. Used for
5348 -- zero cost exception handling to make sure these
5349 -- addresses are included in the top level procedure
5352 EA : aliased constant array (1 .. 23) of System.Address := (
5353 adainit'Code_Address,
5354 Do_Finalize'Code_Address,
5355 Ada.Exceptions'Elab_Spec'Address,
5356 System.Exceptions'Elab_Spec'Address,
5357 Interfaces.C_Streams'Elab_Spec'Address,
5358 System.Exception_Table'Elab_Body'Address,
5359 Ada.Io_Exceptions'Elab_Spec'Address,
5360 System.Stack_Checking'Elab_Spec'Address,
5361 System.Soft_Links'Elab_Body'Address,
5362 System.Secondary_Stack'Elab_Body'Address,
5363 Ada.Tags'Elab_Spec'Address,
5364 Ada.Tags'Elab_Body'Address,
5365 Ada.Streams'Elab_Spec'Address,
5366 System.Finalization_Root'Elab_Spec'Address,
5367 Ada.Exceptions'Elab_Body'Address,
5368 System.Finalization_Implementation'Elab_Spec'Address,
5369 System.Finalization_Implementation'Elab_Body'Address,
5370 Ada.Finalization'Elab_Spec'Address,
5371 Ada.Finalization.List_Controller'Elab_Spec'Address,
5372 System.File_Control_Block'Elab_Spec'Address,
5373 System.File_Io'Elab_Body'Address,
5374 Ada.Text_Io'Elab_Spec'Address,
5375 Ada.Text_Io'Elab_Body'Address);
5377 -- Start of processing for adainit
5381 -- Call SDP_Table_Build to build the top level procedure
5382 -- table for zero cost exception handling (omitted in
5383 -- longjmp/setjump mode).
5385 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
5387 -- Call Set_Globals to record various information for
5388 -- this partition. The values are derived by the binder
5389 -- from information stored in the ali files by the compiler.
5391 @findex __gnat_set_globals
5393 (Main_Priority => -1,
5394 -- Priority of main program, -1 if no pragma Priority used
5396 Time_Slice_Value => -1,
5397 -- Time slice from Time_Slice pragma, -1 if none used
5400 -- Wide_Character encoding used, default is brackets
5402 Locking_Policy => ' ',
5403 -- Locking_Policy used, default of space means not
5404 -- specified, otherwise it is the first character of
5407 Queuing_Policy => ' ',
5408 -- Queuing_Policy used, default of space means not
5409 -- specified, otherwise it is the first character of
5412 Task_Dispatching_Policy => ' ',
5413 -- Task_Dispatching_Policy used, default of space means
5414 -- not specified, otherwise first character of the
5417 Adafinal => System.Null_Address,
5418 -- Address of Adafinal routine, not used anymore
5420 Unreserve_All_Interrupts => 0,
5421 -- Set true if pragma Unreserve_All_Interrupts was used
5423 Exception_Tracebacks => 0);
5424 -- Indicates if exception tracebacks are enabled
5426 Elab_Final_Code := 1;
5428 -- Now we have the elaboration calls for all units in the partition.
5429 -- The Elab_Spec and Elab_Body attributes generate references to the
5430 -- implicit elaboration procedures generated by the compiler for
5431 -- each unit that requires elaboration.
5434 Interfaces.C_Streams'Elab_Spec;
5438 Ada.Exceptions'Elab_Spec;
5441 System.Exception_Table'Elab_Body;
5445 Ada.Io_Exceptions'Elab_Spec;
5449 System.Exceptions'Elab_Spec;
5453 System.Stack_Checking'Elab_Spec;
5456 System.Soft_Links'Elab_Body;
5461 System.Secondary_Stack'Elab_Body;
5472 Ada.Streams'Elab_Spec;
5476 System.Finalization_Root'Elab_Spec;
5480 Ada.Exceptions'Elab_Body;
5484 System.Finalization_Implementation'Elab_Spec;
5487 System.Finalization_Implementation'Elab_Body;
5491 Ada.Finalization'Elab_Spec;
5495 Ada.Finalization.List_Controller'Elab_Spec;
5499 System.File_Control_Block'Elab_Spec;
5503 System.File_Io'Elab_Body;
5507 Ada.Text_Io'Elab_Spec;
5510 Ada.Text_Io'Elab_Body;
5514 Elab_Final_Code := 0;
5522 procedure adafinal is
5531 -- main is actually a function, as in the ANSI C standard,
5532 -- defined to return the exit status. The three parameters
5533 -- are the argument count, argument values and environment
5536 @findex Main Program
5539 argv : System.Address;
5540 envp : System.Address)
5543 -- The initialize routine performs low level system
5544 -- initialization using a standard library routine which
5545 -- sets up signal handling and performs any other
5546 -- required setup. The routine can be found in file
5549 @findex __gnat_initialize
5550 procedure initialize;
5551 pragma Import (C, initialize, "__gnat_initialize");
5553 -- The finalize routine performs low level system
5554 -- finalization using a standard library routine. The
5555 -- routine is found in file a-final.c and in the standard
5556 -- distribution is a dummy routine that does nothing, so
5557 -- really this is a hook for special user finalization.
5559 @findex __gnat_finalize
5561 pragma Import (C, finalize, "__gnat_finalize");
5563 -- We get to the main program of the partition by using
5564 -- pragma Import because if we try to with the unit and
5565 -- call it Ada style, then not only do we waste time
5566 -- recompiling it, but also, we don't really know the right
5567 -- switches (e.g. identifier character set) to be used
5570 procedure Ada_Main_Program;
5571 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
5573 -- Start of processing for main
5576 -- Save global variables
5582 -- Call low level system initialization
5586 -- Call our generated Ada initialization routine
5590 -- This is the point at which we want the debugger to get
5595 -- Now we call the main program of the partition
5599 -- Perform Ada finalization
5603 -- Perform low level system finalization
5607 -- Return the proper exit status
5608 return (gnat_exit_status);
5611 -- This section is entirely comments, so it has no effect on the
5612 -- compilation of the Ada_Main package. It provides the list of
5613 -- object files and linker options, as well as some standard
5614 -- libraries needed for the link. The gnatlink utility parses
5615 -- this b~hello.adb file to read these comment lines to generate
5616 -- the appropriate command line arguments for the call to the
5617 -- system linker. The BEGIN/END lines are used for sentinels for
5618 -- this parsing operation.
5620 -- The exact file names will of course depend on the environment,
5621 -- host/target and location of files on the host system.
5623 @findex Object file list
5624 -- BEGIN Object file/option list
5627 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
5628 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
5629 -- END Object file/option list
5636 The Ada code in the above example is exactly what is generated by the
5637 binder. We have added comments to more clearly indicate the function
5638 of each part of the generated @code{Ada_Main} package.
5640 The code is standard Ada in all respects, and can be processed by any
5641 tools that handle Ada. In particular, it is possible to use the debugger
5642 in Ada mode to debug the generated Ada_Main package. For example, suppose
5643 that for reasons that you do not understand, your program is blowing up
5644 during elaboration of the body of @code{Ada.Text_IO}. To chase this bug
5645 down, you can place a breakpoint on the call:
5648 Ada.Text_Io'Elab_Body;
5652 and trace the elaboration routine for this package to find out where
5653 the problem might be (more usually of course you would be debugging
5654 elaboration code in your own application).
5656 @node Generating the Binder Program in C
5657 @section Generating the Binder Program in C
5659 In most normal usage, the default mode of @code{gnatbind} which is to
5660 generate the main package in Ada, as described in the previous section.
5661 In particular, this means that any Ada programmer can read and understand
5662 the generated main program. It can also be debugged just like any other
5663 Ada code provided the @code{-g} switch is used for @code{gnatbind}
5664 and @code{gnatlink}.
5666 However for some purposes it may be convenient to generate the main
5667 program in C rather than Ada. This may for example be helpful when you
5668 are generating a mixed language program with the main program in C. The
5669 GNAT compiler itself is an example. The use of the @code{-C} switch
5670 for both @code{gnatbind} and @code{gnatlink} will cause the program to
5671 be generated in C (and compiled using the gnu C compiler). The
5672 following shows the C code generated for the same "Hello World"
5678 #define PARAMS(paramlist) paramlist
5680 #define PARAMS(paramlist) ()
5683 extern void __gnat_set_globals
5684 PARAMS ((int, int, int, int, int, int,
5685 void (*) PARAMS ((void)), int, int));
5686 extern void adafinal PARAMS ((void));
5687 extern void adainit PARAMS ((void));
5688 extern void system__standard_library__adafinal PARAMS ((void));
5689 extern int main PARAMS ((int, char **, char **));
5690 extern void exit PARAMS ((int));
5691 extern void __gnat_break_start PARAMS ((void));
5692 extern void _ada_hello PARAMS ((void));
5693 extern void __gnat_initialize PARAMS ((void));
5694 extern void __gnat_finalize PARAMS ((void));
5696 extern void ada__exceptions___elabs PARAMS ((void));
5697 extern void system__exceptions___elabs PARAMS ((void));
5698 extern void interfaces__c_streams___elabs PARAMS ((void));
5699 extern void system__exception_table___elabb PARAMS ((void));
5700 extern void ada__io_exceptions___elabs PARAMS ((void));
5701 extern void system__stack_checking___elabs PARAMS ((void));
5702 extern void system__soft_links___elabb PARAMS ((void));
5703 extern void system__secondary_stack___elabb PARAMS ((void));
5704 extern void ada__tags___elabs PARAMS ((void));
5705 extern void ada__tags___elabb PARAMS ((void));
5706 extern void ada__streams___elabs PARAMS ((void));
5707 extern void system__finalization_root___elabs PARAMS ((void));
5708 extern void ada__exceptions___elabb PARAMS ((void));
5709 extern void system__finalization_implementation___elabs PARAMS ((void));
5710 extern void system__finalization_implementation___elabb PARAMS ((void));
5711 extern void ada__finalization___elabs PARAMS ((void));
5712 extern void ada__finalization__list_controller___elabs PARAMS ((void));
5713 extern void system__file_control_block___elabs PARAMS ((void));
5714 extern void system__file_io___elabb PARAMS ((void));
5715 extern void ada__text_io___elabs PARAMS ((void));
5716 extern void ada__text_io___elabb PARAMS ((void));
5718 extern int __gnat_inside_elab_final_code;
5720 extern int gnat_argc;
5721 extern char **gnat_argv;
5722 extern char **gnat_envp;
5723 extern int gnat_exit_status;
5725 char __gnat_version[] = "GNAT Version: 3.15w (20010315)";
5727 system__standard_library__adafinal ();
5732 extern char ada__exceptions_E;
5733 extern char system__exceptions_E;
5734 extern char interfaces__c_streams_E;
5735 extern char system__exception_table_E;
5736 extern char ada__io_exceptions_E;
5737 extern char system__secondary_stack_E;
5738 extern char system__stack_checking_E;
5739 extern char system__soft_links_E;
5740 extern char ada__tags_E;
5741 extern char ada__streams_E;
5742 extern char system__finalization_root_E;
5743 extern char system__finalization_implementation_E;
5744 extern char ada__finalization_E;
5745 extern char ada__finalization__list_controller_E;
5746 extern char system__file_control_block_E;
5747 extern char system__file_io_E;
5748 extern char ada__text_io_E;
5750 extern void *__gnat_hello__SDP;
5751 extern void *__gnat_ada__text_io__SDP;
5752 extern void *__gnat_ada__exceptions__SDP;
5753 extern void *__gnat_gnat__heap_sort_a__SDP;
5754 extern void *__gnat_system__exception_table__SDP;
5755 extern void *__gnat_system__machine_state_operations__SDP;
5756 extern void *__gnat_system__secondary_stack__SDP;
5757 extern void *__gnat_system__parameters__SDP;
5758 extern void *__gnat_system__soft_links__SDP;
5759 extern void *__gnat_system__stack_checking__SDP;
5760 extern void *__gnat_system__traceback__SDP;
5761 extern void *__gnat_ada__streams__SDP;
5762 extern void *__gnat_ada__tags__SDP;
5763 extern void *__gnat_system__string_ops__SDP;
5764 extern void *__gnat_interfaces__c_streams__SDP;
5765 extern void *__gnat_system__file_io__SDP;
5766 extern void *__gnat_ada__finalization__SDP;
5767 extern void *__gnat_system__finalization_root__SDP;
5768 extern void *__gnat_system__finalization_implementation__SDP;
5769 extern void *__gnat_system__string_ops_concat_3__SDP;
5770 extern void *__gnat_system__stream_attributes__SDP;
5771 extern void *__gnat_system__file_control_block__SDP;
5772 extern void *__gnat_ada__finalization__list_controller__SDP;
5776 &__gnat_ada__text_io__SDP,
5777 &__gnat_ada__exceptions__SDP,
5778 &__gnat_gnat__heap_sort_a__SDP,
5779 &__gnat_system__exception_table__SDP,
5780 &__gnat_system__machine_state_operations__SDP,
5781 &__gnat_system__secondary_stack__SDP,
5782 &__gnat_system__parameters__SDP,
5783 &__gnat_system__soft_links__SDP,
5784 &__gnat_system__stack_checking__SDP,
5785 &__gnat_system__traceback__SDP,
5786 &__gnat_ada__streams__SDP,
5787 &__gnat_ada__tags__SDP,
5788 &__gnat_system__string_ops__SDP,
5789 &__gnat_interfaces__c_streams__SDP,
5790 &__gnat_system__file_io__SDP,
5791 &__gnat_ada__finalization__SDP,
5792 &__gnat_system__finalization_root__SDP,
5793 &__gnat_system__finalization_implementation__SDP,
5794 &__gnat_system__string_ops_concat_3__SDP,
5795 &__gnat_system__stream_attributes__SDP,
5796 &__gnat_system__file_control_block__SDP,
5797 &__gnat_ada__finalization__list_controller__SDP@};
5799 extern void ada__exceptions___elabs ();
5800 extern void system__exceptions___elabs ();
5801 extern void interfaces__c_streams___elabs ();
5802 extern void system__exception_table___elabb ();
5803 extern void ada__io_exceptions___elabs ();
5804 extern void system__stack_checking___elabs ();
5805 extern void system__soft_links___elabb ();
5806 extern void system__secondary_stack___elabb ();
5807 extern void ada__tags___elabs ();
5808 extern void ada__tags___elabb ();
5809 extern void ada__streams___elabs ();
5810 extern void system__finalization_root___elabs ();
5811 extern void ada__exceptions___elabb ();
5812 extern void system__finalization_implementation___elabs ();
5813 extern void system__finalization_implementation___elabb ();
5814 extern void ada__finalization___elabs ();
5815 extern void ada__finalization__list_controller___elabs ();
5816 extern void system__file_control_block___elabs ();
5817 extern void system__file_io___elabb ();
5818 extern void ada__text_io___elabs ();
5819 extern void ada__text_io___elabb ();
5821 void (*ea[23]) () = @{
5823 system__standard_library__adafinal,
5824 ada__exceptions___elabs,
5825 system__exceptions___elabs,
5826 interfaces__c_streams___elabs,
5827 system__exception_table___elabb,
5828 ada__io_exceptions___elabs,
5829 system__stack_checking___elabs,
5830 system__soft_links___elabb,
5831 system__secondary_stack___elabb,
5834 ada__streams___elabs,
5835 system__finalization_root___elabs,
5836 ada__exceptions___elabb,
5837 system__finalization_implementation___elabs,
5838 system__finalization_implementation___elabb,
5839 ada__finalization___elabs,
5840 ada__finalization__list_controller___elabs,
5841 system__file_control_block___elabs,
5842 system__file_io___elabb,
5843 ada__text_io___elabs,
5844 ada__text_io___elabb@};
5846 __gnat_SDP_Table_Build (&st, 23, ea, 23);
5847 __gnat_set_globals (
5848 -1, /* Main_Priority */
5849 -1, /* Time_Slice_Value */
5850 'b', /* WC_Encoding */
5851 ' ', /* Locking_Policy */
5852 ' ', /* Queuing_Policy */
5853 ' ', /* Tasking_Dispatching_Policy */
5854 0, /* Finalization routine address, not used anymore */
5855 0, /* Unreserve_All_Interrupts */
5856 0); /* Exception_Tracebacks */
5858 __gnat_inside_elab_final_code = 1;
5860 if (ada__exceptions_E == 0) @{
5861 ada__exceptions___elabs ();
5863 if (system__exceptions_E == 0) @{
5864 system__exceptions___elabs ();
5865 system__exceptions_E++;
5867 if (interfaces__c_streams_E == 0) @{
5868 interfaces__c_streams___elabs ();
5870 interfaces__c_streams_E = 1;
5871 if (system__exception_table_E == 0) @{
5872 system__exception_table___elabb ();
5873 system__exception_table_E++;
5875 if (ada__io_exceptions_E == 0) @{
5876 ada__io_exceptions___elabs ();
5877 ada__io_exceptions_E++;
5879 if (system__stack_checking_E == 0) @{
5880 system__stack_checking___elabs ();
5882 if (system__soft_links_E == 0) @{
5883 system__soft_links___elabb ();
5884 system__soft_links_E++;
5886 system__stack_checking_E = 1;
5887 if (system__secondary_stack_E == 0) @{
5888 system__secondary_stack___elabb ();
5889 system__secondary_stack_E++;
5891 if (ada__tags_E == 0) @{
5892 ada__tags___elabs ();
5894 if (ada__tags_E == 0) @{
5895 ada__tags___elabb ();
5898 if (ada__streams_E == 0) @{
5899 ada__streams___elabs ();
5902 if (system__finalization_root_E == 0) @{
5903 system__finalization_root___elabs ();
5905 system__finalization_root_E = 1;
5906 if (ada__exceptions_E == 0) @{
5907 ada__exceptions___elabb ();
5908 ada__exceptions_E++;
5910 if (system__finalization_implementation_E == 0) @{
5911 system__finalization_implementation___elabs ();
5913 if (system__finalization_implementation_E == 0) @{
5914 system__finalization_implementation___elabb ();
5915 system__finalization_implementation_E++;
5917 if (ada__finalization_E == 0) @{
5918 ada__finalization___elabs ();
5920 ada__finalization_E = 1;
5921 if (ada__finalization__list_controller_E == 0) @{
5922 ada__finalization__list_controller___elabs ();
5924 ada__finalization__list_controller_E = 1;
5925 if (system__file_control_block_E == 0) @{
5926 system__file_control_block___elabs ();
5927 system__file_control_block_E++;
5929 if (system__file_io_E == 0) @{
5930 system__file_io___elabb ();
5931 system__file_io_E++;
5933 if (ada__text_io_E == 0) @{
5934 ada__text_io___elabs ();
5936 if (ada__text_io_E == 0) @{
5937 ada__text_io___elabb ();
5941 __gnat_inside_elab_final_code = 0;
5943 int main (argc, argv, envp)
5952 __gnat_initialize ();
5954 __gnat_break_start ();
5958 system__standard_library__adafinal ();
5960 exit (gnat_exit_status);
5962 unsigned helloB = 0x7880BEB3;
5963 unsigned system__standard_libraryB = 0x0D24CBD0;
5964 unsigned system__standard_libraryS = 0x3283DBEB;
5965 unsigned adaS = 0x2359F9ED;
5966 unsigned ada__text_ioB = 0x47C85FC4;
5967 unsigned ada__text_ioS = 0x496FE45C;
5968 unsigned ada__exceptionsB = 0x74F50187;
5969 unsigned ada__exceptionsS = 0x6736945B;
5970 unsigned gnatS = 0x156A40CF;
5971 unsigned gnat__heap_sort_aB = 0x033DABE0;
5972 unsigned gnat__heap_sort_aS = 0x6AB38FEA;
5973 unsigned systemS = 0x0331C6FE;
5974 unsigned system__exceptionsS = 0x20C9ECA4;
5975 unsigned system__exception_tableB = 0x68A22947;
5976 unsigned system__exception_tableS = 0x394BADD5;
5977 unsigned gnat__htableB = 0x08258E1B;
5978 unsigned gnat__htableS = 0x367D5222;
5979 unsigned system__machine_state_operationsB = 0x4F3B7492;
5980 unsigned system__machine_state_operationsS = 0x182F5CF4;
5981 unsigned system__storage_elementsB = 0x2F1EB794;
5982 unsigned system__storage_elementsS = 0x102C83C7;
5983 unsigned system__secondary_stackB = 0x1574B6E9;
5984 unsigned system__secondary_stackS = 0x708E260A;
5985 unsigned system__parametersB = 0x56D770CD;
5986 unsigned system__parametersS = 0x237E39BE;
5987 unsigned system__soft_linksB = 0x08AB6B2C;
5988 unsigned system__soft_linksS = 0x1E2491F3;
5989 unsigned system__stack_checkingB = 0x476457A0;
5990 unsigned system__stack_checkingS = 0x5299FCED;
5991 unsigned system__tracebackB = 0x2971EBDE;
5992 unsigned system__tracebackS = 0x2E9C3122;
5993 unsigned ada__streamsS = 0x7C25DE96;
5994 unsigned ada__tagsB = 0x39ADFFA2;
5995 unsigned ada__tagsS = 0x769A0464;
5996 unsigned system__string_opsB = 0x5EB646AB;
5997 unsigned system__string_opsS = 0x63CED018;
5998 unsigned interfacesS = 0x0357E00A;
5999 unsigned interfaces__c_streamsB = 0x3784FB72;
6000 unsigned interfaces__c_streamsS = 0x2E723019;
6001 unsigned system__file_ioB = 0x623358EA;
6002 unsigned system__file_ioS = 0x31F873E6;
6003 unsigned ada__finalizationB = 0x6843F68A;
6004 unsigned ada__finalizationS = 0x63305874;
6005 unsigned system__finalization_rootB = 0x31E56CE1;
6006 unsigned system__finalization_rootS = 0x23169EF3;
6007 unsigned system__finalization_implementationB = 0x6CCBA70E;
6008 unsigned system__finalization_implementationS = 0x604AA587;
6009 unsigned system__string_ops_concat_3B = 0x572E3F58;
6010 unsigned system__string_ops_concat_3S = 0x01F57876;
6011 unsigned system__stream_attributesB = 0x1D4F93E8;
6012 unsigned system__stream_attributesS = 0x30B2EC3D;
6013 unsigned ada__io_exceptionsS = 0x34054F96;
6014 unsigned system__unsigned_typesS = 0x7B9E7FE3;
6015 unsigned system__file_control_blockS = 0x2FF876A8;
6016 unsigned ada__finalization__list_controllerB = 0x5760634A;
6017 unsigned ada__finalization__list_controllerS = 0x5D851835;
6019 /* BEGIN ELABORATION ORDER
6022 gnat.heap_sort_a (spec)
6027 system.parameters (spec)
6028 system.standard_library (spec)
6029 ada.exceptions (spec)
6030 system.exceptions (spec)
6031 system.parameters (body)
6032 gnat.heap_sort_a (body)
6033 interfaces.c_streams (spec)
6034 interfaces.c_streams (body)
6035 system.exception_table (spec)
6036 system.exception_table (body)
6037 ada.io_exceptions (spec)
6038 system.storage_elements (spec)
6039 system.storage_elements (body)
6040 system.machine_state_operations (spec)
6041 system.machine_state_operations (body)
6042 system.secondary_stack (spec)
6043 system.stack_checking (spec)
6044 system.soft_links (spec)
6045 system.soft_links (body)
6046 system.stack_checking (body)
6047 system.secondary_stack (body)
6048 system.standard_library (body)
6049 system.string_ops (spec)
6050 system.string_ops (body)
6054 system.finalization_root (spec)
6055 system.finalization_root (body)
6056 system.string_ops_concat_3 (spec)
6057 system.string_ops_concat_3 (body)
6058 system.traceback (spec)
6059 system.traceback (body)
6060 ada.exceptions (body)
6061 system.unsigned_types (spec)
6062 system.stream_attributes (spec)
6063 system.stream_attributes (body)
6064 system.finalization_implementation (spec)
6065 system.finalization_implementation (body)
6066 ada.finalization (spec)
6067 ada.finalization (body)
6068 ada.finalization.list_controller (spec)
6069 ada.finalization.list_controller (body)
6070 system.file_control_block (spec)
6071 system.file_io (spec)
6072 system.file_io (body)
6076 END ELABORATION ORDER */
6078 /* BEGIN Object file/option list
6081 -L/usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/
6082 /usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/libgnat.a
6084 END Object file/option list */
6089 Here again, the C code is exactly what is generated by the binder. The
6090 functions of the various parts of this code correspond in an obvious
6091 manner with the commented Ada code shown in the example in the previous
6094 @node Consistency-Checking Modes
6095 @section Consistency-Checking Modes
6098 As described in the previous section, by default @code{gnatbind} checks
6099 that object files are consistent with one another and are consistent
6100 with any source files it can locate. The following switches control binder
6105 @cindex @code{-s} (@code{gnatbind})
6106 Require source files to be present. In this mode, the binder must be
6107 able to locate all source files that are referenced, in order to check
6108 their consistency. In normal mode, if a source file cannot be located it
6109 is simply ignored. If you specify this switch, a missing source
6113 @cindex @code{-x} (@code{gnatbind})
6114 Exclude source files. In this mode, the binder only checks that ALI
6115 files are consistent with one another. Source files are not accessed.
6116 The binder runs faster in this mode, and there is still a guarantee that
6117 the resulting program is self-consistent.
6118 If a source file has been edited since it was last compiled, and you
6119 specify this switch, the binder will not detect that the object
6120 file is out of date with respect to the source file. Note that this is the
6121 mode that is automatically used by @code{gnatmake} because in this
6122 case the checking against sources has already been performed by
6123 @code{gnatmake} in the course of compilation (i.e. before binding).
6127 @node Binder Error Message Control
6128 @section Binder Error Message Control
6131 The following switches provide control over the generation of error
6132 messages from the binder:
6136 @cindex @code{-v} (@code{gnatbind})
6137 Verbose mode. In the normal mode, brief error messages are generated to
6138 @file{stderr}. If this switch is present, a header is written
6139 to @file{stdout} and any error messages are directed to @file{stdout}.
6140 All that is written to @file{stderr} is a brief summary message.
6143 @cindex @code{-b} (@code{gnatbind})
6144 Generate brief error messages to @file{stderr} even if verbose mode is
6145 specified. This is relevant only when used with the
6149 @cindex @code{-m} (@code{gnatbind})
6150 Limits the number of error messages to @var{n}, a decimal integer in the
6151 range 1-999. The binder terminates immediately if this limit is reached.
6154 @cindex @code{-M} (@code{gnatbind})
6155 Renames the generated main program from @code{main} to @code{xxx}.
6156 This is useful in the case of some cross-building environments, where
6157 the actual main program is separate from the one generated
6161 @cindex @code{-ws} (@code{gnatbind})
6163 Suppress all warning messages.
6166 @cindex @code{-we} (@code{gnatbind})
6167 Treat any warning messages as fatal errors.
6171 @cindex @code{-t} (@code{gnatbind})
6172 @cindex Time stamp checks, in binder
6173 @cindex Binder consistency checks
6174 @cindex Consistency checks, in binder
6175 The binder performs a number of consistency checks including:
6179 Check that time stamps of a given source unit are consistent
6181 Check that checksums of a given source unit are consistent
6183 Check that consistent versions of @code{GNAT} were used for compilation
6185 Check consistency of configuration pragmas as required
6189 Normally failure of such checks, in accordance with the consistency
6190 requirements of the Ada Reference Manual, causes error messages to be
6191 generated which abort the binder and prevent the output of a binder
6192 file and subsequent link to obtain an executable.
6194 The @code{-t} switch converts these error messages
6195 into warnings, so that
6196 binding and linking can continue to completion even in the presence of such
6197 errors. The result may be a failed link (due to missing symbols), or a
6198 non-functional executable which has undefined semantics.
6199 @emph{This means that
6200 @code{-t} should be used only in unusual situations,
6204 @node Elaboration Control
6205 @section Elaboration Control
6208 The following switches provide additional control over the elaboration
6209 order. For full details see @xref{Elaboration Order Handling in GNAT}.
6213 @cindex @code{-h} (@code{gnatbind})
6214 Normally the binder attempts to choose an elaboration order that is
6215 likely to minimize the likelihood of an elaboration order error resulting
6216 in raising a @code{Program_Error} exception. This switch reverses the
6217 action of the binder, and requests that it deliberately choose an order
6218 that is likely to maximize the likelihood of an elaboration error.
6219 This is useful in ensuring portability and avoiding dependence on
6220 accidental fortuitous elaboration ordering.
6222 Normally it only makes sense to use the @code{-p} switch if dynamic
6223 elaboration checking is used (@option{-gnatE} switch used for compilation).
6224 This is because in the default static elaboration mode, all necessary
6225 @code{Elaborate_All} pragmas are implicitly inserted. These implicit
6226 pragmas are still respected by the binder in @code{-p} mode, so a
6227 safe elaboration order is assured.
6230 @node Output Control
6231 @section Output Control
6234 The following switches allow additional control over the output
6235 generated by the binder.
6240 @cindex @code{-A} (@code{gnatbind})
6241 Generate binder program in Ada (default). The binder program is named
6242 @file{b~@var{mainprog}.adb} by default. This can be changed with
6243 @code{-o} @code{gnatbind} option.
6246 @cindex @code{-c} (@code{gnatbind})
6247 Check only. Do not generate the binder output file. In this mode the
6248 binder performs all error checks but does not generate an output file.
6251 @cindex @code{-C} (@code{gnatbind})
6252 Generate binder program in C. The binder program is named
6253 @file{b_@var{mainprog}.c}. This can be changed with @code{-o} @code{gnatbind}
6257 @cindex @code{-e} (@code{gnatbind})
6258 Output complete list of elaboration-order dependencies, showing the
6259 reason for each dependency. This output can be rather extensive but may
6260 be useful in diagnosing problems with elaboration order. The output is
6261 written to @file{stdout}.
6264 @cindex @code{-h} (@code{gnatbind})
6265 Output usage information. The output is written to @file{stdout}.
6268 @cindex @code{-K} (@code{gnatbind})
6269 Output linker options to @file{stdout}. Includes library search paths,
6270 contents of pragmas Ident and Linker_Options, and libraries added
6274 @cindex @code{-l} (@code{gnatbind})
6275 Output chosen elaboration order. The output is written to @file{stdout}.
6278 @cindex @code{-O} (@code{gnatbind})
6279 Output full names of all the object files that must be linked to provide
6280 the Ada component of the program. The output is written to @file{stdout}.
6281 This list includes the files explicitly supplied and referenced by the user
6282 as well as implicitly referenced run-time unit files. The latter are
6283 omitted if the corresponding units reside in shared libraries. The
6284 directory names for the run-time units depend on the system configuration.
6287 @cindex @code{-o} (@code{gnatbind})
6288 Set name of output file to @var{file} instead of the normal
6289 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
6290 binder generated body filename. In C mode you would normally give
6291 @var{file} an extension of @file{.c} because it will be a C source program.
6292 Note that if this option is used, then linking must be done manually.
6293 It is not possible to use gnatlink in this case, since it cannot locate
6297 @cindex @code{-r} (@code{gnatbind})
6298 Generate list of @code{pragma Rerstrictions} that could be applied to
6299 the current unit. This is useful for code audit purposes, and also may
6300 be used to improve code generation in some cases.
6304 @node Binding with Non-Ada Main Programs
6305 @section Binding with Non-Ada Main Programs
6308 In our description so far we have assumed that the main
6309 program is in Ada, and that the task of the binder is to generate a
6310 corresponding function @code{main} that invokes this Ada main
6311 program. GNAT also supports the building of executable programs where
6312 the main program is not in Ada, but some of the called routines are
6313 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
6314 The following switch is used in this situation:
6318 @cindex @code{-n} (@code{gnatbind})
6319 No main program. The main program is not in Ada.
6323 In this case, most of the functions of the binder are still required,
6324 but instead of generating a main program, the binder generates a file
6325 containing the following callable routines:
6330 You must call this routine to initialize the Ada part of the program by
6331 calling the necessary elaboration routines. A call to @code{adainit} is
6332 required before the first call to an Ada subprogram.
6334 Note that it is assumed that the basic execution environment must be setup
6335 to be appropriate for Ada execution at the point where the first Ada
6336 subprogram is called. In particular, if the Ada code will do any
6337 floating-point operations, then the FPU must be setup in an appropriate
6338 manner. For the case of the x86, for example, full precision mode is
6339 required. The procedure GNAT.Float_Control.Reset may be used to ensure
6340 that the FPU is in the right state.
6344 You must call this routine to perform any library-level finalization
6345 required by the Ada subprograms. A call to @code{adafinal} is required
6346 after the last call to an Ada subprogram, and before the program
6351 If the @code{-n} switch
6352 @cindex Binder, multiple input files
6353 is given, more than one ALI file may appear on
6354 the command line for @code{gnatbind}. The normal @dfn{closure}
6355 calculation is performed for each of the specified units. Calculating
6356 the closure means finding out the set of units involved by tracing
6357 @code{with} references. The reason it is necessary to be able to
6358 specify more than one ALI file is that a given program may invoke two or
6359 more quite separate groups of Ada units.
6361 The binder takes the name of its output file from the last specified ALI
6362 file, unless overridden by the use of the @code{-o file}.
6363 The output is an Ada unit in source form that can
6364 be compiled with GNAT unless the -C switch is used in which case the
6365 output is a C source file, which must be compiled using the C compiler.
6366 This compilation occurs automatically as part of the @code{gnatlink}
6369 Currently the GNAT run time requires a FPU using 80 bits mode
6370 precision. Under targets where this is not the default it is required to
6371 call GNAT.Float_Control.Reset before using floating point numbers (this
6372 include float computation, float input and output) in the Ada code. A
6373 side effect is that this could be the wrong mode for the foreign code
6374 where floating point computation could be broken after this call.
6376 @node Binding Programs with No Main Subprogram
6377 @section Binding Programs with No Main Subprogram
6380 It is possible to have an Ada program which does not have a main
6381 subprogram. This program will call the elaboration routines of all the
6382 packages, then the finalization routines.
6384 The following switch is used to bind programs organized in this manner:
6388 @cindex @code{-z} (@code{gnatbind})
6389 Normally the binder checks that the unit name given on the command line
6390 corresponds to a suitable main subprogram. When this switch is used,
6391 a list of ALI files can be given, and the execution of the program
6392 consists of elaboration of these units in an appropriate order.
6395 @node Summary of Binder Switches
6396 @section Summary of Binder Switches
6399 The following are the switches available with @code{gnatbind}:
6403 Specify directory to be searched for ALI files.
6406 Specify directory to be searched for source file.
6409 Generate binder program in Ada (default)
6412 Generate brief messages to @file{stderr} even if verbose mode set.
6415 Check only, no generation of binder output file.
6418 Generate binder program in C
6421 Output complete list of elaboration-order dependencies.
6424 Store tracebacks in exception occurrences when the target supports it.
6425 This is the default with the zero cost exception mechanism.
6426 This option is currently supported on the following targets:
6427 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
6428 See also the packages @code{GNAT.Traceback} and
6429 @code{GNAT.Traceback.Symbolic} for more information.
6430 Note that on x86 ports, you must not use @code{-fomit-frame-pointer}
6434 Output usage (help) information
6437 Specify directory to be searched for source and ALI files.
6440 Do not look for sources in the current directory where @code{gnatbind} was
6441 invoked, and do not look for ALI files in the directory containing the
6442 ALI file named in the @code{gnatbind} command line.
6445 Output chosen elaboration order.
6448 Binds the units for library building. In this case the adainit and
6449 adafinal procedures (See @pxref{Binding with Non-Ada Main Programs})
6450 are renamed to xxxinit and xxxfinal. Implies -n.
6451 See @pxref{GNAT and Libraries} for more details.
6454 Rename generated main program from main to xyz
6457 Limit number of detected errors to @var{n} (1-999).
6463 Do not look for sources in the system default directory.
6466 Do not look for library files in the system default directory.
6468 @item --RTS=@var{rts-path}
6469 @cindex @code{--RTS} (@code{gnatbind})
6470 Specifies the default location of the runtime library. Same meaning as the
6471 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
6474 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
6475 Note that if this option is used, then linking must be done manually,
6476 gnatlink cannot be used.
6482 Pessimistic (worst-case) elaboration order
6485 Require all source files to be present.
6488 Link against a static GNAT run time.
6491 Link against a shared GNAT run time when available.
6494 Tolerate time stamp and other consistency errors
6497 Set the time slice value to n microseconds. A value of zero means no time
6498 slicing and also indicates to the tasking run time to match as close as
6499 possible to the annex D requirements of the RM.
6502 Verbose mode. Write error messages, header, summary output to
6506 Warning mode (@var{x}=s/e for suppress/treat as error)
6510 Exclude source files (check object consistency only).
6518 You may obtain this listing by running the program @code{gnatbind} with
6521 @node Command-Line Access
6522 @section Command-Line Access
6525 The package @code{Ada.Command_Line} provides access to the command-line
6526 arguments and program name. In order for this interface to operate
6527 correctly, the two variables
6541 are declared in one of the GNAT library routines. These variables must
6542 be set from the actual @code{argc} and @code{argv} values passed to the
6543 main program. With no @code{n} present, @code{gnatbind}
6544 generates the C main program to automatically set these variables.
6545 If the @code{n} switch is used, there is no automatic way to
6546 set these variables. If they are not set, the procedures in
6547 @code{Ada.Command_Line} will not be available, and any attempt to use
6548 them will raise @code{Constraint_Error}. If command line access is
6549 required, your main program must set @code{gnat_argc} and
6550 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
6553 @node Search Paths for gnatbind
6554 @section Search Paths for @code{gnatbind}
6557 The binder takes the name of an ALI file as its argument and needs to
6558 locate source files as well as other ALI files to verify object consistency.
6560 For source files, it follows exactly the same search rules as @code{gcc}
6561 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
6562 directories searched are:
6566 The directory containing the ALI file named in the command line, unless
6567 the switch @code{-I-} is specified.
6570 All directories specified by @code{-I}
6571 switches on the @code{gnatbind}
6572 command line, in the order given.
6575 @findex ADA_OBJECTS_PATH
6576 Each of the directories listed in the value of the
6577 @code{ADA_OBJECTS_PATH} environment variable.
6578 Construct this value
6579 exactly as the @code{PATH} environment variable: a list of directory
6580 names separated by colons (semicolons when working with the NT version
6584 The content of the "ada_object_path" file which is part of the GNAT
6585 installation tree and is used to store standard libraries such as the
6586 GNAT Run Time Library (RTL) unless the switch @code{-nostdlib} is
6588 @ref{Installing an Ada Library}
6592 In the binder the switch @code{-I}
6593 is used to specify both source and
6594 library file paths. Use @code{-aI}
6595 instead if you want to specify
6596 source paths only, and @code{-aO}
6597 if you want to specify library paths
6598 only. This means that for the binder
6599 @code{-I}@var{dir} is equivalent to
6601 @code{-aO}@var{dir}.
6602 The binder generates the bind file (a C language source file) in the
6603 current working directory.
6609 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
6610 children make up the GNAT Run-Time Library, together with the package
6611 GNAT and its children, which contain a set of useful additional
6612 library functions provided by GNAT. The sources for these units are
6613 needed by the compiler and are kept together in one directory. The ALI
6614 files and object files generated by compiling the RTL are needed by the
6615 binder and the linker and are kept together in one directory, typically
6616 different from the directory containing the sources. In a normal
6617 installation, you need not specify these directory names when compiling
6618 or binding. Either the environment variables or the built-in defaults
6619 cause these files to be found.
6621 Besides simplifying access to the RTL, a major use of search paths is
6622 in compiling sources from multiple directories. This can make
6623 development environments much more flexible.
6625 @node Examples of gnatbind Usage
6626 @section Examples of @code{gnatbind} Usage
6629 This section contains a number of examples of using the GNAT binding
6630 utility @code{gnatbind}.
6633 @item gnatbind hello
6634 The main program @code{Hello} (source program in @file{hello.adb}) is
6635 bound using the standard switch settings. The generated main program is
6636 @file{b~hello.adb}. This is the normal, default use of the binder.
6638 @item gnatbind hello -o mainprog.adb
6639 The main program @code{Hello} (source program in @file{hello.adb}) is
6640 bound using the standard switch settings. The generated main program is
6641 @file{mainprog.adb} with the associated spec in
6642 @file{mainprog.ads}. Note that you must specify the body here not the
6643 spec, in the case where the output is in Ada. Note that if this option
6644 is used, then linking must be done manually, since gnatlink will not
6645 be able to find the generated file.
6647 @item gnatbind main -C -o mainprog.c -x
6648 The main program @code{Main} (source program in
6649 @file{main.adb}) is bound, excluding source files from the
6650 consistency checking, generating
6651 the file @file{mainprog.c}.
6653 @item gnatbind -x main_program -C -o mainprog.c
6654 This command is exactly the same as the previous example. Switches may
6655 appear anywhere in the command line, and single letter switches may be
6656 combined into a single switch.
6658 @item gnatbind -n math dbase -C -o ada-control.c
6659 The main program is in a language other than Ada, but calls to
6660 subprograms in packages @code{Math} and @code{Dbase} appear. This call
6661 to @code{gnatbind} generates the file @file{ada-control.c} containing
6662 the @code{adainit} and @code{adafinal} routines to be called before and
6663 after accessing the Ada units.
6666 @node Linking Using gnatlink
6667 @chapter Linking Using @code{gnatlink}
6671 This chapter discusses @code{gnatlink}, a utility program used to link
6672 Ada programs and build an executable file. This is a simple program
6673 that invokes the Unix linker (via the @code{gcc}
6674 command) with a correct list of object files and library references.
6675 @code{gnatlink} automatically determines the list of files and
6676 references for the Ada part of a program. It uses the binder file
6677 generated by the binder to determine this list.
6680 * Running gnatlink::
6681 * Switches for gnatlink::
6682 * Setting Stack Size from gnatlink::
6683 * Setting Heap Size from gnatlink::
6686 @node Running gnatlink
6687 @section Running @code{gnatlink}
6690 The form of the @code{gnatlink} command is
6693 $ gnatlink [@var{switches}] @var{mainprog}[.ali] [@var{non-Ada objects}]
6694 [@var{linker options}]
6698 @file{@var{mainprog}.ali} references the ALI file of the main program.
6699 The @file{.ali} extension of this file can be omitted. From this
6700 reference, @code{gnatlink} locates the corresponding binder file
6701 @file{b~@var{mainprog}.adb} and, using the information in this file along
6702 with the list of non-Ada objects and linker options, constructs a Unix
6703 linker command file to create the executable.
6705 The arguments following @file{@var{mainprog}.ali} are passed to the
6706 linker uninterpreted. They typically include the names of object files
6707 for units written in other languages than Ada and any library references
6708 required to resolve references in any of these foreign language units,
6709 or in @code{pragma Import} statements in any Ada units.
6711 @var{linker options} is an optional list of linker specific
6712 switches. The default linker called by gnatlink is @var{gcc} which in
6713 turn calls the appropriate system linker usually called
6714 @var{ld}. Standard options for the linker such as @code{-lmy_lib} or
6715 @code{-Ldir} can be added as is. For options that are not recognized by
6716 @var{gcc} as linker options, the @var{gcc} switches @code{-Xlinker} or
6717 @code{-Wl,} shall be used. Refer to the GCC documentation for
6718 details. Here is an example showing how to generate a linker map
6719 assuming that the underlying linker is GNU ld:
6722 $ gnatlink my_prog -Wl,-Map,MAPFILE
6725 Using @var{linker options} it is possible to set the program stack and
6726 heap size. See @pxref{Setting Stack Size from gnatlink} and
6727 @pxref{Setting Heap Size from gnatlink}.
6729 @code{gnatlink} determines the list of objects required by the Ada
6730 program and prepends them to the list of objects passed to the linker.
6731 @code{gnatlink} also gathers any arguments set by the use of
6732 @code{pragma Linker_Options} and adds them to the list of arguments
6733 presented to the linker.
6736 @node Switches for gnatlink
6737 @section Switches for @code{gnatlink}
6740 The following switches are available with the @code{gnatlink} utility:
6745 @cindex @code{-A} (@code{gnatlink})
6746 The binder has generated code in Ada. This is the default.
6749 @cindex @code{-C} (@code{gnatlink})
6750 If instead of generating a file in Ada, the binder has generated one in
6751 C, then the linker needs to know about it. Use this switch to signal
6752 to @code{gnatlink} that the binder has generated C code rather than
6756 @cindex Command line length
6757 @cindex @code{-f} (@code{gnatlink})
6758 On some targets, the command line length is limited, and @code{gnatlink}
6759 will generate a separate file for the linker if the list of object files
6760 is too long. The @code{-f} flag forces this file to be generated even if
6761 the limit is not exceeded. This is useful in some cases to deal with
6762 special situations where the command line length is exceeded.
6765 @cindex Debugging information, including
6766 @cindex @code{-g} (@code{gnatlink})
6767 The option to include debugging information causes the Ada bind file (in
6768 other words, @file{b~@var{mainprog}.adb}) to be compiled with
6770 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
6771 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
6772 Without @code{-g}, the binder removes these files by
6773 default. The same procedure apply if a C bind file was generated using
6774 @code{-C} @code{gnatbind} option, in this case the filenames are
6775 @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
6778 @cindex @code{-n} (@code{gnatlink})
6779 Do not compile the file generated by the binder. This may be used when
6780 a link is rerun with different options, but there is no need to recompile
6784 @cindex @code{-v} (@code{gnatlink})
6785 Causes additional information to be output, including a full list of the
6786 included object files. This switch option is most useful when you want
6787 to see what set of object files are being used in the link step.
6790 @cindex @code{-v -v} (@code{gnatlink})
6791 Very verbose mode. Requests that the compiler operate in verbose mode when
6792 it compiles the binder file, and that the system linker run in verbose mode.
6794 @item -o @var{exec-name}
6795 @cindex @code{-o} (@code{gnatlink})
6796 @var{exec-name} specifies an alternate name for the generated
6797 executable program. If this switch is omitted, the executable has the same
6798 name as the main unit. For example, @code{gnatlink try.ali} creates
6799 an executable called @file{try}.
6801 @item -b @var{target}
6802 @cindex @code{-b} (@code{gnatlink})
6803 Compile your program to run on @var{target}, which is the name of a
6804 system configuration. You must have a GNAT cross-compiler built if
6805 @var{target} is not the same as your host system.
6808 @cindex @code{-B} (@code{gnatlink})
6809 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
6810 from @var{dir} instead of the default location. Only use this switch
6811 when multiple versions of the GNAT compiler are available. See the
6812 @code{gcc} manual page for further details. You would normally use the
6813 @code{-b} or @code{-V} switch instead.
6815 @item --GCC=@var{compiler_name}
6816 @cindex @code{--GCC=compiler_name} (@code{gnatlink})
6817 Program used for compiling the binder file. The default is
6818 `@code{gcc}'. You need to use quotes around @var{compiler_name} if
6819 @code{compiler_name} contains spaces or other separator characters. As
6820 an example @code{--GCC="foo -x -y"} will instruct @code{gnatlink} to use
6821 @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
6822 inserted after your command name. Thus in the above example the compiler
6823 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
6824 If several @code{--GCC=compiler_name} are used, only the last
6825 @var{compiler_name} is taken into account. However, all the additional
6826 switches are also taken into account. Thus,
6827 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
6828 @code{--GCC="bar -x -y -z -t"}.
6830 @item --LINK=@var{name}
6831 @cindex @code{--LINK=} (@code{gnatlink})
6832 @var{name} is the name of the linker to be invoked. This is especially
6833 useful in mixed language programs since languages such as c++ require
6834 their own linker to be used. When this switch is omitted, the default
6835 name for the linker is (@file{gcc}). When this switch is used, the
6836 specified linker is called instead of (@file{gcc}) with exactly the same
6837 parameters that would have been passed to (@file{gcc}) so if the desired
6838 linker requires different parameters it is necessary to use a wrapper
6839 script that massages the parameters before invoking the real linker. It
6840 may be useful to control the exact invocation by using the verbose
6847 @node Setting Stack Size from gnatlink
6848 @section Setting Stack Size from @code{gnatlink}
6851 It is possible to specify the program stack size from @code{gnatlink}.
6852 Assuming that the underlying linker is GNU ld there is two ways to do so:
6856 @item using @code{-Xlinker} linker option
6859 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
6862 This set the stack reserve size to 0x10000 bytes and the stack commit
6863 size to 0x1000 bytes.
6865 @item using @code{-Wl} linker option
6868 $ gnatlink hello -Wl,--stack=0x1000000
6871 This set the stack reserve size to 0x1000000 bytes. Note that with
6872 @code{-Wl} option it is not possible to set the stack commit size
6873 because the coma is a separator for this option.
6877 @node Setting Heap Size from gnatlink
6878 @section Setting Heap Size from @code{gnatlink}
6881 It is possible to specify the program heap size from @code{gnatlink}.
6882 Assuming that the underlying linker is GNU ld there is two ways to do so:
6886 @item using @code{-Xlinker} linker option
6889 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
6892 This set the heap reserve size to 0x10000 bytes and the heap commit
6893 size to 0x1000 bytes.
6895 @item using @code{-Wl} linker option
6898 $ gnatlink hello -Wl,--heap=0x1000000
6901 This set the heap reserve size to 0x1000000 bytes. Note that with
6902 @code{-Wl} option it is not possible to set the heap commit size
6903 because the coma is a separator for this option.
6907 @node The GNAT Make Program gnatmake
6908 @chapter The GNAT Make Program @code{gnatmake}
6912 * Running gnatmake::
6913 * Switches for gnatmake::
6914 * Mode Switches for gnatmake::
6915 * Notes on the Command Line::
6916 * How gnatmake Works::
6917 * Examples of gnatmake Usage::
6920 A typical development cycle when working on an Ada program consists of
6921 the following steps:
6925 Edit some sources to fix bugs.
6931 Compile all sources affected.
6941 The third step can be tricky, because not only do the modified files
6942 @cindex Dependency rules
6943 have to be compiled, but any files depending on these files must also be
6944 recompiled. The dependency rules in Ada can be quite complex, especially
6945 in the presence of overloading, @code{use} clauses, generics and inlined
6948 @code{gnatmake} automatically takes care of the third and fourth steps
6949 of this process. It determines which sources need to be compiled,
6950 compiles them, and binds and links the resulting object files.
6952 Unlike some other Ada make programs, the dependencies are always
6953 accurately recomputed from the new sources. The source based approach of
6954 the GNAT compilation model makes this possible. This means that if
6955 changes to the source program cause corresponding changes in
6956 dependencies, they will always be tracked exactly correctly by
6959 @node Running gnatmake
6960 @section Running @code{gnatmake}
6963 The usual form of the @code{gnatmake} command is
6966 $ gnatmake [@var{switches}] @var{file_name} [@var{file_names}] [@var{mode_switches}]
6970 The only required argument is one @var{file_name}, which specifies
6971 a compilation unit that is a main program. Several @var{file_names} can be
6972 specified: this will result in several executables being built.
6973 If @code{switches} are present, they can be placed before the first
6974 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
6975 If @var{mode_switches} are present, they must always be placed after
6976 the last @var{file_name} and all @code{switches}.
6978 If you are using standard file extensions (.adb and .ads), then the
6979 extension may be omitted from the @var{file_name} arguments. However, if
6980 you are using non-standard extensions, then it is required that the
6981 extension be given. A relative or absolute directory path can be
6982 specified in a @var{file_name}, in which case, the input source file will
6983 be searched for in the specified directory only. Otherwise, the input
6984 source file will first be searched in the directory where
6985 @code{gnatmake} was invoked and if it is not found, it will be search on
6986 the source path of the compiler as described in
6987 @ref{Search Paths and the Run-Time Library (RTL)}.
6989 When several @var{file_names} are specified, if an executable needs to be
6990 rebuilt and relinked, all subsequent executables will be rebuilt and
6991 relinked, even if this would not be absolutely necessary.
6993 All @code{gnatmake} output (except when you specify
6995 @file{stderr}. The output produced by the
6996 @code{-M} switch is send to
6999 @node Switches for gnatmake
7000 @section Switches for @code{gnatmake}
7003 You may specify any of the following switches to @code{gnatmake}:
7006 @item --GCC=@var{compiler_name}
7007 @cindex @code{--GCC=compiler_name} (@code{gnatmake})
7008 Program used for compiling. The default is `@code{gcc}'. You need to use
7009 quotes around @var{compiler_name} if @code{compiler_name} contains
7010 spaces or other separator characters. As an example @code{--GCC="foo -x
7011 -y"} will instruct @code{gnatmake} to use @code{foo -x -y} as your
7012 compiler. Note that switch @code{-c} is always inserted after your
7013 command name. Thus in the above example the compiler command that will
7014 be used by @code{gnatmake} will be @code{foo -c -x -y}.
7015 If several @code{--GCC=compiler_name} are used, only the last
7016 @var{compiler_name} is taken into account. However, all the additional
7017 switches are also taken into account. Thus,
7018 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7019 @code{--GCC="bar -x -y -z -t"}.
7021 @item --GNATBIND=@var{binder_name}
7022 @cindex @code{--GNATBIND=binder_name} (@code{gnatmake})
7023 Program used for binding. The default is `@code{gnatbind}'. You need to
7024 use quotes around @var{binder_name} if @var{binder_name} contains spaces
7025 or other separator characters. As an example @code{--GNATBIND="bar -x
7026 -y"} will instruct @code{gnatmake} to use @code{bar -x -y} as your
7027 binder. Binder switches that are normally appended by @code{gnatmake} to
7028 `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
7030 @item --GNATLINK=@var{linker_name}
7031 @cindex @code{--GNATLINK=linker_name} (@code{gnatmake})
7032 Program used for linking. The default is `@code{gnatlink}'. You need to
7033 use quotes around @var{linker_name} if @var{linker_name} contains spaces
7034 or other separator characters. As an example @code{--GNATLINK="lan -x
7035 -y"} will instruct @code{gnatmake} to use @code{lan -x -y} as your
7036 linker. Linker switches that are normally appended by @code{gnatmake} to
7037 `@code{gnatlink}' are now appended to the end of @code{lan -x -y}.
7041 @cindex @code{-a} (@code{gnatmake})
7042 Consider all files in the make process, even the GNAT internal system
7043 files (for example, the predefined Ada library files), as well as any
7044 locked files. Locked files are files whose ALI file is write-protected.
7046 @code{gnatmake} does not check these files,
7047 because the assumption is that the GNAT internal files are properly up
7048 to date, and also that any write protected ALI files have been properly
7049 installed. Note that if there is an installation problem, such that one
7050 of these files is not up to date, it will be properly caught by the
7052 You may have to specify this switch if you are working on GNAT
7053 itself. @code{-a} is also useful in conjunction with
7055 if you need to recompile an entire application,
7056 including run-time files, using special configuration pragma settings,
7057 such as a non-standard @code{Float_Representation} pragma.
7059 @code{gnatmake -a} compiles all GNAT
7061 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
7064 @cindex @code{-b} (@code{gnatmake})
7065 Bind only. Can be combined with @code{-c} to do compilation
7066 and binding, but no link. Can be combined with @code{-l}
7067 to do binding and linking. When not combined with @code{-c}
7068 all the units in the closure of the main program must have been previously
7069 compiled and must be up to date. The root unit specified by @var{file_name}
7070 may be given without extension, with the source extension or, if no GNAT
7071 Project File is specified, with the ALI file extension.
7074 @cindex @code{-c} (@code{gnatmake})
7075 Compile only. Do not perform binding, except when @code{-b}
7076 is also specified. Do not perform linking, except if both
7078 @code{-l} are also specified.
7079 If the root unit specified by @var{file_name} is not a main unit, this is the
7080 default. Otherwise @code{gnatmake} will attempt binding and linking
7081 unless all objects are up to date and the executable is more recent than
7085 @cindex @code{-C} (@code{gnatmake})
7086 Use a mapping file. A mapping file is a way to communicate to the compiler
7087 two mappings: from unit names to file names (without any directory information)
7088 and from file names to path names (with full directory information).
7089 These mappings are used by the compiler to short-circuit the path search.
7090 When @code{gnatmake} is invoked with this switch, it will create a mapping
7091 file, initially populated by the project manager, if @code{-P} is used,
7092 otherwise initially empty. Each invocation of the compiler will add the newly
7093 accessed sources to the mapping file. This will improve the source search
7094 during the next invocation of the compiler.
7097 @cindex @code{-f} (@code{gnatmake})
7098 Force recompilations. Recompile all sources, even though some object
7099 files may be up to date, but don't recompile predefined or GNAT internal
7100 files or locked files (files with a write-protected ALI file),
7101 unless the @code{-a} switch is also specified.
7105 @cindex @code{-i} (@code{gnatmake})
7106 In normal mode, @code{gnatmake} compiles all object files and ALI files
7107 into the current directory. If the @code{-i} switch is used,
7108 then instead object files and ALI files that already exist are overwritten
7109 in place. This means that once a large project is organized into separate
7110 directories in the desired manner, then @code{gnatmake} will automatically
7111 maintain and update this organization. If no ALI files are found on the
7112 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
7113 the new object and ALI files are created in the
7114 directory containing the source being compiled. If another organization
7115 is desired, where objects and sources are kept in different directories,
7116 a useful technique is to create dummy ALI files in the desired directories.
7117 When detecting such a dummy file, @code{gnatmake} will be forced to recompile
7118 the corresponding source file, and it will be put the resulting object
7119 and ALI files in the directory where it found the dummy file.
7122 @cindex @code{-j} (@code{gnatmake})
7123 @cindex Parallel make
7124 Use @var{n} processes to carry out the (re)compilations. On a
7125 multiprocessor machine compilations will occur in parallel. In the
7126 event of compilation errors, messages from various compilations might
7127 get interspersed (but @code{gnatmake} will give you the full ordered
7128 list of failing compiles at the end). If this is problematic, rerun
7129 the make process with n set to 1 to get a clean list of messages.
7132 @cindex @code{-k} (@code{gnatmake})
7133 Keep going. Continue as much as possible after a compilation error. To
7134 ease the programmer's task in case of compilation errors, the list of
7135 sources for which the compile fails is given when @code{gnatmake}
7138 If @code{gnatmake} is invoked with several @file{file_names} and with this
7139 switch, if there are compilation errors when building an executable,
7140 @code{gnatmake} will not attempt to build the following executables.
7143 @cindex @code{-l} (@code{gnatmake})
7144 Link only. Can be combined with @code{-b} to binding
7145 and linking. Linking will not be performed if combined with
7147 but not with @code{-b}.
7148 When not combined with @code{-b}
7149 all the units in the closure of the main program must have been previously
7150 compiled and must be up to date, and the main program need to have been bound.
7151 The root unit specified by @var{file_name}
7152 may be given without extension, with the source extension or, if no GNAT
7153 Project File is specified, with the ALI file extension.
7156 @cindex @code{-m} (@code{gnatmake})
7157 Specifies that the minimum necessary amount of recompilations
7158 be performed. In this mode @code{gnatmake} ignores time
7159 stamp differences when the only
7160 modifications to a source file consist in adding/removing comments,
7161 empty lines, spaces or tabs. This means that if you have changed the
7162 comments in a source file or have simply reformatted it, using this
7163 switch will tell gnatmake not to recompile files that depend on it
7164 (provided other sources on which these files depend have undergone no
7165 semantic modifications). Note that the debugging information may be
7166 out of date with respect to the sources if the @code{-m} switch causes
7167 a compilation to be switched, so the use of this switch represents a
7168 trade-off between compilation time and accurate debugging information.
7171 @cindex Dependencies, producing list
7172 @cindex @code{-M} (@code{gnatmake})
7173 Check if all objects are up to date. If they are, output the object
7174 dependences to @file{stdout} in a form that can be directly exploited in
7175 a @file{Makefile}. By default, each source file is prefixed with its
7176 (relative or absolute) directory name. This name is whatever you
7177 specified in the various @code{-aI}
7178 and @code{-I} switches. If you use
7181 (see below), only the source file names,
7182 without relative paths, are output. If you just specify the
7184 switch, dependencies of the GNAT internal system files are omitted. This
7185 is typically what you want. If you also specify
7186 the @code{-a} switch,
7187 dependencies of the GNAT internal files are also listed. Note that
7188 dependencies of the objects in external Ada libraries (see switch
7189 @code{-aL}@var{dir} in the following list) are never reported.
7192 @cindex @code{-n} (@code{gnatmake})
7193 Don't compile, bind, or link. Checks if all objects are up to date.
7194 If they are not, the full name of the first file that needs to be
7195 recompiled is printed.
7196 Repeated use of this option, followed by compiling the indicated source
7197 file, will eventually result in recompiling all required units.
7199 @item -o @var{exec_name}
7200 @cindex @code{-o} (@code{gnatmake})
7201 Output executable name. The name of the final executable program will be
7202 @var{exec_name}. If the @code{-o} switch is omitted the default
7203 name for the executable will be the name of the input file in appropriate form
7204 for an executable file on the host system.
7206 This switch cannot be used when invoking @code{gnatmake} with several
7210 @cindex @code{-q} (@code{gnatmake})
7211 Quiet. When this flag is not set, the commands carried out by
7212 @code{gnatmake} are displayed.
7215 @cindex @code{-s} (@code{gnatmake})
7216 Recompile if compiler switches have changed since last compilation.
7217 All compiler switches but -I and -o are taken into account in the
7219 orders between different ``first letter'' switches are ignored, but
7220 orders between same switches are taken into account. For example,
7221 @code{-O -O2} is different than @code{-O2 -O}, but @code{-g -O} is equivalent
7225 @cindex @code{-u} (@code{gnatmake})
7226 Unique. Recompile at most the main file. It implies -c. Combined with
7227 -f, it is equivalent to calling the compiler directly.
7230 @cindex @code{-v} (@code{gnatmake})
7231 Verbose. Displays the reason for all recompilations @code{gnatmake}
7232 decides are necessary.
7235 @cindex @code{-z} (@code{gnatmake})
7236 No main subprogram. Bind and link the program even if the unit name
7237 given on the command line is a package name. The resulting executable
7238 will execute the elaboration routines of the package and its closure,
7239 then the finalization routines.
7241 @item @code{gcc} @asis{switches}
7242 The switch @code{-g} or any uppercase switch (other than @code{-A},
7244 @code{-S}) or any switch that is more than one character is passed to
7245 @code{gcc} (e.g. @code{-O}, @option{-gnato,} etc.)
7249 Source and library search path switches:
7253 @cindex @code{-aI} (@code{gnatmake})
7254 When looking for source files also look in directory @var{dir}.
7255 The order in which source files search is undertaken is
7256 described in @ref{Search Paths and the Run-Time Library (RTL)}.
7259 @cindex @code{-aL} (@code{gnatmake})
7260 Consider @var{dir} as being an externally provided Ada library.
7261 Instructs @code{gnatmake} to skip compilation units whose @file{.ali}
7262 files have been located in directory @var{dir}. This allows you to have
7263 missing bodies for the units in @var{dir} and to ignore out of date bodies
7264 for the same units. You still need to specify
7265 the location of the specs for these units by using the switches
7267 or @code{-I@var{dir}}.
7268 Note: this switch is provided for compatibility with previous versions
7269 of @code{gnatmake}. The easier method of causing standard libraries
7270 to be excluded from consideration is to write-protect the corresponding
7274 @cindex @code{-aO} (@code{gnatmake})
7275 When searching for library and object files, look in directory
7276 @var{dir}. The order in which library files are searched is described in
7277 @ref{Search Paths for gnatbind}.
7280 @cindex Search paths, for @code{gnatmake}
7281 @cindex @code{-A} (@code{gnatmake})
7282 Equivalent to @code{-aL@var{dir}
7286 @cindex @code{-I} (@code{gnatmake})
7287 Equivalent to @code{-aO@var{dir}
7291 @cindex @code{-I-} (@code{gnatmake})
7292 @cindex Source files, suppressing search
7293 Do not look for source files in the directory containing the source
7294 file named in the command line.
7295 Do not look for ALI or object files in the directory
7296 where @code{gnatmake} was invoked.
7299 @cindex @code{-L} (@code{gnatmake})
7300 @cindex Linker libraries
7301 Add directory @var{dir} to the list of directories in which the linker
7302 will search for libraries. This is equivalent to
7303 @code{-largs -L}@var{dir}.
7306 @cindex @code{-nostdinc} (@code{gnatmake})
7307 Do not look for source files in the system default directory.
7310 @cindex @code{-nostdlib} (@code{gnatmake})
7311 Do not look for library files in the system default directory.
7313 @item --RTS=@var{rts-path}
7314 @cindex @code{--RTS} (@code{gnatmake})
7315 Specifies the default location of the runtime library. We look for the runtime
7316 in the following directories, and stop as soon as a valid runtime is found
7317 ("adainclude" or "ada_source_path", and "adalib" or "ada_object_path" present):
7320 @item <current directory>/$rts_path
7322 @item <default-search-dir>/$rts_path
7324 @item <default-search-dir>/rts-$rts_path
7328 The selected path is handled like a normal RTS path.
7332 @node Mode Switches for gnatmake
7333 @section Mode Switches for @code{gnatmake}
7336 The mode switches (referred to as @code{mode_switches}) allow the
7337 inclusion of switches that are to be passed to the compiler itself, the
7338 binder or the linker. The effect of a mode switch is to cause all
7339 subsequent switches up to the end of the switch list, or up to the next
7340 mode switch, to be interpreted as switches to be passed on to the
7341 designated component of GNAT.
7344 @item -cargs @var{switches}
7345 @cindex @code{-cargs} (@code{gnatmake})
7346 Compiler switches. Here @var{switches} is a list of switches
7347 that are valid switches for @code{gcc}. They will be passed on to
7348 all compile steps performed by @code{gnatmake}.
7350 @item -bargs @var{switches}
7351 @cindex @code{-bargs} (@code{gnatmake})
7352 Binder switches. Here @var{switches} is a list of switches
7353 that are valid switches for @code{gcc}. They will be passed on to
7354 all bind steps performed by @code{gnatmake}.
7356 @item -largs @var{switches}
7357 @cindex @code{-largs} (@code{gnatmake})
7358 Linker switches. Here @var{switches} is a list of switches
7359 that are valid switches for @code{gcc}. They will be passed on to
7360 all link steps performed by @code{gnatmake}.
7363 @node Notes on the Command Line
7364 @section Notes on the Command Line
7367 This section contains some additional useful notes on the operation
7368 of the @code{gnatmake} command.
7372 @cindex Recompilation, by @code{gnatmake}
7373 If @code{gnatmake} finds no ALI files, it recompiles the main program
7374 and all other units required by the main program.
7375 This means that @code{gnatmake}
7376 can be used for the initial compile, as well as during subsequent steps of
7377 the development cycle.
7380 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
7381 is a subunit or body of a generic unit, @code{gnatmake} recompiles
7382 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
7386 In @code{gnatmake} the switch @code{-I}
7387 is used to specify both source and
7388 library file paths. Use @code{-aI}
7389 instead if you just want to specify
7390 source paths only and @code{-aO}
7391 if you want to specify library paths
7395 @code{gnatmake} examines both an ALI file and its corresponding object file
7396 for consistency. If an ALI is more recent than its corresponding object,
7397 or if the object file is missing, the corresponding source will be recompiled.
7398 Note that @code{gnatmake} expects an ALI and the corresponding object file
7399 to be in the same directory.
7402 @code{gnatmake} will ignore any files whose ALI file is write-protected.
7403 This may conveniently be used to exclude standard libraries from
7404 consideration and in particular it means that the use of the
7405 @code{-f} switch will not recompile these files
7406 unless @code{-a} is also specified.
7409 @code{gnatmake} has been designed to make the use of Ada libraries
7410 particularly convenient. Assume you have an Ada library organized
7411 as follows: @var{obj-dir} contains the objects and ALI files for
7412 of your Ada compilation units,
7413 whereas @var{include-dir} contains the
7414 specs of these units, but no bodies. Then to compile a unit
7415 stored in @code{main.adb}, which uses this Ada library you would just type
7418 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
7422 Using @code{gnatmake} along with the
7423 @code{-m (minimal recompilation)}
7424 switch provides a mechanism for avoiding unnecessary rcompilations. Using
7426 you can update the comments/format of your
7427 source files without having to recompile everything. Note, however, that
7428 adding or deleting lines in a source files may render its debugging
7429 info obsolete. If the file in question is a spec, the impact is rather
7430 limited, as that debugging info will only be useful during the
7431 elaboration phase of your program. For bodies the impact can be more
7432 significant. In all events, your debugger will warn you if a source file
7433 is more recent than the corresponding object, and alert you to the fact
7434 that the debugging information may be out of date.
7437 @node How gnatmake Works
7438 @section How @code{gnatmake} Works
7441 Generally @code{gnatmake} automatically performs all necessary
7442 recompilations and you don't need to worry about how it works. However,
7443 it may be useful to have some basic understanding of the @code{gnatmake}
7444 approach and in particular to understand how it uses the results of
7445 previous compilations without incorrectly depending on them.
7447 First a definition: an object file is considered @dfn{up to date} if the
7448 corresponding ALI file exists and its time stamp predates that of the
7449 object file and if all the source files listed in the
7450 dependency section of this ALI file have time stamps matching those in
7451 the ALI file. This means that neither the source file itself nor any
7452 files that it depends on have been modified, and hence there is no need
7453 to recompile this file.
7455 @code{gnatmake} works by first checking if the specified main unit is up
7456 to date. If so, no compilations are required for the main unit. If not,
7457 @code{gnatmake} compiles the main program to build a new ALI file that
7458 reflects the latest sources. Then the ALI file of the main unit is
7459 examined to find all the source files on which the main program depends,
7460 and @code{gnatmake} recursively applies the above procedure on all these files.
7462 This process ensures that @code{gnatmake} only trusts the dependencies
7463 in an existing ALI file if they are known to be correct. Otherwise it
7464 always recompiles to determine a new, guaranteed accurate set of
7465 dependencies. As a result the program is compiled "upside down" from what may
7466 be more familiar as the required order of compilation in some other Ada
7467 systems. In particular, clients are compiled before the units on which
7468 they depend. The ability of GNAT to compile in any order is critical in
7469 allowing an order of compilation to be chosen that guarantees that
7470 @code{gnatmake} will recompute a correct set of new dependencies if
7473 When invoking @code{gnatmake} with several @var{file_names}, if a unit is
7474 imported by several of the executables, it will be recompiled at most once.
7476 @node Examples of gnatmake Usage
7477 @section Examples of @code{gnatmake} Usage
7480 @item gnatmake hello.adb
7481 Compile all files necessary to bind and link the main program
7482 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
7483 resulting object files to generate an executable file @file{hello}.
7485 @item gnatmake main1 main2 main3
7486 Compile all files necessary to bind and link the main programs
7487 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
7488 (containing unit @code{Main2}) and @file{main3.adb}
7489 (containing unit @code{Main3}) and bind and link the resulting object files
7490 to generate three executable files @file{main1},
7494 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
7496 Compile all files necessary to bind and link the main program unit
7497 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
7498 be done with optimization level 2 and the order of elaboration will be
7499 listed by the binder. @code{gnatmake} will operate in quiet mode, not
7500 displaying commands it is executing.
7503 @node Renaming Files Using gnatchop
7504 @chapter Renaming Files Using @code{gnatchop}
7508 This chapter discusses how to handle files with multiple units by using
7509 the @code{gnatchop} utility. This utility is also useful in renaming
7510 files to meet the standard GNAT default file naming conventions.
7513 * Handling Files with Multiple Units::
7514 * Operating gnatchop in Compilation Mode::
7515 * Command Line for gnatchop::
7516 * Switches for gnatchop::
7517 * Examples of gnatchop Usage::
7520 @node Handling Files with Multiple Units
7521 @section Handling Files with Multiple Units
7524 The basic compilation model of GNAT requires that a file submitted to the
7525 compiler have only one unit and there be a strict correspondence
7526 between the file name and the unit name.
7528 The @code{gnatchop} utility allows both of these rules to be relaxed,
7529 allowing GNAT to process files which contain multiple compilation units
7530 and files with arbitrary file names. @code{gnatchop}
7531 reads the specified file and generates one or more output files,
7532 containing one unit per file. The unit and the file name correspond,
7533 as required by GNAT.
7535 If you want to permanently restructure a set of "foreign" files so that
7536 they match the GNAT rules, and do the remaining development using the
7537 GNAT structure, you can simply use @code{gnatchop} once, generate the
7538 new set of files and work with them from that point on.
7540 Alternatively, if you want to keep your files in the "foreign" format,
7541 perhaps to maintain compatibility with some other Ada compilation
7542 system, you can set up a procedure where you use @code{gnatchop} each
7543 time you compile, regarding the source files that it writes as temporary
7544 files that you throw away.
7546 @node Operating gnatchop in Compilation Mode
7547 @section Operating gnatchop in Compilation Mode
7550 The basic function of @code{gnatchop} is to take a file with multiple units
7551 and split it into separate files. The boundary between files is reasonably
7552 clear, except for the issue of comments and pragmas. In default mode, the
7553 rule is that any pragmas between units belong to the previous unit, except
7554 that configuration pragmas always belong to the following unit. Any comments
7555 belong to the following unit. These rules
7556 almost always result in the right choice of
7557 the split point without needing to mark it explicitly and most users will
7558 find this default to be what they want. In this default mode it is incorrect to
7559 submit a file containing only configuration pragmas, or one that ends in
7560 configuration pragmas, to @code{gnatchop}.
7562 However, using a special option to activate "compilation mode",
7564 can perform another function, which is to provide exactly the semantics
7565 required by the RM for handling of configuration pragmas in a compilation.
7566 In the absence of configuration pragmas (at the main file level), this
7567 option has no effect, but it causes such configuration pragmas to be handled
7568 in a quite different manner.
7570 First, in compilation mode, if @code{gnatchop} is given a file that consists of
7571 only configuration pragmas, then this file is appended to the
7572 @file{gnat.adc} file in the current directory. This behavior provides
7573 the required behavior described in the RM for the actions to be taken
7574 on submitting such a file to the compiler, namely that these pragmas
7575 should apply to all subsequent compilations in the same compilation
7576 environment. Using GNAT, the current directory, possibly containing a
7577 @file{gnat.adc} file is the representation
7578 of a compilation environment. For more information on the
7579 @file{gnat.adc} file, see the section on handling of configuration
7580 pragmas @pxref{Handling of Configuration Pragmas}.
7582 Second, in compilation mode, if @code{gnatchop}
7583 is given a file that starts with
7584 configuration pragmas, and contains one or more units, then these
7585 configuration pragmas are prepended to each of the chopped files. This
7586 behavior provides the required behavior described in the RM for the
7587 actions to be taken on compiling such a file, namely that the pragmas
7588 apply to all units in the compilation, but not to subsequently compiled
7591 Finally, if configuration pragmas appear between units, they are appended
7592 to the previous unit. This results in the previous unit being illegal,
7593 since the compiler does not accept configuration pragmas that follow
7594 a unit. This provides the required RM behavior that forbids configuration
7595 pragmas other than those preceding the first compilation unit of a
7598 For most purposes, @code{gnatchop} will be used in default mode. The
7599 compilation mode described above is used only if you need exactly
7600 accurate behavior with respect to compilations, and you have files
7601 that contain multiple units and configuration pragmas. In this
7602 circumstance the use of @code{gnatchop} with the compilation mode
7603 switch provides the required behavior, and is for example the mode
7604 in which GNAT processes the ACVC tests.
7606 @node Command Line for gnatchop
7607 @section Command Line for @code{gnatchop}
7610 The @code{gnatchop} command has the form:
7613 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
7618 The only required argument is the file name of the file to be chopped.
7619 There are no restrictions on the form of this file name. The file itself
7620 contains one or more Ada units, in normal GNAT format, concatenated
7621 together. As shown, more than one file may be presented to be chopped.
7623 When run in default mode, @code{gnatchop} generates one output file in
7624 the current directory for each unit in each of the files.
7626 @var{directory}, if specified, gives the name of the directory to which
7627 the output files will be written. If it is not specified, all files are
7628 written to the current directory.
7630 For example, given a
7631 file called @file{hellofiles} containing
7636 @b{procedure} hello;
7638 @b{with} Text_IO; @b{use} Text_IO;
7639 @b{procedure} hello @b{is}
7651 $ gnatchop hellofiles
7655 generates two files in the current directory, one called
7656 @file{hello.ads} containing the single line that is the procedure spec,
7657 and the other called @file{hello.adb} containing the remaining text. The
7658 original file is not affected. The generated files can be compiled in
7661 @node Switches for gnatchop
7662 @section Switches for @code{gnatchop}
7665 @code{gnatchop} recognizes the following switches:
7670 @cindex @code{-c} (@code{gnatchop})
7671 Causes @code{gnatchop} to operate in compilation mode, in which
7672 configuration pragmas are handled according to strict RM rules. See
7673 previous section for a full description of this mode.
7676 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
7677 used to parse the given file. Not all @code{xxx} options make sense,
7678 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
7679 process a source file that uses Latin-2 coding for identifiers.
7682 Causes @code{gnatchop} to generate a brief help summary to the standard
7683 output file showing usage information.
7686 @cindex @code{-k} (@code{gnatchop})
7687 Limit generated file names to the specified number @code{mm}
7689 This is useful if the
7690 resulting set of files is required to be interoperable with systems
7691 which limit the length of file names.
7692 No space is allowed between the @code{-k} and the numeric value. The numeric
7693 value may be omitted in which case a default of @code{-k8},
7695 with DOS-like file systems, is used. If no @code{-k} switch
7697 there is no limit on the length of file names.
7700 @cindex @code{-p} (@code{gnatchop})
7701 Causes the file modification time stamp of the input file to be
7702 preserved and used for the time stamp of the output file(s). This may be
7703 useful for preserving coherency of time stamps in an enviroment where
7704 @code{gnatchop} is used as part of a standard build process.
7707 @cindex @code{-q} (@code{gnatchop})
7708 Causes output of informational messages indicating the set of generated
7709 files to be suppressed. Warnings and error messages are unaffected.
7712 @cindex @code{-r} (@code{gnatchop})
7713 @findex Source_Reference
7714 Generate @code{Source_Reference} pragmas. Use this switch if the output
7715 files are regarded as temporary and development is to be done in terms
7716 of the original unchopped file. This switch causes
7717 @code{Source_Reference} pragmas to be inserted into each of the
7718 generated files to refers back to the original file name and line number.
7719 The result is that all error messages refer back to the original
7721 In addition, the debugging information placed into the object file (when
7722 the @code{-g} switch of @code{gcc} or @code{gnatmake} is specified) also
7723 refers back to this original file so that tools like profilers and
7724 debuggers will give information in terms of the original unchopped file.
7726 If the original file to be chopped itself contains
7727 a @code{Source_Reference}
7728 pragma referencing a third file, then gnatchop respects
7729 this pragma, and the generated @code{Source_Reference} pragmas
7730 in the chopped file refer to the original file, with appropriate
7731 line numbers. This is particularly useful when @code{gnatchop}
7732 is used in conjunction with @code{gnatprep} to compile files that
7733 contain preprocessing statements and multiple units.
7736 @cindex @code{-v} (@code{gnatchop})
7737 Causes @code{gnatchop} to operate in verbose mode. The version
7738 number and copyright notice are output, as well as exact copies of
7739 the gnat1 commands spawned to obtain the chop control information.
7742 @cindex @code{-w} (@code{gnatchop})
7743 Overwrite existing file names. Normally @code{gnatchop} regards it as a
7744 fatal error if there is already a file with the same name as a
7745 file it would otherwise output, in other words if the files to be
7746 chopped contain duplicated units. This switch bypasses this
7747 check, and causes all but the last instance of such duplicated
7748 units to be skipped.
7751 @cindex @code{--GCC=} (@code{gnatchop})
7752 Specify the path of the GNAT parser to be used. When this switch is used,
7753 no attempt is made to add the prefix to the GNAT parser executable.
7756 @node Examples of gnatchop Usage
7757 @section Examples of @code{gnatchop} Usage
7760 @item gnatchop -w hello_s.ada ichbiah/files
7762 Chops the source file @file{hello_s.ada}. The output files will be
7763 placed in the directory @file{ichbiah/files},
7765 files with matching names in that directory (no files in the current
7766 directory are modified).
7768 @item gnatchop archive
7769 Chops the source file @file{archive}
7770 into the current directory. One
7771 useful application of @code{gnatchop} is in sending sets of sources
7772 around, for example in email messages. The required sources are simply
7773 concatenated (for example, using a Unix @code{cat}
7775 @code{gnatchop} is used at the other end to reconstitute the original
7778 @item gnatchop file1 file2 file3 direc
7779 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
7780 the resulting files in the directory @file{direc}. Note that if any units
7781 occur more than once anywhere within this set of files, an error message
7782 is generated, and no files are written. To override this check, use the
7784 in which case the last occurrence in the last file will
7785 be the one that is output, and earlier duplicate occurrences for a given
7786 unit will be skipped.
7789 @node Configuration Pragmas
7790 @chapter Configuration Pragmas
7791 @cindex Configuration pragmas
7792 @cindex Pragmas, configuration
7795 In Ada 95, configuration pragmas include those pragmas described as
7796 such in the Ada 95 Reference Manual, as well as
7797 implementation-dependent pragmas that are configuration pragmas. See the
7798 individual descriptions of pragmas in the GNAT Reference Manual for
7799 details on these additional GNAT-specific configuration pragmas. Most
7800 notably, the pragma @code{Source_File_Name}, which allows
7801 specifying non-default names for source files, is a configuration
7802 pragma. The following is a complete list of configuration pragmas
7803 recognized by @code{GNAT}:
7815 External_Name_Casing
7816 Float_Representation
7824 Propagate_Exceptions
7833 Task_Dispatching_Policy
7841 * Handling of Configuration Pragmas::
7842 * The Configuration Pragmas Files::
7845 @node Handling of Configuration Pragmas
7846 @section Handling of Configuration Pragmas
7848 Configuration pragmas may either appear at the start of a compilation
7849 unit, in which case they apply only to that unit, or they may apply to
7850 all compilations performed in a given compilation environment.
7852 GNAT also provides the @code{gnatchop} utility to provide an automatic
7853 way to handle configuration pragmas following the semantics for
7854 compilations (that is, files with multiple units), described in the RM.
7855 See section @pxref{Operating gnatchop in Compilation Mode} for details.
7856 However, for most purposes, it will be more convenient to edit the
7857 @file{gnat.adc} file that contains configuration pragmas directly,
7858 as described in the following section.
7860 @node The Configuration Pragmas Files
7861 @section The Configuration Pragmas Files
7862 @cindex @file{gnat.adc}
7865 In GNAT a compilation environment is defined by the current
7866 directory at the time that a compile command is given. This current
7867 directory is searched for a file whose name is @file{gnat.adc}. If
7868 this file is present, it is expected to contain one or more
7869 configuration pragmas that will be applied to the current compilation.
7870 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
7873 Configuration pragmas may be entered into the @file{gnat.adc} file
7874 either by running @code{gnatchop} on a source file that consists only of
7875 configuration pragmas, or more conveniently by
7876 direct editing of the @file{gnat.adc} file, which is a standard format
7879 In addition to @file{gnat.adc}, one additional file containing configuration
7880 pragmas may be applied to the current compilation using the switch
7881 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
7882 contains only configuration pragmas. These configuration pragmas are
7883 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
7884 is present and switch @option{-gnatA} is not used).
7886 It is allowed to specify several switches @option{-gnatec}, however only
7887 the last one on the command line will be taken into account.
7890 @node Handling Arbitrary File Naming Conventions Using gnatname
7891 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
7892 @cindex Arbitrary File Naming Conventions
7895 * Arbitrary File Naming Conventions::
7896 * Running gnatname::
7897 * Switches for gnatname::
7898 * Examples of gnatname Usage::
7901 @node Arbitrary File Naming Conventions
7902 @section Arbitrary File Naming Conventions
7905 The GNAT compiler must be able to know the source file name of a compilation unit.
7906 When using the standard GNAT default file naming conventions (@code{.ads} for specs,
7907 @code{.adb} for bodies), the GNAT compiler does not need additional information.
7910 When the source file names do not follow the standard GNAT default file naming
7911 conventions, the GNAT compiler must be given additional information through
7912 a configuration pragmas file (see @ref{Configuration Pragmas}) or a project file.
7913 When the non standard file naming conventions are well-defined, a small number of
7914 pragmas @code{Source_File_Name} specifying a naming pattern
7915 (see @ref{Alternative File Naming Schemes}) may be sufficient. However,
7916 if the file naming conventions are irregular or arbitrary, a number
7917 of pragma @code{Source_File_Name} for individual compilation units must be defined.
7918 To help maintain the correspondence between compilation unit names and
7919 source file names within the compiler,
7920 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
7923 @node Running gnatname
7924 @section Running @code{gnatname}
7927 The usual form of the @code{gnatname} command is
7930 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
7934 All of the arguments are optional. If invoked without any argument,
7935 @code{gnatname} will display its usage.
7938 When used with at least one naming pattern, @code{gnatname} will attempt to
7939 find all the compilation units in files that follow at least one of the
7940 naming patterns. To find these compilation units,
7941 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
7945 One or several Naming Patterns may be given as arguments to @code{gnatname}.
7946 Each Naming Pattern is enclosed between double quotes.
7947 A Naming Pattern is a regular expression similar to the wildcard patterns
7948 used in file names by the Unix shells or the DOS prompt.
7951 Examples of Naming Patterns are
7960 For a more complete description of the syntax of Naming Patterns, see the second kind
7961 of regular expressions described in @file{g-regexp.ads} (the "Glob" regular
7965 When invoked with no switches, @code{gnatname} will create a configuration
7966 pragmas file @file{gnat.adc} in the current working directory, with pragmas
7967 @code{Source_File_Name} for each file that contains a valid Ada unit.
7969 @node Switches for gnatname
7970 @section Switches for @code{gnatname}
7973 Switches for @code{gnatname} must precede any specified Naming Pattern.
7976 You may specify any of the following switches to @code{gnatname}:
7981 @cindex @code{-c} (@code{gnatname})
7982 Create a configuration pragmas file @file{file} (instead of the default
7983 @file{gnat.adc}). There may be zero, one or more space between @code{-c} and
7984 @file{file}. @file{file} may include directory information. @file{file} must be
7985 writeable. There may be only one switch @code{-c}. When a switch @code{-c} is
7986 specified, no switch @code{-P} may be specified (see below).
7989 @cindex @code{-d} (@code{gnatname})
7990 Look for source files in directory @file{dir}. There may be zero, one or more spaces
7991 between @code{-d} and @file{dir}. When a switch @code{-d} is specified,
7992 the current working directory will not be searched for source files, unless it
7994 specified with a @code{-d} or @code{-D} switch. Several switches @code{-d} may be
7995 specified. If @file{dir} is a relative path, it is relative to the directory of
7996 the configuration pragmas file specified with switch @code{-c}, or to the directory
7997 of the project file specified with switch @code{-P} or, if neither switch @code{-c}
7998 nor switch @code{-P} are specified, it is relative to the current working
7999 directory. The directory
8000 specified with switch @code{-c} must exist and be readable.
8003 @cindex @code{-D} (@code{gnatname})
8004 Look for source files in all directories listed in text file @file{file}. There may be
8005 zero, one or more spaces between @code{-d} and @file{dir}. @file{file}
8006 must be an existing, readable text file. Each non empty line in @file{file} must be
8007 a directory. Specifying switch @code{-D} is equivalent to specifying as many switches
8008 @code{-d} as there are non empty lines in @file{file}.
8011 @cindex @code{-h} (@code{gnatname})
8012 Output usage (help) information. The output is written to @file{stdout}.
8015 @cindex @code{-P} (@code{gnatname})
8016 Create or update project file @file{proj}. There may be zero, one or more space
8017 between @code{-P} and @file{proj}. @file{proj} may include directory information.
8018 @file{proj} must be writeable. There may be only one switch @code{-P}.
8019 When a switch @code{-P} is specified, no switch @code{-c} may be specified.
8022 @cindex @code{-v} (@code{gnatname})
8023 Verbose mode. Output detailed explanation of behavior to @file{stdout}. This includes
8024 name of the file written, the name of the directories to search and, for each file
8025 in those directories whose name matches at least one of the Naming Patterns, an
8026 indication of whether the file contains a unit, and if so the name of the unit.
8029 Very Verbose mode. In addition to the output produced in verbose mode, for each file
8030 in the searched directories whose name matches none of the Naming Patterns, an
8031 indication is given that there is no match.
8033 @item -x@file{pattern}
8034 Excluded patterns. Using this switch, it is possible to exclude some files
8035 that would match the name patterns. For example,
8036 @code{"gnatname -x "*_nt.ada" "*.ada"} will look for Ada units in all files
8037 with the @file{.ada} extension, except those whose names end with
8042 @node Examples of gnatname Usage
8043 @section Examples of @code{gnatname} Usage
8046 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
8049 In this example, the directory @file{/home/me} must already exist and be
8050 writeable. In addition, the directory @file{/home/me/sources} (specified by
8051 @code{-d sources}) must exist and be readable. Note the optional spaces after
8052 @code{-c} and @code{-d}.
8055 $ gnatname -P/home/me/proj -x "*_nt_body.ada" -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
8058 Note that several switches @code{-d} may be used, even in conjunction with one
8059 or several switches @code{-D}. Several Naming Patterns and one excluded pattern
8060 are used in this example.
8063 @c *****************************************
8064 @c * G N A T P r o j e c t M a n a g e r *
8065 @c *****************************************
8066 @node GNAT Project Manager
8067 @chapter GNAT Project Manager
8071 * Examples of Project Files::
8072 * Project File Syntax::
8073 * Objects and Sources in Project Files::
8074 * Importing Projects::
8075 * Project Extension::
8076 * External References in Project Files::
8077 * Packages in Project Files::
8078 * Variables from Imported Projects::
8080 * Library Projects::
8081 * Switches Related to Project Files::
8082 * Tools Supporting Project Files::
8083 * An Extended Example::
8084 * Project File Complete Syntax::
8093 @section Introduction
8096 This chapter describes GNAT's @emph{Project Manager}, a facility that
8097 lets you configure various properties for a collection of source files. In
8098 particular, you can specify:
8101 The directory or set of directories containing the source files, and/or the
8102 names of the specific source files themselves
8104 The directory in which the compiler's output
8105 (@file{ALI} files, object files, tree files) will be placed
8107 The directory in which the executable programs will be placed
8109 Switch settings for any of the project-enabled tools (@command{gnatmake},
8110 compiler, binder, linker, @code{gnatls}, @code{gnatxref}, @code{gnatfind});
8111 you can apply these settings either globally or to individual units
8113 The source files containing the main subprogram(s) to be built
8115 The source programming language(s) (currently Ada and/or C)
8117 Source file naming conventions; you can specify these either globally or for
8126 @subsection Project Files
8129 A @dfn{project} is a specific set of values for these properties. You can
8130 define a project's settings in a @dfn{project file}, a text file with an
8131 Ada-like syntax; a property value is either a string or a list of strings.
8132 Properties that are not explicitly set receive default values. A project
8133 file may interrogate the values of @dfn{external variables} (user-defined
8134 command-line switches or environment variables), and it may specify property
8135 settings conditionally, based on the value of such variables.
8137 In simple cases, a project's source files depend only on other source files
8138 in the same project, or on the predefined libraries. ("Dependence" is in
8139 the technical sense; for example, one Ada unit "with"ing another.) However,
8140 the Project Manager also allows much more sophisticated arrangements,
8141 with the source files in one project depending on source files in other
8145 One project can @emph{import} other projects containing needed source files.
8147 You can organize GNAT projects in a hierarchy: a @emph{child} project
8148 can extend a @emph{parent} project, inheriting the parent's source files and
8149 optionally overriding any of them with alternative versions
8153 More generally, the Project Manager lets you structure large development
8154 efforts into hierarchical subsystems, with build decisions deferred to the
8155 subsystem level and thus different compilation environments (switch settings)
8156 used for different subsystems.
8158 The Project Manager is invoked through the @option{-P@emph{projectfile}}
8159 switch to @command{gnatmake} or to the @command{gnat} front driver.
8160 If you want to define (on the command line) an external variable that is
8161 queried by the project file, additionally use the
8162 @option{-X@emph{vbl}=@emph{value}} switch.
8163 The Project Manager parses and interprets the project file, and drives the
8164 invoked tool based on the project settings.
8166 The Project Manager supports a wide range of development strategies,
8167 for systems of all sizes. Some typical practices that are easily handled:
8170 Using a common set of source files, but generating object files in different
8171 directories via different switch settings
8173 Using a mostly-shared set of source files, but with different versions of
8178 The destination of an executable can be controlled inside a project file
8179 using the @option{-o} switch. In the absence of such a switch either inside
8180 the project file or on the command line, any executable files generated by
8181 @command{gnatmake} will be placed in the directory @code{Exec_Dir} specified
8182 in the project file. If no @code{Exec_Dir} is specified, they will be placed
8183 in the object directory of the project.
8185 You can use project files to achieve some of the effects of a source
8186 versioning system (for example, defining separate projects for
8187 the different sets of sources that comprise different releases) but the
8188 Project Manager is independent of any source configuration management tools
8189 that might be used by the developers.
8191 The next section introduces the main features of GNAT's project facility
8192 through a sequence of examples; subsequent sections will present the syntax
8193 and semantics in more detail.
8196 @c *****************************
8197 @c * Examples of Project Files *
8198 @c *****************************
8200 @node Examples of Project Files
8201 @section Examples of Project Files
8203 This section illustrates some of the typical uses of project files and
8204 explains their basic structure and behavior.
8207 * Common Sources with Different Switches and Different Output Directories::
8208 * Using External Variables::
8209 * Importing Other Projects::
8210 * Extending a Project::
8213 @node Common Sources with Different Switches and Different Output Directories
8214 @subsection Common Sources with Different Switches and Different Output Directories
8218 * Specifying the Object Directory::
8219 * Specifying the Exec Directory::
8220 * Project File Packages::
8221 * Specifying Switch Settings::
8222 * Main Subprograms::
8223 * Source File Naming Conventions::
8224 * Source Language(s)::
8228 Assume that the Ada source files @file{pack.ads}, @file{pack.adb}, and
8229 @file{proc.adb} are in the @file{/common} directory. The file
8230 @file{proc.adb} contains an Ada main subprogram @code{Proc} that "with"s
8231 package @code{Pack}. We want to compile these source files under two sets
8235 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
8236 and the @option{-gnata}, @option{-gnato}, and @option{-gnatE} switches to the
8237 compiler; the compiler's output is to appear in @file{/common/debug}
8239 When preparing a release version, we want to pass the @option{-O2} switch to
8240 the compiler; the compiler's output is to appear in @file{/common/release}
8244 The GNAT project files shown below, respectively @file{debug.gpr} and
8245 @file{release.gpr} in the @file{/common} directory, achieve these effects.
8258 /common/debug @{-g, -gnata, -gnato, -gnatE@}
8263 /common/release @{-O2@}
8268 Here are the project files:
8272 for Object_Dir use "debug";
8273 for Main use ("proc");
8276 for Default_Switches ("Ada") use ("-g");
8282 for Default_Switches ("Ada")
8283 use ("-fstack-check", "-gnata", "-gnato", "-gnatE");
8292 for Object_Dir use "release";
8293 for Exec_Dir use ".";
8294 for Main use ("proc");
8297 for Default_Switches ("Ada") use ("-O2");
8304 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
8305 insensitive), and analogously the project defined by @file{release.gpr} is
8306 @code{"Release"}. For consistency the file should have the same name as the
8307 project, and the project file's extension should be @code{"gpr"}. These
8308 conventions are not required, but a warning is issued if they are not followed.
8310 If the current directory is @file{/temp}, then the command
8312 gnatmake -P/common/debug.gpr
8316 generates object and ALI files in @file{/common/debug}, and the @code{proc}
8317 executable also in @file{/common/debug}, using the switch settings defined in
8320 Likewise, the command
8322 gnatmake -P/common/release.gpr
8326 generates object and ALI files in @file{/common/release}, and the @code{proc}
8327 executable in @file{/common}, using the switch settings from the project file.
8330 @unnumberedsubsubsec Source Files
8333 If a project file does not explicitly specify a set of source directories or
8334 a set of source files, then by default the project's source files are the
8335 Ada source files in the project file directory. Thus @file{pack.ads},
8336 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
8338 @node Specifying the Object Directory
8339 @unnumberedsubsubsec Specifying the Object Directory
8342 Several project properties are modeled by Ada-style @emph{attributes};
8343 you define the property by supplying the equivalent of an Ada attribute
8344 definition clause in the project file.
8345 A project's object directory is such a property; the corresponding
8346 attribute is @code{Object_Dir}, and its value is a string expression. A
8347 directory may be specified either as absolute or as relative; in the latter
8348 case, it is relative to the project file directory. Thus the compiler's
8349 output is directed to @file{/common/debug} (for the @code{Debug} project)
8350 and to @file{/common/release} (for the @code{Release} project). If
8351 @code{Object_Dir} is not specified, then the default is the project file
8354 @node Specifying the Exec Directory
8355 @unnumberedsubsubsec Specifying the Exec Directory
8358 A project's exec directory is another property; the corresponding
8359 attribute is @code{Exec_Dir}, and its value is also a string expression,
8360 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
8361 then the default is the object directory (which may also be the project file
8362 directory if attribute @code{Object_Dir} is not specified). Thus the executable
8363 is placed in @file{/common/debug} for the @code{Debug} project (attribute
8364 @code{Exec_Dir} not specified) and in @file{/common} for the @code{Release}
8367 @node Project File Packages
8368 @unnumberedsubsubsec Project File Packages
8371 A GNAT tool integrated with the Project Manager is modeled by a
8372 corresponding package in the project file.
8373 The @code{Debug} project defines the packages @code{Builder}
8374 (for @command{gnatmake}) and @code{Compiler};
8375 the @code{Release} project defines only the @code{Compiler} package.
8377 The Ada package syntax is not to be taken literally. Although packages in
8378 project files bear a surface resemblance to packages in Ada source code, the
8379 notation is simply a way to convey a grouping of properties for a named
8380 entity. Indeed, the package names permitted in project files are restricted
8381 to a predefined set, corresponding to the project-aware tools, and the contents
8382 of packages are limited to a small set of constructs.
8383 The packages in the example above contain attribute definitions.
8386 @node Specifying Switch Settings
8387 @unnumberedsubsubsec Specifying Switch Settings
8390 Switch settings for a project-aware tool can be specified through attributes
8391 in the package corresponding to the tool.
8392 The example above illustrates one of the relevant attributes,
8393 @code{Default_Switches}, defined in the packages in both project files.
8394 Unlike simple attributes like @code{Source_Dirs}, @code{Default_Switches} is
8395 known as an @emph{associative array}. When you define this attribute, you must
8396 supply an "index" (a literal string), and the effect of the attribute
8397 definition is to set the value of the "array" at the specified "index".
8398 For the @code{Default_Switches} attribute, the index is a programming
8399 language (in our case, Ada) , and the value specified (after @code{use})
8400 must be a list of string expressions.
8402 The attributes permitted in project files are restricted to a predefined set.
8403 Some may appear at project level, others in packages.
8404 For any attribute that is an associate array, the index must always be a
8405 literal string, but the restrictions on this string (e.g., a file name or a
8406 language name) depend on the individual attribute.
8407 Also depending on the attribute, its specified value will need to be either a
8408 string or a string list.
8410 In the @code{Debug} project, we set the switches for two tools,
8411 @command{gnatmake} and the compiler, and thus we include corresponding
8412 packages, with each package defining the @code{Default_Switches} attribute
8413 with index @code{"Ada"}.
8414 Note that the package corresponding to
8415 @command{gnatmake} is named @code{Builder}. The @code{Release} project is
8416 similar, but with just the @code{Compiler} package.
8418 In project @code{Debug} above the switches starting with @option{-gnat} that
8419 are specified in package @code{Compiler} could have been placed in package
8420 @code{Builder}, since @command{gnatmake} transmits all such switches to the
8423 @node Main Subprograms
8424 @unnumberedsubsubsec Main Subprograms
8427 One of the properties of a project is its list of main subprograms (actually
8428 a list of names of source files containing main subprograms, with the file
8429 extension optional. This property is captured in the @code{Main} attribute,
8430 whose value is a list of strings. If a project defines the @code{Main}
8431 attribute, then you do not need to identify the main subprogram(s) when
8432 invoking @command{gnatmake} (see @ref{gnatmake and Project Files}).
8434 @node Source File Naming Conventions
8435 @unnumberedsubsubsec Source File Naming Conventions
8438 Since the project files do not specify any source file naming conventions,
8439 the GNAT defaults are used. The mechanism for defining source file naming
8440 conventions -- a package named @code{Naming} -- will be described below
8441 (@pxref{Naming Schemes}).
8443 @node Source Language(s)
8444 @unnumberedsubsubsec Source Language(s)
8447 Since the project files do not specify a @code{Languages} attribute, by
8448 default the GNAT tools assume that the language of the project file is Ada.
8449 More generally, a project can comprise source files
8450 in Ada, C, and/or other languages.
8452 @node Using External Variables
8453 @subsection Using External Variables
8456 Instead of supplying different project files for debug and release, we can
8457 define a single project file that queries an external variable (set either
8458 on the command line or via an environment variable) in order to
8459 conditionally define the appropriate settings. Again, assume that the
8460 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
8461 located in directory @file{/common}. The following project file,
8462 @file{build.gpr}, queries the external variable named @code{STYLE} and
8463 defines an object directory and switch settings based on whether the value
8464 is @code{"deb"} (debug) or @code{"rel"} (release), where the default is
8470 for Main use ("proc");
8472 type Style_Type is ("deb", "rel");
8473 Style : Style_Type := external ("STYLE", "deb");
8477 for Object_Dir use "debug";
8480 for Object_Dir use "release";
8481 for Exec_Dir use ".";
8490 for Default_Switches ("Ada") use ("-g");
8501 for Default_Switches ("Ada") use ("-gnata", "-gnato", "-gnatE");
8504 for Default_Switches ("Ada") use ("-O2");
8514 @code{Style_Type} is an example of a @emph{string type}, which is the project
8515 file analog of an Ada enumeration type but containing string literals rather
8516 than identifiers. @code{Style} is declared as a variable of this type.
8518 The form @code{external("STYLE", "deb")} is known as an
8519 @emph{external reference}; its first argument is the name of an
8520 @emph{external variable}, and the second argument is a default value to be
8521 used if the external variable doesn't exist. You can define an external
8522 variable on the command line via the @option{-X} switch, or you can use an
8523 environment variable as an external variable.
8525 Each @code{case} construct is expanded by the Project Manager based on the
8526 value of @code{Style}. Thus the command
8528 gnatmake -P/common/build.gpr -XSTYLE=deb
8532 is equivalent to the @command{gnatmake} invocation using the project file
8533 @file{debug.gpr} in the earlier example. So is the command
8535 gnatmake -P/common/build.gpr
8539 since @code{"deb"} is the default for @code{STYLE}.
8543 gnatmake -P/common/build.gpr -XSTYLE=rel
8547 is equivalent to the @command{gnatmake} invocation using the project file
8548 @file{release.gpr} in the earlier example.
8551 @node Importing Other Projects
8552 @subsection Importing Other Projects
8555 A compilation unit in a source file in one project may depend on compilation
8556 units in source files in other projects. To obtain this behavior, the
8557 dependent project must @emph{import} the projects containing the needed source
8558 files. This effect is embodied in syntax similar to an Ada @code{with} clause,
8559 but the "with"ed entities are strings denoting project files.
8561 As an example, suppose that the two projects @code{GUI_Proj} and
8562 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
8563 @file{comm_proj.gpr} in directories @file{/gui} and @file{/comm},
8564 respectively. Assume that the source files for @code{GUI_Proj} are
8565 @file{gui.ads} and @file{gui.adb}, and that the source files for
8566 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, with each set of
8567 files located in its respective project file directory. Diagrammatically:
8586 We want to develop an application in directory @file{/app} that "with"s the
8587 packages @code{GUI} and @code{Comm}, using the properties of the
8588 corresponding project files (e.g. the switch settings and object directory).
8589 Skeletal code for a main procedure might be something like the following:
8594 procedure App_Main is
8603 Here is a project file, @file{app_proj.gpr}, that achieves the desired
8608 with "/gui/gui_proj", "/comm/comm_proj";
8610 for Main use ("app_main");
8616 Building an executable is achieved through the command:
8618 gnatmake -P/app/app_proj
8621 which will generate the @code{app_main} executable in the directory where
8622 @file{app_proj.gpr} resides.
8624 If an imported project file uses the standard extension (@code{gpr}) then
8625 (as illustrated above) the @code{with} clause can omit the extension.
8627 Our example specified an absolute path for each imported project file.
8628 Alternatively, you can omit the directory if either
8631 The imported project file is in the same directory as the importing project
8634 You have defined an environment variable @code{ADA_PROJECT_PATH} that
8635 includes the directory containing the needed project file.
8639 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{/gui} and
8640 @file{/comm}, then our project file @file{app_proj.gpr} could be written as
8645 with "gui_proj", "comm_proj";
8647 for Main use ("app_main");
8653 Importing other projects raises the possibility of ambiguities. For
8654 example, the same unit might be present in different imported projects, or
8655 it might be present in both the importing project and an imported project.
8656 Both of these conditions are errors. Note that in the current version of
8657 the Project Manager, it is illegal to have an ambiguous unit even if the
8658 unit is never referenced by the importing project. This restriction may be
8659 relaxed in a future release.
8661 @node Extending a Project
8662 @subsection Extending a Project
8665 A common situation in large software systems is to have multiple
8666 implementations for a common interface; in Ada terms, multiple versions of a
8667 package body for the same specification. For example, one implementation
8668 might be safe for use in tasking programs, while another might only be used
8669 in sequential applications. This can be modeled in GNAT using the concept
8670 of @emph{project extension}. If one project (the "child") @emph{extends}
8671 another project (the "parent") then by default all source files of the
8672 parent project are inherited by the child, but the child project can
8673 override any of the parent's source files with new versions, and can also
8674 add new files. This facility is the project analog of extension in
8675 Object-Oriented Programming. Project hierarchies are permitted (a child
8676 project may be the parent of yet another project), and a project that
8677 inherits one project can also import other projects.
8679 As an example, suppose that directory @file{/seq} contains the project file
8680 @file{seq_proj.gpr} and the source files @file{pack.ads}, @file{pack.adb},
8681 and @file{proc.adb}:
8694 Note that the project file can simply be empty (that is, no attribute or
8695 package is defined):
8705 implying that its source files are all the Ada source files in the project
8708 Suppose we want to supply an alternate version of @file{pack.adb}, in
8709 directory @file{/tasking}, but use the existing versions of @file{pack.ads}
8710 and @file{proc.adb}. We can define a project @code{Tasking_Proj} that
8711 inherits @code{Seq_Proj}:
8721 project Tasking_Proj extends "/seq/seq_proj" is
8727 The version of @file{pack.adb} used in a build depends on which project file
8730 Note that we could have designed this using project import rather than
8731 project inheritance; a @code{base} project would contain the sources for
8732 @file{pack.ads} and @file{proc.adb}, a sequential project would import
8733 @code{base} and add @file{pack.adb}, and likewise a tasking project would
8734 import @code{base} and add a different version of @file{pack.adb}. The
8735 choice depends on whether other sources in the original project need to be
8736 overridden. If they do, then project extension is necessary, otherwise,
8737 importing is sufficient.
8740 @c ***********************
8741 @c * Project File Syntax *
8742 @c ***********************
8744 @node Project File Syntax
8745 @section Project File Syntax
8754 * Associative Array Attributes::
8755 * case Constructions::
8759 This section describes the structure of project files.
8761 A project may be an @emph{independent project}, entirely defined by a single
8762 project file. Any Ada source file in an independent project depends only
8763 on the predefined library and other Ada source files in the same project.
8766 A project may also @dfn{depend on} other projects, in either or both of the following ways:
8768 @item It may import any number of projects
8769 @item It may extend at most one other project
8773 The dependence relation is a directed acyclic graph (the subgraph reflecting
8774 the "extends" relation is a tree).
8776 A project's @dfn{immediate sources} are the source files directly defined by
8777 that project, either implicitly by residing in the project file's directory,
8778 or explicitly through any of the source-related attributes described below.
8779 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
8780 of @var{proj} together with the immediate sources (unless overridden) of any
8781 project on which @var{proj} depends (either directly or indirectly).
8784 @subsection Basic Syntax
8787 As seen in the earlier examples, project files have an Ada-like syntax.
8788 The minimal project file is:
8798 The identifier @code{Empty} is the name of the project.
8799 This project name must be present after the reserved
8800 word @code{end} at the end of the project file, followed by a semi-colon.
8802 Any name in a project file, such as the project name or a variable name,
8803 has the same syntax as an Ada identifier.
8805 The reserved words of project files are the Ada reserved words plus
8806 @code{extends}, @code{external}, and @code{project}. Note that the only Ada
8807 reserved words currently used in project file syntax are:
8835 Comments in project files have the same syntax as in Ada, two consecutives
8836 hyphens through the end of the line.
8839 @subsection Packages
8842 A project file may contain @emph{packages}. The name of a package must be one
8843 of the identifiers (case insensitive) from a predefined list, and a package
8844 with a given name may only appear once in a project file. The predefined list
8845 includes the following packages:
8861 @code{Cross_Reference}
8867 (The complete list of the package names and their attributes can be found
8868 in file @file{prj-attr.adb}).
8871 In its simplest form, a package may be empty:
8883 A package may contain @emph{attribute declarations},
8884 @emph{variable declarations} and @emph{case constructions}, as will be
8887 When there is ambiguity between a project name and a package name,
8888 the name always designates the project. To avoid possible confusion, it is
8889 always a good idea to avoid naming a project with one of the
8890 names allowed for packages or any name that starts with @code{gnat}.
8894 @subsection Expressions
8897 An @emph{expression} is either a @emph{string expression} or a
8898 @emph{string list expression}.
8900 A @emph{string expression} is either a @emph{simple string expression} or a
8901 @emph{compound string expression}.
8903 A @emph{simple string expression} is one of the following:
8905 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
8906 @item A string-valued variable reference (see @ref{Variables})
8907 @item A string-valued attribute reference (see @ref{Attributes})
8908 @item An external reference (see @ref{External References in Project Files})
8912 A @emph{compound string expression} is a concatenation of string expressions,
8915 Path & "/" & File_Name & ".ads"
8919 A @emph{string list expression} is either a
8920 @emph{simple string list expression} or a
8921 @emph{compound string list expression}.
8923 A @emph{simple string list expression} is one of the following:
8925 @item A parenthesized list of zero or more string expressions, separated by commas
8927 File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
8930 @item A string list-valued variable reference
8931 @item A string list-valued attribute reference
8935 A @emph{compound string list expression} is the concatenation (using
8936 @code{"&"}) of a simple string list expression and an expression. Note that
8937 each term in a compound string list expression, except the first, may be
8938 either a string expression or a string list expression.
8942 File_Name_List := () & File_Name; -- One string in this list
8943 Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
8945 Big_List := File_Name_List & Extended_File_Name_List;
8946 -- Concatenation of two string lists: three strings
8947 Illegal_List := "gnat.adc" & Extended_File_Name_List;
8948 -- Illegal: must start with a string list
8954 @subsection String Types
8957 The value of a variable may be restricted to a list of string literals.
8958 The restricted list of string literals is given in a
8959 @emph{string type declaration}.
8961 Here is an example of a string type declaration:
8964 type OS is ("NT, "nt", "Unix", "Linux", "other OS");
8968 Variables of a string type are called @emph{typed variables}; all other
8969 variables are called @emph{untyped variables}. Typed variables are
8970 particularly useful in @code{case} constructions
8971 (see @ref{case Constructions}).
8973 A string type declaration starts with the reserved word @code{type}, followed
8974 by the name of the string type (case-insensitive), followed by the reserved
8975 word @code{is}, followed by a parenthesized list of one or more string literals
8976 separated by commas, followed by a semicolon.
8978 The string literals in the list are case sensitive and must all be different.
8979 They may include any graphic characters allowed in Ada, including spaces.
8981 A string type may only be declared at the project level, not inside a package.
8983 A string type may be referenced by its name if it has been declared in the same
8984 project file, or by its project name, followed by a dot,
8985 followed by the string type name.
8989 @subsection Variables
8992 A variable may be declared at the project file level, or in a package.
8993 Here are some examples of variable declarations:
8997 This_OS : OS := external ("OS"); -- a typed variable declaration
8998 That_OS := "Linux"; -- an untyped variable declaration
9003 A @emph{typed variable declaration} includes the variable name, followed by a colon,
9004 followed by the name of a string type, followed by @code{:=}, followed by
9005 a simple string expression.
9007 An @emph{untyped variable declaration} includes the variable name,
9008 followed by @code{:=}, followed by an expression. Note that, despite the
9009 terminology, this form of "declaration" resembles more an assignment
9010 than a declaration in Ada. It is a declaration in several senses:
9013 The variable name does not need to be defined previously
9015 The declaration establishes the @emph{kind} (string versus string list) of the
9016 variable, and later declarations of the same variable need to be consistent
9021 A string variable declaration (typed or untyped) declares a variable
9022 whose value is a string. This variable may be used as a string expression.
9024 File_Name := "readme.txt";
9025 Saved_File_Name := File_Name & ".saved";
9029 A string list variable declaration declares a variable whose value is a list
9030 of strings. The list may contain any number (zero or more) of strings.
9034 List_With_One_Element := ("-gnaty");
9035 List_With_Two_Elements := List_With_One_Element & "-gnatg";
9036 Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
9037 "pack2.ada", "util_.ada", "util.ada");
9041 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 or a readonly variable.
9043 The same untyped variable may be declared several times.
9044 In this case, the new value replaces the old one,
9045 and any subsequent reference to the variable uses the new value.
9046 However, as noted above, if a variable has been declared as a string, all subsequent
9047 declarations must give it a string value. Similarly, if a variable has
9048 been declared as a string list, all subsequent declarations
9049 must give it a string list value.
9051 A @emph{variable reference} may take several forms:
9054 @item The simple variable name, for a variable in the current package (if any) or in the current project
9055 @item A context name, followed by a dot, followed by the variable name.
9059 A @emph{context} may be one of the following:
9062 @item The name of an existing package in the current project
9063 @item The name of an imported project of the current project
9064 @item The name of an ancestor project (i.e., a project extended by the current project, either directly or indirectly)
9065 @item An imported/parent project name, followed by a dot, followed by a package name
9069 A variable reference may be used in an expression.
9073 @subsection Attributes
9076 A project (and its packages) may have @emph{attributes} that define the project's properties.
9077 Some attributes have values that are strings;
9078 others have values that are string lists.
9080 There are two categories of attributes: @emph{simple attributes} and @emph{associative arrays}
9081 (see @ref{Associative Array Attributes}).
9083 The names of the attributes are restricted; there is a list of project
9084 attributes, and a list of package attributes for each package.
9085 The names are not case sensitive.
9087 The project attributes are as follows (all are simple attributes):
9089 @multitable @columnfractions .4 .3
9090 @item @emph{Attribute Name}
9092 @item @code{Source_Files}
9094 @item @code{Source_Dirs}
9096 @item @code{Source_List_File}
9098 @item @code{Object_Dir}
9100 @item @code{Exec_Dir}
9104 @item @code{Languages}
9106 @item @code{Library_Dir}
9108 @item @code{Library_Name}
9110 @item @code{Library_Kind}
9112 @item @code{Library_Elaboration}
9114 @item @code{Library_Version}
9119 The attributes for package @code{Naming} are as follows
9120 (see @ref{Naming Schemes}):
9122 @multitable @columnfractions .4 .2 .2 .2
9123 @item Attribute Name @tab Category @tab Index @tab Value
9124 @item @code{Specification_Suffix}
9125 @tab associative array
9128 @item @code{Implementation_Suffix}
9129 @tab associative array
9132 @item @code{Separate_Suffix}
9133 @tab simple attribute
9137 @tab simple attribute
9140 @item @code{Dot_Replacement}
9141 @tab simple attribute
9144 @item @code{Specification}
9145 @tab associative array
9148 @item @code{Implementation}
9149 @tab associative array
9152 @item @code{Specification_Exceptions}
9153 @tab associative array
9156 @item @code{Implementation_Exceptions}
9157 @tab associative array
9163 The attributes for package @code{Builder}, @code{Compiler}, @code{Binder},
9164 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
9165 are as follows (see @ref{Switches and Project Files}).
9167 @multitable @columnfractions .4 .2 .2 .2
9168 @item Attribute Name @tab Category @tab Index @tab Value
9169 @item @code{Default_Switches}
9170 @tab associative array
9173 @item @code{Switches}
9174 @tab associative array
9180 In addition, package @code{Builder} has a single string attribute
9181 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
9182 string attribute @code{Global_Configuration_Pragmas}.
9185 The attribute for package @code{Glide} are not documented: they are for
9189 Each simple attribute has a default value: the empty string (for string-valued
9190 attributes) and the empty list (for string list-valued attributes).
9192 Similar to variable declarations, an attribute declaration defines a new value
9195 Examples of simple attribute declarations:
9198 for Object_Dir use "objects";
9199 for Source_Dirs use ("units", "test/drivers");
9203 A @dfn{simple attribute declaration} starts with the reserved word @code{for},
9204 followed by the name of the attribute, followed by the reserved word
9205 @code{use}, followed by an expression (whose kind depends on the attribute),
9206 followed by a semicolon.
9208 Attributes may be referenced in expressions.
9209 The general form for such a reference is @code{<entity>'<attribute>}:
9210 the entity for which the attribute is defined,
9211 followed by an apostrophe, followed by the name of the attribute.
9212 For associative array attributes, a litteral string between parentheses
9213 need to be supplied as index.
9219 Naming'Dot_Replacement
9220 Imported_Project'Source_Dirs
9221 Imported_Project.Naming'Casing
9222 Builder'Default_Switches("Ada")
9228 @item @code{project} for an attribute of the current project
9229 @item The name of an existing package of the current project
9230 @item The name of an imported project
9231 @item The name of a parent project (extended by the current project)
9232 @item An imported/parent project name, followed by a dot,
9233 followed by a package name
9241 for Source_Dirs use project'Source_Dirs & "units";
9242 for Source_Dirs use project'Source_Dirs & "test/drivers"
9248 In the first attribute declaration, initially the attribute @code{Source_Dirs}
9249 has the default value: an empty string list. After this declaration,
9250 @code{Source_Dirs} is a string list of one element: "units".
9251 After the second attribute declaration @code{Source_Dirs} is a string list of
9252 two elements: "units" and "test/drivers".
9254 Note: this example is for illustration only. In practice,
9255 the project file would contain only one attribute declaration:
9258 for Source_Dirs use ("units", "test/drivers");
9262 @node Associative Array Attributes
9263 @subsection Associative Array Attributes
9266 Some attributes are defined as @emph{associative arrays}. An associative
9267 array may be regarded as a function that takes a string as a parameter
9268 and delivers a string or string list value as its result.
9270 Here are some examples of associative array attribute declarations:
9273 for Implementation ("main") use "Main.ada";
9274 for Switches ("main.ada") use ("-v", "-gnatv");
9275 for Switches ("main.ada") use Builder'Switches ("main.ada") & "-g";
9279 Like untyped variables and simple attributes, associative array attributes may be declared several times. Each declaration supplies a new value for the
9280 attribute, replacing the previous setting.
9283 @node case Constructions
9284 @subsection @code{case} Constructions
9287 A @code{case} construction is used in a project file to effect conditional
9289 Here is a typical example:
9294 type OS_Type is ("Linux", "Unix", "NT", "VMS");
9296 OS : OS_Type := external ("OS", "Linux");
9302 when "Linux" | "Unix" =>
9303 for Default_Switches ("Ada") use ("-gnath");
9305 for Default_Switches ("Ada") use ("-gnatP");
9314 The syntax of a @code{case} construction is based on the Ada case statement
9315 (although there is no @code{null} construction for empty alternatives).
9317 Following the reserved word @code{case} there is the case variable (a typed
9318 string variable), the reserved word @code{is}, and then a sequence of one or
9320 Each alternative comprises the reserved word @code{when}, either a list of
9321 literal strings separated by the @code{"|"} character or the reserved word
9322 @code{others}, and the @code{"=>"} token.
9323 Each literal string must belong to the string type that is the type of the
9325 An @code{others} alternative, if present, must occur last.
9326 The @code{end case;} sequence terminates the case construction.
9328 After each @code{=>}, there are zero or more constructions. The only
9329 constructions allowed in a case construction are other case constructions and
9330 attribute declarations. String type declarations, variable declarations and
9331 package declarations are not allowed.
9333 The value of the case variable is often given by an external reference
9334 (see @ref{External References in Project Files}).
9337 @c ****************************************
9338 @c * Objects and Sources in Project Files *
9339 @c ****************************************
9341 @node Objects and Sources in Project Files
9342 @section Objects and Sources in Project Files
9345 * Object Directory::
9347 * Source Directories::
9348 * Source File Names::
9352 Each project has exactly one object directory and one or more source
9353 directories. The source directories must contain at least one source file,
9354 unless the project file explicitly specifies that no source files are present
9355 (see @ref{Source File Names}).
9358 @node Object Directory
9359 @subsection Object Directory
9362 The object directory for a project is the directory containing the compiler's
9363 output (such as @file{ALI} files and object files) for the project's immediate
9364 sources. Note that for inherited sources (when extending a parent project) the
9365 parent project's object directory is used.
9367 The object directory is given by the value of the attribute @code{Object_Dir}
9368 in the project file.
9371 for Object_Dir use "objects";
9375 The attribute @var{Object_Dir} has a string value, the path name of the object
9376 directory. The path name may be absolute or relative to the directory of the
9377 project file. This directory must already exist, and be readable and writable.
9379 By default, when the attribute @code{Object_Dir} is not given an explicit value
9380 or when its value is the empty string, the object directory is the same as the
9381 directory containing the project file.
9384 @node Exec Directory
9385 @subsection Exec Directory
9388 The exec directory for a project is the directory containing the executables
9389 for the project's main subprograms.
9391 The exec directory is given by the value of the attribute @code{Exec_Dir}
9392 in the project file.
9395 for Exec_Dir use "executables";
9399 The attribute @var{Exec_Dir} has a string value, the path name of the exec
9400 directory. The path name may be absolute or relative to the directory of the
9401 project file. This directory must already exist, and be writable.
9403 By default, when the attribute @code{Exec_Dir} is not given an explicit value
9404 or when its value is the empty string, the exec directory is the same as the
9405 object directory of the project file.
9408 @node Source Directories
9409 @subsection Source Directories
9412 The source directories of a project are specified by the project file
9413 attribute @code{Source_Dirs}.
9415 This attribute's value is a string list. If the attribute is not given an
9416 explicit value, then there is only one source directory, the one where the
9417 project file resides.
9419 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
9423 for Source_Dirs use ();
9427 indicates that the project contains no source files.
9429 Otherwise, each string in the string list designates one or more
9433 for Source_Dirs use ("sources", "test/drivers");
9437 If a string in the list ends with @code{"/**"}, then the directory whose path
9438 name precedes the two asterisks, as well as all its subdirectories
9439 (recursively), are source directories.
9442 for Source_Dirs use ("/system/sources/**");
9446 Here the directory @code{/system/sources} and all of its subdirectories
9447 (recursively) are source directories.
9449 To specify that the source directories are the directory of the project file
9450 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
9452 for Source_Dirs use ("./**");
9456 Each of the source directories must exist and be readable.
9459 @node Source File Names
9460 @subsection Source File Names
9463 In a project that contains source files, their names may be specified by the
9464 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
9465 (a string). Source file names never include any directory information.
9467 If the attribute @code{Source_Files} is given an explicit value, then each
9468 element of the list is a source file name.
9471 for Source_Files use ("main.adb");
9472 for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
9476 If the attribute @code{Source_Files} is not given an explicit value,
9477 but the attribute @code{Source_List_File} is given a string value,
9478 then the source file names are contained in the text file whose path name
9479 (absolute or relative to the directory of the project file) is the
9480 value of the attribute @code{Source_List_File}.
9482 Each line in the file that is not empty or is not a comment
9483 contains a source file name. A comment line starts with two hyphens.
9486 for Source_List_File use "source_list.txt";
9490 By default, if neither the attribute @code{Source_Files} nor the attribute
9491 @code{Source_List_File} is given an explicit value, then each file in the
9492 source directories that conforms to the project's naming scheme
9493 (see @ref{Naming Schemes}) is an immediate source of the project.
9495 A warning is issued if both attributes @code{Source_Files} and
9496 @code{Source_List_File} are given explicit values. In this case, the attribute
9497 @code{Source_Files} prevails.
9499 Each source file name must be the name of one and only one existing source file
9500 in one of the source directories.
9502 A @code{Source_Files} attribute defined with an empty list as its value
9503 indicates that there are no source files in the project.
9505 Except for projects that are clearly specified as containing no Ada source
9506 files (@code{Source_Dirs} or @code{Source_Files} specified as an empty list,
9507 or @code{Languages} specified without @code{"Ada"} in the list)
9509 for Source_Dirs use ();
9510 for Source_Files use ();
9511 for Languages use ("C", "C++");
9515 a project must contain at least one immediate source.
9517 Projects with no source files are useful as template packages
9518 (see @ref{Packages in Project Files}) for other projects; in particular to
9519 define a package @code{Naming} (see @ref{Naming Schemes}).
9522 @c ****************************
9523 @c * Importing Projects *
9524 @c ****************************
9526 @node Importing Projects
9527 @section Importing Projects
9530 An immediate source of a project P may depend on source files that
9531 are neither immediate sources of P nor in the predefined library.
9532 To get this effect, P must @emph{import} the projects that contain the needed
9537 with "project1", "utilities.gpr";
9538 with "/namings/apex.gpr";
9545 As can be seen in this example, the syntax for importing projects is similar
9546 to the syntax for importing compilation units in Ada. However, project files
9547 use literal strings instead of names, and the @code{with} clause identifies
9548 project files rather than packages.
9550 Each literal string is the file name or path name (absolute or relative) of a
9551 project file. If a string is simply a file name, with no path, then its
9552 location is determined by the @emph{project path}:
9556 If the environment variable @env{ADA_PROJECT_PATH} exists, then the project
9557 path includes all the directories in this environment variable, plus the
9558 directory of the project file.
9561 If the environment variable @env{ADA_PROJECT_PATH} does not exist,
9562 then the project path contains only one directory, namely the one where
9563 the project file is located.
9567 If a relative pathname is used as in
9574 then the path is relative to the directory where the importing project file is
9575 located. Any symbolic link will be fully resolved in the directory
9576 of the importing project file before the imported project file is looked up.
9578 When the @code{with}'ed project file name does not have an extension,
9579 the default is @file{.gpr}. If a file with this extension is not found, then
9580 the file name as specified in the @code{with} clause (no extension) will be
9581 used. In the above example, if a file @code{project1.gpr} is found, then it
9582 will be used; otherwise, if a file @code{project1} exists then it will be used;
9583 if neither file exists, this is an error.
9585 A warning is issued if the name of the project file does not match the
9586 name of the project; this check is case insensitive.
9588 Any source file that is an immediate source of the imported project can be
9589 used by the immediate sources of the importing project, and recursively. Thus
9590 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
9591 sources of @code{A} may depend on the immediate sources of @code{C}, even if
9592 @code{A} does not import @code{C} explicitly. However, this is not recommended,
9593 because if and when @code{B} ceases to import @code{C}, some sources in
9594 @code{A} will no longer compile.
9596 A side effect of this capability is that cyclic dependences are not permitted:
9597 if @code{A} imports @code{B} (directly or indirectly) then @code{B} is not
9598 allowed to import @code{A}.
9601 @c *********************
9602 @c * Project Extension *
9603 @c *********************
9605 @node Project Extension
9606 @section Project Extension
9609 During development of a large system, it is sometimes necessary to use
9610 modified versions of some of the source files without changing the original
9611 sources. This can be achieved through a facility known as
9612 @emph{project extension}.
9615 project Modified_Utilities extends "/baseline/utilities.gpr" is ...
9619 The project file for the project being extended (the @emph{parent}) is
9620 identified by the literal string that follows the reserved word @code{extends},
9621 which itself follows the name of the extending project (the @emph{child}).
9623 By default, a child project inherits all the sources of its parent.
9624 However, inherited sources can be overridden: a unit with the same name as one
9625 in the parent will hide the original unit.
9626 Inherited sources are considered to be sources (but not immediate sources)
9627 of the child project; see @ref{Project File Syntax}.
9629 An inherited source file retains any switches specified in the parent project.
9631 For example if the project @code{Utilities} contains the specification and the
9632 body of an Ada package @code{Util_IO}, then the project
9633 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
9634 The original body of @code{Util_IO} will not be considered in program builds.
9635 However, the package specification will still be found in the project
9638 A child project can have only one parent but it may import any number of other
9641 A project is not allowed to import directly or indirectly at the same time a
9642 child project and any of its ancestors.
9645 @c ****************************************
9646 @c * External References in Project Files *
9647 @c ****************************************
9649 @node External References in Project Files
9650 @section External References in Project Files
9653 A project file may contain references to external variables; such references
9654 are called @emph{external references}.
9656 An external variable is either defined as part of the environment (an
9657 environment variable in Unix, for example) or else specified on the command
9658 line via the @option{-X@emph{vbl}=@emph{value}} switch. If both, then the
9659 command line value is used.
9661 An external reference is denoted by the built-in function
9662 @code{external}, which returns a string value. This function has two forms:
9664 @item @code{external (external_variable_name)}
9665 @item @code{external (external_variable_name, default_value)}
9669 Each parameter must be a string literal. For example:
9673 external ("OS", "Linux")
9677 In the form with one parameter, the function returns the value of
9678 the external variable given as parameter. If this name is not present in the
9679 environment, then the returned value is an empty string.
9681 In the form with two string parameters, the second parameter is
9682 the value returned when the variable given as the first parameter is not
9683 present in the environment. In the example above, if @code{"OS"} is not
9684 the name of an environment variable and is not passed on the command line,
9685 then the returned value will be @code{"Linux"}.
9687 An external reference may be part of a string expression or of a string
9688 list expression, to define variables or attributes.
9692 type Mode_Type is ("Debug", "Release");
9693 Mode : Mode_Type := external ("MODE");
9701 @c *****************************
9702 @c * Packages in Project Files *
9703 @c *****************************
9705 @node Packages in Project Files
9706 @section Packages in Project Files
9709 The @emph{package} is the project file feature that defines the settings for
9710 project-aware tools.
9711 For each such tool you can declare a corresponding package; the names for these
9712 packages are preset (see @ref{Packages}) but are not case sensitive.
9713 A package may contain variable declarations, attribute declarations, and case
9719 package Builder is -- used by gnatmake
9720 for Default_Switches ("Ada") use ("-v", "-g");
9727 A package declaration starts with the reserved word @code{package},
9728 followed by the package name (case insensitive), followed by the reserved word
9729 @code{is}. It ends with the reserved word @code{end}, followed by the package
9730 name, finally followed by a semi-colon.
9732 Most of the packages have an attribute @code{Default_Switches}.
9733 This attribute is an associative array, and its value is a string list.
9734 The index of the associative array is the name of a programming language (case
9735 insensitive). This attribute indicates the switch or switches to be used
9736 with the corresponding tool.
9738 Some packages also have another attribute, @code{Switches}, an associative
9739 array whose value is a string list. The index is the name of a source file.
9740 This attribute indicates the switch or switches to be used by the corresponding
9741 tool when dealing with this specific file.
9743 Further information on these switch-related attributes is found in
9744 @ref{Switches and Project Files}.
9746 A package may be declared as a @emph{renaming} of another package; e.g., from
9747 the project file for an imported project.
9751 with "/global/apex.gpr";
9753 package Naming renames Apex.Naming;
9760 Packages that are renamed in other project files often come from project files
9761 that have no sources: they are just used as templates. Any modification in the
9762 template will be reflected automatically in all the project files that rename
9763 a package from the template.
9765 In addition to the tool-oriented packages, you can also declare a package
9766 named @code{Naming} to establish specialized source file naming conventions
9767 (see @ref{Naming Schemes}).
9770 @c ************************************
9771 @c * Variables from Imported Projects *
9772 @c ************************************
9774 @node Variables from Imported Projects
9775 @section Variables from Imported Projects
9778 An attribute or variable defined in an imported or parent project can
9779 be used in expressions in the importing / extending project.
9780 Such an attribute or variable is prefixed with the name of the project
9781 and (if relevant) the name of package where it is defined.
9786 project Main extends "base" is
9787 Var1 := Imported.Var;
9788 Var2 := Base.Var & ".new";
9793 for Default_Switches ("Ada") use Imported.Builder.Ada_Switches &
9800 for Default_Switches ("Ada") use Base.Compiler.Ada_Switches;
9811 @code{Var1} is a copy of the variable @code{Var} defined in the project file
9812 @file{"imported.gpr"}
9814 the value of @code{Var2} is a copy of the value of variable @code{Var}
9815 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
9817 attribute @code{Default_Switches ("Ada")} in package @code{Builder}
9818 is a string list that includes in its value a copy of variable
9819 @code{Ada_Switches} defined in the @code{Builder} package in project file
9820 @file{imported.gpr} plus two new elements: @option{"-gnatg"} and @option{"-v"};
9822 attribute @code{Default_Switches ("Ada")} in package @code{Compiler}
9823 is a copy of the variable @code{Ada_Switches} defined in the @code{Compiler}
9824 package in project file @file{base.gpr}, the project being extended.
9828 @c ******************
9829 @c * Naming Schemes *
9830 @c ******************
9832 @node Naming Schemes
9833 @section Naming Schemes
9836 Sometimes an Ada software system is ported from a foreign compilation
9837 environment to GNAT, with file names that do not use the default GNAT
9838 conventions. Instead of changing all the file names (which for a variety of
9839 reasons might not be possible), you can define the relevant file naming scheme
9840 in the @code{Naming} package in your project file. For example, the following
9841 package models the Apex file naming rules:
9846 for Casing use "lowercase";
9847 for Dot_Replacement use ".";
9848 for Specification_Suffix ("Ada") use ".1.ada";
9849 for Implementation_Suffix ("Ada") use ".2.ada";
9855 You can define the following attributes in package @code{Naming}:
9860 This must be a string with one of the three values @code{"lowercase"},
9861 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
9864 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
9866 @item @var{Dot_Replacement}
9867 This must be a string whose value satisfies the following conditions:
9870 @item It must not be empty
9871 @item It cannot start or end with an alphanumeric character
9872 @item It cannot be a single underscore
9873 @item It cannot start with an underscore followed by an alphanumeric
9874 @item It cannot contain a dot @code{'.'} except if it the entire string is @code{"."}
9878 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
9880 @item @var{Specification_Suffix}
9881 This is an associative array (indexed by the programming language name, case
9882 insensitive) whose value is a string that must satisfy the following
9886 @item It must not be empty
9887 @item It cannot start with an alphanumeric character
9888 @item It cannot start with an underscore followed by an alphanumeric character
9891 If @code{Specification_Suffix ("Ada")} is not specified, then the default is
9894 @item @var{Implementation_Suffix}
9895 This is an associative array (indexed by the programming language name, case
9896 insensitive) whose value is a string that must satisfy the following
9900 @item It must not be empty
9901 @item It cannot start with an alphanumeric character
9902 @item It cannot start with an underscore followed by an alphanumeric character
9903 @item It cannot be a suffix of @code{Specification_Suffix}
9906 If @code{Implementation_Suffix ("Ada")} is not specified, then the default is
9909 @item @var{Separate_Suffix}
9910 This must be a string whose value satisfies the same conditions as
9911 @code{Implementation_Suffix}.
9914 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
9915 value as @code{Implementation_Suffix ("Ada")}.
9917 @item @var{Specification}
9919 You can use the @code{Specification} attribute, an associative array, to define
9920 the source file name for an individual Ada compilation unit's spec. The array
9921 index must be a string literal that identifies the Ada unit (case insensitive).
9922 The value of this attribute must be a string that identifies the file that
9923 contains this unit's spec (case sensitive or insensitive depending on the
9927 for Specification ("MyPack.MyChild") use "mypack.mychild.spec";
9930 @item @var{Implementation}
9932 You can use the @code{Implementation} attribute, an associative array, to
9933 define the source file name for an individual Ada compilation unit's body
9934 (possibly a subunit). The array index must be a string literal that identifies
9935 the Ada unit (case insensitive). The value of this attribute must be a string
9936 that identifies the file that contains this unit's body or subunit (case
9937 sensitive or insensitive depending on the operating system).
9940 for Implementation ("MyPack.MyChild") use "mypack.mychild.body";
9945 @c ********************
9946 @c * Library Projects *
9947 @c ********************
9949 @node Library Projects
9950 @section Library Projects
9953 @emph{Library projects} are projects whose object code is placed in a library.
9954 (Note that this facility is not yet supported on all platforms)
9956 To create a library project, you need to define in its project file
9957 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
9958 Additionally, you may define the library-related attributes
9959 @code{Library_Kind}, @code{Library_Version} and @code{Library_Elaboration}.
9961 The @code{Library_Name} attribute has a string value that must start with a
9962 letter and include only letters and digits.
9964 The @code{Library_Dir} attribute has a string value that designates the path
9965 (absolute or relative) of the directory where the library will reside.
9966 It must designate an existing directory, and this directory needs to be
9967 different from the project's object directory. It also needs to be writable.
9969 If both @code{Library_Name} and @code{Library_Dir} are specified and
9970 are legal, then the project file defines a library project. The optional
9971 library-related attributes are checked only for such project files.
9973 The @code{Library_Kind} attribute has a string value that must be one of the
9974 following (case insensitive): @code{"static"}, @code{"dynamic"} or
9975 @code{"relocatable"}. If this attribute is not specified, the library is a
9976 static library. Otherwise, the library may be dynamic or relocatable.
9977 Depending on the operating system, there may or may not be a distinction
9978 between dynamic and relocatable libraries. For example, on Unix there is no
9981 The @code{Library_Version} attribute has a string value whose interpretation
9982 is platform dependent. On Unix, it is used only for dynamic/relocatable
9983 libraries as the internal name of the library (the @code{"soname"}). If the
9984 library file name (built from the @code{Library_Name}) is different from the
9985 @code{Library_Version}, then the library file will be a symbolic link to the
9986 actual file whose name will be @code{Library_Version}.
9996 for Library_Dir use "lib_dir";
9997 for Library_Name use "dummy";
9998 for Library_Kind use "relocatable";
9999 for Library_Version use "libdummy.so." & Version;
10006 Directory @file{lib_dir} will contain the internal library file whose name
10007 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
10008 @file{libdummy.so.1}.
10010 When @command{gnatmake} detects that a project file (not the main project file)
10011 is a library project file, it will check all immediate sources of the project
10012 and rebuild the library if any of the sources have been recompiled.
10013 All @file{ALI} files will also be copied from the object directory to the
10014 library directory. To build executables, @command{gnatmake} will use the
10015 library rather than the individual object files.
10018 @c *************************************
10019 @c * Switches Related to Project Files *
10020 @c *************************************
10021 @node Switches Related to Project Files
10022 @section Switches Related to Project Files
10025 The following switches are used by GNAT tools that support project files:
10029 @item @option{-P@var{project}}
10030 Indicates the name of a project file. This project file will be parsed with
10031 the verbosity indicated by @option{-vP@emph{x}}, if any, and using the external
10032 references indicated by @option{-X} switches, if any.
10035 There must be only one @option{-P} switch on the command line.
10038 Since the Project Manager parses the project file only after all the switches
10039 on the command line are checked, the order of the switches @option{-P},
10040 @option{-Vp@emph{x}} or @option{-X} is not significant.
10042 @item @option{-X@var{name=value}}
10043 Indicates that external variable @var{name} has the value @var{value}.
10044 The Project Manager will use this value for occurrences of
10045 @code{external(name)} when parsing the project file.
10048 If @var{name} or @var{value} includes a space, then @var{name=value} should be
10049 put between quotes.
10056 Several @option{-X} switches can be used simultaneously.
10057 If several @option{-X} switches specify the same @var{name}, only the last one
10061 An external variable specified with a @option{-X} switch takes precedence
10062 over the value of the same name in the environment.
10064 @item @option{-vP@emph{x}}
10065 Indicates the verbosity of the parsing of GNAT project files.
10066 @option{-vP0} means Default (no output for syntactically correct project
10068 @option{-vP1} means Medium;
10069 @option{-vP2} means High.
10071 The default is Default.
10073 If several @option{-vP@emph{x}} switches are present, only the last one is
10079 @c **********************************
10080 @c * Tools Supporting Project Files *
10081 @c **********************************
10083 @node Tools Supporting Project Files
10084 @section Tools Supporting Project Files
10087 * gnatmake and Project Files::
10088 * The GNAT Driver and Project Files::
10089 * Glide and Project Files::
10092 @node gnatmake and Project Files
10093 @subsection gnatmake and Project Files
10096 This section covers two topics related to @command{gnatmake} and project files:
10097 defining switches for @command{gnatmake} and for the tools that it invokes;
10098 and the use of the @code{Main} attribute.
10101 * Switches and Project Files::
10102 * Project Files and Main Subprograms::
10105 @node Switches and Project Files
10106 @subsubsection Switches and Project Files
10109 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
10110 @code{Linker}, you can specify a @code{Default_Switches} attribute, a
10111 @code{Switches} attribute, or both; as their names imply, these switch-related
10112 attributes affect which switches are used for which files when
10113 @command{gnatmake} is invoked. As will be explained below, these
10114 package-contributed switches precede the switches passed on the
10115 @command{gnatmake} command line.
10117 The @code{Default_Switches} attribute is an associative array indexed by
10118 language name (case insensitive) and returning a string list. For example:
10122 package Compiler is
10123 for Default_Switches ("Ada") use ("-gnaty", "-v");
10129 The @code{Switches} attribute is also an associative array, indexed by a file
10130 name (which may or may not be case sensitive, depending on the operating
10131 system) and returning a string list. For example:
10136 for Switches ("main1.adb") use ("-O2");
10137 for Switches ("main2.adb") use ("-g");
10143 For the @code{Builder} package, the file names should designate source files
10144 for main subprograms. For the @code{Binder} and @code{Linker} packages, the
10145 file names should designate @file{ALI} or source files for main subprograms.
10146 In each case just the file name (without explicit extension) is acceptable.
10148 For each tool used in a program build (@command{gnatmake}, the compiler, the
10149 binder, and the linker), its corresponding package @dfn{contributes} a set of
10150 switches for each file on which the tool is invoked, based on the
10151 switch-related attributes defined in the package. In particular, the switches
10152 that each of these packages contributes for a given file @var{f} comprise:
10156 the value of attribute @code{Switches (@var{f})}, if it is specified in the
10157 package for the given file,
10159 otherwise, the value of @code{Default_Switches ("Ada")}, if it is specified in
10164 If neither of these attributes is defined in the package, then the package does
10165 not contribute any switches for the given file.
10167 When @command{gnatmake} is invoked on a file, the switches comprise two sets,
10168 in the following order: those contributed for the file by the @code{Builder}
10169 package; and the switches passed on the command line.
10171 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
10172 the switches passed to the tool comprise three sets, in the following order:
10176 the applicable switches contributed for the file by the @code{Builder} package
10177 in the project file supplied on the command line;
10180 those contributed for the file by the package (in the relevant project file --
10181 see below) corresponding to the tool; and
10184 the applicable switches passed on the command line.
10188 The term @emph{applicable switches} reflects the fact that @command{gnatmake}
10189 switches may or may not be passed to individual tools, depending on the
10192 @command{gnatmake} may invoke the compiler on source files from different
10193 projects. The Project Manager will use the appropriate project file to
10194 determine the @code{Compiler} package for each source file being compiled.
10195 Likewise for the @code{Binder} and @code{Linker} packages.
10197 As an example, consider the following package in a project file:
10202 package Compiler is
10203 for Default_Switches ("Ada") use ("-g");
10204 for Switches ("a.adb") use ("-O1");
10205 for Switches ("b.adb") use ("-O2", "-gnaty");
10212 If @command{gnatmake} is invoked with this project file, and it needs to
10213 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
10214 @file{a.adb} will be compiled with the switch @option{-O1}, @file{b.adb}
10215 with switches @option{-O2} and @option{-gnaty}, and @file{c.adb} with
10218 Another example illustrates the ordering of the switches contributed by
10219 different packages:
10225 for Switches ("main.adb") use ("-g", "-O1", "-f");
10230 package Compiler is
10231 for Switches ("main.adb") use ("-O2");
10238 If you issue the command:
10241 gnatmake -PProj2 -O0 main
10245 then the compiler will be invoked on @file{main.adb} with the following sequence of switches
10251 with the last @option{-O} switch having precedence over the earlier ones;
10252 several other switches (such as @option{-c}) are added implicitly.
10254 The switches @option{-g} and @option{-O1} are contributed by package
10255 @code{Builder}, @option{-O2} is contributed by the package @code{Compiler}
10256 and @option{-O0} comes from the command line.
10258 The @option{-g} switch will also be passed in the invocation of
10259 @command{gnatlink.}
10261 A final example illustrates switch contributions from packages in different
10267 for Source_Files use ("pack.ads", "pack.adb");
10268 package Compiler is
10269 for Default_Switches ("Ada") use ("-gnata");
10277 for Source_Files use ("foo_main.adb", "bar_main.adb");
10279 for Switches ("foo_main.adb") use ("-s", "-g");
10285 -- Ada source file:
10287 procedure Foo_Main is
10295 gnatmake -PProj4 foo_main.adb -cargs -gnato
10299 then the switches passed to the compiler for @file{foo_main.adb} are
10300 @option{-g} (contributed by the package @code{Proj4.Builder}) and
10301 @option{-gnato} (passed on the command line).
10302 When the imported package @code{Pack} is compiled, the switches used are
10303 @option{-g} from @code{Proj4.Builder}, @option{-gnata} (contributed from
10304 package @code{Proj3.Compiler}, and @option{-gnato} from the command line.
10307 @node Project Files and Main Subprograms
10308 @subsubsection Project Files and Main Subprograms
10311 When using a project file, you can invoke @command{gnatmake}
10312 with several main subprograms, by specifying their source files on the command
10313 line. Each of these needs to be an immediate source file of the project.
10316 gnatmake -Pprj main1 main2 main3
10320 When using a project file, you can also invoke @command{gnatmake} without
10321 explicitly specifying any main, and the effect depends on whether you have
10322 defined the @code{Main} attribute. This attribute has a string list value,
10323 where each element in the list is the name of a source file (the file
10324 extension is optional) containing a main subprogram.
10326 If the @code{Main} attribute is defined in a project file as a non-empty
10327 string list and the switch @option{-u} is not used on the command line, then
10328 invoking @command{gnatmake} with this project file but without any main on the
10329 command line is equivalent to invoking @command{gnatmake} with all the file
10330 names in the @code{Main} attribute on the command line.
10336 for Main use ("main1", "main2", "main3");
10342 With this project file, @code{"gnatmake -Pprj"} is equivalent to
10343 @code{"gnatmake -Pprj main1 main2 main3"}.
10345 When the project attribute @code{Main} is not specified, or is specified
10346 as an empty string list, or when the switch @option{-u} is used on the command
10347 line, then invoking @command{gnatmake} with no main on the command line will
10348 result in all immediate sources of the project file being checked, and
10349 potentially recompiled. Depending on the presence of the switch @option{-u},
10350 sources from other project files on which the immediate sources of the main
10351 project file depend are also checked and potentially recompiled. In other
10352 words, the @option{-u} switch is applied to all of the immediate sources of themain project file.
10355 @node The GNAT Driver and Project Files
10356 @subsection The GNAT Driver and Project Files
10359 A number of GNAT tools, other than @command{gnatmake} are project-aware:
10360 @command{gnatbind}, @command{gnatfind}, @command{gnatlink}, @command{gnatls}
10361 and @command{gnatxref}. However, none of these tools can be invoked directly
10362 with a project file switch (@code{-P}). They need to be invoke through the
10363 @command{gnat} driver.
10365 The @command{gnat} driver is a front-end that accepts a number of commands and
10366 call the corresponding tool. It has been designed initially for VMS to convert
10367 VMS style qualifiers to Unix style switches, but it is now available to all
10368 the GNAT supported platforms.
10370 On non VMS platforms, the @command{gnat} driver accepts the following commands
10371 (case insensitive):
10375 BIND to invoke @command{gnatbind}
10377 CHOP to invoke @command{gnatchop}
10379 COMP or COMPILE to invoke the compiler
10381 ELIM to invoke @command{gnatelim}
10383 FIND to invoke @command{gnatfind}
10385 KR or KRUNCH to invoke @command{gnatkr}
10387 LINK to invoke @command{gnatlink}
10389 LS or LIST to invoke @command{gnatls}
10391 MAKE to invoke @command{gnatmake}
10393 NAME to invoke @command{gnatname}
10395 PREP or PREPROCESS to invoke @command{gnatprep}
10397 PSTA or STANDARD to invoke @command{gnatpsta}
10399 STUB to invoke @command{gnatstub}
10401 XREF to invoke @command{gnatxref}
10405 Note that the compiler is invoked using the command @command{gnatmake -f -u}.
10408 Following the command, you may put switches and arguments for the invoked
10412 gnat bind -C main.ali
10418 In addition, for command BIND, FIND, LS or LIST, LINK and XREF, the project
10419 file related switches (@code{-P}, @code{-X} and @code{-vPx}) may be used in
10420 addition to the switches of the invoking tool.
10423 For each of these command, there is possibly a package in the main project that
10424 corresponds to the invoked tool.
10428 package @code{Binder} for command BIND (invoking @code{gnatbind})
10431 package @code{Finder} for command FIND (invoking @code{gnatfind})
10434 package @code{Gnatls} for command LS or LIST (invoking @code{gnatls})
10437 package @code{Linker} for command LINK (invoking @code{gnatlink})
10440 package @code{Cross_Reference} for command XREF (invoking @code{gnatlink})
10445 Package @code{Gnatls} has a unique attribute @code{Switches}, a simple variable
10446 with a string list value. It contains switches for the invocation of
10453 for Switches use ("-a", "-v");
10460 All other packages contains a switch @code{Default_Switches}, an associative
10461 array, indexed by the programming language (case insensitive) and having a
10462 string list value. @code{Default_Switches ("Ada")} contains the switches for
10463 the invocation of the tool corresponding to the package.
10469 for Source_Dirs use ("./**");
10472 for Switches use ("-a", "-v");
10478 for Default_Switches ("Ada") use ("-C", "-e");
10484 for Default_Switches ("Ada") use ("-C");
10490 for Default_Switches ("Ada") use ("-a", "-f");
10495 package Cross_Reference is
10496 for Default_Switches ("Ada") use ("-a", "-f", "-d", "-u");
10497 end Cross_Reference;
10503 With the above project file, commands such as
10506 gnat ls -Pproj main
10507 gnat xref -Pproj main
10508 gnat bind -Pproj main.ali
10512 will set up the environment properly and invoke the tool with the switches
10513 found in the package corresponding to the tool.
10516 @node Glide and Project Files
10517 @subsection Glide and Project Files
10520 Glide will automatically recognize the @file{.gpr} extension for
10521 project files, and will
10522 convert them to its own internal format automatically. However, it
10523 doesn't provide a syntax-oriented editor for modifying these
10525 The project file will be loaded as text when you select the menu item
10526 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
10527 You can edit this text and save the @file{gpr} file;
10528 when you next select this project file in Glide it
10529 will be automatically reloaded.
10533 @node An Extended Example
10534 @section An Extended Example
10537 Suppose that we have two programs, @var{prog1} and @var{prog2}, with the sources
10538 in the respective directories. We would like to build them with a single
10539 @command{gnatmake} command, and we would like to place their object files into
10540 @file{.build} subdirectories of the source directories. Furthermore, we would
10541 like to have to have two separate subdirectories in @file{.build} --
10542 @file{release} and @file{debug} -- which will contain the object files compiled with
10543 different set of compilation flags.
10545 In other words, we have the following structure:
10562 Here are the project files that we need to create in a directory @file{main}
10563 to maintain this structure:
10567 @item We create a @code{Common} project with a package @code{Compiler} that
10568 specifies the compilation switches:
10573 @b{project} Common @b{is}
10575 @b{for} Source_Dirs @b{use} (); -- No source files
10579 @b{type} Build_Type @b{is} ("release", "debug");
10580 Build : Build_Type := External ("BUILD", "debug");
10583 @b{package} Compiler @b{is}
10584 @b{case} Build @b{is}
10585 @b{when} "release" =>
10586 @b{for} Default_Switches ("Ada") @b{use} ("-O2");
10587 @b{when} "debug" =>
10588 @b{for} Default_Switches ("Ada") @b{use} ("-g");
10596 @item We create separate projects for the two programs:
10603 @b{project} Prog1 @b{is}
10605 @b{for} Source_Dirs @b{use} ("prog1");
10606 @b{for} Object_Dir @b{use} "prog1/.build/" & Common.Build;
10608 @b{package} Compiler @b{renames} Common.Compiler;
10619 @b{project} Prog2 @b{is}
10621 @b{for} Source_Dirs @b{use} ("prog2");
10622 @b{for} Object_Dir @b{use} "prog2/.build/" & Common.Build;
10624 @b{package} Compiler @b{renames} Common.Compiler;
10630 @item We create a wrapping project @var{Main}:
10639 @b{project} Main @b{is}
10641 @b{package} Compiler @b{renames} Common.Compiler;
10647 @item Finally we need to create a dummy procedure that @code{with}s (either
10648 explicitly or implicitly) all the sources of our two programs.
10653 Now we can build the programs using the command
10656 gnatmake -Pmain dummy
10660 for the Debug mode, or
10663 gnatmake -Pmain -XBUILD=release
10667 for the Release mode.
10670 @c ********************************
10671 @c * Project File Complete Syntax *
10672 @c ********************************
10674 @node Project File Complete Syntax
10675 @section Project File Complete Syntax
10679 context_clause project_declaration
10685 @b{with} literal_string @{ , literal_string @} ;
10687 project_declaration ::=
10688 @b{project} <project_>simple_name [ @b{extends} literal_string ] @b{is}
10689 @{declarative_item@}
10690 @b{end} <project_>simple_name;
10692 declarative_item ::=
10693 package_declaration |
10694 typed_string_declaration |
10695 other_declarative_item
10697 package_declaration ::=
10698 @b{package} <package_>simple_name package_completion
10700 package_completion ::=
10701 package_body | package_renaming
10705 @{other_declarative_item@}
10706 @b{end} <package_>simple_name ;
10708 package_renaming ::==
10709 @b{renames} <project_>simple_name.<package_>simple_name ;
10711 typed_string_declaration ::=
10712 @b{type} <typed_string_>_simple_name @b{is}
10713 ( literal_string @{, literal_string@} );
10715 other_declarative_item ::=
10716 attribute_declaration |
10717 typed_variable_declaration |
10718 variable_declaration |
10721 attribute_declaration ::=
10722 @b{for} attribute @b{use} expression ;
10725 <simple_attribute_>simple_name |
10726 <associative_array_attribute_>simple_name ( literal_string )
10728 typed_variable_declaration ::=
10729 <typed_variable_>simple_name : <typed_string_>name := string_expression ;
10731 variable_declaration ::=
10732 <variable_>simple_name := expression;
10742 attribute_reference
10748 ( <string_>expression @{ , <string_>expression @} )
10751 @b{external} ( literal_string [, literal_string] )
10753 attribute_reference ::=
10754 attribute_parent ' <simple_attribute_>simple_name [ ( literal_string ) ]
10756 attribute_parent ::=
10758 <project_or_package>simple_name |
10759 <project_>simple_name . <package_>simple_name
10761 case_construction ::=
10762 @b{case} <typed_variable_>name @b{is}
10767 @b{when} discrete_choice_list => @{case_construction | attribute_declaration@}
10769 discrete_choice_list ::=
10770 literal_string @{| literal_string@}
10773 simple_name @{. simple_name@}
10776 identifier (same as Ada)
10781 @node Elaboration Order Handling in GNAT
10782 @chapter Elaboration Order Handling in GNAT
10783 @cindex Order of elaboration
10784 @cindex Elaboration control
10787 * Elaboration Code in Ada 95::
10788 * Checking the Elaboration Order in Ada 95::
10789 * Controlling the Elaboration Order in Ada 95::
10790 * Controlling Elaboration in GNAT - Internal Calls::
10791 * Controlling Elaboration in GNAT - External Calls::
10792 * Default Behavior in GNAT - Ensuring Safety::
10793 * Elaboration Issues for Library Tasks::
10794 * Mixing Elaboration Models::
10795 * What to Do If the Default Elaboration Behavior Fails::
10796 * Elaboration for Access-to-Subprogram Values::
10797 * Summary of Procedures for Elaboration Control::
10798 * Other Elaboration Order Considerations::
10802 This chapter describes the handling of elaboration code in Ada 95 and
10803 in GNAT, and discusses how the order of elaboration of program units can
10804 be controlled in GNAT, either automatically or with explicit programming
10807 @node Elaboration Code in Ada 95
10808 @section Elaboration Code in Ada 95
10811 Ada 95 provides rather general mechanisms for executing code at elaboration
10812 time, that is to say before the main program starts executing. Such code arises
10816 @item Initializers for variables.
10817 Variables declared at the library level, in package specs or bodies, can
10818 require initialization that is performed at elaboration time, as in:
10821 Sqrt_Half : Float := Sqrt (0.5);
10825 @item Package initialization code
10826 Code in a @code{BEGIN-END} section at the outer level of a package body is
10827 executed as part of the package body elaboration code.
10829 @item Library level task allocators
10830 Tasks that are declared using task allocators at the library level
10831 start executing immediately and hence can execute at elaboration time.
10835 Subprogram calls are possible in any of these contexts, which means that
10836 any arbitrary part of the program may be executed as part of the elaboration
10837 code. It is even possible to write a program which does all its work at
10838 elaboration time, with a null main program, although stylistically this
10839 would usually be considered an inappropriate way to structure
10842 An important concern arises in the context of elaboration code:
10843 we have to be sure that it is executed in an appropriate order. What we
10844 have is a series of elaboration code sections, potentially one section
10845 for each unit in the program. It is important that these execute
10846 in the correct order. Correctness here means that, taking the above
10847 example of the declaration of @code{Sqrt_Half},
10848 if some other piece of
10849 elaboration code references @code{Sqrt_Half},
10850 then it must run after the
10851 section of elaboration code that contains the declaration of
10854 There would never be any order of elaboration problem if we made a rule
10855 that whenever you @code{with} a unit, you must elaborate both the spec and body
10856 of that unit before elaborating the unit doing the @code{with}'ing:
10862 @b{package} Unit_2 @b{is} ...
10868 would require that both the body and spec of @code{Unit_1} be elaborated
10869 before the spec of @code{Unit_2}. However, a rule like that would be far too
10870 restrictive. In particular, it would make it impossible to have routines
10871 in separate packages that were mutually recursive.
10873 You might think that a clever enough compiler could look at the actual
10874 elaboration code and determine an appropriate correct order of elaboration,
10875 but in the general case, this is not possible. Consider the following
10878 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
10880 the variable @code{Sqrt_1}, which is declared in the elaboration code
10881 of the body of @code{Unit_1}:
10885 Sqrt_1 : Float := Sqrt (0.1);
10890 The elaboration code of the body of @code{Unit_1} also contains:
10895 @b{if} expression_1 = 1 @b{then}
10896 Q := Unit_2.Func_2;
10903 @code{Unit_2} is exactly parallel,
10904 it has a procedure @code{Func_2} that references
10905 the variable @code{Sqrt_2}, which is declared in the elaboration code of
10906 the body @code{Unit_2}:
10910 Sqrt_2 : Float := Sqrt (0.1);
10915 The elaboration code of the body of @code{Unit_2} also contains:
10920 @b{if} expression_2 = 2 @b{then}
10921 Q := Unit_1.Func_1;
10928 Now the question is, which of the following orders of elaboration is
10953 If you carefully analyze the flow here, you will see that you cannot tell
10954 at compile time the answer to this question.
10955 If @code{expression_1} is not equal to 1,
10956 and @code{expression_2} is not equal to 2,
10957 then either order is acceptable, because neither of the function calls is
10958 executed. If both tests evaluate to true, then neither order is acceptable
10959 and in fact there is no correct order.
10961 If one of the two expressions is true, and the other is false, then one
10962 of the above orders is correct, and the other is incorrect. For example,
10963 if @code{expression_1} = 1 and @code{expression_2} /= 2,
10964 then the call to @code{Func_2}
10965 will occur, but not the call to @code{Func_1.}
10966 This means that it is essential
10967 to elaborate the body of @code{Unit_1} before
10968 the body of @code{Unit_2}, so the first
10969 order of elaboration is correct and the second is wrong.
10971 By making @code{expression_1} and @code{expression_2}
10972 depend on input data, or perhaps
10973 the time of day, we can make it impossible for the compiler or binder
10974 to figure out which of these expressions will be true, and hence it
10975 is impossible to guarantee a safe order of elaboration at run time.
10977 @node Checking the Elaboration Order in Ada 95
10978 @section Checking the Elaboration Order in Ada 95
10981 In some languages that involve the same kind of elaboration problems,
10982 e.g. Java and C++, the programmer is expected to worry about these
10983 ordering problems himself, and it is common to
10984 write a program in which an incorrect elaboration order gives
10985 surprising results, because it references variables before they
10987 Ada 95 is designed to be a safe language, and a programmer-beware approach is
10988 clearly not sufficient. Consequently, the language provides three lines
10992 @item Standard rules
10993 Some standard rules restrict the possible choice of elaboration
10994 order. In particular, if you @code{with} a unit, then its spec is always
10995 elaborated before the unit doing the @code{with}. Similarly, a parent
10996 spec is always elaborated before the child spec, and finally
10997 a spec is always elaborated before its corresponding body.
10999 @item Dynamic elaboration checks
11000 @cindex Elaboration checks
11001 @cindex Checks, elaboration
11002 Dynamic checks are made at run time, so that if some entity is accessed
11003 before it is elaborated (typically by means of a subprogram call)
11004 then the exception (@code{Program_Error}) is raised.
11006 @item Elaboration control
11007 Facilities are provided for the programmer to specify the desired order
11011 Let's look at these facilities in more detail. First, the rules for
11012 dynamic checking. One possible rule would be simply to say that the
11013 exception is raised if you access a variable which has not yet been
11014 elaborated. The trouble with this approach is that it could require
11015 expensive checks on every variable reference. Instead Ada 95 has two
11016 rules which are a little more restrictive, but easier to check, and
11020 @item Restrictions on calls
11021 A subprogram can only be called at elaboration time if its body
11022 has been elaborated. The rules for elaboration given above guarantee
11023 that the spec of the subprogram has been elaborated before the
11024 call, but not the body. If this rule is violated, then the
11025 exception @code{Program_Error} is raised.
11027 @item Restrictions on instantiations
11028 A generic unit can only be instantiated if the body of the generic
11029 unit has been elaborated. Again, the rules for elaboration given above
11030 guarantee that the spec of the generic unit has been elaborated
11031 before the instantiation, but not the body. If this rule is
11032 violated, then the exception @code{Program_Error} is raised.
11036 The idea is that if the body has been elaborated, then any variables
11037 it references must have been elaborated; by checking for the body being
11038 elaborated we guarantee that none of its references causes any
11039 trouble. As we noted above, this is a little too restrictive, because a
11040 subprogram that has no non-local references in its body may in fact be safe
11041 to call. However, it really would be unsafe to rely on this, because
11042 it would mean that the caller was aware of details of the implementation
11043 in the body. This goes against the basic tenets of Ada.
11045 A plausible implementation can be described as follows.
11046 A Boolean variable is associated with each subprogram
11047 and each generic unit. This variable is initialized to False, and is set to
11048 True at the point body is elaborated. Every call or instantiation checks the
11049 variable, and raises @code{Program_Error} if the variable is False.
11051 Note that one might think that it would be good enough to have one Boolean
11052 variable for each package, but that would not deal with cases of trying
11053 to call a body in the same package as the call
11054 that has not been elaborated yet.
11055 Of course a compiler may be able to do enough analysis to optimize away
11056 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
11057 does such optimizations, but still the easiest conceptual model is to
11058 think of there being one variable per subprogram.
11060 @node Controlling the Elaboration Order in Ada 95
11061 @section Controlling the Elaboration Order in Ada 95
11064 In the previous section we discussed the rules in Ada 95 which ensure
11065 that @code{Program_Error} is raised if an incorrect elaboration order is
11066 chosen. This prevents erroneous executions, but we need mechanisms to
11067 specify a correct execution and avoid the exception altogether.
11068 To achieve this, Ada 95 provides a number of features for controlling
11069 the order of elaboration. We discuss these features in this section.
11071 First, there are several ways of indicating to the compiler that a given
11072 unit has no elaboration problems:
11075 @item packages that do not require a body
11076 In Ada 95, a library package that does not require a body does not permit
11077 a body. This means that if we have a such a package, as in:
11082 @b{package} Definitions @b{is}
11084 @b{type} m @b{is new} integer;
11085 @b{package} Subp @b{is}
11086 @b{type} a @b{is array} (1 .. 10) @b{of} m;
11087 @b{type} b @b{is array} (1 .. 20) @b{of} m;
11089 @b{end} Definitions;
11095 A package that @code{with}'s @code{Definitions} may safely instantiate
11096 @code{Definitions.Subp} because the compiler can determine that there
11097 definitely is no package body to worry about in this case
11100 @cindex pragma Pure
11102 Places sufficient restrictions on a unit to guarantee that
11103 no call to any subprogram in the unit can result in an
11104 elaboration problem. This means that the compiler does not need
11105 to worry about the point of elaboration of such units, and in
11106 particular, does not need to check any calls to any subprograms
11109 @item pragma Preelaborate
11110 @findex Preelaborate
11111 @cindex pragma Preelaborate
11112 This pragma places slightly less stringent restrictions on a unit than
11114 but these restrictions are still sufficient to ensure that there
11115 are no elaboration problems with any calls to the unit.
11117 @item pragma Elaborate_Body
11118 @findex Elaborate_Body
11119 @cindex pragma Elaborate_Body
11120 This pragma requires that the body of a unit be elaborated immediately
11121 after its spec. Suppose a unit @code{A} has such a pragma,
11122 and unit @code{B} does
11123 a @code{with} of unit @code{A}. Recall that the standard rules require
11124 the spec of unit @code{A}
11125 to be elaborated before the @code{with}'ing unit; given the pragma in
11126 @code{A}, we also know that the body of @code{A}
11127 will be elaborated before @code{B}, so
11128 that calls to @code{A} are safe and do not need a check.
11133 unlike pragma @code{Pure} and pragma @code{Preelaborate},
11135 @code{Elaborate_Body} does not guarantee that the program is
11136 free of elaboration problems, because it may not be possible
11137 to satisfy the requested elaboration order.
11138 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
11140 marks @code{Unit_1} as @code{Elaborate_Body},
11141 and not @code{Unit_2,} then the order of
11142 elaboration will be:
11154 Now that means that the call to @code{Func_1} in @code{Unit_2}
11155 need not be checked,
11156 it must be safe. But the call to @code{Func_2} in
11157 @code{Unit_1} may still fail if
11158 @code{Expression_1} is equal to 1,
11159 and the programmer must still take
11160 responsibility for this not being the case.
11162 If all units carry a pragma @code{Elaborate_Body}, then all problems are
11163 eliminated, except for calls entirely within a body, which are
11164 in any case fully under programmer control. However, using the pragma
11165 everywhere is not always possible.
11166 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
11167 we marked both of them as having pragma @code{Elaborate_Body}, then
11168 clearly there would be no possible elaboration order.
11170 The above pragmas allow a server to guarantee safe use by clients, and
11171 clearly this is the preferable approach. Consequently a good rule in
11172 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
11173 and if this is not possible,
11174 mark them as @code{Elaborate_Body} if possible.
11175 As we have seen, there are situations where neither of these
11176 three pragmas can be used.
11177 So we also provide methods for clients to control the
11178 order of elaboration of the servers on which they depend:
11181 @item pragma Elaborate (unit)
11183 @cindex pragma Elaborate
11184 This pragma is placed in the context clause, after a @code{with} clause,
11185 and it requires that the body of the named unit be elaborated before
11186 the unit in which the pragma occurs. The idea is to use this pragma
11187 if the current unit calls at elaboration time, directly or indirectly,
11188 some subprogram in the named unit.
11190 @item pragma Elaborate_All (unit)
11191 @findex Elaborate_All
11192 @cindex pragma Elaborate_All
11193 This is a stronger version of the Elaborate pragma. Consider the
11197 Unit A @code{with}'s unit B and calls B.Func in elab code
11198 Unit B @code{with}'s unit C, and B.Func calls C.Func
11202 Now if we put a pragma @code{Elaborate (B)}
11203 in unit @code{A}, this ensures that the
11204 body of @code{B} is elaborated before the call, but not the
11205 body of @code{C}, so
11206 the call to @code{C.Func} could still cause @code{Program_Error} to
11209 The effect of a pragma @code{Elaborate_All} is stronger, it requires
11210 not only that the body of the named unit be elaborated before the
11211 unit doing the @code{with}, but also the bodies of all units that the
11212 named unit uses, following @code{with} links transitively. For example,
11213 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
11215 not only that the body of @code{B} be elaborated before @code{A},
11217 body of @code{C}, because @code{B} @code{with}'s @code{C}.
11221 We are now in a position to give a usage rule in Ada 95 for avoiding
11222 elaboration problems, at least if dynamic dispatching and access to
11223 subprogram values are not used. We will handle these cases separately
11226 The rule is simple. If a unit has elaboration code that can directly or
11227 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
11228 a generic unit in a @code{with}'ed unit,
11229 then if the @code{with}'ed unit does not have
11230 pragma @code{Pure} or @code{Preelaborate}, then the client should have
11231 a pragma @code{Elaborate_All}
11232 for the @code{with}'ed unit. By following this rule a client is
11233 assured that calls can be made without risk of an exception.
11234 If this rule is not followed, then a program may be in one of four
11238 @item No order exists
11239 No order of elaboration exists which follows the rules, taking into
11240 account any @code{Elaborate}, @code{Elaborate_All},
11241 or @code{Elaborate_Body} pragmas. In
11242 this case, an Ada 95 compiler must diagnose the situation at bind
11243 time, and refuse to build an executable program.
11245 @item One or more orders exist, all incorrect
11246 One or more acceptable elaboration orders exists, and all of them
11247 generate an elaboration order problem. In this case, the binder
11248 can build an executable program, but @code{Program_Error} will be raised
11249 when the program is run.
11251 @item Several orders exist, some right, some incorrect
11252 One or more acceptable elaboration orders exists, and some of them
11253 work, and some do not. The programmer has not controlled
11254 the order of elaboration, so the binder may or may not pick one of
11255 the correct orders, and the program may or may not raise an
11256 exception when it is run. This is the worst case, because it means
11257 that the program may fail when moved to another compiler, or even
11258 another version of the same compiler.
11260 @item One or more orders exists, all correct
11261 One ore more acceptable elaboration orders exist, and all of them
11262 work. In this case the program runs successfully. This state of
11263 affairs can be guaranteed by following the rule we gave above, but
11264 may be true even if the rule is not followed.
11268 Note that one additional advantage of following our Elaborate_All rule
11269 is that the program continues to stay in the ideal (all orders OK) state
11270 even if maintenance
11271 changes some bodies of some subprograms. Conversely, if a program that does
11272 not follow this rule happens to be safe at some point, this state of affairs
11273 may deteriorate silently as a result of maintenance changes.
11275 You may have noticed that the above discussion did not mention
11276 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
11277 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
11278 code in the body makes calls to some other unit, so it is still necessary
11279 to use @code{Elaborate_All} on such units.
11281 @node Controlling Elaboration in GNAT - Internal Calls
11282 @section Controlling Elaboration in GNAT - Internal Calls
11285 In the case of internal calls, i.e. calls within a single package, the
11286 programmer has full control over the order of elaboration, and it is up
11287 to the programmer to elaborate declarations in an appropriate order. For
11293 @b{function} One @b{return} Float;
11297 @b{function} One @b{return} Float @b{is}
11306 will obviously raise @code{Program_Error} at run time, because function
11307 One will be called before its body is elaborated. In this case GNAT will
11308 generate a warning that the call will raise @code{Program_Error}:
11314 2. function One return Float;
11316 4. Q : Float := One;
11318 >>> warning: cannot call "One" before body is elaborated
11319 >>> warning: Program_Error will be raised at run time
11322 6. function One return Float is
11335 Note that in this particular case, it is likely that the call is safe, because
11336 the function @code{One} does not access any global variables.
11337 Nevertheless in Ada 95, we do not want the validity of the check to depend on
11338 the contents of the body (think about the separate compilation case), so this
11339 is still wrong, as we discussed in the previous sections.
11341 The error is easily corrected by rearranging the declarations so that the
11342 body of One appears before the declaration containing the call
11343 (note that in Ada 95,
11344 declarations can appear in any order, so there is no restriction that
11345 would prevent this reordering, and if we write:
11350 @b{function} One @b{return} Float;
11352 @b{function} One @b{return} Float @b{is}
11363 then all is well, no warning is generated, and no
11364 @code{Program_Error} exception
11366 Things are more complicated when a chain of subprograms is executed:
11371 @b{function} A @b{return} Integer;
11372 @b{function} B @b{return} Integer;
11373 @b{function} C @b{return} Integer;
11375 @b{function} B @b{return} Integer @b{is begin return} A; @b{end};
11376 @b{function} C @b{return} Integer @b{is begin return} B; @b{end};
11380 @b{function} A @b{return} Integer @b{is begin return} 1; @b{end};
11386 Now the call to @code{C}
11387 at elaboration time in the declaration of @code{X} is correct, because
11388 the body of @code{C} is already elaborated,
11389 and the call to @code{B} within the body of
11390 @code{C} is correct, but the call
11391 to @code{A} within the body of @code{B} is incorrect, because the body
11392 of @code{A} has not been elaborated, so @code{Program_Error}
11393 will be raised on the call to @code{A}.
11394 In this case GNAT will generate a
11395 warning that @code{Program_Error} may be
11396 raised at the point of the call. Let's look at the warning:
11402 2. function A return Integer;
11403 3. function B return Integer;
11404 4. function C return Integer;
11406 6. function B return Integer is begin return A; end;
11408 >>> warning: call to "A" before body is elaborated may
11409 raise Program_Error
11410 >>> warning: "B" called at line 7
11411 >>> warning: "C" called at line 9
11413 7. function C return Integer is begin return B; end;
11415 9. X : Integer := C;
11417 11. function A return Integer is begin return 1; end;
11427 Note that the message here says "may raise", instead of the direct case,
11428 where the message says "will be raised". That's because whether
11430 actually called depends in general on run-time flow of control.
11431 For example, if the body of @code{B} said
11436 @b{function} B @b{return} Integer @b{is}
11438 @b{if} some-condition-depending-on-input-data @b{then}
11449 then we could not know until run time whether the incorrect call to A would
11450 actually occur, so @code{Program_Error} might
11451 or might not be raised. It is possible for a compiler to
11452 do a better job of analyzing bodies, to
11453 determine whether or not @code{Program_Error}
11454 might be raised, but it certainly
11455 couldn't do a perfect job (that would require solving the halting problem
11456 and is provably impossible), and because this is a warning anyway, it does
11457 not seem worth the effort to do the analysis. Cases in which it
11458 would be relevant are rare.
11460 In practice, warnings of either of the forms given
11461 above will usually correspond to
11462 real errors, and should be examined carefully and eliminated.
11463 In the rare case where a warning is bogus, it can be suppressed by any of
11464 the following methods:
11468 Compile with the @option{-gnatws} switch set
11471 Suppress @code{Elaboration_Checks} for the called subprogram
11474 Use pragma @code{Warnings_Off} to turn warnings off for the call
11478 For the internal elaboration check case,
11479 GNAT by default generates the
11480 necessary run-time checks to ensure
11481 that @code{Program_Error} is raised if any
11482 call fails an elaboration check. Of course this can only happen if a
11483 warning has been issued as described above. The use of pragma
11484 @code{Suppress (Elaboration_Checks)} may (but is not guaranteed to) suppress
11485 some of these checks, meaning that it may be possible (but is not
11486 guaranteed) for a program to be able to call a subprogram whose body
11487 is not yet elaborated, without raising a @code{Program_Error} exception.
11489 @node Controlling Elaboration in GNAT - External Calls
11490 @section Controlling Elaboration in GNAT - External Calls
11493 The previous section discussed the case in which the execution of a
11494 particular thread of elaboration code occurred entirely within a
11495 single unit. This is the easy case to handle, because a programmer
11496 has direct and total control over the order of elaboration, and
11497 furthermore, checks need only be generated in cases which are rare
11498 and which the compiler can easily detect.
11499 The situation is more complex when separate compilation is taken into account.
11500 Consider the following:
11505 @b{package} Math @b{is}
11506 @b{function} Sqrt (Arg : Float) @b{return} Float;
11509 @b{package body} Math @b{is}
11510 @b{function} Sqrt (Arg : Float) @b{return} Float @b{is}
11518 @b{package} Stuff @b{is}
11519 X : Float := Math.Sqrt (0.5);
11523 @b{procedure} Main @b{is}
11532 where @code{Main} is the main program. When this program is executed, the
11533 elaboration code must first be executed, and one of the jobs of the
11534 binder is to determine the order in which the units of a program are
11535 to be elaborated. In this case we have four units: the spec and body
11537 the spec of @code{Stuff} and the body of @code{Main}).
11538 In what order should the four separate sections of elaboration code
11541 There are some restrictions in the order of elaboration that the binder
11542 can choose. In particular, if unit U has a @code{with}
11543 for a package @code{X}, then you
11544 are assured that the spec of @code{X}
11545 is elaborated before U , but you are
11546 not assured that the body of @code{X}
11547 is elaborated before U.
11548 This means that in the above case, the binder is allowed to choose the
11559 but that's not good, because now the call to @code{Math.Sqrt}
11560 that happens during
11561 the elaboration of the @code{Stuff}
11562 spec happens before the body of @code{Math.Sqrt} is
11563 elaborated, and hence causes @code{Program_Error} exception to be raised.
11564 At first glance, one might say that the binder is misbehaving, because
11565 obviously you want to elaborate the body of something you @code{with}
11567 that is not a general rule that can be followed in all cases. Consider
11572 @b{package} X @b{is} ...
11574 @b{package} Y @b{is} ...
11577 @b{package body} Y @b{is} ...
11580 @b{package body} X @b{is} ...
11586 This is a common arrangement, and, apart from the order of elaboration
11587 problems that might arise in connection with elaboration code, this works fine.
11588 A rule that says that you must first elaborate the body of anything you
11589 @code{with} cannot work in this case:
11590 the body of @code{X} @code{with}'s @code{Y},
11591 which means you would have to
11592 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
11594 you have to elaborate the body of @code{X} first, but ... and we have a
11595 loop that cannot be broken.
11597 It is true that the binder can in many cases guess an order of elaboration
11598 that is unlikely to cause a @code{Program_Error}
11599 exception to be raised, and it tries to do so (in the
11600 above example of @code{Math/Stuff/Spec}, the GNAT binder will
11602 elaborate the body of @code{Math} right after its spec, so all will be well).
11604 However, a program that blindly relies on the binder to be helpful can
11605 get into trouble, as we discussed in the previous sections, so
11607 provides a number of facilities for assisting the programmer in
11608 developing programs that are robust with respect to elaboration order.
11610 @node Default Behavior in GNAT - Ensuring Safety
11611 @section Default Behavior in GNAT - Ensuring Safety
11614 The default behavior in GNAT ensures elaboration safety. In its
11615 default mode GNAT implements the
11616 rule we previously described as the right approach. Let's restate it:
11620 @emph{If a unit has elaboration code that can directly or indirectly make a
11621 call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit
11622 in a @code{with}'ed unit, then if the @code{with}'ed unit
11623 does not have pragma @code{Pure} or
11624 @code{Preelaborate}, then the client should have an
11625 @code{Elaborate_All} for the @code{with}'ed unit.}
11629 By following this rule a client
11630 is assured that calls and instantiations can be made without risk of an exception.
11632 In this mode GNAT traces all calls that are potentially made from
11633 elaboration code, and puts in any missing implicit @code{Elaborate_All}
11635 The advantage of this approach is that no elaboration problems
11636 are possible if the binder can find an elaboration order that is
11637 consistent with these implicit @code{Elaborate_All} pragmas. The
11638 disadvantage of this approach is that no such order may exist.
11640 If the binder does not generate any diagnostics, then it means that it
11641 has found an elaboration order that is guaranteed to be safe. However,
11642 the binder may still be relying on implicitly generated
11643 @code{Elaborate_All} pragmas so portability to other compilers than
11644 GNAT is not guaranteed.
11646 If it is important to guarantee portability, then the compilations should
11649 (warn on elaboration problems) switch. This will cause warning messages
11650 to be generated indicating the missing @code{Elaborate_All} pragmas.
11651 Consider the following source program:
11657 @b{package} j @b{is}
11658 m : integer := k.r;
11665 where it is clear that there
11666 should be a pragma @code{Elaborate_All}
11667 for unit @code{k}. An implicit pragma will be generated, and it is
11668 likely that the binder will be able to honor it. However,
11669 it is safer to include the pragma explicitly in the source. If this
11670 unit is compiled with the
11672 switch, then the compiler outputs a warning:
11679 3. m : integer := k.r;
11681 >>> warning: call to "r" may raise Program_Error
11682 >>> warning: missing pragma Elaborate_All for "k"
11690 and these warnings can be used as a guide for supplying manually
11691 the missing pragmas.
11693 This default mode is more restrictive than the Ada Reference
11694 Manual, and it is possible to construct programs which will compile
11695 using the dynamic model described there, but will run into a
11696 circularity using the safer static model we have described.
11698 Of course any Ada compiler must be able to operate in a mode
11699 consistent with the requirements of the Ada Reference Manual,
11700 and in particular must have the capability of implementing the
11701 standard dynamic model of elaboration with run-time checks.
11703 In GNAT, this standard mode can be achieved either by the use of
11704 the @option{-gnatE} switch on the compiler (@code{gcc} or @code{gnatmake})
11705 command, or by the use of the configuration pragma:
11708 pragma Elaboration_Checks (RM);
11712 Either approach will cause the unit affected to be compiled using the
11713 standard dynamic run-time elaboration checks described in the Ada
11714 Reference Manual. The static model is generally preferable, since it
11715 is clearly safer to rely on compile and link time checks rather than
11716 run-time checks. However, in the case of legacy code, it may be
11717 difficult to meet the requirements of the static model. This
11718 issue is further discussed in
11719 @ref{What to Do If the Default Elaboration Behavior Fails}.
11721 Note that the static model provides a strict subset of the allowed
11722 behavior and programs of the Ada Reference Manual, so if you do
11723 adhere to the static model and no circularities exist,
11724 then you are assured that your program will
11725 work using the dynamic model.
11727 @node Elaboration Issues for Library Tasks
11728 @section Elaboration Issues for Library Tasks
11729 @cindex Library tasks, elaboration issues
11730 @cindex Elaboration of library tasks
11733 In this section we examine special elaboration issues that arise for
11734 programs that declare library level tasks.
11736 Generally the model of execution of an Ada program is that all units are
11737 elaborated, and then execution of the program starts. However, the
11738 declaration of library tasks definitely does not fit this model. The
11739 reason for this is that library tasks start as soon as they are declared
11740 (more precisely, as soon as the statement part of the enclosing package
11741 body is reached), that is to say before elaboration
11742 of the program is complete. This means that if such a task calls a
11743 subprogram, or an entry in another task, the callee may or may not be
11744 elaborated yet, and in the standard
11745 Reference Manual model of dynamic elaboration checks, you can even
11746 get timing dependent Program_Error exceptions, since there can be
11747 a race between the elaboration code and the task code.
11749 The static model of elaboration in GNAT seeks to avoid all such
11750 dynamic behavior, by being conservative, and the conservative
11751 approach in this particular case is to assume that all the code
11752 in a task body is potentially executed at elaboration time if
11753 a task is declared at the library level.
11755 This can definitely result in unexpected circularities. Consider
11756 the following example
11764 type My_Int is new Integer;
11766 function Ident (M : My_Int) return My_Int;
11770 package body Decls is
11771 task body Lib_Task is
11777 function Ident (M : My_Int) return My_Int is
11785 procedure Put_Val (Arg : Decls.My_Int);
11789 package body Utils is
11790 procedure Put_Val (Arg : Decls.My_Int) is
11792 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
11799 Decls.Lib_Task.Start;
11804 If the above example is compiled in the default static elaboration
11805 mode, then a circularity occurs. The circularity comes from the call
11806 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
11807 this call occurs in elaboration code, we need an implicit pragma
11808 @code{Elaborate_All} for @code{Utils}. This means that not only must
11809 the spec and body of @code{Utils} be elaborated before the body
11810 of @code{Decls}, but also the spec and body of any unit that is
11811 @code{with'ed} by the body of @code{Utils} must also be elaborated before
11812 the body of @code{Decls}. This is the transitive implication of
11813 pragma @code{Elaborate_All} and it makes sense, because in general
11814 the body of @code{Put_Val} might have a call to something in a
11815 @code{with'ed} unit.
11817 In this case, the body of Utils (actually its spec) @code{with's}
11818 @code{Decls}. Unfortunately this means that the body of @code{Decls}
11819 must be elaborated before itself, in case there is a call from the
11820 body of @code{Utils}.
11822 Here is the exact chain of events we are worrying about:
11826 In the body of @code{Decls} a call is made from within the body of a library
11827 task to a subprogram in the package @code{Utils}. Since this call may
11828 occur at elaboration time (given that the task is activated at elaboration
11829 time), we have to assume the worst, i.e. that the
11830 call does happen at elaboration time.
11833 This means that the body and spec of @code{Util} must be elaborated before
11834 the body of @code{Decls} so that this call does not cause an access before
11838 Within the body of @code{Util}, specifically within the body of
11839 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
11843 One such @code{with}'ed package is package @code{Decls}, so there
11844 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
11845 In fact there is such a call in this example, but we would have to
11846 assume that there was such a call even if it were not there, since
11847 we are not supposed to write the body of @code{Decls} knowing what
11848 is in the body of @code{Utils}; certainly in the case of the
11849 static elaboration model, the compiler does not know what is in
11850 other bodies and must assume the worst.
11853 This means that the spec and body of @code{Decls} must also be
11854 elaborated before we elaborate the unit containing the call, but
11855 that unit is @code{Decls}! This means that the body of @code{Decls}
11856 must be elaborated before itself, and that's a circularity.
11860 Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in
11861 the body of @code{Decls} you will get a true Ada Reference Manual
11862 circularity that makes the program illegal.
11864 In practice, we have found that problems with the static model of
11865 elaboration in existing code often arise from library tasks, so
11866 we must address this particular situation.
11868 Note that if we compile and run the program above, using the dynamic model of
11869 elaboration (that is to say use the @option{-gnatE} switch),
11870 then it compiles, binds,
11871 links, and runs, printing the expected result of 2. Therefore in some sense
11872 the circularity here is only apparent, and we need to capture
11873 the properties of this program that distinguish it from other library-level
11874 tasks that have real elaboration problems.
11876 We have four possible answers to this question:
11881 Use the dynamic model of elaboration.
11883 If we use the @option{-gnatE} switch, then as noted above, the program works.
11884 Why is this? If we examine the task body, it is apparent that the task cannot
11886 @code{accept} statement until after elaboration has been completed, because
11887 the corresponding entry call comes from the main program, not earlier.
11888 This is why the dynamic model works here. But that's really giving
11889 up on a precise analysis, and we prefer to take this approach only if we cannot
11891 problem in any other manner. So let us examine two ways to reorganize
11892 the program to avoid the potential elaboration problem.
11895 Split library tasks into separate packages.
11897 Write separate packages, so that library tasks are isolated from
11898 other declarations as much as possible. Let us look at a variation on
11909 package body Decls1 is
11910 task body Lib_Task is
11918 type My_Int is new Integer;
11919 function Ident (M : My_Int) return My_Int;
11923 package body Decls2 is
11924 function Ident (M : My_Int) return My_Int is
11932 procedure Put_Val (Arg : Decls2.My_Int);
11936 package body Utils is
11937 procedure Put_Val (Arg : Decls2.My_Int) is
11939 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
11946 Decls1.Lib_Task.Start;
11951 All we have done is to split @code{Decls} into two packages, one
11952 containing the library task, and one containing everything else. Now
11953 there is no cycle, and the program compiles, binds, links and executes
11954 using the default static model of elaboration.
11957 Declare separate task types.
11959 A significant part of the problem arises because of the use of the
11960 single task declaration form. This means that the elaboration of
11961 the task type, and the elaboration of the task itself (i.e. the
11962 creation of the task) happen at the same time. A good rule
11963 of style in Ada 95 is to always create explicit task types. By
11964 following the additional step of placing task objects in separate
11965 packages from the task type declaration, many elaboration problems
11966 are avoided. Here is another modified example of the example program:
11970 task type Lib_Task_Type is
11974 type My_Int is new Integer;
11976 function Ident (M : My_Int) return My_Int;
11980 package body Decls is
11981 task body Lib_Task_Type is
11987 function Ident (M : My_Int) return My_Int is
11995 procedure Put_Val (Arg : Decls.My_Int);
11999 package body Utils is
12000 procedure Put_Val (Arg : Decls.My_Int) is
12002 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
12008 Lib_Task : Decls.Lib_Task_Type;
12014 Declst.Lib_Task.Start;
12019 What we have done here is to replace the @code{task} declaration in
12020 package @code{Decls} with a @code{task type} declaration. Then we
12021 introduce a separate package @code{Declst} to contain the actual
12022 task object. This separates the elaboration issues for
12023 the @code{task type}
12024 declaration, which causes no trouble, from the elaboration issues
12025 of the task object, which is also unproblematic, since it is now independent
12026 of the elaboration of @code{Utils}.
12027 This separation of concerns also corresponds to
12028 a generally sound engineering principle of separating declarations
12029 from instances. This version of the program also compiles, binds, links,
12030 and executes, generating the expected output.
12033 Use No_Entry_Calls_In_Elaboration_Code restriction.
12034 @cindex No_Entry_Calls_In_Elaboration_Code
12036 The previous two approaches described how a program can be restructured
12037 to avoid the special problems caused by library task bodies. in practice,
12038 however, such restructuring may be difficult to apply to existing legacy code,
12039 so we must consider solutions that do not require massive rewriting.
12041 Let us consider more carefully why our original sample program works
12042 under the dynamic model of elaboration. The reason is that the code
12043 in the task body blocks immediately on the @code{accept}
12044 statement. Now of course there is nothing to prohibit elaboration
12045 code from making entry calls (for example from another library level task),
12046 so we cannot tell in isolation that
12047 the task will not execute the accept statement during elaboration.
12049 However, in practice it is very unusual to see elaboration code
12050 make any entry calls, and the pattern of tasks starting
12051 at elaboration time and then immediately blocking on @code{accept} or
12052 @code{select} statements is very common. What this means is that
12053 the compiler is being too pessimistic when it analyzes the
12054 whole package body as though it might be executed at elaboration
12057 If we know that the elaboration code contains no entry calls, (a very safe
12058 assumption most of the time, that could almost be made the default
12059 behavior), then we can compile all units of the program under control
12060 of the following configuration pragma:
12063 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
12067 This pragma can be placed in the @file{gnat.adc} file in the usual
12068 manner. If we take our original unmodified program and compile it
12069 in the presence of a @file{gnat.adc} containing the above pragma,
12070 then once again, we can compile, bind, link, and execute, obtaining
12071 the expected result. In the presence of this pragma, the compiler does
12072 not trace calls in a task body, that appear after the first @code{accept}
12073 or @code{select} statement, and therefore does not report a potential
12074 circularity in the original program.
12076 The compiler will check to the extent it can that the above
12077 restriction is not violated, but it is not always possible to do a
12078 complete check at compile time, so it is important to use this
12079 pragma only if the stated restriction is in fact met, that is to say
12080 no task receives an entry call before elaboration of all units is completed.
12084 @node Mixing Elaboration Models
12085 @section Mixing Elaboration Models
12087 So far, we have assumed that the entire program is either compiled
12088 using the dynamic model or static model, ensuring consistency. It
12089 is possible to mix the two models, but rules have to be followed
12090 if this mixing is done to ensure that elaboration checks are not
12093 The basic rule is that @emph{a unit compiled with the static model cannot
12094 be @code{with'ed} by a unit compiled with the dynamic model}. The
12095 reason for this is that in the static model, a unit assumes that
12096 its clients guarantee to use (the equivalent of) pragma
12097 @code{Elaborate_All} so that no elaboration checks are required
12098 in inner subprograms, and this assumption is violated if the
12099 client is compiled with dynamic checks.
12101 The precise rule is as follows. A unit that is compiled with dynamic
12102 checks can only @code{with} a unit that meets at least one of the
12103 following criteria:
12108 The @code{with'ed} unit is itself compiled with dynamic elaboration
12109 checks (that is with the @option{-gnatE} switch.
12112 The @code{with'ed} unit is an internal GNAT implementation unit from
12113 the System, Interfaces, Ada, or GNAT hierarchies.
12116 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
12119 The @code{with'ing} unit (that is the client) has an explicit pragma
12120 @code{Elaborate_All} for the @code{with'ed} unit.
12125 If this rule is violated, that is if a unit with dynamic elaboration
12126 checks @code{with's} a unit that does not meet one of the above four
12127 criteria, then the binder (@code{gnatbind}) will issue a warning
12128 similar to that in the following example:
12131 warning: "x.ads" has dynamic elaboration checks and with's
12132 warning: "y.ads" which has static elaboration checks
12136 These warnings indicate that the rule has been violated, and that as a result
12137 elaboration checks may be missed in the resulting executable file.
12138 This warning may be suppressed using the @code{-ws} binder switch
12139 in the usual manner.
12141 One useful application of this mixing rule is in the case of a subsystem
12142 which does not itself @code{with} units from the remainder of the
12143 application. In this case, the entire subsystem can be compiled with
12144 dynamic checks to resolve a circularity in the subsystem, while
12145 allowing the main application that uses this subsystem to be compiled
12146 using the more reliable default static model.
12148 @node What to Do If the Default Elaboration Behavior Fails
12149 @section What to Do If the Default Elaboration Behavior Fails
12152 If the binder cannot find an acceptable order, it outputs detailed
12153 diagnostics. For example:
12159 error: elaboration circularity detected
12160 info: "proc (body)" must be elaborated before "pack (body)"
12161 info: reason: Elaborate_All probably needed in unit "pack (body)"
12162 info: recompile "pack (body)" with -gnatwl
12163 info: for full details
12164 info: "proc (body)"
12165 info: is needed by its spec:
12166 info: "proc (spec)"
12167 info: which is withed by:
12168 info: "pack (body)"
12169 info: "pack (body)" must be elaborated before "proc (body)"
12170 info: reason: pragma Elaborate in unit "proc (body)"
12176 In this case we have a cycle that the binder cannot break. On the one
12177 hand, there is an explicit pragma Elaborate in @code{proc} for
12178 @code{pack}. This means that the body of @code{pack} must be elaborated
12179 before the body of @code{proc}. On the other hand, there is elaboration
12180 code in @code{pack} that calls a subprogram in @code{proc}. This means
12181 that for maximum safety, there should really be a pragma
12182 Elaborate_All in @code{pack} for @code{proc} which would require that
12183 the body of @code{proc} be elaborated before the body of
12184 @code{pack}. Clearly both requirements cannot be satisfied.
12185 Faced with a circularity of this kind, you have three different options.
12188 @item Fix the program
12189 The most desirable option from the point of view of long-term maintenance
12190 is to rearrange the program so that the elaboration problems are avoided.
12191 One useful technique is to place the elaboration code into separate
12192 child packages. Another is to move some of the initialization code to
12193 explicitly called subprograms, where the program controls the order
12194 of initialization explicitly. Although this is the most desirable option,
12195 it may be impractical and involve too much modification, especially in
12196 the case of complex legacy code.
12198 @item Perform dynamic checks
12199 If the compilations are done using the
12201 (dynamic elaboration check) switch, then GNAT behaves in
12202 a quite different manner. Dynamic checks are generated for all calls
12203 that could possibly result in raising an exception. With this switch,
12204 the compiler does not generate implicit @code{Elaborate_All} pragmas.
12205 The behavior then is exactly as specified in the Ada 95 Reference Manual.
12206 The binder will generate an executable program that may or may not
12207 raise @code{Program_Error}, and then it is the programmer's job to ensure
12208 that it does not raise an exception. Note that it is important to
12209 compile all units with the switch, it cannot be used selectively.
12211 @item Suppress checks
12212 The drawback of dynamic checks is that they generate a
12213 significant overhead at run time, both in space and time. If you
12214 are absolutely sure that your program cannot raise any elaboration
12215 exceptions, and you still want to use the dynamic elaboration model,
12216 then you can use the configuration pragma
12217 @code{Suppress (Elaboration_Checks)} to suppress all such checks. For
12218 example this pragma could be placed in the @file{gnat.adc} file.
12220 @item Suppress checks selectively
12221 When you know that certain calls in elaboration code cannot possibly
12222 lead to an elaboration error, and the binder nevertheless generates warnings
12223 on those calls and inserts Elaborate_All pragmas that lead to elaboration
12224 circularities, it is possible to remove those warnings locally and obtain
12225 a program that will bind. Clearly this can be unsafe, and it is the
12226 responsibility of the programmer to make sure that the resulting program has
12227 no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can
12228 be used with different granularity to suppress warnings and break
12229 elaboration circularities:
12233 Place the pragma that names the called subprogram in the declarative part
12234 that contains the call.
12237 Place the pragma in the declarative part, without naming an entity. This
12238 disables warnings on all calls in the corresponding declarative region.
12241 Place the pragma in the package spec that declares the called subprogram,
12242 and name the subprogram. This disables warnings on all elaboration calls to
12246 Place the pragma in the package spec that declares the called subprogram,
12247 without naming any entity. This disables warnings on all elaboration calls to
12248 all subprograms declared in this spec.
12252 These four cases are listed in order of decreasing safety, and therefore
12253 require increasing programmer care in their application. Consider the
12258 function F1 return Integer;
12263 function F2 return Integer;
12264 function Pure (x : integer) return integer;
12265 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
12266 -- pragma Suppress (Elaboration_Check); -- (4)
12270 package body Pack1 is
12271 function F1 return Integer is
12275 Val : integer := Pack2.Pure (11); -- Elab. call (1)
12278 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
12279 -- pragma Suppress(Elaboration_Check); -- (2)
12281 X1 := Pack2.F2 + 1; -- Elab. call (2)
12286 package body Pack2 is
12287 function F2 return Integer is
12291 function Pure (x : integer) return integer is
12293 return x ** 3 - 3 * x;
12297 with Pack1, Ada.Text_IO;
12300 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
12303 In the absence of any pragmas, an attempt to bind this program produces
12304 the following diagnostics:
12310 error: elaboration circularity detected
12311 info: "pack1 (body)" must be elaborated before "pack1 (body)"
12312 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
12313 info: recompile "pack1 (body)" with -gnatwl for full details
12314 info: "pack1 (body)"
12315 info: must be elaborated along with its spec:
12316 info: "pack1 (spec)"
12317 info: which is withed by:
12318 info: "pack2 (body)"
12319 info: which must be elaborated along with its spec:
12320 info: "pack2 (spec)"
12321 info: which is withed by:
12322 info: "pack1 (body)"
12325 The sources of the circularity are the two calls to @code{Pack2.Pure} and
12326 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
12327 F2 is safe, even though F2 calls F1, because the call appears after the
12328 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
12329 remove the warning on the call. It is also possible to use pragma (2)
12330 because there are no other potentially unsafe calls in the block.
12333 The call to @code{Pure} is safe because this function does not depend on the
12334 state of @code{Pack2}. Therefore any call to this function is safe, and it
12335 is correct to place pragma (3) in the corresponding package spec.
12338 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
12339 warnings on all calls to functions declared therein. Note that this is not
12340 necessarily safe, and requires more detailed examination of the subprogram
12341 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
12342 be already elaborated.
12346 It is hard to generalize on which of these four approaches should be
12347 taken. Obviously if it is possible to fix the program so that the default
12348 treatment works, this is preferable, but this may not always be practical.
12349 It is certainly simple enough to use
12351 but the danger in this case is that, even if the GNAT binder
12352 finds a correct elaboration order, it may not always do so,
12353 and certainly a binder from another Ada compiler might not. A
12354 combination of testing and analysis (for which the warnings generated
12357 switch can be useful) must be used to ensure that the program is free
12358 of errors. One switch that is useful in this testing is the
12359 @code{-p (pessimistic elaboration order)}
12362 Normally the binder tries to find an order that has the best chance of
12363 of avoiding elaboration problems. With this switch, the binder
12364 plays a devil's advocate role, and tries to choose the order that
12365 has the best chance of failing. If your program works even with this
12366 switch, then it has a better chance of being error free, but this is still
12369 For an example of this approach in action, consider the C-tests (executable
12370 tests) from the ACVC suite. If these are compiled and run with the default
12371 treatment, then all but one of them succeed without generating any error
12372 diagnostics from the binder. However, there is one test that fails, and
12373 this is not surprising, because the whole point of this test is to ensure
12374 that the compiler can handle cases where it is impossible to determine
12375 a correct order statically, and it checks that an exception is indeed
12376 raised at run time.
12378 This one test must be compiled and run using the
12380 switch, and then it passes. Alternatively, the entire suite can
12381 be run using this switch. It is never wrong to run with the dynamic
12382 elaboration switch if your code is correct, and we assume that the
12383 C-tests are indeed correct (it is less efficient, but efficiency is
12384 not a factor in running the ACVC tests.)
12386 @node Elaboration for Access-to-Subprogram Values
12387 @section Elaboration for Access-to-Subprogram Values
12388 @cindex Access-to-subprogram
12391 The introduction of access-to-subprogram types in Ada 95 complicates
12392 the handling of elaboration. The trouble is that it becomes
12393 impossible to tell at compile time which procedure
12394 is being called. This means that it is not possible for the binder
12395 to analyze the elaboration requirements in this case.
12397 If at the point at which the access value is created
12398 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
12399 the body of the subprogram is
12400 known to have been elaborated, then the access value is safe, and its use
12401 does not require a check. This may be achieved by appropriate arrangement
12402 of the order of declarations if the subprogram is in the current unit,
12403 or, if the subprogram is in another unit, by using pragma
12404 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
12405 on the referenced unit.
12407 If the referenced body is not known to have been elaborated at the point
12408 the access value is created, then any use of the access value must do a
12409 dynamic check, and this dynamic check will fail and raise a
12410 @code{Program_Error} exception if the body has not been elaborated yet.
12411 GNAT will generate the necessary checks, and in addition, if the
12413 switch is set, will generate warnings that such checks are required.
12415 The use of dynamic dispatching for tagged types similarly generates
12416 a requirement for dynamic checks, and premature calls to any primitive
12417 operation of a tagged type before the body of the operation has been elaborated,
12418 will result in the raising of @code{Program_Error}.
12420 @node Summary of Procedures for Elaboration Control
12421 @section Summary of Procedures for Elaboration Control
12422 @cindex Elaboration control
12425 First, compile your program with the default options, using none of
12426 the special elaboration control switches. If the binder successfully
12427 binds your program, then you can be confident that, apart from issues
12428 raised by the use of access-to-subprogram types and dynamic dispatching,
12429 the program is free of elaboration errors. If it is important that the
12430 program be portable, then use the
12432 switch to generate warnings about missing @code{Elaborate_All}
12433 pragmas, and supply the missing pragmas.
12435 If the program fails to bind using the default static elaboration
12436 handling, then you can fix the program to eliminate the binder
12437 message, or recompile the entire program with the
12438 @option{-gnatE} switch to generate dynamic elaboration checks,
12439 and, if you are sure there really are no elaboration problems,
12440 use a global pragma @code{Suppress (Elaboration_Checks)}.
12442 @node Other Elaboration Order Considerations
12443 @section Other Elaboration Order Considerations
12445 This section has been entirely concerned with the issue of finding a valid
12446 elaboration order, as defined by the Ada Reference Manual. In a case
12447 where several elaboration orders are valid, the task is to find one
12448 of the possible valid elaboration orders (and the static model in GNAT
12449 will ensure that this is achieved).
12451 The purpose of the elaboration rules in the Ada Reference Manual is to
12452 make sure that no entity is accessed before it has been elaborated. For
12453 a subprogram, this means that the spec and body must have been elaborated
12454 before the subprogram is called. For an object, this means that the object
12455 must have been elaborated before its value is read or written. A violation
12456 of either of these two requirements is an access before elaboration order,
12457 and this section has been all about avoiding such errors.
12459 In the case where more than one order of elaboration is possible, in the
12460 sense that access before elaboration errors are avoided, then any one of
12461 the orders is "correct" in the sense that it meets the requirements of
12462 the Ada Reference Manual, and no such error occurs.
12464 However, it may be the case for a given program, that there are
12465 constraints on the order of elaboration that come not from consideration
12466 of avoiding elaboration errors, but rather from extra-lingual logic
12467 requirements. Consider this example:
12470 with Init_Constants;
12471 package Constants is
12476 package Init_Constants is
12478 end Init_Constants;
12481 package body Init_Constants is
12482 procedure Calc is begin null; end;
12486 end Init_Constants;
12490 Z : Integer := Constants.X + Constants.Y;
12494 with Text_IO; use Text_IO;
12497 Put_Line (Calc.Z'Img);
12502 In this example, there is more than one valid order of elaboration. For
12503 example both the following are correct orders:
12506 Init_Constants spec
12510 Init_Constants body
12514 Init_Constants spec
12515 Init_Constants body
12522 There is no language rule to prefer one or the other, both are correct
12523 from an order of elaboration point of view. But the programmatic effects
12524 of the two orders are very different. In the first, the elaboration routine
12525 of @code{Calc} initializes @code{Z} to zero, and then the main program
12526 runs with this value of zero. But in the second order, the elaboration
12527 routine of @code{Calc} runs after the body of Init_Constants has set
12528 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
12531 One could perhaps by applying pretty clever non-artificial intelligence
12532 to the situation guess that it is more likely that the second order of
12533 elaboration is the one desired, but there is no formal linguistic reason
12534 to prefer one over the other. In fact in this particular case, GNAT will
12535 prefer the second order, because of the rule that bodies are elaborated
12536 as soon as possible, but it's just luck that this is what was wanted
12537 (if indeed the second order was preferred).
12539 If the program cares about the order of elaboration routines in a case like
12540 this, it is important to specify the order required. In this particular
12541 case, that could have been achieved by adding to the spec of Calc:
12544 pragma Elaborate_All (Constants);
12548 which requires that the body (if any) and spec of @code{Constants},
12549 as well as the body and spec of any unit @code{with}'ed by
12550 @code{Constants} be elaborated before @code{Calc} is elaborated.
12552 Clearly no automatic method can always guess which alternative you require,
12553 and if you are working with legacy code that had constraints of this kind
12554 which were not properly specified by adding @code{Elaborate} or
12555 @code{Elaborate_All} pragmas, then indeed it is possible that two different
12556 compilers can choose different orders.
12558 The @code{gnatbind}
12559 @code{-p} switch may be useful in smoking
12560 out problems. This switch causes bodies to be elaborated as late as possible
12561 instead of as early as possible. In the example above, it would have forced
12562 the choice of the first elaboration order. If you get different results
12563 when using this switch, and particularly if one set of results is right,
12564 and one is wrong as far as you are concerned, it shows that you have some
12565 missing @code{Elaborate} pragmas. For the example above, we have the
12569 gnatmake -f -q main
12572 gnatmake -f -q main -bargs -p
12578 It is of course quite unlikely that both these results are correct, so
12579 it is up to you in a case like this to investigate the source of the
12580 difference, by looking at the two elaboration orders that are chosen,
12581 and figuring out which is correct, and then adding the necessary
12582 @code{Elaborate_All} pragmas to ensure the desired order.
12584 @node The Cross-Referencing Tools gnatxref and gnatfind
12585 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12590 The compiler generates cross-referencing information (unless
12591 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12592 This information indicates where in the source each entity is declared and
12593 referenced. Note that entities in package Standard are not included, but
12594 entities in all other predefined units are included in the output.
12596 Before using any of these two tools, you need to compile successfully your
12597 application, so that GNAT gets a chance to generate the cross-referencing
12600 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12601 information to provide the user with the capability to easily locate the
12602 declaration and references to an entity. These tools are quite similar,
12603 the difference being that @code{gnatfind} is intended for locating
12604 definitions and/or references to a specified entity or entities, whereas
12605 @code{gnatxref} is oriented to generating a full report of all
12608 To use these tools, you must not compile your application using the
12609 @option{-gnatx} switch on the @file{gnatmake} command line (@inforef{The
12610 GNAT Make Program gnatmake,,gnat_ug}). Otherwise, cross-referencing
12611 information will not be generated.
12614 * gnatxref Switches::
12615 * gnatfind Switches::
12616 * Project Files for gnatxref and gnatfind::
12617 * Regular Expressions in gnatfind and gnatxref::
12618 * Examples of gnatxref Usage::
12619 * Examples of gnatfind Usage::
12622 @node gnatxref Switches
12623 @section @code{gnatxref} Switches
12626 The command lines for @code{gnatxref} is:
12628 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
12635 @item sourcefile1, sourcefile2
12636 identifies the source files for which a report is to be generated. The
12637 'with'ed units will be processed too. You must provide at least one file.
12639 These file names are considered to be regular expressions, so for instance
12640 specifying 'source*.adb' is the same as giving every file in the current
12641 directory whose name starts with 'source' and whose extension is 'adb'.
12646 The switches can be :
12649 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12650 the read-only files found in the library search path. Otherwise, these files
12651 will be ignored. This option can be used to protect Gnat sources or your own
12652 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12653 much faster, and their output much smaller.
12656 When looking for source files also look in directory DIR. The order in which
12657 source file search is undertaken is the same as for @file{gnatmake}.
12660 When searching for library and object files, look in directory
12661 DIR. The order in which library files are searched is the same as for
12665 Do not look for sources in the system default directory.
12668 Do not look for library files in the system default directory.
12670 @item --RTS=@var{rts-path}
12671 @cindex @code{--RTS} (@code{gnatxref})
12672 Specifies the default location of the runtime library. Same meaning as the
12673 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
12676 If this switch is set @code{gnatxref} will output the parent type
12677 reference for each matching derived types.
12680 If this switch is set, the output file names will be preceded by their
12681 directory (if the file was found in the search path). If this switch is
12682 not set, the directory will not be printed.
12685 If this switch is set, information is output only for library-level
12686 entities, ignoring local entities. The use of this switch may accelerate
12687 @code{gnatfind} and @code{gnatxref}.
12690 Equivalent to @samp{-aODIR -aIDIR}.
12693 Specify a project file to use @xref{Project Files}.
12694 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12695 project file in the current directory.
12697 If a project file is either specified or found by the tools, then the content
12698 of the source directory and object directory lines are added as if they
12699 had been specified respectively by @samp{-aI}
12702 Output only unused symbols. This may be really useful if you give your
12703 main compilation unit on the command line, as @code{gnatxref} will then
12704 display every unused entity and 'with'ed package.
12707 Instead of producing the default output, @code{gnatxref} will generate a
12708 @file{tags} file that can be used by vi. For examples how to use this
12709 feature, see @xref{Examples of gnatxref Usage}. The tags file is output
12710 to the standard output, thus you will have to redirect it to a file.
12714 All these switches may be in any order on the command line, and may even
12715 appear after the file names. They need not be separated by spaces, thus
12716 you can say @samp{gnatxref -ag} instead of
12717 @samp{gnatxref -a -g}.
12719 @node gnatfind Switches
12720 @section @code{gnatfind} Switches
12723 The command line for @code{gnatfind} is:
12726 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
12735 An entity will be output only if it matches the regular expression found
12736 in @samp{pattern}, see @xref{Regular Expressions in gnatfind and gnatxref}.
12738 Omitting the pattern is equivalent to specifying @samp{*}, which
12739 will match any entity. Note that if you do not provide a pattern, you
12740 have to provide both a sourcefile and a line.
12742 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12743 for matching purposes. At the current time there is no support for
12744 8-bit codes other than Latin-1, or for wide characters in identifiers.
12747 @code{gnatfind} will look for references, bodies or declarations
12748 of symbols referenced in @file{sourcefile}, at line @samp{line}
12749 and column @samp{column}. See @pxref{Examples of gnatfind Usage}
12750 for syntax examples.
12753 is a decimal integer identifying the line number containing
12754 the reference to the entity (or entities) to be located.
12757 is a decimal integer identifying the exact location on the
12758 line of the first character of the identifier for the
12759 entity reference. Columns are numbered from 1.
12761 @item file1 file2 ...
12762 The search will be restricted to these files. If none are given, then
12763 the search will be done for every library file in the search path.
12764 These file must appear only after the pattern or sourcefile.
12766 These file names are considered to be regular expressions, so for instance
12767 specifying 'source*.adb' is the same as giving every file in the current
12768 directory whose name starts with 'source' and whose extension is 'adb'.
12770 Not that if you specify at least one file in this part, @code{gnatfind} may
12771 sometimes not be able to find the body of the subprograms...
12775 At least one of 'sourcefile' or 'pattern' has to be present on
12778 The following switches are available:
12782 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12783 the read-only files found in the library search path. Otherwise, these files
12784 will be ignored. This option can be used to protect Gnat sources or your own
12785 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12786 much faster, and their output much smaller.
12789 When looking for source files also look in directory DIR. The order in which
12790 source file search is undertaken is the same as for @file{gnatmake}.
12793 When searching for library and object files, look in directory
12794 DIR. The order in which library files are searched is the same as for
12798 Do not look for sources in the system default directory.
12801 Do not look for library files in the system default directory.
12803 @item --RTS=@var{rts-path}
12804 @cindex @code{--RTS} (@code{gnatfind})
12805 Specifies the default location of the runtime library. Same meaning as the
12806 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
12809 If this switch is set, then @code{gnatfind} will output the parent type
12810 reference for each matching derived types.
12813 By default, @code{gnatfind} accept the simple regular expression set for
12814 @samp{pattern}. If this switch is set, then the pattern will be
12815 considered as full Unix-style regular expression.
12818 If this switch is set, the output file names will be preceded by their
12819 directory (if the file was found in the search path). If this switch is
12820 not set, the directory will not be printed.
12823 If this switch is set, information is output only for library-level
12824 entities, ignoring local entities. The use of this switch may accelerate
12825 @code{gnatfind} and @code{gnatxref}.
12828 Equivalent to @samp{-aODIR -aIDIR}.
12831 Specify a project file (@pxref{Project Files}) to use.
12832 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12833 project file in the current directory.
12835 If a project file is either specified or found by the tools, then the content
12836 of the source directory and object directory lines are added as if they
12837 had been specified respectively by @samp{-aI} and
12841 By default, @code{gnatfind} will output only the information about the
12842 declaration, body or type completion of the entities. If this switch is
12843 set, the @code{gnatfind} will locate every reference to the entities in
12844 the files specified on the command line (or in every file in the search
12845 path if no file is given on the command line).
12848 If this switch is set, then @code{gnatfind} will output the content
12849 of the Ada source file lines were the entity was found.
12852 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12853 the specified type. It act like -d option but recursively from parent
12854 type to parent type. When this switch is set it is not possible to
12855 specify more than one file.
12859 All these switches may be in any order on the command line, and may even
12860 appear after the file names. They need not be separated by spaces, thus
12861 you can say @samp{gnatxref -ag} instead of
12862 @samp{gnatxref -a -g}.
12864 As stated previously, gnatfind will search in every directory in the
12865 search path. You can force it to look only in the current directory if
12866 you specify @code{*} at the end of the command line.
12869 @node Project Files for gnatxref and gnatfind
12870 @section Project Files for @command{gnatxref} and @command{gnatfind}
12873 Project files allow a programmer to specify how to compile its
12874 application, where to find sources,... These files are used primarily by
12875 the Glide Ada mode, but they can also be used by the two tools
12876 @code{gnatxref} and @code{gnatfind}.
12878 A project file name must end with @file{.adp}. If a single one is
12879 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12880 extract the information from it. If multiple project files are found, none of
12881 them is read, and you have to use the @samp{-p} switch to specify the one
12884 The following lines can be included, even though most of them have default
12885 values which can be used in most cases.
12886 The lines can be entered in any order in the file.
12887 Except for @samp{src_dir} and @samp{obj_dir}, you can only have one instance of
12888 each line. If you have multiple instances, only the last one is taken into
12892 @item src_dir=DIR [default: "./"]
12893 specifies a directory where to look for source files. Multiple src_dir lines
12894 can be specified and they will be searched in the order they
12897 @item obj_dir=DIR [default: "./"]
12898 specifies a directory where to look for object and library files. Multiple
12899 obj_dir lines can be specified and they will be searched in the order they
12902 @item comp_opt=SWITCHES [default: ""]
12903 creates a variable which can be referred to subsequently by using
12904 the @samp{$@{comp_opt@}} notation. This is intended to store the default
12905 switches given to @file{gnatmake} and @file{gcc}.
12907 @item bind_opt=SWITCHES [default: ""]
12908 creates a variable which can be referred to subsequently by using
12909 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12910 switches given to @file{gnatbind}.
12912 @item link_opt=SWITCHES [default: ""]
12913 creates a variable which can be referred to subsequently by using
12914 the @samp{$@{link_opt@}} notation. This is intended to store the default
12915 switches given to @file{gnatlink}.
12917 @item main=EXECUTABLE [default: ""]
12918 specifies the name of the executable for the application. This variable can
12919 be referred to in the following lines by using the @samp{$@{main@}} notation.
12921 @item comp_cmd=COMMAND [default: "gcc -c -I$@{src_dir@} -g -gnatq"]
12922 specifies the command used to compile a single file in the application.
12924 @item make_cmd=COMMAND [default: "gnatmake $@{main@} -aI$@{src_dir@} -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@} -bargs $@{bind_opt@} -largs $@{link_opt@}"]
12925 specifies the command used to recompile the whole application.
12927 @item run_cmd=COMMAND [default: "$@{main@}"]
12928 specifies the command used to run the application.
12930 @item debug_cmd=COMMAND [default: "gdb $@{main@}"]
12931 specifies the command used to debug the application
12935 @code{gnatxref} and @code{gnatfind} only take into account the @samp{src_dir}
12936 and @samp{obj_dir} lines, and ignore the others.
12938 @node Regular Expressions in gnatfind and gnatxref
12939 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
12942 As specified in the section about @code{gnatfind}, the pattern can be a
12943 regular expression. Actually, there are to set of regular expressions
12944 which are recognized by the program :
12947 @item globbing patterns
12948 These are the most usual regular expression. They are the same that you
12949 generally used in a Unix shell command line, or in a DOS session.
12951 Here is a more formal grammar :
12958 term ::= elmt -- matches elmt
12959 term ::= elmt elmt -- concatenation (elmt then elmt)
12960 term ::= * -- any string of 0 or more characters
12961 term ::= ? -- matches any character
12962 term ::= [char @{char@}] -- matches any character listed
12963 term ::= [char - char] -- matches any character in range
12967 @item full regular expression
12968 The second set of regular expressions is much more powerful. This is the
12969 type of regular expressions recognized by utilities such a @file{grep}.
12971 The following is the form of a regular expression, expressed in Ada
12972 reference manual style BNF is as follows
12979 regexp ::= term @{| term@} -- alternation (term or term ...)
12981 term ::= item @{item@} -- concatenation (item then item)
12983 item ::= elmt -- match elmt
12984 item ::= elmt * -- zero or more elmt's
12985 item ::= elmt + -- one or more elmt's
12986 item ::= elmt ? -- matches elmt or nothing
12989 elmt ::= nschar -- matches given character
12990 elmt ::= [nschar @{nschar@}] -- matches any character listed
12991 elmt ::= [^ nschar @{nschar@}] -- matches any character not listed
12992 elmt ::= [char - char] -- matches chars in given range
12993 elmt ::= \ char -- matches given character
12994 elmt ::= . -- matches any single character
12995 elmt ::= ( regexp ) -- parens used for grouping
12997 char ::= any character, including special characters
12998 nschar ::= any character except ()[].*+?^
13002 Following are a few examples :
13006 will match any of the two strings 'abcde' and 'fghi'.
13009 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
13012 will match any string which has only lowercase characters in it (and at
13013 least one character
13018 @node Examples of gnatxref Usage
13019 @section Examples of @code{gnatxref} Usage
13021 @subsection General Usage
13024 For the following examples, we will consider the following units :
13031 2: @b{package} Main @b{is}
13032 3: @b{procedure} Foo (B : @b{in} Integer);
13039 1: @b{package body} Main @b{is}
13040 2: @b{procedure} Foo (B : @b{in} Integer) @b{is}
13050 1: @b{package} Bar @b{is}
13051 2: @b{procedure} Print (B : Integer);
13060 The first thing to do is to recompile your application (for instance, in
13061 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13062 the cross-referencing information.
13063 You can then issue any of the following commands:
13065 @item gnatxref main.adb
13066 @code{gnatxref} generates cross-reference information for main.adb
13067 and every unit 'with'ed by main.adb.
13069 The output would be:
13077 Decl: main.ads 3:20
13078 Body: main.adb 2:20
13079 Ref: main.adb 4:13 5:13 6:19
13082 Ref: main.adb 6:8 7:8
13092 Decl: main.ads 3:15
13093 Body: main.adb 2:15
13096 Body: main.adb 1:14
13099 Ref: main.adb 6:12 7:12
13103 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13104 its body is in main.adb, line 1, column 14 and is not referenced any where.
13106 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13107 it referenced in main.adb, line 6 column 12 and line 7 column 12.
13109 @item gnatxref package1.adb package2.ads
13110 @code{gnatxref} will generates cross-reference information for
13111 package1.adb, package2.ads and any other package 'with'ed by any
13116 @subsection Using gnatxref with vi
13118 @code{gnatxref} can generate a tags file output, which can be used
13119 directly from @file{vi}. Note that the standard version of @file{vi}
13120 will not work properly with overloaded symbols. Consider using another
13121 free implementation of @file{vi}, such as @file{vim}.
13124 $ gnatxref -v gnatfind.adb > tags
13128 will generate the tags file for @code{gnatfind} itself (if the sources
13129 are in the search path!).
13131 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
13132 (replacing @i{entity} by whatever you are looking for), and vi will
13133 display a new file with the corresponding declaration of entity.
13135 @node Examples of gnatfind Usage
13136 @section Examples of @code{gnatfind} Usage
13140 @item gnatfind -f xyz:main.adb
13141 Find declarations for all entities xyz referenced at least once in
13142 main.adb. The references are search in every library file in the search
13145 The directories will be printed as well (as the @samp{-f}
13148 The output will look like:
13150 directory/main.ads:106:14: xyz <= declaration
13151 directory/main.adb:24:10: xyz <= body
13152 directory/foo.ads:45:23: xyz <= declaration
13156 that is to say, one of the entities xyz found in main.adb is declared at
13157 line 12 of main.ads (and its body is in main.adb), and another one is
13158 declared at line 45 of foo.ads
13160 @item gnatfind -fs xyz:main.adb
13161 This is the same command as the previous one, instead @code{gnatfind} will
13162 display the content of the Ada source file lines.
13164 The output will look like:
13167 directory/main.ads:106:14: xyz <= declaration
13169 directory/main.adb:24:10: xyz <= body
13171 directory/foo.ads:45:23: xyz <= declaration
13176 This can make it easier to find exactly the location your are looking
13179 @item gnatfind -r "*x*":main.ads:123 foo.adb
13180 Find references to all entities containing an x that are
13181 referenced on line 123 of main.ads.
13182 The references will be searched only in main.adb and foo.adb.
13184 @item gnatfind main.ads:123
13185 Find declarations and bodies for all entities that are referenced on
13186 line 123 of main.ads.
13188 This is the same as @code{gnatfind "*":main.adb:123}.
13190 @item gnatfind mydir/main.adb:123:45
13191 Find the declaration for the entity referenced at column 45 in
13192 line 123 of file main.adb in directory mydir. Note that it
13193 is usual to omit the identifier name when the column is given,
13194 since the column position identifies a unique reference.
13196 The column has to be the beginning of the identifier, and should not
13197 point to any character in the middle of the identifier.
13201 @node File Name Krunching Using gnatkr
13202 @chapter File Name Krunching Using @code{gnatkr}
13206 This chapter discusses the method used by the compiler to shorten
13207 the default file names chosen for Ada units so that they do not
13208 exceed the maximum length permitted. It also describes the
13209 @code{gnatkr} utility that can be used to determine the result of
13210 applying this shortening.
13214 * Krunching Method::
13215 * Examples of gnatkr Usage::
13219 @section About @code{gnatkr}
13222 The default file naming rule in GNAT
13223 is that the file name must be derived from
13224 the unit name. The exact default rule is as follows:
13227 Take the unit name and replace all dots by hyphens.
13229 If such a replacement occurs in the
13230 second character position of a name, and the first character is
13231 a, g, s, or i then replace the dot by the character
13233 instead of a minus.
13235 The reason for this exception is to avoid clashes
13236 with the standard names for children of System, Ada, Interfaces,
13237 and GNAT, which use the prefixes s- a- i- and g-
13240 The @code{-gnatk@var{nn}}
13241 switch of the compiler activates a "krunching"
13242 circuit that limits file names to nn characters (where nn is a decimal
13243 integer). For example, using OpenVMS,
13244 where the maximum file name length is
13245 39, the value of nn is usually set to 39, but if you want to generate
13246 a set of files that would be usable if ported to a system with some
13247 different maximum file length, then a different value can be specified.
13248 The default value of 39 for OpenVMS need not be specified.
13250 The @code{gnatkr} utility can be used to determine the krunched name for
13251 a given file, when krunched to a specified maximum length.
13254 @section Using @code{gnatkr}
13257 The @code{gnatkr} command has the form
13260 $ gnatkr @var{name} [@var{length}]
13265 @var{name} can be an Ada name with dots or the GNAT name of the unit,
13266 where the dots representing child units or subunit are replaced by
13267 hyphens. The only confusion arises if a name ends in @code{.ads} or
13268 @code{.adb}. @code{gnatkr} takes this to be an extension if there are
13269 no other dots in the name and the whole name is in lowercase.
13271 @var{length} represents the length of the krunched name. The default
13272 when no argument is given is 8 characters. A length of zero stands for
13273 unlimited, in other words do not chop except for system files which are
13277 The output is the krunched name. The output has an extension only if the
13278 original argument was a file name with an extension.
13280 @node Krunching Method
13281 @section Krunching Method
13284 The initial file name is determined by the name of the unit that the file
13285 contains. The name is formed by taking the full expanded name of the
13286 unit and replacing the separating dots with hyphens and
13288 for all letters, except that a hyphen in the second character position is
13289 replaced by a tilde if the first character is
13291 The extension is @code{.ads} for a
13292 specification and @code{.adb} for a body.
13293 Krunching does not affect the extension, but the file name is shortened to
13294 the specified length by following these rules:
13298 The name is divided into segments separated by hyphens, tildes or
13299 underscores and all hyphens, tildes, and underscores are
13300 eliminated. If this leaves the name short enough, we are done.
13303 If the name is too long, the longest segment is located (left-most if there are two
13304 of equal length), and shortened by dropping its last character. This is
13305 repeated until the name is short enough.
13307 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
13308 to fit the name into 8 characters as required by some operating systems.
13311 our-strings-wide_fixed 22
13312 our strings wide fixed 19
13313 our string wide fixed 18
13314 our strin wide fixed 17
13315 our stri wide fixed 16
13316 our stri wide fixe 15
13317 our str wide fixe 14
13318 our str wid fixe 13
13324 Final file name: oustwifi.adb
13328 The file names for all predefined units are always krunched to eight
13329 characters. The krunching of these predefined units uses the following
13330 special prefix replacements:
13334 replaced by @file{a-}
13337 replaced by @file{g-}
13340 replaced by @file{i-}
13343 replaced by @file{s-}
13346 These system files have a hyphen in the second character position. That
13347 is why normal user files replace such a character with a
13349 avoid confusion with system file names.
13351 As an example of this special rule, consider
13352 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
13355 ada-strings-wide_fixed 22
13356 a- strings wide fixed 18
13357 a- string wide fixed 17
13358 a- strin wide fixed 16
13359 a- stri wide fixed 15
13360 a- stri wide fixe 14
13361 a- str wide fixe 13
13367 Final file name: a-stwifi.adb
13371 Of course no file shortening algorithm can guarantee uniqueness over all
13372 possible unit names, and if file name krunching is used then it is your
13373 responsibility to ensure that no name clashes occur. The utility
13374 program @code{gnatkr} is supplied for conveniently determining the
13375 krunched name of a file.
13377 @node Examples of gnatkr Usage
13378 @section Examples of @code{gnatkr} Usage
13384 $ gnatkr very_long_unit_name.ads --> velounna.ads
13385 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
13386 $ gnatkr Grandparent.Parent.Child --> grparchi
13387 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
13388 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
13391 @node Preprocessing Using gnatprep
13392 @chapter Preprocessing Using @code{gnatprep}
13396 The @code{gnatprep} utility provides
13397 a simple preprocessing capability for Ada programs.
13398 It is designed for use with GNAT, but is not dependent on any special
13403 * Switches for gnatprep::
13404 * Form of Definitions File::
13405 * Form of Input Text for gnatprep::
13408 @node Using gnatprep
13409 @section Using @code{gnatprep}
13412 To call @code{gnatprep} use
13415 $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
13422 is the full name of the input file, which is an Ada source
13423 file containing preprocessor directives.
13426 is the full name of the output file, which is an Ada source
13427 in standard Ada form. When used with GNAT, this file name will
13428 normally have an ads or adb suffix.
13431 is the full name of a text file containing definitions of
13432 symbols to be referenced by the preprocessor. This argument is
13433 optional, and can be replaced by the use of the @code{-D} switch.
13436 is an optional sequence of switches as described in the next section.
13439 @node Switches for gnatprep
13440 @section Switches for @code{gnatprep}
13445 Causes both preprocessor lines and the lines deleted by
13446 preprocessing to be replaced by blank lines in the output source file,
13447 preserving line numbers in the output file.
13450 Causes both preprocessor lines and the lines deleted
13451 by preprocessing to be retained in the output source as comments marked
13452 with the special string "--! ". This option will result in line numbers
13453 being preserved in the output file.
13455 @item -Dsymbol=value
13456 Defines a new symbol, associated with value. If no value is given on the
13457 command line, then symbol is considered to be @code{True}. This switch
13458 can be used in place of a definition file.
13462 Causes a @code{Source_Reference} pragma to be generated that
13463 references the original input file, so that error messages will use
13464 the file name of this original file. The use of this switch implies
13465 that preprocessor lines are not to be removed from the file, so its
13466 use will force @code{-b} mode if
13468 has not been specified explicitly.
13470 Note that if the file to be preprocessed contains multiple units, then
13471 it will be necessary to @code{gnatchop} the output file from
13472 @code{gnatprep}. If a @code{Source_Reference} pragma is present
13473 in the preprocessed file, it will be respected by
13475 so that the final chopped files will correctly refer to the original
13476 input source file for @code{gnatprep}.
13479 Causes a sorted list of symbol names and values to be
13480 listed on the standard output file.
13483 Causes undefined symbols to be treated as having the value FALSE in the context
13484 of a preprocessor test. In the absence of this option, an undefined symbol in
13485 a @code{#if} or @code{#elsif} test will be treated as an error.
13490 Note: if neither @code{-b} nor @code{-c} is present,
13491 then preprocessor lines and
13492 deleted lines are completely removed from the output, unless -r is
13493 specified, in which case -b is assumed.
13495 @node Form of Definitions File
13496 @section Form of Definitions File
13499 The definitions file contains lines of the form
13506 where symbol is an identifier, following normal Ada (case-insensitive)
13507 rules for its syntax, and value is one of the following:
13511 Empty, corresponding to a null substitution
13513 A string literal using normal Ada syntax
13515 Any sequence of characters from the set
13516 (letters, digits, period, underline).
13520 Comment lines may also appear in the definitions file, starting with
13521 the usual @code{--},
13522 and comments may be added to the definitions lines.
13524 @node Form of Input Text for gnatprep
13525 @section Form of Input Text for @code{gnatprep}
13528 The input text may contain preprocessor conditional inclusion lines,
13529 as well as general symbol substitution sequences.
13531 The preprocessor conditional inclusion commands have the form
13536 #if @i{expression} [then]
13538 #elsif @i{expression} [then]
13540 #elsif @i{expression} [then]
13551 In this example, @i{expression} is defined by the following grammar:
13553 @i{expression} ::= <symbol>
13554 @i{expression} ::= <symbol> = "<value>"
13555 @i{expression} ::= <symbol> = <symbol>
13556 @i{expression} ::= <symbol> 'Defined
13557 @i{expression} ::= not @i{expression}
13558 @i{expression} ::= @i{expression} and @i{expression}
13559 @i{expression} ::= @i{expression} or @i{expression}
13560 @i{expression} ::= @i{expression} and then @i{expression}
13561 @i{expression} ::= @i{expression} or else @i{expression}
13562 @i{expression} ::= ( @i{expression} )
13566 For the first test (@i{expression} ::= <symbol>) the symbol must have
13567 either the value true or false, that is to say the right-hand of the
13568 symbol definition must be one of the (case-insensitive) literals
13569 @code{True} or @code{False}. If the value is true, then the
13570 corresponding lines are included, and if the value is false, they are
13573 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
13574 the symbol has been defined in the definition file or by a @code{-D}
13575 switch on the command line. Otherwise, the test is false.
13577 The equality tests are case insensitive, as are all the preprocessor lines.
13579 If the symbol referenced is not defined in the symbol definitions file,
13580 then the effect depends on whether or not switch @code{-u}
13581 is specified. If so, then the symbol is treated as if it had the value
13582 false and the test fails. If this switch is not specified, then
13583 it is an error to reference an undefined symbol. It is also an error to
13584 reference a symbol that is defined with a value other than @code{True}
13587 The use of the @code{not} operator inverts the sense of this logical test, so
13588 that the lines are included only if the symbol is not defined.
13589 The @code{then} keyword is optional as shown
13591 The @code{#} must be the first non-blank character on a line, but
13592 otherwise the format is free form. Spaces or tabs may appear between
13593 the @code{#} and the keyword. The keywords and the symbols are case
13594 insensitive as in normal Ada code. Comments may be used on a
13595 preprocessor line, but other than that, no other tokens may appear on a
13596 preprocessor line. Any number of @code{elsif} clauses can be present,
13597 including none at all. The @code{else} is optional, as in Ada.
13599 The @code{#} marking the start of a preprocessor line must be the first
13600 non-blank character on the line, i.e. it must be preceded only by
13601 spaces or horizontal tabs.
13603 Symbol substitution outside of preprocessor lines is obtained by using
13611 anywhere within a source line, except in a comment or within a
13612 string literal. The identifier
13613 following the @code{$} must match one of the symbols defined in the symbol
13614 definition file, and the result is to substitute the value of the
13615 symbol in place of @code{$symbol} in the output file.
13617 Note that although the substitution of strings within a string literal
13618 is not possible, it is possible to have a symbol whose defined value is
13619 a string literal. So instead of setting XYZ to @code{hello} and writing:
13622 Header : String := "$XYZ";
13626 you should set XYZ to @code{"hello"} and write:
13629 Header : String := $XYZ;
13633 and then the substitution will occur as desired.
13636 @node The GNAT Library Browser gnatls
13637 @chapter The GNAT Library Browser @code{gnatls}
13639 @cindex Library browser
13642 @code{gnatls} is a tool that outputs information about compiled
13643 units. It gives the relationship between objects, unit names and source
13644 files. It can also be used to check the source dependencies of a unit
13645 as well as various characteristics.
13649 * Switches for gnatls::
13650 * Examples of gnatls Usage::
13653 @node Running gnatls
13654 @section Running @code{gnatls}
13657 The @code{gnatls} command has the form
13660 $ gnatls switches @var{object_or_ali_file}
13664 The main argument is the list of object or @file{ali} files
13665 (@pxref{The Ada Library Information Files})
13666 for which information is requested.
13668 In normal mode, without additional option, @code{gnatls} produces a
13669 four-column listing. Each line represents information for a specific
13670 object. The first column gives the full path of the object, the second
13671 column gives the name of the principal unit in this object, the third
13672 column gives the status of the source and the fourth column gives the
13673 full path of the source representing this unit.
13674 Here is a simple example of use:
13678 ./demo1.o demo1 DIF demo1.adb
13679 ./demo2.o demo2 OK demo2.adb
13680 ./hello.o h1 OK hello.adb
13681 ./instr-child.o instr.child MOK instr-child.adb
13682 ./instr.o instr OK instr.adb
13683 ./tef.o tef DIF tef.adb
13684 ./text_io_example.o text_io_example OK text_io_example.adb
13685 ./tgef.o tgef DIF tgef.adb
13689 The first line can be interpreted as follows: the main unit which is
13691 object file @file{demo1.o} is demo1, whose main source is in
13692 @file{demo1.adb}. Furthermore, the version of the source used for the
13693 compilation of demo1 has been modified (DIF). Each source file has a status
13694 qualifier which can be:
13697 @item OK (unchanged)
13698 The version of the source file used for the compilation of the
13699 specified unit corresponds exactly to the actual source file.
13701 @item MOK (slightly modified)
13702 The version of the source file used for the compilation of the
13703 specified unit differs from the actual source file but not enough to
13704 require recompilation. If you use gnatmake with the qualifier
13705 @code{-m (minimal recompilation)}, a file marked
13706 MOK will not be recompiled.
13708 @item DIF (modified)
13709 No version of the source found on the path corresponds to the source
13710 used to build this object.
13712 @item ??? (file not found)
13713 No source file was found for this unit.
13715 @item HID (hidden, unchanged version not first on PATH)
13716 The version of the source that corresponds exactly to the source used
13717 for compilation has been found on the path but it is hidden by another
13718 version of the same source that has been modified.
13722 @node Switches for gnatls
13723 @section Switches for @code{gnatls}
13726 @code{gnatls} recognizes the following switches:
13730 @cindex @code{-a} (@code{gnatls})
13731 Consider all units, including those of the predefined Ada library.
13732 Especially useful with @code{-d}.
13735 @cindex @code{-d} (@code{gnatls})
13736 List sources from which specified units depend on.
13739 @cindex @code{-h} (@code{gnatls})
13740 Output the list of options.
13743 @cindex @code{-o} (@code{gnatls})
13744 Only output information about object files.
13747 @cindex @code{-s} (@code{gnatls})
13748 Only output information about source files.
13751 @cindex @code{-u} (@code{gnatls})
13752 Only output information about compilation units.
13755 @itemx -aI@var{dir}
13759 Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags
13760 (see @ref{Switches for gnatmake}).
13762 @item --RTS=@var{rts-path}
13763 @cindex @code{--RTS} (@code{gnatls})
13764 Specifies the default location of the runtime library. Same meaning as the
13765 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13768 @cindex @code{-s} (@code{gnatls})
13769 Verbose mode. Output the complete source and object paths. Do not use
13770 the default column layout but instead use long format giving as much as
13771 information possible on each requested units, including special
13772 characteristics such as:
13775 @item Preelaborable
13776 The unit is preelaborable in the Ada 95 sense.
13779 No elaboration code has been produced by the compiler for this unit.
13782 The unit is pure in the Ada 95 sense.
13784 @item Elaborate_Body
13785 The unit contains a pragma Elaborate_Body.
13788 The unit contains a pragma Remote_Types.
13790 @item Shared_Passive
13791 The unit contains a pragma Shared_Passive.
13794 This unit is part of the predefined environment and cannot be modified
13797 @item Remote_Call_Interface
13798 The unit contains a pragma Remote_Call_Interface.
13804 @node Examples of gnatls Usage
13805 @section Example of @code{gnatls} Usage
13808 Example of using the verbose switch. Note how the source and
13809 object paths are affected by the -I switch.
13812 $ gnatls -v -I.. demo1.o
13814 GNATLS 3.10w (970212) Copyright 1999 Free Software Foundation, Inc.
13816 Source Search Path:
13817 <Current_Directory>
13819 /home/comar/local/adainclude/
13821 Object Search Path:
13822 <Current_Directory>
13824 /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/
13829 Kind => subprogram body
13830 Flags => No_Elab_Code
13831 Source => demo1.adb modified
13835 The following is an example of use of the dependency list.
13836 Note the use of the -s switch
13837 which gives a straight list of source files. This can be useful for
13838 building specialized scripts.
13841 $ gnatls -d demo2.o
13842 ./demo2.o demo2 OK demo2.adb
13848 $ gnatls -d -s -a demo1.o
13850 /home/comar/local/adainclude/ada.ads
13851 /home/comar/local/adainclude/a-finali.ads
13852 /home/comar/local/adainclude/a-filico.ads
13853 /home/comar/local/adainclude/a-stream.ads
13854 /home/comar/local/adainclude/a-tags.ads
13857 /home/comar/local/adainclude/gnat.ads
13858 /home/comar/local/adainclude/g-io.ads
13860 /home/comar/local/adainclude/system.ads
13861 /home/comar/local/adainclude/s-exctab.ads
13862 /home/comar/local/adainclude/s-finimp.ads
13863 /home/comar/local/adainclude/s-finroo.ads
13864 /home/comar/local/adainclude/s-secsta.ads
13865 /home/comar/local/adainclude/s-stalib.ads
13866 /home/comar/local/adainclude/s-stoele.ads
13867 /home/comar/local/adainclude/s-stratt.ads
13868 /home/comar/local/adainclude/s-tasoli.ads
13869 /home/comar/local/adainclude/s-unstyp.ads
13870 /home/comar/local/adainclude/unchconv.ads
13874 @node GNAT and Libraries
13875 @chapter GNAT and Libraries
13876 @cindex Library, building, installing
13879 This chapter addresses some of the issues related to building and using
13880 a library with GNAT. It also shows how the GNAT run-time library can be
13884 * Creating an Ada Library::
13885 * Installing an Ada Library::
13886 * Using an Ada Library::
13887 * Creating an Ada Library to be Used in a Non-Ada Context::
13888 * Rebuilding the GNAT Run-Time Library::
13891 @node Creating an Ada Library
13892 @section Creating an Ada Library
13895 In the GNAT environment, a library has two components:
13900 Compiled code and Ali files. See @ref{The Ada Library Information Files}.
13904 In order to use other packages @ref{The GNAT Compilation Model}
13905 requires a certain number of sources to be available to the compiler.
13907 sources required includes the specs of all the packages that make up the
13908 visible part of the library as well as all the sources upon which they
13909 depend. The bodies of all visible generic units must also be provided.
13911 Although it is not strictly mandatory, it is recommended that all sources
13912 needed to recompile the library be provided, so that the user can make
13913 full use of inter-unit inlining and source-level debugging. This can also
13914 make the situation easier for users that need to upgrade their compilation
13915 toolchain and thus need to recompile the library from sources.
13918 The compiled code can be provided in different ways. The simplest way is
13919 to provide directly the set of objects produced by the compiler during
13920 the compilation of the library. It is also possible to group the objects
13921 into an archive using whatever commands are provided by the operating
13922 system. Finally, it is also possible to create a shared library (see
13923 option -shared in the GCC manual).
13926 There are various possibilities for compiling the units that make up the
13927 library: for example with a Makefile @ref{Using the GNU make Utility},
13928 or with a conventional script.
13929 For simple libraries, it is also possible to create a
13930 dummy main program which depends upon all the packages that comprise the
13931 interface of the library. This dummy main program can then be given to
13932 gnatmake, in order to build all the necessary objects. Here is an example
13933 of such a dummy program and the generic commands used to build an
13934 archive or a shared library.
13940 @b{with} My_Lib.Service1;
13941 @b{with} My_Lib.Service2;
13942 @b{with} My_Lib.Service3;
13943 @b{procedure} My_Lib_Dummy @b{is}
13948 # compiling the library
13949 $ gnatmake -c my_lib_dummy.adb
13951 # we don't need the dummy object itself
13952 $ rm my_lib_dummy.o my_lib_dummy.ali
13954 # create an archive with the remaining objects
13955 $ ar rc libmy_lib.a *.o
13956 # some systems may require "ranlib" to be run as well
13958 # or create a shared library
13959 $ gcc -shared -o libmy_lib.so *.o
13960 # some systems may require the code to have been compiled with -fPIC
13964 When the objects are grouped in an archive or a shared library, the user
13965 needs to specify the desired library at link time, unless a pragma
13966 linker_options has been used in one of the sources:
13968 @b{pragma} Linker_Options ("-lmy_lib");
13971 @node Installing an Ada Library
13972 @section Installing an Ada Library
13975 In the GNAT model, installing a library consists in copying into a specific
13976 location the files that make up this library. It is possible to install
13977 the sources in a different directory from the other files (ALI, objects,
13978 archives) since the source path and the object path can easily be
13979 specified separately.
13982 For general purpose libraries, it is possible for the system
13983 administrator to put those libraries in the default compiler paths. To
13984 achieve this, he must specify their location in the configuration files
13985 "ada_source_path" and "ada_object_path" that must be located in the GNAT
13986 installation tree at the same place as the gcc spec file. The location of
13987 the gcc spec file can be determined as follows:
13993 The configuration files mentioned above have simple format: each line in them
13994 must contain one unique
13995 directory name. Those names are added to the corresponding path
13996 in their order of appearance in the file. The names can be either absolute
13997 or relative, in the latter case, they are relative to where theses files
14001 "ada_source_path" and "ada_object_path" might actually not be present in a
14002 GNAT installation, in which case, GNAT will look for its run-time library in
14003 the directories "adainclude" for the sources and "adalib" for the
14004 objects and ALI files. When the files exist, the compiler does not
14005 look in "adainclude" and "adalib" at all, and thus the "ada_source_path" file
14006 must contain the location for the GNAT run-time sources (which can simply
14007 be "adainclude"). In the same way, the "ada_object_path" file must contain
14008 the location for the GNAT run-time objects (which can simply
14012 You can also specify a new default path to the runtime library at compilation
14013 time with the switch "--RTS=@var{rts-path}". You can easily choose and change
14014 the runtime you want your program to be compiled with. This switch is
14015 recognized by gcc, gnatmake, gnatbind, gnatls, gnatfind and gnatxref.
14018 It is possible to install a library before or after the standard GNAT
14019 library, by reordering the lines in the configuration files. In general, a
14020 library must be installed before the GNAT library if it redefines any part of it.
14022 @node Using an Ada Library
14023 @section Using an Ada Library
14026 In order to use a Ada library, you need to make sure that this
14027 library is on both your source and object path
14028 @ref{Search Paths and the Run-Time Library (RTL)}
14029 and @ref{Search Paths for gnatbind}. For
14030 instance, you can use the library "mylib" installed in "/dir/my_lib_src"
14031 and "/dir/my_lib_obj" with the following commands:
14034 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
14039 This can be simplified down to the following:
14043 when the following conditions are met:
14046 "/dir/my_lib_src" has been added by the user to the environment
14047 variable "ADA_INCLUDE_PATH", or by the administrator to the file
14050 "/dir/my_lib_obj" has been added by the user to the environment
14051 variable "ADA_OBJECTS_PATH", or by the administrator to the file
14054 a pragma linker_options, as mentioned in @ref{Creating an Ada Library}
14055 as been added to the sources.
14059 @node Creating an Ada Library to be Used in a Non-Ada Context
14060 @section Creating an Ada Library to be Used in a Non-Ada Context
14063 The previous sections detailed how to create and install a library that
14064 was usable from an Ada main program. Using this library in a non-Ada
14065 context is not possible, because the elaboration of the library is
14066 automatically done as part of the main program elaboration.
14068 GNAT also provides the ability to build libraries that can be used both
14069 in an Ada and non-Ada context. This section describes how to build such
14070 a library, and then how to use it from a C program. The method for
14071 interfacing with the library from other languages such as Fortran for
14072 instance remains the same.
14074 @subsection Creating the Library
14077 @item Identify the units representing the interface of the library.
14079 Here is an example of simple library interface:
14082 package Interface is
14084 procedure Do_Something;
14086 procedure Do_Something_Else;
14091 @item Use @code{pragma Export} or @code{pragma Convention} for the
14094 Our package @code{Interface} is then updated as follow:
14096 package Interface is
14098 procedure Do_Something;
14099 pragma Export (C, Do_Something, "do_something");
14101 procedure Do_Something_Else;
14102 pragma Export (C, Do_Something_Else, "do_something_else");
14107 @item Compile all the units composing the library.
14109 @item Bind the library objects.
14111 This step is performed by invoking gnatbind with the @code{-L<prefix>}
14112 switch. @code{gnatbind} will then generate the library elaboration
14113 procedure (named @code{<prefix>init}) and the run-time finalization
14114 procedure (named @code{<prefix>final}).
14117 # generate the binder file in Ada
14118 $ gnatbind -Lmylib interface
14120 # generate the binder file in C
14121 $ gnatbind -C -Lmylib interface
14124 @item Compile the files generated by the binder
14127 $ gcc -c b~interface.adb
14130 @item Create the library;
14132 The procedure is identical to the procedure explained in
14133 @ref{Creating an Ada Library},
14134 except that @file{b~interface.o} needs to be added to
14135 the list of objects.
14138 # create an archive file
14139 $ ar cr libmylib.a b~interface.o <other object files>
14141 # create a shared library
14142 $ gcc -shared -o libmylib.so b~interface.o <other object files>
14145 @item Provide a "foreign" view of the library interface;
14147 The example below shows the content of @code{mylib_interface.h} (note
14148 that there is no rule for the naming of this file, any name can be used)
14150 /* the library elaboration procedure */
14151 extern void mylibinit (void);
14153 /* the library finalization procedure */
14154 extern void mylibfinal (void);
14156 /* the interface exported by the library */
14157 extern void do_something (void);
14158 extern void do_something_else (void);
14162 @subsection Using the Library
14165 Libraries built as explained above can be used from any program, provided
14166 that the elaboration procedures (named @code{mylibinit} in the previous
14167 example) are called before the library services are used. Any number of
14168 libraries can be used simultaneously, as long as the elaboration
14169 procedure of each library is called.
14171 Below is an example of C program that uses our @code{mylib} library.
14174 #include "mylib_interface.h"
14179 /* First, elaborate the library before using it */
14182 /* Main program, using the library exported entities */
14184 do_something_else ();
14186 /* Library finalization at the end of the program */
14193 Note that this same library can be used from an equivalent Ada main
14194 program. In addition, if the libraries are installed as detailed in
14195 @ref{Installing an Ada Library}, it is not necessary to invoke the
14196 library elaboration and finalization routines. The binder will ensure
14197 that this is done as part of the main program elaboration and
14198 finalization phases.
14200 @subsection The Finalization Phase
14203 Invoking any library finalization procedure generated by @code{gnatbind}
14204 shuts down the Ada run time permanently. Consequently, the finalization
14205 of all Ada libraries must be performed at the end of the program. No
14206 call to these libraries nor the Ada run time should be made past the
14207 finalization phase.
14209 @subsection Restrictions in Libraries
14212 The pragmas listed below should be used with caution inside libraries,
14213 as they can create incompatibilities with other Ada libraries:
14215 @item pragma @code{Locking_Policy}
14216 @item pragma @code{Queuing_Policy}
14217 @item pragma @code{Task_Dispatching_Policy}
14218 @item pragma @code{Unreserve_All_Interrupts}
14220 When using a library that contains such pragmas, the user must make sure
14221 that all libraries use the same pragmas with the same values. Otherwise,
14222 a @code{Program_Error} will
14223 be raised during the elaboration of the conflicting
14224 libraries. The usage of these pragmas and its consequences for the user
14225 should therefore be well documented.
14227 Similarly, the traceback in exception occurrences mechanism should be
14228 enabled or disabled in a consistent manner across all libraries.
14229 Otherwise, a Program_Error will be raised during the elaboration of the
14230 conflicting libraries.
14232 If the @code{'Version} and @code{'Body_Version}
14233 attributes are used inside a library, then it is necessary to
14234 perform a @code{gnatbind} step that mentions all ali files in all
14235 libraries, so that version identifiers can be properly computed.
14236 In practice these attributes are rarely used, so this is unlikely
14237 to be a consideration.
14239 @node Rebuilding the GNAT Run-Time Library
14240 @section Rebuilding the GNAT Run-Time Library
14243 It may be useful to recompile the GNAT library in various contexts, the
14244 most important one being the use of partition-wide configuration pragmas
14245 such as Normalize_Scalar. A special Makefile called
14246 @code{Makefile.adalib} is provided to that effect and can be found in
14247 the directory containing the GNAT library. The location of this
14248 directory depends on the way the GNAT environment has been installed and can
14249 be determined by means of the command:
14256 The last entry in the object search path usually contains the
14257 gnat library. This Makefile contains its own documentation and in
14258 particular the set of instructions needed to rebuild a new library and
14261 @node Using the GNU make Utility
14262 @chapter Using the GNU @code{make} Utility
14266 This chapter offers some examples of makefiles that solve specific
14267 problems. It does not explain how to write a makefile (see the GNU make
14268 documentation), nor does it try to replace the @code{gnatmake} utility
14269 (@pxref{The GNAT Make Program gnatmake}).
14271 All the examples in this section are specific to the GNU version of
14272 make. Although @code{make} is a standard utility, and the basic language
14273 is the same, these examples use some advanced features found only in
14277 * Using gnatmake in a Makefile::
14278 * Automatically Creating a List of Directories::
14279 * Generating the Command Line Switches::
14280 * Overcoming Command Line Length Limits::
14283 @node Using gnatmake in a Makefile
14284 @section Using gnatmake in a Makefile
14289 Complex project organizations can be handled in a very powerful way by
14290 using GNU make combined with gnatmake. For instance, here is a Makefile
14291 which allows you to build each subsystem of a big project into a separate
14292 shared library. Such a makefile allows you to significantly reduce the link
14293 time of very big applications while maintaining full coherence at
14294 each step of the build process.
14296 The list of dependencies are handled automatically by
14297 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
14298 the appropriate directories.
14300 Note that you should also read the example on how to automatically
14301 create the list of directories (@pxref{Automatically Creating a List of Directories})
14302 which might help you in case your project has a lot of
14308 @font@heightrm=cmr8
14311 ## This Makefile is intended to be used with the following directory
14313 ## - The sources are split into a series of csc (computer software components)
14314 ## Each of these csc is put in its own directory.
14315 ## Their name are referenced by the directory names.
14316 ## They will be compiled into shared library (although this would also work
14317 ## with static libraries
14318 ## - The main program (and possibly other packages that do not belong to any
14319 ## csc is put in the top level directory (where the Makefile is).
14320 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
14321 ## \_ second_csc (sources) __ lib (will contain the library)
14323 ## Although this Makefile is build for shared library, it is easy to modify
14324 ## to build partial link objects instead (modify the lines with -shared and
14327 ## With this makefile, you can change any file in the system or add any new
14328 ## file, and everything will be recompiled correctly (only the relevant shared
14329 ## objects will be recompiled, and the main program will be re-linked).
14331 # The list of computer software component for your project. This might be
14332 # generated automatically.
14335 # Name of the main program (no extension)
14338 # If we need to build objects with -fPIC, uncomment the following line
14341 # The following variable should give the directory containing libgnat.so
14342 # You can get this directory through 'gnatls -v'. This is usually the last
14343 # directory in the Object_Path.
14346 # The directories for the libraries
14347 # (This macro expands the list of CSC to the list of shared libraries, you
14348 # could simply use the expanded form :
14349 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
14350 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
14352 $@{MAIN@}: objects $@{LIB_DIR@}
14353 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
14354 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
14357 # recompile the sources
14358 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
14360 # Note: In a future version of GNAT, the following commands will be simplified
14361 # by a new tool, gnatmlib
14363 mkdir -p $@{dir $@@ @}
14364 cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
14365 cd $@{dir $@@ @}; cp -f ../*.ali .
14367 # The dependencies for the modules
14368 # Note that we have to force the expansion of *.o, since in some cases make won't
14369 # be able to do it itself.
14370 aa/lib/libaa.so: $@{wildcard aa/*.o@}
14371 bb/lib/libbb.so: $@{wildcard bb/*.o@}
14372 cc/lib/libcc.so: $@{wildcard cc/*.o@}
14374 # Make sure all of the shared libraries are in the path before starting the
14377 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
14380 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
14381 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
14382 $@{RM@} $@{CSC_LIST:%=%/*.o@}
14383 $@{RM@} *.o *.ali $@{MAIN@}
14386 @node Automatically Creating a List of Directories
14387 @section Automatically Creating a List of Directories
14390 In most makefiles, you will have to specify a list of directories, and
14391 store it in a variable. For small projects, it is often easier to
14392 specify each of them by hand, since you then have full control over what
14393 is the proper order for these directories, which ones should be
14396 However, in larger projects, which might involve hundreds of
14397 subdirectories, it might be more convenient to generate this list
14400 The example below presents two methods. The first one, although less
14401 general, gives you more control over the list. It involves wildcard
14402 characters, that are automatically expanded by @code{make}. Its
14403 shortcoming is that you need to explicitly specify some of the
14404 organization of your project, such as for instance the directory tree
14405 depth, whether some directories are found in a separate tree,...
14407 The second method is the most general one. It requires an external
14408 program, called @code{find}, which is standard on all Unix systems. All
14409 the directories found under a given root directory will be added to the
14415 @font@heightrm=cmr8
14418 # The examples below are based on the following directory hierarchy:
14419 # All the directories can contain any number of files
14420 # ROOT_DIRECTORY -> a -> aa -> aaa
14423 # -> b -> ba -> baa
14426 # This Makefile creates a variable called DIRS, that can be reused any time
14427 # you need this list (see the other examples in this section)
14429 # The root of your project's directory hierarchy
14433 # First method: specify explicitly the list of directories
14434 # This allows you to specify any subset of all the directories you need.
14437 DIRS := a/aa/ a/ab/ b/ba/
14440 # Second method: use wildcards
14441 # Note that the argument(s) to wildcard below should end with a '/'.
14442 # Since wildcards also return file names, we have to filter them out
14443 # to avoid duplicate directory names.
14444 # We thus use make's @code{dir} and @code{sort} functions.
14445 # It sets DIRs to the following value (note that the directories aaa and baa
14446 # are not given, unless you change the arguments to wildcard).
14447 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
14450 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/ $@{ROOT_DIRECTORY@}/*/*/@}@}@}
14453 # Third method: use an external program
14454 # This command is much faster if run on local disks, avoiding NFS slowdowns.
14455 # This is the most complete command: it sets DIRs to the following value:
14456 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
14459 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
14463 @node Generating the Command Line Switches
14464 @section Generating the Command Line Switches
14467 Once you have created the list of directories as explained in the
14468 previous section (@pxref{Automatically Creating a List of Directories}),
14469 you can easily generate the command line arguments to pass to gnatmake.
14471 For the sake of completeness, this example assumes that the source path
14472 is not the same as the object path, and that you have two separate lists
14476 # see "Automatically creating a list of directories" to create
14481 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
14482 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
14485 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
14488 @node Overcoming Command Line Length Limits
14489 @section Overcoming Command Line Length Limits
14492 One problem that might be encountered on big projects is that many
14493 operating systems limit the length of the command line. It is thus hard to give
14494 gnatmake the list of source and object directories.
14496 This example shows how you can set up environment variables, which will
14497 make @code{gnatmake} behave exactly as if the directories had been
14498 specified on the command line, but have a much higher length limit (or
14499 even none on most systems).
14501 It assumes that you have created a list of directories in your Makefile,
14502 using one of the methods presented in
14503 @ref{Automatically Creating a List of Directories}.
14504 For the sake of completeness, we assume that the object
14505 path (where the ALI files are found) is different from the sources patch.
14507 Note a small trick in the Makefile below: for efficiency reasons, we
14508 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
14509 expanded immediately by @code{make}. This way we overcome the standard
14510 make behavior which is to expand the variables only when they are
14516 @font@heightrm=cmr8
14519 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
14520 # This is the same thing as putting the -I arguments on the command line.
14521 # (the equivalent of using -aI on the command line would be to define
14522 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
14523 # You can of course have different values for these variables.
14525 # Note also that we need to keep the previous values of these variables, since
14526 # they might have been set before running 'make' to specify where the GNAT
14527 # library is installed.
14529 # see "Automatically creating a list of directories" to create these
14535 space:=$@{empty@} $@{empty@}
14536 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
14537 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
14538 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
14539 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
14540 export ADA_INCLUDE_PATH
14541 export ADA_OBJECT_PATH
14547 @node Finding Memory Problems with gnatmem
14548 @chapter Finding Memory Problems with @code{gnatmem}
14552 @code{gnatmem}, is a tool that monitors dynamic allocation and
14553 deallocation activity in a program, and displays information about
14554 incorrect deallocations and possible sources of memory leaks. Gnatmem
14555 provides three type of information:
14558 General information concerning memory management, such as the total
14559 number of allocations and deallocations, the amount of allocated
14560 memory and the high water mark, i.e. the largest amount of allocated
14561 memory in the course of program execution.
14564 Backtraces for all incorrect deallocations, that is to say deallocations
14565 which do not correspond to a valid allocation.
14568 Information on each allocation that is potentially the origin of a memory
14572 The @code{gnatmem} command has two modes. It can be used with @code{gdb}
14573 or with instrumented allocation and deallocation routines. The later
14574 mode is called the @code{GMEM} mode. Both modes produce the very same
14578 * Running gnatmem (GDB Mode)::
14579 * Running gnatmem (GMEM Mode)::
14580 * Switches for gnatmem::
14581 * Examples of gnatmem Usage::
14582 * GDB and GMEM Modes::
14583 * Implementation Note::
14586 @node Running gnatmem (GDB Mode)
14587 @section Running @code{gnatmem} (GDB Mode)
14590 The @code{gnatmem} command has the form
14593 $ gnatmem [-q] [n] [-o file] user_program [program_arg]*
14595 $ gnatmem [-q] [n] -i file
14599 Gnatmem must be supplied with the executable to examine, followed by its
14600 run-time inputs. For example, if a program is executed with the command:
14602 $ my_program arg1 arg2
14604 then it can be run under @code{gnatmem} control using the command:
14606 $ gnatmem my_program arg1 arg2
14609 The program is transparently executed under the control of the debugger
14610 @ref{The GNAT Debugger GDB}. This does not affect the behavior
14611 of the program, except for sensitive real-time programs. When the program
14612 has completed execution, @code{gnatmem} outputs a report containing general
14613 allocation/deallocation information and potential memory leak.
14614 For better results, the user program should be compiled with
14615 debugging options @ref{Switches for gcc}.
14617 Here is a simple example of use:
14619 *************** debut cc
14625 Total number of allocations : 45
14626 Total number of deallocations : 6
14627 Final Water Mark (non freed mem) : 11.29 Kilobytes
14628 High Water Mark : 11.40 Kilobytes
14633 Allocation Root # 2
14634 -------------------
14635 Number of non freed allocations : 11
14636 Final Water Mark (non freed mem) : 1.16 Kilobytes
14637 High Water Mark : 1.27 Kilobytes
14639 test_gm.adb:23 test_gm.alloc
14645 The first block of output give general information. In this case, the
14646 Ada construct "@b{new}" was executed 45 times, and only 6 calls to an
14647 unchecked deallocation routine occurred.
14649 Subsequent paragraphs display information on all allocation roots.
14650 An allocation root is a specific point in the execution of the program
14651 that generates some dynamic allocation, such as a "@b{new}" construct. This
14652 root is represented by an execution backtrace (or subprogram call
14653 stack). By default the backtrace depth for allocations roots is 1, so
14654 that a root corresponds exactly to a source location. The backtrace can
14655 be made deeper, to make the root more specific.
14657 @node Running gnatmem (GMEM Mode)
14658 @section Running @code{gnatmem} (GMEM Mode)
14659 @cindex @code{GMEM} (@code{gnatmem})
14662 The @code{gnatmem} command has the form
14665 $ gnatmem [-q] [n] -i gmem.out user_program [program_arg]*
14668 The program must have been linked with the instrumented version of the
14669 allocation and deallocation routines. This is done with linking with the
14670 @file{libgmem.a} library. For better results, the user program should be
14671 compiled with debugging options @ref{Switches for gcc}. For example to
14672 build @file{my_program}:
14675 $ gnatmake -g my_program -largs -lgmem
14679 When running @file{my_program} the file @file{gmem.out} is produced. This file
14680 contains information about all allocations and deallocations done by the
14681 program. It is produced by the instrumented allocations and
14682 deallocations routines and will be used by @code{gnatmem}.
14685 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
14686 examine followed by its run-time inputs. For example, if a program is
14687 executed with the command:
14689 $ my_program arg1 arg2
14691 then @file{gmem.out} can be analysed by @code{gnatmem} using the command:
14693 $ gnatmem -i gmem.out my_program arg1 arg2
14696 @node Switches for gnatmem
14697 @section Switches for @code{gnatmem}
14700 @code{gnatmem} recognizes the following switches:
14705 @cindex @code{-q} (@code{gnatmem})
14706 Quiet. Gives the minimum output needed to identify the origin of the
14707 memory leaks. Omit statistical information.
14710 @cindex @code{n} (@code{gnatmem})
14711 N is an integer literal (usually between 1 and 10) which controls the
14712 depth of the backtraces defining allocation root. The default value for
14713 N is 1. The deeper the backtrace, the more precise the localization of
14714 the root. Note that the total number of roots can depend on this
14717 @item @code{-o file}
14718 @cindex @code{-o} (@code{gnatmem})
14719 Direct the gdb output to the specified file. The @code{gdb} script used
14720 to generate this output is also saved in the file @file{gnatmem.tmp}.
14722 @item @code{-i file}
14723 @cindex @code{-i} (@code{gnatmem})
14724 Do the @code{gnatmem} processing starting from @file{file} which has
14725 been generated by a previous call to @code{gnatmem} with the -o
14726 switch or @file{gmem.out} produced by @code{GMEM} mode. This is useful
14727 for post mortem processing.
14731 @node Examples of gnatmem Usage
14732 @section Example of @code{gnatmem} Usage
14735 This section is based on the @code{GDB} mode of @code{gnatmem}. The same
14736 results can be achieved using @code{GMEM} mode. See section
14737 @ref{Running gnatmem (GMEM Mode)}.
14740 The first example shows the use of @code{gnatmem}
14741 on a simple leaking program.
14742 Suppose that we have the following Ada program:
14747 @b{with} Unchecked_Deallocation;
14748 @b{procedure} Test_Gm @b{is}
14750 @b{type} T @b{is array} (1..1000) @b{of} Integer;
14751 @b{type} Ptr @b{is access} T;
14752 @b{procedure} Free @b{is new} Unchecked_Deallocation (T, Ptr);
14755 @b{procedure} My_Alloc @b{is}
14760 @b{procedure} My_DeAlloc @b{is}
14764 @b{end} My_DeAlloc;
14768 @b{for} I @b{in} 1 .. 5 @b{loop}
14769 @b{for} J @b{in} I .. 5 @b{loop}
14780 The program needs to be compiled with debugging option:
14783 $ gnatmake -g test_gm
14786 @code{gnatmem} is invoked simply with
14792 which produces the following output:
14797 Total number of allocations : 18
14798 Total number of deallocations : 5
14799 Final Water Mark (non freed mem) : 53.00 Kilobytes
14800 High Water Mark : 56.90 Kilobytes
14802 Allocation Root # 1
14803 -------------------
14804 Number of non freed allocations : 11
14805 Final Water Mark (non freed mem) : 42.97 Kilobytes
14806 High Water Mark : 46.88 Kilobytes
14808 test_gm.adb:11 test_gm.my_alloc
14810 Allocation Root # 2
14811 -------------------
14812 Number of non freed allocations : 1
14813 Final Water Mark (non freed mem) : 10.02 Kilobytes
14814 High Water Mark : 10.02 Kilobytes
14816 s-secsta.adb:81 system.secondary_stack.ss_init
14818 Allocation Root # 3
14819 -------------------
14820 Number of non freed allocations : 1
14821 Final Water Mark (non freed mem) : 12 Bytes
14822 High Water Mark : 12 Bytes
14824 s-secsta.adb:181 system.secondary_stack.ss_init
14828 Note that the GNAT run time contains itself a certain number of
14829 allocations that have no corresponding deallocation,
14830 as shown here for root #2 and root
14831 #1. This is a normal behavior when the number of non freed allocations
14832 is one, it locates dynamic data structures that the run time needs for
14833 the complete lifetime of the program. Note also that there is only one
14834 allocation root in the user program with a single line back trace:
14835 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
14836 program shows that 'My_Alloc' is called at 2 different points in the
14837 source (line 21 and line 24). If those two allocation roots need to be
14838 distinguished, the backtrace depth parameter can be used:
14841 $ gnatmem 3 test_gm
14845 which will give the following output:
14850 Total number of allocations : 18
14851 Total number of deallocations : 5
14852 Final Water Mark (non freed mem) : 53.00 Kilobytes
14853 High Water Mark : 56.90 Kilobytes
14855 Allocation Root # 1
14856 -------------------
14857 Number of non freed allocations : 10
14858 Final Water Mark (non freed mem) : 39.06 Kilobytes
14859 High Water Mark : 42.97 Kilobytes
14861 test_gm.adb:11 test_gm.my_alloc
14862 test_gm.adb:24 test_gm
14863 b_test_gm.c:52 main
14865 Allocation Root # 2
14866 -------------------
14867 Number of non freed allocations : 1
14868 Final Water Mark (non freed mem) : 10.02 Kilobytes
14869 High Water Mark : 10.02 Kilobytes
14871 s-secsta.adb:81 system.secondary_stack.ss_init
14872 s-secsta.adb:283 <system__secondary_stack___elabb>
14873 b_test_gm.c:33 adainit
14875 Allocation Root # 3
14876 -------------------
14877 Number of non freed allocations : 1
14878 Final Water Mark (non freed mem) : 3.91 Kilobytes
14879 High Water Mark : 3.91 Kilobytes
14881 test_gm.adb:11 test_gm.my_alloc
14882 test_gm.adb:21 test_gm
14883 b_test_gm.c:52 main
14885 Allocation Root # 4
14886 -------------------
14887 Number of non freed allocations : 1
14888 Final Water Mark (non freed mem) : 12 Bytes
14889 High Water Mark : 12 Bytes
14891 s-secsta.adb:181 system.secondary_stack.ss_init
14892 s-secsta.adb:283 <system__secondary_stack___elabb>
14893 b_test_gm.c:33 adainit
14897 The allocation root #1 of the first example has been split in 2 roots #1
14898 and #3 thanks to the more precise associated backtrace.
14900 @node GDB and GMEM Modes
14901 @section GDB and GMEM Modes
14904 The main advantage of the @code{GMEM} mode is that it is a lot faster than the
14905 @code{GDB} mode where the application must be monitored by a @code{GDB} script.
14906 But the @code{GMEM} mode is available only for DEC Unix, Linux x86,
14907 Solaris (sparc and x86) and Windows 95/98/NT/2000 (x86).
14910 The main advantage of the @code{GDB} mode is that it is available on all
14911 supported platforms. But it can be very slow if the application does a
14912 lot of allocations and deallocations.
14914 @node Implementation Note
14915 @section Implementation Note
14918 * gnatmem Using GDB Mode::
14919 * gnatmem Using GMEM Mode::
14922 @node gnatmem Using GDB Mode
14923 @subsection @code{gnatmem} Using @code{GDB} Mode
14926 @code{gnatmem} executes the user program under the control of @code{GDB} using
14927 a script that sets breakpoints and gathers information on each dynamic
14928 allocation and deallocation. The output of the script is then analyzed
14930 in order to locate memory leaks and their origin in the
14931 program. Gnatmem works by recording each address returned by the
14932 allocation procedure (@code{__gnat_malloc})
14933 along with the backtrace at the
14934 allocation point. On each deallocation, the deallocated address is
14935 matched with the corresponding allocation. At the end of the processing,
14936 the unmatched allocations are considered potential leaks. All the
14937 allocations associated with the same backtrace are grouped together and
14938 form an allocation root. The allocation roots are then sorted so that
14939 those with the biggest number of unmatched allocation are printed
14940 first. A delicate aspect of this technique is to distinguish between the
14941 data produced by the user program and the data produced by the gdb
14942 script. Currently, on systems that allow probing the terminal, the gdb
14943 command "tty" is used to force the program output to be redirected to the
14944 current terminal while the @code{gdb} output is directed to a file or to a
14945 pipe in order to be processed subsequently by @code{gnatmem}.
14947 @node gnatmem Using GMEM Mode
14948 @subsection @code{gnatmem} Using @code{GMEM} Mode
14951 This mode use the same algorithm to detect memory leak as the @code{GDB}
14952 mode of @code{gnatmem}, the only difference is in the way data are
14953 gathered. In @code{GMEM} mode the program is linked with instrumented
14954 version of @code{__gnat_malloc} and @code{__gnat_free}
14955 routines. Information needed to find memory leak are recorded by these
14956 routines in file @file{gmem.out}. This mode also require that the stack
14957 traceback be available, this is only implemented on some platforms
14958 @ref{GDB and GMEM Modes}.
14961 @node Finding Memory Problems with GNAT Debug Pool
14962 @chapter Finding Memory Problems with GNAT Debug Pool
14964 @cindex storage, pool, memory corruption
14967 The use of unchecked deallocation and unchecked conversion can easily
14968 lead to incorrect memory references. The problems generated by such
14969 references are usually difficult to tackle because the symptoms can be
14970 very remote from the origin of the problem. In such cases, it is
14971 very helpful to detect the problem as early as possible. This is the
14972 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
14975 In order to use the GNAT specific debugging pool, the user must
14976 associate a debug pool object with each of the access types that may be
14977 related to suspected memory problems. See Ada Reference Manual
14980 @b{type} Ptr @b{is} @b{access} Some_Type;
14981 Pool : GNAT.Debug_Pools.Debug_Pool;
14982 @b{for} Ptr'Storage_Pool @b{use} Pool;
14985 @code{GNAT.Debug_Pools} is derived from of a GNAT-specific kind of
14986 pool: the Checked_Pool. Such pools, like standard Ada storage pools,
14987 allow the user to redefine allocation and deallocation strategies. They
14988 also provide a checkpoint for each dereference, through the use of
14989 the primitive operation @code{Dereference} which is implicitly called at
14990 each dereference of an access value.
14992 Once an access type has been associated with a debug pool, operations on
14993 values of the type may raise four distinct exceptions,
14994 which correspond to four potential kinds of memory corruption:
14997 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
14999 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
15001 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
15003 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
15007 For types associated with a Debug_Pool, dynamic allocation is performed using
15009 GNAT allocation routine. References to all allocated chunks of memory
15010 are kept in an internal dictionary. The deallocation strategy consists
15011 in not releasing the memory to the underlying system but rather to fill
15012 it with a memory pattern easily recognizable during debugging sessions:
15013 The memory pattern is the old IBM hexadecimal convention: 16#DEADBEEF#.
15014 Upon each dereference, a check is made that the access value denotes a properly
15015 allocated memory location. Here is a complete example of use of
15016 @code{Debug_Pools}, that includes typical instances of memory corruption:
15021 @b{with} Gnat.Io; @b{use} Gnat.Io;
15022 @b{with} Unchecked_Deallocation;
15023 @b{with} Unchecked_Conversion;
15024 @b{with} GNAT.Debug_Pools;
15025 @b{with} System.Storage_Elements;
15026 @b{with} Ada.Exceptions; @b{use} Ada.Exceptions;
15027 @b{procedure} Debug_Pool_Test @b{is}
15029 @b{type} T @b{is} @b{access} Integer;
15030 @b{type} U @b{is} @b{access} @b{all} T;
15032 P : GNAT.Debug_Pools.Debug_Pool;
15033 @b{for} T'Storage_Pool @b{use} P;
15035 @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (Integer, T);
15036 @b{function} UC @b{is} @b{new} Unchecked_Conversion (U, T);
15037 A, B : @b{aliased} T;
15039 @b{procedure} Info @b{is} @b{new} GNAT.Debug_Pools.Print_Info(Put_Line);
15043 A := @b{new} Integer;
15044 B := @b{new} Integer;
15049 Put_Line (Integer'Image(B.@b{all}));
15051 @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
15056 @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
15060 Put_Line (Integer'Image(B.@b{all}));
15062 @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
15067 @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
15070 @b{end} Debug_Pool_Test;
15073 The debug pool mechanism provides the following precise diagnostics on the
15074 execution of this erroneous program:
15077 Total allocated bytes : 0
15078 Total deallocated bytes : 0
15079 Current Water Mark: 0
15083 Total allocated bytes : 8
15084 Total deallocated bytes : 0
15085 Current Water Mark: 8
15088 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
15089 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
15090 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
15091 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
15093 Total allocated bytes : 8
15094 Total deallocated bytes : 4
15095 Current Water Mark: 4
15100 @node Creating Sample Bodies Using gnatstub
15101 @chapter Creating Sample Bodies Using @code{gnatstub}
15105 @code{gnatstub} creates body stubs, that is, empty but compilable bodies
15106 for library unit declarations.
15108 To create a body stub, @code{gnatstub} has to compile the library
15109 unit declaration. Therefore, bodies can be created only for legal
15110 library units. Moreover, if a library unit depends semantically upon
15111 units located outside the current directory, you have to provide
15112 the source search path when calling @code{gnatstub}, see the description
15113 of @code{gnatstub} switches below.
15116 * Running gnatstub::
15117 * Switches for gnatstub::
15120 @node Running gnatstub
15121 @section Running @code{gnatstub}
15124 @code{gnatstub} has the command-line interface of the form
15127 $ gnatstub [switches] filename [directory]
15134 is the name of the source file that contains a library unit declaration
15135 for which a body must be created. This name should follow the GNAT file name
15136 conventions. No crunching is allowed for this file name. The file
15137 name may contain the path information.
15140 indicates the directory to place a body stub (default is the
15144 is an optional sequence of switches as described in the next section
15147 @node Switches for gnatstub
15148 @section Switches for @code{gnatstub}
15153 If the destination directory already contains a file with a name of the body file
15154 for the argument spec file, replace it with the generated body stub.
15157 Put the comment header (i.e. all the comments preceding the
15158 compilation unit) from the source of the library unit declaration
15159 into the body stub.
15162 Put a sample comment header into the body stub.
15166 These switches have the same meaning as in calls to gcc.
15167 They define the source search path in the call to gcc issued
15168 by @code{gnatstub} to compile an argument source file.
15171 (@var{n} is a decimal natural number). Set the indentation level in the
15172 generated body sample to n, '-i0' means "no indentation",
15173 the default indentation is 3.
15176 Do not remove the tree file (i.e. the snapshot of the compiler internal
15177 structures used by @code{gnatstub}) after creating the body stub.
15180 (@var{n} is a decimal positive number) Set the maximum line length in the
15181 body stub to n, the default is 78.
15184 Quiet mode: do not generate a confirmation when a body is
15185 successfully created or a message when a body is not required for an
15189 Reuse the tree file (if it exists) instead of creating it: instead of
15190 creating the tree file for the library unit declaration, gnatstub
15191 tries to find it in the current directory and use it for creating
15192 a body. If the tree file is not found, no body is created. @code{-r}
15193 also implies @code{-k}, whether or not
15194 @code{-k} is set explicitly.
15197 Overwrite the existing tree file: if the current directory already
15198 contains the file which, according to the GNAT file name rules should
15199 be considered as a tree file for the argument source file, gnatstub
15200 will refuse to create the tree file needed to create a body sampler,
15201 unless @code{-t} option is set
15204 Verbose mode: generate version information.
15208 @node Reducing the Size of Ada Executables with gnatelim
15209 @chapter Reducing the Size of Ada Executables with @code{gnatelim}
15214 * Eliminate Pragma::
15216 * Preparing Tree and Bind Files for gnatelim::
15217 * Running gnatelim::
15218 * Correcting the List of Eliminate Pragmas::
15219 * Making Your Executables Smaller::
15220 * Summary of the gnatelim Usage Cycle::
15223 @node About gnatelim
15224 @section About @code{gnatelim}
15227 When a program shares a set of Ada
15228 packages with other programs, it may happen that this program uses
15229 only a fraction of the subprograms defined in these packages. The code
15230 created for these unused subprograms increases the size of the executable.
15232 @code{gnatelim} tracks unused subprograms in an Ada program and
15233 outputs a list of GNAT-specific @code{Eliminate} pragmas (see next
15234 section) marking all the subprograms that are declared but never called.
15235 By placing the list of @code{Eliminate} pragmas in the GNAT configuration
15236 file @file{gnat.adc} and recompiling your program, you may decrease the
15237 size of its executable, because the compiler will not generate the code
15238 for 'eliminated' subprograms.
15240 @code{gnatelim} needs as its input data a set of tree files
15241 (see @ref{Tree Files}) representing all the components of a program to
15242 process and a bind file for a main subprogram (see
15243 @ref{Preparing Tree and Bind Files for gnatelim}).
15245 @node Eliminate Pragma
15246 @section @code{Eliminate} Pragma
15250 The simplified syntax of the Eliminate pragma used by @code{gnatelim} is:
15254 @b{pragma} Eliminate (Library_Unit_Name, Subprogram_Name);
15261 @item Library_Unit_Name
15262 full expanded Ada name of a library unit
15264 @item Subprogram_Name
15265 a simple or expanded name of a subprogram declared within this
15271 The effect of an @code{Eliminate} pragma placed in the GNAT configuration
15272 file @file{gnat.adc} is:
15277 If the subprogram @code{Subprogram_Name} is declared within
15278 the library unit @code{Library_Unit_Name}, the compiler will not generate
15279 code for this subprogram. This applies to all overloaded subprograms denoted
15280 by @code{Subprogram_Name}.
15283 If a subprogram marked by the pragma @code{Eliminate} is used (called)
15284 in a program, the compiler will produce an error message in the place where
15289 @section Tree Files
15293 A tree file stores a snapshot of the compiler internal data
15294 structures at the very end of a successful compilation. It contains all the
15295 syntactic and semantic information for the compiled unit and all the
15296 units upon which it depends semantically.
15297 To use tools that make use of tree files, you
15298 need to first produce the right set of tree files.
15300 GNAT produces correct tree files when -gnatt -gnatc options are set
15301 in a gcc call. The tree files have an .adt extension.
15302 Therefore, to produce a tree file for the compilation unit contained in a file
15303 named @file{foo.adb}, you must use the command
15306 $ gcc -c -gnatc -gnatt foo.adb
15310 and you will get the tree file @file{foo.adt}.
15313 @node Preparing Tree and Bind Files for gnatelim
15314 @section Preparing Tree and Bind Files for @code{gnatelim}
15317 A set of tree files covering the program to be analyzed with
15318 @code{gnatelim} and
15319 the bind file for the main subprogram does not have to
15320 be in the current directory.
15321 '-T' gnatelim option may be used to provide
15322 the search path for tree files, and '-b'
15323 option may be used to point to the bind
15324 file to process (see @ref{Running gnatelim})
15326 If you do not have the appropriate set of tree
15327 files and the right bind file, you
15328 may create them in the current directory using the following procedure.
15330 Let @code{Main_Prog} be the name of a main subprogram, and suppose
15331 this subprogram is in a file named @file{main_prog.adb}.
15333 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
15334 the main subprogram. @code{gnatelim} can work with both Ada and C
15335 bind files; when both are present, it uses the Ada bind file.
15336 The following commands will build the program and create the bind file:
15339 $ gnatmake -c Main_Prog
15340 $ gnatbind main_prog
15344 To create a minimal set of tree files covering the whole program, call
15345 @code{gnatmake} for this program as follows:
15348 $ gnatmake -f -c -gnatc -gnatt Main_Prog
15352 The @code{-c} gnatmake option turns off the bind and link
15353 steps, that are useless anyway because the sources are compiled with
15354 @option{-gnatc} option which turns off code generation.
15356 The @code{-f} gnatmake option forces
15357 recompilation of all the needed sources.
15359 This sequence of actions will create all the data needed by @code{gnatelim}
15360 from scratch and therefore guarantee its consistency. If you would like to
15361 use some existing set of files as @code{gnatelim} output, you must make
15362 sure that the set of files is complete and consistent. You can use the
15363 @code{-m} switch to check if there are missed tree files
15365 Note, that @code{gnatelim} needs neither object nor ALI files.
15367 @node Running gnatelim
15368 @section Running @code{gnatelim}
15371 @code{gnatelim} has the following command-line interface:
15374 $ gnatelim [options] name
15378 @code{name} should be a full expanded Ada name of a main subprogram
15379 of a program (partition).
15381 @code{gnatelim} options:
15385 Quiet mode: by default @code{gnatelim} generates to the standard error
15386 stream a trace of the source file names of the compilation units being
15387 processed. This option turns this trace off.
15390 Verbose mode: @code{gnatelim} version information is printed as Ada
15391 comments to the standard output stream.
15394 Also look for subprograms from the GNAT run time that can be eliminated.
15397 Check if any tree files are missing for an accurate result.
15400 When looking for tree files also look in directory @var{dir}
15402 @item -b@var{bind_file}
15403 Specifies @var{bind_file} as the bind file to process. If not set, the name
15404 of the bind file is computed from the full expanded Ada name of a main subprogram.
15407 Activate internal debugging switches. @var{x} is a letter or digit, or
15408 string of letters or digits, which specifies the type of debugging
15409 mode desired. Normally these are used only for internal development
15410 or system debugging purposes. You can find full documentation for these
15411 switches in the body of the @code{Gnatelim.Options} unit in the compiler
15412 source file @file{gnatelim-options.adb}.
15416 @code{gnatelim} sends its output to the standard output stream, and all the
15417 tracing and debug information is sent to the standard error stream.
15418 In order to produce a proper GNAT configuration file
15419 @file{gnat.adc}, redirection must be used:
15422 $ gnatelim Main_Prog > gnat.adc
15429 $ gnatelim Main_Prog >> gnat.adc
15433 In order to append the @code{gnatelim} output to the existing contents of
15436 @node Correcting the List of Eliminate Pragmas
15437 @section Correcting the List of Eliminate Pragmas
15440 In some rare cases it may happen that @code{gnatelim} will try to eliminate
15441 subprograms which are actually called in the program. In this case, the
15442 compiler will generate an error message of the form:
15445 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
15449 You will need to manually remove the wrong @code{Eliminate} pragmas from
15450 the @file{gnat.adc} file. It is advised that you recompile your program
15451 from scratch after that because you need a consistent @file{gnat.adc} file
15452 during the entire compilation.
15454 @node Making Your Executables Smaller
15455 @section Making Your Executables Smaller
15458 In order to get a smaller executable for your program you now have to
15459 recompile the program completely with the new @file{gnat.adc} file
15460 created by @code{gnatelim} in your current directory:
15463 $ gnatmake -f Main_Prog
15467 (you will need @code{-f} option for gnatmake to
15468 recompile everything
15469 with the set of pragmas @code{Eliminate} you have obtained with
15472 Be aware that the set of @code{Eliminate} pragmas is specific to each
15473 program. It is not recommended to merge sets of @code{Eliminate}
15474 pragmas created for different programs in one @file{gnat.adc} file.
15476 @node Summary of the gnatelim Usage Cycle
15477 @section Summary of the gnatelim Usage Cycle
15480 Here is a quick summary of the steps to be taken in order to reduce
15481 the size of your executables with @code{gnatelim}. You may use
15482 other GNAT options to control the optimization level,
15483 to produce the debugging information, to set search path, etc.
15487 Produce a bind file and a set of tree files
15490 $ gnatmake -c Main_Prog
15491 $ gnatbind main_prog
15492 $ gnatmake -f -c -gnatc -gnatt Main_Prog
15496 Generate a list of @code{Eliminate} pragmas
15498 $ gnatelim Main_Prog >[>] gnat.adc
15502 Recompile the application
15505 $ gnatmake -f Main_Prog
15510 @node Other Utility Programs
15511 @chapter Other Utility Programs
15514 This chapter discusses some other utility programs available in the Ada
15518 * Using Other Utility Programs with GNAT::
15519 * The gnatpsta Utility Program::
15520 * The External Symbol Naming Scheme of GNAT::
15521 * Ada Mode for Glide::
15522 * Converting Ada Files to html with gnathtml::
15523 * Installing gnathtml::
15526 @node Using Other Utility Programs with GNAT
15527 @section Using Other Utility Programs with GNAT
15530 The object files generated by GNAT are in standard system format and in
15531 particular the debugging information uses this format. This means
15532 programs generated by GNAT can be used with existing utilities that
15533 depend on these formats.
15535 In general, any utility program that works with C will also often work with
15536 Ada programs generated by GNAT. This includes software utilities such as
15537 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
15540 @node The gnatpsta Utility Program
15541 @section The @code{gnatpsta} Utility Program
15544 Many of the definitions in package Standard are implementation-dependent.
15545 However, the source of this package does not exist as an Ada source
15546 file, so these values cannot be determined by inspecting the source.
15547 They can be determined by examining in detail the coding of
15548 @file{cstand.adb} which creates the image of Standard in the compiler,
15549 but this is awkward and requires a great deal of internal knowledge
15552 The @code{gnatpsta} utility is designed to deal with this situation.
15553 It is an Ada program that dynamically determines the
15554 values of all the relevant parameters in Standard, and prints them
15555 out in the form of an Ada source listing for Standard, displaying all
15556 the values of interest. This output is generated to
15559 To determine the value of any parameter in package Standard, simply
15560 run @code{gnatpsta} with no qualifiers or arguments, and examine
15561 the output. This is preferable to consulting documentation, because
15562 you know that the values you are getting are the actual ones provided
15563 by the executing system.
15565 @node The External Symbol Naming Scheme of GNAT
15566 @section The External Symbol Naming Scheme of GNAT
15569 In order to interpret the output from GNAT, when using tools that are
15570 originally intended for use with other languages, it is useful to
15571 understand the conventions used to generate link names from the Ada
15574 All link names are in all lowercase letters. With the exception of library
15575 procedure names, the mechanism used is simply to use the full expanded
15576 Ada name with dots replaced by double underscores. For example, suppose
15577 we have the following package spec:
15582 @b{package} QRS @b{is}
15590 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
15591 the corresponding link name is @code{qrs__mn}.
15593 Of course if a @code{pragma Export} is used this may be overridden:
15598 @b{package} Exports @b{is}
15600 @b{pragma} Export (Var1, C, External_Name => "var1_name");
15602 @b{pragma} Export (Var2, C, Link_Name => "var2_link_name");
15609 In this case, the link name for @var{Var1} is whatever link name the
15610 C compiler would assign for the C function @var{var1_name}. This typically
15611 would be either @var{var1_name} or @var{_var1_name}, depending on operating
15612 system conventions, but other possibilities exist. The link name for
15613 @var{Var2} is @var{var2_link_name}, and this is not operating system
15617 One exception occurs for library level procedures. A potential ambiguity
15618 arises between the required name @code{_main} for the C main program,
15619 and the name we would otherwise assign to an Ada library level procedure
15620 called @code{Main} (which might well not be the main program).
15622 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
15623 names. So if we have a library level procedure such as
15628 @b{procedure} Hello (S : String);
15634 the external name of this procedure will be @var{_ada_hello}.
15636 @node Ada Mode for Glide
15637 @section Ada Mode for @code{Glide}
15640 The Glide mode for programming in Ada (both, Ada83 and Ada95) helps the
15641 user in understanding existing code and facilitates writing new code. It
15642 furthermore provides some utility functions for easier integration of
15643 standard Emacs features when programming in Ada.
15645 @subsection General Features:
15649 Full Integrated Development Environment :
15653 support of 'project files' for the configuration (directories,
15654 compilation options,...)
15657 compiling and stepping through error messages.
15660 running and debugging your applications within Glide.
15664 easy to use for beginners by pull-down menus,
15667 user configurable by many user-option variables.
15670 @subsection Ada Mode Features That Help Understanding Code:
15674 functions for easy and quick stepping through Ada code,
15677 getting cross reference information for identifiers (e.g. find the
15678 defining place by a keystroke),
15681 displaying an index menu of types and subprograms and move point to
15685 automatic color highlighting of the various entities in Ada code.
15688 @subsection Glide Support for Writing Ada Code:
15692 switching between spec and body files with possible
15693 autogeneration of body files,
15696 automatic formating of subprograms parameter lists.
15699 automatic smart indentation according to Ada syntax,
15702 automatic completion of identifiers,
15705 automatic casing of identifiers, keywords, and attributes,
15708 insertion of statement templates,
15711 filling comment paragraphs like filling normal text,
15714 For more information, please refer to the online Glide documentation
15715 available in the Glide --> Help Menu.
15717 @node Converting Ada Files to html with gnathtml
15718 @section Converting Ada Files to html with @code{gnathtml}
15721 This @code{Perl} script allows Ada source files to be browsed using
15722 standard Web browsers. For installation procedure, see the section
15723 @xref{Installing gnathtml}.
15725 Ada reserved keywords are highlighted in a bold font and Ada comments in
15726 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
15727 switch to suppress the generation of cross-referencing information, user
15728 defined variables and types will appear in a different color; you will
15729 be able to click on any identifier and go to its declaration.
15731 The command line is as follow:
15733 $ perl gnathtml.pl [switches] ada-files
15736 You can pass it as many Ada files as you want. @code{gnathtml} will generate
15737 an html file for every ada file, and a global file called @file{index.htm}.
15738 This file is an index of every identifier defined in the files.
15740 The available switches are the following ones :
15744 @cindex @code{-83} (@code{gnathtml})
15745 Only the subset on the Ada 83 keywords will be highlighted, not the full
15746 Ada 95 keywords set.
15748 @item -cc @var{color}
15749 This option allows you to change the color used for comments. The default
15750 value is green. The color argument can be any name accepted by html.
15753 @cindex @code{-d} (@code{gnathtml})
15754 If the ada files depend on some other files (using for instance the
15755 @code{with} command, the latter will also be converted to html.
15756 Only the files in the user project will be converted to html, not the files
15757 in the run-time library itself.
15760 This command is the same as -d above, but @code{gnathtml} will also look
15761 for files in the run-time library, and generate html files for them.
15764 @cindex @code{-f} (@code{gnathtml})
15765 By default, gnathtml will generate html links only for global entities
15766 ('with'ed units, global variables and types,...). If you specify the
15767 @code{-f} on the command line, then links will be generated for local
15770 @item -l @var{number}
15771 @cindex @code{-l} (@code{gnathtml})
15772 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
15773 will number the html files every @var{number} line.
15776 @cindex @code{-I} (@code{gnathtml})
15777 Specify a directory to search for library files (@file{.ali} files) and
15778 source files. You can provide several -I switches on the command line,
15779 and the directories will be parsed in the order of the command line.
15782 @cindex @code{-o} (@code{gnathtml})
15783 Specify the output directory for html files. By default, gnathtml will
15784 saved the generated html files in a subdirectory named @file{html/}.
15786 @item -p @var{file}
15787 @cindex @code{-p} (@code{gnathtml})
15788 If you are using Emacs and the most recent Emacs Ada mode, which provides
15789 a full Integrated Development Environment for compiling, checking,
15790 running and debugging applications, you may be using @file{.adp} files
15791 to give the directories where Emacs can find sources and object files.
15793 Using this switch, you can tell gnathtml to use these files. This allows
15794 you to get an html version of your application, even if it is spread
15795 over multiple directories.
15797 @item -sc @var{color}
15798 @cindex @code{-sc} (@code{gnathtml})
15799 This option allows you to change the color used for symbol definitions.
15800 The default value is red. The color argument can be any name accepted by html.
15802 @item -t @var{file}
15803 @cindex @code{-t} (@code{gnathtml})
15804 This switch provides the name of a file. This file contains a list of
15805 file names to be converted, and the effect is exactly as though they had
15806 appeared explicitly on the command line. This
15807 is the recommended way to work around the command line length limit on some
15812 @node Installing gnathtml
15813 @section Installing @code{gnathtml}
15816 @code{Perl} needs to be installed on your machine to run this script.
15817 @code{Perl} is freely available for almost every architecture and
15818 Operating System via the Internet.
15820 On Unix systems, you may want to modify the first line of the script
15821 @code{gnathtml}, to explicitly tell the Operating system where Perl
15822 is. The syntax of this line is :
15824 #!full_path_name_to_perl
15828 Alternatively, you may run the script using the following command line:
15831 $ perl gnathtml.pl [switches] files
15835 @node Running and Debugging Ada Programs
15836 @chapter Running and Debugging Ada Programs
15840 This chapter discusses how to debug Ada programs. An incorrect Ada program
15841 may be handled in three ways by the GNAT compiler:
15845 The illegality may be a violation of the static semantics of Ada. In
15846 that case GNAT diagnoses the constructs in the program that are illegal.
15847 It is then a straightforward matter for the user to modify those parts of
15851 The illegality may be a violation of the dynamic semantics of Ada. In
15852 that case the program compiles and executes, but may generate incorrect
15853 results, or may terminate abnormally with some exception.
15856 When presented with a program that contains convoluted errors, GNAT
15857 itself may terminate abnormally without providing full diagnostics on
15858 the incorrect user program.
15862 * The GNAT Debugger GDB::
15864 * Introduction to GDB Commands::
15865 * Using Ada Expressions::
15866 * Calling User-Defined Subprograms::
15867 * Using the Next Command in a Function::
15870 * Debugging Generic Units::
15871 * GNAT Abnormal Termination or Failure to Terminate::
15872 * Naming Conventions for GNAT Source Files::
15873 * Getting Internal Debugging Information::
15874 * Stack Traceback::
15880 @node The GNAT Debugger GDB
15881 @section The GNAT Debugger GDB
15884 @code{GDB} is a general purpose, platform-independent debugger that
15885 can be used to debug mixed-language programs compiled with @code{GCC},
15886 and in particular is capable of debugging Ada programs compiled with
15887 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
15888 complex Ada data structures.
15890 The manual @cite{Debugging with GDB}
15891 contains full details on the usage of @code{GDB}, including a section on
15892 its usage on programs. This manual should be consulted for full
15893 details. The section that follows is a brief introduction to the
15894 philosophy and use of @code{GDB}.
15896 When GNAT programs are compiled, the compiler optionally writes debugging
15897 information into the generated object file, including information on
15898 line numbers, and on declared types and variables. This information is
15899 separate from the generated code. It makes the object files considerably
15900 larger, but it does not add to the size of the actual executable that
15901 will be loaded into memory, and has no impact on run-time performance. The
15902 generation of debug information is triggered by the use of the
15903 -g switch in the gcc or gnatmake command used to carry out
15904 the compilations. It is important to emphasize that the use of these
15905 options does not change the generated code.
15907 The debugging information is written in standard system formats that
15908 are used by many tools, including debuggers and profilers. The format
15909 of the information is typically designed to describe C types and
15910 semantics, but GNAT implements a translation scheme which allows full
15911 details about Ada types and variables to be encoded into these
15912 standard C formats. Details of this encoding scheme may be found in
15913 the file exp_dbug.ads in the GNAT source distribution. However, the
15914 details of this encoding are, in general, of no interest to a user,
15915 since @code{GDB} automatically performs the necessary decoding.
15917 When a program is bound and linked, the debugging information is
15918 collected from the object files, and stored in the executable image of
15919 the program. Again, this process significantly increases the size of
15920 the generated executable file, but it does not increase the size of
15921 the executable program itself. Furthermore, if this program is run in
15922 the normal manner, it runs exactly as if the debug information were
15923 not present, and takes no more actual memory.
15925 However, if the program is run under control of @code{GDB}, the
15926 debugger is activated. The image of the program is loaded, at which
15927 point it is ready to run. If a run command is given, then the program
15928 will run exactly as it would have if @code{GDB} were not present. This
15929 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
15930 entirely non-intrusive until a breakpoint is encountered. If no
15931 breakpoint is ever hit, the program will run exactly as it would if no
15932 debugger were present. When a breakpoint is hit, @code{GDB} accesses
15933 the debugging information and can respond to user commands to inspect
15934 variables, and more generally to report on the state of execution.
15937 @section Running GDB
15940 The debugger can be launched directly and simply from @code{glide} or
15941 through its graphical interface: @code{gvd}. It can also be used
15942 directly in text mode. Here is described the basic use of @code{GDB}
15943 in text mode. All the commands described below can be used in the
15944 @code{gvd} console window eventhough there is usually other more
15945 graphical ways to achieve the same goals.
15948 The command to run de graphical interface of the debugger is
15954 The command to run @code{GDB} in text mode is
15961 where @code{program} is the name of the executable file. This
15962 activates the debugger and results in a prompt for debugger commands.
15963 The simplest command is simply @code{run}, which causes the program to run
15964 exactly as if the debugger were not present. The following section
15965 describes some of the additional commands that can be given to @code{GDB}.
15968 @node Introduction to GDB Commands
15969 @section Introduction to GDB Commands
15972 @code{GDB} contains a large repertoire of commands. The manual
15973 @cite{Debugging with GDB}
15974 includes extensive documentation on the use
15975 of these commands, together with examples of their use. Furthermore,
15976 the command @var{help} invoked from within @code{GDB} activates a simple help
15977 facility which summarizes the available commands and their options.
15978 In this section we summarize a few of the most commonly
15979 used commands to give an idea of what @code{GDB} is about. You should create
15980 a simple program with debugging information and experiment with the use of
15981 these @code{GDB} commands on the program as you read through the
15985 @item set args @var{arguments}
15986 The @var{arguments} list above is a list of arguments to be passed to
15987 the program on a subsequent run command, just as though the arguments
15988 had been entered on a normal invocation of the program. The @code{set args}
15989 command is not needed if the program does not require arguments.
15992 The @code{run} command causes execution of the program to start from
15993 the beginning. If the program is already running, that is to say if
15994 you are currently positioned at a breakpoint, then a prompt will ask
15995 for confirmation that you want to abandon the current execution and
15998 @item breakpoint @var{location}
15999 The breakpoint command sets a breakpoint, that is to say a point at which
16000 execution will halt and @code{GDB} will await further
16001 commands. @var{location} is
16002 either a line number within a file, given in the format @code{file:linenumber},
16003 or it is the name of a subprogram. If you request that a breakpoint be set on
16004 a subprogram that is overloaded, a prompt will ask you to specify on which of
16005 those subprograms you want to breakpoint. You can also
16006 specify that all of them should be breakpointed. If the program is run
16007 and execution encounters the breakpoint, then the program
16008 stops and @code{GDB} signals that the breakpoint was encountered by
16009 printing the line of code before which the program is halted.
16011 @item breakpoint exception @var{name}
16012 A special form of the breakpoint command which breakpoints whenever
16013 exception @var{name} is raised.
16014 If @var{name} is omitted,
16015 then a breakpoint will occur when any exception is raised.
16017 @item print @var{expression}
16018 This will print the value of the given expression. Most simple
16019 Ada expression formats are properly handled by @code{GDB}, so the expression
16020 can contain function calls, variables, operators, and attribute references.
16023 Continues execution following a breakpoint, until the next breakpoint or the
16024 termination of the program.
16027 Executes a single line after a breakpoint. If the next statement is a subprogram
16028 call, execution continues into (the first statement of) the
16032 Executes a single line. If this line is a subprogram call, executes and
16033 returns from the call.
16036 Lists a few lines around the current source location. In practice, it
16037 is usually more convenient to have a separate edit window open with the
16038 relevant source file displayed. Successive applications of this command
16039 print subsequent lines. The command can be given an argument which is a
16040 line number, in which case it displays a few lines around the specified one.
16043 Displays a backtrace of the call chain. This command is typically
16044 used after a breakpoint has occurred, to examine the sequence of calls that
16045 leads to the current breakpoint. The display includes one line for each
16046 activation record (frame) corresponding to an active subprogram.
16049 At a breakpoint, @code{GDB} can display the values of variables local
16050 to the current frame. The command @code{up} can be used to
16051 examine the contents of other active frames, by moving the focus up
16052 the stack, that is to say from callee to caller, one frame at a time.
16055 Moves the focus of @code{GDB} down from the frame currently being
16056 examined to the frame of its callee (the reverse of the previous command),
16058 @item frame @var{n}
16059 Inspect the frame with the given number. The value 0 denotes the frame
16060 of the current breakpoint, that is to say the top of the call stack.
16064 The above list is a very short introduction to the commands that
16065 @code{GDB} provides. Important additional capabilities, including conditional
16066 breakpoints, the ability to execute command sequences on a breakpoint,
16067 the ability to debug at the machine instruction level and many other
16068 features are described in detail in @cite{Debugging with GDB}.
16069 Note that most commands can be abbreviated
16070 (for example, c for continue, bt for backtrace).
16072 @node Using Ada Expressions
16073 @section Using Ada Expressions
16074 @cindex Ada expressions
16077 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
16078 extensions. The philosophy behind the design of this subset is
16082 That @code{GDB} should provide basic literals and access to operations for
16083 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
16084 leaving more sophisticated computations to subprograms written into the
16085 program (which therefore may be called from @code{GDB}).
16088 That type safety and strict adherence to Ada language restrictions
16089 are not particularly important to the @code{GDB} user.
16092 That brevity is important to the @code{GDB} user.
16095 Thus, for brevity, the debugger acts as if there were
16096 implicit @code{with} and @code{use} clauses in effect for all user-written
16097 packages, thus making it unnecessary to fully qualify most names with
16098 their packages, regardless of context. Where this causes ambiguity,
16099 @code{GDB} asks the user's intent.
16101 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
16103 @node Calling User-Defined Subprograms
16104 @section Calling User-Defined Subprograms
16107 An important capability of @code{GDB} is the ability to call user-defined
16108 subprograms while debugging. This is achieved simply by entering
16109 a subprogram call statement in the form:
16112 call subprogram-name (parameters)
16116 The keyword @code{call} can be omitted in the normal case where the
16117 @code{subprogram-name} does not coincide with any of the predefined
16118 @code{GDB} commands.
16120 The effect is to invoke the given subprogram, passing it the
16121 list of parameters that is supplied. The parameters can be expressions and
16122 can include variables from the program being debugged. The
16123 subprogram must be defined
16124 at the library level within your program, and @code{GDB} will call the
16125 subprogram within the environment of your program execution (which
16126 means that the subprogram is free to access or even modify variables
16127 within your program).
16129 The most important use of this facility is in allowing the inclusion of
16130 debugging routines that are tailored to particular data structures
16131 in your program. Such debugging routines can be written to provide a suitably
16132 high-level description of an abstract type, rather than a low-level dump
16133 of its physical layout. After all, the standard
16134 @code{GDB print} command only knows the physical layout of your
16135 types, not their abstract meaning. Debugging routines can provide information
16136 at the desired semantic level and are thus enormously useful.
16138 For example, when debugging GNAT itself, it is crucial to have access to
16139 the contents of the tree nodes used to represent the program internally.
16140 But tree nodes are represented simply by an integer value (which in turn
16141 is an index into a table of nodes).
16142 Using the @code{print} command on a tree node would simply print this integer
16143 value, which is not very useful. But the PN routine (defined in file
16144 treepr.adb in the GNAT sources) takes a tree node as input, and displays
16145 a useful high level representation of the tree node, which includes the
16146 syntactic category of the node, its position in the source, the integers
16147 that denote descendant nodes and parent node, as well as varied
16148 semantic information. To study this example in more detail, you might want to
16149 look at the body of the PN procedure in the stated file.
16151 @node Using the Next Command in a Function
16152 @section Using the Next Command in a Function
16155 When you use the @code{next} command in a function, the current source
16156 location will advance to the next statement as usual. A special case
16157 arises in the case of a @code{return} statement.
16159 Part of the code for a return statement is the "epilog" of the function.
16160 This is the code that returns to the caller. There is only one copy of
16161 this epilog code, and it is typically associated with the last return
16162 statement in the function if there is more than one return. In some
16163 implementations, this epilog is associated with the first statement
16166 The result is that if you use the @code{next} command from a return
16167 statement that is not the last return statement of the function you
16168 may see a strange apparent jump to the last return statement or to
16169 the start of the function. You should simply ignore this odd jump.
16170 The value returned is always that from the first return statement
16171 that was stepped through.
16173 @node Ada Exceptions
16174 @section Breaking on Ada Exceptions
16178 You can set breakpoints that trip when your program raises
16179 selected exceptions.
16182 @item break exception
16183 Set a breakpoint that trips whenever (any task in the) program raises
16186 @item break exception @var{name}
16187 Set a breakpoint that trips whenever (any task in the) program raises
16188 the exception @var{name}.
16190 @item break exception unhandled
16191 Set a breakpoint that trips whenever (any task in the) program raises an
16192 exception for which there is no handler.
16194 @item info exceptions
16195 @itemx info exceptions @var{regexp}
16196 The @code{info exceptions} command permits the user to examine all defined
16197 exceptions within Ada programs. With a regular expression, @var{regexp}, as
16198 argument, prints out only those exceptions whose name matches @var{regexp}.
16206 @code{GDB} allows the following task-related commands:
16210 This command shows a list of current Ada tasks, as in the following example:
16217 ID TID P-ID Thread Pri State Name
16218 1 8088000 0 807e000 15 Child Activation Wait main_task
16219 2 80a4000 1 80ae000 15 Accept/Select Wait b
16220 3 809a800 1 80a4800 15 Child Activation Wait a
16221 * 4 80ae800 3 80b8000 15 Running c
16225 In this listing, the asterisk before the first task indicates it to be the
16226 currently running task. The first column lists the task ID that is used
16227 to refer to tasks in the following commands.
16229 @item break @var{linespec} task @var{taskid}
16230 @itemx break @var{linespec} task @var{taskid} if @dots{}
16231 @cindex Breakpoints and tasks
16232 These commands are like the @code{break @dots{} thread @dots{}}.
16233 @var{linespec} specifies source lines.
16235 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
16236 to specify that you only want @code{GDB} to stop the program when a
16237 particular Ada task reaches this breakpoint. @var{taskid} is one of the
16238 numeric task identifiers assigned by @code{GDB}, shown in the first
16239 column of the @samp{info tasks} display.
16241 If you do not specify @samp{task @var{taskid}} when you set a
16242 breakpoint, the breakpoint applies to @emph{all} tasks of your
16245 You can use the @code{task} qualifier on conditional breakpoints as
16246 well; in this case, place @samp{task @var{taskid}} before the
16247 breakpoint condition (before the @code{if}).
16249 @item task @var{taskno}
16250 @cindex Task switching
16252 This command allows to switch to the task referred by @var{taskno}. In
16253 particular, This allows to browse the backtrace of the specified
16254 task. It is advised to switch back to the original task before
16255 continuing execution otherwise the scheduling of the program may be
16260 For more detailed information on the tasking support, see @cite{Debugging with GDB}.
16262 @node Debugging Generic Units
16263 @section Debugging Generic Units
16264 @cindex Debugging Generic Units
16268 GNAT always uses code expansion for generic instantiation. This means that
16269 each time an instantiation occurs, a complete copy of the original code is
16270 made, with appropriate substitutions of formals by actuals.
16272 It is not possible to refer to the original generic entities in
16273 @code{GDB}, but it is always possible to debug a particular instance of
16274 a generic, by using the appropriate expanded names. For example, if we have
16279 @b{procedure} g @b{is}
16281 @b{generic package} k @b{is}
16282 @b{procedure} kp (v1 : @b{in out} integer);
16285 @b{package body} k @b{is}
16286 @b{procedure} kp (v1 : @b{in out} integer) @b{is}
16292 @b{package} k1 @b{is new} k;
16293 @b{package} k2 @b{is new} k;
16295 var : integer := 1;
16308 Then to break on a call to procedure kp in the k2 instance, simply
16312 (gdb) break g.k2.kp
16316 When the breakpoint occurs, you can step through the code of the
16317 instance in the normal manner and examine the values of local variables, as for
16320 @node GNAT Abnormal Termination or Failure to Terminate
16321 @section GNAT Abnormal Termination or Failure to Terminate
16322 @cindex GNAT Abnormal Termination or Failure to Terminate
16325 When presented with programs that contain serious errors in syntax
16327 GNAT may on rare occasions experience problems in operation, such
16329 segmentation fault or illegal memory access, raising an internal
16330 exception, terminating abnormally, or failing to terminate at all.
16331 In such cases, you can activate
16332 various features of GNAT that can help you pinpoint the construct in your
16333 program that is the likely source of the problem.
16335 The following strategies are presented in increasing order of
16336 difficulty, corresponding to your experience in using GNAT and your
16337 familiarity with compiler internals.
16341 Run @code{gcc} with the @option{-gnatf}. This first
16342 switch causes all errors on a given line to be reported. In its absence,
16343 only the first error on a line is displayed.
16345 The @option{-gnatdO} switch causes errors to be displayed as soon as they
16346 are encountered, rather than after compilation is terminated. If GNAT
16347 terminates prematurely or goes into an infinite loop, the last error
16348 message displayed may help to pinpoint the culprit.
16351 Run @code{gcc} with the @code{-v (verbose)} switch. In this mode,
16352 @code{gcc} produces ongoing information about the progress of the
16353 compilation and provides the name of each procedure as code is
16354 generated. This switch allows you to find which Ada procedure was being
16355 compiled when it encountered a code generation problem.
16358 @cindex @option{-gnatdc} switch
16359 Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
16360 switch that does for the front-end what @code{-v} does for the back end.
16361 The system prints the name of each unit, either a compilation unit or
16362 nested unit, as it is being analyzed.
16364 Finally, you can start
16365 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
16366 front-end of GNAT, and can be run independently (normally it is just
16367 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
16368 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
16369 @code{where} command is the first line of attack; the variable
16370 @code{lineno} (seen by @code{print lineno}), used by the second phase of
16371 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
16372 which the execution stopped, and @code{input_file name} indicates the name of
16376 @node Naming Conventions for GNAT Source Files
16377 @section Naming Conventions for GNAT Source Files
16380 In order to examine the workings of the GNAT system, the following
16381 brief description of its organization may be helpful:
16385 Files with prefix @file{sc} contain the lexical scanner.
16388 All files prefixed with @file{par} are components of the parser. The
16389 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
16390 parsing of select statements can be found in @file{par-ch9.adb}.
16393 All files prefixed with @file{sem} perform semantic analysis. The
16394 numbers correspond to chapters of the Ada standard. For example, all
16395 issues involving context clauses can be found in @file{sem_ch10.adb}. In
16396 addition, some features of the language require sufficient special processing
16397 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
16398 dynamic dispatching, etc.
16401 All files prefixed with @file{exp} perform normalization and
16402 expansion of the intermediate representation (abstract syntax tree, or AST).
16403 these files use the same numbering scheme as the parser and semantics files.
16404 For example, the construction of record initialization procedures is done in
16405 @file{exp_ch3.adb}.
16408 The files prefixed with @file{bind} implement the binder, which
16409 verifies the consistency of the compilation, determines an order of
16410 elaboration, and generates the bind file.
16413 The files @file{atree.ads} and @file{atree.adb} detail the low-level
16414 data structures used by the front-end.
16417 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
16418 the abstract syntax tree as produced by the parser.
16421 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
16422 all entities, computed during semantic analysis.
16425 Library management issues are dealt with in files with prefix
16431 Ada files with the prefix @file{a-} are children of @code{Ada}, as
16432 defined in Annex A.
16437 Files with prefix @file{i-} are children of @code{Interfaces}, as
16438 defined in Annex B.
16442 Files with prefix @file{s-} are children of @code{System}. This includes
16443 both language-defined children and GNAT run-time routines.
16447 Files with prefix @file{g-} are children of @code{GNAT}. These are useful
16448 general-purpose packages, fully documented in their specifications. All
16449 the other @file{.c} files are modifications of common @code{gcc} files.
16452 @node Getting Internal Debugging Information
16453 @section Getting Internal Debugging Information
16456 Most compilers have internal debugging switches and modes. GNAT
16457 does also, except GNAT internal debugging switches and modes are not
16458 secret. A summary and full description of all the compiler and binder
16459 debug flags are in the file @file{debug.adb}. You must obtain the
16460 sources of the compiler to see the full detailed effects of these flags.
16462 The switches that print the source of the program (reconstructed from
16463 the internal tree) are of general interest for user programs, as are the
16465 the full internal tree, and the entity table (the symbol table
16466 information). The reconstructed source provides a readable version of the
16467 program after the front-end has completed analysis and expansion, and is useful
16468 when studying the performance of specific constructs. For example, constraint
16469 checks are indicated, complex aggregates are replaced with loops and
16470 assignments, and tasking primitives are replaced with run-time calls.
16472 @node Stack Traceback
16473 @section Stack Traceback
16475 @cindex stack traceback
16476 @cindex stack unwinding
16479 Traceback is a mechanism to display the sequence of subprogram calls that
16480 leads to a specified execution point in a program. Often (but not always)
16481 the execution point is an instruction at which an exception has been raised.
16482 This mechanism is also known as @i{stack unwinding} because it obtains
16483 its information by scanning the run-time stack and recovering the activation
16484 records of all active subprograms. Stack unwinding is one of the most
16485 important tools for program debugging.
16488 The first entry stored in traceback corresponds to the deepest calling level,
16489 that is to say the subprogram currently executing the instruction
16490 from which we want to obtain the traceback.
16493 Note that there is no runtime performance penalty when stack traceback
16494 is enabled and no exception are raised during program execution.
16497 * Non-Symbolic Traceback::
16498 * Symbolic Traceback::
16501 @node Non-Symbolic Traceback
16502 @subsection Non-Symbolic Traceback
16503 @cindex traceback, non-symbolic
16506 Note: this feature is not supported on all platforms. See
16507 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
16511 * Tracebacks From an Unhandled Exception::
16512 * Tracebacks From Exception Occurrences (non-symbolic)::
16513 * Tracebacks From Anywhere in a Program (non-symbolic)::
16516 @node Tracebacks From an Unhandled Exception
16517 @subsubsection Tracebacks From an Unhandled Exception
16520 A runtime non-symbolic traceback is a list of addresses of call instructions.
16521 To enable this feature you must use the @code{-E}
16522 @code{gnatbind}'s option. With this option a stack traceback is stored as part
16523 of exception information. It is possible to retrieve this information using the
16524 standard @code{Ada.Exception.Exception_Information} routine.
16527 Let's have a look at a simple example:
16536 raise Constraint_Error;
16552 $ gnatmake stb -bargs -E
16555 Execution terminated by unhandled exception
16556 Exception name: CONSTRAINT_ERROR
16558 Call stack traceback locations:
16559 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
16563 As we see the traceback lists a sequence of addresses for the unhandled
16564 exception @code{CONSTAINT_ERROR} raised in procedure P1. It is easy to
16565 guess that this exception come from procedure P1. To translate these
16566 addresses into the source lines where the calls appear, the
16567 @code{addr2line} tool, described below, is invaluable. The use of this tool
16568 requires the program to be compiled with debug information.
16571 $ gnatmake -g stb -bargs -E
16574 Execution terminated by unhandled exception
16575 Exception name: CONSTRAINT_ERROR
16577 Call stack traceback locations:
16578 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
16580 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
16581 0x4011f1 0x77e892a4
16583 00401373 at d:/stb/stb.adb:5
16584 0040138B at d:/stb/stb.adb:10
16585 0040139C at d:/stb/stb.adb:14
16586 00401335 at d:/stb/b~stb.adb:104
16587 004011C4 at /build/.../crt1.c:200
16588 004011F1 at /build/.../crt1.c:222
16589 77E892A4 in ?? at ??:0
16593 @code{addr2line} has a number of other useful options:
16597 to get the function name corresponding to any location
16599 @item --demangle=gnat
16600 to use the @b{gnat} decoding mode for the function names. Note that
16601 for binutils version 2.9.x the option is simply @code{--demangle}.
16605 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
16606 0x40139c 0x401335 0x4011c4 0x4011f1
16608 00401373 in stb.p1 at d:/stb/stb.adb:5
16609 0040138B in stb.p2 at d:/stb/stb.adb:10
16610 0040139C in stb at d:/stb/stb.adb:14
16611 00401335 in main at d:/stb/b~stb.adb:104
16612 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
16613 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
16617 From this traceback we can see that the exception was raised in
16618 @file{stb.adb} at line 5, which was reached from a procedure call in
16619 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
16620 which contains the call to the main program.
16621 @pxref{Running gnatbind}. The remaining entries are assorted runtime routines,
16622 and the output will vary from platform to platform.
16625 It is also possible to use @code{GDB} with these traceback addresses to debug
16626 the program. For example, we can break at a given code location, as reported
16627 in the stack traceback:
16632 (gdb) break *0x401373
16633 Breakpoint 1 at 0x401373: file stb.adb, line 5.
16637 It is important to note that the stack traceback addresses
16638 do not change when debug information is included. This is particularly useful
16639 because it makes it possible to release software without debug information (to
16640 minimize object size), get a field report that includes a stack traceback
16641 whenever an internal bug occurs, and then be able to retrieve the sequence
16642 of calls with the same program compiled with debug information.
16644 @node Tracebacks From Exception Occurrences (non-symbolic)
16645 @subsubsection Tracebacks From Exception Occurrences
16648 Non-symbolic tracebacks are obtained by using the @code{-E} binder argument.
16649 The stack traceback is attached to the exception information string, and can
16650 be retrieved in an exception handler within the Ada program, by means of the
16651 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
16657 with Ada.Exceptions;
16662 use Ada.Exceptions;
16670 Text_IO.Put_Line (Exception_Information (E));
16686 This program will output:
16691 Exception name: CONSTRAINT_ERROR
16692 Message: stb.adb:12
16693 Call stack traceback locations:
16694 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
16697 @node Tracebacks From Anywhere in a Program (non-symbolic)
16698 @subsubsection Tracebacks From Anywhere in a Program
16701 It is also possible to retrieve a stack traceback from anywhere in a
16702 program. For this you need to
16703 use the @code{GNAT.Traceback} API. This package includes a procedure called
16704 @code{Call_Chain} that computes a complete stack traceback, as well as useful
16705 display procedures described below. It is not necessary to use the
16706 @code{-E gnatbind} option in this case, because the stack traceback mechanism
16707 is invoked explicitly.
16710 In the following example we compute a traceback at a specific location in
16711 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
16712 convert addresses to strings:
16718 with GNAT.Traceback;
16719 with GNAT.Debug_Utilities;
16725 use GNAT.Traceback;
16728 TB : Tracebacks_Array (1 .. 10);
16729 -- We are asking for a maximum of 10 stack frames.
16731 -- Len will receive the actual number of stack frames returned.
16733 Call_Chain (TB, Len);
16735 Text_IO.Put ("In STB.P1 : ");
16737 for K in 1 .. Len loop
16738 Text_IO.Put (Debug_Utilities.Image (TB (K)));
16761 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
16762 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
16765 @node Symbolic Traceback
16766 @subsection Symbolic Traceback
16767 @cindex traceback, symbolic
16770 A symbolic traceback is a stack traceback in which procedure names are
16771 associated with each code location.
16774 Note that this feature is not supported on all platforms. See
16775 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
16776 list of currently supported platforms.
16779 Note that the symbolic traceback requires that the program be compiled
16780 with debug information. If it is not compiled with debug information
16781 only the non-symbolic information will be valid.
16784 * Tracebacks From Exception Occurrences (symbolic)::
16785 * Tracebacks From Anywhere in a Program (symbolic)::
16788 @node Tracebacks From Exception Occurrences (symbolic)
16789 @subsubsection Tracebacks From Exception Occurrences
16795 with GNAT.Traceback.Symbolic;
16801 raise Constraint_Error;
16818 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
16825 $ gnatmake -g stb -bargs -E -largs -lgnat -laddr2line -lintl
16828 0040149F in stb.p1 at stb.adb:8
16829 004014B7 in stb.p2 at stb.adb:13
16830 004014CF in stb.p3 at stb.adb:18
16831 004015DD in ada.stb at stb.adb:22
16832 00401461 in main at b~stb.adb:168
16833 004011C4 in __mingw_CRTStartup at crt1.c:200
16834 004011F1 in mainCRTStartup at crt1.c:222
16835 77E892A4 in ?? at ??:0
16839 The exact sequence of linker options may vary from platform to platform.
16840 The above @code{-largs} section is for Windows platforms. By contrast,
16841 under Unix there is no need for the @code{-largs} section.
16842 Differences across platforms are due to details of linker implementation.
16844 @node Tracebacks From Anywhere in a Program (symbolic)
16845 @subsubsection Tracebacks From Anywhere in a Program
16848 It is possible to get a symbolic stack traceback
16849 from anywhere in a program, just as for non-symbolic tracebacks.
16850 The first step is to obtain a non-symbolic
16851 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
16852 information. Here is an example:
16858 with GNAT.Traceback;
16859 with GNAT.Traceback.Symbolic;
16864 use GNAT.Traceback;
16865 use GNAT.Traceback.Symbolic;
16868 TB : Tracebacks_Array (1 .. 10);
16869 -- We are asking for a maximum of 10 stack frames.
16871 -- Len will receive the actual number of stack frames returned.
16873 Call_Chain (TB, Len);
16874 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
16890 @node Inline Assembler
16891 @chapter Inline Assembler
16894 If you need to write low-level software that interacts directly with the hardware, Ada provides two ways to incorporate assembly language code into your program. First, you can import and invoke external routines written in assembly language, an Ada feature fully supported by GNAT. However, for small sections of code it may be simpler or more efficient to include assembly language statements directly in your Ada source program, using the facilities of the implementation-defined package @code{System.Machine_Code}, which incorporates the gcc Inline Assembler. The Inline Assembler approach offers a number of advantages, including the following:
16897 @item No need to use non-Ada tools
16898 @item Consistent interface over different targets
16899 @item Automatic usage of the proper calling conventions
16900 @item Access to Ada constants and variables
16901 @item Definition of intrinsic routines
16902 @item Possibility of inlining a subprogram comprising assembler code
16903 @item Code optimizer can take Inline Assembler code into account
16906 This chapter presents a series of examples to show you how to use the Inline Assembler. Although it focuses on the Intel x86, the general approach applies also to other processors. It is assumed that you are familiar with Ada and with assembly language programming.
16909 * Basic Assembler Syntax::
16910 * A Simple Example of Inline Assembler::
16911 * Output Variables in Inline Assembler::
16912 * Input Variables in Inline Assembler::
16913 * Inlining Inline Assembler Code::
16914 * Other Asm Functionality::
16915 * A Complete Example::
16918 @c ---------------------------------------------------------------------------
16919 @node Basic Assembler Syntax
16920 @section Basic Assembler Syntax
16923 The assembler used by GNAT and gcc is based not on the Intel assembly language, but rather on a
16924 language that descends from the AT&T Unix assembler @emph{as} (and which is often
16925 referred to as ``AT&T syntax'').
16926 The following table summarizes the main features of @emph{as} syntax and points out the differences from the Intel conventions.
16927 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
16928 pre-processor) documentation for further information.
16931 @item Register names
16932 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
16934 Intel: No extra punctuation; for example @code{eax}
16936 @item Immediate operand
16937 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
16939 Intel: No extra punctuation; for example @code{4}
16942 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
16944 Intel: No extra punctuation; for example @code{loc}
16946 @item Memory contents
16947 gcc / @emph{as}: No extra punctuation; for example @code{loc}
16949 Intel: Square brackets; for example @code{[loc]}
16951 @item Register contents
16952 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
16954 Intel: Square brackets; for example @code{[eax]}
16956 @item Hexadecimal numbers
16957 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
16959 Intel: Trailing ``h''; for example @code{A0h}
16962 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move a 16-bit word
16964 Intel: Implicit, deduced by assembler; for example @code{mov}
16966 @item Instruction repetition
16967 gcc / @emph{as}: Split into two lines; for example
16973 Intel: Keep on one line; for example @code{rep stosl}
16975 @item Order of operands
16976 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
16978 Intel: Destination first; for example @code{mov eax, 4}
16981 @c ---------------------------------------------------------------------------
16982 @node A Simple Example of Inline Assembler
16983 @section A Simple Example of Inline Assembler
16986 The following example will generate a single assembly language statement, @code{nop}, which does nothing. Despite its lack of run-time effect, the example will be useful in illustrating the basics of the Inline Assembler facility.
16990 with System.Machine_Code; use System.Machine_Code;
16991 procedure Nothing is
16998 @code{Asm} is a procedure declared in package @code{System.Machine_Code}; here it takes one parameter, a @emph{template string} that must be a static expression and that will form the generated instruction.
16999 @code{Asm} may be regarded as a compile-time procedure that parses the template string and additional parameters (none here), from which it generates a sequence of assembly language instructions.
17001 The examples in this chapter will illustrate several of the forms for invoking @code{Asm}; a complete specification of the syntax is found in the @cite{GNAT Reference Manual}.
17003 Under the standard GNAT conventions, the @code{Nothing} procedure should be in a file named @file{nothing.adb}. You can build the executable in the usual way:
17007 However, the interesting aspect of this example is not its run-time behavior but rather the
17008 generated assembly code. To see this output, invoke the compiler as follows:
17010 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
17012 where the options are:
17016 compile only (no bind or link)
17018 generate assembler listing
17019 @item -fomit-frame-pointer
17020 do not set up separate stack frames
17022 do not add runtime checks
17025 This gives a human-readable assembler version of the code. The resulting
17026 file will have the same name as the Ada source file, but with a @code{.s} extension.
17027 In our example, the file @file{nothing.s} has the following contents:
17031 .file "nothing.adb"
17033 ___gnu_compiled_ada:
17036 .globl __ada_nothing
17048 The assembly code you included is clearly indicated by
17049 the compiler, between the @code{#APP} and @code{#NO_APP}
17050 delimiters. The character before the 'APP' and 'NOAPP'
17051 can differ on different targets. For example, Linux uses '#APP' while
17052 on NT you will see '/APP'.
17054 If you make a mistake in your assembler code (such as using the
17055 wrong size modifier, or using a wrong operand for the instruction) GNAT
17056 will report this error in a temporary file, which will be deleted when
17057 the compilation is finished. Generating an assembler file will help
17058 in such cases, since you can assemble this file separately using the
17059 @emph{as} assembler that comes with gcc.
17061 Assembling the file using the command
17064 as @file{nothing.s}
17067 will give you error messages whose lines correspond to the assembler
17068 input file, so you can easily find and correct any mistakes you made.
17069 If there are no errors, @emph{as} will generate an object file @file{nothing.out}.
17071 @c ---------------------------------------------------------------------------
17072 @node Output Variables in Inline Assembler
17073 @section Output Variables in Inline Assembler
17076 The examples in this section, showing how to access the processor flags, illustrate how to specify the destination operands for assembly language statements.
17080 with Interfaces; use Interfaces;
17081 with Ada.Text_IO; use Ada.Text_IO;
17082 with System.Machine_Code; use System.Machine_Code;
17083 procedure Get_Flags is
17084 Flags : Unsigned_32;
17087 Asm ("pushfl" & LF & HT & -- push flags on stack
17088 "popl %%eax" & LF & HT & -- load eax with flags
17089 "movl %%eax, %0", -- store flags in variable
17090 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
17091 Put_Line ("Flags register:" & Flags'Img);
17096 In order to have a nicely aligned assembly listing, we have separated
17097 multiple assembler statements in the Asm template string with linefeed (ASCII.LF)
17098 and horizontal tab (ASCII.HT) characters. The resulting section of the
17099 assembly output file is:
17106 movl %eax, -40(%ebp)
17111 It would have been legal to write the Asm invocation as:
17114 Asm ("pushfl popl %%eax movl %%eax, %0")
17117 but in the generated assembler file, this would come out as:
17121 pushfl popl %eax movl %eax, -40(%ebp)
17125 which is not so convenient for the human reader.
17127 We use Ada comments
17128 at the end of each line to explain what the assembler instructions
17129 actually do. This is a useful convention.
17131 When writing Inline Assembler instructions, you need to precede each register and variable name with a percent sign. Since the assembler already requires a percent sign at the beginning of a register name, you need two consecutive percent signs for such names in the Asm template string, thus @code{%%eax}. In the generated assembly code, one of the percent signs will be stripped off.
17133 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output variables: operands you later define using @code{Input} or @code{Output} parameters to @code{Asm}.
17134 An output variable is illustrated in
17135 the third statement in the Asm template string:
17139 The intent is to store the contents of the eax register in a variable that can be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not necessarily work, since the compiler might optimize by using a register to hold Flags, and the expansion of the @code{movl} instruction would not be aware of this optimization. The solution is not to store the result directly but rather to advise the compiler to choose the correct operand form; that is the purpose of the @code{%0} output variable.
17141 Information about the output variable is supplied in the @code{Outputs} parameter to @code{Asm}:
17143 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
17146 The output is defined by the @code{Asm_Output} attribute of the target type; the general format is
17148 Type'Asm_Output (constraint_string, variable_name)
17151 The constraint string directs the compiler how
17152 to store/access the associated variable. In the example
17154 Unsigned_32'Asm_Output ("=m", Flags);
17156 the @code{"m"} (memory) constraint tells the compiler that the variable
17157 @code{Flags} should be stored in a memory variable, thus preventing
17158 the optimizer from keeping it in a register. In contrast,
17160 Unsigned_32'Asm_Output ("=r", Flags);
17162 uses the @code{"r"} (register) constraint, telling the compiler to
17163 store the variable in a register.
17165 If the constraint is preceded by the equal character (@strong{=}), it tells the
17166 compiler that the variable will be used to store data into it.
17168 In the @code{Get_Flags} example, we used the "g" (global) constraint, allowing the optimizer
17169 to choose whatever it deems best.
17171 There are a fairly large number of constraints, but the ones that are most useful (for the Intel x86 processor) are the following:
17177 global (i.e. can be stored anywhere)
17195 use one of eax, ebx, ecx or edx
17197 use one of eax, ebx, ecx, edx, esi or edi
17200 The full set of constraints is described in the gcc and @emph{as} documentation; note that it is possible to combine certain constraints in one constraint string.
17202 You specify the association of an output variable with an assembler operand through the @code{%}@emph{n} notation, where @emph{n} is a non-negative integer. Thus in
17205 Asm ("pushfl" & LF & HT & -- push flags on stack
17206 "popl %%eax" & LF & HT & -- load eax with flags
17207 "movl %%eax, %0", -- store flags in variable
17208 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
17212 @code{%0} will be replaced in the expanded code by the appropriate operand,
17214 the compiler decided for the @code{Flags} variable.
17216 In general, you may have any number of output variables:
17219 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
17221 Specify the @code{Outputs} parameter as a parenthesized comma-separated list of @code{Asm_Output} attributes
17227 Asm ("movl %%eax, %0" & LF & HT &
17228 "movl %%ebx, %1" & LF & HT &
17230 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
17231 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
17232 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
17236 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables in the Ada program.
17238 As a variation on the @code{Get_Flags} example, we can use the constraints string to direct the compiler to store the eax register into the @code{Flags} variable, instead of including the store instruction explicitly in the @code{Asm} template string:
17242 with Interfaces; use Interfaces;
17243 with Ada.Text_IO; use Ada.Text_IO;
17244 with System.Machine_Code; use System.Machine_Code;
17245 procedure Get_Flags_2 is
17246 Flags : Unsigned_32;
17249 Asm ("pushfl" & LF & HT & -- push flags on stack
17250 "popl %%eax", -- save flags in eax
17251 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
17252 Put_Line ("Flags register:" & Flags'Img);
17258 The @code{"a"} constraint tells the compiler that the @code{Flags}
17259 variable will come from the eax register. Here is the resulting code:
17267 movl %eax,-40(%ebp)
17272 The compiler generated the store of eax into Flags after
17273 expanding the assembler code.
17275 Actually, there was no need to pop the flags into the eax register; more simply, we could just pop the flags directly into the program variable:
17279 with Interfaces; use Interfaces;
17280 with Ada.Text_IO; use Ada.Text_IO;
17281 with System.Machine_Code; use System.Machine_Code;
17282 procedure Get_Flags_3 is
17283 Flags : Unsigned_32;
17286 Asm ("pushfl" & LF & HT & -- push flags on stack
17287 "pop %0", -- save flags in Flags
17288 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
17289 Put_Line ("Flags register:" & Flags'Img);
17294 @c ---------------------------------------------------------------------------
17295 @node Input Variables in Inline Assembler
17296 @section Input Variables in Inline Assembler
17299 The example in this section illustrates how to specify the source operands for assembly language statements. The program simply increments its input value by 1:
17303 with Interfaces; use Interfaces;
17304 with Ada.Text_IO; use Ada.Text_IO;
17305 with System.Machine_Code; use System.Machine_Code;
17306 procedure Increment is
17308 function Incr (Value : Unsigned_32) return Unsigned_32 is
17309 Result : Unsigned_32;
17312 Inputs => Unsigned_32'Asm_Input ("a", Value),
17313 Outputs => Unsigned_32'Asm_Output ("=a", Result));
17317 Value : Unsigned_32;
17321 Put_Line ("Value before is" & Value'Img);
17322 Value := Incr (Value);
17323 Put_Line ("Value after is" & Value'Img);
17328 The @code{Outputs} parameter to @code{Asm} specifies
17329 that the result will be in the eax register and that it is to be stored in the @code{Result}
17332 The @code{Inputs} parameter looks much like the @code{Outputs} parameter, but with an
17333 @code{Asm_Input} attribute. The
17334 @code{"="} constraint, indicating an output value, is not present.
17336 You can have multiple input variables, in the same way that you can have more
17337 than one output variable.
17339 The parameter count (%0, %1) etc, now starts at the first input
17340 statement, and continues with the output statements.
17341 When both parameters use the same variable, the
17342 compiler will treat them as the same %n operand, which is the case here.
17344 Just as the @code{Outputs} parameter causes the register to be stored into the
17345 target variable after execution of the assembler statements, so does the
17346 @code{Inputs} parameter cause its variable to be loaded into the register before execution
17348 assembler statements.
17350 Thus the effect of the @code{Asm} invocation is:
17352 @item load the 32-bit value of @code{Value} into eax
17353 @item execute the @code{incl %eax} instruction
17354 @item store the contents of eax into the @code{Result} variable
17357 The resulting assembler file (with @code{-O2} optimization) contains:
17360 _increment__incr.1:
17373 @c ---------------------------------------------------------------------------
17374 @node Inlining Inline Assembler Code
17375 @section Inlining Inline Assembler Code
17378 For a short subprogram such as the @code{Incr} function in the previous section, the overhead of the call and return (creating / deleting the stack frame)
17379 can be significant, compared to the amount of code in the subprogram body.
17380 A solution is to apply Ada's @code{Inline} pragma to the subprogram,
17381 which directs the compiler to expand invocations of the subprogram at the point(s)
17382 of call, instead of setting up a stack frame for out-of-line calls.
17383 Here is the resulting program:
17387 with Interfaces; use Interfaces;
17388 with Ada.Text_IO; use Ada.Text_IO;
17389 with System.Machine_Code; use System.Machine_Code;
17390 procedure Increment_2 is
17392 function Incr (Value : Unsigned_32) return Unsigned_32 is
17393 Result : Unsigned_32;
17396 Inputs => Unsigned_32'Asm_Input ("a", Value),
17397 Outputs => Unsigned_32'Asm_Output ("=a", Result));
17400 pragma Inline (Increment);
17402 Value : Unsigned_32;
17406 Put_Line ("Value before is" & Value'Img);
17407 Value := Increment (Value);
17408 Put_Line ("Value after is" & Value'Img);
17413 Compile the program with both optimization (@code{-O2}) and inlining
17414 enabled (@option{-gnatpn} instead of @option{-gnatp}).
17416 The @code{Incr} function is still compiled as usual, but at the
17417 point in @code{Increment} where our function used to be called:
17422 call _increment__incr.1
17427 the code for the function body directly appears:
17440 thus saving the overhead of stack frame setup and an out-of-line call.
17442 @c ---------------------------------------------------------------------------
17443 @node Other Asm Functionality
17444 @section Other @code{Asm} Functionality
17447 This section describes two important parameters to the @code{Asm} procedure: @code{Clobber}, which identifies register usage; and @code{Volatile}, which inhibits unwanted optimizations.
17450 * The Clobber Parameter::
17451 * The Volatile Parameter::
17454 @c ---------------------------------------------------------------------------
17455 @node The Clobber Parameter
17456 @subsection The @code{Clobber} Parameter
17459 One of the dangers of intermixing assembly language and a compiled language such as Ada is
17460 that the compiler needs to be aware of which registers are being used by the assembly code.
17461 In some cases, such as the earlier examples, the constraint string is sufficient to
17462 indicate register usage (e.g. "a" for the eax register). But more generally, the
17463 compiler needs an explicit identification of the registers that are used by the Inline
17464 Assembly statements.
17466 Using a register that the compiler doesn't know about
17467 could be a side effect of an instruction (like @code{mull}
17468 storing its result in both eax and edx).
17469 It can also arise from explicit register usage in your
17470 assembly code; for example:
17473 Asm ("movl %0, %%ebx" & LF & HT &
17475 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
17476 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
17480 where the compiler (since it does not analyze the @code{Asm} template string)
17481 does not know you are using the ebx register.
17483 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
17484 to identify the registers that will be used by your assembly code:
17488 Asm ("movl %0, %%ebx" & LF & HT &
17490 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
17491 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
17496 The Clobber parameter is a static string expression specifying the
17497 register(s) you are using. Note that register names are @emph{not} prefixed by a percent sign.
17498 Also, if more than one register is used then their names are separated by commas; e.g., @code{"eax, ebx"}
17500 The @code{Clobber} parameter has several additional uses:
17502 @item Use the "register" name @code{cc} to indicate that flags might have changed
17503 @item Use the "register" name @code{memory} if you changed a memory location
17506 @c ---------------------------------------------------------------------------
17507 @node The Volatile Parameter
17508 @subsection The @code{Volatile} Parameter
17509 @cindex Volatile parameter
17512 Compiler optimizations in the presence of Inline Assembler may sometimes have unwanted effects.
17514 an @code{Asm} invocation with an input variable is inside a loop, the compiler might move
17515 the loading of the input variable outside the loop, regarding it as a
17516 one-time initialization.
17518 If this effect is not desired, you can disable such optimizations by setting the
17519 @code{Volatile} parameter to @code{True}; for example:
17523 Asm ("movl %0, %%ebx" & LF & HT &
17525 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
17526 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
17532 By default, @code{Volatile} is set to @code{False} unless there is no @code{Outputs}
17535 Although setting @code{Volatile} to @code{True} prevents unwanted optimizations,
17536 it will also disable other optimizations that might be important for efficiency.
17537 In general, you should set @code{Volatile} to @code{True} only if the compiler's
17538 optimizations have created problems.
17540 @c ---------------------------------------------------------------------------
17541 @node A Complete Example
17542 @section A Complete Example
17545 This section contains a complete program illustrating a realistic usage of GNAT's Inline Assembler
17546 capabilities. It comprises a main procedure @code{Check_CPU} and a package @code{Intel_CPU}.
17547 The package declares a collection of functions that detect the properties of the 32-bit
17548 x86 processor that is running the program. The main procedure invokes these functions
17549 and displays the information.
17551 The Intel_CPU package could be enhanced by adding functions to
17552 detect the type of x386 co-processor, the processor caching options and
17553 special operations such as the SIMD extensions.
17555 Although the Intel_CPU package has been written for 32-bit Intel
17556 compatible CPUs, it is OS neutral. It has been tested on DOS,
17557 Windows/NT and Linux.
17560 * Check_CPU Procedure::
17561 * Intel_CPU Package Specification::
17562 * Intel_CPU Package Body::
17565 @c ---------------------------------------------------------------------------
17566 @node Check_CPU Procedure
17567 @subsection @code{Check_CPU} Procedure
17568 @cindex Check_CPU procedure
17571 ---------------------------------------------------------------------
17573 -- Uses the Intel_CPU package to identify the CPU the program is --
17574 -- running on, and some of the features it supports. --
17576 ---------------------------------------------------------------------
17578 with Intel_CPU; -- Intel CPU detection functions
17579 with Ada.Text_IO; -- Standard text I/O
17580 with Ada.Command_Line; -- To set the exit status
17582 procedure Check_CPU is
17584 Type_Found : Boolean := False;
17585 -- Flag to indicate that processor was identified
17587 Features : Intel_CPU.Processor_Features;
17588 -- The processor features
17590 Signature : Intel_CPU.Processor_Signature;
17591 -- The processor type signature
17595 -----------------------------------
17596 -- Display the program banner. --
17597 -----------------------------------
17599 Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name &
17600 ": check Intel CPU version and features, v1.0");
17601 Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever");
17602 Ada.Text_IO.New_Line;
17604 -----------------------------------------------------------------------
17605 -- We can safely start with the assumption that we are on at least --
17606 -- a x386 processor. If the CPUID instruction is present, then we --
17607 -- have a later processor type. --
17608 -----------------------------------------------------------------------
17610 if Intel_CPU.Has_CPUID = False then
17612 -- No CPUID instruction, so we assume this is indeed a x386
17613 -- processor. We can still check if it has a FP co-processor.
17614 if Intel_CPU.Has_FPU then
17615 Ada.Text_IO.Put_Line
17616 ("x386-type processor with a FP co-processor");
17618 Ada.Text_IO.Put_Line
17619 ("x386-type processor without a FP co-processor");
17620 end if; -- check for FPU
17623 Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
17626 end if; -- check for CPUID
17628 -----------------------------------------------------------------------
17629 -- If CPUID is supported, check if this is a true Intel processor, --
17630 -- if it is not, display a warning. --
17631 -----------------------------------------------------------------------
17633 if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then
17634 Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor");
17635 Ada.Text_IO.Put_Line ("*** Some information may be incorrect");
17636 end if; -- check if Intel
17638 ----------------------------------------------------------------------
17639 -- With the CPUID instruction present, we can assume at least a --
17640 -- x486 processor. If the CPUID support level is < 1 then we have --
17641 -- to leave it at that. --
17642 ----------------------------------------------------------------------
17644 if Intel_CPU.CPUID_Level < 1 then
17646 -- Ok, this is a x486 processor. we still can get the Vendor ID
17647 Ada.Text_IO.Put_Line ("x486-type processor");
17648 Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID);
17650 -- We can also check if there is a FPU present
17651 if Intel_CPU.Has_FPU then
17652 Ada.Text_IO.Put_Line ("Floating-Point support");
17654 Ada.Text_IO.Put_Line ("No Floating-Point support");
17655 end if; -- check for FPU
17658 Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
17661 end if; -- check CPUID level
17663 ---------------------------------------------------------------------
17664 -- With a CPUID level of 1 we can use the processor signature to --
17665 -- determine it's exact type. --
17666 ---------------------------------------------------------------------
17668 Signature := Intel_CPU.Signature;
17670 ----------------------------------------------------------------------
17671 -- Ok, now we go into a lot of messy comparisons to get the --
17672 -- processor type. For clarity, no attememt to try to optimize the --
17673 -- comparisons has been made. Note that since Intel_CPU does not --
17674 -- support getting cache info, we cannot distinguish between P5 --
17675 -- and Celeron types yet. --
17676 ----------------------------------------------------------------------
17679 if Signature.Processor_Type = 2#00# and
17680 Signature.Family = 2#0100# and
17681 Signature.Model = 2#0100# then
17682 Type_Found := True;
17683 Ada.Text_IO.Put_Line ("x486SL processor");
17686 -- x486DX2 Write-Back
17687 if Signature.Processor_Type = 2#00# and
17688 Signature.Family = 2#0100# and
17689 Signature.Model = 2#0111# then
17690 Type_Found := True;
17691 Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor");
17695 if Signature.Processor_Type = 2#00# and
17696 Signature.Family = 2#0100# and
17697 Signature.Model = 2#1000# then
17698 Type_Found := True;
17699 Ada.Text_IO.Put_Line ("x486DX4 processor");
17702 -- x486DX4 Overdrive
17703 if Signature.Processor_Type = 2#01# and
17704 Signature.Family = 2#0100# and
17705 Signature.Model = 2#1000# then
17706 Type_Found := True;
17707 Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor");
17710 -- Pentium (60, 66)
17711 if Signature.Processor_Type = 2#00# and
17712 Signature.Family = 2#0101# and
17713 Signature.Model = 2#0001# then
17714 Type_Found := True;
17715 Ada.Text_IO.Put_Line ("Pentium processor (60, 66)");
17718 -- Pentium (75, 90, 100, 120, 133, 150, 166, 200)
17719 if Signature.Processor_Type = 2#00# and
17720 Signature.Family = 2#0101# and
17721 Signature.Model = 2#0010# then
17722 Type_Found := True;
17723 Ada.Text_IO.Put_Line
17724 ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)");
17727 -- Pentium OverDrive (60, 66)
17728 if Signature.Processor_Type = 2#01# and
17729 Signature.Family = 2#0101# and
17730 Signature.Model = 2#0001# then
17731 Type_Found := True;
17732 Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)");
17735 -- Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200)
17736 if Signature.Processor_Type = 2#01# and
17737 Signature.Family = 2#0101# and
17738 Signature.Model = 2#0010# then
17739 Type_Found := True;
17740 Ada.Text_IO.Put_Line
17741 ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)");
17744 -- Pentium OverDrive processor for x486 processor-based systems
17745 if Signature.Processor_Type = 2#01# and
17746 Signature.Family = 2#0101# and
17747 Signature.Model = 2#0011# then
17748 Type_Found := True;
17749 Ada.Text_IO.Put_Line
17750 ("Pentium OverDrive processor for x486 processor-based systems");
17753 -- Pentium processor with MMX technology (166, 200)
17754 if Signature.Processor_Type = 2#00# and
17755 Signature.Family = 2#0101# and
17756 Signature.Model = 2#0100# then
17757 Type_Found := True;
17758 Ada.Text_IO.Put_Line
17759 ("Pentium processor with MMX technology (166, 200)");
17762 -- Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133)
17763 if Signature.Processor_Type = 2#01# and
17764 Signature.Family = 2#0101# and
17765 Signature.Model = 2#0100# then
17766 Type_Found := True;
17767 Ada.Text_IO.Put_Line
17768 ("Pentium OverDrive processor with MMX " &
17769 "technology for Pentium processor (75, 90, 100, 120, 133)");
17772 -- Pentium Pro processor
17773 if Signature.Processor_Type = 2#00# and
17774 Signature.Family = 2#0110# and
17775 Signature.Model = 2#0001# then
17776 Type_Found := True;
17777 Ada.Text_IO.Put_Line ("Pentium Pro processor");
17780 -- Pentium II processor, model 3
17781 if Signature.Processor_Type = 2#00# and
17782 Signature.Family = 2#0110# and
17783 Signature.Model = 2#0011# then
17784 Type_Found := True;
17785 Ada.Text_IO.Put_Line ("Pentium II processor, model 3");
17788 -- Pentium II processor, model 5 or Celeron processor
17789 if Signature.Processor_Type = 2#00# and
17790 Signature.Family = 2#0110# and
17791 Signature.Model = 2#0101# then
17792 Type_Found := True;
17793 Ada.Text_IO.Put_Line
17794 ("Pentium II processor, model 5 or Celeron processor");
17797 -- Pentium Pro OverDrive processor
17798 if Signature.Processor_Type = 2#01# and
17799 Signature.Family = 2#0110# and
17800 Signature.Model = 2#0011# then
17801 Type_Found := True;
17802 Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor");
17805 -- If no type recognized, we have an unknown. Display what
17807 if Type_Found = False then
17808 Ada.Text_IO.Put_Line ("Unknown processor");
17811 -----------------------------------------
17812 -- Display processor stepping level. --
17813 -----------------------------------------
17815 Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img);
17817 ---------------------------------
17818 -- Display vendor ID string. --
17819 ---------------------------------
17821 Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID);
17823 ------------------------------------
17824 -- Get the processors features. --
17825 ------------------------------------
17827 Features := Intel_CPU.Features;
17829 -----------------------------
17830 -- Check for a FPU unit. --
17831 -----------------------------
17833 if Features.FPU = True then
17834 Ada.Text_IO.Put_Line ("Floating-Point unit available");
17836 Ada.Text_IO.Put_Line ("no Floating-Point unit");
17837 end if; -- check for FPU
17839 --------------------------------
17840 -- List processor features. --
17841 --------------------------------
17843 Ada.Text_IO.Put_Line ("Supported features: ");
17845 -- Virtual Mode Extension
17846 if Features.VME = True then
17847 Ada.Text_IO.Put_Line (" VME - Virtual Mode Extension");
17850 -- Debugging Extension
17851 if Features.DE = True then
17852 Ada.Text_IO.Put_Line (" DE - Debugging Extension");
17855 -- Page Size Extension
17856 if Features.PSE = True then
17857 Ada.Text_IO.Put_Line (" PSE - Page Size Extension");
17860 -- Time Stamp Counter
17861 if Features.TSC = True then
17862 Ada.Text_IO.Put_Line (" TSC - Time Stamp Counter");
17865 -- Model Specific Registers
17866 if Features.MSR = True then
17867 Ada.Text_IO.Put_Line (" MSR - Model Specific Registers");
17870 -- Physical Address Extension
17871 if Features.PAE = True then
17872 Ada.Text_IO.Put_Line (" PAE - Physical Address Extension");
17875 -- Machine Check Extension
17876 if Features.MCE = True then
17877 Ada.Text_IO.Put_Line (" MCE - Machine Check Extension");
17880 -- CMPXCHG8 instruction supported
17881 if Features.CX8 = True then
17882 Ada.Text_IO.Put_Line (" CX8 - CMPXCHG8 instruction");
17885 -- on-chip APIC hardware support
17886 if Features.APIC = True then
17887 Ada.Text_IO.Put_Line (" APIC - on-chip APIC hardware support");
17890 -- Fast System Call
17891 if Features.SEP = True then
17892 Ada.Text_IO.Put_Line (" SEP - Fast System Call");
17895 -- Memory Type Range Registers
17896 if Features.MTRR = True then
17897 Ada.Text_IO.Put_Line (" MTTR - Memory Type Range Registers");
17900 -- Page Global Enable
17901 if Features.PGE = True then
17902 Ada.Text_IO.Put_Line (" PGE - Page Global Enable");
17905 -- Machine Check Architecture
17906 if Features.MCA = True then
17907 Ada.Text_IO.Put_Line (" MCA - Machine Check Architecture");
17910 -- Conditional Move Instruction Supported
17911 if Features.CMOV = True then
17912 Ada.Text_IO.Put_Line
17913 (" CMOV - Conditional Move Instruction Supported");
17916 -- Page Attribute Table
17917 if Features.PAT = True then
17918 Ada.Text_IO.Put_Line (" PAT - Page Attribute Table");
17921 -- 36-bit Page Size Extension
17922 if Features.PSE_36 = True then
17923 Ada.Text_IO.Put_Line (" PSE_36 - 36-bit Page Size Extension");
17926 -- MMX technology supported
17927 if Features.MMX = True then
17928 Ada.Text_IO.Put_Line (" MMX - MMX technology supported");
17931 -- Fast FP Save and Restore
17932 if Features.FXSR = True then
17933 Ada.Text_IO.Put_Line (" FXSR - Fast FP Save and Restore");
17936 ---------------------
17937 -- Program done. --
17938 ---------------------
17940 Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
17945 Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
17951 @c ---------------------------------------------------------------------------
17952 @node Intel_CPU Package Specification
17953 @subsection @code{Intel_CPU} Package Specification
17954 @cindex Intel_CPU package specification
17957 -------------------------------------------------------------------------
17959 -- file: intel_cpu.ads --
17961 -- ********************************************* --
17962 -- * WARNING: for 32-bit Intel processors only * --
17963 -- ********************************************* --
17965 -- This package contains a number of subprograms that are useful in --
17966 -- determining the Intel x86 CPU (and the features it supports) on --
17967 -- which the program is running. --
17969 -- The package is based upon the information given in the Intel --
17970 -- Application Note AP-485: "Intel Processor Identification and the --
17971 -- CPUID Instruction" as of April 1998. This application note can be --
17972 -- found on www.intel.com. --
17974 -- It currently deals with 32-bit processors only, will not detect --
17975 -- features added after april 1998, and does not guarantee proper --
17976 -- results on Intel-compatible processors. --
17978 -- Cache info and x386 fpu type detection are not supported. --
17980 -- This package does not use any privileged instructions, so should --
17981 -- work on any OS running on a 32-bit Intel processor. --
17983 -------------------------------------------------------------------------
17985 with Interfaces; use Interfaces;
17986 -- for using unsigned types
17988 with System.Machine_Code; use System.Machine_Code;
17989 -- for using inline assembler code
17991 with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
17992 -- for inserting control characters
17994 package Intel_CPU is
17996 ----------------------
17997 -- Processor bits --
17998 ----------------------
18000 subtype Num_Bits is Natural range 0 .. 31;
18001 -- the number of processor bits (32)
18003 --------------------------
18004 -- Processor register --
18005 --------------------------
18007 -- define a processor register type for easy access to
18008 -- the individual bits
18010 type Processor_Register is array (Num_Bits) of Boolean;
18011 pragma Pack (Processor_Register);
18012 for Processor_Register'Size use 32;
18014 -------------------------
18015 -- Unsigned register --
18016 -------------------------
18018 -- define a processor register type for easy access to
18019 -- the individual bytes
18021 type Unsigned_Register is
18029 for Unsigned_Register use
18031 L1 at 0 range 0 .. 7;
18032 H1 at 0 range 8 .. 15;
18033 L2 at 0 range 16 .. 23;
18034 H2 at 0 range 24 .. 31;
18037 for Unsigned_Register'Size use 32;
18039 ---------------------------------
18040 -- Intel processor vendor ID --
18041 ---------------------------------
18043 Intel_Processor : constant String (1 .. 12) := "GenuineIntel";
18044 -- indicates an Intel manufactured processor
18046 ------------------------------------
18047 -- Processor signature register --
18048 ------------------------------------
18050 -- a register type to hold the processor signature
18052 type Processor_Signature is
18054 Stepping : Natural range 0 .. 15;
18055 Model : Natural range 0 .. 15;
18056 Family : Natural range 0 .. 15;
18057 Processor_Type : Natural range 0 .. 3;
18058 Reserved : Natural range 0 .. 262143;
18061 for Processor_Signature use
18063 Stepping at 0 range 0 .. 3;
18064 Model at 0 range 4 .. 7;
18065 Family at 0 range 8 .. 11;
18066 Processor_Type at 0 range 12 .. 13;
18067 Reserved at 0 range 14 .. 31;
18070 for Processor_Signature'Size use 32;
18072 -----------------------------------
18073 -- Processor features register --
18074 -----------------------------------
18076 -- a processor register to hold the processor feature flags
18078 type Processor_Features is
18080 FPU : Boolean; -- floating point unit on chip
18081 VME : Boolean; -- virtual mode extension
18082 DE : Boolean; -- debugging extension
18083 PSE : Boolean; -- page size extension
18084 TSC : Boolean; -- time stamp counter
18085 MSR : Boolean; -- model specific registers
18086 PAE : Boolean; -- physical address extension
18087 MCE : Boolean; -- machine check extension
18088 CX8 : Boolean; -- cmpxchg8 instruction
18089 APIC : Boolean; -- on-chip apic hardware
18090 Res_1 : Boolean; -- reserved for extensions
18091 SEP : Boolean; -- fast system call
18092 MTRR : Boolean; -- memory type range registers
18093 PGE : Boolean; -- page global enable
18094 MCA : Boolean; -- machine check architecture
18095 CMOV : Boolean; -- conditional move supported
18096 PAT : Boolean; -- page attribute table
18097 PSE_36 : Boolean; -- 36-bit page size extension
18098 Res_2 : Natural range 0 .. 31; -- reserved for extensions
18099 MMX : Boolean; -- MMX technology supported
18100 FXSR : Boolean; -- fast FP save and restore
18101 Res_3 : Natural range 0 .. 127; -- reserved for extensions
18104 for Processor_Features use
18106 FPU at 0 range 0 .. 0;
18107 VME at 0 range 1 .. 1;
18108 DE at 0 range 2 .. 2;
18109 PSE at 0 range 3 .. 3;
18110 TSC at 0 range 4 .. 4;
18111 MSR at 0 range 5 .. 5;
18112 PAE at 0 range 6 .. 6;
18113 MCE at 0 range 7 .. 7;
18114 CX8 at 0 range 8 .. 8;
18115 APIC at 0 range 9 .. 9;
18116 Res_1 at 0 range 10 .. 10;
18117 SEP at 0 range 11 .. 11;
18118 MTRR at 0 range 12 .. 12;
18119 PGE at 0 range 13 .. 13;
18120 MCA at 0 range 14 .. 14;
18121 CMOV at 0 range 15 .. 15;
18122 PAT at 0 range 16 .. 16;
18123 PSE_36 at 0 range 17 .. 17;
18124 Res_2 at 0 range 18 .. 22;
18125 MMX at 0 range 23 .. 23;
18126 FXSR at 0 range 24 .. 24;
18127 Res_3 at 0 range 25 .. 31;
18130 for Processor_Features'Size use 32;
18132 -------------------
18134 -------------------
18136 function Has_FPU return Boolean;
18137 -- return True if a FPU is found
18138 -- use only if CPUID is not supported
18140 function Has_CPUID return Boolean;
18141 -- return True if the processor supports the CPUID instruction
18143 function CPUID_Level return Natural;
18144 -- return the CPUID support level (0, 1 or 2)
18145 -- can only be called if the CPUID instruction is supported
18147 function Vendor_ID return String;
18148 -- return the processor vendor identification string
18149 -- can only be called if the CPUID instruction is supported
18151 function Signature return Processor_Signature;
18152 -- return the processor signature
18153 -- can only be called if the CPUID instruction is supported
18155 function Features return Processor_Features;
18156 -- return the processors features
18157 -- can only be called if the CPUID instruction is supported
18161 ------------------------
18162 -- EFLAGS bit names --
18163 ------------------------
18165 ID_Flag : constant Num_Bits := 21;
18171 @c ---------------------------------------------------------------------------
18172 @node Intel_CPU Package Body
18173 @subsection @code{Intel_CPU} Package Body
18174 @cindex Intel_CPU package body
18177 package body Intel_CPU is
18179 ---------------------------
18180 -- Detect FPU presence --
18181 ---------------------------
18183 -- There is a FPU present if we can set values to the FPU Status
18184 -- and Control Words.
18186 function Has_FPU return Boolean is
18188 Register : Unsigned_16;
18189 -- processor register to store a word
18193 -- check if we can change the status word
18196 -- the assembler code
18197 "finit" & LF & HT & -- reset status word
18198 "movw $0x5A5A, %%ax" & LF & HT & -- set value status word
18199 "fnstsw %0" & LF & HT & -- save status word
18200 "movw %%ax, %0", -- store status word
18202 -- output stored in Register
18203 -- register must be a memory location
18204 Outputs => Unsigned_16'Asm_output ("=m", Register),
18206 -- tell compiler that we used eax
18209 -- if the status word is zero, there is no FPU
18210 if Register = 0 then
18211 return False; -- no status word
18212 end if; -- check status word value
18214 -- check if we can get the control word
18217 -- the assembler code
18218 "fnstcw %0", -- save the control word
18220 -- output into Register
18221 -- register must be a memory location
18222 Outputs => Unsigned_16'Asm_output ("=m", Register));
18224 -- check the relevant bits
18225 if (Register and 16#103F#) /= 16#003F# then
18226 return False; -- no control word
18227 end if; -- check control word value
18234 --------------------------------
18235 -- Detect CPUID instruction --
18236 --------------------------------
18238 -- The processor supports the CPUID instruction if it is possible
18239 -- to change the value of ID flag bit in the EFLAGS register.
18241 function Has_CPUID return Boolean is
18243 Original_Flags, Modified_Flags : Processor_Register;
18244 -- EFLAG contents before and after changing the ID flag
18248 -- try flipping the ID flag in the EFLAGS register
18251 -- the assembler code
18252 "pushfl" & LF & HT & -- push EFLAGS on stack
18253 "pop %%eax" & LF & HT & -- pop EFLAGS into eax
18254 "movl %%eax, %0" & LF & HT & -- save EFLAGS content
18255 "xor $0x200000, %%eax" & LF & HT & -- flip ID flag
18256 "push %%eax" & LF & HT & -- push EFLAGS on stack
18257 "popfl" & LF & HT & -- load EFLAGS register
18258 "pushfl" & LF & HT & -- push EFLAGS on stack
18259 "pop %1", -- save EFLAGS content
18261 -- output values, may be anything
18262 -- Original_Flags is %0
18263 -- Modified_Flags is %1
18265 (Processor_Register'Asm_output ("=g", Original_Flags),
18266 Processor_Register'Asm_output ("=g", Modified_Flags)),
18268 -- tell compiler eax is destroyed
18271 -- check if CPUID is supported
18272 if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then
18273 return True; -- ID flag was modified
18275 return False; -- ID flag unchanged
18276 end if; -- check for CPUID
18280 -------------------------------
18281 -- Get CPUID support level --
18282 -------------------------------
18284 function CPUID_Level return Natural is
18286 Level : Unsigned_32;
18287 -- returned support level
18291 -- execute CPUID, storing the results in the Level register
18294 -- the assembler code
18295 "cpuid", -- execute CPUID
18297 -- zero is stored in eax
18298 -- returning the support level in eax
18299 Inputs => Unsigned_32'Asm_input ("a", 0),
18301 -- eax is stored in Level
18302 Outputs => Unsigned_32'Asm_output ("=a", Level),
18304 -- tell compiler ebx, ecx and edx registers are destroyed
18305 Clobber => "ebx, ecx, edx");
18307 -- return the support level
18308 return Natural (Level);
18312 --------------------------------
18313 -- Get CPU Vendor ID String --
18314 --------------------------------
18316 -- The vendor ID string is returned in the ebx, ecx and edx register
18317 -- after executing the CPUID instruction with eax set to zero.
18318 -- In case of a true Intel processor the string returned is
18321 function Vendor_ID return String is
18323 Ebx, Ecx, Edx : Unsigned_Register;
18324 -- registers containing the vendor ID string
18326 Vendor_ID : String (1 .. 12);
18327 -- the vendor ID string
18331 -- execute CPUID, storing the results in the processor registers
18334 -- the assembler code
18335 "cpuid", -- execute CPUID
18337 -- zero stored in eax
18338 -- vendor ID string returned in ebx, ecx and edx
18339 Inputs => Unsigned_32'Asm_input ("a", 0),
18341 -- ebx is stored in Ebx
18342 -- ecx is stored in Ecx
18343 -- edx is stored in Edx
18344 Outputs => (Unsigned_Register'Asm_output ("=b", Ebx),
18345 Unsigned_Register'Asm_output ("=c", Ecx),
18346 Unsigned_Register'Asm_output ("=d", Edx)));
18348 -- now build the vendor ID string
18349 Vendor_ID( 1) := Character'Val (Ebx.L1);
18350 Vendor_ID( 2) := Character'Val (Ebx.H1);
18351 Vendor_ID( 3) := Character'Val (Ebx.L2);
18352 Vendor_ID( 4) := Character'Val (Ebx.H2);
18353 Vendor_ID( 5) := Character'Val (Edx.L1);
18354 Vendor_ID( 6) := Character'Val (Edx.H1);
18355 Vendor_ID( 7) := Character'Val (Edx.L2);
18356 Vendor_ID( 8) := Character'Val (Edx.H2);
18357 Vendor_ID( 9) := Character'Val (Ecx.L1);
18358 Vendor_ID(10) := Character'Val (Ecx.H1);
18359 Vendor_ID(11) := Character'Val (Ecx.L2);
18360 Vendor_ID(12) := Character'Val (Ecx.H2);
18367 -------------------------------
18368 -- Get processor signature --
18369 -------------------------------
18371 function Signature return Processor_Signature is
18373 Result : Processor_Signature;
18374 -- processor signature returned
18378 -- execute CPUID, storing the results in the Result variable
18381 -- the assembler code
18382 "cpuid", -- execute CPUID
18384 -- one is stored in eax
18385 -- processor signature returned in eax
18386 Inputs => Unsigned_32'Asm_input ("a", 1),
18388 -- eax is stored in Result
18389 Outputs => Processor_Signature'Asm_output ("=a", Result),
18391 -- tell compiler that ebx, ecx and edx are also destroyed
18392 Clobber => "ebx, ecx, edx");
18394 -- return processor signature
18399 ------------------------------
18400 -- Get processor features --
18401 ------------------------------
18403 function Features return Processor_Features is
18405 Result : Processor_Features;
18406 -- processor features returned
18410 -- execute CPUID, storing the results in the Result variable
18413 -- the assembler code
18414 "cpuid", -- execute CPUID
18416 -- one stored in eax
18417 -- processor features returned in edx
18418 Inputs => Unsigned_32'Asm_input ("a", 1),
18420 -- edx is stored in Result
18421 Outputs => Processor_Features'Asm_output ("=d", Result),
18423 -- tell compiler that ebx and ecx are also destroyed
18424 Clobber => "ebx, ecx");
18426 -- return processor signature
18433 @c END OF INLINE ASSEMBLER CHAPTER
18434 @c ===============================
18439 @node Performance Considerations
18440 @chapter Performance Considerations
18441 @cindex Performance
18444 The GNAT system provides a number of options that allow a trade-off
18449 performance of the generated code
18452 speed of compilation
18455 minimization of dependences and recompilation
18458 the degree of run-time checking.
18462 The defaults (if no options are selected) aim at improving the speed
18463 of compilation and minimizing dependences, at the expense of performance
18464 of the generated code:
18471 no inlining of subprogram calls
18474 all run-time checks enabled except overflow and elaboration checks
18478 These options are suitable for most program development purposes. This
18479 chapter describes how you can modify these choices, and also provides
18480 some guidelines on debugging optimized code.
18483 * Controlling Run-Time Checks::
18484 * Optimization Levels::
18485 * Debugging Optimized Code::
18486 * Inlining of Subprograms::
18489 @node Controlling Run-Time Checks
18490 @section Controlling Run-Time Checks
18493 By default, GNAT generates all run-time checks, except arithmetic overflow
18494 checking for integer operations and checks for access before elaboration on
18495 subprogram calls. The latter are not required in default mode, because all
18496 necessary checking is done at compile time.
18497 @cindex @option{-gnatp} (@code{gcc})
18498 @cindex @option{-gnato} (@code{gcc})
18499 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
18500 be modified. @xref{Run-Time Checks}.
18502 Our experience is that the default is suitable for most development
18505 We treat integer overflow specially because these
18506 are quite expensive and in our experience are not as important as other
18507 run-time checks in the development process. Note that division by zero
18508 is not considered an overflow check, and divide by zero checks are
18509 generated where required by default.
18511 Elaboration checks are off by default, and also not needed by default, since
18512 GNAT uses a static elaboration analysis approach that avoids the need for
18513 run-time checking. This manual contains a full chapter discussing the issue
18514 of elaboration checks, and if the default is not satisfactory for your use,
18515 you should read this chapter.
18517 For validity checks, the minimal checks required by the Ada Reference
18518 Manual (for case statements and assignments to array elements) are on
18519 by default. These can be suppressed by use of the @option{-gnatVn} switch.
18520 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
18521 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
18522 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
18523 are also suppressed entirely if @option{-gnatp} is used.
18525 @cindex Overflow checks
18526 @cindex Checks, overflow
18529 @cindex pragma Suppress
18530 @cindex pragma Unsuppress
18531 Note that the setting of the switches controls the default setting of
18532 the checks. They may be modified using either @code{pragma Suppress} (to
18533 remove checks) or @code{pragma Unsuppress} (to add back suppressed
18534 checks) in the program source.
18536 @node Optimization Levels
18537 @section Optimization Levels
18538 @cindex @code{-O} (@code{gcc})
18541 The default is optimization off. This results in the fastest compile
18542 times, but GNAT makes absolutely no attempt to optimize, and the
18543 generated programs are considerably larger and slower than when
18544 optimization is enabled. You can use the
18545 @code{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
18546 on the @code{gcc} command line to control the optimization level:
18550 no optimization (the default)
18553 medium level optimization
18559 full optimization, and also attempt automatic inlining of small
18560 subprograms within a unit (@pxref{Inlining of Subprograms}).
18563 Higher optimization levels perform more global transformations on the
18564 program and apply more expensive analysis algorithms in order to generate
18565 faster and more compact code. The price in compilation time, and the
18566 resulting improvement in execution time,
18567 both depend on the particular application and the hardware environment.
18568 You should experiment to find the best level for your application.
18570 Note: Unlike some other compilation systems, @code{gcc} has
18571 been tested extensively at all optimization levels. There are some bugs
18572 which appear only with optimization turned on, but there have also been
18573 bugs which show up only in @emph{unoptimized} code. Selecting a lower
18574 level of optimization does not improve the reliability of the code
18575 generator, which in practice is highly reliable at all optimization
18578 Note regarding the use of @code{-O3}: The use of this optimization level
18579 is generally discouraged with GNAT, since it often results in larger
18580 executables which run more slowly. See further discussion of this point
18581 in @pxref{Inlining of Subprograms}.
18583 @node Debugging Optimized Code
18584 @section Debugging Optimized Code
18587 Since the compiler generates debugging tables for a compilation unit before
18588 it performs optimizations, the optimizing transformations may invalidate some
18589 of the debugging data. You therefore need to anticipate certain
18590 anomalous situations that may arise while debugging optimized code. This
18591 section describes the most common cases.
18595 @i{The "hopping Program Counter":} Repeated 'step' or 'next' commands show the PC
18596 bouncing back and forth in the code. This may result from any of the following
18601 @i{Common subexpression elimination:} using a single instance of code for a
18602 quantity that the source computes several times. As a result you
18603 may not be able to stop on what looks like a statement.
18606 @i{Invariant code motion:} moving an expression that does not change within a
18607 loop, to the beginning of the loop.
18610 @i{Instruction scheduling:} moving instructions so as to
18611 overlap loads and stores (typically) with other code, or in
18612 general to move computations of values closer to their uses. Often
18613 this causes you to pass an assignment statement without the assignment
18614 happening and then later bounce back to the statement when the
18615 value is actually needed. Placing a breakpoint on a line of code
18616 and then stepping over it may, therefore, not always cause all the
18617 expected side-effects.
18621 @i{The "big leap":} More commonly known as @i{cross-jumping}, in which two
18622 identical pieces of code are merged and the program counter suddenly
18623 jumps to a statement that is not supposed to be executed, simply because
18624 it (and the code following) translates to the same thing as the code
18625 that @emph{was} supposed to be executed. This effect is typically seen in
18626 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
18627 a @code{break} in a C @code{switch} statement.
18630 @i{The "roving variable":} The symptom is an unexpected value in a variable.
18631 There are various reasons for this effect:
18635 In a subprogram prologue, a parameter may not yet have been moved to its
18639 A variable may be dead, and its register re-used. This is
18640 probably the most common cause.
18643 As mentioned above, the assignment of a value to a variable may
18647 A variable may be eliminated entirely by value propagation or
18648 other means. In this case, GCC may incorrectly generate debugging
18649 information for the variable
18653 In general, when an unexpected value appears for a local variable or parameter
18654 you should first ascertain if that value was actually computed by
18655 your program, as opposed to being incorrectly reported by the debugger.
18657 array elements in an object designated by an access value
18658 are generally less of a problem, once you have ascertained that the access value
18660 Typically, this means checking variables in the preceding code and in the
18661 calling subprogram to verify that the value observed is explainable from other
18662 values (one must apply the procedure recursively to those
18663 other values); or re-running the code and stopping a little earlier
18664 (perhaps before the call) and stepping to better see how the variable obtained
18665 the value in question; or continuing to step @emph{from} the point of the
18666 strange value to see if code motion had simply moved the variable's
18670 @node Inlining of Subprograms
18671 @section Inlining of Subprograms
18674 A call to a subprogram in the current unit is inlined if all the
18675 following conditions are met:
18679 The optimization level is at least @code{-O1}.
18682 The called subprogram is suitable for inlining: It must be small enough
18683 and not contain nested subprograms or anything else that @code{gcc}
18684 cannot support in inlined subprograms.
18687 The call occurs after the definition of the body of the subprogram.
18690 @cindex pragma Inline
18692 Either @code{pragma Inline} applies to the subprogram or it is
18693 small and automatic inlining (optimization level @code{-O3}) is
18698 Calls to subprograms in @code{with}'ed units are normally not inlined.
18699 To achieve this level of inlining, the following conditions must all be
18704 The optimization level is at least @code{-O1}.
18707 The called subprogram is suitable for inlining: It must be small enough
18708 and not contain nested subprograms or anything else @code{gcc} cannot
18709 support in inlined subprograms.
18712 The call appears in a body (not in a package spec).
18715 There is a @code{pragma Inline} for the subprogram.
18718 @cindex @option{-gnatn} (@code{gcc})
18719 The @code{-gnatn} switch
18720 is used in the @code{gcc} command line
18723 Note that specifying the @option{-gnatn} switch causes additional
18724 compilation dependencies. Consider the following:
18729 @b{package} R @b{is}
18731 @b{pragma} Inline (Q);
18733 @b{package body} R @b{is}
18738 @b{procedure} Main @b{is}
18748 With the default behavior (no @option{-gnatn} switch specified), the
18749 compilation of the @code{Main} procedure depends only on its own source,
18750 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
18751 means that editing the body of @code{R} does not require recompiling
18754 On the other hand, the call @code{R.Q} is not inlined under these
18755 circumstances. If the @option{-gnatn} switch is present when @code{Main}
18756 is compiled, the call will be inlined if the body of @code{Q} is small
18757 enough, but now @code{Main} depends on the body of @code{R} in
18758 @file{r.adb} as well as on the spec. This means that if this body is edited,
18759 the main program must be recompiled. Note that this extra dependency
18760 occurs whether or not the call is in fact inlined by @code{gcc}.
18762 The use of front end inlining with @option{-gnatN} generates similar
18763 additional dependencies.
18765 @cindex @code{-fno-inline} (@code{gcc})
18766 Note: The @code{-fno-inline} switch
18767 can be used to prevent
18768 all inlining. This switch overrides all other conditions and ensures
18769 that no inlining occurs. The extra dependences resulting from
18770 @option{-gnatn} will still be active, even if
18771 this switch is used to suppress the resulting inlining actions.
18773 Note regarding the use of @code{-O3}: There is no difference in inlining
18774 behavior between @code{-O2} and @code{-O3} for subprograms with an explicit
18775 pragma @code{Inline} assuming the use of @option{-gnatn}
18776 or @option{-gnatN} (the switches that activate inlining). If you have used
18777 pragma @code{Inline} in appropriate cases, then it is usually much better
18778 to use @code{-O2} and @option{-gnatn} and avoid the use of @code{-O3} which
18779 in this case only has the effect of inlining subprograms you did not
18780 think should be inlined. We often find that the use of @code{-O3} slows
18781 down code by performing excessive inlining, leading to increased instruction
18782 cache pressure from the increased code size. So the bottom line here is
18783 that you should not automatically assume that @code{-O3} is better than
18784 @code{-O2}, and indeed you should use @code{-O3} only if tests show that
18785 it actually improves performance.
18789 @c GNU Free Documentation License
18791 @node Index,,GNU Free Documentation License, Top