OSDN Git Service

PR bootstrap/11932
[pf3gnuchains/gcc-fork.git] / gcc / ada / gnat_ug_unx.texi
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c                                                                            o
6 @c                            GNAT DOCUMENTATION                              o
7 @c                                                                            o
8 @c                              G N A T _ U G                                 o
9 @c                                                                            o
10 @c          Copyright (C) 1992-2002 Ada Core Technologies, Inc.               o
11 @c                                                                            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
22 @c                                                                            o
23 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
24
25 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
26 @c
27 @c                           GNAT_UG Style Guide
28 @c
29 @c  1. Always put a @noindent on the line before the first paragraph
30 @c     after any of these commands:
31 @c
32 @c          @chapter
33 @c          @section
34 @c          @subsection
35 @c          @subsubsection
36 @c          @subsubsubsection
37 @c
38 @c          @end smallexample
39 @c          @end itemize
40 @c          @end enumerate
41 @c
42 @c  2. DO NOT use @example. Use @smallexample instead.
43 @c
44 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
45 @c     command must be preceded by two empty lines
46 @c
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.
49 @c
50 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
51 @c     or "ali".
52 @c
53 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
54
55
56
57 @setfilename gnat_ug_unx.info
58 @settitle GNAT User's Guide for Unix Platforms
59
60
61 @include gcc-common.texi
62
63 @setchapternewpage odd
64 @syncodeindex fn cp
65 @c %**end of header
66
67 @copying
68 Copyright @copyright{} 1995-2003, Free Software Foundation
69
70 Permission is granted to copy, distribute and/or modify this document
71 under the terms of the GNU Free Documentation License, Version 1.2
72 or any later version published by the Free Software Foundation;
73 with the Invariant Sections being ``GNU Free Documentation License'', with the
74 Front-Cover Texts being
75 ``GNAT User's Guide for Unix Platforms'',
76 and with no Back-Cover Texts.
77 A copy of the license is included in the section entitled ``GNU
78 Free Documentation License''.
79 @end copying
80
81 @titlepage
82
83
84
85 @title GNAT User's Guide
86 @center @titlefont{for Unix Platforms}
87
88
89 @subtitle GNAT, The GNU Ada 95 Compiler
90 @subtitle GNAT Version for GCC @value{version-GCC}
91
92 @author Ada Core Technologies, Inc.
93
94 @page
95 @vskip 0pt plus 1filll
96
97 @insertcopying
98
99 @end titlepage
100
101 @ifnottex
102 @node Top, About This Guide, (dir), (dir)
103 @top GNAT User's Guide
104
105
106
107 GNAT User's Guide for Unix Platforms
108
109
110 GNAT, The GNU Ada 95 Compiler
111
112 GNAT Version for GCC @value{version-GCC}
113
114 Ada Core Technologies, Inc.
115
116 @insertcopying
117
118 @menu
119 * About This Guide::
120 * Getting Started with GNAT::
121 * The GNAT Compilation Model::
122 * Compiling Using gcc::
123 * Binding Using gnatbind::
124 * Linking Using gnatlink::
125 * The GNAT Make Program gnatmake::
126 * Renaming Files Using gnatchop::
127 * Configuration Pragmas::
128 * Handling Arbitrary File Naming Conventions Using gnatname::
129 * GNAT Project Manager::
130 * Elaboration Order Handling in GNAT::
131 * The Cross-Referencing Tools gnatxref and gnatfind::
132 * File Name Krunching Using gnatkr::
133 * Preprocessing Using gnatprep::
134 * The GNAT Library Browser gnatls::
135 * GNAT and Libraries::
136 * Using the GNU make Utility::
137 * Finding Memory Problems with gnatmem::
138 * Finding Memory Problems with GNAT Debug Pool::
139 * Creating Sample Bodies Using gnatstub::
140 * Reducing the Size of Ada Executables with gnatelim::
141 * Other Utility Programs::
142 * Running and Debugging Ada Programs::
143 * Inline Assembler::
144 * Performance Considerations::
145 * GNU Free Documentation License::
146 * Index::
147
148  --- The Detailed Node Listing ---
149
150 About This Guide
151
152 * What This Guide Contains::
153 * What You Should Know before Reading This Guide::
154 * Related Information::
155 * Conventions::
156
157
158 Getting Started with GNAT
159
160 * Running GNAT::
161 * Running a Simple Ada Program::
162 * Running a Program with Multiple Units::
163 * Using the gnatmake Utility::
164
165 The GNAT Compilation Model
166
167 * Source Representation::
168 * Foreign Language Representation::
169 * File Naming Rules::
170 * Using Other File Names::
171 * Alternative File Naming Schemes::
172 * Generating Object Files::
173 * Source Dependencies::
174 * The Ada Library Information Files::
175 * Binding an Ada Program::
176 * Mixed Language Programming::
177 * Building Mixed Ada & C++ Programs::
178 * Comparison between GNAT and C/C++ Compilation Models::
179 * Comparison between GNAT and Conventional Ada Library Models::
180
181 Foreign Language Representation
182
183 * Latin-1::
184 * Other 8-Bit Codes::
185 * Wide Character Encodings::
186
187 Compiling Ada Programs With gcc
188
189 * Compiling Programs::
190 * Switches for gcc::
191 * Search Paths and the Run-Time Library (RTL)::
192 * Order of Compilation Issues::
193 * Examples::
194
195 Switches for gcc
196
197 * Output and Error Message Control::
198 * Debugging and Assertion Control::
199 * Run-Time Checks::
200 * Stack Overflow Checking::
201 * Run-Time Control::
202 * Validity Checking::
203 * Style Checking::
204 * Using gcc for Syntax Checking::
205 * Using gcc for Semantic Checking::
206 * Compiling Ada 83 Programs::
207 * Character Set Control::
208 * File Naming Control::
209 * Subprogram Inlining Control::
210 * Auxiliary Output Control::
211 * Debugging Control::
212 * Units to Sources Mapping Files::
213
214 Binding Ada Programs With gnatbind
215
216 * Running gnatbind::
217 * Generating the Binder Program in C::
218 * Consistency-Checking Modes::
219 * Binder Error Message Control::
220 * Elaboration Control::
221 * Output Control::
222 * Binding with Non-Ada Main Programs::
223 * Binding Programs with No Main Subprogram::
224 * Summary of Binder Switches::
225 * Command-Line Access::
226 * Search Paths for gnatbind::
227 * Examples of gnatbind Usage::
228
229 Linking Using gnatlink
230
231 * Running gnatlink::
232 * Switches for gnatlink::
233 * Setting Stack Size from gnatlink::
234 * Setting Heap Size from gnatlink::
235
236 The GNAT Make Program gnatmake
237
238 * Running gnatmake::
239 * Switches for gnatmake::
240 * Mode Switches for gnatmake::
241 * Notes on the Command Line::
242 * How gnatmake Works::
243 * Examples of gnatmake Usage::
244
245 Renaming Files Using gnatchop
246
247 * Handling Files with Multiple Units::
248 * Operating gnatchop in Compilation Mode::
249 * Command Line for gnatchop::
250 * Switches for gnatchop::
251 * Examples of gnatchop Usage::
252
253 Configuration Pragmas
254
255 * Handling of Configuration Pragmas::
256 * The Configuration Pragmas Files::
257
258 Handling Arbitrary File Naming Conventions Using gnatname
259
260 * Arbitrary File Naming Conventions::
261 * Running gnatname::
262 * Switches for gnatname::
263 * Examples of gnatname Usage::
264
265 GNAT Project Manager
266
267 * Introduction::
268 * Examples of Project Files::
269 * Project File Syntax::
270 * Objects and Sources in Project Files::
271 * Importing Projects::
272 * Project Extension::
273 * External References in Project Files::
274 * Packages in Project Files::
275 * Variables from Imported Projects::
276 * Naming Schemes::
277 * Library Projects::
278 * Switches Related to Project Files::
279 * Tools Supporting Project Files::
280 * An Extended Example::
281 * Project File Complete Syntax::
282
283 Elaboration Order Handling in GNAT
284
285 * Elaboration Code in Ada 95::
286 * Checking the Elaboration Order in Ada 95::
287 * Controlling the Elaboration Order in Ada 95::
288 * Controlling Elaboration in GNAT - Internal Calls::
289 * Controlling Elaboration in GNAT - External Calls::
290 * Default Behavior in GNAT - Ensuring Safety::
291 * Elaboration Issues for Library Tasks::
292 * Mixing Elaboration Models::
293 * What to Do If the Default Elaboration Behavior Fails::
294 * Elaboration for Access-to-Subprogram Values::
295 * Summary of Procedures for Elaboration Control::
296 * Other Elaboration Order Considerations::
297
298 The Cross-Referencing Tools gnatxref and gnatfind
299
300 * gnatxref Switches::
301 * gnatfind Switches::
302 * Project Files for gnatxref and gnatfind::
303 * Regular Expressions in gnatfind and gnatxref::
304 * Examples of gnatxref Usage::
305 * Examples of gnatfind Usage::
306
307 File Name Krunching Using gnatkr
308
309 * About gnatkr::
310 * Using gnatkr::
311 * Krunching Method::
312 * Examples of gnatkr Usage::
313
314 Preprocessing Using gnatprep
315
316 * Using gnatprep::
317 * Switches for gnatprep::
318 * Form of Definitions File::
319 * Form of Input Text for gnatprep::
320
321
322 The GNAT Library Browser gnatls
323
324 * Running gnatls::
325 * Switches for gnatls::
326 * Examples of gnatls Usage::
327
328
329 GNAT and Libraries
330
331 * Creating an Ada Library::
332 * Installing an Ada Library::
333 * Using an Ada Library::
334 * Creating an Ada Library to be Used in a Non-Ada Context::
335 * Rebuilding the GNAT Run-Time Library::
336
337 Using the GNU make Utility
338
339 * Using gnatmake in a Makefile::
340 * Automatically Creating a List of Directories::
341 * Generating the Command Line Switches::
342 * Overcoming Command Line Length Limits::
343
344 Finding Memory Problems with gnatmem
345
346 * Running gnatmem (GDB Mode)::
347 * Running gnatmem (GMEM Mode)::
348 * Switches for gnatmem::
349 * Examples of gnatmem Usage::
350 * GDB and GMEM Modes::
351 * Implementation Note::
352
353
354 Finding Memory Problems with GNAT Debug Pool
355
356 Creating Sample Bodies Using gnatstub
357
358 * Running gnatstub::
359 * Switches for gnatstub::
360
361 Reducing the Size of Ada Executables with gnatelim
362
363 * About gnatelim::
364 * Eliminate Pragma::
365 * Tree Files::
366 * Preparing Tree and Bind Files for gnatelim::
367 * Running gnatelim::
368 * Correcting the List of Eliminate Pragmas::
369 * Making Your Executables Smaller::
370 * Summary of the gnatelim Usage Cycle::
371
372 Other Utility Programs
373
374 * Using Other Utility Programs with GNAT::
375 * The gnatpsta Utility Program::
376 * The External Symbol Naming Scheme of GNAT::
377 * Ada Mode for Glide::
378 * Converting Ada Files to html with gnathtml::
379
380
381 Running and Debugging Ada Programs
382
383 * The GNAT Debugger GDB::
384 * Running GDB::
385 * Introduction to GDB Commands::
386 * Using Ada Expressions::
387 * Calling User-Defined Subprograms::
388 * Using the Next Command in a Function::
389 * Ada Exceptions::
390 * Ada Tasks::
391 * Debugging Generic Units::
392 * GNAT Abnormal Termination or Failure to Terminate::
393 * Naming Conventions for GNAT Source Files::
394 * Getting Internal Debugging Information::
395 * Stack Traceback::
396
397 Inline Assembler
398
399 * Basic Assembler Syntax::
400 * A Simple Example of Inline Assembler::
401 * Output Variables in Inline Assembler::
402 * Input Variables in Inline Assembler::
403 * Inlining Inline Assembler Code::
404 * Other Asm Functionality::
405 * A Complete Example::
406
407
408
409 Performance Considerations
410
411 * Controlling Run-Time Checks::
412 * Optimization Levels::
413 * Debugging Optimized Code::
414 * Inlining of Subprograms::
415
416 * Index::
417 @end menu
418 @end ifnottex
419
420 @node About This Guide
421 @unnumbered About This Guide
422
423 @noindent
424 This guide describes the use of GNAT, a compiler and software development
425 toolset for the full Ada 95 programming language.
426 It describes the features of the compiler and tools, and details
427 how to use them to build Ada 95 applications.
428
429 @menu
430 * What This Guide Contains::
431 * What You Should Know before Reading This Guide::
432 * Related Information::
433 * Conventions::
434 @end menu
435
436 @node What This Guide Contains
437 @unnumberedsec What This Guide Contains
438
439 @noindent
440 This guide contains the following chapters:
441 @itemize @bullet
442 @item
443 @ref{Getting Started with GNAT}, describes how to get started compiling
444 and running Ada programs with the GNAT Ada programming environment.
445 @item
446 @ref{The GNAT Compilation Model}, describes the compilation model used
447 by GNAT.
448 @item
449 @ref{Compiling Using gcc}, describes how to compile
450 Ada programs with @code{gcc}, the Ada compiler.
451 @item
452 @ref{Binding Using gnatbind}, describes how to
453 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
454 utility.
455 @item
456 @ref{Linking Using gnatlink},
457 describes @code{gnatlink}, a
458 program that provides for linking using the GNAT run-time library to
459 construct a program. @code{gnatlink} can also incorporate foreign language
460 object units into the executable.
461 @item
462 @ref{The GNAT Make Program gnatmake}, describes @code{gnatmake}, a
463 utility that automatically determines the set of sources
464 needed by an Ada compilation unit, and executes the necessary compilations
465 binding and link.
466 @item
467 @ref{Renaming Files Using gnatchop}, describes
468 @code{gnatchop}, a utility that allows you to preprocess a file that
469 contains Ada source code, and split it into one or more new files, one
470 for each compilation unit.
471 @item
472 @ref{Configuration Pragmas}, describes the configuration pragmas handled by GNAT.
473 @item
474 @ref{Handling Arbitrary File Naming Conventions Using gnatname}, shows how to override
475 the default GNAT file naming conventions, either for an individual unit or globally.
476 @item
477 @ref{GNAT Project Manager}, describes how to use project files to organize large projects.
478 @item
479 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps you deal with
480 elaboration order issues.
481 @item
482 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
483 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
484 way to navigate through sources.
485 @item
486 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
487 file name krunching utility, used to handle shortened
488 file names on operating systems with a limit on the length of names.
489 @item
490 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
491 preprocessor utility that allows a single source file to be used to
492 generate multiple or parameterized source files, by means of macro
493 substitution.
494 @item
495 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
496 utility that displays information about compiled units, including dependences
497 on the corresponding sources files, and consistency of compilations.
498 @item
499 @ref{GNAT and Libraries}, describes the process of creating and using
500 Libraries with GNAT. It also describes how to recompile the GNAT run-time
501 library.
502
503 @item
504 @ref{Using the GNU make Utility}, describes some techniques for using
505 the GNAT toolset in Makefiles.
506
507 @item
508 @ref{Finding Memory Problems with gnatmem}, describes @code{gnatmem}, a
509 utility that monitors dynamic allocation and deallocation activity in a
510 program, and displays information about incorrect deallocations and sources
511 of possible memory leaks.
512 @item
513 @ref{Finding Memory Problems with GNAT Debug Pool}, describes how to
514 use the GNAT-specific Debug Pool in order to detect as early as possible
515 the use of incorrect memory references.
516
517 @item
518 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
519 a utility that generates empty but compilable bodies for library units.
520
521 @item
522 @ref{Reducing the Size of Ada Executables with gnatelim}, describes
523 @code{gnatelim}, a tool which detects unused subprograms and helps
524 the compiler to create a smaller executable for the program.
525
526 @item
527 @ref{Other Utility Programs}, discusses several other GNAT utilities,
528 including @code{gnatpsta}.
529
530 @item
531 @ref{Running and Debugging Ada Programs}, describes how to run and debug
532 Ada programs.
533
534 @item
535 @ref{Inline Assembler}, shows how to use the inline assembly facility in an Ada program.
536
537
538 @item
539 @ref{Performance Considerations}, reviews the trade offs between using
540 defaults or options in program development.
541 @end itemize
542
543 @node What You Should Know before Reading This Guide
544 @unnumberedsec What You Should Know before Reading This Guide
545
546 @cindex Ada 95 Language Reference Manual
547 @noindent
548 This user's guide assumes that you are familiar with Ada 95 language, as
549 described in the International Standard ANSI/ISO/IEC-8652:1995, Jan
550 1995.
551
552 @node Related Information
553 @unnumberedsec Related Information
554
555 @noindent
556 For further information about related tools, refer to the following
557 documents:
558
559 @itemize @bullet
560 @item
561 @cite{GNAT Reference Manual}, which contains all reference
562 material for the GNAT implementation of Ada 95.
563
564 @item
565 @cite{Ada 95 Language Reference Manual}, which contains all reference
566 material for the Ada 95 programming language.
567
568 @item
569 @cite{Debugging with GDB}
570 contains all details on the use of the GNU source-level debugger.
571
572 @item
573 @cite{GNU Emacs Manual}
574 contains full information on the extensible editor and programming
575 environment Emacs.
576
577 @end itemize
578
579 @node Conventions
580 @unnumberedsec Conventions
581 @cindex Conventions
582 @cindex Typographical conventions
583
584 @noindent
585 Following are examples of the typographical and graphic conventions used
586 in this guide:
587
588 @itemize @bullet
589 @item
590 @code{Functions}, @code{utility program names}, @code{standard names},
591 and @code{classes}.
592
593 @item
594 @samp{Option flags}
595
596 @item
597 @file{File Names}, @file{button names}, and @file{field names}.
598
599 @item
600 @var{Variables}.
601
602 @item
603 @emph{Emphasis}.
604
605 @item
606 [optional information or parameters]
607
608 @item
609 Examples are described by text
610 @smallexample
611 and then shown this way.
612 @end smallexample
613 @end itemize
614
615 @noindent
616 Commands that are entered by the user are preceded in this manual by the
617 characters @w{"@code{$ }"} (dollar sign followed by space). If your system
618 uses this sequence as a prompt, then the commands will appear exactly as
619 you see them in the manual. If your system uses some other prompt, then
620 the command will appear with the @code{$} replaced by whatever prompt
621 character you are using.
622
623
624 @node Getting Started with GNAT
625 @chapter Getting Started with GNAT
626
627 @noindent
628 This chapter describes some simple ways of using GNAT to build
629 executable Ada programs.
630
631 @menu
632 * Running GNAT::
633 * Running a Simple Ada Program::
634
635 * Running a Program with Multiple Units::
636
637 * Using the gnatmake Utility::
638 * Introduction to Glide and GVD::
639 @end menu
640
641 @node Running GNAT
642 @section Running GNAT
643
644 @noindent
645 Three steps are needed to create an executable file from an Ada source
646 file:
647
648 @enumerate
649 @item
650 The source file(s) must be compiled.
651 @item
652 The file(s) must be bound using the GNAT binder.
653 @item
654 All appropriate object files must be linked to produce an executable.
655 @end enumerate
656
657 @noindent
658 All three steps are most commonly handled by using the @code{gnatmake}
659 utility program that, given the name of the main program, automatically
660 performs the necessary compilation, binding and linking steps.
661
662 @node Running a Simple Ada Program
663 @section Running a Simple Ada Program
664
665 @noindent
666 Any text editor may be used to prepare an Ada program. If @code{Glide} is
667 used, the optional Ada mode may be helpful in laying out the program. The
668 program text is a normal text file. We will suppose in our initial
669 example that you have used your editor to prepare the following
670 standard format text file:
671
672 @smallexample
673 @group
674 @cartouche
675 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
676 @b{procedure} Hello @b{is}
677 @b{begin}
678    Put_Line ("Hello WORLD!");
679 @b{end} Hello;
680 @end cartouche
681 @end group
682 @end smallexample
683
684 @noindent
685 This file should be named @file{hello.adb}.
686 With the normal default file naming conventions, GNAT requires
687 that each file
688 contain a single compilation unit whose file name is the
689 unit name,
690 with periods replaced by hyphens; the
691 extension is @file{ads} for a
692 spec and @file{adb} for a body.
693 You can override this default file naming convention by use of the
694 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
695 Alternatively, if you want to rename your files according to this default
696 convention, which is probably more convenient if you will be using GNAT
697 for all your compilations, then the @code{gnatchop} utility
698 can be used to generate correctly-named source files
699 (@pxref{Renaming Files Using gnatchop}).
700
701 You can compile the program using the following command (@code{$} is used
702 as the command prompt in the examples in this document):
703
704 @smallexample
705 $ gcc -c hello.adb
706 @end smallexample
707
708
709 @noindent
710 @code{gcc} is the command used to run the compiler. This compiler is
711 capable of compiling programs in several languages, including Ada 95 and
712 C. It assumes that you have given it an Ada program if the file extension is
713 either @file{.ads} or @file{.adb}, and it will then call the GNAT compiler to compile
714 the specified file.
715
716 The @option{-c} switch is required. It tells @command{gcc} to only do a
717 compilation. (For C programs, @command{gcc} can also do linking, but this
718 capability is not used directly for Ada programs, so the @option{-c}
719 switch must always be present.)
720
721 This compile command generates a file
722 @file{hello.o}, which is the object
723 file corresponding to your Ada program. It also generates an "Ada Library Information" file
724 @file{hello.ali},
725 which contains additional information used to check
726 that an Ada program is consistent.
727 To build an executable file,
728 use @code{gnatbind} to bind the program
729 and @code{gnatlink} to link it. The
730 argument to both @code{gnatbind} and @code{gnatlink} is the name of the
731 @file{ali} file, but the default extension of @file{.ali} can
732 be omitted. This means that in the most common case, the argument
733 is simply the name of the main program:
734
735 @smallexample
736 $ gnatbind hello
737 $ gnatlink hello
738 @end smallexample
739
740
741 @noindent
742 A simpler method of carrying out these steps is to use
743 @command{gnatmake},
744 a master program that invokes all the required
745 compilation, binding and linking tools in the correct order. In particular,
746 @command{gnatmake} automatically recompiles any sources that have been modified
747 since they were last compiled, or sources that depend
748 on such modified sources, so that "version skew" is avoided.
749 @cindex Version skew (avoided by @command{gnatmake})
750
751 @smallexample
752 $ gnatmake hello.adb
753 @end smallexample
754
755
756 @noindent
757 The result is an executable program called @file{hello}, which can be
758 run by entering:
759
760 @c The following should be removed (BMB 2001-01-23)
761 @c @smallexample
762 @c $ ./hello
763 @c @end smallexample
764
765 @smallexample
766 $ hello
767 @end smallexample
768
769 @noindent
770 assuming that the current directory is on the search path for executable programs.
771
772 @noindent
773 and, if all has gone well, you will see
774
775 @smallexample
776 Hello WORLD!
777 @end smallexample
778
779 @noindent
780 appear in response to this command.
781
782
783
784
785 @node Running a Program with Multiple Units
786 @section Running a Program with Multiple Units
787
788 @noindent
789 Consider a slightly more complicated example that has three files: a
790 main program, and the spec and body of a package:
791
792 @smallexample
793 @cartouche
794 @group
795 @b{package} Greetings @b{is}
796    @b{procedure} Hello;
797    @b{procedure} Goodbye;
798 @b{end} Greetings;
799
800 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
801 @b{package} @b{body} Greetings @b{is}
802    @b{procedure} Hello @b{is}
803    @b{begin}
804       Put_Line ("Hello WORLD!");
805    @b{end} Hello;
806
807    @b{procedure} Goodbye @b{is}
808    @b{begin}
809       Put_Line ("Goodbye WORLD!");
810    @b{end} Goodbye;
811 @b{end} Greetings;
812 @end group
813
814 @group
815 @b{with} Greetings;
816 @b{procedure} Gmain @b{is}
817 @b{begin}
818    Greetings.Hello;
819    Greetings.Goodbye;
820 @b{end} Gmain;
821 @end group
822 @end cartouche
823 @end smallexample
824
825 @noindent
826 Following the one-unit-per-file rule, place this program in the
827 following three separate files:
828
829 @table @file
830 @item greetings.ads
831 spec of package @code{Greetings}
832
833 @item greetings.adb
834 body of package @code{Greetings}
835
836 @item gmain.adb
837 body of main program
838 @end table
839
840 @noindent
841 To build an executable version of
842 this program, we could use four separate steps to compile, bind, and link
843 the program, as follows:
844
845 @smallexample
846 $ gcc -c gmain.adb
847 $ gcc -c greetings.adb
848 $ gnatbind gmain
849 $ gnatlink gmain
850 @end smallexample
851
852
853 @noindent
854 Note that there is no required order of compilation when using GNAT.
855 In particular it is perfectly fine to compile the main program first.
856 Also, it is not necessary to compile package specs in the case where
857 there is an accompanying body; you only need to compile the body. If you want
858 to submit these files to the compiler for semantic checking and not code generation,
859 then use the
860 @option{-gnatc} switch:
861
862 @smallexample
863    $ gcc -c greetings.ads -gnatc
864 @end smallexample
865
866
867 @noindent
868 Although the compilation can be done in separate steps as in the
869 above example, in practice it is almost always more convenient
870 to use the @code{gnatmake} tool. All you need to know in this case
871 is the name of the main program's source file. The effect of the above four
872 commands can be achieved with a single one:
873
874 @smallexample
875 $ gnatmake gmain.adb
876 @end smallexample
877
878
879 @noindent
880 In the next section we discuss the advantages of using @code{gnatmake} in
881 more detail.
882
883 @node Using the gnatmake Utility
884 @section Using the @command{gnatmake} Utility
885
886 @noindent
887 If you work on a program by compiling single components at a time using
888 @code{gcc}, you typically keep track of the units you modify. In order to
889 build a consistent system, you compile not only these units, but also any
890 units that depend on the units you have modified.
891 For example, in the preceding case,
892 if you edit @file{gmain.adb}, you only need to recompile that file. But if
893 you edit @file{greetings.ads}, you must recompile both
894 @file{greetings.adb} and @file{gmain.adb}, because both files contain
895 units that depend on @file{greetings.ads}.
896
897 @code{gnatbind} will warn you if you forget one of these compilation
898 steps, so that it is impossible to generate an inconsistent program as a
899 result of forgetting to do a compilation. Nevertheless it is tedious and
900 error-prone to keep track of dependencies among units.
901 One approach to handle the dependency-bookkeeping is to use a
902 makefile. However, makefiles present maintenance problems of their own:
903 if the dependencies change as you change the program, you must make
904 sure that the makefile is kept up-to-date manually, which is also an
905 error-prone process.
906
907 The @code{gnatmake} utility takes care of these details automatically.
908 Invoke it using either one of the following forms:
909
910 @smallexample
911 $ gnatmake gmain.adb
912 $ gnatmake gmain
913 @end smallexample
914
915
916 @noindent
917 The argument is the name of the file containing the main program;
918 you may omit the extension. @code{gnatmake}
919 examines the environment, automatically recompiles any files that need
920 recompiling, and binds and links the resulting set of object files,
921 generating the executable file, @file{gmain}.
922 In a large program, it
923 can be extremely helpful to use @code{gnatmake}, because working out by hand
924 what needs to be recompiled can be difficult.
925
926 Note that @code{gnatmake}
927 takes into account all the Ada 95 rules that
928 establish dependencies among units. These include dependencies that result
929 from inlining subprogram bodies, and from
930 generic instantiation. Unlike some other
931 Ada make tools, @code{gnatmake} does not rely on the dependencies that were
932 found by the compiler on a previous compilation, which may possibly
933 be wrong when sources change. @code{gnatmake} determines the exact set of
934 dependencies from scratch each time it is run.
935
936
937 @node Introduction to Glide and GVD
938 @section Introduction to Glide and GVD
939 @cindex Glide
940 @cindex GVD
941 @noindent
942 Although it is possible to develop programs using only the command line interface (@command{gnatmake}, etc.) a graphical Interactive Development Environment can make it easier for you to compose, navigate, and debug programs.  This section describes the main features of Glide, the GNAT graphical IDE, and also shows how to use the basic commands in GVD, the GNU Visual Debugger.  Additional information may be found in the on-line help for these tools.
943
944 @menu
945 * Building a New Program with Glide::
946 * Simple Debugging with GVD::
947 * Other Glide Features::
948 @end menu
949
950 @node Building a New Program with Glide
951 @subsection Building a New Program with Glide
952 @noindent
953 The simplest way to invoke Glide is to enter @command{glide} at the command prompt.  It will generally be useful to issue this as a background command, thus allowing you to continue using your command window for other purposes while Glide is running:
954
955 @smallexample
956 $ glide&
957 @end smallexample
958
959 @noindent
960 Glide will start up with an initial screen displaying the top-level menu items as well as some other information.  The menu selections are as follows
961 @itemize @bullet
962 @item @code{Buffers}
963 @item @code{Files}
964 @item @code{Tools}
965 @item @code{Edit}
966 @item @code{Search}
967 @item @code{Mule}
968 @item @code{Glide}
969 @item @code{Help}
970 @end itemize
971
972 @noindent
973 For this introductory example, you will need to create a new Ada source file.  First, select the @code{Files} menu.  This will pop open a menu with around a dozen or so items.  To create a file, select the @code{Open file...} choice.  Depending on the platform, you may see a pop-up window where you can browse to an appropriate directory and then enter the file name, or else simply see a line at the bottom of the Glide window where you can likewise enter the file name.  Note that in Glide, when you attempt to open a non-existent file, the effect is to create a file with that name.  For this example enter @file{hello.adb} as the name of the file.
974
975 A new buffer will now appear, occupying the entire Glide window, with the file name at the top.  The menu selections are slightly different from the ones you saw on the opening screen; there is an @code{Entities} item, and in place of @code{Glide} there is now an @code{Ada} item.  Glide uses the file extension to identify the source language, so @file{adb} indicates an Ada source file.
976
977 You will enter some of the source program lines explicitly, and use the syntax-oriented template mechanism to enter other lines.  First, type the following text:
978 @smallexample
979 with Ada.Text_IO; use Ada.Text_IO;
980 procedure Hello is
981 begin
982 @end smallexample
983
984 @noindent
985 Observe that Glide uses different colors to distinguish reserved words from identifiers.  Also, after the @code{procedure Hello is} line, the cursor is automatically indented in anticipation of declarations.  When you enter @code{begin}, Glide recognizes that there are no declarations and thus places @code{begin} flush left.  But after the @code{begin} line the cursor is again indented, where the statement(s) will be placed.
986
987 The main part of the program will be a @code{for} loop.  Instead of entering the text explicitly, however, use a statement template.  Select the @code{Ada} item on the top menu bar, move the mouse to the @code{Statements} item, and you will see a large selection of alternatives.  Choose @code{for loop}.  You will be prompted (at the bottom of the buffer) for a loop name; simply press the @key{Enter} key since a loop name is not needed.  You should see the beginning of a @code{for} loop appear in the source program window.  You will now be prompted for the name of the loop variable; enter a line with the identifier @code{ind} (lower case).  Note that, by default, Glide capitalizes the name (you can override such behavior if you wish, although this is outside the scope of this introduction).  Next, Glide prompts you for the loop range; enter a line containing @code{1..5} and you will see this also appear in the source program, together with the remaining elements of the @code{for} loop syntax.
988
989 Next enter the statement (with an intentional error, a missing semicolon) that will form the body of the loop:
990 @smallexample
991 Put_Line("Hello, World" & Integer'Image(I))
992 @end smallexample
993
994 @noindent
995 Finally, type @code{end Hello;} as the last line in the program.  Now save the file: choose the @code{File} menu item, and then the @code{Save buffer} selection.  You will see a message at the bottom of the buffer confirming that the file has been saved.
996
997 You are now ready to attempt to build the program.  Select the @code{Ada} item from the top menu bar.  Although we could choose simply to compile the file, we will instead attempt to do a build (which invokes @command{gnatmake}) since, if the compile is successful, we want to build an executable.  Thus select @code{Ada build}.  This will fail because of the compilation error, and you will notice that the Glide window has been split: the top window contains the source file, and the bottom window contains the output from the GNAT tools.  Glide allows you to navigate from a compilation error to the source file position corresponding to the error: click the middle mouse button (or simultaneously press the left and right buttons, on a two-button mouse) on the diagnostic line in the tool window.  The focus will shift to the source window, and the cursor will be positioned on the character at which the error was detected.
998
999 Correct the error: type in a semicolon to terminate the statement.  Although you can again save the file explicitly, you can also simply invoke @code{Ada} @result{} @code{Build} and you will be prompted to save the file.  This time the build will succeed; the tool output window shows you the options that are supplied by default.  The GNAT tools' output (e.g., object and ALI files, executable) will go in the directory from which Glide was launched.
1000
1001 To execute the program, choose @code{Ada} and then @code{Run}.  You should see the program's output displayed in the bottom window:
1002
1003 @smallexample
1004 Hello, world 1
1005 Hello, world 2
1006 Hello, world 3
1007 Hello, world 4
1008 Hello, world 5
1009 @end smallexample
1010
1011 @node Simple Debugging with GVD
1012 @subsection Simple Debugging with GVD
1013
1014 @noindent
1015 This section describes how to set breakpoints, examine/modify variables, and step through execution.
1016
1017 In order to enable debugging, you need to pass the @option{-g} switch to both the compiler and to @command{gnatlink}.  If you are using the command line, passing @option{-g} to @command{gnatmake} will have this effect.  You can then launch GVD, e.g. on the @code{hello} program, by issuing the command:
1018
1019 @smallexample
1020 $ gvd hello
1021 @end smallexample
1022
1023 @noindent
1024 If you are using Glide, then @option{-g} is passed to the relevant tools by default when you do a build.  Start the debugger by selecting the @code{Ada} menu item, and then @code{Debug}.
1025
1026 GVD comes up in a multi-part window.  One pane shows the names of files comprising your executable; another pane shows the source code of the current unit (initially your main subprogram), another pane shows the debugger output and user interactions, and the fourth pane (the data canvas at the top of the window) displays data objects that you have selected.
1027
1028 To the left of the source file pane, you will notice green dots adjacent to some lines.  These are lines for which object code exists and where breakpoints can thus be set.  You set/reset a breakpoint by clicking the green dot.  When a breakpoint is set, the dot is replaced by an @code{X} in a red circle.  Clicking the circle toggles the breakpoint off, and the red circle is replaced by the green dot.
1029
1030 For this example, set a breakpoint at the statement where @code{Put_Line} is invoked.
1031
1032 Start program execution by selecting the @code{Run} button on the top menu bar.  (The @code{Start} button will also start your program, but it will cause program execution to break at the entry to your main subprogram.)  Evidence of reaching the breakpoint will appear: the source file line will be highlighted, and the debugger interactions pane will display a relevant message.
1033
1034 You can examine the values of variables in several ways.  Move the mouse over an occurrence of @code{Ind} in the @code{for} loop, and you will see the value (now @code{1}) displayed.  Alternatively, right-click on @code{Ind} and select @code{Display Ind}; a box showing the variable's name and value will appear in the data canvas.
1035
1036 Although a loop index is a constant with respect to Ada semantics, you can change its value in the debugger.  Right-click in the box for @code{Ind}, and select the @code{Set Value of Ind} item.  Enter @code{2} as the new value, and press @command{OK}.  The box for @code{Ind} shows the update.
1037
1038 Press the @code{Step} button on the top menu bar; this will step through one line of program text (the invocation of @code{Put_Line}), and you can observe the effect of having modified @code{Ind} since the value displayed is @code{2}.
1039
1040 Remove the breakpoint, and resume execution by selecting the @code{Cont} button.  You will see the remaining output lines displayed in the debugger interaction window, along with a message confirming normal program termination.
1041
1042
1043 @node Other Glide Features
1044 @subsection Other Glide Features
1045
1046 @noindent
1047 You may have observed that some of the menu selections contain abbreviations; e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu.  These are @emph{shortcut keys} that you can use instead of selecting menu items.  The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead of selecting @code{Files} and then @code{Open file...}.
1048
1049 To abort a Glide command, type @key{Ctrl-g}.
1050
1051 If you want Glide to start with an existing source file, you can either launch Glide as above and then open the file via @code{Files} @result{} @code{Open file...}, or else simply pass the name of the source file on the command line:
1052
1053 @smallexample
1054 $ glide hello.adb&
1055 @end smallexample
1056
1057 @noindent
1058 While you are using Glide, a number of @emph{buffers} exist.  You create some explicitly; e.g., when you open/create a file.  Others arise as an effect of the commands that you issue; e.g., the buffer containing the output of the tools invoked during a build.  If a buffer is hidden, you can bring it into a visible window by first opening the @code{Buffers} menu and then selecting the desired entry.
1059
1060 If a buffer occupies only part of the Glide screen and you want to expand it to fill the entire screen, then click in the buffer and then select @code{Files} @result{} @code{One Window}.
1061
1062 If a window is occupied by one buffer and you want to split the window to bring up a second buffer, perform the following steps:
1063 @itemize @bullet
1064 @item Select @code{Files} @result{} @code{Split Window}; this will produce two windows each of which holds the original buffer (these are not copies, but rather different views of the same buffer contents)
1065 @item With the focus in one of the windows, select the desired buffer from the @code{Buffers} menu
1066 @end itemize
1067
1068 @noindent
1069 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1070
1071 @node The GNAT Compilation Model
1072 @chapter The GNAT Compilation Model
1073 @cindex GNAT compilation model
1074 @cindex Compilation model
1075
1076 @menu
1077 * Source Representation::
1078 * Foreign Language Representation::
1079 * File Naming Rules::
1080 * Using Other File Names::
1081 * Alternative File Naming Schemes::
1082 * Generating Object Files::
1083 * Source Dependencies::
1084 * The Ada Library Information Files::
1085 * Binding an Ada Program::
1086 * Mixed Language Programming::
1087 * Building Mixed Ada & C++ Programs::
1088 * Comparison between GNAT and C/C++ Compilation Models::
1089 * Comparison between GNAT and Conventional Ada Library Models::
1090 @end menu
1091
1092 @noindent
1093 This chapter describes the compilation model used by GNAT. Although
1094 similar to that used by other languages, such as C and C++, this model
1095 is substantially different from the traditional Ada compilation models,
1096 which are based on a library. The model is initially described without
1097 reference to the library-based model. If you have not previously used an
1098 Ada compiler, you need only read the first part of this chapter. The
1099 last section describes and discusses the differences between the GNAT
1100 model and the traditional Ada compiler models. If you have used other
1101 Ada compilers, this section will help you to understand those
1102 differences, and the advantages of the GNAT model.
1103
1104 @node Source Representation
1105 @section Source Representation
1106 @cindex Latin-1
1107
1108 @noindent
1109 Ada source programs are represented in standard text files, using
1110 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1111 7-bit ASCII set, plus additional characters used for
1112 representing foreign languages (@pxref{Foreign Language Representation}
1113 for support of non-USA character sets). The format effector characters
1114 are represented using their standard ASCII encodings, as follows:
1115
1116 @table @code
1117 @item VT
1118 @findex VT
1119 Vertical tab, @code{16#0B#}
1120
1121 @item HT
1122 @findex HT
1123 Horizontal tab, @code{16#09#}
1124
1125 @item CR
1126 @findex CR
1127 Carriage return, @code{16#0D#}
1128
1129 @item LF
1130 @findex LF
1131 Line feed, @code{16#0A#}
1132
1133 @item FF
1134 @findex FF
1135 Form feed, @code{16#0C#}
1136 @end table
1137
1138 @noindent
1139 Source files are in standard text file format. In addition, GNAT will
1140 recognize a wide variety of stream formats, in which the end of physical
1141 physical lines is marked by any of the following sequences:
1142 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1143 in accommodating files that are imported from other operating systems.
1144
1145 @cindex End of source file
1146 @cindex Source file, end
1147 @findex SUB
1148 The end of a source file is normally represented by the physical end of
1149 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1150 recognized as signalling the end of the source file. Again, this is
1151 provided for compatibility with other operating systems where this
1152 code is used to represent the end of file.
1153
1154 Each file contains a single Ada compilation unit, including any pragmas
1155 associated with the unit. For example, this means you must place a
1156 package declaration (a package @dfn{spec}) and the corresponding body in
1157 separate files. An Ada @dfn{compilation} (which is a sequence of
1158 compilation units) is represented using a sequence of files. Similarly,
1159 you will place each subunit or child unit in a separate file.
1160
1161 @node Foreign Language Representation
1162 @section Foreign Language Representation
1163
1164 @noindent
1165 GNAT supports the standard character sets defined in Ada 95 as well as
1166 several other non-standard character sets for use in localized versions
1167 of the compiler (@pxref{Character Set Control}).
1168 @menu
1169 * Latin-1::
1170 * Other 8-Bit Codes::
1171 * Wide Character Encodings::
1172 @end menu
1173
1174 @node Latin-1
1175 @subsection Latin-1
1176 @cindex Latin-1
1177
1178 @noindent
1179 The basic character set is Latin-1. This character set is defined by ISO
1180 standard 8859, part 1. The lower half (character codes @code{16#00#}
1181 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half is
1182 used to represent additional characters. These include extended letters
1183 used by European languages, such as French accents, the vowels with umlauts
1184 used in German, and the extra letter A-ring used in Swedish.
1185
1186 @findex Ada.Characters.Latin_1
1187 For a complete list of Latin-1 codes and their encodings, see the source
1188 file of library unit @code{Ada.Characters.Latin_1} in file
1189 @file{a-chlat1.ads}.
1190 You may use any of these extended characters freely in character or
1191 string literals. In addition, the extended characters that represent
1192 letters can be used in identifiers.
1193
1194 @node Other 8-Bit Codes
1195 @subsection Other 8-Bit Codes
1196
1197 @noindent
1198 GNAT also supports several other 8-bit coding schemes:
1199
1200 @table @asis
1201 @cindex Latin-2
1202 @item Latin-2
1203 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1204 equivalence.
1205
1206 @item Latin-3
1207 @cindex Latin-3
1208 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1209 equivalence.
1210
1211 @item Latin-4
1212 @cindex Latin-4
1213 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1214 equivalence.
1215
1216 @item Latin-5
1217 @cindex Latin-5
1218 @cindex Cyrillic
1219 Latin-4 letters (Cyrillic) allowed in identifiers, with uppercase and lowercase
1220 equivalence.
1221
1222 @item IBM PC (code page 437)
1223 @cindex code page 437
1224 This code page is the normal default for PCs in the U.S. It corresponds
1225 to the original IBM PC character set. This set has some, but not all, of
1226 the extended Latin-1 letters, but these letters do not have the same
1227 encoding as Latin-1. In this mode, these letters are allowed in
1228 identifiers with uppercase and lowercase equivalence.
1229
1230 @item IBM PC (code page 850)
1231 @cindex code page 850
1232 This code page is a modification of 437 extended to include all the
1233 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1234 mode, all these letters are allowed in identifiers with uppercase and
1235 lowercase equivalence.
1236
1237 @item Full Upper 8-bit
1238 Any character in the range 80-FF allowed in identifiers, and all are
1239 considered distinct. In other words, there are no uppercase and lowercase
1240 equivalences in this range. This is useful in conjunction with
1241 certain encoding schemes used for some foreign character sets (e.g.
1242 the typical method of representing Chinese characters on the PC).
1243
1244 @item No Upper-Half
1245 No upper-half characters in the range 80-FF are allowed in identifiers.
1246 This gives Ada 83 compatibility for identifier names.
1247 @end table
1248
1249 @noindent
1250 For precise data on the encodings permitted, and the uppercase and lowercase
1251 equivalences that are recognized, see the file @file{csets.adb} in
1252 the GNAT compiler sources. You will need to obtain a full source release
1253 of GNAT to obtain this file.
1254
1255 @node Wide Character Encodings
1256 @subsection Wide Character Encodings
1257
1258 @noindent
1259 GNAT allows wide character codes to appear in character and string
1260 literals, and also optionally in identifiers, by means of the following
1261 possible encoding schemes:
1262
1263 @table @asis
1264
1265 @item Hex Coding
1266 In this encoding, a wide character is represented by the following five
1267 character sequence:
1268
1269 @smallexample
1270 ESC a b c d
1271 @end smallexample
1272
1273 @noindent
1274 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1275 characters (using uppercase letters) of the wide character code. For
1276 example, ESC A345 is used to represent the wide character with code
1277 @code{16#A345#}.
1278 This scheme is compatible with use of the full Wide_Character set.
1279
1280 @item Upper-Half Coding
1281 @cindex Upper-Half Coding
1282 The wide character with encoding @code{16#abcd#} where the upper bit is on (in
1283 other words, "a" is in the range 8-F) is represented as two bytes,
1284 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1285 character, but is not required to be in the upper half. This method can
1286 be also used for shift-JIS or EUC, where the internal coding matches the
1287 external coding.
1288
1289 @item Shift JIS Coding
1290 @cindex Shift JIS Coding
1291 A wide character is represented by a two-character sequence,
1292 @code{16#ab#} and
1293 @code{16#cd#}, with the restrictions described for upper-half encoding as
1294 described above. The internal character code is the corresponding JIS
1295 character according to the standard algorithm for Shift-JIS
1296 conversion. Only characters defined in the JIS code set table can be
1297 used with this encoding method.
1298
1299 @item EUC Coding
1300 @cindex EUC Coding
1301 A wide character is represented by a two-character sequence
1302 @code{16#ab#} and
1303 @code{16#cd#}, with both characters being in the upper half. The internal
1304 character code is the corresponding JIS character according to the EUC
1305 encoding algorithm. Only characters defined in the JIS code set table
1306 can be used with this encoding method.
1307
1308 @item UTF-8 Coding
1309 A wide character is represented using
1310 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1311 10646-1/Am.2. Depending on the character value, the representation
1312 is a one, two, or three byte sequence:
1313 @smallexample
1314 @iftex
1315 @leftskip=.7cm
1316 @end iftex
1317 16#0000#-16#007f#: 2#0xxxxxxx#
1318 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
1319 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1320
1321 @end smallexample
1322
1323 @noindent
1324 where the xxx bits correspond to the left-padded bits of the
1325 16-bit character value. Note that all lower half ASCII characters
1326 are represented as ASCII bytes and all upper half characters and
1327 other wide characters are represented as sequences of upper-half
1328 (The full UTF-8 scheme allows for encoding 31-bit characters as
1329 6-byte sequences, but in this implementation, all UTF-8 sequences
1330 of four or more bytes length will be treated as illegal).
1331 @item Brackets Coding
1332 In this encoding, a wide character is represented by the following eight
1333 character sequence:
1334
1335 @smallexample
1336 [ " a b c d " ]
1337 @end smallexample
1338
1339 @noindent
1340 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1341 characters (using uppercase letters) of the wide character code. For
1342 example, ["A345"] is used to represent the wide character with code
1343 @code{16#A345#}. It is also possible (though not required) to use the
1344 Brackets coding for upper half characters. For example, the code
1345 @code{16#A3#} can be represented as @code{["A3"]}.
1346
1347 This scheme is compatible with use of the full Wide_Character set,
1348 and is also the method used for wide character encoding in the standard
1349 ACVC (Ada Compiler Validation Capability) test suite distributions.
1350
1351 @end table
1352
1353 @noindent
1354 Note: Some of these coding schemes do not permit the full use of the
1355 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
1356 use of the upper half of the Latin-1 set.
1357
1358 @node File Naming Rules
1359 @section File Naming Rules
1360
1361 @noindent
1362 The default file name is determined by the name of the unit that the
1363 file contains. The name is formed by taking the full expanded name of
1364 the unit and replacing the separating dots with hyphens and using
1365 lowercase for all letters.
1366
1367 An exception arises if the file name generated by the above rules starts
1368 with one of the characters
1369 a,g,i, or s,
1370 and the second character is a
1371 minus. In this case, the character tilde is used in place
1372 of the minus. The reason for this special rule is to avoid clashes with
1373 the standard names for child units of the packages System, Ada,
1374 Interfaces, and GNAT, which use the prefixes
1375 s- a- i- and g-
1376 respectively.
1377
1378 The file extension is @file{.ads} for a spec and
1379 @file{.adb} for a body. The following list shows some
1380 examples of these rules.
1381
1382 @table @file
1383 @item main.ads
1384 Main (spec)
1385 @item main.adb
1386 Main (body)
1387 @item arith_functions.ads
1388 Arith_Functions (package spec)
1389 @item arith_functions.adb
1390 Arith_Functions (package body)
1391 @item func-spec.ads
1392 Func.Spec (child package spec)
1393 @item func-spec.adb
1394 Func.Spec (child package body)
1395 @item main-sub.adb
1396 Sub (subunit of Main)
1397 @item a~bad.adb
1398 A.Bad (child package body)
1399 @end table
1400
1401 @noindent
1402 Following these rules can result in excessively long
1403 file names if corresponding
1404 unit names are long (for example, if child units or subunits are
1405 heavily nested). An option is available to shorten such long file names
1406 (called file name "krunching"). This may be particularly useful when
1407 programs being developed with GNAT are to be used on operating systems
1408 with limited file name lengths. @xref{Using gnatkr}.
1409
1410 Of course, no file shortening algorithm can guarantee uniqueness over
1411 all possible unit names; if file name krunching is used, it is your
1412 responsibility to ensure no name clashes occur. Alternatively you
1413 can specify the exact file names that you want used, as described
1414 in the next section. Finally, if your Ada programs are migrating from a
1415 compiler with a different naming convention, you can use the gnatchop
1416 utility to produce source files that follow the GNAT naming conventions.
1417 (For details @pxref{Renaming Files Using gnatchop}.)
1418
1419 @node Using Other File Names
1420 @section Using Other File Names
1421 @cindex File names
1422
1423 @noindent
1424 In the previous section, we have described the default rules used by
1425 GNAT to determine the file name in which a given unit resides. It is
1426 often convenient to follow these default rules, and if you follow them,
1427 the compiler knows without being explicitly told where to find all
1428 the files it needs.
1429
1430 However, in some cases, particularly when a program is imported from
1431 another Ada compiler environment, it may be more convenient for the
1432 programmer to specify which file names contain which units. GNAT allows
1433 arbitrary file names to be used by means of the Source_File_Name pragma.
1434 The form of this pragma is as shown in the following examples:
1435 @cindex Source_File_Name pragma
1436
1437 @smallexample
1438 @group
1439 @cartouche
1440 @b{pragma} Source_File_Name (My_Utilities.Stacks,
1441   Spec_File_Name => "myutilst_a.ada");
1442 @b{pragma} Source_File_name (My_Utilities.Stacks,
1443   Body_File_Name => "myutilst.ada");
1444 @end cartouche
1445 @end group
1446 @end smallexample
1447
1448 @noindent
1449 As shown in this example, the first argument for the pragma is the unit
1450 name (in this example a child unit). The second argument has the form
1451 of a named association. The identifier
1452 indicates whether the file name is for a spec or a body;
1453 the file name itself is given by a string literal.
1454
1455 The source file name pragma is a configuration pragma, which means that
1456 normally it will be placed in the @file{gnat.adc}
1457 file used to hold configuration
1458 pragmas that apply to a complete compilation environment.
1459 For more details on how the @file{gnat.adc} file is created and used
1460 @pxref{Handling of Configuration Pragmas}
1461 @cindex @file{gnat.adc}
1462
1463 GNAT allows completely arbitrary file names to be specified using the
1464 source file name pragma. However, if the file name specified has an
1465 extension other than @file{.ads} or @file{.adb} it is necessary to use a special
1466 syntax when compiling the file. The name in this case must be preceded
1467 by the special sequence @code{-x} followed by a space and the name of the
1468 language, here @code{ada}, as in:
1469
1470 @smallexample
1471 $ gcc -c -x ada peculiar_file_name.sim
1472 @end smallexample
1473
1474 @noindent
1475 @code{gnatmake} handles non-standard file names in the usual manner (the
1476 non-standard file name for the main program is simply used as the
1477 argument to gnatmake). Note that if the extension is also non-standard,
1478 then it must be included in the gnatmake command, it may not be omitted.
1479
1480 @node Alternative File Naming Schemes
1481 @section Alternative File Naming Schemes
1482 @cindex File naming schemes, alternative
1483 @cindex File names
1484
1485 In the previous section, we described the use of the @code{Source_File_Name}
1486 pragma to allow arbitrary names to be assigned to individual source files.
1487 However, this approach requires one pragma for each file, and especially in
1488 large systems can result in very long @file{gnat.adc} files, and also create
1489 a maintenance problem.
1490
1491 GNAT also provides a facility for specifying systematic file naming schemes
1492 other than the standard default naming scheme previously described. An
1493 alternative scheme for naming is specified by the use of
1494 @code{Source_File_Name} pragmas having the following format:
1495 @cindex Source_File_Name pragma
1496
1497 @smallexample
1498 pragma Source_File_Name (
1499    Spec_File_Name  => FILE_NAME_PATTERN
1500  [,Casing          => CASING_SPEC]
1501  [,Dot_Replacement => STRING_LITERAL]);
1502
1503 pragma Source_File_Name (
1504    Body_File_Name  => FILE_NAME_PATTERN
1505  [,Casing          => CASING_SPEC]
1506  [,Dot_Replacement => STRING_LITERAL]);
1507
1508 pragma Source_File_Name (
1509    Subunit_File_Name  => FILE_NAME_PATTERN
1510  [,Casing             => CASING_SPEC]
1511  [,Dot_Replacement    => STRING_LITERAL]);
1512
1513 FILE_NAME_PATTERN ::= STRING_LITERAL
1514 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1515
1516 @end smallexample
1517
1518 @noindent
1519 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1520 It contains a single asterisk character, and the unit name is substituted
1521 systematically for this asterisk. The optional parameter
1522 @code{Casing} indicates
1523 whether the unit name is to be all upper-case letters, all lower-case letters,
1524 or mixed-case. If no
1525 @code{Casing} parameter is used, then the default is all
1526 lower-case.
1527
1528 The optional @code{Dot_Replacement} string is used to replace any periods
1529 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1530 argument is used then separating dots appear unchanged in the resulting
1531 file name.
1532 Although the above syntax indicates that the
1533 @code{Casing} argument must appear
1534 before the @code{Dot_Replacement} argument, but it
1535 is also permissible to write these arguments in the opposite order.
1536
1537 As indicated, it is possible to specify different naming schemes for
1538 bodies, specs, and subunits. Quite often the rule for subunits is the
1539 same as the rule for bodies, in which case, there is no need to give
1540 a separate @code{Subunit_File_Name} rule, and in this case the
1541 @code{Body_File_name} rule is used for subunits as well.
1542
1543 The separate rule for subunits can also be used to implement the rather
1544 unusual case of a compilation environment (e.g. a single directory) which
1545 contains a subunit and a child unit with the same unit name. Although
1546 both units cannot appear in the same partition, the Ada Reference Manual
1547 allows (but does not require) the possibility of the two units coexisting
1548 in the same environment.
1549
1550 The file name translation works in the following steps:
1551
1552 @itemize @bullet
1553
1554 @item
1555 If there is a specific @code{Source_File_Name} pragma for the given unit,
1556 then this is always used, and any general pattern rules are ignored.
1557
1558 @item
1559 If there is a pattern type @code{Source_File_Name} pragma that applies to
1560 the unit, then the resulting file name will be used if the file exists. If
1561 more than one pattern matches, the latest one will be tried first, and the
1562 first attempt resulting in a reference to a file that exists will be used.
1563
1564 @item
1565 If no pattern type @code{Source_File_Name} pragma that applies to the unit
1566 for which the corresponding file exists, then the standard GNAT default
1567 naming rules are used.
1568
1569 @end itemize
1570
1571 @noindent
1572 As an example of the use of this mechanism, consider a commonly used scheme
1573 in which file names are all lower case, with separating periods copied
1574 unchanged to the resulting file name, and specs end with ".1.ada", and
1575 bodies end with ".2.ada". GNAT will follow this scheme if the following
1576 two pragmas appear:
1577
1578 @smallexample
1579 pragma Source_File_Name
1580   (Spec_File_Name => "*.1.ada");
1581 pragma Source_File_Name
1582   (Body_File_Name => "*.2.ada");
1583 @end smallexample
1584
1585 @noindent
1586 The default GNAT scheme is actually implemented by providing the following
1587 default pragmas internally:
1588
1589 @smallexample
1590 pragma Source_File_Name
1591   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
1592 pragma Source_File_Name
1593   (Body_File_Name => "*.adb", Dot_Replacement => "-");
1594 @end smallexample
1595
1596 @noindent
1597 Our final example implements a scheme typically used with one of the
1598 Ada 83 compilers, where the separator character for subunits was "__"
1599 (two underscores), specs were identified by adding @file{_.ADA}, bodies
1600 by adding @file{.ADA}, and subunits by
1601 adding @file{.SEP}. All file names were
1602 upper case. Child units were not present of course since this was an
1603 Ada 83 compiler, but it seems reasonable to extend this scheme to use
1604 the same double underscore separator for child units.
1605
1606 @smallexample
1607 pragma Source_File_Name
1608   (Spec_File_Name => "*_.ADA",
1609    Dot_Replacement => "__",
1610    Casing = Uppercase);
1611 pragma Source_File_Name
1612   (Body_File_Name => "*.ADA",
1613    Dot_Replacement => "__",
1614    Casing = Uppercase);
1615 pragma Source_File_Name
1616   (Subunit_File_Name => "*.SEP",
1617    Dot_Replacement => "__",
1618    Casing = Uppercase);
1619 @end smallexample
1620
1621 @node Generating Object Files
1622 @section Generating Object Files
1623
1624 @noindent
1625 An Ada program consists of a set of source files, and the first step in
1626 compiling the program is to generate the corresponding object files.
1627 These are generated by compiling a subset of these source files.
1628 The files you need to compile are the following:
1629
1630 @itemize @bullet
1631 @item
1632 If a package spec has no body, compile the package spec to produce the
1633 object file for the package.
1634
1635 @item
1636 If a package has both a spec and a body, compile the body to produce the
1637 object file for the package. The source file for the package spec need
1638 not be compiled in this case because there is only one object file, which
1639 contains the code for both the spec and body of the package.
1640
1641 @item
1642 For a subprogram, compile the subprogram body to produce the object file
1643 for the subprogram. The spec, if one is present, is as usual in a
1644 separate file, and need not be compiled.
1645
1646 @item
1647 @cindex Subunits
1648 In the case of subunits, only compile the parent unit. A single object
1649 file is generated for the entire subunit tree, which includes all the
1650 subunits.
1651
1652 @item
1653 Compile child units independently of their parent units
1654 (though, of course, the spec of all the ancestor unit must be present in order
1655 to compile a child unit).
1656
1657 @item
1658 @cindex Generics
1659 Compile generic units in the same manner as any other units. The object
1660 files in this case are small dummy files that contain at most the
1661 flag used for elaboration checking. This is because GNAT always handles generic
1662 instantiation by means of macro expansion. However, it is still necessary to
1663 compile generic units, for dependency checking and elaboration purposes.
1664 @end itemize
1665
1666 @noindent
1667 The preceding rules describe the set of files that must be compiled to
1668 generate the object files for a program. Each object file has the same
1669 name as the corresponding source file, except that the extension is
1670 @file{.o} as usual.
1671
1672 You may wish to compile other files for the purpose of checking their
1673 syntactic and semantic correctness. For example, in the case where a
1674 package has a separate spec and body, you would not normally compile the
1675 spec. However, it is convenient in practice to compile the spec to make
1676 sure it is error-free before compiling clients of this spec, because such
1677 compilations will fail if there is an error in the spec.
1678
1679 GNAT provides an option for compiling such files purely for the
1680 purposes of checking correctness; such compilations are not required as
1681 part of the process of building a program. To compile a file in this
1682 checking mode, use the @option{-gnatc} switch.
1683
1684 @node Source Dependencies
1685 @section Source Dependencies
1686
1687 @noindent
1688 A given object file clearly depends on the source file which is compiled
1689 to produce it. Here we are using @dfn{depends} in the sense of a typical
1690 @code{make} utility; in other words, an object file depends on a source
1691 file if changes to the source file require the object file to be
1692 recompiled.
1693 In addition to this basic dependency, a given object may depend on
1694 additional source files as follows:
1695
1696 @itemize @bullet
1697 @item
1698 If a file being compiled @code{with}'s a unit @var{X}, the object file
1699 depends on the file containing the spec of unit @var{X}. This includes
1700 files that are @code{with}'ed implicitly either because they are parents
1701 of @code{with}'ed child units or they are run-time units required by the
1702 language constructs used in a particular unit.
1703
1704 @item
1705 If a file being compiled instantiates a library level generic unit, the
1706 object file depends on both the spec and body files for this generic
1707 unit.
1708
1709 @item
1710 If a file being compiled instantiates a generic unit defined within a
1711 package, the object file depends on the body file for the package as
1712 well as the spec file.
1713
1714 @item
1715 @findex Inline
1716 @cindex @option{-gnatn} switch
1717 If a file being compiled contains a call to a subprogram for which
1718 pragma @code{Inline} applies and inlining is activated with the
1719 @option{-gnatn} switch, the object file depends on the file containing the
1720 body of this subprogram as well as on the file containing the spec. Note
1721 that for inlining to actually occur as a result of the use of this switch,
1722 it is necessary to compile in optimizing mode.
1723
1724 @cindex @option{-gnatN} switch
1725 The use of @option{-gnatN} activates a more extensive inlining optimization
1726 that is performed by the front end of the compiler. This inlining does
1727 not require that the code generation be optimized. Like @option{-gnatn},
1728 the use of this switch generates additional dependencies.
1729
1730 @item
1731 If an object file O  depends on the proper body of a subunit through inlining
1732 or instantiation, it depends on the parent unit of the subunit. This means that
1733 any modification of the parent unit or one of its subunits affects the
1734 compilation of O.
1735
1736 @item
1737 The object file for a parent unit depends on all its subunit body files.
1738
1739 @item
1740 The previous two rules meant that for purposes of computing dependencies and
1741 recompilation, a body and all its subunits are treated as an indivisible whole.
1742
1743 @noindent
1744 These rules are applied transitively: if unit @code{A} @code{with}'s
1745 unit @code{B}, whose elaboration calls an inlined procedure in package
1746 @code{C}, the object file for unit @code{A} will depend on the body of
1747 @code{C}, in file @file{c.adb}.
1748
1749 The set of dependent files described by these rules includes all the
1750 files on which the unit is semantically dependent, as described in the
1751 Ada 95 Language Reference Manual. However, it is a superset of what the
1752 ARM describes, because it includes generic, inline, and subunit dependencies.
1753
1754 An object file must be recreated by recompiling the corresponding source
1755 file if any of the source files on which it depends are modified. For
1756 example, if the @code{make} utility is used to control compilation,
1757 the rule for an Ada object file must mention all the source files on
1758 which the object file depends, according to the above definition.
1759 The determination of the necessary
1760 recompilations is done automatically when one uses @code{gnatmake}.
1761 @end itemize
1762
1763 @node The Ada Library Information Files
1764 @section The Ada Library Information Files
1765 @cindex Ada Library Information files
1766 @cindex @file{ali} files
1767
1768 @noindent
1769 Each compilation actually generates two output files. The first of these
1770 is the normal object file that has a @file{.o} extension. The second is a
1771 text file containing full dependency information. It has the same
1772 name as the source file, but an @file{.ali} extension.
1773 This file is known as the Ada Library Information (@file{ali}) file.
1774 The following information is contained in the @file{ali} file.
1775
1776 @itemize @bullet
1777 @item
1778 Version information (indicates which version of GNAT was used to compile
1779 the unit(s) in question)
1780
1781 @item
1782 Main program information (including priority and time slice settings,
1783 as well as the wide character encoding used during compilation).
1784
1785 @item
1786 List of arguments used in the @code{gcc} command for the compilation
1787
1788 @item
1789 Attributes of the unit, including configuration pragmas used, an indication
1790 of whether the compilation was successful, exception model used etc.
1791
1792 @item
1793 A list of relevant restrictions applying to the unit (used for consistency)
1794 checking.
1795
1796 @item
1797 Categorization information (e.g. use of pragma @code{Pure}).
1798
1799 @item
1800 Information on all @code{with}'ed units, including presence of
1801 @code{Elaborate} or @code{Elaborate_All} pragmas.
1802
1803 @item
1804 Information from any @code{Linker_Options} pragmas used in the unit
1805
1806 @item
1807 Information on the use of @code{Body_Version} or @code{Version}
1808 attributes in the unit.
1809
1810 @item
1811 Dependency information. This is a list of files, together with
1812 time stamp and checksum information. These are files on which
1813 the unit depends in the sense that recompilation is required
1814 if any of these units are modified.
1815
1816 @item
1817 Cross-reference data. Contains information on all entities referenced
1818 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
1819 provide cross-reference information.
1820
1821 @end itemize
1822
1823 @noindent
1824 For a full detailed description of the format of the @file{ali} file,
1825 see the source of the body of unit @code{Lib.Writ}, contained in file
1826 @file{lib-writ.adb} in the GNAT compiler sources.
1827
1828 @node Binding an Ada Program
1829 @section Binding an Ada Program
1830
1831 @noindent
1832 When using languages such as C and C++, once the source files have been
1833 compiled the only remaining step in building an executable program
1834 is linking the object modules together. This means that it is possible to
1835 link an inconsistent version of a program, in which two units have
1836 included different versions of the same header.
1837
1838 The rules of Ada do not permit such an inconsistent program to be built.
1839 For example, if two clients have different versions of the same package,
1840 it is illegal to build a program containing these two clients.
1841 These rules are enforced by the GNAT binder, which also determines an
1842 elaboration order consistent with the Ada rules.
1843
1844 The GNAT binder is run after all the object files for a program have
1845 been created. It is given the name of the main program unit, and from
1846 this it determines the set of units required by the program, by reading the
1847 corresponding ALI files. It generates error messages if the program is
1848 inconsistent or if no valid order of elaboration exists.
1849
1850 If no errors are detected, the binder produces a main program, in Ada by
1851 default, that contains calls to the elaboration procedures of those
1852 compilation unit that require them, followed by
1853 a call to the main program. This Ada program is compiled to generate the
1854 object file for the main program. The name of
1855 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
1856 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
1857 main program unit.
1858
1859 Finally, the linker is used to build the resulting executable program,
1860 using the object from the main program from the bind step as well as the
1861 object files for the Ada units of the program.
1862
1863 @node Mixed Language Programming
1864 @section Mixed Language Programming
1865 @cindex Mixed Language Programming
1866
1867 @menu
1868 * Interfacing to C::
1869 * Calling Conventions::
1870 @end menu
1871
1872 @node Interfacing to C
1873 @subsection Interfacing to C
1874 @noindent
1875 There are two ways to
1876 build a program that contains some Ada files and some other language
1877 files depending on whether the main program is in Ada or not.
1878 If the main program is in Ada, you should proceed as follows:
1879
1880 @enumerate
1881 @item
1882 Compile the other language files to generate object files. For instance:
1883 @smallexample
1884 gcc -c file1.c
1885 gcc -c file2.c
1886 @end smallexample
1887
1888 @item
1889 Compile the Ada units to produce a set of object files and ALI
1890 files. For instance:
1891 @smallexample
1892 gnatmake -c my_main.adb
1893 @end smallexample
1894
1895 @item
1896 Run the Ada binder on the Ada main program. For instance:
1897 @smallexample
1898 gnatbind my_main.ali
1899 @end smallexample
1900
1901 @item
1902 Link the Ada main program, the Ada objects and the other language
1903 objects. For instance:
1904 @smallexample
1905 gnatlink my_main.ali file1.o file2.o
1906 @end smallexample
1907 @end enumerate
1908
1909 The three last steps can be grouped in a single command:
1910 @smallexample
1911 gnatmake my_main.adb -largs file1.o file2.o
1912 @end smallexample
1913
1914 @cindex Binder output file
1915 @noindent
1916 If the main program is in some language other than Ada, you may
1917 have more than one entry point in the Ada subsystem. You must use a
1918 special option of the binder to generate callable routines to initialize
1919 and finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
1920 Calls to the initialization and finalization routines must be inserted in
1921 the main program, or some other appropriate point in the code. The call to
1922 initialize the Ada units must occur before the first Ada subprogram is
1923 called, and the call to finalize the Ada units must occur after the last
1924 Ada subprogram returns. You use the same procedure for building the
1925 program as described previously. In this case, however, the binder
1926 only places the initialization and finalization subprograms into file
1927 @file{b~@var{xxx}.adb} instead of the main program.
1928 So, if the main program is not in Ada, you should proceed as follows:
1929
1930 @enumerate
1931 @item
1932 Compile the other language files to generate object files. For instance:
1933 @smallexample
1934 gcc -c file1.c
1935 gcc -c file2.c
1936 @end smallexample
1937
1938 @item
1939 Compile the Ada units to produce a set of object files and ALI
1940 files. For instance:
1941 @smallexample
1942 gnatmake -c entry_point1.adb
1943 gnatmake -c entry_point2.adb
1944 @end smallexample
1945
1946 @item
1947 Run the Ada binder on the Ada main program. For instance:
1948 @smallexample
1949 gnatbind -n entry_point1.ali entry_point2.ali
1950 @end smallexample
1951
1952 @item
1953 Link the Ada main program, the Ada objects and the other language
1954 objects. You only need to give the last entry point here. For instance:
1955 @smallexample
1956 gnatlink entry_point2.ali file1.o file2.o
1957 @end smallexample
1958 @end enumerate
1959
1960 @node Calling Conventions
1961 @subsection Calling Conventions
1962 @cindex Foreign Languages
1963 @cindex Calling Conventions
1964 GNAT follows standard calling sequence conventions and will thus interface
1965 to any other language that also follows these conventions. The following
1966 Convention identifiers are recognized by GNAT:
1967
1968 @itemize @bullet
1969 @cindex Interfacing to Ada
1970 @cindex Other Ada compilers
1971 @cindex Convention Ada
1972 @item
1973 Ada. This indicates that the standard Ada calling sequence will be
1974 used and all Ada data items may be passed without any limitations in the
1975 case where GNAT is used to generate both the caller and callee. It is also
1976 possible to mix GNAT generated code and code generated by another Ada
1977 compiler. In this case, the data types should be restricted to simple
1978 cases, including primitive types. Whether complex data types can be passed
1979 depends on the situation. Probably it is safe to pass simple arrays, such
1980 as arrays of integers or floats. Records may or may not work, depending
1981 on whether both compilers lay them out identically. Complex structures
1982 involving variant records, access parameters, tasks, or protected types,
1983 are unlikely to be able to be passed.
1984
1985 Note that in the case of GNAT running
1986 on a platform that supports DEC Ada 83, a higher degree of compatibility
1987 can be guaranteed, and in particular records are layed out in an identical
1988 manner in the two compilers. Note also that if output from two different
1989 compilers is mixed, the program is responsible for dealing with elaboration
1990 issues. Probably the safest approach is to write the main program in the
1991 version of Ada other than GNAT, so that it takes care of its own elaboration
1992 requirements, and then call the GNAT-generated adainit procedure to ensure
1993 elaboration of the GNAT components. Consult the documentation of the other
1994 Ada compiler for further details on elaboration.
1995
1996 However, it is not possible to mix the tasking run time of GNAT and
1997 DEC Ada 83, All the tasking operations must either be entirely within
1998 GNAT compiled sections of the program, or entirely within DEC Ada 83
1999 compiled sections of the program.
2000
2001 @cindex Interfacing to Assembly
2002 @cindex Convention Assembler
2003 @item
2004 Assembler. Specifies assembler as the convention. In practice this has the
2005 same effect as convention Ada (but is not equivalent in the sense of being
2006 considered the same convention).
2007
2008 @cindex Convention Asm
2009 @findex Asm
2010 @item
2011 Asm. Equivalent to Assembler.
2012
2013 @cindex Convention Asm
2014 @findex Asm
2015 @item
2016 Asm. Equivalent to Assembly.
2017
2018 @cindex Interfacing to COBOL
2019 @cindex Convention COBOL
2020 @findex COBOL
2021 @item
2022 COBOL. Data will be passed according to the conventions described
2023 in section B.4 of the Ada 95 Reference Manual.
2024
2025 @findex C
2026 @cindex Interfacing to C
2027 @cindex Convention C
2028 @item
2029 C. Data will be passed according to the conventions described
2030 in section B.3 of the Ada 95 Reference Manual.
2031
2032 @cindex Convention Default
2033 @findex Default
2034 @item
2035 Default. Equivalent to C.
2036
2037 @cindex Convention External
2038 @findex External
2039 @item
2040 External. Equivalent to C.
2041
2042 @findex C++
2043 @cindex Interfacing to C++
2044 @cindex Convention C++
2045 @item
2046 CPP. This stands for C++. For most purposes this is identical to C.
2047 See the separate description of the specialized GNAT pragmas relating to
2048 C++ interfacing for further details.
2049
2050 @findex Fortran
2051 @cindex Interfacing to Fortran
2052 @cindex Convention Fortran
2053 @item
2054 Fortran. Data will be passed according to the conventions described
2055 in section B.5 of the Ada 95 Reference Manual.
2056
2057 @item
2058 Intrinsic. This applies to an intrinsic operation, as defined in the Ada 95
2059 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
2060 this means that the body of the subprogram is provided by the compiler itself,
2061 usually by means of an efficient code sequence, and that the user does not
2062 supply an explicit body for it. In an application program, the pragma can only
2063 be applied to the following two sets of names, which the GNAT compiler
2064 recognizes.
2065 @itemize @bullet
2066 @item
2067 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
2068 Arithmetic.  The corresponding subprogram declaration must have
2069 two formal parameters. The
2070 first one must be a signed integer type or a modular type with a binary
2071 modulus, and the second parameter must be of type Natural.
2072 The return type must be the same as the type of the first argument. The size
2073 of this type can only be 8, 16, 32, or 64.
2074 @item binary arithmetic operators: "+", "-", "*", "/"
2075 The corresponding operator declaration must have parameters and result type
2076 that have the same root numeric type (for example, all three are long_float
2077 types). This simplifies the definition of operations that use type checking
2078 to perform dimensional checks:
2079 @smallexample
2080 type Distance is new Long_Float;
2081 type Time     is new Long_Float;
2082 type Velocity is new Long_Float;
2083 function "/" (D : Distance; T : Time)
2084   return Velocity;
2085 pragma Import (Intrinsic, "/");
2086 @end smallexample
2087 @noindent
2088 This common idiom is often programmed with a generic definition and an explicit
2089 body. The pragma makes it simpler to introduce such declarations. It incurs
2090 no overhead in compilation time or code size, because it is implemented as a
2091 single machine instruction.
2092 @end itemize
2093 @noindent
2094
2095 @findex Stdcall
2096 @cindex Convention Stdcall
2097 @item
2098 Stdcall. This is relevant only to NT/Win95 implementations of GNAT,
2099 and specifies that the Stdcall calling sequence will be used, as defined
2100 by the NT API.
2101
2102 @findex DLL
2103 @cindex Convention DLL
2104 @item
2105 DLL. This is equivalent to Stdcall.
2106
2107 @findex Win32
2108 @cindex Convention Win32
2109 @item
2110 Win32. This is equivalent to Stdcall.
2111
2112 @findex Stubbed
2113 @cindex Convention Stubbed
2114 @item
2115 Stubbed. This is a special convention that indicates that the compiler
2116 should provide a stub body that raises @code{Program_Error}.
2117 @end itemize
2118
2119 @noindent
2120 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2121 that can be used to parametrize conventions and allow additional synonyms
2122 to be specified. For example if you have legacy code in which the convention
2123 identifier Fortran77 was used for Fortran, you can use the configuration
2124 pragma:
2125
2126 @smallexample
2127    pragma Convention_Identifier (Fortran77, Fortran);
2128 @end smallexample
2129
2130 @noindent
2131 And from now on the identifier Fortran77 may be used as a convention
2132 identifier (for example in an @code{Import} pragma) with the same
2133 meaning as Fortran.
2134
2135 @node Building Mixed Ada & C++ Programs
2136 @section Building Mixed Ada & C++ Programs
2137
2138 @noindent
2139 Building a mixed application containing both Ada and C++ code may be a
2140 challenge for the unaware programmer. As a matter of fact, this
2141 interfacing has not been standardized in the Ada 95 reference manual due
2142 to the immaturity and lack of standard of C++ at the time. This
2143 section gives a few hints that should make this task easier. In
2144 particular the first section addresses the differences with
2145 interfacing with C. The second section looks into the delicate problem
2146 of linking the complete application from its Ada and C++ parts. The last
2147 section give some hints on how the GNAT run time can be adapted in order
2148 to allow inter-language dispatching with a new C++ compiler.
2149
2150 @menu
2151 * Interfacing to C++::
2152 * Linking a Mixed C++ & Ada Program::
2153 * A Simple Example::
2154 * Adapting the Run Time to a New C++ Compiler::
2155 @end menu
2156
2157 @node Interfacing to C++
2158 @subsection Interfacing to C++
2159
2160 @noindent
2161 GNAT supports interfacing with C++ compilers generating code that is
2162 compatible with the standard Application Binary Interface of the given
2163 platform.
2164
2165 @noindent
2166 Interfacing can be done at 3 levels: simple data, subprograms and
2167 classes. In the first 2 cases, GNAT offer a specific @var{Convention
2168 CPP} that behaves exactly like @var{Convention C}. Usually C++ mangle
2169 names of subprograms and currently GNAT does not provide any help to
2170 solve the demangling problem. This problem can be addressed in 2 ways:
2171 @itemize @bullet
2172 @item
2173 by modifying the C++ code in order to force a C convention using
2174 the @var{extern "C"} syntax.
2175
2176 @item
2177 by figuring out the mangled name and use it as the Link_Name argument of
2178 the pragma import.
2179 @end itemize
2180
2181 @noindent
2182 Interfacing at the class level can be achieved by using the GNAT specific
2183 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
2184 Reference Manual for additional information.
2185
2186 @node Linking a Mixed C++ & Ada Program
2187 @subsection Linking a Mixed C++ & Ada Program
2188
2189 @noindent
2190 Usually the linker of the C++ development system must be used to link
2191 mixed applications because most C++ systems will resolve elaboration
2192 issues (such as calling constructors on global class instances)
2193 transparently during the link phase. GNAT has been adapted to ease the
2194 use of a foreign linker for the last phase. Three cases can be
2195 considered:
2196 @enumerate
2197
2198 @item
2199 Using GNAT and G++ (GNU C++ compiler) from the same GCC
2200 installation. The c++ linker can simply be called by using the c++
2201 specific driver called @code{c++}. Note that this setup is not
2202 very common because it may request recompiling the whole GCC
2203 tree from sources and it does not allow to upgrade easily to a new
2204 version of one compiler for one of the two languages without taking the
2205 risk of destabilizing the other.
2206
2207 @smallexample
2208 $ c++ -c file1.C
2209 $ c++ -c file2.C
2210 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
2211 @end smallexample
2212
2213 @item
2214 Using GNAT and G++ from 2 different GCC installations. If both compilers
2215 are on the PATH, the same method can be used. It is important to be
2216 aware that environment variables such as C_INCLUDE_PATH,
2217 GCC_EXEC_PREFIX, BINUTILS_ROOT or GCC_ROOT will affect both compilers at
2218 the same time and thus may make one of the 2 compilers operate
2219 improperly if they are set for the other. In particular it is important
2220 that the link command has access to the proper gcc library @file{libgcc.a},
2221 that is to say the one that is part of the C++ compiler
2222 installation. The implicit link command as suggested in the gnatmake
2223 command from the former example can be replaced by an explicit link
2224 command with full verbosity in order to verify which library is used:
2225 @smallexample
2226 $ gnatbind ada_unit
2227 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
2228 @end smallexample
2229 If there is a problem due to interfering environment variables, it can
2230 be workaround by using an intermediate script. The following example
2231 shows the proper script to use when GNAT has not been installed at its
2232 default location and g++ has been installed at its default location:
2233
2234 @smallexample
2235 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
2236 $ cat ./my_script
2237 #!/bin/sh
2238 unset BINUTILS_ROOT
2239 unset GCC_ROOT
2240 c++ $*
2241 @end smallexample
2242
2243 @item
2244 Using a non GNU C++ compiler. The same set of command as previously
2245 described can be used to insure that the c++ linker is
2246 used. Nonetheless, you need to add the path to libgcc explicitely, since some
2247 libraries needed by GNAT are located in this directory:
2248
2249 @smallexample
2250
2251 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2252 $ cat ./my_script
2253 #!/bin/sh
2254 CC $* `gcc -print-libgcc-file-name`
2255
2256 @end smallexample
2257
2258 Where CC is the name of the non GNU C++ compiler.
2259
2260 @end enumerate
2261
2262 @node A Simple Example
2263 @subsection  A Simple Example
2264 @noindent
2265 The following example, provided as part of the GNAT examples, show how
2266 to achieve procedural interfacing between Ada and C++ in both
2267 directions. The C++ class A has 2 methods. The first method is exported
2268 to Ada by the means of an extern C wrapper function. The second method
2269 calls an Ada subprogram. On the Ada side, The C++ calls is modelized by
2270 a limited record with a layout comparable to the C++ class. The Ada
2271 subprogram, in turn, calls the c++ method. So from the C++ main program
2272 the code goes back and forth between the 2 languages.
2273
2274 @noindent
2275 Here are the compilation commands
2276 for native configurations:
2277 @smallexample
2278 $ gnatmake -c simple_cpp_interface
2279 $ c++ -c cpp_main.C
2280 $ c++ -c ex7.C
2281 $ gnatbind -n simple_cpp_interface
2282 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
2283       -lstdc++ ex7.o cpp_main.o
2284 @end smallexample
2285 @noindent
2286 Here are the corresponding sources:
2287 @smallexample
2288
2289 //cpp_main.C
2290
2291 #include "ex7.h"
2292
2293 extern "C" @{
2294   void adainit (void);
2295   void adafinal (void);
2296   void method1 (A *t);
2297 @}
2298
2299 void method1 (A *t)
2300 @{
2301   t->method1 ();
2302 @}
2303
2304 int main ()
2305 @{
2306   A obj;
2307   adainit ();
2308   obj.method2 (3030);
2309   adafinal ();
2310 @}
2311
2312 //ex7.h
2313
2314 class Origin @{
2315  public:
2316   int o_value;
2317 @};
2318 class A : public Origin @{
2319  public:
2320   void method1 (void);
2321   virtual void method2 (int v);
2322   A();
2323   int   a_value;
2324 @};
2325
2326 //ex7.C
2327
2328 #include "ex7.h"
2329 #include <stdio.h>
2330
2331 extern "C" @{ void ada_method2 (A *t, int v);@}
2332
2333 void A::method1 (void)
2334 @{
2335   a_value = 2020;
2336   printf ("in A::method1, a_value = %d \n",a_value);
2337
2338 @}
2339
2340 void A::method2 (int v)
2341 @{
2342    ada_method2 (this, v);
2343    printf ("in A::method2, a_value = %d \n",a_value);
2344
2345 @}
2346
2347 A::A(void)
2348 @{
2349    a_value = 1010;
2350   printf ("in A::A, a_value = %d \n",a_value);
2351 @}
2352
2353 -- Ada sources
2354 @b{package} @b{body} Simple_Cpp_Interface @b{is}
2355
2356    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
2357    @b{begin}
2358       Method1 (This);
2359       This.A_Value := V;
2360    @b{end} Ada_Method2;
2361
2362 @b{end} Simple_Cpp_Interface;
2363
2364 @b{package} Simple_Cpp_Interface @b{is}
2365    @b{type} A @b{is} @b{limited}
2366       @b{record}
2367          O_Value : Integer;
2368          A_Value : Integer;
2369       @b{end} @b{record};
2370    @b{pragma} Convention (C, A);
2371
2372    @b{procedure} Method1 (This : @b{in} @b{out} A);
2373    @b{pragma} Import (C, Method1);
2374
2375    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
2376    @b{pragma} Export (C, Ada_Method2);
2377
2378 @b{end} Simple_Cpp_Interface;
2379 @end smallexample
2380
2381 @node Adapting the Run Time to a New C++ Compiler
2382 @subsection Adapting the Run Time to a New C++ Compiler
2383 @noindent
2384 GNAT offers the capability to derive Ada 95 tagged types directly from
2385 preexisting C++ classes and . See "Interfacing with C++" in the GNAT
2386 reference manual. The mechanism used by GNAT for achieving such a goal
2387 has been made user configurable through a GNAT library unit
2388 @code{Interfaces.CPP}. The default version of this file is adapted to
2389 the GNU c++ compiler. Internal knowledge of the virtual
2390 table layout used by the new C++ compiler is needed to configure
2391 properly this unit. The Interface of this unit is known by the compiler
2392 and cannot be changed except for the value of the constants defining the
2393 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
2394 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
2395 of this unit for more details.
2396
2397 @node Comparison between GNAT and C/C++ Compilation Models
2398 @section Comparison between GNAT and C/C++ Compilation Models
2399
2400 @noindent
2401 The GNAT model of compilation is close to the C and C++ models. You can
2402 think of Ada specs as corresponding to header files in C. As in C, you
2403 don't need to compile specs; they are compiled when they are used. The
2404 Ada @code{with} is similar in effect to the @code{#include} of a C
2405 header.
2406
2407 One notable difference is that, in Ada, you may compile specs separately
2408 to check them for semantic and syntactic accuracy. This is not always
2409 possible with C headers because they are fragments of programs that have
2410 less specific syntactic or semantic rules.
2411
2412 The other major difference is the requirement for running the binder,
2413 which performs two important functions. First, it checks for
2414 consistency. In C or C++, the only defense against assembling
2415 inconsistent programs lies outside the compiler, in a makefile, for
2416 example. The binder satisfies the Ada requirement that it be impossible
2417 to construct an inconsistent program when the compiler is used in normal
2418 mode.
2419
2420 @cindex Elaboration order control
2421 The other important function of the binder is to deal with elaboration
2422 issues. There are also elaboration issues in C++ that are handled
2423 automatically. This automatic handling has the advantage of being
2424 simpler to use, but the C++ programmer has no control over elaboration.
2425 Where @code{gnatbind} might complain there was no valid order of
2426 elaboration, a C++ compiler would simply construct a program that
2427 malfunctioned at run time.
2428
2429 @node Comparison between GNAT and Conventional Ada Library Models
2430 @section Comparison between GNAT and Conventional Ada Library Models
2431
2432 @noindent
2433 This section is intended to be useful to Ada programmers who have
2434 previously used an Ada compiler implementing the traditional Ada library
2435 model, as described in the Ada 95 Language Reference Manual. If you
2436 have not used such a system, please go on to the next section.
2437
2438 @cindex GNAT library
2439 In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
2440 source files themselves acts as the library. Compiling Ada programs does
2441 not generate any centralized information, but rather an object file and
2442 a ALI file, which are of interest only to the binder and linker.
2443 In a traditional system, the compiler reads information not only from
2444 the source file being compiled, but also from the centralized library.
2445 This means that the effect of a compilation depends on what has been
2446 previously compiled. In particular:
2447
2448 @itemize @bullet
2449 @item
2450 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
2451 to the version of the unit most recently compiled into the library.
2452
2453 @item
2454 Inlining is effective only if the necessary body has already been
2455 compiled into the library.
2456
2457 @item
2458 Compiling a unit may obsolete other units in the library.
2459 @end itemize
2460
2461 @noindent
2462 In GNAT, compiling one unit never affects the compilation of any other
2463 units because the compiler reads only source files. Only changes to source
2464 files can affect the results of a compilation. In particular:
2465
2466 @itemize @bullet
2467 @item
2468 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
2469 to the source version of the unit that is currently accessible to the
2470 compiler.
2471
2472 @item
2473 @cindex Inlining
2474 Inlining requires the appropriate source files for the package or
2475 subprogram bodies to be available to the compiler. Inlining is always
2476 effective, independent of the order in which units are complied.
2477
2478 @item
2479 Compiling a unit never affects any other compilations. The editing of
2480 sources may cause previous compilations to be out of date if they
2481 depended on the source file being modified.
2482 @end itemize
2483
2484 @noindent
2485 The most important result of these differences is that order of compilation
2486 is never significant in GNAT. There is no situation in which one is
2487 required to do one compilation before another. What shows up as order of
2488 compilation requirements in the traditional Ada library becomes, in
2489 GNAT, simple source dependencies; in other words, there is only a set
2490 of rules saying what source files must be present when a file is
2491 compiled.
2492
2493 @node Compiling Using gcc
2494 @chapter Compiling Using @code{gcc}
2495
2496 @noindent
2497 This chapter discusses how to compile Ada programs using the @code{gcc}
2498 command. It also describes the set of switches
2499 that can be used to control the behavior of the compiler.
2500 @menu
2501 * Compiling Programs::
2502 * Switches for gcc::
2503 * Search Paths and the Run-Time Library (RTL)::
2504 * Order of Compilation Issues::
2505 * Examples::
2506 @end menu
2507
2508 @node Compiling Programs
2509 @section Compiling Programs
2510
2511 @noindent
2512 The first step in creating an executable program is to compile the units
2513 of the program using the @code{gcc} command. You must compile the
2514 following files:
2515
2516 @itemize @bullet
2517 @item
2518 the body file (@file{.adb}) for a library level subprogram or generic
2519 subprogram
2520
2521 @item
2522 the spec file (@file{.ads}) for a library level package or generic
2523 package that has no body
2524
2525 @item
2526 the body file (@file{.adb}) for a library level package
2527 or generic package that has a body
2528
2529 @end itemize
2530
2531 @noindent
2532 You need @emph{not} compile the following files
2533
2534 @itemize @bullet
2535
2536 @item
2537 the spec of a library unit which has a body
2538
2539 @item
2540 subunits
2541 @end itemize
2542
2543 @noindent
2544 because they are compiled as part of compiling related units. GNAT
2545 package specs
2546 when the corresponding body is compiled, and subunits when the parent is
2547 compiled.
2548 @cindex No code generated
2549 If you attempt to compile any of these files, you will get one of the
2550 following error messages (where fff is the name of the file you compiled):
2551
2552 @smallexample
2553 No code generated for file @var{fff} (@var{package spec})
2554 No code generated for file @var{fff} (@var{subunit})
2555 @end smallexample
2556
2557 @noindent
2558 The basic command for compiling a file containing an Ada unit is
2559
2560 @smallexample
2561 $ gcc -c [@var{switches}] @file{file name}
2562 @end smallexample
2563
2564 @noindent
2565 where @var{file name} is the name of the Ada file (usually
2566 having an extension
2567 @file{.ads} for a spec or @file{.adb} for a body).
2568 You specify the
2569 @code{-c} switch to tell @code{gcc} to compile, but not link, the file.
2570 The result of a successful compilation is an object file, which has the
2571 same name as the source file but an extension of @file{.o} and an Ada
2572 Library Information (ALI) file, which also has the same name as the
2573 source file, but with @file{.ali} as the extension. GNAT creates these
2574 two output files in the current directory, but you may specify a source
2575 file in any directory using an absolute or relative path specification
2576 containing the directory information.
2577
2578 @findex gnat1
2579 @code{gcc} is actually a driver program that looks at the extensions of
2580 the file arguments and loads the appropriate compiler. For example, the
2581 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
2582 These programs are in directories known to the driver program (in some
2583 configurations via environment variables you set), but need not be in
2584 your path. The @code{gcc} driver also calls the assembler and any other
2585 utilities needed to complete the generation of the required object
2586 files.
2587
2588 It is possible to supply several file names on the same @code{gcc}
2589 command. This causes @code{gcc} to call the appropriate compiler for
2590 each file. For example, the following command lists three separate
2591 files to be compiled:
2592
2593 @smallexample
2594 $ gcc -c x.adb y.adb z.c
2595 @end smallexample
2596
2597 @noindent
2598 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
2599 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
2600 The compiler generates three object files @file{x.o}, @file{y.o} and
2601 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
2602 Ada compilations. Any switches apply to all the files listed,
2603 except for
2604 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
2605
2606 @node Switches for gcc
2607 @section Switches for @code{gcc}
2608
2609 @noindent
2610 The @code{gcc} command accepts switches that control the
2611 compilation process. These switches are fully described in this section.
2612 First we briefly list all the switches, in alphabetical order, then we
2613 describe the switches in more detail in functionally grouped sections.
2614
2615 @menu
2616 * Output and Error Message Control::
2617 * Debugging and Assertion Control::
2618 * Run-Time Checks::
2619 * Stack Overflow Checking::
2620 * Run-Time Control::
2621 * Validity Checking::
2622 * Style Checking::
2623 * Using gcc for Syntax Checking::
2624 * Using gcc for Semantic Checking::
2625 * Compiling Ada 83 Programs::
2626 * Character Set Control::
2627 * File Naming Control::
2628 * Subprogram Inlining Control::
2629 * Auxiliary Output Control::
2630 * Debugging Control::
2631 * Units to Sources Mapping Files::
2632 @end menu
2633
2634 @table @code
2635 @cindex @code{-b} (@code{gcc})
2636 @item -b @var{target}
2637 Compile your program to run on @var{target}, which is the name of a
2638 system configuration. You must have a GNAT cross-compiler built if
2639 @var{target} is not the same as your host system.
2640
2641 @item -B@var{dir}
2642 @cindex @code{-B} (@code{gcc})
2643 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
2644 from @var{dir} instead of the default location. Only use this switch
2645 when multiple versions of the GNAT compiler are available. See the
2646 @code{gcc} manual page for further details. You would normally use the
2647 @code{-b} or @code{-V} switch instead.
2648
2649 @item -c
2650 @cindex @code{-c} (@code{gcc})
2651 Compile. Always use this switch when compiling Ada programs.
2652
2653 Note: for some other languages when using @code{gcc}, notably in
2654 the case of C and C++, it is possible to use
2655 use @code{gcc} without a @code{-c} switch to
2656 compile and link in one step. In the case of GNAT, you
2657 cannot use this approach, because the binder must be run
2658 and @code{gcc} cannot be used to run the GNAT binder.
2659
2660 @item -g
2661 @cindex @code{-g} (@code{gcc})
2662 Generate debugging information. This information is stored in the object
2663 file and copied from there to the final executable file by the linker,
2664 where it can be read by the debugger. You must use the
2665 @code{-g} switch if you plan on using the debugger.
2666
2667 @item -I@var{dir}
2668 @cindex @code{-I} (@code{gcc})
2669 @cindex RTL
2670 Direct GNAT to search the @var{dir} directory for source files needed by
2671 the current compilation
2672 (@pxref{Search Paths and the Run-Time Library (RTL)}).
2673
2674 @item -I-
2675 @cindex @code{-I-} (@code{gcc})
2676 @cindex RTL
2677 Except for the source file named in the command line, do not look for source files
2678 in the directory containing the source file named in the command line
2679 (@pxref{Search Paths and the Run-Time Library (RTL)}).
2680
2681 @item -o @var{file}
2682 @cindex @code{-o} (@code{gcc})
2683 This switch is used in @code{gcc} to redirect the generated object file
2684 and its associated ALI file. Beware of this switch with GNAT, because it may
2685 cause the object file and ALI file to have different names which in turn
2686 may confuse the binder and the linker.
2687
2688 @item -O[@var{n}]
2689 @cindex @code{-O} (@code{gcc})
2690 @var{n} controls the optimization level.
2691
2692 @table @asis
2693 @item n = 0
2694 No optimization, the default setting if no @code{-O} appears
2695
2696 @item n = 1
2697 Normal optimization, the default if you specify @code{-O} without
2698 an operand.
2699
2700 @item n = 2
2701 Extensive optimization
2702
2703 @item n = 3
2704 Extensive optimization with automatic inlining. This applies only to
2705 inlining within a unit. For details on control of inter-unit inlining
2706 see @xref{Subprogram Inlining Control}.
2707 @end table
2708
2709
2710 @item --RTS=@var{rts-path}
2711 @cindex @code{--RTS} (@code{gcc})
2712 Specifies the default location of the runtime library. Same meaning as the
2713 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
2714
2715 @item -S
2716 @cindex @code{-S} (@code{gcc})
2717 Used in place of @code{-c} to
2718 cause the assembler source file to be
2719 generated, using @file{.s} as the extension,
2720 instead of the object file.
2721 This may be useful if you need to examine the generated assembly code.
2722
2723 @item -v
2724 @cindex @code{-v} (@code{gcc})
2725 Show commands generated by the @code{gcc} driver. Normally used only for
2726 debugging purposes or if you need to be sure what version of the
2727 compiler you are executing.
2728
2729 @item -V @var{ver}
2730 @cindex @code{-V} (@code{gcc})
2731 Execute @var{ver} version of the compiler. This is the @code{gcc}
2732 version, not the GNAT version.
2733
2734 @item -gnata
2735 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
2736 activated.
2737
2738 @item -gnatA
2739 Avoid processing @file{gnat.adc}. If a gnat.adc file is present, it will be ignored.
2740
2741 @item -gnatb
2742 Generate brief messages to @file{stderr} even if verbose mode set.
2743
2744 @item -gnatc
2745 Check syntax and semantics only (no code generation attempted).
2746
2747 @item -gnatC
2748 Compress debug information and external symbol name table entries.
2749
2750 @item -gnatD
2751 Output expanded source files for source level debugging. This switch
2752 also suppress generation of cross-reference information (see -gnatx).
2753
2754 @item -gnatec@var{path}
2755 Specify a configuration pragma file. (see @ref{The Configuration Pragmas Files})
2756
2757 @item -gnatem@var{path}
2758 Specify a mapping file. (see @ref{Units to Sources Mapping Files})
2759
2760 @item -gnatE
2761 Full dynamic elaboration checks.
2762
2763 @item -gnatf
2764 Full errors. Multiple errors per line, all undefined references.
2765
2766 @item -gnatF
2767 Externals names are folded to all uppercase.
2768
2769 @item -gnatg
2770 Internal GNAT implementation mode. This should not be used for
2771 applications programs, it is intended only for use by the compiler
2772 and its run-time library. For documentation, see the GNAT sources.
2773
2774 @item -gnatG
2775 List generated expanded code in source form.
2776
2777 @item -gnati@var{c}
2778 Identifier character set
2779 (@var{c}=1/2/3/4/8/9/p/f/n/w).
2780
2781 @item -gnath
2782 Output usage information. The output is written to @file{stdout}.
2783
2784 @item -gnatk@var{n}
2785 Limit file names to @var{n} (1-999) characters (@code{k} = krunch).
2786
2787 @item -gnatl
2788 Output full source listing with embedded error messages.
2789
2790 @item -gnatm@var{n}
2791 Limit number of detected errors to @var{n} (1-999).
2792
2793 @item -gnatn
2794 Activate inlining across unit boundaries for subprograms for which
2795 pragma @code{inline} is specified.
2796
2797 @item -gnatN
2798 Activate front end inlining.
2799
2800 @item -fno-inline
2801 Suppresses all inlining, even if other optimization or inlining switches
2802 are set.
2803
2804 @item -fstack-check
2805 Activates stack checking. See separate section on stack checking for
2806 details of the use of this option.
2807
2808 @item -gnato
2809 Enable numeric overflow checking (which is not normally enabled by
2810 default). Not that division by zero is a separate check that is not
2811 controlled by this switch (division by zero checking is on by default).
2812
2813 @item -gnatp
2814 Suppress all checks.
2815
2816 @item -gnatq
2817 Don't quit; try semantics, even if parse errors.
2818
2819 @item -gnatQ
2820 Don't quit; generate @file{ali} and tree files even if illegalities.
2821
2822 @item -gnatP
2823 Enable polling. This is required on some systems (notably Windows NT) to
2824 obtain asynchronous abort and asynchronous transfer of control capability.
2825 See the description of pragma Polling in the GNAT Reference Manual for
2826 full details.
2827
2828 @item -gnatR[0/1/2/3][s]
2829 Output representation information for declared types and objects.
2830
2831 @item -gnats
2832 Syntax check only.
2833
2834 @item -gnatt
2835 Tree output file to be generated.
2836
2837 @item -gnatT nnn
2838 Set time slice to specified number of microseconds
2839
2840 @item -gnatu
2841 List units for this compilation.
2842
2843 @item -gnatU
2844 Tag all error messages with the unique string "error:"
2845
2846 @item -gnatv
2847 Verbose mode. Full error output with source lines to @file{stdout}.
2848
2849 @item -gnatV
2850 Control level of validity checking. See separate section describing
2851 this feature.
2852
2853 @item -gnatwxxx@var{xxx}
2854 Warning mode where
2855 @var{xxx} is a string of options describing the exact warnings that
2856 are enabled or disabled. See separate section on warning control.
2857
2858 @item -gnatW@var{e}
2859 Wide character encoding method
2860 (@var{e}=n/h/u/s/e/8).
2861
2862 @item -gnatx
2863 Suppress generation of cross-reference information.
2864
2865 @item -gnaty
2866 Enable built-in style checks. See separate section describing this feature.
2867
2868 @item -gnatz@var{m}
2869 Distribution stub generation and compilation
2870 (@var{m}=r/c for receiver/caller stubs).
2871
2872 @item -gnat83
2873 Enforce Ada 83 restrictions.
2874
2875 @item -pass-exit-codes
2876 Catch exit codes from the compiler and use the most meaningful as
2877 exit status.
2878 @end table
2879
2880 You may combine a sequence of GNAT switches into a single switch. For
2881 example, the combined switch
2882
2883 @cindex Combining GNAT switches
2884 @smallexample
2885 -gnatofi3
2886 @end smallexample
2887
2888 @noindent
2889 is equivalent to specifying the following sequence of switches:
2890
2891 @smallexample
2892 -gnato -gnatf -gnati3
2893 @end smallexample
2894
2895 @noindent
2896 The following restrictions apply to the combination of switches
2897 in this manner:
2898
2899 @itemize @bullet
2900 @item
2901 The switch @option{-gnatc} if combined with other switches must come
2902 first in the string.
2903
2904 @item
2905 The switch @option{-gnats} if combined with other switches must come
2906 first in the string.
2907
2908 @item
2909 Once a "y" appears in the string (that is a use of the @option{-gnaty}
2910 switch), then all further characters in the switch are interpreted
2911 as style modifiers (see description of @option{-gnaty}).
2912
2913 @item
2914 Once a "d" appears in the string (that is a use of the @option{-gnatd}
2915 switch), then all further characters in the switch are interpreted
2916 as debug flags (see description of @option{-gnatd}).
2917
2918 @item
2919 Once a "w" appears in the string (that is a use of the @option{-gnatw}
2920 switch), then all further characters in the switch are interpreted
2921 as warning mode modifiers (see description of @option{-gnatw}).
2922
2923 @item
2924 Once a "V" appears in the string (that is a use of the @option{-gnatV}
2925 switch), then all further characters in the switch are interpreted
2926 as validity checking options (see description of @option{-gnatV}).
2927
2928 @end itemize
2929
2930 @node Output and Error Message Control
2931 @subsection Output and Error Message Control
2932 @findex stderr
2933
2934 @noindent
2935 The standard default format for error messages is called "brief format."
2936 Brief format messages are written to @file{stderr} (the standard error
2937 file) and have the following form:
2938
2939 @smallexample
2940 @iftex
2941 @leftskip=.7cm
2942 @end iftex
2943 e.adb:3:04: Incorrect spelling of keyword "function"
2944 e.adb:4:20: ";" should be "is"
2945 @end smallexample
2946
2947 @noindent
2948 The first integer after the file name is the line number in the file,
2949 and the second integer is the column number within the line.
2950 @code{glide} can parse the error messages
2951 and point to the referenced character.
2952 The following switches provide control over the error message
2953 format:
2954
2955 @table @code
2956 @item -gnatv
2957 @cindex @option{-gnatv} (@code{gcc})
2958 @findex stdout
2959 The v stands for verbose.
2960 The effect of this setting is to write long-format error
2961 messages to @file{stdout} (the standard output file.
2962 The same program compiled with the
2963 @option{-gnatv} switch would generate:
2964
2965 @smallexample
2966 @group
2967 @cartouche
2968 3. funcion X (Q : Integer)
2969    |
2970 >>> Incorrect spelling of keyword "function"
2971 4. return Integer;
2972                  |
2973 >>> ";" should be "is"
2974 @end cartouche
2975 @end group
2976 @end smallexample
2977
2978 @noindent
2979 The vertical bar indicates the location of the error, and the @samp{>>>}
2980 prefix can be used to search for error messages. When this switch is
2981 used the only source lines output are those with errors.
2982
2983 @item -gnatl
2984 @cindex @option{-gnatl} (@code{gcc})
2985 The @code{l} stands for list.
2986 This switch causes a full listing of
2987 the file to be generated. The output might look as follows:
2988
2989 @smallexample
2990 @group
2991 @cartouche
2992  1. procedure E is
2993  2.    V : Integer;
2994  3.    funcion X (Q : Integer)
2995        |
2996     >>> Incorrect spelling of keyword "function"
2997  4.     return Integer;
2998                       |
2999     >>> ";" should be "is"
3000  5.    begin
3001  6.       return Q + Q;
3002  7.    end;
3003  8. begin
3004  9.    V := X + X;
3005 10.end E;
3006 @end cartouche
3007 @end group
3008 @end smallexample
3009
3010 @noindent
3011 @findex stderr
3012 When you specify the @option{-gnatv} or @option{-gnatl} switches and
3013 standard output is redirected, a brief summary is written to
3014 @file{stderr} (standard error) giving the number of error messages and
3015 warning messages generated.
3016
3017 @item -gnatU
3018 @cindex @option{-gnatU} (@code{gcc})
3019 This switch forces all error messages to be preceded by the unique
3020 string "error:". This means that error messages take a few more
3021 characters in space, but allows easy searching for and identification
3022 of error messages.
3023
3024 @item -gnatb
3025 @cindex @option{-gnatb} (@code{gcc})
3026 The @code{b} stands for brief.
3027 This switch causes GNAT to generate the
3028 brief format error messages to @file{stderr} (the standard error
3029 file) as well as the verbose
3030 format message or full listing (which as usual is written to
3031 @file{stdout} (the standard output file).
3032
3033 @item -gnatm@var{n}
3034 @cindex @option{-gnatm} (@code{gcc})
3035 The @code{m} stands for maximum.
3036 @var{n} is a decimal integer in the
3037 range of 1 to 999 and limits the number of error messages to be
3038 generated. For example, using @option{-gnatm2} might yield
3039
3040 @smallexample
3041 @iftex
3042 @leftskip=.7cm
3043 @end iftex
3044 e.adb:3:04: Incorrect spelling of keyword "function"
3045 e.adb:5:35: missing ".."
3046 fatal error: maximum errors reached
3047 compilation abandoned
3048 @end smallexample
3049
3050 @item -gnatf
3051 @cindex @option{-gnatf} (@code{gcc})
3052 @cindex Error messages, suppressing
3053 The @code{f} stands for full.
3054 Normally, the compiler suppresses error messages that are likely to be
3055 redundant. This switch causes all error
3056 messages to be generated. In particular, in the case of
3057 references to undefined variables. If a given variable is referenced
3058 several times, the normal format of messages is
3059 @smallexample
3060 @iftex
3061 @leftskip=.7cm
3062 @end iftex
3063 e.adb:7:07: "V" is undefined (more references follow)
3064 @end smallexample
3065
3066 @noindent
3067 where the parenthetical comment warns that there are additional
3068 references to the variable @code{V}. Compiling the same program with the
3069 @option{-gnatf} switch yields
3070
3071 @smallexample
3072 e.adb:7:07: "V" is undefined
3073 e.adb:8:07: "V" is undefined
3074 e.adb:8:12: "V" is undefined
3075 e.adb:8:16: "V" is undefined
3076 e.adb:9:07: "V" is undefined
3077 e.adb:9:12: "V" is undefined
3078 @end smallexample
3079
3080 @item -gnatq
3081 @cindex @option{-gnatq} (@code{gcc})
3082 The @code{q} stands for quit (really "don't quit").
3083 In normal operation mode, the compiler first parses the program and
3084 determines if there are any syntax errors. If there are, appropriate
3085 error messages are generated and compilation is immediately terminated.
3086 This switch tells
3087 GNAT to continue with semantic analysis even if syntax errors have been
3088 found. This may enable the detection of more errors in a single run. On
3089 the other hand, the semantic analyzer is more likely to encounter some
3090 internal fatal error when given a syntactically invalid tree.
3091
3092 @item -gnatQ
3093 In normal operation mode, the @file{ali} file is not generated if any
3094 illegalities are detected in the program. The use of @option{-gnatQ} forces
3095 generation of the @file{ali} file. This file is marked as being in
3096 error, so it cannot be used for binding purposes, but it does contain
3097 reasonably complete cross-reference information, and thus may be useful
3098 for use by tools (e.g. semantic browsing tools or integrated development
3099 environments) that are driven from the @file{ali} file.
3100
3101 In addition, if @option{-gnatt} is also specified, then the tree file is
3102 generated even if there are illegalities. It may be useful in this case
3103 to also specify @option{-gnatq} to ensure that full semantic processing
3104 occurs. The resulting tree file can be processed by ASIS, for the purpose
3105 of providing partial information about illegal units, but if the error
3106 causes the tree to be badly malformed, then ASIS may crash during the
3107 analysis.
3108
3109 @end table
3110
3111 @noindent
3112 In addition to error messages, which correspond to illegalities as defined
3113 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
3114 situations.
3115
3116 @cindex Warning messages
3117 First, the compiler considers some constructs suspicious and generates a
3118 warning message to alert you to a possible error. Second, if the
3119 compiler detects a situation that is sure to raise an exception at
3120 run time, it generates a warning message. The following shows an example
3121 of warning messages:
3122 @smallexample
3123 @iftex
3124 @leftskip=.2cm
3125 @end iftex
3126 e.adb:4:24: warning: creation of object may raise Storage_Error
3127 e.adb:10:17: warning: static value out of range
3128 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
3129
3130 @end smallexample
3131
3132 @noindent
3133 GNAT considers a large number of situations as appropriate
3134 for the generation of warning messages. As always, warnings are not
3135 definite indications of errors. For example, if you do an out-of-range
3136 assignment with the deliberate intention of raising a
3137 @code{Constraint_Error} exception, then the warning that may be
3138 issued does not indicate an error. Some of the situations for which GNAT
3139 issues warnings (at least some of the time) are given in the following
3140 list, which is not necessarily complete.
3141
3142 @itemize @bullet
3143 @item
3144 Possible infinitely recursive calls
3145
3146 @item
3147 Out-of-range values being assigned
3148
3149 @item
3150 Possible order of elaboration problems
3151
3152 @item
3153 Unreachable code
3154
3155 @item
3156 Fixed-point type declarations with a null range
3157
3158 @item
3159 Variables that are never assigned a value
3160
3161 @item
3162 Variables that are referenced before being initialized
3163
3164 @item
3165 Task entries with no corresponding accept statement
3166
3167 @item
3168 Duplicate accepts for the same task entry in a select
3169
3170 @item
3171 Objects that take too much storage
3172
3173 @item
3174 Unchecked conversion between types of differing sizes
3175
3176 @item
3177 Missing return statements along some execution paths in a function
3178
3179 @item
3180 Incorrect (unrecognized) pragmas
3181
3182 @item
3183 Incorrect external names
3184
3185 @item
3186 Allocation from empty storage pool
3187
3188 @item
3189 Potentially blocking operations in protected types
3190
3191 @item
3192 Suspicious parenthesization of expressions
3193
3194 @item
3195 Mismatching bounds in an aggregate
3196
3197 @item
3198 Attempt to return local value by reference
3199
3200 @item
3201 Unrecognized pragmas
3202
3203 @item
3204 Premature instantiation of a generic body
3205
3206 @item
3207 Attempt to pack aliased components
3208
3209 @item
3210 Out of bounds array subscripts
3211
3212 @item
3213 Wrong length on string assignment
3214
3215 @item
3216 Violations of style rules if style checking is enabled
3217
3218 @item
3219 Unused with clauses
3220
3221 @item
3222 Bit_Order usage that does not have any effect
3223
3224 @item
3225 Compile time biased rounding of floating-point constant
3226
3227 @item
3228 Standard.Duration used to resolve universal fixed expression
3229
3230 @item
3231 Dereference of possibly null value
3232
3233 @item
3234 Declaration that is likely to cause storage error
3235
3236 @item
3237 Internal GNAT unit with'ed by application unit
3238
3239 @item
3240 Values known to be out of range at compile time
3241
3242 @item
3243 Unreferenced labels and variables
3244
3245 @item
3246 Address overlays that could clobber memory
3247
3248 @item
3249 Unexpected initialization when address clause present
3250
3251 @item
3252 Bad alignment for address clause
3253
3254 @item
3255 Useless type conversions
3256
3257 @item
3258 Redundant assignment statements
3259
3260 @item
3261 Accidental hiding of name by child unit
3262
3263 @item
3264 Unreachable code
3265
3266 @item
3267 Access before elaboration detected at compile time
3268
3269 @item
3270 A range in a @code{for} loop that is known to be null or might be null
3271
3272 @end itemize
3273
3274 @noindent
3275 The following switches are available to control the handling of
3276 warning messages:
3277
3278 @table @code
3279 @item -gnatwa (activate all optional errors)
3280 @cindex @option{-gnatwa} (@code{gcc})
3281 This switch activates most optional warning messages, see remaining list
3282 in this section for details on optional warning messages that can be
3283 individually controlled. The warnings that are not turned on by this
3284 switch are @option{-gnatwb} (biased rounding),
3285 @option{-gnatwd} (implicit dereferencing),
3286 and @option{-gnatwh} (hiding). All other optional warnings are
3287 turned on.
3288
3289 @item -gnatwA (suppress all optional errors)
3290 @cindex @option{-gnatwA} (@code{gcc})
3291 This switch suppresses all optional warning messages, see remaining list
3292 in this section for details on optional warning messages that can be
3293 individually controlled.
3294
3295 @item -gnatwb (activate warnings on biased rounding)
3296 @cindex @option{-gnatwb} (@code{gcc})
3297 @cindex Rounding, biased
3298 @cindex Biased rounding
3299 If a static floating-point expression has a value that is exactly half
3300 way between two adjacent machine numbers, then the rules of Ada
3301 (Ada Reference Manual, section 4.9(38)) require that this rounding
3302 be done away from zero, even if the normal unbiased rounding rules
3303 at run time would require rounding towards zero. This warning message
3304 alerts you to such instances where compile-time rounding and run-time
3305 rounding are not equivalent. If it is important to get proper run-time
3306 rounding, then you can force this by making one of the operands into
3307 a variable. The default is that such warnings are not generated.
3308 Note that @option{-gnatwa} does not affect the setting of
3309 this warning option.
3310
3311 @item -gnatwB (suppress warnings on biased rounding)
3312 @cindex @option{-gnatwB} (@code{gcc})
3313 This switch disables warnings on biased rounding.
3314
3315 @item -gnatwc (activate warnings on conditionals)
3316 @cindex @option{-gnatwc} (@code{gcc})
3317 @cindex Conditionals, constant
3318 This switch activates warnings for conditional expressions used in
3319 tests that are known to be True or False at compile time. The default
3320 is that such warnings are not generated.
3321 This warning can also be turned on using @option{-gnatwa}.
3322
3323 @item -gnatwC (suppress warnings on conditionals)
3324 @cindex @option{-gnatwC} (@code{gcc})
3325 This switch suppresses warnings for conditional expressions used in
3326 tests that are known to be True or False at compile time.
3327
3328 @item -gnatwd (activate warnings on implicit dereferencing)
3329 @cindex @option{-gnatwd} (@code{gcc})
3330 If this switch is set, then the use of a prefix of an access type
3331 in an indexed component, slice, or selected component without an
3332 explicit @code{.all} will generate a warning. With this warning
3333 enabled, access checks occur only at points where an explicit
3334 @code{.all} appears in the source code (assuming no warnings are
3335 generated as a result of this switch). The default is that such
3336 warnings are not generated.
3337 Note that @option{-gnatwa} does not affect the setting of
3338 this warning option.
3339
3340 @item -gnatwD (suppress warnings on implicit dereferencing)
3341 @cindex @option{-gnatwD} (@code{gcc})
3342 @cindex Implicit dereferencing
3343 @cindex Dereferencing, implicit
3344 This switch suppresses warnings for implicit deferences in
3345 indexed components, slices, and selected components.
3346
3347 @item -gnatwe (treat warnings as errors)
3348 @cindex @option{-gnatwe} (@code{gcc})
3349 @cindex Warnings, treat as error
3350 This switch causes warning messages to be treated as errors.
3351 The warning string still appears, but the warning messages are counted
3352 as errors, and prevent the generation of an object file.
3353
3354 @item -gnatwf (activate warnings on unreferenced formals)
3355 @cindex @option{-gnatwf} (@code{gcc})
3356 @cindex Formals, unreferenced
3357 This switch causes a warning to be generated if a formal parameter
3358 is not referenced in the body of the subprogram. This warning can
3359 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
3360
3361 @item -gnatwF (suppress warnings on unreferenced formals)
3362 @cindex @option{-gnatwF} (@code{gcc})
3363 This switch suppresses warnings for unreferenced formal
3364 parameters. Note that the
3365 combination @option{-gnatwu} followed by @option{-gnatwF} has the
3366 effect of warning on unreferenced entities other than subprogram
3367 formals.
3368
3369 @item -gnatwh (activate warnings on hiding)
3370 @cindex @option{-gnatwh} (@code{gcc})
3371 @cindex Hiding of Declarations
3372 This switch activates warnings on hiding declarations.
3373 A declaration is considered hiding
3374 if it is for a non-overloadable entity, and it declares an entity with the
3375 same name as some other entity that is directly or use-visible. The default
3376 is that such warnings are not generated.
3377 Note that @option{-gnatwa} does not affect the setting of this warning option.
3378
3379 @item -gnatwH (suppress warnings on hiding)
3380 @cindex @option{-gnatwH} (@code{gcc})
3381 This switch suppresses warnings on hiding declarations.
3382
3383 @item -gnatwi (activate warnings on implementation units).
3384 @cindex @option{-gnatwi} (@code{gcc})
3385 This switch activates warnings for a @code{with} of an internal GNAT
3386 implementation unit, defined as any unit from the @code{Ada},
3387 @code{Interfaces}, @code{GNAT},
3388  or @code{System}
3389 hierarchies that is not
3390 documented in either the Ada Reference Manual or the GNAT
3391 Programmer's Reference Manual. Such units are intended only
3392 for internal implementation purposes and should not be @code{with}'ed
3393 by user programs. The default is that such warnings are generated
3394 This warning can also be turned on using @option{-gnatwa}.
3395
3396 @item -gnatwI (disable warnings on implementation units).
3397 @cindex @option{-gnatwI} (@code{gcc})
3398 This switch disables warnings for a @code{with} of an internal GNAT
3399 implementation unit.
3400
3401 @item -gnatwl (activate warnings on elaboration pragmas)
3402 @cindex @option{-gnatwl} (@code{gcc})
3403 @cindex Elaboration, warnings
3404 This switch activates warnings on missing pragma Elaborate_All statements.
3405 See the section in this guide on elaboration checking for details on
3406 when such pragma should be used. The default is that such warnings
3407 are not generated.
3408 This warning can also be turned on using @option{-gnatwa}.
3409
3410 @item -gnatwL (suppress warnings on elaboration pragmas)
3411 @cindex @option{-gnatwL} (@code{gcc})
3412 This switch suppresses warnings on missing pragma Elaborate_All statements.
3413 See the section in this guide on elaboration checking for details on
3414 when such pragma should be used.
3415
3416 @item -gnatwo (activate warnings on address clause overlays)
3417 @cindex @option{-gnatwo} (@code{gcc})
3418 @cindex Address Clauses, warnings
3419 This switch activates warnings for possibly unintended initialization
3420 effects of defining address clauses that cause one variable to overlap
3421 another. The default is that such warnings are generated.
3422 This warning can also be turned on using @option{-gnatwa}.
3423
3424 @item -gnatwO (suppress warnings on address clause overlays)
3425 @cindex @option{-gnatwO} (@code{gcc})
3426 This switch suppresses warnings on possibly unintended initialization
3427 effects of defining address clauses that cause one variable to overlap
3428 another.
3429
3430 @item -gnatwp (activate warnings on ineffective pragma Inlines)
3431 @cindex @option{-gnatwp} (@code{gcc})
3432 @cindex Inlining, warnings
3433 This switch activates warnings for failure of front end inlining
3434 (activated by @option{-gnatN}) to inline a particular call. There are
3435 many reasons for not being able to inline a call, including most
3436 commonly that the call is too complex to inline.
3437 This warning can also be turned on using @option{-gnatwa}.
3438
3439 @item -gnatwP (suppress warnings on ineffective pragma Inlines)
3440 @cindex @option{-gnatwP} (@code{gcc})
3441 This switch suppresses warnings on ineffective pragma Inlines. If the
3442 inlining mechanism cannot inline a call, it will simply ignore the
3443 request silently.
3444
3445 @item -gnatwr (activate warnings on redundant constructs)
3446 @cindex @option{-gnatwr} (@code{gcc})
3447 This switch activates warnings for redundant constructs. The following
3448 is the current list of constructs regarded as redundant:
3449 This warning can also be turned on using @option{-gnatwa}.
3450
3451 @itemize @bullet
3452 @item
3453 Assignment of an item to itself.
3454 @item
3455 Type conversion that converts an expression to its own type.
3456 @item
3457 Use of the attribute @code{Base} where @code{typ'Base} is the same
3458 as @code{typ}.
3459 @item
3460 Use of pragma @code{Pack} when all components are placed by a record
3461 representation clause.
3462 @end itemize
3463
3464 @item -gnatwR (suppress warnings on redundant constructs)
3465 @cindex @option{-gnatwR} (@code{gcc})
3466 This switch suppresses warnings for redundant constructs.
3467
3468 @item -gnatws (suppress all warnings)
3469 @cindex @option{-gnatws} (@code{gcc})
3470 This switch completely suppresses the
3471 output of all warning messages from the GNAT front end.
3472 Note that it does not suppress warnings from the @code{gcc} back end.
3473 To suppress these back end warnings as well, use the switch @code{-w}
3474 in addition to @option{-gnatws}.
3475
3476 @item -gnatwu (activate warnings on unused entities)
3477 @cindex @option{-gnatwu} (@code{gcc})
3478 This switch activates warnings to be generated for entities that
3479 are defined but not referenced, and for units that are @code{with}'ed
3480 and not
3481 referenced. In the case of packages, a warning is also generated if
3482 no entities in the package are referenced. This means that if the package
3483 is referenced but the only references are in @code{use}
3484 clauses or @code{renames}
3485 declarations, a warning is still generated. A warning is also generated
3486 for a generic package that is @code{with}'ed but never instantiated.
3487 In the case where a package or subprogram body is compiled, and there
3488 is a @code{with} on the corresponding spec
3489 that is only referenced in the body,
3490 a warning is also generated, noting that the
3491 @code{with} can be moved to the body. The default is that
3492 such warnings are not generated.
3493 This switch also activates warnings on unreferenced formals
3494 (it is includes the effect of @option{-gnatwf}).
3495 This warning can also be turned on using @option{-gnatwa}.
3496
3497 @item -gnatwU (suppress warnings on unused entities)
3498 @cindex @option{-gnatwU} (@code{gcc})
3499 This switch suppresses warnings for unused entities and packages.
3500 It also turns off warnings on unreferenced formals (and thus includes
3501 the effect of @option{-gnatwF}).
3502
3503 @noindent
3504 A string of warning parameters can be used in the same parameter. For example:
3505
3506 @smallexample
3507 -gnatwaLe
3508 @end smallexample
3509
3510 @noindent
3511 Would turn on all optional warnings except for elaboration pragma warnings,
3512 and also specify that warnings should be treated as errors.
3513
3514 @item -w
3515 @cindex @code{-w}
3516 This switch suppresses warnings from the @code{gcc} backend. It may be
3517 used in conjunction with @option{-gnatws} to ensure that all warnings
3518 are suppressed during the entire compilation process.
3519
3520 @end table
3521
3522 @node Debugging and Assertion Control
3523 @subsection Debugging and Assertion Control
3524
3525 @table @code
3526 @item -gnata
3527 @cindex @option{-gnata} (@code{gcc})
3528 @findex Assert
3529 @findex Debug
3530 @cindex Assertions
3531
3532 @noindent
3533 The pragmas @code{Assert} and @code{Debug} normally have no effect and
3534 are ignored. This switch, where @samp{a} stands for assert, causes
3535 @code{Assert} and @code{Debug} pragmas to be activated.
3536
3537 The pragmas have the form:
3538
3539 @smallexample
3540 @group
3541 @cartouche
3542    @b{pragma} Assert (@var{Boolean-expression} [,
3543                       @var{static-string-expression}])
3544    @b{pragma} Debug (@var{procedure call})
3545 @end cartouche
3546 @end group
3547 @end smallexample
3548
3549 @noindent
3550 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
3551 If the result is @code{True}, the pragma has no effect (other than
3552 possible side effects from evaluating the expression). If the result is
3553 @code{False}, the exception @code{Assert_Failure} declared in the package
3554 @code{System.Assertions} is
3555 raised (passing @var{static-string-expression}, if present, as the
3556 message associated with the exception). If no string expression is
3557 given the default is a string giving the file name and line number
3558 of the pragma.
3559
3560 The @code{Debug} pragma causes @var{procedure} to be called. Note that
3561 @code{pragma Debug} may appear within a declaration sequence, allowing
3562 debugging procedures to be called between declarations.
3563
3564 @end table
3565
3566 @node Validity Checking
3567 @subsection Validity Checking
3568 @findex Validity Checking
3569
3570 @noindent
3571 The Ada 95 Reference Manual has specific requirements for checking
3572 for invalid values. In particular, RM 13.9.1 requires that the
3573 evaluation of invalid values (for example from unchecked conversions),
3574 not result in erroneous execution. In GNAT, the result of such an
3575 evaluation in normal default mode is to either use the value
3576 unmodified, or to raise Constraint_Error in those cases where use
3577 of the unmodified value would cause erroneous execution. The cases
3578 where unmodified values might lead to erroneous execution are case
3579 statements (where a wild jump might result from an invalid value),
3580 and subscripts on the left hand side (where memory corruption could
3581 occur as a result of an invalid value).
3582
3583 The @option{-gnatVx} switch allows more control over the validity checking
3584 mode. The @code{x} argument here is a string of letters which control which
3585 validity checks are performed in addition to the default checks described
3586 above.
3587
3588 @itemize @bullet
3589 @item
3590 @option{-gnatVc} Validity checks for copies
3591
3592 The right hand side of assignments, and the initializing values of
3593 object declarations are validity checked.
3594
3595 @item
3596 @option{-gnatVd} Default (RM) validity checks
3597
3598 Some validity checks are done by default following normal Ada semantics
3599 (RM 13.9.1 (9-11)).
3600 A check is done in case statements that the expression is within the range
3601 of the subtype. If it is not, Constraint_Error is raised.
3602 For assignments to array components, a check is done that the expression used
3603 as index is within the range. If it is not, Constraint_Error is raised.
3604 Both these validity checks may be turned off using switch @option{-gnatVD}.
3605 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
3606 switch @option{-gnatVd} will leave the checks turned on.
3607 Switch @option{-gnatVD} should be used only if you are sure that all such
3608 expressions have valid values. If you use this switch and invalid values
3609 are present, then the program is erroneous, and wild jumps or memory
3610 overwriting may occur.
3611
3612 @item
3613 @option{-gnatVi} Validity checks for @code{in} mode parameters
3614
3615 Arguments for parameters of mode @code{in} are validity checked in function
3616 and procedure calls at the point of call.
3617
3618 @item
3619 @option{-gnatVm} Validity checks for @code{in out} mode parameters
3620
3621 Arguments for parameters of mode @code{in out} are validity checked in
3622 procedure calls at the point of call. The @code{'m'} here stands for
3623 modify, since this concerns parameters that can be modified by the call.
3624 Note that there is no specific option to test @code{out} parameters,
3625 but any reference within the subprogram will be tested in the usual
3626 manner, and if an invalid value is copied back, any reference to it
3627 will be subject to validity checking.
3628
3629 @item
3630 @option{-gnatVo} Validity checks for operator and attribute operands
3631
3632 Arguments for predefined operators and attributes are validity checked.
3633 This includes all operators in package @code{Standard},
3634 the shift operators defined as intrinsic in package @code{Interfaces}
3635 and operands for attributes such as @code{Pos}.
3636
3637 @item
3638 @option{-gnatVr} Validity checks for function returns
3639
3640 The expression in @code{return} statements in functions is validity
3641 checked.
3642
3643 @item
3644 @option{-gnatVs} Validity checks for subscripts
3645
3646 All subscripts expressions are checked for validity, whether they appear
3647 on the right side or left side (in default mode only left side subscripts
3648 are validity checked).
3649
3650 @item
3651 @option{-gnatVt} Validity checks for tests
3652
3653 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
3654 statements are checked, as well as guard expressions in entry calls.
3655
3656 @item
3657 @option{-gnatVf} Validity checks for floating-point values
3658
3659 In the absence of this switch, validity checking occurs only for discrete
3660 values. If @option{-gnatVf} is specified, then validity checking also applies
3661 for floating-point values, and NaN's and infinities are considered invalid,
3662 as well as out of range values for constrained types. Note that this means
3663 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
3664 in which floating-point values are checked depends on the setting of other
3665 options. For example @option{-gnatVif} or @option{-gnatVfi} (the order does
3666 not matter) specifies that floating-point parameters of mode @code{in} should
3667 be validity checked.
3668
3669 @item
3670 @option{-gnatVa} All validity checks
3671
3672 All the above validity checks are turned on. That is @option{-gnatVa} is
3673 equivalent to @code{gnatVcdfimorst}.
3674
3675 @item
3676 @option{-gnatVn} No validity checks
3677
3678 This switch turns off all validity checking, including the default checking
3679 for case statements and left hand side subscripts. Note that the use of
3680 the switch @option{-gnatp} supresses all run-time checks, including
3681 validity checks, and thus implies @option{-gnatVn}.
3682
3683 @end itemize
3684
3685 The @option{-gnatV} switch may be followed by a string of letters to turn on
3686 a series of validity checking options. For example, @option{-gnatVcr} specifies
3687 that in addition to the default validity checking, copies and function
3688 return expressions be validity checked. In order to make it easier to specify
3689 a set of options, the upper case letters @code{CDFIMORST} may be used to turn
3690 off the corresponding lower case option, so for example @option{-gnatVaM} turns
3691 on all validity checking options except for checking of @code{in out}
3692 procedure arguments.
3693
3694 The specification of additional validity checking generates extra code (and
3695 in the case of @option{-gnatva} the code expansion can be substantial. However,
3696 these additional checks can be very useful in smoking out cases of
3697 uninitialized variables, incorrect use of unchecked conversion, and other
3698 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
3699 is useful in conjunction with the extra validity checking, since this
3700 ensures that wherever possible uninitialized variables have invalid values.
3701
3702 See also the pragma @code{Validity_Checks} which allows modification of
3703 the validity checking mode at the program source level, and also allows for
3704 temporary disabling of validity checks.
3705
3706 @node Style Checking
3707 @subsection Style Checking
3708 @findex Style checking
3709
3710 @noindent
3711 The -gnaty@var{x} switch causes the compiler to
3712 enforce specified style rules. A limited set of style rules has been used
3713 in writing the GNAT sources themselves. This switch allows user programs
3714 to activate all or some of these checks. If the source program fails a
3715 specified style check, an appropriate warning message is given, preceded by
3716 the character sequence "(style)".
3717 The string @var{x} is a sequence of letters or digits
3718 indicating the particular style
3719 checks to be performed. The following checks are defined:
3720
3721 @table @code
3722 @item 1-9 (specify indentation level)
3723 If a digit from 1-9 appears in the string after @option{-gnaty} then proper
3724 indentation is checked, with the digit indicating the indentation level
3725 required. The general style of required indentation is as specified by
3726 the examples in the Ada Reference Manual. Full line comments must be
3727 aligned with the @code{--} starting on a column that is a multiple of
3728 the alignment level.
3729
3730 @item a (check attribute casing)
3731 If the letter a appears in the string after @option{-gnaty} then
3732 attribute names, including the case of keywords such as @code{digits}
3733 used as attributes names, must be written in mixed case, that is, the
3734 initial letter and any letter following an underscore must be uppercase.
3735 All other letters must be lowercase.
3736
3737 @item b (blanks not allowed at statement end)
3738 If the letter b appears in the string after @option{-gnaty} then
3739 trailing blanks are not allowed at the end of statements. The purpose of this
3740 rule, together with h (no horizontal tabs), is to enforce a canonical format
3741 for the use of blanks to separate source tokens.
3742
3743 @item c (check comments)
3744 If the letter c appears in the string after @option{-gnaty} then
3745 comments must meet the following set of rules:
3746
3747 @itemize @bullet
3748
3749 @item
3750 The "--" that starts the column must either start in column one, or else
3751 at least one blank must precede this sequence.
3752
3753 @item
3754 Comments that follow other tokens on a line must have at least one blank
3755 following the "--" at the start of the comment.
3756
3757 @item
3758 Full line comments must have two blanks following the "--" that starts
3759 the comment, with the following exceptions.
3760
3761 @item
3762 A line consisting only of the "--" characters, possibly preceded by blanks
3763 is permitted.
3764
3765 @item
3766 A comment starting with "--x" where x is a special character is permitted.
3767 This alows proper processing of the output generated by specialized tools
3768 including @code{gnatprep} (where --! is used) and the SPARK annnotation
3769 language (where --# is used). For the purposes of this rule, a special
3770 character is defined as being in one of the ASCII ranges
3771 16#21#..16#2F# or 16#3A#..16#3F#.
3772
3773 @item
3774 A line consisting entirely of minus signs, possibly preceded by blanks, is
3775 permitted. This allows the construction of box comments where lines of minus
3776 signs are used to form the top and bottom of the box.
3777
3778 @item
3779 If a comment starts and ends with "--" is permitted as long as at least
3780 one blank follows the initial "--". Together with the preceding rule,
3781 this allows the construction of box comments, as shown in the following
3782 example:
3783 @smallexample
3784 ---------------------------
3785 -- This is a box comment --
3786 -- with two text lines.  --
3787 ---------------------------
3788 @end smallexample
3789 @end itemize
3790
3791 @item e (check end/exit labels)
3792 If the letter e appears in the string after @option{-gnaty} then
3793 optional labels on @code{end} statements ending subprograms and on
3794 @code{exit} statements exiting named loops, are required to be present.
3795
3796 @item f (no form feeds or vertical tabs)
3797 If the letter f appears in the string after @option{-gnaty} then
3798 neither form feeds nor vertical tab characters are not permitted
3799 in the source text.
3800
3801 @item h (no horizontal tabs)
3802 If the letter h appears in the string after @option{-gnaty} then
3803 horizontal tab characters are not permitted in the source text.
3804 Together with the b (no blanks at end of line) check, this
3805 enforces a canonical form for the use of blanks to separate
3806 source tokens.
3807
3808 @item i (check if-then layout)
3809 If the letter i appears in the string after @option{-gnaty},
3810 then the keyword @code{then} must appear either on the same
3811 line as corresponding @code{if}, or on a line on its own, lined
3812 up under the @code{if} with at least one non-blank line in between
3813 containing all or part of the condition to be tested.
3814
3815 @item k (check keyword casing)
3816 If the letter k appears in the string after @option{-gnaty} then
3817 all keywords must be in lower case (with the exception of keywords
3818 such as @code{digits} used as attribute names to which this check
3819 does not apply).
3820
3821 @item l (check layout)
3822 If the letter l appears in the string after @option{-gnaty} then
3823 layout of statement and declaration constructs must follow the
3824 recommendations in the Ada Reference Manual, as indicated by the
3825 form of the syntax rules. For example an @code{else} keyword must
3826 be lined up with the corresponding @code{if} keyword.
3827
3828 There are two respects in which the style rule enforced by this check
3829 option are more liberal than those in the Ada Reference Manual. First
3830 in the case of record declarations, it is permissible to put the
3831 @code{record} keyword on the same line as the @code{type} keyword, and
3832 then the @code{end} in @code{end record} must line up under @code{type}.
3833 For example, either of the following two layouts is acceptable:
3834
3835 @smallexample
3836 @group
3837 @cartouche
3838 @b{type} q @b{is record}
3839    a : integer;
3840    b : integer;
3841 @b{end record};
3842
3843 @b{type} q @b{is}
3844    @b{record}
3845       a : integer;
3846       b : integer;
3847    @b{end record};
3848 @end cartouche
3849 @end group
3850 @end smallexample
3851
3852 @noindent
3853 Second, in the case of a block statement, a permitted alternative
3854 is to put the block label on the same line as the @code{declare} or
3855 @code{begin} keyword, and then line the @code{end} keyword up under
3856 the block label. For example both the following are permitted:
3857
3858 @smallexample
3859 @group
3860 @cartouche
3861 Block : @b{declare}
3862    A : Integer := 3;
3863 @b{begin}
3864    Proc (A, A);
3865 @b{end} Block;
3866
3867 Block :
3868    @b{declare}
3869       A : Integer := 3;
3870    @b{begin}
3871       Proc (A, A);
3872    @b{end} Block;
3873 @end cartouche
3874 @end group
3875 @end smallexample
3876
3877 @noindent
3878 The same alternative format is allowed for loops. For example, both of
3879 the following are permitted:
3880
3881 @smallexample
3882 @group
3883 @cartouche
3884 Clear : @b{while} J < 10 @b{loop}
3885    A (J) := 0;
3886 @b{end loop} Clear;
3887
3888 Clear :
3889    @b{while} J < 10 @b{loop}
3890       A (J) := 0;
3891    @b{end loop} Clear;
3892 @end cartouche
3893 @end group
3894 @end smallexample
3895
3896 @item m (check maximum line length)
3897 If the letter m appears in the string after @option{-gnaty}
3898 then the length of source lines must not exceed 79 characters, including
3899 any trailing blanks. The value of 79 allows convenient display on an
3900 80 character wide device or window, allowing for possible special
3901 treatment of 80 character lines.
3902
3903 @item Mnnn (set maximum line length)
3904 If the sequence Mnnn, where nnn is a decimal number, appears in
3905 the string after @option{-gnaty} then the length of lines must not exceed the
3906 given value.
3907
3908 @item n (check casing of entities in Standard)
3909 If the letter n appears in the string
3910 after @option{-gnaty} then any identifier from Standard must be cased
3911 to match the presentation in the Ada Reference Manual (for example,
3912 @code{Integer} and @code{ASCII.NUL}).
3913
3914 @item o (check order of subprogram bodies)
3915 If the letter o appears in the string
3916 after @option{-gnaty} then all subprogram bodies in a given scope
3917 (e.g. a package body) must be in alphabetical order. The ordering
3918 rule uses normal Ada rules for comparing strings, ignoring casing
3919 of letters, except that if there is a trailing numeric suffix, then
3920 the value of this suffix is used in the ordering (e.g. Junk2 comes
3921 before Junk10).
3922
3923 @item p (check pragma casing)
3924 If the letter p appears in the string after @option{-gnaty} then
3925 pragma names must be written in mixed case, that is, the
3926 initial letter and any letter following an underscore must be uppercase.
3927 All other letters must be lowercase.
3928
3929 @item r (check references)
3930 If the letter r appears in the string after @option{-gnaty}
3931 then all identifier references must be cased in the same way as the
3932 corresponding declaration. No specific casing style is imposed on
3933 identifiers. The only requirement is for consistency of references
3934 with declarations.
3935
3936 @item s (check separate specs)
3937 If the letter s appears in the string after @option{-gnaty} then
3938 separate declarations ("specs") are required for subprograms (a
3939 body is not allowed to serve as its own declaration). The only
3940 exception is that parameterless library level procedures are
3941 not required to have a separate declaration. This exception covers
3942 the most frequent form of main program procedures.
3943
3944 @item t (check token spacing)
3945 If the letter t appears in the string after @option{-gnaty} then
3946 the following token spacing rules are enforced:
3947
3948 @itemize @bullet
3949
3950 @item
3951 The keywords @code{abs} and @code{not} must be followed by a space.
3952
3953 @item
3954 The token @code{=>} must be surrounded by spaces.
3955
3956 @item
3957 The token @code{<>} must be preceded by a space or a left parenthesis.
3958
3959 @item
3960 Binary operators other than @code{**} must be surrounded by spaces.
3961 There is no restriction on the layout of the @code{**} binary operator.
3962
3963 @item
3964 Colon must be surrounded by spaces.
3965
3966 @item
3967 Colon-equal (assignment) must be surrounded by spaces.
3968
3969 @item
3970 Comma must be the first non-blank character on the line, or be
3971 immediately preceded by a non-blank character, and must be followed
3972 by a space.
3973
3974 @item
3975 If the token preceding a left paren ends with a letter or digit, then
3976 a space must separate the two tokens.
3977
3978 @item
3979 A right parenthesis must either be the first non-blank character on
3980 a line, or it must be preceded by a non-blank character.
3981
3982 @item
3983 A semicolon must not be preceded by a space, and must not be followed by
3984 a non-blank character.
3985
3986 @item
3987 A unary plus or minus may not be followed by a space.
3988
3989 @item
3990 A vertical bar must be surrounded by spaces.
3991 @end itemize
3992
3993 @noindent
3994 In the above rules, appearing in column one is always permitted, that is,
3995 counts as meeting either a requirement for a required preceding space,
3996 or as meeting a requirement for no preceding space.
3997
3998 Appearing at the end of a line is also always permitted, that is, counts
3999 as meeting either a requirement for a following space, or as meeting
4000 a requirement for no following space.
4001
4002 @end table
4003
4004 @noindent
4005 If any of these style rules is violated, a message is generated giving
4006 details on the violation. The initial characters of such messages are
4007 always "(style)". Note that these messages are treated as warning
4008 messages, so they normally do not prevent the generation of an object
4009 file. The @option{-gnatwe} switch can be used to treat warning messages,
4010 including style messages, as fatal errors.
4011
4012 @noindent
4013 The switch
4014 @option{-gnaty} on its own (that is not followed by any letters or digits),
4015 is equivalent to @code{gnaty3abcefhiklmprst}, that is all checking
4016 options are enabled with
4017 the exception of -gnatyo,
4018 with an indentation level of 3. This is the standard
4019 checking option that is used for the GNAT sources.
4020
4021 @node Run-Time Checks
4022 @subsection Run-Time Checks
4023 @cindex Division by zero
4024 @cindex Access before elaboration
4025 @cindex Checks, division by zero
4026 @cindex Checks, access before elaboration
4027
4028 @noindent
4029 If you compile with the default options, GNAT will insert many run-time
4030 checks into the compiled code, including code that performs range
4031 checking against constraints, but not arithmetic overflow checking for
4032 integer operations (including division by zero) or checks for access
4033 before elaboration on subprogram calls. All other run-time checks, as
4034 required by the Ada 95 Reference Manual, are generated by default.
4035 The following @code{gcc} switches refine this default behavior:
4036
4037 @table @code
4038 @item -gnatp
4039 @cindex @option{-gnatp} (@code{gcc})
4040 @cindex Suppressing checks
4041 @cindex Checks, suppressing
4042 @findex Suppress
4043 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
4044 had been present in the source. Validity checks are also suppressed (in
4045 other words @option{-gnatp} also implies @option{-gnatVn}.
4046 Use this switch to improve the performance
4047 of the code at the expense of safety in the presence of invalid data or
4048 program bugs.
4049
4050 @item -gnato
4051 @cindex @option{-gnato} (@code{gcc})
4052 @cindex Overflow checks
4053 @cindex Check, overflow
4054 Enables overflow checking for integer operations.
4055 This causes GNAT to generate slower and larger executable
4056 programs by adding code to check for overflow (resulting in raising
4057 @code{Constraint_Error} as required by standard Ada
4058 semantics). These overflow checks correspond to situations in which
4059 the true value of the result of an operation may be outside the base
4060 range of the result type. The following example shows the distinction:
4061
4062 @smallexample
4063 X1 : Integer := Integer'Last;
4064 X2 : Integer range 1 .. 5 := 5;
4065 ...
4066 X1 := X1 + 1;   -- @option{-gnato} required to catch the Constraint_Error
4067 X2 := X2 + 1;   -- range check, @option{-gnato} has no effect here
4068 @end smallexample
4069
4070 @noindent
4071 Here the first addition results in a value that is outside the base range
4072 of Integer, and hence requires an overflow check for detection of the
4073 constraint error. The second increment operation results in a violation
4074 of the explicit range constraint, and such range checks are always
4075 performed. Basically the compiler can assume that in the absence of
4076 the @option{-gnato} switch that any value of type @code{xxx} is
4077 in range of the base type of @code{xxx}.
4078
4079 @findex Machine_Overflows
4080 Note that the @option{-gnato} switch does not affect the code generated
4081 for any floating-point operations; it applies only to integer
4082 semantics).
4083 For floating-point, GNAT has the @code{Machine_Overflows}
4084 attribute set to @code{False} and the normal mode of operation is to
4085 generate IEEE NaN and infinite values on overflow or invalid operations
4086 (such as dividing 0.0 by 0.0).
4087
4088 The reason that we distinguish overflow checking from other kinds of
4089 range constraint checking is that a failure of an overflow check can
4090 generate an incorrect value, but cannot cause erroneous behavior. This
4091 is unlike the situation with a constraint check on an array subscript,
4092 where failure to perform the check can result in random memory description,
4093 or the range check on a case statement, where failure to perform the check
4094 can cause a wild jump.
4095
4096 Note again that @option{-gnato} is off by default, so overflow checking is
4097 not performed in default mode. This means that out of the box, with the
4098 default settings, GNAT does not do all the checks expected from the
4099 language description in the Ada Reference Manual. If you want all constraint
4100 checks to be performed, as described in this Manual, then you must
4101 explicitly use the -gnato switch either on the @code{gnatmake} or
4102 @code{gcc} command.
4103
4104 @item -gnatE
4105 @cindex @option{-gnatE} (@code{gcc})
4106 @cindex Elaboration checks
4107 @cindex Check, elaboration
4108 Enables dynamic checks for access-before-elaboration
4109 on subprogram calls and generic instantiations.
4110 For full details of the effect and use of this switch,
4111 @xref{Compiling Using gcc}.
4112 @end table
4113
4114 @findex Unsuppress
4115 @noindent
4116 The setting of these switches only controls the default setting of the
4117 checks. You may modify them using either @code{Suppress} (to remove
4118 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
4119 the program source.
4120
4121 @node Stack Overflow Checking
4122 @subsection Stack Overflow Checking
4123 @cindex Stack Overflow Checking
4124 @cindex -fstack-check
4125
4126 @noindent
4127 For most operating systems, @code{gcc} does not perform stack overflow
4128 checking by default. This means that if the main environment task or
4129 some other task exceeds the available stack space, then unpredictable
4130 behavior will occur.
4131
4132 To activate stack checking, compile all units with the gcc option
4133 @code{-fstack-check}. For example:
4134
4135 @smallexample
4136 gcc -c -fstack-check package1.adb
4137 @end smallexample
4138
4139 @noindent
4140 Units compiled with this option will generate extra instructions to check
4141 that any use of the stack (for procedure calls or for declaring local
4142 variables in declare blocks) do not exceed the available stack space.
4143 If the space is exceeded, then a @code{Storage_Error} exception is raised.
4144
4145 For declared tasks, the stack size is always controlled by the size
4146 given in an applicable @code{Storage_Size} pragma (or is set to
4147 the default size if no pragma is used.
4148
4149 For the environment task, the stack size depends on
4150 system defaults and is unknown to the compiler. The stack
4151 may even dynamically grow on some systems, precluding the
4152 normal Ada semantics for stack overflow. In the worst case,
4153 unbounded stack usage, causes unbounded stack expansion
4154 resulting in the system running out of virtual memory.
4155
4156 The stack checking may still work correctly if a fixed
4157 size stack is allocated, but this cannot be guaranteed.
4158 To ensure that a clean exception is signalled for stack
4159 overflow, set the environment variable
4160 @code{GNAT_STACK_LIMIT} to indicate the maximum
4161 stack area that can be used, as in:
4162 @cindex GNAT_STACK_LIMIT
4163
4164 @smallexample
4165 SET GNAT_STACK_LIMIT 1600
4166 @end smallexample
4167
4168 @noindent
4169 The limit is given in kilobytes, so the above declaration would
4170 set the stack limit of the environment task to 1.6 megabytes.
4171 Note that the only purpose of this usage is to limit the amount
4172 of stack used by the environment task. If it is necessary to
4173 increase the amount of stack for the environment task, then this
4174 is an operating systems issue, and must be addressed with the
4175 appropriate operating systems commands.
4176
4177 @node Run-Time Control
4178 @subsection Run-Time Control
4179
4180 @table @code
4181 @item -gnatT nnn
4182 @cindex @option{-gnatT} (@code{gcc})
4183 @cindex Time Slicing
4184
4185 @noindent
4186 The @code{gnatT} switch can be used to specify the time-slicing value
4187 to be used for task switching between equal priority tasks. The value
4188 @code{nnn} is given in microseconds as a decimal integer.
4189
4190 Setting the time-slicing value is only effective if the underlying thread
4191 control system can accommodate time slicing. Check the documentation of
4192 your operating system for details. Note that the time-slicing value can
4193 also be set by use of pragma @code{Time_Slice} or by use of the
4194 @code{t} switch in the gnatbind step. The pragma overrides a command
4195 line argument if both are present, and the @code{t} switch for gnatbind
4196 overrides both the pragma and the @code{gcc} command line switch.
4197 @end table
4198
4199 @node Using gcc for Syntax Checking
4200 @subsection Using @code{gcc} for Syntax Checking
4201 @table @code
4202 @item -gnats
4203 @cindex @option{-gnats} (@code{gcc})
4204
4205 @noindent
4206 The @code{s} stands for syntax.
4207
4208 Run GNAT in syntax checking only mode. For
4209 example, the command
4210
4211 @smallexample
4212 $ gcc -c -gnats x.adb
4213 @end smallexample
4214
4215 @noindent
4216 compiles file @file{x.adb} in syntax-check-only mode. You can check a
4217 series of files in a single command
4218 , and can use wild cards to specify such a group of files.
4219 Note that you must specify the @code{-c} (compile
4220 only) flag in addition to the @option{-gnats} flag.
4221 .
4222
4223 You may use other switches in conjunction with @option{-gnats}. In
4224 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
4225 format of any generated error messages.
4226
4227 The output is simply the error messages, if any. No object file or ALI
4228 file is generated by a syntax-only compilation. Also, no units other
4229 than the one specified are accessed. For example, if a unit @code{X}
4230 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
4231 check only mode does not access the source file containing unit
4232 @code{Y}.
4233
4234 @cindex Multiple units, syntax checking
4235 Normally, GNAT allows only a single unit in a source file. However, this
4236 restriction does not apply in syntax-check-only mode, and it is possible
4237 to check a file containing multiple compilation units concatenated
4238 together. This is primarily used by the @code{gnatchop} utility
4239 (@pxref{Renaming Files Using gnatchop}).
4240 @end table
4241
4242 @node Using gcc for Semantic Checking
4243 @subsection Using @code{gcc} for Semantic Checking
4244 @table @code
4245 @item -gnatc
4246 @cindex @option{-gnatc} (@code{gcc})
4247
4248 @noindent
4249 The @code{c} stands for check.
4250 Causes the compiler to operate in semantic check mode,
4251 with full checking for all illegalities specified in the
4252 Ada 95 Reference Manual, but without generation of any object code
4253 (no object file is generated).
4254
4255 Because dependent files must be accessed, you must follow the GNAT
4256 semantic restrictions on file structuring to operate in this mode:
4257
4258 @itemize @bullet
4259 @item
4260 The needed source files must be accessible
4261 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4262
4263 @item
4264 Each file must contain only one compilation unit.
4265
4266 @item
4267 The file name and unit name must match (@pxref{File Naming Rules}).
4268 @end itemize
4269
4270 The output consists of error messages as appropriate. No object file is
4271 generated. An @file{ALI} file is generated for use in the context of
4272 cross-reference tools, but this file is marked as not being suitable
4273 for binding (since no object file is generated).
4274 The checking corresponds exactly to the notion of
4275 legality in the Ada 95 Reference Manual.
4276
4277 Any unit can be compiled in semantics-checking-only mode, including
4278 units that would not normally be compiled (subunits,
4279 and specifications where a separate body is present).
4280 @end table
4281
4282 @node Compiling Ada 83 Programs
4283 @subsection Compiling Ada 83 Programs
4284 @table @code
4285 @cindex Ada 83 compatibility
4286 @item -gnat83
4287 @cindex @option{-gnat83} (@code{gcc})
4288 @cindex ACVC, Ada 83 tests
4289
4290 @noindent
4291 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
4292 specify that an Ada 83 program is to be compiled in Ada83 mode. If you specify
4293 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
4294 where this can be done easily.
4295 It is not possible to guarantee this switch does a perfect
4296 job; for example, some subtle tests, such as are
4297 found in earlier ACVC tests (that have been removed from the ACVC suite for Ada
4298 95), may not compile correctly. However, for most purposes, using
4299 this switch should help to ensure that programs that compile correctly
4300 under the @option{-gnat83} switch can be ported easily to an Ada 83
4301 compiler. This is the main use of the switch.
4302
4303 With few exceptions (most notably the need to use @code{<>} on
4304 @cindex Generic formal parameters
4305 unconstrained generic formal parameters, the use of the new Ada 95
4306 keywords, and the use of packages
4307 with optional bodies), it is not necessary to use the
4308 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
4309 exceptions, Ada 95 is upwardly compatible with Ada 83. This
4310 means that a correct Ada 83 program is usually also a correct Ada 95
4311 program.
4312
4313 @end table
4314
4315 @node Character Set Control
4316 @subsection Character Set Control
4317 @table @code
4318 @item -gnati@var{c}
4319 @cindex @code{-gnati} (@code{gcc})
4320
4321 @noindent
4322 Normally GNAT recognizes the Latin-1 character set in source program
4323 identifiers, as described in the Ada 95 Reference Manual.
4324 This switch causes
4325 GNAT to recognize alternate character sets in identifiers. @var{c} is a
4326 single character  indicating the character set, as follows:
4327
4328 @table @code
4329 @item 1
4330 Latin-1 identifiers
4331
4332 @item 2
4333 Latin-2 letters allowed in identifiers
4334
4335 @item 3
4336 Latin-3 letters allowed in identifiers
4337
4338 @item 4
4339 Latin-4 letters allowed in identifiers
4340
4341 @item 5
4342 Latin-5 (Cyrillic) letters allowed in identifiers
4343
4344 @item 9
4345 Latin-9 letters allowed in identifiers
4346
4347 @item p
4348 IBM PC letters (code page 437) allowed in identifiers
4349
4350 @item 8
4351 IBM PC letters (code page 850) allowed in identifiers
4352
4353 @item f
4354 Full upper-half codes allowed in identifiers
4355
4356 @item n
4357 No upper-half codes allowed in identifiers
4358
4359 @item w
4360 Wide-character codes (that is, codes greater than 255)
4361 allowed in identifiers
4362 @end table
4363
4364 @xref{Foreign Language Representation}, for full details on the
4365 implementation of these character sets.
4366
4367 @item -gnatW@var{e}
4368 @cindex @code{-gnatW} (@code{gcc})
4369 Specify the method of encoding for wide characters.
4370 @var{e} is one of the following:
4371
4372 @table @code
4373
4374 @item h
4375 Hex encoding (brackets coding also recognized)
4376
4377 @item u
4378 Upper half encoding (brackets encoding also recognized)
4379
4380 @item s
4381 Shift/JIS encoding (brackets encoding also recognized)
4382
4383 @item e
4384 EUC encoding (brackets encoding also recognized)
4385
4386 @item 8
4387 UTF-8 encoding (brackets encoding also recognized)
4388
4389 @item b
4390 Brackets encoding only (default value)
4391 @end table
4392 For full details on the these encoding
4393 methods see @xref{Wide Character Encodings}.
4394 Note that brackets coding is always accepted, even if one of the other
4395 options is specified, so for example @option{-gnatW8} specifies that both
4396 brackets and @code{UTF-8} encodings will be recognized. The units that are
4397 with'ed directly or indirectly will be scanned using the specified
4398 representation scheme, and so if one of the non-brackets scheme is
4399 used, it must be used consistently throughout the program. However,
4400 since brackets encoding is always recognized, it may be conveniently
4401 used in standard libraries, allowing these libraries to be used with
4402 any of the available coding schemes.
4403 scheme. If no @option{-gnatW?} parameter is present, then the default
4404 representation is Brackets encoding only.
4405
4406 Note that the wide character representation that is specified (explicitly
4407 or by default) for the main program also acts as the default encoding used
4408 for Wide_Text_IO files if not specifically overridden by a WCEM form
4409 parameter.
4410
4411 @end table
4412 @node File Naming Control
4413 @subsection File Naming Control
4414
4415 @table @code
4416 @item -gnatk@var{n}
4417 @cindex @option{-gnatk} (@code{gcc})
4418 Activates file name "krunching". @var{n}, a decimal integer in the range
4419 1-999, indicates the maximum allowable length of a file name (not
4420 including the @file{.ads} or @file{.adb} extension). The default is not
4421 to enable file name krunching.
4422
4423 For the source file naming rules, @xref{File Naming Rules}.
4424 @end table
4425
4426 @node Subprogram Inlining Control
4427 @subsection Subprogram Inlining Control
4428
4429 @table @code
4430 @item -gnatn
4431 @cindex @option{-gnatn} (@code{gcc})
4432 The @code{n} here is intended to suggest the first syllable of the
4433 word "inline".
4434 GNAT recognizes and processes @code{Inline} pragmas. However, for the
4435 inlining to actually occur, optimization must be enabled. To enable
4436 inlining across unit boundaries, this is, inlining a call in one unit of
4437 a subprogram declared in a @code{with}'ed unit, you must also specify
4438 this switch.
4439 In the absence of this switch, GNAT does not attempt
4440 inlining across units and does not need to access the bodies of
4441 subprograms for which @code{pragma Inline} is specified if they are not
4442 in the current unit.
4443
4444 If you specify this switch the compiler will access these bodies,
4445 creating an extra source dependency for the resulting object file, and
4446 where possible, the call will be inlined.
4447 For further details on when inlining is possible
4448 see @xref{Inlining of Subprograms}.
4449
4450 @item -gnatN
4451 @cindex @option{-gnatN} (@code{gcc})
4452 The front end inlining activated by this switch is generally more extensive,
4453 and quite often more effective than the standard @option{-gnatn} inlining mode.
4454 It will also generate additional dependencies.
4455
4456 @end table
4457
4458 @node Auxiliary Output Control
4459 @subsection Auxiliary Output Control
4460
4461 @table @code
4462 @item -gnatt
4463 @cindex @option{-gnatt} (@code{gcc})
4464 @cindex Writing internal trees
4465 @cindex Internal trees, writing to file
4466 Causes GNAT to write the internal tree for a unit to a file (with the
4467 extension @file{.adt}.
4468 This not normally required, but is used by separate analysis tools.
4469 Typically
4470 these tools do the necessary compilations automatically, so you should
4471 not have to specify this switch in normal operation.
4472
4473 @item -gnatu
4474 @cindex @option{-gnatu} (@code{gcc})
4475 Print a list of units required by this compilation on @file{stdout}.
4476 The listing includes all units on which the unit being compiled depends
4477 either directly or indirectly.
4478
4479 @item -pass-exit-codes
4480 @cindex @code{-pass-exit-codes} (@code{gcc})
4481 If this switch is not used, the exit code returned by @code{gcc} when
4482 compiling multiple files indicates whether all source files have
4483 been successfully used to generate object files or not.
4484
4485 When @code{-pass-exit-codes} is used, @code{gcc} exits with an extended
4486 exit status and allows an integrated development environment to better
4487 react to a compilation failure. Those exit status are:
4488
4489 @table @asis
4490 @item 5
4491 There was an error in at least one source file.
4492 @item 3
4493 At least one source file did not generate an object file.
4494 @item 2
4495 The compiler died unexpectedly (internal error for example).
4496 @item 0
4497 An object file has been generated for every source file.
4498 @end table
4499 @end table
4500
4501 @node Debugging Control
4502 @subsection Debugging Control
4503
4504 @table @code
4505 @cindex Debugging options
4506 @item -gnatd@var{x}
4507 Activate internal debugging switches. @var{x} is a letter or digit, or
4508 string of letters or digits, which specifies the type of debugging
4509 outputs desired. Normally these are used only for internal development
4510 or system debugging purposes. You can find full documentation for these
4511 switches in the body of the @code{Debug} unit in the compiler source
4512 file @file{debug.adb}.
4513
4514 @item -gnatG
4515 @cindex @option{-gnatG} (@code{gcc})
4516 This switch causes the compiler to generate auxiliary output containing
4517 a pseudo-source listing of the generated expanded code. Like most Ada
4518 compilers, GNAT works by first transforming the high level Ada code into
4519 lower level constructs. For example, tasking operations are transformed
4520 into calls to the tasking run-time routines. A unique capability of GNAT
4521 is to list this expanded code in a form very close to normal Ada source.
4522 This is very useful in understanding the implications of various Ada
4523 usage on the efficiency of the generated code. There are many cases in
4524 Ada (e.g. the use of controlled types), where simple Ada statements can
4525 generate a lot of run-time code. By using @option{-gnatG} you can identify
4526 these cases, and consider whether it may be desirable to modify the coding
4527 approach to improve efficiency.
4528
4529 The format of the output is very similar to standard Ada source, and is
4530 easily understood by an Ada programmer. The following special syntactic
4531 additions correspond to low level features used in the generated code that
4532 do not have any exact analogies in pure Ada source form. The following
4533 is a partial list of these special constructions. See the specification
4534 of package @code{Sprint} in file @file{sprint.ads} for a full list.
4535
4536 @table @code
4537 @item new @var{xxx} [storage_pool = @var{yyy}]
4538 Shows the storage pool being used for an allocator.
4539
4540 @item at end @var{procedure-name};
4541 Shows the finalization (cleanup) procedure for a scope.
4542
4543 @item (if @var{expr} then @var{expr} else @var{expr})
4544 Conditional expression equivalent to the @code{x?y:z} construction in C.
4545
4546 @item @var{target}^(@var{source})
4547 A conversion with floating-point truncation instead of rounding.
4548
4549 @item @var{target}?(@var{source})
4550 A conversion that bypasses normal Ada semantic checking. In particular
4551 enumeration types and fixed-point types are treated simply as integers.
4552
4553 @item @var{target}?^(@var{source})
4554 Combines the above two cases.
4555
4556 @item @var{x} #/ @var{y}
4557 @itemx @var{x} #mod @var{y}
4558 @itemx @var{x} #* @var{y}
4559 @itemx @var{x} #rem @var{y}
4560 A division or multiplication of fixed-point values which are treated as
4561 integers without any kind of scaling.
4562
4563 @item free @var{expr} [storage_pool = @var{xxx}]
4564 Shows the storage pool associated with a @code{free} statement.
4565
4566 @item freeze @var{typename} [@var{actions}]
4567 Shows the point at which @var{typename} is frozen, with possible
4568 associated actions to be performed at the freeze point.
4569
4570 @item reference @var{itype}
4571 Reference (and hence definition) to internal type @var{itype}.
4572
4573 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
4574 Intrinsic function call.
4575
4576 @item @var{labelname} : label
4577 Declaration of label @var{labelname}.
4578
4579 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
4580 A multiple concatenation (same effect as @var{expr} & @var{expr} &
4581 @var{expr}, but handled more efficiently).
4582
4583 @item [constraint_error]
4584 Raise the @code{Constraint_Error} exception.
4585
4586 @item @var{expression}'reference
4587 A pointer to the result of evaluating @var{expression}.
4588
4589 @item @var{target-type}!(@var{source-expression})
4590 An unchecked conversion of @var{source-expression} to @var{target-type}.
4591
4592 @item [@var{numerator}/@var{denominator}]
4593 Used to represent internal real literals (that) have no exact
4594 representation in base 2-16 (for example, the result of compile time
4595 evaluation of the expression 1.0/27.0).
4596
4597 @item -gnatD
4598 @cindex @option{-gnatD} (@code{gcc})
4599 This switch is used in conjunction with @option{-gnatG} to cause the expanded
4600 source, as described above to be written to files with names
4601 @file{xxx.dg}, where @file{xxx} is the normal file name,
4602 for example, if the source file name is @file{hello.adb},
4603 then a file @file{hello.adb.dg} will be written.
4604 The debugging information generated
4605 by the @code{gcc} @code{-g} switch will refer to the generated
4606 @file{xxx.dg} file. This allows you to do source level debugging using
4607 the generated code which is sometimes useful for complex code, for example
4608 to find out exactly which part of a complex construction raised an
4609 exception. This switch also suppress generation of cross-reference
4610 information (see -gnatx).
4611
4612 @item -gnatC
4613 @cindex @option{-gnatE} (@code{gcc})
4614 In the generated debugging information, and also in the case of long external
4615 names, the compiler uses a compression mechanism if the name is very long.
4616 This compression method uses a checksum, and avoids trouble on some operating
4617 systems which have difficulty with very long names. The @option{-gnatC} switch
4618 forces this compression approach to be used on all external names and names
4619 in the debugging information tables. This reduces the size of the generated
4620 executable, at the expense of making the naming scheme more complex. The
4621 compression only affects the qualification of the name. Thus a name in
4622 the source:
4623
4624 @smallexample
4625 Very_Long_Package.Very_Long_Inner_Package.Var
4626 @end smallexample
4627
4628 @noindent
4629 would normally appear in these tables as:
4630
4631 @smallexample
4632 very_long_package__very_long_inner_package__var
4633 @end smallexample
4634
4635 @noindent
4636 but if the @option{-gnatC} switch is used, then the name appears as
4637
4638 @smallexample
4639 XCb7e0c705__var
4640 @end smallexample
4641
4642 @noindent
4643 Here b7e0c705 is a compressed encoding of the qualification prefix.
4644 The GNAT Ada aware version of GDB understands these encoded prefixes, so if this
4645 debugger is used, the encoding is largely hidden from the user of the compiler.
4646
4647 @end table
4648
4649 @item -gnatR[0|1|2|3][s]
4650 @cindex @option{-gnatR} (@code{gcc})
4651 This switch controls output from the compiler of a listing showing
4652 representation information for declared types and objects. For
4653 @option{-gnatR0}, no information is output (equivalent to omitting
4654 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
4655 so @option{-gnatR} with no parameter has the same effect), size and alignment
4656 information is listed for declared array and record types. For
4657 @option{-gnatR2}, size and alignment information is listed for all
4658 expression information for values that are computed at run time for
4659 variant records. These symbolic expressions have a mostly obvious
4660 format with #n being used to represent the value of the n'th
4661 discriminant. See source files @file{repinfo.ads/adb} in the
4662 @code{GNAT} sources for full detalis on the format of @option{-gnatR3}
4663 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
4664 the output is to a file with the name @file{file.rep} where
4665 file is the name of the corresponding source file.
4666
4667 @item -gnatx
4668 @cindex @option{-gnatx} (@code{gcc})
4669 Normally the compiler generates full cross-referencing information in
4670 the @file{ALI} file. This information is used by a number of tools,
4671 including @code{gnatfind} and @code{gnatxref}. The -gnatx switch
4672 suppresses this information. This saves some space and may slightly
4673 speed up compilation, but means that these tools cannot be used.
4674 @end table
4675
4676 @node Units to Sources Mapping Files
4677 @subsection Units to Sources Mapping Files
4678
4679 @table @code
4680
4681 @item -gnatem@var{path}
4682 @cindex @option{-gnatem} (@code{gcc})
4683 A mapping file is a way to communicate to the compiler two mappings:
4684 from unit names to file names (without any directory information) and from
4685 file names to path names (with full directory information). These mappings
4686 are used by the compiler to short-circuit the path search.
4687
4688 A mapping file is a sequence of sets of three lines. In each set,
4689 the first line is the unit name, in lower case, with "%s" appended for
4690 specifications and "%b" appended for bodies; the second line is the file
4691 name; and the third line is the path name.
4692
4693 Example:
4694 @smallexample
4695    main%b
4696    main.2.ada
4697    /gnat/project1/sources/main.2.ada
4698 @end smallexample
4699
4700 When the switch @option{-gnatem} is specified, the compiler will create
4701 in memory the two mappings from the specified file. If there is any problem
4702 (non existent file, truncated file or duplicate entries), no mapping
4703 will be created.
4704
4705 Several @option{-gnatem} switches may be specified; however, only the last
4706 one on the command line will be taken into account.
4707
4708 When using a project file, @code{gnatmake} create a temporary mapping file
4709 and communicates it to the compiler using this switch.
4710
4711 @end table
4712
4713 @node Search Paths and the Run-Time Library (RTL)
4714 @section Search Paths and the Run-Time Library (RTL)
4715
4716 @noindent
4717 With the GNAT source-based library system, the compiler must be able to
4718 find source files for units that are needed by the unit being compiled.
4719 Search paths are used to guide this process.
4720
4721 The compiler compiles one source file whose name must be given
4722 explicitly on the command line. In other words, no searching is done
4723 for this file. To find all other source files that are needed (the most
4724 common being the specs of units), the compiler examines the following
4725 directories, in the following order:
4726
4727 @enumerate
4728 @item
4729 The directory containing the source file of the main unit being compiled
4730 (the file name on the command line).
4731
4732 @item
4733 Each directory named by an @code{-I} switch given on the @code{gcc}
4734 command line, in the order given.
4735
4736 @item
4737 @findex ADA_INCLUDE_PATH
4738 Each of the directories listed in the value of the
4739 @code{ADA_INCLUDE_PATH} environment variable.
4740 Construct this value
4741 exactly as the @code{PATH} environment variable: a list of directory
4742 names separated by colons (semicolons when working with the NT version).
4743 @item
4744 The content of the "ada_source_path" file which is part of the GNAT
4745 installation tree and is used to store standard libraries such as the
4746 GNAT Run Time Library (RTL) source files.
4747 @ref{Installing an Ada Library}
4748 @end enumerate
4749
4750 @noindent
4751 Specifying the switch @code{-I-}
4752 inhibits the use of the directory
4753 containing the source file named in the command line. You can still
4754 have this directory on your search path, but in this case it must be
4755 explicitly requested with a @code{-I} switch.
4756
4757 Specifying the switch @code{-nostdinc}
4758 inhibits the search of the default location for the GNAT Run Time
4759 Library (RTL) source files.
4760
4761 The compiler outputs its object files and ALI files in the current
4762 working directory.
4763 Caution: The object file can be redirected with the @code{-o} switch;
4764 however, @code{gcc} and @code{gnat1} have not been coordinated on this
4765 so the ALI file will not go to the right place. Therefore, you should
4766 avoid using the @code{-o} switch.
4767
4768 @findex System.IO
4769 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
4770 children make up the GNAT RTL, together with the simple @code{System.IO}
4771 package used in the "Hello World" example. The sources for these units
4772 are needed by the compiler and are kept together in one directory. Not
4773 all of the bodies are needed, but all of the sources are kept together
4774 anyway. In a normal installation, you need not specify these directory
4775 names when compiling or binding. Either the environment variables or
4776 the built-in defaults cause these files to be found.
4777
4778 In addition to the language-defined hierarchies (System, Ada and
4779 Interfaces), the GNAT distribution provides a fourth hierarchy,
4780 consisting of child units of GNAT. This is a collection of generally
4781 useful routines. See the GNAT Reference Manual for further details.
4782
4783 Besides simplifying access to the RTL, a major use of search paths is
4784 in compiling sources from multiple directories. This can make
4785 development environments much more flexible.
4786
4787 @node Order of Compilation Issues
4788 @section Order of Compilation Issues
4789
4790 @noindent
4791 If, in our earlier example, there was a spec for the @code{hello}
4792 procedure, it would be contained in the file @file{hello.ads}; yet this
4793 file would not have to be explicitly compiled. This is the result of the
4794 model we chose to implement library management. Some of the consequences
4795 of this model are as follows:
4796
4797 @itemize @bullet
4798 @item
4799 There is no point in compiling specs (except for package
4800 specs with no bodies) because these are compiled as needed by clients. If
4801 you attempt a useless compilation, you will receive an error message.
4802 It is also useless to compile subunits because they are compiled as needed
4803 by the parent.
4804
4805 @item
4806 There are no order of compilation requirements: performing a
4807 compilation never obsoletes anything. The only way you can obsolete
4808 something and require recompilations is to modify one of the
4809 source files on which it depends.
4810
4811 @item
4812 There is no library as such, apart from the ALI files
4813 (@pxref{The Ada Library Information Files}, for information on the format of these
4814 files). For now we find it convenient to create separate ALI files, but
4815 eventually the information therein may be incorporated into the object
4816 file directly.
4817
4818 @item
4819 When you compile a unit, the source files for the specs of all units
4820 that it @code{with}'s, all its subunits, and the bodies of any generics it
4821 instantiates must be available (reachable by the search-paths mechanism
4822 described above), or you will receive a fatal error message.
4823 @end itemize
4824
4825 @node Examples
4826 @section Examples
4827
4828 @noindent
4829 The following are some typical Ada compilation command line examples:
4830
4831 @table @code
4832 @item $ gcc -c xyz.adb
4833 Compile body in file @file{xyz.adb} with all default options.
4834
4835 @item $ gcc -c -O2 -gnata xyz-def.adb
4836
4837 Compile the child unit package in file @file{xyz-def.adb} with extensive
4838 optimizations, and pragma @code{Assert}/@code{Debug} statements
4839 enabled.
4840
4841 @item $ gcc -c -gnatc abc-def.adb
4842 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
4843 mode.
4844 @end table
4845
4846 @node Binding Using gnatbind
4847 @chapter Binding Using @code{gnatbind}
4848 @findex gnatbind
4849
4850 @menu
4851 * Running gnatbind::
4852 * Generating the Binder Program in C::
4853 * Consistency-Checking Modes::
4854 * Binder Error Message Control::
4855 * Elaboration Control::
4856 * Output Control::
4857 * Binding with Non-Ada Main Programs::
4858 * Binding Programs with No Main Subprogram::
4859 * Summary of Binder Switches::
4860 * Command-Line Access::
4861 * Search Paths for gnatbind::
4862 * Examples of gnatbind Usage::
4863 @end menu
4864
4865 @noindent
4866 This chapter describes the GNAT binder, @code{gnatbind}, which is used
4867 to bind compiled GNAT objects. The @code{gnatbind} program performs
4868 four separate functions:
4869
4870 @enumerate
4871 @item
4872 Checks that a program is consistent, in accordance with the rules in
4873 Chapter 10 of the Ada 95 Reference Manual. In particular, error
4874 messages are generated if a program uses inconsistent versions of a
4875 given unit.
4876
4877 @item
4878 Checks that an acceptable order of elaboration exists for the program
4879 and issues an error message if it cannot find an order of elaboration
4880 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
4881
4882 @item
4883 Generates a main program incorporating the given elaboration order.
4884 This program is a small Ada package (body and spec) that
4885 must be subsequently compiled
4886 using the GNAT compiler. The necessary compilation step is usually
4887 performed automatically by @code{gnatlink}. The two most important
4888 functions of this program
4889 are to call the elaboration routines of units in an appropriate order
4890 and to call the main program.
4891
4892 @item
4893 Determines the set of object files required by the given main program.
4894 This information is output in the forms of comments in the generated program,
4895 to be read by the @code{gnatlink} utility used to link the Ada application.
4896 @end enumerate
4897
4898 @node Running gnatbind
4899 @section Running @code{gnatbind}
4900
4901 @noindent
4902 The form of the @code{gnatbind} command is
4903
4904 @smallexample
4905 $ gnatbind [@var{switches}] @var{mainprog}[.ali] [@var{switches}]
4906 @end smallexample
4907
4908 @noindent
4909 where @var{mainprog}.adb is the Ada file containing the main program
4910 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
4911 package in two files which names are
4912 @file{b~@var{ada_main}.ads}, and @file{b~@var{ada_main}.adb}.
4913 For example, if given the
4914 parameter @samp{hello.ali}, for a main program contained in file
4915 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
4916 and @file{b~hello.adb}.
4917
4918 When doing consistency checking, the binder takes into consideration
4919 any source files it can locate. For example, if the binder determines
4920 that the given main program requires the package @code{Pack}, whose
4921 @file{.ali}
4922 file is @file{pack.ali} and whose corresponding source spec file is
4923 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
4924 (using the same search path conventions as previously described for the
4925 @code{gcc} command). If it can locate this source file, it checks that
4926 the time stamps
4927 or source checksums of the source and its references to in @file{ali} files
4928 match. In other words, any @file{ali} files that mentions this spec must have
4929 resulted from compiling this version of the source file (or in the case
4930 where the source checksums match, a version close enough that the
4931 difference does not matter).
4932
4933 @cindex Source files, use by binder
4934 The effect of this consistency checking, which includes source files, is
4935 that the binder ensures that the program is consistent with the latest
4936 version of the source files that can be located at bind time. Editing a
4937 source file without compiling files that depend on the source file cause
4938 error messages to be generated by the binder.
4939
4940 For example, suppose you have a main program @file{hello.adb} and a
4941 package @code{P}, from file @file{p.ads} and you perform the following
4942 steps:
4943
4944 @enumerate
4945 @item
4946 Enter @code{gcc -c hello.adb} to compile the main program.
4947
4948 @item
4949 Enter @code{gcc -c p.ads} to compile package @code{P}.
4950
4951 @item
4952 Edit file @file{p.ads}.
4953
4954 @item
4955 Enter @code{gnatbind hello}.
4956 @end enumerate
4957
4958 At this point, the file @file{p.ali} contains an out-of-date time stamp
4959 because the file @file{p.ads} has been edited. The attempt at binding
4960 fails, and the binder generates the following error messages:
4961
4962 @smallexample
4963 error: "hello.adb" must be recompiled ("p.ads" has been modified)
4964 error: "p.ads" has been modified and must be recompiled
4965 @end smallexample
4966
4967 @noindent
4968 Now both files must be recompiled as indicated, and then the bind can
4969 succeed, generating a main program. You need not normally be concerned
4970 with the contents of this file, but it is similar to the following which
4971 is the binder file generated for a simple "hello world" program.
4972
4973 @smallexample
4974 @iftex
4975 @leftskip=0cm
4976 @end iftex
4977 --  The package is called Ada_Main unless this name is actually used
4978 --  as a unit name in the partition, in which case some other unique
4979 --  name is used.
4980
4981 with System;
4982 package ada_main is
4983
4984    Elab_Final_Code : Integer;
4985    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
4986
4987    --  The main program saves the parameters (argument count,
4988    --  argument values, environment pointer) in global variables
4989    --  for later access by other units including
4990    --  Ada.Command_Line.
4991
4992    gnat_argc : Integer;
4993    gnat_argv : System.Address;
4994    gnat_envp : System.Address;
4995
4996    --  The actual variables are stored in a library routine. This
4997    --  is useful for some shared library situations, where there
4998    --  are problems if variables are not in the library.
4999
5000    pragma Import (C, gnat_argc);
5001    pragma Import (C, gnat_argv);
5002    pragma Import (C, gnat_envp);
5003
5004    --  The exit status is similarly an external location
5005
5006    gnat_exit_status : Integer;
5007    pragma Import (C, gnat_exit_status);
5008
5009    GNAT_Version : constant String :=
5010                     "GNAT Version: 3.15w (20010315)";
5011    pragma Export (C, GNAT_Version, "__gnat_version");
5012
5013    --  This is the generated adafinal routine that performs
5014    --  finalization at the end of execution. In the case where
5015    --  Ada is the main program, this main program makes a call
5016    --  to adafinal at program termination.
5017
5018    procedure adafinal;
5019    pragma Export (C, adafinal, "adafinal");
5020
5021    --  This is the generated adainit routine that performs
5022    --  initialization at the start of execution. In the case
5023    --  where Ada is the main program, this main program makes
5024    --  a call to adainit at program startup.
5025
5026    procedure adainit;
5027    pragma Export (C, adainit, "adainit");
5028
5029    --  This routine is called at the start of execution. It is
5030    --  a dummy routine that is used by the debugger to breakpoint
5031    --  at the start of execution.
5032
5033    procedure Break_Start;
5034    pragma Import (C, Break_Start, "__gnat_break_start");
5035
5036    --  This is the actual generated main program (it would be
5037    --  suppressed if the no main program switch were used). As
5038    --  required by standard system conventions, this program has
5039    --  the external name main.
5040
5041    function main
5042      (argc : Integer;
5043       argv : System.Address;
5044       envp : System.Address)
5045       return Integer;
5046    pragma Export (C, main, "main");
5047
5048    --  The following set of constants give the version
5049    --  identification values for every unit in the bound
5050    --  partition. This identification is computed from all
5051    --  dependent semantic units, and corresponds to the
5052    --  string that would be returned by use of the
5053    --  Body_Version or Version attributes.
5054
5055    type Version_32 is mod 2 ** 32;
5056    u00001 : constant Version_32 := 16#7880BEB3#;
5057    u00002 : constant Version_32 := 16#0D24CBD0#;
5058    u00003 : constant Version_32 := 16#3283DBEB#;
5059    u00004 : constant Version_32 := 16#2359F9ED#;
5060    u00005 : constant Version_32 := 16#664FB847#;
5061    u00006 : constant Version_32 := 16#68E803DF#;
5062    u00007 : constant Version_32 := 16#5572E604#;
5063    u00008 : constant Version_32 := 16#46B173D8#;
5064    u00009 : constant Version_32 := 16#156A40CF#;
5065    u00010 : constant Version_32 := 16#033DABE0#;
5066    u00011 : constant Version_32 := 16#6AB38FEA#;
5067    u00012 : constant Version_32 := 16#22B6217D#;
5068    u00013 : constant Version_32 := 16#68A22947#;
5069    u00014 : constant Version_32 := 16#18CC4A56#;
5070    u00015 : constant Version_32 := 16#08258E1B#;
5071    u00016 : constant Version_32 := 16#367D5222#;
5072    u00017 : constant Version_32 := 16#20C9ECA4#;
5073    u00018 : constant Version_32 := 16#50D32CB6#;
5074    u00019 : constant Version_32 := 16#39A8BB77#;
5075    u00020 : constant Version_32 := 16#5CF8FA2B#;
5076    u00021 : constant Version_32 := 16#2F1EB794#;
5077    u00022 : constant Version_32 := 16#31AB6444#;
5078    u00023 : constant Version_32 := 16#1574B6E9#;
5079    u00024 : constant Version_32 := 16#5109C189#;
5080    u00025 : constant Version_32 := 16#56D770CD#;
5081    u00026 : constant Version_32 := 16#02F9DE3D#;
5082    u00027 : constant Version_32 := 16#08AB6B2C#;
5083    u00028 : constant Version_32 := 16#3FA37670#;
5084    u00029 : constant Version_32 := 16#476457A0#;
5085    u00030 : constant Version_32 := 16#731E1B6E#;
5086    u00031 : constant Version_32 := 16#23C2E789#;
5087    u00032 : constant Version_32 := 16#0F1BD6A1#;
5088    u00033 : constant Version_32 := 16#7C25DE96#;
5089    u00034 : constant Version_32 := 16#39ADFFA2#;
5090    u00035 : constant Version_32 := 16#571DE3E7#;
5091    u00036 : constant Version_32 := 16#5EB646AB#;
5092    u00037 : constant Version_32 := 16#4249379B#;
5093    u00038 : constant Version_32 := 16#0357E00A#;
5094    u00039 : constant Version_32 := 16#3784FB72#;
5095    u00040 : constant Version_32 := 16#2E723019#;
5096    u00041 : constant Version_32 := 16#623358EA#;
5097    u00042 : constant Version_32 := 16#107F9465#;
5098    u00043 : constant Version_32 := 16#6843F68A#;
5099    u00044 : constant Version_32 := 16#63305874#;
5100    u00045 : constant Version_32 := 16#31E56CE1#;
5101    u00046 : constant Version_32 := 16#02917970#;
5102    u00047 : constant Version_32 := 16#6CCBA70E#;
5103    u00048 : constant Version_32 := 16#41CD4204#;
5104    u00049 : constant Version_32 := 16#572E3F58#;
5105    u00050 : constant Version_32 := 16#20729FF5#;
5106    u00051 : constant Version_32 := 16#1D4F93E8#;
5107    u00052 : constant Version_32 := 16#30B2EC3D#;
5108    u00053 : constant Version_32 := 16#34054F96#;
5109    u00054 : constant Version_32 := 16#5A199860#;
5110    u00055 : constant Version_32 := 16#0E7F912B#;
5111    u00056 : constant Version_32 := 16#5760634A#;
5112    u00057 : constant Version_32 := 16#5D851835#;
5113
5114    --  The following Export pragmas export the version numbers
5115    --  with symbolic names ending in B (for body) or S
5116    --  (for spec) so that they can be located in a link. The
5117    --  information provided here is sufficient to track down
5118    --  the exact versions of units used in a given build.
5119
5120    pragma Export (C, u00001, "helloB");
5121    pragma Export (C, u00002, "system__standard_libraryB");
5122    pragma Export (C, u00003, "system__standard_libraryS");
5123    pragma Export (C, u00004, "adaS");
5124    pragma Export (C, u00005, "ada__text_ioB");
5125    pragma Export (C, u00006, "ada__text_ioS");
5126    pragma Export (C, u00007, "ada__exceptionsB");
5127    pragma Export (C, u00008, "ada__exceptionsS");
5128    pragma Export (C, u00009, "gnatS");
5129    pragma Export (C, u00010, "gnat__heap_sort_aB");
5130    pragma Export (C, u00011, "gnat__heap_sort_aS");
5131    pragma Export (C, u00012, "systemS");
5132    pragma Export (C, u00013, "system__exception_tableB");
5133    pragma Export (C, u00014, "system__exception_tableS");
5134    pragma Export (C, u00015, "gnat__htableB");
5135    pragma Export (C, u00016, "gnat__htableS");
5136    pragma Export (C, u00017, "system__exceptionsS");
5137    pragma Export (C, u00018, "system__machine_state_operationsB");
5138    pragma Export (C, u00019, "system__machine_state_operationsS");
5139    pragma Export (C, u00020, "system__machine_codeS");
5140    pragma Export (C, u00021, "system__storage_elementsB");
5141    pragma Export (C, u00022, "system__storage_elementsS");
5142    pragma Export (C, u00023, "system__secondary_stackB");
5143    pragma Export (C, u00024, "system__secondary_stackS");
5144    pragma Export (C, u00025, "system__parametersB");
5145    pragma Export (C, u00026, "system__parametersS");
5146    pragma Export (C, u00027, "system__soft_linksB");
5147    pragma Export (C, u00028, "system__soft_linksS");
5148    pragma Export (C, u00029, "system__stack_checkingB");
5149    pragma Export (C, u00030, "system__stack_checkingS");
5150    pragma Export (C, u00031, "system__tracebackB");
5151    pragma Export (C, u00032, "system__tracebackS");
5152    pragma Export (C, u00033, "ada__streamsS");
5153    pragma Export (C, u00034, "ada__tagsB");
5154    pragma Export (C, u00035, "ada__tagsS");
5155    pragma Export (C, u00036, "system__string_opsB");
5156    pragma Export (C, u00037, "system__string_opsS");
5157    pragma Export (C, u00038, "interfacesS");
5158    pragma Export (C, u00039, "interfaces__c_streamsB");
5159    pragma Export (C, u00040, "interfaces__c_streamsS");
5160    pragma Export (C, u00041, "system__file_ioB");
5161    pragma Export (C, u00042, "system__file_ioS");
5162    pragma Export (C, u00043, "ada__finalizationB");
5163    pragma Export (C, u00044, "ada__finalizationS");
5164    pragma Export (C, u00045, "system__finalization_rootB");
5165    pragma Export (C, u00046, "system__finalization_rootS");
5166    pragma Export (C, u00047, "system__finalization_implementationB");
5167    pragma Export (C, u00048, "system__finalization_implementationS");
5168    pragma Export (C, u00049, "system__string_ops_concat_3B");
5169    pragma Export (C, u00050, "system__string_ops_concat_3S");
5170    pragma Export (C, u00051, "system__stream_attributesB");
5171    pragma Export (C, u00052, "system__stream_attributesS");
5172    pragma Export (C, u00053, "ada__io_exceptionsS");
5173    pragma Export (C, u00054, "system__unsigned_typesS");
5174    pragma Export (C, u00055, "system__file_control_blockS");
5175    pragma Export (C, u00056, "ada__finalization__list_controllerB");
5176    pragma Export (C, u00057, "ada__finalization__list_controllerS");
5177
5178    -- BEGIN ELABORATION ORDER
5179    -- ada (spec)
5180    -- gnat (spec)
5181    -- gnat.heap_sort_a (spec)
5182    -- gnat.heap_sort_a (body)
5183    -- gnat.htable (spec)
5184    -- gnat.htable (body)
5185    -- interfaces (spec)
5186    -- system (spec)
5187    -- system.machine_code (spec)
5188    -- system.parameters (spec)
5189    -- system.parameters (body)
5190    -- interfaces.c_streams (spec)
5191    -- interfaces.c_streams (body)
5192    -- system.standard_library (spec)
5193    -- ada.exceptions (spec)
5194    -- system.exception_table (spec)
5195    -- system.exception_table (body)
5196    -- ada.io_exceptions (spec)
5197    -- system.exceptions (spec)
5198    -- system.storage_elements (spec)
5199    -- system.storage_elements (body)
5200    -- system.machine_state_operations (spec)
5201    -- system.machine_state_operations (body)
5202    -- system.secondary_stack (spec)
5203    -- system.stack_checking (spec)
5204    -- system.soft_links (spec)
5205    -- system.soft_links (body)
5206    -- system.stack_checking (body)
5207    -- system.secondary_stack (body)
5208    -- system.standard_library (body)
5209    -- system.string_ops (spec)
5210    -- system.string_ops (body)
5211    -- ada.tags (spec)
5212    -- ada.tags (body)
5213    -- ada.streams (spec)
5214    -- system.finalization_root (spec)
5215    -- system.finalization_root (body)
5216    -- system.string_ops_concat_3 (spec)
5217    -- system.string_ops_concat_3 (body)
5218    -- system.traceback (spec)
5219    -- system.traceback (body)
5220    -- ada.exceptions (body)
5221    -- system.unsigned_types (spec)
5222    -- system.stream_attributes (spec)
5223    -- system.stream_attributes (body)
5224    -- system.finalization_implementation (spec)
5225    -- system.finalization_implementation (body)
5226    -- ada.finalization (spec)
5227    -- ada.finalization (body)
5228    -- ada.finalization.list_controller (spec)
5229    -- ada.finalization.list_controller (body)
5230    -- system.file_control_block (spec)
5231    -- system.file_io (spec)
5232    -- system.file_io (body)
5233    -- ada.text_io (spec)
5234    -- ada.text_io (body)
5235    -- hello (body)
5236    -- END ELABORATION ORDER
5237
5238 end ada_main;
5239
5240 --  The following source file name pragmas allow the generated file
5241 --  names to be unique for different main programs. They are needed
5242 --  since the package name will always be Ada_Main.
5243
5244 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
5245 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
5246
5247 --  Generated package body for Ada_Main starts here
5248
5249 package body ada_main is
5250
5251    --  The actual finalization is performed by calling the
5252    --  library routine in System.Standard_Library.Adafinal
5253
5254    procedure Do_Finalize;
5255    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
5256
5257    -------------
5258    -- adainit --
5259    -------------
5260
5261 @findex adainit
5262    procedure adainit is
5263
5264       --  These booleans are set to True once the associated unit has
5265       --  been elaborated. It is also used to avoid elaborating the
5266       --  same unit twice.
5267
5268       E040 : Boolean; pragma Import (Ada, E040, "interfaces__c_streams_E");
5269       E008 : Boolean; pragma Import (Ada, E008, "ada__exceptions_E");
5270       E014 : Boolean; pragma Import (Ada, E014, "system__exception_table_E");
5271       E053 : Boolean; pragma Import (Ada, E053, "ada__io_exceptions_E");
5272       E017 : Boolean; pragma Import (Ada, E017, "system__exceptions_E");
5273       E024 : Boolean; pragma Import (Ada, E024, "system__secondary_stack_E");
5274       E030 : Boolean; pragma Import (Ada, E030, "system__stack_checking_E");
5275       E028 : Boolean; pragma Import (Ada, E028, "system__soft_links_E");
5276       E035 : Boolean; pragma Import (Ada, E035, "ada__tags_E");
5277       E033 : Boolean; pragma Import (Ada, E033, "ada__streams_E");
5278       E046 : Boolean; pragma Import (Ada, E046, "system__finalization_root_E");
5279       E048 : Boolean; pragma Import (Ada, E048, "system__finalization_implementation_E");
5280       E044 : Boolean; pragma Import (Ada, E044, "ada__finalization_E");
5281       E057 : Boolean; pragma Import (Ada, E057, "ada__finalization__list_controller_E");
5282       E055 : Boolean; pragma Import (Ada, E055, "system__file_control_block_E");
5283       E042 : Boolean; pragma Import (Ada, E042, "system__file_io_E");
5284       E006 : Boolean; pragma Import (Ada, E006, "ada__text_io_E");
5285
5286       --  Set_Globals is a library routine that stores away the
5287       --  value of the indicated set of global values in global
5288       --  variables within the library.
5289
5290       procedure Set_Globals
5291         (Main_Priority            : Integer;
5292          Time_Slice_Value         : Integer;
5293          WC_Encoding              : Character;
5294          Locking_Policy           : Character;
5295          Queuing_Policy           : Character;
5296          Task_Dispatching_Policy  : Character;
5297          Adafinal                 : System.Address;
5298          Unreserve_All_Interrupts : Integer;
5299          Exception_Tracebacks     : Integer);
5300 @findex __gnat_set_globals
5301       pragma Import (C, Set_Globals, "__gnat_set_globals");
5302
5303       --  SDP_Table_Build is a library routine used to build the
5304       --  exception tables. See unit Ada.Exceptions in files
5305       --  a-except.ads/adb for full details of how zero cost
5306       --  exception handling works. This procedure, the call to
5307       --  it, and the two following tables are all omitted if the
5308       --  build is in longjmp/setjump exception mode.
5309
5310 @findex SDP_Table_Build
5311 @findex Zero Cost Exceptions
5312       procedure SDP_Table_Build
5313         (SDP_Addresses   : System.Address;
5314          SDP_Count       : Natural;
5315          Elab_Addresses  : System.Address;
5316          Elab_Addr_Count : Natural);
5317       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
5318
5319       --  Table of Unit_Exception_Table addresses. Used for zero
5320       --  cost exception handling to build the top level table.
5321
5322       ST : aliased constant array (1 .. 23) of System.Address := (
5323         Hello'UET_Address,
5324         Ada.Text_Io'UET_Address,
5325         Ada.Exceptions'UET_Address,
5326         Gnat.Heap_Sort_A'UET_Address,
5327         System.Exception_Table'UET_Address,
5328         System.Machine_State_Operations'UET_Address,
5329         System.Secondary_Stack'UET_Address,
5330         System.Parameters'UET_Address,
5331         System.Soft_Links'UET_Address,
5332         System.Stack_Checking'UET_Address,
5333         System.Traceback'UET_Address,
5334         Ada.Streams'UET_Address,
5335         Ada.Tags'UET_Address,
5336         System.String_Ops'UET_Address,
5337         Interfaces.C_Streams'UET_Address,
5338         System.File_Io'UET_Address,
5339         Ada.Finalization'UET_Address,
5340         System.Finalization_Root'UET_Address,
5341         System.Finalization_Implementation'UET_Address,
5342         System.String_Ops_Concat_3'UET_Address,
5343         System.Stream_Attributes'UET_Address,
5344         System.File_Control_Block'UET_Address,
5345         Ada.Finalization.List_Controller'UET_Address);
5346
5347       --  Table of addresses of elaboration routines. Used for
5348       --  zero cost exception handling to make sure these
5349       --  addresses are included in the top level procedure
5350       --  address table.
5351
5352       EA : aliased constant array (1 .. 23) of System.Address := (
5353         adainit'Code_Address,
5354         Do_Finalize'Code_Address,
5355         Ada.Exceptions'Elab_Spec'Address,
5356         System.Exceptions'Elab_Spec'Address,
5357         Interfaces.C_Streams'Elab_Spec'Address,
5358         System.Exception_Table'Elab_Body'Address,
5359         Ada.Io_Exceptions'Elab_Spec'Address,
5360         System.Stack_Checking'Elab_Spec'Address,
5361         System.Soft_Links'Elab_Body'Address,
5362         System.Secondary_Stack'Elab_Body'Address,
5363         Ada.Tags'Elab_Spec'Address,
5364         Ada.Tags'Elab_Body'Address,
5365         Ada.Streams'Elab_Spec'Address,
5366         System.Finalization_Root'Elab_Spec'Address,
5367         Ada.Exceptions'Elab_Body'Address,
5368         System.Finalization_Implementation'Elab_Spec'Address,
5369         System.Finalization_Implementation'Elab_Body'Address,
5370         Ada.Finalization'Elab_Spec'Address,
5371         Ada.Finalization.List_Controller'Elab_Spec'Address,
5372         System.File_Control_Block'Elab_Spec'Address,
5373         System.File_Io'Elab_Body'Address,
5374         Ada.Text_Io'Elab_Spec'Address,
5375         Ada.Text_Io'Elab_Body'Address);
5376
5377    --  Start of processing for adainit
5378
5379    begin
5380
5381       --  Call SDP_Table_Build to build the top level procedure
5382       --  table for zero cost exception handling (omitted in
5383       --  longjmp/setjump mode).
5384
5385       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
5386
5387       --  Call Set_Globals to record various information for
5388       --  this partition.  The values are derived by the binder
5389       --  from information stored in the ali files by the compiler.
5390
5391 @findex __gnat_set_globals
5392       Set_Globals
5393         (Main_Priority            => -1,
5394          --  Priority of main program, -1 if no pragma Priority used
5395
5396          Time_Slice_Value         => -1,
5397          --  Time slice from Time_Slice pragma, -1 if none used
5398
5399          WC_Encoding              => 'b',
5400          --  Wide_Character encoding used, default is brackets
5401
5402          Locking_Policy           => ' ',
5403          --  Locking_Policy used, default of space means not
5404          --  specified, otherwise it is the first character of
5405          --  the policy name.
5406
5407          Queuing_Policy           => ' ',
5408          --  Queuing_Policy used, default of space means not
5409          --  specified, otherwise it is the first character of
5410          --  the policy name.
5411
5412          Task_Dispatching_Policy  => ' ',
5413          --  Task_Dispatching_Policy used, default of space means
5414          --  not specified, otherwise first character of the
5415          --  policy name.
5416
5417          Adafinal                 => System.Null_Address,
5418          --  Address of Adafinal routine, not used anymore
5419
5420          Unreserve_All_Interrupts => 0,
5421          --  Set true if pragma Unreserve_All_Interrupts was used
5422
5423          Exception_Tracebacks     => 0);
5424          --  Indicates if exception tracebacks are enabled
5425
5426       Elab_Final_Code := 1;
5427
5428       --  Now we have the elaboration calls for all units in the partition.
5429       --  The Elab_Spec and Elab_Body attributes generate references to the
5430       --  implicit elaboration procedures generated by the compiler for
5431       --  each unit that requires elaboration.
5432
5433       if not E040 then
5434          Interfaces.C_Streams'Elab_Spec;
5435       end if;
5436       E040 := True;
5437       if not E008 then
5438          Ada.Exceptions'Elab_Spec;
5439       end if;
5440       if not E014 then
5441          System.Exception_Table'Elab_Body;
5442          E014 := True;
5443       end if;
5444       if not E053 then
5445          Ada.Io_Exceptions'Elab_Spec;
5446          E053 := True;
5447       end if;
5448       if not E017 then
5449          System.Exceptions'Elab_Spec;
5450          E017 := True;
5451       end if;
5452       if not E030 then
5453          System.Stack_Checking'Elab_Spec;
5454       end if;
5455       if not E028 then
5456          System.Soft_Links'Elab_Body;
5457          E028 := True;
5458       end if;
5459       E030 := True;
5460       if not E024 then
5461          System.Secondary_Stack'Elab_Body;
5462          E024 := True;
5463       end if;
5464       if not E035 then
5465          Ada.Tags'Elab_Spec;
5466       end if;
5467       if not E035 then
5468          Ada.Tags'Elab_Body;
5469          E035 := True;
5470       end if;
5471       if not E033 then
5472          Ada.Streams'Elab_Spec;
5473          E033 := True;
5474       end if;
5475       if not E046 then
5476          System.Finalization_Root'Elab_Spec;
5477       end if;
5478       E046 := True;
5479       if not E008 then
5480          Ada.Exceptions'Elab_Body;
5481          E008 := True;
5482       end if;
5483       if not E048 then
5484          System.Finalization_Implementation'Elab_Spec;
5485       end if;
5486       if not E048 then
5487          System.Finalization_Implementation'Elab_Body;
5488          E048 := True;
5489       end if;
5490       if not E044 then
5491          Ada.Finalization'Elab_Spec;
5492       end if;
5493       E044 := True;
5494       if not E057 then
5495          Ada.Finalization.List_Controller'Elab_Spec;
5496       end if;
5497       E057 := True;
5498       if not E055 then
5499          System.File_Control_Block'Elab_Spec;
5500          E055 := True;
5501       end if;
5502       if not E042 then
5503          System.File_Io'Elab_Body;
5504          E042 := True;
5505       end if;
5506       if not E006 then
5507          Ada.Text_Io'Elab_Spec;
5508       end if;
5509       if not E006 then
5510          Ada.Text_Io'Elab_Body;
5511          E006 := True;
5512       end if;
5513
5514       Elab_Final_Code := 0;
5515    end adainit;
5516
5517    --------------
5518    -- adafinal --
5519    --------------
5520
5521 @findex adafinal
5522    procedure adafinal is
5523    begin
5524       Do_Finalize;
5525    end adafinal;
5526
5527    ----------
5528    -- main --
5529    ----------
5530
5531    --  main is actually a function, as in the ANSI C standard,
5532    --  defined to return the exit status. The three parameters
5533    --  are the argument count, argument values and environment
5534    --  pointer.
5535
5536 @findex Main Program
5537    function main
5538      (argc : Integer;
5539       argv : System.Address;
5540       envp : System.Address)
5541       return Integer
5542    is
5543       --  The initialize routine performs low level system
5544       --  initialization using a standard library routine which
5545       --  sets up signal handling and performs any other
5546       --  required setup. The routine can be found in file
5547       --  a-init.c.
5548
5549 @findex __gnat_initialize
5550       procedure initialize;
5551       pragma Import (C, initialize, "__gnat_initialize");
5552
5553       --  The finalize routine performs low level system
5554       --  finalization using a standard library routine. The
5555       --  routine is found in file a-final.c and in the standard
5556       --  distribution is a dummy routine that does nothing, so
5557       --  really this is a hook for special user finalization.
5558
5559 @findex __gnat_finalize
5560       procedure finalize;
5561       pragma Import (C, finalize, "__gnat_finalize");
5562
5563       --  We get to the main program of the partition by using
5564       --  pragma Import because if we try to with the unit and
5565       --  call it Ada style, then not only do we waste time
5566       --  recompiling it, but also, we don't really know the right
5567       --  switches (e.g. identifier character set) to be used
5568       --  to compile it.
5569
5570       procedure Ada_Main_Program;
5571       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
5572
5573    --  Start of processing for main
5574
5575    begin
5576       --  Save global variables
5577
5578       gnat_argc := argc;
5579       gnat_argv := argv;
5580       gnat_envp := envp;
5581
5582       --  Call low level system initialization
5583
5584       Initialize;
5585
5586       --  Call our generated Ada initialization routine
5587
5588       adainit;
5589
5590       --  This is the point at which we want the debugger to get
5591       --  control
5592
5593       Break_Start;
5594
5595       --  Now we call the main program of the partition
5596
5597       Ada_Main_Program;
5598
5599       --  Perform Ada finalization
5600
5601       adafinal;
5602
5603       --  Perform low level system finalization
5604
5605       Finalize;
5606
5607       --  Return the proper exit status
5608       return (gnat_exit_status);
5609    end;
5610
5611 --  This section is entirely comments, so it has no effect on the
5612 --  compilation of the Ada_Main package. It provides the list of
5613 --  object files and linker options, as well as some standard
5614 --  libraries needed for the link. The gnatlink utility parses
5615 --  this b~hello.adb file to read these comment lines to generate
5616 --  the appropriate command line arguments for the call to the
5617 --  system linker. The BEGIN/END lines are used for sentinels for
5618 --  this parsing operation.
5619
5620 --  The exact file names will of course depend on the environment,
5621 --  host/target and location of files on the host system.
5622
5623 @findex Object file list
5624 -- BEGIN Object file/option list
5625    --   ./hello.o
5626    --   -L./
5627    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
5628    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
5629 -- END Object file/option list
5630
5631 end ada_main;
5632
5633 @end smallexample
5634
5635 @noindent
5636 The Ada code in the above example is exactly what is generated by the
5637 binder. We have added comments to more clearly indicate the function
5638 of each part of the generated @code{Ada_Main} package.
5639
5640 The code is standard Ada in all respects, and can be processed by any
5641 tools that handle Ada. In particular, it is possible to use the debugger
5642 in Ada mode to debug the generated Ada_Main package. For example, suppose
5643 that for reasons that you do not understand, your program is blowing up
5644 during elaboration of the body of @code{Ada.Text_IO}. To chase this bug
5645 down, you can place a breakpoint on the call:
5646
5647 @smallexample
5648 Ada.Text_Io'Elab_Body;
5649 @end smallexample
5650
5651 @noindent
5652 and trace the elaboration routine for this package to find out where
5653 the problem might be (more usually of course you would be debugging
5654 elaboration code in your own application).
5655
5656 @node Generating the Binder Program in C
5657 @section Generating the Binder Program in C
5658 @noindent
5659 In most normal usage, the default mode of @code{gnatbind} which is to
5660 generate the main package in Ada, as described in the previous section.
5661 In particular, this means that any Ada programmer can read and understand
5662 the generated main program. It can also be debugged just like any other
5663 Ada code provided the @code{-g} switch is used for @code{gnatbind}
5664 and @code{gnatlink}.
5665
5666 However for some purposes it may be convenient to generate the main
5667 program in C rather than Ada. This may for example be helpful when you
5668 are generating a mixed language program with the main program in C. The
5669 GNAT compiler itself is an example. The use of the @code{-C} switch
5670 for both @code{gnatbind} and @code{gnatlink} will cause the program to
5671 be generated in C (and compiled using the gnu C compiler). The
5672 following shows the C code generated for the same "Hello World"
5673 program:
5674
5675 @smallexample
5676
5677 #ifdef __STDC__
5678 #define PARAMS(paramlist) paramlist
5679 #else
5680 #define PARAMS(paramlist) ()
5681 #endif
5682
5683 extern void __gnat_set_globals
5684  PARAMS ((int, int, int, int, int, int,
5685           void (*) PARAMS ((void)), int, int));
5686 extern void adafinal PARAMS ((void));
5687 extern void adainit PARAMS ((void));
5688 extern void system__standard_library__adafinal PARAMS ((void));
5689 extern int main PARAMS ((int, char **, char **));
5690 extern void exit PARAMS ((int));
5691 extern void __gnat_break_start PARAMS ((void));
5692 extern void _ada_hello PARAMS ((void));
5693 extern void __gnat_initialize PARAMS ((void));
5694 extern void __gnat_finalize PARAMS ((void));
5695
5696 extern void ada__exceptions___elabs PARAMS ((void));
5697 extern void system__exceptions___elabs PARAMS ((void));
5698 extern void interfaces__c_streams___elabs PARAMS ((void));
5699 extern void system__exception_table___elabb PARAMS ((void));
5700 extern void ada__io_exceptions___elabs PARAMS ((void));
5701 extern void system__stack_checking___elabs PARAMS ((void));
5702 extern void system__soft_links___elabb PARAMS ((void));
5703 extern void system__secondary_stack___elabb PARAMS ((void));
5704 extern void ada__tags___elabs PARAMS ((void));
5705 extern void ada__tags___elabb PARAMS ((void));
5706 extern void ada__streams___elabs PARAMS ((void));
5707 extern void system__finalization_root___elabs PARAMS ((void));
5708 extern void ada__exceptions___elabb PARAMS ((void));
5709 extern void system__finalization_implementation___elabs PARAMS ((void));
5710 extern void system__finalization_implementation___elabb PARAMS ((void));
5711 extern void ada__finalization___elabs PARAMS ((void));
5712 extern void ada__finalization__list_controller___elabs PARAMS ((void));
5713 extern void system__file_control_block___elabs PARAMS ((void));
5714 extern void system__file_io___elabb PARAMS ((void));
5715 extern void ada__text_io___elabs PARAMS ((void));
5716 extern void ada__text_io___elabb PARAMS ((void));
5717
5718 extern int __gnat_inside_elab_final_code;
5719
5720 extern int gnat_argc;
5721 extern char **gnat_argv;
5722 extern char **gnat_envp;
5723 extern int gnat_exit_status;
5724
5725 char __gnat_version[] = "GNAT Version: 3.15w (20010315)";
5726 void adafinal () @{
5727    system__standard_library__adafinal ();
5728 @}
5729
5730 void adainit ()
5731 @{
5732    extern char ada__exceptions_E;
5733    extern char system__exceptions_E;
5734    extern char interfaces__c_streams_E;
5735    extern char system__exception_table_E;
5736    extern char ada__io_exceptions_E;
5737    extern char system__secondary_stack_E;
5738    extern char system__stack_checking_E;
5739    extern char system__soft_links_E;
5740    extern char ada__tags_E;
5741    extern char ada__streams_E;
5742    extern char system__finalization_root_E;
5743    extern char system__finalization_implementation_E;
5744    extern char ada__finalization_E;
5745    extern char ada__finalization__list_controller_E;
5746    extern char system__file_control_block_E;
5747    extern char system__file_io_E;
5748    extern char ada__text_io_E;
5749
5750    extern void *__gnat_hello__SDP;
5751    extern void *__gnat_ada__text_io__SDP;
5752    extern void *__gnat_ada__exceptions__SDP;
5753    extern void *__gnat_gnat__heap_sort_a__SDP;
5754    extern void *__gnat_system__exception_table__SDP;
5755    extern void *__gnat_system__machine_state_operations__SDP;
5756    extern void *__gnat_system__secondary_stack__SDP;
5757    extern void *__gnat_system__parameters__SDP;
5758    extern void *__gnat_system__soft_links__SDP;
5759    extern void *__gnat_system__stack_checking__SDP;
5760    extern void *__gnat_system__traceback__SDP;
5761    extern void *__gnat_ada__streams__SDP;
5762    extern void *__gnat_ada__tags__SDP;
5763    extern void *__gnat_system__string_ops__SDP;
5764    extern void *__gnat_interfaces__c_streams__SDP;
5765    extern void *__gnat_system__file_io__SDP;
5766    extern void *__gnat_ada__finalization__SDP;
5767    extern void *__gnat_system__finalization_root__SDP;
5768    extern void *__gnat_system__finalization_implementation__SDP;
5769    extern void *__gnat_system__string_ops_concat_3__SDP;
5770    extern void *__gnat_system__stream_attributes__SDP;
5771    extern void *__gnat_system__file_control_block__SDP;
5772    extern void *__gnat_ada__finalization__list_controller__SDP;
5773
5774    void **st[23] = @{
5775      &__gnat_hello__SDP,
5776      &__gnat_ada__text_io__SDP,
5777      &__gnat_ada__exceptions__SDP,
5778      &__gnat_gnat__heap_sort_a__SDP,
5779      &__gnat_system__exception_table__SDP,
5780      &__gnat_system__machine_state_operations__SDP,
5781      &__gnat_system__secondary_stack__SDP,
5782      &__gnat_system__parameters__SDP,
5783      &__gnat_system__soft_links__SDP,
5784      &__gnat_system__stack_checking__SDP,
5785      &__gnat_system__traceback__SDP,
5786      &__gnat_ada__streams__SDP,
5787      &__gnat_ada__tags__SDP,
5788      &__gnat_system__string_ops__SDP,
5789      &__gnat_interfaces__c_streams__SDP,
5790      &__gnat_system__file_io__SDP,
5791      &__gnat_ada__finalization__SDP,
5792      &__gnat_system__finalization_root__SDP,
5793      &__gnat_system__finalization_implementation__SDP,
5794      &__gnat_system__string_ops_concat_3__SDP,
5795      &__gnat_system__stream_attributes__SDP,
5796      &__gnat_system__file_control_block__SDP,
5797      &__gnat_ada__finalization__list_controller__SDP@};
5798
5799    extern void ada__exceptions___elabs ();
5800    extern void system__exceptions___elabs ();
5801    extern void interfaces__c_streams___elabs ();
5802    extern void system__exception_table___elabb ();
5803    extern void ada__io_exceptions___elabs ();
5804    extern void system__stack_checking___elabs ();
5805    extern void system__soft_links___elabb ();
5806    extern void system__secondary_stack___elabb ();
5807    extern void ada__tags___elabs ();
5808    extern void ada__tags___elabb ();
5809    extern void ada__streams___elabs ();
5810    extern void system__finalization_root___elabs ();
5811    extern void ada__exceptions___elabb ();
5812    extern void system__finalization_implementation___elabs ();
5813    extern void system__finalization_implementation___elabb ();
5814    extern void ada__finalization___elabs ();
5815    extern void ada__finalization__list_controller___elabs ();
5816    extern void system__file_control_block___elabs ();
5817    extern void system__file_io___elabb ();
5818    extern void ada__text_io___elabs ();
5819    extern void ada__text_io___elabb ();
5820
5821    void (*ea[23]) () = @{
5822      adainit,
5823      system__standard_library__adafinal,
5824      ada__exceptions___elabs,
5825      system__exceptions___elabs,
5826      interfaces__c_streams___elabs,
5827      system__exception_table___elabb,
5828      ada__io_exceptions___elabs,
5829      system__stack_checking___elabs,
5830      system__soft_links___elabb,
5831      system__secondary_stack___elabb,
5832      ada__tags___elabs,
5833      ada__tags___elabb,
5834      ada__streams___elabs,
5835      system__finalization_root___elabs,
5836      ada__exceptions___elabb,
5837      system__finalization_implementation___elabs,
5838      system__finalization_implementation___elabb,
5839      ada__finalization___elabs,
5840      ada__finalization__list_controller___elabs,
5841      system__file_control_block___elabs,
5842      system__file_io___elabb,
5843      ada__text_io___elabs,
5844      ada__text_io___elabb@};
5845
5846    __gnat_SDP_Table_Build (&st, 23, ea, 23);
5847    __gnat_set_globals (
5848       -1,      /* Main_Priority              */
5849       -1,      /* Time_Slice_Value           */
5850       'b',     /* WC_Encoding                */
5851       ' ',     /* Locking_Policy             */
5852       ' ',     /* Queuing_Policy             */
5853       ' ',     /* Tasking_Dispatching_Policy */
5854       0,       /* Finalization routine address, not used anymore */
5855       0,       /* Unreserve_All_Interrupts */
5856       0);      /* Exception_Tracebacks */
5857
5858    __gnat_inside_elab_final_code = 1;
5859
5860    if (ada__exceptions_E == 0) @{
5861       ada__exceptions___elabs ();
5862    @}
5863    if (system__exceptions_E == 0) @{
5864       system__exceptions___elabs ();
5865       system__exceptions_E++;
5866    @}
5867    if (interfaces__c_streams_E == 0) @{
5868       interfaces__c_streams___elabs ();
5869    @}
5870    interfaces__c_streams_E = 1;
5871    if (system__exception_table_E == 0) @{
5872       system__exception_table___elabb ();
5873       system__exception_table_E++;
5874    @}
5875    if (ada__io_exceptions_E == 0) @{
5876       ada__io_exceptions___elabs ();
5877       ada__io_exceptions_E++;
5878    @}
5879    if (system__stack_checking_E == 0) @{
5880       system__stack_checking___elabs ();
5881    @}
5882    if (system__soft_links_E == 0) @{
5883       system__soft_links___elabb ();
5884       system__soft_links_E++;
5885    @}
5886    system__stack_checking_E = 1;
5887    if (system__secondary_stack_E == 0) @{
5888       system__secondary_stack___elabb ();
5889       system__secondary_stack_E++;
5890    @}
5891    if (ada__tags_E == 0) @{
5892       ada__tags___elabs ();
5893    @}
5894    if (ada__tags_E == 0) @{
5895       ada__tags___elabb ();
5896       ada__tags_E++;
5897    @}
5898    if (ada__streams_E == 0) @{
5899       ada__streams___elabs ();
5900       ada__streams_E++;
5901    @}
5902    if (system__finalization_root_E == 0) @{
5903       system__finalization_root___elabs ();
5904    @}
5905    system__finalization_root_E = 1;
5906    if (ada__exceptions_E == 0) @{
5907       ada__exceptions___elabb ();
5908       ada__exceptions_E++;
5909    @}
5910    if (system__finalization_implementation_E == 0) @{
5911       system__finalization_implementation___elabs ();
5912    @}
5913    if (system__finalization_implementation_E == 0) @{
5914       system__finalization_implementation___elabb ();
5915       system__finalization_implementation_E++;
5916    @}
5917    if (ada__finalization_E == 0) @{
5918       ada__finalization___elabs ();
5919    @}
5920    ada__finalization_E = 1;
5921    if (ada__finalization__list_controller_E == 0) @{
5922       ada__finalization__list_controller___elabs ();
5923    @}
5924    ada__finalization__list_controller_E = 1;
5925    if (system__file_control_block_E == 0) @{
5926       system__file_control_block___elabs ();
5927       system__file_control_block_E++;
5928    @}
5929    if (system__file_io_E == 0) @{
5930       system__file_io___elabb ();
5931       system__file_io_E++;
5932    @}
5933    if (ada__text_io_E == 0) @{
5934       ada__text_io___elabs ();
5935    @}
5936    if (ada__text_io_E == 0) @{
5937       ada__text_io___elabb ();
5938       ada__text_io_E++;
5939    @}
5940
5941    __gnat_inside_elab_final_code = 0;
5942 @}
5943 int main (argc, argv, envp)
5944     int argc;
5945     char **argv;
5946     char **envp;
5947 @{
5948    gnat_argc = argc;
5949    gnat_argv = argv;
5950    gnat_envp = envp;
5951
5952    __gnat_initialize ();
5953    adainit ();
5954    __gnat_break_start ();
5955
5956    _ada_hello ();
5957
5958    system__standard_library__adafinal ();
5959    __gnat_finalize ();
5960    exit (gnat_exit_status);
5961 @}
5962 unsigned helloB = 0x7880BEB3;
5963 unsigned system__standard_libraryB = 0x0D24CBD0;
5964 unsigned system__standard_libraryS = 0x3283DBEB;
5965 unsigned adaS = 0x2359F9ED;
5966 unsigned ada__text_ioB = 0x47C85FC4;
5967 unsigned ada__text_ioS = 0x496FE45C;
5968 unsigned ada__exceptionsB = 0x74F50187;
5969 unsigned ada__exceptionsS = 0x6736945B;
5970 unsigned gnatS = 0x156A40CF;
5971 unsigned gnat__heap_sort_aB = 0x033DABE0;
5972 unsigned gnat__heap_sort_aS = 0x6AB38FEA;
5973 unsigned systemS = 0x0331C6FE;
5974 unsigned system__exceptionsS = 0x20C9ECA4;
5975 unsigned system__exception_tableB = 0x68A22947;
5976 unsigned system__exception_tableS = 0x394BADD5;
5977 unsigned gnat__htableB = 0x08258E1B;
5978 unsigned gnat__htableS = 0x367D5222;
5979 unsigned system__machine_state_operationsB = 0x4F3B7492;
5980 unsigned system__machine_state_operationsS = 0x182F5CF4;
5981 unsigned system__storage_elementsB = 0x2F1EB794;
5982 unsigned system__storage_elementsS = 0x102C83C7;
5983 unsigned system__secondary_stackB = 0x1574B6E9;
5984 unsigned system__secondary_stackS = 0x708E260A;
5985 unsigned system__parametersB = 0x56D770CD;
5986 unsigned system__parametersS = 0x237E39BE;
5987 unsigned system__soft_linksB = 0x08AB6B2C;
5988 unsigned system__soft_linksS = 0x1E2491F3;
5989 unsigned system__stack_checkingB = 0x476457A0;
5990 unsigned system__stack_checkingS = 0x5299FCED;
5991 unsigned system__tracebackB = 0x2971EBDE;
5992 unsigned system__tracebackS = 0x2E9C3122;
5993 unsigned ada__streamsS = 0x7C25DE96;
5994 unsigned ada__tagsB = 0x39ADFFA2;
5995 unsigned ada__tagsS = 0x769A0464;
5996 unsigned system__string_opsB = 0x5EB646AB;
5997 unsigned system__string_opsS = 0x63CED018;
5998 unsigned interfacesS = 0x0357E00A;
5999 unsigned interfaces__c_streamsB = 0x3784FB72;
6000 unsigned interfaces__c_streamsS = 0x2E723019;
6001 unsigned system__file_ioB = 0x623358EA;
6002 unsigned system__file_ioS = 0x31F873E6;
6003 unsigned ada__finalizationB = 0x6843F68A;
6004 unsigned ada__finalizationS = 0x63305874;
6005 unsigned system__finalization_rootB = 0x31E56CE1;
6006 unsigned system__finalization_rootS = 0x23169EF3;
6007 unsigned system__finalization_implementationB = 0x6CCBA70E;
6008 unsigned system__finalization_implementationS = 0x604AA587;
6009 unsigned system__string_ops_concat_3B = 0x572E3F58;
6010 unsigned system__string_ops_concat_3S = 0x01F57876;
6011 unsigned system__stream_attributesB = 0x1D4F93E8;
6012 unsigned system__stream_attributesS = 0x30B2EC3D;
6013 unsigned ada__io_exceptionsS = 0x34054F96;
6014 unsigned system__unsigned_typesS = 0x7B9E7FE3;
6015 unsigned system__file_control_blockS = 0x2FF876A8;
6016 unsigned ada__finalization__list_controllerB = 0x5760634A;
6017 unsigned ada__finalization__list_controllerS = 0x5D851835;
6018
6019 /* BEGIN ELABORATION ORDER
6020 ada (spec)
6021 gnat (spec)
6022 gnat.heap_sort_a (spec)
6023 gnat.htable (spec)
6024 gnat.htable (body)
6025 interfaces (spec)
6026 system (spec)
6027 system.parameters (spec)
6028 system.standard_library (spec)
6029 ada.exceptions (spec)
6030 system.exceptions (spec)
6031 system.parameters (body)
6032 gnat.heap_sort_a (body)
6033 interfaces.c_streams (spec)
6034 interfaces.c_streams (body)
6035 system.exception_table (spec)
6036 system.exception_table (body)
6037 ada.io_exceptions (spec)
6038 system.storage_elements (spec)
6039 system.storage_elements (body)
6040 system.machine_state_operations (spec)
6041 system.machine_state_operations (body)
6042 system.secondary_stack (spec)
6043 system.stack_checking (spec)
6044 system.soft_links (spec)
6045 system.soft_links (body)
6046 system.stack_checking (body)
6047 system.secondary_stack (body)
6048 system.standard_library (body)
6049 system.string_ops (spec)
6050 system.string_ops (body)
6051 ada.tags (spec)
6052 ada.tags (body)
6053 ada.streams (spec)
6054 system.finalization_root (spec)
6055 system.finalization_root (body)
6056 system.string_ops_concat_3 (spec)
6057 system.string_ops_concat_3 (body)
6058 system.traceback (spec)
6059 system.traceback (body)
6060 ada.exceptions (body)
6061 system.unsigned_types (spec)
6062 system.stream_attributes (spec)
6063 system.stream_attributes (body)
6064 system.finalization_implementation (spec)
6065 system.finalization_implementation (body)
6066 ada.finalization (spec)
6067 ada.finalization (body)
6068 ada.finalization.list_controller (spec)
6069 ada.finalization.list_controller (body)
6070 system.file_control_block (spec)
6071 system.file_io (spec)
6072 system.file_io (body)
6073 ada.text_io (spec)
6074 ada.text_io (body)
6075 hello (body)
6076    END ELABORATION ORDER */
6077
6078 /* BEGIN Object file/option list
6079 ./hello.o
6080 -L./
6081 -L/usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/
6082 /usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/libgnat.a
6083 -lexc
6084    END Object file/option list */
6085
6086 @end smallexample
6087
6088 @noindent
6089 Here again, the C code is exactly what is generated by the binder. The
6090 functions of the various parts of this code correspond in an obvious
6091 manner with the commented Ada code shown in the example in the previous
6092 section.
6093
6094 @node Consistency-Checking Modes
6095 @section Consistency-Checking Modes
6096
6097 @noindent
6098 As described in the previous section, by default @code{gnatbind} checks
6099 that object files are consistent with one another and are consistent
6100 with any source files it can locate. The following switches control binder
6101 access to sources.
6102
6103 @table @code
6104 @item -s
6105 @cindex @code{-s} (@code{gnatbind})
6106 Require source files to be present. In this mode, the binder must be
6107 able to locate all source files that are referenced, in order to check
6108 their consistency. In normal mode, if a source file cannot be located it
6109 is simply ignored. If you specify this switch, a missing source
6110 file is an error.
6111
6112 @item -x
6113 @cindex @code{-x} (@code{gnatbind})
6114 Exclude source files. In this mode, the binder only checks that ALI
6115 files are consistent with one another. Source files are not accessed.
6116 The binder runs faster in this mode, and there is still a guarantee that
6117 the resulting program is self-consistent.
6118 If a source file has been edited since it was last compiled, and you
6119 specify this switch, the binder will not detect that the object
6120 file is out of date with respect to the source file. Note that this is the
6121 mode that is automatically used by @code{gnatmake} because in this
6122 case the checking against sources has already been performed by
6123 @code{gnatmake} in the course of compilation (i.e. before binding).
6124
6125 @end table
6126
6127 @node Binder Error Message Control
6128 @section Binder Error Message Control
6129
6130 @noindent
6131 The following switches provide control over the generation of error
6132 messages from the binder:
6133
6134 @table @code
6135 @item -v
6136 @cindex @code{-v} (@code{gnatbind})
6137 Verbose mode. In the normal mode, brief error messages are generated to
6138 @file{stderr}. If this switch is present, a header is written
6139 to @file{stdout} and any error messages are directed to @file{stdout}.
6140 All that is written to @file{stderr} is a brief summary message.
6141
6142 @item -b
6143 @cindex @code{-b} (@code{gnatbind})
6144 Generate brief error messages to @file{stderr} even if verbose mode is
6145 specified. This is relevant only when used with the
6146 @code{-v} switch.
6147
6148 @item -m@var{n}
6149 @cindex @code{-m} (@code{gnatbind})
6150 Limits the number of error messages to @var{n}, a decimal integer in the
6151 range 1-999. The binder terminates immediately if this limit is reached.
6152
6153 @item -M@var{xxx}
6154 @cindex @code{-M} (@code{gnatbind})
6155 Renames the generated main program from @code{main} to @code{xxx}.
6156 This is useful in the case of some cross-building environments, where
6157 the actual main program is separate from the one generated
6158 by @code{gnatbind}.
6159
6160 @item -ws
6161 @cindex @code{-ws} (@code{gnatbind})
6162 @cindex Warnings
6163 Suppress all warning messages.
6164
6165 @item -we
6166 @cindex @code{-we} (@code{gnatbind})
6167 Treat any warning messages as fatal errors.
6168
6169
6170 @item -t
6171 @cindex @code{-t} (@code{gnatbind})
6172 @cindex Time stamp checks, in binder
6173 @cindex Binder consistency checks
6174 @cindex Consistency checks, in binder
6175 The binder performs a number of consistency checks including:
6176
6177 @itemize @bullet
6178 @item
6179 Check that time stamps of a given source unit are consistent
6180 @item
6181 Check that checksums of a given source unit are consistent
6182 @item
6183 Check that consistent versions of @code{GNAT} were used for compilation
6184 @item
6185 Check consistency of configuration pragmas as required
6186 @end itemize
6187
6188 @noindent
6189 Normally failure of such checks, in accordance with the consistency
6190 requirements of the Ada Reference Manual, causes error messages to be
6191 generated which abort the binder and prevent the output of a binder
6192 file and subsequent link to obtain an executable.
6193
6194 The @code{-t} switch converts these error messages
6195 into warnings, so that
6196 binding and linking can continue to completion even in the presence of such
6197 errors. The result may be a failed link (due to missing symbols), or a
6198 non-functional executable which has undefined semantics.
6199 @emph{This means that
6200 @code{-t} should be used only in unusual situations,
6201 with extreme care.}
6202 @end table
6203
6204 @node Elaboration Control
6205 @section Elaboration Control
6206
6207 @noindent
6208 The following switches provide additional control over the elaboration
6209 order. For full details see @xref{Elaboration Order Handling in GNAT}.
6210
6211 @table @code
6212 @item -p
6213 @cindex @code{-h} (@code{gnatbind})
6214 Normally the binder attempts to choose an elaboration order that is
6215 likely to minimize the likelihood of an elaboration order error resulting
6216 in raising a @code{Program_Error} exception. This switch reverses the
6217 action of the binder, and requests that it deliberately choose an order
6218 that is likely to maximize the likelihood of an elaboration error.
6219 This is useful in ensuring portability and avoiding dependence on
6220 accidental fortuitous elaboration ordering.
6221
6222 Normally it only makes sense to use the @code{-p} switch if dynamic
6223 elaboration checking is used (@option{-gnatE} switch used for compilation).
6224 This is because in the default static elaboration mode, all necessary
6225 @code{Elaborate_All} pragmas are implicitly inserted. These implicit
6226 pragmas are still respected by the binder in @code{-p} mode, so a
6227 safe elaboration order is assured.
6228 @end table
6229
6230 @node Output Control
6231 @section Output Control
6232
6233 @noindent
6234 The following switches allow additional control over the output
6235 generated by the binder.
6236
6237 @table @code
6238
6239 @item -A
6240 @cindex @code{-A} (@code{gnatbind})
6241 Generate binder program in Ada (default). The binder program is named
6242 @file{b~@var{mainprog}.adb} by default. This can be changed with
6243 @code{-o} @code{gnatbind} option.
6244
6245 @item -c
6246 @cindex @code{-c} (@code{gnatbind})
6247 Check only. Do not generate the binder output file. In this mode the
6248 binder performs all error checks but does not generate an output file.
6249
6250 @item -C
6251 @cindex @code{-C} (@code{gnatbind})
6252 Generate binder program in C. The binder program is named
6253 @file{b_@var{mainprog}.c}. This can be changed with @code{-o} @code{gnatbind}
6254 option.
6255
6256 @item -e
6257 @cindex @code{-e} (@code{gnatbind})
6258 Output complete list of elaboration-order dependencies, showing the
6259 reason for each dependency. This output can be rather extensive but may
6260 be useful in diagnosing problems with elaboration order. The output is
6261 written to @file{stdout}.
6262
6263 @item -h
6264 @cindex @code{-h} (@code{gnatbind})
6265 Output usage information. The output is written to @file{stdout}.
6266
6267 @item -K
6268 @cindex @code{-K} (@code{gnatbind})
6269 Output linker options to @file{stdout}. Includes library search paths,
6270 contents of pragmas Ident and Linker_Options, and libraries added
6271 by @code{gnatbind}.
6272
6273 @item -l
6274 @cindex @code{-l} (@code{gnatbind})
6275 Output chosen elaboration order. The output is written to @file{stdout}.
6276
6277 @item -O
6278 @cindex @code{-O} (@code{gnatbind})
6279 Output full names of all the object files that must be linked to provide
6280 the Ada component of the program. The output is written to @file{stdout}.
6281 This list includes the files explicitly supplied and referenced by the user
6282 as well as implicitly referenced run-time unit files. The latter are
6283 omitted if the corresponding units reside in shared libraries. The
6284 directory names for the run-time units depend on the system configuration.
6285
6286 @item -o @var{file}
6287 @cindex @code{-o} (@code{gnatbind})
6288 Set name of output file to @var{file} instead of the normal
6289 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
6290 binder generated body filename. In C mode you would normally give
6291 @var{file} an extension of @file{.c} because it will be a C source program.
6292 Note that if this option is used, then linking must be done manually.
6293 It is not possible to use gnatlink in this case, since it cannot locate
6294 the binder file.
6295
6296 @item -r
6297 @cindex @code{-r} (@code{gnatbind})
6298 Generate list of @code{pragma Rerstrictions} that could be applied to
6299 the current unit. This is useful for code audit purposes, and also may
6300 be used to improve code generation in some cases.
6301
6302 @end table
6303
6304 @node Binding with Non-Ada Main Programs
6305 @section Binding with Non-Ada Main Programs
6306
6307 @noindent
6308 In our description so far we have assumed that the main
6309 program is in Ada, and that the task of the binder is to generate a
6310 corresponding function @code{main} that invokes this Ada main
6311 program. GNAT also supports the building of executable programs where
6312 the main program is not in Ada, but some of the called routines are
6313 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
6314 The following switch is used in this situation:
6315
6316 @table @code
6317 @item -n
6318 @cindex @code{-n} (@code{gnatbind})
6319 No main program. The main program is not in Ada.
6320 @end table
6321
6322 @noindent
6323 In this case, most of the functions of the binder are still required,
6324 but instead of generating a main program, the binder generates a file
6325 containing the following callable routines:
6326
6327 @table @code
6328 @item adainit
6329 @findex adainit
6330 You must call this routine to initialize the Ada part of the program by
6331 calling the necessary elaboration routines. A call to @code{adainit} is
6332 required before the first call to an Ada subprogram.
6333
6334 Note that it is assumed that the basic execution environment must be setup
6335 to be appropriate for Ada execution at the point where the first Ada
6336 subprogram is called. In particular, if the Ada code will do any
6337 floating-point operations, then the FPU must be setup in an appropriate
6338 manner. For the case of the x86, for example, full precision mode is
6339 required. The procedure GNAT.Float_Control.Reset may be used to ensure
6340 that the FPU is in the right state.
6341
6342 @item adafinal
6343 @findex adafinal
6344 You must call this routine to perform any library-level finalization
6345 required by the Ada subprograms. A call to @code{adafinal} is required
6346 after the last call to an Ada subprogram, and before the program
6347 terminates.
6348 @end table
6349
6350 @noindent
6351 If the @code{-n} switch
6352 @cindex Binder, multiple input files
6353 is given, more than one ALI file may appear on
6354 the command line for @code{gnatbind}. The normal @dfn{closure}
6355 calculation is performed for each of the specified units. Calculating
6356 the closure means finding out the set of units involved by tracing
6357 @code{with} references. The reason it is necessary to be able to
6358 specify more than one ALI file is that a given program may invoke two or
6359 more quite separate groups of Ada units.
6360
6361 The binder takes the name of its output file from the last specified ALI
6362 file, unless overridden by the use of the @code{-o file}.
6363 The output is an Ada unit in source form that can
6364 be compiled with GNAT unless the -C switch is used in which case the
6365 output is a C source file, which must be compiled using the C compiler.
6366 This compilation occurs automatically as part of the @code{gnatlink}
6367 processing.
6368
6369 Currently the GNAT run time requires a FPU using 80 bits mode
6370 precision. Under targets where this is not the default it is required to
6371 call GNAT.Float_Control.Reset before using floating point numbers (this
6372 include float computation, float input and output) in the Ada code. A
6373 side effect is that this could be the wrong mode for the foreign code
6374 where floating point computation could be broken after this call.
6375
6376 @node Binding Programs with No Main Subprogram
6377 @section Binding Programs with No Main Subprogram
6378
6379 @noindent
6380 It is possible to have an Ada program which does not have a main
6381 subprogram. This program will call the elaboration routines of all the
6382 packages, then the finalization routines.
6383
6384 The following switch is used to bind programs organized in this manner:
6385
6386 @table @code
6387 @item -z
6388 @cindex @code{-z} (@code{gnatbind})
6389 Normally the binder checks that the unit name given on the command line
6390 corresponds to a suitable main subprogram. When this switch is used,
6391 a list of ALI files can be given, and the execution of the program
6392 consists of elaboration of these units in an appropriate order.
6393 @end table
6394
6395 @node Summary of Binder Switches
6396 @section Summary of Binder Switches
6397
6398 @noindent
6399 The following are the switches available with @code{gnatbind}:
6400
6401 @table @code
6402 @item -aO
6403 Specify directory to be searched for ALI files.
6404
6405 @item -aI
6406 Specify directory to be searched for source file.
6407
6408 @item -A
6409 Generate binder program in Ada (default)
6410
6411 @item -b
6412 Generate brief messages to @file{stderr} even if verbose mode set.
6413
6414 @item -c
6415 Check only, no generation of binder output file.
6416
6417 @item -C
6418 Generate binder program in C
6419
6420 @item -e
6421 Output complete list of elaboration-order dependencies.
6422
6423 @item -E
6424 Store tracebacks in exception occurrences when the target supports it.
6425 This is the default with the zero cost exception mechanism.
6426 This option is currently supported on the following targets:
6427 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
6428 See also the packages @code{GNAT.Traceback} and
6429 @code{GNAT.Traceback.Symbolic} for more information.
6430 Note that on x86 ports, you must not use @code{-fomit-frame-pointer}
6431 @code{gcc} option.
6432
6433 @item -h
6434 Output usage (help) information
6435
6436 @item -I
6437 Specify directory to be searched for source and ALI files.
6438
6439 @item -I-
6440 Do not look for sources in the current directory where @code{gnatbind} was
6441 invoked, and do not look for ALI files in the directory containing the
6442 ALI file named in the @code{gnatbind} command line.
6443
6444 @item -l
6445 Output chosen elaboration order.
6446
6447 @item -Lxxx
6448 Binds the units for library building. In this case the adainit and
6449 adafinal procedures (See @pxref{Binding with Non-Ada Main Programs})
6450 are renamed to xxxinit and xxxfinal. Implies -n.
6451 See @pxref{GNAT and Libraries} for more details.
6452
6453 @item -Mxyz
6454 Rename generated main program from main to xyz
6455
6456 @item -m@var{n}
6457 Limit number of detected errors to @var{n} (1-999).
6458
6459 @item -n
6460 No main program.
6461
6462 @item -nostdinc
6463 Do not look for sources in the system default directory.
6464
6465 @item -nostdlib
6466 Do not look for library files in the system default directory.
6467
6468 @item --RTS=@var{rts-path}
6469 @cindex @code{--RTS} (@code{gnatbind})
6470 Specifies the default location of the runtime library. Same meaning as the
6471 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
6472
6473 @item -o @var{file}
6474 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
6475 Note that if this option is used, then linking must be done manually,
6476 gnatlink cannot be used.
6477
6478 @item -O
6479 Output object list.
6480
6481 @item -p
6482 Pessimistic (worst-case) elaboration order
6483
6484 @item -s
6485 Require all source files to be present.
6486
6487 @item -static
6488 Link against a static GNAT run time.
6489
6490 @item -shared
6491 Link against a shared GNAT run time when available.
6492
6493 @item -t
6494 Tolerate time stamp and other consistency errors
6495
6496 @item -T@var{n}
6497 Set the time slice value to n microseconds. A value of zero means no time
6498 slicing and also indicates to the tasking run time to match as close as
6499 possible to the annex D requirements of the RM.
6500
6501 @item -v
6502 Verbose mode. Write error messages, header, summary output to
6503 @file{stdout}.
6504
6505 @item -w@var{x}
6506 Warning mode (@var{x}=s/e for suppress/treat as error)
6507
6508
6509 @item -x
6510 Exclude source files (check object consistency only).
6511
6512
6513 @item -z
6514 No main subprogram.
6515
6516 @end table
6517
6518 You may obtain this listing by running the program @code{gnatbind} with
6519 no arguments.
6520
6521 @node Command-Line Access
6522 @section Command-Line Access
6523
6524 @noindent
6525 The package @code{Ada.Command_Line} provides access to the command-line
6526 arguments and program name. In order for this interface to operate
6527 correctly, the two variables
6528
6529 @smallexample
6530 @group
6531 @cartouche
6532 int gnat_argc;
6533 char **gnat_argv;
6534 @end cartouche
6535 @end group
6536 @end smallexample
6537
6538 @noindent
6539 @findex gnat_argv
6540 @findex gnat_argc
6541 are declared in one of the GNAT library routines. These variables must
6542 be set from the actual @code{argc} and @code{argv} values passed to the
6543 main program. With no @code{n} present, @code{gnatbind}
6544 generates the C main program to automatically set these variables.
6545 If the @code{n} switch is used, there is no automatic way to
6546 set these variables. If they are not set, the procedures in
6547 @code{Ada.Command_Line} will not be available, and any attempt to use
6548 them will raise @code{Constraint_Error}. If command line access is
6549 required, your main program must set @code{gnat_argc} and
6550 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
6551 it.
6552
6553 @node Search Paths for gnatbind
6554 @section Search Paths for @code{gnatbind}
6555
6556 @noindent
6557 The binder takes the name of an ALI file as its argument and needs to
6558 locate source files as well as other ALI files to verify object consistency.
6559
6560 For source files, it follows exactly the same search rules as @code{gcc}
6561 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
6562 directories searched are:
6563
6564 @enumerate
6565 @item
6566 The directory containing the ALI file named in the command line, unless
6567 the switch @code{-I-} is specified.
6568
6569 @item
6570 All directories specified by @code{-I}
6571 switches on the @code{gnatbind}
6572 command line, in the order given.
6573
6574 @item
6575 @findex ADA_OBJECTS_PATH
6576 Each of the directories listed in the value of the
6577 @code{ADA_OBJECTS_PATH} environment variable.
6578 Construct this value
6579 exactly as the @code{PATH} environment variable: a list of directory
6580 names separated by colons (semicolons when working with the NT version
6581 of GNAT).
6582
6583 @item
6584 The content of the "ada_object_path" file which is part of the GNAT
6585 installation tree and is used to store standard libraries such as the
6586 GNAT Run Time Library (RTL) unless the switch @code{-nostdlib} is
6587 specified.
6588 @ref{Installing an Ada Library}
6589 @end enumerate
6590
6591 @noindent
6592 In the binder the switch @code{-I}
6593 is used to specify both source and
6594 library file paths. Use @code{-aI}
6595 instead if you want to specify
6596 source paths only, and @code{-aO}
6597 if you want to specify library paths
6598 only. This means that for the binder
6599 @code{-I}@var{dir} is equivalent to
6600 @code{-aI}@var{dir}
6601 @code{-aO}@var{dir}.
6602 The binder generates the bind file (a C language source file) in the
6603 current working directory.
6604
6605 @findex Ada
6606 @findex System
6607 @findex Interfaces
6608 @findex GNAT
6609 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
6610 children make up the GNAT Run-Time Library, together with the package
6611 GNAT and its children, which contain a set of useful additional
6612 library functions provided by GNAT. The sources for these units are
6613 needed by the compiler and are kept together in one directory. The ALI
6614 files and object files generated by compiling the RTL are needed by the
6615 binder and the linker and are kept together in one directory, typically
6616 different from the directory containing the sources. In a normal
6617 installation, you need not specify these directory names when compiling
6618 or binding. Either the environment variables or the built-in defaults
6619 cause these files to be found.
6620
6621 Besides simplifying access to the RTL, a major use of search paths is
6622 in compiling sources from multiple directories. This can make
6623 development environments much more flexible.
6624
6625 @node Examples of gnatbind Usage
6626 @section Examples of @code{gnatbind} Usage
6627
6628 @noindent
6629 This section contains a number of examples of using the GNAT binding
6630 utility @code{gnatbind}.
6631
6632 @table @code
6633 @item gnatbind hello
6634 The main program @code{Hello} (source program in @file{hello.adb}) is
6635 bound using the standard switch settings. The generated main program is
6636 @file{b~hello.adb}. This is the normal, default use of the binder.
6637
6638 @item gnatbind hello -o mainprog.adb
6639 The main program @code{Hello} (source program in @file{hello.adb}) is
6640 bound using the standard switch settings. The generated main program is
6641 @file{mainprog.adb} with the associated spec in
6642 @file{mainprog.ads}. Note that you must specify the body here not the
6643 spec, in the case where the output is in Ada. Note that if this option
6644 is used, then linking must be done manually, since gnatlink will not
6645 be able to find the generated file.
6646
6647 @item gnatbind main -C -o mainprog.c -x
6648 The main program @code{Main} (source program in
6649 @file{main.adb}) is bound, excluding source files from the
6650 consistency checking, generating
6651 the file @file{mainprog.c}.
6652
6653 @item gnatbind -x main_program -C -o mainprog.c
6654 This command is exactly the same as the previous example. Switches may
6655 appear anywhere in the command line, and single letter switches may be
6656 combined into a single switch.
6657
6658 @item gnatbind -n math dbase -C -o ada-control.c
6659 The main program is in a language other than Ada, but calls to
6660 subprograms in packages @code{Math} and @code{Dbase} appear. This call
6661 to @code{gnatbind} generates the file @file{ada-control.c} containing
6662 the @code{adainit} and @code{adafinal} routines to be called before and
6663 after accessing the Ada units.
6664 @end table
6665
6666 @node Linking Using gnatlink
6667 @chapter Linking Using @code{gnatlink}
6668 @findex gnatlink
6669
6670 @noindent
6671 This chapter discusses @code{gnatlink}, a utility program used to link
6672 Ada programs and build an executable file. This is a simple program
6673 that invokes the Unix linker (via the @code{gcc}
6674 command) with a correct list of object files and library references.
6675 @code{gnatlink} automatically determines the list of files and
6676 references for the Ada part of a program. It uses the binder file
6677 generated by the binder to determine this list.
6678
6679 @menu
6680 * Running gnatlink::
6681 * Switches for gnatlink::
6682 * Setting Stack Size from gnatlink::
6683 * Setting Heap Size from gnatlink::
6684 @end menu
6685
6686 @node Running gnatlink
6687 @section Running @code{gnatlink}
6688
6689 @noindent
6690 The form of the @code{gnatlink} command is
6691
6692 @smallexample
6693 $ gnatlink [@var{switches}] @var{mainprog}[.ali] [@var{non-Ada objects}]
6694       [@var{linker options}]
6695 @end smallexample
6696
6697 @noindent
6698 @file{@var{mainprog}.ali} references the ALI file of the main program.
6699 The @file{.ali} extension of this file can be omitted. From this
6700 reference, @code{gnatlink} locates the corresponding binder file
6701 @file{b~@var{mainprog}.adb} and, using the information in this file along
6702 with the list of non-Ada objects and linker options, constructs a Unix
6703 linker command file to create the executable.
6704
6705 The arguments following @file{@var{mainprog}.ali} are passed to the
6706 linker uninterpreted. They typically include the names of object files
6707 for units written in other languages than Ada and any library references
6708 required to resolve references in any of these foreign language units,
6709 or in @code{pragma Import} statements in any Ada units.
6710
6711 @var{linker options} is an optional list of linker specific
6712 switches. The default linker called by gnatlink is @var{gcc} which in
6713 turn calls the appropriate system linker usually called
6714 @var{ld}. Standard options for the linker such as @code{-lmy_lib} or
6715 @code{-Ldir} can be added as is. For options that are not recognized by
6716 @var{gcc} as linker options, the @var{gcc} switches @code{-Xlinker} or
6717 @code{-Wl,} shall be used. Refer to the GCC documentation for
6718 details. Here is an example showing how to generate a linker map
6719 assuming that the underlying linker is GNU ld:
6720
6721 @smallexample
6722 $ gnatlink my_prog -Wl,-Map,MAPFILE
6723 @end smallexample
6724
6725 Using @var{linker options} it is possible to set the program stack and
6726 heap size. See @pxref{Setting Stack Size from gnatlink} and
6727 @pxref{Setting Heap Size from gnatlink}.
6728
6729 @code{gnatlink} determines the list of objects required by the Ada
6730 program and prepends them to the list of objects passed to the linker.
6731 @code{gnatlink} also gathers any arguments set by the use of
6732 @code{pragma Linker_Options} and adds them to the list of arguments
6733 presented to the linker.
6734
6735
6736 @node Switches for gnatlink
6737 @section Switches for @code{gnatlink}
6738
6739 @noindent
6740 The following switches are available with the @code{gnatlink} utility:
6741
6742 @table @code
6743
6744 @item -A
6745 @cindex @code{-A} (@code{gnatlink})
6746 The binder has generated code in Ada. This is the default.
6747
6748 @item -C
6749 @cindex @code{-C} (@code{gnatlink})
6750 If instead of generating a file in Ada, the binder has generated one in
6751 C, then the linker needs to know about it. Use this switch to signal
6752 to @code{gnatlink} that the binder has generated C code rather than
6753 Ada code.
6754
6755 @item -f
6756 @cindex Command line length
6757 @cindex @code{-f} (@code{gnatlink})
6758 On some targets, the command line length is limited, and @code{gnatlink}
6759 will generate a separate file for the linker if the list of object files
6760 is too long. The @code{-f} flag forces this file to be generated even if
6761 the limit is not exceeded. This is useful in some cases to deal with
6762 special situations where the command line length is exceeded.
6763
6764 @item -g
6765 @cindex Debugging information, including
6766 @cindex @code{-g} (@code{gnatlink})
6767 The option to include debugging information causes the Ada bind file (in
6768 other words, @file{b~@var{mainprog}.adb}) to be compiled with
6769 @code{-g}.
6770 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
6771 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
6772 Without @code{-g}, the binder removes these files by
6773 default. The same procedure apply if a C bind file was generated using
6774 @code{-C} @code{gnatbind} option, in this case the filenames are
6775 @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
6776
6777 @item -n
6778 @cindex @code{-n} (@code{gnatlink})
6779 Do not compile the file generated by the binder. This may be used when
6780 a link is rerun with different options, but there is no need to recompile
6781 the binder file.
6782
6783 @item -v
6784 @cindex @code{-v} (@code{gnatlink})
6785 Causes additional information to be output, including a full list of the
6786 included object files. This switch option is most useful when you want
6787 to see what set of object files are being used in the link step.
6788
6789 @item -v -v
6790 @cindex @code{-v -v} (@code{gnatlink})
6791 Very verbose mode. Requests that the compiler operate in verbose mode when
6792 it compiles the binder file, and that the system linker run in verbose mode.
6793
6794 @item -o @var{exec-name}
6795 @cindex @code{-o} (@code{gnatlink})
6796 @var{exec-name} specifies an alternate name for the generated
6797 executable program. If this switch is omitted, the executable has the same
6798 name as the main unit. For example, @code{gnatlink try.ali} creates
6799 an executable called @file{try}.
6800
6801 @item -b @var{target}
6802 @cindex @code{-b} (@code{gnatlink})
6803 Compile your program to run on @var{target}, which is the name of a
6804 system configuration. You must have a GNAT cross-compiler built if
6805 @var{target} is not the same as your host system.
6806
6807 @item -B@var{dir}
6808 @cindex @code{-B} (@code{gnatlink})
6809 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
6810 from @var{dir} instead of the default location. Only use this switch
6811 when multiple versions of the GNAT compiler are available. See the
6812 @code{gcc} manual page for further details. You would normally use the
6813 @code{-b} or @code{-V} switch instead.
6814
6815 @item --GCC=@var{compiler_name}
6816 @cindex @code{--GCC=compiler_name} (@code{gnatlink})
6817 Program used for compiling the binder file. The default is
6818 `@code{gcc}'. You need to use quotes around @var{compiler_name} if
6819 @code{compiler_name} contains spaces or other separator characters. As
6820 an example @code{--GCC="foo -x -y"} will instruct @code{gnatlink} to use
6821 @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
6822 inserted after your command name. Thus in the above example the compiler
6823 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
6824 If several @code{--GCC=compiler_name} are used, only the last
6825 @var{compiler_name} is taken into account. However, all the additional
6826 switches are also taken into account. Thus,
6827 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
6828 @code{--GCC="bar -x -y -z -t"}.
6829
6830 @item --LINK=@var{name}
6831 @cindex @code{--LINK=} (@code{gnatlink})
6832 @var{name} is the name of the linker to be invoked. This is especially
6833 useful in mixed language programs since languages such as c++ require
6834 their own linker to be used. When this switch is omitted, the default
6835 name for the linker is (@file{gcc}). When this switch is used, the
6836 specified linker is called instead of (@file{gcc}) with exactly the same
6837 parameters that would have been passed to (@file{gcc}) so if the desired
6838 linker requires different parameters it is necessary to use a wrapper
6839 script that massages the parameters before invoking the real linker. It
6840 may be useful to control the exact invocation by using the verbose
6841 switch.
6842
6843
6844
6845 @end table
6846
6847 @node Setting Stack Size from gnatlink
6848 @section Setting Stack Size from @code{gnatlink}
6849
6850 @noindent
6851 It is possible to specify the program stack size from @code{gnatlink}.
6852 Assuming that the underlying linker is GNU ld there is two ways to do so:
6853
6854 @itemize @bullet
6855
6856 @item using @code{-Xlinker} linker option
6857
6858 @smallexample
6859 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
6860 @end smallexample
6861
6862 This set the stack reserve size to 0x10000 bytes and the stack commit
6863 size to 0x1000 bytes.
6864
6865 @item using @code{-Wl} linker option
6866
6867 @smallexample
6868 $ gnatlink hello -Wl,--stack=0x1000000
6869 @end smallexample
6870
6871 This set the stack reserve size to 0x1000000 bytes. Note that with
6872 @code{-Wl} option it is not possible to set the stack commit size
6873 because the coma is a separator for this option.
6874
6875 @end itemize
6876
6877 @node Setting Heap Size from gnatlink
6878 @section Setting Heap Size from @code{gnatlink}
6879
6880 @noindent
6881 It is possible to specify the program heap size from @code{gnatlink}.
6882 Assuming that the underlying linker is GNU ld there is two ways to do so:
6883
6884 @itemize @bullet
6885
6886 @item using @code{-Xlinker} linker option
6887
6888 @smallexample
6889 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
6890 @end smallexample
6891
6892 This set the heap reserve size to 0x10000 bytes and the heap commit
6893 size to 0x1000 bytes.
6894
6895 @item using @code{-Wl} linker option
6896
6897 @smallexample
6898 $ gnatlink hello -Wl,--heap=0x1000000
6899 @end smallexample
6900
6901 This set the heap reserve size to 0x1000000 bytes. Note that with
6902 @code{-Wl} option it is not possible to set the heap commit size
6903 because the coma is a separator for this option.
6904
6905 @end itemize
6906
6907 @node The GNAT Make Program gnatmake
6908 @chapter The GNAT Make Program @code{gnatmake}
6909 @findex gnatmake
6910
6911 @menu
6912 * Running gnatmake::
6913 * Switches for gnatmake::
6914 * Mode Switches for gnatmake::
6915 * Notes on the Command Line::
6916 * How gnatmake Works::
6917 * Examples of gnatmake Usage::
6918 @end menu
6919 @noindent
6920 A typical development cycle when working on an Ada program consists of
6921 the following steps:
6922
6923 @enumerate
6924 @item
6925 Edit some sources to fix bugs.
6926
6927 @item
6928 Add enhancements.
6929
6930 @item
6931 Compile all sources affected.
6932
6933 @item
6934 Rebind and relink.
6935
6936 @item
6937 Test.
6938 @end enumerate
6939
6940 @noindent
6941 The third step can be tricky, because not only do the modified files
6942 @cindex Dependency rules
6943 have to be compiled, but any files depending on these files must also be
6944 recompiled. The dependency rules in Ada can be quite complex, especially
6945 in the presence of overloading, @code{use} clauses, generics and inlined
6946 subprograms.
6947
6948 @code{gnatmake} automatically takes care of the third and fourth steps
6949 of this process. It determines which sources need to be compiled,
6950 compiles them, and binds and links the resulting object files.
6951
6952 Unlike some other Ada make programs, the dependencies are always
6953 accurately recomputed from the new sources. The source based approach of
6954 the GNAT compilation model makes this possible. This means that if
6955 changes to the source program cause corresponding changes in
6956 dependencies, they will always be tracked exactly correctly by
6957 @code{gnatmake}.
6958
6959 @node Running gnatmake
6960 @section Running @code{gnatmake}
6961
6962 @noindent
6963 The usual form of the @code{gnatmake} command is
6964
6965 @smallexample
6966 $ gnatmake [@var{switches}] @var{file_name} [@var{file_names}] [@var{mode_switches}]
6967 @end smallexample
6968
6969 @noindent
6970 The only required argument is one @var{file_name}, which specifies
6971 a compilation unit that is a main program. Several @var{file_names} can be
6972 specified: this will result in several executables being built.
6973 If @code{switches} are present, they can be placed before the first
6974 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
6975 If @var{mode_switches} are present, they must always be placed after
6976 the last @var{file_name} and all @code{switches}.
6977
6978 If you are using standard file extensions (.adb and .ads), then the
6979 extension may be omitted from the @var{file_name} arguments. However, if
6980 you are using non-standard extensions, then it is required that the
6981 extension be given. A relative or absolute directory path can be
6982 specified in a @var{file_name}, in which case, the input source file will
6983 be searched for in the specified directory only. Otherwise, the input
6984 source file will first be searched in the directory where
6985 @code{gnatmake} was invoked and if it is not found, it will be search on
6986 the source path of the compiler as described in
6987 @ref{Search Paths and the Run-Time Library (RTL)}.
6988
6989 When several @var{file_names} are specified, if an executable needs to be
6990 rebuilt and relinked, all subsequent executables will be rebuilt and
6991 relinked, even if this would not be absolutely necessary.
6992
6993 All @code{gnatmake} output (except when you specify
6994 @code{-M}) is to
6995 @file{stderr}. The output produced by the
6996 @code{-M} switch is send to
6997 @file{stdout}.
6998
6999 @node Switches for gnatmake
7000 @section Switches for @code{gnatmake}
7001
7002 @noindent
7003 You may specify any of the following switches to @code{gnatmake}:
7004
7005 @table @code
7006 @item --GCC=@var{compiler_name}
7007 @cindex @code{--GCC=compiler_name} (@code{gnatmake})
7008 Program used for compiling. The default is `@code{gcc}'. You need to use
7009 quotes around @var{compiler_name} if @code{compiler_name} contains
7010 spaces or other separator characters. As an example @code{--GCC="foo -x
7011 -y"} will instruct @code{gnatmake} to use @code{foo -x -y} as your
7012 compiler. Note that switch @code{-c} is always inserted after your
7013 command name. Thus in the above example the compiler command that will
7014 be used by @code{gnatmake} will be @code{foo -c -x -y}.
7015 If several @code{--GCC=compiler_name} are used, only the last
7016 @var{compiler_name} is taken into account. However, all the additional
7017 switches are also taken into account. Thus,
7018 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7019 @code{--GCC="bar -x -y -z -t"}.
7020
7021 @item --GNATBIND=@var{binder_name}
7022 @cindex @code{--GNATBIND=binder_name} (@code{gnatmake})
7023 Program used for binding. The default is `@code{gnatbind}'. You need to
7024 use quotes around @var{binder_name} if @var{binder_name} contains spaces
7025 or other separator characters. As an example @code{--GNATBIND="bar -x
7026 -y"} will instruct @code{gnatmake} to use @code{bar -x -y} as your
7027 binder. Binder switches that are normally appended by @code{gnatmake} to
7028 `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
7029
7030 @item --GNATLINK=@var{linker_name}
7031 @cindex @code{--GNATLINK=linker_name} (@code{gnatmake})
7032 Program used for linking. The default is `@code{gnatlink}'. You need to
7033 use quotes around @var{linker_name} if @var{linker_name} contains spaces
7034 or other separator characters. As an example @code{--GNATLINK="lan -x
7035 -y"} will instruct @code{gnatmake} to use @code{lan -x -y} as your
7036 linker. Linker switches that are normally appended by @code{gnatmake} to
7037 `@code{gnatlink}' are now appended to the end of @code{lan -x -y}.
7038
7039
7040 @item -a
7041 @cindex @code{-a} (@code{gnatmake})
7042 Consider all files in the make process, even the GNAT internal system
7043 files (for example, the predefined Ada library files), as well as any
7044 locked files. Locked files are files whose ALI file is write-protected.
7045 By default,
7046 @code{gnatmake} does not check these files,
7047 because the assumption is that the GNAT internal files are properly up
7048 to date, and also that any write protected ALI files have been properly
7049 installed. Note that if there is an installation problem, such that one
7050 of these files is not up to date, it will be properly caught by the
7051 binder.
7052 You may have to specify this switch if you are working on GNAT
7053 itself. @code{-a} is also useful in conjunction with
7054 @code{-f}
7055 if you need to recompile an entire application,
7056 including run-time files, using special configuration pragma settings,
7057 such as a non-standard @code{Float_Representation} pragma.
7058 By default
7059 @code{gnatmake -a} compiles all GNAT
7060 internal files with
7061 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
7062
7063 @item -b
7064 @cindex @code{-b} (@code{gnatmake})
7065 Bind only. Can be combined with @code{-c} to do compilation
7066 and binding, but no link. Can be combined with @code{-l}
7067 to do binding and linking. When not combined with @code{-c}
7068 all the units in the closure of the main program must have been previously
7069 compiled and must be up to date. The root unit specified by @var{file_name}
7070 may be given without extension, with the source extension or, if no GNAT
7071 Project File is specified, with the ALI file extension.
7072
7073 @item -c
7074 @cindex @code{-c} (@code{gnatmake})
7075 Compile only. Do not perform binding, except when @code{-b}
7076 is also specified. Do not perform linking, except if both
7077 @code{-b} and
7078  @code{-l} are also specified.
7079 If the root unit specified by @var{file_name} is not a main unit, this is the
7080 default. Otherwise @code{gnatmake} will attempt binding and linking
7081 unless all objects are up to date and the executable is more recent than
7082 the objects.
7083
7084 @item -C
7085 @cindex @code{-C} (@code{gnatmake})
7086 Use a mapping file. A mapping file is a way to communicate to the compiler
7087 two mappings: from unit names to file names (without any directory information)
7088 and from file names to path names (with full directory information).
7089 These mappings are used by the compiler to short-circuit the path search.
7090 When @code{gnatmake} is invoked with this switch, it will create a mapping
7091 file, initially populated by the project manager, if @code{-P} is used,
7092 otherwise initially empty. Each invocation of the compiler will add the newly
7093 accessed sources to the mapping file. This will improve the source search
7094 during the next invocation of the compiler.
7095
7096 @item -f
7097 @cindex @code{-f} (@code{gnatmake})
7098 Force recompilations. Recompile all sources, even though some object
7099 files may be up to date, but don't recompile predefined or GNAT internal
7100 files or locked files (files with a write-protected ALI file),
7101 unless the @code{-a} switch is also specified.
7102
7103 @item
7104 @item -i
7105 @cindex @code{-i} (@code{gnatmake})
7106 In normal mode, @code{gnatmake} compiles all object files and ALI files
7107 into the current directory. If the @code{-i} switch is used,
7108 then instead object files and ALI files that already exist are overwritten
7109 in place. This means that once a large project is organized into separate
7110 directories in the desired manner, then @code{gnatmake} will automatically
7111 maintain and update this organization. If no ALI files are found on the
7112 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
7113 the new object and ALI files are created in the
7114 directory containing the source being compiled. If another organization
7115 is desired, where objects and sources are kept in different directories,
7116 a useful technique is to create dummy ALI files in the desired directories.
7117 When detecting such a dummy file, @code{gnatmake} will be forced to recompile
7118 the corresponding source file, and it will be put the resulting object
7119 and ALI files in the directory where it found the dummy file.
7120
7121 @item -j@var{n}
7122 @cindex @code{-j} (@code{gnatmake})
7123 @cindex Parallel make
7124 Use @var{n} processes to carry out the (re)compilations. On a
7125 multiprocessor machine compilations will occur in parallel. In the
7126 event of compilation errors, messages from various compilations might
7127 get interspersed (but @code{gnatmake} will give you the full ordered
7128 list of failing compiles at the end). If this is problematic, rerun
7129 the make process with n set to 1 to get a clean list of messages.
7130
7131 @item -k
7132 @cindex @code{-k} (@code{gnatmake})
7133 Keep going. Continue as much as possible after a compilation error. To
7134 ease the programmer's task in case of compilation errors, the list of
7135 sources for which the compile fails is given when @code{gnatmake}
7136 terminates.
7137
7138 If @code{gnatmake} is invoked with several @file{file_names} and with this
7139 switch, if there are compilation errors when building an executable,
7140 @code{gnatmake} will not attempt to build the following executables.
7141
7142 @item -l
7143 @cindex @code{-l} (@code{gnatmake})
7144 Link only. Can be combined with @code{-b} to binding
7145 and linking. Linking will not be performed if combined with
7146 @code{-c}
7147 but not with @code{-b}.
7148 When not combined with @code{-b}
7149 all the units in the closure of the main program must have been previously
7150 compiled and must be up to date, and the main program need to have been bound.
7151 The root unit specified by @var{file_name}
7152 may be given without extension, with the source extension or, if no GNAT
7153 Project File is specified, with the ALI file extension.
7154
7155 @item -m
7156 @cindex @code{-m} (@code{gnatmake})
7157 Specifies that the minimum necessary amount of recompilations
7158 be performed. In this mode @code{gnatmake} ignores time
7159 stamp differences when the only
7160 modifications to a source file consist in adding/removing comments,
7161 empty lines, spaces or tabs. This means that if you have changed the
7162 comments in a source file or have simply reformatted it, using this
7163 switch will tell gnatmake not to recompile files that depend on it
7164 (provided other sources on which these files depend have undergone no
7165 semantic modifications). Note that the debugging information may be
7166 out of date with respect to the sources if the @code{-m} switch causes
7167 a compilation to be switched, so the use of this switch represents a
7168 trade-off between compilation time and accurate debugging information.
7169
7170 @item -M
7171 @cindex Dependencies, producing list
7172 @cindex @code{-M} (@code{gnatmake})
7173 Check if all objects are up to date. If they are, output the object
7174 dependences to @file{stdout} in a form that can be directly exploited in
7175 a @file{Makefile}. By default, each source file is prefixed with its
7176 (relative or absolute) directory name. This name is whatever you
7177 specified in the various @code{-aI}
7178 and @code{-I} switches. If you use
7179 @code{gnatmake -M}
7180 @code{-q}
7181 (see below), only the source file names,
7182 without relative paths, are output. If you just specify the
7183 @code{-M}
7184 switch, dependencies of the GNAT internal system files are omitted. This
7185 is typically what you want. If you also specify
7186 the @code{-a} switch,
7187 dependencies of the GNAT internal files are also listed. Note that
7188 dependencies of the objects in external Ada libraries (see switch
7189 @code{-aL}@var{dir} in the following list) are never reported.
7190
7191 @item -n
7192 @cindex @code{-n} (@code{gnatmake})
7193 Don't compile, bind, or link. Checks if all objects are up to date.
7194 If they are not, the full name of the first file that needs to be
7195 recompiled is printed.
7196 Repeated use of this option, followed by compiling the indicated source
7197 file, will eventually result in recompiling all required units.
7198
7199 @item -o @var{exec_name}
7200 @cindex @code{-o} (@code{gnatmake})
7201 Output executable name. The name of the final executable program will be
7202 @var{exec_name}. If the @code{-o} switch is omitted the default
7203 name for the executable will be the name of the input file in appropriate form
7204 for an executable file on the host system.
7205
7206 This switch cannot be used when invoking @code{gnatmake} with several
7207 @file{file_names}.
7208
7209 @item -q
7210 @cindex @code{-q} (@code{gnatmake})
7211 Quiet. When this flag is not set, the commands carried out by
7212 @code{gnatmake} are displayed.
7213
7214 @item -s
7215 @cindex @code{-s} (@code{gnatmake})
7216 Recompile if compiler switches have changed since last compilation.
7217 All compiler switches but -I and -o are taken into account in the
7218 following way:
7219 orders between different ``first letter'' switches are ignored, but
7220 orders between same switches are taken into account. For example,
7221 @code{-O -O2} is different than @code{-O2 -O}, but @code{-g -O} is equivalent
7222 to @code{-O -g}.
7223
7224 @item -u
7225 @cindex @code{-u} (@code{gnatmake})
7226 Unique. Recompile at most the main file. It implies -c. Combined with
7227 -f, it is equivalent to calling the compiler directly.
7228
7229 @item -v
7230 @cindex @code{-v} (@code{gnatmake})
7231 Verbose. Displays the reason for all recompilations @code{gnatmake}
7232 decides are necessary.
7233
7234 @item -z
7235 @cindex @code{-z} (@code{gnatmake})
7236 No main subprogram. Bind and link the program even if the unit name
7237 given on the command line is a package name. The resulting executable
7238 will execute the elaboration routines of the package and its closure,
7239 then the finalization routines.
7240
7241 @item @code{gcc} @asis{switches}
7242 The switch @code{-g} or any uppercase switch (other than @code{-A},
7243 @code{-L} or
7244 @code{-S}) or any switch that is more than one character is passed to
7245 @code{gcc} (e.g. @code{-O}, @option{-gnato,} etc.)
7246 @end table
7247
7248 @noindent
7249 Source and library search path switches:
7250
7251 @table @code
7252 @item -aI@var{dir}
7253 @cindex @code{-aI} (@code{gnatmake})
7254 When looking for source files also look in directory @var{dir}.
7255 The order in which source files search is undertaken is
7256 described in @ref{Search Paths and the Run-Time Library (RTL)}.
7257
7258 @item -aL@var{dir}
7259 @cindex @code{-aL} (@code{gnatmake})
7260 Consider @var{dir} as being an externally provided Ada library.
7261 Instructs @code{gnatmake} to skip compilation units whose @file{.ali}
7262 files have been located in directory @var{dir}. This allows you to have
7263 missing bodies for the units in @var{dir} and to ignore out of date bodies
7264 for the same units. You still need to specify
7265 the location of the specs for these units by using the switches
7266 @code{-aI@var{dir}}
7267 or @code{-I@var{dir}}.
7268 Note: this switch is provided for compatibility with previous versions
7269 of @code{gnatmake}. The easier method of causing standard libraries
7270 to be excluded from consideration is to write-protect the corresponding
7271 ALI files.
7272
7273 @item -aO@var{dir}
7274 @cindex @code{-aO} (@code{gnatmake})
7275 When searching for library and object files, look in directory
7276 @var{dir}. The order in which library files are searched is described in
7277 @ref{Search Paths for gnatbind}.
7278
7279 @item -A@var{dir}
7280 @cindex Search paths, for @code{gnatmake}
7281 @cindex @code{-A} (@code{gnatmake})
7282 Equivalent to @code{-aL@var{dir}
7283 -aI@var{dir}}.
7284
7285 @item -I@var{dir}
7286 @cindex @code{-I} (@code{gnatmake})
7287 Equivalent to @code{-aO@var{dir}
7288 -aI@var{dir}}.
7289
7290 @item -I-
7291 @cindex @code{-I-} (@code{gnatmake})
7292 @cindex Source files, suppressing search
7293 Do not look for source files in the directory containing the source
7294 file named in the command line.
7295 Do not look for ALI or object files in the directory
7296 where @code{gnatmake} was invoked.
7297
7298 @item -L@var{dir}
7299 @cindex @code{-L} (@code{gnatmake})
7300 @cindex Linker libraries
7301 Add directory @var{dir} to the list of directories in which the linker
7302 will search for libraries. This is equivalent to
7303 @code{-largs -L}@var{dir}.
7304
7305 @item -nostdinc
7306 @cindex @code{-nostdinc} (@code{gnatmake})
7307 Do not look for source files in the system default directory.
7308
7309 @item -nostdlib
7310 @cindex @code{-nostdlib} (@code{gnatmake})
7311 Do not look for library files in the system default directory.
7312
7313 @item --RTS=@var{rts-path}
7314 @cindex @code{--RTS} (@code{gnatmake})
7315 Specifies the default location of the runtime library. We look for the runtime
7316 in the following directories, and stop as soon as a valid runtime is found
7317 ("adainclude" or "ada_source_path", and "adalib" or "ada_object_path" present):
7318
7319 @itemize @bullet
7320 @item <current directory>/$rts_path
7321
7322 @item <default-search-dir>/$rts_path
7323
7324 @item <default-search-dir>/rts-$rts_path
7325 @end itemize
7326
7327 @noindent
7328 The selected path is handled like a normal RTS path.
7329
7330 @end table
7331
7332 @node Mode Switches for gnatmake
7333 @section Mode Switches for @code{gnatmake}
7334
7335 @noindent
7336 The mode switches (referred to as @code{mode_switches}) allow the
7337 inclusion of switches that are to be passed to the compiler itself, the
7338 binder or the linker. The effect of a mode switch is to cause all
7339 subsequent switches up to the end of the switch list, or up to the next
7340 mode switch, to be interpreted as switches to be passed on to the
7341 designated component of GNAT.
7342
7343 @table @code
7344 @item -cargs @var{switches}
7345 @cindex @code{-cargs} (@code{gnatmake})
7346 Compiler switches. Here @var{switches} is a list of switches
7347 that are valid switches for @code{gcc}. They will be passed on to
7348 all compile steps performed by @code{gnatmake}.
7349
7350 @item -bargs @var{switches}
7351 @cindex @code{-bargs} (@code{gnatmake})
7352 Binder switches. Here @var{switches} is a list of switches
7353 that are valid switches for @code{gcc}. They will be passed on to
7354 all bind steps performed by @code{gnatmake}.
7355
7356 @item -largs @var{switches}
7357 @cindex @code{-largs} (@code{gnatmake})
7358 Linker switches. Here @var{switches} is a list of switches
7359 that are valid switches for @code{gcc}. They will be passed on to
7360 all link steps performed by @code{gnatmake}.
7361 @end table
7362
7363 @node Notes on the Command Line
7364 @section Notes on the Command Line
7365
7366 @noindent
7367 This section contains some additional useful notes on the operation
7368 of the @code{gnatmake} command.
7369
7370 @itemize @bullet
7371 @item
7372 @cindex Recompilation, by @code{gnatmake}
7373 If @code{gnatmake} finds no ALI files, it recompiles the main program
7374 and all other units required by the main program.
7375 This means that @code{gnatmake}
7376 can be used for the initial compile, as well as during subsequent steps of
7377 the development cycle.
7378
7379 @item
7380 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
7381 is a subunit or body of a generic unit, @code{gnatmake} recompiles
7382 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
7383 warning.
7384
7385 @item
7386 In @code{gnatmake} the switch @code{-I}
7387 is used to specify both source and
7388 library file paths. Use @code{-aI}
7389 instead if you just want to specify
7390 source paths only and @code{-aO}
7391 if you want to specify library paths
7392 only.
7393
7394 @item
7395 @code{gnatmake} examines both an ALI file and its corresponding object file
7396 for consistency. If an ALI is more recent than its corresponding object,
7397 or if the object file is missing, the corresponding source will be recompiled.
7398 Note that @code{gnatmake} expects an ALI and the corresponding object file
7399 to be in the same directory.
7400
7401 @item
7402 @code{gnatmake} will ignore any files whose ALI file is write-protected.
7403 This may conveniently be used to exclude standard libraries from
7404 consideration and in particular it means that the use of the
7405 @code{-f} switch will not recompile these files
7406 unless @code{-a} is also specified.
7407
7408 @item
7409 @code{gnatmake} has been designed to make the use of Ada libraries
7410 particularly convenient. Assume you have an Ada library organized
7411 as follows: @var{obj-dir} contains the objects and ALI files for
7412 of your Ada compilation units,
7413 whereas @var{include-dir} contains the
7414 specs of these units, but no bodies. Then to compile a unit
7415 stored in @code{main.adb}, which uses this Ada library you would just type
7416
7417 @smallexample
7418 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
7419 @end smallexample
7420
7421 @item
7422 Using @code{gnatmake} along with the
7423 @code{-m (minimal recompilation)}
7424 switch provides a mechanism for avoiding unnecessary rcompilations. Using
7425 this switch,
7426 you can update the comments/format of your
7427 source files without having to recompile everything. Note, however, that
7428 adding or deleting lines in a source files may render its debugging
7429 info obsolete. If the file in question is a spec, the impact is rather
7430 limited, as that debugging info will only be useful during the
7431 elaboration phase of your program. For bodies the impact can be more
7432 significant. In all events, your debugger will warn you if a source file
7433 is more recent than the corresponding object, and alert you to the fact
7434 that the debugging information may be out of date.
7435 @end itemize
7436
7437 @node How gnatmake Works
7438 @section How @code{gnatmake} Works
7439
7440 @noindent
7441 Generally @code{gnatmake} automatically performs all necessary
7442 recompilations and you don't need to worry about how it works. However,
7443 it may be useful to have some basic understanding of the @code{gnatmake}
7444 approach and in particular to understand how it uses the results of
7445 previous compilations without incorrectly depending on them.
7446
7447 First a definition: an object file is considered @dfn{up to date} if the
7448 corresponding ALI file exists and its time stamp predates that of the
7449 object file and if all the source files listed in the
7450 dependency section of this ALI file have time stamps matching those in
7451 the ALI file. This means that neither the source file itself nor any
7452 files that it depends on have been modified, and hence there is no need
7453 to recompile this file.
7454
7455 @code{gnatmake} works by first checking if the specified main unit is up
7456 to date. If so, no compilations are required for the main unit. If not,
7457 @code{gnatmake} compiles the main program to build a new ALI file that
7458 reflects the latest sources. Then the ALI file of the main unit is
7459 examined to find all the source files on which the main program depends,
7460 and @code{gnatmake} recursively applies the above procedure on all these files.
7461
7462 This process ensures that @code{gnatmake} only trusts the dependencies
7463 in an existing ALI file if they are known to be correct. Otherwise it
7464 always recompiles to determine a new, guaranteed accurate set of
7465 dependencies. As a result the program is compiled "upside down" from what may
7466 be more familiar as the required order of compilation in some other Ada
7467 systems. In particular, clients are compiled before the units on which
7468 they depend. The ability of GNAT to compile in any order is critical in
7469 allowing an order of compilation to be chosen that guarantees that
7470 @code{gnatmake} will recompute a correct set of new dependencies if
7471 necessary.
7472
7473 When invoking @code{gnatmake} with several @var{file_names}, if a unit is
7474 imported by several of the executables, it will be recompiled at most once.
7475
7476 @node Examples of gnatmake Usage
7477 @section Examples of @code{gnatmake} Usage
7478
7479 @table @code
7480 @item gnatmake hello.adb
7481 Compile all files necessary to bind and link the main program
7482 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
7483 resulting object files to generate an executable file @file{hello}.
7484
7485 @item gnatmake main1 main2 main3
7486 Compile all files necessary to bind and link the main programs
7487 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
7488 (containing unit @code{Main2}) and @file{main3.adb}
7489 (containing unit @code{Main3}) and bind and link the resulting object files
7490 to generate three executable files @file{main1},
7491 @file{main2}
7492 and @file{main3}.
7493
7494 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
7495
7496 Compile all files necessary to bind and link the main program unit
7497 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
7498 be done with optimization level 2 and the order of elaboration will be
7499 listed by the binder. @code{gnatmake} will operate in quiet mode, not
7500 displaying commands it is executing.
7501 @end table
7502
7503 @node Renaming Files Using gnatchop
7504 @chapter Renaming Files Using @code{gnatchop}
7505 @findex gnatchop
7506
7507 @noindent
7508 This chapter discusses how to handle files with multiple units by using
7509 the @code{gnatchop} utility. This utility is also useful in renaming
7510 files to meet the standard GNAT default file naming conventions.
7511
7512 @menu
7513 * Handling Files with Multiple Units::
7514 * Operating gnatchop in Compilation Mode::
7515 * Command Line for gnatchop::
7516 * Switches for gnatchop::
7517 * Examples of gnatchop Usage::
7518 @end menu
7519
7520 @node Handling Files with Multiple Units
7521 @section Handling Files with Multiple Units
7522
7523 @noindent
7524 The basic compilation model of GNAT requires that a file submitted to the
7525 compiler have only one unit and there be a strict correspondence
7526 between the file name and the unit name.
7527
7528 The @code{gnatchop} utility allows both of these rules to be relaxed,
7529 allowing GNAT to process files which contain multiple compilation units
7530 and files with arbitrary file names. @code{gnatchop}
7531 reads the specified file and generates one or more output files,
7532 containing one unit per file. The unit and the file name correspond,
7533 as required by GNAT.
7534
7535 If you want to permanently restructure a set of "foreign" files so that
7536 they match the GNAT rules, and do the remaining development using the
7537 GNAT structure, you can simply use @code{gnatchop} once, generate the
7538 new set of files and work with them from that point on.
7539
7540 Alternatively, if you want to keep your files in the "foreign" format,
7541 perhaps to maintain compatibility with some other Ada compilation
7542 system, you can set up a procedure where you use @code{gnatchop} each
7543 time you compile, regarding the source files that it writes as temporary
7544 files that you throw away.
7545
7546 @node Operating gnatchop in Compilation Mode
7547 @section Operating gnatchop in Compilation Mode
7548
7549 @noindent
7550 The basic function of @code{gnatchop} is to take a file with multiple units
7551 and split it into separate files. The boundary between files is reasonably
7552 clear, except for the issue of comments and pragmas. In default mode, the
7553 rule is that any pragmas between units belong to the previous unit, except
7554 that configuration pragmas always belong to the following unit. Any comments
7555 belong to the following unit. These rules
7556 almost always result in the right choice of
7557 the split point without needing to mark it explicitly and most users will
7558 find this default to be what they want. In this default mode it is incorrect to
7559 submit a file containing only configuration pragmas, or one that ends in
7560 configuration pragmas, to @code{gnatchop}.
7561
7562 However, using a special option to activate "compilation mode",
7563 @code{gnatchop}
7564 can perform another function, which is to provide exactly the semantics
7565 required by the RM for handling of configuration pragmas in a compilation.
7566 In the absence of configuration pragmas (at the main file level), this
7567 option has no effect, but it causes such configuration pragmas to be handled
7568 in a quite different manner.
7569
7570 First, in compilation mode, if @code{gnatchop} is given a file that consists of
7571 only configuration pragmas, then this file is appended to the
7572 @file{gnat.adc} file in the current directory. This behavior provides
7573 the required behavior described in the RM for the actions to be taken
7574 on submitting such a file to the compiler, namely that these pragmas
7575 should apply to all subsequent compilations in the same compilation
7576 environment. Using GNAT, the current directory, possibly containing a
7577 @file{gnat.adc} file is the representation
7578 of a compilation environment. For more information on the
7579 @file{gnat.adc} file, see the section on handling of configuration
7580 pragmas @pxref{Handling of Configuration Pragmas}.
7581
7582 Second, in compilation mode, if @code{gnatchop}
7583 is given a file that starts with
7584 configuration pragmas, and contains one or more units, then these
7585 configuration pragmas are prepended to each of the chopped files. This
7586 behavior provides the required behavior described in the RM for the
7587 actions to be taken on compiling such a file, namely that the pragmas
7588 apply to all units in the compilation, but not to subsequently compiled
7589 units.
7590
7591 Finally, if configuration pragmas appear between units, they are appended
7592 to the previous unit. This results in the previous unit being illegal,
7593 since the compiler does not accept configuration pragmas that follow
7594 a unit. This provides the required RM behavior that forbids configuration
7595 pragmas other than those preceding the first compilation unit of a
7596 compilation.
7597
7598 For most purposes, @code{gnatchop} will be used in default mode. The
7599 compilation mode described above is used only if you need exactly
7600 accurate behavior with respect to compilations, and you have files
7601 that contain multiple units and configuration pragmas. In this
7602 circumstance the use of @code{gnatchop} with the compilation mode
7603 switch provides the required behavior, and is for example the mode
7604 in which GNAT processes the ACVC tests.
7605
7606 @node Command Line for gnatchop
7607 @section Command Line for @code{gnatchop}
7608
7609 @noindent
7610 The @code{gnatchop} command has the form:
7611
7612 @smallexample
7613 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
7614       [@var{directory}]
7615 @end smallexample
7616
7617 @noindent
7618 The only required argument is the file name of the file to be chopped.
7619 There are no restrictions on the form of this file name. The file itself
7620 contains one or more Ada units, in normal GNAT format, concatenated
7621 together. As shown, more than one file may be presented to be chopped.
7622
7623 When run in default mode, @code{gnatchop} generates one output file in
7624 the current directory for each unit in each of the files.
7625
7626 @var{directory}, if specified, gives the name of the directory to which
7627 the output files will be written. If it is not specified, all files are
7628 written to the current directory.
7629
7630 For example, given a
7631 file called @file{hellofiles} containing
7632
7633 @smallexample
7634 @group
7635 @cartouche
7636 @b{procedure} hello;
7637
7638 @b{with} Text_IO; @b{use} Text_IO;
7639 @b{procedure} hello @b{is}
7640 @b{begin}
7641    Put_Line ("Hello");
7642 @b{end} hello;
7643 @end cartouche
7644 @end group
7645 @end smallexample
7646
7647 @noindent
7648 the command
7649
7650 @smallexample
7651 $ gnatchop hellofiles
7652 @end smallexample
7653
7654 @noindent
7655 generates two files in the current directory, one called
7656 @file{hello.ads} containing the single line that is the procedure spec,
7657 and the other called @file{hello.adb} containing the remaining text. The
7658 original file is not affected. The generated files can be compiled in
7659 the normal manner.
7660
7661 @node Switches for gnatchop
7662 @section Switches for @code{gnatchop}
7663
7664 @noindent
7665 @code{gnatchop} recognizes the following switches:
7666
7667 @table @code
7668
7669 @item -c
7670 @cindex @code{-c} (@code{gnatchop})
7671 Causes @code{gnatchop} to operate in compilation mode, in which
7672 configuration pragmas are handled according to strict RM rules. See
7673 previous section for a full description of this mode.
7674
7675 @item -gnatxxx
7676 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
7677 used to parse the given file. Not all @code{xxx} options make sense,
7678 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
7679 process a source file that uses Latin-2 coding for identifiers.
7680
7681 @item -h
7682 Causes @code{gnatchop} to generate a brief help summary to the standard
7683 output file showing usage information.
7684
7685 @item -k@var{mm}
7686 @cindex @code{-k} (@code{gnatchop})
7687 Limit generated file names to the specified number @code{mm}
7688 of characters.
7689 This is useful if the
7690 resulting set of files is required to be interoperable with systems
7691 which limit the length of file names.
7692 No space is allowed between the @code{-k} and the numeric value. The numeric
7693 value may be omitted in which case a default of @code{-k8},
7694 suitable for use
7695 with DOS-like file systems, is used. If no @code{-k} switch
7696 is present then
7697 there is no limit on the length of file names.
7698
7699 @item -p
7700 @cindex @code{-p} (@code{gnatchop})
7701 Causes the file modification time stamp of the input file to be
7702 preserved and used for the time stamp of the output file(s). This may be
7703 useful for preserving coherency of time stamps in an enviroment where
7704 @code{gnatchop} is used as part of a standard build process.
7705
7706 @item -q
7707 @cindex @code{-q} (@code{gnatchop})
7708 Causes output of informational messages indicating the set of generated
7709 files to be suppressed. Warnings and error messages are unaffected.
7710
7711 @item -r
7712 @cindex @code{-r} (@code{gnatchop})
7713 @findex Source_Reference
7714 Generate @code{Source_Reference} pragmas. Use this switch if the output
7715 files are regarded as temporary and development is to be done in terms
7716 of the original unchopped file. This switch causes
7717 @code{Source_Reference} pragmas to be inserted into each of the
7718 generated files to refers back to the original file name and line number.
7719 The result is that all error messages refer back to the original
7720 unchopped file.
7721 In addition, the debugging information placed into the object file (when
7722 the @code{-g} switch of @code{gcc} or @code{gnatmake} is specified) also
7723 refers back to this original file so that tools like profilers and
7724 debuggers will give information in terms of the original unchopped file.
7725
7726 If the original file to be chopped itself contains
7727 a @code{Source_Reference}
7728 pragma referencing a third file, then gnatchop respects
7729 this pragma, and the generated @code{Source_Reference} pragmas
7730 in the chopped file refer to the original file, with appropriate
7731 line numbers. This is particularly useful when @code{gnatchop}
7732 is used in conjunction with @code{gnatprep} to compile files that
7733 contain preprocessing statements and multiple units.
7734
7735 @item -v
7736 @cindex @code{-v} (@code{gnatchop})
7737 Causes @code{gnatchop} to operate in verbose mode. The version
7738 number and copyright notice are output, as well as exact copies of
7739 the gnat1 commands spawned to obtain the chop control information.
7740
7741 @item -w
7742 @cindex @code{-w} (@code{gnatchop})
7743 Overwrite existing file names. Normally @code{gnatchop} regards it as a
7744 fatal error if there is already a file with the same name as a
7745 file it would otherwise output, in other words if the files to be
7746 chopped contain duplicated units. This switch bypasses this
7747 check, and causes all but the last instance of such duplicated
7748 units to be skipped.
7749
7750 @item --GCC=xxxx
7751 @cindex @code{--GCC=} (@code{gnatchop})
7752 Specify the path of the GNAT parser to be used. When this switch is used,
7753 no attempt is made to add the prefix to the GNAT parser executable.
7754 @end table
7755
7756 @node Examples of gnatchop Usage
7757 @section Examples of @code{gnatchop} Usage
7758
7759 @table @code
7760 @item gnatchop -w hello_s.ada ichbiah/files
7761
7762 Chops the source file @file{hello_s.ada}. The output files will be
7763 placed in the directory @file{ichbiah/files},
7764 overwriting any
7765 files with matching names in that directory (no files in the current
7766 directory are modified).
7767
7768 @item gnatchop archive
7769 Chops the source file @file{archive}
7770 into the current directory. One
7771 useful application of @code{gnatchop} is in sending sets of sources
7772 around, for example in email messages. The required sources are simply
7773 concatenated (for example, using a Unix @code{cat}
7774 command), and then
7775 @code{gnatchop} is used at the other end to reconstitute the original
7776 file names.
7777
7778 @item gnatchop file1 file2 file3 direc
7779 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
7780 the resulting files in the directory @file{direc}. Note that if any units
7781 occur more than once anywhere within this set of files, an error message
7782 is generated, and no files are written. To override this check, use the
7783 @code{-w} switch,
7784 in which case the last occurrence in the last file will
7785 be the one that is output, and earlier duplicate occurrences for a given
7786 unit will be skipped.
7787 @end table
7788
7789 @node Configuration Pragmas
7790 @chapter Configuration Pragmas
7791 @cindex Configuration pragmas
7792 @cindex Pragmas, configuration
7793
7794 @noindent
7795 In Ada 95, configuration pragmas include those pragmas described as
7796 such in the Ada 95 Reference Manual, as well as
7797 implementation-dependent pragmas that are configuration pragmas. See the
7798 individual descriptions of pragmas in the GNAT Reference Manual for
7799 details on these additional GNAT-specific configuration pragmas. Most
7800 notably, the pragma @code{Source_File_Name}, which allows
7801 specifying non-default names for source files, is a configuration
7802 pragma. The following is a complete list of configuration pragmas
7803 recognized by @code{GNAT}:
7804
7805 @smallexample
7806    Ada_83
7807    Ada_95
7808    C_Pass_By_Copy
7809    Component_Alignment
7810    Discard_Names
7811    Elaboration_Checks
7812    Eliminate
7813    Extend_System
7814    Extensions_Allowed
7815    External_Name_Casing
7816    Float_Representation
7817    Initialize_Scalars
7818    License
7819    Locking_Policy
7820    Long_Float
7821    No_Run_Time
7822    Normalize_Scalars
7823    Polling
7824    Propagate_Exceptions
7825    Queuing_Policy
7826    Ravenscar
7827    Restricted_Run_Time
7828    Restrictions
7829    Reviewable
7830    Source_File_Name
7831    Style_Checks
7832    Suppress
7833    Task_Dispatching_Policy
7834    Unsuppress
7835    Use_VADS_Size
7836    Warnings
7837    Validity_Checks
7838 @end smallexample
7839
7840 @menu
7841 * Handling of Configuration Pragmas::
7842 * The Configuration Pragmas Files::
7843 @end menu
7844
7845 @node Handling of Configuration Pragmas
7846 @section Handling of Configuration Pragmas
7847
7848 Configuration pragmas may either appear at the start of a compilation
7849 unit, in which case they apply only to that unit, or they may apply to
7850 all compilations performed in a given compilation environment.
7851
7852 GNAT also provides the @code{gnatchop} utility to provide an automatic
7853 way to handle configuration pragmas following the semantics for
7854 compilations (that is, files with multiple units), described in the RM.
7855 See section @pxref{Operating gnatchop in Compilation Mode} for details.
7856 However, for most purposes, it will be more convenient to edit the
7857 @file{gnat.adc} file that contains configuration pragmas directly,
7858 as described in the following section.
7859
7860 @node The Configuration Pragmas Files
7861 @section The Configuration Pragmas Files
7862 @cindex @file{gnat.adc}
7863
7864 @noindent
7865 In GNAT a compilation environment is defined by the current
7866 directory at the time that a compile command is given. This current
7867 directory is searched for a file whose name is @file{gnat.adc}. If
7868 this file is present, it is expected to contain one or more
7869 configuration pragmas that will be applied to the current compilation.
7870 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
7871 considered.
7872
7873 Configuration pragmas may be entered into the @file{gnat.adc} file
7874 either by running @code{gnatchop} on a source file that consists only of
7875 configuration pragmas, or more conveniently  by
7876 direct editing of the @file{gnat.adc} file, which is a standard format
7877 source file.
7878
7879 In addition to @file{gnat.adc}, one additional file containing configuration
7880 pragmas may be applied to the current compilation using the switch
7881 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
7882 contains only configuration pragmas. These configuration pragmas are
7883 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
7884 is present and switch @option{-gnatA} is not used).
7885
7886 It is allowed to specify several switches @option{-gnatec}, however only
7887 the last one on the command line will be taken into account.
7888
7889
7890 @node Handling Arbitrary File Naming Conventions Using gnatname
7891 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
7892 @cindex Arbitrary File Naming Conventions
7893
7894 @menu
7895 * Arbitrary File Naming Conventions::
7896 * Running gnatname::
7897 * Switches for gnatname::
7898 * Examples of gnatname Usage::
7899 @end menu
7900
7901 @node Arbitrary File Naming Conventions
7902 @section Arbitrary File Naming Conventions
7903
7904 @noindent
7905 The GNAT compiler must be able to know the source file name of a compilation unit.
7906 When using the standard GNAT default file naming conventions (@code{.ads} for specs,
7907 @code{.adb} for bodies), the GNAT compiler does not need additional information.
7908
7909 @noindent
7910 When the source file names do not follow the standard GNAT default file naming
7911 conventions, the GNAT compiler must be given additional information through
7912 a configuration pragmas file (see @ref{Configuration Pragmas}) or a project file.
7913 When the non standard file naming conventions are well-defined, a small number of
7914 pragmas @code{Source_File_Name} specifying a naming pattern
7915 (see @ref{Alternative File Naming Schemes}) may be sufficient. However,
7916 if the file naming conventions are irregular or arbitrary, a number
7917 of pragma @code{Source_File_Name} for individual compilation units must be defined.
7918 To help maintain the correspondence between compilation unit names and
7919 source file names within the compiler,
7920 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
7921 set of files.
7922
7923 @node Running gnatname
7924 @section Running @code{gnatname}
7925
7926 @noindent
7927 The usual form of the @code{gnatname} command is
7928
7929 @smallexample
7930 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
7931 @end smallexample
7932
7933 @noindent
7934 All of the arguments are optional. If invoked without any argument,
7935 @code{gnatname} will display its usage.
7936
7937 @noindent
7938 When used with at least one naming pattern, @code{gnatname} will attempt to
7939 find all the compilation units in files that follow at least one of the
7940 naming patterns. To find these compilation units,
7941 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
7942 regular files.
7943
7944 @noindent
7945 One or several Naming Patterns may be given as arguments to @code{gnatname}.
7946 Each Naming Pattern is enclosed between double quotes.
7947 A Naming Pattern is a regular expression similar to the wildcard patterns
7948 used in file names by the Unix shells or the DOS prompt.
7949
7950 @noindent
7951 Examples of Naming Patterns are
7952
7953 @smallexample
7954    "*.[12].ada"
7955    "*.ad[sb]*"
7956    "body_*"    "spec_*"
7957 @end smallexample
7958
7959 @noindent
7960 For a more complete description of the syntax of Naming Patterns, see the second kind
7961 of regular expressions described in @file{g-regexp.ads} (the "Glob" regular
7962 expressions).
7963
7964 @noindent
7965 When invoked with no switches, @code{gnatname} will create a configuration
7966 pragmas file @file{gnat.adc} in the current working directory, with pragmas
7967 @code{Source_File_Name} for each file that contains a valid Ada unit.
7968
7969 @node Switches for gnatname
7970 @section Switches for @code{gnatname}
7971
7972 @noindent
7973 Switches for @code{gnatname} must precede any specified Naming Pattern.
7974
7975 @noindent
7976 You may specify any of the following switches to @code{gnatname}:
7977
7978 @table @code
7979
7980 @item -c@file{file}
7981 @cindex @code{-c} (@code{gnatname})
7982 Create a configuration pragmas file @file{file} (instead of the default
7983 @file{gnat.adc}). There may be zero, one or more space between @code{-c} and
7984 @file{file}. @file{file} may include directory information. @file{file} must be
7985 writeable. There may be only one switch @code{-c}. When a switch @code{-c} is
7986 specified, no switch @code{-P} may be specified (see below).
7987
7988 @item -d@file{dir}
7989 @cindex @code{-d} (@code{gnatname})
7990 Look for source files in directory @file{dir}. There may be zero, one or more spaces
7991 between @code{-d} and @file{dir}. When a switch @code{-d} is specified,
7992 the current working directory will not be searched for source files, unless it
7993 is explictly
7994 specified with a @code{-d} or @code{-D} switch. Several switches @code{-d} may be
7995 specified. If @file{dir} is a relative path, it is relative to the directory of
7996 the configuration pragmas file specified with switch @code{-c}, or to the directory
7997 of the project file specified with switch @code{-P} or, if neither switch @code{-c}
7998 nor switch @code{-P} are specified, it is relative to the current working
7999 directory. The directory
8000 specified with switch @code{-c} must exist and be readable.
8001
8002 @item -D@file{file}
8003 @cindex @code{-D} (@code{gnatname})
8004 Look for source files in all directories listed in text file @file{file}. There may be
8005 zero, one or more spaces between @code{-d} and @file{dir}. @file{file}
8006 must be an existing, readable text file. Each non empty line in @file{file} must be
8007 a directory. Specifying switch @code{-D} is equivalent to specifying as many switches
8008 @code{-d} as there are non empty lines in @file{file}.
8009
8010 @item -h
8011 @cindex @code{-h} (@code{gnatname})
8012 Output usage (help) information. The output is written to @file{stdout}.
8013
8014 @item -P@file{proj}
8015 @cindex @code{-P} (@code{gnatname})
8016 Create or update project file @file{proj}. There may be zero, one or more space
8017 between @code{-P} and @file{proj}. @file{proj} may include directory information.
8018 @file{proj} must be writeable. There may be only one switch @code{-P}.
8019 When a switch @code{-P} is specified, no switch @code{-c} may be specified.
8020
8021 @item -v
8022 @cindex @code{-v} (@code{gnatname})
8023 Verbose mode. Output detailed explanation of behavior to @file{stdout}. This includes
8024 name of the file written, the name of the directories to search and, for each file
8025 in those directories whose name matches at least one of the Naming Patterns, an
8026 indication of whether the file contains a unit, and if so the name of the unit.
8027
8028 @item -v -v
8029 Very Verbose mode. In addition to the output produced in verbose mode, for each file
8030 in the searched directories whose name matches none of the Naming Patterns, an
8031 indication is given that there is no match.
8032
8033 @item -x@file{pattern}
8034 Excluded patterns. Using this switch, it is possible to exclude some files
8035 that would match the name patterns. For example,
8036 @code{"gnatname -x "*_nt.ada" "*.ada"} will look for Ada units in all files
8037 with the @file{.ada} extension, except those whose names end with
8038 @file{_nt.ada}.
8039
8040 @end table
8041
8042 @node Examples of gnatname Usage
8043 @section Examples of @code{gnatname} Usage
8044
8045 @smallexample
8046 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
8047 @end smallexample
8048
8049 In this example, the directory @file{/home/me} must already exist and be
8050 writeable. In addition, the directory @file{/home/me/sources} (specified by
8051 @code{-d sources}) must exist and be readable. Note the optional spaces after
8052 @code{-c} and @code{-d}.
8053
8054 @smallexample
8055 $ gnatname -P/home/me/proj -x "*_nt_body.ada" -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
8056 @end smallexample
8057
8058 Note that several switches @code{-d} may be used, even in conjunction with one
8059 or several switches @code{-D}. Several Naming Patterns and one excluded pattern
8060 are used in this example.
8061
8062
8063 @c *****************************************
8064 @c * G N A T  P r o j e c t  M a n a g e r *
8065 @c *****************************************
8066 @node GNAT Project Manager
8067 @chapter GNAT Project Manager
8068
8069 @menu
8070 * Introduction::
8071 * Examples of Project Files::
8072 * Project File Syntax::
8073 * Objects and Sources in Project Files::
8074 * Importing Projects::
8075 * Project Extension::
8076 * External References in Project Files::
8077 * Packages in Project Files::
8078 * Variables from Imported Projects::
8079 * Naming Schemes::
8080 * Library Projects::
8081 * Switches Related to Project Files::
8082 * Tools Supporting Project Files::
8083 * An Extended Example::
8084 * Project File Complete Syntax::
8085 @end menu
8086
8087
8088 @c ****************
8089 @c * Introduction *
8090 @c ****************
8091
8092 @node Introduction
8093 @section Introduction
8094
8095 @noindent
8096 This chapter describes GNAT's @emph{Project Manager}, a facility that
8097 lets you configure various properties for a collection of source files.  In
8098 particular, you can specify:
8099 @itemize @bullet
8100 @item
8101 The directory or set of directories containing the source files, and/or the
8102 names of the specific source files themselves
8103 @item
8104 The directory in which the compiler's output
8105 (@file{ALI} files, object files, tree files) will be placed
8106 @item
8107 The directory in which the executable programs will be placed
8108 @item
8109 Switch settings for any of the project-enabled tools (@command{gnatmake},
8110 compiler, binder, linker, @code{gnatls}, @code{gnatxref}, @code{gnatfind});
8111 you can apply these settings either globally or to individual units
8112 @item
8113 The source files containing the main subprogram(s) to be built
8114 @item
8115 The source programming language(s) (currently Ada and/or C)
8116 @item
8117 Source file naming conventions; you can specify these either globally or for
8118 individual units
8119 @end itemize
8120
8121 @menu
8122 * Project Files::
8123 @end menu
8124
8125 @node Project Files
8126 @subsection Project Files
8127
8128 @noindent
8129 A @dfn{project} is a specific set of values for these properties.  You can
8130 define a project's settings in a @dfn{project file}, a text file with an
8131 Ada-like syntax; a property value is either a string or a list of strings.
8132 Properties that are not explicitly set receive default values.  A project
8133 file may interrogate the values of @dfn{external variables} (user-defined
8134 command-line switches or environment variables), and it may specify property
8135 settings conditionally, based on the value of such variables.
8136
8137 In simple cases, a project's source files depend only on other source files
8138 in the same project, or on the predefined libraries.  ("Dependence" is in
8139 the technical sense; for example, one Ada unit "with"ing another.)  However,
8140 the Project Manager also allows much more sophisticated arrangements,
8141 with the source files in one project depending on source files in other
8142 projects:
8143 @itemize @bullet
8144 @item
8145 One project can @emph{import} other projects containing needed source files.
8146 @item
8147 You can organize GNAT projects in a hierarchy: a @emph{child} project
8148 can extend a @emph{parent} project, inheriting the parent's source files and
8149 optionally overriding any of them with alternative versions
8150 @end itemize
8151
8152 @noindent
8153 More generally, the Project Manager lets you structure large development
8154 efforts into hierarchical subsystems, with build decisions deferred to the
8155 subsystem level and thus different compilation environments (switch settings)
8156 used for different subsystems.
8157
8158 The Project Manager is invoked through the @option{-P@emph{projectfile}}
8159 switch to @command{gnatmake} or to the @command{gnat} front driver.
8160 If you want to define (on the command line) an external variable that is
8161 queried by the project file, additionally use the
8162 @option{-X@emph{vbl}=@emph{value}} switch.
8163 The Project Manager parses and interprets the project file, and drives the
8164 invoked tool based on the project settings.
8165
8166 The Project Manager supports a wide range of development strategies,
8167 for systems of all sizes.  Some typical practices that are easily handled:
8168 @itemize @bullet
8169 @item
8170 Using a common set of source files, but generating object files in different
8171 directories via different switch settings
8172 @item
8173 Using a mostly-shared set of source files, but with different versions of
8174 some unit or units
8175 @end itemize
8176
8177 @noindent
8178 The destination of an executable can be controlled inside a project file
8179 using the @option{-o} switch. In the absence of such a switch either inside
8180 the project file or on the command line, any executable files generated by
8181 @command{gnatmake} will be placed in the directory @code{Exec_Dir} specified
8182 in the project file. If no @code{Exec_Dir} is specified, they will be placed
8183 in the object directory of the project.
8184
8185 You can use project files to achieve some of the effects of a source
8186 versioning system (for example, defining separate projects for
8187 the different sets of sources that comprise different releases) but the
8188 Project Manager is independent of any source configuration management tools
8189 that might be used by the developers.
8190
8191 The next section introduces the main features of GNAT's project facility
8192 through a sequence of examples; subsequent sections will present the syntax
8193 and semantics in more detail.
8194
8195
8196 @c *****************************
8197 @c * Examples of Project Files *
8198 @c *****************************
8199
8200 @node Examples of Project Files
8201 @section Examples of Project Files
8202 @noindent
8203 This section illustrates some of the typical uses of project files and
8204 explains their basic structure and behavior.
8205
8206 @menu
8207 * Common Sources with Different Switches and Different Output Directories::
8208 * Using External Variables::
8209 * Importing Other Projects::
8210 * Extending a Project::
8211 @end menu
8212
8213 @node Common Sources with Different Switches and Different Output Directories
8214 @subsection Common Sources with Different Switches and Different Output Directories
8215
8216 @menu
8217 * Source Files::
8218 * Specifying the Object Directory::
8219 * Specifying the Exec Directory::
8220 * Project File Packages::
8221 * Specifying Switch Settings::
8222 * Main Subprograms::
8223 * Source File Naming Conventions::
8224 * Source Language(s)::
8225 @end menu
8226
8227 @noindent
8228 Assume that the Ada source files @file{pack.ads}, @file{pack.adb}, and
8229 @file{proc.adb} are in the @file{/common} directory.  The file
8230 @file{proc.adb} contains an Ada main subprogram @code{Proc} that "with"s
8231 package @code{Pack}.  We want to compile these source files under two sets
8232 of switches:
8233 @itemize @bullet
8234 @item
8235 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
8236 and the @option{-gnata}, @option{-gnato}, and @option{-gnatE} switches to the
8237 compiler; the compiler's output is to appear in @file{/common/debug}
8238 @item
8239 When preparing a release version, we want to pass the @option{-O2} switch to
8240 the compiler; the compiler's output is to appear in @file{/common/release}
8241 @end itemize
8242
8243 @noindent
8244 The GNAT project files shown below, respectively @file{debug.gpr} and
8245 @file{release.gpr} in the @file{/common} directory, achieve these effects.
8246
8247 Diagrammatically:
8248 @smallexample
8249 @group
8250 /common
8251   debug.gpr
8252   release.gpr
8253   pack.ads
8254   pack.adb
8255   proc.adb
8256 @end group
8257 @group
8258 /common/debug @{-g, -gnata, -gnato, -gnatE@}
8259   proc.ali, proc.o
8260   pack.ali, pack.o
8261 @end group
8262 @group
8263 /common/release @{-O2@}
8264   proc.ali, proc.o
8265   pack.ali, pack.o
8266 @end group
8267 @end smallexample
8268 Here are the project files:
8269 @smallexample
8270 @group
8271 project Debug is
8272   for Object_Dir use "debug";
8273   for Main use ("proc");
8274
8275   package Builder is
8276     for Default_Switches ("Ada") use ("-g");
8277   end Builder;
8278 @end group
8279
8280 @group
8281   package Compiler is
8282     for Default_Switches ("Ada")
8283        use ("-fstack-check", "-gnata", "-gnato", "-gnatE");
8284   end Compiler;
8285 end Debug;
8286 @end group
8287 @end smallexample
8288
8289 @smallexample
8290 @group
8291 project Release is
8292   for Object_Dir use "release";
8293   for Exec_Dir use ".";
8294   for Main use ("proc");
8295
8296   package Compiler is
8297     for Default_Switches ("Ada") use ("-O2");
8298   end Compiler;
8299 end Release;
8300 @end group
8301 @end smallexample
8302
8303 @noindent
8304 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
8305 insensitive), and analogously the project defined by @file{release.gpr} is
8306 @code{"Release"}.  For consistency the file should have the same name as the
8307 project, and the project file's extension should be @code{"gpr"}. These
8308 conventions are not required, but a warning is issued if they are not followed.
8309
8310 If the current directory is @file{/temp}, then the command
8311 @smallexample
8312 gnatmake -P/common/debug.gpr
8313 @end smallexample
8314
8315 @noindent
8316 generates object and ALI files in @file{/common/debug}, and the @code{proc}
8317 executable also in @file{/common/debug}, using the switch settings defined in
8318 the project file.
8319
8320 Likewise, the command
8321 @smallexample
8322 gnatmake -P/common/release.gpr
8323 @end smallexample
8324
8325 @noindent
8326 generates object and ALI files in @file{/common/release}, and the @code{proc}
8327 executable in @file{/common}, using the switch settings from the project file.
8328
8329 @node Source Files
8330 @unnumberedsubsubsec Source Files
8331
8332 @noindent
8333 If a project file does not explicitly specify a set of source directories or
8334 a set of source files, then by default the project's source files are the
8335 Ada source files in the project file directory.  Thus @file{pack.ads},
8336 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
8337
8338 @node Specifying the Object Directory
8339 @unnumberedsubsubsec Specifying the Object Directory
8340
8341 @noindent
8342 Several project properties are modeled by Ada-style @emph{attributes};
8343 you define the property by supplying the equivalent of an Ada attribute
8344 definition clause in the project file.
8345 A project's object directory is such a property; the corresponding
8346 attribute is @code{Object_Dir}, and its value is a string expression.  A
8347 directory may be specified either as absolute or as relative; in the latter
8348 case, it is relative to the project file directory.  Thus the compiler's
8349 output is directed to @file{/common/debug} (for the @code{Debug} project)
8350 and to @file{/common/release} (for the @code{Release} project).  If
8351 @code{Object_Dir} is not specified, then the default is the project file
8352 directory.
8353
8354 @node Specifying the Exec Directory
8355 @unnumberedsubsubsec Specifying the Exec Directory
8356
8357 @noindent
8358 A project's exec directory is another property; the corresponding
8359 attribute is @code{Exec_Dir}, and its value is also a string expression,
8360 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
8361 then the default is the object directory (which may also be the project file
8362 directory if attribute @code{Object_Dir} is not specified). Thus the executable
8363 is placed in @file{/common/debug} for the @code{Debug} project (attribute
8364 @code{Exec_Dir} not specified) and in @file{/common} for the @code{Release}
8365 project.
8366
8367 @node Project File Packages
8368 @unnumberedsubsubsec Project File Packages
8369
8370 @noindent
8371 A GNAT tool integrated with the Project Manager is modeled by a
8372 corresponding package in the project file.
8373 The @code{Debug} project defines the packages @code{Builder}
8374 (for @command{gnatmake}) and @code{Compiler};
8375 the @code{Release} project defines only the @code{Compiler} package.
8376
8377 The Ada package syntax is not to be taken literally.  Although packages in
8378 project files bear a surface resemblance to packages in Ada source code, the
8379 notation is simply a way to convey a grouping of properties for a named
8380 entity.  Indeed, the package names permitted in project files are restricted
8381 to a predefined set, corresponding to the project-aware tools, and the contents
8382 of packages are limited to a small set of constructs.
8383 The packages in the example above contain attribute definitions.
8384
8385
8386 @node Specifying Switch Settings
8387 @unnumberedsubsubsec Specifying Switch Settings
8388
8389 @noindent
8390 Switch settings for a project-aware tool can be specified through attributes
8391 in the package corresponding to the tool.
8392 The example above illustrates one of the relevant attributes,
8393 @code{Default_Switches}, defined in the packages in both project files.
8394 Unlike simple attributes like @code{Source_Dirs}, @code{Default_Switches} is
8395 known as an @emph{associative array}.  When you define this attribute, you must
8396 supply an "index" (a literal string), and the effect of the attribute
8397 definition is to set the value of the "array" at the specified "index".
8398 For the @code{Default_Switches} attribute, the index is a programming
8399 language (in our case, Ada) , and the value specified (after @code{use})
8400 must be a list of string expressions.
8401
8402 The attributes permitted in project files are restricted to a predefined set.
8403 Some may appear at project level, others in packages.
8404 For any attribute that is an associate array, the index must always be a
8405 literal string, but the restrictions on this string (e.g., a file name or a
8406 language name) depend on the individual attribute.
8407 Also depending on the attribute, its specified value will need to be either a
8408 string or a string list.
8409
8410 In the @code{Debug} project, we set the switches for two tools,
8411 @command{gnatmake} and the compiler, and thus we include corresponding
8412 packages, with each package defining the @code{Default_Switches} attribute
8413 with index @code{"Ada"}.
8414 Note that the package corresponding to
8415 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
8416 similar, but with just the @code{Compiler} package.
8417
8418 In project @code{Debug} above the switches starting with @option{-gnat} that
8419 are specified in package @code{Compiler} could have been placed in package
8420 @code{Builder}, since @command{gnatmake} transmits all such switches to the
8421 compiler.
8422
8423 @node Main Subprograms
8424 @unnumberedsubsubsec Main Subprograms
8425
8426 @noindent
8427 One of the properties of a project is its list of main subprograms (actually
8428 a list of names of source files containing main subprograms, with the file
8429 extension optional.  This property is captured in the @code{Main} attribute,
8430 whose value is a list of strings.  If a project defines the @code{Main}
8431 attribute, then you do not need to identify the main subprogram(s) when
8432 invoking @command{gnatmake} (see @ref{gnatmake and Project Files}).
8433
8434 @node Source File Naming Conventions
8435 @unnumberedsubsubsec Source File Naming Conventions
8436
8437 @noindent
8438 Since the project files do not specify any source file naming conventions,
8439 the GNAT defaults are used.  The mechanism for defining source file naming
8440 conventions -- a package named @code{Naming} -- will be described below
8441 (@pxref{Naming Schemes}).
8442
8443 @node Source Language(s)
8444 @unnumberedsubsubsec Source Language(s)
8445
8446 @noindent
8447 Since the project files do not specify a @code{Languages} attribute, by
8448 default the GNAT tools assume that the language of the project file is Ada.
8449 More generally, a project can comprise source files
8450 in Ada, C, and/or other languages.
8451
8452 @node Using External Variables
8453 @subsection Using External Variables
8454
8455 @noindent
8456 Instead of supplying different project files for debug and release, we can
8457 define a single project file that queries an external variable (set either
8458 on the command line or via an environment variable) in order to
8459 conditionally define the appropriate settings.  Again, assume that the
8460 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
8461 located in directory @file{/common}.  The following project file,
8462 @file{build.gpr}, queries the external variable named @code{STYLE} and
8463 defines an object directory and switch settings based on whether the value
8464 is @code{"deb"} (debug) or @code{"rel"} (release), where the default is
8465 @code{"deb"}.
8466
8467 @smallexample
8468 @group
8469 project Build is
8470   for Main use ("proc");
8471
8472   type Style_Type is ("deb", "rel");
8473   Style : Style_Type := external ("STYLE", "deb");
8474
8475   case Style is
8476     when "deb" =>
8477       for Object_Dir use "debug";
8478
8479     when "rel" =>
8480       for Object_Dir use "release";
8481       for Exec_Dir use ".";
8482   end case;
8483 @end group
8484
8485 @group
8486   package Builder is
8487
8488     case Style is
8489       when "deb" =>
8490         for Default_Switches ("Ada") use ("-g");
8491     end case;
8492
8493   end Builder;
8494 @end group
8495
8496 @group
8497   package Compiler is
8498
8499     case Style is
8500       when "deb" =>
8501         for Default_Switches ("Ada") use ("-gnata", "-gnato", "-gnatE");
8502
8503       when "rel" =>
8504         for Default_Switches ("Ada") use ("-O2");
8505     end case;
8506
8507   end Compiler;
8508
8509 end Build;
8510 @end group
8511 @end smallexample
8512
8513 @noindent
8514 @code{Style_Type} is an example of a @emph{string type}, which is the project
8515 file analog of an Ada enumeration type but containing string literals rather
8516 than identifiers.  @code{Style} is declared as a variable of this type.
8517
8518 The form @code{external("STYLE", "deb")} is known as an
8519 @emph{external reference}; its first argument is the name of an
8520 @emph{external variable}, and the second argument is a default value to be
8521 used if the external variable doesn't exist.  You can define an external
8522 variable on the command line via the @option{-X} switch, or you can use an
8523 environment variable as an external variable.
8524
8525 Each @code{case} construct is expanded by the Project Manager based on the
8526 value of @code{Style}. Thus the command
8527 @smallexample
8528 gnatmake -P/common/build.gpr -XSTYLE=deb
8529 @end smallexample
8530
8531 @noindent
8532 is equivalent to the @command{gnatmake} invocation using the project file
8533 @file{debug.gpr} in the earlier example.  So is the command
8534 @smallexample
8535 gnatmake -P/common/build.gpr
8536 @end smallexample
8537
8538 @noindent
8539 since @code{"deb"} is the default for @code{STYLE}.
8540
8541 Analogously,
8542 @smallexample
8543 gnatmake -P/common/build.gpr -XSTYLE=rel
8544 @end smallexample
8545
8546 @noindent
8547 is equivalent to the @command{gnatmake} invocation using the project file
8548 @file{release.gpr} in the earlier example.
8549
8550
8551 @node Importing Other Projects
8552 @subsection Importing Other Projects
8553
8554 @noindent
8555 A compilation unit in a source file in one project may depend on compilation
8556 units in source files in other projects.  To obtain this behavior, the
8557 dependent project must @emph{import} the projects containing the needed source
8558 files.  This effect is embodied in syntax similar to an Ada @code{with} clause,
8559 but the "with"ed entities are strings denoting project files.
8560
8561 As an example, suppose that the two projects @code{GUI_Proj} and
8562 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
8563 @file{comm_proj.gpr} in directories @file{/gui} and @file{/comm},
8564 respectively.  Assume that the source files for @code{GUI_Proj} are
8565 @file{gui.ads} and @file{gui.adb}, and that the source files for
8566 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, with each set of
8567 files located in its respective project file directory.  Diagrammatically:
8568
8569 @smallexample
8570 @group
8571 /gui
8572   gui_proj.gpr
8573   gui.ads
8574   gui.adb
8575 @end group
8576
8577 @group
8578 /comm
8579   comm_proj.gpr
8580   comm.ads
8581   comm.adb
8582 @end group
8583 @end smallexample
8584
8585 @noindent
8586 We want to develop an application in directory @file{/app} that "with"s the
8587 packages @code{GUI} and @code{Comm}, using the properties of the
8588 corresponding project files (e.g. the switch settings and object directory).
8589 Skeletal code for a main procedure might be something like the following:
8590
8591 @smallexample
8592 @group
8593 with GUI, Comm;
8594 procedure App_Main is
8595    ...
8596 begin
8597    ...
8598 end App_Main;
8599 @end group
8600 @end smallexample
8601
8602 @noindent
8603 Here is a project file, @file{app_proj.gpr}, that achieves the desired
8604 effect:
8605
8606 @smallexample
8607 @group
8608 with "/gui/gui_proj", "/comm/comm_proj";
8609 project App_Proj is
8610    for Main use ("app_main");
8611 end App_Proj;
8612 @end group
8613 @end smallexample
8614
8615 @noindent
8616 Building an executable is achieved through the command:
8617 @smallexample
8618 gnatmake -P/app/app_proj
8619 @end smallexample
8620 @noindent
8621 which will generate the @code{app_main} executable in the directory where
8622 @file{app_proj.gpr} resides.
8623
8624 If an imported project file uses the standard extension (@code{gpr}) then
8625 (as illustrated above) the @code{with} clause can omit the extension.
8626
8627 Our example specified an absolute path for each imported project file.
8628 Alternatively, you can omit the directory if either
8629 @itemize @bullet
8630 @item
8631 The imported project file is in the same directory as the importing project
8632 file, or
8633 @item
8634 You have defined an environment variable @code{ADA_PROJECT_PATH} that
8635 includes the directory containing the needed project file.
8636 @end itemize
8637
8638 @noindent
8639 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{/gui} and
8640 @file{/comm}, then our project file @file{app_proj.gpr} could be written as
8641 follows:
8642
8643 @smallexample
8644 @group
8645 with "gui_proj", "comm_proj";
8646 project App_Proj is
8647    for Main use ("app_main");
8648 end App_Proj;
8649 @end group
8650 @end smallexample
8651
8652 @noindent
8653 Importing other projects raises the possibility of ambiguities.  For
8654 example, the same unit might be present in different imported projects, or
8655 it might be present in both the importing project and an imported project.
8656 Both of these conditions are errors.  Note that in the current version of
8657 the Project Manager, it is illegal to have an ambiguous unit even if the
8658 unit is never referenced by the importing project.  This restriction may be
8659 relaxed in a future release.
8660
8661 @node Extending a Project
8662 @subsection Extending a Project
8663
8664 @noindent
8665 A common situation in large software systems is to have multiple
8666 implementations for a common interface; in Ada terms, multiple versions of a
8667 package body for the same specification.  For example, one implementation
8668 might be safe for use in tasking programs, while another might only be used
8669 in sequential applications.  This can be modeled in GNAT using the concept
8670 of @emph{project extension}.  If one project (the "child") @emph{extends}
8671 another project (the "parent") then by default all source files of the
8672 parent project are inherited by the child, but the child project can
8673 override any of the parent's source files with new versions, and can also
8674 add new files.  This facility is the project analog of extension in
8675 Object-Oriented Programming.  Project hierarchies are permitted (a child
8676 project may be the parent of yet another project), and a project that
8677 inherits one project can also import other projects.
8678
8679 As an example, suppose that directory @file{/seq} contains the project file
8680 @file{seq_proj.gpr} and the source files @file{pack.ads}, @file{pack.adb},
8681 and @file{proc.adb}:
8682
8683 @smallexample
8684 @group
8685 /seq
8686   pack.ads
8687   pack.adb
8688   proc.adb
8689   seq_proj.gpr
8690 @end group
8691 @end smallexample
8692
8693 @noindent
8694 Note that the project file can simply be empty (that is, no attribute or
8695 package is defined):
8696
8697 @smallexample
8698 @group
8699 project Seq_Proj is
8700 end Seq_Proj;
8701 @end group
8702 @end smallexample
8703
8704 @noindent
8705 implying that its source files are all the Ada source files in the project
8706 directory.
8707
8708 Suppose we want to supply an alternate version of @file{pack.adb}, in
8709 directory @file{/tasking}, but use the existing versions of @file{pack.ads}
8710 and @file{proc.adb}.  We can define a project @code{Tasking_Proj} that
8711 inherits @code{Seq_Proj}:
8712
8713 @smallexample
8714 @group
8715 /tasking
8716   pack.adb
8717   tasking_proj.gpr
8718 @end group
8719
8720 @group
8721 project Tasking_Proj extends "/seq/seq_proj" is
8722 end Tasking_Proj;
8723 @end group
8724 @end smallexample
8725
8726 @noindent
8727 The version of @file{pack.adb} used in a build depends on which project file
8728 is specified.
8729
8730 Note that we could have designed this using project import rather than
8731 project inheritance; a @code{base} project would contain the sources for
8732 @file{pack.ads} and @file{proc.adb}, a sequential project would import
8733 @code{base} and add @file{pack.adb}, and likewise a tasking project would
8734 import @code{base} and add a different version of @file{pack.adb}.  The
8735 choice depends on whether other sources in the original project need to be
8736 overridden.  If they do, then project extension is necessary, otherwise,
8737 importing is sufficient.
8738
8739
8740 @c ***********************
8741 @c * Project File Syntax *
8742 @c ***********************
8743
8744 @node Project File Syntax
8745 @section Project File Syntax
8746
8747 @menu
8748 * Basic Syntax::
8749 * Packages::
8750 * Expressions::
8751 * String Types::
8752 * Variables::
8753 * Attributes::
8754 * Associative Array Attributes::
8755 * case Constructions::
8756 @end menu
8757
8758 @noindent
8759 This section describes the structure of project files.
8760
8761 A project may be an @emph{independent project}, entirely defined by a single
8762 project file. Any Ada source file in an independent project depends only
8763 on the predefined library and other Ada source files in the same project.
8764
8765 @noindent
8766 A project may also @dfn{depend on} other projects, in either or both of the following ways:
8767 @itemize @bullet
8768 @item It may import any number of projects
8769 @item It may extend at most one other project
8770 @end itemize
8771
8772 @noindent
8773 The dependence relation is a directed acyclic graph (the subgraph reflecting
8774 the "extends" relation is a tree).
8775
8776 A project's @dfn{immediate sources} are the source files directly defined by
8777 that project, either implicitly by residing in the project file's directory,
8778 or explicitly through any of the source-related attributes described below.
8779 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
8780 of @var{proj} together with the immediate sources (unless overridden) of any
8781 project on which @var{proj} depends (either directly or indirectly).
8782
8783 @node Basic Syntax
8784 @subsection Basic Syntax
8785
8786 @noindent
8787 As seen in the earlier examples, project files have an Ada-like syntax.
8788 The minimal project file is:
8789 @smallexample
8790 @group
8791 project Empty is
8792
8793 end Empty;
8794 @end group
8795 @end smallexample
8796
8797 @noindent
8798 The identifier @code{Empty} is the name of the project.
8799 This project name must be present after the reserved
8800 word @code{end} at the end of the project file, followed by a semi-colon.
8801
8802 Any name in a project file, such as the project name or a variable name,
8803 has the same syntax as an Ada identifier.
8804
8805 The reserved words of project files are the Ada reserved words plus
8806 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
8807 reserved words currently used in project file syntax are:
8808
8809 @itemize @bullet
8810 @item
8811 @code{case}
8812 @item
8813 @code{end}
8814 @item
8815 @code{for}
8816 @item
8817 @code{is}
8818 @item
8819 @code{others}
8820 @item
8821 @code{package}
8822 @item
8823 @code{renames}
8824 @item
8825 @code{type}
8826 @item
8827 @code{use}
8828 @item
8829 @code{when}
8830 @item
8831 @code{with}
8832 @end itemize
8833
8834 @noindent
8835 Comments in project files have the same syntax as in Ada, two consecutives
8836 hyphens through the end of the line.
8837
8838 @node Packages
8839 @subsection Packages
8840
8841 @noindent
8842 A project file may contain @emph{packages}. The name of a package must be one
8843 of the identifiers (case insensitive) from a predefined list, and a package
8844 with a given name may only appear once in a project file. The predefined list
8845 includes the following packages:
8846
8847 @itemize @bullet
8848 @item
8849 @code{Naming}
8850 @item
8851 @code{Builder}
8852 @item
8853 @code{Compiler}
8854 @item
8855 @code{Binder}
8856 @item
8857 @code{Linker}
8858 @item
8859 @code{Finder}
8860 @item
8861 @code{Cross_Reference}
8862 @item
8863 @code{gnatls}
8864 @end itemize
8865
8866 @noindent
8867 (The complete list of the package names and their attributes can be found
8868 in file @file{prj-attr.adb}).
8869
8870 @noindent
8871 In its simplest form, a package may be empty:
8872
8873 @smallexample
8874 @group
8875 project Simple is
8876   package Builder is
8877   end Builder;
8878 end Simple;
8879 @end group
8880 @end smallexample
8881
8882 @noindent
8883 A package may contain @emph{attribute declarations},
8884 @emph{variable declarations} and @emph{case constructions}, as will be
8885 described below.
8886
8887 When there is ambiguity between a project name and a package name,
8888 the name always designates the project. To avoid possible confusion, it is
8889 always a good idea to avoid naming a project with one of the
8890 names allowed for packages or any name that starts with @code{gnat}.
8891
8892
8893 @node Expressions
8894 @subsection Expressions
8895
8896 @noindent
8897 An @emph{expression} is either a @emph{string expression} or a
8898 @emph{string list expression}.
8899
8900 A @emph{string expression} is either a @emph{simple string expression} or a
8901 @emph{compound string expression}.
8902
8903 A @emph{simple string expression} is one of the following:
8904 @itemize @bullet
8905 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
8906 @item A string-valued variable reference (see @ref{Variables})
8907 @item A string-valued attribute reference (see @ref{Attributes})
8908 @item An external reference (see @ref{External References in Project Files})
8909 @end itemize
8910
8911 @noindent
8912 A @emph{compound string expression} is a concatenation of string expressions,
8913 using @code{"&"}
8914 @smallexample
8915        Path & "/" & File_Name & ".ads"
8916 @end smallexample
8917
8918 @noindent
8919 A @emph{string list expression} is either a
8920 @emph{simple string list expression} or a
8921 @emph{compound string list expression}.
8922
8923 A @emph{simple string list expression} is one of the following:
8924 @itemize @bullet
8925 @item A parenthesized list of zero or more string expressions, separated by commas
8926 @smallexample
8927    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
8928    Empty_List := ();
8929 @end smallexample
8930 @item A string list-valued variable reference
8931 @item A string list-valued attribute reference
8932 @end itemize
8933
8934 @noindent
8935 A @emph{compound string list expression} is the concatenation (using
8936 @code{"&"}) of a simple string list expression and an expression.  Note that
8937 each term in a compound string list expression, except the first, may be
8938 either a string expression or a string list expression.
8939
8940 @smallexample
8941 @group
8942    File_Name_List := () & File_Name; --  One string in this list
8943    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
8944    --  Two strings
8945    Big_List := File_Name_List & Extended_File_Name_List;
8946    --  Concatenation of two string lists: three strings
8947    Illegal_List := "gnat.adc" & Extended_File_Name_List;
8948    --  Illegal: must start with a string list
8949 @end group
8950 @end smallexample
8951
8952
8953 @node String Types
8954 @subsection String Types
8955
8956 @noindent
8957 The value of a variable may be restricted to a list of string literals.
8958 The restricted list of string literals is given in a
8959 @emph{string type declaration}.
8960
8961 Here is an example of a string type declaration:
8962
8963 @smallexample
8964    type OS is ("NT, "nt", "Unix", "Linux", "other OS");
8965 @end smallexample
8966
8967 @noindent
8968 Variables of a string type are called @emph{typed variables}; all other
8969 variables are called @emph{untyped variables}. Typed variables are
8970 particularly useful in @code{case} constructions
8971 (see @ref{case Constructions}).
8972
8973 A string type declaration starts with the reserved word @code{type}, followed
8974 by the name of the string type (case-insensitive), followed by the reserved
8975 word @code{is}, followed by a parenthesized list of one or more string literals
8976 separated by commas, followed by a semicolon.
8977
8978 The string literals in the list are case sensitive and must all be different.
8979 They may include any graphic characters allowed in Ada, including spaces.
8980
8981 A string type may only be declared at the project level, not inside a package.
8982
8983 A string type may be referenced by its name if it has been declared in the same
8984 project file, or by its project name, followed by a dot,
8985 followed by the string type name.
8986
8987
8988 @node Variables
8989 @subsection Variables
8990
8991 @noindent
8992 A variable may be declared at the project file level, or in a package.
8993 Here are some examples of variable declarations:
8994
8995 @smallexample
8996 @group
8997    This_OS : OS := external ("OS"); --  a typed variable declaration
8998    That_OS := "Linux";              --  an untyped variable declaration
8999 @end group
9000 @end smallexample
9001
9002 @noindent
9003 A @emph{typed variable declaration} includes the variable name, followed by a colon,
9004 followed by the name of a string type, followed by @code{:=}, followed by
9005 a simple string expression.
9006
9007 An @emph{untyped variable declaration} includes the variable name,
9008 followed by @code{:=}, followed by an expression.  Note that, despite the
9009 terminology, this form of "declaration" resembles more an assignment
9010 than a declaration in Ada.  It is a declaration in several senses:
9011 @itemize @bullet
9012 @item
9013 The variable name does not need to be defined previously
9014 @item
9015 The declaration establishes the @emph{kind} (string versus string list) of the
9016 variable, and later declarations of the same variable need to be consistent
9017 with this
9018 @end itemize
9019
9020 @noindent
9021 A string variable declaration (typed or untyped) declares a variable
9022 whose value is a string. This variable may be used as a string expression.
9023 @smallexample
9024    File_Name       := "readme.txt";
9025    Saved_File_Name := File_Name & ".saved";
9026 @end smallexample
9027
9028 @noindent
9029 A string list variable declaration declares a variable whose value is a list
9030 of strings. The list may contain any number (zero or more) of strings.
9031
9032 @smallexample
9033    Empty_List := ();
9034    List_With_One_Element := ("-gnaty");
9035    List_With_Two_Elements := List_With_One_Element & "-gnatg";
9036    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
9037                  "pack2.ada", "util_.ada", "util.ada");
9038 @end smallexample
9039
9040 @noindent
9041 The same typed variable may not be declared more than once at project level, and it may not be declared more than once in any package; it is in effect a constant or a readonly variable.
9042
9043 The same untyped variable may be declared several times.
9044 In this case, the new value replaces the old one,
9045 and any subsequent reference to the variable uses the new value.
9046 However, as noted above, if a variable has been declared as a string, all subsequent
9047 declarations must give it a string value. Similarly, if a variable has
9048 been declared as a string list, all subsequent declarations
9049 must give it a string list value.
9050
9051 A @emph{variable reference} may take several forms:
9052
9053 @itemize @bullet
9054 @item The simple variable name, for a variable in the current package (if any) or in the current project
9055 @item A context name, followed by a dot, followed by the variable name.
9056 @end itemize
9057
9058 @noindent
9059 A @emph{context} may be one of the following:
9060
9061 @itemize @bullet
9062 @item The name of an existing package in the current project
9063 @item The name of an imported project of the current project
9064 @item The name of an ancestor project (i.e., a project extended by the current project, either directly or indirectly)
9065 @item An imported/parent project name, followed by a dot, followed by a package name
9066 @end itemize
9067
9068 @noindent
9069 A variable reference may be used in an expression.
9070
9071
9072 @node Attributes
9073 @subsection Attributes
9074
9075 @noindent
9076 A project (and its packages) may have @emph{attributes} that define the project's properties.
9077 Some attributes have values that are strings;
9078 others have values that are string lists.
9079
9080 There are two categories of attributes: @emph{simple attributes} and @emph{associative arrays}
9081 (see @ref{Associative Array Attributes}).
9082
9083 The names of the attributes are restricted; there is a list of project
9084 attributes, and a list of package attributes for each package.
9085 The names are not case sensitive.
9086
9087 The project attributes are as follows (all are simple attributes):
9088
9089 @multitable @columnfractions .4 .3
9090 @item @emph{Attribute Name}
9091 @tab @emph{Value}
9092 @item @code{Source_Files}
9093 @tab string list
9094 @item @code{Source_Dirs}
9095 @tab string list
9096 @item @code{Source_List_File}
9097 @tab string
9098 @item @code{Object_Dir}
9099 @tab string
9100 @item @code{Exec_Dir}
9101 @tab string
9102 @item @code{Main}
9103 @tab string list
9104 @item @code{Languages}
9105 @tab string list
9106 @item @code{Library_Dir}
9107 @tab string
9108 @item @code{Library_Name}
9109 @tab string
9110 @item @code{Library_Kind}
9111 @tab string
9112 @item @code{Library_Elaboration}
9113 @tab string
9114 @item @code{Library_Version}
9115 @tab string
9116 @end multitable
9117
9118 @noindent
9119 The attributes for package @code{Naming} are as follows
9120 (see @ref{Naming Schemes}):
9121
9122 @multitable @columnfractions .4 .2 .2 .2
9123 @item Attribute Name @tab Category @tab Index @tab Value
9124 @item @code{Specification_Suffix}
9125 @tab associative array
9126 @tab language name
9127 @tab string
9128 @item @code{Implementation_Suffix}
9129 @tab associative array
9130 @tab language name
9131 @tab string
9132 @item @code{Separate_Suffix}
9133 @tab simple attribute
9134 @tab n/a
9135 @tab string
9136 @item @code{Casing}
9137 @tab simple attribute
9138 @tab n/a
9139 @tab string
9140 @item @code{Dot_Replacement}
9141 @tab simple attribute
9142 @tab n/a
9143 @tab string
9144 @item @code{Specification}
9145 @tab associative array
9146 @tab Ada unit name
9147 @tab string
9148 @item @code{Implementation}
9149 @tab associative array
9150 @tab Ada unit name
9151 @tab string
9152 @item @code{Specification_Exceptions}
9153 @tab associative array
9154 @tab language name
9155 @tab string list
9156 @item @code{Implementation_Exceptions}
9157 @tab associative array
9158 @tab language name
9159 @tab string list
9160 @end multitable
9161
9162 @noindent
9163 The attributes for package @code{Builder}, @code{Compiler}, @code{Binder},
9164 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
9165 are as follows (see @ref{Switches and Project Files}).
9166
9167 @multitable @columnfractions .4 .2 .2 .2
9168 @item Attribute Name @tab Category @tab Index @tab Value
9169 @item @code{Default_Switches}
9170 @tab associative array
9171 @tab language name
9172 @tab string list
9173 @item @code{Switches}
9174 @tab associative array
9175 @tab file name
9176 @tab string list
9177 @end multitable
9178
9179 @noindent
9180 In addition, package @code{Builder} has a single string attribute
9181 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
9182 string attribute @code{Global_Configuration_Pragmas}.
9183
9184 @noindent
9185 The attribute for package @code{Glide} are not documented: they are for
9186 internal use only.
9187
9188 @noindent
9189 Each simple attribute has a default value: the empty string (for string-valued
9190 attributes) and the empty list (for string list-valued attributes).
9191
9192 Similar to variable declarations, an attribute declaration defines a new value
9193 for an attribute.
9194
9195 Examples of simple attribute declarations:
9196
9197 @smallexample
9198    for Object_Dir use "objects";
9199    for Source_Dirs use ("units", "test/drivers");
9200 @end smallexample
9201
9202 @noindent
9203 A @dfn{simple attribute declaration} starts with the reserved word @code{for},
9204 followed by the name of the attribute, followed by the reserved word
9205 @code{use}, followed by an expression (whose kind depends on the attribute),
9206 followed by a semicolon.
9207
9208 Attributes may be referenced in expressions.
9209 The general form for such a reference is @code{<entity>'<attribute>}:
9210 the entity for which the attribute is defined,
9211 followed by an apostrophe, followed by the name of the attribute.
9212 For associative array attributes, a litteral string between parentheses
9213 need to be supplied as index.
9214
9215 Examples are:
9216
9217 @smallexample
9218   project'Object_Dir
9219   Naming'Dot_Replacement
9220   Imported_Project'Source_Dirs
9221   Imported_Project.Naming'Casing
9222   Builder'Default_Switches("Ada")
9223 @end smallexample
9224
9225 @noindent
9226 The entity may be:
9227 @itemize @bullet
9228 @item @code{project} for an attribute of the current project
9229 @item The name of an existing package of the current project
9230 @item The name of an imported project
9231 @item The name of a parent project (extended by the current project)
9232 @item An imported/parent project name, followed by a dot,
9233       followed by a package name
9234 @end itemize
9235
9236 @noindent
9237 Example:
9238 @smallexample
9239 @group
9240    project Prj is
9241      for Source_Dirs use project'Source_Dirs & "units";
9242      for Source_Dirs use project'Source_Dirs & "test/drivers"
9243    end Prj;
9244 @end group
9245 @end smallexample
9246
9247 @noindent
9248 In the first attribute declaration, initially the attribute @code{Source_Dirs}
9249 has the default value: an empty string list. After this declaration,
9250 @code{Source_Dirs} is a string list of one element: "units".
9251 After the second attribute declaration @code{Source_Dirs} is a string list of
9252 two elements: "units" and "test/drivers".
9253
9254 Note: this example is for illustration only. In practice,
9255 the project file would contain only one attribute declaration:
9256
9257 @smallexample
9258    for Source_Dirs use ("units", "test/drivers");
9259 @end smallexample
9260
9261
9262 @node Associative Array Attributes
9263 @subsection Associative Array Attributes
9264
9265 @noindent
9266 Some attributes are defined as @emph{associative arrays}. An associative
9267 array may be regarded as a function that takes a string as a parameter
9268 and delivers a string or string list value as its result.
9269
9270 Here are some examples of associative array attribute declarations:
9271
9272 @smallexample
9273    for Implementation ("main") use "Main.ada";
9274    for Switches ("main.ada") use ("-v", "-gnatv");
9275    for Switches ("main.ada") use Builder'Switches ("main.ada") & "-g";
9276 @end smallexample
9277
9278 @noindent
9279 Like untyped variables and simple attributes, associative array attributes may be declared several times. Each declaration supplies a new value for the
9280 attribute, replacing the previous setting.
9281
9282
9283 @node case Constructions
9284 @subsection @code{case} Constructions
9285
9286 @noindent
9287 A @code{case} construction is used in a project file to effect conditional
9288 behavior.
9289 Here is a typical example:
9290
9291 @smallexample
9292 @group
9293 project MyProj is
9294    type OS_Type is ("Linux", "Unix", "NT", "VMS");
9295
9296    OS : OS_Type := external ("OS", "Linux");
9297 @end group
9298
9299 @group
9300    package Compiler is
9301      case OS is
9302        when "Linux" | "Unix" =>
9303          for Default_Switches ("Ada") use ("-gnath");
9304        when "NT" =>
9305          for Default_Switches ("Ada") use ("-gnatP");
9306        when others =>
9307      end case;
9308    end Compiler;
9309 end MyProj;
9310 @end group
9311 @end smallexample
9312
9313 @noindent
9314 The syntax of a @code{case} construction is based on the Ada case statement
9315 (although there is no @code{null} construction for empty alternatives).
9316
9317 Following the reserved word @code{case} there is the case variable (a typed
9318 string variable), the reserved word @code{is}, and then a sequence of one or
9319 more alternatives.
9320 Each alternative comprises the reserved word @code{when}, either a list of
9321 literal strings separated by the @code{"|"} character or the reserved word
9322 @code{others},  and the @code{"=>"} token.
9323 Each literal string must belong to the string type that is the type of the
9324 case variable.
9325 An @code{others} alternative, if present, must occur last.
9326 The @code{end case;} sequence terminates the case construction.
9327
9328 After each @code{=>}, there are zero or more constructions.  The only
9329 constructions allowed in a case construction are other case constructions and
9330 attribute declarations. String type declarations, variable declarations and
9331 package declarations are not allowed.
9332
9333 The value of the case variable is often given by an external reference
9334 (see @ref{External References in Project Files}).
9335
9336
9337 @c ****************************************
9338 @c * Objects and Sources in Project Files *
9339 @c ****************************************
9340
9341 @node Objects and Sources in Project Files
9342 @section Objects and Sources in Project Files
9343
9344 @menu
9345 * Object Directory::
9346 * Exec Directory::
9347 * Source Directories::
9348 * Source File Names::
9349 @end menu
9350
9351 @noindent
9352 Each project has exactly one object directory and one or more source
9353 directories. The source directories must contain at least one source file,
9354 unless  the project file explicitly specifies that no source files are present
9355 (see @ref{Source File Names}).
9356
9357
9358 @node Object Directory
9359 @subsection Object Directory
9360
9361 @noindent
9362 The object directory for a project is the directory containing the compiler's
9363 output (such as @file{ALI} files and object files) for the project's immediate
9364 sources. Note that for inherited sources (when extending a parent project) the
9365 parent project's object directory is used.
9366
9367 The object directory is given by the value of the attribute @code{Object_Dir}
9368 in the project file.
9369
9370 @smallexample
9371    for Object_Dir use "objects";
9372 @end smallexample
9373
9374 @noindent
9375 The attribute @var{Object_Dir} has a string value, the path name of the object
9376 directory. The path name may be absolute or relative to the directory of the
9377 project file. This directory must already exist, and be readable and writable.
9378
9379 By default, when the attribute @code{Object_Dir} is not given an explicit value
9380 or when its value is the empty string, the object directory is the same as the
9381 directory containing the project file.
9382
9383
9384 @node Exec Directory
9385 @subsection Exec Directory
9386
9387 @noindent
9388 The exec directory for a project is the directory containing the executables
9389 for the project's main subprograms.
9390
9391 The exec directory is given by the value of the attribute @code{Exec_Dir}
9392 in the project file.
9393
9394 @smallexample
9395    for Exec_Dir use "executables";
9396 @end smallexample
9397
9398 @noindent
9399 The attribute @var{Exec_Dir} has a string value, the path name of the exec
9400 directory. The path name may be absolute or relative to the directory of the
9401 project file. This directory must already exist, and be writable.
9402
9403 By default, when the attribute @code{Exec_Dir} is not given an explicit value
9404 or when its value is the empty string, the exec directory is the same as the
9405 object directory of the project file.
9406
9407
9408 @node Source Directories
9409 @subsection Source Directories
9410
9411 @noindent
9412 The source directories of a project are specified by the project file
9413 attribute @code{Source_Dirs}.
9414
9415 This attribute's value is a string list. If the attribute is not given an
9416 explicit value, then there is only one source directory, the one where the
9417 project file resides.
9418
9419 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
9420 as in
9421
9422 @smallexample
9423     for Source_Dirs use ();
9424 @end smallexample
9425
9426 @noindent
9427 indicates that the project contains no source files.
9428
9429 Otherwise, each string in the string list designates one or more
9430 source directories.
9431
9432 @smallexample
9433    for Source_Dirs use ("sources", "test/drivers");
9434 @end smallexample
9435
9436 @noindent
9437 If a string in the list ends with @code{"/**"},  then the directory whose path
9438 name precedes the two asterisks, as well as all its subdirectories
9439 (recursively), are source directories.
9440
9441 @smallexample
9442    for Source_Dirs use ("/system/sources/**");
9443 @end smallexample
9444
9445 @noindent
9446 Here the directory @code{/system/sources} and all of its subdirectories
9447 (recursively) are source directories.
9448
9449 To specify that the source directories are the directory of the project file
9450 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
9451 @smallexample
9452    for Source_Dirs use ("./**");
9453 @end smallexample
9454
9455 @noindent
9456 Each of the source directories must exist and be readable.
9457
9458
9459 @node Source File Names
9460 @subsection Source File Names
9461
9462 @noindent
9463 In a project that contains source files, their names may be specified by the
9464 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
9465 (a string). Source file names never include any directory information.
9466
9467 If the attribute @code{Source_Files} is given an explicit value, then each
9468 element of the list is a source file name.
9469
9470 @smallexample
9471    for Source_Files use ("main.adb");
9472    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
9473 @end smallexample
9474
9475 @noindent
9476 If the attribute @code{Source_Files} is not given an explicit value,
9477 but the attribute @code{Source_List_File} is given a string value,
9478 then the source file names are contained in the text file whose path name
9479 (absolute or relative to the directory of the project file) is the
9480 value of the attribute @code{Source_List_File}.
9481
9482 Each line in the file that is not empty or is not a comment
9483 contains a source file name. A comment line starts with two hyphens.
9484
9485 @smallexample
9486    for Source_List_File use "source_list.txt";
9487 @end smallexample
9488
9489 @noindent
9490 By default, if neither the attribute @code{Source_Files} nor the attribute
9491 @code{Source_List_File} is given an explicit value, then each file in the
9492 source directories that conforms to the project's naming scheme
9493 (see @ref{Naming Schemes}) is an immediate source of the project.
9494
9495 A warning is issued if both attributes @code{Source_Files} and
9496 @code{Source_List_File} are given explicit values. In this case, the attribute
9497 @code{Source_Files} prevails.
9498
9499 Each source file name must be the name of one and only one existing source file
9500 in one of the source directories.
9501
9502 A @code{Source_Files} attribute defined with an empty list as its value
9503 indicates that there are no source files in the project.
9504
9505 Except for projects that are clearly specified as containing no Ada source
9506 files (@code{Source_Dirs} or @code{Source_Files} specified as an empty list,
9507 or @code{Languages} specified without @code{"Ada"} in the list)
9508 @smallexample
9509    for Source_Dirs use ();
9510    for Source_Files use ();
9511    for Languages use ("C", "C++");
9512 @end smallexample
9513
9514 @noindent
9515 a project must contain at least one immediate source.
9516
9517 Projects with no source files are useful as template packages
9518 (see @ref{Packages in Project Files}) for other projects; in particular to
9519 define a package @code{Naming} (see @ref{Naming Schemes}).
9520
9521
9522 @c ****************************
9523 @c * Importing Projects *
9524 @c ****************************
9525
9526 @node  Importing Projects
9527 @section Importing Projects
9528
9529 @noindent
9530 An immediate source of a project P may depend on source files that
9531 are neither immediate sources of P nor in the predefined library.
9532 To get this effect, P must @emph{import} the projects that contain the needed
9533 source files.
9534
9535 @smallexample
9536 @group
9537   with "project1", "utilities.gpr";
9538   with "/namings/apex.gpr";
9539   project Main is
9540     ...
9541 @end group
9542 @end smallexample
9543
9544 @noindent
9545 As can be seen in this example, the syntax for importing projects is similar
9546 to the syntax for importing compilation units in Ada. However, project files
9547 use literal strings instead of names, and the @code{with} clause identifies
9548 project files rather than packages.
9549
9550 Each literal string is the file name or path name (absolute or relative) of a
9551 project file. If a string is simply a file name, with no path, then its
9552 location is determined by the @emph{project path}:
9553
9554 @itemize @bullet
9555 @item
9556 If the environment variable @env{ADA_PROJECT_PATH} exists, then the project
9557 path includes all the directories in this environment variable, plus the
9558 directory of the project file.
9559
9560 @item
9561 If the environment variable @env{ADA_PROJECT_PATH} does not exist,
9562 then the project path contains only one directory, namely the one where
9563 the project file is located.
9564 @end itemize
9565
9566 @noindent
9567 If a relative pathname is used as in
9568
9569 @smallexample
9570   with "tests/proj";
9571 @end smallexample
9572
9573 @noindent
9574 then the path is relative to the directory where the importing project file is
9575 located. Any symbolic link will be fully resolved in the directory
9576 of the importing project file before the imported project file is looked up.
9577
9578 When the @code{with}'ed project file name does not have an extension,
9579 the default is @file{.gpr}. If a file with this extension is not found, then
9580 the file name as specified in the @code{with} clause (no extension) will be
9581 used. In the above example, if a file @code{project1.gpr} is found, then it
9582 will be used; otherwise, if a file @code{project1} exists then it will be used;
9583 if neither file exists, this is an error.
9584
9585 A warning is issued if the name of the project file does not match the
9586 name of the project; this check is case insensitive.
9587
9588 Any source file that is an immediate source of the imported project can be
9589 used by the immediate sources of the importing project, and recursively. Thus
9590 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
9591 sources of @code{A} may depend on the immediate sources of @code{C}, even if
9592 @code{A} does not import @code{C} explicitly. However, this is not recommended,
9593 because if and when @code{B} ceases to import @code{C}, some sources in
9594 @code{A} will no longer compile.
9595
9596 A side effect of this capability is that cyclic dependences are not permitted:
9597 if @code{A} imports @code{B} (directly or indirectly) then @code{B} is not
9598 allowed to import @code{A}.
9599
9600
9601 @c *********************
9602 @c * Project Extension *
9603 @c *********************
9604
9605 @node Project Extension
9606 @section Project Extension
9607
9608 @noindent
9609 During development of a large system, it is sometimes necessary to use
9610 modified versions of some of the source files without changing the original
9611 sources. This can be achieved through a facility known as
9612 @emph{project extension}.
9613
9614 @smallexample
9615    project Modified_Utilities extends "/baseline/utilities.gpr" is ...
9616 @end smallexample
9617
9618 @noindent
9619 The project file for the project being extended (the @emph{parent}) is
9620 identified by the literal string that follows the reserved word @code{extends},
9621 which itself follows the name of the extending project (the @emph{child}).
9622
9623 By default, a child project inherits all the sources of its parent.
9624 However, inherited sources can be overridden: a unit with the same name as one
9625 in the parent will hide the original unit.
9626 Inherited sources are considered to be sources (but not immediate sources)
9627 of the child project; see @ref{Project File Syntax}.
9628
9629 An inherited source file retains any switches specified in the parent project.
9630
9631 For example if the project @code{Utilities} contains the specification and the
9632 body of an Ada package @code{Util_IO}, then the project
9633 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
9634 The original body of @code{Util_IO} will not be considered in program builds.
9635 However, the package specification will still be found in the project
9636 @code{Utilities}.
9637
9638 A child project can have only one parent but it may import any number of other
9639 projects.
9640
9641 A project is not allowed to import directly or indirectly at the same time a
9642 child project and any of its ancestors.
9643
9644
9645 @c ****************************************
9646 @c * External References in Project Files *
9647 @c ****************************************
9648
9649 @node  External References in Project Files
9650 @section External References in Project Files
9651
9652 @noindent
9653 A project file may contain references to external variables; such references
9654 are called @emph{external references}.
9655
9656 An external variable is either defined as part of the environment (an
9657 environment variable in Unix, for example) or else specified on the command
9658 line via the @option{-X@emph{vbl}=@emph{value}} switch. If both, then the
9659 command line value is used.
9660
9661 An external reference is denoted by the built-in function
9662 @code{external}, which returns a string value.  This function has two forms:
9663 @itemize @bullet
9664 @item @code{external (external_variable_name)}
9665 @item @code{external (external_variable_name, default_value)}
9666 @end itemize
9667
9668 @noindent
9669 Each parameter must be a string literal.  For example:
9670
9671 @smallexample
9672    external ("USER")
9673    external ("OS", "Linux")
9674 @end smallexample
9675
9676 @noindent
9677 In the form with one parameter, the function returns the value of
9678 the external variable given as parameter. If this name is not present in the
9679 environment, then the returned value is an empty string.
9680
9681 In the form with two string parameters, the second parameter is
9682 the value returned when the variable given as the first parameter is not
9683 present in the environment. In the example above, if @code{"OS"} is not
9684 the name of an environment variable and is not passed on the command line,
9685 then the returned value will be @code{"Linux"}.
9686
9687 An external reference may be part of a string expression or of a string
9688 list expression, to define variables or attributes.
9689
9690 @smallexample
9691 @group
9692    type Mode_Type is ("Debug", "Release");
9693    Mode : Mode_Type := external ("MODE");
9694    case Mode is
9695      when "Debug" =>
9696         ...
9697 @end group
9698 @end smallexample
9699
9700
9701 @c *****************************
9702 @c * Packages in Project Files *
9703 @c *****************************
9704
9705 @node  Packages in Project Files
9706 @section Packages in Project Files
9707
9708 @noindent
9709 The @emph{package} is the project file feature that defines the settings for
9710 project-aware tools.
9711 For each such tool you can declare a corresponding package; the names for these
9712 packages are preset (see @ref{Packages}) but are not case sensitive.
9713 A package may contain variable declarations, attribute declarations, and case
9714 constructions.
9715
9716 @smallexample
9717 @group
9718    project Proj is
9719       package Builder is  -- used by gnatmake
9720          for Default_Switches ("Ada") use ("-v", "-g");
9721       end Builder;
9722    end Proj;
9723 @end group
9724 @end smallexample
9725
9726 @noindent
9727 A package declaration starts with the reserved word @code{package},
9728 followed by the package name (case insensitive), followed by the reserved word
9729 @code{is}. It ends with the reserved word @code{end}, followed by the package
9730 name, finally followed by a semi-colon.
9731
9732 Most of the packages have an attribute @code{Default_Switches}.
9733 This attribute is an associative array, and its value is a string list.
9734 The index of the associative array is the name of a programming language (case
9735 insensitive). This attribute indicates the switch or switches to be used
9736 with the corresponding tool.
9737
9738 Some packages also have another attribute, @code{Switches}, an associative
9739 array whose value is a string list. The index is the name of a source file.
9740 This attribute indicates the switch or switches to be used by the corresponding
9741 tool when dealing with this specific file.
9742
9743 Further information on these switch-related attributes is found in
9744 @ref{Switches and Project Files}.
9745
9746 A package may be declared as a @emph{renaming} of another package; e.g., from
9747 the project file for an imported project.
9748
9749 @smallexample
9750 @group
9751   with "/global/apex.gpr";
9752   project Example is
9753     package Naming renames Apex.Naming;
9754     ...
9755   end Example;
9756 @end group
9757 @end smallexample
9758
9759 @noindent
9760 Packages that are renamed in other project files often come from project files
9761 that have no sources: they are just used as templates. Any modification in the
9762 template will be reflected automatically in all the project files that rename
9763 a package from the template.
9764
9765 In addition to the tool-oriented packages, you can also declare a package
9766 named @code{Naming} to establish specialized source file naming conventions
9767 (see @ref{Naming Schemes}).
9768
9769
9770 @c ************************************
9771 @c * Variables from Imported Projects *
9772 @c ************************************
9773
9774 @node Variables from Imported Projects
9775 @section Variables from Imported Projects
9776
9777 @noindent
9778 An attribute or variable defined in an imported or parent project can
9779 be used in expressions in the importing / extending project.
9780 Such an attribute or variable is prefixed with the name of the project
9781 and (if relevant) the name of package where it is defined.
9782
9783 @smallexample
9784 @group
9785   with "imported";
9786   project Main extends "base" is
9787      Var1 := Imported.Var;
9788      Var2 := Base.Var & ".new";
9789 @end group
9790
9791 @group
9792      package Builder is
9793         for Default_Switches ("Ada") use Imported.Builder.Ada_Switches &
9794                          "-gnatg" & "-v";
9795      end Builder;
9796 @end group
9797
9798 @group
9799      package Compiler is
9800         for Default_Switches ("Ada") use Base.Compiler.Ada_Switches;
9801      end Compiler;
9802   end Main;
9803 @end group
9804 @end smallexample
9805
9806 @noindent
9807 In this example:
9808
9809 @itemize @bullet
9810 @item
9811 @code{Var1} is a copy of the variable @code{Var} defined in the project file
9812 @file{"imported.gpr"}
9813 @item
9814 the value of @code{Var2} is a copy of the value of variable @code{Var}
9815 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
9816 @item
9817 attribute @code{Default_Switches ("Ada")} in package @code{Builder}
9818 is a string list that includes in its value a copy of variable
9819 @code{Ada_Switches} defined in the @code{Builder} package in project file
9820 @file{imported.gpr} plus two new elements: @option{"-gnatg"} and @option{"-v"};
9821 @item
9822 attribute @code{Default_Switches ("Ada")} in package @code{Compiler}
9823 is a copy of the variable @code{Ada_Switches} defined in the @code{Compiler}
9824 package in project file @file{base.gpr}, the project being extended.
9825 @end itemize
9826
9827
9828 @c ******************
9829 @c * Naming Schemes *
9830 @c ******************
9831
9832 @node  Naming Schemes
9833 @section Naming Schemes
9834
9835 @noindent
9836 Sometimes an Ada software system is ported from a foreign compilation
9837 environment to GNAT, with file names that do not use the default GNAT
9838 conventions. Instead of changing all the file names (which for a variety of
9839 reasons might not be possible), you can define the relevant file naming scheme
9840 in the @code{Naming} package in your project file.  For example, the following
9841 package models the Apex file naming rules:
9842
9843 @smallexample
9844 @group
9845   package Naming is
9846     for Casing                        use "lowercase";
9847     for Dot_Replacement               use ".";
9848     for Specification_Suffix ("Ada")  use ".1.ada";
9849     for Implementation_Suffix ("Ada") use ".2.ada";
9850   end Naming;
9851 @end group
9852 @end smallexample
9853
9854 @noindent
9855 You can define the following attributes in package @code{Naming}:
9856
9857 @table @code
9858
9859 @item @var{Casing}
9860 This must be a string with one of the three values @code{"lowercase"},
9861 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
9862
9863 @noindent
9864 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
9865
9866 @item @var{Dot_Replacement}
9867 This must be a string whose value satisfies the following conditions:
9868
9869 @itemize @bullet
9870 @item It must not be empty
9871 @item It cannot start or end with an alphanumeric character
9872 @item It cannot be a single underscore
9873 @item It cannot start with an underscore followed by an alphanumeric
9874 @item It cannot contain a dot @code{'.'} except if it the entire string is @code{"."}
9875 @end itemize
9876
9877 @noindent
9878 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
9879
9880 @item @var{Specification_Suffix}
9881 This is an associative array (indexed by the programming language name, case
9882 insensitive) whose value is a string that must satisfy the following
9883 conditions:
9884
9885 @itemize @bullet
9886 @item It must not be empty
9887 @item It cannot start with an alphanumeric character
9888 @item It cannot start with an underscore followed by an alphanumeric character
9889 @end itemize
9890 @noindent
9891 If @code{Specification_Suffix ("Ada")} is not specified, then the default is
9892 @code{".ads"}.
9893
9894 @item @var{Implementation_Suffix}
9895 This is an associative array (indexed by the programming language name, case
9896 insensitive) whose value is a string that must satisfy the following
9897 conditions:
9898
9899 @itemize @bullet
9900 @item It must not be empty
9901 @item It cannot start with an alphanumeric character
9902 @item It cannot start with an underscore followed by an alphanumeric character
9903 @item It cannot be a suffix of @code{Specification_Suffix}
9904 @end itemize
9905 @noindent
9906 If @code{Implementation_Suffix ("Ada")} is not specified, then the default is
9907 @code{".adb"}.
9908
9909 @item @var{Separate_Suffix}
9910 This must be a string whose value satisfies the same conditions as
9911 @code{Implementation_Suffix}.
9912
9913 @noindent
9914 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
9915 value as @code{Implementation_Suffix ("Ada")}.
9916
9917 @item @var{Specification}
9918 @noindent
9919 You can use the @code{Specification} attribute, an associative array, to define
9920 the source file name for an individual Ada compilation unit's spec. The array
9921 index must be a string literal that identifies the Ada unit (case insensitive).
9922 The value of this attribute must be a string that identifies the file that
9923 contains this unit's spec (case sensitive or insensitive depending on the
9924 operating system).
9925
9926 @smallexample
9927    for Specification ("MyPack.MyChild") use "mypack.mychild.spec";
9928 @end smallexample
9929
9930 @item @var{Implementation}
9931
9932 You can use the @code{Implementation} attribute, an associative array, to
9933 define the source file name for an individual Ada compilation unit's body
9934 (possibly a subunit).  The array index must be a string literal that identifies
9935 the Ada unit (case insensitive).  The value of this attribute must be a string
9936 that identifies the file that contains this unit's body or subunit (case
9937 sensitive or insensitive depending on the operating system).
9938
9939 @smallexample
9940    for Implementation ("MyPack.MyChild") use "mypack.mychild.body";
9941 @end smallexample
9942 @end table
9943
9944
9945 @c ********************
9946 @c * Library Projects *
9947 @c ********************
9948
9949 @node Library Projects
9950 @section Library Projects
9951
9952 @noindent
9953 @emph{Library projects} are projects whose object code is placed in a library.
9954 (Note that this facility is not yet supported on all platforms)
9955
9956 To create a library project, you need to define in its project file
9957 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
9958 Additionally, you may define the library-related attributes
9959 @code{Library_Kind}, @code{Library_Version} and @code{Library_Elaboration}.
9960
9961 The @code{Library_Name} attribute has a string value that must start with a
9962 letter and include only letters and digits.
9963
9964 The @code{Library_Dir} attribute has a string value that designates the path
9965 (absolute or relative) of the directory where the library will reside.
9966 It must designate an existing directory, and this directory needs to be
9967 different from the project's object directory. It also needs to be writable.
9968
9969 If both @code{Library_Name} and @code{Library_Dir} are specified and
9970 are legal, then the project file defines a library project.  The optional
9971 library-related attributes are checked only for such project files.
9972
9973 The @code{Library_Kind} attribute has a string value that must be one of the
9974 following (case insensitive): @code{"static"}, @code{"dynamic"} or
9975 @code{"relocatable"}. If this attribute is not specified, the library is a
9976 static library. Otherwise, the library may be dynamic or relocatable.
9977 Depending on the operating system, there may or may not be a distinction
9978 between dynamic and relocatable libraries. For example, on Unix there is no
9979 such distinction.
9980
9981 The @code{Library_Version} attribute has a string value whose interpretation
9982 is platform dependent. On Unix, it is used only for dynamic/relocatable
9983 libraries as the internal name of the library (the @code{"soname"}). If the
9984 library file name (built from the @code{Library_Name}) is different from the
9985 @code{Library_Version}, then the library file will be a symbolic link to the
9986 actual file whose name will be @code{Library_Version}.
9987
9988 Example (on Unix):
9989
9990 @smallexample
9991 @group
9992 project Plib is
9993
9994    Version := "1";
9995
9996    for Library_Dir use "lib_dir";
9997    for Library_Name use "dummy";
9998    for Library_Kind use "relocatable";
9999    for Library_Version use "libdummy.so." & Version;
10000
10001 end Plib;
10002 @end group
10003 @end smallexample
10004
10005 @noindent
10006 Directory @file{lib_dir} will contain the internal library file whose name
10007 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
10008 @file{libdummy.so.1}.
10009
10010 When @command{gnatmake} detects that a project file (not the main project file)
10011 is a library project file, it will check all immediate sources of the project
10012 and rebuild the library if any of the sources have been recompiled.
10013 All @file{ALI} files will also be copied from the object directory to the
10014 library directory. To build executables, @command{gnatmake} will use the
10015 library rather than the individual object files.
10016
10017
10018 @c *************************************
10019 @c * Switches Related to Project Files *
10020 @c *************************************
10021 @node Switches Related to Project Files
10022 @section Switches Related to Project Files
10023
10024 @noindent
10025 The following switches are used by GNAT tools that support project files:
10026
10027 @table @code
10028
10029 @item @option{-P@var{project}}
10030 Indicates the name of a project file. This project file will be parsed with
10031 the verbosity indicated by @option{-vP@emph{x}}, if any, and using the external
10032 references indicated by @option{-X} switches, if any.
10033
10034 @noindent
10035 There must be only one @option{-P} switch on the command line.
10036
10037 @noindent
10038 Since the Project Manager parses the project file only after all the switches
10039 on the command line are checked, the order of the switches @option{-P},
10040 @option{-Vp@emph{x}} or @option{-X} is not significant.
10041
10042 @item @option{-X@var{name=value}}
10043 Indicates that external variable @var{name} has the value @var{value}.
10044 The Project Manager will use this value for occurrences of
10045 @code{external(name)} when parsing the project file.
10046
10047 @noindent
10048 If @var{name} or @var{value} includes a space, then @var{name=value} should be
10049 put between quotes.
10050 @smallexample
10051   -XOS=NT
10052   -X"user=John Doe"
10053 @end smallexample
10054
10055 @noindent
10056 Several @option{-X} switches can be used simultaneously.
10057 If several @option{-X} switches specify the same @var{name}, only the last one
10058 is used.
10059
10060 @noindent
10061 An external variable specified with a @option{-X} switch takes precedence
10062 over the value of the same name in the environment.
10063
10064 @item @option{-vP@emph{x}}
10065 Indicates the verbosity of the parsing of GNAT project files.
10066 @option{-vP0} means Default (no output for syntactically correct project
10067 files);
10068 @option{-vP1} means Medium;
10069 @option{-vP2} means High.
10070 @noindent
10071 The default is Default.
10072 @noindent
10073 If several @option{-vP@emph{x}} switches are present, only the last one is
10074 used.
10075
10076 @end table
10077
10078
10079 @c **********************************
10080 @c * Tools Supporting Project Files *
10081 @c **********************************
10082
10083 @node  Tools Supporting Project Files
10084 @section Tools Supporting Project Files
10085
10086 @menu
10087 * gnatmake and Project Files::
10088 * The GNAT Driver and Project Files::
10089 * Glide and Project Files::
10090 @end menu
10091
10092 @node gnatmake and Project Files
10093 @subsection gnatmake and Project Files
10094
10095 @noindent
10096 This section covers two topics related to @command{gnatmake} and project files:
10097 defining switches for @command{gnatmake} and for the tools that it invokes;
10098 and the use of the @code{Main} attribute.
10099
10100 @menu
10101 * Switches and Project Files::
10102 * Project Files and Main Subprograms::
10103 @end menu
10104
10105 @node Switches and Project Files
10106 @subsubsection Switches and Project Files
10107
10108 @noindent
10109 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
10110 @code{Linker}, you can specify a @code{Default_Switches} attribute, a
10111 @code{Switches} attribute, or both; as their names imply, these switch-related
10112 attributes affect which switches are used for which files when
10113 @command{gnatmake} is invoked.  As will be explained below, these
10114 package-contributed switches precede the switches passed on the
10115 @command{gnatmake} command line.
10116
10117 The @code{Default_Switches} attribute is an associative array indexed by
10118 language name (case insensitive) and returning a string list.  For example:
10119
10120 @smallexample
10121 @group
10122 package Compiler is
10123   for Default_Switches ("Ada") use ("-gnaty", "-v");
10124 end Compiler;
10125 @end group
10126 @end smallexample
10127
10128 @noindent
10129 The @code{Switches} attribute is also an associative array, indexed by a file
10130 name (which may or may not be case sensitive, depending on the operating
10131 system) and returning a string list.  For example:
10132
10133 @smallexample
10134 @group
10135 package Builder is
10136    for Switches ("main1.adb") use ("-O2");
10137    for Switches ("main2.adb") use ("-g");
10138 end Builder;
10139 @end group
10140 @end smallexample
10141
10142 @noindent
10143 For the @code{Builder} package, the file names should designate source files
10144 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
10145 file names should designate @file{ALI} or source files for main subprograms.
10146 In each case just the file name (without explicit extension) is acceptable.
10147
10148 For each tool used in a program build (@command{gnatmake}, the compiler, the
10149 binder, and the linker), its corresponding package @dfn{contributes} a set of
10150 switches for each file on which the tool is invoked, based on the
10151 switch-related attributes defined in the package. In particular, the switches
10152 that each of these packages contributes for a given file @var{f} comprise:
10153
10154 @itemize @bullet
10155 @item
10156 the value of attribute @code{Switches (@var{f})}, if it is specified in the
10157 package for the given file,
10158 @item
10159 otherwise, the value of @code{Default_Switches ("Ada")}, if it is specified in
10160 the package.
10161 @end itemize
10162
10163 @noindent
10164 If neither of these attributes is defined in the package, then the package does
10165 not contribute any switches for the given file.
10166
10167 When @command{gnatmake} is invoked on a file, the switches comprise two sets,
10168 in the following order: those contributed for the file by the @code{Builder}
10169 package; and the switches passed on the command line.
10170
10171 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
10172 the switches passed to the tool comprise three sets, in the following order:
10173
10174 @enumerate
10175 @item
10176 the applicable switches contributed for the file by the @code{Builder} package
10177 in the project file supplied on the command line;
10178
10179 @item
10180 those contributed for the file by the package (in the relevant project file --
10181 see below) corresponding to the tool; and
10182
10183 @item
10184 the applicable switches passed on the command line.
10185 @end enumerate
10186
10187 @noindent
10188 The term @emph{applicable switches} reflects the fact that @command{gnatmake}
10189 switches may or may not be passed to individual tools, depending on the
10190 individual switch.
10191
10192 @command{gnatmake} may invoke the compiler on source files from different
10193 projects. The Project Manager will use the appropriate project file to
10194 determine the @code{Compiler} package for each source file being compiled.
10195 Likewise for the @code{Binder} and @code{Linker} packages.
10196
10197 As an example, consider the following package in a project file:
10198
10199 @smallexample
10200 @group
10201 project Proj1 is
10202    package Compiler is
10203       for Default_Switches ("Ada") use ("-g");
10204       for Switches ("a.adb") use ("-O1");
10205       for Switches ("b.adb") use ("-O2", "-gnaty");
10206    end Compiler;
10207 end Proj1;
10208 @end group
10209 @end smallexample
10210
10211 @noindent
10212 If @command{gnatmake} is invoked with this project file, and it needs to
10213 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
10214 @file{a.adb} will be compiled with the switch @option{-O1}, @file{b.adb}
10215 with switches @option{-O2} and @option{-gnaty}, and @file{c.adb} with
10216 @option{-g}.
10217
10218 Another example illustrates the ordering of the switches contributed by
10219 different packages:
10220
10221 @smallexample
10222 @group
10223 project Proj2 is
10224    package Builder is
10225       for Switches ("main.adb") use ("-g", "-O1", "-f");
10226    end Builder;
10227 @end group
10228
10229 @group
10230    package Compiler is
10231       for Switches ("main.adb") use ("-O2");
10232    end Compiler;
10233 end Proj2;
10234 @end group
10235 @end smallexample
10236
10237 @noindent
10238 If you issue the command:
10239
10240 @smallexample
10241     gnatmake -PProj2 -O0 main
10242 @end smallexample
10243
10244 @noindent
10245 then the compiler will be invoked on @file{main.adb} with the following sequence of switches
10246
10247 @smallexample
10248    -g -O1 -O2 -O0
10249 @end smallexample
10250
10251 with the last @option{-O} switch having precedence over the earlier ones;
10252 several other switches (such as @option{-c}) are added implicitly.
10253
10254 The switches @option{-g} and @option{-O1} are contributed by package
10255 @code{Builder},  @option{-O2} is contributed by the package @code{Compiler}
10256 and @option{-O0} comes from the command line.
10257
10258 The @option{-g} switch will also be passed in the invocation of
10259 @command{gnatlink.}
10260
10261 A final example illustrates switch contributions from packages in different
10262 project files:
10263
10264 @smallexample
10265 @group
10266 project Proj3 is
10267    for Source_Files use ("pack.ads", "pack.adb");
10268    package Compiler is
10269       for Default_Switches ("Ada") use ("-gnata");
10270    end Compiler;
10271 end Proj3;
10272 @end group
10273
10274 @group
10275 with "Proj3";
10276 project Proj4 is
10277    for Source_Files use ("foo_main.adb", "bar_main.adb");
10278    package Builder is
10279       for Switches ("foo_main.adb") use ("-s", "-g");
10280    end Builder;
10281 end Proj4;
10282 @end group
10283
10284 @group
10285 -- Ada source file:
10286 with Pack;
10287 procedure Foo_Main is
10288    ...
10289 end Foo_Main;
10290 @end group
10291 @end smallexample
10292
10293 If the command is
10294 @smallexample
10295 gnatmake -PProj4 foo_main.adb -cargs -gnato
10296 @end smallexample
10297
10298 @noindent
10299 then the switches passed to the compiler for @file{foo_main.adb} are
10300 @option{-g} (contributed by the package @code{Proj4.Builder}) and
10301 @option{-gnato} (passed on the command line).
10302 When the imported package @code{Pack} is compiled, the switches used are
10303 @option{-g} from @code{Proj4.Builder}, @option{-gnata} (contributed from
10304 package @code{Proj3.Compiler}, and @option{-gnato} from the command line.
10305
10306
10307 @node Project Files and Main Subprograms
10308 @subsubsection Project Files and Main Subprograms
10309
10310 @noindent
10311 When using a project file, you can invoke @command{gnatmake}
10312 with several main subprograms, by specifying their source files on the command
10313 line.  Each of these needs to be an immediate source file of the project.
10314
10315 @smallexample
10316     gnatmake -Pprj main1 main2 main3
10317 @end smallexample
10318
10319 @noindent
10320 When using a project file, you can also invoke @command{gnatmake} without
10321 explicitly specifying any main, and the effect depends on whether you have
10322 defined the @code{Main} attribute.  This attribute has a string list value,
10323 where each element in the list is the name of a source file (the file
10324 extension is optional) containing a main subprogram.
10325
10326 If the @code{Main} attribute is defined in a project file as a non-empty
10327 string list and the switch @option{-u} is not used on the command line, then
10328 invoking @command{gnatmake} with this project file but without any main on the
10329 command line is equivalent to invoking @command{gnatmake} with all the file
10330 names in the @code{Main} attribute on the command line.
10331
10332 Example:
10333 @smallexample
10334 @group
10335    project Prj is
10336       for Main use ("main1", "main2", "main3");
10337    end Prj;
10338 @end group
10339 @end smallexample
10340
10341 @noindent
10342 With this project file, @code{"gnatmake -Pprj"} is equivalent to
10343 @code{"gnatmake -Pprj main1 main2 main3"}.
10344
10345 When the project attribute @code{Main} is not specified, or is specified
10346 as an empty string list, or when the switch @option{-u} is used on the command
10347 line, then invoking @command{gnatmake} with no main on the command line will
10348 result in all immediate sources of the project file being checked, and
10349 potentially recompiled. Depending on the presence of the switch @option{-u},
10350 sources from other project files on which the immediate sources of the main
10351 project file depend are also checked and potentially recompiled. In other
10352 words, the @option{-u} switch is applied to all of the immediate sources of themain project file.
10353
10354
10355 @node The GNAT Driver and Project Files
10356 @subsection The GNAT Driver and Project Files
10357
10358 @noindent
10359 A number of GNAT tools, other than @command{gnatmake} are project-aware:
10360 @command{gnatbind}, @command{gnatfind}, @command{gnatlink}, @command{gnatls}
10361 and @command{gnatxref}. However, none of these tools can be invoked directly
10362 with a project file switch (@code{-P}). They need to be invoke through the
10363 @command{gnat} driver.
10364
10365 The @command{gnat} driver is a front-end that accepts a number of commands and
10366 call the corresponding tool. It has been designed initially for VMS to convert
10367 VMS style qualifiers to Unix style switches, but it is now available to all
10368 the GNAT supported platforms.
10369
10370 On non VMS platforms, the @command{gnat} driver accepts the following commands
10371 (case insensitive):
10372
10373 @itemize @bullet
10374 @item
10375 BIND to invoke @command{gnatbind}
10376 @item
10377 CHOP to invoke @command{gnatchop}
10378 @item
10379 COMP or COMPILE to invoke the compiler
10380 @item
10381 ELIM to invoke @command{gnatelim}
10382 @item
10383 FIND to invoke @command{gnatfind}
10384 @item
10385 KR or KRUNCH to invoke @command{gnatkr}
10386 @item
10387 LINK to invoke @command{gnatlink}
10388 @item
10389 LS or LIST to invoke @command{gnatls}
10390 @item
10391 MAKE to invoke @command{gnatmake}
10392 @item
10393 NAME to invoke @command{gnatname}
10394 @item
10395 PREP or PREPROCESS to invoke @command{gnatprep}
10396 @item
10397 PSTA or STANDARD to invoke @command{gnatpsta}
10398 @item
10399 STUB to invoke @command{gnatstub}
10400 @item
10401 XREF to invoke @command{gnatxref}
10402 @end itemize
10403
10404 @noindent
10405 Note that the compiler is invoked using the command @command{gnatmake -f -u}.
10406
10407 @noindent
10408 Following the command, you may put switches and arguments for the invoked
10409 tool.
10410
10411 @smallexample
10412   gnat bind -C main.ali
10413   gnat ls -a main
10414   gnat chop foo.txt
10415 @end smallexample
10416
10417 @noindent
10418 In addition, for command BIND, FIND, LS or LIST, LINK and XREF, the project
10419 file related switches (@code{-P}, @code{-X} and @code{-vPx}) may be used in
10420 addition to the switches of the invoking tool.
10421
10422 @noindent
10423 For each of these command, there is possibly a package in the main project that
10424 corresponds to the invoked tool.
10425
10426 @itemize @bullet
10427 @item
10428 package @code{Binder} for command BIND (invoking @code{gnatbind})
10429
10430 @item
10431 package @code{Finder} for command FIND (invoking @code{gnatfind})
10432
10433 @item
10434 package @code{Gnatls} for command LS or LIST (invoking @code{gnatls})
10435
10436 @item
10437 package @code{Linker} for command LINK (invoking @code{gnatlink})
10438
10439 @item
10440 package @code{Cross_Reference} for command XREF (invoking @code{gnatlink})
10441
10442 @end itemize
10443
10444 @noindent
10445 Package @code{Gnatls} has a unique attribute @code{Switches}, a simple variable
10446 with a string list value. It contains switches for the invocation of
10447 @code{gnatls}.
10448
10449 @smallexample
10450 @group
10451 project Proj1 is
10452    package gnatls is
10453       for Switches use ("-a", "-v");
10454    end gnatls;
10455 end Proj1;
10456 @end group
10457 @end smallexample
10458
10459 @noindent
10460 All other packages contains a switch @code{Default_Switches}, an associative
10461 array, indexed by the programming language (case insensitive) and having a
10462 string list value. @code{Default_Switches ("Ada")} contains the switches for
10463 the invocation of the tool corresponding to the package.
10464
10465 @smallexample
10466 @group
10467 project Proj is
10468
10469    for Source_Dirs use ("./**");
10470
10471    package gnatls is
10472       for Switches use ("-a", "-v");
10473    end gnatls;
10474 @end group
10475 @group
10476
10477    package Binder is
10478       for Default_Switches ("Ada") use ("-C", "-e");
10479    end Binder;
10480 @end group
10481 @group
10482
10483    package Linker is
10484       for Default_Switches ("Ada") use ("-C");
10485    end Linker;
10486 @end group
10487 @group
10488
10489    package Finder is
10490       for Default_Switches ("Ada") use ("-a", "-f");
10491    end Finder;
10492 @end group
10493 @group
10494
10495    package Cross_Reference is
10496       for Default_Switches ("Ada") use ("-a", "-f", "-d", "-u");
10497    end Cross_Reference;
10498 end Proj;
10499 @end group
10500 @end smallexample
10501
10502 @noindent
10503 With the above project file, commands such as
10504
10505 @smallexample
10506    gnat ls -Pproj main
10507    gnat xref -Pproj main
10508    gnat bind -Pproj main.ali
10509 @end smallexample
10510
10511 @noindent
10512 will set up the environment properly and invoke the tool with the switches
10513 found in the package corresponding to the tool.
10514
10515
10516 @node Glide and Project Files
10517 @subsection Glide and Project Files
10518
10519 @noindent
10520 Glide will automatically recognize the @file{.gpr} extension for
10521 project files, and will
10522 convert them to its own internal format automatically. However, it
10523 doesn't provide a syntax-oriented editor for modifying these
10524 files.
10525 The project file will be loaded as text when you select the menu item
10526 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
10527 You can edit this text and save the @file{gpr} file;
10528 when you next select this project file in Glide it
10529 will be automatically reloaded.
10530
10531
10532
10533 @node An Extended Example
10534 @section An Extended Example
10535
10536 @noindent
10537 Suppose that we have two programs, @var{prog1} and @var{prog2}, with the sources
10538 in the respective directories. We would like to build them with a single
10539 @command{gnatmake} command, and we would like to place their object files into
10540 @file{.build} subdirectories of the source directories. Furthermore, we would
10541 like to have to have two separate subdirectories in @file{.build}  --
10542 @file{release} and @file{debug} -- which will contain the object files compiled with
10543 different set of compilation flags.
10544
10545 In other words, we have the following structure:
10546
10547 @smallexample
10548 @group
10549    main
10550      |- prog1
10551      |    |- .build
10552      |         | debug
10553      |         | release
10554      |- prog2
10555           |- .build
10556                | debug
10557                | release
10558 @end group
10559 @end smallexample
10560
10561 @noindent
10562 Here are the project files that we need to create in a directory @file{main}
10563 to maintain this structure:
10564
10565 @enumerate
10566
10567 @item We create a @code{Common} project with a package @code{Compiler} that
10568 specifies the compilation switches:
10569
10570 @smallexample
10571 File "common.gpr":
10572 @group
10573 @b{project} Common @b{is}
10574
10575    @b{for} Source_Dirs @b{use} (); -- No source files
10576 @end group
10577
10578 @group
10579    @b{type} Build_Type @b{is} ("release", "debug");
10580    Build : Build_Type := External ("BUILD", "debug");
10581 @end group
10582 @group
10583    @b{package} Compiler @b{is}
10584       @b{case} Build @b{is}
10585          @b{when} "release" =>
10586            @b{for} Default_Switches ("Ada") @b{use} ("-O2");
10587          @b{when} "debug"   =>
10588            @b{for} Default_Switches ("Ada") @b{use} ("-g");
10589       @b{end case};
10590    @b{end} Compiler;
10591
10592 @b{end} Common;
10593 @end group
10594 @end smallexample
10595
10596 @item We create separate projects for the two programs:
10597
10598 @smallexample
10599 @group
10600 File "prog1.gpr":
10601
10602 @b{with} "common";
10603 @b{project} Prog1 @b{is}
10604
10605     @b{for} Source_Dirs @b{use} ("prog1");
10606     @b{for} Object_Dir  @b{use} "prog1/.build/" & Common.Build;
10607
10608     @b{package} Compiler @b{renames} Common.Compiler;
10609
10610 @b{end} Prog1;
10611 @end group
10612 @end smallexample
10613
10614 @smallexample
10615 @group
10616 File "prog2.gpr":
10617
10618 @b{with} "common";
10619 @b{project} Prog2 @b{is}
10620
10621     @b{for} Source_Dirs @b{use} ("prog2");
10622     @b{for} Object_Dir  @b{use} "prog2/.build/" & Common.Build;
10623
10624     @b{package} Compiler @b{renames} Common.Compiler;
10625
10626 @end group
10627 @b{end} Prog2;
10628 @end smallexample
10629
10630 @item We create a wrapping project @var{Main}:
10631
10632 @smallexample
10633 @group
10634 File "main.gpr":
10635
10636 @b{with} "common";
10637 @b{with} "prog1";
10638 @b{with} "prog2";
10639 @b{project} Main @b{is}
10640
10641    @b{package} Compiler @b{renames} Common.Compiler;
10642
10643 @b{end} Main;
10644 @end group
10645 @end smallexample
10646
10647 @item Finally we need to create a dummy procedure that @code{with}s (either
10648 explicitly or implicitly) all the sources of our two programs.
10649
10650 @end enumerate
10651
10652 @noindent
10653 Now we can build the programs using the command
10654
10655 @smallexample
10656    gnatmake -Pmain dummy
10657 @end smallexample
10658
10659 @noindent
10660 for the Debug mode, or
10661
10662 @smallexample
10663    gnatmake -Pmain -XBUILD=release
10664 @end smallexample
10665
10666 @noindent
10667 for the Release mode.
10668
10669
10670 @c ********************************
10671 @c * Project File Complete Syntax *
10672 @c ********************************
10673
10674 @node Project File Complete Syntax
10675 @section Project File Complete Syntax
10676
10677 @smallexample
10678 project ::=
10679   context_clause project_declaration
10680
10681 context_clause ::=
10682   @{with_clause@}
10683
10684 with_clause ::=
10685   @b{with} literal_string @{ , literal_string @} ;
10686
10687 project_declaration ::=
10688   @b{project} <project_>simple_name [ @b{extends} literal_string ] @b{is}
10689     @{declarative_item@}
10690   @b{end} <project_>simple_name;
10691
10692 declarative_item ::=
10693   package_declaration |
10694   typed_string_declaration |
10695   other_declarative_item
10696
10697 package_declaration ::=
10698   @b{package} <package_>simple_name package_completion
10699
10700 package_completion ::=
10701   package_body | package_renaming
10702
10703 package body ::=
10704   @b{is}
10705     @{other_declarative_item@}
10706   @b{end} <package_>simple_name ;
10707
10708 package_renaming ::==
10709   @b{renames} <project_>simple_name.<package_>simple_name ;
10710
10711 typed_string_declaration ::=
10712   @b{type} <typed_string_>_simple_name @b{is}
10713    ( literal_string @{, literal_string@} );
10714
10715 other_declarative_item ::=
10716   attribute_declaration |
10717   typed_variable_declaration |
10718   variable_declaration |
10719   case_construction
10720
10721 attribute_declaration ::=
10722   @b{for} attribute @b{use} expression ;
10723
10724 attribute ::=
10725   <simple_attribute_>simple_name |
10726   <associative_array_attribute_>simple_name ( literal_string )
10727
10728 typed_variable_declaration ::=
10729   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
10730
10731 variable_declaration ::=
10732   <variable_>simple_name := expression;
10733
10734 expression ::=
10735   term @{& term@}
10736
10737 term ::=
10738   literal_string |
10739   string_list |
10740   <variable_>name |
10741   external_value |
10742   attribute_reference
10743
10744 literal_string ::=
10745   (same as Ada)
10746
10747 string_list ::=
10748   ( <string_>expression @{ , <string_>expression @} )
10749
10750 external_value ::=
10751   @b{external} ( literal_string [, literal_string] )
10752
10753 attribute_reference ::=
10754   attribute_parent ' <simple_attribute_>simple_name [ ( literal_string ) ]
10755
10756 attribute_parent ::=
10757   @b{project} |
10758   <project_or_package>simple_name |
10759   <project_>simple_name . <package_>simple_name
10760
10761 case_construction ::=
10762   @b{case} <typed_variable_>name @b{is}
10763     @{case_item@}
10764   @b{end case} ;
10765
10766 case_item ::=
10767   @b{when} discrete_choice_list => @{case_construction | attribute_declaration@}
10768
10769 discrete_choice_list ::=
10770   literal_string @{| literal_string@}
10771
10772 name ::=
10773   simple_name @{. simple_name@}
10774
10775 simple_name ::=
10776   identifier (same as Ada)
10777
10778 @end smallexample
10779
10780
10781 @node Elaboration Order Handling in GNAT
10782 @chapter Elaboration Order Handling in GNAT
10783 @cindex Order of elaboration
10784 @cindex Elaboration control
10785
10786 @menu
10787 * Elaboration Code in Ada 95::
10788 * Checking the Elaboration Order in Ada 95::
10789 * Controlling the Elaboration Order in Ada 95::
10790 * Controlling Elaboration in GNAT - Internal Calls::
10791 * Controlling Elaboration in GNAT - External Calls::
10792 * Default Behavior in GNAT - Ensuring Safety::
10793 * Elaboration Issues for Library Tasks::
10794 * Mixing Elaboration Models::
10795 * What to Do If the Default Elaboration Behavior Fails::
10796 * Elaboration for Access-to-Subprogram Values::
10797 * Summary of Procedures for Elaboration Control::
10798 * Other Elaboration Order Considerations::
10799 @end menu
10800
10801 @noindent
10802 This chapter describes the handling of elaboration code in Ada 95 and
10803 in GNAT, and discusses how the order of elaboration of program units can
10804 be controlled in GNAT, either automatically or with explicit programming
10805 features.
10806
10807 @node Elaboration Code in Ada 95
10808 @section Elaboration Code in Ada 95
10809
10810 @noindent
10811 Ada 95 provides rather general mechanisms for executing code at elaboration
10812 time, that is to say before the main program starts executing. Such code arises
10813 in three contexts:
10814
10815 @table @asis
10816 @item Initializers for variables.
10817 Variables declared at the library level, in package specs or bodies, can
10818 require initialization that is performed at elaboration time, as in:
10819 @smallexample
10820 @cartouche
10821 Sqrt_Half : Float := Sqrt (0.5);
10822 @end cartouche
10823 @end smallexample
10824
10825 @item Package initialization code
10826 Code in a @code{BEGIN-END} section at the outer level of a package body is
10827 executed as part of the package body elaboration code.
10828
10829 @item Library level task allocators
10830 Tasks that are declared using task allocators at the library level
10831 start executing immediately and hence can execute at elaboration time.
10832 @end table
10833
10834 @noindent
10835 Subprogram calls are possible in any of these contexts, which means that
10836 any arbitrary part of the program may be executed as part of the elaboration
10837 code. It is even possible to write a program which does all its work at
10838 elaboration time, with a null main program, although stylistically this
10839 would usually be considered an inappropriate way to structure
10840 a program.
10841
10842 An important concern arises in the context of elaboration code:
10843 we have to be sure that it is executed in an appropriate order. What we
10844 have is a series of elaboration code sections, potentially one section
10845 for each unit in the program. It is important that these execute
10846 in the correct order. Correctness here means that, taking the above
10847 example of the declaration of @code{Sqrt_Half},
10848 if some other piece of
10849 elaboration code references @code{Sqrt_Half},
10850 then it must run after the
10851 section of elaboration code that contains the declaration of
10852 @code{Sqrt_Half}.
10853
10854 There would never be any order of elaboration problem if we made a rule
10855 that whenever you @code{with} a unit, you must elaborate both the spec and body
10856 of that unit before elaborating the unit doing the @code{with}'ing:
10857
10858 @smallexample
10859 @group
10860 @cartouche
10861 @b{with} Unit_1;
10862 @b{package} Unit_2 @b{is} ...
10863 @end cartouche
10864 @end group
10865 @end smallexample
10866
10867 @noindent
10868 would require that both the body and spec of @code{Unit_1} be elaborated
10869 before the spec of @code{Unit_2}. However, a rule like that would be far too
10870 restrictive. In particular, it would make it impossible to have routines
10871 in separate packages that were mutually recursive.
10872
10873 You might think that a clever enough compiler could look at the actual
10874 elaboration code and determine an appropriate correct order of elaboration,
10875 but in the general case, this is not possible. Consider the following
10876 example.
10877
10878 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
10879 that references
10880 the variable @code{Sqrt_1}, which is declared in the elaboration code
10881 of the body of @code{Unit_1}:
10882
10883 @smallexample
10884 @cartouche
10885 Sqrt_1 : Float := Sqrt (0.1);
10886 @end cartouche
10887 @end smallexample
10888
10889 @noindent
10890 The elaboration code of the body of @code{Unit_1} also contains:
10891
10892 @smallexample
10893 @group
10894 @cartouche
10895 @b{if} expression_1 = 1 @b{then}
10896    Q := Unit_2.Func_2;
10897 @b{end if};
10898 @end cartouche
10899 @end group
10900 @end smallexample
10901
10902 @noindent
10903 @code{Unit_2} is exactly parallel,
10904 it has a procedure @code{Func_2} that references
10905 the variable @code{Sqrt_2}, which is declared in the elaboration code of
10906 the body @code{Unit_2}:
10907
10908 @smallexample
10909 @cartouche
10910 Sqrt_2 : Float := Sqrt (0.1);
10911 @end cartouche
10912 @end smallexample
10913
10914 @noindent
10915 The elaboration code of the body of @code{Unit_2} also contains:
10916
10917 @smallexample
10918 @group
10919 @cartouche
10920 @b{if} expression_2 = 2 @b{then}
10921    Q := Unit_1.Func_1;
10922 @b{end if};
10923 @end cartouche
10924 @end group
10925 @end smallexample
10926
10927 @noindent
10928 Now the question is, which of the following orders of elaboration is
10929 acceptable:
10930
10931 @smallexample
10932 @group
10933 Spec of Unit_1
10934 Spec of Unit_2
10935 Body of Unit_1
10936 Body of Unit_2
10937 @end group
10938 @end smallexample
10939
10940 @noindent
10941 or
10942
10943 @smallexample
10944 @group
10945 Spec of Unit_2
10946 Spec of Unit_1
10947 Body of Unit_2
10948 Body of Unit_1
10949 @end group
10950 @end smallexample
10951
10952 @noindent
10953 If you carefully analyze the flow here, you will see that you cannot tell
10954 at compile time the answer to this question.
10955 If @code{expression_1} is not equal to 1,
10956 and @code{expression_2} is not equal to 2,
10957 then either order is acceptable, because neither of the function calls is
10958 executed. If both tests evaluate to true, then neither order is acceptable
10959 and in fact there is no correct order.
10960
10961 If one of the two expressions is true, and the other is false, then one
10962 of the above orders is correct, and the other is incorrect. For example,
10963 if @code{expression_1} = 1 and @code{expression_2} /= 2,
10964 then the call to @code{Func_2}
10965 will occur, but not the call to @code{Func_1.}
10966 This means that it is essential
10967 to elaborate the body of @code{Unit_1} before
10968 the body of @code{Unit_2}, so the first
10969 order of elaboration is correct and the second is wrong.
10970
10971 By making @code{expression_1} and @code{expression_2}
10972 depend on input data, or perhaps
10973 the time of day, we can make it impossible for the compiler or binder
10974 to figure out which of these expressions will be true, and hence it
10975 is impossible to guarantee a safe order of elaboration at run time.
10976
10977 @node Checking the Elaboration Order in Ada 95
10978 @section Checking the Elaboration Order in Ada 95
10979
10980 @noindent
10981 In some languages that involve the same kind of elaboration problems,
10982 e.g. Java and C++, the programmer is expected to worry about these
10983 ordering problems himself, and it is common to
10984 write a program in which an incorrect elaboration order  gives
10985 surprising results, because it references variables before they
10986 are initialized.
10987 Ada 95 is designed to be a safe language, and a programmer-beware approach is
10988 clearly not sufficient. Consequently, the language provides three lines
10989 of defense:
10990
10991 @table @asis
10992 @item Standard rules
10993 Some standard rules restrict the possible choice of elaboration
10994 order. In particular, if you @code{with} a unit, then its spec is always
10995 elaborated before the unit doing the @code{with}. Similarly, a parent
10996 spec is always elaborated before the child spec, and finally
10997 a spec is always elaborated before its corresponding body.
10998
10999 @item Dynamic elaboration checks
11000 @cindex Elaboration checks
11001 @cindex Checks, elaboration
11002 Dynamic checks are made at run time, so that if some entity is accessed
11003 before it is elaborated (typically  by means of a subprogram call)
11004 then the exception (@code{Program_Error}) is raised.
11005
11006 @item Elaboration control
11007 Facilities are provided for the programmer to specify the desired order
11008 of elaboration.
11009 @end table
11010
11011 Let's look at these facilities in more detail. First, the rules for
11012 dynamic checking. One possible rule would be simply to say that the
11013 exception is raised if you access a variable which has not yet been
11014 elaborated. The trouble with this approach is that it could require
11015 expensive checks on every variable reference. Instead Ada 95 has two
11016 rules which are a little more restrictive, but easier to check, and
11017 easier to state:
11018
11019 @table @asis
11020 @item Restrictions on calls
11021 A subprogram can only be called at elaboration time if its body
11022 has been elaborated. The rules for elaboration given above guarantee
11023 that the spec of the subprogram has been elaborated before the
11024 call, but not the body. If this rule is violated, then the
11025 exception @code{Program_Error} is raised.
11026
11027 @item Restrictions on instantiations
11028 A generic unit can only be instantiated if the body of the generic
11029 unit has been elaborated. Again, the rules for elaboration given above
11030 guarantee that the spec of the generic unit has been elaborated
11031 before the instantiation, but not the body. If this rule is
11032 violated, then the exception @code{Program_Error} is raised.
11033 @end table
11034
11035 @noindent
11036 The idea is that if the body has been elaborated, then any variables
11037 it references must have been elaborated; by checking for the body being
11038 elaborated we guarantee that none of its references causes any
11039 trouble. As we noted above, this is a little too restrictive, because a
11040 subprogram that has no non-local references in its body may in fact be safe
11041 to call. However, it really would be unsafe to rely on this, because
11042 it would mean that the caller was aware of details of the implementation
11043 in the body. This goes against the basic tenets of Ada.
11044
11045 A plausible implementation can be described as follows.
11046 A Boolean variable is associated with each subprogram
11047 and each generic unit. This variable is initialized to False, and is set to
11048 True at the point body is elaborated. Every call or instantiation checks the
11049 variable, and raises @code{Program_Error} if the variable is False.
11050
11051 Note that one might think that it would be good enough to have one Boolean
11052 variable for each package, but that would not deal with cases of trying
11053 to call a body in the same package as the call
11054 that has not been elaborated yet.
11055 Of course a compiler may be able to do enough analysis to optimize away
11056 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
11057 does such optimizations, but still the easiest conceptual model is to
11058 think of there being one variable per subprogram.
11059
11060 @node Controlling the Elaboration Order in Ada 95
11061 @section Controlling the Elaboration Order in Ada 95
11062
11063 @noindent
11064 In the previous section we discussed the rules in Ada 95 which ensure
11065 that @code{Program_Error} is raised if an incorrect elaboration order is
11066 chosen. This prevents erroneous executions, but we need mechanisms to
11067 specify a correct execution and avoid the exception altogether.
11068 To achieve this, Ada 95 provides a number of features for controlling
11069 the order of elaboration. We discuss these features in this section.
11070
11071 First, there are several ways of indicating to the compiler that a given
11072 unit has no elaboration problems:
11073
11074 @table @asis
11075 @item packages that do not require a body
11076 In Ada 95, a library package that does not require a body does not permit
11077 a body. This means that if we have a such a package, as in:
11078
11079 @smallexample
11080 @group
11081 @cartouche
11082 @b{package} Definitions @b{is}
11083    @b{generic}
11084       @b{type} m @b{is new} integer;
11085    @b{package} Subp @b{is}
11086       @b{type} a @b{is array} (1 .. 10) @b{of} m;
11087       @b{type} b @b{is array} (1 .. 20) @b{of} m;
11088    @b{end} Subp;
11089 @b{end} Definitions;
11090 @end cartouche
11091 @end group
11092 @end smallexample
11093
11094 @noindent
11095 A package that @code{with}'s @code{Definitions} may safely instantiate
11096 @code{Definitions.Subp} because the compiler can determine that there
11097 definitely is no package body to worry about in this case
11098
11099 @item pragma Pure
11100 @cindex pragma Pure
11101 @findex Pure
11102 Places sufficient restrictions on a unit to guarantee that
11103 no call to any subprogram in the unit can result in an
11104 elaboration problem. This means that the compiler does not need
11105 to worry about the point of elaboration of such units, and in
11106 particular, does not need to check any calls to any subprograms
11107 in this unit.
11108
11109 @item pragma Preelaborate
11110 @findex Preelaborate
11111 @cindex pragma Preelaborate
11112 This pragma places slightly less stringent restrictions on a unit than
11113 does pragma Pure,
11114 but these restrictions are still sufficient to ensure that there
11115 are no elaboration problems with any calls to the unit.
11116
11117 @item pragma Elaborate_Body
11118 @findex Elaborate_Body
11119 @cindex pragma Elaborate_Body
11120 This pragma requires that the body of a unit be elaborated immediately
11121 after its spec. Suppose a unit @code{A} has such a pragma,
11122 and unit @code{B} does
11123 a @code{with} of unit @code{A}. Recall that the standard rules require
11124 the spec of unit @code{A}
11125 to be elaborated before the @code{with}'ing unit; given the pragma in
11126 @code{A}, we also know that the body of @code{A}
11127 will be elaborated before @code{B}, so
11128 that calls to @code{A} are safe and do not need a check.
11129 @end table
11130
11131 @noindent
11132 Note that,
11133 unlike pragma @code{Pure} and pragma @code{Preelaborate},
11134 the use of
11135 @code{Elaborate_Body} does not guarantee that the program is
11136 free of elaboration problems, because it may not be possible
11137 to satisfy the requested elaboration order.
11138 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
11139 If a programmer
11140 marks @code{Unit_1} as @code{Elaborate_Body},
11141 and not @code{Unit_2,} then the order of
11142 elaboration will be:
11143
11144 @smallexample
11145 @group
11146 Spec of Unit_2
11147 Spec of Unit_1
11148 Body of Unit_1
11149 Body of Unit_2
11150 @end group
11151 @end smallexample
11152
11153 @noindent
11154 Now that means that the call to @code{Func_1} in @code{Unit_2}
11155 need not be checked,
11156 it must be safe. But the call to @code{Func_2} in
11157 @code{Unit_1} may still fail if
11158 @code{Expression_1} is equal to 1,
11159 and the programmer must still take
11160 responsibility for this not being the case.
11161
11162 If all units carry a pragma @code{Elaborate_Body}, then all problems are
11163 eliminated, except for calls entirely within a body, which are
11164 in any case fully under programmer control. However, using the pragma
11165 everywhere is not always possible.
11166 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
11167 we marked both of them as having pragma @code{Elaborate_Body}, then
11168 clearly there would be no possible elaboration order.
11169
11170 The above pragmas allow a server to guarantee safe use by clients, and
11171 clearly this is the preferable approach. Consequently a good rule in
11172 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
11173 and if this is not possible,
11174 mark them as @code{Elaborate_Body} if possible.
11175 As we have seen, there are situations where neither of these
11176 three pragmas can be used.
11177 So we also provide methods for clients to control the
11178 order of elaboration of the servers on which they depend:
11179
11180 @table @asis
11181 @item pragma Elaborate (unit)
11182 @findex Elaborate
11183 @cindex pragma Elaborate
11184 This pragma is placed in the context clause, after a @code{with} clause,
11185 and it requires that the body of the named unit be elaborated before
11186 the unit in which the pragma occurs. The idea is to use this pragma
11187 if the current unit calls at elaboration time, directly or indirectly,
11188 some subprogram in the named unit.
11189
11190 @item pragma Elaborate_All (unit)
11191 @findex Elaborate_All
11192 @cindex pragma Elaborate_All
11193 This is a stronger version of the Elaborate pragma. Consider the
11194 following example:
11195
11196 @smallexample
11197 Unit A @code{with}'s unit B and calls B.Func in elab code
11198 Unit B @code{with}'s unit C, and B.Func calls C.Func
11199 @end smallexample
11200
11201 @noindent
11202 Now if we put a pragma @code{Elaborate (B)}
11203 in unit @code{A}, this ensures that the
11204 body of @code{B} is elaborated before the call, but not the
11205 body of @code{C}, so
11206 the call to @code{C.Func} could still cause @code{Program_Error} to
11207 be raised.
11208
11209 The effect of a pragma @code{Elaborate_All} is stronger, it requires
11210 not only that the body of the named unit be elaborated before the
11211 unit doing the @code{with}, but also the bodies of all units that the
11212 named unit uses, following @code{with} links transitively. For example,
11213 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
11214 then it requires
11215 not only that the body of @code{B} be elaborated before @code{A},
11216 but also the
11217 body of @code{C}, because @code{B} @code{with}'s @code{C}.
11218 @end table
11219
11220 @noindent
11221 We are now in a position to give a usage rule in Ada 95 for avoiding
11222 elaboration problems, at least if dynamic dispatching and access to
11223 subprogram values are not used. We will handle these cases separately
11224 later.
11225
11226 The rule is simple. If a unit has elaboration code that can directly or
11227 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
11228 a generic unit in a @code{with}'ed unit,
11229 then if the @code{with}'ed unit does not have
11230 pragma @code{Pure} or @code{Preelaborate}, then the client should have
11231 a pragma @code{Elaborate_All}
11232 for the @code{with}'ed unit. By following this rule a client is
11233 assured that calls can be made without risk of an exception.
11234 If this rule is not followed, then a program may be in one of four
11235 states:
11236
11237 @table @asis
11238 @item No order exists
11239 No order of elaboration exists which follows the rules, taking into
11240 account any @code{Elaborate}, @code{Elaborate_All},
11241 or @code{Elaborate_Body} pragmas. In
11242 this case, an Ada 95 compiler must diagnose the situation at bind
11243 time, and refuse to build an executable program.
11244
11245 @item One or more orders exist, all incorrect
11246 One or more acceptable elaboration orders exists, and all of them
11247 generate an elaboration order problem. In this case, the binder
11248 can build an executable program, but @code{Program_Error} will be raised
11249 when the program is run.
11250
11251 @item Several orders exist, some right, some incorrect
11252 One or more acceptable elaboration orders exists, and some of them
11253 work, and some do not. The programmer has not controlled
11254 the order of elaboration, so the binder may or may not pick one of
11255 the correct orders, and the program may or may not raise an
11256 exception when it is run. This is the worst case, because it means
11257 that the program may fail when moved to another compiler, or even
11258 another version of the same compiler.
11259
11260 @item One or more orders exists, all correct
11261 One ore more acceptable elaboration orders exist, and all of them
11262 work. In this case the program runs successfully. This state of
11263 affairs can be guaranteed by following the rule we gave above, but
11264 may be true even if the rule is not followed.
11265 @end table
11266
11267 @noindent
11268 Note that one additional advantage of following our Elaborate_All rule
11269 is that the program continues to stay in the ideal (all orders OK) state
11270 even if maintenance
11271 changes some bodies of some subprograms. Conversely, if a program that does
11272 not follow this rule happens to be safe at some point, this state of affairs
11273 may deteriorate silently as a result of maintenance changes.
11274
11275 You may have noticed that the above discussion did not mention
11276 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
11277 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
11278 code in the body makes calls to some other unit, so it is still necessary
11279 to use @code{Elaborate_All} on such units.
11280
11281 @node Controlling Elaboration in GNAT - Internal Calls
11282 @section Controlling Elaboration in GNAT - Internal Calls
11283
11284 @noindent
11285 In the case of internal calls, i.e. calls within a single package, the
11286 programmer has full control over the order of elaboration, and it is up
11287 to the programmer to elaborate declarations in an appropriate order. For
11288 example writing:
11289
11290 @smallexample
11291 @group
11292 @cartouche
11293 @b{function} One @b{return} Float;
11294
11295 Q : Float := One;
11296
11297 @b{function} One @b{return} Float @b{is}
11298 @b{begin}
11299      return 1.0;
11300 @b{end} One;
11301 @end cartouche
11302 @end group
11303 @end smallexample
11304
11305 @noindent
11306 will obviously raise @code{Program_Error} at run time, because function
11307 One will be called before its body is elaborated. In this case GNAT will
11308 generate a warning that the call will raise @code{Program_Error}:
11309
11310 @smallexample
11311 @group
11312 @cartouche
11313  1. procedure y is
11314  2.    function One return Float;
11315  3.
11316  4.    Q : Float := One;
11317                     |
11318     >>> warning: cannot call "One" before body is elaborated
11319     >>> warning: Program_Error will be raised at run time
11320
11321  5.
11322  6.    function One return Float is
11323  7.    begin
11324  8.         return 1.0;
11325  9.    end One;
11326 10.
11327 11. begin
11328 12.    null;
11329 13. end;
11330 @end cartouche
11331 @end group
11332 @end smallexample
11333
11334 @noindent
11335 Note that in this particular case, it is likely that the call is safe, because
11336 the function @code{One} does not access any global variables.
11337 Nevertheless in Ada 95, we do not want the validity of the check to depend on
11338 the contents of the body (think about the separate compilation case), so this
11339 is still wrong, as we discussed in the previous sections.
11340
11341 The error is easily corrected by rearranging the declarations so that the
11342 body of One appears before the declaration containing the call
11343 (note that in Ada 95,
11344 declarations can appear in any order, so there is no restriction that
11345 would prevent this reordering, and if we write:
11346
11347 @smallexample
11348 @group
11349 @cartouche
11350 @b{function} One @b{return} Float;
11351
11352 @b{function} One @b{return} Float @b{is}
11353 @b{begin}
11354      return 1.0;
11355 @b{end} One;
11356
11357 Q : Float := One;
11358 @end cartouche
11359 @end group
11360 @end smallexample
11361
11362 @noindent
11363 then all is well, no warning is generated, and no
11364 @code{Program_Error} exception
11365 will be raised.
11366 Things are more complicated when a chain of subprograms is executed:
11367
11368 @smallexample
11369 @group
11370 @cartouche
11371 @b{function} A @b{return} Integer;
11372 @b{function} B @b{return} Integer;
11373 @b{function} C @b{return} Integer;
11374
11375 @b{function} B @b{return} Integer @b{is begin return} A; @b{end};
11376 @b{function} C @b{return} Integer @b{is begin return} B; @b{end};
11377
11378 X : Integer := C;
11379
11380 @b{function} A @b{return} Integer @b{is begin return} 1; @b{end};
11381 @end cartouche
11382 @end group
11383 @end smallexample
11384
11385 @noindent
11386 Now the call to @code{C}
11387 at elaboration time in the declaration of @code{X} is correct, because
11388 the body of @code{C} is already elaborated,
11389 and the call to @code{B} within the body of
11390 @code{C} is correct, but the call
11391 to @code{A} within the body of @code{B} is incorrect, because the body
11392 of @code{A} has not been elaborated, so @code{Program_Error}
11393 will be raised on the call to @code{A}.
11394 In this case GNAT will generate a
11395 warning that @code{Program_Error} may be
11396 raised at the point of the call. Let's look at the warning:
11397
11398 @smallexample
11399 @group
11400 @cartouche
11401  1. procedure x is
11402  2.    function A return Integer;
11403  3.    function B return Integer;
11404  4.    function C return Integer;
11405  5.
11406  6.    function B return Integer is begin return A; end;
11407                                                     |
11408     >>> warning: call to "A" before body is elaborated may
11409                  raise Program_Error
11410     >>> warning: "B" called at line 7
11411     >>> warning: "C" called at line 9
11412
11413  7.    function C return Integer is begin return B; end;
11414  8.
11415  9.    X : Integer := C;
11416 10.
11417 11.    function A return Integer is begin return 1; end;
11418 12.
11419 13. begin
11420 14.    null;
11421 15. end;
11422 @end cartouche
11423 @end group
11424 @end smallexample
11425
11426 @noindent
11427 Note that the message here says "may raise", instead of the direct case,
11428 where the message says "will be raised". That's because whether
11429 @code{A} is
11430 actually called depends in general on run-time flow of control.
11431 For example, if the body of @code{B} said
11432
11433 @smallexample
11434 @group
11435 @cartouche
11436 @b{function} B @b{return} Integer @b{is}
11437 @b{begin}
11438    @b{if} some-condition-depending-on-input-data @b{then}
11439       @b{return} A;
11440    @b{else}
11441       @b{return} 1;
11442    @b{end if};
11443 @b{end} B;
11444 @end cartouche
11445 @end group
11446 @end smallexample
11447
11448 @noindent
11449 then we could not know until run time whether the incorrect call to A would
11450 actually occur, so @code{Program_Error} might
11451 or might not be raised. It is possible for a compiler to
11452 do a better job of analyzing bodies, to
11453 determine whether or not @code{Program_Error}
11454 might be raised, but it certainly
11455 couldn't do a perfect job (that would require solving the halting problem
11456 and is provably impossible), and because this is a warning anyway, it does
11457 not seem worth the effort to do the analysis. Cases in which it
11458 would be relevant are rare.
11459
11460 In practice, warnings of either of the forms given
11461 above will usually correspond to
11462 real errors, and should be examined carefully and eliminated.
11463 In the rare case where a warning is bogus, it can be suppressed by any of
11464 the following methods:
11465
11466 @itemize @bullet
11467 @item
11468 Compile with the @option{-gnatws} switch set
11469
11470 @item
11471 Suppress @code{Elaboration_Checks} for the called subprogram
11472
11473 @item
11474 Use pragma @code{Warnings_Off} to turn warnings off for the call
11475 @end itemize
11476
11477 @noindent
11478 For the internal elaboration check case,
11479 GNAT by default generates the
11480 necessary run-time checks to ensure
11481 that @code{Program_Error} is raised if any
11482 call fails an elaboration check. Of course this can only happen if a
11483 warning has been issued as described above. The use of pragma
11484 @code{Suppress (Elaboration_Checks)} may (but is not guaranteed to) suppress
11485 some of these checks, meaning that it may be possible (but is not
11486 guaranteed) for a program to be able to call a subprogram whose body
11487 is not yet elaborated, without raising a @code{Program_Error} exception.
11488
11489 @node Controlling Elaboration in GNAT - External Calls
11490 @section Controlling Elaboration in GNAT - External Calls
11491
11492 @noindent
11493 The previous section discussed the case in which the execution of a
11494 particular thread of elaboration code occurred entirely within a
11495 single unit. This is the easy case to handle, because a programmer
11496 has direct and total control over the order of elaboration, and
11497 furthermore, checks need only be generated in cases which are rare
11498 and which the compiler can easily detect.
11499 The situation is more complex when separate compilation is taken into account.
11500 Consider the following:
11501
11502 @smallexample
11503 @cartouche
11504 @group
11505 @b{package} Math @b{is}
11506    @b{function} Sqrt (Arg : Float) @b{return} Float;
11507 @b{end} Math;
11508
11509 @b{package body} Math @b{is}
11510    @b{function} Sqrt (Arg : Float) @b{return} Float @b{is}
11511    @b{begin}
11512          ...
11513    @b{end} Sqrt;
11514 @b{end} Math;
11515 @end group
11516 @group
11517 @b{with} Math;
11518 @b{package} Stuff @b{is}
11519    X : Float := Math.Sqrt (0.5);
11520 @b{end} Stuff;
11521
11522 @b{with} Stuff;
11523 @b{procedure} Main @b{is}
11524 @b{begin}
11525    ...
11526 @b{end} Main;
11527 @end group
11528 @end cartouche
11529 @end smallexample
11530
11531 @noindent
11532 where @code{Main} is the main program. When this program is executed, the
11533 elaboration code must first be executed, and one of the jobs of the
11534 binder is to determine the order in which the units of a program are
11535 to be elaborated. In this case we have four units: the spec and body
11536 of @code{Math},
11537 the spec of @code{Stuff} and the body of @code{Main}).
11538 In what order should the four separate sections of elaboration code
11539 be executed?
11540
11541 There are some restrictions in the order of elaboration that the binder
11542 can choose. In particular, if unit U has a @code{with}
11543 for a package @code{X}, then you
11544 are assured that the spec of @code{X}
11545 is elaborated before U , but you are
11546 not assured that the body of @code{X}
11547 is elaborated before U.
11548 This means that in the above case, the binder is allowed to choose the
11549 order:
11550
11551 @smallexample
11552 spec of Math
11553 spec of Stuff
11554 body of Math
11555 body of Main
11556 @end smallexample
11557
11558 @noindent
11559 but that's not good, because now the call to @code{Math.Sqrt}
11560 that happens during
11561 the elaboration of the @code{Stuff}
11562 spec happens before the body of @code{Math.Sqrt} is
11563 elaborated, and hence causes @code{Program_Error} exception to be raised.
11564 At first glance, one might say that the binder is misbehaving, because
11565 obviously you want to elaborate the body of something you @code{with}
11566 first, but
11567 that is not a general rule that can be followed in all cases. Consider
11568
11569 @smallexample
11570 @group
11571 @cartouche
11572 @b{package} X @b{is} ...
11573
11574 @b{package} Y @b{is} ...
11575
11576 @b{with} X;
11577 @b{package body} Y @b{is} ...
11578
11579 @b{with} Y;
11580 @b{package body} X @b{is} ...
11581 @end cartouche
11582 @end group
11583 @end smallexample
11584
11585 @noindent
11586 This is a common arrangement, and, apart from the order of elaboration
11587 problems that might arise in connection with elaboration code, this works fine.
11588 A rule that says that you must first elaborate the body of anything you
11589 @code{with} cannot work in this case:
11590 the body of @code{X} @code{with}'s @code{Y},
11591 which means you would have to
11592 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
11593 which means
11594 you have to elaborate the body of @code{X} first, but ... and we have a
11595 loop that cannot be broken.
11596
11597 It is true that the binder can in many cases guess an order of elaboration
11598 that is unlikely to cause a @code{Program_Error}
11599 exception to be raised, and it tries to do so (in the
11600 above example of @code{Math/Stuff/Spec}, the GNAT binder will
11601 by default
11602 elaborate the body of @code{Math} right after its spec, so all will be well).
11603
11604 However, a program that blindly relies on the binder to be helpful can
11605 get into trouble, as we discussed in the previous sections, so
11606 GNAT
11607 provides a number of facilities for assisting the programmer in
11608 developing programs that are robust with respect to elaboration order.
11609
11610 @node Default Behavior in GNAT - Ensuring Safety
11611 @section Default Behavior in GNAT - Ensuring Safety
11612
11613 @noindent
11614 The default behavior in GNAT ensures elaboration safety. In its
11615 default mode GNAT implements the
11616 rule we previously described as the right approach. Let's restate it:
11617
11618 @itemize
11619 @item
11620 @emph{If a unit has elaboration code that can directly or indirectly make a
11621 call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit
11622 in a @code{with}'ed unit, then if the @code{with}'ed unit
11623 does not have pragma @code{Pure} or
11624 @code{Preelaborate}, then the client should have an
11625 @code{Elaborate_All} for the @code{with}'ed unit.}
11626 @end itemize
11627
11628 @noindent
11629 By following this rule a client
11630 is assured that calls and instantiations can be made without risk of an exception.
11631
11632 In this mode GNAT traces all calls that are potentially made from
11633 elaboration code, and puts in any missing implicit @code{Elaborate_All}
11634 pragmas.
11635 The advantage of this approach is that no elaboration problems
11636 are possible if the binder can find an elaboration order that is
11637 consistent with these implicit @code{Elaborate_All} pragmas. The
11638 disadvantage of this approach is that no such order may exist.
11639
11640 If the binder does not generate any diagnostics, then it means that it
11641 has found an elaboration order that is guaranteed to be safe. However,
11642 the binder may still be relying on implicitly generated
11643 @code{Elaborate_All} pragmas so portability to other compilers than
11644 GNAT is not guaranteed.
11645
11646 If it is important to guarantee portability, then the compilations should
11647 use the
11648 @option{-gnatwl}
11649 (warn on elaboration problems) switch. This will cause warning messages
11650 to be generated indicating the missing @code{Elaborate_All} pragmas.
11651 Consider the following source program:
11652
11653 @smallexample
11654 @group
11655 @cartouche
11656 @b{with} k;
11657 @b{package} j @b{is}
11658   m : integer := k.r;
11659 @b{end};
11660 @end cartouche
11661 @end group
11662 @end smallexample
11663
11664 @noindent
11665 where it is clear that there
11666 should be a pragma @code{Elaborate_All}
11667 for unit @code{k}. An implicit pragma will be generated, and it is
11668 likely that the binder will be able to honor it. However,
11669 it is safer to include the pragma explicitly in the source. If this
11670 unit is compiled with the
11671 @option{-gnatwl}
11672 switch, then the compiler outputs a warning:
11673
11674 @smallexample
11675 @group
11676 @cartouche
11677 1. with k;
11678 2. package j is
11679 3.   m : integer := k.r;
11680                      |
11681    >>> warning: call to "r" may raise Program_Error
11682    >>> warning: missing pragma Elaborate_All for "k"
11683
11684 4. end;
11685 @end cartouche
11686 @end group
11687 @end smallexample
11688
11689 @noindent
11690 and these warnings can be used as a guide for supplying manually
11691 the missing pragmas.
11692
11693 This default mode is more restrictive than the Ada Reference
11694 Manual, and it is possible to construct programs which will compile
11695 using the dynamic model described there, but will run into a
11696 circularity using the safer static model we have described.
11697
11698 Of course any Ada compiler must be able to operate in a mode
11699 consistent with the requirements of the Ada Reference Manual,
11700 and in particular must have the capability of implementing the
11701 standard dynamic model of elaboration with run-time checks.
11702
11703 In GNAT, this standard mode can be achieved either by the use of
11704 the @option{-gnatE} switch on the compiler (@code{gcc} or @code{gnatmake})
11705 command, or by the use of the configuration pragma:
11706
11707 @smallexample
11708 pragma Elaboration_Checks (RM);
11709 @end smallexample
11710
11711 @noindent
11712 Either approach will cause the unit affected to be compiled using the
11713 standard dynamic run-time elaboration checks described in the Ada
11714 Reference Manual. The static model is generally preferable, since it
11715 is clearly safer to rely on compile and link time checks rather than
11716 run-time checks. However, in the case of legacy code, it may be
11717 difficult to meet the requirements of the static model. This
11718 issue is further discussed in
11719 @ref{What to Do If the Default Elaboration Behavior Fails}.
11720
11721 Note that the static model provides a strict subset of the allowed
11722 behavior and programs of the Ada Reference Manual, so if you do
11723 adhere to the static model and no circularities exist,
11724 then you are assured that your program will
11725 work using the dynamic model.
11726
11727 @node Elaboration Issues for Library Tasks
11728 @section Elaboration Issues for Library Tasks
11729 @cindex Library tasks, elaboration issues
11730 @cindex Elaboration of library tasks
11731
11732 @noindent
11733 In this section we examine special elaboration issues that arise for
11734 programs that declare library level tasks.
11735
11736 Generally the model of execution of an Ada program is that all units are
11737 elaborated, and then execution of the program starts. However, the
11738 declaration of library tasks definitely does not fit this model. The
11739 reason for this is that library tasks start as soon as they are declared
11740 (more precisely, as soon as the statement part of the enclosing package
11741 body is reached), that is to say before elaboration
11742 of the program is complete. This means that if such a task calls a
11743 subprogram, or an entry in another task, the callee may or may not be
11744 elaborated yet, and in the standard
11745 Reference Manual model of dynamic elaboration checks, you can even
11746 get timing dependent Program_Error exceptions, since there can be
11747 a race between the elaboration code and the task code.
11748
11749 The static model of elaboration in GNAT seeks to avoid all such
11750 dynamic behavior, by being conservative, and the conservative
11751 approach in this particular case is to assume that all the code
11752 in a task body is potentially executed at elaboration time if
11753 a task is declared at the library level.
11754
11755 This can definitely result in unexpected circularities. Consider
11756 the following example
11757
11758 @smallexample
11759 package Decls is
11760   task Lib_Task is
11761      entry Start;
11762   end Lib_Task;
11763
11764   type My_Int is new Integer;
11765
11766   function Ident (M : My_Int) return My_Int;
11767 end Decls;
11768
11769 with Utils;
11770 package body Decls is
11771   task body Lib_Task is
11772   begin
11773      accept Start;
11774      Utils.Put_Val (2);
11775   end Lib_Task;
11776
11777   function Ident (M : My_Int) return My_Int is
11778   begin
11779      return M;
11780   end Ident;
11781 end Decls;
11782
11783 with Decls;
11784 package Utils is
11785   procedure Put_Val (Arg : Decls.My_Int);
11786 end Utils;
11787
11788 with Text_IO;
11789 package body Utils is
11790   procedure Put_Val (Arg : Decls.My_Int) is
11791   begin
11792      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
11793   end Put_Val;
11794 end Utils;
11795
11796 with Decls;
11797 procedure Main is
11798 begin
11799    Decls.Lib_Task.Start;
11800 end;
11801 @end smallexample
11802
11803 @noindent
11804 If the above example is compiled in the default static elaboration
11805 mode, then a circularity occurs. The circularity comes from the call
11806 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
11807 this call occurs in elaboration code, we need an implicit pragma
11808 @code{Elaborate_All} for @code{Utils}. This means that not only must
11809 the spec and body of @code{Utils} be elaborated before the body
11810 of @code{Decls}, but also the spec and body of any unit that is
11811 @code{with'ed} by the body of @code{Utils} must also be elaborated before
11812 the body of @code{Decls}. This is the transitive implication of
11813 pragma @code{Elaborate_All} and it makes sense, because in general
11814 the body of @code{Put_Val} might have a call to something in a
11815 @code{with'ed} unit.
11816
11817 In this case, the body of Utils (actually its spec) @code{with's}
11818 @code{Decls}. Unfortunately this means that the body of @code{Decls}
11819 must be elaborated before itself, in case there is a call from the
11820 body of @code{Utils}.
11821
11822 Here is the exact chain of events we are worrying about:
11823
11824 @enumerate
11825 @item
11826 In the body of @code{Decls} a call is made from within the body of a library
11827 task to a subprogram in the package @code{Utils}. Since this call may
11828 occur at elaboration time (given that the task is activated at elaboration
11829 time), we have to assume the worst, i.e. that the
11830 call does happen at elaboration time.
11831
11832 @item
11833 This means that the body and spec of @code{Util} must be elaborated before
11834 the body of @code{Decls} so that this call does not cause an access before
11835 elaboration.
11836
11837 @item
11838 Within the body of @code{Util}, specifically within the body of
11839 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
11840 by this package.
11841
11842 @item
11843 One such @code{with}'ed package is package @code{Decls}, so there
11844 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
11845 In fact there is such a call in this example, but we would have to
11846 assume that there was such a call even if it were not there, since
11847 we are not supposed to write the body of @code{Decls} knowing what
11848 is in the body of @code{Utils}; certainly in the case of the
11849 static elaboration model, the compiler does not know what is in
11850 other bodies and must assume the worst.
11851
11852 @item
11853 This means that the spec and body of @code{Decls} must also be
11854 elaborated before we elaborate the unit containing the call, but
11855 that unit is @code{Decls}! This means that the body of @code{Decls}
11856 must be elaborated before itself, and that's a circularity.
11857 @end enumerate
11858
11859 @noindent
11860 Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in
11861 the body of @code{Decls} you will get a true Ada Reference Manual
11862 circularity that makes the program illegal.
11863
11864 In practice, we have found that problems with the static model of
11865 elaboration in existing code often arise from library tasks, so
11866 we must address this particular situation.
11867
11868 Note that if we compile and run the program above, using the dynamic model of
11869 elaboration (that is to say use the @option{-gnatE} switch),
11870 then it compiles, binds,
11871 links, and runs, printing the expected result of 2. Therefore in some sense
11872 the circularity here is only apparent, and we need to capture
11873 the properties of this program that  distinguish it from other library-level
11874 tasks that have real elaboration problems.
11875
11876 We have four possible answers to this question:
11877
11878 @itemize @bullet
11879
11880 @item
11881 Use the dynamic model of elaboration.
11882
11883 If we use the @option{-gnatE} switch, then as noted above, the program works.
11884 Why is this? If we examine the task body, it is apparent that the task cannot
11885 proceed past the
11886 @code{accept} statement until after elaboration has been completed, because
11887 the corresponding entry call comes from the main program, not earlier.
11888 This is why the dynamic model works here. But that's really giving
11889 up on a precise analysis, and we prefer to take this approach only if we cannot
11890 solve the
11891 problem in any other manner. So let us examine two ways to reorganize
11892 the program to avoid the potential elaboration problem.
11893
11894 @item
11895 Split library tasks into separate packages.
11896
11897 Write separate packages, so that library tasks are isolated from
11898 other declarations as much as possible. Let us look at a variation on
11899 the above program.
11900
11901 @smallexample
11902 package Decls1 is
11903   task Lib_Task is
11904      entry Start;
11905   end Lib_Task;
11906 end Decls1;
11907
11908 with Utils;
11909 package body Decls1 is
11910   task body Lib_Task is
11911   begin
11912      accept Start;
11913      Utils.Put_Val (2);
11914   end Lib_Task;
11915 end Decls1;
11916
11917 package Decls2 is
11918   type My_Int is new Integer;
11919   function Ident (M : My_Int) return My_Int;
11920 end Decls2;
11921
11922 with Utils;
11923 package body Decls2 is
11924   function Ident (M : My_Int) return My_Int is
11925   begin
11926      return M;
11927   end Ident;
11928 end Decls2;
11929
11930 with Decls2;
11931 package Utils is
11932   procedure Put_Val (Arg : Decls2.My_Int);
11933 end Utils;
11934
11935 with Text_IO;
11936 package body Utils is
11937   procedure Put_Val (Arg : Decls2.My_Int) is
11938   begin
11939      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
11940   end Put_Val;
11941 end Utils;
11942
11943 with Decls1;
11944 procedure Main is
11945 begin
11946    Decls1.Lib_Task.Start;
11947 end;
11948 @end smallexample
11949
11950 @noindent
11951 All we have done is to split @code{Decls} into two packages, one
11952 containing the library task, and one containing everything else. Now
11953 there is no cycle, and the program compiles, binds, links and executes
11954 using the default static model of elaboration.
11955
11956 @item
11957 Declare separate task types.
11958
11959 A significant part of the problem arises because of the use of the
11960 single task declaration form. This means that the elaboration of
11961 the task type, and the elaboration of the task itself (i.e. the
11962 creation of the task) happen at the same time. A good rule
11963 of style in Ada 95 is to always create explicit task types. By
11964 following the additional step of placing task objects in separate
11965 packages from the task type declaration, many elaboration problems
11966 are avoided. Here is another modified example of the example program:
11967
11968 @smallexample
11969 package Decls is
11970   task type Lib_Task_Type is
11971      entry Start;
11972   end Lib_Task_Type;
11973
11974   type My_Int is new Integer;
11975
11976   function Ident (M : My_Int) return My_Int;
11977 end Decls;
11978
11979 with Utils;
11980 package body Decls is
11981   task body Lib_Task_Type is
11982   begin
11983      accept Start;
11984      Utils.Put_Val (2);
11985   end Lib_Task_Type;
11986
11987   function Ident (M : My_Int) return My_Int is
11988   begin
11989      return M;
11990   end Ident;
11991 end Decls;
11992
11993 with Decls;
11994 package Utils is
11995   procedure Put_Val (Arg : Decls.My_Int);
11996 end Utils;
11997
11998 with Text_IO;
11999 package body Utils is
12000   procedure Put_Val (Arg : Decls.My_Int) is
12001   begin
12002      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
12003   end Put_Val;
12004 end Utils;
12005
12006 with Decls;
12007 package Declst is
12008    Lib_Task : Decls.Lib_Task_Type;
12009 end Declst;
12010
12011 with Declst;
12012 procedure Main is
12013 begin
12014    Declst.Lib_Task.Start;
12015 end;
12016 @end smallexample
12017
12018 @noindent
12019 What we have done here is to replace the @code{task} declaration in
12020 package @code{Decls} with a @code{task type} declaration. Then we
12021 introduce a separate package @code{Declst} to contain the actual
12022 task object. This separates the elaboration issues for
12023 the @code{task type}
12024 declaration, which causes no trouble, from the elaboration issues
12025 of the task object, which is also unproblematic, since it is now independent
12026 of the elaboration of  @code{Utils}.
12027 This separation of concerns also corresponds to
12028 a generally sound engineering principle of separating declarations
12029 from instances. This version of the program also compiles, binds, links,
12030 and executes, generating the expected output.
12031
12032 @item
12033 Use No_Entry_Calls_In_Elaboration_Code restriction.
12034 @cindex No_Entry_Calls_In_Elaboration_Code
12035
12036 The previous two approaches described how a program can be restructured
12037 to avoid the special problems caused by library task bodies. in practice,
12038 however, such restructuring may be difficult to apply to existing legacy code,
12039 so we must consider solutions that do not require massive rewriting.
12040
12041 Let us consider more carefully why our original sample program works
12042 under the dynamic model of elaboration. The reason is that the code
12043 in the task body blocks immediately on the @code{accept}
12044 statement. Now of course there is nothing to prohibit elaboration
12045 code from making entry calls (for example from another library level task),
12046 so we cannot tell in isolation that
12047 the task will not execute the accept statement  during elaboration.
12048
12049 However, in practice it is very unusual to see elaboration code
12050 make any entry calls, and the pattern of tasks starting
12051 at elaboration time and then immediately blocking on @code{accept} or
12052 @code{select} statements is very common. What this means is that
12053 the compiler is being too pessimistic when it analyzes the
12054 whole package body as though it might be executed at elaboration
12055 time.
12056
12057 If we know that the elaboration code contains no entry calls, (a very safe
12058 assumption most of the time, that could almost be made the default
12059 behavior), then we can compile all units of the program under control
12060 of the following configuration pragma:
12061
12062 @smallexample
12063 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
12064 @end smallexample
12065
12066 @noindent
12067 This pragma can be placed in the @file{gnat.adc} file in the usual
12068 manner. If we take our original unmodified program and compile it
12069 in the presence of a @file{gnat.adc} containing the above pragma,
12070 then once again, we can compile, bind, link, and execute, obtaining
12071 the expected result. In the presence of this pragma, the compiler does
12072 not trace calls in a task body, that appear after the first @code{accept}
12073 or @code{select} statement, and therefore does not report a potential
12074 circularity in the original program.
12075
12076 The compiler will check to the extent it can that the above
12077 restriction is not violated, but it is not always possible to do a
12078 complete check at compile time, so it is important to use this
12079 pragma only if the stated restriction is in fact met, that is to say
12080 no task receives an entry call before elaboration of all units is completed.
12081
12082 @end itemize
12083
12084 @node Mixing Elaboration Models
12085 @section Mixing Elaboration Models
12086 @noindent
12087 So far, we have assumed that the entire program is either compiled
12088 using the dynamic model or static model, ensuring consistency. It
12089 is possible to mix the two models, but rules have to be followed
12090 if this mixing is done to ensure that elaboration checks are not
12091 omitted.
12092
12093 The basic rule is that @emph{a unit compiled with the static model cannot
12094 be @code{with'ed} by a unit compiled with the dynamic model}. The
12095 reason for this is that in the static model, a unit assumes that
12096 its clients guarantee to use (the equivalent of) pragma
12097 @code{Elaborate_All} so that no elaboration checks are required
12098 in inner subprograms, and this assumption is violated if the
12099 client is compiled with dynamic checks.
12100
12101 The precise rule is as follows. A unit that is compiled with dynamic
12102 checks can only @code{with} a unit that meets at least one of the
12103 following criteria:
12104
12105 @itemize @bullet
12106
12107 @item
12108 The @code{with'ed} unit is itself compiled with dynamic elaboration
12109 checks (that is with the @option{-gnatE} switch.
12110
12111 @item
12112 The @code{with'ed} unit is an internal GNAT implementation unit from
12113 the System, Interfaces, Ada, or GNAT hierarchies.
12114
12115 @item
12116 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
12117
12118 @item
12119 The @code{with'ing} unit (that is the client) has an explicit pragma
12120 @code{Elaborate_All} for the @code{with'ed} unit.
12121
12122 @end itemize
12123
12124 @noindent
12125 If this rule is violated, that is if a unit with dynamic elaboration
12126 checks @code{with's} a unit that does not meet one of the above four
12127 criteria, then the binder (@code{gnatbind}) will issue a warning
12128 similar to that in the following example:
12129
12130 @smallexample
12131 warning: "x.ads" has dynamic elaboration checks and with's
12132 warning:   "y.ads" which has static elaboration checks
12133 @end smallexample
12134
12135 @noindent
12136 These warnings indicate that the rule has been violated, and that as a result
12137 elaboration checks may be missed in the resulting executable file.
12138 This warning may be suppressed using the @code{-ws} binder switch
12139 in the usual manner.
12140
12141 One useful application of this mixing rule is in the case of a subsystem
12142 which does not itself @code{with} units from the remainder of the
12143 application. In this case, the entire subsystem can be compiled with
12144 dynamic checks to resolve a circularity in the subsystem, while
12145 allowing the main application that uses this subsystem to be compiled
12146 using the more reliable default static model.
12147
12148 @node What to Do If the Default Elaboration Behavior Fails
12149 @section What to Do If the Default Elaboration Behavior Fails
12150
12151 @noindent
12152 If the binder cannot find an acceptable order, it outputs detailed
12153 diagnostics. For example:
12154 @smallexample
12155 @group
12156 @iftex
12157 @leftskip=0cm
12158 @end iftex
12159 error: elaboration circularity detected
12160 info:   "proc (body)" must be elaborated before "pack (body)"
12161 info:     reason: Elaborate_All probably needed in unit "pack (body)"
12162 info:     recompile "pack (body)" with -gnatwl
12163 info:                             for full details
12164 info:       "proc (body)"
12165 info:         is needed by its spec:
12166 info:       "proc (spec)"
12167 info:         which is withed by:
12168 info:       "pack (body)"
12169 info:  "pack (body)" must be elaborated before "proc (body)"
12170 info:     reason: pragma Elaborate in unit "proc (body)"
12171 @end group
12172
12173 @end smallexample
12174
12175 @noindent
12176 In this case we have a cycle that the binder cannot break. On the one
12177 hand, there is an explicit pragma Elaborate in @code{proc} for
12178 @code{pack}. This means that the body of @code{pack} must be elaborated
12179 before the body of @code{proc}. On the other hand, there is elaboration
12180 code in @code{pack} that calls a subprogram in @code{proc}. This means
12181 that for maximum safety, there should really be a pragma
12182 Elaborate_All in @code{pack} for @code{proc} which would require that
12183 the body of @code{proc} be elaborated before the body of
12184 @code{pack}. Clearly both requirements cannot be satisfied.
12185 Faced with a circularity of this kind, you have three different options.
12186
12187 @table @asis
12188 @item Fix the program
12189 The most desirable option from the point of view of long-term maintenance
12190 is to rearrange the program so that the elaboration problems are avoided.
12191 One useful technique is to place the elaboration code into separate
12192 child packages. Another is to move some of the initialization code to
12193 explicitly called subprograms, where the program controls the order
12194 of initialization explicitly. Although this is the most desirable option,
12195 it may be impractical and involve too much modification, especially in
12196 the case of complex legacy code.
12197
12198 @item Perform dynamic checks
12199 If the compilations are done using the
12200 @option{-gnatE}
12201 (dynamic elaboration check) switch, then GNAT behaves in
12202 a quite different manner. Dynamic checks are generated for all calls
12203 that could possibly result in raising an exception. With this switch,
12204 the compiler does not generate implicit @code{Elaborate_All} pragmas.
12205 The behavior then is exactly as specified in the Ada 95 Reference Manual.
12206 The binder will generate an executable program that may or may not
12207 raise @code{Program_Error}, and then it is the programmer's job to ensure
12208 that it does not raise an exception. Note that it is important to
12209 compile all units with the switch, it cannot be used selectively.
12210
12211 @item Suppress checks
12212 The drawback of dynamic checks is that they generate a
12213 significant overhead at run time, both in space and time. If you
12214 are absolutely sure that your program cannot raise any elaboration
12215 exceptions, and you still want to use the dynamic elaboration model,
12216 then you can use the configuration pragma
12217 @code{Suppress (Elaboration_Checks)} to suppress all such checks. For
12218 example this pragma could be placed in the @file{gnat.adc} file.
12219
12220 @item Suppress checks selectively
12221 When you know that certain calls in elaboration code cannot possibly
12222 lead to an elaboration error, and the binder nevertheless generates warnings
12223 on those calls and inserts Elaborate_All pragmas that lead to elaboration
12224 circularities, it is possible to remove those warnings locally and obtain
12225 a program that will bind. Clearly this can be unsafe, and it is the
12226 responsibility of the programmer to make sure that the resulting program has
12227 no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can
12228 be used with different granularity to suppress warnings and break
12229 elaboration circularities:
12230
12231 @itemize @bullet
12232 @item
12233 Place the pragma that names the called subprogram in the declarative part
12234 that contains the call.
12235
12236 @item
12237 Place the pragma in the declarative part, without naming an entity. This
12238 disables warnings on all calls in the corresponding  declarative region.
12239
12240 @item
12241 Place the pragma in the package spec that declares the called subprogram,
12242 and name the subprogram. This disables warnings on all elaboration calls to
12243 that subprogram.
12244
12245 @item
12246 Place the pragma in the package spec that declares the called subprogram,
12247 without naming any entity. This disables warnings on all elaboration calls to
12248 all subprograms declared in this spec.
12249 @end itemize
12250
12251 @noindent
12252 These four cases are listed in order of decreasing safety, and therefore
12253 require increasing programmer care in their application. Consider the
12254 following program:
12255 @smallexample
12256
12257 package Pack1 is
12258   function F1 return Integer;
12259   X1 : Integer;
12260 end Pack1;
12261
12262 package Pack2 is
12263   function F2 return Integer;
12264   function Pure (x : integer) return integer;
12265   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
12266   --  pragma Suppress (Elaboration_Check);              -- (4)
12267 end Pack2;
12268
12269 with Pack2;
12270 package body Pack1 is
12271   function F1 return Integer is
12272   begin
12273     return 100;
12274   end F1;
12275   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
12276 begin
12277   declare
12278     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
12279     --  pragma Suppress(Elaboration_Check);             -- (2)
12280   begin
12281     X1 := Pack2.F2 + 1;                --  Elab. call (2)
12282   end;
12283 end Pack1;
12284
12285 with Pack1;
12286 package body Pack2 is
12287   function F2 return Integer is
12288   begin
12289      return Pack1.F1;
12290   end F2;
12291   function Pure (x : integer) return integer is
12292   begin
12293      return x ** 3 - 3 * x;
12294   end;
12295 end Pack2;
12296
12297 with Pack1, Ada.Text_IO;
12298 procedure Proc3 is
12299 begin
12300   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
12301 end Proc3;
12302 @end smallexample
12303 In the absence of any pragmas, an attempt to bind this program produces
12304 the following diagnostics:
12305 @smallexample
12306 @group
12307 @iftex
12308 @leftskip=.5cm
12309 @end iftex
12310 error: elaboration circularity detected
12311 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
12312 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
12313 info:       recompile "pack1 (body)" with -gnatwl for full details
12314 info:          "pack1 (body)"
12315 info:             must be elaborated along with its spec:
12316 info:          "pack1 (spec)"
12317 info:             which is withed by:
12318 info:          "pack2 (body)"
12319 info:             which must be elaborated along with its spec:
12320 info:          "pack2 (spec)"
12321 info:             which is withed by:
12322 info:          "pack1 (body)"
12323 @end group
12324 @end smallexample
12325 The sources of the circularity are the two calls to @code{Pack2.Pure} and
12326 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
12327 F2 is safe, even though F2 calls F1, because the call appears after the
12328 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
12329 remove the warning on the call. It is also possible to use pragma (2)
12330 because there are no other potentially unsafe calls in the block.
12331
12332 @noindent
12333 The call to @code{Pure} is safe because this function does not depend on the
12334 state of @code{Pack2}. Therefore any call to this function is safe, and it
12335 is correct to place pragma (3) in the corresponding package spec.
12336
12337 @noindent
12338 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
12339 warnings on all calls to functions declared therein. Note that this is not
12340 necessarily safe, and requires more detailed examination of the subprogram
12341 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
12342 be already elaborated.
12343 @end table
12344
12345 @noindent
12346 It is hard to generalize on which of these four approaches should be
12347 taken. Obviously if it is possible to fix the program so that the default
12348 treatment works, this is preferable, but this may not always be practical.
12349 It is certainly simple enough to use
12350 @option{-gnatE}
12351 but the danger in this case is that, even if the GNAT binder
12352 finds a correct elaboration order, it may not always do so,
12353 and certainly a binder from another Ada compiler might not. A
12354 combination of testing and analysis (for which the warnings generated
12355 with the
12356 @option{-gnatwl}
12357 switch can be useful) must be used to ensure that the program is free
12358 of errors. One switch that is useful in this testing is the
12359 @code{-p (pessimistic elaboration order)}
12360 switch for
12361 @code{gnatbind}.
12362 Normally the binder tries to find an order that has the best chance of
12363 of avoiding elaboration problems. With this switch, the binder
12364 plays a devil's advocate role, and tries to choose the order that
12365 has the best chance of failing. If your program works even with this
12366 switch, then it has a better chance of being error free, but this is still
12367 not a guarantee.
12368
12369 For an example of this approach in action, consider the C-tests (executable
12370 tests) from the ACVC suite. If these are compiled and run with the default
12371 treatment, then all but one of them succeed without generating any error
12372 diagnostics from the binder. However, there is one test that fails, and
12373 this is not surprising, because the whole point of this test is to ensure
12374 that the compiler can handle cases where it is impossible to determine
12375 a correct order statically, and it checks that an exception is indeed
12376 raised at run time.
12377
12378 This one test must be compiled and run using the
12379 @option{-gnatE}
12380 switch, and then it passes. Alternatively, the entire suite can
12381 be run using this switch. It is never wrong to run with the dynamic
12382 elaboration switch if your code is correct, and we assume that the
12383 C-tests are indeed correct (it is less efficient, but efficiency is
12384 not a factor in running the ACVC tests.)
12385
12386 @node Elaboration for Access-to-Subprogram Values
12387 @section Elaboration for Access-to-Subprogram Values
12388 @cindex Access-to-subprogram
12389
12390 @noindent
12391 The introduction of access-to-subprogram types in Ada 95 complicates
12392 the handling of elaboration. The trouble is that it becomes
12393 impossible to tell at compile time which procedure
12394 is being called. This means that it is not possible for the binder
12395 to analyze the elaboration requirements in this case.
12396
12397 If at the point at which the access value is created
12398 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
12399 the body of the subprogram is
12400 known to have been elaborated, then the access value is safe, and its use
12401 does not require a check. This may be achieved by appropriate arrangement
12402 of the order of declarations if the subprogram is in the current unit,
12403 or, if the subprogram is in another unit, by using pragma
12404 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
12405 on the referenced unit.
12406
12407 If the referenced body is not known to have been elaborated at the point
12408 the access value is created, then any use of the access value must do a
12409 dynamic check, and this dynamic check will fail and raise a
12410 @code{Program_Error} exception if the body has not been elaborated yet.
12411 GNAT will generate the necessary checks, and in addition, if the
12412 @option{-gnatwl}
12413 switch is set, will generate warnings that such checks are required.
12414
12415 The use of dynamic dispatching for tagged types similarly generates
12416 a requirement for dynamic checks, and premature calls to any primitive
12417 operation of a tagged type before the body of the operation has been elaborated,
12418 will result in the raising of @code{Program_Error}.
12419
12420 @node Summary of Procedures for Elaboration Control
12421 @section Summary of Procedures for Elaboration Control
12422 @cindex Elaboration control
12423
12424 @noindent
12425 First, compile your program with the default options, using none of
12426 the special elaboration control switches. If the binder successfully
12427 binds your program, then you can be confident that, apart from issues
12428 raised by the use of access-to-subprogram types and dynamic dispatching,
12429 the program is free of elaboration errors. If it is important that the
12430 program be portable, then use the
12431 @option{-gnatwl}
12432 switch to generate warnings about missing @code{Elaborate_All}
12433 pragmas, and supply the missing pragmas.
12434
12435 If the program fails to bind using the default static elaboration
12436 handling, then you can fix the program to eliminate the binder
12437 message, or recompile the entire program with the
12438 @option{-gnatE} switch to generate dynamic elaboration checks,
12439 and, if you are sure there really are no elaboration problems,
12440 use a global pragma @code{Suppress (Elaboration_Checks)}.
12441
12442 @node Other Elaboration Order Considerations
12443 @section Other Elaboration Order Considerations
12444 @noindent
12445 This section has been entirely concerned with the issue of finding a valid
12446 elaboration order, as defined by the Ada Reference Manual. In a case
12447 where several elaboration orders are valid, the task is to find one
12448 of the possible valid elaboration orders (and the static model in GNAT
12449 will ensure that this is achieved).
12450
12451 The purpose of the elaboration rules in the Ada Reference Manual is to
12452 make sure that no entity is accessed before it has been elaborated. For
12453 a subprogram, this means that the spec and body must have been elaborated
12454 before the subprogram is called. For an object, this means that the object
12455 must have been elaborated before its value is read or written. A violation
12456 of either of these two requirements is an access before elaboration order,
12457 and this section has been all about avoiding such errors.
12458
12459 In the case where more than one order of elaboration is possible, in the
12460 sense that access before elaboration errors are avoided, then any one of
12461 the orders is "correct" in the sense that it meets the requirements of
12462 the Ada Reference Manual, and no such error occurs.
12463
12464 However, it may be the case for a given program, that there are
12465 constraints on the order of elaboration that come not from consideration
12466 of avoiding elaboration errors, but rather from extra-lingual logic
12467 requirements. Consider this example:
12468
12469 @smallexample
12470 with Init_Constants;
12471 package Constants is
12472    X : Integer := 0;
12473    Y : Integer := 0;
12474 end Constants;
12475
12476 package Init_Constants is
12477    procedure Calc;
12478 end Init_Constants;
12479
12480 with Constants;
12481 package body Init_Constants is
12482    procedure Calc is begin null; end;
12483 begin
12484    Constants.X := 3;
12485    Constants.Y := 4;
12486 end Init_Constants;
12487
12488 with Constants;
12489 package Calc is
12490    Z : Integer := Constants.X + Constants.Y;
12491 end Calc;
12492
12493 with Calc;
12494 with Text_IO; use Text_IO;
12495 procedure Main is
12496 begin
12497    Put_Line (Calc.Z'Img);
12498 end Main;
12499 @end smallexample
12500
12501 @noindent
12502 In this example, there is more than one valid order of elaboration. For
12503 example both the following are correct orders:
12504
12505 @smallexample
12506 Init_Constants spec
12507 Constants spec
12508 Calc spec
12509 Main body
12510 Init_Constants body
12511
12512   and
12513
12514 Init_Constants spec
12515 Init_Constants body
12516 Constants spec
12517 Calc spec
12518 Main body
12519 @end smallexample
12520
12521 @noindent
12522 There is no language rule to prefer one or the other, both are correct
12523 from an order of elaboration point of view. But the programmatic effects
12524 of the two orders are very different. In the first, the elaboration routine
12525 of @code{Calc} initializes @code{Z} to zero, and then the main program
12526 runs with this value of zero. But in the second order, the elaboration
12527 routine of @code{Calc} runs after the body of Init_Constants has set
12528 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
12529 runs.
12530
12531 One could perhaps by applying pretty clever non-artificial intelligence
12532 to the situation guess that it is more likely that the second order of
12533 elaboration is the one desired, but there is no formal linguistic reason
12534 to prefer one over the other. In fact in this particular case, GNAT will
12535 prefer the second order, because of the rule that bodies are elaborated
12536 as soon as possible, but it's just luck that this is what was wanted
12537 (if indeed the second order was preferred).
12538
12539 If the program cares about the order of elaboration routines in a case like
12540 this, it is important to specify the order required. In this particular
12541 case, that could have been achieved by adding to the spec of Calc:
12542
12543 @smallexample
12544 pragma Elaborate_All (Constants);
12545 @end smallexample
12546
12547 @noindent
12548 which requires that the body (if any) and spec of @code{Constants},
12549 as well as the body and spec of any unit @code{with}'ed by
12550 @code{Constants} be elaborated before @code{Calc} is elaborated.
12551
12552 Clearly no automatic method can always guess which alternative you require,
12553 and if you are working with legacy code that had constraints of this kind
12554 which were not properly specified by adding @code{Elaborate} or
12555 @code{Elaborate_All} pragmas, then indeed it is possible that two different
12556 compilers can choose different orders.
12557
12558 The @code{gnatbind}
12559 @code{-p} switch may be useful in smoking
12560 out problems. This switch causes bodies to be elaborated as late as possible
12561 instead of as early as possible. In the example above, it would have forced
12562 the choice of the first elaboration order. If you get different results
12563 when using this switch, and particularly if one set of results is right,
12564 and one is wrong as far as you are concerned, it shows that you have some
12565 missing @code{Elaborate} pragmas. For the example above, we have the
12566 following output:
12567
12568 @smallexample
12569 gnatmake -f -q main
12570 main
12571  7
12572 gnatmake -f -q main -bargs -p
12573 main
12574  0
12575 @end smallexample
12576
12577 @noindent
12578 It is of course quite unlikely that both these results are correct, so
12579 it is up to you in a case like this to investigate the source of the
12580 difference, by looking at the two elaboration orders that are chosen,
12581 and figuring out which is correct, and then adding the necessary
12582 @code{Elaborate_All} pragmas to ensure the desired order.
12583
12584 @node The Cross-Referencing Tools gnatxref and gnatfind
12585 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12586 @findex gnatxref
12587 @findex gnatfind
12588
12589 @noindent
12590 The compiler generates cross-referencing information (unless
12591 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12592 This information indicates where in the source each entity is declared and
12593 referenced. Note that entities in package Standard are not included, but
12594 entities in all other predefined units are included in the output.
12595
12596 Before using any of these two tools, you need to compile successfully your
12597 application, so that GNAT gets a chance to generate the cross-referencing
12598 information.
12599
12600 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12601 information to provide the user with the capability to easily locate the
12602 declaration and references to an entity. These tools are quite similar,
12603 the difference being that @code{gnatfind} is intended for locating
12604 definitions and/or references to a specified entity or entities, whereas
12605 @code{gnatxref} is oriented to generating a full report of all
12606 cross-references.
12607
12608 To use these tools, you must not compile your application using the
12609 @option{-gnatx} switch on the @file{gnatmake} command line (@inforef{The
12610 GNAT Make Program gnatmake,,gnat_ug}). Otherwise, cross-referencing
12611 information will not be generated.
12612
12613 @menu
12614 * gnatxref Switches::
12615 * gnatfind Switches::
12616 * Project Files for gnatxref and gnatfind::
12617 * Regular Expressions in gnatfind and gnatxref::
12618 * Examples of gnatxref Usage::
12619 * Examples of gnatfind Usage::
12620 @end menu
12621
12622 @node gnatxref Switches
12623 @section @code{gnatxref} Switches
12624
12625 @noindent
12626 The command lines for @code{gnatxref} is:
12627 @smallexample
12628 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
12629 @end smallexample
12630
12631 @noindent
12632 where
12633
12634 @table @code
12635 @item sourcefile1, sourcefile2
12636 identifies the source files for which a report is to be generated. The
12637 'with'ed units will be processed too. You must provide at least one file.
12638
12639 These file names are considered to be regular expressions, so for instance
12640 specifying 'source*.adb' is the same as giving every file in the current
12641 directory whose name starts with 'source' and whose extension is 'adb'.
12642
12643 @end table
12644
12645 @noindent
12646 The switches can be :
12647 @table @code
12648 @item -a
12649 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12650 the read-only files found in the library search path. Otherwise, these files
12651 will be ignored. This option can be used to protect Gnat sources or your own
12652 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12653 much faster, and their output much smaller.
12654
12655 @item -aIDIR
12656 When looking for source files also look in directory DIR. The order in which
12657 source file search is undertaken is the same as for @file{gnatmake}.
12658
12659 @item -aODIR
12660 When searching for library and object files, look in directory
12661 DIR. The order in which library files are searched is the same as for
12662 @file{gnatmake}.
12663
12664 @item -nostdinc
12665 Do not look for sources in the system default directory.
12666
12667 @item -nostdlib
12668 Do not look for library files in the system default directory.
12669
12670 @item --RTS=@var{rts-path}
12671 @cindex @code{--RTS} (@code{gnatxref})
12672 Specifies the default location of the runtime library. Same meaning as the
12673 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
12674
12675 @item -d
12676 If this switch is set @code{gnatxref} will output the parent type
12677 reference for each matching derived types.
12678
12679 @item -f
12680 If this switch is set, the output file names will be preceded by their
12681 directory (if the file was found in the search path). If this switch is
12682 not set, the directory will not be printed.
12683
12684 @item -g
12685 If this switch is set, information is output only for library-level
12686 entities, ignoring local entities. The use of this switch may accelerate
12687 @code{gnatfind} and @code{gnatxref}.
12688
12689 @item -IDIR
12690 Equivalent to @samp{-aODIR -aIDIR}.
12691
12692 @item -pFILE
12693 Specify a project file to use @xref{Project Files}.
12694 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12695 project file in the current directory.
12696
12697 If a project file is either specified or found by the tools, then the content
12698 of the source directory and object directory lines are added as if they
12699 had been specified respectively by @samp{-aI}
12700 and @samp{-aO}.
12701 @item -u
12702 Output only unused symbols. This may be really useful if you give your
12703 main compilation unit on the command line, as @code{gnatxref} will then
12704 display every unused entity and 'with'ed package.
12705
12706 @item -v
12707 Instead of producing the default output, @code{gnatxref} will generate a
12708 @file{tags} file that can be used by vi. For examples how to use this
12709 feature, see @xref{Examples of gnatxref Usage}. The tags file is output
12710 to the standard output, thus you will have to redirect it to a file.
12711
12712 @end table
12713
12714 All these switches may be in any order on the command line, and may even
12715 appear after the file names. They need not be separated by spaces, thus
12716 you can say @samp{gnatxref -ag} instead of
12717 @samp{gnatxref -a -g}.
12718
12719 @node gnatfind Switches
12720 @section @code{gnatfind} Switches
12721
12722 @noindent
12723 The command line for @code{gnatfind} is:
12724
12725 @smallexample
12726 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
12727       [file1 file2 ...]
12728 @end smallexample
12729
12730 @noindent
12731 where
12732
12733 @table @code
12734 @item pattern
12735 An entity will be output only if it matches the regular expression found
12736 in @samp{pattern}, see @xref{Regular Expressions in gnatfind and gnatxref}.
12737
12738 Omitting the pattern is equivalent to specifying @samp{*}, which
12739 will match any entity. Note that if you do not provide a pattern, you
12740 have to provide both a sourcefile and a line.
12741
12742 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12743 for matching purposes. At the current time there is no support for
12744 8-bit codes other than Latin-1, or for wide characters in identifiers.
12745
12746 @item sourcefile
12747 @code{gnatfind} will look for references, bodies or declarations
12748 of symbols referenced in @file{sourcefile}, at line @samp{line}
12749 and column @samp{column}. See @pxref{Examples of gnatfind Usage}
12750 for syntax examples.
12751
12752 @item line
12753 is a decimal integer identifying the line number containing
12754 the reference to the entity (or entities) to be located.
12755
12756 @item column
12757 is a decimal integer identifying the exact location on the
12758 line of the first character of the identifier for the
12759 entity reference. Columns are numbered from 1.
12760
12761 @item file1 file2 ...
12762 The search will be restricted to these files. If none are given, then
12763 the search will be done for every library file in the search path.
12764 These file must appear only after the pattern or sourcefile.
12765
12766 These file names are considered to be regular expressions, so for instance
12767 specifying 'source*.adb' is the same as giving every file in the current
12768 directory whose name starts with 'source' and whose extension is 'adb'.
12769
12770 Not that if you specify at least one file in this part, @code{gnatfind} may
12771 sometimes not be able to find the body of the subprograms...
12772
12773 @end table
12774
12775 At least one of 'sourcefile' or 'pattern' has to be present on
12776 the command line.
12777
12778 The following switches are available:
12779 @table @code
12780
12781 @item -a
12782 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12783 the read-only files found in the library search path. Otherwise, these files
12784 will be ignored. This option can be used to protect Gnat sources or your own
12785 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12786 much faster, and their output much smaller.
12787
12788 @item -aIDIR
12789 When looking for source files also look in directory DIR. The order in which
12790 source file search is undertaken is the same as for @file{gnatmake}.
12791
12792 @item -aODIR
12793 When searching for library and object files, look in directory
12794 DIR. The order in which library files are searched is the same as for
12795 @file{gnatmake}.
12796
12797 @item -nostdinc
12798 Do not look for sources in the system default directory.
12799
12800 @item -nostdlib
12801 Do not look for library files in the system default directory.
12802
12803 @item --RTS=@var{rts-path}
12804 @cindex @code{--RTS} (@code{gnatfind})
12805 Specifies the default location of the runtime library. Same meaning as the
12806 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
12807
12808 @item -d
12809 If this switch is set, then @code{gnatfind} will output the parent type
12810 reference for each matching derived types.
12811
12812 @item -e
12813 By default, @code{gnatfind} accept the simple regular expression set for
12814 @samp{pattern}. If this switch is set, then the pattern will be
12815 considered as full Unix-style regular expression.
12816
12817 @item -f
12818 If this switch is set, the output file names will be preceded by their
12819 directory (if the file was found in the search path). If this switch is
12820 not set, the directory will not be printed.
12821
12822 @item -g
12823 If this switch is set, information is output only for library-level
12824 entities, ignoring local entities. The use of this switch may accelerate
12825 @code{gnatfind} and @code{gnatxref}.
12826
12827 @item -IDIR
12828 Equivalent to @samp{-aODIR -aIDIR}.
12829
12830 @item -pFILE
12831 Specify a project file (@pxref{Project Files}) to use.
12832 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12833 project file in the current directory.
12834
12835 If a project file is either specified or found by the tools, then the content
12836 of the source directory and object directory lines are added as if they
12837 had been specified respectively by @samp{-aI} and
12838 @samp{-aO}.
12839
12840 @item -r
12841 By default, @code{gnatfind} will output only the information about the
12842 declaration, body or type completion of the entities. If this switch is
12843 set, the @code{gnatfind} will locate every reference to the entities in
12844 the files specified on the command line (or in every file in the search
12845 path if no file is given on the command line).
12846
12847 @item -s
12848 If this switch is set, then @code{gnatfind} will output the content
12849 of the Ada source file lines were the entity was found.
12850
12851 @item -t
12852 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12853 the specified type. It act like -d option but recursively from parent
12854 type to parent type. When this switch is set it is not possible to
12855 specify more than one file.
12856
12857 @end table
12858
12859 All these switches may be in any order on the command line, and may even
12860 appear after the file names. They need not be separated by spaces, thus
12861 you can say @samp{gnatxref -ag} instead of
12862 @samp{gnatxref -a -g}.
12863
12864 As stated previously, gnatfind will search in every directory in the
12865 search path. You can force it to look only in the current directory if
12866 you specify @code{*} at the end of the command line.
12867
12868
12869 @node Project Files for gnatxref and gnatfind
12870 @section Project Files for @command{gnatxref} and @command{gnatfind}
12871
12872 @noindent
12873 Project files allow a programmer to specify how to compile its
12874 application, where to find sources,... These files are used primarily by
12875 the Glide Ada mode, but they can also be used by the two tools
12876 @code{gnatxref} and @code{gnatfind}.
12877
12878 A project file name must end with @file{.adp}. If a single one is
12879 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
12880 extract the information from it. If multiple project files are found, none of
12881 them is read, and you have to use the @samp{-p} switch to specify the one
12882 you want to use.
12883
12884 The following lines can be included, even though most of them have default
12885 values which can be used in most cases.
12886 The lines can be entered in any order in the file.
12887 Except for @samp{src_dir} and @samp{obj_dir}, you can only have one instance of
12888 each line. If you have multiple instances, only the last one is taken into
12889 account.
12890
12891 @table @code
12892 @item src_dir=DIR         [default: "./"]
12893 specifies a directory where to look for source files. Multiple src_dir lines
12894 can be specified and they will be searched in the order they
12895 are specified.
12896
12897 @item obj_dir=DIR         [default: "./"]
12898 specifies a directory where to look for object and library files. Multiple
12899 obj_dir lines can be specified and they will be searched in the order they
12900 are specified
12901
12902 @item comp_opt=SWITCHES   [default: ""]
12903 creates a variable which can be referred to subsequently by using
12904 the @samp{$@{comp_opt@}} notation. This is intended to store the default
12905 switches given to @file{gnatmake} and @file{gcc}.
12906
12907 @item bind_opt=SWITCHES   [default: ""]
12908 creates a variable which can be referred to subsequently by using
12909 the @samp{$@{bind_opt@}} notation. This is intended to store the default
12910 switches given to @file{gnatbind}.
12911
12912 @item link_opt=SWITCHES   [default: ""]
12913 creates a variable which can be referred to subsequently by using
12914 the @samp{$@{link_opt@}} notation. This is intended to store the default
12915 switches given to @file{gnatlink}.
12916
12917 @item main=EXECUTABLE     [default: ""]
12918 specifies the name of the executable for the application. This variable can
12919 be referred to in the following lines by using the @samp{$@{main@}} notation.
12920
12921 @item comp_cmd=COMMAND    [default: "gcc -c -I$@{src_dir@} -g -gnatq"]
12922 specifies the command used to compile a single file in the application.
12923
12924 @item make_cmd=COMMAND    [default: "gnatmake $@{main@} -aI$@{src_dir@} -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@} -bargs $@{bind_opt@} -largs $@{link_opt@}"]
12925 specifies the command used to recompile the whole application.
12926
12927 @item run_cmd=COMMAND     [default: "$@{main@}"]
12928 specifies the command used to run the application.
12929
12930 @item debug_cmd=COMMAND   [default: "gdb $@{main@}"]
12931 specifies the command used to debug the application
12932
12933 @end table
12934
12935 @code{gnatxref} and @code{gnatfind} only take into account the @samp{src_dir}
12936 and @samp{obj_dir} lines, and ignore the others.
12937
12938 @node Regular Expressions in gnatfind and gnatxref
12939 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
12940
12941 @noindent
12942 As specified in the section about @code{gnatfind}, the pattern can be a
12943 regular expression. Actually, there are to set of regular expressions
12944 which are recognized by the program :
12945
12946 @table @code
12947 @item globbing patterns
12948 These are the most usual regular expression. They are the same that you
12949 generally used in a Unix shell command line, or in a DOS session.
12950
12951 Here is a more formal grammar :
12952 @smallexample
12953 @group
12954 @iftex
12955 @leftskip=.5cm
12956 @end iftex
12957 regexp ::= term
12958 term   ::= elmt            -- matches elmt
12959 term   ::= elmt elmt       -- concatenation (elmt then elmt)
12960 term   ::= *               -- any string of 0 or more characters
12961 term   ::= ?               -- matches any character
12962 term   ::= [char @{char@}] -- matches any character listed
12963 term   ::= [char - char]   -- matches any character in range
12964 @end group
12965 @end smallexample
12966
12967 @item full regular expression
12968 The second set of regular expressions is much more powerful. This is the
12969 type of regular expressions recognized by utilities such a @file{grep}.
12970
12971 The following is the form of a regular expression, expressed in Ada
12972 reference manual style BNF is as follows
12973
12974 @smallexample
12975 @iftex
12976 @leftskip=.5cm
12977 @end iftex
12978 @group
12979 regexp ::= term @{| term@} -- alternation (term or term ...)
12980
12981 term ::= item @{item@}     -- concatenation (item then item)
12982
12983 item ::= elmt              -- match elmt
12984 item ::= elmt *            -- zero or more elmt's
12985 item ::= elmt +            -- one or more elmt's
12986 item ::= elmt ?            -- matches elmt or nothing
12987 @end group
12988 @group
12989 elmt ::= nschar            -- matches given character
12990 elmt ::= [nschar @{nschar@}]   -- matches any character listed
12991 elmt ::= [^ nschar @{nschar@}] -- matches any character not listed
12992 elmt ::= [char - char]     -- matches chars in given range
12993 elmt ::= \ char            -- matches given character
12994 elmt ::= .                 -- matches any single character
12995 elmt ::= ( regexp )        -- parens used for grouping
12996
12997 char ::= any character, including special characters
12998 nschar ::= any character except ()[].*+?^
12999 @end group
13000 @end smallexample
13001
13002 Following are a few examples :
13003
13004 @table @samp
13005 @item abcde|fghi
13006 will match any of the two strings 'abcde' and 'fghi'.
13007
13008 @item abc*d
13009 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
13010
13011 @item [a-z]+
13012 will match any string which has only lowercase characters in it (and at
13013 least one character
13014
13015 @end table
13016 @end table
13017
13018 @node Examples of gnatxref Usage
13019 @section Examples of @code{gnatxref} Usage
13020
13021 @subsection General Usage
13022
13023 @noindent
13024 For the following examples, we will consider the following units :
13025
13026 @smallexample
13027 @group
13028 @cartouche
13029 main.ads:
13030 1: @b{with} Bar;
13031 2: @b{package} Main @b{is}
13032 3:     @b{procedure} Foo (B : @b{in} Integer);
13033 4:     C : Integer;
13034 5: @b{private}
13035 6:     D : Integer;
13036 7: @b{end} Main;
13037
13038 main.adb:
13039 1: @b{package body} Main @b{is}
13040 2:     @b{procedure} Foo (B : @b{in} Integer) @b{is}
13041 3:     @b{begin}
13042 4:        C := B;
13043 5:        D := B;
13044 6:        Bar.Print (B);
13045 7:        Bar.Print (C);
13046 8:     @b{end} Foo;
13047 9: @b{end} Main;
13048
13049 bar.ads:
13050 1: @b{package} Bar @b{is}
13051 2:     @b{procedure} Print (B : Integer);
13052 3: @b{end} bar;
13053 @end cartouche
13054 @end group
13055 @end smallexample
13056
13057 @table @code
13058
13059 @noindent
13060 The first thing to do is to recompile your application (for instance, in
13061 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13062 the cross-referencing information.
13063 You can then issue any of the following commands:
13064
13065 @item gnatxref main.adb
13066 @code{gnatxref} generates cross-reference information for main.adb
13067 and every unit 'with'ed by main.adb.
13068
13069 The output would be:
13070 @smallexample
13071 @iftex
13072 @leftskip=0cm
13073 @end iftex
13074 B                                                      Type: Integer
13075   Decl: bar.ads           2:22
13076 B                                                      Type: Integer
13077   Decl: main.ads          3:20
13078   Body: main.adb          2:20
13079   Ref:  main.adb          4:13     5:13     6:19
13080 Bar                                                    Type: Unit
13081   Decl: bar.ads           1:9
13082   Ref:  main.adb          6:8      7:8
13083        main.ads           1:6
13084 C                                                      Type: Integer
13085   Decl: main.ads          4:5
13086   Modi: main.adb          4:8
13087   Ref:  main.adb          7:19
13088 D                                                      Type: Integer
13089   Decl: main.ads          6:5
13090   Modi: main.adb          5:8
13091 Foo                                                    Type: Unit
13092   Decl: main.ads          3:15
13093   Body: main.adb          2:15
13094 Main                                                    Type: Unit
13095   Decl: main.ads          2:9
13096   Body: main.adb          1:14
13097 Print                                                   Type: Unit
13098   Decl: bar.ads           2:15
13099   Ref:  main.adb          6:12     7:12
13100 @end smallexample
13101
13102 @noindent
13103 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13104 its body is in main.adb, line 1, column 14 and is not referenced any where.
13105
13106 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13107 it referenced in main.adb, line 6 column 12 and line 7 column 12.
13108
13109 @item gnatxref package1.adb package2.ads
13110 @code{gnatxref} will generates cross-reference information for
13111 package1.adb, package2.ads and any other package 'with'ed by any
13112 of these.
13113
13114 @end table
13115
13116 @subsection Using gnatxref with vi
13117
13118 @code{gnatxref} can generate a tags file output, which can be used
13119 directly from @file{vi}. Note that the standard version of @file{vi}
13120 will not work properly with overloaded symbols. Consider using another
13121 free implementation of @file{vi}, such as @file{vim}.
13122
13123 @smallexample
13124 $ gnatxref -v gnatfind.adb > tags
13125 @end smallexample
13126
13127 @noindent
13128 will generate the tags file for @code{gnatfind} itself (if the sources
13129 are in the search path!).
13130
13131 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
13132 (replacing @i{entity} by whatever you are looking for), and vi will
13133 display a new file with the corresponding declaration of entity.
13134
13135 @node Examples of gnatfind Usage
13136 @section Examples of @code{gnatfind} Usage
13137
13138 @table @code
13139
13140 @item gnatfind -f xyz:main.adb
13141 Find declarations for all entities xyz referenced at least once in
13142 main.adb. The references are search in every library file in the search
13143 path.
13144
13145 The directories will be printed as well (as the @samp{-f}
13146 switch is set)
13147
13148 The output will look like:
13149 @smallexample
13150 directory/main.ads:106:14: xyz <= declaration
13151 directory/main.adb:24:10: xyz <= body
13152 directory/foo.ads:45:23: xyz <= declaration
13153 @end smallexample
13154
13155 @noindent
13156 that is to say, one of the entities xyz found in main.adb is declared at
13157 line 12 of main.ads (and its body is in main.adb), and another one is
13158 declared at line 45 of foo.ads
13159
13160 @item gnatfind -fs xyz:main.adb
13161 This is the same command as the previous one, instead @code{gnatfind} will
13162 display the content of the Ada source file lines.
13163
13164 The output will look like:
13165
13166 @smallexample
13167 directory/main.ads:106:14: xyz <= declaration
13168    procedure xyz;
13169 directory/main.adb:24:10: xyz <= body
13170    procedure xyz is
13171 directory/foo.ads:45:23: xyz <= declaration
13172    xyz : Integer;
13173 @end smallexample
13174
13175 @noindent
13176 This can make it easier to find exactly the location your are looking
13177 for.
13178
13179 @item gnatfind -r "*x*":main.ads:123 foo.adb
13180 Find references to all entities containing an x that are
13181 referenced on line 123 of main.ads.
13182 The references will be searched only in main.adb and foo.adb.
13183
13184 @item gnatfind main.ads:123
13185 Find declarations and bodies for all entities that are referenced on
13186 line 123 of main.ads.
13187
13188 This is the same as @code{gnatfind "*":main.adb:123}.
13189
13190 @item gnatfind mydir/main.adb:123:45
13191 Find the declaration for the entity referenced at column 45 in
13192 line 123 of file main.adb in directory mydir. Note that it
13193 is usual to omit the identifier name when the column is given,
13194 since the column position identifies a unique reference.
13195
13196 The column has to be the beginning of the identifier, and should not
13197 point to any character in the middle of the identifier.
13198
13199 @end table
13200
13201 @node File Name Krunching Using gnatkr
13202 @chapter File Name Krunching Using @code{gnatkr}
13203 @findex gnatkr
13204
13205 @noindent
13206 This chapter discusses the method used by the compiler to shorten
13207 the default file names chosen for Ada units so that they do not
13208 exceed the maximum length permitted. It also describes the
13209 @code{gnatkr} utility that can be used to determine the result of
13210 applying this shortening.
13211 @menu
13212 * About gnatkr::
13213 * Using gnatkr::
13214 * Krunching Method::
13215 * Examples of gnatkr Usage::
13216 @end menu
13217
13218 @node About gnatkr
13219 @section About @code{gnatkr}
13220
13221 @noindent
13222 The default file naming rule in GNAT
13223 is that the file name must be derived from
13224 the unit name. The exact default rule is as follows:
13225 @itemize @bullet
13226 @item
13227 Take the unit name and replace all dots by hyphens.
13228 @item
13229 If such a replacement occurs in the
13230 second character position of a name, and the first character is
13231 a, g, s, or i then replace the dot by the character
13232 ~ (tilde)
13233 instead of a minus.
13234 @end itemize
13235 The reason for this exception is to avoid clashes
13236 with the standard names for children of System, Ada, Interfaces,
13237 and GNAT, which use the prefixes s- a- i- and g-
13238 respectively.
13239
13240 The @code{-gnatk@var{nn}}
13241 switch of the compiler activates a "krunching"
13242 circuit that limits file names to nn characters (where nn is a decimal
13243 integer). For example, using OpenVMS,
13244 where the maximum file name length is
13245 39, the value of nn is usually set to 39, but if you want to generate
13246 a set of files that would be usable if ported to a system with some
13247 different maximum file length, then a different value can be specified.
13248 The default value of 39 for OpenVMS need not be specified.
13249
13250 The @code{gnatkr} utility can be used to determine the krunched name for
13251 a given file, when krunched to a specified maximum length.
13252
13253 @node Using gnatkr
13254 @section Using @code{gnatkr}
13255
13256 @noindent
13257 The @code{gnatkr} command has the form
13258
13259 @smallexample
13260 $ gnatkr @var{name} [@var{length}]
13261 @end smallexample
13262
13263
13264 @noindent
13265 @var{name} can be an Ada name with dots or the GNAT name of the unit,
13266 where the dots representing child units or subunit are replaced by
13267 hyphens. The only confusion arises if a name ends in @code{.ads} or
13268 @code{.adb}. @code{gnatkr} takes this to be an extension if there are
13269 no other dots in the name and the whole name is in lowercase.
13270
13271 @var{length} represents the length of the krunched name. The default
13272 when no argument is given is 8 characters. A length of zero stands for
13273 unlimited, in other words do not chop except for system files which are
13274 always 8.
13275
13276 @noindent
13277 The output is the krunched name. The output has an extension only if the
13278 original argument was a file name with an extension.
13279
13280 @node Krunching Method
13281 @section Krunching Method
13282
13283 @noindent
13284 The initial file name is determined by the name of the unit that the file
13285 contains. The name is formed by taking the full expanded name of the
13286 unit and replacing the separating dots with hyphens and
13287 using lowercase
13288 for all letters, except that a hyphen in the second character position is
13289 replaced by a tilde if the first character is
13290 a, i, g, or s.
13291 The extension is @code{.ads} for a
13292 specification and @code{.adb} for a body.
13293 Krunching does not affect the extension, but the file name is shortened to
13294 the specified length by following these rules:
13295
13296 @itemize @bullet
13297 @item
13298 The name is divided into segments separated by hyphens, tildes or
13299 underscores and all hyphens, tildes, and underscores are
13300 eliminated. If this leaves the name short enough, we are done.
13301
13302 @item
13303 If the name is too long, the longest segment is located (left-most if there are two
13304 of equal length), and shortened by dropping its last character. This is
13305 repeated until the name is short enough.
13306
13307 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
13308 to fit the name into 8 characters as required by some operating systems.
13309
13310 @smallexample
13311 our-strings-wide_fixed 22
13312 our strings wide fixed 19
13313 our string  wide fixed 18
13314 our strin   wide fixed 17
13315 our stri    wide fixed 16
13316 our stri    wide fixe  15
13317 our str     wide fixe  14
13318 our str     wid  fixe  13
13319 our str     wid  fix   12
13320 ou  str     wid  fix   11
13321 ou  st      wid  fix   10
13322 ou  st      wi   fix   9
13323 ou  st      wi   fi    8
13324 Final file name: oustwifi.adb
13325 @end smallexample
13326
13327 @item
13328 The file names for all predefined units are always krunched to eight
13329 characters. The krunching of these predefined units uses the following
13330 special prefix replacements:
13331
13332 @table @file
13333 @item ada-
13334 replaced by @file{a-}
13335
13336 @item gnat-
13337 replaced by @file{g-}
13338
13339 @item interfaces-
13340 replaced by @file{i-}
13341
13342 @item system-
13343 replaced by @file{s-}
13344 @end table
13345
13346 These system files have a hyphen in the second character position. That
13347 is why normal user files replace such a character with a
13348 tilde, to
13349 avoid confusion with system file names.
13350
13351 As an example of this special rule, consider
13352 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
13353
13354 @smallexample
13355 ada-strings-wide_fixed 22
13356 a-  strings wide fixed 18
13357 a-  string  wide fixed 17
13358 a-  strin   wide fixed 16
13359 a-  stri    wide fixed 15
13360 a-  stri    wide fixe  14
13361 a-  str     wide fixe  13
13362 a-  str     wid  fixe  12
13363 a-  str     wid  fix   11
13364 a-  st      wid  fix   10
13365 a-  st      wi   fix   9
13366 a-  st      wi   fi    8
13367 Final file name: a-stwifi.adb
13368 @end smallexample
13369 @end itemize
13370
13371 Of course no file shortening algorithm can guarantee uniqueness over all
13372 possible unit names, and if file name krunching is used then it is your
13373 responsibility to ensure that no name clashes occur. The utility
13374 program @code{gnatkr} is supplied for conveniently determining the
13375 krunched name of a file.
13376
13377 @node Examples of gnatkr Usage
13378 @section Examples of @code{gnatkr} Usage
13379
13380 @smallexample
13381 @iftex
13382 @leftskip=0cm
13383 @end iftex
13384 $ gnatkr very_long_unit_name.ads      --> velounna.ads
13385 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
13386 $ gnatkr Grandparent.Parent.Child     --> grparchi
13387 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
13388 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
13389 @end smallexample
13390
13391 @node Preprocessing Using gnatprep
13392 @chapter Preprocessing Using @code{gnatprep}
13393 @findex gnatprep
13394
13395 @noindent
13396 The @code{gnatprep} utility provides
13397 a simple preprocessing capability for Ada programs.
13398 It is designed for use with GNAT, but is not dependent on any special
13399 features of GNAT.
13400
13401 @menu
13402 * Using gnatprep::
13403 * Switches for gnatprep::
13404 * Form of Definitions File::
13405 * Form of Input Text for gnatprep::
13406 @end menu
13407
13408 @node Using gnatprep
13409 @section Using @code{gnatprep}
13410
13411 @noindent
13412 To call @code{gnatprep} use
13413
13414 @smallexample
13415 $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
13416 @end smallexample
13417
13418 @noindent
13419 where
13420 @table @code
13421 @item infile
13422 is the full name of the input file, which is an Ada source
13423 file containing preprocessor directives.
13424
13425 @item outfile
13426 is the full name of the output file, which is an Ada source
13427 in standard Ada form. When used with GNAT, this file name will
13428 normally have an ads or adb suffix.
13429
13430 @item deffile
13431 is the full name of a text file containing definitions of
13432 symbols to be referenced by the preprocessor. This argument is
13433 optional, and can be replaced by the use of the @code{-D} switch.
13434
13435 @item switches
13436 is an optional sequence of switches as described in the next section.
13437 @end table
13438
13439 @node Switches for gnatprep
13440 @section Switches for @code{gnatprep}
13441
13442 @table @code
13443
13444 @item -b
13445 Causes both preprocessor lines and the lines deleted by
13446 preprocessing to be replaced by blank lines in the output source file,
13447 preserving line numbers in the output file.
13448
13449 @item -c
13450 Causes both preprocessor lines and the lines deleted
13451 by preprocessing to be retained in the output source as comments marked
13452 with the special string "--! ". This option will result in line numbers
13453 being preserved in the output file.
13454
13455 @item -Dsymbol=value
13456 Defines a new symbol, associated with value. If no value is given on the
13457 command line, then symbol is considered to be @code{True}. This switch
13458 can be used in place of a definition file.
13459
13460
13461 @item -r
13462 Causes a @code{Source_Reference} pragma to be generated that
13463 references the original input file, so that error messages will use
13464 the file name of this original file. The use of this switch implies
13465 that preprocessor lines are not to be removed from the file, so its
13466 use will force @code{-b} mode if
13467 @code{-c}
13468 has not been specified explicitly.
13469
13470 Note that if the file to be preprocessed contains multiple units, then
13471 it will be necessary to @code{gnatchop} the output file from
13472 @code{gnatprep}. If a @code{Source_Reference} pragma is present
13473 in the preprocessed file, it will be respected by
13474 @code{gnatchop -r}
13475 so that the final chopped files will correctly refer to the original
13476 input source file for @code{gnatprep}.
13477
13478 @item -s
13479 Causes a sorted list of symbol names and values to be
13480 listed on the standard output file.
13481
13482 @item -u
13483 Causes undefined symbols to be treated as having the value FALSE in the context
13484 of a preprocessor test. In the absence of this option, an undefined symbol in
13485 a @code{#if} or @code{#elsif} test will be treated as an error.
13486
13487 @end table
13488
13489 @noindent
13490 Note: if neither @code{-b} nor @code{-c} is present,
13491 then preprocessor lines and
13492 deleted lines are completely removed from the output, unless -r is
13493 specified, in which case -b is assumed.
13494
13495 @node Form of Definitions File
13496 @section Form of Definitions File
13497
13498 @noindent
13499 The definitions file contains lines of the form
13500
13501 @smallexample
13502 symbol := value
13503 @end smallexample
13504
13505 @noindent
13506 where symbol is an identifier, following normal Ada (case-insensitive)
13507 rules for its syntax, and value is one of the following:
13508
13509 @itemize @bullet
13510 @item
13511 Empty, corresponding to a null substitution
13512 @item
13513 A string literal using normal Ada syntax
13514 @item
13515 Any sequence of characters from the set
13516 (letters, digits, period, underline).
13517 @end itemize
13518
13519 @noindent
13520 Comment lines may also appear in the definitions file, starting with
13521 the usual @code{--},
13522 and comments may be added to the definitions lines.
13523
13524 @node Form of Input Text for gnatprep
13525 @section Form of Input Text for @code{gnatprep}
13526
13527 @noindent
13528 The input text may contain preprocessor conditional inclusion lines,
13529 as well as general symbol substitution sequences.
13530
13531 The preprocessor conditional inclusion commands have the form
13532
13533 @smallexample
13534 @group
13535 @cartouche
13536 #if @i{expression} [then]
13537    lines
13538 #elsif @i{expression} [then]
13539    lines
13540 #elsif @i{expression} [then]
13541    lines
13542 ...
13543 #else
13544    lines
13545 #end if;
13546 @end cartouche
13547 @end group
13548 @end smallexample
13549
13550 @noindent
13551 In this example, @i{expression} is defined by the following grammar:
13552 @smallexample
13553 @i{expression} ::=  <symbol>
13554 @i{expression} ::=  <symbol> = "<value>"
13555 @i{expression} ::=  <symbol> = <symbol>
13556 @i{expression} ::=  <symbol> 'Defined
13557 @i{expression} ::=  not @i{expression}
13558 @i{expression} ::=  @i{expression} and @i{expression}
13559 @i{expression} ::=  @i{expression} or @i{expression}
13560 @i{expression} ::=  @i{expression} and then @i{expression}
13561 @i{expression} ::=  @i{expression} or else @i{expression}
13562 @i{expression} ::=  ( @i{expression} )
13563 @end smallexample
13564
13565 @noindent
13566 For the first test (@i{expression} ::= <symbol>) the symbol must have
13567 either the value true or false, that is to say the right-hand of the
13568 symbol definition must be one of the (case-insensitive) literals
13569 @code{True} or @code{False}. If the value is true, then the
13570 corresponding lines are included, and if the value is false, they are
13571 excluded.
13572
13573 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
13574 the symbol has been defined in the definition file or by a @code{-D}
13575 switch on the command line. Otherwise, the test is false.
13576
13577 The equality tests are case insensitive, as are all the preprocessor lines.
13578
13579 If the symbol referenced is not defined in the symbol definitions file,
13580 then the effect depends on whether or not switch @code{-u}
13581 is specified. If so, then the symbol is treated as if it had the value
13582 false and the test fails. If this switch is not specified, then
13583 it is an error to reference an undefined symbol. It is also an error to
13584 reference a symbol that is defined with a value other than @code{True}
13585 or @code{False}.
13586
13587 The use of the @code{not} operator inverts the sense of this logical test, so
13588 that the lines are included only if the symbol is not defined.
13589 The @code{then} keyword is optional as shown
13590
13591 The @code{#} must be the first non-blank character on a line, but
13592 otherwise the format is free form. Spaces or tabs may appear between
13593 the @code{#} and the keyword. The keywords and the symbols are case
13594 insensitive as in normal Ada code. Comments may be used on a
13595 preprocessor line, but other than that, no other tokens may appear on a
13596 preprocessor line. Any number of @code{elsif} clauses can be present,
13597 including none at all. The @code{else} is optional, as in Ada.
13598
13599 The @code{#} marking the start of a preprocessor line must be the first
13600 non-blank character on the line, i.e. it must be preceded only by
13601 spaces or horizontal tabs.
13602
13603 Symbol substitution outside of preprocessor lines is obtained by using
13604 the sequence
13605
13606 @smallexample
13607 $symbol
13608 @end smallexample
13609
13610 @noindent
13611 anywhere within a source line, except in a comment or within a
13612 string literal. The identifier
13613 following the @code{$} must match one of the symbols defined in the symbol
13614 definition file, and the result is to substitute the value of the
13615 symbol in place of @code{$symbol} in the output file.
13616
13617 Note that although the substitution of strings within a string literal
13618 is not possible, it is possible to have a symbol whose defined value is
13619 a string literal. So instead of setting XYZ to @code{hello} and writing:
13620
13621 @smallexample
13622 Header : String := "$XYZ";
13623 @end smallexample
13624
13625 @noindent
13626 you should set XYZ to @code{"hello"} and write:
13627
13628 @smallexample
13629 Header : String := $XYZ;
13630 @end smallexample
13631
13632 @noindent
13633 and then the substitution will occur as desired.
13634
13635
13636 @node The GNAT Library Browser gnatls
13637 @chapter The GNAT Library Browser @code{gnatls}
13638 @findex gnatls
13639 @cindex Library browser
13640
13641 @noindent
13642 @code{gnatls} is a tool that outputs information about compiled
13643 units. It gives the relationship between objects, unit names and source
13644 files. It can also be used to check the source dependencies of a unit
13645 as well as various characteristics.
13646
13647 @menu
13648 * Running gnatls::
13649 * Switches for gnatls::
13650 * Examples of gnatls Usage::
13651 @end menu
13652
13653 @node Running gnatls
13654 @section Running @code{gnatls}
13655
13656 @noindent
13657 The @code{gnatls} command has the form
13658
13659 @smallexample
13660 $ gnatls switches @var{object_or_ali_file}
13661 @end smallexample
13662
13663 @noindent
13664 The main argument is the list of object or @file{ali} files
13665 (@pxref{The Ada Library Information Files})
13666 for which information is requested.
13667
13668 In normal mode, without additional option, @code{gnatls} produces a
13669 four-column listing. Each line represents information for a specific
13670 object. The first column gives the full path of the object, the second
13671 column gives the name of the principal unit in this object, the third
13672 column gives the status of the source and the fourth column gives the
13673 full path of the source representing this unit.
13674 Here is a simple example of use:
13675
13676 @smallexample
13677 $ gnatls *.o
13678 ./demo1.o            demo1            DIF demo1.adb
13679 ./demo2.o            demo2             OK demo2.adb
13680 ./hello.o            h1                OK hello.adb
13681 ./instr-child.o      instr.child      MOK instr-child.adb
13682 ./instr.o            instr             OK instr.adb
13683 ./tef.o              tef              DIF tef.adb
13684 ./text_io_example.o  text_io_example   OK text_io_example.adb
13685 ./tgef.o             tgef             DIF tgef.adb
13686 @end smallexample
13687
13688 @noindent
13689 The first line can be interpreted as follows: the main unit which is
13690 contained in
13691 object file @file{demo1.o} is demo1, whose main source is in
13692 @file{demo1.adb}. Furthermore, the version of the source used for the
13693 compilation of demo1 has been modified (DIF). Each source file has a status
13694 qualifier which can be:
13695
13696 @table @code
13697 @item OK (unchanged)
13698 The version of the source file used for the compilation of the
13699 specified unit corresponds exactly to the actual source file.
13700
13701 @item MOK (slightly modified)
13702 The version of the source file used for the compilation of the
13703 specified unit differs from the actual source file but not enough to
13704 require recompilation. If you use gnatmake with the qualifier
13705 @code{-m (minimal recompilation)}, a file marked
13706 MOK will not be recompiled.
13707
13708 @item DIF (modified)
13709 No version of the source found on the path corresponds to the source
13710 used to build this object.
13711
13712 @item ??? (file not found)
13713 No source file was found for this unit.
13714
13715 @item HID (hidden,  unchanged version not first on PATH)
13716 The version of the source that corresponds exactly to the source used
13717 for compilation has been found on the path but it is hidden by another
13718 version of the same source that has been modified.
13719
13720 @end table
13721
13722 @node Switches for gnatls
13723 @section Switches for @code{gnatls}
13724
13725 @noindent
13726 @code{gnatls} recognizes the following switches:
13727
13728 @table @code
13729 @item -a
13730 @cindex @code{-a} (@code{gnatls})
13731 Consider all units, including those of the predefined Ada library.
13732 Especially useful with @code{-d}.
13733
13734 @item -d
13735 @cindex @code{-d} (@code{gnatls})
13736 List sources from which specified units depend on.
13737
13738 @item -h
13739 @cindex @code{-h} (@code{gnatls})
13740 Output the list of options.
13741
13742 @item -o
13743 @cindex @code{-o} (@code{gnatls})
13744 Only output information about object files.
13745
13746 @item -s
13747 @cindex @code{-s} (@code{gnatls})
13748 Only output information about source files.
13749
13750 @item -u
13751 @cindex @code{-u} (@code{gnatls})
13752 Only output information about compilation units.
13753
13754 @item -aO@var{dir}
13755 @itemx -aI@var{dir}
13756 @itemx -I@var{dir}
13757 @itemx  -I-
13758 @itemx -nostdinc
13759 Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags
13760 (see @ref{Switches for gnatmake}).
13761
13762 @item --RTS=@var{rts-path}
13763 @cindex @code{--RTS} (@code{gnatls})
13764 Specifies the default location of the runtime library. Same meaning as the
13765 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13766
13767 @item -v
13768 @cindex @code{-s} (@code{gnatls})
13769 Verbose mode. Output the complete source and object paths. Do not use
13770 the default column layout but instead use long format giving as much as
13771 information possible on each requested units, including special
13772 characteristics such as:
13773
13774 @table @code
13775 @item  Preelaborable
13776 The unit is preelaborable in the Ada 95 sense.
13777
13778 @item No_Elab_Code
13779 No elaboration code has been produced by the compiler for this unit.
13780
13781 @item Pure
13782 The unit is pure in the Ada 95 sense.
13783
13784 @item Elaborate_Body
13785 The unit contains a pragma Elaborate_Body.
13786
13787 @item Remote_Types
13788 The unit contains a pragma Remote_Types.
13789
13790 @item Shared_Passive
13791 The unit contains a pragma Shared_Passive.
13792
13793 @item Predefined
13794 This unit is part of the predefined environment and cannot be modified
13795 by the user.
13796
13797 @item Remote_Call_Interface
13798 The unit contains a pragma Remote_Call_Interface.
13799
13800 @end table
13801
13802 @end table
13803
13804 @node Examples of gnatls Usage
13805 @section Example of @code{gnatls} Usage
13806
13807 @noindent
13808 Example of using the verbose switch. Note how the source and
13809 object paths are affected by the -I switch.
13810
13811 @smallexample
13812 $ gnatls -v -I.. demo1.o
13813
13814 GNATLS 3.10w (970212) Copyright 1999 Free Software Foundation, Inc.
13815
13816 Source Search Path:
13817    <Current_Directory>
13818    ../
13819    /home/comar/local/adainclude/
13820
13821 Object Search Path:
13822    <Current_Directory>
13823    ../
13824    /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/
13825
13826 ./demo1.o
13827    Unit =>
13828      Name   => demo1
13829      Kind   => subprogram body
13830      Flags  => No_Elab_Code
13831      Source => demo1.adb    modified
13832 @end smallexample
13833
13834 @noindent
13835 The following is an example of use of the dependency list.
13836 Note the use of the -s switch
13837 which gives a straight list of source files. This can be useful for
13838 building specialized scripts.
13839
13840 @smallexample
13841 $ gnatls -d demo2.o
13842 ./demo2.o   demo2        OK demo2.adb
13843                          OK gen_list.ads
13844                          OK gen_list.adb
13845                          OK instr.ads
13846                          OK instr-child.ads
13847
13848 $ gnatls -d -s -a demo1.o
13849 demo1.adb
13850 /home/comar/local/adainclude/ada.ads
13851 /home/comar/local/adainclude/a-finali.ads
13852 /home/comar/local/adainclude/a-filico.ads
13853 /home/comar/local/adainclude/a-stream.ads
13854 /home/comar/local/adainclude/a-tags.ads
13855 gen_list.ads
13856 gen_list.adb
13857 /home/comar/local/adainclude/gnat.ads
13858 /home/comar/local/adainclude/g-io.ads
13859 instr.ads
13860 /home/comar/local/adainclude/system.ads
13861 /home/comar/local/adainclude/s-exctab.ads
13862 /home/comar/local/adainclude/s-finimp.ads
13863 /home/comar/local/adainclude/s-finroo.ads
13864 /home/comar/local/adainclude/s-secsta.ads
13865 /home/comar/local/adainclude/s-stalib.ads
13866 /home/comar/local/adainclude/s-stoele.ads
13867 /home/comar/local/adainclude/s-stratt.ads
13868 /home/comar/local/adainclude/s-tasoli.ads
13869 /home/comar/local/adainclude/s-unstyp.ads
13870 /home/comar/local/adainclude/unchconv.ads
13871 @end smallexample
13872
13873
13874 @node GNAT and Libraries
13875 @chapter GNAT and Libraries
13876 @cindex Library, building, installing
13877
13878 @noindent
13879 This chapter addresses some of the issues related to building and using
13880 a library with GNAT. It also shows how the GNAT run-time library can be
13881 recompiled.
13882
13883 @menu
13884 * Creating an Ada Library::
13885 * Installing an Ada Library::
13886 * Using an Ada Library::
13887 * Creating an Ada Library to be Used in a Non-Ada Context::
13888 * Rebuilding the GNAT Run-Time Library::
13889 @end menu
13890
13891 @node Creating an Ada Library
13892 @section Creating an Ada Library
13893
13894 @noindent
13895 In the GNAT environment, a library has two components:
13896 @itemize @bullet
13897 @item
13898 Source files.
13899 @item
13900 Compiled code and Ali files. See @ref{The Ada Library Information Files}.
13901 @end itemize
13902
13903 @noindent
13904 In order to use other packages @ref{The GNAT Compilation Model}
13905 requires a certain number of sources to be available to the compiler.
13906 The minimal set of
13907 sources required includes the specs of all the packages that make up the
13908 visible part of the library as well as all the sources upon which they
13909 depend. The bodies of all visible generic units must also be provided.
13910 @noindent
13911 Although it is not strictly mandatory, it is recommended that all sources
13912 needed to recompile the library be provided, so that the user can make
13913 full use of inter-unit inlining and source-level debugging. This can also
13914 make the situation easier for users that need to upgrade their compilation
13915 toolchain and thus need to recompile the library from sources.
13916
13917 @noindent
13918 The compiled code can be provided in different ways. The simplest way is
13919 to provide directly the set of objects produced by the compiler during
13920 the compilation of the library. It is also possible to group the objects
13921 into an archive using whatever commands are provided by the operating
13922 system. Finally, it is also possible to create a shared library (see
13923 option -shared in the GCC manual).
13924
13925 @noindent
13926 There are various possibilities for compiling the units that make up the
13927 library: for example with a Makefile @ref{Using the GNU make Utility},
13928 or with a conventional script.
13929 For simple libraries, it is also possible to create a
13930 dummy main program which depends upon all the packages that comprise the
13931 interface of the library. This dummy main program can then be given to
13932 gnatmake, in order to build all the necessary objects. Here is an example
13933 of such a dummy program and the generic commands used to build an
13934 archive or a shared library.
13935
13936 @smallexample
13937 @iftex
13938 @leftskip=.7cm
13939 @end iftex
13940 @b{with} My_Lib.Service1;
13941 @b{with} My_Lib.Service2;
13942 @b{with} My_Lib.Service3;
13943 @b{procedure} My_Lib_Dummy @b{is}
13944 @b{begin}
13945    @b{null};
13946 @b{end};
13947
13948 # compiling the library
13949 $ gnatmake -c my_lib_dummy.adb
13950
13951 # we don't need the dummy object itself
13952 $ rm my_lib_dummy.o my_lib_dummy.ali
13953
13954 # create an archive with the remaining objects
13955 $ ar rc libmy_lib.a *.o
13956 # some systems may require "ranlib" to be run as well
13957
13958 # or create a shared library
13959 $ gcc -shared -o libmy_lib.so *.o
13960 # some systems may require the code to have been compiled with -fPIC
13961 @end smallexample
13962
13963 @noindent
13964 When the objects are grouped in an archive or a shared library, the user
13965 needs to specify the desired library at link time, unless a pragma
13966 linker_options has been used in one of the sources:
13967 @smallexample
13968 @b{pragma} Linker_Options ("-lmy_lib");
13969 @end smallexample
13970
13971 @node Installing an Ada Library
13972 @section Installing an Ada Library
13973
13974 @noindent
13975 In the GNAT model, installing a library consists in copying into a specific
13976 location the files that make up this library. It is possible to install
13977 the sources in a different directory from the other files (ALI, objects,
13978 archives) since the source path and the object path can easily be
13979 specified separately.
13980
13981 @noindent
13982 For general purpose libraries, it is possible for the system
13983 administrator to put those libraries in the default compiler paths. To
13984 achieve this, he must specify their location in the configuration files
13985 "ada_source_path" and "ada_object_path" that must be located in the GNAT
13986 installation tree at the same place as the gcc spec file. The location of
13987 the gcc spec file can be determined as follows:
13988 @smallexample
13989 $ gcc -v
13990 @end smallexample
13991
13992 @noindent
13993 The configuration files mentioned above have simple format: each line in them
13994 must contain one unique
13995 directory name. Those names are added to the corresponding path
13996 in their order of appearance in the file. The names can be either absolute
13997 or relative, in the latter case, they are relative to where theses files
13998 are located.
13999
14000 @noindent
14001 "ada_source_path" and "ada_object_path" might actually not be present in a
14002 GNAT installation, in which case, GNAT will look for its run-time library in
14003 the directories "adainclude" for the sources and "adalib" for the
14004 objects and ALI files. When the files exist, the compiler does not
14005 look in "adainclude" and "adalib" at all, and thus the "ada_source_path" file
14006 must contain the location for the GNAT run-time sources (which can simply
14007 be "adainclude"). In the same way, the "ada_object_path" file must contain
14008 the location for the GNAT run-time objects (which can simply
14009 be "adalib").
14010
14011 @noindent
14012 You can also specify a new default path to the runtime library at compilation
14013 time with the switch "--RTS=@var{rts-path}". You can easily choose and change
14014 the runtime you want your program to be compiled with. This switch is
14015 recognized by gcc, gnatmake, gnatbind, gnatls, gnatfind and gnatxref.
14016
14017 @noindent
14018 It is possible to install a library before or after the standard GNAT
14019 library, by reordering the lines in the configuration files. In general, a
14020 library must be installed before the GNAT library if it redefines any part of it.
14021
14022 @node Using an Ada Library
14023 @section Using an Ada Library
14024
14025 @noindent
14026 In order to use a Ada library, you need to make sure that this
14027 library is on both your source and object path
14028 @ref{Search Paths and the Run-Time Library (RTL)}
14029 and @ref{Search Paths for gnatbind}. For
14030 instance, you can use the library "mylib" installed in "/dir/my_lib_src"
14031 and "/dir/my_lib_obj" with the following commands:
14032
14033 @smallexample
14034 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
14035   -largs -lmy_lib
14036 @end smallexample
14037
14038 @noindent
14039 This can be simplified down to the following:
14040 @smallexample
14041 $ gnatmake my_appl
14042 @end smallexample
14043 when the following conditions are met:
14044 @itemize @bullet
14045 @item
14046 "/dir/my_lib_src" has been added by the user to the environment
14047 variable "ADA_INCLUDE_PATH", or by the administrator to the file
14048 "ada_source_path"
14049 @item
14050 "/dir/my_lib_obj" has been added by the user to the environment
14051 variable "ADA_OBJECTS_PATH", or by the administrator to the file
14052 "ada_object_path"
14053 @item
14054 a pragma linker_options, as mentioned in @ref{Creating an Ada Library}
14055 as been added to the sources.
14056 @end itemize
14057 @noindent
14058
14059 @node Creating an Ada Library to be Used in a Non-Ada Context
14060 @section Creating an Ada Library to be Used in a Non-Ada Context
14061
14062 @noindent
14063 The previous sections detailed how to create and install a library that
14064 was usable from an Ada main program. Using this library in a non-Ada
14065 context is not possible, because the elaboration of the library is
14066 automatically done as part of the main program elaboration.
14067
14068 GNAT also provides the ability to build libraries that can be used both
14069 in an Ada and non-Ada context.  This section describes how to build such
14070 a library, and then how to use it from a C program. The method for
14071 interfacing with the library from other languages such as Fortran for
14072 instance remains the same.
14073
14074 @subsection Creating the Library
14075
14076 @itemize @bullet
14077 @item Identify the units representing the interface of the library.
14078
14079 Here is an example of simple library interface:
14080
14081 @smallexample
14082 package Interface is
14083
14084    procedure Do_Something;
14085
14086    procedure Do_Something_Else;
14087
14088 end Interface;
14089 @end smallexample
14090
14091 @item Use @code{pragma Export} or @code{pragma Convention} for the
14092 exported entities.
14093
14094 Our package @code{Interface} is then updated as follow:
14095 @smallexample
14096 package Interface is
14097
14098    procedure Do_Something;
14099    pragma Export (C, Do_Something, "do_something");
14100
14101    procedure Do_Something_Else;
14102    pragma Export (C, Do_Something_Else, "do_something_else");
14103
14104 end Interface;
14105 @end smallexample
14106
14107 @item Compile all the units composing the library.
14108
14109 @item Bind the library objects.
14110
14111 This step is performed by invoking gnatbind with the @code{-L<prefix>}
14112 switch. @code{gnatbind} will then generate the library elaboration
14113 procedure (named @code{<prefix>init}) and the run-time finalization
14114 procedure (named @code{<prefix>final}).
14115
14116 @smallexample
14117 # generate the binder file in Ada
14118 $ gnatbind -Lmylib interface
14119
14120 # generate the binder file in C
14121 $ gnatbind -C -Lmylib interface
14122 @end smallexample
14123
14124 @item Compile the files generated by the binder
14125
14126 @smallexample
14127 $ gcc -c b~interface.adb
14128 @end smallexample
14129
14130 @item Create the library;
14131
14132 The procedure is identical to the procedure explained in
14133 @ref{Creating an Ada Library},
14134 except that @file{b~interface.o} needs to be added to
14135 the list of objects.
14136
14137 @smallexample
14138 # create an archive file
14139 $ ar cr libmylib.a b~interface.o <other object files>
14140
14141 # create a shared library
14142 $ gcc -shared -o libmylib.so b~interface.o <other object files>
14143 @end smallexample
14144
14145 @item Provide a "foreign" view of the library interface;
14146
14147 The example below shows the content of @code{mylib_interface.h} (note
14148 that there is no rule for the naming of this file, any name can be used)
14149 @smallexample
14150 /* the library elaboration procedure */
14151 extern void mylibinit (void);
14152
14153 /* the library finalization procedure */
14154 extern void mylibfinal (void);
14155
14156 /* the interface exported by the library */
14157 extern void do_something (void);
14158 extern void do_something_else (void);
14159 @end smallexample
14160 @end itemize
14161
14162 @subsection Using the Library
14163
14164 @noindent
14165 Libraries built as explained above can be used from any program, provided
14166 that the elaboration procedures (named @code{mylibinit} in the previous
14167 example) are called before the library services are used. Any number of
14168 libraries can be used simultaneously, as long as the elaboration
14169 procedure of each library is called.
14170
14171 Below is an example of C program that uses our @code{mylib} library.
14172
14173 @smallexample
14174 #include "mylib_interface.h"
14175
14176 int
14177 main (void)
14178 @{
14179    /* First, elaborate the library before using it */
14180    mylibinit ();
14181
14182    /* Main program, using the library exported entities */
14183    do_something ();
14184    do_something_else ();
14185
14186    /* Library finalization at the end of the program */
14187    mylibfinal ();
14188    return 0;
14189 @}
14190 @end smallexample
14191
14192 @noindent
14193 Note that this same library can be used from an equivalent Ada main
14194 program. In addition, if the libraries are installed as detailed in
14195 @ref{Installing an Ada Library}, it is not necessary to invoke the
14196 library elaboration and finalization routines. The binder will ensure
14197 that this is done as part of the main program elaboration and
14198 finalization phases.
14199
14200 @subsection The Finalization Phase
14201
14202 @noindent
14203 Invoking any library finalization procedure generated by @code{gnatbind}
14204 shuts down the Ada run time permanently. Consequently, the finalization
14205 of all Ada libraries must be performed at the end of the program. No
14206 call to these libraries nor the Ada run time should be made past the
14207 finalization phase.
14208
14209 @subsection Restrictions in Libraries
14210
14211 @noindent
14212 The pragmas listed below should be used with caution inside libraries,
14213 as they can create incompatibilities with other Ada libraries:
14214 @itemize @bullet
14215 @item pragma @code{Locking_Policy}
14216 @item pragma @code{Queuing_Policy}
14217 @item pragma @code{Task_Dispatching_Policy}
14218 @item pragma @code{Unreserve_All_Interrupts}
14219 @end itemize
14220 When using a library that contains such pragmas, the user must make sure
14221 that all libraries use the same pragmas with the same values. Otherwise,
14222 a @code{Program_Error} will
14223 be raised during the elaboration of the conflicting
14224 libraries. The usage of these pragmas and its consequences for the user
14225 should therefore be well documented.
14226
14227 Similarly, the traceback in exception occurrences mechanism should be
14228 enabled or disabled in a consistent manner across all libraries.
14229 Otherwise, a Program_Error will be raised during the elaboration of the
14230 conflicting libraries.
14231
14232 If the @code{'Version} and @code{'Body_Version}
14233 attributes are used inside a library, then it is necessary to
14234 perform a @code{gnatbind} step that mentions all ali files in all
14235 libraries, so that version identifiers can be properly computed.
14236 In practice these attributes are rarely used, so this is unlikely
14237 to be a consideration.
14238
14239 @node  Rebuilding the GNAT Run-Time Library
14240 @section Rebuilding the GNAT Run-Time Library
14241
14242 @noindent
14243 It may be useful to recompile the GNAT library in various contexts, the
14244 most important one being the use of partition-wide configuration pragmas
14245 such as Normalize_Scalar. A special Makefile called
14246 @code{Makefile.adalib} is provided to that effect and can be found in
14247 the directory containing the GNAT library. The location of this
14248 directory depends on the way the GNAT environment has been installed and can
14249 be determined by means of the command:
14250
14251 @smallexample
14252 $ gnatls -v
14253 @end smallexample
14254
14255 @noindent
14256 The last entry in the object search path usually contains the
14257 gnat library. This Makefile contains its own documentation and in
14258 particular the set of instructions needed to rebuild a new library and
14259 to use it.
14260
14261 @node Using the GNU make Utility
14262 @chapter Using the GNU @code{make} Utility
14263 @findex make
14264
14265 @noindent
14266 This chapter offers some examples of makefiles that solve specific
14267 problems. It does not explain how to write a makefile (see the GNU make
14268 documentation), nor does it try to replace the @code{gnatmake} utility
14269 (@pxref{The GNAT Make Program gnatmake}).
14270
14271 All the examples in this section are specific to the GNU version of
14272 make. Although @code{make} is a standard utility, and the basic language
14273 is the same, these examples use some advanced features found only in
14274 @code{GNU make}.
14275
14276 @menu
14277 * Using gnatmake in a Makefile::
14278 * Automatically Creating a List of Directories::
14279 * Generating the Command Line Switches::
14280 * Overcoming Command Line Length Limits::
14281 @end menu
14282
14283 @node Using gnatmake in a Makefile
14284 @section Using gnatmake in a Makefile
14285 @findex makefile
14286 @cindex GNU make
14287
14288 @noindent
14289 Complex project organizations can be handled in a very powerful way by
14290 using GNU make combined with gnatmake. For instance, here is a Makefile
14291 which allows you to build each subsystem of a big project into a separate
14292 shared library. Such a makefile allows you to significantly reduce the link
14293 time of very big applications while maintaining full coherence at
14294 each step of the build process.
14295
14296 The list of dependencies are handled automatically by
14297 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
14298 the appropriate directories.
14299
14300 Note that you should also read the example on how to automatically
14301 create the list of directories (@pxref{Automatically Creating a List of Directories})
14302 which might help you in case your project has a lot of
14303 subdirectories.
14304
14305 @smallexample
14306 @iftex
14307 @leftskip=0cm
14308 @font@heightrm=cmr8
14309 @heightrm
14310 @end iftex
14311 ## This Makefile is intended to be used with the following directory
14312 ## configuration:
14313 ##  - The sources are split into a series of csc (computer software components)
14314 ##    Each of these csc is put in its own directory.
14315 ##    Their name are referenced by the directory names.
14316 ##    They will be compiled into shared library (although this would also work
14317 ##    with static libraries
14318 ##  - The main program (and possibly other packages that do not belong to any
14319 ##    csc is put in the top level directory (where the Makefile is).
14320 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
14321 ##                    \_ second_csc (sources) __ lib (will contain the library)
14322 ##                    \_ ...
14323 ## Although this Makefile is build for shared library, it is easy to modify
14324 ## to build partial link objects instead (modify the lines with -shared and
14325 ## gnatlink below)
14326 ##
14327 ## With this makefile, you can change any file in the system or add any new
14328 ## file, and everything will be recompiled correctly (only the relevant shared
14329 ## objects will be recompiled, and the main program will be re-linked).
14330
14331 # The list of computer software component for your project. This might be
14332 # generated automatically.
14333 CSC_LIST=aa bb cc
14334
14335 # Name of the main program (no extension)
14336 MAIN=main
14337
14338 # If we need to build objects with -fPIC, uncomment the following line
14339 #NEED_FPIC=-fPIC
14340
14341 # The following variable should give the directory containing libgnat.so
14342 # You can get this directory through 'gnatls -v'. This is usually the last
14343 # directory in the Object_Path.
14344 GLIB=...
14345
14346 # The directories for the libraries
14347 # (This macro expands the list of CSC to the list of shared libraries, you
14348 # could simply use the expanded form :
14349 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
14350 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
14351
14352 $@{MAIN@}: objects $@{LIB_DIR@}
14353     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
14354     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
14355
14356 objects::
14357     # recompile the sources
14358     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
14359
14360 # Note: In a future version of GNAT, the following commands will be simplified
14361 # by a new tool, gnatmlib
14362 $@{LIB_DIR@}:
14363     mkdir -p $@{dir $@@ @}
14364     cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
14365     cd $@{dir $@@ @}; cp -f ../*.ali .
14366
14367 # The dependencies for the modules
14368 # Note that we have to force the expansion of *.o, since in some cases make won't
14369 # be able to do it itself.
14370 aa/lib/libaa.so: $@{wildcard aa/*.o@}
14371 bb/lib/libbb.so: $@{wildcard bb/*.o@}
14372 cc/lib/libcc.so: $@{wildcard cc/*.o@}
14373
14374 # Make sure all of the shared libraries are in the path before starting the
14375 # program
14376 run::
14377     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
14378
14379 clean::
14380     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
14381     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
14382     $@{RM@} $@{CSC_LIST:%=%/*.o@}
14383     $@{RM@} *.o *.ali $@{MAIN@}
14384 @end smallexample
14385
14386 @node Automatically Creating a List of Directories
14387 @section Automatically Creating a List of Directories
14388
14389 @noindent
14390 In most makefiles, you will have to specify a list of directories, and
14391 store it in a variable. For small projects, it is often easier to
14392 specify each of them by hand, since you then have full control over what
14393 is the proper order for these directories, which ones should be
14394 included...
14395
14396 However, in larger projects, which might involve hundreds of
14397 subdirectories, it might be more convenient to generate this list
14398 automatically.
14399
14400 The example below presents two methods. The first one, although less
14401 general, gives you more control over the list. It involves wildcard
14402 characters, that are automatically expanded by @code{make}. Its
14403 shortcoming is that you need to explicitly specify some of the
14404 organization of your project, such as for instance the directory tree
14405 depth, whether some directories are found in a separate tree,...
14406
14407 The second method is the most general one. It requires an external
14408 program, called @code{find}, which is standard on all Unix systems. All
14409 the directories found under a given root directory will be added to the
14410 list.
14411
14412 @smallexample
14413 @iftex
14414 @leftskip=0cm
14415 @font@heightrm=cmr8
14416 @heightrm
14417 @end iftex
14418 # The examples below are based on the following directory hierarchy:
14419 # All the directories can contain any number of files
14420 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
14421 #                       ->  ab
14422 #                       ->  ac
14423 #                ->  b  ->  ba  ->  baa
14424 #                       ->  bb
14425 #                       ->  bc
14426 # This Makefile creates a variable called DIRS, that can be reused any time
14427 # you need this list (see the other examples in this section)
14428
14429 # The root of your project's directory hierarchy
14430 ROOT_DIRECTORY=.
14431
14432 ####
14433 # First method: specify explicitly the list of directories
14434 # This allows you to specify any subset of all the directories you need.
14435 ####
14436
14437 DIRS := a/aa/ a/ab/ b/ba/
14438
14439 ####
14440 # Second method: use wildcards
14441 # Note that the argument(s) to wildcard below should end with a '/'.
14442 # Since wildcards also return file names, we have to filter them out
14443 # to avoid duplicate directory names.
14444 # We thus use make's @code{dir} and @code{sort} functions.
14445 # It sets DIRs to the following value (note that the directories aaa and baa
14446 # are not given, unless you change the arguments to wildcard).
14447 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
14448 ####
14449
14450 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/ $@{ROOT_DIRECTORY@}/*/*/@}@}@}
14451
14452 ####
14453 # Third method: use an external program
14454 # This command is much faster if run on local disks, avoiding NFS slowdowns.
14455 # This is the most complete command: it sets DIRs to the following value:
14456 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
14457 ####
14458
14459 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
14460
14461 @end smallexample
14462
14463 @node Generating the Command Line Switches
14464 @section Generating the Command Line Switches
14465
14466 @noindent
14467 Once you have created the list of directories as explained in the
14468 previous section (@pxref{Automatically Creating a List of Directories}),
14469 you can easily generate the command line arguments to pass to gnatmake.
14470
14471 For the sake of completeness, this example assumes that the source path
14472 is not the same as the object path, and that you have two separate lists
14473 of directories.
14474
14475 @smallexample
14476 # see "Automatically creating a list of directories" to create
14477 # these variables
14478 SOURCE_DIRS=
14479 OBJECT_DIRS=
14480
14481 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
14482 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
14483
14484 all:
14485         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
14486 @end smallexample
14487
14488 @node Overcoming Command Line Length Limits
14489 @section Overcoming Command Line Length Limits
14490
14491 @noindent
14492 One problem that might be encountered on big projects is that many
14493 operating systems limit the length of the command line. It is thus hard to give
14494 gnatmake the list of source and object directories.
14495
14496 This example shows how you can set up environment variables, which will
14497 make @code{gnatmake} behave exactly as if the directories had been
14498 specified on the command line, but have a much higher length limit (or
14499 even none on most systems).
14500
14501 It assumes that you have created a list of directories in your Makefile,
14502 using one of the methods presented in
14503 @ref{Automatically Creating a List of Directories}.
14504 For the sake of completeness, we assume that the object
14505 path (where the ALI files are found) is different from the sources patch.
14506
14507 Note a small trick in the Makefile below: for efficiency reasons, we
14508 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
14509 expanded immediately by @code{make}. This way we overcome the standard
14510 make behavior which is to expand the variables only when they are
14511 actually used.
14512
14513 @smallexample
14514 @iftex
14515 @leftskip=0cm
14516 @font@heightrm=cmr8
14517 @heightrm
14518 @end iftex
14519 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
14520 # This is the same thing as putting the -I arguments on the command line.
14521 # (the equivalent of using -aI on the command line would be to define
14522 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
14523 # You can of course have different values for these variables.
14524 #
14525 # Note also that we need to keep the previous values of these variables, since
14526 # they might have been set before running 'make' to specify where the GNAT
14527 # library is installed.
14528
14529 # see "Automatically creating a list of directories" to create these
14530 # variables
14531 SOURCE_DIRS=
14532 OBJECT_DIRS=
14533
14534 empty:=
14535 space:=$@{empty@} $@{empty@}
14536 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
14537 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
14538 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
14539 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
14540 export ADA_INCLUDE_PATH
14541 export ADA_OBJECT_PATH
14542
14543 all:
14544         gnatmake main_unit
14545 @end smallexample
14546
14547 @node Finding Memory Problems with gnatmem
14548 @chapter Finding Memory Problems with @code{gnatmem}
14549 @findex gnatmem
14550
14551 @noindent
14552 @code{gnatmem}, is a tool that monitors dynamic allocation and
14553 deallocation activity in a program, and displays information about
14554 incorrect deallocations and possible sources of memory leaks. Gnatmem
14555 provides three type of information:
14556 @itemize @bullet
14557 @item
14558 General information concerning memory management, such as the total
14559 number of allocations and deallocations, the amount of allocated
14560 memory and the high water mark, i.e. the largest amount of allocated
14561 memory in the course of program execution.
14562
14563 @item
14564 Backtraces for all incorrect deallocations, that is to say deallocations
14565 which do not correspond to a valid allocation.
14566
14567 @item
14568 Information on each allocation that is potentially the origin of a memory
14569 leak.
14570 @end itemize
14571
14572 The @code{gnatmem} command has two modes. It can be used with @code{gdb}
14573 or with instrumented allocation and deallocation routines. The later
14574 mode is called the @code{GMEM} mode. Both modes produce the very same
14575 output.
14576
14577 @menu
14578 * Running gnatmem (GDB Mode)::
14579 * Running gnatmem (GMEM Mode)::
14580 * Switches for gnatmem::
14581 * Examples of gnatmem Usage::
14582 * GDB and GMEM Modes::
14583 * Implementation Note::
14584 @end menu
14585
14586 @node Running gnatmem (GDB Mode)
14587 @section Running @code{gnatmem} (GDB Mode)
14588
14589 @noindent
14590 The @code{gnatmem} command has the form
14591
14592 @smallexample
14593    $ gnatmem [-q] [n] [-o file] user_program [program_arg]*
14594 or
14595    $ gnatmem [-q] [n] -i file
14596 @end smallexample
14597
14598 @noindent
14599 Gnatmem must be supplied with the executable to examine, followed by its
14600 run-time inputs. For example, if a program is executed with the command:
14601 @smallexample
14602 $ my_program arg1 arg2
14603 @end smallexample
14604 then it can be run under @code{gnatmem} control using the command:
14605 @smallexample
14606 $ gnatmem my_program arg1 arg2
14607 @end smallexample
14608
14609 The program is transparently executed under the control of the debugger
14610 @ref{The GNAT Debugger GDB}. This does not affect the behavior
14611 of the program, except for sensitive real-time programs. When the program
14612 has completed execution, @code{gnatmem} outputs a report containing general
14613 allocation/deallocation information and potential memory leak.
14614 For better results, the user program should be compiled with
14615 debugging options @ref{Switches for gcc}.
14616
14617 Here is a simple example of use:
14618
14619 *************** debut cc
14620 @smallexample
14621 $ gnatmem test_gm
14622
14623 Global information
14624 ------------------
14625    Total number of allocations        :  45
14626    Total number of deallocations      :   6
14627    Final Water Mark (non freed mem)   :  11.29 Kilobytes
14628    High Water Mark                    :  11.40 Kilobytes
14629
14630 .
14631 .
14632 .
14633 Allocation Root # 2
14634 -------------------
14635  Number of non freed allocations    :  11
14636  Final Water Mark (non freed mem)   :   1.16 Kilobytes
14637  High Water Mark                    :   1.27 Kilobytes
14638  Backtrace                          :
14639    test_gm.adb:23 test_gm.alloc
14640 .
14641 .
14642 .
14643 @end smallexample
14644
14645 The first block of output give general information. In this case, the
14646 Ada construct "@b{new}" was executed 45 times, and only 6 calls to an
14647 unchecked deallocation routine occurred.
14648
14649 Subsequent paragraphs display  information on all allocation roots.
14650 An allocation root is a specific point in the execution of the program
14651 that generates some dynamic allocation, such as a "@b{new}" construct. This
14652 root is represented by an execution backtrace (or subprogram call
14653 stack). By default the backtrace depth for allocations roots is 1, so
14654 that a root corresponds exactly to a source location. The backtrace can
14655 be made deeper, to make the root more specific.
14656
14657 @node Running gnatmem (GMEM Mode)
14658 @section Running @code{gnatmem} (GMEM Mode)
14659 @cindex @code{GMEM} (@code{gnatmem})
14660
14661 @noindent
14662 The @code{gnatmem} command has the form
14663
14664 @smallexample
14665    $ gnatmem [-q] [n] -i gmem.out user_program [program_arg]*
14666 @end smallexample
14667
14668 The program must have been linked with the instrumented version of the
14669 allocation and deallocation routines. This is done with linking with the
14670 @file{libgmem.a} library. For better results, the user program should be
14671 compiled with debugging options @ref{Switches for gcc}. For example to
14672 build @file{my_program}:
14673
14674 @smallexample
14675 $ gnatmake -g my_program -largs -lgmem
14676 @end smallexample
14677
14678 @noindent
14679 When running @file{my_program} the file @file{gmem.out} is produced. This file
14680 contains information about all allocations and deallocations done by the
14681 program. It is produced by the instrumented allocations and
14682 deallocations routines and will be used by @code{gnatmem}.
14683
14684 @noindent
14685 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
14686 examine followed by its run-time inputs. For example, if a program is
14687 executed with the command:
14688 @smallexample
14689 $ my_program arg1 arg2
14690 @end smallexample
14691 then @file{gmem.out} can be analysed by @code{gnatmem} using the command:
14692 @smallexample
14693 $ gnatmem -i gmem.out my_program arg1 arg2
14694 @end smallexample
14695
14696 @node Switches for gnatmem
14697 @section Switches for @code{gnatmem}
14698
14699 @noindent
14700 @code{gnatmem} recognizes the following switches:
14701
14702 @table @code
14703
14704 @item @code{-q}
14705 @cindex @code{-q} (@code{gnatmem})
14706 Quiet. Gives the minimum output needed to identify the origin of the
14707 memory leaks. Omit statistical information.
14708
14709 @item @code{n}
14710 @cindex @code{n} (@code{gnatmem})
14711 N is an integer literal (usually between 1 and 10) which controls the
14712 depth of the backtraces defining allocation root. The default value for
14713 N is 1. The deeper the backtrace, the more precise the localization of
14714 the root. Note that the total number of roots can depend on this
14715 parameter.
14716
14717 @item @code{-o file}
14718 @cindex @code{-o} (@code{gnatmem})
14719 Direct the gdb output to the specified file. The @code{gdb} script used
14720 to generate this output is also saved in the file @file{gnatmem.tmp}.
14721
14722 @item @code{-i file}
14723 @cindex @code{-i} (@code{gnatmem})
14724 Do the @code{gnatmem} processing starting from @file{file} which has
14725 been generated by a previous call to @code{gnatmem} with the -o
14726 switch or @file{gmem.out} produced by @code{GMEM} mode. This is useful
14727 for post mortem processing.
14728
14729 @end table
14730
14731 @node Examples of gnatmem Usage
14732 @section Example of @code{gnatmem} Usage
14733
14734 @noindent
14735 This section is based on the @code{GDB} mode of @code{gnatmem}. The same
14736 results can be achieved using @code{GMEM} mode. See section
14737 @ref{Running gnatmem (GMEM Mode)}.
14738
14739 @noindent
14740 The first example shows the use of @code{gnatmem}
14741 on a simple leaking program.
14742 Suppose that we have the following Ada program:
14743
14744 @smallexample
14745 @group
14746 @cartouche
14747 @b{with} Unchecked_Deallocation;
14748 @b{procedure} Test_Gm @b{is}
14749
14750    @b{type} T @b{is array} (1..1000) @b{of} Integer;
14751    @b{type} Ptr @b{is access} T;
14752    @b{procedure} Free @b{is new} Unchecked_Deallocation (T, Ptr);
14753    A : Ptr;
14754
14755    @b{procedure} My_Alloc @b{is}
14756    @b{begin}
14757       A := @b{new} T;
14758    @b{end} My_Alloc;
14759
14760    @b{procedure} My_DeAlloc @b{is}
14761       B : Ptr := A;
14762    @b{begin}
14763       Free (B);
14764    @b{end} My_DeAlloc;
14765
14766 @b{begin}
14767    My_Alloc;
14768    @b{for} I @b{in} 1 .. 5 @b{loop}
14769       @b{for} J @b{in} I .. 5 @b{loop}
14770          My_Alloc;
14771       @b{end loop};
14772       My_Dealloc;
14773    @b{end loop};
14774 @b{end};
14775 @end cartouche
14776 @end group
14777 @end smallexample
14778
14779 @noindent
14780 The program needs to be compiled with debugging option:
14781
14782 @smallexample
14783 $ gnatmake -g test_gm
14784 @end smallexample
14785
14786 @code{gnatmem} is invoked simply with
14787 @smallexample
14788 $ gnatmem test_gm
14789 @end smallexample
14790
14791 @noindent
14792 which produces the following output:
14793
14794 @smallexample
14795 Global information
14796 ------------------
14797    Total number of allocations        :  18
14798    Total number of deallocations      :   5
14799    Final Water Mark (non freed mem)   :  53.00 Kilobytes
14800    High Water Mark                    :  56.90 Kilobytes
14801
14802 Allocation Root # 1
14803 -------------------
14804  Number of non freed allocations    :  11
14805  Final Water Mark (non freed mem)   :  42.97 Kilobytes
14806  High Water Mark                    :  46.88 Kilobytes
14807  Backtrace                          :
14808    test_gm.adb:11 test_gm.my_alloc
14809
14810 Allocation Root # 2
14811 -------------------
14812  Number of non freed allocations    :   1
14813  Final Water Mark (non freed mem)   :  10.02 Kilobytes
14814  High Water Mark                    :  10.02 Kilobytes
14815  Backtrace                          :
14816    s-secsta.adb:81 system.secondary_stack.ss_init
14817
14818 Allocation Root # 3
14819 -------------------
14820  Number of non freed allocations    :   1
14821  Final Water Mark (non freed mem)   :  12 Bytes
14822  High Water Mark                    :  12 Bytes
14823  Backtrace                          :
14824    s-secsta.adb:181 system.secondary_stack.ss_init
14825 @end smallexample
14826
14827 @noindent
14828 Note that the GNAT run time contains itself a certain number of
14829 allocations that have no  corresponding deallocation,
14830 as shown here for root #2 and root
14831 #1. This is a normal behavior when the number of non freed allocations
14832 is one, it locates dynamic data structures that the run time needs for
14833 the complete lifetime of the program. Note also that there is only one
14834 allocation root in the user program with a single line back trace:
14835 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
14836 program shows that 'My_Alloc' is called at 2 different points in the
14837 source (line 21 and line 24). If those two allocation roots need to be
14838 distinguished, the backtrace depth parameter can be used:
14839
14840 @smallexample
14841 $ gnatmem 3 test_gm
14842 @end smallexample
14843
14844 @noindent
14845 which will give the following output:
14846
14847 @smallexample
14848 Global information
14849 ------------------
14850    Total number of allocations        :  18
14851    Total number of deallocations      :   5
14852    Final Water Mark (non freed mem)   :  53.00 Kilobytes
14853    High Water Mark                    :  56.90 Kilobytes
14854
14855 Allocation Root # 1
14856 -------------------
14857  Number of non freed allocations    :  10
14858  Final Water Mark (non freed mem)   :  39.06 Kilobytes
14859  High Water Mark                    :  42.97 Kilobytes
14860  Backtrace                          :
14861    test_gm.adb:11 test_gm.my_alloc
14862    test_gm.adb:24 test_gm
14863    b_test_gm.c:52 main
14864
14865 Allocation Root # 2
14866 -------------------
14867  Number of non freed allocations    :   1
14868  Final Water Mark (non freed mem)   :  10.02 Kilobytes
14869  High Water Mark                    :  10.02 Kilobytes
14870  Backtrace                          :
14871    s-secsta.adb:81  system.secondary_stack.ss_init
14872    s-secsta.adb:283 <system__secondary_stack___elabb>
14873    b_test_gm.c:33   adainit
14874
14875 Allocation Root # 3
14876 -------------------
14877  Number of non freed allocations    :   1
14878  Final Water Mark (non freed mem)   :   3.91 Kilobytes
14879  High Water Mark                    :   3.91 Kilobytes
14880  Backtrace                          :
14881    test_gm.adb:11 test_gm.my_alloc
14882    test_gm.adb:21 test_gm
14883    b_test_gm.c:52 main
14884
14885 Allocation Root # 4
14886 -------------------
14887  Number of non freed allocations    :   1
14888  Final Water Mark (non freed mem)   :  12 Bytes
14889  High Water Mark                    :  12 Bytes
14890  Backtrace                          :
14891    s-secsta.adb:181 system.secondary_stack.ss_init
14892    s-secsta.adb:283 <system__secondary_stack___elabb>
14893    b_test_gm.c:33   adainit
14894 @end smallexample
14895
14896 @noindent
14897 The allocation root #1 of the first example has been split in 2 roots #1
14898 and #3 thanks to the more precise associated backtrace.
14899
14900 @node GDB and GMEM Modes
14901 @section GDB and GMEM Modes
14902
14903 @noindent
14904 The main advantage of the @code{GMEM} mode is that it is a lot faster than the
14905 @code{GDB} mode where the application must be monitored by a @code{GDB} script.
14906 But the @code{GMEM} mode is available only for DEC Unix, Linux x86,
14907 Solaris (sparc and x86) and Windows 95/98/NT/2000 (x86).
14908
14909 @noindent
14910 The main advantage of the @code{GDB} mode is that it is available on all
14911 supported platforms. But it can be very slow if the application does a
14912 lot of allocations and deallocations.
14913
14914 @node Implementation Note
14915 @section Implementation Note
14916
14917 @menu
14918 * gnatmem Using GDB Mode::
14919 * gnatmem Using GMEM Mode::
14920 @end menu
14921
14922 @node gnatmem Using GDB Mode
14923 @subsection @code{gnatmem} Using @code{GDB} Mode
14924
14925 @noindent
14926 @code{gnatmem} executes the user program under the control of @code{GDB} using
14927 a script that sets breakpoints and gathers information on each dynamic
14928 allocation and deallocation. The output of the script is then analyzed
14929 by @code{gnatmem}
14930 in order to locate memory leaks and their origin in the
14931 program. Gnatmem works by recording each address returned by the
14932 allocation procedure (@code{__gnat_malloc})
14933 along with the backtrace at the
14934 allocation point. On each deallocation, the deallocated address is
14935 matched with the corresponding allocation. At the end of the processing,
14936 the unmatched allocations are considered potential leaks. All the
14937 allocations associated with the same backtrace are grouped together and
14938 form an allocation root. The allocation roots are then sorted so that
14939 those with the biggest number of unmatched allocation are printed
14940 first. A delicate aspect of this technique is to distinguish between the
14941 data produced by the user program and the data produced by the gdb
14942 script. Currently, on systems that allow probing the terminal, the gdb
14943 command "tty" is used to force the program output to be redirected to the
14944 current terminal while the @code{gdb} output is directed to a file or to a
14945 pipe in order to be processed subsequently by @code{gnatmem}.
14946
14947 @node gnatmem Using GMEM Mode
14948 @subsection @code{gnatmem} Using @code{GMEM} Mode
14949
14950 @noindent
14951 This mode use the same algorithm to detect memory leak as the @code{GDB}
14952 mode of @code{gnatmem}, the only difference is in the way data are
14953 gathered. In @code{GMEM} mode the program is linked with instrumented
14954 version of @code{__gnat_malloc} and @code{__gnat_free}
14955 routines. Information needed to find memory leak are recorded by these
14956 routines in file @file{gmem.out}. This mode also require that the stack
14957 traceback be available, this is only implemented on some platforms
14958 @ref{GDB and GMEM Modes}.
14959
14960
14961 @node Finding Memory Problems with GNAT Debug Pool
14962 @chapter Finding Memory Problems with GNAT Debug Pool
14963 @findex Debug Pool
14964 @cindex storage, pool, memory corruption
14965
14966 @noindent
14967 The use of unchecked deallocation and unchecked conversion can easily
14968 lead to incorrect memory references. The problems generated by such
14969 references are usually difficult to tackle because the symptoms can be
14970 very remote from the origin of the problem. In such cases, it is
14971 very helpful to detect the problem as early as possible. This is the
14972 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
14973
14974 @noindent
14975 In order to use the GNAT specific debugging pool, the user must
14976 associate a debug pool object with each of the access types that may be
14977 related to suspected memory problems. See Ada Reference Manual
14978 13.11.
14979 @smallexample
14980 @b{type} Ptr @b{is} @b{access} Some_Type;
14981 Pool : GNAT.Debug_Pools.Debug_Pool;
14982 @b{for} Ptr'Storage_Pool @b{use} Pool;
14983 @end smallexample
14984
14985 @code{GNAT.Debug_Pools} is derived from of a GNAT-specific kind of
14986 pool: the Checked_Pool. Such pools, like standard Ada storage pools,
14987 allow the user to redefine allocation and deallocation strategies. They
14988 also provide a checkpoint for each dereference, through the use of
14989 the primitive operation @code{Dereference} which is implicitly called at
14990 each dereference of an access value.
14991
14992 Once an access type has been associated with a debug pool, operations on
14993 values of the type may raise four distinct exceptions,
14994 which correspond to four potential kinds of memory corruption:
14995 @itemize @bullet
14996 @item
14997 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
14998 @item
14999 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
15000 @item
15001 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
15002 @item
15003 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
15004 @end itemize
15005
15006 @noindent
15007 For types associated with a Debug_Pool, dynamic allocation is performed using
15008 the standard
15009 GNAT allocation routine. References to all allocated chunks of memory
15010 are kept in an internal dictionary. The deallocation strategy consists
15011 in not releasing the memory to the underlying system but rather to fill
15012 it with a memory pattern easily recognizable during debugging sessions:
15013 The memory pattern is the old IBM hexadecimal convention: 16#DEADBEEF#.
15014 Upon each dereference, a check is made that the access value denotes a properly
15015 allocated memory location. Here is a complete example of use of
15016 @code{Debug_Pools}, that includes typical instances of  memory corruption:
15017 @smallexample
15018 @iftex
15019 @leftskip=0cm
15020 @end iftex
15021 @b{with} Gnat.Io; @b{use} Gnat.Io;
15022 @b{with} Unchecked_Deallocation;
15023 @b{with} Unchecked_Conversion;
15024 @b{with} GNAT.Debug_Pools;
15025 @b{with} System.Storage_Elements;
15026 @b{with} Ada.Exceptions; @b{use} Ada.Exceptions;
15027 @b{procedure} Debug_Pool_Test @b{is}
15028
15029    @b{type} T @b{is} @b{access} Integer;
15030    @b{type} U @b{is} @b{access} @b{all} T;
15031
15032    P : GNAT.Debug_Pools.Debug_Pool;
15033    @b{for} T'Storage_Pool @b{use} P;
15034
15035    @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (Integer, T);
15036    @b{function} UC @b{is} @b{new} Unchecked_Conversion (U, T);
15037    A, B : @b{aliased} T;
15038
15039    @b{procedure} Info @b{is} @b{new} GNAT.Debug_Pools.Print_Info(Put_Line);
15040
15041 @b{begin}
15042    Info (P);
15043    A := @b{new} Integer;
15044    B := @b{new} Integer;
15045    B := A;
15046    Info (P);
15047    Free (A);
15048    @b{begin}
15049       Put_Line (Integer'Image(B.@b{all}));
15050    @b{exception}
15051       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
15052    @b{end};
15053    @b{begin}
15054       Free (B);
15055    @b{exception}
15056       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
15057    @b{end};
15058    B := UC(A'Access);
15059    @b{begin}
15060       Put_Line (Integer'Image(B.@b{all}));
15061    @b{exception}
15062       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
15063    @b{end};
15064    @b{begin}
15065       Free (B);
15066    @b{exception}
15067       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
15068    @b{end};
15069    Info (P);
15070 @b{end} Debug_Pool_Test;
15071 @end smallexample
15072 @noindent
15073 The debug pool mechanism provides the following precise diagnostics on the
15074 execution of this erroneous program:
15075 @smallexample
15076 Debug Pool info:
15077   Total allocated bytes :  0
15078   Total deallocated bytes :  0
15079   Current Water Mark:  0
15080   High Water Mark:  0
15081
15082 Debug Pool info:
15083   Total allocated bytes :  8
15084   Total deallocated bytes :  0
15085   Current Water Mark:  8
15086   High Water Mark:  8
15087
15088 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
15089 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
15090 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
15091 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
15092 Debug Pool info:
15093   Total allocated bytes :  8
15094   Total deallocated bytes :  4
15095   Current Water Mark:  4
15096   High Water Mark:  8
15097
15098 @end smallexample
15099
15100 @node Creating Sample Bodies Using gnatstub
15101 @chapter Creating Sample Bodies Using @code{gnatstub}
15102 @findex gnatstub
15103
15104 @noindent
15105 @code{gnatstub} creates body stubs, that is, empty but compilable bodies
15106 for library unit declarations.
15107
15108 To create a body stub, @code{gnatstub} has to compile the library
15109 unit declaration. Therefore, bodies can be created only for legal
15110 library units. Moreover, if a library unit depends semantically upon
15111 units located outside the current directory, you have to provide
15112 the source search path when calling @code{gnatstub}, see the description
15113 of @code{gnatstub} switches below.
15114
15115 @menu
15116 * Running gnatstub::
15117 * Switches for gnatstub::
15118 @end menu
15119
15120 @node Running gnatstub
15121 @section Running @code{gnatstub}
15122
15123 @noindent
15124 @code{gnatstub} has the command-line interface of the form
15125
15126 @smallexample
15127 $ gnatstub [switches] filename [directory]
15128 @end smallexample
15129
15130 @noindent
15131 where
15132 @table @code
15133 @item filename
15134 is the name of the source file that contains a library unit declaration
15135 for which a body must be created. This name should follow the GNAT file name
15136 conventions. No crunching is allowed for this file name. The file
15137 name may contain the path information.
15138
15139 @item directory
15140 indicates the directory to place a body stub (default is the
15141 current directory)
15142
15143 @item switches
15144 is an optional sequence of switches as described in the next section
15145 @end table
15146
15147 @node Switches for gnatstub
15148 @section Switches for @code{gnatstub}
15149
15150 @table @code
15151
15152 @item -f
15153 If the destination directory already contains a file with a name of the body file
15154 for the argument spec file, replace it with the generated body stub.
15155
15156 @item -hs
15157 Put the comment header (i.e. all the comments preceding the
15158 compilation unit) from the source of the library unit declaration
15159 into the body stub.
15160
15161 @item -hg
15162 Put a sample comment header into the body stub.
15163
15164 @item -IDIR
15165 @itemx -I-
15166 These switches have the same meaning as in calls to gcc.
15167 They define the source search path in the call to gcc issued
15168 by @code{gnatstub} to compile an argument source file.
15169
15170 @item -i@var{n}
15171 (@var{n} is a decimal natural number). Set the indentation level in the
15172 generated body sample to n, '-i0' means "no indentation",
15173 the default indentation is 3.
15174
15175 @item -k
15176 Do not remove the tree file (i.e. the snapshot of the compiler internal
15177 structures used by @code{gnatstub}) after creating the body stub.
15178
15179 @item -l@var{n}
15180 (@var{n} is a decimal positive number) Set the maximum line length in the
15181 body stub to n, the default is 78.
15182
15183 @item -q
15184 Quiet mode: do not generate a confirmation when a body is
15185 successfully created or a message when a body is not required for an
15186 argument unit.
15187
15188 @item -r
15189 Reuse the tree file (if it exists) instead of creating it: instead of
15190 creating the tree file for the library unit declaration, gnatstub
15191 tries to find it in the current directory and use it for creating
15192 a body. If the tree file is not found, no body is created. @code{-r}
15193 also implies @code{-k}, whether or not
15194 @code{-k} is set explicitly.
15195
15196 @item -t
15197 Overwrite the existing tree file: if the current directory already
15198 contains the file which, according to the GNAT file name rules should
15199 be considered as a tree file for the argument source file, gnatstub
15200 will refuse to create the tree file needed to create a body sampler,
15201 unless @code{-t} option is set
15202
15203 @item -v
15204 Verbose mode: generate version information.
15205
15206 @end table
15207
15208 @node Reducing the Size of Ada Executables with gnatelim
15209 @chapter Reducing the Size of Ada Executables with @code{gnatelim}
15210 @findex gnatelim
15211
15212 @menu
15213 * About gnatelim::
15214 * Eliminate Pragma::
15215 * Tree Files::
15216 * Preparing Tree and Bind Files for gnatelim::
15217 * Running gnatelim::
15218 * Correcting the List of Eliminate Pragmas::
15219 * Making Your Executables Smaller::
15220 * Summary of the gnatelim Usage Cycle::
15221 @end menu
15222
15223 @node About gnatelim
15224 @section About @code{gnatelim}
15225
15226 @noindent
15227 When a program shares a set of Ada
15228 packages with other programs, it may happen that this program uses
15229 only a fraction of the subprograms defined in these packages. The code
15230 created for these unused subprograms increases the size of the executable.
15231
15232 @code{gnatelim} tracks unused subprograms in an Ada program and
15233 outputs a list of GNAT-specific @code{Eliminate} pragmas (see next
15234 section) marking all the subprograms that are declared but never called.
15235 By placing the list of @code{Eliminate} pragmas in the GNAT configuration
15236 file @file{gnat.adc} and recompiling your program, you may decrease the
15237 size of its executable, because the compiler will not generate the code
15238 for 'eliminated' subprograms.
15239
15240 @code{gnatelim} needs as its input data a set of tree files
15241 (see @ref{Tree Files}) representing all the components of a program to
15242 process and a bind file for a main subprogram (see
15243 @ref{Preparing Tree and Bind Files for gnatelim}).
15244
15245 @node Eliminate Pragma
15246 @section @code{Eliminate} Pragma
15247 @findex Eliminate
15248
15249 @noindent
15250 The simplified syntax of the Eliminate pragma used by @code{gnatelim} is:
15251
15252 @smallexample
15253 @cartouche
15254 @b{pragma} Eliminate (Library_Unit_Name, Subprogram_Name);
15255 @end cartouche
15256 @end smallexample
15257
15258 @noindent
15259 where
15260 @table @code
15261 @item Library_Unit_Name
15262 full expanded Ada name of a library unit
15263
15264 @item Subprogram_Name
15265 a simple or expanded name of a subprogram declared within this
15266 compilation unit
15267
15268 @end table
15269
15270 @noindent
15271 The effect of an @code{Eliminate} pragma placed in the GNAT configuration
15272 file @file{gnat.adc} is:
15273
15274 @itemize @bullet
15275
15276 @item
15277 If the subprogram @code{Subprogram_Name} is declared within
15278 the library unit @code{Library_Unit_Name}, the compiler will not generate
15279 code for this subprogram. This applies to all overloaded subprograms denoted
15280 by @code{Subprogram_Name}.
15281
15282 @item
15283 If a subprogram marked by the pragma @code{Eliminate} is used (called)
15284 in a program, the compiler will produce an error message in the place where
15285 it is called.
15286 @end itemize
15287
15288 @node Tree Files
15289 @section Tree Files
15290 @cindex Tree file
15291
15292 @noindent
15293 A tree file stores a snapshot of the compiler internal data
15294 structures at the very end of a successful compilation. It contains all the
15295 syntactic and semantic information for the compiled unit and all the
15296 units upon which it depends semantically.
15297 To use tools that make use of tree files, you
15298 need to first produce the right set of tree files.
15299
15300 GNAT produces correct tree files when -gnatt -gnatc options are set
15301 in a gcc call. The tree files have an .adt extension.
15302 Therefore, to produce a tree file for the compilation unit contained in a file
15303 named @file{foo.adb}, you must use the command
15304
15305 @smallexample
15306 $ gcc -c -gnatc -gnatt foo.adb
15307 @end smallexample
15308
15309 @noindent
15310 and you will get the tree file @file{foo.adt}.
15311 compilation.
15312
15313 @node Preparing Tree and Bind Files for gnatelim
15314 @section Preparing Tree and Bind Files for @code{gnatelim}
15315
15316 @noindent
15317 A set of tree files covering the program to be analyzed with
15318 @code{gnatelim} and
15319 the bind file for the main subprogram does not have to
15320 be in the current directory.
15321 '-T' gnatelim option may be used to provide
15322 the search path for tree files, and '-b'
15323 option may be used to point to the bind
15324 file to process (see @ref{Running gnatelim})
15325
15326 If you do not have the appropriate set of tree
15327 files and the right bind file, you
15328 may create them in the current directory using the following procedure.
15329
15330 Let @code{Main_Prog} be the name of a main subprogram, and suppose
15331 this subprogram is in a file named @file{main_prog.adb}.
15332
15333 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
15334 the main subprogram. @code{gnatelim} can work with both Ada and C
15335 bind files; when both are present, it uses the Ada bind file.
15336 The following commands will build the program and create the bind file:
15337
15338 @smallexample
15339 $ gnatmake -c Main_Prog
15340 $ gnatbind main_prog
15341 @end smallexample
15342
15343 @noindent
15344 To create a minimal set of tree files covering the whole program, call
15345 @code{gnatmake} for this program as follows:
15346
15347 @smallexample
15348 $ gnatmake -f -c -gnatc -gnatt Main_Prog
15349 @end smallexample
15350
15351 @noindent
15352 The @code{-c} gnatmake option turns off the bind and link
15353 steps, that are useless anyway because the sources are compiled with
15354 @option{-gnatc} option which turns off code generation.
15355
15356 The @code{-f} gnatmake option forces
15357 recompilation of all the needed sources.
15358
15359 This sequence of actions will create all the data needed by @code{gnatelim}
15360 from scratch and therefore guarantee its consistency. If you would like to
15361 use some existing set of files as @code{gnatelim} output, you must make
15362 sure that the set of files is complete and consistent. You can use the
15363 @code{-m} switch to check if there are missed tree files
15364
15365 Note, that @code{gnatelim} needs neither object nor ALI files.
15366
15367 @node Running gnatelim
15368 @section Running @code{gnatelim}
15369
15370 @noindent
15371 @code{gnatelim} has the following command-line interface:
15372
15373 @smallexample
15374 $ gnatelim [options] name
15375 @end smallexample
15376
15377 @noindent
15378 @code{name} should be a full expanded Ada name of a main subprogram
15379 of a program (partition).
15380
15381 @code{gnatelim} options:
15382
15383 @table @code
15384 @item -q
15385 Quiet mode: by default @code{gnatelim} generates to the standard error
15386 stream a trace of the source file names of the compilation units being
15387 processed. This option turns this trace off.
15388
15389 @item -v
15390 Verbose mode: @code{gnatelim} version information is printed as Ada
15391 comments to the standard output stream.
15392
15393 @item -a
15394 Also look for subprograms from the GNAT run time that can be eliminated.
15395
15396 @item -m
15397 Check if any tree files are missing for an accurate result.
15398
15399 @item -T@var{dir}
15400 When looking for tree files also look in directory @var{dir}
15401
15402 @item -b@var{bind_file}
15403 Specifies @var{bind_file} as the bind file to process. If not set, the name
15404 of the bind file is computed from the full expanded Ada name of a main subprogram.
15405
15406 @item -d@var{x}
15407 Activate internal debugging switches. @var{x} is a letter or digit, or
15408 string of letters or digits, which specifies the type of debugging
15409 mode desired.  Normally these are used only for internal development
15410 or system debugging purposes. You can find full documentation for these
15411 switches in the body of the @code{Gnatelim.Options} unit in the compiler
15412 source file @file{gnatelim-options.adb}.
15413 @end table
15414
15415 @noindent
15416 @code{gnatelim} sends its output to the standard output stream, and all the
15417 tracing and debug information is sent to the standard error stream.
15418 In order to produce a proper GNAT configuration file
15419 @file{gnat.adc}, redirection must be used:
15420
15421 @smallexample
15422 $ gnatelim Main_Prog > gnat.adc
15423 @end smallexample
15424
15425 @noindent
15426 or
15427
15428 @smallexample
15429 $ gnatelim Main_Prog >> gnat.adc
15430 @end smallexample
15431
15432 @noindent
15433 In order to append the @code{gnatelim} output to the existing contents of
15434 @file{gnat.adc}.
15435
15436 @node Correcting the List of Eliminate Pragmas
15437 @section Correcting the List of Eliminate Pragmas
15438
15439 @noindent
15440 In some rare cases it may happen that @code{gnatelim} will try to eliminate
15441 subprograms which are actually called in the program. In this case, the
15442 compiler will generate an error message of the form:
15443
15444 @smallexample
15445 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
15446 @end smallexample
15447
15448 @noindent
15449 You will need to manually remove the wrong @code{Eliminate} pragmas from
15450 the @file{gnat.adc} file. It is advised that you recompile your program
15451 from scratch after that because you need a consistent @file{gnat.adc} file
15452 during the entire compilation.
15453
15454 @node Making Your Executables Smaller
15455 @section Making Your Executables Smaller
15456
15457 @noindent
15458 In order to get a smaller executable for your program you now have to
15459 recompile the program completely with the new @file{gnat.adc} file
15460 created by @code{gnatelim} in your current directory:
15461
15462 @smallexample
15463 $ gnatmake -f Main_Prog
15464 @end smallexample
15465
15466 @noindent
15467 (you will need @code{-f} option for gnatmake to
15468 recompile everything
15469 with the set of pragmas @code{Eliminate} you have obtained with
15470 @code{gnatelim}).
15471
15472 Be aware that the set of @code{Eliminate} pragmas is specific to each
15473 program. It is not recommended to merge sets of @code{Eliminate}
15474 pragmas created for different programs in one @file{gnat.adc} file.
15475
15476 @node Summary of the gnatelim Usage Cycle
15477 @section Summary of the gnatelim Usage Cycle
15478
15479 @noindent
15480 Here is a quick summary of the steps to be taken in order to reduce
15481 the size of your executables with @code{gnatelim}. You may use
15482 other GNAT options to control the optimization level,
15483 to produce the debugging information, to set search path, etc.
15484
15485 @enumerate
15486 @item
15487 Produce a bind file and a set of tree files
15488
15489 @smallexample
15490 $ gnatmake -c Main_Prog
15491 $ gnatbind main_prog
15492 $ gnatmake -f -c -gnatc -gnatt Main_Prog
15493 @end smallexample
15494
15495 @item
15496 Generate a list of @code{Eliminate} pragmas
15497 @smallexample
15498 $ gnatelim Main_Prog >[>] gnat.adc
15499 @end smallexample
15500
15501 @item
15502 Recompile the application
15503
15504 @smallexample
15505 $ gnatmake -f Main_Prog
15506 @end smallexample
15507
15508 @end enumerate
15509
15510 @node Other Utility Programs
15511 @chapter Other Utility Programs
15512
15513 @noindent
15514 This chapter discusses some other utility programs available in the Ada
15515 environment.
15516
15517 @menu
15518 * Using Other Utility Programs with GNAT::
15519 * The gnatpsta Utility Program::
15520 * The External Symbol Naming Scheme of GNAT::
15521 * Ada Mode for Glide::
15522 * Converting Ada Files to html with gnathtml::
15523 * Installing gnathtml::
15524 @end menu
15525
15526 @node Using Other Utility Programs with GNAT
15527 @section Using Other Utility Programs with GNAT
15528
15529 @noindent
15530 The object files generated by GNAT are in standard system format and in
15531 particular the debugging information uses this format. This means
15532 programs generated by GNAT can be used with existing utilities that
15533 depend on these formats.
15534
15535 In general, any utility program that works with C will also often work with
15536 Ada programs generated by GNAT. This includes software utilities such as
15537 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
15538 as Purify.
15539
15540 @node The gnatpsta Utility Program
15541 @section The @code{gnatpsta} Utility Program
15542
15543 @noindent
15544 Many of the definitions in package Standard are implementation-dependent.
15545 However, the source of this package does not exist as an Ada source
15546 file, so these values cannot be determined by inspecting the source.
15547 They can be determined by examining in detail the coding of
15548 @file{cstand.adb} which creates the image of Standard in the compiler,
15549 but this is awkward and requires a great deal of internal knowledge
15550 about the system.
15551
15552 The @code{gnatpsta} utility is designed to deal with this situation.
15553 It is an Ada program that dynamically determines the
15554 values of all the relevant parameters in Standard, and prints them
15555 out in the form of an Ada source listing for Standard, displaying all
15556 the values of interest. This output is generated to
15557 @file{stdout}.
15558
15559 To determine the value of any parameter in package Standard, simply
15560 run @code{gnatpsta} with no qualifiers or arguments, and examine
15561 the output. This is preferable to consulting documentation, because
15562 you know that the values you are getting are the actual ones provided
15563 by the executing system.
15564
15565 @node The External Symbol Naming Scheme of GNAT
15566 @section The External Symbol Naming Scheme of GNAT
15567
15568 @noindent
15569 In order to interpret the output from GNAT, when using tools that are
15570 originally intended for use with other languages, it is useful to
15571 understand the conventions used to generate link names from the Ada
15572 entity names.
15573
15574 All link names are in all lowercase letters. With the exception of library
15575 procedure names, the mechanism used is simply to use the full expanded
15576 Ada name with dots replaced by double underscores. For example, suppose
15577 we have the following package spec:
15578
15579 @smallexample
15580 @group
15581 @cartouche
15582 @b{package} QRS @b{is}
15583    MN : Integer;
15584 @b{end} QRS;
15585 @end cartouche
15586 @end group
15587 @end smallexample
15588
15589 @noindent
15590 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
15591 the corresponding link name is @code{qrs__mn}.
15592 @findex Export
15593 Of course if a @code{pragma Export} is used this may be overridden:
15594
15595 @smallexample
15596 @group
15597 @cartouche
15598 @b{package} Exports @b{is}
15599    Var1 : Integer;
15600    @b{pragma} Export (Var1, C, External_Name => "var1_name");
15601    Var2 : Integer;
15602    @b{pragma} Export (Var2, C, Link_Name => "var2_link_name");
15603 @b{end} Exports;
15604 @end cartouche
15605 @end group
15606 @end smallexample
15607
15608 @noindent
15609 In this case, the link name for @var{Var1} is whatever link name the
15610 C compiler would assign for the C function @var{var1_name}. This typically
15611 would be either @var{var1_name} or @var{_var1_name}, depending on operating
15612 system conventions, but other possibilities exist. The link name for
15613 @var{Var2} is @var{var2_link_name}, and this is not operating system
15614 dependent.
15615
15616 @findex _main
15617 One exception occurs for library level procedures. A potential ambiguity
15618 arises between the required name @code{_main} for the C main program,
15619 and the name we would otherwise assign to an Ada library level procedure
15620 called @code{Main} (which might well not be the main program).
15621
15622 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
15623 names. So if we have a library level procedure such as
15624
15625 @smallexample
15626 @group
15627 @cartouche
15628 @b{procedure} Hello (S : String);
15629 @end cartouche
15630 @end group
15631 @end smallexample
15632
15633 @noindent
15634 the external name of this procedure will be @var{_ada_hello}.
15635
15636 @node Ada Mode for Glide
15637 @section Ada Mode for @code{Glide}
15638
15639 @noindent
15640 The Glide mode for programming in Ada (both, Ada83 and Ada95) helps the
15641 user in understanding existing code and facilitates writing new code. It
15642 furthermore provides some utility functions for easier integration of
15643 standard Emacs features when programming in Ada.
15644
15645 @subsection General Features:
15646
15647 @itemize @bullet
15648 @item
15649 Full Integrated Development Environment :
15650
15651 @itemize @bullet
15652 @item
15653 support of 'project files' for the configuration (directories,
15654 compilation options,...)
15655
15656 @item
15657 compiling and stepping through error messages.
15658
15659 @item
15660 running and debugging your applications within Glide.
15661 @end itemize
15662
15663 @item
15664 easy to use for beginners by pull-down menus,
15665
15666 @item
15667 user configurable by many user-option variables.
15668 @end itemize
15669
15670 @subsection Ada Mode Features That Help Understanding Code:
15671
15672 @itemize @bullet
15673 @item
15674 functions for easy and quick stepping through Ada code,
15675
15676 @item
15677 getting cross reference information for identifiers (e.g. find the
15678 defining place by a keystroke),
15679
15680 @item
15681 displaying an index menu of types and subprograms and move point to
15682 the chosen one,
15683
15684 @item
15685 automatic color highlighting of the various entities in Ada code.
15686 @end itemize
15687
15688 @subsection Glide Support for Writing Ada Code:
15689
15690 @itemize @bullet
15691 @item
15692 switching between spec and body files with possible
15693 autogeneration of body files,
15694
15695 @item
15696 automatic formating of subprograms parameter lists.
15697
15698 @item
15699 automatic smart indentation according to Ada syntax,
15700
15701 @item
15702 automatic completion of identifiers,
15703
15704 @item
15705 automatic casing of identifiers, keywords, and attributes,
15706
15707 @item
15708 insertion of statement templates,
15709
15710 @item
15711 filling comment paragraphs like filling normal text,
15712 @end itemize
15713
15714 For more information, please refer to the online Glide documentation
15715 available in the Glide --> Help Menu.
15716
15717 @node Converting Ada Files to html with gnathtml
15718 @section Converting Ada Files to html with @code{gnathtml}
15719
15720 @noindent
15721 This @code{Perl} script allows Ada source files to be browsed using
15722 standard Web browsers. For installation procedure, see the section
15723 @xref{Installing gnathtml}.
15724
15725 Ada reserved keywords are highlighted in a bold font and Ada comments in
15726 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
15727 switch to suppress the generation of cross-referencing information, user
15728 defined variables and types will appear in a different color; you will
15729 be able to click on any identifier and go to its declaration.
15730
15731 The command line is as follow:
15732 @smallexample
15733 $ perl gnathtml.pl [switches] ada-files
15734 @end smallexample
15735
15736 You can pass it as many Ada files as you want. @code{gnathtml} will generate
15737 an html file for every ada file, and a global file called @file{index.htm}.
15738 This file is an index of every identifier defined in the files.
15739
15740 The available switches are the following ones :
15741
15742 @table @code
15743 @item -83
15744 @cindex @code{-83} (@code{gnathtml})
15745 Only the subset on the Ada 83 keywords will be highlighted, not the full
15746 Ada 95 keywords set.
15747
15748 @item -cc @var{color}
15749 This option allows you to change the color used for comments. The default
15750 value is green. The color argument can be any name accepted by html.
15751
15752 @item -d
15753 @cindex @code{-d} (@code{gnathtml})
15754 If the ada files depend on some other files (using for instance the
15755 @code{with} command, the latter will also be converted to html.
15756 Only the files in the user project will be converted to html, not the files
15757 in the run-time library itself.
15758
15759 @item -D
15760 This command is the same as -d above, but @code{gnathtml} will also look
15761 for files in the run-time library, and generate html files for them.
15762
15763 @item -f
15764 @cindex @code{-f} (@code{gnathtml})
15765 By default, gnathtml will generate html links only for global entities
15766 ('with'ed units, global variables and types,...). If you specify the
15767 @code{-f} on the command line, then links will be generated for local
15768 entities too.
15769
15770 @item -l @var{number}
15771 @cindex @code{-l} (@code{gnathtml})
15772 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
15773 will number the html files every @var{number} line.
15774
15775 @item -I @var{dir}
15776 @cindex @code{-I} (@code{gnathtml})
15777 Specify a directory to search for library files (@file{.ali} files) and
15778 source files. You can provide several -I switches on the command line,
15779 and the directories will be parsed in the order of the command line.
15780
15781 @item -o @var{dir}
15782 @cindex @code{-o} (@code{gnathtml})
15783 Specify the output directory for html files. By default, gnathtml will
15784 saved the generated html files in a subdirectory named @file{html/}.
15785
15786 @item -p @var{file}
15787 @cindex @code{-p} (@code{gnathtml})
15788 If you are using Emacs and the most recent Emacs Ada mode, which provides
15789 a full Integrated Development Environment for compiling, checking,
15790 running and debugging applications, you may be using @file{.adp} files
15791 to give the directories where Emacs can find sources and object files.
15792
15793 Using this switch, you can tell gnathtml to use these files. This allows
15794 you to get an html version of your application, even if it is spread
15795 over multiple directories.
15796
15797 @item -sc @var{color}
15798 @cindex @code{-sc} (@code{gnathtml})
15799 This option allows you to change the color used for symbol definitions.
15800 The default value is red. The color argument can be any name accepted by html.
15801
15802 @item -t @var{file}
15803 @cindex @code{-t} (@code{gnathtml})
15804 This switch provides the name of a file. This file contains a list of
15805 file names to be converted, and the effect is exactly as though they had
15806 appeared explicitly on the command line. This
15807 is the recommended way to work around the command line length limit on some
15808 systems.
15809
15810 @end table
15811
15812 @node Installing gnathtml
15813 @section Installing @code{gnathtml}
15814
15815 @noindent
15816 @code{Perl} needs to be installed on your machine to run this script.
15817 @code{Perl} is freely available for almost every architecture and
15818 Operating System via the Internet.
15819
15820 On Unix systems, you  may want to modify  the  first line of  the script
15821 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
15822 is. The syntax of this line is :
15823 @smallexample
15824 #!full_path_name_to_perl
15825 @end smallexample
15826
15827 @noindent
15828 Alternatively, you may run the script using the following command line:
15829
15830 @smallexample
15831 $ perl gnathtml.pl [switches] files
15832 @end smallexample
15833
15834
15835 @node Running and Debugging Ada Programs
15836 @chapter Running and Debugging Ada Programs
15837 @cindex Debugging
15838
15839 @noindent
15840 This chapter discusses how to debug Ada programs. An incorrect Ada program
15841 may be handled in three ways by the GNAT compiler:
15842
15843 @enumerate
15844 @item
15845 The illegality may be a violation of the static semantics of Ada. In
15846 that case GNAT diagnoses the constructs in the program that are illegal.
15847 It is then a straightforward matter for the user to modify those parts of
15848 the program.
15849
15850 @item
15851 The illegality may be a violation of the dynamic semantics of Ada. In
15852 that case the program compiles and executes, but may generate incorrect
15853 results, or may terminate abnormally with some exception.
15854
15855 @item
15856 When presented with a program that contains convoluted errors, GNAT
15857 itself may terminate abnormally without providing full diagnostics on
15858 the incorrect user program.
15859 @end enumerate
15860
15861 @menu
15862 * The GNAT Debugger GDB::
15863 * Running GDB::
15864 * Introduction to GDB Commands::
15865 * Using Ada Expressions::
15866 * Calling User-Defined Subprograms::
15867 * Using the Next Command in a Function::
15868 * Ada Exceptions::
15869 * Ada Tasks::
15870 * Debugging Generic Units::
15871 * GNAT Abnormal Termination or Failure to Terminate::
15872 * Naming Conventions for GNAT Source Files::
15873 * Getting Internal Debugging Information::
15874 * Stack Traceback::
15875 @end menu
15876
15877 @cindex Debugger
15878 @findex gdb
15879
15880 @node The GNAT Debugger GDB
15881 @section The GNAT Debugger GDB
15882
15883 @noindent
15884 @code{GDB} is a general purpose, platform-independent debugger that
15885 can be used to debug mixed-language programs compiled with @code{GCC},
15886 and in particular is capable of debugging Ada programs compiled with
15887 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
15888 complex Ada data structures.
15889
15890 The manual @cite{Debugging with GDB}
15891 contains full details on the usage of @code{GDB}, including a section on
15892 its usage on programs. This manual should be consulted for full
15893 details. The section that follows is a brief introduction to the
15894 philosophy and use of @code{GDB}.
15895
15896 When GNAT programs are compiled, the compiler optionally writes debugging
15897 information into the generated object file, including information on
15898 line numbers, and on declared types and variables. This information is
15899 separate from the generated code. It makes the object files considerably
15900 larger, but it does not add to the size of the actual executable that
15901 will be loaded into memory, and has no impact on run-time performance. The
15902 generation of debug information is triggered by the use of the
15903 -g switch in the gcc or gnatmake command used to carry out
15904 the compilations. It is important to emphasize that the use of these
15905 options does not change the generated code.
15906
15907 The debugging information is written in standard system formats that
15908 are used by many tools, including debuggers and profilers. The format
15909 of the information is typically designed to describe C types and
15910 semantics, but GNAT implements a translation scheme which allows full
15911 details about Ada types and variables to be encoded into these
15912 standard C formats. Details of this encoding scheme may be found in
15913 the file exp_dbug.ads in the GNAT source distribution. However, the
15914 details of this encoding are, in general, of no interest to a user,
15915 since @code{GDB} automatically performs the necessary decoding.
15916
15917 When a program is bound and linked, the debugging information is
15918 collected from the object files, and stored in the executable image of
15919 the program. Again, this process significantly increases the size of
15920 the generated executable file, but it does not increase the size of
15921 the executable program itself. Furthermore, if this program is run in
15922 the normal manner, it runs exactly as if the debug information were
15923 not present, and takes no more actual memory.
15924
15925 However, if the program is run under control of @code{GDB}, the
15926 debugger is activated.  The image of the program is loaded, at which
15927 point it is ready to run.  If a run command is given, then the program
15928 will run exactly as it would have if @code{GDB} were not present. This
15929 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
15930 entirely non-intrusive until a breakpoint is encountered.  If no
15931 breakpoint is ever hit, the program will run exactly as it would if no
15932 debugger were present. When a breakpoint is hit, @code{GDB} accesses
15933 the debugging information and can respond to user commands to inspect
15934 variables, and more generally to report on the state of execution.
15935
15936 @node Running GDB
15937 @section Running GDB
15938
15939 @noindent
15940 The debugger can be launched directly and simply from @code{glide} or
15941 through its graphical interface: @code{gvd}. It can also be used
15942 directly in text mode. Here is described the basic use of @code{GDB}
15943 in text mode. All the commands described below can be used in the
15944 @code{gvd} console window eventhough there is usually other more
15945 graphical ways to achieve the same goals.
15946
15947 @noindent
15948 The command to run de graphical interface of the debugger is
15949 @smallexample
15950 $ gvd program
15951 @end smallexample
15952
15953 @noindent
15954 The command to run @code{GDB} in text mode is
15955
15956 @smallexample
15957 $ gdb program
15958 @end smallexample
15959
15960 @noindent
15961 where @code{program} is the name of the executable file. This
15962 activates the debugger and results in a prompt for debugger commands.
15963 The simplest command is simply @code{run}, which causes the program to run
15964 exactly as if the debugger were not present. The following section
15965 describes some of the additional commands that can be given to @code{GDB}.
15966
15967
15968 @node Introduction to GDB Commands
15969 @section Introduction to GDB Commands
15970
15971 @noindent
15972 @code{GDB} contains a large repertoire of commands. The manual
15973 @cite{Debugging with GDB}
15974 includes extensive documentation on the use
15975 of these commands, together with examples of their use. Furthermore,
15976 the command @var{help} invoked from within @code{GDB} activates a simple help
15977 facility which summarizes the available commands and their options.
15978 In this section we summarize a few of the most commonly
15979 used commands to give an idea of what @code{GDB} is about. You should create
15980 a simple program with debugging information and experiment with the use of
15981 these @code{GDB} commands on the program as you read through the
15982 following section.
15983
15984 @table @code
15985 @item set args @var{arguments}
15986 The @var{arguments} list above is a list of arguments to be passed to
15987 the program on a subsequent run command, just as though the arguments
15988 had been entered on a normal invocation of the program. The @code{set args}
15989 command is not needed if the program does not require arguments.
15990
15991 @item run
15992 The @code{run} command causes execution of the program to start from
15993 the beginning. If the program is already running, that is to say if
15994 you are currently positioned at a breakpoint, then a prompt will ask
15995 for confirmation that you want to abandon the current execution and
15996 restart.
15997
15998 @item breakpoint @var{location}
15999 The breakpoint command sets a breakpoint, that is to say a point at which
16000 execution will halt and @code{GDB} will await further
16001 commands. @var{location} is
16002 either a line number within a file, given in the format @code{file:linenumber},
16003 or it is the name of a subprogram. If you request that a breakpoint be set on
16004 a subprogram that is overloaded, a prompt will ask you to specify on which of
16005 those subprograms you want to breakpoint. You can also
16006 specify that all of them should be breakpointed. If the program is run
16007 and execution encounters the breakpoint, then the program
16008 stops and @code{GDB} signals that the breakpoint was encountered by
16009 printing the line of code before which the program is halted.
16010
16011 @item breakpoint exception @var{name}
16012 A special form of the breakpoint command which breakpoints whenever
16013 exception @var{name} is raised.
16014 If @var{name} is omitted,
16015 then a breakpoint will occur when any exception is raised.
16016
16017 @item print @var{expression}
16018 This will print the value of the given expression. Most simple
16019 Ada expression formats are properly handled by @code{GDB}, so the expression
16020 can contain function calls, variables, operators, and attribute references.
16021
16022 @item continue
16023 Continues execution following a breakpoint, until the next breakpoint or the
16024 termination of the program.
16025
16026 @item step
16027 Executes a single line after a breakpoint. If the next statement is a subprogram
16028 call, execution continues into (the first statement of) the
16029 called subprogram.
16030
16031 @item next
16032 Executes a single line. If this line is a subprogram call, executes and
16033 returns from the call.
16034
16035 @item list
16036 Lists a few lines around the current source location. In practice, it
16037 is usually more convenient to have a separate edit window open with the
16038 relevant source file displayed. Successive applications of this command
16039 print subsequent lines. The command can be given an argument which is a
16040 line number, in which case it displays a few lines around the specified one.
16041
16042 @item backtrace
16043 Displays a backtrace of the call chain. This command is typically
16044 used after a breakpoint has occurred, to examine the sequence of calls that
16045 leads to the current breakpoint. The display includes one line for each
16046 activation record (frame) corresponding to an active subprogram.
16047
16048 @item up
16049 At a breakpoint, @code{GDB} can display the values of variables local
16050 to the current frame. The command @code{up} can be used to
16051 examine the contents of other active frames, by moving the focus up
16052 the stack, that is to say from callee to caller, one frame at a time.
16053
16054 @item down
16055 Moves the focus of @code{GDB} down from the frame currently being
16056 examined to the frame of its callee (the reverse of the previous command),
16057
16058 @item frame @var{n}
16059 Inspect the frame with the given number. The value 0 denotes the frame
16060 of the current breakpoint, that is to say the top of the call stack.
16061
16062 @end table
16063
16064 The above list is a very short introduction to the commands that
16065 @code{GDB} provides. Important additional capabilities, including conditional
16066 breakpoints, the ability to execute command sequences on a breakpoint,
16067 the ability to debug at the machine instruction level and many other
16068 features are described in detail in @cite{Debugging with GDB}.
16069 Note that most commands can be abbreviated
16070 (for example, c for continue, bt for backtrace).
16071
16072 @node Using Ada Expressions
16073 @section Using Ada Expressions
16074 @cindex Ada expressions
16075
16076 @noindent
16077 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
16078 extensions. The philosophy behind the design of this subset is
16079
16080 @itemize @bullet
16081 @item
16082 That @code{GDB} should provide basic literals and access to operations for
16083 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
16084 leaving more sophisticated computations to subprograms written into the
16085 program (which therefore may be called from @code{GDB}).
16086
16087 @item
16088 That type safety and strict adherence to Ada language restrictions
16089 are not particularly important to the @code{GDB} user.
16090
16091 @item
16092 That brevity is important to the @code{GDB} user.
16093 @end itemize
16094
16095 Thus, for brevity, the debugger acts as if there were
16096 implicit @code{with} and @code{use} clauses in effect for all user-written
16097 packages, thus making it unnecessary to fully qualify most names with
16098 their packages, regardless of context. Where this causes ambiguity,
16099 @code{GDB} asks the user's intent.
16100
16101 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
16102
16103 @node Calling User-Defined Subprograms
16104 @section Calling User-Defined Subprograms
16105
16106 @noindent
16107 An important capability of @code{GDB} is the ability to call user-defined
16108 subprograms while debugging. This is achieved simply by entering
16109 a subprogram call statement in the form:
16110
16111 @smallexample
16112 call subprogram-name (parameters)
16113 @end smallexample
16114
16115 @noindent
16116 The keyword @code{call} can be omitted in the normal case where the
16117 @code{subprogram-name} does not coincide with any of the predefined
16118 @code{GDB} commands.
16119
16120 The effect is to invoke the given subprogram, passing it the
16121 list of parameters that is supplied. The parameters can be expressions and
16122 can include variables from the program being debugged. The
16123 subprogram must be defined
16124 at the library level within your program, and @code{GDB} will call the
16125 subprogram within the environment of your program execution (which
16126 means that the subprogram is free to access or even modify variables
16127 within your program).
16128
16129 The most important use of this facility is in allowing the inclusion of
16130 debugging routines that are tailored to particular data structures
16131 in your program. Such debugging routines can be written to provide a suitably
16132 high-level description of an abstract type, rather than a low-level dump
16133 of its physical layout. After all, the standard
16134 @code{GDB print} command only knows the physical layout of your
16135 types, not their abstract meaning. Debugging routines can provide information
16136 at the desired semantic level and are thus enormously useful.
16137
16138 For example, when debugging GNAT itself, it is crucial to have access to
16139 the contents of the tree nodes used to represent the program internally.
16140 But tree nodes are represented simply by an integer value (which in turn
16141 is an index into a table of nodes).
16142 Using the @code{print} command on a tree node would simply print this integer
16143 value, which is not very useful. But the PN routine (defined in file
16144 treepr.adb in the GNAT sources) takes a tree node as input, and displays
16145 a useful high level representation of the tree node, which includes the
16146 syntactic category of the node, its position in the source, the integers
16147 that denote descendant nodes and parent node, as well as varied
16148 semantic information. To study this example in more detail, you might want to
16149 look at the body of the PN procedure in the stated file.
16150
16151 @node Using the Next Command in a Function
16152 @section Using the Next Command in a Function
16153
16154 @noindent
16155 When you use the @code{next} command in a function, the current source
16156 location will advance to the next statement as usual. A special case
16157 arises in the case of a @code{return} statement.
16158
16159 Part of the code for a return statement is the "epilog" of the function.
16160 This is the code that returns to the caller. There is only one copy of
16161 this epilog code, and it is typically associated with the last return
16162 statement in the function if there is more than one return. In some
16163 implementations, this epilog is associated with the first statement
16164 of the function.
16165
16166 The result is that if you use the @code{next} command from a return
16167 statement that is not the last return statement of the function you
16168 may see a strange apparent jump to the last return statement or to
16169 the start of the function. You should simply ignore this odd jump.
16170 The value returned is always that from the first return statement
16171 that was stepped through.
16172
16173 @node Ada Exceptions
16174 @section Breaking on Ada Exceptions
16175 @cindex Exceptions
16176
16177 @noindent
16178 You can set breakpoints that trip when your program raises
16179 selected exceptions.
16180
16181 @table @code
16182 @item break exception
16183 Set a breakpoint that trips whenever (any task in the) program raises
16184 any exception.
16185
16186 @item break exception @var{name}
16187 Set a breakpoint that trips whenever (any task in the) program raises
16188 the exception @var{name}.
16189
16190 @item break exception unhandled
16191 Set a breakpoint that trips whenever (any task in the) program raises an
16192 exception for which there is no handler.
16193
16194 @item info exceptions
16195 @itemx info exceptions @var{regexp}
16196 The @code{info exceptions} command permits the user to examine all defined
16197 exceptions within Ada programs. With a regular expression, @var{regexp}, as
16198 argument, prints out only those exceptions whose name matches @var{regexp}.
16199 @end table
16200
16201 @node Ada Tasks
16202 @section Ada Tasks
16203 @cindex Tasks
16204
16205 @noindent
16206 @code{GDB} allows the following task-related commands:
16207
16208 @table @code
16209 @item info tasks
16210 This command shows a list of current Ada tasks, as in the following example:
16211
16212 @smallexample
16213 @iftex
16214 @leftskip=0cm
16215 @end iftex
16216 (gdb) info tasks
16217   ID       TID P-ID   Thread Pri State                 Name
16218    1   8088000   0   807e000  15 Child Activation Wait main_task
16219    2   80a4000   1   80ae000  15 Accept/Select Wait    b
16220    3   809a800   1   80a4800  15 Child Activation Wait a
16221 *  4   80ae800   3   80b8000  15 Running               c
16222 @end smallexample
16223
16224 @noindent
16225 In this listing, the asterisk before the first task indicates it to be the
16226 currently running task. The first column lists the task ID that is used
16227 to refer to tasks in the following commands.
16228
16229 @item break @var{linespec} task @var{taskid}
16230 @itemx break @var{linespec} task @var{taskid} if @dots{}
16231 @cindex Breakpoints and tasks
16232 These commands are like the @code{break @dots{} thread @dots{}}.
16233 @var{linespec} specifies source lines.
16234
16235 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
16236 to specify that you only want @code{GDB} to stop the program when a
16237 particular Ada task reaches this breakpoint. @var{taskid} is one of the
16238 numeric task identifiers assigned by @code{GDB}, shown in the first
16239 column of the @samp{info tasks} display.
16240
16241 If you do not specify @samp{task @var{taskid}} when you set a
16242 breakpoint, the breakpoint applies to @emph{all} tasks of your
16243 program.
16244
16245 You can use the @code{task} qualifier on conditional breakpoints as
16246 well; in this case, place @samp{task @var{taskid}} before the
16247 breakpoint condition (before the @code{if}).
16248
16249 @item task @var{taskno}
16250 @cindex Task switching
16251
16252 This command allows to switch to the task referred by @var{taskno}. In
16253 particular, This allows to browse the backtrace of the specified
16254 task. It is advised to switch back to the original task before
16255 continuing execution otherwise the scheduling of the program may be
16256 perturbated.
16257 @end table
16258
16259 @noindent
16260 For more detailed information on the tasking support, see @cite{Debugging with GDB}.
16261
16262 @node Debugging Generic Units
16263 @section Debugging Generic Units
16264 @cindex Debugging Generic Units
16265 @cindex Generics
16266
16267 @noindent
16268 GNAT always uses code expansion for generic instantiation. This means that
16269 each time an instantiation occurs, a complete copy of the original code is
16270 made, with appropriate substitutions of formals by actuals.
16271
16272 It is not possible to refer to the original generic entities in
16273 @code{GDB}, but it is always possible to debug a particular instance of
16274 a generic, by using the appropriate expanded names. For example, if we have
16275
16276 @smallexample
16277 @group
16278 @cartouche
16279 @b{procedure} g @b{is}
16280
16281    @b{generic package} k @b{is}
16282       @b{procedure} kp (v1 : @b{in out} integer);
16283    @b{end} k;
16284
16285    @b{package body} k @b{is}
16286       @b{procedure} kp (v1 : @b{in out} integer) @b{is}
16287       @b{begin}
16288          v1 := v1 + 1;
16289       @b{end} kp;
16290    @b{end} k;
16291
16292    @b{package} k1 @b{is new} k;
16293    @b{package} k2 @b{is new} k;
16294
16295    var : integer := 1;
16296
16297 @b{begin}
16298    k1.kp (var);
16299    k2.kp (var);
16300    k1.kp (var);
16301    k2.kp (var);
16302 @b{end};
16303 @end cartouche
16304 @end group
16305 @end smallexample
16306
16307 @noindent
16308 Then to break on a call to procedure kp in the k2 instance, simply
16309 use the command:
16310
16311 @smallexample
16312 (gdb) break g.k2.kp
16313 @end smallexample
16314
16315 @noindent
16316 When the breakpoint occurs, you can step through the code of the
16317 instance in the normal manner and examine the values of local variables, as for
16318 other units.
16319
16320 @node GNAT Abnormal Termination or Failure to Terminate
16321 @section GNAT Abnormal Termination or Failure to Terminate
16322 @cindex GNAT Abnormal Termination or Failure to Terminate
16323
16324 @noindent
16325 When presented with programs that contain serious errors in syntax
16326 or semantics,
16327 GNAT may on rare occasions  experience problems in operation, such
16328 as aborting with a
16329 segmentation fault or illegal memory access, raising an internal
16330 exception, terminating abnormally, or failing to terminate at all.
16331 In such cases, you can activate
16332 various features of GNAT that can help you pinpoint the construct in your
16333 program that is the likely source of the problem.
16334
16335 The following strategies are presented in increasing order of
16336 difficulty, corresponding to your experience in using GNAT and your
16337 familiarity with compiler internals.
16338
16339 @enumerate
16340 @item
16341 Run @code{gcc} with the @option{-gnatf}. This first
16342 switch causes all errors on a given line to be reported. In its absence,
16343 only the first error on a line is displayed.
16344
16345 The @option{-gnatdO} switch causes errors to be displayed as soon as they
16346 are encountered, rather than after compilation is terminated. If GNAT
16347 terminates prematurely or goes into an infinite loop, the last error
16348 message displayed may help to pinpoint the culprit.
16349
16350 @item
16351 Run @code{gcc} with the @code{-v (verbose)} switch. In this mode,
16352 @code{gcc} produces ongoing information about the progress of the
16353 compilation and provides the name of each procedure as code is
16354 generated. This switch allows you to find which Ada procedure was being
16355 compiled when it encountered a code generation problem.
16356
16357 @item
16358 @cindex @option{-gnatdc} switch
16359 Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
16360 switch that does for the front-end what @code{-v} does for the back end.
16361 The system prints the name of each unit, either a compilation unit or
16362 nested unit, as it is being analyzed.
16363 @item
16364 Finally, you can start
16365 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
16366 front-end of GNAT, and can be run independently (normally it is just
16367 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
16368 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
16369 @code{where} command is the first line of attack; the variable
16370 @code{lineno} (seen by @code{print lineno}), used by the second phase of
16371 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
16372 which the execution stopped, and @code{input_file name} indicates the name of
16373 the source file.
16374 @end enumerate
16375
16376 @node Naming Conventions for GNAT Source Files
16377 @section Naming Conventions for GNAT Source Files
16378
16379 @noindent
16380 In order to examine the workings of the GNAT system, the following
16381 brief description of its organization may be helpful:
16382
16383 @itemize @bullet
16384 @item
16385 Files with prefix @file{sc} contain the lexical scanner.
16386
16387 @item
16388 All files prefixed with @file{par} are components of the parser. The
16389 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
16390 parsing of select statements can be found in @file{par-ch9.adb}.
16391
16392 @item
16393 All files prefixed with @file{sem} perform semantic analysis. The
16394 numbers correspond to chapters of the Ada standard. For example, all
16395 issues involving context clauses can be found in @file{sem_ch10.adb}. In
16396 addition, some features of the language require sufficient special processing
16397 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
16398 dynamic dispatching, etc.
16399
16400 @item
16401 All files prefixed with @file{exp} perform normalization and
16402 expansion of the intermediate representation (abstract syntax tree, or AST).
16403 these files use the same numbering scheme as the parser and semantics files.
16404 For example, the construction of record initialization procedures is done in
16405 @file{exp_ch3.adb}.
16406
16407 @item
16408 The files prefixed with @file{bind} implement the binder, which
16409 verifies the consistency of the compilation, determines an order of
16410 elaboration, and generates the bind file.
16411
16412 @item
16413 The files @file{atree.ads} and @file{atree.adb} detail the low-level
16414 data structures used by the front-end.
16415
16416 @item
16417 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
16418 the abstract syntax tree as produced by the parser.
16419
16420 @item
16421 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
16422 all entities, computed during semantic analysis.
16423
16424 @item
16425 Library management issues are dealt with in files with prefix
16426 @file{lib}.
16427
16428 @item
16429 @findex Ada
16430 @cindex Annex A
16431 Ada files with the prefix @file{a-} are children of @code{Ada}, as
16432 defined in Annex A.
16433
16434 @item
16435 @findex Interfaces
16436 @cindex Annex B
16437 Files with prefix @file{i-} are children of @code{Interfaces}, as
16438 defined in Annex B.
16439
16440 @item
16441 @findex System
16442 Files with prefix @file{s-} are children of @code{System}. This includes
16443 both language-defined children and GNAT run-time routines.
16444
16445 @item
16446 @findex GNAT
16447 Files with prefix @file{g-} are children of @code{GNAT}. These are useful
16448 general-purpose packages, fully documented in their specifications. All
16449 the other @file{.c} files are modifications of common @code{gcc} files.
16450 @end itemize
16451
16452 @node Getting Internal Debugging Information
16453 @section Getting Internal Debugging Information
16454
16455 @noindent
16456 Most compilers have internal debugging switches and modes. GNAT
16457 does also, except GNAT internal debugging switches and modes are not
16458 secret. A summary and full description of all the compiler and binder
16459 debug flags are in the file @file{debug.adb}. You must obtain the
16460 sources of the compiler to see the full detailed effects of these flags.
16461
16462 The switches that print the source of the program (reconstructed from
16463 the internal tree) are of general interest for user programs, as are the
16464 options to print
16465 the full internal tree, and the entity table (the symbol table
16466 information). The reconstructed source provides a readable version of the
16467 program after the front-end has completed analysis and  expansion, and is useful
16468 when studying the performance of specific constructs. For example, constraint
16469 checks are indicated, complex aggregates are replaced with loops and
16470 assignments, and tasking primitives are replaced with run-time calls.
16471
16472 @node Stack Traceback
16473 @section Stack Traceback
16474 @cindex traceback
16475 @cindex stack traceback
16476 @cindex stack unwinding
16477
16478 @noindent
16479 Traceback is a mechanism to display the sequence of subprogram calls that
16480 leads to a specified execution point in a program. Often (but not always)
16481 the execution point is an instruction at which an exception has been raised.
16482 This mechanism is also known as @i{stack unwinding} because it obtains
16483 its information by scanning the run-time stack and recovering the activation
16484 records of all active subprograms. Stack unwinding is one of the most
16485 important tools for program debugging.
16486
16487 @noindent
16488 The first entry stored in traceback corresponds to the deepest calling level,
16489 that is to say the subprogram currently executing the instruction
16490 from which we want to obtain the traceback.
16491
16492 @noindent
16493 Note that there is no runtime performance penalty when stack traceback
16494 is enabled and no exception are raised during program execution.
16495
16496 @menu
16497 * Non-Symbolic Traceback::
16498 * Symbolic Traceback::
16499 @end menu
16500
16501 @node Non-Symbolic Traceback
16502 @subsection Non-Symbolic Traceback
16503 @cindex traceback, non-symbolic
16504
16505 @noindent
16506 Note: this feature is not supported on all platforms. See
16507 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
16508 platforms.
16509
16510 @menu
16511 * Tracebacks From an Unhandled Exception::
16512 * Tracebacks From Exception Occurrences (non-symbolic)::
16513 * Tracebacks From Anywhere in a Program (non-symbolic)::
16514 @end menu
16515
16516 @node Tracebacks From an Unhandled Exception
16517 @subsubsection Tracebacks From an Unhandled Exception
16518
16519 @noindent
16520 A runtime non-symbolic traceback is a list of addresses of call instructions.
16521 To enable this feature you must use the @code{-E}
16522 @code{gnatbind}'s option. With this option a stack traceback is stored as part
16523 of exception information. It is possible to retrieve this information using the
16524 standard @code{Ada.Exception.Exception_Information} routine.
16525
16526 @noindent
16527 Let's have a look at a simple example:
16528
16529 @smallexample
16530 @cartouche
16531 @group
16532 procedure STB is
16533
16534    procedure P1 is
16535    begin
16536       raise Constraint_Error;
16537    end P1;
16538
16539    procedure P2 is
16540    begin
16541       P1;
16542    end P2;
16543
16544 begin
16545    P2;
16546 end STB;
16547 @end group
16548 @end cartouche
16549 @end smallexample
16550
16551 @smallexample
16552 $ gnatmake stb -bargs -E
16553 $ stb
16554
16555 Execution terminated by unhandled exception
16556 Exception name: CONSTRAINT_ERROR
16557 Message: stb.adb:5
16558 Call stack traceback locations:
16559 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
16560 @end smallexample
16561
16562 @noindent
16563 As we see the traceback lists a sequence of addresses for the unhandled
16564 exception @code{CONSTAINT_ERROR} raised in procedure P1. It is easy to
16565 guess that this exception come from procedure P1. To translate these
16566 addresses into the source lines where the calls appear, the
16567 @code{addr2line} tool, described below, is invaluable. The use of this tool
16568 requires the program to be compiled with debug information.
16569
16570 @smallexample
16571 $ gnatmake -g stb -bargs -E
16572 $ stb
16573
16574 Execution terminated by unhandled exception
16575 Exception name: CONSTRAINT_ERROR
16576 Message: stb.adb:5
16577 Call stack traceback locations:
16578 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
16579
16580 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
16581    0x4011f1 0x77e892a4
16582
16583 00401373 at d:/stb/stb.adb:5
16584 0040138B at d:/stb/stb.adb:10
16585 0040139C at d:/stb/stb.adb:14
16586 00401335 at d:/stb/b~stb.adb:104
16587 004011C4 at /build/.../crt1.c:200
16588 004011F1 at /build/.../crt1.c:222
16589 77E892A4 in ?? at ??:0
16590 @end smallexample
16591
16592 @noindent
16593 @code{addr2line} has a number of other useful options:
16594
16595 @table @code
16596 @item --functions
16597 to get the function name corresponding to any location
16598
16599 @item --demangle=gnat
16600 to use the @b{gnat} decoding mode for the function names. Note that
16601 for binutils version 2.9.x the option is simply @code{--demangle}.
16602 @end table
16603
16604 @smallexample
16605 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
16606    0x40139c 0x401335 0x4011c4 0x4011f1
16607
16608 00401373 in stb.p1 at d:/stb/stb.adb:5
16609 0040138B in stb.p2 at d:/stb/stb.adb:10
16610 0040139C in stb at d:/stb/stb.adb:14
16611 00401335 in main at d:/stb/b~stb.adb:104
16612 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
16613 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
16614 @end smallexample
16615
16616 @noindent
16617 From this traceback we can see that the exception was raised in
16618 @file{stb.adb} at line 5, which was reached from a procedure call in
16619 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
16620 which contains the call to the main program.
16621 @pxref{Running gnatbind}. The remaining entries are assorted runtime routines,
16622 and the output will vary from platform to platform.
16623
16624 @noindent
16625 It is also possible to use @code{GDB} with these traceback addresses to debug
16626 the program. For example, we can break at a given code location, as reported
16627 in the stack traceback:
16628
16629 @smallexample
16630 $ gdb -nw stb
16631
16632 (gdb) break *0x401373
16633 Breakpoint 1 at 0x401373: file stb.adb, line 5.
16634 @end smallexample
16635
16636 @noindent
16637 It is important to note that the stack traceback addresses
16638 do not change when debug information is included. This is particularly useful
16639 because it makes it possible to release software without debug information (to
16640 minimize object size), get a field report that includes a stack traceback
16641 whenever an internal bug occurs, and then be able to retrieve the sequence
16642 of calls with the same program compiled with debug information.
16643
16644 @node Tracebacks From Exception Occurrences (non-symbolic)
16645 @subsubsection Tracebacks From Exception Occurrences
16646
16647 @noindent
16648 Non-symbolic tracebacks are obtained by using the @code{-E} binder argument.
16649 The stack traceback is attached to the exception information string, and can
16650 be retrieved in an exception handler within the Ada program, by means of the
16651 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
16652
16653 @smallexample
16654 @cartouche
16655 @group
16656 with Ada.Text_IO;
16657 with Ada.Exceptions;
16658
16659 procedure STB is
16660
16661    use Ada;
16662    use Ada.Exceptions;
16663
16664    procedure P1 is
16665       K : Positive := 1;
16666    begin
16667       K := K - 1;
16668    exception
16669       when E : others =>
16670          Text_IO.Put_Line (Exception_Information (E));
16671    end P1;
16672
16673    procedure P2 is
16674    begin
16675       P1;
16676    end P2;
16677
16678 begin
16679    P2;
16680 end STB;
16681 @end group
16682 @end cartouche
16683 @end smallexample
16684
16685 @noindent
16686 This program will output:
16687
16688 @smallexample
16689 $ stb
16690
16691 Exception name: CONSTRAINT_ERROR
16692 Message: stb.adb:12
16693 Call stack traceback locations:
16694 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
16695 @end smallexample
16696
16697 @node Tracebacks From Anywhere in a Program (non-symbolic)
16698 @subsubsection Tracebacks From Anywhere in a Program
16699
16700 @noindent
16701 It is also possible to retrieve a stack traceback from anywhere in a
16702 program. For this you need to
16703 use the @code{GNAT.Traceback} API. This package includes a procedure called
16704 @code{Call_Chain} that computes a complete stack traceback, as well as useful
16705 display procedures described below. It is not necessary to use the
16706 @code{-E gnatbind} option in this case, because the stack traceback mechanism
16707 is invoked explicitly.
16708
16709 @noindent
16710 In the following example we compute a traceback at a specific location in
16711 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
16712 convert addresses to strings:
16713
16714 @smallexample
16715 @cartouche
16716 @group
16717 with Ada.Text_IO;
16718 with GNAT.Traceback;
16719 with GNAT.Debug_Utilities;
16720
16721 procedure STB is
16722
16723    use Ada;
16724    use GNAT;
16725    use GNAT.Traceback;
16726
16727    procedure P1 is
16728       TB  : Tracebacks_Array (1 .. 10);
16729       --  We are asking for a maximum of 10 stack frames.
16730       Len : Natural;
16731       --  Len will receive the actual number of stack frames returned.
16732    begin
16733       Call_Chain (TB, Len);
16734
16735       Text_IO.Put ("In STB.P1 : ");
16736
16737       for K in 1 .. Len loop
16738          Text_IO.Put (Debug_Utilities.Image (TB (K)));
16739          Text_IO.Put (' ');
16740       end loop;
16741
16742       Text_IO.New_Line;
16743    end P1;
16744
16745    procedure P2 is
16746    begin
16747       P1;
16748    end P2;
16749
16750 begin
16751    P2;
16752 end STB;
16753 @end group
16754 @end cartouche
16755 @end smallexample
16756
16757 @smallexample
16758 $ gnatmake stb
16759 $ stb
16760
16761 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
16762 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
16763 @end smallexample
16764
16765 @node Symbolic Traceback
16766 @subsection Symbolic Traceback
16767 @cindex traceback, symbolic
16768
16769 @noindent
16770 A symbolic traceback is a stack traceback in which procedure names are
16771 associated with each code location.
16772
16773 @noindent
16774 Note that this feature is not supported on all platforms. See
16775 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
16776 list of currently supported platforms.
16777
16778 @noindent
16779 Note that the symbolic traceback requires that the program be compiled
16780 with debug information. If it is not compiled with debug information
16781 only the non-symbolic information will be valid.
16782
16783 @menu
16784 * Tracebacks From Exception Occurrences (symbolic)::
16785 * Tracebacks From Anywhere in a Program (symbolic)::
16786 @end menu
16787
16788 @node Tracebacks From Exception Occurrences (symbolic)
16789 @subsubsection Tracebacks From Exception Occurrences
16790
16791 @smallexample
16792 @cartouche
16793 @group
16794 with Ada.Text_IO;
16795 with GNAT.Traceback.Symbolic;
16796
16797 procedure STB is
16798
16799    procedure P1 is
16800    begin
16801       raise Constraint_Error;
16802    end P1;
16803
16804    procedure P2 is
16805    begin
16806       P1;
16807    end P2;
16808
16809    procedure P3 is
16810    begin
16811       P2;
16812    end P3;
16813
16814 begin
16815    P3;
16816 exception
16817    when E : others =>
16818       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
16819 end STB;
16820 @end group
16821 @end cartouche
16822 @end smallexample
16823
16824 @smallexample
16825 $ gnatmake -g stb -bargs -E -largs -lgnat -laddr2line -lintl
16826 $ stb
16827
16828 0040149F in stb.p1 at stb.adb:8
16829 004014B7 in stb.p2 at stb.adb:13
16830 004014CF in stb.p3 at stb.adb:18
16831 004015DD in ada.stb at stb.adb:22
16832 00401461 in main at b~stb.adb:168
16833 004011C4 in __mingw_CRTStartup at crt1.c:200
16834 004011F1 in mainCRTStartup at crt1.c:222
16835 77E892A4 in ?? at ??:0
16836 @end smallexample
16837
16838 @noindent
16839 The exact sequence of linker options may vary from platform to platform.
16840 The above @code{-largs} section is for Windows platforms. By contrast,
16841 under Unix there is no need for the @code{-largs} section.
16842 Differences across platforms are due to details of linker implementation.
16843
16844 @node Tracebacks From Anywhere in a Program (symbolic)
16845 @subsubsection Tracebacks From Anywhere in a Program
16846
16847 @noindent
16848 It is possible to get a symbolic stack traceback
16849 from anywhere in a program, just as for non-symbolic tracebacks.
16850 The first step is to obtain a non-symbolic
16851 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
16852 information. Here is an example:
16853
16854 @smallexample
16855 @cartouche
16856 @group
16857 with Ada.Text_IO;
16858 with GNAT.Traceback;
16859 with GNAT.Traceback.Symbolic;
16860
16861 procedure STB is
16862
16863    use Ada;
16864    use GNAT.Traceback;
16865    use GNAT.Traceback.Symbolic;
16866
16867    procedure P1 is
16868       TB  : Tracebacks_Array (1 .. 10);
16869       --  We are asking for a maximum of 10 stack frames.
16870       Len : Natural;
16871       --  Len will receive the actual number of stack frames returned.
16872    begin
16873       Call_Chain (TB, Len);
16874       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
16875    end P1;
16876
16877    procedure P2 is
16878    begin
16879       P1;
16880    end P2;
16881
16882 begin
16883    P2;
16884 end STB;
16885 @end group
16886 @end cartouche
16887 @end smallexample
16888
16889
16890 @node Inline Assembler
16891 @chapter Inline Assembler
16892
16893 @noindent
16894 If you need to write low-level software that interacts directly with the hardware, Ada provides two ways to incorporate assembly language code into your program.  First, you can import and invoke external routines written in assembly language, an Ada feature fully supported by GNAT.  However, for small sections of code it may be simpler or more efficient to include assembly language statements directly in your Ada source program, using the facilities of the implementation-defined package @code{System.Machine_Code}, which incorporates the gcc Inline Assembler.  The Inline Assembler approach offers a number of advantages, including the following:
16895
16896 @itemize @bullet
16897 @item No need to use non-Ada tools
16898 @item Consistent interface over different targets
16899 @item Automatic usage of the proper calling conventions
16900 @item Access to Ada constants and variables
16901 @item Definition of intrinsic routines
16902 @item Possibility of inlining a subprogram comprising assembler code
16903 @item Code optimizer can take Inline Assembler code into account
16904 @end itemize
16905
16906 This chapter presents a series of examples to show you how to use the Inline Assembler.  Although it focuses on the Intel x86, the general approach applies also to other processors.  It is assumed that you are familiar with Ada and with assembly language programming.
16907
16908 @menu
16909 * Basic Assembler Syntax::
16910 * A Simple Example of Inline Assembler::
16911 * Output Variables in Inline Assembler::
16912 * Input Variables in Inline Assembler::
16913 * Inlining Inline Assembler Code::
16914 * Other Asm Functionality::
16915 * A Complete Example::
16916 @end menu
16917
16918 @c ---------------------------------------------------------------------------
16919 @node Basic Assembler Syntax
16920 @section Basic Assembler Syntax
16921
16922 @noindent
16923 The assembler used by GNAT and gcc is based not on the Intel assembly language, but rather on a
16924 language that descends from the AT&T Unix assembler @emph{as} (and which is often
16925 referred to as ``AT&T syntax'').
16926 The following table summarizes the main features of @emph{as} syntax and points out the differences from the Intel conventions.
16927 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
16928 pre-processor) documentation for further information.
16929
16930 @table @asis
16931 @item Register names
16932 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
16933 @*
16934 Intel: No extra punctuation; for example @code{eax}
16935
16936 @item Immediate operand
16937 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
16938 @*
16939 Intel: No extra punctuation; for example @code{4}
16940
16941 @item Address
16942 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
16943 @*
16944 Intel: No extra punctuation; for example @code{loc}
16945
16946 @item Memory contents
16947 gcc / @emph{as}: No extra punctuation; for example @code{loc}
16948 @*
16949 Intel: Square brackets; for example @code{[loc]}
16950
16951 @item Register contents
16952 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
16953 @*
16954 Intel: Square brackets; for example @code{[eax]}
16955
16956 @item Hexadecimal numbers
16957 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
16958 @*
16959 Intel: Trailing ``h''; for example @code{A0h}
16960
16961 @item Operand size
16962 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move a 16-bit word
16963 @*
16964 Intel: Implicit, deduced by assembler; for example @code{mov}
16965
16966 @item Instruction repetition
16967 gcc / @emph{as}: Split into two lines; for example
16968 @*
16969 @code{rep}
16970 @*
16971 @code{stosl}
16972 @*
16973 Intel: Keep on one line; for example @code{rep stosl}
16974
16975 @item Order of operands
16976 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
16977 @*
16978 Intel: Destination first; for example @code{mov eax, 4}
16979 @end table
16980
16981 @c ---------------------------------------------------------------------------
16982 @node A Simple Example of Inline Assembler
16983 @section A Simple Example of Inline Assembler
16984
16985 @noindent
16986 The following example will generate a single assembly language statement, @code{nop}, which does nothing.  Despite its lack of run-time effect, the example will be useful in illustrating the basics of the Inline Assembler facility.
16987
16988 @smallexample
16989 @group
16990 with System.Machine_Code; use System.Machine_Code;
16991 procedure Nothing is
16992 begin
16993    Asm ("nop");
16994 end Nothing;
16995 @end group
16996 @end smallexample
16997
16998 @code{Asm} is a procedure declared in package @code{System.Machine_Code}; here it takes one parameter, a @emph{template string} that must be a static expression and that will form the generated instruction.
16999 @code{Asm} may be regarded as a compile-time procedure that parses the template string and additional parameters (none here), from which it generates a sequence of assembly language instructions.
17000
17001 The examples in this chapter will illustrate several of the forms for invoking @code{Asm}; a complete specification of the syntax is found in the @cite{GNAT Reference Manual}.
17002
17003 Under the standard GNAT conventions, the @code{Nothing} procedure should be in a file named @file{nothing.adb}.  You can build the executable in the usual way:
17004 @smallexample
17005 gnatmake nothing
17006 @end smallexample
17007 However, the interesting aspect of this example is not its run-time behavior but rather the
17008 generated assembly code.  To see this output, invoke the compiler as follows:
17009 @smallexample
17010    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
17011 @end smallexample
17012 where the options are:
17013
17014 @table @code
17015 @item -c
17016 compile only (no bind or link)
17017 @item -S
17018 generate assembler listing
17019 @item -fomit-frame-pointer
17020 do not set up separate stack frames
17021 @item -gnatp
17022 do not add runtime checks
17023 @end table
17024
17025 This gives a human-readable assembler version of the code. The resulting
17026 file will have the same name as the Ada source file, but with a @code{.s} extension.
17027 In our example, the file @file{nothing.s} has the following contents:
17028
17029 @smallexample
17030 @group
17031 .file "nothing.adb"
17032 gcc2_compiled.:
17033 ___gnu_compiled_ada:
17034 .text
17035    .align 4
17036 .globl __ada_nothing
17037 __ada_nothing:
17038 #APP
17039    nop
17040 #NO_APP
17041    jmp L1
17042    .align 2,0x90
17043 L1:
17044    ret
17045 @end group
17046 @end smallexample
17047
17048 The assembly code you included is clearly indicated by
17049 the compiler, between the @code{#APP} and @code{#NO_APP}
17050 delimiters. The character before the 'APP' and 'NOAPP'
17051 can differ on different targets. For example, Linux uses '#APP' while
17052 on NT you will see '/APP'.
17053
17054 If you make a mistake in your assembler code (such as using the
17055 wrong size modifier, or using a wrong operand for the instruction) GNAT
17056 will report this error in a temporary file, which will be deleted when
17057 the compilation is finished.  Generating an assembler file will help
17058 in such cases, since you can assemble this file separately using the
17059 @emph{as} assembler that comes with gcc.
17060
17061 Assembling the file using the command
17062
17063 @smallexample
17064 as @file{nothing.s}
17065 @end smallexample
17066 @noindent
17067 will give you error messages whose lines correspond to the assembler
17068 input file, so you can easily find and correct any mistakes you made.
17069 If there are no errors, @emph{as} will generate an object file @file{nothing.out}.
17070
17071 @c ---------------------------------------------------------------------------
17072 @node Output Variables in Inline Assembler
17073 @section Output Variables in Inline Assembler
17074
17075 @noindent
17076 The examples in this section, showing how to access the processor flags, illustrate how to specify the destination operands for assembly language statements.
17077
17078 @smallexample
17079 @group
17080 with Interfaces; use Interfaces;
17081 with Ada.Text_IO; use Ada.Text_IO;
17082 with System.Machine_Code; use System.Machine_Code;
17083 procedure Get_Flags is
17084    Flags : Unsigned_32;
17085    use ASCII;
17086 begin
17087    Asm ("pushfl"          & LF & HT & -- push flags on stack
17088         "popl %%eax"      & LF & HT & -- load eax with flags
17089         "movl %%eax, %0",             -- store flags in variable
17090         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
17091    Put_Line ("Flags register:" & Flags'Img);
17092 end Get_Flags;
17093 @end group
17094 @end smallexample
17095
17096 In order to have a nicely aligned assembly listing, we have separated
17097 multiple assembler statements in the Asm template string with linefeed (ASCII.LF)
17098 and horizontal tab (ASCII.HT) characters.  The resulting section of the
17099 assembly output file is:
17100
17101 @smallexample
17102 @group
17103 #APP
17104    pushfl
17105    popl %eax
17106    movl %eax, -40(%ebp)
17107 #NO_APP
17108 @end group
17109 @end smallexample
17110
17111 It would have been legal to write the Asm invocation as:
17112
17113 @smallexample
17114 Asm ("pushfl popl %%eax movl %%eax, %0")
17115 @end smallexample
17116
17117 but in the generated assembler file, this would come out as:
17118
17119 @smallexample
17120 #APP
17121    pushfl popl %eax movl %eax, -40(%ebp)
17122 #NO_APP
17123 @end smallexample
17124
17125 which is not so convenient for the human reader.
17126
17127 We use Ada comments
17128 at the end of each line to explain what the assembler instructions
17129 actually do.  This is a useful convention.
17130
17131 When writing Inline Assembler instructions, you need to precede each register and variable name with a percent sign.  Since the assembler already requires a percent sign at the beginning of a register name, you need two consecutive percent signs for such names in the Asm template string, thus @code{%%eax}.  In the generated assembly code, one of the percent signs will be stripped off.
17132
17133 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output variables: operands you later define using @code{Input} or @code{Output} parameters to @code{Asm}.
17134 An output variable is illustrated in
17135 the third statement in the Asm template string:
17136 @smallexample
17137 movl %%eax, %0
17138 @end smallexample
17139 The intent is to store the contents of the eax register in a variable that can be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not necessarily work, since the compiler might optimize by using a register to hold Flags, and the expansion of the @code{movl} instruction would not be aware of this optimization.  The solution is not to store the result directly but rather to advise the compiler to choose the correct operand form; that is the purpose of the @code{%0} output variable.
17140
17141 Information about the output variable is supplied in the @code{Outputs} parameter to @code{Asm}:
17142 @smallexample
17143 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
17144 @end smallexample
17145
17146 The output is defined by the @code{Asm_Output} attribute of the target type; the general format is
17147 @smallexample
17148 Type'Asm_Output (constraint_string, variable_name)
17149 @end smallexample
17150
17151 The constraint string directs the compiler how
17152 to store/access the associated variable.  In the example
17153 @smallexample
17154 Unsigned_32'Asm_Output ("=m", Flags);
17155 @end smallexample
17156 the @code{"m"} (memory) constraint tells the compiler that the variable
17157 @code{Flags} should be stored in a memory variable, thus preventing
17158 the optimizer from keeping it in a register.  In contrast,
17159 @smallexample
17160 Unsigned_32'Asm_Output ("=r", Flags);
17161 @end smallexample
17162 uses the @code{"r"} (register) constraint, telling the compiler to
17163 store the variable in a register.
17164
17165 If the constraint is preceded by the equal character (@strong{=}), it tells the
17166 compiler that the variable will be used to store data into it.
17167
17168 In the @code{Get_Flags} example, we used the "g" (global) constraint, allowing the optimizer
17169 to choose whatever it deems best.
17170
17171 There are a fairly large number of constraints, but the ones that are most useful (for the Intel x86 processor) are the following:
17172
17173 @table @code
17174 @item =
17175 output constraint
17176 @item g
17177 global (i.e. can be stored anywhere)
17178 @item m
17179 in memory
17180 @item I
17181 a constant
17182 @item a
17183 use eax
17184 @item b
17185 use ebx
17186 @item c
17187 use ecx
17188 @item d
17189 use edx
17190 @item S
17191 use esi
17192 @item D
17193 use edi
17194 @item r
17195 use one of eax, ebx, ecx or edx
17196 @item q
17197 use one of eax, ebx, ecx, edx, esi or edi
17198 @end table
17199
17200 The full set of constraints is described in the gcc and @emph{as} documentation; note that it is possible to combine certain constraints in one constraint string.
17201
17202 You specify the association of an output variable with an assembler operand through the @code{%}@emph{n} notation, where @emph{n} is a non-negative integer.  Thus in
17203 @smallexample
17204 @group
17205 Asm ("pushfl"          & LF & HT & -- push flags on stack
17206      "popl %%eax"      & LF & HT & -- load eax with flags
17207      "movl %%eax, %0",             -- store flags in variable
17208      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
17209 @end group
17210 @end smallexample
17211 @noindent
17212 @code{%0} will be replaced in the expanded code by the appropriate operand,
17213 whatever
17214 the compiler decided for the @code{Flags} variable.
17215
17216 In general, you may have any number of output variables:
17217 @itemize @bullet
17218 @item
17219 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
17220 @item
17221 Specify the @code{Outputs} parameter as a parenthesized comma-separated list of @code{Asm_Output} attributes
17222 @end itemize
17223
17224 For example:
17225 @smallexample
17226 @group
17227 Asm ("movl %%eax, %0" & LF & HT &
17228      "movl %%ebx, %1" & LF & HT &
17229      "movl %%ecx, %2",
17230      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
17231                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
17232                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
17233 @end group
17234 @end smallexample
17235 @noindent
17236 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables in the Ada program.
17237
17238 As a variation on the @code{Get_Flags} example, we can use the constraints string to direct the compiler to store the eax register into the @code{Flags} variable, instead of including the store instruction explicitly in the @code{Asm} template string:
17239
17240 @smallexample
17241 @group
17242 with Interfaces; use Interfaces;
17243 with Ada.Text_IO; use Ada.Text_IO;
17244 with System.Machine_Code; use System.Machine_Code;
17245 procedure Get_Flags_2 is
17246    Flags : Unsigned_32;
17247    use ASCII;
17248 begin
17249    Asm ("pushfl"      & LF & HT & -- push flags on stack
17250         "popl %%eax",             -- save flags in eax
17251         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
17252    Put_Line ("Flags register:" & Flags'Img);
17253 end Get_Flags_2;
17254 @end group
17255 @end smallexample
17256
17257 @noindent
17258 The @code{"a"} constraint tells the compiler that the @code{Flags}
17259 variable will come from the eax register. Here is the resulting code:
17260
17261 @smallexample
17262 @group
17263 #APP
17264    pushfl
17265    popl %eax
17266 #NO_APP
17267    movl %eax,-40(%ebp)
17268 @end group
17269 @end smallexample
17270
17271 @noindent
17272 The compiler generated the store of eax into Flags after
17273 expanding the assembler code.
17274
17275 Actually, there was no need to pop the flags into the eax register; more simply, we could just pop the flags directly into the program variable:
17276
17277 @smallexample
17278 @group
17279 with Interfaces; use Interfaces;
17280 with Ada.Text_IO; use Ada.Text_IO;
17281 with System.Machine_Code; use System.Machine_Code;
17282 procedure Get_Flags_3 is
17283    Flags : Unsigned_32;
17284    use ASCII;
17285 begin
17286    Asm ("pushfl"  & LF & HT & -- push flags on stack
17287         "pop %0",             -- save flags in Flags
17288         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
17289    Put_Line ("Flags register:" & Flags'Img);
17290 end Get_Flags_3;
17291 @end group
17292 @end smallexample
17293
17294 @c ---------------------------------------------------------------------------
17295 @node Input Variables in Inline Assembler
17296 @section Input Variables in Inline Assembler
17297
17298 @noindent
17299 The example in this section illustrates how to specify the source operands for assembly language statements.  The program simply increments its input value by 1:
17300
17301 @smallexample
17302 @group
17303 with Interfaces; use Interfaces;
17304 with Ada.Text_IO; use Ada.Text_IO;
17305 with System.Machine_Code; use System.Machine_Code;
17306 procedure Increment is
17307
17308    function Incr (Value : Unsigned_32) return Unsigned_32 is
17309       Result : Unsigned_32;
17310    begin
17311       Asm ("incl %0",
17312            Inputs  => Unsigned_32'Asm_Input ("a", Value),
17313            Outputs => Unsigned_32'Asm_Output ("=a", Result));
17314       return Result;
17315    end Incr;
17316
17317    Value : Unsigned_32;
17318
17319 begin
17320    Value := 5;
17321    Put_Line ("Value before is" & Value'Img);
17322    Value := Incr (Value);
17323    Put_Line ("Value after is" & Value'Img);
17324 end Increment;
17325 @end group
17326 @end smallexample
17327
17328 The @code{Outputs} parameter to @code{Asm} specifies
17329 that the result will be in the eax register and that it is to be stored in the @code{Result}
17330 variable.
17331
17332 The @code{Inputs} parameter looks much like the @code{Outputs} parameter, but with an
17333 @code{Asm_Input} attribute. The
17334 @code{"="} constraint, indicating an output value, is not present.
17335
17336 You can have multiple input variables, in the same way that you can have more
17337 than one output variable.
17338
17339 The parameter count (%0, %1) etc, now starts at the first input
17340 statement, and continues with the output statements.
17341 When both parameters use the same variable, the
17342 compiler will treat them as the same %n operand, which is the case here.
17343
17344 Just as the @code{Outputs} parameter causes the register to be stored into the
17345 target variable after execution of the assembler statements, so does the
17346 @code{Inputs} parameter cause its variable to be loaded into the register before execution
17347 of the
17348 assembler statements.
17349
17350 Thus the effect of the @code{Asm} invocation is:
17351 @enumerate
17352 @item load the 32-bit value of @code{Value} into eax
17353 @item execute the @code{incl %eax} instruction
17354 @item store the contents of eax into the @code{Result} variable
17355 @end enumerate
17356
17357 The resulting assembler file (with @code{-O2} optimization) contains:
17358 @smallexample
17359 @group
17360 _increment__incr.1:
17361    subl $4,%esp
17362    movl 8(%esp),%eax
17363 #APP
17364    incl %eax
17365 #NO_APP
17366    movl %eax,%edx
17367    movl %ecx,(%esp)
17368    addl $4,%esp
17369    ret
17370 @end group
17371 @end smallexample
17372
17373 @c ---------------------------------------------------------------------------
17374 @node Inlining Inline Assembler Code
17375 @section Inlining Inline Assembler Code
17376
17377 @noindent
17378 For a short subprogram such as the @code{Incr} function in the previous section, the overhead of the call and return (creating / deleting the stack frame)
17379 can be significant, compared to the amount of code in the subprogram body.
17380 A solution is to apply Ada's @code{Inline} pragma to the subprogram,
17381 which directs the compiler to expand invocations of the subprogram at the point(s)
17382 of call, instead of setting up a stack frame for out-of-line calls.
17383 Here is the resulting program:
17384
17385 @smallexample
17386 @group
17387 with Interfaces; use Interfaces;
17388 with Ada.Text_IO; use Ada.Text_IO;
17389 with System.Machine_Code; use System.Machine_Code;
17390 procedure Increment_2 is
17391
17392    function Incr (Value : Unsigned_32) return Unsigned_32 is
17393       Result : Unsigned_32;
17394    begin
17395       Asm ("incl %0",
17396            Inputs  => Unsigned_32'Asm_Input ("a", Value),
17397            Outputs => Unsigned_32'Asm_Output ("=a", Result));
17398       return Result;
17399    end Incr;
17400    pragma Inline (Increment);
17401
17402    Value : Unsigned_32;
17403
17404 begin
17405    Value := 5;
17406    Put_Line ("Value before is" & Value'Img);
17407    Value := Increment (Value);
17408    Put_Line ("Value after is" & Value'Img);
17409 end Increment_2;
17410 @end group
17411 @end smallexample
17412
17413 Compile the program with both optimization (@code{-O2}) and inlining
17414 enabled (@option{-gnatpn} instead of @option{-gnatp}).
17415
17416 The @code{Incr} function is still compiled as usual, but at the
17417 point in @code{Increment} where our function used to be called:
17418
17419 @smallexample
17420 @group
17421 pushl %edi
17422 call _increment__incr.1
17423 @end group
17424 @end smallexample
17425
17426 @noindent
17427 the code for the function body directly appears:
17428
17429 @smallexample
17430 @group
17431 movl %esi,%eax
17432 #APP
17433    incl %eax
17434 #NO_APP
17435    movl %eax,%edx
17436 @end group
17437 @end smallexample
17438
17439 @noindent
17440 thus saving the overhead of stack frame setup and an out-of-line call.
17441
17442 @c ---------------------------------------------------------------------------
17443 @node Other Asm Functionality
17444 @section Other @code{Asm} Functionality
17445
17446 @noindent
17447 This section describes two important parameters to the @code{Asm} procedure: @code{Clobber}, which identifies register usage; and @code{Volatile}, which inhibits unwanted optimizations.
17448
17449 @menu
17450 * The Clobber Parameter::
17451 * The Volatile Parameter::
17452 @end menu
17453
17454 @c ---------------------------------------------------------------------------
17455 @node The Clobber Parameter
17456 @subsection The @code{Clobber} Parameter
17457
17458 @noindent
17459 One of the dangers of intermixing assembly language and a compiled language such as Ada is
17460 that the compiler needs to be aware of which registers are being used by the assembly code.
17461 In some cases, such as the earlier examples, the constraint string is sufficient to
17462 indicate register usage (e.g. "a" for the eax register).  But more generally, the
17463 compiler needs an explicit identification of the registers that are used by the Inline
17464 Assembly statements.
17465
17466 Using a register that the compiler doesn't know about
17467 could be a side effect of an instruction (like @code{mull}
17468 storing its result in both eax and edx).
17469 It can also arise from explicit register usage in your
17470 assembly code; for example:
17471 @smallexample
17472 @group
17473 Asm ("movl %0, %%ebx" & LF & HT &
17474      "movl %%ebx, %1",
17475      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
17476      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
17477 @end group
17478 @end smallexample
17479 @noindent
17480 where the compiler (since it does not analyze the @code{Asm} template string)
17481 does not know you are using the ebx register.
17482
17483 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
17484 to identify the registers that will be used by your assembly code:
17485
17486 @smallexample
17487 @group
17488 Asm ("movl %0, %%ebx" & LF & HT &
17489      "movl %%ebx, %1",
17490      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
17491      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
17492      Clobber => "ebx");
17493 @end group
17494 @end smallexample
17495
17496 The Clobber parameter is a static string expression specifying the
17497 register(s) you are using.  Note that register names are @emph{not} prefixed by a percent sign.
17498 Also, if more than one register is used then their names are separated by commas; e.g., @code{"eax, ebx"}
17499
17500 The @code{Clobber} parameter has several additional uses:
17501 @enumerate
17502 @item Use the "register" name @code{cc} to indicate that flags might have changed
17503 @item Use the "register" name @code{memory} if you changed a memory location
17504 @end enumerate
17505
17506 @c ---------------------------------------------------------------------------
17507 @node The Volatile Parameter
17508 @subsection The @code{Volatile} Parameter
17509 @cindex Volatile parameter
17510
17511 @noindent
17512 Compiler optimizations in the presence of Inline Assembler may sometimes have unwanted effects.
17513 For example, when
17514 an @code{Asm} invocation with an input variable is inside a loop, the compiler might move
17515 the loading of the input variable outside the loop, regarding it as a
17516 one-time initialization.
17517
17518 If this effect is not desired, you can disable such optimizations by setting the
17519 @code{Volatile} parameter to @code{True}; for example:
17520
17521 @smallexample
17522 @group
17523 Asm ("movl %0, %%ebx" & LF & HT &
17524      "movl %%ebx, %1",
17525      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
17526      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
17527      Clobber  => "ebx",
17528      Volatile => True);
17529 @end group
17530 @end smallexample
17531
17532 By default, @code{Volatile} is set to @code{False} unless there is no @code{Outputs}
17533 parameter.
17534
17535 Although setting @code{Volatile} to @code{True} prevents unwanted optimizations,
17536 it will also disable other optimizations that might be important for efficiency.
17537 In general, you should set @code{Volatile} to @code{True} only if the compiler's
17538 optimizations have created problems.
17539
17540 @c ---------------------------------------------------------------------------
17541 @node A Complete Example
17542 @section A Complete Example
17543
17544 @noindent
17545 This section contains a complete program illustrating a realistic usage of GNAT's Inline Assembler
17546 capabilities.  It comprises a main procedure @code{Check_CPU} and a package @code{Intel_CPU}.
17547 The package declares a collection of functions that detect the properties of the 32-bit
17548 x86 processor that is running the program.  The main procedure invokes these functions
17549 and displays the information.
17550
17551 The Intel_CPU package could be enhanced by adding functions to
17552 detect the type of x386 co-processor, the processor caching options and
17553 special operations such as the SIMD extensions.
17554
17555 Although the Intel_CPU package has been written for 32-bit Intel
17556 compatible CPUs, it is OS neutral. It has been tested on DOS,
17557 Windows/NT and Linux.
17558
17559 @menu
17560 * Check_CPU Procedure::
17561 * Intel_CPU Package Specification::
17562 * Intel_CPU Package Body::
17563 @end menu
17564
17565 @c ---------------------------------------------------------------------------
17566 @node Check_CPU Procedure
17567 @subsection @code{Check_CPU} Procedure
17568 @cindex Check_CPU procedure
17569
17570 @smallexample
17571 ---------------------------------------------------------------------
17572 --                                                                 --
17573 --  Uses the Intel_CPU package to identify the CPU the program is  --
17574 --  running on, and some of the features it supports.              --
17575 --                                                                 --
17576 ---------------------------------------------------------------------
17577
17578 with Intel_CPU;                     --  Intel CPU detection functions
17579 with Ada.Text_IO;                   --  Standard text I/O
17580 with Ada.Command_Line;              --  To set the exit status
17581
17582 procedure Check_CPU is
17583
17584    Type_Found : Boolean := False;
17585    --  Flag to indicate that processor was identified
17586
17587    Features   : Intel_CPU.Processor_Features;
17588    --  The processor features
17589
17590    Signature  : Intel_CPU.Processor_Signature;
17591    --  The processor type signature
17592
17593 begin
17594
17595    -----------------------------------
17596    --  Display the program banner.  --
17597    -----------------------------------
17598
17599    Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name &
17600                          ": check Intel CPU version and features, v1.0");
17601    Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever");
17602    Ada.Text_IO.New_Line;
17603
17604    -----------------------------------------------------------------------
17605    --  We can safely start with the assumption that we are on at least  --
17606    --  a x386 processor. If the CPUID instruction is present, then we   --
17607    --  have a later processor type.                                     --
17608    -----------------------------------------------------------------------
17609
17610    if Intel_CPU.Has_CPUID = False then
17611
17612       --  No CPUID instruction, so we assume this is indeed a x386
17613       --  processor. We can still check if it has a FP co-processor.
17614       if Intel_CPU.Has_FPU then
17615          Ada.Text_IO.Put_Line
17616            ("x386-type processor with a FP co-processor");
17617       else
17618          Ada.Text_IO.Put_Line
17619            ("x386-type processor without a FP co-processor");
17620       end if;  --  check for FPU
17621
17622       --  Program done
17623       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
17624       return;
17625
17626    end if;  --  check for CPUID
17627
17628    -----------------------------------------------------------------------
17629    --  If CPUID is supported, check if this is a true Intel processor,  --
17630    --  if it is not, display a warning.                                 --
17631    -----------------------------------------------------------------------
17632
17633    if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then
17634       Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor");
17635       Ada.Text_IO.Put_Line ("*** Some information may be incorrect");
17636    end if;  --  check if Intel
17637
17638    ----------------------------------------------------------------------
17639    --  With the CPUID instruction present, we can assume at least a    --
17640    --  x486 processor. If the CPUID support level is < 1 then we have  --
17641    --  to leave it at that.                                            --
17642    ----------------------------------------------------------------------
17643
17644    if Intel_CPU.CPUID_Level < 1 then
17645
17646       --  Ok, this is a x486 processor. we still can get the Vendor ID
17647       Ada.Text_IO.Put_Line ("x486-type processor");
17648       Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID);
17649
17650       --  We can also check if there is a FPU present
17651       if Intel_CPU.Has_FPU then
17652          Ada.Text_IO.Put_Line ("Floating-Point support");
17653       else
17654          Ada.Text_IO.Put_Line ("No Floating-Point support");
17655       end if;  --  check for FPU
17656
17657       --  Program done
17658       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
17659       return;
17660
17661    end if;  --  check CPUID level
17662
17663    ---------------------------------------------------------------------
17664    --  With a CPUID level of 1 we can use the processor signature to  --
17665    --  determine it's exact type.                                     --
17666    ---------------------------------------------------------------------
17667
17668    Signature := Intel_CPU.Signature;
17669
17670    ----------------------------------------------------------------------
17671    --  Ok, now we go into a lot of messy comparisons to get the        --
17672    --  processor type. For clarity, no attememt to try to optimize the --
17673    --  comparisons has been made. Note that since Intel_CPU does not   --
17674    --  support getting cache info, we cannot distinguish between P5    --
17675    --  and Celeron types yet.                                          --
17676    ----------------------------------------------------------------------
17677
17678    --  x486SL
17679    if Signature.Processor_Type = 2#00#   and
17680      Signature.Family          = 2#0100# and
17681      Signature.Model           = 2#0100# then
17682       Type_Found := True;
17683       Ada.Text_IO.Put_Line ("x486SL processor");
17684    end if;
17685
17686    --  x486DX2 Write-Back
17687    if Signature.Processor_Type = 2#00#   and
17688      Signature.Family          = 2#0100# and
17689      Signature.Model           = 2#0111# then
17690       Type_Found := True;
17691       Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor");
17692    end if;
17693
17694    --  x486DX4
17695    if Signature.Processor_Type = 2#00#   and
17696      Signature.Family          = 2#0100# and
17697      Signature.Model           = 2#1000# then
17698       Type_Found := True;
17699       Ada.Text_IO.Put_Line ("x486DX4 processor");
17700    end if;
17701
17702    --  x486DX4 Overdrive
17703    if Signature.Processor_Type = 2#01#   and
17704      Signature.Family          = 2#0100# and
17705      Signature.Model           = 2#1000# then
17706       Type_Found := True;
17707       Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor");
17708    end if;
17709
17710    --  Pentium (60, 66)
17711    if Signature.Processor_Type = 2#00#   and
17712      Signature.Family          = 2#0101# and
17713      Signature.Model           = 2#0001# then
17714       Type_Found := True;
17715       Ada.Text_IO.Put_Line ("Pentium processor (60, 66)");
17716    end if;
17717
17718    --  Pentium (75, 90, 100, 120, 133, 150, 166, 200)
17719    if Signature.Processor_Type = 2#00#   and
17720      Signature.Family          = 2#0101# and
17721      Signature.Model           = 2#0010# then
17722       Type_Found := True;
17723       Ada.Text_IO.Put_Line
17724         ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)");
17725    end if;
17726
17727    --  Pentium OverDrive (60, 66)
17728    if Signature.Processor_Type = 2#01#   and
17729      Signature.Family          = 2#0101# and
17730      Signature.Model           = 2#0001# then
17731       Type_Found := True;
17732       Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)");
17733    end if;
17734
17735    --  Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200)
17736    if Signature.Processor_Type = 2#01#   and
17737      Signature.Family          = 2#0101# and
17738      Signature.Model           = 2#0010# then
17739       Type_Found := True;
17740       Ada.Text_IO.Put_Line
17741         ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)");
17742    end if;
17743
17744    --  Pentium OverDrive processor for x486 processor-based systems
17745    if Signature.Processor_Type = 2#01#   and
17746      Signature.Family          = 2#0101# and
17747      Signature.Model           = 2#0011# then
17748       Type_Found := True;
17749       Ada.Text_IO.Put_Line
17750         ("Pentium OverDrive processor for x486 processor-based systems");
17751    end if;
17752
17753    --  Pentium processor with MMX technology (166, 200)
17754    if Signature.Processor_Type = 2#00#   and
17755      Signature.Family          = 2#0101# and
17756      Signature.Model           = 2#0100# then
17757       Type_Found := True;
17758       Ada.Text_IO.Put_Line
17759         ("Pentium processor with MMX technology (166, 200)");
17760    end if;
17761
17762    --  Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133)
17763    if Signature.Processor_Type = 2#01#   and
17764      Signature.Family          = 2#0101# and
17765      Signature.Model           = 2#0100# then
17766       Type_Found := True;
17767       Ada.Text_IO.Put_Line
17768         ("Pentium OverDrive processor with MMX " &
17769          "technology for Pentium processor (75, 90, 100, 120, 133)");
17770    end if;
17771
17772    --  Pentium Pro processor
17773    if Signature.Processor_Type = 2#00#   and
17774      Signature.Family          = 2#0110# and
17775      Signature.Model           = 2#0001# then
17776       Type_Found := True;
17777       Ada.Text_IO.Put_Line ("Pentium Pro processor");
17778    end if;
17779
17780    --  Pentium II processor, model 3
17781    if Signature.Processor_Type = 2#00#   and
17782      Signature.Family          = 2#0110# and
17783      Signature.Model           = 2#0011# then
17784       Type_Found := True;
17785       Ada.Text_IO.Put_Line ("Pentium II processor, model 3");
17786    end if;
17787
17788    --  Pentium II processor, model 5 or Celeron processor
17789    if Signature.Processor_Type = 2#00#   and
17790      Signature.Family          = 2#0110# and
17791      Signature.Model           = 2#0101# then
17792       Type_Found := True;
17793       Ada.Text_IO.Put_Line
17794         ("Pentium II processor, model 5 or Celeron processor");
17795    end if;
17796
17797    --  Pentium Pro OverDrive processor
17798    if Signature.Processor_Type = 2#01#   and
17799      Signature.Family          = 2#0110# and
17800      Signature.Model           = 2#0011# then
17801       Type_Found := True;
17802       Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor");
17803    end if;
17804
17805    --  If no type recognized, we have an unknown. Display what
17806    --  we _do_ know
17807    if Type_Found = False then
17808       Ada.Text_IO.Put_Line ("Unknown processor");
17809    end if;
17810
17811    -----------------------------------------
17812    --  Display processor stepping level.  --
17813    -----------------------------------------
17814
17815    Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img);
17816
17817    ---------------------------------
17818    --  Display vendor ID string.  --
17819    ---------------------------------
17820
17821    Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID);
17822
17823    ------------------------------------
17824    --  Get the processors features.  --
17825    ------------------------------------
17826
17827    Features := Intel_CPU.Features;
17828
17829    -----------------------------
17830    --  Check for a FPU unit.  --
17831    -----------------------------
17832
17833    if Features.FPU = True then
17834       Ada.Text_IO.Put_Line ("Floating-Point unit available");
17835    else
17836       Ada.Text_IO.Put_Line ("no Floating-Point unit");
17837    end if;  --  check for FPU
17838
17839    --------------------------------
17840    --  List processor features.  --
17841    --------------------------------
17842
17843    Ada.Text_IO.Put_Line ("Supported features: ");
17844
17845    --  Virtual Mode Extension
17846    if Features.VME = True then
17847       Ada.Text_IO.Put_Line ("    VME    - Virtual Mode Extension");
17848    end if;
17849
17850    --  Debugging Extension
17851    if Features.DE = True then
17852       Ada.Text_IO.Put_Line ("    DE     - Debugging Extension");
17853    end if;
17854
17855    --  Page Size Extension
17856    if Features.PSE = True then
17857       Ada.Text_IO.Put_Line ("    PSE    - Page Size Extension");
17858    end if;
17859
17860    --  Time Stamp Counter
17861    if Features.TSC = True then
17862       Ada.Text_IO.Put_Line ("    TSC    - Time Stamp Counter");
17863    end if;
17864
17865    --  Model Specific Registers
17866    if Features.MSR = True then
17867       Ada.Text_IO.Put_Line ("    MSR    - Model Specific Registers");
17868    end if;
17869
17870    --  Physical Address Extension
17871    if Features.PAE = True then
17872       Ada.Text_IO.Put_Line ("    PAE    - Physical Address Extension");
17873    end if;
17874
17875    --  Machine Check Extension
17876    if Features.MCE = True then
17877       Ada.Text_IO.Put_Line ("    MCE    - Machine Check Extension");
17878    end if;
17879
17880    --  CMPXCHG8 instruction supported
17881    if Features.CX8 = True then
17882       Ada.Text_IO.Put_Line ("    CX8    - CMPXCHG8 instruction");
17883    end if;
17884
17885    --  on-chip APIC hardware support
17886    if Features.APIC = True then
17887       Ada.Text_IO.Put_Line ("    APIC   - on-chip APIC hardware support");
17888    end if;
17889
17890    --  Fast System Call
17891    if Features.SEP = True then
17892       Ada.Text_IO.Put_Line ("    SEP    - Fast System Call");
17893    end if;
17894
17895    --  Memory Type Range Registers
17896    if Features.MTRR = True then
17897       Ada.Text_IO.Put_Line ("    MTTR   - Memory Type Range Registers");
17898    end if;
17899
17900    --  Page Global Enable
17901    if Features.PGE = True then
17902       Ada.Text_IO.Put_Line ("    PGE    - Page Global Enable");
17903    end if;
17904
17905    --  Machine Check Architecture
17906    if Features.MCA = True then
17907       Ada.Text_IO.Put_Line ("    MCA    - Machine Check Architecture");
17908    end if;
17909
17910    --  Conditional Move Instruction Supported
17911    if Features.CMOV = True then
17912       Ada.Text_IO.Put_Line
17913         ("    CMOV   - Conditional Move Instruction Supported");
17914    end if;
17915
17916    --  Page Attribute Table
17917    if Features.PAT = True then
17918       Ada.Text_IO.Put_Line ("    PAT    - Page Attribute Table");
17919    end if;
17920
17921    --  36-bit Page Size Extension
17922    if Features.PSE_36 = True then
17923       Ada.Text_IO.Put_Line ("    PSE_36 - 36-bit Page Size Extension");
17924    end if;
17925
17926    --  MMX technology supported
17927    if Features.MMX = True then
17928       Ada.Text_IO.Put_Line ("    MMX    - MMX technology supported");
17929    end if;
17930
17931    --  Fast FP Save and Restore
17932    if Features.FXSR = True then
17933       Ada.Text_IO.Put_Line ("    FXSR   - Fast FP Save and Restore");
17934    end if;
17935
17936    ---------------------
17937    --  Program done.  --
17938    ---------------------
17939
17940    Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
17941
17942 exception
17943
17944    when others =>
17945       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
17946       raise;
17947
17948 end Check_CPU;
17949 @end smallexample
17950
17951 @c ---------------------------------------------------------------------------
17952 @node Intel_CPU Package Specification
17953 @subsection @code{Intel_CPU} Package Specification
17954 @cindex Intel_CPU package specification
17955
17956 @smallexample
17957 -------------------------------------------------------------------------
17958 --                                                                     --
17959 --  file: intel_cpu.ads                                                --
17960 --                                                                     --
17961 --           *********************************************             --
17962 --           * WARNING: for 32-bit Intel processors only *             --
17963 --           *********************************************             --
17964 --                                                                     --
17965 --  This package contains a number of subprograms that are useful in   --
17966 --  determining the Intel x86 CPU (and the features it supports) on    --
17967 --  which the program is running.                                      --
17968 --                                                                     --
17969 --  The package is based upon the information given in the Intel       --
17970 --  Application Note AP-485: "Intel Processor Identification and the   --
17971 --  CPUID Instruction" as of April 1998. This application note can be  --
17972 --  found on www.intel.com.                                            --
17973 --                                                                     --
17974 --  It currently deals with 32-bit processors only, will not detect    --
17975 --  features added after april 1998, and does not guarantee proper     --
17976 --  results on Intel-compatible processors.                            --
17977 --                                                                     --
17978 --  Cache info and x386 fpu type detection are not supported.          --
17979 --                                                                     --
17980 --  This package does not use any privileged instructions, so should   --
17981 --  work on any OS running on a 32-bit Intel processor.                --
17982 --                                                                     --
17983 -------------------------------------------------------------------------
17984
17985 with Interfaces;             use Interfaces;
17986 --  for using unsigned types
17987
17988 with System.Machine_Code;    use System.Machine_Code;
17989 --  for using inline assembler code
17990
17991 with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
17992 --  for inserting control characters
17993
17994 package Intel_CPU is
17995
17996    ----------------------
17997    --  Processor bits  --
17998    ----------------------
17999
18000    subtype Num_Bits is Natural range 0 .. 31;
18001    --  the number of processor bits (32)
18002
18003    --------------------------
18004    --  Processor register  --
18005    --------------------------
18006
18007    --  define a processor register type for easy access to
18008    --  the individual bits
18009
18010    type Processor_Register is array (Num_Bits) of Boolean;
18011    pragma Pack (Processor_Register);
18012    for Processor_Register'Size use 32;
18013
18014    -------------------------
18015    --  Unsigned register  --
18016    -------------------------
18017
18018    --  define a processor register type for easy access to
18019    --  the individual bytes
18020
18021    type Unsigned_Register is
18022       record
18023          L1 : Unsigned_8;
18024          H1 : Unsigned_8;
18025          L2 : Unsigned_8;
18026          H2 : Unsigned_8;
18027       end record;
18028
18029    for Unsigned_Register use
18030       record
18031          L1 at 0 range  0 ..  7;
18032          H1 at 0 range  8 .. 15;
18033          L2 at 0 range 16 .. 23;
18034          H2 at 0 range 24 .. 31;
18035       end record;
18036
18037    for Unsigned_Register'Size use 32;
18038
18039    ---------------------------------
18040    --  Intel processor vendor ID  --
18041    ---------------------------------
18042
18043    Intel_Processor : constant String (1 .. 12) := "GenuineIntel";
18044    --  indicates an Intel manufactured processor
18045
18046    ------------------------------------
18047    --  Processor signature register  --
18048    ------------------------------------
18049
18050    --  a register type to hold the processor signature
18051
18052    type Processor_Signature is
18053       record
18054          Stepping       : Natural range 0 .. 15;
18055          Model          : Natural range 0 .. 15;
18056          Family         : Natural range 0 .. 15;
18057          Processor_Type : Natural range 0 .. 3;
18058          Reserved       : Natural range 0 .. 262143;
18059       end record;
18060
18061    for Processor_Signature use
18062       record
18063          Stepping       at 0 range  0 ..  3;
18064          Model          at 0 range  4 ..  7;
18065          Family         at 0 range  8 .. 11;
18066          Processor_Type at 0 range 12 .. 13;
18067          Reserved       at 0 range 14 .. 31;
18068       end record;
18069
18070    for Processor_Signature'Size use 32;
18071
18072    -----------------------------------
18073    --  Processor features register  --
18074    -----------------------------------
18075
18076    --  a processor register to hold the processor feature flags
18077
18078    type Processor_Features is
18079       record
18080          FPU    : Boolean;                --  floating point unit on chip
18081          VME    : Boolean;                --  virtual mode extension
18082          DE     : Boolean;                --  debugging extension
18083          PSE    : Boolean;                --  page size extension
18084          TSC    : Boolean;                --  time stamp counter
18085          MSR    : Boolean;                --  model specific registers
18086          PAE    : Boolean;                --  physical address extension
18087          MCE    : Boolean;                --  machine check extension
18088          CX8    : Boolean;                --  cmpxchg8 instruction
18089          APIC   : Boolean;                --  on-chip apic hardware
18090          Res_1  : Boolean;                --  reserved for extensions
18091          SEP    : Boolean;                --  fast system call
18092          MTRR   : Boolean;                --  memory type range registers
18093          PGE    : Boolean;                --  page global enable
18094          MCA    : Boolean;                --  machine check architecture
18095          CMOV   : Boolean;                --  conditional move supported
18096          PAT    : Boolean;                --  page attribute table
18097          PSE_36 : Boolean;                --  36-bit page size extension
18098          Res_2  : Natural range 0 .. 31;  --  reserved for extensions
18099          MMX    : Boolean;                --  MMX technology supported
18100          FXSR   : Boolean;                --  fast FP save and restore
18101          Res_3  : Natural range 0 .. 127; --  reserved for extensions
18102       end record;
18103
18104    for Processor_Features use
18105       record
18106          FPU    at 0 range  0 ..  0;
18107          VME    at 0 range  1 ..  1;
18108          DE     at 0 range  2 ..  2;
18109          PSE    at 0 range  3 ..  3;
18110          TSC    at 0 range  4 ..  4;
18111          MSR    at 0 range  5 ..  5;
18112          PAE    at 0 range  6 ..  6;
18113          MCE    at 0 range  7 ..  7;
18114          CX8    at 0 range  8 ..  8;
18115          APIC   at 0 range  9 ..  9;
18116          Res_1  at 0 range 10 .. 10;
18117          SEP    at 0 range 11 .. 11;
18118          MTRR   at 0 range 12 .. 12;
18119          PGE    at 0 range 13 .. 13;
18120          MCA    at 0 range 14 .. 14;
18121          CMOV   at 0 range 15 .. 15;
18122          PAT    at 0 range 16 .. 16;
18123          PSE_36 at 0 range 17 .. 17;
18124          Res_2  at 0 range 18 .. 22;
18125          MMX    at 0 range 23 .. 23;
18126          FXSR   at 0 range 24 .. 24;
18127          Res_3  at 0 range 25 .. 31;
18128       end record;
18129
18130    for Processor_Features'Size use 32;
18131
18132    -------------------
18133    --  Subprograms  --
18134    -------------------
18135
18136    function Has_FPU return Boolean;
18137    --  return True if a FPU is found
18138    --  use only if CPUID is not supported
18139
18140    function Has_CPUID return Boolean;
18141    --  return True if the processor supports the CPUID instruction
18142
18143    function CPUID_Level return Natural;
18144    --  return the CPUID support level (0, 1 or 2)
18145    --  can only be called if the CPUID instruction is supported
18146
18147    function Vendor_ID return String;
18148    --  return the processor vendor identification string
18149    --  can only be called if the CPUID instruction is supported
18150
18151    function Signature return Processor_Signature;
18152    --  return the processor signature
18153    --  can only be called if the CPUID instruction is supported
18154
18155    function Features return Processor_Features;
18156    --  return the processors features
18157    --  can only be called if the CPUID instruction is supported
18158
18159 private
18160
18161    ------------------------
18162    --  EFLAGS bit names  --
18163    ------------------------
18164
18165    ID_Flag : constant Num_Bits := 21;
18166    --  ID flag bit
18167
18168 end Intel_CPU;
18169 @end smallexample
18170
18171 @c ---------------------------------------------------------------------------
18172 @node Intel_CPU Package Body
18173 @subsection @code{Intel_CPU} Package Body
18174 @cindex Intel_CPU package body
18175
18176 @smallexample
18177 package body Intel_CPU is
18178
18179    ---------------------------
18180    --  Detect FPU presence  --
18181    ---------------------------
18182
18183    --  There is a FPU present if we can set values to the FPU Status
18184    --  and Control Words.
18185
18186    function Has_FPU return Boolean is
18187
18188       Register : Unsigned_16;
18189       --  processor register to store a word
18190
18191    begin
18192
18193       --  check if we can change the status word
18194       Asm (
18195
18196            --  the assembler code
18197            "finit"              & LF & HT &    --  reset status word
18198            "movw $0x5A5A, %%ax" & LF & HT &    --  set value status word
18199            "fnstsw %0"          & LF & HT &    --  save status word
18200            "movw %%ax, %0",                    --  store status word
18201
18202            --  output stored in Register
18203            --  register must be a memory location
18204            Outputs => Unsigned_16'Asm_output ("=m", Register),
18205
18206            --  tell compiler that we used eax
18207            Clobber => "eax");
18208
18209       --  if the status word is zero, there is no FPU
18210       if Register = 0 then
18211          return False;   --  no status word
18212       end if;  --  check status word value
18213
18214       --  check if we can get the control word
18215       Asm (
18216
18217            --  the assembler code
18218            "fnstcw %0",   --  save the control word
18219
18220            --  output into Register
18221            --  register must be a memory location
18222            Outputs => Unsigned_16'Asm_output ("=m", Register));
18223
18224       --  check the relevant bits
18225       if (Register and 16#103F#) /= 16#003F# then
18226          return False;   --  no control word
18227       end if;  --  check control word value
18228
18229       --  FPU found
18230       return True;
18231
18232    end Has_FPU;
18233
18234    --------------------------------
18235    --  Detect CPUID instruction  --
18236    --------------------------------
18237
18238    --  The processor supports the CPUID instruction if it is possible
18239    --  to change the value of ID flag bit in the EFLAGS register.
18240
18241    function Has_CPUID return Boolean is
18242
18243       Original_Flags, Modified_Flags : Processor_Register;
18244       --  EFLAG contents before and after changing the ID flag
18245
18246    begin
18247
18248       --  try flipping the ID flag in the EFLAGS register
18249       Asm (
18250
18251            --  the assembler code
18252            "pushfl"               & LF & HT &     --  push EFLAGS on stack
18253            "pop %%eax"            & LF & HT &     --  pop EFLAGS into eax
18254            "movl %%eax, %0"       & LF & HT &     --  save EFLAGS content
18255            "xor $0x200000, %%eax" & LF & HT &     --  flip ID flag
18256            "push %%eax"           & LF & HT &     --  push EFLAGS on stack
18257            "popfl"                & LF & HT &     --  load EFLAGS register
18258            "pushfl"               & LF & HT &     --  push EFLAGS on stack
18259            "pop %1",                              --  save EFLAGS content
18260
18261            --  output values, may be anything
18262            --  Original_Flags is %0
18263            --  Modified_Flags is %1
18264            Outputs =>
18265               (Processor_Register'Asm_output ("=g", Original_Flags),
18266                Processor_Register'Asm_output ("=g", Modified_Flags)),
18267
18268            --  tell compiler eax is destroyed
18269            Clobber => "eax");
18270
18271       --  check if CPUID is supported
18272       if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then
18273          return True;   --  ID flag was modified
18274       else
18275          return False;  --  ID flag unchanged
18276       end if;  --  check for CPUID
18277
18278    end Has_CPUID;
18279
18280    -------------------------------
18281    --  Get CPUID support level  --
18282    -------------------------------
18283
18284    function CPUID_Level return Natural is
18285
18286       Level : Unsigned_32;
18287       --  returned support level
18288
18289    begin
18290
18291       --  execute CPUID, storing the results in the Level register
18292       Asm (
18293
18294            --  the assembler code
18295            "cpuid",    --  execute CPUID
18296
18297            --  zero is stored in eax
18298            --  returning the support level in eax
18299            Inputs => Unsigned_32'Asm_input ("a", 0),
18300
18301            --  eax is stored in Level
18302            Outputs => Unsigned_32'Asm_output ("=a", Level),
18303
18304            --  tell compiler ebx, ecx and edx registers are destroyed
18305            Clobber => "ebx, ecx, edx");
18306
18307       --  return the support level
18308       return Natural (Level);
18309
18310    end CPUID_Level;
18311
18312    --------------------------------
18313    --  Get CPU Vendor ID String  --
18314    --------------------------------
18315
18316    --  The vendor ID string is returned in the ebx, ecx and edx register
18317    --  after executing the CPUID instruction with eax set to zero.
18318    --  In case of a true Intel processor the string returned is
18319    --  "GenuineIntel"
18320
18321    function Vendor_ID return String is
18322
18323       Ebx, Ecx, Edx : Unsigned_Register;
18324       --  registers containing the vendor ID string
18325
18326       Vendor_ID : String (1 .. 12);
18327       -- the vendor ID string
18328
18329    begin
18330
18331       --  execute CPUID, storing the results in the processor registers
18332       Asm (
18333
18334            --  the assembler code
18335            "cpuid",    --  execute CPUID
18336
18337            --  zero stored in eax
18338            --  vendor ID string returned in ebx, ecx and edx
18339            Inputs => Unsigned_32'Asm_input ("a", 0),
18340
18341            --  ebx is stored in Ebx
18342            --  ecx is stored in Ecx
18343            --  edx is stored in Edx
18344            Outputs => (Unsigned_Register'Asm_output ("=b", Ebx),
18345                        Unsigned_Register'Asm_output ("=c", Ecx),
18346                        Unsigned_Register'Asm_output ("=d", Edx)));
18347
18348       --  now build the vendor ID string
18349       Vendor_ID( 1) := Character'Val (Ebx.L1);
18350       Vendor_ID( 2) := Character'Val (Ebx.H1);
18351       Vendor_ID( 3) := Character'Val (Ebx.L2);
18352       Vendor_ID( 4) := Character'Val (Ebx.H2);
18353       Vendor_ID( 5) := Character'Val (Edx.L1);
18354       Vendor_ID( 6) := Character'Val (Edx.H1);
18355       Vendor_ID( 7) := Character'Val (Edx.L2);
18356       Vendor_ID( 8) := Character'Val (Edx.H2);
18357       Vendor_ID( 9) := Character'Val (Ecx.L1);
18358       Vendor_ID(10) := Character'Val (Ecx.H1);
18359       Vendor_ID(11) := Character'Val (Ecx.L2);
18360       Vendor_ID(12) := Character'Val (Ecx.H2);
18361
18362       --  return string
18363       return Vendor_ID;
18364
18365    end Vendor_ID;
18366
18367    -------------------------------
18368    --  Get processor signature  --
18369    -------------------------------
18370
18371    function Signature return Processor_Signature is
18372
18373       Result : Processor_Signature;
18374       --  processor signature returned
18375
18376    begin
18377
18378       --  execute CPUID, storing the results in the Result variable
18379       Asm (
18380
18381            --  the assembler code
18382            "cpuid",    --  execute CPUID
18383
18384            --  one is stored in eax
18385            --  processor signature returned in eax
18386            Inputs => Unsigned_32'Asm_input ("a", 1),
18387
18388            --  eax is stored in Result
18389            Outputs => Processor_Signature'Asm_output ("=a", Result),
18390
18391            --  tell compiler that ebx, ecx and edx are also destroyed
18392            Clobber => "ebx, ecx, edx");
18393
18394       --  return processor signature
18395       return Result;
18396
18397    end Signature;
18398
18399    ------------------------------
18400    --  Get processor features  --
18401    ------------------------------
18402
18403    function Features return Processor_Features is
18404
18405       Result : Processor_Features;
18406       --  processor features returned
18407
18408    begin
18409
18410       --  execute CPUID, storing the results in the Result variable
18411       Asm (
18412
18413            --  the assembler code
18414            "cpuid",    --  execute CPUID
18415
18416            --  one stored in eax
18417            --  processor features returned in edx
18418            Inputs => Unsigned_32'Asm_input ("a", 1),
18419
18420            --  edx is stored in Result
18421            Outputs => Processor_Features'Asm_output ("=d", Result),
18422
18423            --  tell compiler that ebx and ecx are also destroyed
18424            Clobber => "ebx, ecx");
18425
18426       --  return processor signature
18427       return Result;
18428
18429    end Features;
18430
18431 end Intel_CPU;
18432 @end smallexample
18433 @c END OF INLINE ASSEMBLER CHAPTER
18434 @c ===============================
18435
18436
18437
18438
18439 @node Performance Considerations
18440 @chapter Performance Considerations
18441 @cindex Performance
18442
18443 @noindent
18444 The GNAT system provides a number of options that allow a trade-off
18445 between
18446
18447 @itemize @bullet
18448 @item
18449 performance of the generated code
18450
18451 @item
18452 speed of compilation
18453
18454 @item
18455 minimization of dependences and recompilation
18456
18457 @item
18458 the degree of run-time checking.
18459 @end itemize
18460
18461 @noindent
18462 The defaults (if no options are selected) aim at improving the speed
18463 of compilation and minimizing dependences, at the expense of performance
18464 of the generated code:
18465
18466 @itemize @bullet
18467 @item
18468 no optimization
18469
18470 @item
18471 no inlining of subprogram calls
18472
18473 @item
18474 all run-time checks enabled except overflow and elaboration checks
18475 @end itemize
18476
18477 @noindent
18478 These options are suitable for most program development purposes. This
18479 chapter describes how you can modify these choices, and also provides
18480 some guidelines on debugging optimized code.
18481
18482 @menu
18483 * Controlling Run-Time Checks::
18484 * Optimization Levels::
18485 * Debugging Optimized Code::
18486 * Inlining of Subprograms::
18487 @end menu
18488
18489 @node Controlling Run-Time Checks
18490 @section Controlling Run-Time Checks
18491
18492 @noindent
18493 By default, GNAT generates all run-time checks, except arithmetic overflow
18494 checking for integer operations and checks for access before elaboration on
18495 subprogram calls. The latter are not required in default mode, because all
18496 necessary checking is done at compile time.
18497 @cindex @option{-gnatp} (@code{gcc})
18498 @cindex @option{-gnato} (@code{gcc})
18499 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
18500 be modified. @xref{Run-Time Checks}.
18501
18502 Our experience is that the default is suitable for most development
18503 purposes.
18504
18505 We treat integer overflow specially because these
18506 are quite expensive and in our experience are not as important as other
18507 run-time checks in the development process. Note that division by zero
18508 is not considered an overflow check, and divide by zero checks are
18509 generated where required by default.
18510
18511 Elaboration checks are off by default, and also not needed by default, since
18512 GNAT uses a static elaboration analysis approach that avoids the need for
18513 run-time checking. This manual contains a full chapter discussing the issue
18514 of elaboration checks, and if the default is not satisfactory for your use,
18515 you should read this chapter.
18516
18517 For validity checks, the minimal checks required by the Ada Reference
18518 Manual (for case statements and assignments to array elements) are on
18519 by default. These can be suppressed by use of the @option{-gnatVn} switch.
18520 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
18521 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
18522 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
18523 are also suppressed entirely if @option{-gnatp} is used.
18524
18525 @cindex Overflow checks
18526 @cindex Checks, overflow
18527 @findex Suppress
18528 @findex Unsuppress
18529 @cindex pragma Suppress
18530 @cindex pragma Unsuppress
18531 Note that the setting of the switches controls the default setting of
18532 the checks. They may be modified using either @code{pragma Suppress} (to
18533 remove checks) or @code{pragma Unsuppress} (to add back suppressed
18534 checks) in the program source.
18535
18536 @node Optimization Levels
18537 @section Optimization Levels
18538 @cindex @code{-O} (@code{gcc})
18539
18540 @noindent
18541 The default is optimization off. This results in the fastest compile
18542 times, but GNAT makes absolutely no attempt to optimize, and the
18543 generated programs are considerably larger and slower than when
18544 optimization is enabled. You can use the
18545 @code{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
18546 on the @code{gcc} command line to control the optimization level:
18547
18548 @table @code
18549 @item -O0
18550 no optimization (the default)
18551
18552 @item -O1
18553 medium level optimization
18554
18555 @item -O2
18556 full optimization
18557
18558 @item -O3
18559 full optimization, and also attempt automatic inlining of small
18560 subprograms within a unit (@pxref{Inlining of Subprograms}).
18561 @end table
18562
18563 Higher optimization levels perform more global transformations on the
18564 program and apply more expensive analysis algorithms in order to generate
18565 faster and more compact code. The price in compilation time, and the
18566 resulting improvement in execution time,
18567 both depend on the particular application and the hardware environment.
18568 You should experiment to find the best level for your application.
18569
18570 Note: Unlike some other compilation systems, @code{gcc} has
18571 been tested extensively at all optimization levels. There are some bugs
18572 which appear only with optimization turned on, but there have also been
18573 bugs which show up only in @emph{unoptimized} code. Selecting a lower
18574 level of optimization does not improve the reliability of the code
18575 generator, which in practice is highly reliable at all optimization
18576 levels.
18577
18578 Note regarding the use of @code{-O3}: The use of this optimization level
18579 is generally discouraged with GNAT, since it often results in larger
18580 executables which run more slowly. See further discussion of this point
18581 in @pxref{Inlining of Subprograms}.
18582
18583 @node Debugging Optimized Code
18584 @section Debugging Optimized Code
18585
18586 @noindent
18587 Since the compiler generates debugging tables for a compilation unit before
18588 it performs optimizations, the optimizing transformations may invalidate some
18589 of the debugging data.  You therefore need to anticipate certain
18590 anomalous situations that may arise while debugging optimized code.  This
18591 section describes the most common cases.
18592
18593 @enumerate
18594 @item
18595 @i{The "hopping Program Counter":}  Repeated 'step' or 'next' commands show the PC
18596 bouncing back and forth in the code.  This may result from any of the following
18597 optimizations:
18598
18599 @itemize @bullet
18600 @item
18601 @i{Common subexpression elimination:} using a single instance of code for a
18602 quantity that the source computes several times.  As a result you
18603 may not be able to stop on what looks like a statement.
18604
18605 @item
18606 @i{Invariant code motion:} moving an expression that does not change within a
18607 loop, to the beginning of the loop.
18608
18609 @item
18610 @i{Instruction scheduling:} moving instructions so as to
18611 overlap loads and stores (typically) with other code, or in
18612 general to move computations of values closer to their uses. Often
18613 this causes you to pass an assignment statement without the assignment
18614 happening and then later bounce back to the statement when the
18615 value is actually needed.  Placing a breakpoint on a line of code
18616 and then stepping over it may, therefore, not always cause all the
18617 expected side-effects.
18618 @end itemize
18619
18620 @item
18621 @i{The "big leap":} More commonly known as @i{cross-jumping}, in which two
18622 identical pieces of code are merged and the program counter suddenly
18623 jumps to a statement that is not supposed to be executed, simply because
18624 it (and the code following) translates to the same thing as the code
18625 that @emph{was} supposed to be executed.  This effect is typically seen in
18626 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
18627 a @code{break} in a C @code{switch} statement.
18628
18629 @item
18630 @i{The "roving variable":} The symptom is an unexpected value in a variable.
18631 There are various reasons for this effect:
18632
18633 @itemize @bullet
18634 @item
18635 In a subprogram prologue, a parameter may not yet have been moved to its
18636 "home".
18637
18638 @item
18639 A variable may be dead, and its register re-used.  This is
18640 probably the most common cause.
18641
18642 @item
18643 As mentioned above, the assignment of a value to a variable may
18644 have been moved.
18645
18646 @item
18647 A variable may be eliminated entirely by value propagation or
18648 other means.  In this case, GCC may incorrectly generate debugging
18649 information for the variable
18650 @end itemize
18651
18652 @noindent
18653 In general, when an unexpected value appears for a local variable or parameter
18654 you should first ascertain if that value was actually computed by
18655 your program, as opposed to being incorrectly reported by the debugger.
18656 Record fields or
18657 array elements in an object designated by an access value
18658 are generally less of a problem, once you have ascertained that the access value
18659 is sensible.
18660 Typically, this means checking variables in the preceding code and in the
18661 calling subprogram to verify that the value observed is explainable from other
18662 values (one must apply the procedure recursively to those
18663 other values); or re-running the code and stopping a little earlier
18664 (perhaps before the call) and stepping to better see how the variable obtained
18665 the value in question; or continuing to step @emph{from} the point of the
18666 strange value to see if code motion had simply moved the variable's
18667 assignments later.
18668 @end enumerate
18669
18670 @node Inlining of Subprograms
18671 @section Inlining of Subprograms
18672
18673 @noindent
18674 A call to a subprogram in the current unit is inlined if all the
18675 following conditions are met:
18676
18677 @itemize @bullet
18678 @item
18679 The optimization level is at least @code{-O1}.
18680
18681 @item
18682 The called subprogram is suitable for inlining: It must be small enough
18683 and not contain nested subprograms or anything else that @code{gcc}
18684 cannot support in inlined subprograms.
18685
18686 @item
18687 The call occurs after the definition of the body of the subprogram.
18688
18689 @item
18690 @cindex pragma Inline
18691 @findex Inline
18692 Either @code{pragma Inline} applies to the subprogram or it is
18693 small and automatic inlining (optimization level @code{-O3}) is
18694 specified.
18695 @end itemize
18696
18697 @noindent
18698 Calls to subprograms in @code{with}'ed units are normally not inlined.
18699 To achieve this level of inlining, the following conditions must all be
18700 true:
18701
18702 @itemize @bullet
18703 @item
18704 The optimization level is at least @code{-O1}.
18705
18706 @item
18707 The called subprogram is suitable for inlining: It must be small enough
18708 and not contain nested subprograms or anything else @code{gcc} cannot
18709 support in inlined subprograms.
18710
18711 @item
18712 The call appears in a body (not in a package spec).
18713
18714 @item
18715 There is a @code{pragma Inline} for the subprogram.
18716
18717 @item
18718 @cindex @option{-gnatn} (@code{gcc})
18719 The @code{-gnatn} switch
18720 is used in the @code{gcc} command line
18721 @end itemize
18722
18723 Note that specifying the @option{-gnatn} switch causes additional
18724 compilation dependencies. Consider the following:
18725
18726 @smallexample
18727 @group
18728 @cartouche
18729 @b{package} R @b{is}
18730    @b{procedure} Q;
18731    @b{pragma} Inline (Q);
18732 @b{end} R;
18733 @b{package body} R @b{is}
18734    ...
18735 @b{end} R;
18736
18737 @b{with} R;
18738 @b{procedure} Main @b{is}
18739 @b{begin}
18740    ...
18741    R.Q;
18742 @b{end} Main;
18743 @end cartouche
18744 @end group
18745 @end smallexample
18746
18747 @noindent
18748 With the default behavior (no @option{-gnatn} switch specified), the
18749 compilation of the @code{Main} procedure depends only on its own source,
18750 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
18751 means that editing the body of @code{R} does not require recompiling
18752 @code{Main}.
18753
18754 On the other hand, the call @code{R.Q} is not inlined under these
18755 circumstances. If the @option{-gnatn} switch is present when @code{Main}
18756 is compiled, the call will be inlined if the body of @code{Q} is small
18757 enough, but now @code{Main} depends on the body of @code{R} in
18758 @file{r.adb} as well as on the spec. This means that if this body is edited,
18759 the main program must be recompiled. Note that this extra dependency
18760 occurs whether or not the call is in fact inlined by @code{gcc}.
18761
18762 The use of front end inlining with @option{-gnatN} generates similar
18763 additional dependencies.
18764
18765 @cindex @code{-fno-inline} (@code{gcc})
18766 Note: The @code{-fno-inline} switch
18767 can be used to prevent
18768 all inlining. This switch overrides all other conditions and ensures
18769 that no inlining occurs. The extra dependences resulting from
18770 @option{-gnatn} will still be active, even if
18771 this switch is used to suppress the resulting inlining actions.
18772
18773 Note regarding the use of @code{-O3}: There is no difference in inlining
18774 behavior between @code{-O2} and @code{-O3} for subprograms with an explicit
18775 pragma @code{Inline} assuming the use of @option{-gnatn}
18776 or @option{-gnatN} (the switches that activate inlining). If you have used
18777 pragma @code{Inline} in appropriate cases, then it is usually much better
18778 to use @code{-O2} and @option{-gnatn} and avoid the use of @code{-O3} which
18779 in this case only has the effect of inlining subprograms you did not
18780 think should be inlined. We often find that the use of @code{-O3} slows
18781 down code by performing excessive inlining, leading to increased instruction
18782 cache pressure from the increased code size. So the bottom line here is
18783 that you should not automatically assume that @code{-O3} is better than
18784 @code{-O2}, and indeed you should use @code{-O3} only if tests show that
18785 it actually improves performance.
18786
18787
18788 @include fdl.texi
18789 @c GNU Free Documentation License
18790
18791 @node Index,,GNU Free Documentation License, Top
18792 @unnumbered Index
18793
18794 @printindex cp
18795
18796 @contents
18797
18798 @bye