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
56 @setfilename gnat_ug_wnt.info
57 @settitle GNAT User's Guide for Windows NT
58 @dircategory GNU Ada tools
60 * GNAT User's Guide (gnat_ug_wnt). GNAT User's Guide for Windows NT.
65 @include gcc-common.texi
67 @setchapternewpage odd
72 Copyright @copyright{} 1995-2003, Free Software Foundation
74 Permission is granted to copy, distribute and/or modify this document
75 under the terms of the GNU Free Documentation License, Version 1.2
76 or any later version published by the Free Software Foundation;
77 with the Invariant Sections being ``GNU Free Documentation License'', with the
78 Front-Cover Texts being
79 ``GNAT User's Guide for Windows NT'',
80 and with no Back-Cover Texts.
81 A copy of the license is included in the section entitled ``GNU
82 Free Documentation License''.
88 @title GNAT User's Guide
89 @center @titlefont{for Windows NT}
93 @subtitle GNAT, The GNU Ada 95 Compiler
94 @subtitle GNAT Version for GCC @value{version-GCC}
96 @author Ada Core Technologies, Inc.
99 @vskip 0pt plus 1filll
106 @node Top, About This Guide, (dir), (dir)
107 @top GNAT User's Guide
110 GNAT User's Guide for Windows NT
114 GNAT, The GNU Ada 95 Compiler
116 GNAT Version for GCC @value{version-GCC}
118 Ada Core Technologies, Inc.
124 * Getting Started with GNAT::
125 * The GNAT Compilation Model::
126 * Compiling Using gcc::
127 * Binding Using gnatbind::
128 * Linking Using gnatlink::
129 * The GNAT Make Program gnatmake::
130 * Renaming Files Using gnatchop::
131 * Configuration Pragmas::
132 * Handling Arbitrary File Naming Conventions Using gnatname::
133 * GNAT Project Manager::
134 * Elaboration Order Handling in GNAT::
135 * The Cross-Referencing Tools gnatxref and gnatfind::
136 * File Name Krunching Using gnatkr::
137 * Preprocessing Using gnatprep::
138 * The GNAT Library Browser gnatls::
139 * GNAT and Libraries::
140 * Using the GNU make Utility::
141 * Finding Memory Problems with gnatmem::
142 * Finding Memory Problems with GNAT Debug Pool::
143 * Creating Sample Bodies Using gnatstub::
144 * Reducing the Size of Ada Executables with gnatelim::
145 * Other Utility Programs::
146 * Running and Debugging Ada Programs::
148 * Microsoft Windows Topics::
149 * Performance Considerations::
150 * GNU Free Documentation License::
153 --- The Detailed Node Listing ---
157 * What This Guide Contains::
158 * What You Should Know before Reading This Guide::
159 * Related Information::
163 Getting Started with GNAT
166 * Running a Simple Ada Program::
167 * Running a Program with Multiple Units::
168 * Using the gnatmake Utility::
170 The GNAT Compilation Model
172 * Source Representation::
173 * Foreign Language Representation::
174 * File Naming Rules::
175 * Using Other File Names::
176 * Alternative File Naming Schemes::
177 * Generating Object Files::
178 * Source Dependencies::
179 * The Ada Library Information Files::
180 * Binding an Ada Program::
181 * Mixed Language Programming::
182 * Building Mixed Ada & C++ Programs::
183 * Comparison between GNAT and C/C++ Compilation Models::
184 * Comparison between GNAT and Conventional Ada Library Models::
186 Foreign Language Representation
189 * Other 8-Bit Codes::
190 * Wide Character Encodings::
192 Compiling Ada Programs With gcc
194 * Compiling Programs::
196 * Search Paths and the Run-Time Library (RTL)::
197 * Order of Compilation Issues::
202 * Output and Error Message Control::
203 * Debugging and Assertion Control::
205 * Stack Overflow Checking::
207 * Validity Checking::
209 * Using gcc for Syntax Checking::
210 * Using gcc for Semantic Checking::
211 * Compiling Ada 83 Programs::
212 * Character Set Control::
213 * File Naming Control::
214 * Subprogram Inlining Control::
215 * Auxiliary Output Control::
216 * Debugging Control::
217 * Units to Sources Mapping Files::
219 Binding Ada Programs With gnatbind
222 * Generating the Binder Program in C::
223 * Consistency-Checking Modes::
224 * Binder Error Message Control::
225 * Elaboration Control::
227 * Binding with Non-Ada Main Programs::
228 * Binding Programs with No Main Subprogram::
229 * Summary of Binder Switches::
230 * Command-Line Access::
231 * Search Paths for gnatbind::
232 * Examples of gnatbind Usage::
234 Linking Using gnatlink
237 * Switches for gnatlink::
238 * Setting Stack Size from gnatlink::
239 * Setting Heap Size from gnatlink::
241 The GNAT Make Program gnatmake
244 * Switches for gnatmake::
245 * Mode Switches for gnatmake::
246 * Notes on the Command Line::
247 * How gnatmake Works::
248 * Examples of gnatmake Usage::
250 Renaming Files Using gnatchop
252 * Handling Files with Multiple Units::
253 * Operating gnatchop in Compilation Mode::
254 * Command Line for gnatchop::
255 * Switches for gnatchop::
256 * Examples of gnatchop Usage::
258 Configuration Pragmas
260 * Handling of Configuration Pragmas::
261 * The Configuration Pragmas Files::
263 Handling Arbitrary File Naming Conventions Using gnatname
265 * Arbitrary File Naming Conventions::
267 * Switches for gnatname::
268 * Examples of gnatname Usage::
273 * Examples of Project Files::
274 * Project File Syntax::
275 * Objects and Sources in Project Files::
276 * Importing Projects::
277 * Project Extension::
278 * External References in Project Files::
279 * Packages in Project Files::
280 * Variables from Imported Projects::
283 * Switches Related to Project Files::
284 * Tools Supporting Project Files::
285 * An Extended Example::
286 * Project File Complete Syntax::
288 Elaboration Order Handling in GNAT
290 * Elaboration Code in Ada 95::
291 * Checking the Elaboration Order in Ada 95::
292 * Controlling the Elaboration Order in Ada 95::
293 * Controlling Elaboration in GNAT - Internal Calls::
294 * Controlling Elaboration in GNAT - External Calls::
295 * Default Behavior in GNAT - Ensuring Safety::
296 * Elaboration Issues for Library Tasks::
297 * Mixing Elaboration Models::
298 * What to Do If the Default Elaboration Behavior Fails::
299 * Elaboration for Access-to-Subprogram Values::
300 * Summary of Procedures for Elaboration Control::
301 * Other Elaboration Order Considerations::
303 The Cross-Referencing Tools gnatxref and gnatfind
305 * gnatxref Switches::
306 * gnatfind Switches::
307 * Project Files for gnatxref and gnatfind::
308 * Regular Expressions in gnatfind and gnatxref::
309 * Examples of gnatxref Usage::
310 * Examples of gnatfind Usage::
312 File Name Krunching Using gnatkr
317 * Examples of gnatkr Usage::
319 Preprocessing Using gnatprep
322 * Switches for gnatprep::
323 * Form of Definitions File::
324 * Form of Input Text for gnatprep::
327 The GNAT Library Browser gnatls
330 * Switches for gnatls::
331 * Examples of gnatls Usage::
336 * Creating an Ada Library::
337 * Installing an Ada Library::
338 * Using an Ada Library::
339 * Creating an Ada Library to be Used in a Non-Ada Context::
340 * Rebuilding the GNAT Run-Time Library::
342 Using the GNU make Utility
344 * Using gnatmake in a Makefile::
345 * Automatically Creating a List of Directories::
346 * Generating the Command Line Switches::
347 * Overcoming Command Line Length Limits::
349 Finding Memory Problems with gnatmem
351 * Running gnatmem (GDB Mode)::
352 * Running gnatmem (GMEM Mode)::
353 * Switches for gnatmem::
354 * Examples of gnatmem Usage::
355 * GDB and GMEM Modes::
356 * Implementation Note::
359 Finding Memory Problems with GNAT Debug Pool
361 Creating Sample Bodies Using gnatstub
364 * Switches for gnatstub::
366 Reducing the Size of Ada Executables with gnatelim
371 * Preparing Tree and Bind Files for gnatelim::
373 * Correcting the List of Eliminate Pragmas::
374 * Making Your Executables Smaller::
375 * Summary of the gnatelim Usage Cycle::
377 Other Utility Programs
379 * Using Other Utility Programs with GNAT::
380 * The gnatpsta Utility Program::
381 * The External Symbol Naming Scheme of GNAT::
382 * Ada Mode for Glide::
383 * Converting Ada Files to html with gnathtml::
386 Running and Debugging Ada Programs
388 * The GNAT Debugger GDB::
390 * Introduction to GDB Commands::
391 * Using Ada Expressions::
392 * Calling User-Defined Subprograms::
393 * Using the Next Command in a Function::
396 * Debugging Generic Units::
397 * GNAT Abnormal Termination or Failure to Terminate::
398 * Naming Conventions for GNAT Source Files::
399 * Getting Internal Debugging Information::
404 * Basic Assembler Syntax::
405 * A Simple Example of Inline Assembler::
406 * Output Variables in Inline Assembler::
407 * Input Variables in Inline Assembler::
408 * Inlining Inline Assembler Code::
409 * Other Asm Functionality::
410 * A Complete Example::
412 Microsoft Windows Topics
414 * Using GNAT on Windows::
416 * CONSOLE and WINDOWS subsystems::
418 * Mixed-Language Programming on Windows::
419 * Windows Calling Conventions::
420 * Introduction to Dynamic Link Libraries (DLLs)::
421 * Using DLLs with GNAT::
422 * Building DLLs with GNAT::
423 * GNAT and Windows Resources::
424 * GNAT and COM/DCOM Objects::
427 Performance Considerations
429 * Controlling Run-Time Checks::
430 * Optimization Levels::
431 * Debugging Optimized Code::
432 * Inlining of Subprograms::
438 @node About This Guide
439 @unnumbered About This Guide
442 This guide describes the use of GNAT, a compiler and software development
443 toolset for the full Ada 95 programming language.
444 It describes the features of the compiler and tools, and details
445 how to use them to build Ada 95 applications.
448 * What This Guide Contains::
449 * What You Should Know before Reading This Guide::
450 * Related Information::
454 @node What This Guide Contains
455 @unnumberedsec What This Guide Contains
458 This guide contains the following chapters:
461 @ref{Getting Started with GNAT}, describes how to get started compiling
462 and running Ada programs with the GNAT Ada programming environment.
464 @ref{The GNAT Compilation Model}, describes the compilation model used
467 @ref{Compiling Using gcc}, describes how to compile
468 Ada programs with @code{gcc}, the Ada compiler.
470 @ref{Binding Using gnatbind}, describes how to
471 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
474 @ref{Linking Using gnatlink},
475 describes @code{gnatlink}, a
476 program that provides for linking using the GNAT run-time library to
477 construct a program. @code{gnatlink} can also incorporate foreign language
478 object units into the executable.
480 @ref{The GNAT Make Program gnatmake}, describes @code{gnatmake}, a
481 utility that automatically determines the set of sources
482 needed by an Ada compilation unit, and executes the necessary compilations
485 @ref{Renaming Files Using gnatchop}, describes
486 @code{gnatchop}, a utility that allows you to preprocess a file that
487 contains Ada source code, and split it into one or more new files, one
488 for each compilation unit.
490 @ref{Configuration Pragmas}, describes the configuration pragmas handled by GNAT.
492 @ref{Handling Arbitrary File Naming Conventions Using gnatname}, shows how to override
493 the default GNAT file naming conventions, either for an individual unit or globally.
495 @ref{GNAT Project Manager}, describes how to use project files to organize large projects.
497 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps you deal with
498 elaboration order issues.
500 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
501 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
502 way to navigate through sources.
504 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
505 file name krunching utility, used to handle shortened
506 file names on operating systems with a limit on the length of names.
508 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
509 preprocessor utility that allows a single source file to be used to
510 generate multiple or parameterized source files, by means of macro
513 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
514 utility that displays information about compiled units, including dependences
515 on the corresponding sources files, and consistency of compilations.
517 @ref{GNAT and Libraries}, describes the process of creating and using
518 Libraries with GNAT. It also describes how to recompile the GNAT run-time
522 @ref{Using the GNU make Utility}, describes some techniques for using
523 the GNAT toolset in Makefiles.
526 @ref{Finding Memory Problems with gnatmem}, describes @code{gnatmem}, a
527 utility that monitors dynamic allocation and deallocation activity in a
528 program, and displays information about incorrect deallocations and sources
529 of possible memory leaks.
531 @ref{Finding Memory Problems with GNAT Debug Pool}, describes how to
532 use the GNAT-specific Debug Pool in order to detect as early as possible
533 the use of incorrect memory references.
536 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
537 a utility that generates empty but compilable bodies for library units.
540 @ref{Reducing the Size of Ada Executables with gnatelim}, describes
541 @code{gnatelim}, a tool which detects unused subprograms and helps
542 the compiler to create a smaller executable for the program.
545 @ref{Other Utility Programs}, discusses several other GNAT utilities,
546 including @code{gnatpsta}.
549 @ref{Running and Debugging Ada Programs}, describes how to run and debug
553 @ref{Inline Assembler}, shows how to use the inline assembly facility in an Ada program.
557 @ref{Performance Considerations}, reviews the trade offs between using
558 defaults or options in program development.
561 @node What You Should Know before Reading This Guide
562 @unnumberedsec What You Should Know before Reading This Guide
564 @cindex Ada 95 Language Reference Manual
566 This user's guide assumes that you are familiar with Ada 95 language, as
567 described in the International Standard ANSI/ISO/IEC-8652:1995, Jan
570 @node Related Information
571 @unnumberedsec Related Information
574 For further information about related tools, refer to the following
579 @cite{GNAT Reference Manual}, which contains all reference
580 material for the GNAT implementation of Ada 95.
583 @cite{Ada 95 Language Reference Manual}, which contains all reference
584 material for the Ada 95 programming language.
587 @cite{Debugging with GDB}
588 contains all details on the use of the GNU source-level debugger.
591 @cite{GNU Emacs Manual}
592 contains full information on the extensible editor and programming
598 @unnumberedsec Conventions
600 @cindex Typographical conventions
603 Following are examples of the typographical and graphic conventions used
608 @code{Functions}, @code{utility program names}, @code{standard names},
615 @file{File Names}, @file{button names}, and @file{field names}.
624 [optional information or parameters]
627 Examples are described by text
629 and then shown this way.
634 Commands that are entered by the user are preceded in this manual by the
635 characters @w{"@code{$ }"} (dollar sign followed by space). If your system
636 uses this sequence as a prompt, then the commands will appear exactly as
637 you see them in the manual. If your system uses some other prompt, then
638 the command will appear with the @code{$} replaced by whatever prompt
639 character you are using.
642 @node Getting Started with GNAT
643 @chapter Getting Started with GNAT
646 This chapter describes some simple ways of using GNAT to build
647 executable Ada programs.
651 * Running a Simple Ada Program::
653 * Running a Program with Multiple Units::
655 * Using the gnatmake Utility::
656 * Introduction to Glide and GVD::
660 @section Running GNAT
663 Three steps are needed to create an executable file from an Ada source
668 The source file(s) must be compiled.
670 The file(s) must be bound using the GNAT binder.
672 All appropriate object files must be linked to produce an executable.
676 All three steps are most commonly handled by using the @code{gnatmake}
677 utility program that, given the name of the main program, automatically
678 performs the necessary compilation, binding and linking steps.
680 @node Running a Simple Ada Program
681 @section Running a Simple Ada Program
684 Any text editor may be used to prepare an Ada program. If @code{Glide} is
685 used, the optional Ada mode may be helpful in laying out the program. The
686 program text is a normal text file. We will suppose in our initial
687 example that you have used your editor to prepare the following
688 standard format text file:
693 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
694 @b{procedure} Hello @b{is}
696 Put_Line ("Hello WORLD!");
703 This file should be named @file{hello.adb}.
704 With the normal default file naming conventions, GNAT requires
706 contain a single compilation unit whose file name is the
708 with periods replaced by hyphens; the
709 extension is @file{ads} for a
710 spec and @file{adb} for a body.
711 You can override this default file naming convention by use of the
712 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
713 Alternatively, if you want to rename your files according to this default
714 convention, which is probably more convenient if you will be using GNAT
715 for all your compilations, then the @code{gnatchop} utility
716 can be used to generate correctly-named source files
717 (@pxref{Renaming Files Using gnatchop}).
719 You can compile the program using the following command (@code{$} is used
720 as the command prompt in the examples in this document):
728 @code{gcc} is the command used to run the compiler. This compiler is
729 capable of compiling programs in several languages, including Ada 95 and
730 C. It assumes that you have given it an Ada program if the file extension is
731 either @file{.ads} or @file{.adb}, and it will then call the GNAT compiler to compile
734 The @option{-c} switch is required. It tells @command{gcc} to only do a
735 compilation. (For C programs, @command{gcc} can also do linking, but this
736 capability is not used directly for Ada programs, so the @option{-c}
737 switch must always be present.)
739 This compile command generates a file
740 @file{hello.o}, which is the object
741 file corresponding to your Ada program. It also generates an "Ada Library Information" file
743 which contains additional information used to check
744 that an Ada program is consistent.
745 To build an executable file,
746 use @code{gnatbind} to bind the program
747 and @code{gnatlink} to link it. The
748 argument to both @code{gnatbind} and @code{gnatlink} is the name of the
749 @file{ali} file, but the default extension of @file{.ali} can
750 be omitted. This means that in the most common case, the argument
751 is simply the name of the main program:
760 A simpler method of carrying out these steps is to use
762 a master program that invokes all the required
763 compilation, binding and linking tools in the correct order. In particular,
764 @command{gnatmake} automatically recompiles any sources that have been modified
765 since they were last compiled, or sources that depend
766 on such modified sources, so that "version skew" is avoided.
767 @cindex Version skew (avoided by @command{gnatmake})
775 The result is an executable program called @file{hello}, which can be
778 @c The following should be removed (BMB 2001-01-23)
788 assuming that the current directory is on the search path for executable programs.
791 and, if all has gone well, you will see
798 appear in response to this command.
803 @node Running a Program with Multiple Units
804 @section Running a Program with Multiple Units
807 Consider a slightly more complicated example that has three files: a
808 main program, and the spec and body of a package:
813 @b{package} Greetings @b{is}
815 @b{procedure} Goodbye;
818 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
819 @b{package} @b{body} Greetings @b{is}
820 @b{procedure} Hello @b{is}
822 Put_Line ("Hello WORLD!");
825 @b{procedure} Goodbye @b{is}
827 Put_Line ("Goodbye WORLD!");
834 @b{procedure} Gmain @b{is}
844 Following the one-unit-per-file rule, place this program in the
845 following three separate files:
849 spec of package @code{Greetings}
852 body of package @code{Greetings}
859 To build an executable version of
860 this program, we could use four separate steps to compile, bind, and link
861 the program, as follows:
865 $ gcc -c greetings.adb
872 Note that there is no required order of compilation when using GNAT.
873 In particular it is perfectly fine to compile the main program first.
874 Also, it is not necessary to compile package specs in the case where
875 there is an accompanying body; you only need to compile the body. If you want
876 to submit these files to the compiler for semantic checking and not code generation,
878 @option{-gnatc} switch:
881 $ gcc -c greetings.ads -gnatc
886 Although the compilation can be done in separate steps as in the
887 above example, in practice it is almost always more convenient
888 to use the @code{gnatmake} tool. All you need to know in this case
889 is the name of the main program's source file. The effect of the above four
890 commands can be achieved with a single one:
898 In the next section we discuss the advantages of using @code{gnatmake} in
901 @node Using the gnatmake Utility
902 @section Using the @command{gnatmake} Utility
905 If you work on a program by compiling single components at a time using
906 @code{gcc}, you typically keep track of the units you modify. In order to
907 build a consistent system, you compile not only these units, but also any
908 units that depend on the units you have modified.
909 For example, in the preceding case,
910 if you edit @file{gmain.adb}, you only need to recompile that file. But if
911 you edit @file{greetings.ads}, you must recompile both
912 @file{greetings.adb} and @file{gmain.adb}, because both files contain
913 units that depend on @file{greetings.ads}.
915 @code{gnatbind} will warn you if you forget one of these compilation
916 steps, so that it is impossible to generate an inconsistent program as a
917 result of forgetting to do a compilation. Nevertheless it is tedious and
918 error-prone to keep track of dependencies among units.
919 One approach to handle the dependency-bookkeeping is to use a
920 makefile. However, makefiles present maintenance problems of their own:
921 if the dependencies change as you change the program, you must make
922 sure that the makefile is kept up-to-date manually, which is also an
925 The @code{gnatmake} utility takes care of these details automatically.
926 Invoke it using either one of the following forms:
935 The argument is the name of the file containing the main program;
936 you may omit the extension. @code{gnatmake}
937 examines the environment, automatically recompiles any files that need
938 recompiling, and binds and links the resulting set of object files,
939 generating the executable file, @file{gmain}.
940 In a large program, it
941 can be extremely helpful to use @code{gnatmake}, because working out by hand
942 what needs to be recompiled can be difficult.
944 Note that @code{gnatmake}
945 takes into account all the Ada 95 rules that
946 establish dependencies among units. These include dependencies that result
947 from inlining subprogram bodies, and from
948 generic instantiation. Unlike some other
949 Ada make tools, @code{gnatmake} does not rely on the dependencies that were
950 found by the compiler on a previous compilation, which may possibly
951 be wrong when sources change. @code{gnatmake} determines the exact set of
952 dependencies from scratch each time it is run.
955 @node Introduction to Glide and GVD
956 @section Introduction to Glide and GVD
960 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.
963 * Building a New Program with Glide::
964 * Simple Debugging with GVD::
965 * Other Glide Features::
968 @node Building a New Program with Glide
969 @subsection Building a New Program with Glide
971 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:
978 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
991 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.
993 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.
995 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:
997 with Ada.Text_IO; use Ada.Text_IO;
1003 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.
1005 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.
1007 Next enter the statement (with an intentional error, a missing semicolon) that will form the body of the loop:
1009 Put_Line("Hello, World" & Integer'Image(I))
1013 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.
1015 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.
1017 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.
1019 To execute the program, choose @code{Ada} and then @code{Run}. You should see the program's output displayed in the bottom window:
1029 @node Simple Debugging with GVD
1030 @subsection Simple Debugging with GVD
1033 This section describes how to set breakpoints, examine/modify variables, and step through execution.
1035 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:
1042 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}.
1044 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.
1046 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.
1048 For this example, set a breakpoint at the statement where @code{Put_Line} is invoked.
1050 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.
1052 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.
1054 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.
1056 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}.
1058 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.
1061 @node Other Glide Features
1062 @subsection Other Glide Features
1065 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...}.
1067 To abort a Glide command, type @key{Ctrl-g}.
1069 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:
1076 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.
1078 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}.
1080 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:
1082 @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)
1083 @item With the focus in one of the windows, select the desired buffer from the @code{Buffers} menu
1087 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1089 @node The GNAT Compilation Model
1090 @chapter The GNAT Compilation Model
1091 @cindex GNAT compilation model
1092 @cindex Compilation model
1095 * Source Representation::
1096 * Foreign Language Representation::
1097 * File Naming Rules::
1098 * Using Other File Names::
1099 * Alternative File Naming Schemes::
1100 * Generating Object Files::
1101 * Source Dependencies::
1102 * The Ada Library Information Files::
1103 * Binding an Ada Program::
1104 * Mixed Language Programming::
1105 * Building Mixed Ada & C++ Programs::
1106 * Comparison between GNAT and C/C++ Compilation Models::
1107 * Comparison between GNAT and Conventional Ada Library Models::
1111 This chapter describes the compilation model used by GNAT. Although
1112 similar to that used by other languages, such as C and C++, this model
1113 is substantially different from the traditional Ada compilation models,
1114 which are based on a library. The model is initially described without
1115 reference to the library-based model. If you have not previously used an
1116 Ada compiler, you need only read the first part of this chapter. The
1117 last section describes and discusses the differences between the GNAT
1118 model and the traditional Ada compiler models. If you have used other
1119 Ada compilers, this section will help you to understand those
1120 differences, and the advantages of the GNAT model.
1122 @node Source Representation
1123 @section Source Representation
1127 Ada source programs are represented in standard text files, using
1128 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1129 7-bit ASCII set, plus additional characters used for
1130 representing foreign languages (@pxref{Foreign Language Representation}
1131 for support of non-USA character sets). The format effector characters
1132 are represented using their standard ASCII encodings, as follows:
1137 Vertical tab, @code{16#0B#}
1141 Horizontal tab, @code{16#09#}
1145 Carriage return, @code{16#0D#}
1149 Line feed, @code{16#0A#}
1153 Form feed, @code{16#0C#}
1157 Source files are in standard text file format. In addition, GNAT will
1158 recognize a wide variety of stream formats, in which the end of physical
1159 physical lines is marked by any of the following sequences:
1160 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1161 in accommodating files that are imported from other operating systems.
1163 @cindex End of source file
1164 @cindex Source file, end
1166 The end of a source file is normally represented by the physical end of
1167 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1168 recognized as signalling the end of the source file. Again, this is
1169 provided for compatibility with other operating systems where this
1170 code is used to represent the end of file.
1172 Each file contains a single Ada compilation unit, including any pragmas
1173 associated with the unit. For example, this means you must place a
1174 package declaration (a package @dfn{spec}) and the corresponding body in
1175 separate files. An Ada @dfn{compilation} (which is a sequence of
1176 compilation units) is represented using a sequence of files. Similarly,
1177 you will place each subunit or child unit in a separate file.
1179 @node Foreign Language Representation
1180 @section Foreign Language Representation
1183 GNAT supports the standard character sets defined in Ada 95 as well as
1184 several other non-standard character sets for use in localized versions
1185 of the compiler (@pxref{Character Set Control}).
1188 * Other 8-Bit Codes::
1189 * Wide Character Encodings::
1197 The basic character set is Latin-1. This character set is defined by ISO
1198 standard 8859, part 1. The lower half (character codes @code{16#00#}
1199 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half is
1200 used to represent additional characters. These include extended letters
1201 used by European languages, such as French accents, the vowels with umlauts
1202 used in German, and the extra letter A-ring used in Swedish.
1204 @findex Ada.Characters.Latin_1
1205 For a complete list of Latin-1 codes and their encodings, see the source
1206 file of library unit @code{Ada.Characters.Latin_1} in file
1207 @file{a-chlat1.ads}.
1208 You may use any of these extended characters freely in character or
1209 string literals. In addition, the extended characters that represent
1210 letters can be used in identifiers.
1212 @node Other 8-Bit Codes
1213 @subsection Other 8-Bit Codes
1216 GNAT also supports several other 8-bit coding schemes:
1221 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1226 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1231 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1237 Latin-4 letters (Cyrillic) allowed in identifiers, with uppercase and lowercase
1240 @item IBM PC (code page 437)
1241 @cindex code page 437
1242 This code page is the normal default for PCs in the U.S. It corresponds
1243 to the original IBM PC character set. This set has some, but not all, of
1244 the extended Latin-1 letters, but these letters do not have the same
1245 encoding as Latin-1. In this mode, these letters are allowed in
1246 identifiers with uppercase and lowercase equivalence.
1248 @item IBM PC (code page 850)
1249 @cindex code page 850
1250 This code page is a modification of 437 extended to include all the
1251 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1252 mode, all these letters are allowed in identifiers with uppercase and
1253 lowercase equivalence.
1255 @item Full Upper 8-bit
1256 Any character in the range 80-FF allowed in identifiers, and all are
1257 considered distinct. In other words, there are no uppercase and lowercase
1258 equivalences in this range. This is useful in conjunction with
1259 certain encoding schemes used for some foreign character sets (e.g.
1260 the typical method of representing Chinese characters on the PC).
1263 No upper-half characters in the range 80-FF are allowed in identifiers.
1264 This gives Ada 83 compatibility for identifier names.
1268 For precise data on the encodings permitted, and the uppercase and lowercase
1269 equivalences that are recognized, see the file @file{csets.adb} in
1270 the GNAT compiler sources. You will need to obtain a full source release
1271 of GNAT to obtain this file.
1273 @node Wide Character Encodings
1274 @subsection Wide Character Encodings
1277 GNAT allows wide character codes to appear in character and string
1278 literals, and also optionally in identifiers, by means of the following
1279 possible encoding schemes:
1284 In this encoding, a wide character is represented by the following five
1292 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1293 characters (using uppercase letters) of the wide character code. For
1294 example, ESC A345 is used to represent the wide character with code
1296 This scheme is compatible with use of the full Wide_Character set.
1298 @item Upper-Half Coding
1299 @cindex Upper-Half Coding
1300 The wide character with encoding @code{16#abcd#} where the upper bit is on (in
1301 other words, "a" is in the range 8-F) is represented as two bytes,
1302 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1303 character, but is not required to be in the upper half. This method can
1304 be also used for shift-JIS or EUC, where the internal coding matches the
1307 @item Shift JIS Coding
1308 @cindex Shift JIS Coding
1309 A wide character is represented by a two-character sequence,
1311 @code{16#cd#}, with the restrictions described for upper-half encoding as
1312 described above. The internal character code is the corresponding JIS
1313 character according to the standard algorithm for Shift-JIS
1314 conversion. Only characters defined in the JIS code set table can be
1315 used with this encoding method.
1319 A wide character is represented by a two-character sequence
1321 @code{16#cd#}, with both characters being in the upper half. The internal
1322 character code is the corresponding JIS character according to the EUC
1323 encoding algorithm. Only characters defined in the JIS code set table
1324 can be used with this encoding method.
1327 A wide character is represented using
1328 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1329 10646-1/Am.2. Depending on the character value, the representation
1330 is a one, two, or three byte sequence:
1335 16#0000#-16#007f#: 2#0xxxxxxx#
1336 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
1337 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1342 where the xxx bits correspond to the left-padded bits of the
1343 16-bit character value. Note that all lower half ASCII characters
1344 are represented as ASCII bytes and all upper half characters and
1345 other wide characters are represented as sequences of upper-half
1346 (The full UTF-8 scheme allows for encoding 31-bit characters as
1347 6-byte sequences, but in this implementation, all UTF-8 sequences
1348 of four or more bytes length will be treated as illegal).
1349 @item Brackets Coding
1350 In this encoding, a wide character is represented by the following eight
1358 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1359 characters (using uppercase letters) of the wide character code. For
1360 example, ["A345"] is used to represent the wide character with code
1361 @code{16#A345#}. It is also possible (though not required) to use the
1362 Brackets coding for upper half characters. For example, the code
1363 @code{16#A3#} can be represented as @code{["A3"]}.
1365 This scheme is compatible with use of the full Wide_Character set,
1366 and is also the method used for wide character encoding in the standard
1367 ACVC (Ada Compiler Validation Capability) test suite distributions.
1372 Note: Some of these coding schemes do not permit the full use of the
1373 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
1374 use of the upper half of the Latin-1 set.
1376 @node File Naming Rules
1377 @section File Naming Rules
1380 The default file name is determined by the name of the unit that the
1381 file contains. The name is formed by taking the full expanded name of
1382 the unit and replacing the separating dots with hyphens and using
1383 lowercase for all letters.
1385 An exception arises if the file name generated by the above rules starts
1386 with one of the characters
1388 and the second character is a
1389 minus. In this case, the character tilde is used in place
1390 of the minus. The reason for this special rule is to avoid clashes with
1391 the standard names for child units of the packages System, Ada,
1392 Interfaces, and GNAT, which use the prefixes
1396 The file extension is @file{.ads} for a spec and
1397 @file{.adb} for a body. The following list shows some
1398 examples of these rules.
1405 @item arith_functions.ads
1406 Arith_Functions (package spec)
1407 @item arith_functions.adb
1408 Arith_Functions (package body)
1410 Func.Spec (child package spec)
1412 Func.Spec (child package body)
1414 Sub (subunit of Main)
1416 A.Bad (child package body)
1420 Following these rules can result in excessively long
1421 file names if corresponding
1422 unit names are long (for example, if child units or subunits are
1423 heavily nested). An option is available to shorten such long file names
1424 (called file name "krunching"). This may be particularly useful when
1425 programs being developed with GNAT are to be used on operating systems
1426 with limited file name lengths. @xref{Using gnatkr}.
1428 Of course, no file shortening algorithm can guarantee uniqueness over
1429 all possible unit names; if file name krunching is used, it is your
1430 responsibility to ensure no name clashes occur. Alternatively you
1431 can specify the exact file names that you want used, as described
1432 in the next section. Finally, if your Ada programs are migrating from a
1433 compiler with a different naming convention, you can use the gnatchop
1434 utility to produce source files that follow the GNAT naming conventions.
1435 (For details @pxref{Renaming Files Using gnatchop}.)
1437 @node Using Other File Names
1438 @section Using Other File Names
1442 In the previous section, we have described the default rules used by
1443 GNAT to determine the file name in which a given unit resides. It is
1444 often convenient to follow these default rules, and if you follow them,
1445 the compiler knows without being explicitly told where to find all
1448 However, in some cases, particularly when a program is imported from
1449 another Ada compiler environment, it may be more convenient for the
1450 programmer to specify which file names contain which units. GNAT allows
1451 arbitrary file names to be used by means of the Source_File_Name pragma.
1452 The form of this pragma is as shown in the following examples:
1453 @cindex Source_File_Name pragma
1458 @b{pragma} Source_File_Name (My_Utilities.Stacks,
1459 Spec_File_Name => "myutilst_a.ada");
1460 @b{pragma} Source_File_name (My_Utilities.Stacks,
1461 Body_File_Name => "myutilst.ada");
1467 As shown in this example, the first argument for the pragma is the unit
1468 name (in this example a child unit). The second argument has the form
1469 of a named association. The identifier
1470 indicates whether the file name is for a spec or a body;
1471 the file name itself is given by a string literal.
1473 The source file name pragma is a configuration pragma, which means that
1474 normally it will be placed in the @file{gnat.adc}
1475 file used to hold configuration
1476 pragmas that apply to a complete compilation environment.
1477 For more details on how the @file{gnat.adc} file is created and used
1478 @pxref{Handling of Configuration Pragmas}
1479 @cindex @file{gnat.adc}
1481 GNAT allows completely arbitrary file names to be specified using the
1482 source file name pragma. However, if the file name specified has an
1483 extension other than @file{.ads} or @file{.adb} it is necessary to use a special
1484 syntax when compiling the file. The name in this case must be preceded
1485 by the special sequence @code{-x} followed by a space and the name of the
1486 language, here @code{ada}, as in:
1489 $ gcc -c -x ada peculiar_file_name.sim
1493 @code{gnatmake} handles non-standard file names in the usual manner (the
1494 non-standard file name for the main program is simply used as the
1495 argument to gnatmake). Note that if the extension is also non-standard,
1496 then it must be included in the gnatmake command, it may not be omitted.
1498 @node Alternative File Naming Schemes
1499 @section Alternative File Naming Schemes
1500 @cindex File naming schemes, alternative
1503 In the previous section, we described the use of the @code{Source_File_Name}
1504 pragma to allow arbitrary names to be assigned to individual source files.
1505 However, this approach requires one pragma for each file, and especially in
1506 large systems can result in very long @file{gnat.adc} files, and also create
1507 a maintenance problem.
1509 GNAT also provides a facility for specifying systematic file naming schemes
1510 other than the standard default naming scheme previously described. An
1511 alternative scheme for naming is specified by the use of
1512 @code{Source_File_Name} pragmas having the following format:
1513 @cindex Source_File_Name pragma
1516 pragma Source_File_Name (
1517 Spec_File_Name => FILE_NAME_PATTERN
1518 [,Casing => CASING_SPEC]
1519 [,Dot_Replacement => STRING_LITERAL]);
1521 pragma Source_File_Name (
1522 Body_File_Name => FILE_NAME_PATTERN
1523 [,Casing => CASING_SPEC]
1524 [,Dot_Replacement => STRING_LITERAL]);
1526 pragma Source_File_Name (
1527 Subunit_File_Name => FILE_NAME_PATTERN
1528 [,Casing => CASING_SPEC]
1529 [,Dot_Replacement => STRING_LITERAL]);
1531 FILE_NAME_PATTERN ::= STRING_LITERAL
1532 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1537 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1538 It contains a single asterisk character, and the unit name is substituted
1539 systematically for this asterisk. The optional parameter
1540 @code{Casing} indicates
1541 whether the unit name is to be all upper-case letters, all lower-case letters,
1542 or mixed-case. If no
1543 @code{Casing} parameter is used, then the default is all
1546 The optional @code{Dot_Replacement} string is used to replace any periods
1547 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1548 argument is used then separating dots appear unchanged in the resulting
1550 Although the above syntax indicates that the
1551 @code{Casing} argument must appear
1552 before the @code{Dot_Replacement} argument, but it
1553 is also permissible to write these arguments in the opposite order.
1555 As indicated, it is possible to specify different naming schemes for
1556 bodies, specs, and subunits. Quite often the rule for subunits is the
1557 same as the rule for bodies, in which case, there is no need to give
1558 a separate @code{Subunit_File_Name} rule, and in this case the
1559 @code{Body_File_name} rule is used for subunits as well.
1561 The separate rule for subunits can also be used to implement the rather
1562 unusual case of a compilation environment (e.g. a single directory) which
1563 contains a subunit and a child unit with the same unit name. Although
1564 both units cannot appear in the same partition, the Ada Reference Manual
1565 allows (but does not require) the possibility of the two units coexisting
1566 in the same environment.
1568 The file name translation works in the following steps:
1573 If there is a specific @code{Source_File_Name} pragma for the given unit,
1574 then this is always used, and any general pattern rules are ignored.
1577 If there is a pattern type @code{Source_File_Name} pragma that applies to
1578 the unit, then the resulting file name will be used if the file exists. If
1579 more than one pattern matches, the latest one will be tried first, and the
1580 first attempt resulting in a reference to a file that exists will be used.
1583 If no pattern type @code{Source_File_Name} pragma that applies to the unit
1584 for which the corresponding file exists, then the standard GNAT default
1585 naming rules are used.
1590 As an example of the use of this mechanism, consider a commonly used scheme
1591 in which file names are all lower case, with separating periods copied
1592 unchanged to the resulting file name, and specs end with ".1.ada", and
1593 bodies end with ".2.ada". GNAT will follow this scheme if the following
1597 pragma Source_File_Name
1598 (Spec_File_Name => "*.1.ada");
1599 pragma Source_File_Name
1600 (Body_File_Name => "*.2.ada");
1604 The default GNAT scheme is actually implemented by providing the following
1605 default pragmas internally:
1608 pragma Source_File_Name
1609 (Spec_File_Name => "*.ads", Dot_Replacement => "-");
1610 pragma Source_File_Name
1611 (Body_File_Name => "*.adb", Dot_Replacement => "-");
1615 Our final example implements a scheme typically used with one of the
1616 Ada 83 compilers, where the separator character for subunits was "__"
1617 (two underscores), specs were identified by adding @file{_.ADA}, bodies
1618 by adding @file{.ADA}, and subunits by
1619 adding @file{.SEP}. All file names were
1620 upper case. Child units were not present of course since this was an
1621 Ada 83 compiler, but it seems reasonable to extend this scheme to use
1622 the same double underscore separator for child units.
1625 pragma Source_File_Name
1626 (Spec_File_Name => "*_.ADA",
1627 Dot_Replacement => "__",
1628 Casing = Uppercase);
1629 pragma Source_File_Name
1630 (Body_File_Name => "*.ADA",
1631 Dot_Replacement => "__",
1632 Casing = Uppercase);
1633 pragma Source_File_Name
1634 (Subunit_File_Name => "*.SEP",
1635 Dot_Replacement => "__",
1636 Casing = Uppercase);
1639 @node Generating Object Files
1640 @section Generating Object Files
1643 An Ada program consists of a set of source files, and the first step in
1644 compiling the program is to generate the corresponding object files.
1645 These are generated by compiling a subset of these source files.
1646 The files you need to compile are the following:
1650 If a package spec has no body, compile the package spec to produce the
1651 object file for the package.
1654 If a package has both a spec and a body, compile the body to produce the
1655 object file for the package. The source file for the package spec need
1656 not be compiled in this case because there is only one object file, which
1657 contains the code for both the spec and body of the package.
1660 For a subprogram, compile the subprogram body to produce the object file
1661 for the subprogram. The spec, if one is present, is as usual in a
1662 separate file, and need not be compiled.
1666 In the case of subunits, only compile the parent unit. A single object
1667 file is generated for the entire subunit tree, which includes all the
1671 Compile child units independently of their parent units
1672 (though, of course, the spec of all the ancestor unit must be present in order
1673 to compile a child unit).
1677 Compile generic units in the same manner as any other units. The object
1678 files in this case are small dummy files that contain at most the
1679 flag used for elaboration checking. This is because GNAT always handles generic
1680 instantiation by means of macro expansion. However, it is still necessary to
1681 compile generic units, for dependency checking and elaboration purposes.
1685 The preceding rules describe the set of files that must be compiled to
1686 generate the object files for a program. Each object file has the same
1687 name as the corresponding source file, except that the extension is
1690 You may wish to compile other files for the purpose of checking their
1691 syntactic and semantic correctness. For example, in the case where a
1692 package has a separate spec and body, you would not normally compile the
1693 spec. However, it is convenient in practice to compile the spec to make
1694 sure it is error-free before compiling clients of this spec, because such
1695 compilations will fail if there is an error in the spec.
1697 GNAT provides an option for compiling such files purely for the
1698 purposes of checking correctness; such compilations are not required as
1699 part of the process of building a program. To compile a file in this
1700 checking mode, use the @option{-gnatc} switch.
1702 @node Source Dependencies
1703 @section Source Dependencies
1706 A given object file clearly depends on the source file which is compiled
1707 to produce it. Here we are using @dfn{depends} in the sense of a typical
1708 @code{make} utility; in other words, an object file depends on a source
1709 file if changes to the source file require the object file to be
1711 In addition to this basic dependency, a given object may depend on
1712 additional source files as follows:
1716 If a file being compiled @code{with}'s a unit @var{X}, the object file
1717 depends on the file containing the spec of unit @var{X}. This includes
1718 files that are @code{with}'ed implicitly either because they are parents
1719 of @code{with}'ed child units or they are run-time units required by the
1720 language constructs used in a particular unit.
1723 If a file being compiled instantiates a library level generic unit, the
1724 object file depends on both the spec and body files for this generic
1728 If a file being compiled instantiates a generic unit defined within a
1729 package, the object file depends on the body file for the package as
1730 well as the spec file.
1734 @cindex @option{-gnatn} switch
1735 If a file being compiled contains a call to a subprogram for which
1736 pragma @code{Inline} applies and inlining is activated with the
1737 @option{-gnatn} switch, the object file depends on the file containing the
1738 body of this subprogram as well as on the file containing the spec. Note
1739 that for inlining to actually occur as a result of the use of this switch,
1740 it is necessary to compile in optimizing mode.
1742 @cindex @option{-gnatN} switch
1743 The use of @option{-gnatN} activates a more extensive inlining optimization
1744 that is performed by the front end of the compiler. This inlining does
1745 not require that the code generation be optimized. Like @option{-gnatn},
1746 the use of this switch generates additional dependencies.
1749 If an object file O depends on the proper body of a subunit through inlining
1750 or instantiation, it depends on the parent unit of the subunit. This means that
1751 any modification of the parent unit or one of its subunits affects the
1755 The object file for a parent unit depends on all its subunit body files.
1758 The previous two rules meant that for purposes of computing dependencies and
1759 recompilation, a body and all its subunits are treated as an indivisible whole.
1762 These rules are applied transitively: if unit @code{A} @code{with}'s
1763 unit @code{B}, whose elaboration calls an inlined procedure in package
1764 @code{C}, the object file for unit @code{A} will depend on the body of
1765 @code{C}, in file @file{c.adb}.
1767 The set of dependent files described by these rules includes all the
1768 files on which the unit is semantically dependent, as described in the
1769 Ada 95 Language Reference Manual. However, it is a superset of what the
1770 ARM describes, because it includes generic, inline, and subunit dependencies.
1772 An object file must be recreated by recompiling the corresponding source
1773 file if any of the source files on which it depends are modified. For
1774 example, if the @code{make} utility is used to control compilation,
1775 the rule for an Ada object file must mention all the source files on
1776 which the object file depends, according to the above definition.
1777 The determination of the necessary
1778 recompilations is done automatically when one uses @code{gnatmake}.
1781 @node The Ada Library Information Files
1782 @section The Ada Library Information Files
1783 @cindex Ada Library Information files
1784 @cindex @file{ali} files
1787 Each compilation actually generates two output files. The first of these
1788 is the normal object file that has a @file{.o} extension. The second is a
1789 text file containing full dependency information. It has the same
1790 name as the source file, but an @file{.ali} extension.
1791 This file is known as the Ada Library Information (@file{ali}) file.
1792 The following information is contained in the @file{ali} file.
1796 Version information (indicates which version of GNAT was used to compile
1797 the unit(s) in question)
1800 Main program information (including priority and time slice settings,
1801 as well as the wide character encoding used during compilation).
1804 List of arguments used in the @code{gcc} command for the compilation
1807 Attributes of the unit, including configuration pragmas used, an indication
1808 of whether the compilation was successful, exception model used etc.
1811 A list of relevant restrictions applying to the unit (used for consistency)
1815 Categorization information (e.g. use of pragma @code{Pure}).
1818 Information on all @code{with}'ed units, including presence of
1819 @code{Elaborate} or @code{Elaborate_All} pragmas.
1822 Information from any @code{Linker_Options} pragmas used in the unit
1825 Information on the use of @code{Body_Version} or @code{Version}
1826 attributes in the unit.
1829 Dependency information. This is a list of files, together with
1830 time stamp and checksum information. These are files on which
1831 the unit depends in the sense that recompilation is required
1832 if any of these units are modified.
1835 Cross-reference data. Contains information on all entities referenced
1836 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
1837 provide cross-reference information.
1842 For a full detailed description of the format of the @file{ali} file,
1843 see the source of the body of unit @code{Lib.Writ}, contained in file
1844 @file{lib-writ.adb} in the GNAT compiler sources.
1846 @node Binding an Ada Program
1847 @section Binding an Ada Program
1850 When using languages such as C and C++, once the source files have been
1851 compiled the only remaining step in building an executable program
1852 is linking the object modules together. This means that it is possible to
1853 link an inconsistent version of a program, in which two units have
1854 included different versions of the same header.
1856 The rules of Ada do not permit such an inconsistent program to be built.
1857 For example, if two clients have different versions of the same package,
1858 it is illegal to build a program containing these two clients.
1859 These rules are enforced by the GNAT binder, which also determines an
1860 elaboration order consistent with the Ada rules.
1862 The GNAT binder is run after all the object files for a program have
1863 been created. It is given the name of the main program unit, and from
1864 this it determines the set of units required by the program, by reading the
1865 corresponding ALI files. It generates error messages if the program is
1866 inconsistent or if no valid order of elaboration exists.
1868 If no errors are detected, the binder produces a main program, in Ada by
1869 default, that contains calls to the elaboration procedures of those
1870 compilation unit that require them, followed by
1871 a call to the main program. This Ada program is compiled to generate the
1872 object file for the main program. The name of
1873 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
1874 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
1877 Finally, the linker is used to build the resulting executable program,
1878 using the object from the main program from the bind step as well as the
1879 object files for the Ada units of the program.
1881 @node Mixed Language Programming
1882 @section Mixed Language Programming
1883 @cindex Mixed Language Programming
1886 * Interfacing to C::
1887 * Calling Conventions::
1890 @node Interfacing to C
1891 @subsection Interfacing to C
1893 There are two ways to
1894 build a program that contains some Ada files and some other language
1895 files depending on whether the main program is in Ada or not.
1896 If the main program is in Ada, you should proceed as follows:
1900 Compile the other language files to generate object files. For instance:
1907 Compile the Ada units to produce a set of object files and ALI
1908 files. For instance:
1910 gnatmake -c my_main.adb
1914 Run the Ada binder on the Ada main program. For instance:
1916 gnatbind my_main.ali
1920 Link the Ada main program, the Ada objects and the other language
1921 objects. For instance:
1923 gnatlink my_main.ali file1.o file2.o
1927 The three last steps can be grouped in a single command:
1929 gnatmake my_main.adb -largs file1.o file2.o
1932 @cindex Binder output file
1934 If the main program is in some language other than Ada, you may
1935 have more than one entry point in the Ada subsystem. You must use a
1936 special option of the binder to generate callable routines to initialize
1937 and finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
1938 Calls to the initialization and finalization routines must be inserted in
1939 the main program, or some other appropriate point in the code. The call to
1940 initialize the Ada units must occur before the first Ada subprogram is
1941 called, and the call to finalize the Ada units must occur after the last
1942 Ada subprogram returns. You use the same procedure for building the
1943 program as described previously. In this case, however, the binder
1944 only places the initialization and finalization subprograms into file
1945 @file{b~@var{xxx}.adb} instead of the main program.
1946 So, if the main program is not in Ada, you should proceed as follows:
1950 Compile the other language files to generate object files. For instance:
1957 Compile the Ada units to produce a set of object files and ALI
1958 files. For instance:
1960 gnatmake -c entry_point1.adb
1961 gnatmake -c entry_point2.adb
1965 Run the Ada binder on the Ada main program. For instance:
1967 gnatbind -n entry_point1.ali entry_point2.ali
1971 Link the Ada main program, the Ada objects and the other language
1972 objects. You only need to give the last entry point here. For instance:
1974 gnatlink entry_point2.ali file1.o file2.o
1978 @node Calling Conventions
1979 @subsection Calling Conventions
1980 @cindex Foreign Languages
1981 @cindex Calling Conventions
1982 GNAT follows standard calling sequence conventions and will thus interface
1983 to any other language that also follows these conventions. The following
1984 Convention identifiers are recognized by GNAT:
1987 @cindex Interfacing to Ada
1988 @cindex Other Ada compilers
1989 @cindex Convention Ada
1991 Ada. This indicates that the standard Ada calling sequence will be
1992 used and all Ada data items may be passed without any limitations in the
1993 case where GNAT is used to generate both the caller and callee. It is also
1994 possible to mix GNAT generated code and code generated by another Ada
1995 compiler. In this case, the data types should be restricted to simple
1996 cases, including primitive types. Whether complex data types can be passed
1997 depends on the situation. Probably it is safe to pass simple arrays, such
1998 as arrays of integers or floats. Records may or may not work, depending
1999 on whether both compilers lay them out identically. Complex structures
2000 involving variant records, access parameters, tasks, or protected types,
2001 are unlikely to be able to be passed.
2003 Note that in the case of GNAT running
2004 on a platform that supports DEC Ada 83, a higher degree of compatibility
2005 can be guaranteed, and in particular records are layed out in an identical
2006 manner in the two compilers. Note also that if output from two different
2007 compilers is mixed, the program is responsible for dealing with elaboration
2008 issues. Probably the safest approach is to write the main program in the
2009 version of Ada other than GNAT, so that it takes care of its own elaboration
2010 requirements, and then call the GNAT-generated adainit procedure to ensure
2011 elaboration of the GNAT components. Consult the documentation of the other
2012 Ada compiler for further details on elaboration.
2014 However, it is not possible to mix the tasking run time of GNAT and
2015 DEC Ada 83, All the tasking operations must either be entirely within
2016 GNAT compiled sections of the program, or entirely within DEC Ada 83
2017 compiled sections of the program.
2019 @cindex Interfacing to Assembly
2020 @cindex Convention Assembler
2022 Assembler. Specifies assembler as the convention. In practice this has the
2023 same effect as convention Ada (but is not equivalent in the sense of being
2024 considered the same convention).
2026 @cindex Convention Asm
2029 Asm. Equivalent to Assembler.
2031 @cindex Convention Asm
2034 Asm. Equivalent to Assembly.
2036 @cindex Interfacing to COBOL
2037 @cindex Convention COBOL
2040 COBOL. Data will be passed according to the conventions described
2041 in section B.4 of the Ada 95 Reference Manual.
2044 @cindex Interfacing to C
2045 @cindex Convention C
2047 C. Data will be passed according to the conventions described
2048 in section B.3 of the Ada 95 Reference Manual.
2050 @cindex Convention Default
2053 Default. Equivalent to C.
2055 @cindex Convention External
2058 External. Equivalent to C.
2061 @cindex Interfacing to C++
2062 @cindex Convention C++
2064 CPP. This stands for C++. For most purposes this is identical to C.
2065 See the separate description of the specialized GNAT pragmas relating to
2066 C++ interfacing for further details.
2069 @cindex Interfacing to Fortran
2070 @cindex Convention Fortran
2072 Fortran. Data will be passed according to the conventions described
2073 in section B.5 of the Ada 95 Reference Manual.
2076 Intrinsic. This applies to an intrinsic operation, as defined in the Ada 95
2077 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
2078 this means that the body of the subprogram is provided by the compiler itself,
2079 usually by means of an efficient code sequence, and that the user does not
2080 supply an explicit body for it. In an application program, the pragma can only
2081 be applied to the following two sets of names, which the GNAT compiler
2085 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
2086 Arithmetic. The corresponding subprogram declaration must have
2087 two formal parameters. The
2088 first one must be a signed integer type or a modular type with a binary
2089 modulus, and the second parameter must be of type Natural.
2090 The return type must be the same as the type of the first argument. The size
2091 of this type can only be 8, 16, 32, or 64.
2092 @item binary arithmetic operators: "+", "-", "*", "/"
2093 The corresponding operator declaration must have parameters and result type
2094 that have the same root numeric type (for example, all three are long_float
2095 types). This simplifies the definition of operations that use type checking
2096 to perform dimensional checks:
2098 type Distance is new Long_Float;
2099 type Time is new Long_Float;
2100 type Velocity is new Long_Float;
2101 function "/" (D : Distance; T : Time)
2103 pragma Import (Intrinsic, "/");
2106 This common idiom is often programmed with a generic definition and an explicit
2107 body. The pragma makes it simpler to introduce such declarations. It incurs
2108 no overhead in compilation time or code size, because it is implemented as a
2109 single machine instruction.
2114 @cindex Convention Stdcall
2116 Stdcall. This is relevant only to NT/Win95 implementations of GNAT,
2117 and specifies that the Stdcall calling sequence will be used, as defined
2121 @cindex Convention DLL
2123 DLL. This is equivalent to Stdcall.
2126 @cindex Convention Win32
2128 Win32. This is equivalent to Stdcall.
2131 @cindex Convention Stubbed
2133 Stubbed. This is a special convention that indicates that the compiler
2134 should provide a stub body that raises @code{Program_Error}.
2138 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2139 that can be used to parametrize conventions and allow additional synonyms
2140 to be specified. For example if you have legacy code in which the convention
2141 identifier Fortran77 was used for Fortran, you can use the configuration
2145 pragma Convention_Identifier (Fortran77, Fortran);
2149 And from now on the identifier Fortran77 may be used as a convention
2150 identifier (for example in an @code{Import} pragma) with the same
2153 @node Building Mixed Ada & C++ Programs
2154 @section Building Mixed Ada & C++ Programs
2157 Building a mixed application containing both Ada and C++ code may be a
2158 challenge for the unaware programmer. As a matter of fact, this
2159 interfacing has not been standardized in the Ada 95 reference manual due
2160 to the immaturity and lack of standard of C++ at the time. This
2161 section gives a few hints that should make this task easier. In
2162 particular the first section addresses the differences with
2163 interfacing with C. The second section looks into the delicate problem
2164 of linking the complete application from its Ada and C++ parts. The last
2165 section give some hints on how the GNAT run time can be adapted in order
2166 to allow inter-language dispatching with a new C++ compiler.
2169 * Interfacing to C++::
2170 * Linking a Mixed C++ & Ada Program::
2171 * A Simple Example::
2172 * Adapting the Run Time to a New C++ Compiler::
2175 @node Interfacing to C++
2176 @subsection Interfacing to C++
2179 GNAT supports interfacing with C++ compilers generating code that is
2180 compatible with the standard Application Binary Interface of the given
2184 Interfacing can be done at 3 levels: simple data, subprograms and
2185 classes. In the first 2 cases, GNAT offer a specific @var{Convention
2186 CPP} that behaves exactly like @var{Convention C}. Usually C++ mangle
2187 names of subprograms and currently GNAT does not provide any help to
2188 solve the demangling problem. This problem can be addressed in 2 ways:
2191 by modifying the C++ code in order to force a C convention using
2192 the @var{extern "C"} syntax.
2195 by figuring out the mangled name and use it as the Link_Name argument of
2200 Interfacing at the class level can be achieved by using the GNAT specific
2201 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
2202 Reference Manual for additional information.
2204 @node Linking a Mixed C++ & Ada Program
2205 @subsection Linking a Mixed C++ & Ada Program
2208 Usually the linker of the C++ development system must be used to link
2209 mixed applications because most C++ systems will resolve elaboration
2210 issues (such as calling constructors on global class instances)
2211 transparently during the link phase. GNAT has been adapted to ease the
2212 use of a foreign linker for the last phase. Three cases can be
2217 Using GNAT and G++ (GNU C++ compiler) from the same GCC
2218 installation. The c++ linker can simply be called by using the c++
2219 specific driver called @code{c++}. Note that this setup is not
2220 very common because it may request recompiling the whole GCC
2221 tree from sources and it does not allow to upgrade easily to a new
2222 version of one compiler for one of the two languages without taking the
2223 risk of destabilizing the other.
2228 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
2232 Using GNAT and G++ from 2 different GCC installations. If both compilers
2233 are on the PATH, the same method can be used. It is important to be
2234 aware that environment variables such as C_INCLUDE_PATH,
2235 GCC_EXEC_PREFIX, BINUTILS_ROOT or GCC_ROOT will affect both compilers at
2236 the same time and thus may make one of the 2 compilers operate
2237 improperly if they are set for the other. In particular it is important
2238 that the link command has access to the proper gcc library @file{libgcc.a},
2239 that is to say the one that is part of the C++ compiler
2240 installation. The implicit link command as suggested in the gnatmake
2241 command from the former example can be replaced by an explicit link
2242 command with full verbosity in order to verify which library is used:
2245 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
2247 If there is a problem due to interfering environment variables, it can
2248 be workaround by using an intermediate script. The following example
2249 shows the proper script to use when GNAT has not been installed at its
2250 default location and g++ has been installed at its default location:
2253 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
2262 Using a non GNU C++ compiler. The same set of command as previously
2263 described can be used to insure that the c++ linker is
2264 used. Nonetheless, you need to add the path to libgcc explicitely, since some
2265 libraries needed by GNAT are located in this directory:
2269 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2272 CC $* `gcc -print-libgcc-file-name`
2276 Where CC is the name of the non GNU C++ compiler.
2280 @node A Simple Example
2281 @subsection A Simple Example
2283 The following example, provided as part of the GNAT examples, show how
2284 to achieve procedural interfacing between Ada and C++ in both
2285 directions. The C++ class A has 2 methods. The first method is exported
2286 to Ada by the means of an extern C wrapper function. The second method
2287 calls an Ada subprogram. On the Ada side, The C++ calls is modelized by
2288 a limited record with a layout comparable to the C++ class. The Ada
2289 subprogram, in turn, calls the c++ method. So from the C++ main program
2290 the code goes back and forth between the 2 languages.
2293 Here are the compilation commands
2294 for native configurations:
2296 $ gnatmake -c simple_cpp_interface
2299 $ gnatbind -n simple_cpp_interface
2300 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
2301 -lstdc++ ex7.o cpp_main.o
2304 Here are the corresponding sources:
2312 void adainit (void);
2313 void adafinal (void);
2314 void method1 (A *t);
2336 class A : public Origin @{
2338 void method1 (void);
2339 virtual void method2 (int v);
2349 extern "C" @{ void ada_method2 (A *t, int v);@}
2351 void A::method1 (void)
2354 printf ("in A::method1, a_value = %d \n",a_value);
2358 void A::method2 (int v)
2360 ada_method2 (this, v);
2361 printf ("in A::method2, a_value = %d \n",a_value);
2368 printf ("in A::A, a_value = %d \n",a_value);
2372 @b{package} @b{body} Simple_Cpp_Interface @b{is}
2374 @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
2378 @b{end} Ada_Method2;
2380 @b{end} Simple_Cpp_Interface;
2382 @b{package} Simple_Cpp_Interface @b{is}
2383 @b{type} A @b{is} @b{limited}
2388 @b{pragma} Convention (C, A);
2390 @b{procedure} Method1 (This : @b{in} @b{out} A);
2391 @b{pragma} Import (C, Method1);
2393 @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
2394 @b{pragma} Export (C, Ada_Method2);
2396 @b{end} Simple_Cpp_Interface;
2399 @node Adapting the Run Time to a New C++ Compiler
2400 @subsection Adapting the Run Time to a New C++ Compiler
2402 GNAT offers the capability to derive Ada 95 tagged types directly from
2403 preexisting C++ classes and . See "Interfacing with C++" in the GNAT
2404 reference manual. The mechanism used by GNAT for achieving such a goal
2405 has been made user configurable through a GNAT library unit
2406 @code{Interfaces.CPP}. The default version of this file is adapted to
2407 the GNU c++ compiler. Internal knowledge of the virtual
2408 table layout used by the new C++ compiler is needed to configure
2409 properly this unit. The Interface of this unit is known by the compiler
2410 and cannot be changed except for the value of the constants defining the
2411 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
2412 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
2413 of this unit for more details.
2415 @node Comparison between GNAT and C/C++ Compilation Models
2416 @section Comparison between GNAT and C/C++ Compilation Models
2419 The GNAT model of compilation is close to the C and C++ models. You can
2420 think of Ada specs as corresponding to header files in C. As in C, you
2421 don't need to compile specs; they are compiled when they are used. The
2422 Ada @code{with} is similar in effect to the @code{#include} of a C
2425 One notable difference is that, in Ada, you may compile specs separately
2426 to check them for semantic and syntactic accuracy. This is not always
2427 possible with C headers because they are fragments of programs that have
2428 less specific syntactic or semantic rules.
2430 The other major difference is the requirement for running the binder,
2431 which performs two important functions. First, it checks for
2432 consistency. In C or C++, the only defense against assembling
2433 inconsistent programs lies outside the compiler, in a makefile, for
2434 example. The binder satisfies the Ada requirement that it be impossible
2435 to construct an inconsistent program when the compiler is used in normal
2438 @cindex Elaboration order control
2439 The other important function of the binder is to deal with elaboration
2440 issues. There are also elaboration issues in C++ that are handled
2441 automatically. This automatic handling has the advantage of being
2442 simpler to use, but the C++ programmer has no control over elaboration.
2443 Where @code{gnatbind} might complain there was no valid order of
2444 elaboration, a C++ compiler would simply construct a program that
2445 malfunctioned at run time.
2447 @node Comparison between GNAT and Conventional Ada Library Models
2448 @section Comparison between GNAT and Conventional Ada Library Models
2451 This section is intended to be useful to Ada programmers who have
2452 previously used an Ada compiler implementing the traditional Ada library
2453 model, as described in the Ada 95 Language Reference Manual. If you
2454 have not used such a system, please go on to the next section.
2456 @cindex GNAT library
2457 In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
2458 source files themselves acts as the library. Compiling Ada programs does
2459 not generate any centralized information, but rather an object file and
2460 a ALI file, which are of interest only to the binder and linker.
2461 In a traditional system, the compiler reads information not only from
2462 the source file being compiled, but also from the centralized library.
2463 This means that the effect of a compilation depends on what has been
2464 previously compiled. In particular:
2468 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
2469 to the version of the unit most recently compiled into the library.
2472 Inlining is effective only if the necessary body has already been
2473 compiled into the library.
2476 Compiling a unit may obsolete other units in the library.
2480 In GNAT, compiling one unit never affects the compilation of any other
2481 units because the compiler reads only source files. Only changes to source
2482 files can affect the results of a compilation. In particular:
2486 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
2487 to the source version of the unit that is currently accessible to the
2492 Inlining requires the appropriate source files for the package or
2493 subprogram bodies to be available to the compiler. Inlining is always
2494 effective, independent of the order in which units are complied.
2497 Compiling a unit never affects any other compilations. The editing of
2498 sources may cause previous compilations to be out of date if they
2499 depended on the source file being modified.
2503 The most important result of these differences is that order of compilation
2504 is never significant in GNAT. There is no situation in which one is
2505 required to do one compilation before another. What shows up as order of
2506 compilation requirements in the traditional Ada library becomes, in
2507 GNAT, simple source dependencies; in other words, there is only a set
2508 of rules saying what source files must be present when a file is
2511 @node Compiling Using gcc
2512 @chapter Compiling Using @code{gcc}
2515 This chapter discusses how to compile Ada programs using the @code{gcc}
2516 command. It also describes the set of switches
2517 that can be used to control the behavior of the compiler.
2519 * Compiling Programs::
2520 * Switches for gcc::
2521 * Search Paths and the Run-Time Library (RTL)::
2522 * Order of Compilation Issues::
2526 @node Compiling Programs
2527 @section Compiling Programs
2530 The first step in creating an executable program is to compile the units
2531 of the program using the @code{gcc} command. You must compile the
2536 the body file (@file{.adb}) for a library level subprogram or generic
2540 the spec file (@file{.ads}) for a library level package or generic
2541 package that has no body
2544 the body file (@file{.adb}) for a library level package
2545 or generic package that has a body
2550 You need @emph{not} compile the following files
2555 the spec of a library unit which has a body
2562 because they are compiled as part of compiling related units. GNAT
2564 when the corresponding body is compiled, and subunits when the parent is
2566 @cindex No code generated
2567 If you attempt to compile any of these files, you will get one of the
2568 following error messages (where fff is the name of the file you compiled):
2571 No code generated for file @var{fff} (@var{package spec})
2572 No code generated for file @var{fff} (@var{subunit})
2576 The basic command for compiling a file containing an Ada unit is
2579 $ gcc -c [@var{switches}] @file{file name}
2583 where @var{file name} is the name of the Ada file (usually
2585 @file{.ads} for a spec or @file{.adb} for a body).
2587 @code{-c} switch to tell @code{gcc} to compile, but not link, the file.
2588 The result of a successful compilation is an object file, which has the
2589 same name as the source file but an extension of @file{.o} and an Ada
2590 Library Information (ALI) file, which also has the same name as the
2591 source file, but with @file{.ali} as the extension. GNAT creates these
2592 two output files in the current directory, but you may specify a source
2593 file in any directory using an absolute or relative path specification
2594 containing the directory information.
2597 @code{gcc} is actually a driver program that looks at the extensions of
2598 the file arguments and loads the appropriate compiler. For example, the
2599 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
2600 These programs are in directories known to the driver program (in some
2601 configurations via environment variables you set), but need not be in
2602 your path. The @code{gcc} driver also calls the assembler and any other
2603 utilities needed to complete the generation of the required object
2606 It is possible to supply several file names on the same @code{gcc}
2607 command. This causes @code{gcc} to call the appropriate compiler for
2608 each file. For example, the following command lists three separate
2609 files to be compiled:
2612 $ gcc -c x.adb y.adb z.c
2616 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
2617 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
2618 The compiler generates three object files @file{x.o}, @file{y.o} and
2619 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
2620 Ada compilations. Any switches apply to all the files listed,
2622 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
2624 @node Switches for gcc
2625 @section Switches for @code{gcc}
2628 The @code{gcc} command accepts switches that control the
2629 compilation process. These switches are fully described in this section.
2630 First we briefly list all the switches, in alphabetical order, then we
2631 describe the switches in more detail in functionally grouped sections.
2634 * Output and Error Message Control::
2635 * Debugging and Assertion Control::
2637 * Stack Overflow Checking::
2638 * Run-Time Control::
2639 * Validity Checking::
2641 * Using gcc for Syntax Checking::
2642 * Using gcc for Semantic Checking::
2643 * Compiling Ada 83 Programs::
2644 * Character Set Control::
2645 * File Naming Control::
2646 * Subprogram Inlining Control::
2647 * Auxiliary Output Control::
2648 * Debugging Control::
2649 * Units to Sources Mapping Files::
2653 @cindex @code{-b} (@code{gcc})
2654 @item -b @var{target}
2655 Compile your program to run on @var{target}, which is the name of a
2656 system configuration. You must have a GNAT cross-compiler built if
2657 @var{target} is not the same as your host system.
2660 @cindex @code{-B} (@code{gcc})
2661 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
2662 from @var{dir} instead of the default location. Only use this switch
2663 when multiple versions of the GNAT compiler are available. See the
2664 @code{gcc} manual page for further details. You would normally use the
2665 @code{-b} or @code{-V} switch instead.
2668 @cindex @code{-c} (@code{gcc})
2669 Compile. Always use this switch when compiling Ada programs.
2671 Note: for some other languages when using @code{gcc}, notably in
2672 the case of C and C++, it is possible to use
2673 use @code{gcc} without a @code{-c} switch to
2674 compile and link in one step. In the case of GNAT, you
2675 cannot use this approach, because the binder must be run
2676 and @code{gcc} cannot be used to run the GNAT binder.
2679 @cindex @code{-g} (@code{gcc})
2680 Generate debugging information. This information is stored in the object
2681 file and copied from there to the final executable file by the linker,
2682 where it can be read by the debugger. You must use the
2683 @code{-g} switch if you plan on using the debugger.
2686 @cindex @code{-I} (@code{gcc})
2688 Direct GNAT to search the @var{dir} directory for source files needed by
2689 the current compilation
2690 (@pxref{Search Paths and the Run-Time Library (RTL)}).
2693 @cindex @code{-I-} (@code{gcc})
2695 Except for the source file named in the command line, do not look for source files
2696 in the directory containing the source file named in the command line
2697 (@pxref{Search Paths and the Run-Time Library (RTL)}).
2700 @cindex @code{-o} (@code{gcc})
2701 This switch is used in @code{gcc} to redirect the generated object file
2702 and its associated ALI file. Beware of this switch with GNAT, because it may
2703 cause the object file and ALI file to have different names which in turn
2704 may confuse the binder and the linker.
2707 @cindex @code{-O} (@code{gcc})
2708 @var{n} controls the optimization level.
2712 No optimization, the default setting if no @code{-O} appears
2715 Normal optimization, the default if you specify @code{-O} without
2719 Extensive optimization
2722 Extensive optimization with automatic inlining. This applies only to
2723 inlining within a unit. For details on control of inter-unit inlining
2724 see @xref{Subprogram Inlining Control}.
2728 @item --RTS=@var{rts-path}
2729 @cindex @code{--RTS} (@code{gcc})
2730 Specifies the default location of the runtime library. Same meaning as the
2731 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
2734 @cindex @code{-S} (@code{gcc})
2735 Used in place of @code{-c} to
2736 cause the assembler source file to be
2737 generated, using @file{.s} as the extension,
2738 instead of the object file.
2739 This may be useful if you need to examine the generated assembly code.
2742 @cindex @code{-v} (@code{gcc})
2743 Show commands generated by the @code{gcc} driver. Normally used only for
2744 debugging purposes or if you need to be sure what version of the
2745 compiler you are executing.
2748 @cindex @code{-V} (@code{gcc})
2749 Execute @var{ver} version of the compiler. This is the @code{gcc}
2750 version, not the GNAT version.
2753 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
2757 Avoid processing @file{gnat.adc}. If a gnat.adc file is present, it will be ignored.
2760 Generate brief messages to @file{stderr} even if verbose mode set.
2763 Check syntax and semantics only (no code generation attempted).
2766 Compress debug information and external symbol name table entries.
2769 Output expanded source files for source level debugging. This switch
2770 also suppress generation of cross-reference information (see -gnatx).
2772 @item -gnatec@var{path}
2773 Specify a configuration pragma file. (see @ref{The Configuration Pragmas Files})
2775 @item -gnatem@var{path}
2776 Specify a mapping file. (see @ref{Units to Sources Mapping Files})
2779 Full dynamic elaboration checks.
2782 Full errors. Multiple errors per line, all undefined references.
2785 Externals names are folded to all uppercase.
2788 Internal GNAT implementation mode. This should not be used for
2789 applications programs, it is intended only for use by the compiler
2790 and its run-time library. For documentation, see the GNAT sources.
2793 List generated expanded code in source form.
2796 Identifier character set
2797 (@var{c}=1/2/3/4/8/9/p/f/n/w).
2800 Output usage information. The output is written to @file{stdout}.
2803 Limit file names to @var{n} (1-999) characters (@code{k} = krunch).
2806 Output full source listing with embedded error messages.
2809 Limit number of detected errors to @var{n} (1-999).
2812 Activate inlining across unit boundaries for subprograms for which
2813 pragma @code{inline} is specified.
2816 Activate front end inlining.
2819 Suppresses all inlining, even if other optimization or inlining switches
2823 Activates stack checking. See separate section on stack checking for
2824 details of the use of this option.
2827 Enable numeric overflow checking (which is not normally enabled by
2828 default). Not that division by zero is a separate check that is not
2829 controlled by this switch (division by zero checking is on by default).
2832 Suppress all checks.
2835 Don't quit; try semantics, even if parse errors.
2838 Don't quit; generate @file{ali} and tree files even if illegalities.
2841 Enable polling. This is required on some systems (notably Windows NT) to
2842 obtain asynchronous abort and asynchronous transfer of control capability.
2843 See the description of pragma Polling in the GNAT Reference Manual for
2846 @item -gnatR[0/1/2/3][s]
2847 Output representation information for declared types and objects.
2853 Tree output file to be generated.
2856 Set time slice to specified number of microseconds
2859 List units for this compilation.
2862 Tag all error messages with the unique string "error:"
2865 Verbose mode. Full error output with source lines to @file{stdout}.
2868 Control level of validity checking. See separate section describing
2871 @item -gnatwxxx@var{xxx}
2873 @var{xxx} is a string of options describing the exact warnings that
2874 are enabled or disabled. See separate section on warning control.
2877 Wide character encoding method
2878 (@var{e}=n/h/u/s/e/8).
2881 Suppress generation of cross-reference information.
2884 Enable built-in style checks. See separate section describing this feature.
2887 Distribution stub generation and compilation
2888 (@var{m}=r/c for receiver/caller stubs).
2891 Enforce Ada 83 restrictions.
2893 @item -pass-exit-codes
2894 Catch exit codes from the compiler and use the most meaningful as
2898 You may combine a sequence of GNAT switches into a single switch. For
2899 example, the combined switch
2901 @cindex Combining GNAT switches
2907 is equivalent to specifying the following sequence of switches:
2910 -gnato -gnatf -gnati3
2914 The following restrictions apply to the combination of switches
2919 The switch @option{-gnatc} if combined with other switches must come
2920 first in the string.
2923 The switch @option{-gnats} if combined with other switches must come
2924 first in the string.
2927 Once a "y" appears in the string (that is a use of the @option{-gnaty}
2928 switch), then all further characters in the switch are interpreted
2929 as style modifiers (see description of @option{-gnaty}).
2932 Once a "d" appears in the string (that is a use of the @option{-gnatd}
2933 switch), then all further characters in the switch are interpreted
2934 as debug flags (see description of @option{-gnatd}).
2937 Once a "w" appears in the string (that is a use of the @option{-gnatw}
2938 switch), then all further characters in the switch are interpreted
2939 as warning mode modifiers (see description of @option{-gnatw}).
2942 Once a "V" appears in the string (that is a use of the @option{-gnatV}
2943 switch), then all further characters in the switch are interpreted
2944 as validity checking options (see description of @option{-gnatV}).
2948 @node Output and Error Message Control
2949 @subsection Output and Error Message Control
2953 The standard default format for error messages is called "brief format."
2954 Brief format messages are written to @file{stderr} (the standard error
2955 file) and have the following form:
2961 e.adb:3:04: Incorrect spelling of keyword "function"
2962 e.adb:4:20: ";" should be "is"
2966 The first integer after the file name is the line number in the file,
2967 and the second integer is the column number within the line.
2968 @code{glide} can parse the error messages
2969 and point to the referenced character.
2970 The following switches provide control over the error message
2975 @cindex @option{-gnatv} (@code{gcc})
2977 The v stands for verbose.
2978 The effect of this setting is to write long-format error
2979 messages to @file{stdout} (the standard output file.
2980 The same program compiled with the
2981 @option{-gnatv} switch would generate:
2986 3. funcion X (Q : Integer)
2988 >>> Incorrect spelling of keyword "function"
2991 >>> ";" should be "is"
2997 The vertical bar indicates the location of the error, and the @samp{>>>}
2998 prefix can be used to search for error messages. When this switch is
2999 used the only source lines output are those with errors.
3002 @cindex @option{-gnatl} (@code{gcc})
3003 The @code{l} stands for list.
3004 This switch causes a full listing of
3005 the file to be generated. The output might look as follows:
3012 3. funcion X (Q : Integer)
3014 >>> Incorrect spelling of keyword "function"
3017 >>> ";" should be "is"
3030 When you specify the @option{-gnatv} or @option{-gnatl} switches and
3031 standard output is redirected, a brief summary is written to
3032 @file{stderr} (standard error) giving the number of error messages and
3033 warning messages generated.
3036 @cindex @option{-gnatU} (@code{gcc})
3037 This switch forces all error messages to be preceded by the unique
3038 string "error:". This means that error messages take a few more
3039 characters in space, but allows easy searching for and identification
3043 @cindex @option{-gnatb} (@code{gcc})
3044 The @code{b} stands for brief.
3045 This switch causes GNAT to generate the
3046 brief format error messages to @file{stderr} (the standard error
3047 file) as well as the verbose
3048 format message or full listing (which as usual is written to
3049 @file{stdout} (the standard output file).
3052 @cindex @option{-gnatm} (@code{gcc})
3053 The @code{m} stands for maximum.
3054 @var{n} is a decimal integer in the
3055 range of 1 to 999 and limits the number of error messages to be
3056 generated. For example, using @option{-gnatm2} might yield
3062 e.adb:3:04: Incorrect spelling of keyword "function"
3063 e.adb:5:35: missing ".."
3064 fatal error: maximum errors reached
3065 compilation abandoned
3069 @cindex @option{-gnatf} (@code{gcc})
3070 @cindex Error messages, suppressing
3071 The @code{f} stands for full.
3072 Normally, the compiler suppresses error messages that are likely to be
3073 redundant. This switch causes all error
3074 messages to be generated. In particular, in the case of
3075 references to undefined variables. If a given variable is referenced
3076 several times, the normal format of messages is
3081 e.adb:7:07: "V" is undefined (more references follow)
3085 where the parenthetical comment warns that there are additional
3086 references to the variable @code{V}. Compiling the same program with the
3087 @option{-gnatf} switch yields
3090 e.adb:7:07: "V" is undefined
3091 e.adb:8:07: "V" is undefined
3092 e.adb:8:12: "V" is undefined
3093 e.adb:8:16: "V" is undefined
3094 e.adb:9:07: "V" is undefined
3095 e.adb:9:12: "V" is undefined
3099 @cindex @option{-gnatq} (@code{gcc})
3100 The @code{q} stands for quit (really "don't quit").
3101 In normal operation mode, the compiler first parses the program and
3102 determines if there are any syntax errors. If there are, appropriate
3103 error messages are generated and compilation is immediately terminated.
3105 GNAT to continue with semantic analysis even if syntax errors have been
3106 found. This may enable the detection of more errors in a single run. On
3107 the other hand, the semantic analyzer is more likely to encounter some
3108 internal fatal error when given a syntactically invalid tree.
3111 In normal operation mode, the @file{ali} file is not generated if any
3112 illegalities are detected in the program. The use of @option{-gnatQ} forces
3113 generation of the @file{ali} file. This file is marked as being in
3114 error, so it cannot be used for binding purposes, but it does contain
3115 reasonably complete cross-reference information, and thus may be useful
3116 for use by tools (e.g. semantic browsing tools or integrated development
3117 environments) that are driven from the @file{ali} file.
3119 In addition, if @option{-gnatt} is also specified, then the tree file is
3120 generated even if there are illegalities. It may be useful in this case
3121 to also specify @option{-gnatq} to ensure that full semantic processing
3122 occurs. The resulting tree file can be processed by ASIS, for the purpose
3123 of providing partial information about illegal units, but if the error
3124 causes the tree to be badly malformed, then ASIS may crash during the
3130 In addition to error messages, which correspond to illegalities as defined
3131 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
3134 @cindex Warning messages
3135 First, the compiler considers some constructs suspicious and generates a
3136 warning message to alert you to a possible error. Second, if the
3137 compiler detects a situation that is sure to raise an exception at
3138 run time, it generates a warning message. The following shows an example
3139 of warning messages:
3144 e.adb:4:24: warning: creation of object may raise Storage_Error
3145 e.adb:10:17: warning: static value out of range
3146 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
3151 GNAT considers a large number of situations as appropriate
3152 for the generation of warning messages. As always, warnings are not
3153 definite indications of errors. For example, if you do an out-of-range
3154 assignment with the deliberate intention of raising a
3155 @code{Constraint_Error} exception, then the warning that may be
3156 issued does not indicate an error. Some of the situations for which GNAT
3157 issues warnings (at least some of the time) are given in the following
3158 list, which is not necessarily complete.
3162 Possible infinitely recursive calls
3165 Out-of-range values being assigned
3168 Possible order of elaboration problems
3174 Fixed-point type declarations with a null range
3177 Variables that are never assigned a value
3180 Variables that are referenced before being initialized
3183 Task entries with no corresponding accept statement
3186 Duplicate accepts for the same task entry in a select
3189 Objects that take too much storage
3192 Unchecked conversion between types of differing sizes
3195 Missing return statements along some execution paths in a function
3198 Incorrect (unrecognized) pragmas
3201 Incorrect external names
3204 Allocation from empty storage pool
3207 Potentially blocking operations in protected types
3210 Suspicious parenthesization of expressions
3213 Mismatching bounds in an aggregate
3216 Attempt to return local value by reference
3219 Unrecognized pragmas
3222 Premature instantiation of a generic body
3225 Attempt to pack aliased components
3228 Out of bounds array subscripts
3231 Wrong length on string assignment
3234 Violations of style rules if style checking is enabled
3240 Bit_Order usage that does not have any effect
3243 Compile time biased rounding of floating-point constant
3246 Standard.Duration used to resolve universal fixed expression
3249 Dereference of possibly null value
3252 Declaration that is likely to cause storage error
3255 Internal GNAT unit with'ed by application unit
3258 Values known to be out of range at compile time
3261 Unreferenced labels and variables
3264 Address overlays that could clobber memory
3267 Unexpected initialization when address clause present
3270 Bad alignment for address clause
3273 Useless type conversions
3276 Redundant assignment statements
3279 Accidental hiding of name by child unit
3285 Access before elaboration detected at compile time
3288 A range in a @code{for} loop that is known to be null or might be null
3293 The following switches are available to control the handling of
3297 @item -gnatwa (activate all optional errors)
3298 @cindex @option{-gnatwa} (@code{gcc})
3299 This switch activates most optional warning messages, see remaining list
3300 in this section for details on optional warning messages that can be
3301 individually controlled. The warnings that are not turned on by this
3302 switch are @option{-gnatwb} (biased rounding),
3303 @option{-gnatwd} (implicit dereferencing),
3304 and @option{-gnatwh} (hiding). All other optional warnings are
3307 @item -gnatwA (suppress all optional errors)
3308 @cindex @option{-gnatwA} (@code{gcc})
3309 This switch suppresses all optional warning messages, see remaining list
3310 in this section for details on optional warning messages that can be
3311 individually controlled.
3313 @item -gnatwb (activate warnings on biased rounding)
3314 @cindex @option{-gnatwb} (@code{gcc})
3315 @cindex Rounding, biased
3316 @cindex Biased rounding
3317 If a static floating-point expression has a value that is exactly half
3318 way between two adjacent machine numbers, then the rules of Ada
3319 (Ada Reference Manual, section 4.9(38)) require that this rounding
3320 be done away from zero, even if the normal unbiased rounding rules
3321 at run time would require rounding towards zero. This warning message
3322 alerts you to such instances where compile-time rounding and run-time
3323 rounding are not equivalent. If it is important to get proper run-time
3324 rounding, then you can force this by making one of the operands into
3325 a variable. The default is that such warnings are not generated.
3326 Note that @option{-gnatwa} does not affect the setting of
3327 this warning option.
3329 @item -gnatwB (suppress warnings on biased rounding)
3330 @cindex @option{-gnatwB} (@code{gcc})
3331 This switch disables warnings on biased rounding.
3333 @item -gnatwc (activate warnings on conditionals)
3334 @cindex @option{-gnatwc} (@code{gcc})
3335 @cindex Conditionals, constant
3336 This switch activates warnings for conditional expressions used in
3337 tests that are known to be True or False at compile time. The default
3338 is that such warnings are not generated.
3339 This warning can also be turned on using @option{-gnatwa}.
3341 @item -gnatwC (suppress warnings on conditionals)
3342 @cindex @option{-gnatwC} (@code{gcc})
3343 This switch suppresses warnings for conditional expressions used in
3344 tests that are known to be True or False at compile time.
3346 @item -gnatwd (activate warnings on implicit dereferencing)
3347 @cindex @option{-gnatwd} (@code{gcc})
3348 If this switch is set, then the use of a prefix of an access type
3349 in an indexed component, slice, or selected component without an
3350 explicit @code{.all} will generate a warning. With this warning
3351 enabled, access checks occur only at points where an explicit
3352 @code{.all} appears in the source code (assuming no warnings are
3353 generated as a result of this switch). The default is that such
3354 warnings are not generated.
3355 Note that @option{-gnatwa} does not affect the setting of
3356 this warning option.
3358 @item -gnatwD (suppress warnings on implicit dereferencing)
3359 @cindex @option{-gnatwD} (@code{gcc})
3360 @cindex Implicit dereferencing
3361 @cindex Dereferencing, implicit
3362 This switch suppresses warnings for implicit deferences in
3363 indexed components, slices, and selected components.
3365 @item -gnatwe (treat warnings as errors)
3366 @cindex @option{-gnatwe} (@code{gcc})
3367 @cindex Warnings, treat as error
3368 This switch causes warning messages to be treated as errors.
3369 The warning string still appears, but the warning messages are counted
3370 as errors, and prevent the generation of an object file.
3372 @item -gnatwf (activate warnings on unreferenced formals)
3373 @cindex @option{-gnatwf} (@code{gcc})
3374 @cindex Formals, unreferenced
3375 This switch causes a warning to be generated if a formal parameter
3376 is not referenced in the body of the subprogram. This warning can
3377 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
3379 @item -gnatwF (suppress warnings on unreferenced formals)
3380 @cindex @option{-gnatwF} (@code{gcc})
3381 This switch suppresses warnings for unreferenced formal
3382 parameters. Note that the
3383 combination @option{-gnatwu} followed by @option{-gnatwF} has the
3384 effect of warning on unreferenced entities other than subprogram
3387 @item -gnatwh (activate warnings on hiding)
3388 @cindex @option{-gnatwh} (@code{gcc})
3389 @cindex Hiding of Declarations
3390 This switch activates warnings on hiding declarations.
3391 A declaration is considered hiding
3392 if it is for a non-overloadable entity, and it declares an entity with the
3393 same name as some other entity that is directly or use-visible. The default
3394 is that such warnings are not generated.
3395 Note that @option{-gnatwa} does not affect the setting of this warning option.
3397 @item -gnatwH (suppress warnings on hiding)
3398 @cindex @option{-gnatwH} (@code{gcc})
3399 This switch suppresses warnings on hiding declarations.
3401 @item -gnatwi (activate warnings on implementation units).
3402 @cindex @option{-gnatwi} (@code{gcc})
3403 This switch activates warnings for a @code{with} of an internal GNAT
3404 implementation unit, defined as any unit from the @code{Ada},
3405 @code{Interfaces}, @code{GNAT},
3407 hierarchies that is not
3408 documented in either the Ada Reference Manual or the GNAT
3409 Programmer's Reference Manual. Such units are intended only
3410 for internal implementation purposes and should not be @code{with}'ed
3411 by user programs. The default is that such warnings are generated
3412 This warning can also be turned on using @option{-gnatwa}.
3414 @item -gnatwI (disable warnings on implementation units).
3415 @cindex @option{-gnatwI} (@code{gcc})
3416 This switch disables warnings for a @code{with} of an internal GNAT
3417 implementation unit.
3419 @item -gnatwl (activate warnings on elaboration pragmas)
3420 @cindex @option{-gnatwl} (@code{gcc})
3421 @cindex Elaboration, warnings
3422 This switch activates warnings on missing pragma Elaborate_All statements.
3423 See the section in this guide on elaboration checking for details on
3424 when such pragma should be used. The default is that such warnings
3426 This warning can also be turned on using @option{-gnatwa}.
3428 @item -gnatwL (suppress warnings on elaboration pragmas)
3429 @cindex @option{-gnatwL} (@code{gcc})
3430 This switch suppresses warnings on missing pragma Elaborate_All statements.
3431 See the section in this guide on elaboration checking for details on
3432 when such pragma should be used.
3434 @item -gnatwo (activate warnings on address clause overlays)
3435 @cindex @option{-gnatwo} (@code{gcc})
3436 @cindex Address Clauses, warnings
3437 This switch activates warnings for possibly unintended initialization
3438 effects of defining address clauses that cause one variable to overlap
3439 another. The default is that such warnings are generated.
3440 This warning can also be turned on using @option{-gnatwa}.
3442 @item -gnatwO (suppress warnings on address clause overlays)
3443 @cindex @option{-gnatwO} (@code{gcc})
3444 This switch suppresses warnings on possibly unintended initialization
3445 effects of defining address clauses that cause one variable to overlap
3448 @item -gnatwp (activate warnings on ineffective pragma Inlines)
3449 @cindex @option{-gnatwp} (@code{gcc})
3450 @cindex Inlining, warnings
3451 This switch activates warnings for failure of front end inlining
3452 (activated by @option{-gnatN}) to inline a particular call. There are
3453 many reasons for not being able to inline a call, including most
3454 commonly that the call is too complex to inline.
3455 This warning can also be turned on using @option{-gnatwa}.
3457 @item -gnatwP (suppress warnings on ineffective pragma Inlines)
3458 @cindex @option{-gnatwP} (@code{gcc})
3459 This switch suppresses warnings on ineffective pragma Inlines. If the
3460 inlining mechanism cannot inline a call, it will simply ignore the
3463 @item -gnatwr (activate warnings on redundant constructs)
3464 @cindex @option{-gnatwr} (@code{gcc})
3465 This switch activates warnings for redundant constructs. The following
3466 is the current list of constructs regarded as redundant:
3467 This warning can also be turned on using @option{-gnatwa}.
3471 Assignment of an item to itself.
3473 Type conversion that converts an expression to its own type.
3475 Use of the attribute @code{Base} where @code{typ'Base} is the same
3478 Use of pragma @code{Pack} when all components are placed by a record
3479 representation clause.
3482 @item -gnatwR (suppress warnings on redundant constructs)
3483 @cindex @option{-gnatwR} (@code{gcc})
3484 This switch suppresses warnings for redundant constructs.
3486 @item -gnatws (suppress all warnings)
3487 @cindex @option{-gnatws} (@code{gcc})
3488 This switch completely suppresses the
3489 output of all warning messages from the GNAT front end.
3490 Note that it does not suppress warnings from the @code{gcc} back end.
3491 To suppress these back end warnings as well, use the switch @code{-w}
3492 in addition to @option{-gnatws}.
3494 @item -gnatwu (activate warnings on unused entities)
3495 @cindex @option{-gnatwu} (@code{gcc})
3496 This switch activates warnings to be generated for entities that
3497 are defined but not referenced, and for units that are @code{with}'ed
3499 referenced. In the case of packages, a warning is also generated if
3500 no entities in the package are referenced. This means that if the package
3501 is referenced but the only references are in @code{use}
3502 clauses or @code{renames}
3503 declarations, a warning is still generated. A warning is also generated
3504 for a generic package that is @code{with}'ed but never instantiated.
3505 In the case where a package or subprogram body is compiled, and there
3506 is a @code{with} on the corresponding spec
3507 that is only referenced in the body,
3508 a warning is also generated, noting that the
3509 @code{with} can be moved to the body. The default is that
3510 such warnings are not generated.
3511 This switch also activates warnings on unreferenced formals
3512 (it is includes the effect of @option{-gnatwf}).
3513 This warning can also be turned on using @option{-gnatwa}.
3515 @item -gnatwU (suppress warnings on unused entities)
3516 @cindex @option{-gnatwU} (@code{gcc})
3517 This switch suppresses warnings for unused entities and packages.
3518 It also turns off warnings on unreferenced formals (and thus includes
3519 the effect of @option{-gnatwF}).
3522 A string of warning parameters can be used in the same parameter. For example:
3529 Would turn on all optional warnings except for elaboration pragma warnings,
3530 and also specify that warnings should be treated as errors.
3534 This switch suppresses warnings from the @code{gcc} backend. It may be
3535 used in conjunction with @option{-gnatws} to ensure that all warnings
3536 are suppressed during the entire compilation process.
3540 @node Debugging and Assertion Control
3541 @subsection Debugging and Assertion Control
3545 @cindex @option{-gnata} (@code{gcc})
3551 The pragmas @code{Assert} and @code{Debug} normally have no effect and
3552 are ignored. This switch, where @samp{a} stands for assert, causes
3553 @code{Assert} and @code{Debug} pragmas to be activated.
3555 The pragmas have the form:
3560 @b{pragma} Assert (@var{Boolean-expression} [,
3561 @var{static-string-expression}])
3562 @b{pragma} Debug (@var{procedure call})
3568 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
3569 If the result is @code{True}, the pragma has no effect (other than
3570 possible side effects from evaluating the expression). If the result is
3571 @code{False}, the exception @code{Assert_Failure} declared in the package
3572 @code{System.Assertions} is
3573 raised (passing @var{static-string-expression}, if present, as the
3574 message associated with the exception). If no string expression is
3575 given the default is a string giving the file name and line number
3578 The @code{Debug} pragma causes @var{procedure} to be called. Note that
3579 @code{pragma Debug} may appear within a declaration sequence, allowing
3580 debugging procedures to be called between declarations.
3584 @node Validity Checking
3585 @subsection Validity Checking
3586 @findex Validity Checking
3589 The Ada 95 Reference Manual has specific requirements for checking
3590 for invalid values. In particular, RM 13.9.1 requires that the
3591 evaluation of invalid values (for example from unchecked conversions),
3592 not result in erroneous execution. In GNAT, the result of such an
3593 evaluation in normal default mode is to either use the value
3594 unmodified, or to raise Constraint_Error in those cases where use
3595 of the unmodified value would cause erroneous execution. The cases
3596 where unmodified values might lead to erroneous execution are case
3597 statements (where a wild jump might result from an invalid value),
3598 and subscripts on the left hand side (where memory corruption could
3599 occur as a result of an invalid value).
3601 The @option{-gnatVx} switch allows more control over the validity checking
3602 mode. The @code{x} argument here is a string of letters which control which
3603 validity checks are performed in addition to the default checks described
3608 @option{-gnatVc} Validity checks for copies
3610 The right hand side of assignments, and the initializing values of
3611 object declarations are validity checked.
3614 @option{-gnatVd} Default (RM) validity checks
3616 Some validity checks are done by default following normal Ada semantics
3618 A check is done in case statements that the expression is within the range
3619 of the subtype. If it is not, Constraint_Error is raised.
3620 For assignments to array components, a check is done that the expression used
3621 as index is within the range. If it is not, Constraint_Error is raised.
3622 Both these validity checks may be turned off using switch @option{-gnatVD}.
3623 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
3624 switch @option{-gnatVd} will leave the checks turned on.
3625 Switch @option{-gnatVD} should be used only if you are sure that all such
3626 expressions have valid values. If you use this switch and invalid values
3627 are present, then the program is erroneous, and wild jumps or memory
3628 overwriting may occur.
3631 @option{-gnatVi} Validity checks for @code{in} mode parameters
3633 Arguments for parameters of mode @code{in} are validity checked in function
3634 and procedure calls at the point of call.
3637 @option{-gnatVm} Validity checks for @code{in out} mode parameters
3639 Arguments for parameters of mode @code{in out} are validity checked in
3640 procedure calls at the point of call. The @code{'m'} here stands for
3641 modify, since this concerns parameters that can be modified by the call.
3642 Note that there is no specific option to test @code{out} parameters,
3643 but any reference within the subprogram will be tested in the usual
3644 manner, and if an invalid value is copied back, any reference to it
3645 will be subject to validity checking.
3648 @option{-gnatVo} Validity checks for operator and attribute operands
3650 Arguments for predefined operators and attributes are validity checked.
3651 This includes all operators in package @code{Standard},
3652 the shift operators defined as intrinsic in package @code{Interfaces}
3653 and operands for attributes such as @code{Pos}.
3656 @option{-gnatVr} Validity checks for function returns
3658 The expression in @code{return} statements in functions is validity
3662 @option{-gnatVs} Validity checks for subscripts
3664 All subscripts expressions are checked for validity, whether they appear
3665 on the right side or left side (in default mode only left side subscripts
3666 are validity checked).
3669 @option{-gnatVt} Validity checks for tests
3671 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
3672 statements are checked, as well as guard expressions in entry calls.
3675 @option{-gnatVf} Validity checks for floating-point values
3677 In the absence of this switch, validity checking occurs only for discrete
3678 values. If @option{-gnatVf} is specified, then validity checking also applies
3679 for floating-point values, and NaN's and infinities are considered invalid,
3680 as well as out of range values for constrained types. Note that this means
3681 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
3682 in which floating-point values are checked depends on the setting of other
3683 options. For example @option{-gnatVif} or @option{-gnatVfi} (the order does
3684 not matter) specifies that floating-point parameters of mode @code{in} should
3685 be validity checked.
3688 @option{-gnatVa} All validity checks
3690 All the above validity checks are turned on. That is @option{-gnatVa} is
3691 equivalent to @code{gnatVcdfimorst}.
3694 @option{-gnatVn} No validity checks
3696 This switch turns off all validity checking, including the default checking
3697 for case statements and left hand side subscripts. Note that the use of
3698 the switch @option{-gnatp} supresses all run-time checks, including
3699 validity checks, and thus implies @option{-gnatVn}.
3703 The @option{-gnatV} switch may be followed by a string of letters to turn on
3704 a series of validity checking options. For example, @option{-gnatVcr} specifies
3705 that in addition to the default validity checking, copies and function
3706 return expressions be validity checked. In order to make it easier to specify
3707 a set of options, the upper case letters @code{CDFIMORST} may be used to turn
3708 off the corresponding lower case option, so for example @option{-gnatVaM} turns
3709 on all validity checking options except for checking of @code{in out}
3710 procedure arguments.
3712 The specification of additional validity checking generates extra code (and
3713 in the case of @option{-gnatva} the code expansion can be substantial. However,
3714 these additional checks can be very useful in smoking out cases of
3715 uninitialized variables, incorrect use of unchecked conversion, and other
3716 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
3717 is useful in conjunction with the extra validity checking, since this
3718 ensures that wherever possible uninitialized variables have invalid values.
3720 See also the pragma @code{Validity_Checks} which allows modification of
3721 the validity checking mode at the program source level, and also allows for
3722 temporary disabling of validity checks.
3724 @node Style Checking
3725 @subsection Style Checking
3726 @findex Style checking
3729 The -gnaty@var{x} switch causes the compiler to
3730 enforce specified style rules. A limited set of style rules has been used
3731 in writing the GNAT sources themselves. This switch allows user programs
3732 to activate all or some of these checks. If the source program fails a
3733 specified style check, an appropriate warning message is given, preceded by
3734 the character sequence "(style)".
3735 The string @var{x} is a sequence of letters or digits
3736 indicating the particular style
3737 checks to be performed. The following checks are defined:
3740 @item 1-9 (specify indentation level)
3741 If a digit from 1-9 appears in the string after @option{-gnaty} then proper
3742 indentation is checked, with the digit indicating the indentation level
3743 required. The general style of required indentation is as specified by
3744 the examples in the Ada Reference Manual. Full line comments must be
3745 aligned with the @code{--} starting on a column that is a multiple of
3746 the alignment level.
3748 @item a (check attribute casing)
3749 If the letter a appears in the string after @option{-gnaty} then
3750 attribute names, including the case of keywords such as @code{digits}
3751 used as attributes names, must be written in mixed case, that is, the
3752 initial letter and any letter following an underscore must be uppercase.
3753 All other letters must be lowercase.
3755 @item b (blanks not allowed at statement end)
3756 If the letter b appears in the string after @option{-gnaty} then
3757 trailing blanks are not allowed at the end of statements. The purpose of this
3758 rule, together with h (no horizontal tabs), is to enforce a canonical format
3759 for the use of blanks to separate source tokens.
3761 @item c (check comments)
3762 If the letter c appears in the string after @option{-gnaty} then
3763 comments must meet the following set of rules:
3768 The "--" that starts the column must either start in column one, or else
3769 at least one blank must precede this sequence.
3772 Comments that follow other tokens on a line must have at least one blank
3773 following the "--" at the start of the comment.
3776 Full line comments must have two blanks following the "--" that starts
3777 the comment, with the following exceptions.
3780 A line consisting only of the "--" characters, possibly preceded by blanks
3784 A comment starting with "--x" where x is a special character is permitted.
3785 This alows proper processing of the output generated by specialized tools
3786 including @code{gnatprep} (where --! is used) and the SPARK annnotation
3787 language (where --# is used). For the purposes of this rule, a special
3788 character is defined as being in one of the ASCII ranges
3789 16#21#..16#2F# or 16#3A#..16#3F#.
3792 A line consisting entirely of minus signs, possibly preceded by blanks, is
3793 permitted. This allows the construction of box comments where lines of minus
3794 signs are used to form the top and bottom of the box.
3797 If a comment starts and ends with "--" is permitted as long as at least
3798 one blank follows the initial "--". Together with the preceding rule,
3799 this allows the construction of box comments, as shown in the following
3802 ---------------------------
3803 -- This is a box comment --
3804 -- with two text lines. --
3805 ---------------------------
3809 @item e (check end/exit labels)
3810 If the letter e appears in the string after @option{-gnaty} then
3811 optional labels on @code{end} statements ending subprograms and on
3812 @code{exit} statements exiting named loops, are required to be present.
3814 @item f (no form feeds or vertical tabs)
3815 If the letter f appears in the string after @option{-gnaty} then
3816 neither form feeds nor vertical tab characters are not permitted
3819 @item h (no horizontal tabs)
3820 If the letter h appears in the string after @option{-gnaty} then
3821 horizontal tab characters are not permitted in the source text.
3822 Together with the b (no blanks at end of line) check, this
3823 enforces a canonical form for the use of blanks to separate
3826 @item i (check if-then layout)
3827 If the letter i appears in the string after @option{-gnaty},
3828 then the keyword @code{then} must appear either on the same
3829 line as corresponding @code{if}, or on a line on its own, lined
3830 up under the @code{if} with at least one non-blank line in between
3831 containing all or part of the condition to be tested.
3833 @item k (check keyword casing)
3834 If the letter k appears in the string after @option{-gnaty} then
3835 all keywords must be in lower case (with the exception of keywords
3836 such as @code{digits} used as attribute names to which this check
3839 @item l (check layout)
3840 If the letter l appears in the string after @option{-gnaty} then
3841 layout of statement and declaration constructs must follow the
3842 recommendations in the Ada Reference Manual, as indicated by the
3843 form of the syntax rules. For example an @code{else} keyword must
3844 be lined up with the corresponding @code{if} keyword.
3846 There are two respects in which the style rule enforced by this check
3847 option are more liberal than those in the Ada Reference Manual. First
3848 in the case of record declarations, it is permissible to put the
3849 @code{record} keyword on the same line as the @code{type} keyword, and
3850 then the @code{end} in @code{end record} must line up under @code{type}.
3851 For example, either of the following two layouts is acceptable:
3856 @b{type} q @b{is record}
3871 Second, in the case of a block statement, a permitted alternative
3872 is to put the block label on the same line as the @code{declare} or
3873 @code{begin} keyword, and then line the @code{end} keyword up under
3874 the block label. For example both the following are permitted:
3896 The same alternative format is allowed for loops. For example, both of
3897 the following are permitted:
3902 Clear : @b{while} J < 10 @b{loop}
3907 @b{while} J < 10 @b{loop}
3914 @item m (check maximum line length)
3915 If the letter m appears in the string after @option{-gnaty}
3916 then the length of source lines must not exceed 79 characters, including
3917 any trailing blanks. The value of 79 allows convenient display on an
3918 80 character wide device or window, allowing for possible special
3919 treatment of 80 character lines.
3921 @item Mnnn (set maximum line length)
3922 If the sequence Mnnn, where nnn is a decimal number, appears in
3923 the string after @option{-gnaty} then the length of lines must not exceed the
3926 @item n (check casing of entities in Standard)
3927 If the letter n appears in the string
3928 after @option{-gnaty} then any identifier from Standard must be cased
3929 to match the presentation in the Ada Reference Manual (for example,
3930 @code{Integer} and @code{ASCII.NUL}).
3932 @item o (check order of subprogram bodies)
3933 If the letter o appears in the string
3934 after @option{-gnaty} then all subprogram bodies in a given scope
3935 (e.g. a package body) must be in alphabetical order. The ordering
3936 rule uses normal Ada rules for comparing strings, ignoring casing
3937 of letters, except that if there is a trailing numeric suffix, then
3938 the value of this suffix is used in the ordering (e.g. Junk2 comes
3941 @item p (check pragma casing)
3942 If the letter p appears in the string after @option{-gnaty} then
3943 pragma names must be written in mixed case, that is, the
3944 initial letter and any letter following an underscore must be uppercase.
3945 All other letters must be lowercase.
3947 @item r (check references)
3948 If the letter r appears in the string after @option{-gnaty}
3949 then all identifier references must be cased in the same way as the
3950 corresponding declaration. No specific casing style is imposed on
3951 identifiers. The only requirement is for consistency of references
3954 @item s (check separate specs)
3955 If the letter s appears in the string after @option{-gnaty} then
3956 separate declarations ("specs") are required for subprograms (a
3957 body is not allowed to serve as its own declaration). The only
3958 exception is that parameterless library level procedures are
3959 not required to have a separate declaration. This exception covers
3960 the most frequent form of main program procedures.
3962 @item t (check token spacing)
3963 If the letter t appears in the string after @option{-gnaty} then
3964 the following token spacing rules are enforced:
3969 The keywords @code{abs} and @code{not} must be followed by a space.
3972 The token @code{=>} must be surrounded by spaces.
3975 The token @code{<>} must be preceded by a space or a left parenthesis.
3978 Binary operators other than @code{**} must be surrounded by spaces.
3979 There is no restriction on the layout of the @code{**} binary operator.
3982 Colon must be surrounded by spaces.
3985 Colon-equal (assignment) must be surrounded by spaces.
3988 Comma must be the first non-blank character on the line, or be
3989 immediately preceded by a non-blank character, and must be followed
3993 If the token preceding a left paren ends with a letter or digit, then
3994 a space must separate the two tokens.
3997 A right parenthesis must either be the first non-blank character on
3998 a line, or it must be preceded by a non-blank character.
4001 A semicolon must not be preceded by a space, and must not be followed by
4002 a non-blank character.
4005 A unary plus or minus may not be followed by a space.
4008 A vertical bar must be surrounded by spaces.
4012 In the above rules, appearing in column one is always permitted, that is,
4013 counts as meeting either a requirement for a required preceding space,
4014 or as meeting a requirement for no preceding space.
4016 Appearing at the end of a line is also always permitted, that is, counts
4017 as meeting either a requirement for a following space, or as meeting
4018 a requirement for no following space.
4023 If any of these style rules is violated, a message is generated giving
4024 details on the violation. The initial characters of such messages are
4025 always "(style)". Note that these messages are treated as warning
4026 messages, so they normally do not prevent the generation of an object
4027 file. The @option{-gnatwe} switch can be used to treat warning messages,
4028 including style messages, as fatal errors.
4032 @option{-gnaty} on its own (that is not followed by any letters or digits),
4033 is equivalent to @code{gnaty3abcefhiklmprst}, that is all checking
4034 options are enabled with
4035 the exception of -gnatyo,
4036 with an indentation level of 3. This is the standard
4037 checking option that is used for the GNAT sources.
4039 @node Run-Time Checks
4040 @subsection Run-Time Checks
4041 @cindex Division by zero
4042 @cindex Access before elaboration
4043 @cindex Checks, division by zero
4044 @cindex Checks, access before elaboration
4047 If you compile with the default options, GNAT will insert many run-time
4048 checks into the compiled code, including code that performs range
4049 checking against constraints, but not arithmetic overflow checking for
4050 integer operations (including division by zero) or checks for access
4051 before elaboration on subprogram calls. All other run-time checks, as
4052 required by the Ada 95 Reference Manual, are generated by default.
4053 The following @code{gcc} switches refine this default behavior:
4057 @cindex @option{-gnatp} (@code{gcc})
4058 @cindex Suppressing checks
4059 @cindex Checks, suppressing
4061 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
4062 had been present in the source. Validity checks are also suppressed (in
4063 other words @option{-gnatp} also implies @option{-gnatVn}.
4064 Use this switch to improve the performance
4065 of the code at the expense of safety in the presence of invalid data or
4069 @cindex @option{-gnato} (@code{gcc})
4070 @cindex Overflow checks
4071 @cindex Check, overflow
4072 Enables overflow checking for integer operations.
4073 This causes GNAT to generate slower and larger executable
4074 programs by adding code to check for overflow (resulting in raising
4075 @code{Constraint_Error} as required by standard Ada
4076 semantics). These overflow checks correspond to situations in which
4077 the true value of the result of an operation may be outside the base
4078 range of the result type. The following example shows the distinction:
4081 X1 : Integer := Integer'Last;
4082 X2 : Integer range 1 .. 5 := 5;
4084 X1 := X1 + 1; -- @option{-gnato} required to catch the Constraint_Error
4085 X2 := X2 + 1; -- range check, @option{-gnato} has no effect here
4089 Here the first addition results in a value that is outside the base range
4090 of Integer, and hence requires an overflow check for detection of the
4091 constraint error. The second increment operation results in a violation
4092 of the explicit range constraint, and such range checks are always
4093 performed. Basically the compiler can assume that in the absence of
4094 the @option{-gnato} switch that any value of type @code{xxx} is
4095 in range of the base type of @code{xxx}.
4097 @findex Machine_Overflows
4098 Note that the @option{-gnato} switch does not affect the code generated
4099 for any floating-point operations; it applies only to integer
4101 For floating-point, GNAT has the @code{Machine_Overflows}
4102 attribute set to @code{False} and the normal mode of operation is to
4103 generate IEEE NaN and infinite values on overflow or invalid operations
4104 (such as dividing 0.0 by 0.0).
4106 The reason that we distinguish overflow checking from other kinds of
4107 range constraint checking is that a failure of an overflow check can
4108 generate an incorrect value, but cannot cause erroneous behavior. This
4109 is unlike the situation with a constraint check on an array subscript,
4110 where failure to perform the check can result in random memory description,
4111 or the range check on a case statement, where failure to perform the check
4112 can cause a wild jump.
4114 Note again that @option{-gnato} is off by default, so overflow checking is
4115 not performed in default mode. This means that out of the box, with the
4116 default settings, GNAT does not do all the checks expected from the
4117 language description in the Ada Reference Manual. If you want all constraint
4118 checks to be performed, as described in this Manual, then you must
4119 explicitly use the -gnato switch either on the @code{gnatmake} or
4123 @cindex @option{-gnatE} (@code{gcc})
4124 @cindex Elaboration checks
4125 @cindex Check, elaboration
4126 Enables dynamic checks for access-before-elaboration
4127 on subprogram calls and generic instantiations.
4128 For full details of the effect and use of this switch,
4129 @xref{Compiling Using gcc}.
4134 The setting of these switches only controls the default setting of the
4135 checks. You may modify them using either @code{Suppress} (to remove
4136 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
4139 @node Stack Overflow Checking
4140 @subsection Stack Overflow Checking
4141 @cindex Stack Overflow Checking
4142 @cindex -fstack-check
4145 For most operating systems, @code{gcc} does not perform stack overflow
4146 checking by default. This means that if the main environment task or
4147 some other task exceeds the available stack space, then unpredictable
4148 behavior will occur.
4150 To activate stack checking, compile all units with the gcc option
4151 @code{-fstack-check}. For example:
4154 gcc -c -fstack-check package1.adb
4158 Units compiled with this option will generate extra instructions to check
4159 that any use of the stack (for procedure calls or for declaring local
4160 variables in declare blocks) do not exceed the available stack space.
4161 If the space is exceeded, then a @code{Storage_Error} exception is raised.
4163 For declared tasks, the stack size is always controlled by the size
4164 given in an applicable @code{Storage_Size} pragma (or is set to
4165 the default size if no pragma is used.
4167 For the environment task, the stack size depends on
4168 system defaults and is unknown to the compiler. The stack
4169 may even dynamically grow on some systems, precluding the
4170 normal Ada semantics for stack overflow. In the worst case,
4171 unbounded stack usage, causes unbounded stack expansion
4172 resulting in the system running out of virtual memory.
4174 The stack checking may still work correctly if a fixed
4175 size stack is allocated, but this cannot be guaranteed.
4176 To ensure that a clean exception is signalled for stack
4177 overflow, set the environment variable
4178 @code{GNAT_STACK_LIMIT} to indicate the maximum
4179 stack area that can be used, as in:
4180 @cindex GNAT_STACK_LIMIT
4183 SET GNAT_STACK_LIMIT 1600
4187 The limit is given in kilobytes, so the above declaration would
4188 set the stack limit of the environment task to 1.6 megabytes.
4189 Note that the only purpose of this usage is to limit the amount
4190 of stack used by the environment task. If it is necessary to
4191 increase the amount of stack for the environment task, then this
4192 is an operating systems issue, and must be addressed with the
4193 appropriate operating systems commands.
4195 @node Run-Time Control
4196 @subsection Run-Time Control
4200 @cindex @option{-gnatT} (@code{gcc})
4201 @cindex Time Slicing
4204 The @code{gnatT} switch can be used to specify the time-slicing value
4205 to be used for task switching between equal priority tasks. The value
4206 @code{nnn} is given in microseconds as a decimal integer.
4208 Setting the time-slicing value is only effective if the underlying thread
4209 control system can accommodate time slicing. Check the documentation of
4210 your operating system for details. Note that the time-slicing value can
4211 also be set by use of pragma @code{Time_Slice} or by use of the
4212 @code{t} switch in the gnatbind step. The pragma overrides a command
4213 line argument if both are present, and the @code{t} switch for gnatbind
4214 overrides both the pragma and the @code{gcc} command line switch.
4217 @node Using gcc for Syntax Checking
4218 @subsection Using @code{gcc} for Syntax Checking
4221 @cindex @option{-gnats} (@code{gcc})
4224 The @code{s} stands for syntax.
4226 Run GNAT in syntax checking only mode. For
4227 example, the command
4230 $ gcc -c -gnats x.adb
4234 compiles file @file{x.adb} in syntax-check-only mode. You can check a
4235 series of files in a single command
4236 , and can use wild cards to specify such a group of files.
4237 Note that you must specify the @code{-c} (compile
4238 only) flag in addition to the @option{-gnats} flag.
4241 You may use other switches in conjunction with @option{-gnats}. In
4242 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
4243 format of any generated error messages.
4245 The output is simply the error messages, if any. No object file or ALI
4246 file is generated by a syntax-only compilation. Also, no units other
4247 than the one specified are accessed. For example, if a unit @code{X}
4248 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
4249 check only mode does not access the source file containing unit
4252 @cindex Multiple units, syntax checking
4253 Normally, GNAT allows only a single unit in a source file. However, this
4254 restriction does not apply in syntax-check-only mode, and it is possible
4255 to check a file containing multiple compilation units concatenated
4256 together. This is primarily used by the @code{gnatchop} utility
4257 (@pxref{Renaming Files Using gnatchop}).
4260 @node Using gcc for Semantic Checking
4261 @subsection Using @code{gcc} for Semantic Checking
4264 @cindex @option{-gnatc} (@code{gcc})
4267 The @code{c} stands for check.
4268 Causes the compiler to operate in semantic check mode,
4269 with full checking for all illegalities specified in the
4270 Ada 95 Reference Manual, but without generation of any object code
4271 (no object file is generated).
4273 Because dependent files must be accessed, you must follow the GNAT
4274 semantic restrictions on file structuring to operate in this mode:
4278 The needed source files must be accessible
4279 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4282 Each file must contain only one compilation unit.
4285 The file name and unit name must match (@pxref{File Naming Rules}).
4288 The output consists of error messages as appropriate. No object file is
4289 generated. An @file{ALI} file is generated for use in the context of
4290 cross-reference tools, but this file is marked as not being suitable
4291 for binding (since no object file is generated).
4292 The checking corresponds exactly to the notion of
4293 legality in the Ada 95 Reference Manual.
4295 Any unit can be compiled in semantics-checking-only mode, including
4296 units that would not normally be compiled (subunits,
4297 and specifications where a separate body is present).
4300 @node Compiling Ada 83 Programs
4301 @subsection Compiling Ada 83 Programs
4303 @cindex Ada 83 compatibility
4305 @cindex @option{-gnat83} (@code{gcc})
4306 @cindex ACVC, Ada 83 tests
4309 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
4310 specify that an Ada 83 program is to be compiled in Ada83 mode. If you specify
4311 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
4312 where this can be done easily.
4313 It is not possible to guarantee this switch does a perfect
4314 job; for example, some subtle tests, such as are
4315 found in earlier ACVC tests (that have been removed from the ACVC suite for Ada
4316 95), may not compile correctly. However, for most purposes, using
4317 this switch should help to ensure that programs that compile correctly
4318 under the @option{-gnat83} switch can be ported easily to an Ada 83
4319 compiler. This is the main use of the switch.
4321 With few exceptions (most notably the need to use @code{<>} on
4322 @cindex Generic formal parameters
4323 unconstrained generic formal parameters, the use of the new Ada 95
4324 keywords, and the use of packages
4325 with optional bodies), it is not necessary to use the
4326 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
4327 exceptions, Ada 95 is upwardly compatible with Ada 83. This
4328 means that a correct Ada 83 program is usually also a correct Ada 95
4333 @node Character Set Control
4334 @subsection Character Set Control
4337 @cindex @code{-gnati} (@code{gcc})
4340 Normally GNAT recognizes the Latin-1 character set in source program
4341 identifiers, as described in the Ada 95 Reference Manual.
4343 GNAT to recognize alternate character sets in identifiers. @var{c} is a
4344 single character indicating the character set, as follows:
4351 Latin-2 letters allowed in identifiers
4354 Latin-3 letters allowed in identifiers
4357 Latin-4 letters allowed in identifiers
4360 Latin-5 (Cyrillic) letters allowed in identifiers
4363 Latin-9 letters allowed in identifiers
4366 IBM PC letters (code page 437) allowed in identifiers
4369 IBM PC letters (code page 850) allowed in identifiers
4372 Full upper-half codes allowed in identifiers
4375 No upper-half codes allowed in identifiers
4378 Wide-character codes (that is, codes greater than 255)
4379 allowed in identifiers
4382 @xref{Foreign Language Representation}, for full details on the
4383 implementation of these character sets.
4386 @cindex @code{-gnatW} (@code{gcc})
4387 Specify the method of encoding for wide characters.
4388 @var{e} is one of the following:
4393 Hex encoding (brackets coding also recognized)
4396 Upper half encoding (brackets encoding also recognized)
4399 Shift/JIS encoding (brackets encoding also recognized)
4402 EUC encoding (brackets encoding also recognized)
4405 UTF-8 encoding (brackets encoding also recognized)
4408 Brackets encoding only (default value)
4410 For full details on the these encoding
4411 methods see @xref{Wide Character Encodings}.
4412 Note that brackets coding is always accepted, even if one of the other
4413 options is specified, so for example @option{-gnatW8} specifies that both
4414 brackets and @code{UTF-8} encodings will be recognized. The units that are
4415 with'ed directly or indirectly will be scanned using the specified
4416 representation scheme, and so if one of the non-brackets scheme is
4417 used, it must be used consistently throughout the program. However,
4418 since brackets encoding is always recognized, it may be conveniently
4419 used in standard libraries, allowing these libraries to be used with
4420 any of the available coding schemes.
4421 scheme. If no @option{-gnatW?} parameter is present, then the default
4422 representation is Brackets encoding only.
4424 Note that the wide character representation that is specified (explicitly
4425 or by default) for the main program also acts as the default encoding used
4426 for Wide_Text_IO files if not specifically overridden by a WCEM form
4430 @node File Naming Control
4431 @subsection File Naming Control
4435 @cindex @option{-gnatk} (@code{gcc})
4436 Activates file name "krunching". @var{n}, a decimal integer in the range
4437 1-999, indicates the maximum allowable length of a file name (not
4438 including the @file{.ads} or @file{.adb} extension). The default is not
4439 to enable file name krunching.
4441 For the source file naming rules, @xref{File Naming Rules}.
4444 @node Subprogram Inlining Control
4445 @subsection Subprogram Inlining Control
4449 @cindex @option{-gnatn} (@code{gcc})
4450 The @code{n} here is intended to suggest the first syllable of the
4452 GNAT recognizes and processes @code{Inline} pragmas. However, for the
4453 inlining to actually occur, optimization must be enabled. To enable
4454 inlining across unit boundaries, this is, inlining a call in one unit of
4455 a subprogram declared in a @code{with}'ed unit, you must also specify
4457 In the absence of this switch, GNAT does not attempt
4458 inlining across units and does not need to access the bodies of
4459 subprograms for which @code{pragma Inline} is specified if they are not
4460 in the current unit.
4462 If you specify this switch the compiler will access these bodies,
4463 creating an extra source dependency for the resulting object file, and
4464 where possible, the call will be inlined.
4465 For further details on when inlining is possible
4466 see @xref{Inlining of Subprograms}.
4469 @cindex @option{-gnatN} (@code{gcc})
4470 The front end inlining activated by this switch is generally more extensive,
4471 and quite often more effective than the standard @option{-gnatn} inlining mode.
4472 It will also generate additional dependencies.
4476 @node Auxiliary Output Control
4477 @subsection Auxiliary Output Control
4481 @cindex @option{-gnatt} (@code{gcc})
4482 @cindex Writing internal trees
4483 @cindex Internal trees, writing to file
4484 Causes GNAT to write the internal tree for a unit to a file (with the
4485 extension @file{.adt}.
4486 This not normally required, but is used by separate analysis tools.
4488 these tools do the necessary compilations automatically, so you should
4489 not have to specify this switch in normal operation.
4492 @cindex @option{-gnatu} (@code{gcc})
4493 Print a list of units required by this compilation on @file{stdout}.
4494 The listing includes all units on which the unit being compiled depends
4495 either directly or indirectly.
4497 @item -pass-exit-codes
4498 @cindex @code{-pass-exit-codes} (@code{gcc})
4499 If this switch is not used, the exit code returned by @code{gcc} when
4500 compiling multiple files indicates whether all source files have
4501 been successfully used to generate object files or not.
4503 When @code{-pass-exit-codes} is used, @code{gcc} exits with an extended
4504 exit status and allows an integrated development environment to better
4505 react to a compilation failure. Those exit status are:
4509 There was an error in at least one source file.
4511 At least one source file did not generate an object file.
4513 The compiler died unexpectedly (internal error for example).
4515 An object file has been generated for every source file.
4519 @node Debugging Control
4520 @subsection Debugging Control
4523 @cindex Debugging options
4525 Activate internal debugging switches. @var{x} is a letter or digit, or
4526 string of letters or digits, which specifies the type of debugging
4527 outputs desired. Normally these are used only for internal development
4528 or system debugging purposes. You can find full documentation for these
4529 switches in the body of the @code{Debug} unit in the compiler source
4530 file @file{debug.adb}.
4533 @cindex @option{-gnatG} (@code{gcc})
4534 This switch causes the compiler to generate auxiliary output containing
4535 a pseudo-source listing of the generated expanded code. Like most Ada
4536 compilers, GNAT works by first transforming the high level Ada code into
4537 lower level constructs. For example, tasking operations are transformed
4538 into calls to the tasking run-time routines. A unique capability of GNAT
4539 is to list this expanded code in a form very close to normal Ada source.
4540 This is very useful in understanding the implications of various Ada
4541 usage on the efficiency of the generated code. There are many cases in
4542 Ada (e.g. the use of controlled types), where simple Ada statements can
4543 generate a lot of run-time code. By using @option{-gnatG} you can identify
4544 these cases, and consider whether it may be desirable to modify the coding
4545 approach to improve efficiency.
4547 The format of the output is very similar to standard Ada source, and is
4548 easily understood by an Ada programmer. The following special syntactic
4549 additions correspond to low level features used in the generated code that
4550 do not have any exact analogies in pure Ada source form. The following
4551 is a partial list of these special constructions. See the specification
4552 of package @code{Sprint} in file @file{sprint.ads} for a full list.
4555 @item new @var{xxx} [storage_pool = @var{yyy}]
4556 Shows the storage pool being used for an allocator.
4558 @item at end @var{procedure-name};
4559 Shows the finalization (cleanup) procedure for a scope.
4561 @item (if @var{expr} then @var{expr} else @var{expr})
4562 Conditional expression equivalent to the @code{x?y:z} construction in C.
4564 @item @var{target}^(@var{source})
4565 A conversion with floating-point truncation instead of rounding.
4567 @item @var{target}?(@var{source})
4568 A conversion that bypasses normal Ada semantic checking. In particular
4569 enumeration types and fixed-point types are treated simply as integers.
4571 @item @var{target}?^(@var{source})
4572 Combines the above two cases.
4574 @item @var{x} #/ @var{y}
4575 @itemx @var{x} #mod @var{y}
4576 @itemx @var{x} #* @var{y}
4577 @itemx @var{x} #rem @var{y}
4578 A division or multiplication of fixed-point values which are treated as
4579 integers without any kind of scaling.
4581 @item free @var{expr} [storage_pool = @var{xxx}]
4582 Shows the storage pool associated with a @code{free} statement.
4584 @item freeze @var{typename} [@var{actions}]
4585 Shows the point at which @var{typename} is frozen, with possible
4586 associated actions to be performed at the freeze point.
4588 @item reference @var{itype}
4589 Reference (and hence definition) to internal type @var{itype}.
4591 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
4592 Intrinsic function call.
4594 @item @var{labelname} : label
4595 Declaration of label @var{labelname}.
4597 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
4598 A multiple concatenation (same effect as @var{expr} & @var{expr} &
4599 @var{expr}, but handled more efficiently).
4601 @item [constraint_error]
4602 Raise the @code{Constraint_Error} exception.
4604 @item @var{expression}'reference
4605 A pointer to the result of evaluating @var{expression}.
4607 @item @var{target-type}!(@var{source-expression})
4608 An unchecked conversion of @var{source-expression} to @var{target-type}.
4610 @item [@var{numerator}/@var{denominator}]
4611 Used to represent internal real literals (that) have no exact
4612 representation in base 2-16 (for example, the result of compile time
4613 evaluation of the expression 1.0/27.0).
4616 @cindex @option{-gnatD} (@code{gcc})
4617 This switch is used in conjunction with @option{-gnatG} to cause the expanded
4618 source, as described above to be written to files with names
4619 @file{xxx.dg}, where @file{xxx} is the normal file name,
4620 for example, if the source file name is @file{hello.adb},
4621 then a file @file{hello.adb.dg} will be written.
4622 The debugging information generated
4623 by the @code{gcc} @code{-g} switch will refer to the generated
4624 @file{xxx.dg} file. This allows you to do source level debugging using
4625 the generated code which is sometimes useful for complex code, for example
4626 to find out exactly which part of a complex construction raised an
4627 exception. This switch also suppress generation of cross-reference
4628 information (see -gnatx).
4631 @cindex @option{-gnatE} (@code{gcc})
4632 In the generated debugging information, and also in the case of long external
4633 names, the compiler uses a compression mechanism if the name is very long.
4634 This compression method uses a checksum, and avoids trouble on some operating
4635 systems which have difficulty with very long names. The @option{-gnatC} switch
4636 forces this compression approach to be used on all external names and names
4637 in the debugging information tables. This reduces the size of the generated
4638 executable, at the expense of making the naming scheme more complex. The
4639 compression only affects the qualification of the name. Thus a name in
4643 Very_Long_Package.Very_Long_Inner_Package.Var
4647 would normally appear in these tables as:
4650 very_long_package__very_long_inner_package__var
4654 but if the @option{-gnatC} switch is used, then the name appears as
4661 Here b7e0c705 is a compressed encoding of the qualification prefix.
4662 The GNAT Ada aware version of GDB understands these encoded prefixes, so if this
4663 debugger is used, the encoding is largely hidden from the user of the compiler.
4667 @item -gnatR[0|1|2|3][s]
4668 @cindex @option{-gnatR} (@code{gcc})
4669 This switch controls output from the compiler of a listing showing
4670 representation information for declared types and objects. For
4671 @option{-gnatR0}, no information is output (equivalent to omitting
4672 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
4673 so @option{-gnatR} with no parameter has the same effect), size and alignment
4674 information is listed for declared array and record types. For
4675 @option{-gnatR2}, size and alignment information is listed for all
4676 expression information for values that are computed at run time for
4677 variant records. These symbolic expressions have a mostly obvious
4678 format with #n being used to represent the value of the n'th
4679 discriminant. See source files @file{repinfo.ads/adb} in the
4680 @code{GNAT} sources for full detalis on the format of @option{-gnatR3}
4681 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
4682 the output is to a file with the name @file{file.rep} where
4683 file is the name of the corresponding source file.
4686 @cindex @option{-gnatx} (@code{gcc})
4687 Normally the compiler generates full cross-referencing information in
4688 the @file{ALI} file. This information is used by a number of tools,
4689 including @code{gnatfind} and @code{gnatxref}. The -gnatx switch
4690 suppresses this information. This saves some space and may slightly
4691 speed up compilation, but means that these tools cannot be used.
4694 @node Units to Sources Mapping Files
4695 @subsection Units to Sources Mapping Files
4699 @item -gnatem@var{path}
4700 @cindex @option{-gnatem} (@code{gcc})
4701 A mapping file is a way to communicate to the compiler two mappings:
4702 from unit names to file names (without any directory information) and from
4703 file names to path names (with full directory information). These mappings
4704 are used by the compiler to short-circuit the path search.
4706 A mapping file is a sequence of sets of three lines. In each set,
4707 the first line is the unit name, in lower case, with "%s" appended for
4708 specifications and "%b" appended for bodies; the second line is the file
4709 name; and the third line is the path name.
4715 /gnat/project1/sources/main.2.ada
4718 When the switch @option{-gnatem} is specified, the compiler will create
4719 in memory the two mappings from the specified file. If there is any problem
4720 (non existent file, truncated file or duplicate entries), no mapping
4723 Several @option{-gnatem} switches may be specified; however, only the last
4724 one on the command line will be taken into account.
4726 When using a project file, @code{gnatmake} create a temporary mapping file
4727 and communicates it to the compiler using this switch.
4731 @node Search Paths and the Run-Time Library (RTL)
4732 @section Search Paths and the Run-Time Library (RTL)
4735 With the GNAT source-based library system, the compiler must be able to
4736 find source files for units that are needed by the unit being compiled.
4737 Search paths are used to guide this process.
4739 The compiler compiles one source file whose name must be given
4740 explicitly on the command line. In other words, no searching is done
4741 for this file. To find all other source files that are needed (the most
4742 common being the specs of units), the compiler examines the following
4743 directories, in the following order:
4747 The directory containing the source file of the main unit being compiled
4748 (the file name on the command line).
4751 Each directory named by an @code{-I} switch given on the @code{gcc}
4752 command line, in the order given.
4755 @findex ADA_INCLUDE_PATH
4756 Each of the directories listed in the value of the
4757 @code{ADA_INCLUDE_PATH} environment variable.
4758 Construct this value
4759 exactly as the @code{PATH} environment variable: a list of directory
4760 names separated by colons (semicolons when working with the NT version).
4762 The content of the "ada_source_path" file which is part of the GNAT
4763 installation tree and is used to store standard libraries such as the
4764 GNAT Run Time Library (RTL) source files.
4765 @ref{Installing an Ada Library}
4769 Specifying the switch @code{-I-}
4770 inhibits the use of the directory
4771 containing the source file named in the command line. You can still
4772 have this directory on your search path, but in this case it must be
4773 explicitly requested with a @code{-I} switch.
4775 Specifying the switch @code{-nostdinc}
4776 inhibits the search of the default location for the GNAT Run Time
4777 Library (RTL) source files.
4779 The compiler outputs its object files and ALI files in the current
4781 Caution: The object file can be redirected with the @code{-o} switch;
4782 however, @code{gcc} and @code{gnat1} have not been coordinated on this
4783 so the ALI file will not go to the right place. Therefore, you should
4784 avoid using the @code{-o} switch.
4787 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
4788 children make up the GNAT RTL, together with the simple @code{System.IO}
4789 package used in the "Hello World" example. The sources for these units
4790 are needed by the compiler and are kept together in one directory. Not
4791 all of the bodies are needed, but all of the sources are kept together
4792 anyway. In a normal installation, you need not specify these directory
4793 names when compiling or binding. Either the environment variables or
4794 the built-in defaults cause these files to be found.
4796 In addition to the language-defined hierarchies (System, Ada and
4797 Interfaces), the GNAT distribution provides a fourth hierarchy,
4798 consisting of child units of GNAT. This is a collection of generally
4799 useful routines. See the GNAT Reference Manual for further details.
4801 Besides simplifying access to the RTL, a major use of search paths is
4802 in compiling sources from multiple directories. This can make
4803 development environments much more flexible.
4805 @node Order of Compilation Issues
4806 @section Order of Compilation Issues
4809 If, in our earlier example, there was a spec for the @code{hello}
4810 procedure, it would be contained in the file @file{hello.ads}; yet this
4811 file would not have to be explicitly compiled. This is the result of the
4812 model we chose to implement library management. Some of the consequences
4813 of this model are as follows:
4817 There is no point in compiling specs (except for package
4818 specs with no bodies) because these are compiled as needed by clients. If
4819 you attempt a useless compilation, you will receive an error message.
4820 It is also useless to compile subunits because they are compiled as needed
4824 There are no order of compilation requirements: performing a
4825 compilation never obsoletes anything. The only way you can obsolete
4826 something and require recompilations is to modify one of the
4827 source files on which it depends.
4830 There is no library as such, apart from the ALI files
4831 (@pxref{The Ada Library Information Files}, for information on the format of these
4832 files). For now we find it convenient to create separate ALI files, but
4833 eventually the information therein may be incorporated into the object
4837 When you compile a unit, the source files for the specs of all units
4838 that it @code{with}'s, all its subunits, and the bodies of any generics it
4839 instantiates must be available (reachable by the search-paths mechanism
4840 described above), or you will receive a fatal error message.
4847 The following are some typical Ada compilation command line examples:
4850 @item $ gcc -c xyz.adb
4851 Compile body in file @file{xyz.adb} with all default options.
4853 @item $ gcc -c -O2 -gnata xyz-def.adb
4855 Compile the child unit package in file @file{xyz-def.adb} with extensive
4856 optimizations, and pragma @code{Assert}/@code{Debug} statements
4859 @item $ gcc -c -gnatc abc-def.adb
4860 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
4864 @node Binding Using gnatbind
4865 @chapter Binding Using @code{gnatbind}
4869 * Running gnatbind::
4870 * Generating the Binder Program in C::
4871 * Consistency-Checking Modes::
4872 * Binder Error Message Control::
4873 * Elaboration Control::
4875 * Binding with Non-Ada Main Programs::
4876 * Binding Programs with No Main Subprogram::
4877 * Summary of Binder Switches::
4878 * Command-Line Access::
4879 * Search Paths for gnatbind::
4880 * Examples of gnatbind Usage::
4884 This chapter describes the GNAT binder, @code{gnatbind}, which is used
4885 to bind compiled GNAT objects. The @code{gnatbind} program performs
4886 four separate functions:
4890 Checks that a program is consistent, in accordance with the rules in
4891 Chapter 10 of the Ada 95 Reference Manual. In particular, error
4892 messages are generated if a program uses inconsistent versions of a
4896 Checks that an acceptable order of elaboration exists for the program
4897 and issues an error message if it cannot find an order of elaboration
4898 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
4901 Generates a main program incorporating the given elaboration order.
4902 This program is a small Ada package (body and spec) that
4903 must be subsequently compiled
4904 using the GNAT compiler. The necessary compilation step is usually
4905 performed automatically by @code{gnatlink}. The two most important
4906 functions of this program
4907 are to call the elaboration routines of units in an appropriate order
4908 and to call the main program.
4911 Determines the set of object files required by the given main program.
4912 This information is output in the forms of comments in the generated program,
4913 to be read by the @code{gnatlink} utility used to link the Ada application.
4916 @node Running gnatbind
4917 @section Running @code{gnatbind}
4920 The form of the @code{gnatbind} command is
4923 $ gnatbind [@var{switches}] @var{mainprog}[.ali] [@var{switches}]
4927 where @var{mainprog}.adb is the Ada file containing the main program
4928 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
4929 package in two files which names are
4930 @file{b~@var{ada_main}.ads}, and @file{b~@var{ada_main}.adb}.
4931 For example, if given the
4932 parameter @samp{hello.ali}, for a main program contained in file
4933 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
4934 and @file{b~hello.adb}.
4936 When doing consistency checking, the binder takes into consideration
4937 any source files it can locate. For example, if the binder determines
4938 that the given main program requires the package @code{Pack}, whose
4940 file is @file{pack.ali} and whose corresponding source spec file is
4941 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
4942 (using the same search path conventions as previously described for the
4943 @code{gcc} command). If it can locate this source file, it checks that
4945 or source checksums of the source and its references to in @file{ali} files
4946 match. In other words, any @file{ali} files that mentions this spec must have
4947 resulted from compiling this version of the source file (or in the case
4948 where the source checksums match, a version close enough that the
4949 difference does not matter).
4951 @cindex Source files, use by binder
4952 The effect of this consistency checking, which includes source files, is
4953 that the binder ensures that the program is consistent with the latest
4954 version of the source files that can be located at bind time. Editing a
4955 source file without compiling files that depend on the source file cause
4956 error messages to be generated by the binder.
4958 For example, suppose you have a main program @file{hello.adb} and a
4959 package @code{P}, from file @file{p.ads} and you perform the following
4964 Enter @code{gcc -c hello.adb} to compile the main program.
4967 Enter @code{gcc -c p.ads} to compile package @code{P}.
4970 Edit file @file{p.ads}.
4973 Enter @code{gnatbind hello}.
4976 At this point, the file @file{p.ali} contains an out-of-date time stamp
4977 because the file @file{p.ads} has been edited. The attempt at binding
4978 fails, and the binder generates the following error messages:
4981 error: "hello.adb" must be recompiled ("p.ads" has been modified)
4982 error: "p.ads" has been modified and must be recompiled
4986 Now both files must be recompiled as indicated, and then the bind can
4987 succeed, generating a main program. You need not normally be concerned
4988 with the contents of this file, but it is similar to the following which
4989 is the binder file generated for a simple "hello world" program.
4995 -- The package is called Ada_Main unless this name is actually used
4996 -- as a unit name in the partition, in which case some other unique
5002 Elab_Final_Code : Integer;
5003 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
5005 -- The main program saves the parameters (argument count,
5006 -- argument values, environment pointer) in global variables
5007 -- for later access by other units including
5008 -- Ada.Command_Line.
5010 gnat_argc : Integer;
5011 gnat_argv : System.Address;
5012 gnat_envp : System.Address;
5014 -- The actual variables are stored in a library routine. This
5015 -- is useful for some shared library situations, where there
5016 -- are problems if variables are not in the library.
5018 pragma Import (C, gnat_argc);
5019 pragma Import (C, gnat_argv);
5020 pragma Import (C, gnat_envp);
5022 -- The exit status is similarly an external location
5024 gnat_exit_status : Integer;
5025 pragma Import (C, gnat_exit_status);
5027 GNAT_Version : constant String :=
5028 "GNAT Version: 3.15w (20010315)";
5029 pragma Export (C, GNAT_Version, "__gnat_version");
5031 -- This is the generated adafinal routine that performs
5032 -- finalization at the end of execution. In the case where
5033 -- Ada is the main program, this main program makes a call
5034 -- to adafinal at program termination.
5037 pragma Export (C, adafinal, "adafinal");
5039 -- This is the generated adainit routine that performs
5040 -- initialization at the start of execution. In the case
5041 -- where Ada is the main program, this main program makes
5042 -- a call to adainit at program startup.
5045 pragma Export (C, adainit, "adainit");
5047 -- This routine is called at the start of execution. It is
5048 -- a dummy routine that is used by the debugger to breakpoint
5049 -- at the start of execution.
5051 procedure Break_Start;
5052 pragma Import (C, Break_Start, "__gnat_break_start");
5054 -- This is the actual generated main program (it would be
5055 -- suppressed if the no main program switch were used). As
5056 -- required by standard system conventions, this program has
5057 -- the external name main.
5061 argv : System.Address;
5062 envp : System.Address)
5064 pragma Export (C, main, "main");
5066 -- The following set of constants give the version
5067 -- identification values for every unit in the bound
5068 -- partition. This identification is computed from all
5069 -- dependent semantic units, and corresponds to the
5070 -- string that would be returned by use of the
5071 -- Body_Version or Version attributes.
5073 type Version_32 is mod 2 ** 32;
5074 u00001 : constant Version_32 := 16#7880BEB3#;
5075 u00002 : constant Version_32 := 16#0D24CBD0#;
5076 u00003 : constant Version_32 := 16#3283DBEB#;
5077 u00004 : constant Version_32 := 16#2359F9ED#;
5078 u00005 : constant Version_32 := 16#664FB847#;
5079 u00006 : constant Version_32 := 16#68E803DF#;
5080 u00007 : constant Version_32 := 16#5572E604#;
5081 u00008 : constant Version_32 := 16#46B173D8#;
5082 u00009 : constant Version_32 := 16#156A40CF#;
5083 u00010 : constant Version_32 := 16#033DABE0#;
5084 u00011 : constant Version_32 := 16#6AB38FEA#;
5085 u00012 : constant Version_32 := 16#22B6217D#;
5086 u00013 : constant Version_32 := 16#68A22947#;
5087 u00014 : constant Version_32 := 16#18CC4A56#;
5088 u00015 : constant Version_32 := 16#08258E1B#;
5089 u00016 : constant Version_32 := 16#367D5222#;
5090 u00017 : constant Version_32 := 16#20C9ECA4#;
5091 u00018 : constant Version_32 := 16#50D32CB6#;
5092 u00019 : constant Version_32 := 16#39A8BB77#;
5093 u00020 : constant Version_32 := 16#5CF8FA2B#;
5094 u00021 : constant Version_32 := 16#2F1EB794#;
5095 u00022 : constant Version_32 := 16#31AB6444#;
5096 u00023 : constant Version_32 := 16#1574B6E9#;
5097 u00024 : constant Version_32 := 16#5109C189#;
5098 u00025 : constant Version_32 := 16#56D770CD#;
5099 u00026 : constant Version_32 := 16#02F9DE3D#;
5100 u00027 : constant Version_32 := 16#08AB6B2C#;
5101 u00028 : constant Version_32 := 16#3FA37670#;
5102 u00029 : constant Version_32 := 16#476457A0#;
5103 u00030 : constant Version_32 := 16#731E1B6E#;
5104 u00031 : constant Version_32 := 16#23C2E789#;
5105 u00032 : constant Version_32 := 16#0F1BD6A1#;
5106 u00033 : constant Version_32 := 16#7C25DE96#;
5107 u00034 : constant Version_32 := 16#39ADFFA2#;
5108 u00035 : constant Version_32 := 16#571DE3E7#;
5109 u00036 : constant Version_32 := 16#5EB646AB#;
5110 u00037 : constant Version_32 := 16#4249379B#;
5111 u00038 : constant Version_32 := 16#0357E00A#;
5112 u00039 : constant Version_32 := 16#3784FB72#;
5113 u00040 : constant Version_32 := 16#2E723019#;
5114 u00041 : constant Version_32 := 16#623358EA#;
5115 u00042 : constant Version_32 := 16#107F9465#;
5116 u00043 : constant Version_32 := 16#6843F68A#;
5117 u00044 : constant Version_32 := 16#63305874#;
5118 u00045 : constant Version_32 := 16#31E56CE1#;
5119 u00046 : constant Version_32 := 16#02917970#;
5120 u00047 : constant Version_32 := 16#6CCBA70E#;
5121 u00048 : constant Version_32 := 16#41CD4204#;
5122 u00049 : constant Version_32 := 16#572E3F58#;
5123 u00050 : constant Version_32 := 16#20729FF5#;
5124 u00051 : constant Version_32 := 16#1D4F93E8#;
5125 u00052 : constant Version_32 := 16#30B2EC3D#;
5126 u00053 : constant Version_32 := 16#34054F96#;
5127 u00054 : constant Version_32 := 16#5A199860#;
5128 u00055 : constant Version_32 := 16#0E7F912B#;
5129 u00056 : constant Version_32 := 16#5760634A#;
5130 u00057 : constant Version_32 := 16#5D851835#;
5132 -- The following Export pragmas export the version numbers
5133 -- with symbolic names ending in B (for body) or S
5134 -- (for spec) so that they can be located in a link. The
5135 -- information provided here is sufficient to track down
5136 -- the exact versions of units used in a given build.
5138 pragma Export (C, u00001, "helloB");
5139 pragma Export (C, u00002, "system__standard_libraryB");
5140 pragma Export (C, u00003, "system__standard_libraryS");
5141 pragma Export (C, u00004, "adaS");
5142 pragma Export (C, u00005, "ada__text_ioB");
5143 pragma Export (C, u00006, "ada__text_ioS");
5144 pragma Export (C, u00007, "ada__exceptionsB");
5145 pragma Export (C, u00008, "ada__exceptionsS");
5146 pragma Export (C, u00009, "gnatS");
5147 pragma Export (C, u00010, "gnat__heap_sort_aB");
5148 pragma Export (C, u00011, "gnat__heap_sort_aS");
5149 pragma Export (C, u00012, "systemS");
5150 pragma Export (C, u00013, "system__exception_tableB");
5151 pragma Export (C, u00014, "system__exception_tableS");
5152 pragma Export (C, u00015, "gnat__htableB");
5153 pragma Export (C, u00016, "gnat__htableS");
5154 pragma Export (C, u00017, "system__exceptionsS");
5155 pragma Export (C, u00018, "system__machine_state_operationsB");
5156 pragma Export (C, u00019, "system__machine_state_operationsS");
5157 pragma Export (C, u00020, "system__machine_codeS");
5158 pragma Export (C, u00021, "system__storage_elementsB");
5159 pragma Export (C, u00022, "system__storage_elementsS");
5160 pragma Export (C, u00023, "system__secondary_stackB");
5161 pragma Export (C, u00024, "system__secondary_stackS");
5162 pragma Export (C, u00025, "system__parametersB");
5163 pragma Export (C, u00026, "system__parametersS");
5164 pragma Export (C, u00027, "system__soft_linksB");
5165 pragma Export (C, u00028, "system__soft_linksS");
5166 pragma Export (C, u00029, "system__stack_checkingB");
5167 pragma Export (C, u00030, "system__stack_checkingS");
5168 pragma Export (C, u00031, "system__tracebackB");
5169 pragma Export (C, u00032, "system__tracebackS");
5170 pragma Export (C, u00033, "ada__streamsS");
5171 pragma Export (C, u00034, "ada__tagsB");
5172 pragma Export (C, u00035, "ada__tagsS");
5173 pragma Export (C, u00036, "system__string_opsB");
5174 pragma Export (C, u00037, "system__string_opsS");
5175 pragma Export (C, u00038, "interfacesS");
5176 pragma Export (C, u00039, "interfaces__c_streamsB");
5177 pragma Export (C, u00040, "interfaces__c_streamsS");
5178 pragma Export (C, u00041, "system__file_ioB");
5179 pragma Export (C, u00042, "system__file_ioS");
5180 pragma Export (C, u00043, "ada__finalizationB");
5181 pragma Export (C, u00044, "ada__finalizationS");
5182 pragma Export (C, u00045, "system__finalization_rootB");
5183 pragma Export (C, u00046, "system__finalization_rootS");
5184 pragma Export (C, u00047, "system__finalization_implementationB");
5185 pragma Export (C, u00048, "system__finalization_implementationS");
5186 pragma Export (C, u00049, "system__string_ops_concat_3B");
5187 pragma Export (C, u00050, "system__string_ops_concat_3S");
5188 pragma Export (C, u00051, "system__stream_attributesB");
5189 pragma Export (C, u00052, "system__stream_attributesS");
5190 pragma Export (C, u00053, "ada__io_exceptionsS");
5191 pragma Export (C, u00054, "system__unsigned_typesS");
5192 pragma Export (C, u00055, "system__file_control_blockS");
5193 pragma Export (C, u00056, "ada__finalization__list_controllerB");
5194 pragma Export (C, u00057, "ada__finalization__list_controllerS");
5196 -- BEGIN ELABORATION ORDER
5199 -- gnat.heap_sort_a (spec)
5200 -- gnat.heap_sort_a (body)
5201 -- gnat.htable (spec)
5202 -- gnat.htable (body)
5203 -- interfaces (spec)
5205 -- system.machine_code (spec)
5206 -- system.parameters (spec)
5207 -- system.parameters (body)
5208 -- interfaces.c_streams (spec)
5209 -- interfaces.c_streams (body)
5210 -- system.standard_library (spec)
5211 -- ada.exceptions (spec)
5212 -- system.exception_table (spec)
5213 -- system.exception_table (body)
5214 -- ada.io_exceptions (spec)
5215 -- system.exceptions (spec)
5216 -- system.storage_elements (spec)
5217 -- system.storage_elements (body)
5218 -- system.machine_state_operations (spec)
5219 -- system.machine_state_operations (body)
5220 -- system.secondary_stack (spec)
5221 -- system.stack_checking (spec)
5222 -- system.soft_links (spec)
5223 -- system.soft_links (body)
5224 -- system.stack_checking (body)
5225 -- system.secondary_stack (body)
5226 -- system.standard_library (body)
5227 -- system.string_ops (spec)
5228 -- system.string_ops (body)
5231 -- ada.streams (spec)
5232 -- system.finalization_root (spec)
5233 -- system.finalization_root (body)
5234 -- system.string_ops_concat_3 (spec)
5235 -- system.string_ops_concat_3 (body)
5236 -- system.traceback (spec)
5237 -- system.traceback (body)
5238 -- ada.exceptions (body)
5239 -- system.unsigned_types (spec)
5240 -- system.stream_attributes (spec)
5241 -- system.stream_attributes (body)
5242 -- system.finalization_implementation (spec)
5243 -- system.finalization_implementation (body)
5244 -- ada.finalization (spec)
5245 -- ada.finalization (body)
5246 -- ada.finalization.list_controller (spec)
5247 -- ada.finalization.list_controller (body)
5248 -- system.file_control_block (spec)
5249 -- system.file_io (spec)
5250 -- system.file_io (body)
5251 -- ada.text_io (spec)
5252 -- ada.text_io (body)
5254 -- END ELABORATION ORDER
5258 -- The following source file name pragmas allow the generated file
5259 -- names to be unique for different main programs. They are needed
5260 -- since the package name will always be Ada_Main.
5262 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
5263 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
5265 -- Generated package body for Ada_Main starts here
5267 package body ada_main is
5269 -- The actual finalization is performed by calling the
5270 -- library routine in System.Standard_Library.Adafinal
5272 procedure Do_Finalize;
5273 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
5280 procedure adainit is
5282 -- These booleans are set to True once the associated unit has
5283 -- been elaborated. It is also used to avoid elaborating the
5286 E040 : Boolean; pragma Import (Ada, E040, "interfaces__c_streams_E");
5287 E008 : Boolean; pragma Import (Ada, E008, "ada__exceptions_E");
5288 E014 : Boolean; pragma Import (Ada, E014, "system__exception_table_E");
5289 E053 : Boolean; pragma Import (Ada, E053, "ada__io_exceptions_E");
5290 E017 : Boolean; pragma Import (Ada, E017, "system__exceptions_E");
5291 E024 : Boolean; pragma Import (Ada, E024, "system__secondary_stack_E");
5292 E030 : Boolean; pragma Import (Ada, E030, "system__stack_checking_E");
5293 E028 : Boolean; pragma Import (Ada, E028, "system__soft_links_E");
5294 E035 : Boolean; pragma Import (Ada, E035, "ada__tags_E");
5295 E033 : Boolean; pragma Import (Ada, E033, "ada__streams_E");
5296 E046 : Boolean; pragma Import (Ada, E046, "system__finalization_root_E");
5297 E048 : Boolean; pragma Import (Ada, E048, "system__finalization_implementation_E");
5298 E044 : Boolean; pragma Import (Ada, E044, "ada__finalization_E");
5299 E057 : Boolean; pragma Import (Ada, E057, "ada__finalization__list_controller_E");
5300 E055 : Boolean; pragma Import (Ada, E055, "system__file_control_block_E");
5301 E042 : Boolean; pragma Import (Ada, E042, "system__file_io_E");
5302 E006 : Boolean; pragma Import (Ada, E006, "ada__text_io_E");
5304 -- Set_Globals is a library routine that stores away the
5305 -- value of the indicated set of global values in global
5306 -- variables within the library.
5308 procedure Set_Globals
5309 (Main_Priority : Integer;
5310 Time_Slice_Value : Integer;
5311 WC_Encoding : Character;
5312 Locking_Policy : Character;
5313 Queuing_Policy : Character;
5314 Task_Dispatching_Policy : Character;
5315 Adafinal : System.Address;
5316 Unreserve_All_Interrupts : Integer;
5317 Exception_Tracebacks : Integer);
5318 @findex __gnat_set_globals
5319 pragma Import (C, Set_Globals, "__gnat_set_globals");
5321 -- SDP_Table_Build is a library routine used to build the
5322 -- exception tables. See unit Ada.Exceptions in files
5323 -- a-except.ads/adb for full details of how zero cost
5324 -- exception handling works. This procedure, the call to
5325 -- it, and the two following tables are all omitted if the
5326 -- build is in longjmp/setjump exception mode.
5328 @findex SDP_Table_Build
5329 @findex Zero Cost Exceptions
5330 procedure SDP_Table_Build
5331 (SDP_Addresses : System.Address;
5332 SDP_Count : Natural;
5333 Elab_Addresses : System.Address;
5334 Elab_Addr_Count : Natural);
5335 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
5337 -- Table of Unit_Exception_Table addresses. Used for zero
5338 -- cost exception handling to build the top level table.
5340 ST : aliased constant array (1 .. 23) of System.Address := (
5342 Ada.Text_Io'UET_Address,
5343 Ada.Exceptions'UET_Address,
5344 Gnat.Heap_Sort_A'UET_Address,
5345 System.Exception_Table'UET_Address,
5346 System.Machine_State_Operations'UET_Address,
5347 System.Secondary_Stack'UET_Address,
5348 System.Parameters'UET_Address,
5349 System.Soft_Links'UET_Address,
5350 System.Stack_Checking'UET_Address,
5351 System.Traceback'UET_Address,
5352 Ada.Streams'UET_Address,
5353 Ada.Tags'UET_Address,
5354 System.String_Ops'UET_Address,
5355 Interfaces.C_Streams'UET_Address,
5356 System.File_Io'UET_Address,
5357 Ada.Finalization'UET_Address,
5358 System.Finalization_Root'UET_Address,
5359 System.Finalization_Implementation'UET_Address,
5360 System.String_Ops_Concat_3'UET_Address,
5361 System.Stream_Attributes'UET_Address,
5362 System.File_Control_Block'UET_Address,
5363 Ada.Finalization.List_Controller'UET_Address);
5365 -- Table of addresses of elaboration routines. Used for
5366 -- zero cost exception handling to make sure these
5367 -- addresses are included in the top level procedure
5370 EA : aliased constant array (1 .. 23) of System.Address := (
5371 adainit'Code_Address,
5372 Do_Finalize'Code_Address,
5373 Ada.Exceptions'Elab_Spec'Address,
5374 System.Exceptions'Elab_Spec'Address,
5375 Interfaces.C_Streams'Elab_Spec'Address,
5376 System.Exception_Table'Elab_Body'Address,
5377 Ada.Io_Exceptions'Elab_Spec'Address,
5378 System.Stack_Checking'Elab_Spec'Address,
5379 System.Soft_Links'Elab_Body'Address,
5380 System.Secondary_Stack'Elab_Body'Address,
5381 Ada.Tags'Elab_Spec'Address,
5382 Ada.Tags'Elab_Body'Address,
5383 Ada.Streams'Elab_Spec'Address,
5384 System.Finalization_Root'Elab_Spec'Address,
5385 Ada.Exceptions'Elab_Body'Address,
5386 System.Finalization_Implementation'Elab_Spec'Address,
5387 System.Finalization_Implementation'Elab_Body'Address,
5388 Ada.Finalization'Elab_Spec'Address,
5389 Ada.Finalization.List_Controller'Elab_Spec'Address,
5390 System.File_Control_Block'Elab_Spec'Address,
5391 System.File_Io'Elab_Body'Address,
5392 Ada.Text_Io'Elab_Spec'Address,
5393 Ada.Text_Io'Elab_Body'Address);
5395 -- Start of processing for adainit
5399 -- Call SDP_Table_Build to build the top level procedure
5400 -- table for zero cost exception handling (omitted in
5401 -- longjmp/setjump mode).
5403 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
5405 -- Call Set_Globals to record various information for
5406 -- this partition. The values are derived by the binder
5407 -- from information stored in the ali files by the compiler.
5409 @findex __gnat_set_globals
5411 (Main_Priority => -1,
5412 -- Priority of main program, -1 if no pragma Priority used
5414 Time_Slice_Value => -1,
5415 -- Time slice from Time_Slice pragma, -1 if none used
5418 -- Wide_Character encoding used, default is brackets
5420 Locking_Policy => ' ',
5421 -- Locking_Policy used, default of space means not
5422 -- specified, otherwise it is the first character of
5425 Queuing_Policy => ' ',
5426 -- Queuing_Policy used, default of space means not
5427 -- specified, otherwise it is the first character of
5430 Task_Dispatching_Policy => ' ',
5431 -- Task_Dispatching_Policy used, default of space means
5432 -- not specified, otherwise first character of the
5435 Adafinal => System.Null_Address,
5436 -- Address of Adafinal routine, not used anymore
5438 Unreserve_All_Interrupts => 0,
5439 -- Set true if pragma Unreserve_All_Interrupts was used
5441 Exception_Tracebacks => 0);
5442 -- Indicates if exception tracebacks are enabled
5444 Elab_Final_Code := 1;
5446 -- Now we have the elaboration calls for all units in the partition.
5447 -- The Elab_Spec and Elab_Body attributes generate references to the
5448 -- implicit elaboration procedures generated by the compiler for
5449 -- each unit that requires elaboration.
5452 Interfaces.C_Streams'Elab_Spec;
5456 Ada.Exceptions'Elab_Spec;
5459 System.Exception_Table'Elab_Body;
5463 Ada.Io_Exceptions'Elab_Spec;
5467 System.Exceptions'Elab_Spec;
5471 System.Stack_Checking'Elab_Spec;
5474 System.Soft_Links'Elab_Body;
5479 System.Secondary_Stack'Elab_Body;
5490 Ada.Streams'Elab_Spec;
5494 System.Finalization_Root'Elab_Spec;
5498 Ada.Exceptions'Elab_Body;
5502 System.Finalization_Implementation'Elab_Spec;
5505 System.Finalization_Implementation'Elab_Body;
5509 Ada.Finalization'Elab_Spec;
5513 Ada.Finalization.List_Controller'Elab_Spec;
5517 System.File_Control_Block'Elab_Spec;
5521 System.File_Io'Elab_Body;
5525 Ada.Text_Io'Elab_Spec;
5528 Ada.Text_Io'Elab_Body;
5532 Elab_Final_Code := 0;
5540 procedure adafinal is
5549 -- main is actually a function, as in the ANSI C standard,
5550 -- defined to return the exit status. The three parameters
5551 -- are the argument count, argument values and environment
5554 @findex Main Program
5557 argv : System.Address;
5558 envp : System.Address)
5561 -- The initialize routine performs low level system
5562 -- initialization using a standard library routine which
5563 -- sets up signal handling and performs any other
5564 -- required setup. The routine can be found in file
5567 @findex __gnat_initialize
5568 procedure initialize;
5569 pragma Import (C, initialize, "__gnat_initialize");
5571 -- The finalize routine performs low level system
5572 -- finalization using a standard library routine. The
5573 -- routine is found in file a-final.c and in the standard
5574 -- distribution is a dummy routine that does nothing, so
5575 -- really this is a hook for special user finalization.
5577 @findex __gnat_finalize
5579 pragma Import (C, finalize, "__gnat_finalize");
5581 -- We get to the main program of the partition by using
5582 -- pragma Import because if we try to with the unit and
5583 -- call it Ada style, then not only do we waste time
5584 -- recompiling it, but also, we don't really know the right
5585 -- switches (e.g. identifier character set) to be used
5588 procedure Ada_Main_Program;
5589 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
5591 -- Start of processing for main
5594 -- Save global variables
5600 -- Call low level system initialization
5604 -- Call our generated Ada initialization routine
5608 -- This is the point at which we want the debugger to get
5613 -- Now we call the main program of the partition
5617 -- Perform Ada finalization
5621 -- Perform low level system finalization
5625 -- Return the proper exit status
5626 return (gnat_exit_status);
5629 -- This section is entirely comments, so it has no effect on the
5630 -- compilation of the Ada_Main package. It provides the list of
5631 -- object files and linker options, as well as some standard
5632 -- libraries needed for the link. The gnatlink utility parses
5633 -- this b~hello.adb file to read these comment lines to generate
5634 -- the appropriate command line arguments for the call to the
5635 -- system linker. The BEGIN/END lines are used for sentinels for
5636 -- this parsing operation.
5638 -- The exact file names will of course depend on the environment,
5639 -- host/target and location of files on the host system.
5641 @findex Object file list
5642 -- BEGIN Object file/option list
5645 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
5646 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
5647 -- END Object file/option list
5654 The Ada code in the above example is exactly what is generated by the
5655 binder. We have added comments to more clearly indicate the function
5656 of each part of the generated @code{Ada_Main} package.
5658 The code is standard Ada in all respects, and can be processed by any
5659 tools that handle Ada. In particular, it is possible to use the debugger
5660 in Ada mode to debug the generated Ada_Main package. For example, suppose
5661 that for reasons that you do not understand, your program is blowing up
5662 during elaboration of the body of @code{Ada.Text_IO}. To chase this bug
5663 down, you can place a breakpoint on the call:
5666 Ada.Text_Io'Elab_Body;
5670 and trace the elaboration routine for this package to find out where
5671 the problem might be (more usually of course you would be debugging
5672 elaboration code in your own application).
5674 @node Generating the Binder Program in C
5675 @section Generating the Binder Program in C
5677 In most normal usage, the default mode of @code{gnatbind} which is to
5678 generate the main package in Ada, as described in the previous section.
5679 In particular, this means that any Ada programmer can read and understand
5680 the generated main program. It can also be debugged just like any other
5681 Ada code provided the @code{-g} switch is used for @code{gnatbind}
5682 and @code{gnatlink}.
5684 However for some purposes it may be convenient to generate the main
5685 program in C rather than Ada. This may for example be helpful when you
5686 are generating a mixed language program with the main program in C. The
5687 GNAT compiler itself is an example. The use of the @code{-C} switch
5688 for both @code{gnatbind} and @code{gnatlink} will cause the program to
5689 be generated in C (and compiled using the gnu C compiler). The
5690 following shows the C code generated for the same "Hello World"
5696 #define PARAMS(paramlist) paramlist
5698 #define PARAMS(paramlist) ()
5701 extern void __gnat_set_globals
5702 PARAMS ((int, int, int, int, int, int,
5703 void (*) PARAMS ((void)), int, int));
5704 extern void adafinal PARAMS ((void));
5705 extern void adainit PARAMS ((void));
5706 extern void system__standard_library__adafinal PARAMS ((void));
5707 extern int main PARAMS ((int, char **, char **));
5708 extern void exit PARAMS ((int));
5709 extern void __gnat_break_start PARAMS ((void));
5710 extern void _ada_hello PARAMS ((void));
5711 extern void __gnat_initialize PARAMS ((void));
5712 extern void __gnat_finalize PARAMS ((void));
5714 extern void ada__exceptions___elabs PARAMS ((void));
5715 extern void system__exceptions___elabs PARAMS ((void));
5716 extern void interfaces__c_streams___elabs PARAMS ((void));
5717 extern void system__exception_table___elabb PARAMS ((void));
5718 extern void ada__io_exceptions___elabs PARAMS ((void));
5719 extern void system__stack_checking___elabs PARAMS ((void));
5720 extern void system__soft_links___elabb PARAMS ((void));
5721 extern void system__secondary_stack___elabb PARAMS ((void));
5722 extern void ada__tags___elabs PARAMS ((void));
5723 extern void ada__tags___elabb PARAMS ((void));
5724 extern void ada__streams___elabs PARAMS ((void));
5725 extern void system__finalization_root___elabs PARAMS ((void));
5726 extern void ada__exceptions___elabb PARAMS ((void));
5727 extern void system__finalization_implementation___elabs PARAMS ((void));
5728 extern void system__finalization_implementation___elabb PARAMS ((void));
5729 extern void ada__finalization___elabs PARAMS ((void));
5730 extern void ada__finalization__list_controller___elabs PARAMS ((void));
5731 extern void system__file_control_block___elabs PARAMS ((void));
5732 extern void system__file_io___elabb PARAMS ((void));
5733 extern void ada__text_io___elabs PARAMS ((void));
5734 extern void ada__text_io___elabb PARAMS ((void));
5736 extern int __gnat_inside_elab_final_code;
5738 extern int gnat_argc;
5739 extern char **gnat_argv;
5740 extern char **gnat_envp;
5741 extern int gnat_exit_status;
5743 char __gnat_version[] = "GNAT Version: 3.15w (20010315)";
5745 system__standard_library__adafinal ();
5750 extern char ada__exceptions_E;
5751 extern char system__exceptions_E;
5752 extern char interfaces__c_streams_E;
5753 extern char system__exception_table_E;
5754 extern char ada__io_exceptions_E;
5755 extern char system__secondary_stack_E;
5756 extern char system__stack_checking_E;
5757 extern char system__soft_links_E;
5758 extern char ada__tags_E;
5759 extern char ada__streams_E;
5760 extern char system__finalization_root_E;
5761 extern char system__finalization_implementation_E;
5762 extern char ada__finalization_E;
5763 extern char ada__finalization__list_controller_E;
5764 extern char system__file_control_block_E;
5765 extern char system__file_io_E;
5766 extern char ada__text_io_E;
5768 extern void *__gnat_hello__SDP;
5769 extern void *__gnat_ada__text_io__SDP;
5770 extern void *__gnat_ada__exceptions__SDP;
5771 extern void *__gnat_gnat__heap_sort_a__SDP;
5772 extern void *__gnat_system__exception_table__SDP;
5773 extern void *__gnat_system__machine_state_operations__SDP;
5774 extern void *__gnat_system__secondary_stack__SDP;
5775 extern void *__gnat_system__parameters__SDP;
5776 extern void *__gnat_system__soft_links__SDP;
5777 extern void *__gnat_system__stack_checking__SDP;
5778 extern void *__gnat_system__traceback__SDP;
5779 extern void *__gnat_ada__streams__SDP;
5780 extern void *__gnat_ada__tags__SDP;
5781 extern void *__gnat_system__string_ops__SDP;
5782 extern void *__gnat_interfaces__c_streams__SDP;
5783 extern void *__gnat_system__file_io__SDP;
5784 extern void *__gnat_ada__finalization__SDP;
5785 extern void *__gnat_system__finalization_root__SDP;
5786 extern void *__gnat_system__finalization_implementation__SDP;
5787 extern void *__gnat_system__string_ops_concat_3__SDP;
5788 extern void *__gnat_system__stream_attributes__SDP;
5789 extern void *__gnat_system__file_control_block__SDP;
5790 extern void *__gnat_ada__finalization__list_controller__SDP;
5794 &__gnat_ada__text_io__SDP,
5795 &__gnat_ada__exceptions__SDP,
5796 &__gnat_gnat__heap_sort_a__SDP,
5797 &__gnat_system__exception_table__SDP,
5798 &__gnat_system__machine_state_operations__SDP,
5799 &__gnat_system__secondary_stack__SDP,
5800 &__gnat_system__parameters__SDP,
5801 &__gnat_system__soft_links__SDP,
5802 &__gnat_system__stack_checking__SDP,
5803 &__gnat_system__traceback__SDP,
5804 &__gnat_ada__streams__SDP,
5805 &__gnat_ada__tags__SDP,
5806 &__gnat_system__string_ops__SDP,
5807 &__gnat_interfaces__c_streams__SDP,
5808 &__gnat_system__file_io__SDP,
5809 &__gnat_ada__finalization__SDP,
5810 &__gnat_system__finalization_root__SDP,
5811 &__gnat_system__finalization_implementation__SDP,
5812 &__gnat_system__string_ops_concat_3__SDP,
5813 &__gnat_system__stream_attributes__SDP,
5814 &__gnat_system__file_control_block__SDP,
5815 &__gnat_ada__finalization__list_controller__SDP@};
5817 extern void ada__exceptions___elabs ();
5818 extern void system__exceptions___elabs ();
5819 extern void interfaces__c_streams___elabs ();
5820 extern void system__exception_table___elabb ();
5821 extern void ada__io_exceptions___elabs ();
5822 extern void system__stack_checking___elabs ();
5823 extern void system__soft_links___elabb ();
5824 extern void system__secondary_stack___elabb ();
5825 extern void ada__tags___elabs ();
5826 extern void ada__tags___elabb ();
5827 extern void ada__streams___elabs ();
5828 extern void system__finalization_root___elabs ();
5829 extern void ada__exceptions___elabb ();
5830 extern void system__finalization_implementation___elabs ();
5831 extern void system__finalization_implementation___elabb ();
5832 extern void ada__finalization___elabs ();
5833 extern void ada__finalization__list_controller___elabs ();
5834 extern void system__file_control_block___elabs ();
5835 extern void system__file_io___elabb ();
5836 extern void ada__text_io___elabs ();
5837 extern void ada__text_io___elabb ();
5839 void (*ea[23]) () = @{
5841 system__standard_library__adafinal,
5842 ada__exceptions___elabs,
5843 system__exceptions___elabs,
5844 interfaces__c_streams___elabs,
5845 system__exception_table___elabb,
5846 ada__io_exceptions___elabs,
5847 system__stack_checking___elabs,
5848 system__soft_links___elabb,
5849 system__secondary_stack___elabb,
5852 ada__streams___elabs,
5853 system__finalization_root___elabs,
5854 ada__exceptions___elabb,
5855 system__finalization_implementation___elabs,
5856 system__finalization_implementation___elabb,
5857 ada__finalization___elabs,
5858 ada__finalization__list_controller___elabs,
5859 system__file_control_block___elabs,
5860 system__file_io___elabb,
5861 ada__text_io___elabs,
5862 ada__text_io___elabb@};
5864 __gnat_SDP_Table_Build (&st, 23, ea, 23);
5865 __gnat_set_globals (
5866 -1, /* Main_Priority */
5867 -1, /* Time_Slice_Value */
5868 'b', /* WC_Encoding */
5869 ' ', /* Locking_Policy */
5870 ' ', /* Queuing_Policy */
5871 ' ', /* Tasking_Dispatching_Policy */
5872 0, /* Finalization routine address, not used anymore */
5873 0, /* Unreserve_All_Interrupts */
5874 0); /* Exception_Tracebacks */
5876 __gnat_inside_elab_final_code = 1;
5878 if (ada__exceptions_E == 0) @{
5879 ada__exceptions___elabs ();
5881 if (system__exceptions_E == 0) @{
5882 system__exceptions___elabs ();
5883 system__exceptions_E++;
5885 if (interfaces__c_streams_E == 0) @{
5886 interfaces__c_streams___elabs ();
5888 interfaces__c_streams_E = 1;
5889 if (system__exception_table_E == 0) @{
5890 system__exception_table___elabb ();
5891 system__exception_table_E++;
5893 if (ada__io_exceptions_E == 0) @{
5894 ada__io_exceptions___elabs ();
5895 ada__io_exceptions_E++;
5897 if (system__stack_checking_E == 0) @{
5898 system__stack_checking___elabs ();
5900 if (system__soft_links_E == 0) @{
5901 system__soft_links___elabb ();
5902 system__soft_links_E++;
5904 system__stack_checking_E = 1;
5905 if (system__secondary_stack_E == 0) @{
5906 system__secondary_stack___elabb ();
5907 system__secondary_stack_E++;
5909 if (ada__tags_E == 0) @{
5910 ada__tags___elabs ();
5912 if (ada__tags_E == 0) @{
5913 ada__tags___elabb ();
5916 if (ada__streams_E == 0) @{
5917 ada__streams___elabs ();
5920 if (system__finalization_root_E == 0) @{
5921 system__finalization_root___elabs ();
5923 system__finalization_root_E = 1;
5924 if (ada__exceptions_E == 0) @{
5925 ada__exceptions___elabb ();
5926 ada__exceptions_E++;
5928 if (system__finalization_implementation_E == 0) @{
5929 system__finalization_implementation___elabs ();
5931 if (system__finalization_implementation_E == 0) @{
5932 system__finalization_implementation___elabb ();
5933 system__finalization_implementation_E++;
5935 if (ada__finalization_E == 0) @{
5936 ada__finalization___elabs ();
5938 ada__finalization_E = 1;
5939 if (ada__finalization__list_controller_E == 0) @{
5940 ada__finalization__list_controller___elabs ();
5942 ada__finalization__list_controller_E = 1;
5943 if (system__file_control_block_E == 0) @{
5944 system__file_control_block___elabs ();
5945 system__file_control_block_E++;
5947 if (system__file_io_E == 0) @{
5948 system__file_io___elabb ();
5949 system__file_io_E++;
5951 if (ada__text_io_E == 0) @{
5952 ada__text_io___elabs ();
5954 if (ada__text_io_E == 0) @{
5955 ada__text_io___elabb ();
5959 __gnat_inside_elab_final_code = 0;
5961 int main (argc, argv, envp)
5970 __gnat_initialize ();
5972 __gnat_break_start ();
5976 system__standard_library__adafinal ();
5978 exit (gnat_exit_status);
5980 unsigned helloB = 0x7880BEB3;
5981 unsigned system__standard_libraryB = 0x0D24CBD0;
5982 unsigned system__standard_libraryS = 0x3283DBEB;
5983 unsigned adaS = 0x2359F9ED;
5984 unsigned ada__text_ioB = 0x47C85FC4;
5985 unsigned ada__text_ioS = 0x496FE45C;
5986 unsigned ada__exceptionsB = 0x74F50187;
5987 unsigned ada__exceptionsS = 0x6736945B;
5988 unsigned gnatS = 0x156A40CF;
5989 unsigned gnat__heap_sort_aB = 0x033DABE0;
5990 unsigned gnat__heap_sort_aS = 0x6AB38FEA;
5991 unsigned systemS = 0x0331C6FE;
5992 unsigned system__exceptionsS = 0x20C9ECA4;
5993 unsigned system__exception_tableB = 0x68A22947;
5994 unsigned system__exception_tableS = 0x394BADD5;
5995 unsigned gnat__htableB = 0x08258E1B;
5996 unsigned gnat__htableS = 0x367D5222;
5997 unsigned system__machine_state_operationsB = 0x4F3B7492;
5998 unsigned system__machine_state_operationsS = 0x182F5CF4;
5999 unsigned system__storage_elementsB = 0x2F1EB794;
6000 unsigned system__storage_elementsS = 0x102C83C7;
6001 unsigned system__secondary_stackB = 0x1574B6E9;
6002 unsigned system__secondary_stackS = 0x708E260A;
6003 unsigned system__parametersB = 0x56D770CD;
6004 unsigned system__parametersS = 0x237E39BE;
6005 unsigned system__soft_linksB = 0x08AB6B2C;
6006 unsigned system__soft_linksS = 0x1E2491F3;
6007 unsigned system__stack_checkingB = 0x476457A0;
6008 unsigned system__stack_checkingS = 0x5299FCED;
6009 unsigned system__tracebackB = 0x2971EBDE;
6010 unsigned system__tracebackS = 0x2E9C3122;
6011 unsigned ada__streamsS = 0x7C25DE96;
6012 unsigned ada__tagsB = 0x39ADFFA2;
6013 unsigned ada__tagsS = 0x769A0464;
6014 unsigned system__string_opsB = 0x5EB646AB;
6015 unsigned system__string_opsS = 0x63CED018;
6016 unsigned interfacesS = 0x0357E00A;
6017 unsigned interfaces__c_streamsB = 0x3784FB72;
6018 unsigned interfaces__c_streamsS = 0x2E723019;
6019 unsigned system__file_ioB = 0x623358EA;
6020 unsigned system__file_ioS = 0x31F873E6;
6021 unsigned ada__finalizationB = 0x6843F68A;
6022 unsigned ada__finalizationS = 0x63305874;
6023 unsigned system__finalization_rootB = 0x31E56CE1;
6024 unsigned system__finalization_rootS = 0x23169EF3;
6025 unsigned system__finalization_implementationB = 0x6CCBA70E;
6026 unsigned system__finalization_implementationS = 0x604AA587;
6027 unsigned system__string_ops_concat_3B = 0x572E3F58;
6028 unsigned system__string_ops_concat_3S = 0x01F57876;
6029 unsigned system__stream_attributesB = 0x1D4F93E8;
6030 unsigned system__stream_attributesS = 0x30B2EC3D;
6031 unsigned ada__io_exceptionsS = 0x34054F96;
6032 unsigned system__unsigned_typesS = 0x7B9E7FE3;
6033 unsigned system__file_control_blockS = 0x2FF876A8;
6034 unsigned ada__finalization__list_controllerB = 0x5760634A;
6035 unsigned ada__finalization__list_controllerS = 0x5D851835;
6037 /* BEGIN ELABORATION ORDER
6040 gnat.heap_sort_a (spec)
6045 system.parameters (spec)
6046 system.standard_library (spec)
6047 ada.exceptions (spec)
6048 system.exceptions (spec)
6049 system.parameters (body)
6050 gnat.heap_sort_a (body)
6051 interfaces.c_streams (spec)
6052 interfaces.c_streams (body)
6053 system.exception_table (spec)
6054 system.exception_table (body)
6055 ada.io_exceptions (spec)
6056 system.storage_elements (spec)
6057 system.storage_elements (body)
6058 system.machine_state_operations (spec)
6059 system.machine_state_operations (body)
6060 system.secondary_stack (spec)
6061 system.stack_checking (spec)
6062 system.soft_links (spec)
6063 system.soft_links (body)
6064 system.stack_checking (body)
6065 system.secondary_stack (body)
6066 system.standard_library (body)
6067 system.string_ops (spec)
6068 system.string_ops (body)
6072 system.finalization_root (spec)
6073 system.finalization_root (body)
6074 system.string_ops_concat_3 (spec)
6075 system.string_ops_concat_3 (body)
6076 system.traceback (spec)
6077 system.traceback (body)
6078 ada.exceptions (body)
6079 system.unsigned_types (spec)
6080 system.stream_attributes (spec)
6081 system.stream_attributes (body)
6082 system.finalization_implementation (spec)
6083 system.finalization_implementation (body)
6084 ada.finalization (spec)
6085 ada.finalization (body)
6086 ada.finalization.list_controller (spec)
6087 ada.finalization.list_controller (body)
6088 system.file_control_block (spec)
6089 system.file_io (spec)
6090 system.file_io (body)
6094 END ELABORATION ORDER */
6096 /* BEGIN Object file/option list
6099 -L/usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/
6100 /usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/libgnat.a
6102 END Object file/option list */
6107 Here again, the C code is exactly what is generated by the binder. The
6108 functions of the various parts of this code correspond in an obvious
6109 manner with the commented Ada code shown in the example in the previous
6112 @node Consistency-Checking Modes
6113 @section Consistency-Checking Modes
6116 As described in the previous section, by default @code{gnatbind} checks
6117 that object files are consistent with one another and are consistent
6118 with any source files it can locate. The following switches control binder
6123 @cindex @code{-s} (@code{gnatbind})
6124 Require source files to be present. In this mode, the binder must be
6125 able to locate all source files that are referenced, in order to check
6126 their consistency. In normal mode, if a source file cannot be located it
6127 is simply ignored. If you specify this switch, a missing source
6131 @cindex @code{-x} (@code{gnatbind})
6132 Exclude source files. In this mode, the binder only checks that ALI
6133 files are consistent with one another. Source files are not accessed.
6134 The binder runs faster in this mode, and there is still a guarantee that
6135 the resulting program is self-consistent.
6136 If a source file has been edited since it was last compiled, and you
6137 specify this switch, the binder will not detect that the object
6138 file is out of date with respect to the source file. Note that this is the
6139 mode that is automatically used by @code{gnatmake} because in this
6140 case the checking against sources has already been performed by
6141 @code{gnatmake} in the course of compilation (i.e. before binding).
6145 @node Binder Error Message Control
6146 @section Binder Error Message Control
6149 The following switches provide control over the generation of error
6150 messages from the binder:
6154 @cindex @code{-v} (@code{gnatbind})
6155 Verbose mode. In the normal mode, brief error messages are generated to
6156 @file{stderr}. If this switch is present, a header is written
6157 to @file{stdout} and any error messages are directed to @file{stdout}.
6158 All that is written to @file{stderr} is a brief summary message.
6161 @cindex @code{-b} (@code{gnatbind})
6162 Generate brief error messages to @file{stderr} even if verbose mode is
6163 specified. This is relevant only when used with the
6167 @cindex @code{-m} (@code{gnatbind})
6168 Limits the number of error messages to @var{n}, a decimal integer in the
6169 range 1-999. The binder terminates immediately if this limit is reached.
6172 @cindex @code{-M} (@code{gnatbind})
6173 Renames the generated main program from @code{main} to @code{xxx}.
6174 This is useful in the case of some cross-building environments, where
6175 the actual main program is separate from the one generated
6179 @cindex @code{-ws} (@code{gnatbind})
6181 Suppress all warning messages.
6184 @cindex @code{-we} (@code{gnatbind})
6185 Treat any warning messages as fatal errors.
6189 @cindex @code{-t} (@code{gnatbind})
6190 @cindex Time stamp checks, in binder
6191 @cindex Binder consistency checks
6192 @cindex Consistency checks, in binder
6193 The binder performs a number of consistency checks including:
6197 Check that time stamps of a given source unit are consistent
6199 Check that checksums of a given source unit are consistent
6201 Check that consistent versions of @code{GNAT} were used for compilation
6203 Check consistency of configuration pragmas as required
6207 Normally failure of such checks, in accordance with the consistency
6208 requirements of the Ada Reference Manual, causes error messages to be
6209 generated which abort the binder and prevent the output of a binder
6210 file and subsequent link to obtain an executable.
6212 The @code{-t} switch converts these error messages
6213 into warnings, so that
6214 binding and linking can continue to completion even in the presence of such
6215 errors. The result may be a failed link (due to missing symbols), or a
6216 non-functional executable which has undefined semantics.
6217 @emph{This means that
6218 @code{-t} should be used only in unusual situations,
6222 @node Elaboration Control
6223 @section Elaboration Control
6226 The following switches provide additional control over the elaboration
6227 order. For full details see @xref{Elaboration Order Handling in GNAT}.
6231 @cindex @code{-h} (@code{gnatbind})
6232 Normally the binder attempts to choose an elaboration order that is
6233 likely to minimize the likelihood of an elaboration order error resulting
6234 in raising a @code{Program_Error} exception. This switch reverses the
6235 action of the binder, and requests that it deliberately choose an order
6236 that is likely to maximize the likelihood of an elaboration error.
6237 This is useful in ensuring portability and avoiding dependence on
6238 accidental fortuitous elaboration ordering.
6240 Normally it only makes sense to use the @code{-p} switch if dynamic
6241 elaboration checking is used (@option{-gnatE} switch used for compilation).
6242 This is because in the default static elaboration mode, all necessary
6243 @code{Elaborate_All} pragmas are implicitly inserted. These implicit
6244 pragmas are still respected by the binder in @code{-p} mode, so a
6245 safe elaboration order is assured.
6248 @node Output Control
6249 @section Output Control
6252 The following switches allow additional control over the output
6253 generated by the binder.
6258 @cindex @code{-A} (@code{gnatbind})
6259 Generate binder program in Ada (default). The binder program is named
6260 @file{b~@var{mainprog}.adb} by default. This can be changed with
6261 @code{-o} @code{gnatbind} option.
6264 @cindex @code{-c} (@code{gnatbind})
6265 Check only. Do not generate the binder output file. In this mode the
6266 binder performs all error checks but does not generate an output file.
6269 @cindex @code{-C} (@code{gnatbind})
6270 Generate binder program in C. The binder program is named
6271 @file{b_@var{mainprog}.c}. This can be changed with @code{-o} @code{gnatbind}
6275 @cindex @code{-e} (@code{gnatbind})
6276 Output complete list of elaboration-order dependencies, showing the
6277 reason for each dependency. This output can be rather extensive but may
6278 be useful in diagnosing problems with elaboration order. The output is
6279 written to @file{stdout}.
6282 @cindex @code{-h} (@code{gnatbind})
6283 Output usage information. The output is written to @file{stdout}.
6286 @cindex @code{-K} (@code{gnatbind})
6287 Output linker options to @file{stdout}. Includes library search paths,
6288 contents of pragmas Ident and Linker_Options, and libraries added
6292 @cindex @code{-l} (@code{gnatbind})
6293 Output chosen elaboration order. The output is written to @file{stdout}.
6296 @cindex @code{-O} (@code{gnatbind})
6297 Output full names of all the object files that must be linked to provide
6298 the Ada component of the program. The output is written to @file{stdout}.
6299 This list includes the files explicitly supplied and referenced by the user
6300 as well as implicitly referenced run-time unit files. The latter are
6301 omitted if the corresponding units reside in shared libraries. The
6302 directory names for the run-time units depend on the system configuration.
6305 @cindex @code{-o} (@code{gnatbind})
6306 Set name of output file to @var{file} instead of the normal
6307 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
6308 binder generated body filename. In C mode you would normally give
6309 @var{file} an extension of @file{.c} because it will be a C source program.
6310 Note that if this option is used, then linking must be done manually.
6311 It is not possible to use gnatlink in this case, since it cannot locate
6315 @cindex @code{-r} (@code{gnatbind})
6316 Generate list of @code{pragma Rerstrictions} that could be applied to
6317 the current unit. This is useful for code audit purposes, and also may
6318 be used to improve code generation in some cases.
6322 @node Binding with Non-Ada Main Programs
6323 @section Binding with Non-Ada Main Programs
6326 In our description so far we have assumed that the main
6327 program is in Ada, and that the task of the binder is to generate a
6328 corresponding function @code{main} that invokes this Ada main
6329 program. GNAT also supports the building of executable programs where
6330 the main program is not in Ada, but some of the called routines are
6331 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
6332 The following switch is used in this situation:
6336 @cindex @code{-n} (@code{gnatbind})
6337 No main program. The main program is not in Ada.
6341 In this case, most of the functions of the binder are still required,
6342 but instead of generating a main program, the binder generates a file
6343 containing the following callable routines:
6348 You must call this routine to initialize the Ada part of the program by
6349 calling the necessary elaboration routines. A call to @code{adainit} is
6350 required before the first call to an Ada subprogram.
6352 Note that it is assumed that the basic execution environment must be setup
6353 to be appropriate for Ada execution at the point where the first Ada
6354 subprogram is called. In particular, if the Ada code will do any
6355 floating-point operations, then the FPU must be setup in an appropriate
6356 manner. For the case of the x86, for example, full precision mode is
6357 required. The procedure GNAT.Float_Control.Reset may be used to ensure
6358 that the FPU is in the right state.
6362 You must call this routine to perform any library-level finalization
6363 required by the Ada subprograms. A call to @code{adafinal} is required
6364 after the last call to an Ada subprogram, and before the program
6369 If the @code{-n} switch
6370 @cindex Binder, multiple input files
6371 is given, more than one ALI file may appear on
6372 the command line for @code{gnatbind}. The normal @dfn{closure}
6373 calculation is performed for each of the specified units. Calculating
6374 the closure means finding out the set of units involved by tracing
6375 @code{with} references. The reason it is necessary to be able to
6376 specify more than one ALI file is that a given program may invoke two or
6377 more quite separate groups of Ada units.
6379 The binder takes the name of its output file from the last specified ALI
6380 file, unless overridden by the use of the @code{-o file}.
6381 The output is an Ada unit in source form that can
6382 be compiled with GNAT unless the -C switch is used in which case the
6383 output is a C source file, which must be compiled using the C compiler.
6384 This compilation occurs automatically as part of the @code{gnatlink}
6387 Currently the GNAT run time requires a FPU using 80 bits mode
6388 precision. Under targets where this is not the default it is required to
6389 call GNAT.Float_Control.Reset before using floating point numbers (this
6390 include float computation, float input and output) in the Ada code. A
6391 side effect is that this could be the wrong mode for the foreign code
6392 where floating point computation could be broken after this call.
6394 @node Binding Programs with No Main Subprogram
6395 @section Binding Programs with No Main Subprogram
6398 It is possible to have an Ada program which does not have a main
6399 subprogram. This program will call the elaboration routines of all the
6400 packages, then the finalization routines.
6402 The following switch is used to bind programs organized in this manner:
6406 @cindex @code{-z} (@code{gnatbind})
6407 Normally the binder checks that the unit name given on the command line
6408 corresponds to a suitable main subprogram. When this switch is used,
6409 a list of ALI files can be given, and the execution of the program
6410 consists of elaboration of these units in an appropriate order.
6413 @node Summary of Binder Switches
6414 @section Summary of Binder Switches
6417 The following are the switches available with @code{gnatbind}:
6421 Specify directory to be searched for ALI files.
6424 Specify directory to be searched for source file.
6427 Generate binder program in Ada (default)
6430 Generate brief messages to @file{stderr} even if verbose mode set.
6433 Check only, no generation of binder output file.
6436 Generate binder program in C
6439 Output complete list of elaboration-order dependencies.
6442 Store tracebacks in exception occurrences when the target supports it.
6443 This is the default with the zero cost exception mechanism.
6444 This option is currently supported on the following targets:
6445 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
6446 See also the packages @code{GNAT.Traceback} and
6447 @code{GNAT.Traceback.Symbolic} for more information.
6448 Note that on x86 ports, you must not use @code{-fomit-frame-pointer}
6452 Output usage (help) information
6455 Specify directory to be searched for source and ALI files.
6458 Do not look for sources in the current directory where @code{gnatbind} was
6459 invoked, and do not look for ALI files in the directory containing the
6460 ALI file named in the @code{gnatbind} command line.
6463 Output chosen elaboration order.
6466 Binds the units for library building. In this case the adainit and
6467 adafinal procedures (See @pxref{Binding with Non-Ada Main Programs})
6468 are renamed to xxxinit and xxxfinal. Implies -n.
6469 See @pxref{GNAT and Libraries} for more details.
6472 Rename generated main program from main to xyz
6475 Limit number of detected errors to @var{n} (1-999).
6476 Furthermore, under Windows, the sources pointed to by the libraries path
6477 set in the registry are not searched for.
6483 Do not look for sources in the system default directory.
6486 Do not look for library files in the system default directory.
6488 @item --RTS=@var{rts-path}
6489 @cindex @code{--RTS} (@code{gnatbind})
6490 Specifies the default location of the runtime library. Same meaning as the
6491 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
6494 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
6495 Note that if this option is used, then linking must be done manually,
6496 gnatlink cannot be used.
6502 Pessimistic (worst-case) elaboration order
6505 Require all source files to be present.
6508 Link against a static GNAT run time.
6511 Link against a shared GNAT run time when available.
6514 Tolerate time stamp and other consistency errors
6517 Set the time slice value to n microseconds. A value of zero means no time
6518 slicing and also indicates to the tasking run time to match as close as
6519 possible to the annex D requirements of the RM.
6522 Verbose mode. Write error messages, header, summary output to
6526 Warning mode (@var{x}=s/e for suppress/treat as error)
6530 Exclude source files (check object consistency only).
6538 You may obtain this listing by running the program @code{gnatbind} with
6541 @node Command-Line Access
6542 @section Command-Line Access
6545 The package @code{Ada.Command_Line} provides access to the command-line
6546 arguments and program name. In order for this interface to operate
6547 correctly, the two variables
6561 are declared in one of the GNAT library routines. These variables must
6562 be set from the actual @code{argc} and @code{argv} values passed to the
6563 main program. With no @code{n} present, @code{gnatbind}
6564 generates the C main program to automatically set these variables.
6565 If the @code{n} switch is used, there is no automatic way to
6566 set these variables. If they are not set, the procedures in
6567 @code{Ada.Command_Line} will not be available, and any attempt to use
6568 them will raise @code{Constraint_Error}. If command line access is
6569 required, your main program must set @code{gnat_argc} and
6570 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
6573 @node Search Paths for gnatbind
6574 @section Search Paths for @code{gnatbind}
6577 The binder takes the name of an ALI file as its argument and needs to
6578 locate source files as well as other ALI files to verify object consistency.
6580 For source files, it follows exactly the same search rules as @code{gcc}
6581 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
6582 directories searched are:
6586 The directory containing the ALI file named in the command line, unless
6587 the switch @code{-I-} is specified.
6590 All directories specified by @code{-I}
6591 switches on the @code{gnatbind}
6592 command line, in the order given.
6595 @findex ADA_OBJECTS_PATH
6596 Each of the directories listed in the value of the
6597 @code{ADA_OBJECTS_PATH} environment variable.
6598 Construct this value
6599 exactly as the @code{PATH} environment variable: a list of directory
6600 names separated by colons (semicolons when working with the NT version
6604 The content of the "ada_object_path" file which is part of the GNAT
6605 installation tree and is used to store standard libraries such as the
6606 GNAT Run Time Library (RTL) unless the switch @code{-nostdlib} is
6608 @ref{Installing an Ada Library}
6612 In the binder the switch @code{-I}
6613 is used to specify both source and
6614 library file paths. Use @code{-aI}
6615 instead if you want to specify
6616 source paths only, and @code{-aO}
6617 if you want to specify library paths
6618 only. This means that for the binder
6619 @code{-I}@var{dir} is equivalent to
6621 @code{-aO}@var{dir}.
6622 The binder generates the bind file (a C language source file) in the
6623 current working directory.
6629 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
6630 children make up the GNAT Run-Time Library, together with the package
6631 GNAT and its children, which contain a set of useful additional
6632 library functions provided by GNAT. The sources for these units are
6633 needed by the compiler and are kept together in one directory. The ALI
6634 files and object files generated by compiling the RTL are needed by the
6635 binder and the linker and are kept together in one directory, typically
6636 different from the directory containing the sources. In a normal
6637 installation, you need not specify these directory names when compiling
6638 or binding. Either the environment variables or the built-in defaults
6639 cause these files to be found.
6641 Besides simplifying access to the RTL, a major use of search paths is
6642 in compiling sources from multiple directories. This can make
6643 development environments much more flexible.
6645 @node Examples of gnatbind Usage
6646 @section Examples of @code{gnatbind} Usage
6649 This section contains a number of examples of using the GNAT binding
6650 utility @code{gnatbind}.
6653 @item gnatbind hello
6654 The main program @code{Hello} (source program in @file{hello.adb}) is
6655 bound using the standard switch settings. The generated main program is
6656 @file{b~hello.adb}. This is the normal, default use of the binder.
6658 @item gnatbind hello -o mainprog.adb
6659 The main program @code{Hello} (source program in @file{hello.adb}) is
6660 bound using the standard switch settings. The generated main program is
6661 @file{mainprog.adb} with the associated spec in
6662 @file{mainprog.ads}. Note that you must specify the body here not the
6663 spec, in the case where the output is in Ada. Note that if this option
6664 is used, then linking must be done manually, since gnatlink will not
6665 be able to find the generated file.
6667 @item gnatbind main -C -o mainprog.c -x
6668 The main program @code{Main} (source program in
6669 @file{main.adb}) is bound, excluding source files from the
6670 consistency checking, generating
6671 the file @file{mainprog.c}.
6673 @item gnatbind -x main_program -C -o mainprog.c
6674 This command is exactly the same as the previous example. Switches may
6675 appear anywhere in the command line, and single letter switches may be
6676 combined into a single switch.
6678 @item gnatbind -n math dbase -C -o ada-control.c
6679 The main program is in a language other than Ada, but calls to
6680 subprograms in packages @code{Math} and @code{Dbase} appear. This call
6681 to @code{gnatbind} generates the file @file{ada-control.c} containing
6682 the @code{adainit} and @code{adafinal} routines to be called before and
6683 after accessing the Ada units.
6686 @node Linking Using gnatlink
6687 @chapter Linking Using @code{gnatlink}
6691 This chapter discusses @code{gnatlink}, a utility program used to link
6692 Ada programs and build an executable file. This is a simple program
6693 that invokes the Unix linker (via the @code{gcc}
6694 command) with a correct list of object files and library references.
6695 @code{gnatlink} automatically determines the list of files and
6696 references for the Ada part of a program. It uses the binder file
6697 generated by the binder to determine this list.
6700 * Running gnatlink::
6701 * Switches for gnatlink::
6702 * Setting Stack Size from gnatlink::
6703 * Setting Heap Size from gnatlink::
6706 @node Running gnatlink
6707 @section Running @code{gnatlink}
6710 The form of the @code{gnatlink} command is
6713 $ gnatlink [@var{switches}] @var{mainprog}[.ali] [@var{non-Ada objects}]
6714 [@var{linker options}]
6718 @file{@var{mainprog}.ali} references the ALI file of the main program.
6719 The @file{.ali} extension of this file can be omitted. From this
6720 reference, @code{gnatlink} locates the corresponding binder file
6721 @file{b~@var{mainprog}.adb} and, using the information in this file along
6722 with the list of non-Ada objects and linker options, constructs a Unix
6723 linker command file to create the executable.
6725 The arguments following @file{@var{mainprog}.ali} are passed to the
6726 linker uninterpreted. They typically include the names of object files
6727 for units written in other languages than Ada and any library references
6728 required to resolve references in any of these foreign language units,
6729 or in @code{pragma Import} statements in any Ada units.
6731 @var{linker options} is an optional list of linker specific
6732 switches. The default linker called by gnatlink is @var{gcc} which in
6733 turn calls the appropriate system linker usually called
6734 @var{ld}. Standard options for the linker such as @code{-lmy_lib} or
6735 @code{-Ldir} can be added as is. For options that are not recognized by
6736 @var{gcc} as linker options, the @var{gcc} switches @code{-Xlinker} or
6737 @code{-Wl,} shall be used. Refer to the GCC documentation for
6738 details. Here is an example showing how to generate a linker map
6739 assuming that the underlying linker is GNU ld:
6742 $ gnatlink my_prog -Wl,-Map,MAPFILE
6745 Using @var{linker options} it is possible to set the program stack and
6746 heap size. See @pxref{Setting Stack Size from gnatlink} and
6747 @pxref{Setting Heap Size from gnatlink}.
6749 @code{gnatlink} determines the list of objects required by the Ada
6750 program and prepends them to the list of objects passed to the linker.
6751 @code{gnatlink} also gathers any arguments set by the use of
6752 @code{pragma Linker_Options} and adds them to the list of arguments
6753 presented to the linker.
6756 @node Switches for gnatlink
6757 @section Switches for @code{gnatlink}
6760 The following switches are available with the @code{gnatlink} utility:
6765 @cindex @code{-A} (@code{gnatlink})
6766 The binder has generated code in Ada. This is the default.
6769 @cindex @code{-C} (@code{gnatlink})
6770 If instead of generating a file in Ada, the binder has generated one in
6771 C, then the linker needs to know about it. Use this switch to signal
6772 to @code{gnatlink} that the binder has generated C code rather than
6776 @cindex Command line length
6777 @cindex @code{-f} (@code{gnatlink})
6778 On some targets, the command line length is limited, and @code{gnatlink}
6779 will generate a separate file for the linker if the list of object files
6780 is too long. The @code{-f} flag forces this file to be generated even if
6781 the limit is not exceeded. This is useful in some cases to deal with
6782 special situations where the command line length is exceeded.
6785 @cindex Debugging information, including
6786 @cindex @code{-g} (@code{gnatlink})
6787 The option to include debugging information causes the Ada bind file (in
6788 other words, @file{b~@var{mainprog}.adb}) to be compiled with
6790 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
6791 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
6792 Without @code{-g}, the binder removes these files by
6793 default. The same procedure apply if a C bind file was generated using
6794 @code{-C} @code{gnatbind} option, in this case the filenames are
6795 @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
6798 @cindex @code{-n} (@code{gnatlink})
6799 Do not compile the file generated by the binder. This may be used when
6800 a link is rerun with different options, but there is no need to recompile
6804 @cindex @code{-v} (@code{gnatlink})
6805 Causes additional information to be output, including a full list of the
6806 included object files. This switch option is most useful when you want
6807 to see what set of object files are being used in the link step.
6810 @cindex @code{-v -v} (@code{gnatlink})
6811 Very verbose mode. Requests that the compiler operate in verbose mode when
6812 it compiles the binder file, and that the system linker run in verbose mode.
6814 @item -o @var{exec-name}
6815 @cindex @code{-o} (@code{gnatlink})
6816 @var{exec-name} specifies an alternate name for the generated
6817 executable program. If this switch is omitted, the executable has the same
6818 name as the main unit. For example, @code{gnatlink try.ali} creates
6819 an executable called @file{try}.
6821 @item -b @var{target}
6822 @cindex @code{-b} (@code{gnatlink})
6823 Compile your program to run on @var{target}, which is the name of a
6824 system configuration. You must have a GNAT cross-compiler built if
6825 @var{target} is not the same as your host system.
6828 @cindex @code{-B} (@code{gnatlink})
6829 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
6830 from @var{dir} instead of the default location. Only use this switch
6831 when multiple versions of the GNAT compiler are available. See the
6832 @code{gcc} manual page for further details. You would normally use the
6833 @code{-b} or @code{-V} switch instead.
6835 @item --GCC=@var{compiler_name}
6836 @cindex @code{--GCC=compiler_name} (@code{gnatlink})
6837 Program used for compiling the binder file. The default is
6838 `@code{gcc}'. You need to use quotes around @var{compiler_name} if
6839 @code{compiler_name} contains spaces or other separator characters. As
6840 an example @code{--GCC="foo -x -y"} will instruct @code{gnatlink} to use
6841 @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
6842 inserted after your command name. Thus in the above example the compiler
6843 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
6844 If several @code{--GCC=compiler_name} are used, only the last
6845 @var{compiler_name} is taken into account. However, all the additional
6846 switches are also taken into account. Thus,
6847 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
6848 @code{--GCC="bar -x -y -z -t"}.
6850 @item --LINK=@var{name}
6851 @cindex @code{--LINK=} (@code{gnatlink})
6852 @var{name} is the name of the linker to be invoked. This is especially
6853 useful in mixed language programs since languages such as c++ require
6854 their own linker to be used. When this switch is omitted, the default
6855 name for the linker is (@file{gcc}). When this switch is used, the
6856 specified linker is called instead of (@file{gcc}) with exactly the same
6857 parameters that would have been passed to (@file{gcc}) so if the desired
6858 linker requires different parameters it is necessary to use a wrapper
6859 script that massages the parameters before invoking the real linker. It
6860 may be useful to control the exact invocation by using the verbose
6867 @node Setting Stack Size from gnatlink
6868 @section Setting Stack Size from @code{gnatlink}
6871 It is possible to specify the program stack size from @code{gnatlink}.
6872 Assuming that the underlying linker is GNU ld there is two ways to do so:
6876 @item using @code{-Xlinker} linker option
6879 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
6882 This set the stack reserve size to 0x10000 bytes and the stack commit
6883 size to 0x1000 bytes.
6885 @item using @code{-Wl} linker option
6888 $ gnatlink hello -Wl,--stack=0x1000000
6891 This set the stack reserve size to 0x1000000 bytes. Note that with
6892 @code{-Wl} option it is not possible to set the stack commit size
6893 because the coma is a separator for this option.
6897 @node Setting Heap Size from gnatlink
6898 @section Setting Heap Size from @code{gnatlink}
6901 It is possible to specify the program heap size from @code{gnatlink}.
6902 Assuming that the underlying linker is GNU ld there is two ways to do so:
6906 @item using @code{-Xlinker} linker option
6909 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
6912 This set the heap reserve size to 0x10000 bytes and the heap commit
6913 size to 0x1000 bytes.
6915 @item using @code{-Wl} linker option
6918 $ gnatlink hello -Wl,--heap=0x1000000
6921 This set the heap reserve size to 0x1000000 bytes. Note that with
6922 @code{-Wl} option it is not possible to set the heap commit size
6923 because the coma is a separator for this option.
6927 @node The GNAT Make Program gnatmake
6928 @chapter The GNAT Make Program @code{gnatmake}
6932 * Running gnatmake::
6933 * Switches for gnatmake::
6934 * Mode Switches for gnatmake::
6935 * Notes on the Command Line::
6936 * How gnatmake Works::
6937 * Examples of gnatmake Usage::
6940 A typical development cycle when working on an Ada program consists of
6941 the following steps:
6945 Edit some sources to fix bugs.
6951 Compile all sources affected.
6961 The third step can be tricky, because not only do the modified files
6962 @cindex Dependency rules
6963 have to be compiled, but any files depending on these files must also be
6964 recompiled. The dependency rules in Ada can be quite complex, especially
6965 in the presence of overloading, @code{use} clauses, generics and inlined
6968 @code{gnatmake} automatically takes care of the third and fourth steps
6969 of this process. It determines which sources need to be compiled,
6970 compiles them, and binds and links the resulting object files.
6972 Unlike some other Ada make programs, the dependencies are always
6973 accurately recomputed from the new sources. The source based approach of
6974 the GNAT compilation model makes this possible. This means that if
6975 changes to the source program cause corresponding changes in
6976 dependencies, they will always be tracked exactly correctly by
6979 @node Running gnatmake
6980 @section Running @code{gnatmake}
6983 The usual form of the @code{gnatmake} command is
6986 $ gnatmake [@var{switches}] @var{file_name} [@var{file_names}] [@var{mode_switches}]
6990 The only required argument is one @var{file_name}, which specifies
6991 a compilation unit that is a main program. Several @var{file_names} can be
6992 specified: this will result in several executables being built.
6993 If @code{switches} are present, they can be placed before the first
6994 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
6995 If @var{mode_switches} are present, they must always be placed after
6996 the last @var{file_name} and all @code{switches}.
6998 If you are using standard file extensions (.adb and .ads), then the
6999 extension may be omitted from the @var{file_name} arguments. However, if
7000 you are using non-standard extensions, then it is required that the
7001 extension be given. A relative or absolute directory path can be
7002 specified in a @var{file_name}, in which case, the input source file will
7003 be searched for in the specified directory only. Otherwise, the input
7004 source file will first be searched in the directory where
7005 @code{gnatmake} was invoked and if it is not found, it will be search on
7006 the source path of the compiler as described in
7007 @ref{Search Paths and the Run-Time Library (RTL)}.
7009 When several @var{file_names} are specified, if an executable needs to be
7010 rebuilt and relinked, all subsequent executables will be rebuilt and
7011 relinked, even if this would not be absolutely necessary.
7013 All @code{gnatmake} output (except when you specify
7015 @file{stderr}. The output produced by the
7016 @code{-M} switch is send to
7019 @node Switches for gnatmake
7020 @section Switches for @code{gnatmake}
7023 You may specify any of the following switches to @code{gnatmake}:
7026 @item --GCC=@var{compiler_name}
7027 @cindex @code{--GCC=compiler_name} (@code{gnatmake})
7028 Program used for compiling. The default is `@code{gcc}'. You need to use
7029 quotes around @var{compiler_name} if @code{compiler_name} contains
7030 spaces or other separator characters. As an example @code{--GCC="foo -x
7031 -y"} will instruct @code{gnatmake} to use @code{foo -x -y} as your
7032 compiler. Note that switch @code{-c} is always inserted after your
7033 command name. Thus in the above example the compiler command that will
7034 be used by @code{gnatmake} will be @code{foo -c -x -y}.
7035 If several @code{--GCC=compiler_name} are used, only the last
7036 @var{compiler_name} is taken into account. However, all the additional
7037 switches are also taken into account. Thus,
7038 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7039 @code{--GCC="bar -x -y -z -t"}.
7041 @item --GNATBIND=@var{binder_name}
7042 @cindex @code{--GNATBIND=binder_name} (@code{gnatmake})
7043 Program used for binding. The default is `@code{gnatbind}'. You need to
7044 use quotes around @var{binder_name} if @var{binder_name} contains spaces
7045 or other separator characters. As an example @code{--GNATBIND="bar -x
7046 -y"} will instruct @code{gnatmake} to use @code{bar -x -y} as your
7047 binder. Binder switches that are normally appended by @code{gnatmake} to
7048 `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
7050 @item --GNATLINK=@var{linker_name}
7051 @cindex @code{--GNATLINK=linker_name} (@code{gnatmake})
7052 Program used for linking. The default is `@code{gnatlink}'. You need to
7053 use quotes around @var{linker_name} if @var{linker_name} contains spaces
7054 or other separator characters. As an example @code{--GNATLINK="lan -x
7055 -y"} will instruct @code{gnatmake} to use @code{lan -x -y} as your
7056 linker. Linker switches that are normally appended by @code{gnatmake} to
7057 `@code{gnatlink}' are now appended to the end of @code{lan -x -y}.
7061 @cindex @code{-a} (@code{gnatmake})
7062 Consider all files in the make process, even the GNAT internal system
7063 files (for example, the predefined Ada library files), as well as any
7064 locked files. Locked files are files whose ALI file is write-protected.
7066 @code{gnatmake} does not check these files,
7067 because the assumption is that the GNAT internal files are properly up
7068 to date, and also that any write protected ALI files have been properly
7069 installed. Note that if there is an installation problem, such that one
7070 of these files is not up to date, it will be properly caught by the
7072 You may have to specify this switch if you are working on GNAT
7073 itself. @code{-a} is also useful in conjunction with
7075 if you need to recompile an entire application,
7076 including run-time files, using special configuration pragma settings,
7077 such as a non-standard @code{Float_Representation} pragma.
7079 @code{gnatmake -a} compiles all GNAT
7081 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
7084 @cindex @code{-b} (@code{gnatmake})
7085 Bind only. Can be combined with @code{-c} to do compilation
7086 and binding, but no link. Can be combined with @code{-l}
7087 to do binding and linking. When not combined with @code{-c}
7088 all the units in the closure of the main program must have been previously
7089 compiled and must be up to date. The root unit specified by @var{file_name}
7090 may be given without extension, with the source extension or, if no GNAT
7091 Project File is specified, with the ALI file extension.
7094 @cindex @code{-c} (@code{gnatmake})
7095 Compile only. Do not perform binding, except when @code{-b}
7096 is also specified. Do not perform linking, except if both
7098 @code{-l} are also specified.
7099 If the root unit specified by @var{file_name} is not a main unit, this is the
7100 default. Otherwise @code{gnatmake} will attempt binding and linking
7101 unless all objects are up to date and the executable is more recent than
7105 @cindex @code{-C} (@code{gnatmake})
7106 Use a mapping file. A mapping file is a way to communicate to the compiler
7107 two mappings: from unit names to file names (without any directory information)
7108 and from file names to path names (with full directory information).
7109 These mappings are used by the compiler to short-circuit the path search.
7110 When @code{gnatmake} is invoked with this switch, it will create a mapping
7111 file, initially populated by the project manager, if @code{-P} is used,
7112 otherwise initially empty. Each invocation of the compiler will add the newly
7113 accessed sources to the mapping file. This will improve the source search
7114 during the next invocation of the compiler.
7117 @cindex @code{-f} (@code{gnatmake})
7118 Force recompilations. Recompile all sources, even though some object
7119 files may be up to date, but don't recompile predefined or GNAT internal
7120 files or locked files (files with a write-protected ALI file),
7121 unless the @code{-a} switch is also specified.
7125 @cindex @code{-i} (@code{gnatmake})
7126 In normal mode, @code{gnatmake} compiles all object files and ALI files
7127 into the current directory. If the @code{-i} switch is used,
7128 then instead object files and ALI files that already exist are overwritten
7129 in place. This means that once a large project is organized into separate
7130 directories in the desired manner, then @code{gnatmake} will automatically
7131 maintain and update this organization. If no ALI files are found on the
7132 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
7133 the new object and ALI files are created in the
7134 directory containing the source being compiled. If another organization
7135 is desired, where objects and sources are kept in different directories,
7136 a useful technique is to create dummy ALI files in the desired directories.
7137 When detecting such a dummy file, @code{gnatmake} will be forced to recompile
7138 the corresponding source file, and it will be put the resulting object
7139 and ALI files in the directory where it found the dummy file.
7142 @cindex @code{-j} (@code{gnatmake})
7143 @cindex Parallel make
7144 Use @var{n} processes to carry out the (re)compilations. On a
7145 multiprocessor machine compilations will occur in parallel. In the
7146 event of compilation errors, messages from various compilations might
7147 get interspersed (but @code{gnatmake} will give you the full ordered
7148 list of failing compiles at the end). If this is problematic, rerun
7149 the make process with n set to 1 to get a clean list of messages.
7152 @cindex @code{-k} (@code{gnatmake})
7153 Keep going. Continue as much as possible after a compilation error. To
7154 ease the programmer's task in case of compilation errors, the list of
7155 sources for which the compile fails is given when @code{gnatmake}
7158 If @code{gnatmake} is invoked with several @file{file_names} and with this
7159 switch, if there are compilation errors when building an executable,
7160 @code{gnatmake} will not attempt to build the following executables.
7163 @cindex @code{-l} (@code{gnatmake})
7164 Link only. Can be combined with @code{-b} to binding
7165 and linking. Linking will not be performed if combined with
7167 but not with @code{-b}.
7168 When not combined with @code{-b}
7169 all the units in the closure of the main program must have been previously
7170 compiled and must be up to date, and the main program need to have been bound.
7171 The root unit specified by @var{file_name}
7172 may be given without extension, with the source extension or, if no GNAT
7173 Project File is specified, with the ALI file extension.
7176 @cindex @code{-m} (@code{gnatmake})
7177 Specifies that the minimum necessary amount of recompilations
7178 be performed. In this mode @code{gnatmake} ignores time
7179 stamp differences when the only
7180 modifications to a source file consist in adding/removing comments,
7181 empty lines, spaces or tabs. This means that if you have changed the
7182 comments in a source file or have simply reformatted it, using this
7183 switch will tell gnatmake not to recompile files that depend on it
7184 (provided other sources on which these files depend have undergone no
7185 semantic modifications). Note that the debugging information may be
7186 out of date with respect to the sources if the @code{-m} switch causes
7187 a compilation to be switched, so the use of this switch represents a
7188 trade-off between compilation time and accurate debugging information.
7191 @cindex Dependencies, producing list
7192 @cindex @code{-M} (@code{gnatmake})
7193 Check if all objects are up to date. If they are, output the object
7194 dependences to @file{stdout} in a form that can be directly exploited in
7195 a @file{Makefile}. By default, each source file is prefixed with its
7196 (relative or absolute) directory name. This name is whatever you
7197 specified in the various @code{-aI}
7198 and @code{-I} switches. If you use
7201 (see below), only the source file names,
7202 without relative paths, are output. If you just specify the
7204 switch, dependencies of the GNAT internal system files are omitted. This
7205 is typically what you want. If you also specify
7206 the @code{-a} switch,
7207 dependencies of the GNAT internal files are also listed. Note that
7208 dependencies of the objects in external Ada libraries (see switch
7209 @code{-aL}@var{dir} in the following list) are never reported.
7212 @cindex @code{-n} (@code{gnatmake})
7213 Don't compile, bind, or link. Checks if all objects are up to date.
7214 If they are not, the full name of the first file that needs to be
7215 recompiled is printed.
7216 Repeated use of this option, followed by compiling the indicated source
7217 file, will eventually result in recompiling all required units.
7219 @item -o @var{exec_name}
7220 @cindex @code{-o} (@code{gnatmake})
7221 Output executable name. The name of the final executable program will be
7222 @var{exec_name}. If the @code{-o} switch is omitted the default
7223 name for the executable will be the name of the input file in appropriate form
7224 for an executable file on the host system.
7226 This switch cannot be used when invoking @code{gnatmake} with several
7230 @cindex @code{-q} (@code{gnatmake})
7231 Quiet. When this flag is not set, the commands carried out by
7232 @code{gnatmake} are displayed.
7235 @cindex @code{-s} (@code{gnatmake})
7236 Recompile if compiler switches have changed since last compilation.
7237 All compiler switches but -I and -o are taken into account in the
7239 orders between different ``first letter'' switches are ignored, but
7240 orders between same switches are taken into account. For example,
7241 @code{-O -O2} is different than @code{-O2 -O}, but @code{-g -O} is equivalent
7245 @cindex @code{-u} (@code{gnatmake})
7246 Unique. Recompile at most the main file. It implies -c. Combined with
7247 -f, it is equivalent to calling the compiler directly.
7250 @cindex @code{-v} (@code{gnatmake})
7251 Verbose. Displays the reason for all recompilations @code{gnatmake}
7252 decides are necessary.
7255 @cindex @code{-z} (@code{gnatmake})
7256 No main subprogram. Bind and link the program even if the unit name
7257 given on the command line is a package name. The resulting executable
7258 will execute the elaboration routines of the package and its closure,
7259 then the finalization routines.
7261 @item @code{gcc} @asis{switches}
7262 The switch @code{-g} or any uppercase switch (other than @code{-A},
7264 @code{-S}) or any switch that is more than one character is passed to
7265 @code{gcc} (e.g. @code{-O}, @option{-gnato,} etc.)
7269 Source and library search path switches:
7273 @cindex @code{-aI} (@code{gnatmake})
7274 When looking for source files also look in directory @var{dir}.
7275 The order in which source files search is undertaken is
7276 described in @ref{Search Paths and the Run-Time Library (RTL)}.
7279 @cindex @code{-aL} (@code{gnatmake})
7280 Consider @var{dir} as being an externally provided Ada library.
7281 Instructs @code{gnatmake} to skip compilation units whose @file{.ali}
7282 files have been located in directory @var{dir}. This allows you to have
7283 missing bodies for the units in @var{dir} and to ignore out of date bodies
7284 for the same units. You still need to specify
7285 the location of the specs for these units by using the switches
7287 or @code{-I@var{dir}}.
7288 Note: this switch is provided for compatibility with previous versions
7289 of @code{gnatmake}. The easier method of causing standard libraries
7290 to be excluded from consideration is to write-protect the corresponding
7294 @cindex @code{-aO} (@code{gnatmake})
7295 When searching for library and object files, look in directory
7296 @var{dir}. The order in which library files are searched is described in
7297 @ref{Search Paths for gnatbind}.
7300 @cindex Search paths, for @code{gnatmake}
7301 @cindex @code{-A} (@code{gnatmake})
7302 Equivalent to @code{-aL@var{dir}
7306 @cindex @code{-I} (@code{gnatmake})
7307 Equivalent to @code{-aO@var{dir}
7311 @cindex @code{-I-} (@code{gnatmake})
7312 @cindex Source files, suppressing search
7313 Do not look for source files in the directory containing the source
7314 file named in the command line.
7315 Do not look for ALI or object files in the directory
7316 where @code{gnatmake} was invoked.
7319 @cindex @code{-L} (@code{gnatmake})
7320 @cindex Linker libraries
7321 Add directory @var{dir} to the list of directories in which the linker
7322 Furthermore, under Windows, the sources pointed to by the libraries path
7323 set in the registry are not searched for.
7324 will search for libraries. This is equivalent to
7325 @code{-largs -L}@var{dir}.
7328 @cindex @code{-nostdinc} (@code{gnatmake})
7329 Do not look for source files in the system default directory.
7332 @cindex @code{-nostdlib} (@code{gnatmake})
7333 Do not look for library files in the system default directory.
7335 @item --RTS=@var{rts-path}
7336 @cindex @code{--RTS} (@code{gnatmake})
7337 Specifies the default location of the runtime library. We look for the runtime
7338 in the following directories, and stop as soon as a valid runtime is found
7339 ("adainclude" or "ada_source_path", and "adalib" or "ada_object_path" present):
7342 @item <current directory>/$rts_path
7344 @item <default-search-dir>/$rts_path
7346 @item <default-search-dir>/rts-$rts_path
7350 The selected path is handled like a normal RTS path.
7354 @node Mode Switches for gnatmake
7355 @section Mode Switches for @code{gnatmake}
7358 The mode switches (referred to as @code{mode_switches}) allow the
7359 inclusion of switches that are to be passed to the compiler itself, the
7360 binder or the linker. The effect of a mode switch is to cause all
7361 subsequent switches up to the end of the switch list, or up to the next
7362 mode switch, to be interpreted as switches to be passed on to the
7363 designated component of GNAT.
7366 @item -cargs @var{switches}
7367 @cindex @code{-cargs} (@code{gnatmake})
7368 Compiler switches. Here @var{switches} is a list of switches
7369 that are valid switches for @code{gcc}. They will be passed on to
7370 all compile steps performed by @code{gnatmake}.
7372 @item -bargs @var{switches}
7373 @cindex @code{-bargs} (@code{gnatmake})
7374 Binder switches. Here @var{switches} is a list of switches
7375 that are valid switches for @code{gcc}. They will be passed on to
7376 all bind steps performed by @code{gnatmake}.
7378 @item -largs @var{switches}
7379 @cindex @code{-largs} (@code{gnatmake})
7380 Linker switches. Here @var{switches} is a list of switches
7381 that are valid switches for @code{gcc}. They will be passed on to
7382 all link steps performed by @code{gnatmake}.
7385 @node Notes on the Command Line
7386 @section Notes on the Command Line
7389 This section contains some additional useful notes on the operation
7390 of the @code{gnatmake} command.
7394 @cindex Recompilation, by @code{gnatmake}
7395 If @code{gnatmake} finds no ALI files, it recompiles the main program
7396 and all other units required by the main program.
7397 This means that @code{gnatmake}
7398 can be used for the initial compile, as well as during subsequent steps of
7399 the development cycle.
7402 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
7403 is a subunit or body of a generic unit, @code{gnatmake} recompiles
7404 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
7408 In @code{gnatmake} the switch @code{-I}
7409 is used to specify both source and
7410 library file paths. Use @code{-aI}
7411 instead if you just want to specify
7412 source paths only and @code{-aO}
7413 if you want to specify library paths
7417 @code{gnatmake} examines both an ALI file and its corresponding object file
7418 for consistency. If an ALI is more recent than its corresponding object,
7419 or if the object file is missing, the corresponding source will be recompiled.
7420 Note that @code{gnatmake} expects an ALI and the corresponding object file
7421 to be in the same directory.
7424 @code{gnatmake} will ignore any files whose ALI file is write-protected.
7425 This may conveniently be used to exclude standard libraries from
7426 consideration and in particular it means that the use of the
7427 @code{-f} switch will not recompile these files
7428 unless @code{-a} is also specified.
7431 @code{gnatmake} has been designed to make the use of Ada libraries
7432 particularly convenient. Assume you have an Ada library organized
7433 as follows: @var{obj-dir} contains the objects and ALI files for
7434 of your Ada compilation units,
7435 whereas @var{include-dir} contains the
7436 specs of these units, but no bodies. Then to compile a unit
7437 stored in @code{main.adb}, which uses this Ada library you would just type
7440 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
7444 Using @code{gnatmake} along with the
7445 @code{-m (minimal recompilation)}
7446 switch provides a mechanism for avoiding unnecessary rcompilations. Using
7448 you can update the comments/format of your
7449 source files without having to recompile everything. Note, however, that
7450 adding or deleting lines in a source files may render its debugging
7451 info obsolete. If the file in question is a spec, the impact is rather
7452 limited, as that debugging info will only be useful during the
7453 elaboration phase of your program. For bodies the impact can be more
7454 significant. In all events, your debugger will warn you if a source file
7455 is more recent than the corresponding object, and alert you to the fact
7456 that the debugging information may be out of date.
7459 @node How gnatmake Works
7460 @section How @code{gnatmake} Works
7463 Generally @code{gnatmake} automatically performs all necessary
7464 recompilations and you don't need to worry about how it works. However,
7465 it may be useful to have some basic understanding of the @code{gnatmake}
7466 approach and in particular to understand how it uses the results of
7467 previous compilations without incorrectly depending on them.
7469 First a definition: an object file is considered @dfn{up to date} if the
7470 corresponding ALI file exists and its time stamp predates that of the
7471 object file and if all the source files listed in the
7472 dependency section of this ALI file have time stamps matching those in
7473 the ALI file. This means that neither the source file itself nor any
7474 files that it depends on have been modified, and hence there is no need
7475 to recompile this file.
7477 @code{gnatmake} works by first checking if the specified main unit is up
7478 to date. If so, no compilations are required for the main unit. If not,
7479 @code{gnatmake} compiles the main program to build a new ALI file that
7480 reflects the latest sources. Then the ALI file of the main unit is
7481 examined to find all the source files on which the main program depends,
7482 and @code{gnatmake} recursively applies the above procedure on all these files.
7484 This process ensures that @code{gnatmake} only trusts the dependencies
7485 in an existing ALI file if they are known to be correct. Otherwise it
7486 always recompiles to determine a new, guaranteed accurate set of
7487 dependencies. As a result the program is compiled "upside down" from what may
7488 be more familiar as the required order of compilation in some other Ada
7489 systems. In particular, clients are compiled before the units on which
7490 they depend. The ability of GNAT to compile in any order is critical in
7491 allowing an order of compilation to be chosen that guarantees that
7492 @code{gnatmake} will recompute a correct set of new dependencies if
7495 When invoking @code{gnatmake} with several @var{file_names}, if a unit is
7496 imported by several of the executables, it will be recompiled at most once.
7498 @node Examples of gnatmake Usage
7499 @section Examples of @code{gnatmake} Usage
7502 @item gnatmake hello.adb
7503 Compile all files necessary to bind and link the main program
7504 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
7505 resulting object files to generate an executable file @file{hello}.
7507 @item gnatmake main1 main2 main3
7508 Compile all files necessary to bind and link the main programs
7509 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
7510 (containing unit @code{Main2}) and @file{main3.adb}
7511 (containing unit @code{Main3}) and bind and link the resulting object files
7512 to generate three executable files @file{main1},
7516 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
7518 Compile all files necessary to bind and link the main program unit
7519 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
7520 be done with optimization level 2 and the order of elaboration will be
7521 listed by the binder. @code{gnatmake} will operate in quiet mode, not
7522 displaying commands it is executing.
7525 @node Renaming Files Using gnatchop
7526 @chapter Renaming Files Using @code{gnatchop}
7530 This chapter discusses how to handle files with multiple units by using
7531 the @code{gnatchop} utility. This utility is also useful in renaming
7532 files to meet the standard GNAT default file naming conventions.
7535 * Handling Files with Multiple Units::
7536 * Operating gnatchop in Compilation Mode::
7537 * Command Line for gnatchop::
7538 * Switches for gnatchop::
7539 * Examples of gnatchop Usage::
7542 @node Handling Files with Multiple Units
7543 @section Handling Files with Multiple Units
7546 The basic compilation model of GNAT requires that a file submitted to the
7547 compiler have only one unit and there be a strict correspondence
7548 between the file name and the unit name.
7550 The @code{gnatchop} utility allows both of these rules to be relaxed,
7551 allowing GNAT to process files which contain multiple compilation units
7552 and files with arbitrary file names. @code{gnatchop}
7553 reads the specified file and generates one or more output files,
7554 containing one unit per file. The unit and the file name correspond,
7555 as required by GNAT.
7557 If you want to permanently restructure a set of "foreign" files so that
7558 they match the GNAT rules, and do the remaining development using the
7559 GNAT structure, you can simply use @code{gnatchop} once, generate the
7560 new set of files and work with them from that point on.
7562 Alternatively, if you want to keep your files in the "foreign" format,
7563 perhaps to maintain compatibility with some other Ada compilation
7564 system, you can set up a procedure where you use @code{gnatchop} each
7565 time you compile, regarding the source files that it writes as temporary
7566 files that you throw away.
7568 @node Operating gnatchop in Compilation Mode
7569 @section Operating gnatchop in Compilation Mode
7572 The basic function of @code{gnatchop} is to take a file with multiple units
7573 and split it into separate files. The boundary between files is reasonably
7574 clear, except for the issue of comments and pragmas. In default mode, the
7575 rule is that any pragmas between units belong to the previous unit, except
7576 that configuration pragmas always belong to the following unit. Any comments
7577 belong to the following unit. These rules
7578 almost always result in the right choice of
7579 the split point without needing to mark it explicitly and most users will
7580 find this default to be what they want. In this default mode it is incorrect to
7581 submit a file containing only configuration pragmas, or one that ends in
7582 configuration pragmas, to @code{gnatchop}.
7584 However, using a special option to activate "compilation mode",
7586 can perform another function, which is to provide exactly the semantics
7587 required by the RM for handling of configuration pragmas in a compilation.
7588 In the absence of configuration pragmas (at the main file level), this
7589 option has no effect, but it causes such configuration pragmas to be handled
7590 in a quite different manner.
7592 First, in compilation mode, if @code{gnatchop} is given a file that consists of
7593 only configuration pragmas, then this file is appended to the
7594 @file{gnat.adc} file in the current directory. This behavior provides
7595 the required behavior described in the RM for the actions to be taken
7596 on submitting such a file to the compiler, namely that these pragmas
7597 should apply to all subsequent compilations in the same compilation
7598 environment. Using GNAT, the current directory, possibly containing a
7599 @file{gnat.adc} file is the representation
7600 of a compilation environment. For more information on the
7601 @file{gnat.adc} file, see the section on handling of configuration
7602 pragmas @pxref{Handling of Configuration Pragmas}.
7604 Second, in compilation mode, if @code{gnatchop}
7605 is given a file that starts with
7606 configuration pragmas, and contains one or more units, then these
7607 configuration pragmas are prepended to each of the chopped files. This
7608 behavior provides the required behavior described in the RM for the
7609 actions to be taken on compiling such a file, namely that the pragmas
7610 apply to all units in the compilation, but not to subsequently compiled
7613 Finally, if configuration pragmas appear between units, they are appended
7614 to the previous unit. This results in the previous unit being illegal,
7615 since the compiler does not accept configuration pragmas that follow
7616 a unit. This provides the required RM behavior that forbids configuration
7617 pragmas other than those preceding the first compilation unit of a
7620 For most purposes, @code{gnatchop} will be used in default mode. The
7621 compilation mode described above is used only if you need exactly
7622 accurate behavior with respect to compilations, and you have files
7623 that contain multiple units and configuration pragmas. In this
7624 circumstance the use of @code{gnatchop} with the compilation mode
7625 switch provides the required behavior, and is for example the mode
7626 in which GNAT processes the ACVC tests.
7628 @node Command Line for gnatchop
7629 @section Command Line for @code{gnatchop}
7632 The @code{gnatchop} command has the form:
7635 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
7640 The only required argument is the file name of the file to be chopped.
7641 There are no restrictions on the form of this file name. The file itself
7642 contains one or more Ada units, in normal GNAT format, concatenated
7643 together. As shown, more than one file may be presented to be chopped.
7645 When run in default mode, @code{gnatchop} generates one output file in
7646 the current directory for each unit in each of the files.
7648 @var{directory}, if specified, gives the name of the directory to which
7649 the output files will be written. If it is not specified, all files are
7650 written to the current directory.
7652 For example, given a
7653 file called @file{hellofiles} containing
7658 @b{procedure} hello;
7660 @b{with} Text_IO; @b{use} Text_IO;
7661 @b{procedure} hello @b{is}
7673 $ gnatchop hellofiles
7677 generates two files in the current directory, one called
7678 @file{hello.ads} containing the single line that is the procedure spec,
7679 and the other called @file{hello.adb} containing the remaining text. The
7680 original file is not affected. The generated files can be compiled in
7683 @node Switches for gnatchop
7684 @section Switches for @code{gnatchop}
7687 @code{gnatchop} recognizes the following switches:
7692 @cindex @code{-c} (@code{gnatchop})
7693 Causes @code{gnatchop} to operate in compilation mode, in which
7694 configuration pragmas are handled according to strict RM rules. See
7695 previous section for a full description of this mode.
7698 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
7699 used to parse the given file. Not all @code{xxx} options make sense,
7700 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
7701 process a source file that uses Latin-2 coding for identifiers.
7704 Causes @code{gnatchop} to generate a brief help summary to the standard
7705 output file showing usage information.
7708 @cindex @code{-k} (@code{gnatchop})
7709 Limit generated file names to the specified number @code{mm}
7711 This is useful if the
7712 resulting set of files is required to be interoperable with systems
7713 which limit the length of file names.
7714 No space is allowed between the @code{-k} and the numeric value. The numeric
7715 value may be omitted in which case a default of @code{-k8},
7717 with DOS-like file systems, is used. If no @code{-k} switch
7719 there is no limit on the length of file names.
7722 @cindex @code{-p} (@code{gnatchop})
7723 Causes the file modification time stamp of the input file to be
7724 preserved and used for the time stamp of the output file(s). This may be
7725 useful for preserving coherency of time stamps in an enviroment where
7726 @code{gnatchop} is used as part of a standard build process.
7729 @cindex @code{-q} (@code{gnatchop})
7730 Causes output of informational messages indicating the set of generated
7731 files to be suppressed. Warnings and error messages are unaffected.
7734 @cindex @code{-r} (@code{gnatchop})
7735 @findex Source_Reference
7736 Generate @code{Source_Reference} pragmas. Use this switch if the output
7737 files are regarded as temporary and development is to be done in terms
7738 of the original unchopped file. This switch causes
7739 @code{Source_Reference} pragmas to be inserted into each of the
7740 generated files to refers back to the original file name and line number.
7741 The result is that all error messages refer back to the original
7743 In addition, the debugging information placed into the object file (when
7744 the @code{-g} switch of @code{gcc} or @code{gnatmake} is specified) also
7745 refers back to this original file so that tools like profilers and
7746 debuggers will give information in terms of the original unchopped file.
7748 If the original file to be chopped itself contains
7749 a @code{Source_Reference}
7750 pragma referencing a third file, then gnatchop respects
7751 this pragma, and the generated @code{Source_Reference} pragmas
7752 in the chopped file refer to the original file, with appropriate
7753 line numbers. This is particularly useful when @code{gnatchop}
7754 is used in conjunction with @code{gnatprep} to compile files that
7755 contain preprocessing statements and multiple units.
7758 @cindex @code{-v} (@code{gnatchop})
7759 Causes @code{gnatchop} to operate in verbose mode. The version
7760 number and copyright notice are output, as well as exact copies of
7761 the gnat1 commands spawned to obtain the chop control information.
7764 @cindex @code{-w} (@code{gnatchop})
7765 Overwrite existing file names. Normally @code{gnatchop} regards it as a
7766 fatal error if there is already a file with the same name as a
7767 file it would otherwise output, in other words if the files to be
7768 chopped contain duplicated units. This switch bypasses this
7769 check, and causes all but the last instance of such duplicated
7770 units to be skipped.
7773 @cindex @code{--GCC=} (@code{gnatchop})
7774 Specify the path of the GNAT parser to be used. When this switch is used,
7775 no attempt is made to add the prefix to the GNAT parser executable.
7778 @node Examples of gnatchop Usage
7779 @section Examples of @code{gnatchop} Usage
7782 @item gnatchop -w hello_s.ada ichbiah/files
7784 Chops the source file @file{hello_s.ada}. The output files will be
7785 placed in the directory @file{ichbiah/files},
7787 files with matching names in that directory (no files in the current
7788 directory are modified).
7790 @item gnatchop archive
7791 Chops the source file @file{archive}
7792 into the current directory. One
7793 useful application of @code{gnatchop} is in sending sets of sources
7794 around, for example in email messages. The required sources are simply
7795 concatenated (for example, using a Unix @code{cat}
7797 @code{gnatchop} is used at the other end to reconstitute the original
7800 @item gnatchop file1 file2 file3 direc
7801 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
7802 the resulting files in the directory @file{direc}. Note that if any units
7803 occur more than once anywhere within this set of files, an error message
7804 is generated, and no files are written. To override this check, use the
7806 in which case the last occurrence in the last file will
7807 be the one that is output, and earlier duplicate occurrences for a given
7808 unit will be skipped.
7811 @node Configuration Pragmas
7812 @chapter Configuration Pragmas
7813 @cindex Configuration pragmas
7814 @cindex Pragmas, configuration
7817 In Ada 95, configuration pragmas include those pragmas described as
7818 such in the Ada 95 Reference Manual, as well as
7819 implementation-dependent pragmas that are configuration pragmas. See the
7820 individual descriptions of pragmas in the GNAT Reference Manual for
7821 details on these additional GNAT-specific configuration pragmas. Most
7822 notably, the pragma @code{Source_File_Name}, which allows
7823 specifying non-default names for source files, is a configuration
7824 pragma. The following is a complete list of configuration pragmas
7825 recognized by @code{GNAT}:
7837 External_Name_Casing
7838 Float_Representation
7846 Propagate_Exceptions
7855 Task_Dispatching_Policy
7863 * Handling of Configuration Pragmas::
7864 * The Configuration Pragmas Files::
7867 @node Handling of Configuration Pragmas
7868 @section Handling of Configuration Pragmas
7870 Configuration pragmas may either appear at the start of a compilation
7871 unit, in which case they apply only to that unit, or they may apply to
7872 all compilations performed in a given compilation environment.
7874 GNAT also provides the @code{gnatchop} utility to provide an automatic
7875 way to handle configuration pragmas following the semantics for
7876 compilations (that is, files with multiple units), described in the RM.
7877 See section @pxref{Operating gnatchop in Compilation Mode} for details.
7878 However, for most purposes, it will be more convenient to edit the
7879 @file{gnat.adc} file that contains configuration pragmas directly,
7880 as described in the following section.
7882 @node The Configuration Pragmas Files
7883 @section The Configuration Pragmas Files
7884 @cindex @file{gnat.adc}
7887 In GNAT a compilation environment is defined by the current
7888 directory at the time that a compile command is given. This current
7889 directory is searched for a file whose name is @file{gnat.adc}. If
7890 this file is present, it is expected to contain one or more
7891 configuration pragmas that will be applied to the current compilation.
7892 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
7895 Configuration pragmas may be entered into the @file{gnat.adc} file
7896 either by running @code{gnatchop} on a source file that consists only of
7897 configuration pragmas, or more conveniently by
7898 direct editing of the @file{gnat.adc} file, which is a standard format
7901 In addition to @file{gnat.adc}, one additional file containing configuration
7902 pragmas may be applied to the current compilation using the switch
7903 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
7904 contains only configuration pragmas. These configuration pragmas are
7905 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
7906 is present and switch @option{-gnatA} is not used).
7908 It is allowed to specify several switches @option{-gnatec}, however only
7909 the last one on the command line will be taken into account.
7912 @node Handling Arbitrary File Naming Conventions Using gnatname
7913 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
7914 @cindex Arbitrary File Naming Conventions
7917 * Arbitrary File Naming Conventions::
7918 * Running gnatname::
7919 * Switches for gnatname::
7920 * Examples of gnatname Usage::
7923 @node Arbitrary File Naming Conventions
7924 @section Arbitrary File Naming Conventions
7927 The GNAT compiler must be able to know the source file name of a compilation unit.
7928 When using the standard GNAT default file naming conventions (@code{.ads} for specs,
7929 @code{.adb} for bodies), the GNAT compiler does not need additional information.
7932 When the source file names do not follow the standard GNAT default file naming
7933 conventions, the GNAT compiler must be given additional information through
7934 a configuration pragmas file (see @ref{Configuration Pragmas}) or a project file.
7935 When the non standard file naming conventions are well-defined, a small number of
7936 pragmas @code{Source_File_Name} specifying a naming pattern
7937 (see @ref{Alternative File Naming Schemes}) may be sufficient. However,
7938 if the file naming conventions are irregular or arbitrary, a number
7939 of pragma @code{Source_File_Name} for individual compilation units must be defined.
7940 To help maintain the correspondence between compilation unit names and
7941 source file names within the compiler,
7942 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
7945 @node Running gnatname
7946 @section Running @code{gnatname}
7949 The usual form of the @code{gnatname} command is
7952 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
7956 All of the arguments are optional. If invoked without any argument,
7957 @code{gnatname} will display its usage.
7960 When used with at least one naming pattern, @code{gnatname} will attempt to
7961 find all the compilation units in files that follow at least one of the
7962 naming patterns. To find these compilation units,
7963 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
7967 One or several Naming Patterns may be given as arguments to @code{gnatname}.
7968 Each Naming Pattern is enclosed between double quotes.
7969 A Naming Pattern is a regular expression similar to the wildcard patterns
7970 used in file names by the Unix shells or the DOS prompt.
7973 Examples of Naming Patterns are
7982 For a more complete description of the syntax of Naming Patterns, see the second kind
7983 of regular expressions described in @file{g-regexp.ads} (the "Glob" regular
7987 When invoked with no switches, @code{gnatname} will create a configuration
7988 pragmas file @file{gnat.adc} in the current working directory, with pragmas
7989 @code{Source_File_Name} for each file that contains a valid Ada unit.
7991 @node Switches for gnatname
7992 @section Switches for @code{gnatname}
7995 Switches for @code{gnatname} must precede any specified Naming Pattern.
7998 You may specify any of the following switches to @code{gnatname}:
8003 @cindex @code{-c} (@code{gnatname})
8004 Create a configuration pragmas file @file{file} (instead of the default
8005 @file{gnat.adc}). There may be zero, one or more space between @code{-c} and
8006 @file{file}. @file{file} may include directory information. @file{file} must be
8007 writeable. There may be only one switch @code{-c}. When a switch @code{-c} is
8008 specified, no switch @code{-P} may be specified (see below).
8011 @cindex @code{-d} (@code{gnatname})
8012 Look for source files in directory @file{dir}. There may be zero, one or more spaces
8013 between @code{-d} and @file{dir}. When a switch @code{-d} is specified,
8014 the current working directory will not be searched for source files, unless it
8016 specified with a @code{-d} or @code{-D} switch. Several switches @code{-d} may be
8017 specified. If @file{dir} is a relative path, it is relative to the directory of
8018 the configuration pragmas file specified with switch @code{-c}, or to the directory
8019 of the project file specified with switch @code{-P} or, if neither switch @code{-c}
8020 nor switch @code{-P} are specified, it is relative to the current working
8021 directory. The directory
8022 specified with switch @code{-c} must exist and be readable.
8025 @cindex @code{-D} (@code{gnatname})
8026 Look for source files in all directories listed in text file @file{file}. There may be
8027 zero, one or more spaces between @code{-d} and @file{dir}. @file{file}
8028 must be an existing, readable text file. Each non empty line in @file{file} must be
8029 a directory. Specifying switch @code{-D} is equivalent to specifying as many switches
8030 @code{-d} as there are non empty lines in @file{file}.
8033 @cindex @code{-h} (@code{gnatname})
8034 Output usage (help) information. The output is written to @file{stdout}.
8037 @cindex @code{-P} (@code{gnatname})
8038 Create or update project file @file{proj}. There may be zero, one or more space
8039 between @code{-P} and @file{proj}. @file{proj} may include directory information.
8040 @file{proj} must be writeable. There may be only one switch @code{-P}.
8041 When a switch @code{-P} is specified, no switch @code{-c} may be specified.
8044 @cindex @code{-v} (@code{gnatname})
8045 Verbose mode. Output detailed explanation of behavior to @file{stdout}. This includes
8046 name of the file written, the name of the directories to search and, for each file
8047 in those directories whose name matches at least one of the Naming Patterns, an
8048 indication of whether the file contains a unit, and if so the name of the unit.
8051 Very Verbose mode. In addition to the output produced in verbose mode, for each file
8052 in the searched directories whose name matches none of the Naming Patterns, an
8053 indication is given that there is no match.
8055 @item -x@file{pattern}
8056 Excluded patterns. Using this switch, it is possible to exclude some files
8057 that would match the name patterns. For example,
8058 @code{"gnatname -x "*_nt.ada" "*.ada"} will look for Ada units in all files
8059 with the @file{.ada} extension, except those whose names end with
8064 @node Examples of gnatname Usage
8065 @section Examples of @code{gnatname} Usage
8068 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
8071 In this example, the directory @file{/home/me} must already exist and be
8072 writeable. In addition, the directory @file{/home/me/sources} (specified by
8073 @code{-d sources}) must exist and be readable. Note the optional spaces after
8074 @code{-c} and @code{-d}.
8077 $ gnatname -P/home/me/proj -x "*_nt_body.ada" -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
8080 Note that several switches @code{-d} may be used, even in conjunction with one
8081 or several switches @code{-D}. Several Naming Patterns and one excluded pattern
8082 are used in this example.
8085 @c *****************************************
8086 @c * G N A T P r o j e c t M a n a g e r *
8087 @c *****************************************
8088 @node GNAT Project Manager
8089 @chapter GNAT Project Manager
8093 * Examples of Project Files::
8094 * Project File Syntax::
8095 * Objects and Sources in Project Files::
8096 * Importing Projects::
8097 * Project Extension::
8098 * External References in Project Files::
8099 * Packages in Project Files::
8100 * Variables from Imported Projects::
8102 * Library Projects::
8103 * Switches Related to Project Files::
8104 * Tools Supporting Project Files::
8105 * An Extended Example::
8106 * Project File Complete Syntax::
8115 @section Introduction
8118 This chapter describes GNAT's @emph{Project Manager}, a facility that
8119 lets you configure various properties for a collection of source files. In
8120 particular, you can specify:
8123 The directory or set of directories containing the source files, and/or the
8124 names of the specific source files themselves
8126 The directory in which the compiler's output
8127 (@file{ALI} files, object files, tree files) will be placed
8129 The directory in which the executable programs will be placed
8131 Switch settings for any of the project-enabled tools (@command{gnatmake},
8132 compiler, binder, linker, @code{gnatls}, @code{gnatxref}, @code{gnatfind});
8133 you can apply these settings either globally or to individual units
8135 The source files containing the main subprogram(s) to be built
8137 The source programming language(s) (currently Ada and/or C)
8139 Source file naming conventions; you can specify these either globally or for
8148 @subsection Project Files
8151 A @dfn{project} is a specific set of values for these properties. You can
8152 define a project's settings in a @dfn{project file}, a text file with an
8153 Ada-like syntax; a property value is either a string or a list of strings.
8154 Properties that are not explicitly set receive default values. A project
8155 file may interrogate the values of @dfn{external variables} (user-defined
8156 command-line switches or environment variables), and it may specify property
8157 settings conditionally, based on the value of such variables.
8159 In simple cases, a project's source files depend only on other source files
8160 in the same project, or on the predefined libraries. ("Dependence" is in
8161 the technical sense; for example, one Ada unit "with"ing another.) However,
8162 the Project Manager also allows much more sophisticated arrangements,
8163 with the source files in one project depending on source files in other
8167 One project can @emph{import} other projects containing needed source files.
8169 You can organize GNAT projects in a hierarchy: a @emph{child} project
8170 can extend a @emph{parent} project, inheriting the parent's source files and
8171 optionally overriding any of them with alternative versions
8175 More generally, the Project Manager lets you structure large development
8176 efforts into hierarchical subsystems, with build decisions deferred to the
8177 subsystem level and thus different compilation environments (switch settings)
8178 used for different subsystems.
8180 The Project Manager is invoked through the @option{-P@emph{projectfile}}
8181 switch to @command{gnatmake} or to the @command{gnat} front driver.
8182 If you want to define (on the command line) an external variable that is
8183 queried by the project file, additionally use the
8184 @option{-X@emph{vbl}=@emph{value}} switch.
8185 The Project Manager parses and interprets the project file, and drives the
8186 invoked tool based on the project settings.
8188 The Project Manager supports a wide range of development strategies,
8189 for systems of all sizes. Some typical practices that are easily handled:
8192 Using a common set of source files, but generating object files in different
8193 directories via different switch settings
8195 Using a mostly-shared set of source files, but with different versions of
8200 The destination of an executable can be controlled inside a project file
8201 using the @option{-o} switch. In the absence of such a switch either inside
8202 the project file or on the command line, any executable files generated by
8203 @command{gnatmake} will be placed in the directory @code{Exec_Dir} specified
8204 in the project file. If no @code{Exec_Dir} is specified, they will be placed
8205 in the object directory of the project.
8207 You can use project files to achieve some of the effects of a source
8208 versioning system (for example, defining separate projects for
8209 the different sets of sources that comprise different releases) but the
8210 Project Manager is independent of any source configuration management tools
8211 that might be used by the developers.
8213 The next section introduces the main features of GNAT's project facility
8214 through a sequence of examples; subsequent sections will present the syntax
8215 and semantics in more detail.
8218 @c *****************************
8219 @c * Examples of Project Files *
8220 @c *****************************
8222 @node Examples of Project Files
8223 @section Examples of Project Files
8225 This section illustrates some of the typical uses of project files and
8226 explains their basic structure and behavior.
8229 * Common Sources with Different Switches and Different Output Directories::
8230 * Using External Variables::
8231 * Importing Other Projects::
8232 * Extending a Project::
8235 @node Common Sources with Different Switches and Different Output Directories
8236 @subsection Common Sources with Different Switches and Different Output Directories
8240 * Specifying the Object Directory::
8241 * Specifying the Exec Directory::
8242 * Project File Packages::
8243 * Specifying Switch Settings::
8244 * Main Subprograms::
8245 * Source File Naming Conventions::
8246 * Source Language(s)::
8250 Assume that the Ada source files @file{pack.ads}, @file{pack.adb}, and
8251 @file{proc.adb} are in the @file{/common} directory. The file
8252 @file{proc.adb} contains an Ada main subprogram @code{Proc} that "with"s
8253 package @code{Pack}. We want to compile these source files under two sets
8257 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
8258 and the @option{-gnata}, @option{-gnato}, and @option{-gnatE} switches to the
8259 compiler; the compiler's output is to appear in @file{/common/debug}
8261 When preparing a release version, we want to pass the @option{-O2} switch to
8262 the compiler; the compiler's output is to appear in @file{/common/release}
8266 The GNAT project files shown below, respectively @file{debug.gpr} and
8267 @file{release.gpr} in the @file{/common} directory, achieve these effects.
8280 /common/debug @{-g, -gnata, -gnato, -gnatE@}
8285 /common/release @{-O2@}
8290 Here are the project files:
8294 for Object_Dir use "debug";
8295 for Main use ("proc");
8298 for Default_Switches ("Ada") use ("-g");
8304 for Default_Switches ("Ada")
8305 use ("-fstack-check", "-gnata", "-gnato", "-gnatE");
8314 for Object_Dir use "release";
8315 for Exec_Dir use ".";
8316 for Main use ("proc");
8319 for Default_Switches ("Ada") use ("-O2");
8326 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
8327 insensitive), and analogously the project defined by @file{release.gpr} is
8328 @code{"Release"}. For consistency the file should have the same name as the
8329 project, and the project file's extension should be @code{"gpr"}. These
8330 conventions are not required, but a warning is issued if they are not followed.
8332 If the current directory is @file{/temp}, then the command
8334 gnatmake -P/common/debug.gpr
8338 generates object and ALI files in @file{/common/debug}, and the @code{proc}
8339 executable also in @file{/common/debug}, using the switch settings defined in
8342 Likewise, the command
8344 gnatmake -P/common/release.gpr
8348 generates object and ALI files in @file{/common/release}, and the @code{proc}
8349 executable in @file{/common}, using the switch settings from the project file.
8352 @unnumberedsubsubsec Source Files
8355 If a project file does not explicitly specify a set of source directories or
8356 a set of source files, then by default the project's source files are the
8357 Ada source files in the project file directory. Thus @file{pack.ads},
8358 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
8360 @node Specifying the Object Directory
8361 @unnumberedsubsubsec Specifying the Object Directory
8364 Several project properties are modeled by Ada-style @emph{attributes};
8365 you define the property by supplying the equivalent of an Ada attribute
8366 definition clause in the project file.
8367 A project's object directory is such a property; the corresponding
8368 attribute is @code{Object_Dir}, and its value is a string expression. A
8369 directory may be specified either as absolute or as relative; in the latter
8370 case, it is relative to the project file directory. Thus the compiler's
8371 output is directed to @file{/common/debug} (for the @code{Debug} project)
8372 and to @file{/common/release} (for the @code{Release} project). If
8373 @code{Object_Dir} is not specified, then the default is the project file
8376 @node Specifying the Exec Directory
8377 @unnumberedsubsubsec Specifying the Exec Directory
8380 A project's exec directory is another property; the corresponding
8381 attribute is @code{Exec_Dir}, and its value is also a string expression,
8382 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
8383 then the default is the object directory (which may also be the project file
8384 directory if attribute @code{Object_Dir} is not specified). Thus the executable
8385 is placed in @file{/common/debug} for the @code{Debug} project (attribute
8386 @code{Exec_Dir} not specified) and in @file{/common} for the @code{Release}
8389 @node Project File Packages
8390 @unnumberedsubsubsec Project File Packages
8393 A GNAT tool integrated with the Project Manager is modeled by a
8394 corresponding package in the project file.
8395 The @code{Debug} project defines the packages @code{Builder}
8396 (for @command{gnatmake}) and @code{Compiler};
8397 the @code{Release} project defines only the @code{Compiler} package.
8399 The Ada package syntax is not to be taken literally. Although packages in
8400 project files bear a surface resemblance to packages in Ada source code, the
8401 notation is simply a way to convey a grouping of properties for a named
8402 entity. Indeed, the package names permitted in project files are restricted
8403 to a predefined set, corresponding to the project-aware tools, and the contents
8404 of packages are limited to a small set of constructs.
8405 The packages in the example above contain attribute definitions.
8408 @node Specifying Switch Settings
8409 @unnumberedsubsubsec Specifying Switch Settings
8412 Switch settings for a project-aware tool can be specified through attributes
8413 in the package corresponding to the tool.
8414 The example above illustrates one of the relevant attributes,
8415 @code{Default_Switches}, defined in the packages in both project files.
8416 Unlike simple attributes like @code{Source_Dirs}, @code{Default_Switches} is
8417 known as an @emph{associative array}. When you define this attribute, you must
8418 supply an "index" (a literal string), and the effect of the attribute
8419 definition is to set the value of the "array" at the specified "index".
8420 For the @code{Default_Switches} attribute, the index is a programming
8421 language (in our case, Ada) , and the value specified (after @code{use})
8422 must be a list of string expressions.
8424 The attributes permitted in project files are restricted to a predefined set.
8425 Some may appear at project level, others in packages.
8426 For any attribute that is an associate array, the index must always be a
8427 literal string, but the restrictions on this string (e.g., a file name or a
8428 language name) depend on the individual attribute.
8429 Also depending on the attribute, its specified value will need to be either a
8430 string or a string list.
8432 In the @code{Debug} project, we set the switches for two tools,
8433 @command{gnatmake} and the compiler, and thus we include corresponding
8434 packages, with each package defining the @code{Default_Switches} attribute
8435 with index @code{"Ada"}.
8436 Note that the package corresponding to
8437 @command{gnatmake} is named @code{Builder}. The @code{Release} project is
8438 similar, but with just the @code{Compiler} package.
8440 In project @code{Debug} above the switches starting with @option{-gnat} that
8441 are specified in package @code{Compiler} could have been placed in package
8442 @code{Builder}, since @command{gnatmake} transmits all such switches to the
8445 @node Main Subprograms
8446 @unnumberedsubsubsec Main Subprograms
8449 One of the properties of a project is its list of main subprograms (actually
8450 a list of names of source files containing main subprograms, with the file
8451 extension optional. This property is captured in the @code{Main} attribute,
8452 whose value is a list of strings. If a project defines the @code{Main}
8453 attribute, then you do not need to identify the main subprogram(s) when
8454 invoking @command{gnatmake} (see @ref{gnatmake and Project Files}).
8456 @node Source File Naming Conventions
8457 @unnumberedsubsubsec Source File Naming Conventions
8460 Since the project files do not specify any source file naming conventions,
8461 the GNAT defaults are used. The mechanism for defining source file naming
8462 conventions -- a package named @code{Naming} -- will be described below
8463 (@pxref{Naming Schemes}).
8465 @node Source Language(s)
8466 @unnumberedsubsubsec Source Language(s)
8469 Since the project files do not specify a @code{Languages} attribute, by
8470 default the GNAT tools assume that the language of the project file is Ada.
8471 More generally, a project can comprise source files
8472 in Ada, C, and/or other languages.
8474 @node Using External Variables
8475 @subsection Using External Variables
8478 Instead of supplying different project files for debug and release, we can
8479 define a single project file that queries an external variable (set either
8480 on the command line or via an environment variable) in order to
8481 conditionally define the appropriate settings. Again, assume that the
8482 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
8483 located in directory @file{/common}. The following project file,
8484 @file{build.gpr}, queries the external variable named @code{STYLE} and
8485 defines an object directory and switch settings based on whether the value
8486 is @code{"deb"} (debug) or @code{"rel"} (release), where the default is
8492 for Main use ("proc");
8494 type Style_Type is ("deb", "rel");
8495 Style : Style_Type := external ("STYLE", "deb");
8499 for Object_Dir use "debug";
8502 for Object_Dir use "release";
8503 for Exec_Dir use ".";
8512 for Default_Switches ("Ada") use ("-g");
8523 for Default_Switches ("Ada") use ("-gnata", "-gnato", "-gnatE");
8526 for Default_Switches ("Ada") use ("-O2");
8536 @code{Style_Type} is an example of a @emph{string type}, which is the project
8537 file analog of an Ada enumeration type but containing string literals rather
8538 than identifiers. @code{Style} is declared as a variable of this type.
8540 The form @code{external("STYLE", "deb")} is known as an
8541 @emph{external reference}; its first argument is the name of an
8542 @emph{external variable}, and the second argument is a default value to be
8543 used if the external variable doesn't exist. You can define an external
8544 variable on the command line via the @option{-X} switch, or you can use an
8545 environment variable as an external variable.
8547 Each @code{case} construct is expanded by the Project Manager based on the
8548 value of @code{Style}. Thus the command
8550 gnatmake -P/common/build.gpr -XSTYLE=deb
8554 is equivalent to the @command{gnatmake} invocation using the project file
8555 @file{debug.gpr} in the earlier example. So is the command
8557 gnatmake -P/common/build.gpr
8561 since @code{"deb"} is the default for @code{STYLE}.
8565 gnatmake -P/common/build.gpr -XSTYLE=rel
8569 is equivalent to the @command{gnatmake} invocation using the project file
8570 @file{release.gpr} in the earlier example.
8573 @node Importing Other Projects
8574 @subsection Importing Other Projects
8577 A compilation unit in a source file in one project may depend on compilation
8578 units in source files in other projects. To obtain this behavior, the
8579 dependent project must @emph{import} the projects containing the needed source
8580 files. This effect is embodied in syntax similar to an Ada @code{with} clause,
8581 but the "with"ed entities are strings denoting project files.
8583 As an example, suppose that the two projects @code{GUI_Proj} and
8584 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
8585 @file{comm_proj.gpr} in directories @file{/gui} and @file{/comm},
8586 respectively. Assume that the source files for @code{GUI_Proj} are
8587 @file{gui.ads} and @file{gui.adb}, and that the source files for
8588 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, with each set of
8589 files located in its respective project file directory. Diagrammatically:
8608 We want to develop an application in directory @file{/app} that "with"s the
8609 packages @code{GUI} and @code{Comm}, using the properties of the
8610 corresponding project files (e.g. the switch settings and object directory).
8611 Skeletal code for a main procedure might be something like the following:
8616 procedure App_Main is
8625 Here is a project file, @file{app_proj.gpr}, that achieves the desired
8630 with "/gui/gui_proj", "/comm/comm_proj";
8632 for Main use ("app_main");
8638 Building an executable is achieved through the command:
8640 gnatmake -P/app/app_proj
8643 which will generate the @code{app_main} executable in the directory where
8644 @file{app_proj.gpr} resides.
8646 If an imported project file uses the standard extension (@code{gpr}) then
8647 (as illustrated above) the @code{with} clause can omit the extension.
8649 Our example specified an absolute path for each imported project file.
8650 Alternatively, you can omit the directory if either
8653 The imported project file is in the same directory as the importing project
8656 You have defined an environment variable @code{ADA_PROJECT_PATH} that
8657 includes the directory containing the needed project file.
8661 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{/gui} and
8662 @file{/comm}, then our project file @file{app_proj.gpr} could be written as
8667 with "gui_proj", "comm_proj";
8669 for Main use ("app_main");
8675 Importing other projects raises the possibility of ambiguities. For
8676 example, the same unit might be present in different imported projects, or
8677 it might be present in both the importing project and an imported project.
8678 Both of these conditions are errors. Note that in the current version of
8679 the Project Manager, it is illegal to have an ambiguous unit even if the
8680 unit is never referenced by the importing project. This restriction may be
8681 relaxed in a future release.
8683 @node Extending a Project
8684 @subsection Extending a Project
8687 A common situation in large software systems is to have multiple
8688 implementations for a common interface; in Ada terms, multiple versions of a
8689 package body for the same specification. For example, one implementation
8690 might be safe for use in tasking programs, while another might only be used
8691 in sequential applications. This can be modeled in GNAT using the concept
8692 of @emph{project extension}. If one project (the "child") @emph{extends}
8693 another project (the "parent") then by default all source files of the
8694 parent project are inherited by the child, but the child project can
8695 override any of the parent's source files with new versions, and can also
8696 add new files. This facility is the project analog of extension in
8697 Object-Oriented Programming. Project hierarchies are permitted (a child
8698 project may be the parent of yet another project), and a project that
8699 inherits one project can also import other projects.
8701 As an example, suppose that directory @file{/seq} contains the project file
8702 @file{seq_proj.gpr} and the source files @file{pack.ads}, @file{pack.adb},
8703 and @file{proc.adb}:
8716 Note that the project file can simply be empty (that is, no attribute or
8717 package is defined):
8727 implying that its source files are all the Ada source files in the project
8730 Suppose we want to supply an alternate version of @file{pack.adb}, in
8731 directory @file{/tasking}, but use the existing versions of @file{pack.ads}
8732 and @file{proc.adb}. We can define a project @code{Tasking_Proj} that
8733 inherits @code{Seq_Proj}:
8743 project Tasking_Proj extends "/seq/seq_proj" is
8749 The version of @file{pack.adb} used in a build depends on which project file
8752 Note that we could have designed this using project import rather than
8753 project inheritance; a @code{base} project would contain the sources for
8754 @file{pack.ads} and @file{proc.adb}, a sequential project would import
8755 @code{base} and add @file{pack.adb}, and likewise a tasking project would
8756 import @code{base} and add a different version of @file{pack.adb}. The
8757 choice depends on whether other sources in the original project need to be
8758 overridden. If they do, then project extension is necessary, otherwise,
8759 importing is sufficient.
8762 @c ***********************
8763 @c * Project File Syntax *
8764 @c ***********************
8766 @node Project File Syntax
8767 @section Project File Syntax
8776 * Associative Array Attributes::
8777 * case Constructions::
8781 This section describes the structure of project files.
8783 A project may be an @emph{independent project}, entirely defined by a single
8784 project file. Any Ada source file in an independent project depends only
8785 on the predefined library and other Ada source files in the same project.
8788 A project may also @dfn{depend on} other projects, in either or both of the following ways:
8790 @item It may import any number of projects
8791 @item It may extend at most one other project
8795 The dependence relation is a directed acyclic graph (the subgraph reflecting
8796 the "extends" relation is a tree).
8798 A project's @dfn{immediate sources} are the source files directly defined by
8799 that project, either implicitly by residing in the project file's directory,
8800 or explicitly through any of the source-related attributes described below.
8801 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
8802 of @var{proj} together with the immediate sources (unless overridden) of any
8803 project on which @var{proj} depends (either directly or indirectly).
8806 @subsection Basic Syntax
8809 As seen in the earlier examples, project files have an Ada-like syntax.
8810 The minimal project file is:
8820 The identifier @code{Empty} is the name of the project.
8821 This project name must be present after the reserved
8822 word @code{end} at the end of the project file, followed by a semi-colon.
8824 Any name in a project file, such as the project name or a variable name,
8825 has the same syntax as an Ada identifier.
8827 The reserved words of project files are the Ada reserved words plus
8828 @code{extends}, @code{external}, and @code{project}. Note that the only Ada
8829 reserved words currently used in project file syntax are:
8857 Comments in project files have the same syntax as in Ada, two consecutives
8858 hyphens through the end of the line.
8861 @subsection Packages
8864 A project file may contain @emph{packages}. The name of a package must be one
8865 of the identifiers (case insensitive) from a predefined list, and a package
8866 with a given name may only appear once in a project file. The predefined list
8867 includes the following packages:
8883 @code{Cross_Reference}
8889 (The complete list of the package names and their attributes can be found
8890 in file @file{prj-attr.adb}).
8893 In its simplest form, a package may be empty:
8905 A package may contain @emph{attribute declarations},
8906 @emph{variable declarations} and @emph{case constructions}, as will be
8909 When there is ambiguity between a project name and a package name,
8910 the name always designates the project. To avoid possible confusion, it is
8911 always a good idea to avoid naming a project with one of the
8912 names allowed for packages or any name that starts with @code{gnat}.
8916 @subsection Expressions
8919 An @emph{expression} is either a @emph{string expression} or a
8920 @emph{string list expression}.
8922 A @emph{string expression} is either a @emph{simple string expression} or a
8923 @emph{compound string expression}.
8925 A @emph{simple string expression} is one of the following:
8927 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
8928 @item A string-valued variable reference (see @ref{Variables})
8929 @item A string-valued attribute reference (see @ref{Attributes})
8930 @item An external reference (see @ref{External References in Project Files})
8934 A @emph{compound string expression} is a concatenation of string expressions,
8937 Path & "/" & File_Name & ".ads"
8941 A @emph{string list expression} is either a
8942 @emph{simple string list expression} or a
8943 @emph{compound string list expression}.
8945 A @emph{simple string list expression} is one of the following:
8947 @item A parenthesized list of zero or more string expressions, separated by commas
8949 File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
8952 @item A string list-valued variable reference
8953 @item A string list-valued attribute reference
8957 A @emph{compound string list expression} is the concatenation (using
8958 @code{"&"}) of a simple string list expression and an expression. Note that
8959 each term in a compound string list expression, except the first, may be
8960 either a string expression or a string list expression.
8964 File_Name_List := () & File_Name; -- One string in this list
8965 Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
8967 Big_List := File_Name_List & Extended_File_Name_List;
8968 -- Concatenation of two string lists: three strings
8969 Illegal_List := "gnat.adc" & Extended_File_Name_List;
8970 -- Illegal: must start with a string list
8976 @subsection String Types
8979 The value of a variable may be restricted to a list of string literals.
8980 The restricted list of string literals is given in a
8981 @emph{string type declaration}.
8983 Here is an example of a string type declaration:
8986 type OS is ("NT, "nt", "Unix", "Linux", "other OS");
8990 Variables of a string type are called @emph{typed variables}; all other
8991 variables are called @emph{untyped variables}. Typed variables are
8992 particularly useful in @code{case} constructions
8993 (see @ref{case Constructions}).
8995 A string type declaration starts with the reserved word @code{type}, followed
8996 by the name of the string type (case-insensitive), followed by the reserved
8997 word @code{is}, followed by a parenthesized list of one or more string literals
8998 separated by commas, followed by a semicolon.
9000 The string literals in the list are case sensitive and must all be different.
9001 They may include any graphic characters allowed in Ada, including spaces.
9003 A string type may only be declared at the project level, not inside a package.
9005 A string type may be referenced by its name if it has been declared in the same
9006 project file, or by its project name, followed by a dot,
9007 followed by the string type name.
9011 @subsection Variables
9014 A variable may be declared at the project file level, or in a package.
9015 Here are some examples of variable declarations:
9019 This_OS : OS := external ("OS"); -- a typed variable declaration
9020 That_OS := "Linux"; -- an untyped variable declaration
9025 A @emph{typed variable declaration} includes the variable name, followed by a colon,
9026 followed by the name of a string type, followed by @code{:=}, followed by
9027 a simple string expression.
9029 An @emph{untyped variable declaration} includes the variable name,
9030 followed by @code{:=}, followed by an expression. Note that, despite the
9031 terminology, this form of "declaration" resembles more an assignment
9032 than a declaration in Ada. It is a declaration in several senses:
9035 The variable name does not need to be defined previously
9037 The declaration establishes the @emph{kind} (string versus string list) of the
9038 variable, and later declarations of the same variable need to be consistent
9043 A string variable declaration (typed or untyped) declares a variable
9044 whose value is a string. This variable may be used as a string expression.
9046 File_Name := "readme.txt";
9047 Saved_File_Name := File_Name & ".saved";
9051 A string list variable declaration declares a variable whose value is a list
9052 of strings. The list may contain any number (zero or more) of strings.
9056 List_With_One_Element := ("-gnaty");
9057 List_With_Two_Elements := List_With_One_Element & "-gnatg";
9058 Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
9059 "pack2.ada", "util_.ada", "util.ada");
9063 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.
9065 The same untyped variable may be declared several times.
9066 In this case, the new value replaces the old one,
9067 and any subsequent reference to the variable uses the new value.
9068 However, as noted above, if a variable has been declared as a string, all subsequent
9069 declarations must give it a string value. Similarly, if a variable has
9070 been declared as a string list, all subsequent declarations
9071 must give it a string list value.
9073 A @emph{variable reference} may take several forms:
9076 @item The simple variable name, for a variable in the current package (if any) or in the current project
9077 @item A context name, followed by a dot, followed by the variable name.
9081 A @emph{context} may be one of the following:
9084 @item The name of an existing package in the current project
9085 @item The name of an imported project of the current project
9086 @item The name of an ancestor project (i.e., a project extended by the current project, either directly or indirectly)
9087 @item An imported/parent project name, followed by a dot, followed by a package name
9091 A variable reference may be used in an expression.
9095 @subsection Attributes
9098 A project (and its packages) may have @emph{attributes} that define the project's properties.
9099 Some attributes have values that are strings;
9100 others have values that are string lists.
9102 There are two categories of attributes: @emph{simple attributes} and @emph{associative arrays}
9103 (see @ref{Associative Array Attributes}).
9105 The names of the attributes are restricted; there is a list of project
9106 attributes, and a list of package attributes for each package.
9107 The names are not case sensitive.
9109 The project attributes are as follows (all are simple attributes):
9111 @multitable @columnfractions .4 .3
9112 @item @emph{Attribute Name}
9114 @item @code{Source_Files}
9116 @item @code{Source_Dirs}
9118 @item @code{Source_List_File}
9120 @item @code{Object_Dir}
9122 @item @code{Exec_Dir}
9126 @item @code{Languages}
9128 @item @code{Library_Dir}
9130 @item @code{Library_Name}
9132 @item @code{Library_Kind}
9134 @item @code{Library_Elaboration}
9136 @item @code{Library_Version}
9141 The attributes for package @code{Naming} are as follows
9142 (see @ref{Naming Schemes}):
9144 @multitable @columnfractions .4 .2 .2 .2
9145 @item Attribute Name @tab Category @tab Index @tab Value
9146 @item @code{Specification_Suffix}
9147 @tab associative array
9150 @item @code{Implementation_Suffix}
9151 @tab associative array
9154 @item @code{Separate_Suffix}
9155 @tab simple attribute
9159 @tab simple attribute
9162 @item @code{Dot_Replacement}
9163 @tab simple attribute
9166 @item @code{Specification}
9167 @tab associative array
9170 @item @code{Implementation}
9171 @tab associative array
9174 @item @code{Specification_Exceptions}
9175 @tab associative array
9178 @item @code{Implementation_Exceptions}
9179 @tab associative array
9185 The attributes for package @code{Builder}, @code{Compiler}, @code{Binder},
9186 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
9187 are as follows (see @ref{Switches and Project Files}).
9189 @multitable @columnfractions .4 .2 .2 .2
9190 @item Attribute Name @tab Category @tab Index @tab Value
9191 @item @code{Default_Switches}
9192 @tab associative array
9195 @item @code{Switches}
9196 @tab associative array
9202 In addition, package @code{Builder} has a single string attribute
9203 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
9204 string attribute @code{Global_Configuration_Pragmas}.
9207 The attribute for package @code{Glide} are not documented: they are for
9211 Each simple attribute has a default value: the empty string (for string-valued
9212 attributes) and the empty list (for string list-valued attributes).
9214 Similar to variable declarations, an attribute declaration defines a new value
9217 Examples of simple attribute declarations:
9220 for Object_Dir use "objects";
9221 for Source_Dirs use ("units", "test/drivers");
9225 A @dfn{simple attribute declaration} starts with the reserved word @code{for},
9226 followed by the name of the attribute, followed by the reserved word
9227 @code{use}, followed by an expression (whose kind depends on the attribute),
9228 followed by a semicolon.
9230 Attributes may be referenced in expressions.
9231 The general form for such a reference is @code{<entity>'<attribute>}:
9232 the entity for which the attribute is defined,
9233 followed by an apostrophe, followed by the name of the attribute.
9234 For associative array attributes, a litteral string between parentheses
9235 need to be supplied as index.
9241 Naming'Dot_Replacement
9242 Imported_Project'Source_Dirs
9243 Imported_Project.Naming'Casing
9244 Builder'Default_Switches("Ada")
9250 @item @code{project} for an attribute of the current project
9251 @item The name of an existing package of the current project
9252 @item The name of an imported project
9253 @item The name of a parent project (extended by the current project)
9254 @item An imported/parent project name, followed by a dot,
9255 followed by a package name
9263 for Source_Dirs use project'Source_Dirs & "units";
9264 for Source_Dirs use project'Source_Dirs & "test/drivers"
9270 In the first attribute declaration, initially the attribute @code{Source_Dirs}
9271 has the default value: an empty string list. After this declaration,
9272 @code{Source_Dirs} is a string list of one element: "units".
9273 After the second attribute declaration @code{Source_Dirs} is a string list of
9274 two elements: "units" and "test/drivers".
9276 Note: this example is for illustration only. In practice,
9277 the project file would contain only one attribute declaration:
9280 for Source_Dirs use ("units", "test/drivers");
9284 @node Associative Array Attributes
9285 @subsection Associative Array Attributes
9288 Some attributes are defined as @emph{associative arrays}. An associative
9289 array may be regarded as a function that takes a string as a parameter
9290 and delivers a string or string list value as its result.
9292 Here are some examples of associative array attribute declarations:
9295 for Implementation ("main") use "Main.ada";
9296 for Switches ("main.ada") use ("-v", "-gnatv");
9297 for Switches ("main.ada") use Builder'Switches ("main.ada") & "-g";
9301 Like untyped variables and simple attributes, associative array attributes may be declared several times. Each declaration supplies a new value for the
9302 attribute, replacing the previous setting.
9305 @node case Constructions
9306 @subsection @code{case} Constructions
9309 A @code{case} construction is used in a project file to effect conditional
9311 Here is a typical example:
9316 type OS_Type is ("Linux", "Unix", "NT", "VMS");
9318 OS : OS_Type := external ("OS", "Linux");
9324 when "Linux" | "Unix" =>
9325 for Default_Switches ("Ada") use ("-gnath");
9327 for Default_Switches ("Ada") use ("-gnatP");
9336 The syntax of a @code{case} construction is based on the Ada case statement
9337 (although there is no @code{null} construction for empty alternatives).
9339 Following the reserved word @code{case} there is the case variable (a typed
9340 string variable), the reserved word @code{is}, and then a sequence of one or
9342 Each alternative comprises the reserved word @code{when}, either a list of
9343 literal strings separated by the @code{"|"} character or the reserved word
9344 @code{others}, and the @code{"=>"} token.
9345 Each literal string must belong to the string type that is the type of the
9347 An @code{others} alternative, if present, must occur last.
9348 The @code{end case;} sequence terminates the case construction.
9350 After each @code{=>}, there are zero or more constructions. The only
9351 constructions allowed in a case construction are other case constructions and
9352 attribute declarations. String type declarations, variable declarations and
9353 package declarations are not allowed.
9355 The value of the case variable is often given by an external reference
9356 (see @ref{External References in Project Files}).
9359 @c ****************************************
9360 @c * Objects and Sources in Project Files *
9361 @c ****************************************
9363 @node Objects and Sources in Project Files
9364 @section Objects and Sources in Project Files
9367 * Object Directory::
9369 * Source Directories::
9370 * Source File Names::
9374 Each project has exactly one object directory and one or more source
9375 directories. The source directories must contain at least one source file,
9376 unless the project file explicitly specifies that no source files are present
9377 (see @ref{Source File Names}).
9380 @node Object Directory
9381 @subsection Object Directory
9384 The object directory for a project is the directory containing the compiler's
9385 output (such as @file{ALI} files and object files) for the project's immediate
9386 sources. Note that for inherited sources (when extending a parent project) the
9387 parent project's object directory is used.
9389 The object directory is given by the value of the attribute @code{Object_Dir}
9390 in the project file.
9393 for Object_Dir use "objects";
9397 The attribute @var{Object_Dir} has a string value, the path name of the object
9398 directory. The path name may be absolute or relative to the directory of the
9399 project file. This directory must already exist, and be readable and writable.
9401 By default, when the attribute @code{Object_Dir} is not given an explicit value
9402 or when its value is the empty string, the object directory is the same as the
9403 directory containing the project file.
9406 @node Exec Directory
9407 @subsection Exec Directory
9410 The exec directory for a project is the directory containing the executables
9411 for the project's main subprograms.
9413 The exec directory is given by the value of the attribute @code{Exec_Dir}
9414 in the project file.
9417 for Exec_Dir use "executables";
9421 The attribute @var{Exec_Dir} has a string value, the path name of the exec
9422 directory. The path name may be absolute or relative to the directory of the
9423 project file. This directory must already exist, and be writable.
9425 By default, when the attribute @code{Exec_Dir} is not given an explicit value
9426 or when its value is the empty string, the exec directory is the same as the
9427 object directory of the project file.
9430 @node Source Directories
9431 @subsection Source Directories
9434 The source directories of a project are specified by the project file
9435 attribute @code{Source_Dirs}.
9437 This attribute's value is a string list. If the attribute is not given an
9438 explicit value, then there is only one source directory, the one where the
9439 project file resides.
9441 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
9445 for Source_Dirs use ();
9449 indicates that the project contains no source files.
9451 Otherwise, each string in the string list designates one or more
9455 for Source_Dirs use ("sources", "test/drivers");
9459 If a string in the list ends with @code{"/**"}, then the directory whose path
9460 name precedes the two asterisks, as well as all its subdirectories
9461 (recursively), are source directories.
9464 for Source_Dirs use ("/system/sources/**");
9468 Here the directory @code{/system/sources} and all of its subdirectories
9469 (recursively) are source directories.
9471 To specify that the source directories are the directory of the project file
9472 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
9474 for Source_Dirs use ("./**");
9478 Each of the source directories must exist and be readable.
9481 @node Source File Names
9482 @subsection Source File Names
9485 In a project that contains source files, their names may be specified by the
9486 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
9487 (a string). Source file names never include any directory information.
9489 If the attribute @code{Source_Files} is given an explicit value, then each
9490 element of the list is a source file name.
9493 for Source_Files use ("main.adb");
9494 for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
9498 If the attribute @code{Source_Files} is not given an explicit value,
9499 but the attribute @code{Source_List_File} is given a string value,
9500 then the source file names are contained in the text file whose path name
9501 (absolute or relative to the directory of the project file) is the
9502 value of the attribute @code{Source_List_File}.
9504 Each line in the file that is not empty or is not a comment
9505 contains a source file name. A comment line starts with two hyphens.
9508 for Source_List_File use "source_list.txt";
9512 By default, if neither the attribute @code{Source_Files} nor the attribute
9513 @code{Source_List_File} is given an explicit value, then each file in the
9514 source directories that conforms to the project's naming scheme
9515 (see @ref{Naming Schemes}) is an immediate source of the project.
9517 A warning is issued if both attributes @code{Source_Files} and
9518 @code{Source_List_File} are given explicit values. In this case, the attribute
9519 @code{Source_Files} prevails.
9521 Each source file name must be the name of one and only one existing source file
9522 in one of the source directories.
9524 A @code{Source_Files} attribute defined with an empty list as its value
9525 indicates that there are no source files in the project.
9527 Except for projects that are clearly specified as containing no Ada source
9528 files (@code{Source_Dirs} or @code{Source_Files} specified as an empty list,
9529 or @code{Languages} specified without @code{"Ada"} in the list)
9531 for Source_Dirs use ();
9532 for Source_Files use ();
9533 for Languages use ("C", "C++");
9537 a project must contain at least one immediate source.
9539 Projects with no source files are useful as template packages
9540 (see @ref{Packages in Project Files}) for other projects; in particular to
9541 define a package @code{Naming} (see @ref{Naming Schemes}).
9544 @c ****************************
9545 @c * Importing Projects *
9546 @c ****************************
9548 @node Importing Projects
9549 @section Importing Projects
9552 An immediate source of a project P may depend on source files that
9553 are neither immediate sources of P nor in the predefined library.
9554 To get this effect, P must @emph{import} the projects that contain the needed
9559 with "project1", "utilities.gpr";
9560 with "/namings/apex.gpr";
9567 As can be seen in this example, the syntax for importing projects is similar
9568 to the syntax for importing compilation units in Ada. However, project files
9569 use literal strings instead of names, and the @code{with} clause identifies
9570 project files rather than packages.
9572 Each literal string is the file name or path name (absolute or relative) of a
9573 project file. If a string is simply a file name, with no path, then its
9574 location is determined by the @emph{project path}:
9578 If the environment variable @env{ADA_PROJECT_PATH} exists, then the project
9579 path includes all the directories in this environment variable, plus the
9580 directory of the project file.
9583 If the environment variable @env{ADA_PROJECT_PATH} does not exist,
9584 then the project path contains only one directory, namely the one where
9585 the project file is located.
9589 If a relative pathname is used as in
9596 then the path is relative to the directory where the importing project file is
9597 located. Any symbolic link will be fully resolved in the directory
9598 of the importing project file before the imported project file is looked up.
9600 When the @code{with}'ed project file name does not have an extension,
9601 the default is @file{.gpr}. If a file with this extension is not found, then
9602 the file name as specified in the @code{with} clause (no extension) will be
9603 used. In the above example, if a file @code{project1.gpr} is found, then it
9604 will be used; otherwise, if a file @code{project1} exists then it will be used;
9605 if neither file exists, this is an error.
9607 A warning is issued if the name of the project file does not match the
9608 name of the project; this check is case insensitive.
9610 Any source file that is an immediate source of the imported project can be
9611 used by the immediate sources of the importing project, and recursively. Thus
9612 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
9613 sources of @code{A} may depend on the immediate sources of @code{C}, even if
9614 @code{A} does not import @code{C} explicitly. However, this is not recommended,
9615 because if and when @code{B} ceases to import @code{C}, some sources in
9616 @code{A} will no longer compile.
9618 A side effect of this capability is that cyclic dependences are not permitted:
9619 if @code{A} imports @code{B} (directly or indirectly) then @code{B} is not
9620 allowed to import @code{A}.
9623 @c *********************
9624 @c * Project Extension *
9625 @c *********************
9627 @node Project Extension
9628 @section Project Extension
9631 During development of a large system, it is sometimes necessary to use
9632 modified versions of some of the source files without changing the original
9633 sources. This can be achieved through a facility known as
9634 @emph{project extension}.
9637 project Modified_Utilities extends "/baseline/utilities.gpr" is ...
9641 The project file for the project being extended (the @emph{parent}) is
9642 identified by the literal string that follows the reserved word @code{extends},
9643 which itself follows the name of the extending project (the @emph{child}).
9645 By default, a child project inherits all the sources of its parent.
9646 However, inherited sources can be overridden: a unit with the same name as one
9647 in the parent will hide the original unit.
9648 Inherited sources are considered to be sources (but not immediate sources)
9649 of the child project; see @ref{Project File Syntax}.
9651 An inherited source file retains any switches specified in the parent project.
9653 For example if the project @code{Utilities} contains the specification and the
9654 body of an Ada package @code{Util_IO}, then the project
9655 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
9656 The original body of @code{Util_IO} will not be considered in program builds.
9657 However, the package specification will still be found in the project
9660 A child project can have only one parent but it may import any number of other
9663 A project is not allowed to import directly or indirectly at the same time a
9664 child project and any of its ancestors.
9667 @c ****************************************
9668 @c * External References in Project Files *
9669 @c ****************************************
9671 @node External References in Project Files
9672 @section External References in Project Files
9675 A project file may contain references to external variables; such references
9676 are called @emph{external references}.
9678 An external variable is either defined as part of the environment (an
9679 environment variable in Unix, for example) or else specified on the command
9680 line via the @option{-X@emph{vbl}=@emph{value}} switch. If both, then the
9681 command line value is used.
9683 An external reference is denoted by the built-in function
9684 @code{external}, which returns a string value. This function has two forms:
9686 @item @code{external (external_variable_name)}
9687 @item @code{external (external_variable_name, default_value)}
9691 Each parameter must be a string literal. For example:
9695 external ("OS", "Linux")
9699 In the form with one parameter, the function returns the value of
9700 the external variable given as parameter. If this name is not present in the
9701 environment, then the returned value is an empty string.
9703 In the form with two string parameters, the second parameter is
9704 the value returned when the variable given as the first parameter is not
9705 present in the environment. In the example above, if @code{"OS"} is not
9706 the name of an environment variable and is not passed on the command line,
9707 then the returned value will be @code{"Linux"}.
9709 An external reference may be part of a string expression or of a string
9710 list expression, to define variables or attributes.
9714 type Mode_Type is ("Debug", "Release");
9715 Mode : Mode_Type := external ("MODE");
9723 @c *****************************
9724 @c * Packages in Project Files *
9725 @c *****************************
9727 @node Packages in Project Files
9728 @section Packages in Project Files
9731 The @emph{package} is the project file feature that defines the settings for
9732 project-aware tools.
9733 For each such tool you can declare a corresponding package; the names for these
9734 packages are preset (see @ref{Packages}) but are not case sensitive.
9735 A package may contain variable declarations, attribute declarations, and case
9741 package Builder is -- used by gnatmake
9742 for Default_Switches ("Ada") use ("-v", "-g");
9749 A package declaration starts with the reserved word @code{package},
9750 followed by the package name (case insensitive), followed by the reserved word
9751 @code{is}. It ends with the reserved word @code{end}, followed by the package
9752 name, finally followed by a semi-colon.
9754 Most of the packages have an attribute @code{Default_Switches}.
9755 This attribute is an associative array, and its value is a string list.
9756 The index of the associative array is the name of a programming language (case
9757 insensitive). This attribute indicates the switch or switches to be used
9758 with the corresponding tool.
9760 Some packages also have another attribute, @code{Switches}, an associative
9761 array whose value is a string list. The index is the name of a source file.
9762 This attribute indicates the switch or switches to be used by the corresponding
9763 tool when dealing with this specific file.
9765 Further information on these switch-related attributes is found in
9766 @ref{Switches and Project Files}.
9768 A package may be declared as a @emph{renaming} of another package; e.g., from
9769 the project file for an imported project.
9773 with "/global/apex.gpr";
9775 package Naming renames Apex.Naming;
9782 Packages that are renamed in other project files often come from project files
9783 that have no sources: they are just used as templates. Any modification in the
9784 template will be reflected automatically in all the project files that rename
9785 a package from the template.
9787 In addition to the tool-oriented packages, you can also declare a package
9788 named @code{Naming} to establish specialized source file naming conventions
9789 (see @ref{Naming Schemes}).
9792 @c ************************************
9793 @c * Variables from Imported Projects *
9794 @c ************************************
9796 @node Variables from Imported Projects
9797 @section Variables from Imported Projects
9800 An attribute or variable defined in an imported or parent project can
9801 be used in expressions in the importing / extending project.
9802 Such an attribute or variable is prefixed with the name of the project
9803 and (if relevant) the name of package where it is defined.
9808 project Main extends "base" is
9809 Var1 := Imported.Var;
9810 Var2 := Base.Var & ".new";
9815 for Default_Switches ("Ada") use Imported.Builder.Ada_Switches &
9822 for Default_Switches ("Ada") use Base.Compiler.Ada_Switches;
9833 @code{Var1} is a copy of the variable @code{Var} defined in the project file
9834 @file{"imported.gpr"}
9836 the value of @code{Var2} is a copy of the value of variable @code{Var}
9837 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
9839 attribute @code{Default_Switches ("Ada")} in package @code{Builder}
9840 is a string list that includes in its value a copy of variable
9841 @code{Ada_Switches} defined in the @code{Builder} package in project file
9842 @file{imported.gpr} plus two new elements: @option{"-gnatg"} and @option{"-v"};
9844 attribute @code{Default_Switches ("Ada")} in package @code{Compiler}
9845 is a copy of the variable @code{Ada_Switches} defined in the @code{Compiler}
9846 package in project file @file{base.gpr}, the project being extended.
9850 @c ******************
9851 @c * Naming Schemes *
9852 @c ******************
9854 @node Naming Schemes
9855 @section Naming Schemes
9858 Sometimes an Ada software system is ported from a foreign compilation
9859 environment to GNAT, with file names that do not use the default GNAT
9860 conventions. Instead of changing all the file names (which for a variety of
9861 reasons might not be possible), you can define the relevant file naming scheme
9862 in the @code{Naming} package in your project file. For example, the following
9863 package models the Apex file naming rules:
9868 for Casing use "lowercase";
9869 for Dot_Replacement use ".";
9870 for Specification_Suffix ("Ada") use ".1.ada";
9871 for Implementation_Suffix ("Ada") use ".2.ada";
9877 You can define the following attributes in package @code{Naming}:
9882 This must be a string with one of the three values @code{"lowercase"},
9883 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
9886 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
9888 @item @var{Dot_Replacement}
9889 This must be a string whose value satisfies the following conditions:
9892 @item It must not be empty
9893 @item It cannot start or end with an alphanumeric character
9894 @item It cannot be a single underscore
9895 @item It cannot start with an underscore followed by an alphanumeric
9896 @item It cannot contain a dot @code{'.'} except if it the entire string is @code{"."}
9900 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
9902 @item @var{Specification_Suffix}
9903 This is an associative array (indexed by the programming language name, case
9904 insensitive) whose value is a string that must satisfy the following
9908 @item It must not be empty
9909 @item It cannot start with an alphanumeric character
9910 @item It cannot start with an underscore followed by an alphanumeric character
9913 If @code{Specification_Suffix ("Ada")} is not specified, then the default is
9916 @item @var{Implementation_Suffix}
9917 This is an associative array (indexed by the programming language name, case
9918 insensitive) whose value is a string that must satisfy the following
9922 @item It must not be empty
9923 @item It cannot start with an alphanumeric character
9924 @item It cannot start with an underscore followed by an alphanumeric character
9925 @item It cannot be a suffix of @code{Specification_Suffix}
9928 If @code{Implementation_Suffix ("Ada")} is not specified, then the default is
9931 @item @var{Separate_Suffix}
9932 This must be a string whose value satisfies the same conditions as
9933 @code{Implementation_Suffix}.
9936 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
9937 value as @code{Implementation_Suffix ("Ada")}.
9939 @item @var{Specification}
9941 You can use the @code{Specification} attribute, an associative array, to define
9942 the source file name for an individual Ada compilation unit's spec. The array
9943 index must be a string literal that identifies the Ada unit (case insensitive).
9944 The value of this attribute must be a string that identifies the file that
9945 contains this unit's spec (case sensitive or insensitive depending on the
9949 for Specification ("MyPack.MyChild") use "mypack.mychild.spec";
9952 @item @var{Implementation}
9954 You can use the @code{Implementation} attribute, an associative array, to
9955 define the source file name for an individual Ada compilation unit's body
9956 (possibly a subunit). The array index must be a string literal that identifies
9957 the Ada unit (case insensitive). The value of this attribute must be a string
9958 that identifies the file that contains this unit's body or subunit (case
9959 sensitive or insensitive depending on the operating system).
9962 for Implementation ("MyPack.MyChild") use "mypack.mychild.body";
9967 @c ********************
9968 @c * Library Projects *
9969 @c ********************
9971 @node Library Projects
9972 @section Library Projects
9975 @emph{Library projects} are projects whose object code is placed in a library.
9976 (Note that this facility is not yet supported on all platforms)
9978 To create a library project, you need to define in its project file
9979 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
9980 Additionally, you may define the library-related attributes
9981 @code{Library_Kind}, @code{Library_Version} and @code{Library_Elaboration}.
9983 The @code{Library_Name} attribute has a string value that must start with a
9984 letter and include only letters and digits.
9986 The @code{Library_Dir} attribute has a string value that designates the path
9987 (absolute or relative) of the directory where the library will reside.
9988 It must designate an existing directory, and this directory needs to be
9989 different from the project's object directory. It also needs to be writable.
9991 If both @code{Library_Name} and @code{Library_Dir} are specified and
9992 are legal, then the project file defines a library project. The optional
9993 library-related attributes are checked only for such project files.
9995 The @code{Library_Kind} attribute has a string value that must be one of the
9996 following (case insensitive): @code{"static"}, @code{"dynamic"} or
9997 @code{"relocatable"}. If this attribute is not specified, the library is a
9998 static library. Otherwise, the library may be dynamic or relocatable.
9999 Depending on the operating system, there may or may not be a distinction
10000 between dynamic and relocatable libraries. For example, on Unix there is no
10003 The @code{Library_Version} attribute has a string value whose interpretation
10004 is platform dependent. On Unix, it is used only for dynamic/relocatable
10005 libraries as the internal name of the library (the @code{"soname"}). If the
10006 library file name (built from the @code{Library_Name}) is different from the
10007 @code{Library_Version}, then the library file will be a symbolic link to the
10008 actual file whose name will be @code{Library_Version}.
10018 for Library_Dir use "lib_dir";
10019 for Library_Name use "dummy";
10020 for Library_Kind use "relocatable";
10021 for Library_Version use "libdummy.so." & Version;
10028 Directory @file{lib_dir} will contain the internal library file whose name
10029 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
10030 @file{libdummy.so.1}.
10032 When @command{gnatmake} detects that a project file (not the main project file)
10033 is a library project file, it will check all immediate sources of the project
10034 and rebuild the library if any of the sources have been recompiled.
10035 All @file{ALI} files will also be copied from the object directory to the
10036 library directory. To build executables, @command{gnatmake} will use the
10037 library rather than the individual object files.
10040 @c *************************************
10041 @c * Switches Related to Project Files *
10042 @c *************************************
10043 @node Switches Related to Project Files
10044 @section Switches Related to Project Files
10047 The following switches are used by GNAT tools that support project files:
10051 @item @option{-P@var{project}}
10052 Indicates the name of a project file. This project file will be parsed with
10053 the verbosity indicated by @option{-vP@emph{x}}, if any, and using the external
10054 references indicated by @option{-X} switches, if any.
10057 There must be only one @option{-P} switch on the command line.
10060 Since the Project Manager parses the project file only after all the switches
10061 on the command line are checked, the order of the switches @option{-P},
10062 @option{-Vp@emph{x}} or @option{-X} is not significant.
10064 @item @option{-X@var{name=value}}
10065 Indicates that external variable @var{name} has the value @var{value}.
10066 The Project Manager will use this value for occurrences of
10067 @code{external(name)} when parsing the project file.
10070 If @var{name} or @var{value} includes a space, then @var{name=value} should be
10071 put between quotes.
10078 Several @option{-X} switches can be used simultaneously.
10079 If several @option{-X} switches specify the same @var{name}, only the last one
10083 An external variable specified with a @option{-X} switch takes precedence
10084 over the value of the same name in the environment.
10086 @item @option{-vP@emph{x}}
10087 Indicates the verbosity of the parsing of GNAT project files.
10088 @option{-vP0} means Default (no output for syntactically correct project
10090 @option{-vP1} means Medium;
10091 @option{-vP2} means High.
10093 The default is Default.
10095 If several @option{-vP@emph{x}} switches are present, only the last one is
10101 @c **********************************
10102 @c * Tools Supporting Project Files *
10103 @c **********************************
10105 @node Tools Supporting Project Files
10106 @section Tools Supporting Project Files
10109 * gnatmake and Project Files::
10110 * The GNAT Driver and Project Files::
10111 * Glide and Project Files::
10114 @node gnatmake and Project Files
10115 @subsection gnatmake and Project Files
10118 This section covers two topics related to @command{gnatmake} and project files:
10119 defining switches for @command{gnatmake} and for the tools that it invokes;
10120 and the use of the @code{Main} attribute.
10123 * Switches and Project Files::
10124 * Project Files and Main Subprograms::
10127 @node Switches and Project Files
10128 @subsubsection Switches and Project Files
10131 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
10132 @code{Linker}, you can specify a @code{Default_Switches} attribute, a
10133 @code{Switches} attribute, or both; as their names imply, these switch-related
10134 attributes affect which switches are used for which files when
10135 @command{gnatmake} is invoked. As will be explained below, these
10136 package-contributed switches precede the switches passed on the
10137 @command{gnatmake} command line.
10139 The @code{Default_Switches} attribute is an associative array indexed by
10140 language name (case insensitive) and returning a string list. For example:
10144 package Compiler is
10145 for Default_Switches ("Ada") use ("-gnaty", "-v");
10151 The @code{Switches} attribute is also an associative array, indexed by a file
10152 name (which may or may not be case sensitive, depending on the operating
10153 system) and returning a string list. For example:
10158 for Switches ("main1.adb") use ("-O2");
10159 for Switches ("main2.adb") use ("-g");
10165 For the @code{Builder} package, the file names should designate source files
10166 for main subprograms. For the @code{Binder} and @code{Linker} packages, the
10167 file names should designate @file{ALI} or source files for main subprograms.
10168 In each case just the file name (without explicit extension) is acceptable.
10170 For each tool used in a program build (@command{gnatmake}, the compiler, the
10171 binder, and the linker), its corresponding package @dfn{contributes} a set of
10172 switches for each file on which the tool is invoked, based on the
10173 switch-related attributes defined in the package. In particular, the switches
10174 that each of these packages contributes for a given file @var{f} comprise:
10178 the value of attribute @code{Switches (@var{f})}, if it is specified in the
10179 package for the given file,
10181 otherwise, the value of @code{Default_Switches ("Ada")}, if it is specified in
10186 If neither of these attributes is defined in the package, then the package does
10187 not contribute any switches for the given file.
10189 When @command{gnatmake} is invoked on a file, the switches comprise two sets,
10190 in the following order: those contributed for the file by the @code{Builder}
10191 package; and the switches passed on the command line.
10193 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
10194 the switches passed to the tool comprise three sets, in the following order:
10198 the applicable switches contributed for the file by the @code{Builder} package
10199 in the project file supplied on the command line;
10202 those contributed for the file by the package (in the relevant project file --
10203 see below) corresponding to the tool; and
10206 the applicable switches passed on the command line.
10210 The term @emph{applicable switches} reflects the fact that @command{gnatmake}
10211 switches may or may not be passed to individual tools, depending on the
10214 @command{gnatmake} may invoke the compiler on source files from different
10215 projects. The Project Manager will use the appropriate project file to
10216 determine the @code{Compiler} package for each source file being compiled.
10217 Likewise for the @code{Binder} and @code{Linker} packages.
10219 As an example, consider the following package in a project file:
10224 package Compiler is
10225 for Default_Switches ("Ada") use ("-g");
10226 for Switches ("a.adb") use ("-O1");
10227 for Switches ("b.adb") use ("-O2", "-gnaty");
10234 If @command{gnatmake} is invoked with this project file, and it needs to
10235 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
10236 @file{a.adb} will be compiled with the switch @option{-O1}, @file{b.adb}
10237 with switches @option{-O2} and @option{-gnaty}, and @file{c.adb} with
10240 Another example illustrates the ordering of the switches contributed by
10241 different packages:
10247 for Switches ("main.adb") use ("-g", "-O1", "-f");
10252 package Compiler is
10253 for Switches ("main.adb") use ("-O2");
10260 If you issue the command:
10263 gnatmake -PProj2 -O0 main
10267 then the compiler will be invoked on @file{main.adb} with the following sequence of switches
10273 with the last @option{-O} switch having precedence over the earlier ones;
10274 several other switches (such as @option{-c}) are added implicitly.
10276 The switches @option{-g} and @option{-O1} are contributed by package
10277 @code{Builder}, @option{-O2} is contributed by the package @code{Compiler}
10278 and @option{-O0} comes from the command line.
10280 The @option{-g} switch will also be passed in the invocation of
10281 @command{gnatlink.}
10283 A final example illustrates switch contributions from packages in different
10289 for Source_Files use ("pack.ads", "pack.adb");
10290 package Compiler is
10291 for Default_Switches ("Ada") use ("-gnata");
10299 for Source_Files use ("foo_main.adb", "bar_main.adb");
10301 for Switches ("foo_main.adb") use ("-s", "-g");
10307 -- Ada source file:
10309 procedure Foo_Main is
10317 gnatmake -PProj4 foo_main.adb -cargs -gnato
10321 then the switches passed to the compiler for @file{foo_main.adb} are
10322 @option{-g} (contributed by the package @code{Proj4.Builder}) and
10323 @option{-gnato} (passed on the command line).
10324 When the imported package @code{Pack} is compiled, the switches used are
10325 @option{-g} from @code{Proj4.Builder}, @option{-gnata} (contributed from
10326 package @code{Proj3.Compiler}, and @option{-gnato} from the command line.
10329 @node Project Files and Main Subprograms
10330 @subsubsection Project Files and Main Subprograms
10333 When using a project file, you can invoke @command{gnatmake}
10334 with several main subprograms, by specifying their source files on the command
10335 line. Each of these needs to be an immediate source file of the project.
10338 gnatmake -Pprj main1 main2 main3
10342 When using a project file, you can also invoke @command{gnatmake} without
10343 explicitly specifying any main, and the effect depends on whether you have
10344 defined the @code{Main} attribute. This attribute has a string list value,
10345 where each element in the list is the name of a source file (the file
10346 extension is optional) containing a main subprogram.
10348 If the @code{Main} attribute is defined in a project file as a non-empty
10349 string list and the switch @option{-u} is not used on the command line, then
10350 invoking @command{gnatmake} with this project file but without any main on the
10351 command line is equivalent to invoking @command{gnatmake} with all the file
10352 names in the @code{Main} attribute on the command line.
10358 for Main use ("main1", "main2", "main3");
10364 With this project file, @code{"gnatmake -Pprj"} is equivalent to
10365 @code{"gnatmake -Pprj main1 main2 main3"}.
10367 When the project attribute @code{Main} is not specified, or is specified
10368 as an empty string list, or when the switch @option{-u} is used on the command
10369 line, then invoking @command{gnatmake} with no main on the command line will
10370 result in all immediate sources of the project file being checked, and
10371 potentially recompiled. Depending on the presence of the switch @option{-u},
10372 sources from other project files on which the immediate sources of the main
10373 project file depend are also checked and potentially recompiled. In other
10374 words, the @option{-u} switch is applied to all of the immediate sources of themain project file.
10377 @node The GNAT Driver and Project Files
10378 @subsection The GNAT Driver and Project Files
10381 A number of GNAT tools, other than @command{gnatmake} are project-aware:
10382 @command{gnatbind}, @command{gnatfind}, @command{gnatlink}, @command{gnatls}
10383 and @command{gnatxref}. However, none of these tools can be invoked directly
10384 with a project file switch (@code{-P}). They need to be invoke through the
10385 @command{gnat} driver.
10387 The @command{gnat} driver is a front-end that accepts a number of commands and
10388 call the corresponding tool. It has been designed initially for VMS to convert
10389 VMS style qualifiers to Unix style switches, but it is now available to all
10390 the GNAT supported platforms.
10392 On non VMS platforms, the @command{gnat} driver accepts the following commands
10393 (case insensitive):
10397 BIND to invoke @command{gnatbind}
10399 CHOP to invoke @command{gnatchop}
10401 COMP or COMPILE to invoke the compiler
10403 ELIM to invoke @command{gnatelim}
10405 FIND to invoke @command{gnatfind}
10407 KR or KRUNCH to invoke @command{gnatkr}
10409 LINK to invoke @command{gnatlink}
10411 LS or LIST to invoke @command{gnatls}
10413 MAKE to invoke @command{gnatmake}
10415 NAME to invoke @command{gnatname}
10417 PREP or PREPROCESS to invoke @command{gnatprep}
10419 PSTA or STANDARD to invoke @command{gnatpsta}
10421 STUB to invoke @command{gnatstub}
10423 XREF to invoke @command{gnatxref}
10427 Note that the compiler is invoked using the command @command{gnatmake -f -u}.
10430 Following the command, you may put switches and arguments for the invoked
10434 gnat bind -C main.ali
10440 In addition, for command BIND, FIND, LS or LIST, LINK and XREF, the project
10441 file related switches (@code{-P}, @code{-X} and @code{-vPx}) may be used in
10442 addition to the switches of the invoking tool.
10445 For each of these command, there is possibly a package in the main project that
10446 corresponds to the invoked tool.
10450 package @code{Binder} for command BIND (invoking @code{gnatbind})
10453 package @code{Finder} for command FIND (invoking @code{gnatfind})
10456 package @code{Gnatls} for command LS or LIST (invoking @code{gnatls})
10459 package @code{Linker} for command LINK (invoking @code{gnatlink})
10462 package @code{Cross_Reference} for command XREF (invoking @code{gnatlink})
10467 Package @code{Gnatls} has a unique attribute @code{Switches}, a simple variable
10468 with a string list value. It contains switches for the invocation of
10475 for Switches use ("-a", "-v");
10482 All other packages contains a switch @code{Default_Switches}, an associative
10483 array, indexed by the programming language (case insensitive) and having a
10484 string list value. @code{Default_Switches ("Ada")} contains the switches for
10485 the invocation of the tool corresponding to the package.
10491 for Source_Dirs use ("./**");
10494 for Switches use ("-a", "-v");
10500 for Default_Switches ("Ada") use ("-C", "-e");
10506 for Default_Switches ("Ada") use ("-C");
10512 for Default_Switches ("Ada") use ("-a", "-f");
10517 package Cross_Reference is
10518 for Default_Switches ("Ada") use ("-a", "-f", "-d", "-u");
10519 end Cross_Reference;
10525 With the above project file, commands such as
10528 gnat ls -Pproj main
10529 gnat xref -Pproj main
10530 gnat bind -Pproj main.ali
10534 will set up the environment properly and invoke the tool with the switches
10535 found in the package corresponding to the tool.
10538 @node Glide and Project Files
10539 @subsection Glide and Project Files
10542 Glide will automatically recognize the @file{.gpr} extension for
10543 project files, and will
10544 convert them to its own internal format automatically. However, it
10545 doesn't provide a syntax-oriented editor for modifying these
10547 The project file will be loaded as text when you select the menu item
10548 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
10549 You can edit this text and save the @file{gpr} file;
10550 when you next select this project file in Glide it
10551 will be automatically reloaded.
10555 @node An Extended Example
10556 @section An Extended Example
10559 Suppose that we have two programs, @var{prog1} and @var{prog2}, with the sources
10560 in the respective directories. We would like to build them with a single
10561 @command{gnatmake} command, and we would like to place their object files into
10562 @file{.build} subdirectories of the source directories. Furthermore, we would
10563 like to have to have two separate subdirectories in @file{.build} --
10564 @file{release} and @file{debug} -- which will contain the object files compiled with
10565 different set of compilation flags.
10567 In other words, we have the following structure:
10584 Here are the project files that we need to create in a directory @file{main}
10585 to maintain this structure:
10589 @item We create a @code{Common} project with a package @code{Compiler} that
10590 specifies the compilation switches:
10595 @b{project} Common @b{is}
10597 @b{for} Source_Dirs @b{use} (); -- No source files
10601 @b{type} Build_Type @b{is} ("release", "debug");
10602 Build : Build_Type := External ("BUILD", "debug");
10605 @b{package} Compiler @b{is}
10606 @b{case} Build @b{is}
10607 @b{when} "release" =>
10608 @b{for} Default_Switches ("Ada") @b{use} ("-O2");
10609 @b{when} "debug" =>
10610 @b{for} Default_Switches ("Ada") @b{use} ("-g");
10618 @item We create separate projects for the two programs:
10625 @b{project} Prog1 @b{is}
10627 @b{for} Source_Dirs @b{use} ("prog1");
10628 @b{for} Object_Dir @b{use} "prog1/.build/" & Common.Build;
10630 @b{package} Compiler @b{renames} Common.Compiler;
10641 @b{project} Prog2 @b{is}
10643 @b{for} Source_Dirs @b{use} ("prog2");
10644 @b{for} Object_Dir @b{use} "prog2/.build/" & Common.Build;
10646 @b{package} Compiler @b{renames} Common.Compiler;
10652 @item We create a wrapping project @var{Main}:
10661 @b{project} Main @b{is}
10663 @b{package} Compiler @b{renames} Common.Compiler;
10669 @item Finally we need to create a dummy procedure that @code{with}s (either
10670 explicitly or implicitly) all the sources of our two programs.
10675 Now we can build the programs using the command
10678 gnatmake -Pmain dummy
10682 for the Debug mode, or
10685 gnatmake -Pmain -XBUILD=release
10689 for the Release mode.
10692 @c ********************************
10693 @c * Project File Complete Syntax *
10694 @c ********************************
10696 @node Project File Complete Syntax
10697 @section Project File Complete Syntax
10701 context_clause project_declaration
10707 @b{with} literal_string @{ , literal_string @} ;
10709 project_declaration ::=
10710 @b{project} <project_>simple_name [ @b{extends} literal_string ] @b{is}
10711 @{declarative_item@}
10712 @b{end} <project_>simple_name;
10714 declarative_item ::=
10715 package_declaration |
10716 typed_string_declaration |
10717 other_declarative_item
10719 package_declaration ::=
10720 @b{package} <package_>simple_name package_completion
10722 package_completion ::=
10723 package_body | package_renaming
10727 @{other_declarative_item@}
10728 @b{end} <package_>simple_name ;
10730 package_renaming ::==
10731 @b{renames} <project_>simple_name.<package_>simple_name ;
10733 typed_string_declaration ::=
10734 @b{type} <typed_string_>_simple_name @b{is}
10735 ( literal_string @{, literal_string@} );
10737 other_declarative_item ::=
10738 attribute_declaration |
10739 typed_variable_declaration |
10740 variable_declaration |
10743 attribute_declaration ::=
10744 @b{for} attribute @b{use} expression ;
10747 <simple_attribute_>simple_name |
10748 <associative_array_attribute_>simple_name ( literal_string )
10750 typed_variable_declaration ::=
10751 <typed_variable_>simple_name : <typed_string_>name := string_expression ;
10753 variable_declaration ::=
10754 <variable_>simple_name := expression;
10764 attribute_reference
10770 ( <string_>expression @{ , <string_>expression @} )
10773 @b{external} ( literal_string [, literal_string] )
10775 attribute_reference ::=
10776 attribute_parent ' <simple_attribute_>simple_name [ ( literal_string ) ]
10778 attribute_parent ::=
10780 <project_or_package>simple_name |
10781 <project_>simple_name . <package_>simple_name
10783 case_construction ::=
10784 @b{case} <typed_variable_>name @b{is}
10789 @b{when} discrete_choice_list => @{case_construction | attribute_declaration@}
10791 discrete_choice_list ::=
10792 literal_string @{| literal_string@}
10795 simple_name @{. simple_name@}
10798 identifier (same as Ada)
10803 @node Elaboration Order Handling in GNAT
10804 @chapter Elaboration Order Handling in GNAT
10805 @cindex Order of elaboration
10806 @cindex Elaboration control
10809 * Elaboration Code in Ada 95::
10810 * Checking the Elaboration Order in Ada 95::
10811 * Controlling the Elaboration Order in Ada 95::
10812 * Controlling Elaboration in GNAT - Internal Calls::
10813 * Controlling Elaboration in GNAT - External Calls::
10814 * Default Behavior in GNAT - Ensuring Safety::
10815 * Elaboration Issues for Library Tasks::
10816 * Mixing Elaboration Models::
10817 * What to Do If the Default Elaboration Behavior Fails::
10818 * Elaboration for Access-to-Subprogram Values::
10819 * Summary of Procedures for Elaboration Control::
10820 * Other Elaboration Order Considerations::
10824 This chapter describes the handling of elaboration code in Ada 95 and
10825 in GNAT, and discusses how the order of elaboration of program units can
10826 be controlled in GNAT, either automatically or with explicit programming
10829 @node Elaboration Code in Ada 95
10830 @section Elaboration Code in Ada 95
10833 Ada 95 provides rather general mechanisms for executing code at elaboration
10834 time, that is to say before the main program starts executing. Such code arises
10838 @item Initializers for variables.
10839 Variables declared at the library level, in package specs or bodies, can
10840 require initialization that is performed at elaboration time, as in:
10843 Sqrt_Half : Float := Sqrt (0.5);
10847 @item Package initialization code
10848 Code in a @code{BEGIN-END} section at the outer level of a package body is
10849 executed as part of the package body elaboration code.
10851 @item Library level task allocators
10852 Tasks that are declared using task allocators at the library level
10853 start executing immediately and hence can execute at elaboration time.
10857 Subprogram calls are possible in any of these contexts, which means that
10858 any arbitrary part of the program may be executed as part of the elaboration
10859 code. It is even possible to write a program which does all its work at
10860 elaboration time, with a null main program, although stylistically this
10861 would usually be considered an inappropriate way to structure
10864 An important concern arises in the context of elaboration code:
10865 we have to be sure that it is executed in an appropriate order. What we
10866 have is a series of elaboration code sections, potentially one section
10867 for each unit in the program. It is important that these execute
10868 in the correct order. Correctness here means that, taking the above
10869 example of the declaration of @code{Sqrt_Half},
10870 if some other piece of
10871 elaboration code references @code{Sqrt_Half},
10872 then it must run after the
10873 section of elaboration code that contains the declaration of
10876 There would never be any order of elaboration problem if we made a rule
10877 that whenever you @code{with} a unit, you must elaborate both the spec and body
10878 of that unit before elaborating the unit doing the @code{with}'ing:
10884 @b{package} Unit_2 @b{is} ...
10890 would require that both the body and spec of @code{Unit_1} be elaborated
10891 before the spec of @code{Unit_2}. However, a rule like that would be far too
10892 restrictive. In particular, it would make it impossible to have routines
10893 in separate packages that were mutually recursive.
10895 You might think that a clever enough compiler could look at the actual
10896 elaboration code and determine an appropriate correct order of elaboration,
10897 but in the general case, this is not possible. Consider the following
10900 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
10902 the variable @code{Sqrt_1}, which is declared in the elaboration code
10903 of the body of @code{Unit_1}:
10907 Sqrt_1 : Float := Sqrt (0.1);
10912 The elaboration code of the body of @code{Unit_1} also contains:
10917 @b{if} expression_1 = 1 @b{then}
10918 Q := Unit_2.Func_2;
10925 @code{Unit_2} is exactly parallel,
10926 it has a procedure @code{Func_2} that references
10927 the variable @code{Sqrt_2}, which is declared in the elaboration code of
10928 the body @code{Unit_2}:
10932 Sqrt_2 : Float := Sqrt (0.1);
10937 The elaboration code of the body of @code{Unit_2} also contains:
10942 @b{if} expression_2 = 2 @b{then}
10943 Q := Unit_1.Func_1;
10950 Now the question is, which of the following orders of elaboration is
10975 If you carefully analyze the flow here, you will see that you cannot tell
10976 at compile time the answer to this question.
10977 If @code{expression_1} is not equal to 1,
10978 and @code{expression_2} is not equal to 2,
10979 then either order is acceptable, because neither of the function calls is
10980 executed. If both tests evaluate to true, then neither order is acceptable
10981 and in fact there is no correct order.
10983 If one of the two expressions is true, and the other is false, then one
10984 of the above orders is correct, and the other is incorrect. For example,
10985 if @code{expression_1} = 1 and @code{expression_2} /= 2,
10986 then the call to @code{Func_2}
10987 will occur, but not the call to @code{Func_1.}
10988 This means that it is essential
10989 to elaborate the body of @code{Unit_1} before
10990 the body of @code{Unit_2}, so the first
10991 order of elaboration is correct and the second is wrong.
10993 By making @code{expression_1} and @code{expression_2}
10994 depend on input data, or perhaps
10995 the time of day, we can make it impossible for the compiler or binder
10996 to figure out which of these expressions will be true, and hence it
10997 is impossible to guarantee a safe order of elaboration at run time.
10999 @node Checking the Elaboration Order in Ada 95
11000 @section Checking the Elaboration Order in Ada 95
11003 In some languages that involve the same kind of elaboration problems,
11004 e.g. Java and C++, the programmer is expected to worry about these
11005 ordering problems himself, and it is common to
11006 write a program in which an incorrect elaboration order gives
11007 surprising results, because it references variables before they
11009 Ada 95 is designed to be a safe language, and a programmer-beware approach is
11010 clearly not sufficient. Consequently, the language provides three lines
11014 @item Standard rules
11015 Some standard rules restrict the possible choice of elaboration
11016 order. In particular, if you @code{with} a unit, then its spec is always
11017 elaborated before the unit doing the @code{with}. Similarly, a parent
11018 spec is always elaborated before the child spec, and finally
11019 a spec is always elaborated before its corresponding body.
11021 @item Dynamic elaboration checks
11022 @cindex Elaboration checks
11023 @cindex Checks, elaboration
11024 Dynamic checks are made at run time, so that if some entity is accessed
11025 before it is elaborated (typically by means of a subprogram call)
11026 then the exception (@code{Program_Error}) is raised.
11028 @item Elaboration control
11029 Facilities are provided for the programmer to specify the desired order
11033 Let's look at these facilities in more detail. First, the rules for
11034 dynamic checking. One possible rule would be simply to say that the
11035 exception is raised if you access a variable which has not yet been
11036 elaborated. The trouble with this approach is that it could require
11037 expensive checks on every variable reference. Instead Ada 95 has two
11038 rules which are a little more restrictive, but easier to check, and
11042 @item Restrictions on calls
11043 A subprogram can only be called at elaboration time if its body
11044 has been elaborated. The rules for elaboration given above guarantee
11045 that the spec of the subprogram has been elaborated before the
11046 call, but not the body. If this rule is violated, then the
11047 exception @code{Program_Error} is raised.
11049 @item Restrictions on instantiations
11050 A generic unit can only be instantiated if the body of the generic
11051 unit has been elaborated. Again, the rules for elaboration given above
11052 guarantee that the spec of the generic unit has been elaborated
11053 before the instantiation, but not the body. If this rule is
11054 violated, then the exception @code{Program_Error} is raised.
11058 The idea is that if the body has been elaborated, then any variables
11059 it references must have been elaborated; by checking for the body being
11060 elaborated we guarantee that none of its references causes any
11061 trouble. As we noted above, this is a little too restrictive, because a
11062 subprogram that has no non-local references in its body may in fact be safe
11063 to call. However, it really would be unsafe to rely on this, because
11064 it would mean that the caller was aware of details of the implementation
11065 in the body. This goes against the basic tenets of Ada.
11067 A plausible implementation can be described as follows.
11068 A Boolean variable is associated with each subprogram
11069 and each generic unit. This variable is initialized to False, and is set to
11070 True at the point body is elaborated. Every call or instantiation checks the
11071 variable, and raises @code{Program_Error} if the variable is False.
11073 Note that one might think that it would be good enough to have one Boolean
11074 variable for each package, but that would not deal with cases of trying
11075 to call a body in the same package as the call
11076 that has not been elaborated yet.
11077 Of course a compiler may be able to do enough analysis to optimize away
11078 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
11079 does such optimizations, but still the easiest conceptual model is to
11080 think of there being one variable per subprogram.
11082 @node Controlling the Elaboration Order in Ada 95
11083 @section Controlling the Elaboration Order in Ada 95
11086 In the previous section we discussed the rules in Ada 95 which ensure
11087 that @code{Program_Error} is raised if an incorrect elaboration order is
11088 chosen. This prevents erroneous executions, but we need mechanisms to
11089 specify a correct execution and avoid the exception altogether.
11090 To achieve this, Ada 95 provides a number of features for controlling
11091 the order of elaboration. We discuss these features in this section.
11093 First, there are several ways of indicating to the compiler that a given
11094 unit has no elaboration problems:
11097 @item packages that do not require a body
11098 In Ada 95, a library package that does not require a body does not permit
11099 a body. This means that if we have a such a package, as in:
11104 @b{package} Definitions @b{is}
11106 @b{type} m @b{is new} integer;
11107 @b{package} Subp @b{is}
11108 @b{type} a @b{is array} (1 .. 10) @b{of} m;
11109 @b{type} b @b{is array} (1 .. 20) @b{of} m;
11111 @b{end} Definitions;
11117 A package that @code{with}'s @code{Definitions} may safely instantiate
11118 @code{Definitions.Subp} because the compiler can determine that there
11119 definitely is no package body to worry about in this case
11122 @cindex pragma Pure
11124 Places sufficient restrictions on a unit to guarantee that
11125 no call to any subprogram in the unit can result in an
11126 elaboration problem. This means that the compiler does not need
11127 to worry about the point of elaboration of such units, and in
11128 particular, does not need to check any calls to any subprograms
11131 @item pragma Preelaborate
11132 @findex Preelaborate
11133 @cindex pragma Preelaborate
11134 This pragma places slightly less stringent restrictions on a unit than
11136 but these restrictions are still sufficient to ensure that there
11137 are no elaboration problems with any calls to the unit.
11139 @item pragma Elaborate_Body
11140 @findex Elaborate_Body
11141 @cindex pragma Elaborate_Body
11142 This pragma requires that the body of a unit be elaborated immediately
11143 after its spec. Suppose a unit @code{A} has such a pragma,
11144 and unit @code{B} does
11145 a @code{with} of unit @code{A}. Recall that the standard rules require
11146 the spec of unit @code{A}
11147 to be elaborated before the @code{with}'ing unit; given the pragma in
11148 @code{A}, we also know that the body of @code{A}
11149 will be elaborated before @code{B}, so
11150 that calls to @code{A} are safe and do not need a check.
11155 unlike pragma @code{Pure} and pragma @code{Preelaborate},
11157 @code{Elaborate_Body} does not guarantee that the program is
11158 free of elaboration problems, because it may not be possible
11159 to satisfy the requested elaboration order.
11160 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
11162 marks @code{Unit_1} as @code{Elaborate_Body},
11163 and not @code{Unit_2,} then the order of
11164 elaboration will be:
11176 Now that means that the call to @code{Func_1} in @code{Unit_2}
11177 need not be checked,
11178 it must be safe. But the call to @code{Func_2} in
11179 @code{Unit_1} may still fail if
11180 @code{Expression_1} is equal to 1,
11181 and the programmer must still take
11182 responsibility for this not being the case.
11184 If all units carry a pragma @code{Elaborate_Body}, then all problems are
11185 eliminated, except for calls entirely within a body, which are
11186 in any case fully under programmer control. However, using the pragma
11187 everywhere is not always possible.
11188 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
11189 we marked both of them as having pragma @code{Elaborate_Body}, then
11190 clearly there would be no possible elaboration order.
11192 The above pragmas allow a server to guarantee safe use by clients, and
11193 clearly this is the preferable approach. Consequently a good rule in
11194 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
11195 and if this is not possible,
11196 mark them as @code{Elaborate_Body} if possible.
11197 As we have seen, there are situations where neither of these
11198 three pragmas can be used.
11199 So we also provide methods for clients to control the
11200 order of elaboration of the servers on which they depend:
11203 @item pragma Elaborate (unit)
11205 @cindex pragma Elaborate
11206 This pragma is placed in the context clause, after a @code{with} clause,
11207 and it requires that the body of the named unit be elaborated before
11208 the unit in which the pragma occurs. The idea is to use this pragma
11209 if the current unit calls at elaboration time, directly or indirectly,
11210 some subprogram in the named unit.
11212 @item pragma Elaborate_All (unit)
11213 @findex Elaborate_All
11214 @cindex pragma Elaborate_All
11215 This is a stronger version of the Elaborate pragma. Consider the
11219 Unit A @code{with}'s unit B and calls B.Func in elab code
11220 Unit B @code{with}'s unit C, and B.Func calls C.Func
11224 Now if we put a pragma @code{Elaborate (B)}
11225 in unit @code{A}, this ensures that the
11226 body of @code{B} is elaborated before the call, but not the
11227 body of @code{C}, so
11228 the call to @code{C.Func} could still cause @code{Program_Error} to
11231 The effect of a pragma @code{Elaborate_All} is stronger, it requires
11232 not only that the body of the named unit be elaborated before the
11233 unit doing the @code{with}, but also the bodies of all units that the
11234 named unit uses, following @code{with} links transitively. For example,
11235 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
11237 not only that the body of @code{B} be elaborated before @code{A},
11239 body of @code{C}, because @code{B} @code{with}'s @code{C}.
11243 We are now in a position to give a usage rule in Ada 95 for avoiding
11244 elaboration problems, at least if dynamic dispatching and access to
11245 subprogram values are not used. We will handle these cases separately
11248 The rule is simple. If a unit has elaboration code that can directly or
11249 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
11250 a generic unit in a @code{with}'ed unit,
11251 then if the @code{with}'ed unit does not have
11252 pragma @code{Pure} or @code{Preelaborate}, then the client should have
11253 a pragma @code{Elaborate_All}
11254 for the @code{with}'ed unit. By following this rule a client is
11255 assured that calls can be made without risk of an exception.
11256 If this rule is not followed, then a program may be in one of four
11260 @item No order exists
11261 No order of elaboration exists which follows the rules, taking into
11262 account any @code{Elaborate}, @code{Elaborate_All},
11263 or @code{Elaborate_Body} pragmas. In
11264 this case, an Ada 95 compiler must diagnose the situation at bind
11265 time, and refuse to build an executable program.
11267 @item One or more orders exist, all incorrect
11268 One or more acceptable elaboration orders exists, and all of them
11269 generate an elaboration order problem. In this case, the binder
11270 can build an executable program, but @code{Program_Error} will be raised
11271 when the program is run.
11273 @item Several orders exist, some right, some incorrect
11274 One or more acceptable elaboration orders exists, and some of them
11275 work, and some do not. The programmer has not controlled
11276 the order of elaboration, so the binder may or may not pick one of
11277 the correct orders, and the program may or may not raise an
11278 exception when it is run. This is the worst case, because it means
11279 that the program may fail when moved to another compiler, or even
11280 another version of the same compiler.
11282 @item One or more orders exists, all correct
11283 One ore more acceptable elaboration orders exist, and all of them
11284 work. In this case the program runs successfully. This state of
11285 affairs can be guaranteed by following the rule we gave above, but
11286 may be true even if the rule is not followed.
11290 Note that one additional advantage of following our Elaborate_All rule
11291 is that the program continues to stay in the ideal (all orders OK) state
11292 even if maintenance
11293 changes some bodies of some subprograms. Conversely, if a program that does
11294 not follow this rule happens to be safe at some point, this state of affairs
11295 may deteriorate silently as a result of maintenance changes.
11297 You may have noticed that the above discussion did not mention
11298 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
11299 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
11300 code in the body makes calls to some other unit, so it is still necessary
11301 to use @code{Elaborate_All} on such units.
11303 @node Controlling Elaboration in GNAT - Internal Calls
11304 @section Controlling Elaboration in GNAT - Internal Calls
11307 In the case of internal calls, i.e. calls within a single package, the
11308 programmer has full control over the order of elaboration, and it is up
11309 to the programmer to elaborate declarations in an appropriate order. For
11315 @b{function} One @b{return} Float;
11319 @b{function} One @b{return} Float @b{is}
11328 will obviously raise @code{Program_Error} at run time, because function
11329 One will be called before its body is elaborated. In this case GNAT will
11330 generate a warning that the call will raise @code{Program_Error}:
11336 2. function One return Float;
11338 4. Q : Float := One;
11340 >>> warning: cannot call "One" before body is elaborated
11341 >>> warning: Program_Error will be raised at run time
11344 6. function One return Float is
11357 Note that in this particular case, it is likely that the call is safe, because
11358 the function @code{One} does not access any global variables.
11359 Nevertheless in Ada 95, we do not want the validity of the check to depend on
11360 the contents of the body (think about the separate compilation case), so this
11361 is still wrong, as we discussed in the previous sections.
11363 The error is easily corrected by rearranging the declarations so that the
11364 body of One appears before the declaration containing the call
11365 (note that in Ada 95,
11366 declarations can appear in any order, so there is no restriction that
11367 would prevent this reordering, and if we write:
11372 @b{function} One @b{return} Float;
11374 @b{function} One @b{return} Float @b{is}
11385 then all is well, no warning is generated, and no
11386 @code{Program_Error} exception
11388 Things are more complicated when a chain of subprograms is executed:
11393 @b{function} A @b{return} Integer;
11394 @b{function} B @b{return} Integer;
11395 @b{function} C @b{return} Integer;
11397 @b{function} B @b{return} Integer @b{is begin return} A; @b{end};
11398 @b{function} C @b{return} Integer @b{is begin return} B; @b{end};
11402 @b{function} A @b{return} Integer @b{is begin return} 1; @b{end};
11408 Now the call to @code{C}
11409 at elaboration time in the declaration of @code{X} is correct, because
11410 the body of @code{C} is already elaborated,
11411 and the call to @code{B} within the body of
11412 @code{C} is correct, but the call
11413 to @code{A} within the body of @code{B} is incorrect, because the body
11414 of @code{A} has not been elaborated, so @code{Program_Error}
11415 will be raised on the call to @code{A}.
11416 In this case GNAT will generate a
11417 warning that @code{Program_Error} may be
11418 raised at the point of the call. Let's look at the warning:
11424 2. function A return Integer;
11425 3. function B return Integer;
11426 4. function C return Integer;
11428 6. function B return Integer is begin return A; end;
11430 >>> warning: call to "A" before body is elaborated may
11431 raise Program_Error
11432 >>> warning: "B" called at line 7
11433 >>> warning: "C" called at line 9
11435 7. function C return Integer is begin return B; end;
11437 9. X : Integer := C;
11439 11. function A return Integer is begin return 1; end;
11449 Note that the message here says "may raise", instead of the direct case,
11450 where the message says "will be raised". That's because whether
11452 actually called depends in general on run-time flow of control.
11453 For example, if the body of @code{B} said
11458 @b{function} B @b{return} Integer @b{is}
11460 @b{if} some-condition-depending-on-input-data @b{then}
11471 then we could not know until run time whether the incorrect call to A would
11472 actually occur, so @code{Program_Error} might
11473 or might not be raised. It is possible for a compiler to
11474 do a better job of analyzing bodies, to
11475 determine whether or not @code{Program_Error}
11476 might be raised, but it certainly
11477 couldn't do a perfect job (that would require solving the halting problem
11478 and is provably impossible), and because this is a warning anyway, it does
11479 not seem worth the effort to do the analysis. Cases in which it
11480 would be relevant are rare.
11482 In practice, warnings of either of the forms given
11483 above will usually correspond to
11484 real errors, and should be examined carefully and eliminated.
11485 In the rare case where a warning is bogus, it can be suppressed by any of
11486 the following methods:
11490 Compile with the @option{-gnatws} switch set
11493 Suppress @code{Elaboration_Checks} for the called subprogram
11496 Use pragma @code{Warnings_Off} to turn warnings off for the call
11500 For the internal elaboration check case,
11501 GNAT by default generates the
11502 necessary run-time checks to ensure
11503 that @code{Program_Error} is raised if any
11504 call fails an elaboration check. Of course this can only happen if a
11505 warning has been issued as described above. The use of pragma
11506 @code{Suppress (Elaboration_Checks)} may (but is not guaranteed to) suppress
11507 some of these checks, meaning that it may be possible (but is not
11508 guaranteed) for a program to be able to call a subprogram whose body
11509 is not yet elaborated, without raising a @code{Program_Error} exception.
11511 @node Controlling Elaboration in GNAT - External Calls
11512 @section Controlling Elaboration in GNAT - External Calls
11515 The previous section discussed the case in which the execution of a
11516 particular thread of elaboration code occurred entirely within a
11517 single unit. This is the easy case to handle, because a programmer
11518 has direct and total control over the order of elaboration, and
11519 furthermore, checks need only be generated in cases which are rare
11520 and which the compiler can easily detect.
11521 The situation is more complex when separate compilation is taken into account.
11522 Consider the following:
11527 @b{package} Math @b{is}
11528 @b{function} Sqrt (Arg : Float) @b{return} Float;
11531 @b{package body} Math @b{is}
11532 @b{function} Sqrt (Arg : Float) @b{return} Float @b{is}
11540 @b{package} Stuff @b{is}
11541 X : Float := Math.Sqrt (0.5);
11545 @b{procedure} Main @b{is}
11554 where @code{Main} is the main program. When this program is executed, the
11555 elaboration code must first be executed, and one of the jobs of the
11556 binder is to determine the order in which the units of a program are
11557 to be elaborated. In this case we have four units: the spec and body
11559 the spec of @code{Stuff} and the body of @code{Main}).
11560 In what order should the four separate sections of elaboration code
11563 There are some restrictions in the order of elaboration that the binder
11564 can choose. In particular, if unit U has a @code{with}
11565 for a package @code{X}, then you
11566 are assured that the spec of @code{X}
11567 is elaborated before U , but you are
11568 not assured that the body of @code{X}
11569 is elaborated before U.
11570 This means that in the above case, the binder is allowed to choose the
11581 but that's not good, because now the call to @code{Math.Sqrt}
11582 that happens during
11583 the elaboration of the @code{Stuff}
11584 spec happens before the body of @code{Math.Sqrt} is
11585 elaborated, and hence causes @code{Program_Error} exception to be raised.
11586 At first glance, one might say that the binder is misbehaving, because
11587 obviously you want to elaborate the body of something you @code{with}
11589 that is not a general rule that can be followed in all cases. Consider
11594 @b{package} X @b{is} ...
11596 @b{package} Y @b{is} ...
11599 @b{package body} Y @b{is} ...
11602 @b{package body} X @b{is} ...
11608 This is a common arrangement, and, apart from the order of elaboration
11609 problems that might arise in connection with elaboration code, this works fine.
11610 A rule that says that you must first elaborate the body of anything you
11611 @code{with} cannot work in this case:
11612 the body of @code{X} @code{with}'s @code{Y},
11613 which means you would have to
11614 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
11616 you have to elaborate the body of @code{X} first, but ... and we have a
11617 loop that cannot be broken.
11619 It is true that the binder can in many cases guess an order of elaboration
11620 that is unlikely to cause a @code{Program_Error}
11621 exception to be raised, and it tries to do so (in the
11622 above example of @code{Math/Stuff/Spec}, the GNAT binder will
11624 elaborate the body of @code{Math} right after its spec, so all will be well).
11626 However, a program that blindly relies on the binder to be helpful can
11627 get into trouble, as we discussed in the previous sections, so
11629 provides a number of facilities for assisting the programmer in
11630 developing programs that are robust with respect to elaboration order.
11632 @node Default Behavior in GNAT - Ensuring Safety
11633 @section Default Behavior in GNAT - Ensuring Safety
11636 The default behavior in GNAT ensures elaboration safety. In its
11637 default mode GNAT implements the
11638 rule we previously described as the right approach. Let's restate it:
11642 @emph{If a unit has elaboration code that can directly or indirectly make a
11643 call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit
11644 in a @code{with}'ed unit, then if the @code{with}'ed unit
11645 does not have pragma @code{Pure} or
11646 @code{Preelaborate}, then the client should have an
11647 @code{Elaborate_All} for the @code{with}'ed unit.}
11651 By following this rule a client
11652 is assured that calls and instantiations can be made without risk of an exception.
11654 In this mode GNAT traces all calls that are potentially made from
11655 elaboration code, and puts in any missing implicit @code{Elaborate_All}
11657 The advantage of this approach is that no elaboration problems
11658 are possible if the binder can find an elaboration order that is
11659 consistent with these implicit @code{Elaborate_All} pragmas. The
11660 disadvantage of this approach is that no such order may exist.
11662 If the binder does not generate any diagnostics, then it means that it
11663 has found an elaboration order that is guaranteed to be safe. However,
11664 the binder may still be relying on implicitly generated
11665 @code{Elaborate_All} pragmas so portability to other compilers than
11666 GNAT is not guaranteed.
11668 If it is important to guarantee portability, then the compilations should
11671 (warn on elaboration problems) switch. This will cause warning messages
11672 to be generated indicating the missing @code{Elaborate_All} pragmas.
11673 Consider the following source program:
11679 @b{package} j @b{is}
11680 m : integer := k.r;
11687 where it is clear that there
11688 should be a pragma @code{Elaborate_All}
11689 for unit @code{k}. An implicit pragma will be generated, and it is
11690 likely that the binder will be able to honor it. However,
11691 it is safer to include the pragma explicitly in the source. If this
11692 unit is compiled with the
11694 switch, then the compiler outputs a warning:
11701 3. m : integer := k.r;
11703 >>> warning: call to "r" may raise Program_Error
11704 >>> warning: missing pragma Elaborate_All for "k"
11712 and these warnings can be used as a guide for supplying manually
11713 the missing pragmas.
11715 This default mode is more restrictive than the Ada Reference
11716 Manual, and it is possible to construct programs which will compile
11717 using the dynamic model described there, but will run into a
11718 circularity using the safer static model we have described.
11720 Of course any Ada compiler must be able to operate in a mode
11721 consistent with the requirements of the Ada Reference Manual,
11722 and in particular must have the capability of implementing the
11723 standard dynamic model of elaboration with run-time checks.
11725 In GNAT, this standard mode can be achieved either by the use of
11726 the @option{-gnatE} switch on the compiler (@code{gcc} or @code{gnatmake})
11727 command, or by the use of the configuration pragma:
11730 pragma Elaboration_Checks (RM);
11734 Either approach will cause the unit affected to be compiled using the
11735 standard dynamic run-time elaboration checks described in the Ada
11736 Reference Manual. The static model is generally preferable, since it
11737 is clearly safer to rely on compile and link time checks rather than
11738 run-time checks. However, in the case of legacy code, it may be
11739 difficult to meet the requirements of the static model. This
11740 issue is further discussed in
11741 @ref{What to Do If the Default Elaboration Behavior Fails}.
11743 Note that the static model provides a strict subset of the allowed
11744 behavior and programs of the Ada Reference Manual, so if you do
11745 adhere to the static model and no circularities exist,
11746 then you are assured that your program will
11747 work using the dynamic model.
11749 @node Elaboration Issues for Library Tasks
11750 @section Elaboration Issues for Library Tasks
11751 @cindex Library tasks, elaboration issues
11752 @cindex Elaboration of library tasks
11755 In this section we examine special elaboration issues that arise for
11756 programs that declare library level tasks.
11758 Generally the model of execution of an Ada program is that all units are
11759 elaborated, and then execution of the program starts. However, the
11760 declaration of library tasks definitely does not fit this model. The
11761 reason for this is that library tasks start as soon as they are declared
11762 (more precisely, as soon as the statement part of the enclosing package
11763 body is reached), that is to say before elaboration
11764 of the program is complete. This means that if such a task calls a
11765 subprogram, or an entry in another task, the callee may or may not be
11766 elaborated yet, and in the standard
11767 Reference Manual model of dynamic elaboration checks, you can even
11768 get timing dependent Program_Error exceptions, since there can be
11769 a race between the elaboration code and the task code.
11771 The static model of elaboration in GNAT seeks to avoid all such
11772 dynamic behavior, by being conservative, and the conservative
11773 approach in this particular case is to assume that all the code
11774 in a task body is potentially executed at elaboration time if
11775 a task is declared at the library level.
11777 This can definitely result in unexpected circularities. Consider
11778 the following example
11786 type My_Int is new Integer;
11788 function Ident (M : My_Int) return My_Int;
11792 package body Decls is
11793 task body Lib_Task is
11799 function Ident (M : My_Int) return My_Int is
11807 procedure Put_Val (Arg : Decls.My_Int);
11811 package body Utils is
11812 procedure Put_Val (Arg : Decls.My_Int) is
11814 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
11821 Decls.Lib_Task.Start;
11826 If the above example is compiled in the default static elaboration
11827 mode, then a circularity occurs. The circularity comes from the call
11828 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
11829 this call occurs in elaboration code, we need an implicit pragma
11830 @code{Elaborate_All} for @code{Utils}. This means that not only must
11831 the spec and body of @code{Utils} be elaborated before the body
11832 of @code{Decls}, but also the spec and body of any unit that is
11833 @code{with'ed} by the body of @code{Utils} must also be elaborated before
11834 the body of @code{Decls}. This is the transitive implication of
11835 pragma @code{Elaborate_All} and it makes sense, because in general
11836 the body of @code{Put_Val} might have a call to something in a
11837 @code{with'ed} unit.
11839 In this case, the body of Utils (actually its spec) @code{with's}
11840 @code{Decls}. Unfortunately this means that the body of @code{Decls}
11841 must be elaborated before itself, in case there is a call from the
11842 body of @code{Utils}.
11844 Here is the exact chain of events we are worrying about:
11848 In the body of @code{Decls} a call is made from within the body of a library
11849 task to a subprogram in the package @code{Utils}. Since this call may
11850 occur at elaboration time (given that the task is activated at elaboration
11851 time), we have to assume the worst, i.e. that the
11852 call does happen at elaboration time.
11855 This means that the body and spec of @code{Util} must be elaborated before
11856 the body of @code{Decls} so that this call does not cause an access before
11860 Within the body of @code{Util}, specifically within the body of
11861 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
11865 One such @code{with}'ed package is package @code{Decls}, so there
11866 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
11867 In fact there is such a call in this example, but we would have to
11868 assume that there was such a call even if it were not there, since
11869 we are not supposed to write the body of @code{Decls} knowing what
11870 is in the body of @code{Utils}; certainly in the case of the
11871 static elaboration model, the compiler does not know what is in
11872 other bodies and must assume the worst.
11875 This means that the spec and body of @code{Decls} must also be
11876 elaborated before we elaborate the unit containing the call, but
11877 that unit is @code{Decls}! This means that the body of @code{Decls}
11878 must be elaborated before itself, and that's a circularity.
11882 Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in
11883 the body of @code{Decls} you will get a true Ada Reference Manual
11884 circularity that makes the program illegal.
11886 In practice, we have found that problems with the static model of
11887 elaboration in existing code often arise from library tasks, so
11888 we must address this particular situation.
11890 Note that if we compile and run the program above, using the dynamic model of
11891 elaboration (that is to say use the @option{-gnatE} switch),
11892 then it compiles, binds,
11893 links, and runs, printing the expected result of 2. Therefore in some sense
11894 the circularity here is only apparent, and we need to capture
11895 the properties of this program that distinguish it from other library-level
11896 tasks that have real elaboration problems.
11898 We have four possible answers to this question:
11903 Use the dynamic model of elaboration.
11905 If we use the @option{-gnatE} switch, then as noted above, the program works.
11906 Why is this? If we examine the task body, it is apparent that the task cannot
11908 @code{accept} statement until after elaboration has been completed, because
11909 the corresponding entry call comes from the main program, not earlier.
11910 This is why the dynamic model works here. But that's really giving
11911 up on a precise analysis, and we prefer to take this approach only if we cannot
11913 problem in any other manner. So let us examine two ways to reorganize
11914 the program to avoid the potential elaboration problem.
11917 Split library tasks into separate packages.
11919 Write separate packages, so that library tasks are isolated from
11920 other declarations as much as possible. Let us look at a variation on
11931 package body Decls1 is
11932 task body Lib_Task is
11940 type My_Int is new Integer;
11941 function Ident (M : My_Int) return My_Int;
11945 package body Decls2 is
11946 function Ident (M : My_Int) return My_Int is
11954 procedure Put_Val (Arg : Decls2.My_Int);
11958 package body Utils is
11959 procedure Put_Val (Arg : Decls2.My_Int) is
11961 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
11968 Decls1.Lib_Task.Start;
11973 All we have done is to split @code{Decls} into two packages, one
11974 containing the library task, and one containing everything else. Now
11975 there is no cycle, and the program compiles, binds, links and executes
11976 using the default static model of elaboration.
11979 Declare separate task types.
11981 A significant part of the problem arises because of the use of the
11982 single task declaration form. This means that the elaboration of
11983 the task type, and the elaboration of the task itself (i.e. the
11984 creation of the task) happen at the same time. A good rule
11985 of style in Ada 95 is to always create explicit task types. By
11986 following the additional step of placing task objects in separate
11987 packages from the task type declaration, many elaboration problems
11988 are avoided. Here is another modified example of the example program:
11992 task type Lib_Task_Type is
11996 type My_Int is new Integer;
11998 function Ident (M : My_Int) return My_Int;
12002 package body Decls is
12003 task body Lib_Task_Type is
12009 function Ident (M : My_Int) return My_Int is
12017 procedure Put_Val (Arg : Decls.My_Int);
12021 package body Utils is
12022 procedure Put_Val (Arg : Decls.My_Int) is
12024 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
12030 Lib_Task : Decls.Lib_Task_Type;
12036 Declst.Lib_Task.Start;
12041 What we have done here is to replace the @code{task} declaration in
12042 package @code{Decls} with a @code{task type} declaration. Then we
12043 introduce a separate package @code{Declst} to contain the actual
12044 task object. This separates the elaboration issues for
12045 the @code{task type}
12046 declaration, which causes no trouble, from the elaboration issues
12047 of the task object, which is also unproblematic, since it is now independent
12048 of the elaboration of @code{Utils}.
12049 This separation of concerns also corresponds to
12050 a generally sound engineering principle of separating declarations
12051 from instances. This version of the program also compiles, binds, links,
12052 and executes, generating the expected output.
12055 Use No_Entry_Calls_In_Elaboration_Code restriction.
12056 @cindex No_Entry_Calls_In_Elaboration_Code
12058 The previous two approaches described how a program can be restructured
12059 to avoid the special problems caused by library task bodies. in practice,
12060 however, such restructuring may be difficult to apply to existing legacy code,
12061 so we must consider solutions that do not require massive rewriting.
12063 Let us consider more carefully why our original sample program works
12064 under the dynamic model of elaboration. The reason is that the code
12065 in the task body blocks immediately on the @code{accept}
12066 statement. Now of course there is nothing to prohibit elaboration
12067 code from making entry calls (for example from another library level task),
12068 so we cannot tell in isolation that
12069 the task will not execute the accept statement during elaboration.
12071 However, in practice it is very unusual to see elaboration code
12072 make any entry calls, and the pattern of tasks starting
12073 at elaboration time and then immediately blocking on @code{accept} or
12074 @code{select} statements is very common. What this means is that
12075 the compiler is being too pessimistic when it analyzes the
12076 whole package body as though it might be executed at elaboration
12079 If we know that the elaboration code contains no entry calls, (a very safe
12080 assumption most of the time, that could almost be made the default
12081 behavior), then we can compile all units of the program under control
12082 of the following configuration pragma:
12085 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
12089 This pragma can be placed in the @file{gnat.adc} file in the usual
12090 manner. If we take our original unmodified program and compile it
12091 in the presence of a @file{gnat.adc} containing the above pragma,
12092 then once again, we can compile, bind, link, and execute, obtaining
12093 the expected result. In the presence of this pragma, the compiler does
12094 not trace calls in a task body, that appear after the first @code{accept}
12095 or @code{select} statement, and therefore does not report a potential
12096 circularity in the original program.
12098 The compiler will check to the extent it can that the above
12099 restriction is not violated, but it is not always possible to do a
12100 complete check at compile time, so it is important to use this
12101 pragma only if the stated restriction is in fact met, that is to say
12102 no task receives an entry call before elaboration of all units is completed.
12106 @node Mixing Elaboration Models
12107 @section Mixing Elaboration Models
12109 So far, we have assumed that the entire program is either compiled
12110 using the dynamic model or static model, ensuring consistency. It
12111 is possible to mix the two models, but rules have to be followed
12112 if this mixing is done to ensure that elaboration checks are not
12115 The basic rule is that @emph{a unit compiled with the static model cannot
12116 be @code{with'ed} by a unit compiled with the dynamic model}. The
12117 reason for this is that in the static model, a unit assumes that
12118 its clients guarantee to use (the equivalent of) pragma
12119 @code{Elaborate_All} so that no elaboration checks are required
12120 in inner subprograms, and this assumption is violated if the
12121 client is compiled with dynamic checks.
12123 The precise rule is as follows. A unit that is compiled with dynamic
12124 checks can only @code{with} a unit that meets at least one of the
12125 following criteria:
12130 The @code{with'ed} unit is itself compiled with dynamic elaboration
12131 checks (that is with the @option{-gnatE} switch.
12134 The @code{with'ed} unit is an internal GNAT implementation unit from
12135 the System, Interfaces, Ada, or GNAT hierarchies.
12138 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
12141 The @code{with'ing} unit (that is the client) has an explicit pragma
12142 @code{Elaborate_All} for the @code{with'ed} unit.
12147 If this rule is violated, that is if a unit with dynamic elaboration
12148 checks @code{with's} a unit that does not meet one of the above four
12149 criteria, then the binder (@code{gnatbind}) will issue a warning
12150 similar to that in the following example:
12153 warning: "x.ads" has dynamic elaboration checks and with's
12154 warning: "y.ads" which has static elaboration checks
12158 These warnings indicate that the rule has been violated, and that as a result
12159 elaboration checks may be missed in the resulting executable file.
12160 This warning may be suppressed using the @code{-ws} binder switch
12161 in the usual manner.
12163 One useful application of this mixing rule is in the case of a subsystem
12164 which does not itself @code{with} units from the remainder of the
12165 application. In this case, the entire subsystem can be compiled with
12166 dynamic checks to resolve a circularity in the subsystem, while
12167 allowing the main application that uses this subsystem to be compiled
12168 using the more reliable default static model.
12170 @node What to Do If the Default Elaboration Behavior Fails
12171 @section What to Do If the Default Elaboration Behavior Fails
12174 If the binder cannot find an acceptable order, it outputs detailed
12175 diagnostics. For example:
12181 error: elaboration circularity detected
12182 info: "proc (body)" must be elaborated before "pack (body)"
12183 info: reason: Elaborate_All probably needed in unit "pack (body)"
12184 info: recompile "pack (body)" with -gnatwl
12185 info: for full details
12186 info: "proc (body)"
12187 info: is needed by its spec:
12188 info: "proc (spec)"
12189 info: which is withed by:
12190 info: "pack (body)"
12191 info: "pack (body)" must be elaborated before "proc (body)"
12192 info: reason: pragma Elaborate in unit "proc (body)"
12198 In this case we have a cycle that the binder cannot break. On the one
12199 hand, there is an explicit pragma Elaborate in @code{proc} for
12200 @code{pack}. This means that the body of @code{pack} must be elaborated
12201 before the body of @code{proc}. On the other hand, there is elaboration
12202 code in @code{pack} that calls a subprogram in @code{proc}. This means
12203 that for maximum safety, there should really be a pragma
12204 Elaborate_All in @code{pack} for @code{proc} which would require that
12205 the body of @code{proc} be elaborated before the body of
12206 @code{pack}. Clearly both requirements cannot be satisfied.
12207 Faced with a circularity of this kind, you have three different options.
12210 @item Fix the program
12211 The most desirable option from the point of view of long-term maintenance
12212 is to rearrange the program so that the elaboration problems are avoided.
12213 One useful technique is to place the elaboration code into separate
12214 child packages. Another is to move some of the initialization code to
12215 explicitly called subprograms, where the program controls the order
12216 of initialization explicitly. Although this is the most desirable option,
12217 it may be impractical and involve too much modification, especially in
12218 the case of complex legacy code.
12220 @item Perform dynamic checks
12221 If the compilations are done using the
12223 (dynamic elaboration check) switch, then GNAT behaves in
12224 a quite different manner. Dynamic checks are generated for all calls
12225 that could possibly result in raising an exception. With this switch,
12226 the compiler does not generate implicit @code{Elaborate_All} pragmas.
12227 The behavior then is exactly as specified in the Ada 95 Reference Manual.
12228 The binder will generate an executable program that may or may not
12229 raise @code{Program_Error}, and then it is the programmer's job to ensure
12230 that it does not raise an exception. Note that it is important to
12231 compile all units with the switch, it cannot be used selectively.
12233 @item Suppress checks
12234 The drawback of dynamic checks is that they generate a
12235 significant overhead at run time, both in space and time. If you
12236 are absolutely sure that your program cannot raise any elaboration
12237 exceptions, and you still want to use the dynamic elaboration model,
12238 then you can use the configuration pragma
12239 @code{Suppress (Elaboration_Checks)} to suppress all such checks. For
12240 example this pragma could be placed in the @file{gnat.adc} file.
12242 @item Suppress checks selectively
12243 When you know that certain calls in elaboration code cannot possibly
12244 lead to an elaboration error, and the binder nevertheless generates warnings
12245 on those calls and inserts Elaborate_All pragmas that lead to elaboration
12246 circularities, it is possible to remove those warnings locally and obtain
12247 a program that will bind. Clearly this can be unsafe, and it is the
12248 responsibility of the programmer to make sure that the resulting program has
12249 no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can
12250 be used with different granularity to suppress warnings and break
12251 elaboration circularities:
12255 Place the pragma that names the called subprogram in the declarative part
12256 that contains the call.
12259 Place the pragma in the declarative part, without naming an entity. This
12260 disables warnings on all calls in the corresponding declarative region.
12263 Place the pragma in the package spec that declares the called subprogram,
12264 and name the subprogram. This disables warnings on all elaboration calls to
12268 Place the pragma in the package spec that declares the called subprogram,
12269 without naming any entity. This disables warnings on all elaboration calls to
12270 all subprograms declared in this spec.
12274 These four cases are listed in order of decreasing safety, and therefore
12275 require increasing programmer care in their application. Consider the
12280 function F1 return Integer;
12285 function F2 return Integer;
12286 function Pure (x : integer) return integer;
12287 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
12288 -- pragma Suppress (Elaboration_Check); -- (4)
12292 package body Pack1 is
12293 function F1 return Integer is
12297 Val : integer := Pack2.Pure (11); -- Elab. call (1)
12300 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
12301 -- pragma Suppress(Elaboration_Check); -- (2)
12303 X1 := Pack2.F2 + 1; -- Elab. call (2)
12308 package body Pack2 is
12309 function F2 return Integer is
12313 function Pure (x : integer) return integer is
12315 return x ** 3 - 3 * x;
12319 with Pack1, Ada.Text_IO;
12322 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
12325 In the absence of any pragmas, an attempt to bind this program produces
12326 the following diagnostics:
12332 error: elaboration circularity detected
12333 info: "pack1 (body)" must be elaborated before "pack1 (body)"
12334 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
12335 info: recompile "pack1 (body)" with -gnatwl for full details
12336 info: "pack1 (body)"
12337 info: must be elaborated along with its spec:
12338 info: "pack1 (spec)"
12339 info: which is withed by:
12340 info: "pack2 (body)"
12341 info: which must be elaborated along with its spec:
12342 info: "pack2 (spec)"
12343 info: which is withed by:
12344 info: "pack1 (body)"
12347 The sources of the circularity are the two calls to @code{Pack2.Pure} and
12348 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
12349 F2 is safe, even though F2 calls F1, because the call appears after the
12350 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
12351 remove the warning on the call. It is also possible to use pragma (2)
12352 because there are no other potentially unsafe calls in the block.
12355 The call to @code{Pure} is safe because this function does not depend on the
12356 state of @code{Pack2}. Therefore any call to this function is safe, and it
12357 is correct to place pragma (3) in the corresponding package spec.
12360 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
12361 warnings on all calls to functions declared therein. Note that this is not
12362 necessarily safe, and requires more detailed examination of the subprogram
12363 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
12364 be already elaborated.
12368 It is hard to generalize on which of these four approaches should be
12369 taken. Obviously if it is possible to fix the program so that the default
12370 treatment works, this is preferable, but this may not always be practical.
12371 It is certainly simple enough to use
12373 but the danger in this case is that, even if the GNAT binder
12374 finds a correct elaboration order, it may not always do so,
12375 and certainly a binder from another Ada compiler might not. A
12376 combination of testing and analysis (for which the warnings generated
12379 switch can be useful) must be used to ensure that the program is free
12380 of errors. One switch that is useful in this testing is the
12381 @code{-p (pessimistic elaboration order)}
12384 Normally the binder tries to find an order that has the best chance of
12385 of avoiding elaboration problems. With this switch, the binder
12386 plays a devil's advocate role, and tries to choose the order that
12387 has the best chance of failing. If your program works even with this
12388 switch, then it has a better chance of being error free, but this is still
12391 For an example of this approach in action, consider the C-tests (executable
12392 tests) from the ACVC suite. If these are compiled and run with the default
12393 treatment, then all but one of them succeed without generating any error
12394 diagnostics from the binder. However, there is one test that fails, and
12395 this is not surprising, because the whole point of this test is to ensure
12396 that the compiler can handle cases where it is impossible to determine
12397 a correct order statically, and it checks that an exception is indeed
12398 raised at run time.
12400 This one test must be compiled and run using the
12402 switch, and then it passes. Alternatively, the entire suite can
12403 be run using this switch. It is never wrong to run with the dynamic
12404 elaboration switch if your code is correct, and we assume that the
12405 C-tests are indeed correct (it is less efficient, but efficiency is
12406 not a factor in running the ACVC tests.)
12408 @node Elaboration for Access-to-Subprogram Values
12409 @section Elaboration for Access-to-Subprogram Values
12410 @cindex Access-to-subprogram
12413 The introduction of access-to-subprogram types in Ada 95 complicates
12414 the handling of elaboration. The trouble is that it becomes
12415 impossible to tell at compile time which procedure
12416 is being called. This means that it is not possible for the binder
12417 to analyze the elaboration requirements in this case.
12419 If at the point at which the access value is created
12420 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
12421 the body of the subprogram is
12422 known to have been elaborated, then the access value is safe, and its use
12423 does not require a check. This may be achieved by appropriate arrangement
12424 of the order of declarations if the subprogram is in the current unit,
12425 or, if the subprogram is in another unit, by using pragma
12426 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
12427 on the referenced unit.
12429 If the referenced body is not known to have been elaborated at the point
12430 the access value is created, then any use of the access value must do a
12431 dynamic check, and this dynamic check will fail and raise a
12432 @code{Program_Error} exception if the body has not been elaborated yet.
12433 GNAT will generate the necessary checks, and in addition, if the
12435 switch is set, will generate warnings that such checks are required.
12437 The use of dynamic dispatching for tagged types similarly generates
12438 a requirement for dynamic checks, and premature calls to any primitive
12439 operation of a tagged type before the body of the operation has been elaborated,
12440 will result in the raising of @code{Program_Error}.
12442 @node Summary of Procedures for Elaboration Control
12443 @section Summary of Procedures for Elaboration Control
12444 @cindex Elaboration control
12447 First, compile your program with the default options, using none of
12448 the special elaboration control switches. If the binder successfully
12449 binds your program, then you can be confident that, apart from issues
12450 raised by the use of access-to-subprogram types and dynamic dispatching,
12451 the program is free of elaboration errors. If it is important that the
12452 program be portable, then use the
12454 switch to generate warnings about missing @code{Elaborate_All}
12455 pragmas, and supply the missing pragmas.
12457 If the program fails to bind using the default static elaboration
12458 handling, then you can fix the program to eliminate the binder
12459 message, or recompile the entire program with the
12460 @option{-gnatE} switch to generate dynamic elaboration checks,
12461 and, if you are sure there really are no elaboration problems,
12462 use a global pragma @code{Suppress (Elaboration_Checks)}.
12464 @node Other Elaboration Order Considerations
12465 @section Other Elaboration Order Considerations
12467 This section has been entirely concerned with the issue of finding a valid
12468 elaboration order, as defined by the Ada Reference Manual. In a case
12469 where several elaboration orders are valid, the task is to find one
12470 of the possible valid elaboration orders (and the static model in GNAT
12471 will ensure that this is achieved).
12473 The purpose of the elaboration rules in the Ada Reference Manual is to
12474 make sure that no entity is accessed before it has been elaborated. For
12475 a subprogram, this means that the spec and body must have been elaborated
12476 before the subprogram is called. For an object, this means that the object
12477 must have been elaborated before its value is read or written. A violation
12478 of either of these two requirements is an access before elaboration order,
12479 and this section has been all about avoiding such errors.
12481 In the case where more than one order of elaboration is possible, in the
12482 sense that access before elaboration errors are avoided, then any one of
12483 the orders is "correct" in the sense that it meets the requirements of
12484 the Ada Reference Manual, and no such error occurs.
12486 However, it may be the case for a given program, that there are
12487 constraints on the order of elaboration that come not from consideration
12488 of avoiding elaboration errors, but rather from extra-lingual logic
12489 requirements. Consider this example:
12492 with Init_Constants;
12493 package Constants is
12498 package Init_Constants is
12500 end Init_Constants;
12503 package body Init_Constants is
12504 procedure Calc is begin null; end;
12508 end Init_Constants;
12512 Z : Integer := Constants.X + Constants.Y;
12516 with Text_IO; use Text_IO;
12519 Put_Line (Calc.Z'Img);
12524 In this example, there is more than one valid order of elaboration. For
12525 example both the following are correct orders:
12528 Init_Constants spec
12532 Init_Constants body
12536 Init_Constants spec
12537 Init_Constants body
12544 There is no language rule to prefer one or the other, both are correct
12545 from an order of elaboration point of view. But the programmatic effects
12546 of the two orders are very different. In the first, the elaboration routine
12547 of @code{Calc} initializes @code{Z} to zero, and then the main program
12548 runs with this value of zero. But in the second order, the elaboration
12549 routine of @code{Calc} runs after the body of Init_Constants has set
12550 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
12553 One could perhaps by applying pretty clever non-artificial intelligence
12554 to the situation guess that it is more likely that the second order of
12555 elaboration is the one desired, but there is no formal linguistic reason
12556 to prefer one over the other. In fact in this particular case, GNAT will
12557 prefer the second order, because of the rule that bodies are elaborated
12558 as soon as possible, but it's just luck that this is what was wanted
12559 (if indeed the second order was preferred).
12561 If the program cares about the order of elaboration routines in a case like
12562 this, it is important to specify the order required. In this particular
12563 case, that could have been achieved by adding to the spec of Calc:
12566 pragma Elaborate_All (Constants);
12570 which requires that the body (if any) and spec of @code{Constants},
12571 as well as the body and spec of any unit @code{with}'ed by
12572 @code{Constants} be elaborated before @code{Calc} is elaborated.
12574 Clearly no automatic method can always guess which alternative you require,
12575 and if you are working with legacy code that had constraints of this kind
12576 which were not properly specified by adding @code{Elaborate} or
12577 @code{Elaborate_All} pragmas, then indeed it is possible that two different
12578 compilers can choose different orders.
12580 The @code{gnatbind}
12581 @code{-p} switch may be useful in smoking
12582 out problems. This switch causes bodies to be elaborated as late as possible
12583 instead of as early as possible. In the example above, it would have forced
12584 the choice of the first elaboration order. If you get different results
12585 when using this switch, and particularly if one set of results is right,
12586 and one is wrong as far as you are concerned, it shows that you have some
12587 missing @code{Elaborate} pragmas. For the example above, we have the
12591 gnatmake -f -q main
12594 gnatmake -f -q main -bargs -p
12600 It is of course quite unlikely that both these results are correct, so
12601 it is up to you in a case like this to investigate the source of the
12602 difference, by looking at the two elaboration orders that are chosen,
12603 and figuring out which is correct, and then adding the necessary
12604 @code{Elaborate_All} pragmas to ensure the desired order.
12606 @node The Cross-Referencing Tools gnatxref and gnatfind
12607 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12612 The compiler generates cross-referencing information (unless
12613 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12614 This information indicates where in the source each entity is declared and
12615 referenced. Note that entities in package Standard are not included, but
12616 entities in all other predefined units are included in the output.
12618 Before using any of these two tools, you need to compile successfully your
12619 application, so that GNAT gets a chance to generate the cross-referencing
12622 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12623 information to provide the user with the capability to easily locate the
12624 declaration and references to an entity. These tools are quite similar,
12625 the difference being that @code{gnatfind} is intended for locating
12626 definitions and/or references to a specified entity or entities, whereas
12627 @code{gnatxref} is oriented to generating a full report of all
12630 To use these tools, you must not compile your application using the
12631 @option{-gnatx} switch on the @file{gnatmake} command line (@inforef{The
12632 GNAT Make Program gnatmake,,gnat_ug}). Otherwise, cross-referencing
12633 information will not be generated.
12636 * gnatxref Switches::
12637 * gnatfind Switches::
12638 * Project Files for gnatxref and gnatfind::
12639 * Regular Expressions in gnatfind and gnatxref::
12640 * Examples of gnatxref Usage::
12641 * Examples of gnatfind Usage::
12644 @node gnatxref Switches
12645 @section @code{gnatxref} Switches
12648 The command lines for @code{gnatxref} is:
12650 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
12657 @item sourcefile1, sourcefile2
12658 identifies the source files for which a report is to be generated. The
12659 'with'ed units will be processed too. You must provide at least one file.
12661 These file names are considered to be regular expressions, so for instance
12662 specifying 'source*.adb' is the same as giving every file in the current
12663 directory whose name starts with 'source' and whose extension is 'adb'.
12668 The switches can be :
12671 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12672 the read-only files found in the library search path. Otherwise, these files
12673 will be ignored. This option can be used to protect Gnat sources or your own
12674 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12675 much faster, and their output much smaller.
12678 When looking for source files also look in directory DIR. The order in which
12679 source file search is undertaken is the same as for @file{gnatmake}.
12682 When searching for library and object files, look in directory
12683 DIR. The order in which library files are searched is the same as for
12687 Do not look for sources in the system default directory.
12690 Do not look for library files in the system default directory.
12692 @item --RTS=@var{rts-path}
12693 @cindex @code{--RTS} (@code{gnatxref})
12694 Specifies the default location of the runtime library. Same meaning as the
12695 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
12698 If this switch is set @code{gnatxref} will output the parent type
12699 reference for each matching derived types.
12702 If this switch is set, the output file names will be preceded by their
12703 directory (if the file was found in the search path). If this switch is
12704 not set, the directory will not be printed.
12707 If this switch is set, information is output only for library-level
12708 entities, ignoring local entities. The use of this switch may accelerate
12709 @code{gnatfind} and @code{gnatxref}.
12712 Equivalent to @samp{-aODIR -aIDIR}.
12715 Specify a project file to use @xref{Project Files}.
12716 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12717 project file in the current directory.
12719 If a project file is either specified or found by the tools, then the content
12720 of the source directory and object directory lines are added as if they
12721 had been specified respectively by @samp{-aI}
12724 Output only unused symbols. This may be really useful if you give your
12725 main compilation unit on the command line, as @code{gnatxref} will then
12726 display every unused entity and 'with'ed package.
12729 Instead of producing the default output, @code{gnatxref} will generate a
12730 @file{tags} file that can be used by vi. For examples how to use this
12731 feature, see @xref{Examples of gnatxref Usage}. The tags file is output
12732 to the standard output, thus you will have to redirect it to a file.
12736 All these switches may be in any order on the command line, and may even
12737 appear after the file names. They need not be separated by spaces, thus
12738 you can say @samp{gnatxref -ag} instead of
12739 @samp{gnatxref -a -g}.
12741 @node gnatfind Switches
12742 @section @code{gnatfind} Switches
12745 The command line for @code{gnatfind} is:
12748 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
12757 An entity will be output only if it matches the regular expression found
12758 in @samp{pattern}, see @xref{Regular Expressions in gnatfind and gnatxref}.
12760 Omitting the pattern is equivalent to specifying @samp{*}, which
12761 will match any entity. Note that if you do not provide a pattern, you
12762 have to provide both a sourcefile and a line.
12764 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12765 for matching purposes. At the current time there is no support for
12766 8-bit codes other than Latin-1, or for wide characters in identifiers.
12769 @code{gnatfind} will look for references, bodies or declarations
12770 of symbols referenced in @file{sourcefile}, at line @samp{line}
12771 and column @samp{column}. See @pxref{Examples of gnatfind Usage}
12772 for syntax examples.
12775 is a decimal integer identifying the line number containing
12776 the reference to the entity (or entities) to be located.
12779 is a decimal integer identifying the exact location on the
12780 line of the first character of the identifier for the
12781 entity reference. Columns are numbered from 1.
12783 @item file1 file2 ...
12784 The search will be restricted to these files. If none are given, then
12785 the search will be done for every library file in the search path.
12786 These file must appear only after the pattern or sourcefile.
12788 These file names are considered to be regular expressions, so for instance
12789 specifying 'source*.adb' is the same as giving every file in the current
12790 directory whose name starts with 'source' and whose extension is 'adb'.
12792 Not that if you specify at least one file in this part, @code{gnatfind} may
12793 sometimes not be able to find the body of the subprograms...
12797 At least one of 'sourcefile' or 'pattern' has to be present on
12800 The following switches are available:
12804 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12805 the read-only files found in the library search path. Otherwise, these files
12806 will be ignored. This option can be used to protect Gnat sources or your own
12807 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12808 much faster, and their output much smaller.
12811 When looking for source files also look in directory DIR. The order in which
12812 source file search is undertaken is the same as for @file{gnatmake}.
12815 When searching for library and object files, look in directory
12816 DIR. The order in which library files are searched is the same as for
12820 Do not look for sources in the system default directory.
12823 Do not look for library files in the system default directory.
12825 @item --RTS=@var{rts-path}
12826 @cindex @code{--RTS} (@code{gnatfind})
12827 Specifies the default location of the runtime library. Same meaning as the
12828 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
12831 If this switch is set, then @code{gnatfind} will output the parent type
12832 reference for each matching derived types.
12835 By default, @code{gnatfind} accept the simple regular expression set for
12836 @samp{pattern}. If this switch is set, then the pattern will be
12837 considered as full Unix-style regular expression.
12840 If this switch is set, the output file names will be preceded by their
12841 directory (if the file was found in the search path). If this switch is
12842 not set, the directory will not be printed.
12845 If this switch is set, information is output only for library-level
12846 entities, ignoring local entities. The use of this switch may accelerate
12847 @code{gnatfind} and @code{gnatxref}.
12850 Equivalent to @samp{-aODIR -aIDIR}.
12853 Specify a project file (@pxref{Project Files}) to use.
12854 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12855 project file in the current directory.
12857 If a project file is either specified or found by the tools, then the content
12858 of the source directory and object directory lines are added as if they
12859 had been specified respectively by @samp{-aI} and
12863 By default, @code{gnatfind} will output only the information about the
12864 declaration, body or type completion of the entities. If this switch is
12865 set, the @code{gnatfind} will locate every reference to the entities in
12866 the files specified on the command line (or in every file in the search
12867 path if no file is given on the command line).
12870 If this switch is set, then @code{gnatfind} will output the content
12871 of the Ada source file lines were the entity was found.
12874 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12875 the specified type. It act like -d option but recursively from parent
12876 type to parent type. When this switch is set it is not possible to
12877 specify more than one file.
12881 All these switches may be in any order on the command line, and may even
12882 appear after the file names. They need not be separated by spaces, thus
12883 you can say @samp{gnatxref -ag} instead of
12884 @samp{gnatxref -a -g}.
12886 As stated previously, gnatfind will search in every directory in the
12887 search path. You can force it to look only in the current directory if
12888 you specify @code{*} at the end of the command line.
12891 @node Project Files for gnatxref and gnatfind
12892 @section Project Files for @command{gnatxref} and @command{gnatfind}
12895 Project files allow a programmer to specify how to compile its
12896 application, where to find sources,... These files are used primarily by
12897 the Glide Ada mode, but they can also be used by the two tools
12898 @code{gnatxref} and @code{gnatfind}.
12900 A project file name must end with @file{.adp}. If a single one is
12901 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12902 extract the information from it. If multiple project files are found, none of
12903 them is read, and you have to use the @samp{-p} switch to specify the one
12906 The following lines can be included, even though most of them have default
12907 values which can be used in most cases.
12908 The lines can be entered in any order in the file.
12909 Except for @samp{src_dir} and @samp{obj_dir}, you can only have one instance of
12910 each line. If you have multiple instances, only the last one is taken into
12914 @item src_dir=DIR [default: "./"]
12915 specifies a directory where to look for source files. Multiple src_dir lines
12916 can be specified and they will be searched in the order they
12919 @item obj_dir=DIR [default: "./"]
12920 specifies a directory where to look for object and library files. Multiple
12921 obj_dir lines can be specified and they will be searched in the order they
12924 @item comp_opt=SWITCHES [default: ""]
12925 creates a variable which can be referred to subsequently by using
12926 the @samp{$@{comp_opt@}} notation. This is intended to store the default
12927 switches given to @file{gnatmake} and @file{gcc}.
12929 @item bind_opt=SWITCHES [default: ""]
12930 creates a variable which can be referred to subsequently by using
12931 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12932 switches given to @file{gnatbind}.
12934 @item link_opt=SWITCHES [default: ""]
12935 creates a variable which can be referred to subsequently by using
12936 the @samp{$@{link_opt@}} notation. This is intended to store the default
12937 switches given to @file{gnatlink}.
12939 @item main=EXECUTABLE [default: ""]
12940 specifies the name of the executable for the application. This variable can
12941 be referred to in the following lines by using the @samp{$@{main@}} notation.
12943 @item comp_cmd=COMMAND [default: "gcc -c -I$@{src_dir@} -g -gnatq"]
12944 specifies the command used to compile a single file in the application.
12946 @item make_cmd=COMMAND [default: "gnatmake $@{main@} -aI$@{src_dir@} -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@} -bargs $@{bind_opt@} -largs $@{link_opt@}"]
12947 specifies the command used to recompile the whole application.
12949 @item run_cmd=COMMAND [default: "$@{main@}"]
12950 specifies the command used to run the application.
12952 @item debug_cmd=COMMAND [default: "gdb $@{main@}"]
12953 specifies the command used to debug the application
12957 @code{gnatxref} and @code{gnatfind} only take into account the @samp{src_dir}
12958 and @samp{obj_dir} lines, and ignore the others.
12960 @node Regular Expressions in gnatfind and gnatxref
12961 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
12964 As specified in the section about @code{gnatfind}, the pattern can be a
12965 regular expression. Actually, there are to set of regular expressions
12966 which are recognized by the program :
12969 @item globbing patterns
12970 These are the most usual regular expression. They are the same that you
12971 generally used in a Unix shell command line, or in a DOS session.
12973 Here is a more formal grammar :
12980 term ::= elmt -- matches elmt
12981 term ::= elmt elmt -- concatenation (elmt then elmt)
12982 term ::= * -- any string of 0 or more characters
12983 term ::= ? -- matches any character
12984 term ::= [char @{char@}] -- matches any character listed
12985 term ::= [char - char] -- matches any character in range
12989 @item full regular expression
12990 The second set of regular expressions is much more powerful. This is the
12991 type of regular expressions recognized by utilities such a @file{grep}.
12993 The following is the form of a regular expression, expressed in Ada
12994 reference manual style BNF is as follows
13001 regexp ::= term @{| term@} -- alternation (term or term ...)
13003 term ::= item @{item@} -- concatenation (item then item)
13005 item ::= elmt -- match elmt
13006 item ::= elmt * -- zero or more elmt's
13007 item ::= elmt + -- one or more elmt's
13008 item ::= elmt ? -- matches elmt or nothing
13011 elmt ::= nschar -- matches given character
13012 elmt ::= [nschar @{nschar@}] -- matches any character listed
13013 elmt ::= [^ nschar @{nschar@}] -- matches any character not listed
13014 elmt ::= [char - char] -- matches chars in given range
13015 elmt ::= \ char -- matches given character
13016 elmt ::= . -- matches any single character
13017 elmt ::= ( regexp ) -- parens used for grouping
13019 char ::= any character, including special characters
13020 nschar ::= any character except ()[].*+?^
13024 Following are a few examples :
13028 will match any of the two strings 'abcde' and 'fghi'.
13031 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
13034 will match any string which has only lowercase characters in it (and at
13035 least one character
13040 @node Examples of gnatxref Usage
13041 @section Examples of @code{gnatxref} Usage
13043 @subsection General Usage
13046 For the following examples, we will consider the following units :
13053 2: @b{package} Main @b{is}
13054 3: @b{procedure} Foo (B : @b{in} Integer);
13061 1: @b{package body} Main @b{is}
13062 2: @b{procedure} Foo (B : @b{in} Integer) @b{is}
13072 1: @b{package} Bar @b{is}
13073 2: @b{procedure} Print (B : Integer);
13082 The first thing to do is to recompile your application (for instance, in
13083 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13084 the cross-referencing information.
13085 You can then issue any of the following commands:
13087 @item gnatxref main.adb
13088 @code{gnatxref} generates cross-reference information for main.adb
13089 and every unit 'with'ed by main.adb.
13091 The output would be:
13099 Decl: main.ads 3:20
13100 Body: main.adb 2:20
13101 Ref: main.adb 4:13 5:13 6:19
13104 Ref: main.adb 6:8 7:8
13114 Decl: main.ads 3:15
13115 Body: main.adb 2:15
13118 Body: main.adb 1:14
13121 Ref: main.adb 6:12 7:12
13125 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13126 its body is in main.adb, line 1, column 14 and is not referenced any where.
13128 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13129 it referenced in main.adb, line 6 column 12 and line 7 column 12.
13131 @item gnatxref package1.adb package2.ads
13132 @code{gnatxref} will generates cross-reference information for
13133 package1.adb, package2.ads and any other package 'with'ed by any
13138 @subsection Using gnatxref with vi
13140 @code{gnatxref} can generate a tags file output, which can be used
13141 directly from @file{vi}. Note that the standard version of @file{vi}
13142 will not work properly with overloaded symbols. Consider using another
13143 free implementation of @file{vi}, such as @file{vim}.
13146 $ gnatxref -v gnatfind.adb > tags
13150 will generate the tags file for @code{gnatfind} itself (if the sources
13151 are in the search path!).
13153 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
13154 (replacing @i{entity} by whatever you are looking for), and vi will
13155 display a new file with the corresponding declaration of entity.
13157 @node Examples of gnatfind Usage
13158 @section Examples of @code{gnatfind} Usage
13162 @item gnatfind -f xyz:main.adb
13163 Find declarations for all entities xyz referenced at least once in
13164 main.adb. The references are search in every library file in the search
13167 The directories will be printed as well (as the @samp{-f}
13170 The output will look like:
13172 directory/main.ads:106:14: xyz <= declaration
13173 directory/main.adb:24:10: xyz <= body
13174 directory/foo.ads:45:23: xyz <= declaration
13178 that is to say, one of the entities xyz found in main.adb is declared at
13179 line 12 of main.ads (and its body is in main.adb), and another one is
13180 declared at line 45 of foo.ads
13182 @item gnatfind -fs xyz:main.adb
13183 This is the same command as the previous one, instead @code{gnatfind} will
13184 display the content of the Ada source file lines.
13186 The output will look like:
13189 directory/main.ads:106:14: xyz <= declaration
13191 directory/main.adb:24:10: xyz <= body
13193 directory/foo.ads:45:23: xyz <= declaration
13198 This can make it easier to find exactly the location your are looking
13201 @item gnatfind -r "*x*":main.ads:123 foo.adb
13202 Find references to all entities containing an x that are
13203 referenced on line 123 of main.ads.
13204 The references will be searched only in main.adb and foo.adb.
13206 @item gnatfind main.ads:123
13207 Find declarations and bodies for all entities that are referenced on
13208 line 123 of main.ads.
13210 This is the same as @code{gnatfind "*":main.adb:123}.
13212 @item gnatfind mydir/main.adb:123:45
13213 Find the declaration for the entity referenced at column 45 in
13214 line 123 of file main.adb in directory mydir. Note that it
13215 is usual to omit the identifier name when the column is given,
13216 since the column position identifies a unique reference.
13218 The column has to be the beginning of the identifier, and should not
13219 point to any character in the middle of the identifier.
13223 @node File Name Krunching Using gnatkr
13224 @chapter File Name Krunching Using @code{gnatkr}
13228 This chapter discusses the method used by the compiler to shorten
13229 the default file names chosen for Ada units so that they do not
13230 exceed the maximum length permitted. It also describes the
13231 @code{gnatkr} utility that can be used to determine the result of
13232 applying this shortening.
13236 * Krunching Method::
13237 * Examples of gnatkr Usage::
13241 @section About @code{gnatkr}
13244 The default file naming rule in GNAT
13245 is that the file name must be derived from
13246 the unit name. The exact default rule is as follows:
13249 Take the unit name and replace all dots by hyphens.
13251 If such a replacement occurs in the
13252 second character position of a name, and the first character is
13253 a, g, s, or i then replace the dot by the character
13255 instead of a minus.
13257 The reason for this exception is to avoid clashes
13258 with the standard names for children of System, Ada, Interfaces,
13259 and GNAT, which use the prefixes s- a- i- and g-
13262 The @code{-gnatk@var{nn}}
13263 switch of the compiler activates a "krunching"
13264 circuit that limits file names to nn characters (where nn is a decimal
13265 integer). For example, using OpenVMS,
13266 where the maximum file name length is
13267 39, the value of nn is usually set to 39, but if you want to generate
13268 a set of files that would be usable if ported to a system with some
13269 different maximum file length, then a different value can be specified.
13270 The default value of 39 for OpenVMS need not be specified.
13272 The @code{gnatkr} utility can be used to determine the krunched name for
13273 a given file, when krunched to a specified maximum length.
13276 @section Using @code{gnatkr}
13279 The @code{gnatkr} command has the form
13282 $ gnatkr @var{name} [@var{length}]
13287 @var{name} can be an Ada name with dots or the GNAT name of the unit,
13288 where the dots representing child units or subunit are replaced by
13289 hyphens. The only confusion arises if a name ends in @code{.ads} or
13290 @code{.adb}. @code{gnatkr} takes this to be an extension if there are
13291 no other dots in the name and the whole name is in lowercase.
13293 @var{length} represents the length of the krunched name. The default
13294 when no argument is given is 8 characters. A length of zero stands for
13295 unlimited, in other words do not chop except for system files which are
13299 The output is the krunched name. The output has an extension only if the
13300 original argument was a file name with an extension.
13302 @node Krunching Method
13303 @section Krunching Method
13306 The initial file name is determined by the name of the unit that the file
13307 contains. The name is formed by taking the full expanded name of the
13308 unit and replacing the separating dots with hyphens and
13310 for all letters, except that a hyphen in the second character position is
13311 replaced by a tilde if the first character is
13313 The extension is @code{.ads} for a
13314 specification and @code{.adb} for a body.
13315 Krunching does not affect the extension, but the file name is shortened to
13316 the specified length by following these rules:
13320 The name is divided into segments separated by hyphens, tildes or
13321 underscores and all hyphens, tildes, and underscores are
13322 eliminated. If this leaves the name short enough, we are done.
13325 If the name is too long, the longest segment is located (left-most if there are two
13326 of equal length), and shortened by dropping its last character. This is
13327 repeated until the name is short enough.
13329 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
13330 to fit the name into 8 characters as required by some operating systems.
13333 our-strings-wide_fixed 22
13334 our strings wide fixed 19
13335 our string wide fixed 18
13336 our strin wide fixed 17
13337 our stri wide fixed 16
13338 our stri wide fixe 15
13339 our str wide fixe 14
13340 our str wid fixe 13
13346 Final file name: oustwifi.adb
13350 The file names for all predefined units are always krunched to eight
13351 characters. The krunching of these predefined units uses the following
13352 special prefix replacements:
13356 replaced by @file{a-}
13359 replaced by @file{g-}
13362 replaced by @file{i-}
13365 replaced by @file{s-}
13368 These system files have a hyphen in the second character position. That
13369 is why normal user files replace such a character with a
13371 avoid confusion with system file names.
13373 As an example of this special rule, consider
13374 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
13377 ada-strings-wide_fixed 22
13378 a- strings wide fixed 18
13379 a- string wide fixed 17
13380 a- strin wide fixed 16
13381 a- stri wide fixed 15
13382 a- stri wide fixe 14
13383 a- str wide fixe 13
13389 Final file name: a-stwifi.adb
13393 Of course no file shortening algorithm can guarantee uniqueness over all
13394 possible unit names, and if file name krunching is used then it is your
13395 responsibility to ensure that no name clashes occur. The utility
13396 program @code{gnatkr} is supplied for conveniently determining the
13397 krunched name of a file.
13399 @node Examples of gnatkr Usage
13400 @section Examples of @code{gnatkr} Usage
13406 $ gnatkr very_long_unit_name.ads --> velounna.ads
13407 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
13408 $ gnatkr Grandparent.Parent.Child --> grparchi
13409 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
13410 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
13413 @node Preprocessing Using gnatprep
13414 @chapter Preprocessing Using @code{gnatprep}
13418 The @code{gnatprep} utility provides
13419 a simple preprocessing capability for Ada programs.
13420 It is designed for use with GNAT, but is not dependent on any special
13425 * Switches for gnatprep::
13426 * Form of Definitions File::
13427 * Form of Input Text for gnatprep::
13430 @node Using gnatprep
13431 @section Using @code{gnatprep}
13434 To call @code{gnatprep} use
13437 $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
13444 is the full name of the input file, which is an Ada source
13445 file containing preprocessor directives.
13448 is the full name of the output file, which is an Ada source
13449 in standard Ada form. When used with GNAT, this file name will
13450 normally have an ads or adb suffix.
13453 is the full name of a text file containing definitions of
13454 symbols to be referenced by the preprocessor. This argument is
13455 optional, and can be replaced by the use of the @code{-D} switch.
13458 is an optional sequence of switches as described in the next section.
13461 @node Switches for gnatprep
13462 @section Switches for @code{gnatprep}
13467 Causes both preprocessor lines and the lines deleted by
13468 preprocessing to be replaced by blank lines in the output source file,
13469 preserving line numbers in the output file.
13472 Causes both preprocessor lines and the lines deleted
13473 by preprocessing to be retained in the output source as comments marked
13474 with the special string "--! ". This option will result in line numbers
13475 being preserved in the output file.
13477 @item -Dsymbol=value
13478 Defines a new symbol, associated with value. If no value is given on the
13479 command line, then symbol is considered to be @code{True}. This switch
13480 can be used in place of a definition file.
13484 Causes a @code{Source_Reference} pragma to be generated that
13485 references the original input file, so that error messages will use
13486 the file name of this original file. The use of this switch implies
13487 that preprocessor lines are not to be removed from the file, so its
13488 use will force @code{-b} mode if
13490 has not been specified explicitly.
13492 Note that if the file to be preprocessed contains multiple units, then
13493 it will be necessary to @code{gnatchop} the output file from
13494 @code{gnatprep}. If a @code{Source_Reference} pragma is present
13495 in the preprocessed file, it will be respected by
13497 so that the final chopped files will correctly refer to the original
13498 input source file for @code{gnatprep}.
13501 Causes a sorted list of symbol names and values to be
13502 listed on the standard output file.
13505 Causes undefined symbols to be treated as having the value FALSE in the context
13506 of a preprocessor test. In the absence of this option, an undefined symbol in
13507 a @code{#if} or @code{#elsif} test will be treated as an error.
13512 Note: if neither @code{-b} nor @code{-c} is present,
13513 then preprocessor lines and
13514 deleted lines are completely removed from the output, unless -r is
13515 specified, in which case -b is assumed.
13517 @node Form of Definitions File
13518 @section Form of Definitions File
13521 The definitions file contains lines of the form
13528 where symbol is an identifier, following normal Ada (case-insensitive)
13529 rules for its syntax, and value is one of the following:
13533 Empty, corresponding to a null substitution
13535 A string literal using normal Ada syntax
13537 Any sequence of characters from the set
13538 (letters, digits, period, underline).
13542 Comment lines may also appear in the definitions file, starting with
13543 the usual @code{--},
13544 and comments may be added to the definitions lines.
13546 @node Form of Input Text for gnatprep
13547 @section Form of Input Text for @code{gnatprep}
13550 The input text may contain preprocessor conditional inclusion lines,
13551 as well as general symbol substitution sequences.
13553 The preprocessor conditional inclusion commands have the form
13558 #if @i{expression} [then]
13560 #elsif @i{expression} [then]
13562 #elsif @i{expression} [then]
13573 In this example, @i{expression} is defined by the following grammar:
13575 @i{expression} ::= <symbol>
13576 @i{expression} ::= <symbol> = "<value>"
13577 @i{expression} ::= <symbol> = <symbol>
13578 @i{expression} ::= <symbol> 'Defined
13579 @i{expression} ::= not @i{expression}
13580 @i{expression} ::= @i{expression} and @i{expression}
13581 @i{expression} ::= @i{expression} or @i{expression}
13582 @i{expression} ::= @i{expression} and then @i{expression}
13583 @i{expression} ::= @i{expression} or else @i{expression}
13584 @i{expression} ::= ( @i{expression} )
13588 For the first test (@i{expression} ::= <symbol>) the symbol must have
13589 either the value true or false, that is to say the right-hand of the
13590 symbol definition must be one of the (case-insensitive) literals
13591 @code{True} or @code{False}. If the value is true, then the
13592 corresponding lines are included, and if the value is false, they are
13595 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
13596 the symbol has been defined in the definition file or by a @code{-D}
13597 switch on the command line. Otherwise, the test is false.
13599 The equality tests are case insensitive, as are all the preprocessor lines.
13601 If the symbol referenced is not defined in the symbol definitions file,
13602 then the effect depends on whether or not switch @code{-u}
13603 is specified. If so, then the symbol is treated as if it had the value
13604 false and the test fails. If this switch is not specified, then
13605 it is an error to reference an undefined symbol. It is also an error to
13606 reference a symbol that is defined with a value other than @code{True}
13609 The use of the @code{not} operator inverts the sense of this logical test, so
13610 that the lines are included only if the symbol is not defined.
13611 The @code{then} keyword is optional as shown
13613 The @code{#} must be the first non-blank character on a line, but
13614 otherwise the format is free form. Spaces or tabs may appear between
13615 the @code{#} and the keyword. The keywords and the symbols are case
13616 insensitive as in normal Ada code. Comments may be used on a
13617 preprocessor line, but other than that, no other tokens may appear on a
13618 preprocessor line. Any number of @code{elsif} clauses can be present,
13619 including none at all. The @code{else} is optional, as in Ada.
13621 The @code{#} marking the start of a preprocessor line must be the first
13622 non-blank character on the line, i.e. it must be preceded only by
13623 spaces or horizontal tabs.
13625 Symbol substitution outside of preprocessor lines is obtained by using
13633 anywhere within a source line, except in a comment or within a
13634 string literal. The identifier
13635 following the @code{$} must match one of the symbols defined in the symbol
13636 definition file, and the result is to substitute the value of the
13637 symbol in place of @code{$symbol} in the output file.
13639 Note that although the substitution of strings within a string literal
13640 is not possible, it is possible to have a symbol whose defined value is
13641 a string literal. So instead of setting XYZ to @code{hello} and writing:
13644 Header : String := "$XYZ";
13648 you should set XYZ to @code{"hello"} and write:
13651 Header : String := $XYZ;
13655 and then the substitution will occur as desired.
13658 @node The GNAT Library Browser gnatls
13659 @chapter The GNAT Library Browser @code{gnatls}
13661 @cindex Library browser
13664 @code{gnatls} is a tool that outputs information about compiled
13665 units. It gives the relationship between objects, unit names and source
13666 files. It can also be used to check the source dependencies of a unit
13667 as well as various characteristics.
13671 * Switches for gnatls::
13672 * Examples of gnatls Usage::
13675 @node Running gnatls
13676 @section Running @code{gnatls}
13679 The @code{gnatls} command has the form
13682 $ gnatls switches @var{object_or_ali_file}
13686 The main argument is the list of object or @file{ali} files
13687 (@pxref{The Ada Library Information Files})
13688 for which information is requested.
13690 In normal mode, without additional option, @code{gnatls} produces a
13691 four-column listing. Each line represents information for a specific
13692 object. The first column gives the full path of the object, the second
13693 column gives the name of the principal unit in this object, the third
13694 column gives the status of the source and the fourth column gives the
13695 full path of the source representing this unit.
13696 Here is a simple example of use:
13700 ./demo1.o demo1 DIF demo1.adb
13701 ./demo2.o demo2 OK demo2.adb
13702 ./hello.o h1 OK hello.adb
13703 ./instr-child.o instr.child MOK instr-child.adb
13704 ./instr.o instr OK instr.adb
13705 ./tef.o tef DIF tef.adb
13706 ./text_io_example.o text_io_example OK text_io_example.adb
13707 ./tgef.o tgef DIF tgef.adb
13711 The first line can be interpreted as follows: the main unit which is
13713 object file @file{demo1.o} is demo1, whose main source is in
13714 @file{demo1.adb}. Furthermore, the version of the source used for the
13715 compilation of demo1 has been modified (DIF). Each source file has a status
13716 qualifier which can be:
13719 @item OK (unchanged)
13720 The version of the source file used for the compilation of the
13721 specified unit corresponds exactly to the actual source file.
13723 @item MOK (slightly modified)
13724 The version of the source file used for the compilation of the
13725 specified unit differs from the actual source file but not enough to
13726 require recompilation. If you use gnatmake with the qualifier
13727 @code{-m (minimal recompilation)}, a file marked
13728 MOK will not be recompiled.
13730 @item DIF (modified)
13731 No version of the source found on the path corresponds to the source
13732 used to build this object.
13734 @item ??? (file not found)
13735 No source file was found for this unit.
13737 @item HID (hidden, unchanged version not first on PATH)
13738 The version of the source that corresponds exactly to the source used
13739 for compilation has been found on the path but it is hidden by another
13740 version of the same source that has been modified.
13744 @node Switches for gnatls
13745 @section Switches for @code{gnatls}
13748 @code{gnatls} recognizes the following switches:
13752 @cindex @code{-a} (@code{gnatls})
13753 Consider all units, including those of the predefined Ada library.
13754 Especially useful with @code{-d}.
13757 @cindex @code{-d} (@code{gnatls})
13758 List sources from which specified units depend on.
13761 @cindex @code{-h} (@code{gnatls})
13762 Output the list of options.
13765 @cindex @code{-o} (@code{gnatls})
13766 Only output information about object files.
13769 @cindex @code{-s} (@code{gnatls})
13770 Only output information about source files.
13773 @cindex @code{-u} (@code{gnatls})
13774 Only output information about compilation units.
13777 @itemx -aI@var{dir}
13781 Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags
13782 (see @ref{Switches for gnatmake}).
13784 @item --RTS=@var{rts-path}
13785 @cindex @code{--RTS} (@code{gnatls})
13786 Specifies the default location of the runtime library. Same meaning as the
13787 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13790 @cindex @code{-s} (@code{gnatls})
13791 Verbose mode. Output the complete source and object paths. Do not use
13792 the default column layout but instead use long format giving as much as
13793 information possible on each requested units, including special
13794 characteristics such as:
13797 @item Preelaborable
13798 The unit is preelaborable in the Ada 95 sense.
13801 No elaboration code has been produced by the compiler for this unit.
13804 The unit is pure in the Ada 95 sense.
13806 @item Elaborate_Body
13807 The unit contains a pragma Elaborate_Body.
13810 The unit contains a pragma Remote_Types.
13812 @item Shared_Passive
13813 The unit contains a pragma Shared_Passive.
13816 This unit is part of the predefined environment and cannot be modified
13819 @item Remote_Call_Interface
13820 The unit contains a pragma Remote_Call_Interface.
13826 @node Examples of gnatls Usage
13827 @section Example of @code{gnatls} Usage
13830 Example of using the verbose switch. Note how the source and
13831 object paths are affected by the -I switch.
13834 $ gnatls -v -I.. demo1.o
13836 GNATLS 3.10w (970212) Copyright 1999 Free Software Foundation, Inc.
13838 Source Search Path:
13839 <Current_Directory>
13841 /home/comar/local/adainclude/
13843 Object Search Path:
13844 <Current_Directory>
13846 /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/
13851 Kind => subprogram body
13852 Flags => No_Elab_Code
13853 Source => demo1.adb modified
13857 The following is an example of use of the dependency list.
13858 Note the use of the -s switch
13859 which gives a straight list of source files. This can be useful for
13860 building specialized scripts.
13863 $ gnatls -d demo2.o
13864 ./demo2.o demo2 OK demo2.adb
13870 $ gnatls -d -s -a demo1.o
13872 /home/comar/local/adainclude/ada.ads
13873 /home/comar/local/adainclude/a-finali.ads
13874 /home/comar/local/adainclude/a-filico.ads
13875 /home/comar/local/adainclude/a-stream.ads
13876 /home/comar/local/adainclude/a-tags.ads
13879 /home/comar/local/adainclude/gnat.ads
13880 /home/comar/local/adainclude/g-io.ads
13882 /home/comar/local/adainclude/system.ads
13883 /home/comar/local/adainclude/s-exctab.ads
13884 /home/comar/local/adainclude/s-finimp.ads
13885 /home/comar/local/adainclude/s-finroo.ads
13886 /home/comar/local/adainclude/s-secsta.ads
13887 /home/comar/local/adainclude/s-stalib.ads
13888 /home/comar/local/adainclude/s-stoele.ads
13889 /home/comar/local/adainclude/s-stratt.ads
13890 /home/comar/local/adainclude/s-tasoli.ads
13891 /home/comar/local/adainclude/s-unstyp.ads
13892 /home/comar/local/adainclude/unchconv.ads
13896 @node GNAT and Libraries
13897 @chapter GNAT and Libraries
13898 @cindex Library, building, installing
13901 This chapter addresses some of the issues related to building and using
13902 a library with GNAT. It also shows how the GNAT run-time library can be
13906 * Creating an Ada Library::
13907 * Installing an Ada Library::
13908 * Using an Ada Library::
13909 * Creating an Ada Library to be Used in a Non-Ada Context::
13910 * Rebuilding the GNAT Run-Time Library::
13913 @node Creating an Ada Library
13914 @section Creating an Ada Library
13917 In the GNAT environment, a library has two components:
13922 Compiled code and Ali files. See @ref{The Ada Library Information Files}.
13926 In order to use other packages @ref{The GNAT Compilation Model}
13927 requires a certain number of sources to be available to the compiler.
13929 sources required includes the specs of all the packages that make up the
13930 visible part of the library as well as all the sources upon which they
13931 depend. The bodies of all visible generic units must also be provided.
13933 Although it is not strictly mandatory, it is recommended that all sources
13934 needed to recompile the library be provided, so that the user can make
13935 full use of inter-unit inlining and source-level debugging. This can also
13936 make the situation easier for users that need to upgrade their compilation
13937 toolchain and thus need to recompile the library from sources.
13940 The compiled code can be provided in different ways. The simplest way is
13941 to provide directly the set of objects produced by the compiler during
13942 the compilation of the library. It is also possible to group the objects
13943 into an archive using whatever commands are provided by the operating
13944 system. Finally, it is also possible to create a shared library (see
13945 option -shared in the GCC manual).
13948 There are various possibilities for compiling the units that make up the
13949 library: for example with a Makefile @ref{Using the GNU make Utility},
13950 or with a conventional script.
13951 For simple libraries, it is also possible to create a
13952 dummy main program which depends upon all the packages that comprise the
13953 interface of the library. This dummy main program can then be given to
13954 gnatmake, in order to build all the necessary objects. Here is an example
13955 of such a dummy program and the generic commands used to build an
13956 archive or a shared library.
13962 @b{with} My_Lib.Service1;
13963 @b{with} My_Lib.Service2;
13964 @b{with} My_Lib.Service3;
13965 @b{procedure} My_Lib_Dummy @b{is}
13970 # compiling the library
13971 $ gnatmake -c my_lib_dummy.adb
13973 # we don't need the dummy object itself
13974 $ rm my_lib_dummy.o my_lib_dummy.ali
13976 # create an archive with the remaining objects
13977 $ ar rc libmy_lib.a *.o
13978 # some systems may require "ranlib" to be run as well
13980 # or create a shared library
13981 $ gcc -shared -o libmy_lib.so *.o
13982 # some systems may require the code to have been compiled with -fPIC
13986 When the objects are grouped in an archive or a shared library, the user
13987 needs to specify the desired library at link time, unless a pragma
13988 linker_options has been used in one of the sources:
13990 @b{pragma} Linker_Options ("-lmy_lib");
13993 @node Installing an Ada Library
13994 @section Installing an Ada Library
13997 In the GNAT model, installing a library consists in copying into a specific
13998 location the files that make up this library. It is possible to install
13999 the sources in a different directory from the other files (ALI, objects,
14000 archives) since the source path and the object path can easily be
14001 specified separately.
14004 For general purpose libraries, it is possible for the system
14005 administrator to put those libraries in the default compiler paths. To
14006 achieve this, he must specify their location in the configuration files
14007 "ada_source_path" and "ada_object_path" that must be located in the GNAT
14008 installation tree at the same place as the gcc spec file. The location of
14009 the gcc spec file can be determined as follows:
14015 The configuration files mentioned above have simple format: each line in them
14016 must contain one unique
14017 directory name. Those names are added to the corresponding path
14018 in their order of appearance in the file. The names can be either absolute
14019 or relative, in the latter case, they are relative to where theses files
14023 "ada_source_path" and "ada_object_path" might actually not be present in a
14024 GNAT installation, in which case, GNAT will look for its run-time library in
14025 the directories "adainclude" for the sources and "adalib" for the
14026 objects and ALI files. When the files exist, the compiler does not
14027 look in "adainclude" and "adalib" at all, and thus the "ada_source_path" file
14028 must contain the location for the GNAT run-time sources (which can simply
14029 be "adainclude"). In the same way, the "ada_object_path" file must contain
14030 the location for the GNAT run-time objects (which can simply
14034 You can also specify a new default path to the runtime library at compilation
14035 time with the switch "--RTS=@var{rts-path}". You can easily choose and change
14036 the runtime you want your program to be compiled with. This switch is
14037 recognized by gcc, gnatmake, gnatbind, gnatls, gnatfind and gnatxref.
14040 It is possible to install a library before or after the standard GNAT
14041 library, by reordering the lines in the configuration files. In general, a
14042 library must be installed before the GNAT library if it redefines any part of it.
14044 @node Using an Ada Library
14045 @section Using an Ada Library
14048 In order to use a Ada library, you need to make sure that this
14049 library is on both your source and object path
14050 @ref{Search Paths and the Run-Time Library (RTL)}
14051 and @ref{Search Paths for gnatbind}. For
14052 instance, you can use the library "mylib" installed in "/dir/my_lib_src"
14053 and "/dir/my_lib_obj" with the following commands:
14056 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
14061 This can be simplified down to the following:
14065 when the following conditions are met:
14068 "/dir/my_lib_src" has been added by the user to the environment
14069 variable "ADA_INCLUDE_PATH", or by the administrator to the file
14072 "/dir/my_lib_obj" has been added by the user to the environment
14073 variable "ADA_OBJECTS_PATH", or by the administrator to the file
14076 a pragma linker_options, as mentioned in @ref{Creating an Ada Library}
14077 as been added to the sources.
14081 @node Creating an Ada Library to be Used in a Non-Ada Context
14082 @section Creating an Ada Library to be Used in a Non-Ada Context
14085 The previous sections detailed how to create and install a library that
14086 was usable from an Ada main program. Using this library in a non-Ada
14087 context is not possible, because the elaboration of the library is
14088 automatically done as part of the main program elaboration.
14090 GNAT also provides the ability to build libraries that can be used both
14091 in an Ada and non-Ada context. This section describes how to build such
14092 a library, and then how to use it from a C program. The method for
14093 interfacing with the library from other languages such as Fortran for
14094 instance remains the same.
14096 @subsection Creating the Library
14099 @item Identify the units representing the interface of the library.
14101 Here is an example of simple library interface:
14104 package Interface is
14106 procedure Do_Something;
14108 procedure Do_Something_Else;
14113 @item Use @code{pragma Export} or @code{pragma Convention} for the
14116 Our package @code{Interface} is then updated as follow:
14118 package Interface is
14120 procedure Do_Something;
14121 pragma Export (C, Do_Something, "do_something");
14123 procedure Do_Something_Else;
14124 pragma Export (C, Do_Something_Else, "do_something_else");
14129 @item Compile all the units composing the library.
14131 @item Bind the library objects.
14133 This step is performed by invoking gnatbind with the @code{-L<prefix>}
14134 switch. @code{gnatbind} will then generate the library elaboration
14135 procedure (named @code{<prefix>init}) and the run-time finalization
14136 procedure (named @code{<prefix>final}).
14139 # generate the binder file in Ada
14140 $ gnatbind -Lmylib interface
14142 # generate the binder file in C
14143 $ gnatbind -C -Lmylib interface
14146 @item Compile the files generated by the binder
14149 $ gcc -c b~interface.adb
14152 @item Create the library;
14154 The procedure is identical to the procedure explained in
14155 @ref{Creating an Ada Library},
14156 except that @file{b~interface.o} needs to be added to
14157 the list of objects.
14160 # create an archive file
14161 $ ar cr libmylib.a b~interface.o <other object files>
14163 # create a shared library
14164 $ gcc -shared -o libmylib.so b~interface.o <other object files>
14167 @item Provide a "foreign" view of the library interface;
14169 The example below shows the content of @code{mylib_interface.h} (note
14170 that there is no rule for the naming of this file, any name can be used)
14172 /* the library elaboration procedure */
14173 extern void mylibinit (void);
14175 /* the library finalization procedure */
14176 extern void mylibfinal (void);
14178 /* the interface exported by the library */
14179 extern void do_something (void);
14180 extern void do_something_else (void);
14184 @subsection Using the Library
14187 Libraries built as explained above can be used from any program, provided
14188 that the elaboration procedures (named @code{mylibinit} in the previous
14189 example) are called before the library services are used. Any number of
14190 libraries can be used simultaneously, as long as the elaboration
14191 procedure of each library is called.
14193 Below is an example of C program that uses our @code{mylib} library.
14196 #include "mylib_interface.h"
14201 /* First, elaborate the library before using it */
14204 /* Main program, using the library exported entities */
14206 do_something_else ();
14208 /* Library finalization at the end of the program */
14215 Note that this same library can be used from an equivalent Ada main
14216 program. In addition, if the libraries are installed as detailed in
14217 @ref{Installing an Ada Library}, it is not necessary to invoke the
14218 library elaboration and finalization routines. The binder will ensure
14219 that this is done as part of the main program elaboration and
14220 finalization phases.
14222 @subsection The Finalization Phase
14225 Invoking any library finalization procedure generated by @code{gnatbind}
14226 shuts down the Ada run time permanently. Consequently, the finalization
14227 of all Ada libraries must be performed at the end of the program. No
14228 call to these libraries nor the Ada run time should be made past the
14229 finalization phase.
14231 @subsection Restrictions in Libraries
14234 The pragmas listed below should be used with caution inside libraries,
14235 as they can create incompatibilities with other Ada libraries:
14237 @item pragma @code{Locking_Policy}
14238 @item pragma @code{Queuing_Policy}
14239 @item pragma @code{Task_Dispatching_Policy}
14240 @item pragma @code{Unreserve_All_Interrupts}
14242 When using a library that contains such pragmas, the user must make sure
14243 that all libraries use the same pragmas with the same values. Otherwise,
14244 a @code{Program_Error} will
14245 be raised during the elaboration of the conflicting
14246 libraries. The usage of these pragmas and its consequences for the user
14247 should therefore be well documented.
14249 Similarly, the traceback in exception occurrences mechanism should be
14250 enabled or disabled in a consistent manner across all libraries.
14251 Otherwise, a Program_Error will be raised during the elaboration of the
14252 conflicting libraries.
14254 If the @code{'Version} and @code{'Body_Version}
14255 attributes are used inside a library, then it is necessary to
14256 perform a @code{gnatbind} step that mentions all ali files in all
14257 libraries, so that version identifiers can be properly computed.
14258 In practice these attributes are rarely used, so this is unlikely
14259 to be a consideration.
14261 @node Rebuilding the GNAT Run-Time Library
14262 @section Rebuilding the GNAT Run-Time Library
14265 It may be useful to recompile the GNAT library in various contexts, the
14266 most important one being the use of partition-wide configuration pragmas
14267 such as Normalize_Scalar. A special Makefile called
14268 @code{Makefile.adalib} is provided to that effect and can be found in
14269 the directory containing the GNAT library. The location of this
14270 directory depends on the way the GNAT environment has been installed and can
14271 be determined by means of the command:
14278 The last entry in the object search path usually contains the
14279 gnat library. This Makefile contains its own documentation and in
14280 particular the set of instructions needed to rebuild a new library and
14283 @node Using the GNU make Utility
14284 @chapter Using the GNU @code{make} Utility
14288 This chapter offers some examples of makefiles that solve specific
14289 problems. It does not explain how to write a makefile (see the GNU make
14290 documentation), nor does it try to replace the @code{gnatmake} utility
14291 (@pxref{The GNAT Make Program gnatmake}).
14293 All the examples in this section are specific to the GNU version of
14294 make. Although @code{make} is a standard utility, and the basic language
14295 is the same, these examples use some advanced features found only in
14299 * Using gnatmake in a Makefile::
14300 * Automatically Creating a List of Directories::
14301 * Generating the Command Line Switches::
14302 * Overcoming Command Line Length Limits::
14305 @node Using gnatmake in a Makefile
14306 @section Using gnatmake in a Makefile
14311 Complex project organizations can be handled in a very powerful way by
14312 using GNU make combined with gnatmake. For instance, here is a Makefile
14313 which allows you to build each subsystem of a big project into a separate
14314 shared library. Such a makefile allows you to significantly reduce the link
14315 time of very big applications while maintaining full coherence at
14316 each step of the build process.
14318 The list of dependencies are handled automatically by
14319 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
14320 the appropriate directories.
14322 Note that you should also read the example on how to automatically
14323 create the list of directories (@pxref{Automatically Creating a List of Directories})
14324 which might help you in case your project has a lot of
14330 @font@heightrm=cmr8
14333 ## This Makefile is intended to be used with the following directory
14335 ## - The sources are split into a series of csc (computer software components)
14336 ## Each of these csc is put in its own directory.
14337 ## Their name are referenced by the directory names.
14338 ## They will be compiled into shared library (although this would also work
14339 ## with static libraries
14340 ## - The main program (and possibly other packages that do not belong to any
14341 ## csc is put in the top level directory (where the Makefile is).
14342 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
14343 ## \_ second_csc (sources) __ lib (will contain the library)
14345 ## Although this Makefile is build for shared library, it is easy to modify
14346 ## to build partial link objects instead (modify the lines with -shared and
14349 ## With this makefile, you can change any file in the system or add any new
14350 ## file, and everything will be recompiled correctly (only the relevant shared
14351 ## objects will be recompiled, and the main program will be re-linked).
14353 # The list of computer software component for your project. This might be
14354 # generated automatically.
14357 # Name of the main program (no extension)
14360 # If we need to build objects with -fPIC, uncomment the following line
14363 # The following variable should give the directory containing libgnat.so
14364 # You can get this directory through 'gnatls -v'. This is usually the last
14365 # directory in the Object_Path.
14368 # The directories for the libraries
14369 # (This macro expands the list of CSC to the list of shared libraries, you
14370 # could simply use the expanded form :
14371 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
14372 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
14374 $@{MAIN@}: objects $@{LIB_DIR@}
14375 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
14376 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
14379 # recompile the sources
14380 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
14382 # Note: In a future version of GNAT, the following commands will be simplified
14383 # by a new tool, gnatmlib
14385 mkdir -p $@{dir $@@ @}
14386 cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
14387 cd $@{dir $@@ @}; cp -f ../*.ali .
14389 # The dependencies for the modules
14390 # Note that we have to force the expansion of *.o, since in some cases make won't
14391 # be able to do it itself.
14392 aa/lib/libaa.so: $@{wildcard aa/*.o@}
14393 bb/lib/libbb.so: $@{wildcard bb/*.o@}
14394 cc/lib/libcc.so: $@{wildcard cc/*.o@}
14396 # Make sure all of the shared libraries are in the path before starting the
14399 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
14402 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
14403 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
14404 $@{RM@} $@{CSC_LIST:%=%/*.o@}
14405 $@{RM@} *.o *.ali $@{MAIN@}
14408 @node Automatically Creating a List of Directories
14409 @section Automatically Creating a List of Directories
14412 In most makefiles, you will have to specify a list of directories, and
14413 store it in a variable. For small projects, it is often easier to
14414 specify each of them by hand, since you then have full control over what
14415 is the proper order for these directories, which ones should be
14418 However, in larger projects, which might involve hundreds of
14419 subdirectories, it might be more convenient to generate this list
14422 The example below presents two methods. The first one, although less
14423 general, gives you more control over the list. It involves wildcard
14424 characters, that are automatically expanded by @code{make}. Its
14425 shortcoming is that you need to explicitly specify some of the
14426 organization of your project, such as for instance the directory tree
14427 depth, whether some directories are found in a separate tree,...
14429 The second method is the most general one. It requires an external
14430 program, called @code{find}, which is standard on all Unix systems. All
14431 the directories found under a given root directory will be added to the
14437 @font@heightrm=cmr8
14440 # The examples below are based on the following directory hierarchy:
14441 # All the directories can contain any number of files
14442 # ROOT_DIRECTORY -> a -> aa -> aaa
14445 # -> b -> ba -> baa
14448 # This Makefile creates a variable called DIRS, that can be reused any time
14449 # you need this list (see the other examples in this section)
14451 # The root of your project's directory hierarchy
14455 # First method: specify explicitly the list of directories
14456 # This allows you to specify any subset of all the directories you need.
14459 DIRS := a/aa/ a/ab/ b/ba/
14462 # Second method: use wildcards
14463 # Note that the argument(s) to wildcard below should end with a '/'.
14464 # Since wildcards also return file names, we have to filter them out
14465 # to avoid duplicate directory names.
14466 # We thus use make's @code{dir} and @code{sort} functions.
14467 # It sets DIRs to the following value (note that the directories aaa and baa
14468 # are not given, unless you change the arguments to wildcard).
14469 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
14472 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/ $@{ROOT_DIRECTORY@}/*/*/@}@}@}
14475 # Third method: use an external program
14476 # This command is much faster if run on local disks, avoiding NFS slowdowns.
14477 # This is the most complete command: it sets DIRs to the following value:
14478 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
14481 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
14485 @node Generating the Command Line Switches
14486 @section Generating the Command Line Switches
14489 Once you have created the list of directories as explained in the
14490 previous section (@pxref{Automatically Creating a List of Directories}),
14491 you can easily generate the command line arguments to pass to gnatmake.
14493 For the sake of completeness, this example assumes that the source path
14494 is not the same as the object path, and that you have two separate lists
14498 # see "Automatically creating a list of directories" to create
14503 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
14504 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
14507 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
14510 @node Overcoming Command Line Length Limits
14511 @section Overcoming Command Line Length Limits
14514 One problem that might be encountered on big projects is that many
14515 operating systems limit the length of the command line. It is thus hard to give
14516 gnatmake the list of source and object directories.
14518 This example shows how you can set up environment variables, which will
14519 make @code{gnatmake} behave exactly as if the directories had been
14520 specified on the command line, but have a much higher length limit (or
14521 even none on most systems).
14523 It assumes that you have created a list of directories in your Makefile,
14524 using one of the methods presented in
14525 @ref{Automatically Creating a List of Directories}.
14526 For the sake of completeness, we assume that the object
14527 path (where the ALI files are found) is different from the sources patch.
14529 Note a small trick in the Makefile below: for efficiency reasons, we
14530 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
14531 expanded immediately by @code{make}. This way we overcome the standard
14532 make behavior which is to expand the variables only when they are
14538 @font@heightrm=cmr8
14541 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
14542 # This is the same thing as putting the -I arguments on the command line.
14543 # (the equivalent of using -aI on the command line would be to define
14544 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
14545 # You can of course have different values for these variables.
14547 # Note also that we need to keep the previous values of these variables, since
14548 # they might have been set before running 'make' to specify where the GNAT
14549 # library is installed.
14551 # see "Automatically creating a list of directories" to create these
14557 space:=$@{empty@} $@{empty@}
14558 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
14559 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
14560 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
14561 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
14562 export ADA_INCLUDE_PATH
14563 export ADA_OBJECT_PATH
14569 @node Finding Memory Problems with gnatmem
14570 @chapter Finding Memory Problems with @code{gnatmem}
14574 @code{gnatmem}, is a tool that monitors dynamic allocation and
14575 deallocation activity in a program, and displays information about
14576 incorrect deallocations and possible sources of memory leaks. Gnatmem
14577 provides three type of information:
14580 General information concerning memory management, such as the total
14581 number of allocations and deallocations, the amount of allocated
14582 memory and the high water mark, i.e. the largest amount of allocated
14583 memory in the course of program execution.
14586 Backtraces for all incorrect deallocations, that is to say deallocations
14587 which do not correspond to a valid allocation.
14590 Information on each allocation that is potentially the origin of a memory
14594 The @code{gnatmem} command has two modes. It can be used with @code{gdb}
14595 or with instrumented allocation and deallocation routines. The later
14596 mode is called the @code{GMEM} mode. Both modes produce the very same
14600 * Running gnatmem (GDB Mode)::
14601 * Running gnatmem (GMEM Mode)::
14602 * Switches for gnatmem::
14603 * Examples of gnatmem Usage::
14604 * GDB and GMEM Modes::
14605 * Implementation Note::
14608 @node Running gnatmem (GDB Mode)
14609 @section Running @code{gnatmem} (GDB Mode)
14612 The @code{gnatmem} command has the form
14615 $ gnatmem [-q] [n] [-o file] user_program [program_arg]*
14617 $ gnatmem [-q] [n] -i file
14621 Gnatmem must be supplied with the executable to examine, followed by its
14622 run-time inputs. For example, if a program is executed with the command:
14624 $ my_program arg1 arg2
14626 then it can be run under @code{gnatmem} control using the command:
14628 $ gnatmem my_program arg1 arg2
14631 The program is transparently executed under the control of the debugger
14632 @ref{The GNAT Debugger GDB}. This does not affect the behavior
14633 of the program, except for sensitive real-time programs. When the program
14634 has completed execution, @code{gnatmem} outputs a report containing general
14635 allocation/deallocation information and potential memory leak.
14636 For better results, the user program should be compiled with
14637 debugging options @ref{Switches for gcc}.
14639 Here is a simple example of use:
14641 *************** debut cc
14647 Total number of allocations : 45
14648 Total number of deallocations : 6
14649 Final Water Mark (non freed mem) : 11.29 Kilobytes
14650 High Water Mark : 11.40 Kilobytes
14655 Allocation Root # 2
14656 -------------------
14657 Number of non freed allocations : 11
14658 Final Water Mark (non freed mem) : 1.16 Kilobytes
14659 High Water Mark : 1.27 Kilobytes
14661 test_gm.adb:23 test_gm.alloc
14667 The first block of output give general information. In this case, the
14668 Ada construct "@b{new}" was executed 45 times, and only 6 calls to an
14669 unchecked deallocation routine occurred.
14671 Subsequent paragraphs display information on all allocation roots.
14672 An allocation root is a specific point in the execution of the program
14673 that generates some dynamic allocation, such as a "@b{new}" construct. This
14674 root is represented by an execution backtrace (or subprogram call
14675 stack). By default the backtrace depth for allocations roots is 1, so
14676 that a root corresponds exactly to a source location. The backtrace can
14677 be made deeper, to make the root more specific.
14679 @node Running gnatmem (GMEM Mode)
14680 @section Running @code{gnatmem} (GMEM Mode)
14681 @cindex @code{GMEM} (@code{gnatmem})
14684 The @code{gnatmem} command has the form
14687 $ gnatmem [-q] [n] -i gmem.out user_program [program_arg]*
14690 The program must have been linked with the instrumented version of the
14691 allocation and deallocation routines. This is done with linking with the
14692 @file{libgmem.a} library. For better results, the user program should be
14693 compiled with debugging options @ref{Switches for gcc}. For example to
14694 build @file{my_program}:
14697 $ gnatmake -g my_program -largs -lgmem
14701 When running @file{my_program} the file @file{gmem.out} is produced. This file
14702 contains information about all allocations and deallocations done by the
14703 program. It is produced by the instrumented allocations and
14704 deallocations routines and will be used by @code{gnatmem}.
14707 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
14708 examine followed by its run-time inputs. For example, if a program is
14709 executed with the command:
14711 $ my_program arg1 arg2
14713 then @file{gmem.out} can be analysed by @code{gnatmem} using the command:
14715 $ gnatmem -i gmem.out my_program arg1 arg2
14718 @node Switches for gnatmem
14719 @section Switches for @code{gnatmem}
14722 @code{gnatmem} recognizes the following switches:
14727 @cindex @code{-q} (@code{gnatmem})
14728 Quiet. Gives the minimum output needed to identify the origin of the
14729 memory leaks. Omit statistical information.
14732 @cindex @code{n} (@code{gnatmem})
14733 N is an integer literal (usually between 1 and 10) which controls the
14734 depth of the backtraces defining allocation root. The default value for
14735 N is 1. The deeper the backtrace, the more precise the localization of
14736 the root. Note that the total number of roots can depend on this
14739 @item @code{-o file}
14740 @cindex @code{-o} (@code{gnatmem})
14741 Direct the gdb output to the specified file. The @code{gdb} script used
14742 to generate this output is also saved in the file @file{gnatmem.tmp}.
14744 @item @code{-i file}
14745 @cindex @code{-i} (@code{gnatmem})
14746 Do the @code{gnatmem} processing starting from @file{file} which has
14747 been generated by a previous call to @code{gnatmem} with the -o
14748 switch or @file{gmem.out} produced by @code{GMEM} mode. This is useful
14749 for post mortem processing.
14753 @node Examples of gnatmem Usage
14754 @section Example of @code{gnatmem} Usage
14757 This section is based on the @code{GDB} mode of @code{gnatmem}. The same
14758 results can be achieved using @code{GMEM} mode. See section
14759 @ref{Running gnatmem (GMEM Mode)}.
14762 The first example shows the use of @code{gnatmem}
14763 on a simple leaking program.
14764 Suppose that we have the following Ada program:
14769 @b{with} Unchecked_Deallocation;
14770 @b{procedure} Test_Gm @b{is}
14772 @b{type} T @b{is array} (1..1000) @b{of} Integer;
14773 @b{type} Ptr @b{is access} T;
14774 @b{procedure} Free @b{is new} Unchecked_Deallocation (T, Ptr);
14777 @b{procedure} My_Alloc @b{is}
14782 @b{procedure} My_DeAlloc @b{is}
14786 @b{end} My_DeAlloc;
14790 @b{for} I @b{in} 1 .. 5 @b{loop}
14791 @b{for} J @b{in} I .. 5 @b{loop}
14802 The program needs to be compiled with debugging option:
14805 $ gnatmake -g test_gm
14808 @code{gnatmem} is invoked simply with
14814 which produces the following output:
14819 Total number of allocations : 18
14820 Total number of deallocations : 5
14821 Final Water Mark (non freed mem) : 53.00 Kilobytes
14822 High Water Mark : 56.90 Kilobytes
14824 Allocation Root # 1
14825 -------------------
14826 Number of non freed allocations : 11
14827 Final Water Mark (non freed mem) : 42.97 Kilobytes
14828 High Water Mark : 46.88 Kilobytes
14830 test_gm.adb:11 test_gm.my_alloc
14832 Allocation Root # 2
14833 -------------------
14834 Number of non freed allocations : 1
14835 Final Water Mark (non freed mem) : 10.02 Kilobytes
14836 High Water Mark : 10.02 Kilobytes
14838 s-secsta.adb:81 system.secondary_stack.ss_init
14840 Allocation Root # 3
14841 -------------------
14842 Number of non freed allocations : 1
14843 Final Water Mark (non freed mem) : 12 Bytes
14844 High Water Mark : 12 Bytes
14846 s-secsta.adb:181 system.secondary_stack.ss_init
14850 Note that the GNAT run time contains itself a certain number of
14851 allocations that have no corresponding deallocation,
14852 as shown here for root #2 and root
14853 #1. This is a normal behavior when the number of non freed allocations
14854 is one, it locates dynamic data structures that the run time needs for
14855 the complete lifetime of the program. Note also that there is only one
14856 allocation root in the user program with a single line back trace:
14857 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
14858 program shows that 'My_Alloc' is called at 2 different points in the
14859 source (line 21 and line 24). If those two allocation roots need to be
14860 distinguished, the backtrace depth parameter can be used:
14863 $ gnatmem 3 test_gm
14867 which will give the following output:
14872 Total number of allocations : 18
14873 Total number of deallocations : 5
14874 Final Water Mark (non freed mem) : 53.00 Kilobytes
14875 High Water Mark : 56.90 Kilobytes
14877 Allocation Root # 1
14878 -------------------
14879 Number of non freed allocations : 10
14880 Final Water Mark (non freed mem) : 39.06 Kilobytes
14881 High Water Mark : 42.97 Kilobytes
14883 test_gm.adb:11 test_gm.my_alloc
14884 test_gm.adb:24 test_gm
14885 b_test_gm.c:52 main
14887 Allocation Root # 2
14888 -------------------
14889 Number of non freed allocations : 1
14890 Final Water Mark (non freed mem) : 10.02 Kilobytes
14891 High Water Mark : 10.02 Kilobytes
14893 s-secsta.adb:81 system.secondary_stack.ss_init
14894 s-secsta.adb:283 <system__secondary_stack___elabb>
14895 b_test_gm.c:33 adainit
14897 Allocation Root # 3
14898 -------------------
14899 Number of non freed allocations : 1
14900 Final Water Mark (non freed mem) : 3.91 Kilobytes
14901 High Water Mark : 3.91 Kilobytes
14903 test_gm.adb:11 test_gm.my_alloc
14904 test_gm.adb:21 test_gm
14905 b_test_gm.c:52 main
14907 Allocation Root # 4
14908 -------------------
14909 Number of non freed allocations : 1
14910 Final Water Mark (non freed mem) : 12 Bytes
14911 High Water Mark : 12 Bytes
14913 s-secsta.adb:181 system.secondary_stack.ss_init
14914 s-secsta.adb:283 <system__secondary_stack___elabb>
14915 b_test_gm.c:33 adainit
14919 The allocation root #1 of the first example has been split in 2 roots #1
14920 and #3 thanks to the more precise associated backtrace.
14922 @node GDB and GMEM Modes
14923 @section GDB and GMEM Modes
14926 The main advantage of the @code{GMEM} mode is that it is a lot faster than the
14927 @code{GDB} mode where the application must be monitored by a @code{GDB} script.
14928 But the @code{GMEM} mode is available only for DEC Unix, Linux x86,
14929 Solaris (sparc and x86) and Windows 95/98/NT/2000 (x86).
14932 The main advantage of the @code{GDB} mode is that it is available on all
14933 supported platforms. But it can be very slow if the application does a
14934 lot of allocations and deallocations.
14936 @node Implementation Note
14937 @section Implementation Note
14940 * gnatmem Using GDB Mode::
14941 * gnatmem Using GMEM Mode::
14944 @node gnatmem Using GDB Mode
14945 @subsection @code{gnatmem} Using @code{GDB} Mode
14948 @code{gnatmem} executes the user program under the control of @code{GDB} using
14949 a script that sets breakpoints and gathers information on each dynamic
14950 allocation and deallocation. The output of the script is then analyzed
14952 in order to locate memory leaks and their origin in the
14953 program. Gnatmem works by recording each address returned by the
14954 allocation procedure (@code{__gnat_malloc})
14955 along with the backtrace at the
14956 allocation point. On each deallocation, the deallocated address is
14957 matched with the corresponding allocation. At the end of the processing,
14958 the unmatched allocations are considered potential leaks. All the
14959 allocations associated with the same backtrace are grouped together and
14960 form an allocation root. The allocation roots are then sorted so that
14961 those with the biggest number of unmatched allocation are printed
14962 first. A delicate aspect of this technique is to distinguish between the
14963 data produced by the user program and the data produced by the gdb
14964 script. Currently, on systems that allow probing the terminal, the gdb
14965 command "tty" is used to force the program output to be redirected to the
14966 current terminal while the @code{gdb} output is directed to a file or to a
14967 pipe in order to be processed subsequently by @code{gnatmem}.
14969 @node gnatmem Using GMEM Mode
14970 @subsection @code{gnatmem} Using @code{GMEM} Mode
14973 This mode use the same algorithm to detect memory leak as the @code{GDB}
14974 mode of @code{gnatmem}, the only difference is in the way data are
14975 gathered. In @code{GMEM} mode the program is linked with instrumented
14976 version of @code{__gnat_malloc} and @code{__gnat_free}
14977 routines. Information needed to find memory leak are recorded by these
14978 routines in file @file{gmem.out}. This mode also require that the stack
14979 traceback be available, this is only implemented on some platforms
14980 @ref{GDB and GMEM Modes}.
14983 @node Finding Memory Problems with GNAT Debug Pool
14984 @chapter Finding Memory Problems with GNAT Debug Pool
14986 @cindex storage, pool, memory corruption
14989 The use of unchecked deallocation and unchecked conversion can easily
14990 lead to incorrect memory references. The problems generated by such
14991 references are usually difficult to tackle because the symptoms can be
14992 very remote from the origin of the problem. In such cases, it is
14993 very helpful to detect the problem as early as possible. This is the
14994 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
14997 In order to use the GNAT specific debugging pool, the user must
14998 associate a debug pool object with each of the access types that may be
14999 related to suspected memory problems. See Ada Reference Manual
15002 @b{type} Ptr @b{is} @b{access} Some_Type;
15003 Pool : GNAT.Debug_Pools.Debug_Pool;
15004 @b{for} Ptr'Storage_Pool @b{use} Pool;
15007 @code{GNAT.Debug_Pools} is derived from of a GNAT-specific kind of
15008 pool: the Checked_Pool. Such pools, like standard Ada storage pools,
15009 allow the user to redefine allocation and deallocation strategies. They
15010 also provide a checkpoint for each dereference, through the use of
15011 the primitive operation @code{Dereference} which is implicitly called at
15012 each dereference of an access value.
15014 Once an access type has been associated with a debug pool, operations on
15015 values of the type may raise four distinct exceptions,
15016 which correspond to four potential kinds of memory corruption:
15019 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
15021 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
15023 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
15025 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
15029 For types associated with a Debug_Pool, dynamic allocation is performed using
15031 GNAT allocation routine. References to all allocated chunks of memory
15032 are kept in an internal dictionary. The deallocation strategy consists
15033 in not releasing the memory to the underlying system but rather to fill
15034 it with a memory pattern easily recognizable during debugging sessions:
15035 The memory pattern is the old IBM hexadecimal convention: 16#DEADBEEF#.
15036 Upon each dereference, a check is made that the access value denotes a properly
15037 allocated memory location. Here is a complete example of use of
15038 @code{Debug_Pools}, that includes typical instances of memory corruption:
15043 @b{with} Gnat.Io; @b{use} Gnat.Io;
15044 @b{with} Unchecked_Deallocation;
15045 @b{with} Unchecked_Conversion;
15046 @b{with} GNAT.Debug_Pools;
15047 @b{with} System.Storage_Elements;
15048 @b{with} Ada.Exceptions; @b{use} Ada.Exceptions;
15049 @b{procedure} Debug_Pool_Test @b{is}
15051 @b{type} T @b{is} @b{access} Integer;
15052 @b{type} U @b{is} @b{access} @b{all} T;
15054 P : GNAT.Debug_Pools.Debug_Pool;
15055 @b{for} T'Storage_Pool @b{use} P;
15057 @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (Integer, T);
15058 @b{function} UC @b{is} @b{new} Unchecked_Conversion (U, T);
15059 A, B : @b{aliased} T;
15061 @b{procedure} Info @b{is} @b{new} GNAT.Debug_Pools.Print_Info(Put_Line);
15065 A := @b{new} Integer;
15066 B := @b{new} Integer;
15071 Put_Line (Integer'Image(B.@b{all}));
15073 @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
15078 @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
15082 Put_Line (Integer'Image(B.@b{all}));
15084 @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
15089 @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
15092 @b{end} Debug_Pool_Test;
15095 The debug pool mechanism provides the following precise diagnostics on the
15096 execution of this erroneous program:
15099 Total allocated bytes : 0
15100 Total deallocated bytes : 0
15101 Current Water Mark: 0
15105 Total allocated bytes : 8
15106 Total deallocated bytes : 0
15107 Current Water Mark: 8
15110 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
15111 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
15112 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
15113 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
15115 Total allocated bytes : 8
15116 Total deallocated bytes : 4
15117 Current Water Mark: 4
15122 @node Creating Sample Bodies Using gnatstub
15123 @chapter Creating Sample Bodies Using @code{gnatstub}
15127 @code{gnatstub} creates body stubs, that is, empty but compilable bodies
15128 for library unit declarations.
15130 To create a body stub, @code{gnatstub} has to compile the library
15131 unit declaration. Therefore, bodies can be created only for legal
15132 library units. Moreover, if a library unit depends semantically upon
15133 units located outside the current directory, you have to provide
15134 the source search path when calling @code{gnatstub}, see the description
15135 of @code{gnatstub} switches below.
15138 * Running gnatstub::
15139 * Switches for gnatstub::
15142 @node Running gnatstub
15143 @section Running @code{gnatstub}
15146 @code{gnatstub} has the command-line interface of the form
15149 $ gnatstub [switches] filename [directory]
15156 is the name of the source file that contains a library unit declaration
15157 for which a body must be created. This name should follow the GNAT file name
15158 conventions. No crunching is allowed for this file name. The file
15159 name may contain the path information.
15162 indicates the directory to place a body stub (default is the
15166 is an optional sequence of switches as described in the next section
15169 @node Switches for gnatstub
15170 @section Switches for @code{gnatstub}
15175 If the destination directory already contains a file with a name of the body file
15176 for the argument spec file, replace it with the generated body stub.
15179 Put the comment header (i.e. all the comments preceding the
15180 compilation unit) from the source of the library unit declaration
15181 into the body stub.
15184 Put a sample comment header into the body stub.
15188 These switches have the same meaning as in calls to gcc.
15189 They define the source search path in the call to gcc issued
15190 by @code{gnatstub} to compile an argument source file.
15193 (@var{n} is a decimal natural number). Set the indentation level in the
15194 generated body sample to n, '-i0' means "no indentation",
15195 the default indentation is 3.
15198 Do not remove the tree file (i.e. the snapshot of the compiler internal
15199 structures used by @code{gnatstub}) after creating the body stub.
15202 (@var{n} is a decimal positive number) Set the maximum line length in the
15203 body stub to n, the default is 78.
15206 Quiet mode: do not generate a confirmation when a body is
15207 successfully created or a message when a body is not required for an
15211 Reuse the tree file (if it exists) instead of creating it: instead of
15212 creating the tree file for the library unit declaration, gnatstub
15213 tries to find it in the current directory and use it for creating
15214 a body. If the tree file is not found, no body is created. @code{-r}
15215 also implies @code{-k}, whether or not
15216 @code{-k} is set explicitly.
15219 Overwrite the existing tree file: if the current directory already
15220 contains the file which, according to the GNAT file name rules should
15221 be considered as a tree file for the argument source file, gnatstub
15222 will refuse to create the tree file needed to create a body sampler,
15223 unless @code{-t} option is set
15226 Verbose mode: generate version information.
15230 @node Reducing the Size of Ada Executables with gnatelim
15231 @chapter Reducing the Size of Ada Executables with @code{gnatelim}
15236 * Eliminate Pragma::
15238 * Preparing Tree and Bind Files for gnatelim::
15239 * Running gnatelim::
15240 * Correcting the List of Eliminate Pragmas::
15241 * Making Your Executables Smaller::
15242 * Summary of the gnatelim Usage Cycle::
15245 @node About gnatelim
15246 @section About @code{gnatelim}
15249 When a program shares a set of Ada
15250 packages with other programs, it may happen that this program uses
15251 only a fraction of the subprograms defined in these packages. The code
15252 created for these unused subprograms increases the size of the executable.
15254 @code{gnatelim} tracks unused subprograms in an Ada program and
15255 outputs a list of GNAT-specific @code{Eliminate} pragmas (see next
15256 section) marking all the subprograms that are declared but never called.
15257 By placing the list of @code{Eliminate} pragmas in the GNAT configuration
15258 file @file{gnat.adc} and recompiling your program, you may decrease the
15259 size of its executable, because the compiler will not generate the code
15260 for 'eliminated' subprograms.
15262 @code{gnatelim} needs as its input data a set of tree files
15263 (see @ref{Tree Files}) representing all the components of a program to
15264 process and a bind file for a main subprogram (see
15265 @ref{Preparing Tree and Bind Files for gnatelim}).
15267 @node Eliminate Pragma
15268 @section @code{Eliminate} Pragma
15272 The simplified syntax of the Eliminate pragma used by @code{gnatelim} is:
15276 @b{pragma} Eliminate (Library_Unit_Name, Subprogram_Name);
15283 @item Library_Unit_Name
15284 full expanded Ada name of a library unit
15286 @item Subprogram_Name
15287 a simple or expanded name of a subprogram declared within this
15293 The effect of an @code{Eliminate} pragma placed in the GNAT configuration
15294 file @file{gnat.adc} is:
15299 If the subprogram @code{Subprogram_Name} is declared within
15300 the library unit @code{Library_Unit_Name}, the compiler will not generate
15301 code for this subprogram. This applies to all overloaded subprograms denoted
15302 by @code{Subprogram_Name}.
15305 If a subprogram marked by the pragma @code{Eliminate} is used (called)
15306 in a program, the compiler will produce an error message in the place where
15311 @section Tree Files
15315 A tree file stores a snapshot of the compiler internal data
15316 structures at the very end of a successful compilation. It contains all the
15317 syntactic and semantic information for the compiled unit and all the
15318 units upon which it depends semantically.
15319 To use tools that make use of tree files, you
15320 need to first produce the right set of tree files.
15322 GNAT produces correct tree files when -gnatt -gnatc options are set
15323 in a gcc call. The tree files have an .adt extension.
15324 Therefore, to produce a tree file for the compilation unit contained in a file
15325 named @file{foo.adb}, you must use the command
15328 $ gcc -c -gnatc -gnatt foo.adb
15332 and you will get the tree file @file{foo.adt}.
15335 @node Preparing Tree and Bind Files for gnatelim
15336 @section Preparing Tree and Bind Files for @code{gnatelim}
15339 A set of tree files covering the program to be analyzed with
15340 @code{gnatelim} and
15341 the bind file for the main subprogram does not have to
15342 be in the current directory.
15343 '-T' gnatelim option may be used to provide
15344 the search path for tree files, and '-b'
15345 option may be used to point to the bind
15346 file to process (see @ref{Running gnatelim})
15348 If you do not have the appropriate set of tree
15349 files and the right bind file, you
15350 may create them in the current directory using the following procedure.
15352 Let @code{Main_Prog} be the name of a main subprogram, and suppose
15353 this subprogram is in a file named @file{main_prog.adb}.
15355 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
15356 the main subprogram. @code{gnatelim} can work with both Ada and C
15357 bind files; when both are present, it uses the Ada bind file.
15358 The following commands will build the program and create the bind file:
15361 $ gnatmake -c Main_Prog
15362 $ gnatbind main_prog
15366 To create a minimal set of tree files covering the whole program, call
15367 @code{gnatmake} for this program as follows:
15370 $ gnatmake -f -c -gnatc -gnatt Main_Prog
15374 The @code{-c} gnatmake option turns off the bind and link
15375 steps, that are useless anyway because the sources are compiled with
15376 @option{-gnatc} option which turns off code generation.
15378 The @code{-f} gnatmake option forces
15379 recompilation of all the needed sources.
15381 This sequence of actions will create all the data needed by @code{gnatelim}
15382 from scratch and therefore guarantee its consistency. If you would like to
15383 use some existing set of files as @code{gnatelim} output, you must make
15384 sure that the set of files is complete and consistent. You can use the
15385 @code{-m} switch to check if there are missed tree files
15387 Note, that @code{gnatelim} needs neither object nor ALI files.
15389 @node Running gnatelim
15390 @section Running @code{gnatelim}
15393 @code{gnatelim} has the following command-line interface:
15396 $ gnatelim [options] name
15400 @code{name} should be a full expanded Ada name of a main subprogram
15401 of a program (partition).
15403 @code{gnatelim} options:
15407 Quiet mode: by default @code{gnatelim} generates to the standard error
15408 stream a trace of the source file names of the compilation units being
15409 processed. This option turns this trace off.
15412 Verbose mode: @code{gnatelim} version information is printed as Ada
15413 comments to the standard output stream.
15416 Also look for subprograms from the GNAT run time that can be eliminated.
15419 Check if any tree files are missing for an accurate result.
15422 When looking for tree files also look in directory @var{dir}
15424 @item -b@var{bind_file}
15425 Specifies @var{bind_file} as the bind file to process. If not set, the name
15426 of the bind file is computed from the full expanded Ada name of a main subprogram.
15429 Activate internal debugging switches. @var{x} is a letter or digit, or
15430 string of letters or digits, which specifies the type of debugging
15431 mode desired. Normally these are used only for internal development
15432 or system debugging purposes. You can find full documentation for these
15433 switches in the body of the @code{Gnatelim.Options} unit in the compiler
15434 source file @file{gnatelim-options.adb}.
15438 @code{gnatelim} sends its output to the standard output stream, and all the
15439 tracing and debug information is sent to the standard error stream.
15440 In order to produce a proper GNAT configuration file
15441 @file{gnat.adc}, redirection must be used:
15444 $ gnatelim Main_Prog > gnat.adc
15451 $ gnatelim Main_Prog >> gnat.adc
15455 In order to append the @code{gnatelim} output to the existing contents of
15458 @node Correcting the List of Eliminate Pragmas
15459 @section Correcting the List of Eliminate Pragmas
15462 In some rare cases it may happen that @code{gnatelim} will try to eliminate
15463 subprograms which are actually called in the program. In this case, the
15464 compiler will generate an error message of the form:
15467 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
15471 You will need to manually remove the wrong @code{Eliminate} pragmas from
15472 the @file{gnat.adc} file. It is advised that you recompile your program
15473 from scratch after that because you need a consistent @file{gnat.adc} file
15474 during the entire compilation.
15476 @node Making Your Executables Smaller
15477 @section Making Your Executables Smaller
15480 In order to get a smaller executable for your program you now have to
15481 recompile the program completely with the new @file{gnat.adc} file
15482 created by @code{gnatelim} in your current directory:
15485 $ gnatmake -f Main_Prog
15489 (you will need @code{-f} option for gnatmake to
15490 recompile everything
15491 with the set of pragmas @code{Eliminate} you have obtained with
15494 Be aware that the set of @code{Eliminate} pragmas is specific to each
15495 program. It is not recommended to merge sets of @code{Eliminate}
15496 pragmas created for different programs in one @file{gnat.adc} file.
15498 @node Summary of the gnatelim Usage Cycle
15499 @section Summary of the gnatelim Usage Cycle
15502 Here is a quick summary of the steps to be taken in order to reduce
15503 the size of your executables with @code{gnatelim}. You may use
15504 other GNAT options to control the optimization level,
15505 to produce the debugging information, to set search path, etc.
15509 Produce a bind file and a set of tree files
15512 $ gnatmake -c Main_Prog
15513 $ gnatbind main_prog
15514 $ gnatmake -f -c -gnatc -gnatt Main_Prog
15518 Generate a list of @code{Eliminate} pragmas
15520 $ gnatelim Main_Prog >[>] gnat.adc
15524 Recompile the application
15527 $ gnatmake -f Main_Prog
15532 @node Other Utility Programs
15533 @chapter Other Utility Programs
15536 This chapter discusses some other utility programs available in the Ada
15540 * Using Other Utility Programs with GNAT::
15541 * The gnatpsta Utility Program::
15542 * The External Symbol Naming Scheme of GNAT::
15543 * Ada Mode for Glide::
15544 * Converting Ada Files to html with gnathtml::
15545 * Installing gnathtml::
15548 @node Using Other Utility Programs with GNAT
15549 @section Using Other Utility Programs with GNAT
15552 The object files generated by GNAT are in standard system format and in
15553 particular the debugging information uses this format. This means
15554 programs generated by GNAT can be used with existing utilities that
15555 depend on these formats.
15557 In general, any utility program that works with C will also often work with
15558 Ada programs generated by GNAT. This includes software utilities such as
15559 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
15562 @node The gnatpsta Utility Program
15563 @section The @code{gnatpsta} Utility Program
15566 Many of the definitions in package Standard are implementation-dependent.
15567 However, the source of this package does not exist as an Ada source
15568 file, so these values cannot be determined by inspecting the source.
15569 They can be determined by examining in detail the coding of
15570 @file{cstand.adb} which creates the image of Standard in the compiler,
15571 but this is awkward and requires a great deal of internal knowledge
15574 The @code{gnatpsta} utility is designed to deal with this situation.
15575 It is an Ada program that dynamically determines the
15576 values of all the relevant parameters in Standard, and prints them
15577 out in the form of an Ada source listing for Standard, displaying all
15578 the values of interest. This output is generated to
15581 To determine the value of any parameter in package Standard, simply
15582 run @code{gnatpsta} with no qualifiers or arguments, and examine
15583 the output. This is preferable to consulting documentation, because
15584 you know that the values you are getting are the actual ones provided
15585 by the executing system.
15587 @node The External Symbol Naming Scheme of GNAT
15588 @section The External Symbol Naming Scheme of GNAT
15591 In order to interpret the output from GNAT, when using tools that are
15592 originally intended for use with other languages, it is useful to
15593 understand the conventions used to generate link names from the Ada
15596 All link names are in all lowercase letters. With the exception of library
15597 procedure names, the mechanism used is simply to use the full expanded
15598 Ada name with dots replaced by double underscores. For example, suppose
15599 we have the following package spec:
15604 @b{package} QRS @b{is}
15612 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
15613 the corresponding link name is @code{qrs__mn}.
15615 Of course if a @code{pragma Export} is used this may be overridden:
15620 @b{package} Exports @b{is}
15622 @b{pragma} Export (Var1, C, External_Name => "var1_name");
15624 @b{pragma} Export (Var2, C, Link_Name => "var2_link_name");
15631 In this case, the link name for @var{Var1} is whatever link name the
15632 C compiler would assign for the C function @var{var1_name}. This typically
15633 would be either @var{var1_name} or @var{_var1_name}, depending on operating
15634 system conventions, but other possibilities exist. The link name for
15635 @var{Var2} is @var{var2_link_name}, and this is not operating system
15639 One exception occurs for library level procedures. A potential ambiguity
15640 arises between the required name @code{_main} for the C main program,
15641 and the name we would otherwise assign to an Ada library level procedure
15642 called @code{Main} (which might well not be the main program).
15644 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
15645 names. So if we have a library level procedure such as
15650 @b{procedure} Hello (S : String);
15656 the external name of this procedure will be @var{_ada_hello}.
15658 @node Ada Mode for Glide
15659 @section Ada Mode for @code{Glide}
15662 The Glide mode for programming in Ada (both, Ada83 and Ada95) helps the
15663 user in understanding existing code and facilitates writing new code. It
15664 furthermore provides some utility functions for easier integration of
15665 standard Emacs features when programming in Ada.
15667 @subsection General Features:
15671 Full Integrated Development Environment :
15675 support of 'project files' for the configuration (directories,
15676 compilation options,...)
15679 compiling and stepping through error messages.
15682 running and debugging your applications within Glide.
15686 easy to use for beginners by pull-down menus,
15689 user configurable by many user-option variables.
15692 @subsection Ada Mode Features That Help Understanding Code:
15696 functions for easy and quick stepping through Ada code,
15699 getting cross reference information for identifiers (e.g. find the
15700 defining place by a keystroke),
15703 displaying an index menu of types and subprograms and move point to
15707 automatic color highlighting of the various entities in Ada code.
15710 @subsection Glide Support for Writing Ada Code:
15714 switching between spec and body files with possible
15715 autogeneration of body files,
15718 automatic formating of subprograms parameter lists.
15721 automatic smart indentation according to Ada syntax,
15724 automatic completion of identifiers,
15727 automatic casing of identifiers, keywords, and attributes,
15730 insertion of statement templates,
15733 filling comment paragraphs like filling normal text,
15736 For more information, please refer to the online Glide documentation
15737 available in the Glide --> Help Menu.
15739 @node Converting Ada Files to html with gnathtml
15740 @section Converting Ada Files to html with @code{gnathtml}
15743 This @code{Perl} script allows Ada source files to be browsed using
15744 standard Web browsers. For installation procedure, see the section
15745 @xref{Installing gnathtml}.
15747 Ada reserved keywords are highlighted in a bold font and Ada comments in
15748 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
15749 switch to suppress the generation of cross-referencing information, user
15750 defined variables and types will appear in a different color; you will
15751 be able to click on any identifier and go to its declaration.
15753 The command line is as follow:
15755 $ perl gnathtml.pl [switches] ada-files
15758 You can pass it as many Ada files as you want. @code{gnathtml} will generate
15759 an html file for every ada file, and a global file called @file{index.htm}.
15760 This file is an index of every identifier defined in the files.
15762 The available switches are the following ones :
15766 @cindex @code{-83} (@code{gnathtml})
15767 Only the subset on the Ada 83 keywords will be highlighted, not the full
15768 Ada 95 keywords set.
15770 @item -cc @var{color}
15771 This option allows you to change the color used for comments. The default
15772 value is green. The color argument can be any name accepted by html.
15775 @cindex @code{-d} (@code{gnathtml})
15776 If the ada files depend on some other files (using for instance the
15777 @code{with} command, the latter will also be converted to html.
15778 Only the files in the user project will be converted to html, not the files
15779 in the run-time library itself.
15782 This command is the same as -d above, but @code{gnathtml} will also look
15783 for files in the run-time library, and generate html files for them.
15786 @cindex @code{-f} (@code{gnathtml})
15787 By default, gnathtml will generate html links only for global entities
15788 ('with'ed units, global variables and types,...). If you specify the
15789 @code{-f} on the command line, then links will be generated for local
15792 @item -l @var{number}
15793 @cindex @code{-l} (@code{gnathtml})
15794 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
15795 will number the html files every @var{number} line.
15798 @cindex @code{-I} (@code{gnathtml})
15799 Specify a directory to search for library files (@file{.ali} files) and
15800 source files. You can provide several -I switches on the command line,
15801 and the directories will be parsed in the order of the command line.
15804 @cindex @code{-o} (@code{gnathtml})
15805 Specify the output directory for html files. By default, gnathtml will
15806 saved the generated html files in a subdirectory named @file{html/}.
15808 @item -p @var{file}
15809 @cindex @code{-p} (@code{gnathtml})
15810 If you are using Emacs and the most recent Emacs Ada mode, which provides
15811 a full Integrated Development Environment for compiling, checking,
15812 running and debugging applications, you may be using @file{.adp} files
15813 to give the directories where Emacs can find sources and object files.
15815 Using this switch, you can tell gnathtml to use these files. This allows
15816 you to get an html version of your application, even if it is spread
15817 over multiple directories.
15819 @item -sc @var{color}
15820 @cindex @code{-sc} (@code{gnathtml})
15821 This option allows you to change the color used for symbol definitions.
15822 The default value is red. The color argument can be any name accepted by html.
15824 @item -t @var{file}
15825 @cindex @code{-t} (@code{gnathtml})
15826 This switch provides the name of a file. This file contains a list of
15827 file names to be converted, and the effect is exactly as though they had
15828 appeared explicitly on the command line. This
15829 is the recommended way to work around the command line length limit on some
15834 @node Installing gnathtml
15835 @section Installing @code{gnathtml}
15838 @code{Perl} needs to be installed on your machine to run this script.
15839 @code{Perl} is freely available for almost every architecture and
15840 Operating System via the Internet.
15842 On Unix systems, you may want to modify the first line of the script
15843 @code{gnathtml}, to explicitly tell the Operating system where Perl
15844 is. The syntax of this line is :
15846 #!full_path_name_to_perl
15850 Alternatively, you may run the script using the following command line:
15853 $ perl gnathtml.pl [switches] files
15857 @node Running and Debugging Ada Programs
15858 @chapter Running and Debugging Ada Programs
15862 This chapter discusses how to debug Ada programs. An incorrect Ada program
15863 may be handled in three ways by the GNAT compiler:
15867 The illegality may be a violation of the static semantics of Ada. In
15868 that case GNAT diagnoses the constructs in the program that are illegal.
15869 It is then a straightforward matter for the user to modify those parts of
15873 The illegality may be a violation of the dynamic semantics of Ada. In
15874 that case the program compiles and executes, but may generate incorrect
15875 results, or may terminate abnormally with some exception.
15878 When presented with a program that contains convoluted errors, GNAT
15879 itself may terminate abnormally without providing full diagnostics on
15880 the incorrect user program.
15884 * The GNAT Debugger GDB::
15886 * Introduction to GDB Commands::
15887 * Using Ada Expressions::
15888 * Calling User-Defined Subprograms::
15889 * Using the Next Command in a Function::
15892 * Debugging Generic Units::
15893 * GNAT Abnormal Termination or Failure to Terminate::
15894 * Naming Conventions for GNAT Source Files::
15895 * Getting Internal Debugging Information::
15896 * Stack Traceback::
15902 @node The GNAT Debugger GDB
15903 @section The GNAT Debugger GDB
15906 @code{GDB} is a general purpose, platform-independent debugger that
15907 can be used to debug mixed-language programs compiled with @code{GCC},
15908 and in particular is capable of debugging Ada programs compiled with
15909 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
15910 complex Ada data structures.
15912 The manual @cite{Debugging with GDB}
15913 contains full details on the usage of @code{GDB}, including a section on
15914 its usage on programs. This manual should be consulted for full
15915 details. The section that follows is a brief introduction to the
15916 philosophy and use of @code{GDB}.
15918 When GNAT programs are compiled, the compiler optionally writes debugging
15919 information into the generated object file, including information on
15920 line numbers, and on declared types and variables. This information is
15921 separate from the generated code. It makes the object files considerably
15922 larger, but it does not add to the size of the actual executable that
15923 will be loaded into memory, and has no impact on run-time performance. The
15924 generation of debug information is triggered by the use of the
15925 -g switch in the gcc or gnatmake command used to carry out
15926 the compilations. It is important to emphasize that the use of these
15927 options does not change the generated code.
15929 The debugging information is written in standard system formats that
15930 are used by many tools, including debuggers and profilers. The format
15931 of the information is typically designed to describe C types and
15932 semantics, but GNAT implements a translation scheme which allows full
15933 details about Ada types and variables to be encoded into these
15934 standard C formats. Details of this encoding scheme may be found in
15935 the file exp_dbug.ads in the GNAT source distribution. However, the
15936 details of this encoding are, in general, of no interest to a user,
15937 since @code{GDB} automatically performs the necessary decoding.
15939 When a program is bound and linked, the debugging information is
15940 collected from the object files, and stored in the executable image of
15941 the program. Again, this process significantly increases the size of
15942 the generated executable file, but it does not increase the size of
15943 the executable program itself. Furthermore, if this program is run in
15944 the normal manner, it runs exactly as if the debug information were
15945 not present, and takes no more actual memory.
15947 However, if the program is run under control of @code{GDB}, the
15948 debugger is activated. The image of the program is loaded, at which
15949 point it is ready to run. If a run command is given, then the program
15950 will run exactly as it would have if @code{GDB} were not present. This
15951 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
15952 entirely non-intrusive until a breakpoint is encountered. If no
15953 breakpoint is ever hit, the program will run exactly as it would if no
15954 debugger were present. When a breakpoint is hit, @code{GDB} accesses
15955 the debugging information and can respond to user commands to inspect
15956 variables, and more generally to report on the state of execution.
15959 @section Running GDB
15962 The debugger can be launched directly and simply from @code{glide} or
15963 through its graphical interface: @code{gvd}. It can also be used
15964 directly in text mode. Here is described the basic use of @code{GDB}
15965 in text mode. All the commands described below can be used in the
15966 @code{gvd} console window eventhough there is usually other more
15967 graphical ways to achieve the same goals.
15970 The command to run de graphical interface of the debugger is
15976 The command to run @code{GDB} in text mode is
15983 where @code{program} is the name of the executable file. This
15984 activates the debugger and results in a prompt for debugger commands.
15985 The simplest command is simply @code{run}, which causes the program to run
15986 exactly as if the debugger were not present. The following section
15987 describes some of the additional commands that can be given to @code{GDB}.
15990 @node Introduction to GDB Commands
15991 @section Introduction to GDB Commands
15994 @code{GDB} contains a large repertoire of commands. The manual
15995 @cite{Debugging with GDB}
15996 includes extensive documentation on the use
15997 of these commands, together with examples of their use. Furthermore,
15998 the command @var{help} invoked from within @code{GDB} activates a simple help
15999 facility which summarizes the available commands and their options.
16000 In this section we summarize a few of the most commonly
16001 used commands to give an idea of what @code{GDB} is about. You should create
16002 a simple program with debugging information and experiment with the use of
16003 these @code{GDB} commands on the program as you read through the
16007 @item set args @var{arguments}
16008 The @var{arguments} list above is a list of arguments to be passed to
16009 the program on a subsequent run command, just as though the arguments
16010 had been entered on a normal invocation of the program. The @code{set args}
16011 command is not needed if the program does not require arguments.
16014 The @code{run} command causes execution of the program to start from
16015 the beginning. If the program is already running, that is to say if
16016 you are currently positioned at a breakpoint, then a prompt will ask
16017 for confirmation that you want to abandon the current execution and
16020 @item breakpoint @var{location}
16021 The breakpoint command sets a breakpoint, that is to say a point at which
16022 execution will halt and @code{GDB} will await further
16023 commands. @var{location} is
16024 either a line number within a file, given in the format @code{file:linenumber},
16025 or it is the name of a subprogram. If you request that a breakpoint be set on
16026 a subprogram that is overloaded, a prompt will ask you to specify on which of
16027 those subprograms you want to breakpoint. You can also
16028 specify that all of them should be breakpointed. If the program is run
16029 and execution encounters the breakpoint, then the program
16030 stops and @code{GDB} signals that the breakpoint was encountered by
16031 printing the line of code before which the program is halted.
16033 @item breakpoint exception @var{name}
16034 A special form of the breakpoint command which breakpoints whenever
16035 exception @var{name} is raised.
16036 If @var{name} is omitted,
16037 then a breakpoint will occur when any exception is raised.
16039 @item print @var{expression}
16040 This will print the value of the given expression. Most simple
16041 Ada expression formats are properly handled by @code{GDB}, so the expression
16042 can contain function calls, variables, operators, and attribute references.
16045 Continues execution following a breakpoint, until the next breakpoint or the
16046 termination of the program.
16049 Executes a single line after a breakpoint. If the next statement is a subprogram
16050 call, execution continues into (the first statement of) the
16054 Executes a single line. If this line is a subprogram call, executes and
16055 returns from the call.
16058 Lists a few lines around the current source location. In practice, it
16059 is usually more convenient to have a separate edit window open with the
16060 relevant source file displayed. Successive applications of this command
16061 print subsequent lines. The command can be given an argument which is a
16062 line number, in which case it displays a few lines around the specified one.
16065 Displays a backtrace of the call chain. This command is typically
16066 used after a breakpoint has occurred, to examine the sequence of calls that
16067 leads to the current breakpoint. The display includes one line for each
16068 activation record (frame) corresponding to an active subprogram.
16071 At a breakpoint, @code{GDB} can display the values of variables local
16072 to the current frame. The command @code{up} can be used to
16073 examine the contents of other active frames, by moving the focus up
16074 the stack, that is to say from callee to caller, one frame at a time.
16077 Moves the focus of @code{GDB} down from the frame currently being
16078 examined to the frame of its callee (the reverse of the previous command),
16080 @item frame @var{n}
16081 Inspect the frame with the given number. The value 0 denotes the frame
16082 of the current breakpoint, that is to say the top of the call stack.
16086 The above list is a very short introduction to the commands that
16087 @code{GDB} provides. Important additional capabilities, including conditional
16088 breakpoints, the ability to execute command sequences on a breakpoint,
16089 the ability to debug at the machine instruction level and many other
16090 features are described in detail in @cite{Debugging with GDB}.
16091 Note that most commands can be abbreviated
16092 (for example, c for continue, bt for backtrace).
16094 @node Using Ada Expressions
16095 @section Using Ada Expressions
16096 @cindex Ada expressions
16099 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
16100 extensions. The philosophy behind the design of this subset is
16104 That @code{GDB} should provide basic literals and access to operations for
16105 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
16106 leaving more sophisticated computations to subprograms written into the
16107 program (which therefore may be called from @code{GDB}).
16110 That type safety and strict adherence to Ada language restrictions
16111 are not particularly important to the @code{GDB} user.
16114 That brevity is important to the @code{GDB} user.
16117 Thus, for brevity, the debugger acts as if there were
16118 implicit @code{with} and @code{use} clauses in effect for all user-written
16119 packages, thus making it unnecessary to fully qualify most names with
16120 their packages, regardless of context. Where this causes ambiguity,
16121 @code{GDB} asks the user's intent.
16123 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
16125 @node Calling User-Defined Subprograms
16126 @section Calling User-Defined Subprograms
16129 An important capability of @code{GDB} is the ability to call user-defined
16130 subprograms while debugging. This is achieved simply by entering
16131 a subprogram call statement in the form:
16134 call subprogram-name (parameters)
16138 The keyword @code{call} can be omitted in the normal case where the
16139 @code{subprogram-name} does not coincide with any of the predefined
16140 @code{GDB} commands.
16142 The effect is to invoke the given subprogram, passing it the
16143 list of parameters that is supplied. The parameters can be expressions and
16144 can include variables from the program being debugged. The
16145 subprogram must be defined
16146 at the library level within your program, and @code{GDB} will call the
16147 subprogram within the environment of your program execution (which
16148 means that the subprogram is free to access or even modify variables
16149 within your program).
16151 The most important use of this facility is in allowing the inclusion of
16152 debugging routines that are tailored to particular data structures
16153 in your program. Such debugging routines can be written to provide a suitably
16154 high-level description of an abstract type, rather than a low-level dump
16155 of its physical layout. After all, the standard
16156 @code{GDB print} command only knows the physical layout of your
16157 types, not their abstract meaning. Debugging routines can provide information
16158 at the desired semantic level and are thus enormously useful.
16160 For example, when debugging GNAT itself, it is crucial to have access to
16161 the contents of the tree nodes used to represent the program internally.
16162 But tree nodes are represented simply by an integer value (which in turn
16163 is an index into a table of nodes).
16164 Using the @code{print} command on a tree node would simply print this integer
16165 value, which is not very useful. But the PN routine (defined in file
16166 treepr.adb in the GNAT sources) takes a tree node as input, and displays
16167 a useful high level representation of the tree node, which includes the
16168 syntactic category of the node, its position in the source, the integers
16169 that denote descendant nodes and parent node, as well as varied
16170 semantic information. To study this example in more detail, you might want to
16171 look at the body of the PN procedure in the stated file.
16173 @node Using the Next Command in a Function
16174 @section Using the Next Command in a Function
16177 When you use the @code{next} command in a function, the current source
16178 location will advance to the next statement as usual. A special case
16179 arises in the case of a @code{return} statement.
16181 Part of the code for a return statement is the "epilog" of the function.
16182 This is the code that returns to the caller. There is only one copy of
16183 this epilog code, and it is typically associated with the last return
16184 statement in the function if there is more than one return. In some
16185 implementations, this epilog is associated with the first statement
16188 The result is that if you use the @code{next} command from a return
16189 statement that is not the last return statement of the function you
16190 may see a strange apparent jump to the last return statement or to
16191 the start of the function. You should simply ignore this odd jump.
16192 The value returned is always that from the first return statement
16193 that was stepped through.
16195 @node Ada Exceptions
16196 @section Breaking on Ada Exceptions
16200 You can set breakpoints that trip when your program raises
16201 selected exceptions.
16204 @item break exception
16205 Set a breakpoint that trips whenever (any task in the) program raises
16208 @item break exception @var{name}
16209 Set a breakpoint that trips whenever (any task in the) program raises
16210 the exception @var{name}.
16212 @item break exception unhandled
16213 Set a breakpoint that trips whenever (any task in the) program raises an
16214 exception for which there is no handler.
16216 @item info exceptions
16217 @itemx info exceptions @var{regexp}
16218 The @code{info exceptions} command permits the user to examine all defined
16219 exceptions within Ada programs. With a regular expression, @var{regexp}, as
16220 argument, prints out only those exceptions whose name matches @var{regexp}.
16228 @code{GDB} allows the following task-related commands:
16232 This command shows a list of current Ada tasks, as in the following example:
16239 ID TID P-ID Thread Pri State Name
16240 1 8088000 0 807e000 15 Child Activation Wait main_task
16241 2 80a4000 1 80ae000 15 Accept/Select Wait b
16242 3 809a800 1 80a4800 15 Child Activation Wait a
16243 * 4 80ae800 3 80b8000 15 Running c
16247 In this listing, the asterisk before the first task indicates it to be the
16248 currently running task. The first column lists the task ID that is used
16249 to refer to tasks in the following commands.
16251 @item break @var{linespec} task @var{taskid}
16252 @itemx break @var{linespec} task @var{taskid} if @dots{}
16253 @cindex Breakpoints and tasks
16254 These commands are like the @code{break @dots{} thread @dots{}}.
16255 @var{linespec} specifies source lines.
16257 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
16258 to specify that you only want @code{GDB} to stop the program when a
16259 particular Ada task reaches this breakpoint. @var{taskid} is one of the
16260 numeric task identifiers assigned by @code{GDB}, shown in the first
16261 column of the @samp{info tasks} display.
16263 If you do not specify @samp{task @var{taskid}} when you set a
16264 breakpoint, the breakpoint applies to @emph{all} tasks of your
16267 You can use the @code{task} qualifier on conditional breakpoints as
16268 well; in this case, place @samp{task @var{taskid}} before the
16269 breakpoint condition (before the @code{if}).
16271 @item task @var{taskno}
16272 @cindex Task switching
16274 This command allows to switch to the task referred by @var{taskno}. In
16275 particular, This allows to browse the backtrace of the specified
16276 task. It is advised to switch back to the original task before
16277 continuing execution otherwise the scheduling of the program may be
16282 For more detailed information on the tasking support, see @cite{Debugging with GDB}.
16284 @node Debugging Generic Units
16285 @section Debugging Generic Units
16286 @cindex Debugging Generic Units
16290 GNAT always uses code expansion for generic instantiation. This means that
16291 each time an instantiation occurs, a complete copy of the original code is
16292 made, with appropriate substitutions of formals by actuals.
16294 It is not possible to refer to the original generic entities in
16295 @code{GDB}, but it is always possible to debug a particular instance of
16296 a generic, by using the appropriate expanded names. For example, if we have
16301 @b{procedure} g @b{is}
16303 @b{generic package} k @b{is}
16304 @b{procedure} kp (v1 : @b{in out} integer);
16307 @b{package body} k @b{is}
16308 @b{procedure} kp (v1 : @b{in out} integer) @b{is}
16314 @b{package} k1 @b{is new} k;
16315 @b{package} k2 @b{is new} k;
16317 var : integer := 1;
16330 Then to break on a call to procedure kp in the k2 instance, simply
16334 (gdb) break g.k2.kp
16338 When the breakpoint occurs, you can step through the code of the
16339 instance in the normal manner and examine the values of local variables, as for
16342 @node GNAT Abnormal Termination or Failure to Terminate
16343 @section GNAT Abnormal Termination or Failure to Terminate
16344 @cindex GNAT Abnormal Termination or Failure to Terminate
16347 When presented with programs that contain serious errors in syntax
16349 GNAT may on rare occasions experience problems in operation, such
16351 segmentation fault or illegal memory access, raising an internal
16352 exception, terminating abnormally, or failing to terminate at all.
16353 In such cases, you can activate
16354 various features of GNAT that can help you pinpoint the construct in your
16355 program that is the likely source of the problem.
16357 The following strategies are presented in increasing order of
16358 difficulty, corresponding to your experience in using GNAT and your
16359 familiarity with compiler internals.
16363 Run @code{gcc} with the @option{-gnatf}. This first
16364 switch causes all errors on a given line to be reported. In its absence,
16365 only the first error on a line is displayed.
16367 The @option{-gnatdO} switch causes errors to be displayed as soon as they
16368 are encountered, rather than after compilation is terminated. If GNAT
16369 terminates prematurely or goes into an infinite loop, the last error
16370 message displayed may help to pinpoint the culprit.
16373 Run @code{gcc} with the @code{-v (verbose)} switch. In this mode,
16374 @code{gcc} produces ongoing information about the progress of the
16375 compilation and provides the name of each procedure as code is
16376 generated. This switch allows you to find which Ada procedure was being
16377 compiled when it encountered a code generation problem.
16380 @cindex @option{-gnatdc} switch
16381 Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
16382 switch that does for the front-end what @code{-v} does for the back end.
16383 The system prints the name of each unit, either a compilation unit or
16384 nested unit, as it is being analyzed.
16386 Finally, you can start
16387 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
16388 front-end of GNAT, and can be run independently (normally it is just
16389 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
16390 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
16391 @code{where} command is the first line of attack; the variable
16392 @code{lineno} (seen by @code{print lineno}), used by the second phase of
16393 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
16394 which the execution stopped, and @code{input_file name} indicates the name of
16398 @node Naming Conventions for GNAT Source Files
16399 @section Naming Conventions for GNAT Source Files
16402 In order to examine the workings of the GNAT system, the following
16403 brief description of its organization may be helpful:
16407 Files with prefix @file{sc} contain the lexical scanner.
16410 All files prefixed with @file{par} are components of the parser. The
16411 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
16412 parsing of select statements can be found in @file{par-ch9.adb}.
16415 All files prefixed with @file{sem} perform semantic analysis. The
16416 numbers correspond to chapters of the Ada standard. For example, all
16417 issues involving context clauses can be found in @file{sem_ch10.adb}. In
16418 addition, some features of the language require sufficient special processing
16419 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
16420 dynamic dispatching, etc.
16423 All files prefixed with @file{exp} perform normalization and
16424 expansion of the intermediate representation (abstract syntax tree, or AST).
16425 these files use the same numbering scheme as the parser and semantics files.
16426 For example, the construction of record initialization procedures is done in
16427 @file{exp_ch3.adb}.
16430 The files prefixed with @file{bind} implement the binder, which
16431 verifies the consistency of the compilation, determines an order of
16432 elaboration, and generates the bind file.
16435 The files @file{atree.ads} and @file{atree.adb} detail the low-level
16436 data structures used by the front-end.
16439 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
16440 the abstract syntax tree as produced by the parser.
16443 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
16444 all entities, computed during semantic analysis.
16447 Library management issues are dealt with in files with prefix
16453 Ada files with the prefix @file{a-} are children of @code{Ada}, as
16454 defined in Annex A.
16459 Files with prefix @file{i-} are children of @code{Interfaces}, as
16460 defined in Annex B.
16464 Files with prefix @file{s-} are children of @code{System}. This includes
16465 both language-defined children and GNAT run-time routines.
16469 Files with prefix @file{g-} are children of @code{GNAT}. These are useful
16470 general-purpose packages, fully documented in their specifications. All
16471 the other @file{.c} files are modifications of common @code{gcc} files.
16474 @node Getting Internal Debugging Information
16475 @section Getting Internal Debugging Information
16478 Most compilers have internal debugging switches and modes. GNAT
16479 does also, except GNAT internal debugging switches and modes are not
16480 secret. A summary and full description of all the compiler and binder
16481 debug flags are in the file @file{debug.adb}. You must obtain the
16482 sources of the compiler to see the full detailed effects of these flags.
16484 The switches that print the source of the program (reconstructed from
16485 the internal tree) are of general interest for user programs, as are the
16487 the full internal tree, and the entity table (the symbol table
16488 information). The reconstructed source provides a readable version of the
16489 program after the front-end has completed analysis and expansion, and is useful
16490 when studying the performance of specific constructs. For example, constraint
16491 checks are indicated, complex aggregates are replaced with loops and
16492 assignments, and tasking primitives are replaced with run-time calls.
16494 @node Stack Traceback
16495 @section Stack Traceback
16497 @cindex stack traceback
16498 @cindex stack unwinding
16501 Traceback is a mechanism to display the sequence of subprogram calls that
16502 leads to a specified execution point in a program. Often (but not always)
16503 the execution point is an instruction at which an exception has been raised.
16504 This mechanism is also known as @i{stack unwinding} because it obtains
16505 its information by scanning the run-time stack and recovering the activation
16506 records of all active subprograms. Stack unwinding is one of the most
16507 important tools for program debugging.
16510 The first entry stored in traceback corresponds to the deepest calling level,
16511 that is to say the subprogram currently executing the instruction
16512 from which we want to obtain the traceback.
16515 Note that there is no runtime performance penalty when stack traceback
16516 is enabled and no exception are raised during program execution.
16519 * Non-Symbolic Traceback::
16520 * Symbolic Traceback::
16523 @node Non-Symbolic Traceback
16524 @subsection Non-Symbolic Traceback
16525 @cindex traceback, non-symbolic
16528 Note: this feature is not supported on all platforms. See
16529 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
16533 * Tracebacks From an Unhandled Exception::
16534 * Tracebacks From Exception Occurrences (non-symbolic)::
16535 * Tracebacks From Anywhere in a Program (non-symbolic)::
16538 @node Tracebacks From an Unhandled Exception
16539 @subsubsection Tracebacks From an Unhandled Exception
16542 A runtime non-symbolic traceback is a list of addresses of call instructions.
16543 To enable this feature you must use the @code{-E}
16544 @code{gnatbind}'s option. With this option a stack traceback is stored as part
16545 of exception information. It is possible to retrieve this information using the
16546 standard @code{Ada.Exception.Exception_Information} routine.
16549 Let's have a look at a simple example:
16558 raise Constraint_Error;
16574 $ gnatmake stb -bargs -E
16577 Execution terminated by unhandled exception
16578 Exception name: CONSTRAINT_ERROR
16580 Call stack traceback locations:
16581 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
16585 As we see the traceback lists a sequence of addresses for the unhandled
16586 exception @code{CONSTAINT_ERROR} raised in procedure P1. It is easy to
16587 guess that this exception come from procedure P1. To translate these
16588 addresses into the source lines where the calls appear, the
16589 @code{addr2line} tool, described below, is invaluable. The use of this tool
16590 requires the program to be compiled with debug information.
16593 $ gnatmake -g stb -bargs -E
16596 Execution terminated by unhandled exception
16597 Exception name: CONSTRAINT_ERROR
16599 Call stack traceback locations:
16600 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
16602 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
16603 0x4011f1 0x77e892a4
16605 00401373 at d:/stb/stb.adb:5
16606 0040138B at d:/stb/stb.adb:10
16607 0040139C at d:/stb/stb.adb:14
16608 00401335 at d:/stb/b~stb.adb:104
16609 004011C4 at /build/.../crt1.c:200
16610 004011F1 at /build/.../crt1.c:222
16611 77E892A4 in ?? at ??:0
16615 @code{addr2line} has a number of other useful options:
16619 to get the function name corresponding to any location
16621 @item --demangle=gnat
16622 to use the @b{gnat} decoding mode for the function names. Note that
16623 for binutils version 2.9.x the option is simply @code{--demangle}.
16627 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
16628 0x40139c 0x401335 0x4011c4 0x4011f1
16630 00401373 in stb.p1 at d:/stb/stb.adb:5
16631 0040138B in stb.p2 at d:/stb/stb.adb:10
16632 0040139C in stb at d:/stb/stb.adb:14
16633 00401335 in main at d:/stb/b~stb.adb:104
16634 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
16635 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
16639 From this traceback we can see that the exception was raised in
16640 @file{stb.adb} at line 5, which was reached from a procedure call in
16641 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
16642 which contains the call to the main program.
16643 @pxref{Running gnatbind}. The remaining entries are assorted runtime routines,
16644 and the output will vary from platform to platform.
16647 It is also possible to use @code{GDB} with these traceback addresses to debug
16648 the program. For example, we can break at a given code location, as reported
16649 in the stack traceback:
16654 Furthermore, this feature is not implemented inside Windows DLL. Only
16655 the non-symbolic traceback is reported in this case.
16657 (gdb) break *0x401373
16658 Breakpoint 1 at 0x401373: file stb.adb, line 5.
16662 It is important to note that the stack traceback addresses
16663 do not change when debug information is included. This is particularly useful
16664 because it makes it possible to release software without debug information (to
16665 minimize object size), get a field report that includes a stack traceback
16666 whenever an internal bug occurs, and then be able to retrieve the sequence
16667 of calls with the same program compiled with debug information.
16669 @node Tracebacks From Exception Occurrences (non-symbolic)
16670 @subsubsection Tracebacks From Exception Occurrences
16673 Non-symbolic tracebacks are obtained by using the @code{-E} binder argument.
16674 The stack traceback is attached to the exception information string, and can
16675 be retrieved in an exception handler within the Ada program, by means of the
16676 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
16682 with Ada.Exceptions;
16687 use Ada.Exceptions;
16695 Text_IO.Put_Line (Exception_Information (E));
16711 This program will output:
16716 Exception name: CONSTRAINT_ERROR
16717 Message: stb.adb:12
16718 Call stack traceback locations:
16719 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
16722 @node Tracebacks From Anywhere in a Program (non-symbolic)
16723 @subsubsection Tracebacks From Anywhere in a Program
16726 It is also possible to retrieve a stack traceback from anywhere in a
16727 program. For this you need to
16728 use the @code{GNAT.Traceback} API. This package includes a procedure called
16729 @code{Call_Chain} that computes a complete stack traceback, as well as useful
16730 display procedures described below. It is not necessary to use the
16731 @code{-E gnatbind} option in this case, because the stack traceback mechanism
16732 is invoked explicitly.
16735 In the following example we compute a traceback at a specific location in
16736 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
16737 convert addresses to strings:
16743 with GNAT.Traceback;
16744 with GNAT.Debug_Utilities;
16750 use GNAT.Traceback;
16753 TB : Tracebacks_Array (1 .. 10);
16754 -- We are asking for a maximum of 10 stack frames.
16756 -- Len will receive the actual number of stack frames returned.
16758 Call_Chain (TB, Len);
16760 Text_IO.Put ("In STB.P1 : ");
16762 for K in 1 .. Len loop
16763 Text_IO.Put (Debug_Utilities.Image (TB (K)));
16786 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
16787 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
16790 @node Symbolic Traceback
16791 @subsection Symbolic Traceback
16792 @cindex traceback, symbolic
16795 A symbolic traceback is a stack traceback in which procedure names are
16796 associated with each code location.
16799 Note that this feature is not supported on all platforms. See
16800 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
16801 list of currently supported platforms.
16804 Note that the symbolic traceback requires that the program be compiled
16805 with debug information. If it is not compiled with debug information
16806 only the non-symbolic information will be valid.
16809 * Tracebacks From Exception Occurrences (symbolic)::
16810 * Tracebacks From Anywhere in a Program (symbolic)::
16813 @node Tracebacks From Exception Occurrences (symbolic)
16814 @subsubsection Tracebacks From Exception Occurrences
16820 with GNAT.Traceback.Symbolic;
16826 raise Constraint_Error;
16843 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
16850 $ gnatmake -g stb -bargs -E -largs -lgnat -laddr2line -lintl
16853 0040149F in stb.p1 at stb.adb:8
16854 004014B7 in stb.p2 at stb.adb:13
16855 004014CF in stb.p3 at stb.adb:18
16856 004015DD in ada.stb at stb.adb:22
16857 00401461 in main at b~stb.adb:168
16858 004011C4 in __mingw_CRTStartup at crt1.c:200
16859 004011F1 in mainCRTStartup at crt1.c:222
16860 77E892A4 in ?? at ??:0
16864 The exact sequence of linker options may vary from platform to platform.
16865 The above @code{-largs} section is for Windows platforms. By contrast,
16866 under Unix there is no need for the @code{-largs} section.
16867 Differences across platforms are due to details of linker implementation.
16869 @node Tracebacks From Anywhere in a Program (symbolic)
16870 @subsubsection Tracebacks From Anywhere in a Program
16873 It is possible to get a symbolic stack traceback
16874 from anywhere in a program, just as for non-symbolic tracebacks.
16875 The first step is to obtain a non-symbolic
16876 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
16877 information. Here is an example:
16883 with GNAT.Traceback;
16884 with GNAT.Traceback.Symbolic;
16889 use GNAT.Traceback;
16890 use GNAT.Traceback.Symbolic;
16893 TB : Tracebacks_Array (1 .. 10);
16894 -- We are asking for a maximum of 10 stack frames.
16896 -- Len will receive the actual number of stack frames returned.
16898 Call_Chain (TB, Len);
16899 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
16915 @node Inline Assembler
16916 @chapter Inline Assembler
16919 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:
16922 @item No need to use non-Ada tools
16923 @item Consistent interface over different targets
16924 @item Automatic usage of the proper calling conventions
16925 @item Access to Ada constants and variables
16926 @item Definition of intrinsic routines
16927 @item Possibility of inlining a subprogram comprising assembler code
16928 @item Code optimizer can take Inline Assembler code into account
16931 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.
16934 * Basic Assembler Syntax::
16935 * A Simple Example of Inline Assembler::
16936 * Output Variables in Inline Assembler::
16937 * Input Variables in Inline Assembler::
16938 * Inlining Inline Assembler Code::
16939 * Other Asm Functionality::
16940 * A Complete Example::
16943 @c ---------------------------------------------------------------------------
16944 @node Basic Assembler Syntax
16945 @section Basic Assembler Syntax
16948 The assembler used by GNAT and gcc is based not on the Intel assembly language, but rather on a
16949 language that descends from the AT&T Unix assembler @emph{as} (and which is often
16950 referred to as ``AT&T syntax'').
16951 The following table summarizes the main features of @emph{as} syntax and points out the differences from the Intel conventions.
16952 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
16953 pre-processor) documentation for further information.
16956 @item Register names
16957 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
16959 Intel: No extra punctuation; for example @code{eax}
16961 @item Immediate operand
16962 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
16964 Intel: No extra punctuation; for example @code{4}
16967 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
16969 Intel: No extra punctuation; for example @code{loc}
16971 @item Memory contents
16972 gcc / @emph{as}: No extra punctuation; for example @code{loc}
16974 Intel: Square brackets; for example @code{[loc]}
16976 @item Register contents
16977 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
16979 Intel: Square brackets; for example @code{[eax]}
16981 @item Hexadecimal numbers
16982 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
16984 Intel: Trailing ``h''; for example @code{A0h}
16987 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move a 16-bit word
16989 Intel: Implicit, deduced by assembler; for example @code{mov}
16991 @item Instruction repetition
16992 gcc / @emph{as}: Split into two lines; for example
16998 Intel: Keep on one line; for example @code{rep stosl}
17000 @item Order of operands
17001 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
17003 Intel: Destination first; for example @code{mov eax, 4}
17006 @c ---------------------------------------------------------------------------
17007 @node A Simple Example of Inline Assembler
17008 @section A Simple Example of Inline Assembler
17011 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.
17015 with System.Machine_Code; use System.Machine_Code;
17016 procedure Nothing is
17023 @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.
17024 @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.
17026 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}.
17028 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:
17032 However, the interesting aspect of this example is not its run-time behavior but rather the
17033 generated assembly code. To see this output, invoke the compiler as follows:
17035 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
17037 where the options are:
17041 compile only (no bind or link)
17043 generate assembler listing
17044 @item -fomit-frame-pointer
17045 do not set up separate stack frames
17047 do not add runtime checks
17050 This gives a human-readable assembler version of the code. The resulting
17051 file will have the same name as the Ada source file, but with a @code{.s} extension.
17052 In our example, the file @file{nothing.s} has the following contents:
17056 .file "nothing.adb"
17058 ___gnu_compiled_ada:
17061 .globl __ada_nothing
17073 The assembly code you included is clearly indicated by
17074 the compiler, between the @code{#APP} and @code{#NO_APP}
17075 delimiters. The character before the 'APP' and 'NOAPP'
17076 can differ on different targets. For example, Linux uses '#APP' while
17077 on NT you will see '/APP'.
17079 If you make a mistake in your assembler code (such as using the
17080 wrong size modifier, or using a wrong operand for the instruction) GNAT
17081 will report this error in a temporary file, which will be deleted when
17082 the compilation is finished. Generating an assembler file will help
17083 in such cases, since you can assemble this file separately using the
17084 @emph{as} assembler that comes with gcc.
17086 Assembling the file using the command
17089 as @file{nothing.s}
17092 will give you error messages whose lines correspond to the assembler
17093 input file, so you can easily find and correct any mistakes you made.
17094 If there are no errors, @emph{as} will generate an object file @file{nothing.out}.
17096 @c ---------------------------------------------------------------------------
17097 @node Output Variables in Inline Assembler
17098 @section Output Variables in Inline Assembler
17101 The examples in this section, showing how to access the processor flags, illustrate how to specify the destination operands for assembly language statements.
17105 with Interfaces; use Interfaces;
17106 with Ada.Text_IO; use Ada.Text_IO;
17107 with System.Machine_Code; use System.Machine_Code;
17108 procedure Get_Flags is
17109 Flags : Unsigned_32;
17112 Asm ("pushfl" & LF & HT & -- push flags on stack
17113 "popl %%eax" & LF & HT & -- load eax with flags
17114 "movl %%eax, %0", -- store flags in variable
17115 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
17116 Put_Line ("Flags register:" & Flags'Img);
17121 In order to have a nicely aligned assembly listing, we have separated
17122 multiple assembler statements in the Asm template string with linefeed (ASCII.LF)
17123 and horizontal tab (ASCII.HT) characters. The resulting section of the
17124 assembly output file is:
17131 movl %eax, -40(%ebp)
17136 It would have been legal to write the Asm invocation as:
17139 Asm ("pushfl popl %%eax movl %%eax, %0")
17142 but in the generated assembler file, this would come out as:
17146 pushfl popl %eax movl %eax, -40(%ebp)
17150 which is not so convenient for the human reader.
17152 We use Ada comments
17153 at the end of each line to explain what the assembler instructions
17154 actually do. This is a useful convention.
17156 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.
17158 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}.
17159 An output variable is illustrated in
17160 the third statement in the Asm template string:
17164 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.
17166 Information about the output variable is supplied in the @code{Outputs} parameter to @code{Asm}:
17168 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
17171 The output is defined by the @code{Asm_Output} attribute of the target type; the general format is
17173 Type'Asm_Output (constraint_string, variable_name)
17176 The constraint string directs the compiler how
17177 to store/access the associated variable. In the example
17179 Unsigned_32'Asm_Output ("=m", Flags);
17181 the @code{"m"} (memory) constraint tells the compiler that the variable
17182 @code{Flags} should be stored in a memory variable, thus preventing
17183 the optimizer from keeping it in a register. In contrast,
17185 Unsigned_32'Asm_Output ("=r", Flags);
17187 uses the @code{"r"} (register) constraint, telling the compiler to
17188 store the variable in a register.
17190 If the constraint is preceded by the equal character (@strong{=}), it tells the
17191 compiler that the variable will be used to store data into it.
17193 In the @code{Get_Flags} example, we used the "g" (global) constraint, allowing the optimizer
17194 to choose whatever it deems best.
17196 There are a fairly large number of constraints, but the ones that are most useful (for the Intel x86 processor) are the following:
17202 global (i.e. can be stored anywhere)
17220 use one of eax, ebx, ecx or edx
17222 use one of eax, ebx, ecx, edx, esi or edi
17225 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.
17227 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
17230 Asm ("pushfl" & LF & HT & -- push flags on stack
17231 "popl %%eax" & LF & HT & -- load eax with flags
17232 "movl %%eax, %0", -- store flags in variable
17233 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
17237 @code{%0} will be replaced in the expanded code by the appropriate operand,
17239 the compiler decided for the @code{Flags} variable.
17241 In general, you may have any number of output variables:
17244 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
17246 Specify the @code{Outputs} parameter as a parenthesized comma-separated list of @code{Asm_Output} attributes
17252 Asm ("movl %%eax, %0" & LF & HT &
17253 "movl %%ebx, %1" & LF & HT &
17255 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
17256 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
17257 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
17261 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables in the Ada program.
17263 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:
17267 with Interfaces; use Interfaces;
17268 with Ada.Text_IO; use Ada.Text_IO;
17269 with System.Machine_Code; use System.Machine_Code;
17270 procedure Get_Flags_2 is
17271 Flags : Unsigned_32;
17274 Asm ("pushfl" & LF & HT & -- push flags on stack
17275 "popl %%eax", -- save flags in eax
17276 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
17277 Put_Line ("Flags register:" & Flags'Img);
17283 The @code{"a"} constraint tells the compiler that the @code{Flags}
17284 variable will come from the eax register. Here is the resulting code:
17292 movl %eax,-40(%ebp)
17297 The compiler generated the store of eax into Flags after
17298 expanding the assembler code.
17300 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:
17304 with Interfaces; use Interfaces;
17305 with Ada.Text_IO; use Ada.Text_IO;
17306 with System.Machine_Code; use System.Machine_Code;
17307 procedure Get_Flags_3 is
17308 Flags : Unsigned_32;
17311 Asm ("pushfl" & LF & HT & -- push flags on stack
17312 "pop %0", -- save flags in Flags
17313 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
17314 Put_Line ("Flags register:" & Flags'Img);
17319 @c ---------------------------------------------------------------------------
17320 @node Input Variables in Inline Assembler
17321 @section Input Variables in Inline Assembler
17324 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:
17328 with Interfaces; use Interfaces;
17329 with Ada.Text_IO; use Ada.Text_IO;
17330 with System.Machine_Code; use System.Machine_Code;
17331 procedure Increment is
17333 function Incr (Value : Unsigned_32) return Unsigned_32 is
17334 Result : Unsigned_32;
17337 Inputs => Unsigned_32'Asm_Input ("a", Value),
17338 Outputs => Unsigned_32'Asm_Output ("=a", Result));
17342 Value : Unsigned_32;
17346 Put_Line ("Value before is" & Value'Img);
17347 Value := Incr (Value);
17348 Put_Line ("Value after is" & Value'Img);
17353 The @code{Outputs} parameter to @code{Asm} specifies
17354 that the result will be in the eax register and that it is to be stored in the @code{Result}
17357 The @code{Inputs} parameter looks much like the @code{Outputs} parameter, but with an
17358 @code{Asm_Input} attribute. The
17359 @code{"="} constraint, indicating an output value, is not present.
17361 You can have multiple input variables, in the same way that you can have more
17362 than one output variable.
17364 The parameter count (%0, %1) etc, now starts at the first input
17365 statement, and continues with the output statements.
17366 When both parameters use the same variable, the
17367 compiler will treat them as the same %n operand, which is the case here.
17369 Just as the @code{Outputs} parameter causes the register to be stored into the
17370 target variable after execution of the assembler statements, so does the
17371 @code{Inputs} parameter cause its variable to be loaded into the register before execution
17373 assembler statements.
17375 Thus the effect of the @code{Asm} invocation is:
17377 @item load the 32-bit value of @code{Value} into eax
17378 @item execute the @code{incl %eax} instruction
17379 @item store the contents of eax into the @code{Result} variable
17382 The resulting assembler file (with @code{-O2} optimization) contains:
17385 _increment__incr.1:
17398 @c ---------------------------------------------------------------------------
17399 @node Inlining Inline Assembler Code
17400 @section Inlining Inline Assembler Code
17403 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)
17404 can be significant, compared to the amount of code in the subprogram body.
17405 A solution is to apply Ada's @code{Inline} pragma to the subprogram,
17406 which directs the compiler to expand invocations of the subprogram at the point(s)
17407 of call, instead of setting up a stack frame for out-of-line calls.
17408 Here is the resulting program:
17412 with Interfaces; use Interfaces;
17413 with Ada.Text_IO; use Ada.Text_IO;
17414 with System.Machine_Code; use System.Machine_Code;
17415 procedure Increment_2 is
17417 function Incr (Value : Unsigned_32) return Unsigned_32 is
17418 Result : Unsigned_32;
17421 Inputs => Unsigned_32'Asm_Input ("a", Value),
17422 Outputs => Unsigned_32'Asm_Output ("=a", Result));
17425 pragma Inline (Increment);
17427 Value : Unsigned_32;
17431 Put_Line ("Value before is" & Value'Img);
17432 Value := Increment (Value);
17433 Put_Line ("Value after is" & Value'Img);
17438 Compile the program with both optimization (@code{-O2}) and inlining
17439 enabled (@option{-gnatpn} instead of @option{-gnatp}).
17441 The @code{Incr} function is still compiled as usual, but at the
17442 point in @code{Increment} where our function used to be called:
17447 call _increment__incr.1
17452 the code for the function body directly appears:
17465 thus saving the overhead of stack frame setup and an out-of-line call.
17467 @c ---------------------------------------------------------------------------
17468 @node Other Asm Functionality
17469 @section Other @code{Asm} Functionality
17472 This section describes two important parameters to the @code{Asm} procedure: @code{Clobber}, which identifies register usage; and @code{Volatile}, which inhibits unwanted optimizations.
17475 * The Clobber Parameter::
17476 * The Volatile Parameter::
17479 @c ---------------------------------------------------------------------------
17480 @node The Clobber Parameter
17481 @subsection The @code{Clobber} Parameter
17484 One of the dangers of intermixing assembly language and a compiled language such as Ada is
17485 that the compiler needs to be aware of which registers are being used by the assembly code.
17486 In some cases, such as the earlier examples, the constraint string is sufficient to
17487 indicate register usage (e.g. "a" for the eax register). But more generally, the
17488 compiler needs an explicit identification of the registers that are used by the Inline
17489 Assembly statements.
17491 Using a register that the compiler doesn't know about
17492 could be a side effect of an instruction (like @code{mull}
17493 storing its result in both eax and edx).
17494 It can also arise from explicit register usage in your
17495 assembly code; for example:
17498 Asm ("movl %0, %%ebx" & LF & HT &
17500 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
17501 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
17505 where the compiler (since it does not analyze the @code{Asm} template string)
17506 does not know you are using the ebx register.
17508 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
17509 to identify the registers that will be used by your assembly code:
17513 Asm ("movl %0, %%ebx" & LF & HT &
17515 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
17516 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
17521 The Clobber parameter is a static string expression specifying the
17522 register(s) you are using. Note that register names are @emph{not} prefixed by a percent sign.
17523 Also, if more than one register is used then their names are separated by commas; e.g., @code{"eax, ebx"}
17525 The @code{Clobber} parameter has several additional uses:
17527 @item Use the "register" name @code{cc} to indicate that flags might have changed
17528 @item Use the "register" name @code{memory} if you changed a memory location
17531 @c ---------------------------------------------------------------------------
17532 @node The Volatile Parameter
17533 @subsection The @code{Volatile} Parameter
17534 @cindex Volatile parameter
17537 Compiler optimizations in the presence of Inline Assembler may sometimes have unwanted effects.
17539 an @code{Asm} invocation with an input variable is inside a loop, the compiler might move
17540 the loading of the input variable outside the loop, regarding it as a
17541 one-time initialization.
17543 If this effect is not desired, you can disable such optimizations by setting the
17544 @code{Volatile} parameter to @code{True}; for example:
17548 Asm ("movl %0, %%ebx" & LF & HT &
17550 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
17551 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
17557 By default, @code{Volatile} is set to @code{False} unless there is no @code{Outputs}
17560 Although setting @code{Volatile} to @code{True} prevents unwanted optimizations,
17561 it will also disable other optimizations that might be important for efficiency.
17562 In general, you should set @code{Volatile} to @code{True} only if the compiler's
17563 optimizations have created problems.
17565 @c ---------------------------------------------------------------------------
17566 @node A Complete Example
17567 @section A Complete Example
17570 This section contains a complete program illustrating a realistic usage of GNAT's Inline Assembler
17571 capabilities. It comprises a main procedure @code{Check_CPU} and a package @code{Intel_CPU}.
17572 The package declares a collection of functions that detect the properties of the 32-bit
17573 x86 processor that is running the program. The main procedure invokes these functions
17574 and displays the information.
17576 The Intel_CPU package could be enhanced by adding functions to
17577 detect the type of x386 co-processor, the processor caching options and
17578 special operations such as the SIMD extensions.
17580 Although the Intel_CPU package has been written for 32-bit Intel
17581 compatible CPUs, it is OS neutral. It has been tested on DOS,
17582 Windows/NT and Linux.
17585 * Check_CPU Procedure::
17586 * Intel_CPU Package Specification::
17587 * Intel_CPU Package Body::
17590 @c ---------------------------------------------------------------------------
17591 @node Check_CPU Procedure
17592 @subsection @code{Check_CPU} Procedure
17593 @cindex Check_CPU procedure
17596 ---------------------------------------------------------------------
17598 -- Uses the Intel_CPU package to identify the CPU the program is --
17599 -- running on, and some of the features it supports. --
17601 ---------------------------------------------------------------------
17603 with Intel_CPU; -- Intel CPU detection functions
17604 with Ada.Text_IO; -- Standard text I/O
17605 with Ada.Command_Line; -- To set the exit status
17607 procedure Check_CPU is
17609 Type_Found : Boolean := False;
17610 -- Flag to indicate that processor was identified
17612 Features : Intel_CPU.Processor_Features;
17613 -- The processor features
17615 Signature : Intel_CPU.Processor_Signature;
17616 -- The processor type signature
17620 -----------------------------------
17621 -- Display the program banner. --
17622 -----------------------------------
17624 Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name &
17625 ": check Intel CPU version and features, v1.0");
17626 Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever");
17627 Ada.Text_IO.New_Line;
17629 -----------------------------------------------------------------------
17630 -- We can safely start with the assumption that we are on at least --
17631 -- a x386 processor. If the CPUID instruction is present, then we --
17632 -- have a later processor type. --
17633 -----------------------------------------------------------------------
17635 if Intel_CPU.Has_CPUID = False then
17637 -- No CPUID instruction, so we assume this is indeed a x386
17638 -- processor. We can still check if it has a FP co-processor.
17639 if Intel_CPU.Has_FPU then
17640 Ada.Text_IO.Put_Line
17641 ("x386-type processor with a FP co-processor");
17643 Ada.Text_IO.Put_Line
17644 ("x386-type processor without a FP co-processor");
17645 end if; -- check for FPU
17648 Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
17651 end if; -- check for CPUID
17653 -----------------------------------------------------------------------
17654 -- If CPUID is supported, check if this is a true Intel processor, --
17655 -- if it is not, display a warning. --
17656 -----------------------------------------------------------------------
17658 if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then
17659 Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor");
17660 Ada.Text_IO.Put_Line ("*** Some information may be incorrect");
17661 end if; -- check if Intel
17663 ----------------------------------------------------------------------
17664 -- With the CPUID instruction present, we can assume at least a --
17665 -- x486 processor. If the CPUID support level is < 1 then we have --
17666 -- to leave it at that. --
17667 ----------------------------------------------------------------------
17669 if Intel_CPU.CPUID_Level < 1 then
17671 -- Ok, this is a x486 processor. we still can get the Vendor ID
17672 Ada.Text_IO.Put_Line ("x486-type processor");
17673 Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID);
17675 -- We can also check if there is a FPU present
17676 if Intel_CPU.Has_FPU then
17677 Ada.Text_IO.Put_Line ("Floating-Point support");
17679 Ada.Text_IO.Put_Line ("No Floating-Point support");
17680 end if; -- check for FPU
17683 Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
17686 end if; -- check CPUID level
17688 ---------------------------------------------------------------------
17689 -- With a CPUID level of 1 we can use the processor signature to --
17690 -- determine it's exact type. --
17691 ---------------------------------------------------------------------
17693 Signature := Intel_CPU.Signature;
17695 ----------------------------------------------------------------------
17696 -- Ok, now we go into a lot of messy comparisons to get the --
17697 -- processor type. For clarity, no attememt to try to optimize the --
17698 -- comparisons has been made. Note that since Intel_CPU does not --
17699 -- support getting cache info, we cannot distinguish between P5 --
17700 -- and Celeron types yet. --
17701 ----------------------------------------------------------------------
17704 if Signature.Processor_Type = 2#00# and
17705 Signature.Family = 2#0100# and
17706 Signature.Model = 2#0100# then
17707 Type_Found := True;
17708 Ada.Text_IO.Put_Line ("x486SL processor");
17711 -- x486DX2 Write-Back
17712 if Signature.Processor_Type = 2#00# and
17713 Signature.Family = 2#0100# and
17714 Signature.Model = 2#0111# then
17715 Type_Found := True;
17716 Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor");
17720 if Signature.Processor_Type = 2#00# and
17721 Signature.Family = 2#0100# and
17722 Signature.Model = 2#1000# then
17723 Type_Found := True;
17724 Ada.Text_IO.Put_Line ("x486DX4 processor");
17727 -- x486DX4 Overdrive
17728 if Signature.Processor_Type = 2#01# and
17729 Signature.Family = 2#0100# and
17730 Signature.Model = 2#1000# then
17731 Type_Found := True;
17732 Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor");
17735 -- Pentium (60, 66)
17736 if Signature.Processor_Type = 2#00# and
17737 Signature.Family = 2#0101# and
17738 Signature.Model = 2#0001# then
17739 Type_Found := True;
17740 Ada.Text_IO.Put_Line ("Pentium processor (60, 66)");
17743 -- Pentium (75, 90, 100, 120, 133, 150, 166, 200)
17744 if Signature.Processor_Type = 2#00# and
17745 Signature.Family = 2#0101# and
17746 Signature.Model = 2#0010# then
17747 Type_Found := True;
17748 Ada.Text_IO.Put_Line
17749 ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)");
17752 -- Pentium OverDrive (60, 66)
17753 if Signature.Processor_Type = 2#01# and
17754 Signature.Family = 2#0101# and
17755 Signature.Model = 2#0001# then
17756 Type_Found := True;
17757 Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)");
17760 -- Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200)
17761 if Signature.Processor_Type = 2#01# and
17762 Signature.Family = 2#0101# and
17763 Signature.Model = 2#0010# then
17764 Type_Found := True;
17765 Ada.Text_IO.Put_Line
17766 ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)");
17769 -- Pentium OverDrive processor for x486 processor-based systems
17770 if Signature.Processor_Type = 2#01# and
17771 Signature.Family = 2#0101# and
17772 Signature.Model = 2#0011# then
17773 Type_Found := True;
17774 Ada.Text_IO.Put_Line
17775 ("Pentium OverDrive processor for x486 processor-based systems");
17778 -- Pentium processor with MMX technology (166, 200)
17779 if Signature.Processor_Type = 2#00# and
17780 Signature.Family = 2#0101# and
17781 Signature.Model = 2#0100# then
17782 Type_Found := True;
17783 Ada.Text_IO.Put_Line
17784 ("Pentium processor with MMX technology (166, 200)");
17787 -- Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133)
17788 if Signature.Processor_Type = 2#01# and
17789 Signature.Family = 2#0101# and
17790 Signature.Model = 2#0100# then
17791 Type_Found := True;
17792 Ada.Text_IO.Put_Line
17793 ("Pentium OverDrive processor with MMX " &
17794 "technology for Pentium processor (75, 90, 100, 120, 133)");
17797 -- Pentium Pro processor
17798 if Signature.Processor_Type = 2#00# and
17799 Signature.Family = 2#0110# and
17800 Signature.Model = 2#0001# then
17801 Type_Found := True;
17802 Ada.Text_IO.Put_Line ("Pentium Pro processor");
17805 -- Pentium II processor, model 3
17806 if Signature.Processor_Type = 2#00# and
17807 Signature.Family = 2#0110# and
17808 Signature.Model = 2#0011# then
17809 Type_Found := True;
17810 Ada.Text_IO.Put_Line ("Pentium II processor, model 3");
17813 -- Pentium II processor, model 5 or Celeron processor
17814 if Signature.Processor_Type = 2#00# and
17815 Signature.Family = 2#0110# and
17816 Signature.Model = 2#0101# then
17817 Type_Found := True;
17818 Ada.Text_IO.Put_Line
17819 ("Pentium II processor, model 5 or Celeron processor");
17822 -- Pentium Pro OverDrive processor
17823 if Signature.Processor_Type = 2#01# and
17824 Signature.Family = 2#0110# and
17825 Signature.Model = 2#0011# then
17826 Type_Found := True;
17827 Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor");
17830 -- If no type recognized, we have an unknown. Display what
17832 if Type_Found = False then
17833 Ada.Text_IO.Put_Line ("Unknown processor");
17836 -----------------------------------------
17837 -- Display processor stepping level. --
17838 -----------------------------------------
17840 Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img);
17842 ---------------------------------
17843 -- Display vendor ID string. --
17844 ---------------------------------
17846 Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID);
17848 ------------------------------------
17849 -- Get the processors features. --
17850 ------------------------------------
17852 Features := Intel_CPU.Features;
17854 -----------------------------
17855 -- Check for a FPU unit. --
17856 -----------------------------
17858 if Features.FPU = True then
17859 Ada.Text_IO.Put_Line ("Floating-Point unit available");
17861 Ada.Text_IO.Put_Line ("no Floating-Point unit");
17862 end if; -- check for FPU
17864 --------------------------------
17865 -- List processor features. --
17866 --------------------------------
17868 Ada.Text_IO.Put_Line ("Supported features: ");
17870 -- Virtual Mode Extension
17871 if Features.VME = True then
17872 Ada.Text_IO.Put_Line (" VME - Virtual Mode Extension");
17875 -- Debugging Extension
17876 if Features.DE = True then
17877 Ada.Text_IO.Put_Line (" DE - Debugging Extension");
17880 -- Page Size Extension
17881 if Features.PSE = True then
17882 Ada.Text_IO.Put_Line (" PSE - Page Size Extension");
17885 -- Time Stamp Counter
17886 if Features.TSC = True then
17887 Ada.Text_IO.Put_Line (" TSC - Time Stamp Counter");
17890 -- Model Specific Registers
17891 if Features.MSR = True then
17892 Ada.Text_IO.Put_Line (" MSR - Model Specific Registers");
17895 -- Physical Address Extension
17896 if Features.PAE = True then
17897 Ada.Text_IO.Put_Line (" PAE - Physical Address Extension");
17900 -- Machine Check Extension
17901 if Features.MCE = True then
17902 Ada.Text_IO.Put_Line (" MCE - Machine Check Extension");
17905 -- CMPXCHG8 instruction supported
17906 if Features.CX8 = True then
17907 Ada.Text_IO.Put_Line (" CX8 - CMPXCHG8 instruction");
17910 -- on-chip APIC hardware support
17911 if Features.APIC = True then
17912 Ada.Text_IO.Put_Line (" APIC - on-chip APIC hardware support");
17915 -- Fast System Call
17916 if Features.SEP = True then
17917 Ada.Text_IO.Put_Line (" SEP - Fast System Call");
17920 -- Memory Type Range Registers
17921 if Features.MTRR = True then
17922 Ada.Text_IO.Put_Line (" MTTR - Memory Type Range Registers");
17925 -- Page Global Enable
17926 if Features.PGE = True then
17927 Ada.Text_IO.Put_Line (" PGE - Page Global Enable");
17930 -- Machine Check Architecture
17931 if Features.MCA = True then
17932 Ada.Text_IO.Put_Line (" MCA - Machine Check Architecture");
17935 -- Conditional Move Instruction Supported
17936 if Features.CMOV = True then
17937 Ada.Text_IO.Put_Line
17938 (" CMOV - Conditional Move Instruction Supported");
17941 -- Page Attribute Table
17942 if Features.PAT = True then
17943 Ada.Text_IO.Put_Line (" PAT - Page Attribute Table");
17946 -- 36-bit Page Size Extension
17947 if Features.PSE_36 = True then
17948 Ada.Text_IO.Put_Line (" PSE_36 - 36-bit Page Size Extension");
17951 -- MMX technology supported
17952 if Features.MMX = True then
17953 Ada.Text_IO.Put_Line (" MMX - MMX technology supported");
17956 -- Fast FP Save and Restore
17957 if Features.FXSR = True then
17958 Ada.Text_IO.Put_Line (" FXSR - Fast FP Save and Restore");
17961 ---------------------
17962 -- Program done. --
17963 ---------------------
17965 Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
17970 Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
17976 @c ---------------------------------------------------------------------------
17977 @node Intel_CPU Package Specification
17978 @subsection @code{Intel_CPU} Package Specification
17979 @cindex Intel_CPU package specification
17982 -------------------------------------------------------------------------
17984 -- file: intel_cpu.ads --
17986 -- ********************************************* --
17987 -- * WARNING: for 32-bit Intel processors only * --
17988 -- ********************************************* --
17990 -- This package contains a number of subprograms that are useful in --
17991 -- determining the Intel x86 CPU (and the features it supports) on --
17992 -- which the program is running. --
17994 -- The package is based upon the information given in the Intel --
17995 -- Application Note AP-485: "Intel Processor Identification and the --
17996 -- CPUID Instruction" as of April 1998. This application note can be --
17997 -- found on www.intel.com. --
17999 -- It currently deals with 32-bit processors only, will not detect --
18000 -- features added after april 1998, and does not guarantee proper --
18001 -- results on Intel-compatible processors. --
18003 -- Cache info and x386 fpu type detection are not supported. --
18005 -- This package does not use any privileged instructions, so should --
18006 -- work on any OS running on a 32-bit Intel processor. --
18008 -------------------------------------------------------------------------
18010 with Interfaces; use Interfaces;
18011 -- for using unsigned types
18013 with System.Machine_Code; use System.Machine_Code;
18014 -- for using inline assembler code
18016 with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
18017 -- for inserting control characters
18019 package Intel_CPU is
18021 ----------------------
18022 -- Processor bits --
18023 ----------------------
18025 subtype Num_Bits is Natural range 0 .. 31;
18026 -- the number of processor bits (32)
18028 --------------------------
18029 -- Processor register --
18030 --------------------------
18032 -- define a processor register type for easy access to
18033 -- the individual bits
18035 type Processor_Register is array (Num_Bits) of Boolean;
18036 pragma Pack (Processor_Register);
18037 for Processor_Register'Size use 32;
18039 -------------------------
18040 -- Unsigned register --
18041 -------------------------
18043 -- define a processor register type for easy access to
18044 -- the individual bytes
18046 type Unsigned_Register is
18054 for Unsigned_Register use
18056 L1 at 0 range 0 .. 7;
18057 H1 at 0 range 8 .. 15;
18058 L2 at 0 range 16 .. 23;
18059 H2 at 0 range 24 .. 31;
18062 for Unsigned_Register'Size use 32;
18064 ---------------------------------
18065 -- Intel processor vendor ID --
18066 ---------------------------------
18068 Intel_Processor : constant String (1 .. 12) := "GenuineIntel";
18069 -- indicates an Intel manufactured processor
18071 ------------------------------------
18072 -- Processor signature register --
18073 ------------------------------------
18075 -- a register type to hold the processor signature
18077 type Processor_Signature is
18079 Stepping : Natural range 0 .. 15;
18080 Model : Natural range 0 .. 15;
18081 Family : Natural range 0 .. 15;
18082 Processor_Type : Natural range 0 .. 3;
18083 Reserved : Natural range 0 .. 262143;
18086 for Processor_Signature use
18088 Stepping at 0 range 0 .. 3;
18089 Model at 0 range 4 .. 7;
18090 Family at 0 range 8 .. 11;
18091 Processor_Type at 0 range 12 .. 13;
18092 Reserved at 0 range 14 .. 31;
18095 for Processor_Signature'Size use 32;
18097 -----------------------------------
18098 -- Processor features register --
18099 -----------------------------------
18101 -- a processor register to hold the processor feature flags
18103 type Processor_Features is
18105 FPU : Boolean; -- floating point unit on chip
18106 VME : Boolean; -- virtual mode extension
18107 DE : Boolean; -- debugging extension
18108 PSE : Boolean; -- page size extension
18109 TSC : Boolean; -- time stamp counter
18110 MSR : Boolean; -- model specific registers
18111 PAE : Boolean; -- physical address extension
18112 MCE : Boolean; -- machine check extension
18113 CX8 : Boolean; -- cmpxchg8 instruction
18114 APIC : Boolean; -- on-chip apic hardware
18115 Res_1 : Boolean; -- reserved for extensions
18116 SEP : Boolean; -- fast system call
18117 MTRR : Boolean; -- memory type range registers
18118 PGE : Boolean; -- page global enable
18119 MCA : Boolean; -- machine check architecture
18120 CMOV : Boolean; -- conditional move supported
18121 PAT : Boolean; -- page attribute table
18122 PSE_36 : Boolean; -- 36-bit page size extension
18123 Res_2 : Natural range 0 .. 31; -- reserved for extensions
18124 MMX : Boolean; -- MMX technology supported
18125 FXSR : Boolean; -- fast FP save and restore
18126 Res_3 : Natural range 0 .. 127; -- reserved for extensions
18129 for Processor_Features use
18131 FPU at 0 range 0 .. 0;
18132 VME at 0 range 1 .. 1;
18133 DE at 0 range 2 .. 2;
18134 PSE at 0 range 3 .. 3;
18135 TSC at 0 range 4 .. 4;
18136 MSR at 0 range 5 .. 5;
18137 PAE at 0 range 6 .. 6;
18138 MCE at 0 range 7 .. 7;
18139 CX8 at 0 range 8 .. 8;
18140 APIC at 0 range 9 .. 9;
18141 Res_1 at 0 range 10 .. 10;
18142 SEP at 0 range 11 .. 11;
18143 MTRR at 0 range 12 .. 12;
18144 PGE at 0 range 13 .. 13;
18145 MCA at 0 range 14 .. 14;
18146 CMOV at 0 range 15 .. 15;
18147 PAT at 0 range 16 .. 16;
18148 PSE_36 at 0 range 17 .. 17;
18149 Res_2 at 0 range 18 .. 22;
18150 MMX at 0 range 23 .. 23;
18151 FXSR at 0 range 24 .. 24;
18152 Res_3 at 0 range 25 .. 31;
18155 for Processor_Features'Size use 32;
18157 -------------------
18159 -------------------
18161 function Has_FPU return Boolean;
18162 -- return True if a FPU is found
18163 -- use only if CPUID is not supported
18165 function Has_CPUID return Boolean;
18166 -- return True if the processor supports the CPUID instruction
18168 function CPUID_Level return Natural;
18169 -- return the CPUID support level (0, 1 or 2)
18170 -- can only be called if the CPUID instruction is supported
18172 function Vendor_ID return String;
18173 -- return the processor vendor identification string
18174 -- can only be called if the CPUID instruction is supported
18176 function Signature return Processor_Signature;
18177 -- return the processor signature
18178 -- can only be called if the CPUID instruction is supported
18180 function Features return Processor_Features;
18181 -- return the processors features
18182 -- can only be called if the CPUID instruction is supported
18186 ------------------------
18187 -- EFLAGS bit names --
18188 ------------------------
18190 ID_Flag : constant Num_Bits := 21;
18196 @c ---------------------------------------------------------------------------
18197 @node Intel_CPU Package Body
18198 @subsection @code{Intel_CPU} Package Body
18199 @cindex Intel_CPU package body
18202 package body Intel_CPU is
18204 ---------------------------
18205 -- Detect FPU presence --
18206 ---------------------------
18208 -- There is a FPU present if we can set values to the FPU Status
18209 -- and Control Words.
18211 function Has_FPU return Boolean is
18213 Register : Unsigned_16;
18214 -- processor register to store a word
18218 -- check if we can change the status word
18221 -- the assembler code
18222 "finit" & LF & HT & -- reset status word
18223 "movw $0x5A5A, %%ax" & LF & HT & -- set value status word
18224 "fnstsw %0" & LF & HT & -- save status word
18225 "movw %%ax, %0", -- store status word
18227 -- output stored in Register
18228 -- register must be a memory location
18229 Outputs => Unsigned_16'Asm_output ("=m", Register),
18231 -- tell compiler that we used eax
18234 -- if the status word is zero, there is no FPU
18235 if Register = 0 then
18236 return False; -- no status word
18237 end if; -- check status word value
18239 -- check if we can get the control word
18242 -- the assembler code
18243 "fnstcw %0", -- save the control word
18245 -- output into Register
18246 -- register must be a memory location
18247 Outputs => Unsigned_16'Asm_output ("=m", Register));
18249 -- check the relevant bits
18250 if (Register and 16#103F#) /= 16#003F# then
18251 return False; -- no control word
18252 end if; -- check control word value
18259 --------------------------------
18260 -- Detect CPUID instruction --
18261 --------------------------------
18263 -- The processor supports the CPUID instruction if it is possible
18264 -- to change the value of ID flag bit in the EFLAGS register.
18266 function Has_CPUID return Boolean is
18268 Original_Flags, Modified_Flags : Processor_Register;
18269 -- EFLAG contents before and after changing the ID flag
18273 -- try flipping the ID flag in the EFLAGS register
18276 -- the assembler code
18277 "pushfl" & LF & HT & -- push EFLAGS on stack
18278 "pop %%eax" & LF & HT & -- pop EFLAGS into eax
18279 "movl %%eax, %0" & LF & HT & -- save EFLAGS content
18280 "xor $0x200000, %%eax" & LF & HT & -- flip ID flag
18281 "push %%eax" & LF & HT & -- push EFLAGS on stack
18282 "popfl" & LF & HT & -- load EFLAGS register
18283 "pushfl" & LF & HT & -- push EFLAGS on stack
18284 "pop %1", -- save EFLAGS content
18286 -- output values, may be anything
18287 -- Original_Flags is %0
18288 -- Modified_Flags is %1
18290 (Processor_Register'Asm_output ("=g", Original_Flags),
18291 Processor_Register'Asm_output ("=g", Modified_Flags)),
18293 -- tell compiler eax is destroyed
18296 -- check if CPUID is supported
18297 if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then
18298 return True; -- ID flag was modified
18300 return False; -- ID flag unchanged
18301 end if; -- check for CPUID
18305 -------------------------------
18306 -- Get CPUID support level --
18307 -------------------------------
18309 function CPUID_Level return Natural is
18311 Level : Unsigned_32;
18312 -- returned support level
18316 -- execute CPUID, storing the results in the Level register
18319 -- the assembler code
18320 "cpuid", -- execute CPUID
18322 -- zero is stored in eax
18323 -- returning the support level in eax
18324 Inputs => Unsigned_32'Asm_input ("a", 0),
18326 -- eax is stored in Level
18327 Outputs => Unsigned_32'Asm_output ("=a", Level),
18329 -- tell compiler ebx, ecx and edx registers are destroyed
18330 Clobber => "ebx, ecx, edx");
18332 -- return the support level
18333 return Natural (Level);
18337 --------------------------------
18338 -- Get CPU Vendor ID String --
18339 --------------------------------
18341 -- The vendor ID string is returned in the ebx, ecx and edx register
18342 -- after executing the CPUID instruction with eax set to zero.
18343 -- In case of a true Intel processor the string returned is
18346 function Vendor_ID return String is
18348 Ebx, Ecx, Edx : Unsigned_Register;
18349 -- registers containing the vendor ID string
18351 Vendor_ID : String (1 .. 12);
18352 -- the vendor ID string
18356 -- execute CPUID, storing the results in the processor registers
18359 -- the assembler code
18360 "cpuid", -- execute CPUID
18362 -- zero stored in eax
18363 -- vendor ID string returned in ebx, ecx and edx
18364 Inputs => Unsigned_32'Asm_input ("a", 0),
18366 -- ebx is stored in Ebx
18367 -- ecx is stored in Ecx
18368 -- edx is stored in Edx
18369 Outputs => (Unsigned_Register'Asm_output ("=b", Ebx),
18370 Unsigned_Register'Asm_output ("=c", Ecx),
18371 Unsigned_Register'Asm_output ("=d", Edx)));
18373 -- now build the vendor ID string
18374 Vendor_ID( 1) := Character'Val (Ebx.L1);
18375 Vendor_ID( 2) := Character'Val (Ebx.H1);
18376 Vendor_ID( 3) := Character'Val (Ebx.L2);
18377 Vendor_ID( 4) := Character'Val (Ebx.H2);
18378 Vendor_ID( 5) := Character'Val (Edx.L1);
18379 Vendor_ID( 6) := Character'Val (Edx.H1);
18380 Vendor_ID( 7) := Character'Val (Edx.L2);
18381 Vendor_ID( 8) := Character'Val (Edx.H2);
18382 Vendor_ID( 9) := Character'Val (Ecx.L1);
18383 Vendor_ID(10) := Character'Val (Ecx.H1);
18384 Vendor_ID(11) := Character'Val (Ecx.L2);
18385 Vendor_ID(12) := Character'Val (Ecx.H2);
18392 -------------------------------
18393 -- Get processor signature --
18394 -------------------------------
18396 function Signature return Processor_Signature is
18398 Result : Processor_Signature;
18399 -- processor signature returned
18403 -- execute CPUID, storing the results in the Result variable
18406 -- the assembler code
18407 "cpuid", -- execute CPUID
18409 -- one is stored in eax
18410 -- processor signature returned in eax
18411 Inputs => Unsigned_32'Asm_input ("a", 1),
18413 -- eax is stored in Result
18414 Outputs => Processor_Signature'Asm_output ("=a", Result),
18416 -- tell compiler that ebx, ecx and edx are also destroyed
18417 Clobber => "ebx, ecx, edx");
18419 -- return processor signature
18424 ------------------------------
18425 -- Get processor features --
18426 ------------------------------
18428 function Features return Processor_Features is
18430 Result : Processor_Features;
18431 -- processor features returned
18435 -- execute CPUID, storing the results in the Result variable
18438 -- the assembler code
18439 "cpuid", -- execute CPUID
18441 -- one stored in eax
18442 -- processor features returned in edx
18443 Inputs => Unsigned_32'Asm_input ("a", 1),
18445 -- edx is stored in Result
18446 Outputs => Processor_Features'Asm_output ("=d", Result),
18448 -- tell compiler that ebx and ecx are also destroyed
18449 Clobber => "ebx, ecx");
18451 -- return processor signature
18458 @c END OF INLINE ASSEMBLER CHAPTER
18459 @c ===============================
18461 @node Microsoft Windows Topics
18462 @chapter Microsoft Windows Topics
18468 This chapter describes topics that are specific to the Microsoft Windows
18469 platforms (NT, 95 and 98).
18472 * Using GNAT on Windows::
18473 * GNAT Setup Tool::
18474 * CONSOLE and WINDOWS subsystems::
18475 * Temporary Files::
18476 * Mixed-Language Programming on Windows::
18477 * Windows Calling Conventions::
18478 * Introduction to Dynamic Link Libraries (DLLs)::
18479 * Using DLLs with GNAT::
18480 * Building DLLs with GNAT::
18481 * GNAT and Windows Resources::
18482 * Debugging a DLL::
18483 * GNAT and COM/DCOM Objects::
18486 @node Using GNAT on Windows
18487 @section Using GNAT on Windows
18490 One of the strengths of the GNAT technology is that its tool set
18491 (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
18492 @code{gdb} debugger, etc.) is used in the same way regardless of the
18495 On Windows this tool set is complemented by a number of Microsoft-specific
18496 tools that have been provided to facilitate interoperability with Windows
18497 when this is required. With these tools:
18502 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
18506 You can use any Dynamically Linked Library (DLL) in your Ada code (both
18507 relocatable and non-relocatable DLLs are supported).
18510 You can build Ada DLLs for use in other applications. These applications
18511 can be written in a language other than Ada (e.g., C, C++, etc). Again both
18512 relocatable and non-relocatable Ada DLLs are supported.
18515 You can include Windows resources in your Ada application.
18518 You can use or create COM/DCOM objects.
18522 Immediately below are listed all known general GNAT-for-Windows restrictions.
18523 Other restrictions about specific features like Windows Resources and DLLs
18524 are listed in separate sections below.
18529 It is not possible to use @code{GetLastError} and @code{SetLastError}
18530 when tasking, protected records, or exceptions are used. In these
18531 cases, in order to implement Ada semantics, the GNAT run-time system
18532 calls certain Win32 routines that set the last error variable to 0 upon
18533 success. It should be possible to use @code{GetLastError} and
18534 @code{SetLastError} when tasking, protected record, and exception
18535 features are not used, but it is not guaranteed to work.
18538 @node GNAT Setup Tool
18539 @section GNAT Setup Tool
18540 @cindex GNAT Setup Tool
18545 * Command-line arguments::
18546 * Creating a network installation of GNAT::
18547 * Registering and unregistering additional libraries::
18551 GNAT installation on Windows is using the Windows registry in order to
18552 locate proper executables and standard libraries. GNAT setup tool, called
18553 @code{gnatreg.exe}, is provided in order to display and modify GNAT-specific
18554 registry entries, allowing to create network GNAT installations, modify the
18555 locations of GNAT components, as well as register and unregister additional
18556 libraries for use with GNAT.
18558 @node Command-line arguments
18559 @subsection Command-line arguments
18562 @code{gnatreg [switches] [parameter]}
18565 Specifying no arguments causes gnatreg to display current configuration.
18568 The switches understood by gnatreg are:
18571 print the help message
18573 add a standard library
18575 remove a standard library
18577 force creation of keys if they don't exist
18582 @node Creating a network installation of GNAT
18583 @subsection Creating a network installation of GNAT
18586 Make sure the system on which GNAT is installed is accessible from the
18591 @code{@ @ @ gnatreg -f \\server\sharename\path}
18593 in order to setup the registry entries on a current machine.
18595 For example, if GNAT is installed in @file{\GNAT} directory of a share location
18596 called @file{c-drive} on a machine @file{LOKI}, the command that can be used on
18597 other machines to allow the remote use of GNAT is,
18599 @code{@ @ @ gnatreg -f \\loki\c-drive\gnat}
18601 Remember to also add @file{\\loki\c-drive\gnat\bin} in front of your PATH variable.
18603 Be aware that every compilation using the network installation results in the
18604 transfer of large amounts of data across the network and may cause serious
18605 performance penalty.
18607 @node Registering and unregistering additional libraries
18608 @subsection Registering and unregistering additional libraries
18611 To register a standard library use a command:
18613 @code{@ @ @ gnatreg -a <library_name>=<path>}
18617 @code{@ @ @ gnatreg -a WIN32ADA=c:\Win32Ada}
18619 The libraries registered in this manner will be treated like standard libraries
18620 by the compiler (i.e. they don't have to be specified in -I and -l switches to
18621 various GNAT tools).
18623 To unregister a library, enter
18624 @code{ gnatreg -r <library_name>}
18627 @code{ gnatreg -r WIN32ADA}
18629 @node CONSOLE and WINDOWS subsystems
18630 @section CONSOLE and WINDOWS subsystems
18631 @cindex CONSOLE Subsystem
18632 @cindex WINDOWS Subsystem
18636 Under Windows there is two main subsystems. The @code{CONSOLE} subsystem
18637 (which is the default subsystem) will always create a console when
18638 launching the application. This is not something desirable when the
18639 application has a Windows GUI. To get rid of this console the
18640 application must be using the @code{WINDOWS} subsystem. To do so
18641 the @code{-mwindows} linker option must be specified.
18644 $ gnatmake winprog -largs -mwindows
18647 @node Temporary Files
18648 @section Temporary Files
18649 @cindex Temporary files
18652 It is possible to control where temporary files gets created by setting
18653 the TMP environment variable. The file will be created:
18656 @item Under the directory pointed to by the TMP environment variable if
18657 this directory exists.
18659 @item Under c:\temp, if the TMP environment variable is not set (or not
18660 pointing to a directory) and if this directory exists.
18662 @item Under the current working directory otherwise.
18666 This allows you to determine exactly where the temporary
18667 file will be created. This is particularly useful in networked
18668 environments where you may not have write access to some
18671 @node Mixed-Language Programming on Windows
18672 @section Mixed-Language Programming on Windows
18675 Developing pure Ada applications on Windows is no different than on
18676 other GNAT-supported platforms. However, when developing or porting an
18677 application that contains a mix of Ada and C/C++, the choice of your
18678 Windows C/C++ development environment conditions your overall
18679 interoperability strategy.
18681 If you use @code{gcc} to compile the non-Ada part of your application,
18682 there are no Windows-specific restrictions that affect the overall
18683 interoperability with your Ada code. If you plan to use
18684 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
18685 the following limitations:
18689 You cannot link your Ada code with an object or library generated with
18690 Microsoft tools if these use the @code{.tls} section (Thread Local
18691 Storage section) since the GNAT linker does not yet support this section.
18694 You cannot link your Ada code with an object or library generated with
18695 Microsoft tools if these use I/O routines other than those provided in
18696 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
18697 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
18698 libraries can cause a conflict with @code{msvcrt.dll} services. For
18699 instance Visual C++ I/O stream routines conflict with those in
18704 If you do want to use the Microsoft tools for your non-Ada code and hit one
18705 of the above limitations, you have two choices:
18709 Encapsulate your non Ada code in a DLL to be linked with your Ada
18710 application. In this case, use the Microsoft or whatever environment to
18711 build the DLL and use GNAT to build your executable
18712 (@pxref{Using DLLs with GNAT}).
18715 Or you can encapsulate your Ada code in a DLL to be linked with the
18716 other part of your application. In this case, use GNAT to build the DLL
18717 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
18718 environment to build your executable.
18721 @node Windows Calling Conventions
18722 @section Windows Calling Conventions
18727 * C Calling Convention::
18728 * Stdcall Calling Convention::
18729 * DLL Calling Convention::
18733 When a subprogram @code{F} (caller) calls a subprogram @code{G}
18734 (callee), there are several ways to push @code{G}'s parameters on the
18735 stack and there are several possible scenarios to clean up the stack
18736 upon @code{G}'s return. A calling convention is an agreed upon software
18737 protocol whereby the responsibilities between the caller (@code{F}) and
18738 the callee (@code{G}) are clearly defined. Several calling conventions
18739 are available for Windows:
18743 @code{C} (Microsoft defined)
18746 @code{Stdcall} (Microsoft defined)
18749 @code{DLL} (GNAT specific)
18752 @node C Calling Convention
18753 @subsection @code{C} Calling Convention
18756 This is the default calling convention used when interfacing to C/C++
18757 routines compiled with either @code{gcc} or Microsoft Visual C++.
18759 In the @code{C} calling convention subprogram parameters are pushed on the
18760 stack by the caller from right to left. The caller itself is in charge of
18761 cleaning up the stack after the call. In addition, the name of a routine
18762 with @code{C} calling convention is mangled by adding a leading underscore.
18764 The name to use on the Ada side when importing (or exporting) a routine
18765 with @code{C} calling convention is the name of the routine. For
18766 instance the C function:
18769 int get_val (long);
18773 should be imported from Ada as follows:
18777 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
18778 @b{pragma} Import (C, Get_Val, External_Name => "get_val");
18783 Note that in this particular case the @code{External_Name} parameter could
18784 have been omitted since, when missing, this parameter is taken to be the
18785 name of the Ada entity in lower case. When the @code{Link_Name} parameter
18786 is missing, as in the above example, this parameter is set to be the
18787 @code{External_Name} with a leading underscore.
18789 When importing a variable defined in C, you should always use the @code{C}
18790 calling convention unless the object containing the variable is part of a
18791 DLL (in which case you should use the @code{DLL} calling convention,
18792 @pxref{DLL Calling Convention}).
18794 @node Stdcall Calling Convention
18795 @subsection @code{Stdcall} Calling Convention
18798 This convention, which was the calling convention used for Pascal
18799 programs, is used by Microsoft for all the routines in the Win32 API for
18800 efficiency reasons. It must be used to import any routine for which this
18801 convention was specified.
18803 In the @code{Stdcall} calling convention subprogram parameters are pushed
18804 on the stack by the caller from right to left. The callee (and not the
18805 caller) is in charge of cleaning the stack on routine exit. In addition,
18806 the name of a routine with @code{Stdcall} calling convention is mangled by
18807 adding a leading underscore (as for the @code{C} calling convention) and a
18808 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
18809 bytes) of the parameters passed to the routine.
18811 The name to use on the Ada side when importing a C routine with a
18812 @code{Stdcall} calling convention is the name of the C routine. The leading
18813 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
18814 the compiler. For instance the Win32 function:
18817 @b{APIENTRY} int get_val (long);
18821 should be imported from Ada as follows:
18825 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
18826 @b{pragma} Import (Stdcall, Get_Val);
18827 -- @i{On the x86 a long is 4 bytes, so the Link_Name is }"_get_val@@4"
18832 As for the @code{C} calling convention, when the @code{External_Name}
18833 parameter is missing, it is taken to be the name of the Ada entity in lower
18834 case. If instead of writing the above import pragma you write:
18838 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
18839 @b{pragma} Import (Stdcall, Get_Val, External_Name => "retrieve_val");
18844 then the imported routine is @code{_retrieve_val@@4}. However, if instead
18845 of specifying the @code{External_Name} parameter you specify the
18846 @code{Link_Name} as in the following example:
18850 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
18851 @b{pragma} Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
18856 then the imported routine is @code{retrieve_val@@4}, that is, there is no
18857 trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
18858 added at the end of the @code{Link_Name} by the compiler.
18861 Note, that in some special cases a DLL's entry point name lacks a trailing
18862 @code{@@}@code{@i{nn}} while the exported name generated for a call has it.
18863 The @code{gnatdll} tool, which creates the import library for the DLL, is able
18864 to handle those cases (see the description of the switches in
18865 @pxref{Using gnatdll} section).
18867 @node DLL Calling Convention
18868 @subsection @code{DLL} Calling Convention
18871 This convention, which is GNAT-specific, must be used when you want to
18872 import in Ada a variables defined in a DLL. For functions and procedures
18873 this convention is equivalent to the @code{Stdcall} convention. As an
18874 example, if a DLL contains a variable defined as:
18881 then, to access this variable from Ada you should write:
18885 My_Var : Interfaces.C.int;
18886 @b{pragma} Import (DLL, My_Var);
18890 The remarks concerning the @code{External_Name} and @code{Link_Name}
18891 parameters given in the previous sections equally apply to the @code{DLL}
18892 calling convention.
18894 @node Introduction to Dynamic Link Libraries (DLLs)
18895 @section Introduction to Dynamic Link Libraries (DLLs)
18899 A Dynamically Linked Library (DLL) is a library that can be shared by
18900 several applications running under Windows. A DLL can contain any number of
18901 routines and variables.
18903 One advantage of DLLs is that you can change and enhance them without
18904 forcing all the applications that depend on them to be relinked or
18905 recompiled. However, you should be aware than all calls to DLL routines are
18906 slower since, as you will understand below, such calls are indirect.
18908 To illustrate the remainder of this section, suppose that an application
18909 wants to use the services of a DLL @file{API.dll}. To use the services
18910 provided by @file{API.dll} you must statically link against an import
18911 library which contains a jump table with an entry for each routine and
18912 variable exported by the DLL. In the Microsoft world this import library is
18913 called @file{API.lib}. When using GNAT this import library is called either
18914 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
18916 After you have statically linked your application with the import library
18917 and you run your application, here is what happens:
18921 Your application is loaded into memory.
18924 The DLL @file{API.dll} is mapped into the address space of your
18925 application. This means that:
18929 The DLL will use the stack of the calling thread.
18932 The DLL will use the virtual address space of the calling process.
18935 The DLL will allocate memory from the virtual address space of the calling
18939 Handles (pointers) can be safely exchanged between routines in the DLL
18940 routines and routines in the application using the DLL.
18944 The entries in the @file{libAPI.a} or @file{API.lib} jump table which is
18945 part of your application are initialized with the addresses of the routines
18946 and variables in @file{API.dll}.
18949 If present in @file{API.dll}, routines @code{DllMain} or
18950 @code{DllMainCRTStartup} are invoked. These routines typically contain
18951 the initialization code needed for the well-being of the routines and
18952 variables exported by the DLL.
18956 There is an additional point which is worth mentioning. In the Windows
18957 world there are two kind of DLLs: relocatable and non-relocatable
18958 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
18959 in the target application address space. If the addresses of two
18960 non-relocatable DLLs overlap and these happen to be used by the same
18961 application, a conflict will occur and the application will run
18962 incorrectly. Hence, when possible, it is always preferable to use and
18963 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
18966 As a side note, an interesting difference between Microsoft DLLs and
18967 Unix shared libraries, is the fact that on most Unix systems all public
18968 routines are exported by default in a Unix shared library, while under
18969 Windows the exported routines must be listed explicitly in a definition
18970 file (@pxref{The Definition File}).
18972 @node Using DLLs with GNAT
18973 @section Using DLLs with GNAT
18976 * Creating an Ada Spec for the DLL Services::
18977 * Creating an Import Library::
18981 To use the services of a DLL, say @file{API.dll}, in your Ada application
18986 The Ada spec for the routines and/or variables you want to access in
18987 @file{API.dll}. If not available this Ada spec must be built from the C/C++
18988 header files provided with the DLL.
18991 The import library (@file{libAPI.a} or @file{API.lib}). As previously
18992 mentioned an import library is a statically linked library containing the
18993 import table which will be filled at load time to point to the actual
18994 @file{API.dll} routines. Sometimes you don't have an import library for the
18995 DLL you want to use. The following sections will explain how to build one.
18998 The actual DLL, @file{API.dll}.
19002 Once you have all the above, to compile an Ada application that uses the
19003 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
19004 you simply issue the command
19007 $ gnatmake my_ada_app -largs -lAPI
19011 The argument @code{-largs -lAPI} at the end of the @code{gnatmake} command
19012 tells the GNAT linker to look first for a library named @file{API.lib}
19013 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
19014 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
19015 contains the following pragma
19018 @b{pragma} Linker_Options ("-lAPI");
19022 you do not have to add @code{-largs -lAPI} at the end of the @code{gnatmake}
19025 If any one of the items above is missing you will have to create it
19026 yourself. The following sections explain how to do so using as an
19027 example a fictitious DLL called @file{API.dll}.
19029 @node Creating an Ada Spec for the DLL Services
19030 @subsection Creating an Ada Spec for the DLL Services
19033 A DLL typically comes with a C/C++ header file which provides the
19034 definitions of the routines and variables exported by the DLL. The Ada
19035 equivalent of this header file is a package spec that contains definitions
19036 for the imported entities. If the DLL you intend to use does not come with
19037 an Ada spec you have to generate one such spec yourself. For example if
19038 the header file of @file{API.dll} is a file @file{api.h} containing the
19039 following two definitions:
19051 then the equivalent Ada spec could be:
19056 @b{with} Interfaces.C.Strings;
19057 @b{package} API @b{is}
19058 @b{use} Interfaces;
19061 @b{function} Get (Str : C.Strings.Chars_Ptr) @b{return} C.int;
19064 @b{pragma} Import (C, Get);
19065 @b{pragma} Import (DLL, Some_Var);
19072 Note that a variable is @strong{always imported with a DLL convention}. A
19073 function can have @code{C}, @code{Stdcall} or @code{DLL} convention. For
19074 subprograms, the @code{DLL} convention is a synonym of @code{Stdcall}
19075 (@pxref{Windows Calling Conventions}).
19077 @node Creating an Import Library
19078 @subsection Creating an Import Library
19079 @cindex Import library
19082 * The Definition File::
19083 * GNAT-Style Import Library::
19084 * Microsoft-Style Import Library::
19088 If a Microsoft-style import library @file{API.lib} or a GNAT-style
19089 import library @file{libAPI.a} is available with @file{API.dll} you
19090 can skip this section. Otherwise read on.
19092 @node The Definition File
19093 @subsubsection The Definition File
19094 @cindex Definition file
19098 As previously mentioned, and unlike Unix systems, the list of symbols
19099 that are exported from a DLL must be provided explicitly in Windows.
19100 The main goal of a definition file is precisely that: list the symbols
19101 exported by a DLL. A definition file (usually a file with a @code{.def}
19102 suffix) has the following structure:
19108 [DESCRIPTION @i{string}]
19118 @item LIBRARY @i{name}
19119 This section, which is optional, gives the name of the DLL.
19121 @item DESCRIPTION @i{string}
19122 This section, which is optional, gives a description string that will be
19123 embedded in the import library.
19126 This section gives the list of exported symbols (procedures, functions or
19127 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
19128 section of @file{API.def} looks like:
19142 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
19143 (@pxref{Windows Calling Conventions}) for a Stdcall
19144 calling convention function in the exported symbols list.
19147 There can actually be other sections in a definition file, but these
19148 sections are not relevant to the discussion at hand.
19150 @node GNAT-Style Import Library
19151 @subsubsection GNAT-Style Import Library
19154 To create a static import library from @file{API.dll} with the GNAT tools
19155 you should proceed as follows:
19159 Create the definition file @file{API.def} (@pxref{The Definition File}).
19160 For that use the @code{dll2def} tool as follows:
19163 $ dll2def API.dll > API.def
19167 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
19168 to standard output the list of entry points in the DLL. Note that if
19169 some routines in the DLL have the @code{Stdcall} convention
19170 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
19171 suffix then you'll have to edit @file{api.def} to add it.
19174 Here are some hints to find the right @code{@@}@i{nn} suffix.
19178 If you have the Microsoft import library (.lib), it is possible to get
19179 the right symbols by using Microsoft @code{dumpbin} tool (see the
19180 corresponding Microsoft documentation for further details).
19183 $ dumpbin /exports api.lib
19187 If you have a message about a missing symbol at link time the compiler
19188 tells you what symbol is expected. You just have to go back to the
19189 definition file and add the right suffix.
19193 Build the import library @code{libAPI.a}, using @code{gnatdll}
19194 (@pxref{Using gnatdll}) as follows:
19197 $ gnatdll -e API.def -d API.dll
19201 @code{gnatdll} takes as input a definition file @file{API.def} and the
19202 name of the DLL containing the services listed in the definition file
19203 @file{API.dll}. The name of the static import library generated is
19204 computed from the name of the definition file as follows: if the
19205 definition file name is @i{xyz}@code{.def}, the import library name will
19206 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
19207 @code{-e} could have been removed because the name of the definition
19208 file (before the "@code{.def}" suffix) is the same as the name of the
19209 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
19212 @node Microsoft-Style Import Library
19213 @subsubsection Microsoft-Style Import Library
19216 With GNAT you can either use a GNAT-style or Microsoft-style import
19217 library. A Microsoft import library is needed only if you plan to make an
19218 Ada DLL available to applications developed with Microsoft
19219 tools (@pxref{Mixed-Language Programming on Windows}).
19221 To create a Microsoft-style import library for @file{API.dll} you
19222 should proceed as follows:
19226 Create the definition file @file{API.def} from the DLL. For this use either
19227 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
19228 tool (see the corresponding Microsoft documentation for further details).
19231 Build the actual import library using Microsoft's @code{lib} utility:
19234 $ lib -machine:IX86 -def:API.def -out:API.lib
19238 If you use the above command the definition file @file{API.def} must
19239 contain a line giving the name of the DLL:
19246 See the Microsoft documentation for further details about the usage of
19250 @node Building DLLs with GNAT
19251 @section Building DLLs with GNAT
19252 @cindex DLLs, building
19255 * Limitations When Using Ada DLLs from Ada::
19256 * Exporting Ada Entities::
19257 * Ada DLLs and Elaboration::
19258 * Ada DLLs and Finalization::
19259 * Creating a Spec for Ada DLLs::
19260 * Creating the Definition File::
19265 This section explains how to build DLLs containing Ada code. These DLLs
19266 will be referred to as Ada DLLs in the remainder of this section.
19268 The steps required to build an Ada DLL that is to be used by Ada as well as
19269 non-Ada applications are as follows:
19273 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
19274 @code{Stdcall} calling convention to avoid any Ada name mangling for the
19275 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
19276 skip this step if you plan to use the Ada DLL only from Ada applications.
19279 Your Ada code must export an initialization routine which calls the routine
19280 @code{adainit} generated by @code{gnatbind} to perform the elaboration of
19281 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
19282 routine exported by the Ada DLL must be invoked by the clients of the DLL
19283 to initialize the DLL.
19286 When useful, the DLL should also export a finalization routine which calls
19287 routine @code{adafinal} generated by @code{gnatbind} to perform the
19288 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
19289 The finalization routine exported by the Ada DLL must be invoked by the
19290 clients of the DLL when the DLL services are no further needed.
19293 You must provide a spec for the services exported by the Ada DLL in each
19294 of the programming languages to which you plan to make the DLL available.
19297 You must provide a definition file listing the exported entities
19298 (@pxref{The Definition File}).
19301 Finally you must use @code{gnatdll} to produce the DLL and the import
19302 library (@pxref{Using gnatdll}).
19305 @node Limitations When Using Ada DLLs from Ada
19306 @subsection Limitations When Using Ada DLLs from Ada
19309 When using Ada DLLs from Ada applications there is a limitation users
19310 should be aware of. Because on Windows the GNAT run time is not in a DLL of
19311 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
19312 each Ada DLL includes the services of the GNAT run time that are necessary
19313 to the Ada code inside the DLL. As a result, when an Ada program uses an
19314 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
19315 one in the main program.
19317 It is therefore not possible to exchange GNAT run-time objects between the
19318 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
19319 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
19322 It is completely safe to exchange plain elementary, array or record types,
19323 Windows object handles, etc.
19325 @node Exporting Ada Entities
19326 @subsection Exporting Ada Entities
19327 @cindex Export table
19330 Building a DLL is a way to encapsulate a set of services usable from any
19331 application. As a result, the Ada entities exported by a DLL should be
19332 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
19333 any Ada name mangling. Please note that the @code{Stdcall} convention
19334 should only be used for subprograms, not for variables. As an example here
19335 is an Ada package @code{API}, spec and body, exporting two procedures, a
19336 function, and a variable:
19341 @b{with} Interfaces.C; @b{use} Interfaces;
19342 @b{package} API @b{is}
19343 Count : C.int := 0;
19344 @b{function} Factorial (Val : C.int) @b{return} C.int;
19346 @b{procedure} Initialize_API;
19347 @b{procedure} Finalize_API;
19348 -- @i{Initialization & Finalization routines. More in the next section.}
19350 @b{pragma} Export (C, Initialize_API);
19351 @b{pragma} Export (C, Finalize_API);
19352 @b{pragma} Export (C, Count);
19353 @b{pragma} Export (C, Factorial);
19362 @b{package body} API @b{is}
19363 @b{function} Factorial (Val : C.int) @b{return} C.int @b{is}
19366 Count := Count + 1;
19367 @b{for} K @b{in} 1 .. Val @b{loop}
19373 @b{procedure} Initialize_API @b{is}
19374 @b{procedure} Adainit;
19375 @b{pragma} Import (C, Adainit);
19378 @b{end} Initialize_API;
19380 @b{procedure} Finalize_API @b{is}
19381 @b{procedure} Adafinal;
19382 @b{pragma} Import (C, Adafinal);
19385 @b{end} Finalize_API;
19392 If the Ada DLL you are building will only be used by Ada applications
19393 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
19394 convention. As an example, the previous package could be written as
19400 @b{package} API @b{is}
19401 Count : Integer := 0;
19402 @b{function} Factorial (Val : Integer) @b{return} Integer;
19404 @b{procedure} Initialize_API;
19405 @b{procedure} Finalize_API;
19406 -- @i{Initialization and Finalization routines.}
19415 @b{package body} API @b{is}
19416 @b{function} Factorial (Val : Integer) @b{return} Integer @b{is}
19417 Fact : Integer := 1;
19419 Count := Count + 1;
19420 @b{for} K @b{in} 1 .. Val @b{loop}
19427 -- @i{The remainder of this package body is unchanged.}
19434 Note that if you do not export the Ada entities with a @code{C} or
19435 @code{Stdcall} convention you will have to provide the mangled Ada names
19436 in the definition file of the Ada DLL
19437 (@pxref{Creating the Definition File}).
19439 @node Ada DLLs and Elaboration
19440 @subsection Ada DLLs and Elaboration
19441 @cindex DLLs and elaboration
19444 The DLL that you are building contains your Ada code as well as all the
19445 routines in the Ada library that are needed by it. The first thing a
19446 user of your DLL must do is elaborate the Ada code
19447 (@pxref{Elaboration Order Handling in GNAT}).
19449 To achieve this you must export an initialization routine
19450 (@code{Initialize_API} in the previous example), which must be invoked
19451 before using any of the DLL services. This elaboration routine must call
19452 the Ada elaboration routine @code{adainit} generated by the GNAT binder
19453 (@pxref{Binding with Non-Ada Main Programs}). See the body of
19454 @code{Initialize_Api} for an example. Note that the GNAT binder is
19455 automatically invoked during the DLL build process by the @code{gnatdll}
19456 tool (@pxref{Using gnatdll}).
19458 When a DLL is loaded, Windows systematically invokes a routine called
19459 @code{DllMain}. It would therefore be possible to call @code{adainit}
19460 directly from @code{DllMain} without having to provide an explicit
19461 initialization routine. Unfortunately, it is not possible to call
19462 @code{adainit} from the @code{DllMain} if your program has library level
19463 tasks because access to the @code{DllMain} entry point is serialized by
19464 the system (that is, only a single thread can execute "through" it at a
19465 time), which means that the GNAT run time will deadlock waiting for the
19466 newly created task to complete its initialization.
19468 @node Ada DLLs and Finalization
19469 @subsection Ada DLLs and Finalization
19470 @cindex DLLs and finalization
19473 When the services of an Ada DLL are no longer needed, the client code should
19474 invoke the DLL finalization routine, if available. The DLL finalization
19475 routine is in charge of releasing all resources acquired by the DLL. In the
19476 case of the Ada code contained in the DLL, this is achieved by calling
19477 routine @code{adafinal} generated by the GNAT binder
19478 (@pxref{Binding with Non-Ada Main Programs}).
19479 See the body of @code{Finalize_Api} for an
19480 example. As already pointed out the GNAT binder is automatically invoked
19481 during the DLL build process by the @code{gnatdll} tool
19482 (@pxref{Using gnatdll}).
19485 @cindex @code{-g} (@code{gnatdll})
19487 Generate debugging information. This information is stored in the object
19488 file and copied from there to the final DLL file by the linker,
19489 where it can be read by the debugger. You must use the
19490 @code{-g} switch if you plan on using the debugger or the symbolic
19493 @node Creating a Spec for Ada DLLs
19494 @subsection Creating a Spec for Ada DLLs
19497 To use the services exported by the Ada DLL from another programming
19498 language (e.g. C), you have to translate the specs of the exported Ada
19499 entities in that language. For instance in the case of @code{API.dll},
19500 the corresponding C header file could look like:
19505 extern int *__imp__count;
19506 #define count (*__imp__count)
19507 int factorial (int);
19513 It is important to understand that when building an Ada DLL to be used by
19514 other Ada applications, you need two different specs for the packages
19515 contained in the DLL: one for building the DLL and the other for using
19516 the DLL. This is because the @code{DLL} calling convention is needed to
19517 use a variable defined in a DLL, but when building the DLL, the variable
19518 must have either the @code{Ada} or @code{C} calling convention. As an
19519 example consider a DLL comprising the following package @code{API}:
19524 @b{package} API @b{is}
19525 Count : Integer := 0;
19527 -- @i{Remainder of the package omitted.}
19534 After producing a DLL containing package @code{API}, the spec that
19535 must be used to import @code{API.Count} from Ada code outside of the
19541 @b{package} API @b{is}
19543 @b{pragma} Import (DLL, Count);
19549 @node Creating the Definition File
19550 @subsection Creating the Definition File
19553 The definition file is the last file needed to build the DLL. It lists
19554 the exported symbols. As an example, the definition file for a DLL
19555 containing only package @code{API} (where all the entities are exported
19556 with a @code{C} calling convention) is:
19571 If the @code{C} calling convention is missing from package @code{API},
19572 then the definition file contains the mangled Ada names of the above
19573 entities, which in this case are:
19582 api__initialize_api
19587 @node Using gnatdll
19588 @subsection Using @code{gnatdll}
19592 * gnatdll Example::
19593 * gnatdll behind the Scenes::
19598 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
19599 and non-Ada sources that make up your DLL have been compiled.
19600 @code{gnatdll} is actually in charge of two distinct tasks: build the
19601 static import library for the DLL and the actual DLL. The form of the
19602 @code{gnatdll} command is
19606 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
19611 where @i{list-of-files} is a list of ALI and object files. The object
19612 file list must be the exact list of objects corresponding to the non-Ada
19613 sources whose services are to be included in the DLL. The ALI file list
19614 must be the exact list of ALI files for the corresponding Ada sources
19615 whose services are to be included in the DLL. If @i{list-of-files} is
19616 missing, only the static import library is generated.
19619 You may specify any of the following switches to @code{gnatdll}:
19622 @item -a[@var{address}]
19623 @cindex @code{-a} (@code{gnatdll})
19624 Build a non-relocatable DLL at @var{address}. If @var{address} is not
19625 specified the default address @var{0x11000000} will be used. By default,
19626 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
19627 advise the reader to build relocatable DLL.
19629 @item -b @var{address}
19630 @cindex @code{-b} (@code{gnatdll})
19631 Set the relocatable DLL base address. By default the address is
19634 @item -d @var{dllfile}
19635 @cindex @code{-d} (@code{gnatdll})
19636 @var{dllfile} is the name of the DLL. This switch must be present for
19637 @code{gnatdll} to do anything. The name of the generated import library is
19638 obtained algorithmically from @var{dllfile} as shown in the following
19639 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
19640 @code{libxyz.a}. The name of the definition file to use (if not specified
19641 by option @code{-e}) is obtained algorithmically from @var{dllfile} as shown in
19642 the following example: if @var{dllfile} is @code{xyz.dll}, the definition
19643 file used is @code{xyz.def}.
19645 @item -e @var{deffile}
19646 @cindex @code{-e} (@code{gnatdll})
19647 @var{deffile} is the name of the definition file.
19650 @cindex @code{-h} (@code{gnatdll})
19651 Help mode. Displays @code{gnatdll} switch usage information.
19654 Direct @code{gnatdll} to search the @var{dir} directory for source and
19655 object files needed to build the DLL.
19656 (@pxref{Search Paths and the Run-Time Library (RTL)}).
19659 Removes the @code{@@}@i{nn} suffix from the import library's exported
19660 names. You must specified this option if you want to use a
19661 @code{Stdcall} function in a DLL for which the @code{@@}@i{nn} suffix
19662 has been removed. This is the case for most of the Windows NT DLL for
19663 example. This option has no effect when @code{-n} option is specified.
19665 @item -l @var{file}
19666 @cindex @code{-l} (@code{gnatdll})
19667 The list of ALI and object files used to build the DLL are listed in
19668 @var{file}, instead of being given in the command line. Each line in
19669 @var{file} contains the name of an ALI or object file.
19672 @cindex @code{-n} (@code{gnatdll})
19673 No Import. Do not create the import library.
19676 @cindex @code{-q} (@code{gnatdll})
19677 Quiet mode. Do not display unnecessary messages.
19680 @cindex @code{-v} (@code{gnatdll})
19681 Verbose mode. Display extra information.
19683 @item -largs @var{opts}
19684 @cindex @code{-largs} (@code{gnatdll})
19685 Linker options. Pass @var{opts} to the linker.
19688 @node gnatdll Example
19689 @subsubsection @code{gnatdll} Example
19692 As an example the command to build a relocatable DLL from @file{api.adb}
19693 once @file{api.adb} has been compiled and @file{api.def} created is
19696 $ gnatdll -d api.dll api.ali
19700 The above command creates two files: @file{libapi.a} (the import
19701 library) and @file{api.dll} (the actual DLL). If you want to create
19702 only the DLL, just type:
19705 $ gnatdll -d api.dll -n api.ali
19709 Alternatively if you want to create just the import library, type:
19712 $ gnatdll -d api.dll
19715 @node gnatdll behind the Scenes
19716 @subsubsection @code{gnatdll} behind the Scenes
19719 This section details the steps involved in creating a DLL. @code{gnatdll}
19720 does these steps for you. Unless you are interested in understanding what
19721 goes on behind the scenes, you should skip this section.
19723 We use the previous example of a DLL containing the Ada package @code{API},
19724 to illustrate the steps necessary to build a DLL. The starting point is a
19725 set of objects that will make up the DLL and the corresponding ALI
19726 files. In the case of this example this means that @file{api.o} and
19727 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
19732 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
19733 the information necessary to generate relocation information for the
19739 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
19744 In addition to the base file, the @code{gnatlink} command generates an
19745 output file @file{api.jnk} which can be discarded. The @code{-mdll} switch
19746 asks @code{gnatlink} to generate the routines @code{DllMain} and
19747 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
19748 is loaded into memory.
19751 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
19752 export table (@file{api.exp}). The export table contains the relocation
19753 information in a form which can be used during the final link to ensure
19754 that the Windows loader is able to place the DLL anywhere in memory.
19758 $ dlltool --dllname api.dll --def api.def --base-file api.base \
19759 --output-exp api.exp
19764 @code{gnatdll} builds the base file using the new export table. Note that
19765 @code{gnatbind} must be called once again since the binder generated file
19766 has been deleted during the previous call to @code{gnatlink}.
19771 $ gnatlink api -o api.jnk api.exp -mdll
19772 -Wl,--base-file,api.base
19777 @code{gnatdll} builds the new export table using the new base file and
19778 generates the DLL import library @file{libAPI.a}.
19782 $ dlltool --dllname api.dll --def api.def --base-file api.base \
19783 --output-exp api.exp --output-lib libAPI.a
19788 Finally @code{gnatdll} builds the relocatable DLL using the final export
19794 $ gnatlink api api.exp -o api.dll -mdll
19799 @node Using dlltool
19800 @subsubsection Using @code{dlltool}
19803 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
19804 DLLs and static import libraries. This section summarizes the most
19805 common @code{dlltool} switches. The form of the @code{dlltool} command
19809 $ dlltool [@var{switches}]
19813 @code{dlltool} switches include:
19816 @item --base-file @var{basefile}
19817 Read the base file @var{basefile} generated by the linker. This switch
19818 is used to create a relocatable DLL.
19820 @item --def @var{deffile}
19821 Read the definition file.
19823 @item --dllname @var{name}
19824 Gives the name of the DLL. This switch is used to embed the name of the
19825 DLL in the static import library generated by @code{dlltool} with switch
19826 @code{--output-lib}.
19829 Kill @code{@@}@i{nn} from exported names
19830 (@pxref{Windows Calling Conventions}
19831 for a discussion about @code{Stdcall}-style symbols.
19834 Prints the @code{dlltool} switches with a concise description.
19836 @item --output-exp @var{exportfile}
19837 Generate an export file @var{exportfile}. The export file contains the
19838 export table (list of symbols in the DLL) and is used to create the DLL.
19840 @item --output-lib @i{libfile}
19841 Generate a static import library @var{libfile}.
19846 @item --as @i{assembler-name}
19847 Use @i{assembler-name} as the assembler. The default is @code{as}.
19850 @node GNAT and Windows Resources
19851 @section GNAT and Windows Resources
19852 @cindex Resources, windows
19855 * Building Resources::
19856 * Compiling Resources::
19857 * Using Resources::
19862 Resources are an easy way to add Windows specific objects to your
19863 application. The objects that can be added as resources include:
19892 This section explains how to build, compile and use resources.
19894 @node Building Resources
19895 @subsection Building Resources
19896 @cindex Resources, building
19899 A resource file is an ASCII file. By convention resource files have an
19900 @file{.rc} extension.
19901 The easiest way to build a resource file is to use Microsoft tools
19902 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
19903 @code{dlgedit.exe} to build dialogs.
19904 It is always possible to build an @file{.rc} file yourself by writing a
19907 It is not our objective to explain how to write a resource file. A
19908 complete description of the resource script language can be found in the
19909 Microsoft documentation.
19911 @node Compiling Resources
19912 @subsection Compiling Resources
19916 @cindex Resources, compiling
19919 This section describes how to build a GNAT-compatible (COFF) object file
19920 containing the resources. This is done using the Resource Compiler
19921 @code{rcl} as follows:
19924 $ rcl -i myres.rc -o myres.o
19928 By default @code{rcl} will run @code{gcc} to preprocess the @file{.rc}
19929 file. You can specify an alternate preprocessor (usually named
19930 @file{cpp.exe}) using the @code{rcl} @code{-cpp} parameter. A list of
19931 all possible options may be obtained by entering the command @code{rcl}
19932 with no parameters.
19934 It is also possible to use the Microsoft resource compiler @code{rc.exe}
19935 to produce a @file{.res} file (binary resource file). See the
19936 corresponding Microsoft documentation for further details. In this case
19937 you need to use @code{res2coff} to translate the @file{.res} file to a
19938 GNAT-compatible object file as follows:
19941 $ res2coff -i myres.res -o myres.o
19944 @node Using Resources
19945 @subsection Using Resources
19946 @cindex Resources, using
19949 To include the resource file in your program just add the
19950 GNAT-compatible object file for the resource(s) to the linker
19951 arguments. With @code{gnatmake} this is done by using the @code{-largs}
19955 $ gnatmake myprog -largs myres.o
19959 @subsection Limitations
19960 @cindex Resources, limitations
19963 In this section we describe the current limitations together with
19964 suggestions for workarounds.
19968 @code{rcl} does not handle the @code{RCINCLUDE} directive.
19970 Workaround: replace @code{RCINCLUDE} by an @code{#include} directive.
19973 @code{rcl} does not handle the brackets as block delimiters.
19975 Workaround: replace character '@{' by @code{BEGIN} and '@}' by
19976 @code{END}. Note that Microsoft's @code{rc} handles both forms of block
19980 @code{rcl} does not handle @code{TypeLib} resources. This type of
19981 resource is used to build COM, DCOM or ActiveX objects.
19983 Workaround: use @code{rc}, the Microsoft resource compiler.
19986 It is not possible to use @code{strip} to remove the debugging symbols
19987 from a program with resources.
19989 Workaround: use linker option @code{-s} to strip debugging symbols from
19990 the final executable.
19993 @node Debugging a DLL
19994 @section Debugging a DLL
19995 @cindex DLL debugging
19998 * The Program and the DLL Are Built with GCC/GNAT::
19999 * The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT::
20003 Debugging a DLL is similar to debugging a standard program. But
20004 we have to deal with two different executable parts: the DLL and the
20005 program that uses it. We have the following four possibilities:
20009 The program and the DLL are built with @code{GCC/GNAT}.
20011 The program is built with foreign tools and the DLL is built with
20014 The program is built with @code{GCC/GNAT} and the DLL is built with
20020 In this section we address only cases one and two above.
20021 There is no point in trying to debug
20022 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
20023 information in it. To do so you must use a debugger compatible with the
20024 tools suite used to build the DLL.
20026 @node The Program and the DLL Are Built with GCC/GNAT
20027 @subsection The Program and the DLL Are Built with GCC/GNAT
20030 This is the simplest case. Both the DLL and the program have @code{GDB}
20031 compatible debugging information. It is then possible to break anywhere in
20032 the process. Let's suppose here that the main procedure is named
20033 @code{ada_main} and that in the DLL there is an entry point named
20037 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
20038 program must have been built with the debugging information (see GNAT -g
20039 switch). Here are the step-by-step instructions for debugging it:
20042 @item Launch @code{GDB} on the main program.
20048 @item Break on the main procedure and run the program.
20051 (gdb) break ada_main
20056 This step is required to be able to set a breakpoint inside the DLL. As long
20057 as the program is not run, the DLL is not loaded. This has the
20058 consequence that the DLL debugging information is also not loaded, so it is not
20059 possible to set a breakpoint in the DLL.
20061 @item Set a breakpoint inside the DLL
20064 (gdb) break ada_dll
20071 At this stage a breakpoint is set inside the DLL. From there on
20072 you can use the standard approach to debug the whole program
20073 (@pxref{Running and Debugging Ada Programs}).
20075 @node The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT
20076 @subsection The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT
20079 * Debugging the DLL Directly::
20080 * Attaching to a Running Process::
20084 In this case things are slightly more complex because it is not possible to
20085 start the main program and then break at the beginning to load the DLL and the
20086 associated DLL debugging information. It is not possible to break at the
20087 beginning of the program because there is no @code{GDB} debugging information,
20088 and therefore there is no direct way of getting initial control. This
20089 section addresses this issue by describing some methods that can be used
20090 to break somewhere in the DLL to debug it.
20093 First suppose that the main procedure is named @code{main} (this is for
20094 example some C code built with Microsoft Visual C) and that there is a
20095 DLL named @code{test.dll} containing an Ada entry point named
20099 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
20100 been built with debugging information (see GNAT -g option).
20102 @node Debugging the DLL Directly
20103 @subsubsection Debugging the DLL Directly
20107 Launch the debugger on the DLL.
20113 @item Set a breakpoint on a DLL subroutine.
20116 (gdb) break ada_dll
20120 Specify the executable file to @code{GDB}.
20123 (gdb) exec-file main.exe
20134 This will run the program until it reaches the breakpoint that has been
20135 set. From that point you can use the standard way to debug a program
20136 as described in (@pxref{Running and Debugging Ada Programs}).
20141 It is also possible to debug the DLL by attaching to a running process.
20143 @node Attaching to a Running Process
20144 @subsubsection Attaching to a Running Process
20145 @cindex DLL debugging, attach to process
20148 With @code{GDB} it is always possible to debug a running process by
20149 attaching to it. It is possible to debug a DLL this way. The limitation
20150 of this approach is that the DLL must run long enough to perform the
20151 attach operation. It may be useful for instance to insert a time wasting
20152 loop in the code of the DLL to meet this criterion.
20156 @item Launch the main program @file{main.exe}.
20162 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
20163 that the process PID for @file{main.exe} is 208.
20171 @item Attach to the running process to be debugged.
20177 @item Load the process debugging information.
20180 (gdb) symbol-file main.exe
20183 @item Break somewhere in the DLL.
20186 (gdb) break ada_dll
20189 @item Continue process execution.
20198 This last step will resume the process execution, and stop at
20199 the breakpoint we have set. From there you can use the standard
20200 approach to debug a program as described in
20201 (@pxref{Running and Debugging Ada Programs}).
20203 @node GNAT and COM/DCOM Objects
20204 @section GNAT and COM/DCOM Objects
20209 This section is temporarily left blank.
20213 ???????????? WE NEED TO DECIDE WHETHER TO DISTRIBUTE IT ??????????????????????
20215 @node gnatreg : Registry Tool for NT
20216 @section @code{gnatreg} : Registry Tool for NT
20221 * Changing the GNAT compiler to Use::
20222 * Adding/Changing a Library Path::
20223 * Removing a Library Path::
20224 * List Current Configuration::
20228 This tool can be used to switch from one compiler to another and to manage
20229 the list of directories where GNAT must look to find packages. It is
20230 also a convenient way to do network installation of GNAT.
20232 The form of the @code{gnatreg} command is
20235 $ gnatreg [@var{-hqcarf}] parameter
20239 Commons options are
20244 print a usage message.
20247 quiet/terse - display nothing, just do the job.
20250 force mode - create the registry keys if they do not
20251 exist. @code{gnatreg} will exit with an error if this option is omitted
20252 and some registry keys are not setup correctly.
20256 @subsection Changing the GNAT compiler to use
20259 $ gnatreg c:\gnatpro
20263 This will setup the registry to use the GNAT compiler that has been
20264 installed under c:\gnatpro. @code{gnatreg} check that this directory contain
20265 effectively a GNAT compiler. If you want to setup a network installation
20266 and if GNAT has never been installed on this computer you'll have to use
20269 @subsection Adding/Changing a library path
20272 $ gnatreg -a COMPNT=c:\ada\components
20276 Add the directory c:\ada\components to the list of standards libraries. When
20277 running gnatmake the option -Ic:\ada\components is added automatically to the
20280 The directory c:\ada\components is associated with the name COMPNT. This
20281 name will be used to remove the library path.
20283 @subsection Removing a library path
20286 $ gnatreg -r COMPNT
20290 Remove the library path named COMPNT.
20292 @subsection List current configuration
20299 @code{gnatreg} will display the GNAT and AdaGIDE path used and
20300 all the standards libraries and their associated names that have been set.
20306 @node Performance Considerations
20307 @chapter Performance Considerations
20308 @cindex Performance
20311 The GNAT system provides a number of options that allow a trade-off
20316 performance of the generated code
20319 speed of compilation
20322 minimization of dependences and recompilation
20325 the degree of run-time checking.
20329 The defaults (if no options are selected) aim at improving the speed
20330 of compilation and minimizing dependences, at the expense of performance
20331 of the generated code:
20338 no inlining of subprogram calls
20341 all run-time checks enabled except overflow and elaboration checks
20345 These options are suitable for most program development purposes. This
20346 chapter describes how you can modify these choices, and also provides
20347 some guidelines on debugging optimized code.
20350 * Controlling Run-Time Checks::
20351 * Optimization Levels::
20352 * Debugging Optimized Code::
20353 * Inlining of Subprograms::
20356 @node Controlling Run-Time Checks
20357 @section Controlling Run-Time Checks
20360 By default, GNAT generates all run-time checks, except arithmetic overflow
20361 checking for integer operations and checks for access before elaboration on
20362 subprogram calls. The latter are not required in default mode, because all
20363 necessary checking is done at compile time.
20364 @cindex @option{-gnatp} (@code{gcc})
20365 @cindex @option{-gnato} (@code{gcc})
20366 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
20367 be modified. @xref{Run-Time Checks}.
20369 Our experience is that the default is suitable for most development
20372 We treat integer overflow specially because these
20373 are quite expensive and in our experience are not as important as other
20374 run-time checks in the development process. Note that division by zero
20375 is not considered an overflow check, and divide by zero checks are
20376 generated where required by default.
20378 Elaboration checks are off by default, and also not needed by default, since
20379 GNAT uses a static elaboration analysis approach that avoids the need for
20380 run-time checking. This manual contains a full chapter discussing the issue
20381 of elaboration checks, and if the default is not satisfactory for your use,
20382 you should read this chapter.
20384 For validity checks, the minimal checks required by the Ada Reference
20385 Manual (for case statements and assignments to array elements) are on
20386 by default. These can be suppressed by use of the @option{-gnatVn} switch.
20387 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
20388 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
20389 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
20390 are also suppressed entirely if @option{-gnatp} is used.
20392 @cindex Overflow checks
20393 @cindex Checks, overflow
20396 @cindex pragma Suppress
20397 @cindex pragma Unsuppress
20398 Note that the setting of the switches controls the default setting of
20399 the checks. They may be modified using either @code{pragma Suppress} (to
20400 remove checks) or @code{pragma Unsuppress} (to add back suppressed
20401 checks) in the program source.
20403 @node Optimization Levels
20404 @section Optimization Levels
20405 @cindex @code{-O} (@code{gcc})
20408 The default is optimization off. This results in the fastest compile
20409 times, but GNAT makes absolutely no attempt to optimize, and the
20410 generated programs are considerably larger and slower than when
20411 optimization is enabled. You can use the
20412 @code{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
20413 on the @code{gcc} command line to control the optimization level:
20417 no optimization (the default)
20420 medium level optimization
20426 full optimization, and also attempt automatic inlining of small
20427 subprograms within a unit (@pxref{Inlining of Subprograms}).
20430 Higher optimization levels perform more global transformations on the
20431 program and apply more expensive analysis algorithms in order to generate
20432 faster and more compact code. The price in compilation time, and the
20433 resulting improvement in execution time,
20434 both depend on the particular application and the hardware environment.
20435 You should experiment to find the best level for your application.
20437 Note: Unlike some other compilation systems, @code{gcc} has
20438 been tested extensively at all optimization levels. There are some bugs
20439 which appear only with optimization turned on, but there have also been
20440 bugs which show up only in @emph{unoptimized} code. Selecting a lower
20441 level of optimization does not improve the reliability of the code
20442 generator, which in practice is highly reliable at all optimization
20445 Note regarding the use of @code{-O3}: The use of this optimization level
20446 is generally discouraged with GNAT, since it often results in larger
20447 executables which run more slowly. See further discussion of this point
20448 in @pxref{Inlining of Subprograms}.
20450 @node Debugging Optimized Code
20451 @section Debugging Optimized Code
20454 Since the compiler generates debugging tables for a compilation unit before
20455 it performs optimizations, the optimizing transformations may invalidate some
20456 of the debugging data. You therefore need to anticipate certain
20457 anomalous situations that may arise while debugging optimized code. This
20458 section describes the most common cases.
20462 @i{The "hopping Program Counter":} Repeated 'step' or 'next' commands show the PC
20463 bouncing back and forth in the code. This may result from any of the following
20468 @i{Common subexpression elimination:} using a single instance of code for a
20469 quantity that the source computes several times. As a result you
20470 may not be able to stop on what looks like a statement.
20473 @i{Invariant code motion:} moving an expression that does not change within a
20474 loop, to the beginning of the loop.
20477 @i{Instruction scheduling:} moving instructions so as to
20478 overlap loads and stores (typically) with other code, or in
20479 general to move computations of values closer to their uses. Often
20480 this causes you to pass an assignment statement without the assignment
20481 happening and then later bounce back to the statement when the
20482 value is actually needed. Placing a breakpoint on a line of code
20483 and then stepping over it may, therefore, not always cause all the
20484 expected side-effects.
20488 @i{The "big leap":} More commonly known as @i{cross-jumping}, in which two
20489 identical pieces of code are merged and the program counter suddenly
20490 jumps to a statement that is not supposed to be executed, simply because
20491 it (and the code following) translates to the same thing as the code
20492 that @emph{was} supposed to be executed. This effect is typically seen in
20493 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
20494 a @code{break} in a C @code{switch} statement.
20497 @i{The "roving variable":} The symptom is an unexpected value in a variable.
20498 There are various reasons for this effect:
20502 In a subprogram prologue, a parameter may not yet have been moved to its
20506 A variable may be dead, and its register re-used. This is
20507 probably the most common cause.
20510 As mentioned above, the assignment of a value to a variable may
20514 A variable may be eliminated entirely by value propagation or
20515 other means. In this case, GCC may incorrectly generate debugging
20516 information for the variable
20520 In general, when an unexpected value appears for a local variable or parameter
20521 you should first ascertain if that value was actually computed by
20522 your program, as opposed to being incorrectly reported by the debugger.
20524 array elements in an object designated by an access value
20525 are generally less of a problem, once you have ascertained that the access value
20527 Typically, this means checking variables in the preceding code and in the
20528 calling subprogram to verify that the value observed is explainable from other
20529 values (one must apply the procedure recursively to those
20530 other values); or re-running the code and stopping a little earlier
20531 (perhaps before the call) and stepping to better see how the variable obtained
20532 the value in question; or continuing to step @emph{from} the point of the
20533 strange value to see if code motion had simply moved the variable's
20537 @node Inlining of Subprograms
20538 @section Inlining of Subprograms
20541 A call to a subprogram in the current unit is inlined if all the
20542 following conditions are met:
20546 The optimization level is at least @code{-O1}.
20549 The called subprogram is suitable for inlining: It must be small enough
20550 and not contain nested subprograms or anything else that @code{gcc}
20551 cannot support in inlined subprograms.
20554 The call occurs after the definition of the body of the subprogram.
20557 @cindex pragma Inline
20559 Either @code{pragma Inline} applies to the subprogram or it is
20560 small and automatic inlining (optimization level @code{-O3}) is
20565 Calls to subprograms in @code{with}'ed units are normally not inlined.
20566 To achieve this level of inlining, the following conditions must all be
20571 The optimization level is at least @code{-O1}.
20574 The called subprogram is suitable for inlining: It must be small enough
20575 and not contain nested subprograms or anything else @code{gcc} cannot
20576 support in inlined subprograms.
20579 The call appears in a body (not in a package spec).
20582 There is a @code{pragma Inline} for the subprogram.
20585 @cindex @option{-gnatn} (@code{gcc})
20586 The @code{-gnatn} switch
20587 is used in the @code{gcc} command line
20590 Note that specifying the @option{-gnatn} switch causes additional
20591 compilation dependencies. Consider the following:
20596 @b{package} R @b{is}
20598 @b{pragma} Inline (Q);
20600 @b{package body} R @b{is}
20605 @b{procedure} Main @b{is}
20615 With the default behavior (no @option{-gnatn} switch specified), the
20616 compilation of the @code{Main} procedure depends only on its own source,
20617 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
20618 means that editing the body of @code{R} does not require recompiling
20621 On the other hand, the call @code{R.Q} is not inlined under these
20622 circumstances. If the @option{-gnatn} switch is present when @code{Main}
20623 is compiled, the call will be inlined if the body of @code{Q} is small
20624 enough, but now @code{Main} depends on the body of @code{R} in
20625 @file{r.adb} as well as on the spec. This means that if this body is edited,
20626 the main program must be recompiled. Note that this extra dependency
20627 occurs whether or not the call is in fact inlined by @code{gcc}.
20629 The use of front end inlining with @option{-gnatN} generates similar
20630 additional dependencies.
20632 @cindex @code{-fno-inline} (@code{gcc})
20633 Note: The @code{-fno-inline} switch
20634 can be used to prevent
20635 all inlining. This switch overrides all other conditions and ensures
20636 that no inlining occurs. The extra dependences resulting from
20637 @option{-gnatn} will still be active, even if
20638 this switch is used to suppress the resulting inlining actions.
20640 Note regarding the use of @code{-O3}: There is no difference in inlining
20641 behavior between @code{-O2} and @code{-O3} for subprograms with an explicit
20642 pragma @code{Inline} assuming the use of @option{-gnatn}
20643 or @option{-gnatN} (the switches that activate inlining). If you have used
20644 pragma @code{Inline} in appropriate cases, then it is usually much better
20645 to use @code{-O2} and @option{-gnatn} and avoid the use of @code{-O3} which
20646 in this case only has the effect of inlining subprograms you did not
20647 think should be inlined. We often find that the use of @code{-O3} slows
20648 down code by performing excessive inlining, leading to increased instruction
20649 cache pressure from the increased code size. So the bottom line here is
20650 that you should not automatically assume that @code{-O3} is better than
20651 @code{-O2}, and indeed you should use @code{-O3} only if tests show that
20652 it actually improves performance.
20656 @c GNU Free Documentation License
20658 @node Index,,GNU Free Documentation License, Top