OSDN Git Service

2003-12-11 Ed Falis <falis@gnat.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / gnat_ug_vxw.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
58 @setfilename gnat_ug_vxw.info
59 @settitle GNAT User's Guide for Cross Platforms
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-2002, 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 Cross 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
86 @title GNAT User's Guide
87 @center @titlefont{for Cross Platforms}
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
108 GNAT User's Guide for Cross Platforms
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 * Preliminary Note for Cross Platform Users::
121 * Getting Started with GNAT::
122 * The GNAT Compilation Model::
123 * Compiling Using gcc::
124 * Binding Using gnatbind::
125 * Linking Using gnatlink::
126 * The GNAT Make Program gnatmake::
127 * Renaming Files Using gnatchop::
128 * Configuration Pragmas::
129 * Handling Arbitrary File Naming Conventions Using gnatname::
130 * GNAT Project Manager::
131 * Elaboration Order Handling in GNAT::
132 * The Cross-Referencing Tools gnatxref and gnatfind::
133 * File Name Krunching Using gnatkr::
134 * Preprocessing Using gnatprep::
135 * The GNAT Library Browser gnatls::
136 * GNAT and Libraries::
137 * Using the GNU make Utility::
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 * VxWorks Topics::
145 * LynxOS Topics::
146 * Performance Considerations::
147 * GNU Free Documentation License::
148 * Index::
149
150  --- The Detailed Node Listing ---
151
152 About This Guide
153
154 * What This Guide Contains::
155 * What You Should Know before Reading This Guide::
156 * Related Information::
157 * Conventions::
158
159 Preliminary Note for Cross Platform Users::
160
161 Getting Started with GNAT
162
163 * Running GNAT::
164 * Building a Simple Ada Program::
165 * Executing a Program on VxWorks::
166 * Running a Program with Multiple Units::
167 * Using the gnatmake Utility::
168
169 The GNAT Compilation Model
170
171 * Source Representation::
172 * Foreign Language Representation::
173 * File Naming Rules::
174 * Using Other File Names::
175 * Alternative File Naming Schemes::
176 * Generating Object Files::
177 * Source Dependencies::
178 * The Ada Library Information Files::
179 * Binding an Ada Program::
180 * Mixed Language Programming::
181 * Building Mixed Ada & C++ Programs::
182 * Comparison between GNAT and C/C++ Compilation Models::
183 * Comparison between GNAT and Conventional Ada Library Models::
184
185 Foreign Language Representation
186
187 * Latin-1::
188 * Other 8-Bit Codes::
189 * Wide Character Encodings::
190
191 Compiling Ada Programs With gcc
192
193 * Compiling Programs::
194 * Switches for gcc::
195 * Search Paths and the Run-Time Library (RTL)::
196 * Order of Compilation Issues::
197 * Examples::
198
199 Switches for gcc
200
201 * Output and Error Message Control::
202 * Debugging and Assertion Control::
203 * Run-Time Checks::
204 * Stack Overflow Checking::
205 * Run-Time Control::
206 * Validity Checking::
207 * Style Checking::
208 * Using gcc for Syntax Checking::
209 * Using gcc for Semantic Checking::
210 * Compiling Ada 83 Programs::
211 * Character Set Control::
212 * File Naming Control::
213 * Subprogram Inlining Control::
214 * Auxiliary Output Control::
215 * Debugging Control::
216 * Units to Sources Mapping Files::
217
218 Binding Ada Programs With gnatbind
219
220 * Running gnatbind::
221 * Generating the Binder Program in C::
222 * Consistency-Checking Modes::
223 * Binder Error Message Control::
224 * Elaboration Control::
225 * Output Control::
226 * Binding with Non-Ada Main Programs::
227 * Binding Programs with No Main Subprogram::
228 * Summary of Binder Switches::
229 * Command-Line Access::
230 * Search Paths for gnatbind::
231 * Examples of gnatbind Usage::
232
233 Linking Using gnatlink
234
235 * Running gnatlink::
236 * Switches for gnatlink::
237 * Setting Stack Size from gnatlink::
238 * Setting Heap Size from gnatlink::
239
240 The GNAT Make Program gnatmake
241
242 * Running gnatmake::
243 * Switches for gnatmake::
244 * Mode Switches for gnatmake::
245 * Notes on the Command Line::
246 * How gnatmake Works::
247 * Examples of gnatmake Usage::
248
249 Renaming Files Using gnatchop
250
251 * Handling Files with Multiple Units::
252 * Operating gnatchop in Compilation Mode::
253 * Command Line for gnatchop::
254 * Switches for gnatchop::
255 * Examples of gnatchop Usage::
256
257 Configuration Pragmas
258
259 * Handling of Configuration Pragmas::
260 * The Configuration Pragmas Files::
261
262 Handling Arbitrary File Naming Conventions Using gnatname
263
264 * Arbitrary File Naming Conventions::
265 * Running gnatname::
266 * Switches for gnatname::
267 * Examples of gnatname Usage::
268
269 GNAT Project Manager
270
271 * Introduction::
272 * Examples of Project Files::
273 * Project File Syntax::
274 * Objects and Sources in Project Files::
275 * Importing Projects::
276 * Project Extension::
277 * External References in Project Files::
278 * Packages in Project Files::
279 * Variables from Imported Projects::
280 * Naming Schemes::
281 * Library Projects::
282 * Switches Related to Project Files::
283 * Tools Supporting Project Files::
284 * An Extended Example::
285 * Project File Complete Syntax::
286
287 Elaboration Order Handling in GNAT
288
289 * Elaboration Code in Ada 95::
290 * Checking the Elaboration Order in Ada 95::
291 * Controlling the Elaboration Order in Ada 95::
292 * Controlling Elaboration in GNAT - Internal Calls::
293 * Controlling Elaboration in GNAT - External Calls::
294 * Default Behavior in GNAT - Ensuring Safety::
295 * Elaboration Issues for Library Tasks::
296 * Mixing Elaboration Models::
297 * What to Do If the Default Elaboration Behavior Fails::
298 * Elaboration for Access-to-Subprogram Values::
299 * Summary of Procedures for Elaboration Control::
300 * Other Elaboration Order Considerations::
301
302 The Cross-Referencing Tools gnatxref and gnatfind
303
304 * gnatxref Switches::
305 * gnatfind Switches::
306 * Project Files for gnatxref and gnatfind::
307 * Regular Expressions in gnatfind and gnatxref::
308 * Examples of gnatxref Usage::
309 * Examples of gnatfind Usage::
310
311 File Name Krunching Using gnatkr
312
313 * About gnatkr::
314 * Using gnatkr::
315 * Krunching Method::
316 * Examples of gnatkr Usage::
317
318 Preprocessing Using gnatprep
319
320 * Using gnatprep::
321 * Switches for gnatprep::
322 * Form of Definitions File::
323 * Form of Input Text for gnatprep::
324
325
326 The GNAT Library Browser gnatls
327
328 * Running gnatls::
329 * Switches for gnatls::
330 * Examples of gnatls Usage::
331
332
333 GNAT and Libraries
334
335 * Creating an Ada Library::
336 * Installing an Ada Library::
337 * Using an Ada Library::
338 * Creating an Ada Library to be Used in a Non-Ada Context::
339 * Rebuilding the GNAT Run-Time Library::
340
341 Using the GNU make Utility
342
343 * Using gnatmake in a Makefile::
344 * Automatically Creating a List of Directories::
345 * Generating the Command Line Switches::
346 * Overcoming Command Line Length Limits::
347
348
349 Finding Memory Problems with GNAT Debug Pool
350
351 Creating Sample Bodies Using gnatstub
352
353 * Running gnatstub::
354 * Switches for gnatstub::
355
356 Reducing the Size of Ada Executables with gnatelim
357
358 * About gnatelim::
359 * Eliminate Pragma::
360 * Tree Files::
361 * Preparing Tree and Bind Files for gnatelim::
362 * Running gnatelim::
363 * Correcting the List of Eliminate Pragmas::
364 * Making Your Executables Smaller::
365 * Summary of the gnatelim Usage Cycle::
366
367 Other Utility Programs
368
369 * Using Other Utility Programs with GNAT::
370 * The gnatpsta Utility Program::
371 * The External Symbol Naming Scheme of GNAT::
372 * Ada Mode for Glide::
373 * Converting Ada Files to html with gnathtml::
374
375
376 Running and Debugging Ada Programs
377
378 * The GNAT Debugger GDB::
379 * Running GDB::
380 * Introduction to GDB Commands::
381 * Using Ada Expressions::
382 * Calling User-Defined Subprograms::
383 * Using the Next Command in a Function::
384 * Ada Exceptions::
385 * Ada Tasks::
386 * Debugging Generic Units::
387 * GNAT Abnormal Termination or Failure to Terminate::
388 * Naming Conventions for GNAT Source Files::
389 * Getting Internal Debugging Information::
390 * Stack Traceback::
391
392 Inline Assembler
393
394 * Basic Assembler Syntax::
395 * A Simple Example of Inline Assembler::
396 * Output Variables in Inline Assembler::
397 * Input Variables in Inline Assembler::
398 * Inlining Inline Assembler Code::
399 * Other Asm Functionality::
400 * A Complete Example::
401
402
403 VxWorks Topics
404
405 * Kernel Configuration for VxWorks::
406 * Kernel Compilation Issues for VxWorks::
407 * Handling Relocation Issues for PowerPc Targets::
408 * Support for Software Floating Point on PowerPC Processors::
409 * Interrupt Handling for VxWorks::
410 * Simulating Command Line Arguments for VxWorks::
411 * Debugging Issues for VxWorks::
412 * Using GNAT from the Tornado 2 Project Facility::
413 * Frequently Asked Questions for VxWorks::
414
415 LynxOS Topics
416
417 * Getting Started with GNAT on LynxOS::
418 * Kernel Configuration for LynxOS::
419 * Patch Level Issues for LynxOS::
420 * Debugging Issues for LynxOS::
421 * An Example Debugging Session for LynxOS::
422
423 Performance Considerations
424
425 * Controlling Run-Time Checks::
426 * Optimization Levels::
427 * Debugging Optimized Code::
428 * Inlining of Subprograms::
429
430 * Index::
431 @end menu
432 @end ifnottex
433
434 @node About This Guide
435 @unnumbered About This Guide
436
437 @noindent
438 This guide describes the use of GNAT, a compiler and software development
439 toolset for the full Ada 95 programming language.
440 It describes the features of the compiler and tools, and details
441 how to use them to build Ada 95 applications.
442
443 @menu
444 * What This Guide Contains::
445 * What You Should Know before Reading This Guide::
446 * Related Information::
447 * Conventions::
448 @end menu
449
450 @node What This Guide Contains
451 @unnumberedsec What This Guide Contains
452
453 @noindent
454 This guide contains the following chapters:
455 @itemize @bullet
456 @item
457 @ref{Preliminary Note for Cross Platform Users}, describes the basic
458 differences between the cross and native versions of GNAT.
459 @item
460 @ref{Getting Started with GNAT}, describes how to get started compiling
461 and running Ada programs with the GNAT Ada programming environment.
462 @item
463 @ref{The GNAT Compilation Model}, describes the compilation model used
464 by GNAT.
465 @item
466 @ref{Compiling Using gcc}, describes how to compile
467 Ada programs with @code{gcc}, the Ada compiler.
468 @item
469 @ref{Binding Using gnatbind}, describes how to
470 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
471 utility.
472 @item
473 @ref{Linking Using gnatlink},
474 describes @code{gnatlink}, a
475 program that provides for linking using the GNAT run-time library to
476 construct a program. @code{gnatlink} can also incorporate foreign language
477 object units into the executable.
478 @item
479 @ref{The GNAT Make Program gnatmake}, describes @code{gnatmake}, a
480 utility that automatically determines the set of sources
481 needed by an Ada compilation unit, and executes the necessary compilations
482 binding and link.
483 @item
484 @ref{Renaming Files Using gnatchop}, describes
485 @code{gnatchop}, a utility that allows you to preprocess a file that
486 contains Ada source code, and split it into one or more new files, one
487 for each compilation unit.
488 @item
489 @ref{Configuration Pragmas}, describes the configuration pragmas handled by GNAT.
490 @item
491 @ref{Handling Arbitrary File Naming Conventions Using gnatname}, shows how to override
492 the default GNAT file naming conventions, either for an individual unit or globally.
493 @item
494 @ref{GNAT Project Manager}, describes how to use project files to organize large projects.
495 @item
496 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps you deal with
497 elaboration order issues.
498 @item
499 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
500 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
501 way to navigate through sources.
502 @item
503 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
504 file name krunching utility, used to handle shortened
505 file names on operating systems with a limit on the length of names.
506 @item
507 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
508 preprocessor utility that allows a single source file to be used to
509 generate multiple or parameterized source files, by means of macro
510 substitution.
511 @item
512 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
513 utility that displays information about compiled units, including dependences
514 on the corresponding sources files, and consistency of compilations.
515 @item
516 @ref{GNAT and Libraries}, describes the process of creating and using
517 Libraries with GNAT. It also describes how to recompile the GNAT run-time
518 library.
519
520 @item
521 @ref{Using the GNU make Utility}, describes some techniques for using
522 the GNAT toolset in Makefiles.
523
524 @item
525 @ref{Finding Memory Problems with GNAT Debug Pool}, describes how to
526 use the GNAT-specific Debug Pool in order to detect as early as possible
527 the use of incorrect memory references.
528
529 @item
530 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
531 a utility that generates empty but compilable bodies for library units.
532
533 @item
534 @ref{Reducing the Size of Ada Executables with gnatelim}, describes
535 @code{gnatelim}, a tool which detects unused subprograms and helps
536 the compiler to create a smaller executable for the program.
537
538 @item
539 @ref{Other Utility Programs}, discusses several other GNAT utilities,
540 including @code{gnatpsta}.
541
542 @item
543 @ref{Running and Debugging Ada Programs}, describes how to run and debug
544 Ada programs.
545
546 @item
547 @ref{Inline Assembler}, shows how to use the inline assembly facility in an Ada program.
548
549 @item
550 @ref{VxWorks Topics}, presents information relevant to the VxWorks target for cross-compilation
551 configurations.
552
553 @item
554 @ref{LynxOS Topics}, presents information relevant to the LynxOS target for cross-compilation
555 configurations.
556
557 @item
558 @ref{Performance Considerations}, reviews the trade offs between using
559 defaults or options in program development.
560 @end itemize
561
562 @node What You Should Know before Reading This Guide
563 @unnumberedsec What You Should Know before Reading This Guide
564
565 @cindex Ada 95 Language Reference Manual
566 @noindent
567 This user's guide assumes that you are familiar with Ada 95 language, as
568 described in the International Standard ANSI/ISO/IEC-8652:1995, Jan
569 1995.
570
571 @node Related Information
572 @unnumberedsec Related Information
573
574 @noindent
575 For further information about related tools, refer to the following
576 documents:
577
578 @itemize @bullet
579 @item
580 @cite{GNAT Reference Manual}, which contains all reference
581 material for the GNAT implementation of Ada 95.
582
583 @item
584 @cite{Ada 95 Language Reference Manual}, which contains all reference
585 material for the Ada 95 programming language.
586
587 @item
588 @cite{Debugging with GDB}
589 contains all details on the use of the GNU source-level debugger.
590
591 @item
592 @cite{GNU Emacs Manual}
593 contains full information on the extensible editor and programming
594 environment Emacs.
595
596 @end itemize
597
598 @node Conventions
599 @unnumberedsec Conventions
600 @cindex Conventions
601 @cindex Typographical conventions
602
603 @noindent
604 Following are examples of the typographical and graphic conventions used
605 in this guide:
606
607 @itemize @bullet
608 @item
609 @code{Functions}, @code{utility program names}, @code{standard names},
610 and @code{classes}.
611
612 @item
613 @samp{Option flags}
614
615 @item
616 @file{File Names}, @file{button names}, and @file{field names}.
617
618 @item
619 @var{Variables}.
620
621 @item
622 @emph{Emphasis}.
623
624 @item
625 [optional information or parameters]
626
627 @item
628 Examples are described by text
629 @smallexample
630 and then shown this way.
631 @end smallexample
632 @end itemize
633
634 @noindent
635 Commands that are entered by the user are preceded in this manual by the
636 characters @w{"@code{$ }"} (dollar sign followed by space). If your system
637 uses this sequence as a prompt, then the commands will appear exactly as
638 you see them in the manual. If your system uses some other prompt, then
639 the command will appear with the @code{$} replaced by whatever prompt
640 character you are using.
641
642 @node Preliminary Note for Cross Platform Users
643 @chapter Preliminary Note for Cross Platform Users
644
645 @noindent
646 The use of GNAT in a cross environment is very similar to its use in a
647 native environment. Most of the tools described in this manual have
648 similar functions and options in both modes. The major
649 difference is that the name of the cross tools includes the target for
650 which the cross compiler is configured. For instance, the cross @command{gnatmake}
651 tool is called @command{@i{target}-gnatmake} where @code{@i{target}} stands for the name of
652 the cross target. Thus, in an environment configured for the
653 target @code{powerpc-wrs-vxworks}, the @command{gnatmake} command is
654 @code{powerpc-wrs-vxworks-gnatmake}. This convention allows the
655 installation of a native and one or several cross development
656 environments at the same location.
657
658 The tools that are most relevant in a cross environment are:
659 @code{@i{target}-gcc}, @code{@i{target}-gnatmake},
660 @code{@i{target}-gnatbind}, @code{@i{target}-gnatlink} to build cross
661 applications and @code{@i{target}-gnatls} for cross library
662 browsing. @code{@i{target}-gdb} is also usually available for cross
663 debugging in text mode. The graphical debugger interface
664 @code{gvd} is always a native tool but it can be configured to drive
665 the above mentioned cross debugger, thus allowing graphical cross debugging
666 sessions. Some other tools such as  @code{@i{target}-gnatchop},
667 @code{@i{target}-gnatkr}, @code{@i{target}-gnatprep},
668 @code{@i{target}-gnatpsta}, @code{@i{target}-gnatxref}, @code{@i{target}-gnatfind}
669 and @code{@i{target}-gnatname} are also provided for completeness
670 even though they do not differ greatly from their native counterpart.
671
672 In the rest of this manual, the tools are sometimes designated with
673 their full cross name, and sometimes with their simplified native
674 name.
675
676
677 @node Getting Started with GNAT
678 @chapter Getting Started with GNAT
679
680 @noindent
681 This introduction is a starting point for using GNAT to develop
682 and execute Ada 95 programs in a cross environment.
683 It provides some specifics
684 about the GNAT toolchain targeted to the Wind River Sytems' VxWorks/Tornado platform;
685 for other targets please refer to the corresponding chapter later in this manual.
686
687 Basic familiarity with use of GNAT in a native environment is
688 presumed. For the VxWorks specific part, a knowledge of how to start
689 Tornado's @code{windsh} tool is also presumed.
690
691 @menu
692 * Running GNAT::
693 * Building a Simple Ada Program::
694 * Executing a Program on VxWorks::
695
696 * Running a Program with Multiple Units::
697
698 * Using the gnatmake Utility::
699 * Introduction to Glide and GVD::
700 @end menu
701
702 @node Running GNAT
703 @section Running GNAT
704
705 @noindent
706 Three steps are needed to create an executable file from an Ada source
707 file:
708
709 @enumerate
710 @item
711 The source file(s) must be compiled.
712 @item
713 The file(s) must be bound using the GNAT binder.
714 @item
715 All appropriate object files must be linked to produce a loadable module.
716 @end enumerate
717
718 @noindent
719 All three steps are most commonly handled by using the @code{gnatmake}
720 utility program that, given the name of the main program, automatically
721 performs the necessary compilation, binding and linking steps.
722
723 @node Building a Simple Ada Program
724 @section Building a Simple Ada Program
725
726 @noindent
727 Any text editor may be used to prepare an Ada program. If @code{Glide} is
728 used, the optional Ada mode may be helpful in laying out the program. The
729 program text is a normal text file. We will suppose in our initial
730 example that you have used your editor to prepare the following
731 standard format text file:
732
733 @smallexample
734 @group
735 @cartouche
736 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
737 @b{procedure} Hello @b{is}
738 @b{begin}
739    Put_Line ("Hello WORLD!");
740 @b{end} Hello;
741 @end cartouche
742 @end group
743 @end smallexample
744
745 @noindent
746 This file should be named @file{hello.adb}.
747 With the normal default file naming conventions, GNAT requires
748 that each file
749 contain a single compilation unit whose file name is the
750 unit name,
751 with periods replaced by hyphens; the
752 extension is @file{ads} for a
753 spec and @file{adb} for a body.
754 You can override this default file naming convention by use of the
755 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
756 Alternatively, if you want to rename your files according to this default
757 convention, which is probably more convenient if you will be using GNAT
758 for all your compilations, then the @code{gnatchop} utility
759 can be used to generate correctly-named source files
760 (@pxref{Renaming Files Using gnatchop}).
761
762 You can compile the program using the following command (@code{$} is used
763 as the command prompt in the examples in this document):
764
765
766 @smallexample
767 $ @i{target}-gcc -c hello.adb
768 @end smallexample
769
770 @noindent
771 @code{gcc} is the command used to run the compiler. This compiler is
772 capable of compiling programs in several languages, including Ada 95 and
773 C. It assumes that you have given it an Ada program if the file extension is
774 either @file{.ads} or @file{.adb}, and it will then call the GNAT compiler to compile
775 the specified file.
776
777 The @option{-c} switch is required. It tells @command{gcc} to only do a
778 compilation. (For C programs, @command{gcc} can also do linking, but this
779 capability is not used directly for Ada programs, so the @option{-c}
780 switch must always be present.)
781
782 This compile command generates a file
783 @file{hello.o}, which is the object
784 file corresponding to your Ada program. It also generates an "Ada Library Information" file
785 @file{hello.ali},
786 which contains additional information used to check
787 that an Ada program is consistent.
788 To build a downloadable module,
789 use @code{gnatbind} to bind the program
790 and @code{gnatlink} to link it. The
791 argument to both @code{gnatbind} and @code{gnatlink} is the name of the
792 @file{ali} file, but the default extension of @file{.ali} can
793 be omitted. This means that in the most common case, the argument
794 is simply the name of the main program:
795
796
797 @smallexample
798 $ @i{target}-gnatbind hello
799 $ @i{target}-gnatlink hello
800 @end smallexample
801
802 @noindent
803 A simpler method of carrying out these steps is to use
804 @command{gnatmake},
805 a master program that invokes all the required
806 compilation, binding and linking tools in the correct order. In particular,
807 @command{gnatmake} automatically recompiles any sources that have been modified
808 since they were last compiled, or sources that depend
809 on such modified sources, so that "version skew" is avoided.
810 @cindex Version skew (avoided by @command{gnatmake})
811
812
813 @smallexample
814 $ @i{target}-gnatmake hello.adb
815 @end smallexample
816
817
818 @noindent
819 The result is a relocatable object called @file{hello}.
820
821 @emph{Technical note:} the result of the linking stage is a
822 relocatable partially-linked object containing all the relevant GNAT
823 run-time units, in contrast with the executable-format object file found in
824 native environments.
825
826
827 @node Executing a Program on VxWorks
828 @section Executing a Program on VxWorks
829
830 @noindent
831 Getting a program to execute involves loading it onto the target, running it, and then (if re-execution is needed) unloading it.
832
833 @menu
834 * Loading and Running the Program::
835 * Unloading the Program::
836 @end menu
837
838 @node Loading and Running the Program
839 @subsection Loading and Running the Program
840
841 @noindent
842 An Ada program is loaded and run in the same way as a C program.
843 Details may be found in the @cite{Tornado User's Guide}.
844
845 In order to load and run our simple "Hello World" example, we assume that
846 the target has access to the disk of the host containing this object and
847 that its working directory has been set to the directory containing this
848 object. The commands are typed in Tornado's Windshell. The @code{windsh} prompt
849 is the @code{->} sequence.
850
851 @smallexample
852 -> vf0=open("/vio/0",2,0)
853 new symbol "vf0" added to symbol table.
854 vf0 = 0x2cab48: value = 12 = 0xc
855 -> ioGlobalStdSet(1,vf0)
856 value = 1 = 0x1
857 -> ld < hello
858 value = 665408 = 0xa2740
859 -> hello
860 Hello World
861 value = 0 = 0x0
862 ->
863 @end smallexample
864
865 @noindent
866 The first two commands redirect output to the shell window.
867 They are only needed if the target server was started without the
868 @code{-C} option.  The third command loads the module, which is the file
869 @file{hello} created previously by the @code{@i{target}-gnatmake} command.
870 Note that for Tornado AE, the @command{ml} command replaces @command{ld}."
871
872 The "Hello World" program comprises a procedure named @code{hello}, and this
873 is the name entered for the procedure in the target server's symbol table
874 when the module is loaded.  To execute the procedure, type the symbol name @code{hello}
875 into @code{windsh} as shown in the last command above.
876
877 Note that by default the entry point of an Ada program is the name of the main
878 Ada subprogram in a VxWorks environment. It is possible to use an alternative
879 name; see the description of @code{gnatbind} options for details.
880
881 @node Unloading the Program
882 @subsection Unloading the Program
883
884 @noindent
885 It is important to remember that
886 you must unload a program once you have run it. You
887 cannot load it once and run it several times. If you don't follow
888 this rule, your program's behavior can be unpredictable, and will most
889 probably crash.
890
891 This effect is due to the implementation of Ada 95's @emph{elaboration} semantics.
892 The unit elaboration phase comprises a @emph{static} elaboration and a
893 @emph{dynamic} elaboration. On a native platform they both take place
894 when the program is run. Thus rerunning the program will repeat the complete
895 elaboration phase, and the program will run correctly.
896
897 On VxWorks, the process is a bit different.
898 The static elaboration phase is handled by
899 the loader (typically when you type @code{ld < program_name} in
900 @code{windsh}). The dynamic phase takes place when the program is run. If the
901 program is run twice and has not been unloaded and then reloaded, the
902 second time it is run, the static elaboration phase is skipped.
903 Variables initialized during the static elaboration phase
904 may have been modified during the first execution of the program. Thus the
905 second execution isn't performed on a completely initialized environment.
906
907 Note that in C programs, elaboration isn't systematic. Multiple runs without reload
908 might work, but, even with C programs, if there is an elaboration
909 phase, you will have to unload your program before re-running it.
910
911
912 @node Running a Program with Multiple Units
913 @section Running a Program with Multiple Units
914
915 @noindent
916 Consider a slightly more complicated example that has three files: a
917 main program, and the spec and body of a package:
918
919 @smallexample
920 @cartouche
921 @group
922 @b{package} Greetings @b{is}
923    @b{procedure} Hello;
924    @b{procedure} Goodbye;
925 @b{end} Greetings;
926
927 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
928 @b{package} @b{body} Greetings @b{is}
929    @b{procedure} Hello @b{is}
930    @b{begin}
931       Put_Line ("Hello WORLD!");
932    @b{end} Hello;
933
934    @b{procedure} Goodbye @b{is}
935    @b{begin}
936       Put_Line ("Goodbye WORLD!");
937    @b{end} Goodbye;
938 @b{end} Greetings;
939 @end group
940
941 @group
942 @b{with} Greetings;
943 @b{procedure} Gmain @b{is}
944 @b{begin}
945    Greetings.Hello;
946    Greetings.Goodbye;
947 @b{end} Gmain;
948 @end group
949 @end cartouche
950 @end smallexample
951
952 @noindent
953 Following the one-unit-per-file rule, place this program in the
954 following three separate files:
955
956 @table @file
957 @item greetings.ads
958 spec of package @code{Greetings}
959
960 @item greetings.adb
961 body of package @code{Greetings}
962
963 @item gmain.adb
964 body of main program
965 @end table
966
967 @noindent
968 To build an executable version of
969 this program, we could use four separate steps to compile, bind, and link
970 the program, as follows:
971
972
973 @smallexample
974 $ @i{target}-gcc -c gmain.adb
975 $ @i{target}-gcc -c greetings.adb
976 $ @i{target}-gnatbind gmain
977 $ @i{target}-gnatlink gmain
978 @end smallexample
979
980 @noindent
981 Note that there is no required order of compilation when using GNAT.
982 In particular it is perfectly fine to compile the main program first.
983 Also, it is not necessary to compile package specs in the case where
984 there is an accompanying body; you only need to compile the body. If you want
985 to submit these files to the compiler for semantic checking and not code generation,
986 then use the
987 @option{-gnatc} switch:
988
989
990 @smallexample
991 $ @i{target}-gcc -c greetings.ads -gnatc
992 @end smallexample
993
994 @noindent
995 Although the compilation can be done in separate steps as in the
996 above example, in practice it is almost always more convenient
997 to use the @code{gnatmake} tool. All you need to know in this case
998 is the name of the main program's source file. The effect of the above four
999 commands can be achieved with a single one:
1000
1001
1002 @smallexample
1003 $ @i{target}-gnatmake gmain.adb
1004 @end smallexample
1005
1006 @noindent
1007 In the next section we discuss the advantages of using @code{gnatmake} in
1008 more detail.
1009
1010 @node Using the gnatmake Utility
1011 @section Using the @command{gnatmake} Utility
1012
1013 @noindent
1014 If you work on a program by compiling single components at a time using
1015 @code{gcc}, you typically keep track of the units you modify. In order to
1016 build a consistent system, you compile not only these units, but also any
1017 units that depend on the units you have modified.
1018 For example, in the preceding case,
1019 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1020 you edit @file{greetings.ads}, you must recompile both
1021 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1022 units that depend on @file{greetings.ads}.
1023
1024 @code{gnatbind} will warn you if you forget one of these compilation
1025 steps, so that it is impossible to generate an inconsistent program as a
1026 result of forgetting to do a compilation. Nevertheless it is tedious and
1027 error-prone to keep track of dependencies among units.
1028 One approach to handle the dependency-bookkeeping is to use a
1029 makefile. However, makefiles present maintenance problems of their own:
1030 if the dependencies change as you change the program, you must make
1031 sure that the makefile is kept up-to-date manually, which is also an
1032 error-prone process.
1033
1034 The @code{gnatmake} utility takes care of these details automatically.
1035 Invoke it using either one of the following forms:
1036
1037
1038 @smallexample
1039 $ @i{target}-gnatmake gmain.adb
1040 $ @i{target}-gnatmake gmain
1041 @end smallexample
1042
1043 @noindent
1044 The argument is the name of the file containing the main program;
1045 you may omit the extension. @code{gnatmake}
1046 examines the environment, automatically recompiles any files that need
1047 recompiling, and binds and links the resulting set of object files,
1048 generating the executable file, @file{gmain}.
1049 In a large program, it
1050 can be extremely helpful to use @code{gnatmake}, because working out by hand
1051 what needs to be recompiled can be difficult.
1052
1053 Note that @code{gnatmake}
1054 takes into account all the Ada 95 rules that
1055 establish dependencies among units. These include dependencies that result
1056 from inlining subprogram bodies, and from
1057 generic instantiation. Unlike some other
1058 Ada make tools, @code{gnatmake} does not rely on the dependencies that were
1059 found by the compiler on a previous compilation, which may possibly
1060 be wrong when sources change. @code{gnatmake} determines the exact set of
1061 dependencies from scratch each time it is run.
1062
1063
1064 @node Introduction to Glide and GVD
1065 @section Introduction to Glide and GVD
1066 @cindex Glide
1067 @cindex GVD
1068 @noindent
1069 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.
1070
1071 @menu
1072 * Building a New Program with Glide::
1073 * Simple Debugging with GVD::
1074 * Other Glide Features::
1075 @end menu
1076
1077 @node Building a New Program with Glide
1078 @subsection Building a New Program with Glide
1079 @noindent
1080 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:
1081
1082 @smallexample
1083 $ glide&
1084 @end smallexample
1085
1086 @noindent
1087 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
1088 @itemize @bullet
1089 @item @code{Buffers}
1090 @item @code{Files}
1091 @item @code{Tools}
1092 @item @code{Edit}
1093 @item @code{Search}
1094 @item @code{Mule}
1095 @item @code{Glide}
1096 @item @code{Help}
1097 @end itemize
1098
1099 @noindent
1100 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.
1101
1102 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.
1103
1104 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:
1105 @smallexample
1106 with Ada.Text_IO; use Ada.Text_IO;
1107 procedure Hello is
1108 begin
1109 @end smallexample
1110
1111 @noindent
1112 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.
1113
1114 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.
1115
1116 Next enter the statement (with an intentional error, a missing semicolon) that will form the body of the loop:
1117 @smallexample
1118 Put_Line("Hello, World" & Integer'Image(I))
1119 @end smallexample
1120
1121 @noindent
1122 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.
1123
1124 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.
1125
1126 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.
1127
1128 To execute the program, choose @code{Ada} and then @code{Run}.  You should see the program's output displayed in the bottom window:
1129
1130 @smallexample
1131 Hello, world 1
1132 Hello, world 2
1133 Hello, world 3
1134 Hello, world 4
1135 Hello, world 5
1136 @end smallexample
1137
1138 @node Simple Debugging with GVD
1139 @subsection Simple Debugging with GVD
1140
1141 @noindent
1142 This section describes how to set breakpoints, examine/modify variables, and step through execution.
1143
1144 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:
1145
1146 @smallexample
1147 $ gvd hello
1148 @end smallexample
1149
1150 @noindent
1151 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}.
1152
1153 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.
1154
1155 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.
1156
1157 For this example, set a breakpoint at the statement where @code{Put_Line} is invoked.
1158
1159 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.
1160
1161 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.
1162
1163 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.
1164
1165 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}.
1166
1167 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.
1168
1169
1170 @node Other Glide Features
1171 @subsection Other Glide Features
1172
1173 @noindent
1174 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...}.
1175
1176 To abort a Glide command, type @key{Ctrl-g}.
1177
1178 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:
1179
1180 @smallexample
1181 $ glide hello.adb&
1182 @end smallexample
1183
1184 @noindent
1185 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.
1186
1187 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}.
1188
1189 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:
1190 @itemize @bullet
1191 @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)
1192 @item With the focus in one of the windows, select the desired buffer from the @code{Buffers} menu
1193 @end itemize
1194
1195 @noindent
1196 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1197
1198 @node The GNAT Compilation Model
1199 @chapter The GNAT Compilation Model
1200 @cindex GNAT compilation model
1201 @cindex Compilation model
1202
1203 @menu
1204 * Source Representation::
1205 * Foreign Language Representation::
1206 * File Naming Rules::
1207 * Using Other File Names::
1208 * Alternative File Naming Schemes::
1209 * Generating Object Files::
1210 * Source Dependencies::
1211 * The Ada Library Information Files::
1212 * Binding an Ada Program::
1213 * Mixed Language Programming::
1214 * Building Mixed Ada & C++ Programs::
1215 * Comparison between GNAT and C/C++ Compilation Models::
1216 * Comparison between GNAT and Conventional Ada Library Models::
1217 @end menu
1218
1219 @noindent
1220 This chapter describes the compilation model used by GNAT. Although
1221 similar to that used by other languages, such as C and C++, this model
1222 is substantially different from the traditional Ada compilation models,
1223 which are based on a library. The model is initially described without
1224 reference to the library-based model. If you have not previously used an
1225 Ada compiler, you need only read the first part of this chapter. The
1226 last section describes and discusses the differences between the GNAT
1227 model and the traditional Ada compiler models. If you have used other
1228 Ada compilers, this section will help you to understand those
1229 differences, and the advantages of the GNAT model.
1230
1231 @node Source Representation
1232 @section Source Representation
1233 @cindex Latin-1
1234
1235 @noindent
1236 Ada source programs are represented in standard text files, using
1237 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1238 7-bit ASCII set, plus additional characters used for
1239 representing foreign languages (@pxref{Foreign Language Representation}
1240 for support of non-USA character sets). The format effector characters
1241 are represented using their standard ASCII encodings, as follows:
1242
1243 @table @code
1244 @item VT
1245 @findex VT
1246 Vertical tab, @code{16#0B#}
1247
1248 @item HT
1249 @findex HT
1250 Horizontal tab, @code{16#09#}
1251
1252 @item CR
1253 @findex CR
1254 Carriage return, @code{16#0D#}
1255
1256 @item LF
1257 @findex LF
1258 Line feed, @code{16#0A#}
1259
1260 @item FF
1261 @findex FF
1262 Form feed, @code{16#0C#}
1263 @end table
1264
1265 @noindent
1266 Source files are in standard text file format. In addition, GNAT will
1267 recognize a wide variety of stream formats, in which the end of physical
1268 physical lines is marked by any of the following sequences:
1269 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1270 in accommodating files that are imported from other operating systems.
1271
1272 @cindex End of source file
1273 @cindex Source file, end
1274 @findex SUB
1275 The end of a source file is normally represented by the physical end of
1276 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1277 recognized as signalling the end of the source file. Again, this is
1278 provided for compatibility with other operating systems where this
1279 code is used to represent the end of file.
1280
1281 Each file contains a single Ada compilation unit, including any pragmas
1282 associated with the unit. For example, this means you must place a
1283 package declaration (a package @dfn{spec}) and the corresponding body in
1284 separate files. An Ada @dfn{compilation} (which is a sequence of
1285 compilation units) is represented using a sequence of files. Similarly,
1286 you will place each subunit or child unit in a separate file.
1287
1288 @node Foreign Language Representation
1289 @section Foreign Language Representation
1290
1291 @noindent
1292 GNAT supports the standard character sets defined in Ada 95 as well as
1293 several other non-standard character sets for use in localized versions
1294 of the compiler (@pxref{Character Set Control}).
1295 @menu
1296 * Latin-1::
1297 * Other 8-Bit Codes::
1298 * Wide Character Encodings::
1299 @end menu
1300
1301 @node Latin-1
1302 @subsection Latin-1
1303 @cindex Latin-1
1304
1305 @noindent
1306 The basic character set is Latin-1. This character set is defined by ISO
1307 standard 8859, part 1. The lower half (character codes @code{16#00#}
1308 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half is
1309 used to represent additional characters. These include extended letters
1310 used by European languages, such as French accents, the vowels with umlauts
1311 used in German, and the extra letter A-ring used in Swedish.
1312
1313 @findex Ada.Characters.Latin_1
1314 For a complete list of Latin-1 codes and their encodings, see the source
1315 file of library unit @code{Ada.Characters.Latin_1} in file
1316 @file{a-chlat1.ads}.
1317 You may use any of these extended characters freely in character or
1318 string literals. In addition, the extended characters that represent
1319 letters can be used in identifiers.
1320
1321 @node Other 8-Bit Codes
1322 @subsection Other 8-Bit Codes
1323
1324 @noindent
1325 GNAT also supports several other 8-bit coding schemes:
1326
1327 @table @asis
1328 @cindex Latin-2
1329 @item Latin-2
1330 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1331 equivalence.
1332
1333 @item Latin-3
1334 @cindex Latin-3
1335 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1336 equivalence.
1337
1338 @item Latin-4
1339 @cindex Latin-4
1340 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1341 equivalence.
1342
1343 @item Latin-5
1344 @cindex Latin-5
1345 @cindex Cyrillic
1346 Latin-4 letters (Cyrillic) allowed in identifiers, with uppercase and lowercase
1347 equivalence.
1348
1349 @item IBM PC (code page 437)
1350 @cindex code page 437
1351 This code page is the normal default for PCs in the U.S. It corresponds
1352 to the original IBM PC character set. This set has some, but not all, of
1353 the extended Latin-1 letters, but these letters do not have the same
1354 encoding as Latin-1. In this mode, these letters are allowed in
1355 identifiers with uppercase and lowercase equivalence.
1356
1357 @item IBM PC (code page 850)
1358 @cindex code page 850
1359 This code page is a modification of 437 extended to include all the
1360 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1361 mode, all these letters are allowed in identifiers with uppercase and
1362 lowercase equivalence.
1363
1364 @item Full Upper 8-bit
1365 Any character in the range 80-FF allowed in identifiers, and all are
1366 considered distinct. In other words, there are no uppercase and lowercase
1367 equivalences in this range. This is useful in conjunction with
1368 certain encoding schemes used for some foreign character sets (e.g.
1369 the typical method of representing Chinese characters on the PC).
1370
1371 @item No Upper-Half
1372 No upper-half characters in the range 80-FF are allowed in identifiers.
1373 This gives Ada 83 compatibility for identifier names.
1374 @end table
1375
1376 @noindent
1377 For precise data on the encodings permitted, and the uppercase and lowercase
1378 equivalences that are recognized, see the file @file{csets.adb} in
1379 the GNAT compiler sources. You will need to obtain a full source release
1380 of GNAT to obtain this file.
1381
1382 @node Wide Character Encodings
1383 @subsection Wide Character Encodings
1384
1385 @noindent
1386 GNAT allows wide character codes to appear in character and string
1387 literals, and also optionally in identifiers, by means of the following
1388 possible encoding schemes:
1389
1390 @table @asis
1391
1392 @item Hex Coding
1393 In this encoding, a wide character is represented by the following five
1394 character sequence:
1395
1396 @smallexample
1397 ESC a b c d
1398 @end smallexample
1399
1400 @noindent
1401 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1402 characters (using uppercase letters) of the wide character code. For
1403 example, ESC A345 is used to represent the wide character with code
1404 @code{16#A345#}.
1405 This scheme is compatible with use of the full Wide_Character set.
1406
1407 @item Upper-Half Coding
1408 @cindex Upper-Half Coding
1409 The wide character with encoding @code{16#abcd#} where the upper bit is on (in
1410 other words, "a" is in the range 8-F) is represented as two bytes,
1411 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1412 character, but is not required to be in the upper half. This method can
1413 be also used for shift-JIS or EUC, where the internal coding matches the
1414 external coding.
1415
1416 @item Shift JIS Coding
1417 @cindex Shift JIS Coding
1418 A wide character is represented by a two-character sequence,
1419 @code{16#ab#} and
1420 @code{16#cd#}, with the restrictions described for upper-half encoding as
1421 described above. The internal character code is the corresponding JIS
1422 character according to the standard algorithm for Shift-JIS
1423 conversion. Only characters defined in the JIS code set table can be
1424 used with this encoding method.
1425
1426 @item EUC Coding
1427 @cindex EUC Coding
1428 A wide character is represented by a two-character sequence
1429 @code{16#ab#} and
1430 @code{16#cd#}, with both characters being in the upper half. The internal
1431 character code is the corresponding JIS character according to the EUC
1432 encoding algorithm. Only characters defined in the JIS code set table
1433 can be used with this encoding method.
1434
1435 @item UTF-8 Coding
1436 A wide character is represented using
1437 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1438 10646-1/Am.2. Depending on the character value, the representation
1439 is a one, two, or three byte sequence:
1440 @smallexample
1441 @iftex
1442 @leftskip=.7cm
1443 @end iftex
1444 16#0000#-16#007f#: 2#0xxxxxxx#
1445 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
1446 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1447
1448 @end smallexample
1449
1450 @noindent
1451 where the xxx bits correspond to the left-padded bits of the
1452 16-bit character value. Note that all lower half ASCII characters
1453 are represented as ASCII bytes and all upper half characters and
1454 other wide characters are represented as sequences of upper-half
1455 (The full UTF-8 scheme allows for encoding 31-bit characters as
1456 6-byte sequences, but in this implementation, all UTF-8 sequences
1457 of four or more bytes length will be treated as illegal).
1458 @item Brackets Coding
1459 In this encoding, a wide character is represented by the following eight
1460 character sequence:
1461
1462 @smallexample
1463 [ " a b c d " ]
1464 @end smallexample
1465
1466 @noindent
1467 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1468 characters (using uppercase letters) of the wide character code. For
1469 example, ["A345"] is used to represent the wide character with code
1470 @code{16#A345#}. It is also possible (though not required) to use the
1471 Brackets coding for upper half characters. For example, the code
1472 @code{16#A3#} can be represented as @code{["A3"]}.
1473
1474 This scheme is compatible with use of the full Wide_Character set,
1475 and is also the method used for wide character encoding in the standard
1476 ACVC (Ada Compiler Validation Capability) test suite distributions.
1477
1478 @end table
1479
1480 @noindent
1481 Note: Some of these coding schemes do not permit the full use of the
1482 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
1483 use of the upper half of the Latin-1 set.
1484
1485 @node File Naming Rules
1486 @section File Naming Rules
1487
1488 @noindent
1489 The default file name is determined by the name of the unit that the
1490 file contains. The name is formed by taking the full expanded name of
1491 the unit and replacing the separating dots with hyphens and using
1492 lowercase for all letters.
1493
1494 An exception arises if the file name generated by the above rules starts
1495 with one of the characters
1496 a,g,i, or s,
1497 and the second character is a
1498 minus. In this case, the character tilde is used in place
1499 of the minus. The reason for this special rule is to avoid clashes with
1500 the standard names for child units of the packages System, Ada,
1501 Interfaces, and GNAT, which use the prefixes
1502 s- a- i- and g-
1503 respectively.
1504
1505 The file extension is @file{.ads} for a spec and
1506 @file{.adb} for a body. The following list shows some
1507 examples of these rules.
1508
1509 @table @file
1510 @item main.ads
1511 Main (spec)
1512 @item main.adb
1513 Main (body)
1514 @item arith_functions.ads
1515 Arith_Functions (package spec)
1516 @item arith_functions.adb
1517 Arith_Functions (package body)
1518 @item func-spec.ads
1519 Func.Spec (child package spec)
1520 @item func-spec.adb
1521 Func.Spec (child package body)
1522 @item main-sub.adb
1523 Sub (subunit of Main)
1524 @item a~bad.adb
1525 A.Bad (child package body)
1526 @end table
1527
1528 @noindent
1529 Following these rules can result in excessively long
1530 file names if corresponding
1531 unit names are long (for example, if child units or subunits are
1532 heavily nested). An option is available to shorten such long file names
1533 (called file name "krunching"). This may be particularly useful when
1534 programs being developed with GNAT are to be used on operating systems
1535 with limited file name lengths. @xref{Using gnatkr}.
1536
1537 Of course, no file shortening algorithm can guarantee uniqueness over
1538 all possible unit names; if file name krunching is used, it is your
1539 responsibility to ensure no name clashes occur. Alternatively you
1540 can specify the exact file names that you want used, as described
1541 in the next section. Finally, if your Ada programs are migrating from a
1542 compiler with a different naming convention, you can use the gnatchop
1543 utility to produce source files that follow the GNAT naming conventions.
1544 (For details @pxref{Renaming Files Using gnatchop}.)
1545
1546 @node Using Other File Names
1547 @section Using Other File Names
1548 @cindex File names
1549
1550 @noindent
1551 In the previous section, we have described the default rules used by
1552 GNAT to determine the file name in which a given unit resides. It is
1553 often convenient to follow these default rules, and if you follow them,
1554 the compiler knows without being explicitly told where to find all
1555 the files it needs.
1556
1557 However, in some cases, particularly when a program is imported from
1558 another Ada compiler environment, it may be more convenient for the
1559 programmer to specify which file names contain which units. GNAT allows
1560 arbitrary file names to be used by means of the Source_File_Name pragma.
1561 The form of this pragma is as shown in the following examples:
1562 @cindex Source_File_Name pragma
1563
1564 @smallexample
1565 @group
1566 @cartouche
1567 @b{pragma} Source_File_Name (My_Utilities.Stacks,
1568   Spec_File_Name => "myutilst_a.ada");
1569 @b{pragma} Source_File_name (My_Utilities.Stacks,
1570   Body_File_Name => "myutilst.ada");
1571 @end cartouche
1572 @end group
1573 @end smallexample
1574
1575 @noindent
1576 As shown in this example, the first argument for the pragma is the unit
1577 name (in this example a child unit). The second argument has the form
1578 of a named association. The identifier
1579 indicates whether the file name is for a spec or a body;
1580 the file name itself is given by a string literal.
1581
1582 The source file name pragma is a configuration pragma, which means that
1583 normally it will be placed in the @file{gnat.adc}
1584 file used to hold configuration
1585 pragmas that apply to a complete compilation environment.
1586 For more details on how the @file{gnat.adc} file is created and used
1587 @pxref{Handling of Configuration Pragmas}
1588 @cindex @file{gnat.adc}
1589
1590 GNAT allows completely arbitrary file names to be specified using the
1591 source file name pragma. However, if the file name specified has an
1592 extension other than @file{.ads} or @file{.adb} it is necessary to use a special
1593 syntax when compiling the file. The name in this case must be preceded
1594 by the special sequence @code{-x} followed by a space and the name of the
1595 language, here @code{ada}, as in:
1596
1597 @smallexample
1598 $ gcc -c -x ada peculiar_file_name.sim
1599 @end smallexample
1600
1601 @noindent
1602 @code{gnatmake} handles non-standard file names in the usual manner (the
1603 non-standard file name for the main program is simply used as the
1604 argument to gnatmake). Note that if the extension is also non-standard,
1605 then it must be included in the gnatmake command, it may not be omitted.
1606
1607 @node Alternative File Naming Schemes
1608 @section Alternative File Naming Schemes
1609 @cindex File naming schemes, alternative
1610 @cindex File names
1611
1612 In the previous section, we described the use of the @code{Source_File_Name}
1613 pragma to allow arbitrary names to be assigned to individual source files.
1614 However, this approach requires one pragma for each file, and especially in
1615 large systems can result in very long @file{gnat.adc} files, and also create
1616 a maintenance problem.
1617
1618 GNAT also provides a facility for specifying systematic file naming schemes
1619 other than the standard default naming scheme previously described. An
1620 alternative scheme for naming is specified by the use of
1621 @code{Source_File_Name} pragmas having the following format:
1622 @cindex Source_File_Name pragma
1623
1624 @smallexample
1625 pragma Source_File_Name (
1626    Spec_File_Name  => FILE_NAME_PATTERN
1627  [,Casing          => CASING_SPEC]
1628  [,Dot_Replacement => STRING_LITERAL]);
1629
1630 pragma Source_File_Name (
1631    Body_File_Name  => FILE_NAME_PATTERN
1632  [,Casing          => CASING_SPEC]
1633  [,Dot_Replacement => STRING_LITERAL]);
1634
1635 pragma Source_File_Name (
1636    Subunit_File_Name  => FILE_NAME_PATTERN
1637  [,Casing             => CASING_SPEC]
1638  [,Dot_Replacement    => STRING_LITERAL]);
1639
1640 FILE_NAME_PATTERN ::= STRING_LITERAL
1641 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1642
1643 @end smallexample
1644
1645 @noindent
1646 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1647 It contains a single asterisk character, and the unit name is substituted
1648 systematically for this asterisk. The optional parameter
1649 @code{Casing} indicates
1650 whether the unit name is to be all upper-case letters, all lower-case letters,
1651 or mixed-case. If no
1652 @code{Casing} parameter is used, then the default is all
1653 lower-case.
1654
1655 The optional @code{Dot_Replacement} string is used to replace any periods
1656 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1657 argument is used then separating dots appear unchanged in the resulting
1658 file name.
1659 Although the above syntax indicates that the
1660 @code{Casing} argument must appear
1661 before the @code{Dot_Replacement} argument, but it
1662 is also permissible to write these arguments in the opposite order.
1663
1664 As indicated, it is possible to specify different naming schemes for
1665 bodies, specs, and subunits. Quite often the rule for subunits is the
1666 same as the rule for bodies, in which case, there is no need to give
1667 a separate @code{Subunit_File_Name} rule, and in this case the
1668 @code{Body_File_name} rule is used for subunits as well.
1669
1670 The separate rule for subunits can also be used to implement the rather
1671 unusual case of a compilation environment (e.g. a single directory) which
1672 contains a subunit and a child unit with the same unit name. Although
1673 both units cannot appear in the same partition, the Ada Reference Manual
1674 allows (but does not require) the possibility of the two units coexisting
1675 in the same environment.
1676
1677 The file name translation works in the following steps:
1678
1679 @itemize @bullet
1680
1681 @item
1682 If there is a specific @code{Source_File_Name} pragma for the given unit,
1683 then this is always used, and any general pattern rules are ignored.
1684
1685 @item
1686 If there is a pattern type @code{Source_File_Name} pragma that applies to
1687 the unit, then the resulting file name will be used if the file exists. If
1688 more than one pattern matches, the latest one will be tried first, and the
1689 first attempt resulting in a reference to a file that exists will be used.
1690
1691 @item
1692 If no pattern type @code{Source_File_Name} pragma that applies to the unit
1693 for which the corresponding file exists, then the standard GNAT default
1694 naming rules are used.
1695
1696 @end itemize
1697
1698 @noindent
1699 As an example of the use of this mechanism, consider a commonly used scheme
1700 in which file names are all lower case, with separating periods copied
1701 unchanged to the resulting file name, and specs end with ".1.ada", and
1702 bodies end with ".2.ada". GNAT will follow this scheme if the following
1703 two pragmas appear:
1704
1705 @smallexample
1706 pragma Source_File_Name
1707   (Spec_File_Name => "*.1.ada");
1708 pragma Source_File_Name
1709   (Body_File_Name => "*.2.ada");
1710 @end smallexample
1711
1712 @noindent
1713 The default GNAT scheme is actually implemented by providing the following
1714 default pragmas internally:
1715
1716 @smallexample
1717 pragma Source_File_Name
1718   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
1719 pragma Source_File_Name
1720   (Body_File_Name => "*.adb", Dot_Replacement => "-");
1721 @end smallexample
1722
1723 @noindent
1724 Our final example implements a scheme typically used with one of the
1725 Ada 83 compilers, where the separator character for subunits was "__"
1726 (two underscores), specs were identified by adding @file{_.ADA}, bodies
1727 by adding @file{.ADA}, and subunits by
1728 adding @file{.SEP}. All file names were
1729 upper case. Child units were not present of course since this was an
1730 Ada 83 compiler, but it seems reasonable to extend this scheme to use
1731 the same double underscore separator for child units.
1732
1733 @smallexample
1734 pragma Source_File_Name
1735   (Spec_File_Name => "*_.ADA",
1736    Dot_Replacement => "__",
1737    Casing = Uppercase);
1738 pragma Source_File_Name
1739   (Body_File_Name => "*.ADA",
1740    Dot_Replacement => "__",
1741    Casing = Uppercase);
1742 pragma Source_File_Name
1743   (Subunit_File_Name => "*.SEP",
1744    Dot_Replacement => "__",
1745    Casing = Uppercase);
1746 @end smallexample
1747
1748 @node Generating Object Files
1749 @section Generating Object Files
1750
1751 @noindent
1752 An Ada program consists of a set of source files, and the first step in
1753 compiling the program is to generate the corresponding object files.
1754 These are generated by compiling a subset of these source files.
1755 The files you need to compile are the following:
1756
1757 @itemize @bullet
1758 @item
1759 If a package spec has no body, compile the package spec to produce the
1760 object file for the package.
1761
1762 @item
1763 If a package has both a spec and a body, compile the body to produce the
1764 object file for the package. The source file for the package spec need
1765 not be compiled in this case because there is only one object file, which
1766 contains the code for both the spec and body of the package.
1767
1768 @item
1769 For a subprogram, compile the subprogram body to produce the object file
1770 for the subprogram. The spec, if one is present, is as usual in a
1771 separate file, and need not be compiled.
1772
1773 @item
1774 @cindex Subunits
1775 In the case of subunits, only compile the parent unit. A single object
1776 file is generated for the entire subunit tree, which includes all the
1777 subunits.
1778
1779 @item
1780 Compile child units independently of their parent units
1781 (though, of course, the spec of all the ancestor unit must be present in order
1782 to compile a child unit).
1783
1784 @item
1785 @cindex Generics
1786 Compile generic units in the same manner as any other units. The object
1787 files in this case are small dummy files that contain at most the
1788 flag used for elaboration checking. This is because GNAT always handles generic
1789 instantiation by means of macro expansion. However, it is still necessary to
1790 compile generic units, for dependency checking and elaboration purposes.
1791 @end itemize
1792
1793 @noindent
1794 The preceding rules describe the set of files that must be compiled to
1795 generate the object files for a program. Each object file has the same
1796 name as the corresponding source file, except that the extension is
1797 @file{.o} as usual.
1798
1799 You may wish to compile other files for the purpose of checking their
1800 syntactic and semantic correctness. For example, in the case where a
1801 package has a separate spec and body, you would not normally compile the
1802 spec. However, it is convenient in practice to compile the spec to make
1803 sure it is error-free before compiling clients of this spec, because such
1804 compilations will fail if there is an error in the spec.
1805
1806 GNAT provides an option for compiling such files purely for the
1807 purposes of checking correctness; such compilations are not required as
1808 part of the process of building a program. To compile a file in this
1809 checking mode, use the @option{-gnatc} switch.
1810
1811 @node Source Dependencies
1812 @section Source Dependencies
1813
1814 @noindent
1815 A given object file clearly depends on the source file which is compiled
1816 to produce it. Here we are using @dfn{depends} in the sense of a typical
1817 @code{make} utility; in other words, an object file depends on a source
1818 file if changes to the source file require the object file to be
1819 recompiled.
1820 In addition to this basic dependency, a given object may depend on
1821 additional source files as follows:
1822
1823 @itemize @bullet
1824 @item
1825 If a file being compiled @code{with}'s a unit @var{X}, the object file
1826 depends on the file containing the spec of unit @var{X}. This includes
1827 files that are @code{with}'ed implicitly either because they are parents
1828 of @code{with}'ed child units or they are run-time units required by the
1829 language constructs used in a particular unit.
1830
1831 @item
1832 If a file being compiled instantiates a library level generic unit, the
1833 object file depends on both the spec and body files for this generic
1834 unit.
1835
1836 @item
1837 If a file being compiled instantiates a generic unit defined within a
1838 package, the object file depends on the body file for the package as
1839 well as the spec file.
1840
1841 @item
1842 @findex Inline
1843 @cindex @option{-gnatn} switch
1844 If a file being compiled contains a call to a subprogram for which
1845 pragma @code{Inline} applies and inlining is activated with the
1846 @option{-gnatn} switch, the object file depends on the file containing the
1847 body of this subprogram as well as on the file containing the spec. Note
1848 that for inlining to actually occur as a result of the use of this switch,
1849 it is necessary to compile in optimizing mode.
1850
1851 @cindex @option{-gnatN} switch
1852 The use of @option{-gnatN} activates a more extensive inlining optimization
1853 that is performed by the front end of the compiler. This inlining does
1854 not require that the code generation be optimized. Like @option{-gnatn},
1855 the use of this switch generates additional dependencies.
1856
1857 @item
1858 If an object file O  depends on the proper body of a subunit through inlining
1859 or instantiation, it depends on the parent unit of the subunit. This means that
1860 any modification of the parent unit or one of its subunits affects the
1861 compilation of O.
1862
1863 @item
1864 The object file for a parent unit depends on all its subunit body files.
1865
1866 @item
1867 The previous two rules meant that for purposes of computing dependencies and
1868 recompilation, a body and all its subunits are treated as an indivisible whole.
1869
1870 @noindent
1871 These rules are applied transitively: if unit @code{A} @code{with}'s
1872 unit @code{B}, whose elaboration calls an inlined procedure in package
1873 @code{C}, the object file for unit @code{A} will depend on the body of
1874 @code{C}, in file @file{c.adb}.
1875
1876 The set of dependent files described by these rules includes all the
1877 files on which the unit is semantically dependent, as described in the
1878 Ada 95 Language Reference Manual. However, it is a superset of what the
1879 ARM describes, because it includes generic, inline, and subunit dependencies.
1880
1881 An object file must be recreated by recompiling the corresponding source
1882 file if any of the source files on which it depends are modified. For
1883 example, if the @code{make} utility is used to control compilation,
1884 the rule for an Ada object file must mention all the source files on
1885 which the object file depends, according to the above definition.
1886 The determination of the necessary
1887 recompilations is done automatically when one uses @code{gnatmake}.
1888 @end itemize
1889
1890 @node The Ada Library Information Files
1891 @section The Ada Library Information Files
1892 @cindex Ada Library Information files
1893 @cindex @file{ali} files
1894
1895 @noindent
1896 Each compilation actually generates two output files. The first of these
1897 is the normal object file that has a @file{.o} extension. The second is a
1898 text file containing full dependency information. It has the same
1899 name as the source file, but an @file{.ali} extension.
1900 This file is known as the Ada Library Information (@file{ali}) file.
1901 The following information is contained in the @file{ali} file.
1902
1903 @itemize @bullet
1904 @item
1905 Version information (indicates which version of GNAT was used to compile
1906 the unit(s) in question)
1907
1908 @item
1909 Main program information (including priority and time slice settings,
1910 as well as the wide character encoding used during compilation).
1911
1912 @item
1913 List of arguments used in the @code{gcc} command for the compilation
1914
1915 @item
1916 Attributes of the unit, including configuration pragmas used, an indication
1917 of whether the compilation was successful, exception model used etc.
1918
1919 @item
1920 A list of relevant restrictions applying to the unit (used for consistency)
1921 checking.
1922
1923 @item
1924 Categorization information (e.g. use of pragma @code{Pure}).
1925
1926 @item
1927 Information on all @code{with}'ed units, including presence of
1928 @code{Elaborate} or @code{Elaborate_All} pragmas.
1929
1930 @item
1931 Information from any @code{Linker_Options} pragmas used in the unit
1932
1933 @item
1934 Information on the use of @code{Body_Version} or @code{Version}
1935 attributes in the unit.
1936
1937 @item
1938 Dependency information. This is a list of files, together with
1939 time stamp and checksum information. These are files on which
1940 the unit depends in the sense that recompilation is required
1941 if any of these units are modified.
1942
1943 @item
1944 Cross-reference data. Contains information on all entities referenced
1945 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
1946 provide cross-reference information.
1947
1948 @end itemize
1949
1950 @noindent
1951 For a full detailed description of the format of the @file{ali} file,
1952 see the source of the body of unit @code{Lib.Writ}, contained in file
1953 @file{lib-writ.adb} in the GNAT compiler sources.
1954
1955 @node Binding an Ada Program
1956 @section Binding an Ada Program
1957
1958 @noindent
1959 When using languages such as C and C++, once the source files have been
1960 compiled the only remaining step in building an executable program
1961 is linking the object modules together. This means that it is possible to
1962 link an inconsistent version of a program, in which two units have
1963 included different versions of the same header.
1964
1965 The rules of Ada do not permit such an inconsistent program to be built.
1966 For example, if two clients have different versions of the same package,
1967 it is illegal to build a program containing these two clients.
1968 These rules are enforced by the GNAT binder, which also determines an
1969 elaboration order consistent with the Ada rules.
1970
1971 The GNAT binder is run after all the object files for a program have
1972 been created. It is given the name of the main program unit, and from
1973 this it determines the set of units required by the program, by reading the
1974 corresponding ALI files. It generates error messages if the program is
1975 inconsistent or if no valid order of elaboration exists.
1976
1977 If no errors are detected, the binder produces a main program, in Ada by
1978 default, that contains calls to the elaboration procedures of those
1979 compilation unit that require them, followed by
1980 a call to the main program. This Ada program is compiled to generate the
1981 object file for the main program. The name of
1982 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
1983 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
1984 main program unit.
1985
1986 Finally, the linker is used to build the resulting executable program,
1987 using the object from the main program from the bind step as well as the
1988 object files for the Ada units of the program.
1989
1990 @node Mixed Language Programming
1991 @section Mixed Language Programming
1992 @cindex Mixed Language Programming
1993
1994 @menu
1995 * Interfacing to C::
1996 * Calling Conventions::
1997 @end menu
1998
1999 @node Interfacing to C
2000 @subsection Interfacing to C
2001 @noindent
2002 There are two ways to
2003 build a program that contains some Ada files and some other language
2004 files depending on whether the main program is in Ada or not.
2005 If the main program is in Ada, you should proceed as follows:
2006
2007 @enumerate
2008 @item
2009 Compile the other language files to generate object files. For instance:
2010 @smallexample
2011 gcc -c file1.c
2012 gcc -c file2.c
2013 @end smallexample
2014
2015 @item
2016 Compile the Ada units to produce a set of object files and ALI
2017 files. For instance:
2018 @smallexample
2019 gnatmake -c my_main.adb
2020 @end smallexample
2021
2022 @item
2023 Run the Ada binder on the Ada main program. For instance:
2024 @smallexample
2025 gnatbind my_main.ali
2026 @end smallexample
2027
2028 @item
2029 Link the Ada main program, the Ada objects and the other language
2030 objects. For instance:
2031 @smallexample
2032 gnatlink my_main.ali file1.o file2.o
2033 @end smallexample
2034 @end enumerate
2035
2036 The three last steps can be grouped in a single command:
2037 @smallexample
2038 gnatmake my_main.adb -largs file1.o file2.o
2039 @end smallexample
2040
2041 @cindex Binder output file
2042 @noindent
2043 If the main program is in some language other than Ada, you may
2044 have more than one entry point in the Ada subsystem. You must use a
2045 special option of the binder to generate callable routines to initialize
2046 and finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2047 Calls to the initialization and finalization routines must be inserted in
2048 the main program, or some other appropriate point in the code. The call to
2049 initialize the Ada units must occur before the first Ada subprogram is
2050 called, and the call to finalize the Ada units must occur after the last
2051 Ada subprogram returns. You use the same procedure for building the
2052 program as described previously. In this case, however, the binder
2053 only places the initialization and finalization subprograms into file
2054 @file{b~@var{xxx}.adb} instead of the main program.
2055 So, if the main program is not in Ada, you should proceed as follows:
2056
2057 @enumerate
2058 @item
2059 Compile the other language files to generate object files. For instance:
2060 @smallexample
2061 gcc -c file1.c
2062 gcc -c file2.c
2063 @end smallexample
2064
2065 @item
2066 Compile the Ada units to produce a set of object files and ALI
2067 files. For instance:
2068 @smallexample
2069 gnatmake -c entry_point1.adb
2070 gnatmake -c entry_point2.adb
2071 @end smallexample
2072
2073 @item
2074 Run the Ada binder on the Ada main program. For instance:
2075 @smallexample
2076 gnatbind -n entry_point1.ali entry_point2.ali
2077 @end smallexample
2078
2079 @item
2080 Link the Ada main program, the Ada objects and the other language
2081 objects. You only need to give the last entry point here. For instance:
2082 @smallexample
2083 gnatlink entry_point2.ali file1.o file2.o
2084 @end smallexample
2085 @end enumerate
2086
2087 @node Calling Conventions
2088 @subsection Calling Conventions
2089 @cindex Foreign Languages
2090 @cindex Calling Conventions
2091 GNAT follows standard calling sequence conventions and will thus interface
2092 to any other language that also follows these conventions. The following
2093 Convention identifiers are recognized by GNAT:
2094
2095 @itemize @bullet
2096 @cindex Interfacing to Ada
2097 @cindex Other Ada compilers
2098 @cindex Convention Ada
2099 @item
2100 Ada. This indicates that the standard Ada calling sequence will be
2101 used and all Ada data items may be passed without any limitations in the
2102 case where GNAT is used to generate both the caller and callee. It is also
2103 possible to mix GNAT generated code and code generated by another Ada
2104 compiler. In this case, the data types should be restricted to simple
2105 cases, including primitive types. Whether complex data types can be passed
2106 depends on the situation. Probably it is safe to pass simple arrays, such
2107 as arrays of integers or floats. Records may or may not work, depending
2108 on whether both compilers lay them out identically. Complex structures
2109 involving variant records, access parameters, tasks, or protected types,
2110 are unlikely to be able to be passed.
2111
2112 Note that in the case of GNAT running
2113 on a platform that supports DEC Ada 83, a higher degree of compatibility
2114 can be guaranteed, and in particular records are layed out in an identical
2115 manner in the two compilers. Note also that if output from two different
2116 compilers is mixed, the program is responsible for dealing with elaboration
2117 issues. Probably the safest approach is to write the main program in the
2118 version of Ada other than GNAT, so that it takes care of its own elaboration
2119 requirements, and then call the GNAT-generated adainit procedure to ensure
2120 elaboration of the GNAT components. Consult the documentation of the other
2121 Ada compiler for further details on elaboration.
2122
2123 However, it is not possible to mix the tasking run time of GNAT and
2124 DEC Ada 83, All the tasking operations must either be entirely within
2125 GNAT compiled sections of the program, or entirely within DEC Ada 83
2126 compiled sections of the program.
2127
2128 @cindex Interfacing to Assembly
2129 @cindex Convention Assembler
2130 @item
2131 Assembler. Specifies assembler as the convention. In practice this has the
2132 same effect as convention Ada (but is not equivalent in the sense of being
2133 considered the same convention).
2134
2135 @cindex Convention Asm
2136 @findex Asm
2137 @item
2138 Asm. Equivalent to Assembler.
2139
2140 @cindex Convention Asm
2141 @findex Asm
2142 @item
2143 Asm. Equivalent to Assembly.
2144
2145 @cindex Interfacing to COBOL
2146 @cindex Convention COBOL
2147 @findex COBOL
2148 @item
2149 COBOL. Data will be passed according to the conventions described
2150 in section B.4 of the Ada 95 Reference Manual.
2151
2152 @findex C
2153 @cindex Interfacing to C
2154 @cindex Convention C
2155 @item
2156 C. Data will be passed according to the conventions described
2157 in section B.3 of the Ada 95 Reference Manual.
2158
2159 @cindex Convention Default
2160 @findex Default
2161 @item
2162 Default. Equivalent to C.
2163
2164 @cindex Convention External
2165 @findex External
2166 @item
2167 External. Equivalent to C.
2168
2169 @findex C++
2170 @cindex Interfacing to C++
2171 @cindex Convention C++
2172 @item
2173 CPP. This stands for C++. For most purposes this is identical to C.
2174 See the separate description of the specialized GNAT pragmas relating to
2175 C++ interfacing for further details.
2176
2177 @findex Fortran
2178 @cindex Interfacing to Fortran
2179 @cindex Convention Fortran
2180 @item
2181 Fortran. Data will be passed according to the conventions described
2182 in section B.5 of the Ada 95 Reference Manual.
2183
2184 @item
2185 Intrinsic. This applies to an intrinsic operation, as defined in the Ada 95
2186 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
2187 this means that the body of the subprogram is provided by the compiler itself,
2188 usually by means of an efficient code sequence, and that the user does not
2189 supply an explicit body for it. In an application program, the pragma can only
2190 be applied to the following two sets of names, which the GNAT compiler
2191 recognizes.
2192 @itemize @bullet
2193 @item
2194 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
2195 Arithmetic.  The corresponding subprogram declaration must have
2196 two formal parameters. The
2197 first one must be a signed integer type or a modular type with a binary
2198 modulus, and the second parameter must be of type Natural.
2199 The return type must be the same as the type of the first argument. The size
2200 of this type can only be 8, 16, 32, or 64.
2201 @item binary arithmetic operators: "+", "-", "*", "/"
2202 The corresponding operator declaration must have parameters and result type
2203 that have the same root numeric type (for example, all three are long_float
2204 types). This simplifies the definition of operations that use type checking
2205 to perform dimensional checks:
2206 @smallexample
2207 type Distance is new Long_Float;
2208 type Time     is new Long_Float;
2209 type Velocity is new Long_Float;
2210 function "/" (D : Distance; T : Time)
2211   return Velocity;
2212 pragma Import (Intrinsic, "/");
2213 @end smallexample
2214 @noindent
2215 This common idiom is often programmed with a generic definition and an explicit
2216 body. The pragma makes it simpler to introduce such declarations. It incurs
2217 no overhead in compilation time or code size, because it is implemented as a
2218 single machine instruction.
2219 @end itemize
2220 @noindent
2221
2222 @findex Stdcall
2223 @cindex Convention Stdcall
2224 @item
2225 Stdcall. This is relevant only to NT/Win95 implementations of GNAT,
2226 and specifies that the Stdcall calling sequence will be used, as defined
2227 by the NT API.
2228
2229 @findex DLL
2230 @cindex Convention DLL
2231 @item
2232 DLL. This is equivalent to Stdcall.
2233
2234 @findex Win32
2235 @cindex Convention Win32
2236 @item
2237 Win32. This is equivalent to Stdcall.
2238
2239 @findex Stubbed
2240 @cindex Convention Stubbed
2241 @item
2242 Stubbed. This is a special convention that indicates that the compiler
2243 should provide a stub body that raises @code{Program_Error}.
2244 @end itemize
2245
2246 @noindent
2247 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2248 that can be used to parametrize conventions and allow additional synonyms
2249 to be specified. For example if you have legacy code in which the convention
2250 identifier Fortran77 was used for Fortran, you can use the configuration
2251 pragma:
2252
2253 @smallexample
2254    pragma Convention_Identifier (Fortran77, Fortran);
2255 @end smallexample
2256
2257 @noindent
2258 And from now on the identifier Fortran77 may be used as a convention
2259 identifier (for example in an @code{Import} pragma) with the same
2260 meaning as Fortran.
2261
2262 @node Building Mixed Ada & C++ Programs
2263 @section Building Mixed Ada & C++ Programs
2264
2265 @noindent
2266 Building a mixed application containing both Ada and C++ code may be a
2267 challenge for the unaware programmer. As a matter of fact, this
2268 interfacing has not been standardized in the Ada 95 reference manual due
2269 to the immaturity and lack of standard of C++ at the time. This
2270 section gives a few hints that should make this task easier. In
2271 particular the first section addresses the differences with
2272 interfacing with C. The second section looks into the delicate problem
2273 of linking the complete application from its Ada and C++ parts. The last
2274 section give some hints on how the GNAT run time can be adapted in order
2275 to allow inter-language dispatching with a new C++ compiler.
2276
2277 @menu
2278 * Interfacing to C++::
2279 * Linking a Mixed C++ & Ada Program::
2280 * A Simple Example::
2281 * Adapting the Run Time to a New C++ Compiler::
2282 @end menu
2283
2284 @node Interfacing to C++
2285 @subsection Interfacing to C++
2286
2287 @noindent
2288 GNAT supports interfacing with C++ compilers generating code that is
2289 compatible with the standard Application Binary Interface of the given
2290 platform.
2291
2292 @noindent
2293 Interfacing can be done at 3 levels: simple data, subprograms and
2294 classes. In the first 2 cases, GNAT offer a specific @var{Convention
2295 CPP} that behaves exactly like @var{Convention C}. Usually C++ mangle
2296 names of subprograms and currently GNAT does not provide any help to
2297 solve the demangling problem. This problem can be addressed in 2 ways:
2298 @itemize @bullet
2299 @item
2300 by modifying the C++ code in order to force a C convention using
2301 the @var{extern "C"} syntax.
2302
2303 @item
2304 by figuring out the mangled name and use it as the Link_Name argument of
2305 the pragma import.
2306 @end itemize
2307
2308 @noindent
2309 Interfacing at the class level can be achieved by using the GNAT specific
2310 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
2311 Reference Manual for additional information.
2312
2313 @node Linking a Mixed C++ & Ada Program
2314 @subsection Linking a Mixed C++ & Ada Program
2315
2316 @noindent
2317 Usually the linker of the C++ development system must be used to link
2318 mixed applications because most C++ systems will resolve elaboration
2319 issues (such as calling constructors on global class instances)
2320 transparently during the link phase. GNAT has been adapted to ease the
2321 use of a foreign linker for the last phase. Three cases can be
2322 considered:
2323 @enumerate
2324
2325 @item
2326 Using GNAT and G++ (GNU C++ compiler) from the same GCC
2327 installation. The c++ linker can simply be called by using the c++
2328 specific driver called @code{c++}. Note that this setup is not
2329 very common because it may request recompiling the whole GCC
2330 tree from sources and it does not allow to upgrade easily to a new
2331 version of one compiler for one of the two languages without taking the
2332 risk of destabilizing the other.
2333
2334 @smallexample
2335 $ c++ -c file1.C
2336 $ c++ -c file2.C
2337 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
2338 @end smallexample
2339
2340 @item
2341 Using GNAT and G++ from 2 different GCC installations. If both compilers
2342 are on the PATH, the same method can be used. It is important to be
2343 aware that environment variables such as C_INCLUDE_PATH,
2344 GCC_EXEC_PREFIX, BINUTILS_ROOT or GCC_ROOT will affect both compilers at
2345 the same time and thus may make one of the 2 compilers operate
2346 improperly if they are set for the other. In particular it is important
2347 that the link command has access to the proper gcc library @file{libgcc.a},
2348 that is to say the one that is part of the C++ compiler
2349 installation. The implicit link command as suggested in the gnatmake
2350 command from the former example can be replaced by an explicit link
2351 command with full verbosity in order to verify which library is used:
2352 @smallexample
2353 $ gnatbind ada_unit
2354 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
2355 @end smallexample
2356 If there is a problem due to interfering environment variables, it can
2357 be workaround by using an intermediate script. The following example
2358 shows the proper script to use when GNAT has not been installed at its
2359 default location and g++ has been installed at its default location:
2360
2361 @smallexample
2362 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
2363 $ cat ./my_script
2364 #!/bin/sh
2365 unset BINUTILS_ROOT
2366 unset GCC_ROOT
2367 c++ $*
2368 @end smallexample
2369
2370 @item
2371 Using a non GNU C++ compiler. The same set of command as previously
2372 described can be used to insure that the c++ linker is
2373 used. Nonetheless, you need to add the path to libgcc explicitely, since some
2374 libraries needed by GNAT are located in this directory:
2375
2376 @smallexample
2377
2378 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2379 $ cat ./my_script
2380 #!/bin/sh
2381 CC $* `gcc -print-libgcc-file-name`
2382
2383 @end smallexample
2384
2385 Where CC is the name of the non GNU C++ compiler.
2386
2387 @end enumerate
2388
2389 @node A Simple Example
2390 @subsection  A Simple Example
2391 @noindent
2392 The following example, provided as part of the GNAT examples, show how
2393 to achieve procedural interfacing between Ada and C++ in both
2394 directions. The C++ class A has 2 methods. The first method is exported
2395 to Ada by the means of an extern C wrapper function. The second method
2396 calls an Ada subprogram. On the Ada side, The C++ calls is modelized by
2397 a limited record with a layout comparable to the C++ class. The Ada
2398 subprogram, in turn, calls the c++ method. So from the C++ main program
2399 the code goes back and forth between the 2 languages.
2400
2401 @noindent
2402 Here are the compilation commands
2403 for a GNAT VxWorks/PowerPC  configuration:
2404 @smallexample
2405 $ powerpc-wrs-vxworks-gnatmake -c simple_cpp_interface
2406 $ powerpc-wrs-vxworks-gnatbind -n simple_cpp_interface
2407 $ gnatlink simple_cpp_interface -o ada_part
2408 $ c++ppc -c -DCPU=PPC604  -I/usr/windppc/target/h  cpp_main.C
2409 $ c++ppc -c -DCPU=PPC604  -I/usr/windppc/target/h  ex7.C
2410 $ ldppc -r -o my_main my_main.o ex7.o ada_part
2411 @end smallexample
2412 @noindent
2413 Here are the corresponding sources:
2414 @smallexample
2415
2416 //cpp_main.C
2417
2418 #include "ex7.h"
2419
2420 extern "C" @{
2421   void adainit (void);
2422   void adafinal (void);
2423   void method1 (A *t);
2424 @}
2425
2426 void method1 (A *t)
2427 @{
2428   t->method1 ();
2429 @}
2430
2431 int main ()
2432 @{
2433   A obj;
2434   adainit ();
2435   obj.method2 (3030);
2436   adafinal ();
2437 @}
2438
2439 //ex7.h
2440
2441 class Origin @{
2442  public:
2443   int o_value;
2444 @};
2445 class A : public Origin @{
2446  public:
2447   void method1 (void);
2448   virtual void method2 (int v);
2449   A();
2450   int   a_value;
2451 @};
2452
2453 //ex7.C
2454
2455 #include "ex7.h"
2456 #include <stdio.h>
2457
2458 extern "C" @{ void ada_method2 (A *t, int v);@}
2459
2460 void A::method1 (void)
2461 @{
2462   a_value = 2020;
2463   printf ("in A::method1, a_value = %d \n",a_value);
2464
2465 @}
2466
2467 void A::method2 (int v)
2468 @{
2469    ada_method2 (this, v);
2470    printf ("in A::method2, a_value = %d \n",a_value);
2471
2472 @}
2473
2474 A::A(void)
2475 @{
2476    a_value = 1010;
2477   printf ("in A::A, a_value = %d \n",a_value);
2478 @}
2479
2480 -- Ada sources
2481 @b{package} @b{body} Simple_Cpp_Interface @b{is}
2482
2483    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
2484    @b{begin}
2485       Method1 (This);
2486       This.A_Value := V;
2487    @b{end} Ada_Method2;
2488
2489 @b{end} Simple_Cpp_Interface;
2490
2491 @b{package} Simple_Cpp_Interface @b{is}
2492    @b{type} A @b{is} @b{limited}
2493       @b{record}
2494          O_Value : Integer;
2495          A_Value : Integer;
2496       @b{end} @b{record};
2497    @b{pragma} Convention (C, A);
2498
2499    @b{procedure} Method1 (This : @b{in} @b{out} A);
2500    @b{pragma} Import (C, Method1);
2501
2502    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
2503    @b{pragma} Export (C, Ada_Method2);
2504
2505 @b{end} Simple_Cpp_Interface;
2506 @end smallexample
2507
2508 @node Adapting the Run Time to a New C++ Compiler
2509 @subsection Adapting the Run Time to a New C++ Compiler
2510 @noindent
2511 GNAT offers the capability to derive Ada 95 tagged types directly from
2512 preexisting C++ classes and . See "Interfacing with C++" in the GNAT
2513 reference manual. The mechanism used by GNAT for achieving such a goal
2514 has been made user configurable through a GNAT library unit
2515 @code{Interfaces.CPP}. The default version of this file is adapted to
2516 the GNU c++ compiler. Internal knowledge of the virtual
2517 table layout used by the new C++ compiler is needed to configure
2518 properly this unit. The Interface of this unit is known by the compiler
2519 and cannot be changed except for the value of the constants defining the
2520 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
2521 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
2522 of this unit for more details.
2523
2524 @node Comparison between GNAT and C/C++ Compilation Models
2525 @section Comparison between GNAT and C/C++ Compilation Models
2526
2527 @noindent
2528 The GNAT model of compilation is close to the C and C++ models. You can
2529 think of Ada specs as corresponding to header files in C. As in C, you
2530 don't need to compile specs; they are compiled when they are used. The
2531 Ada @code{with} is similar in effect to the @code{#include} of a C
2532 header.
2533
2534 One notable difference is that, in Ada, you may compile specs separately
2535 to check them for semantic and syntactic accuracy. This is not always
2536 possible with C headers because they are fragments of programs that have
2537 less specific syntactic or semantic rules.
2538
2539 The other major difference is the requirement for running the binder,
2540 which performs two important functions. First, it checks for
2541 consistency. In C or C++, the only defense against assembling
2542 inconsistent programs lies outside the compiler, in a makefile, for
2543 example. The binder satisfies the Ada requirement that it be impossible
2544 to construct an inconsistent program when the compiler is used in normal
2545 mode.
2546
2547 @cindex Elaboration order control
2548 The other important function of the binder is to deal with elaboration
2549 issues. There are also elaboration issues in C++ that are handled
2550 automatically. This automatic handling has the advantage of being
2551 simpler to use, but the C++ programmer has no control over elaboration.
2552 Where @code{gnatbind} might complain there was no valid order of
2553 elaboration, a C++ compiler would simply construct a program that
2554 malfunctioned at run time.
2555
2556 @node Comparison between GNAT and Conventional Ada Library Models
2557 @section Comparison between GNAT and Conventional Ada Library Models
2558
2559 @noindent
2560 This section is intended to be useful to Ada programmers who have
2561 previously used an Ada compiler implementing the traditional Ada library
2562 model, as described in the Ada 95 Language Reference Manual. If you
2563 have not used such a system, please go on to the next section.
2564
2565 @cindex GNAT library
2566 In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
2567 source files themselves acts as the library. Compiling Ada programs does
2568 not generate any centralized information, but rather an object file and
2569 a ALI file, which are of interest only to the binder and linker.
2570 In a traditional system, the compiler reads information not only from
2571 the source file being compiled, but also from the centralized library.
2572 This means that the effect of a compilation depends on what has been
2573 previously compiled. In particular:
2574
2575 @itemize @bullet
2576 @item
2577 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
2578 to the version of the unit most recently compiled into the library.
2579
2580 @item
2581 Inlining is effective only if the necessary body has already been
2582 compiled into the library.
2583
2584 @item
2585 Compiling a unit may obsolete other units in the library.
2586 @end itemize
2587
2588 @noindent
2589 In GNAT, compiling one unit never affects the compilation of any other
2590 units because the compiler reads only source files. Only changes to source
2591 files can affect the results of a compilation. In particular:
2592
2593 @itemize @bullet
2594 @item
2595 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
2596 to the source version of the unit that is currently accessible to the
2597 compiler.
2598
2599 @item
2600 @cindex Inlining
2601 Inlining requires the appropriate source files for the package or
2602 subprogram bodies to be available to the compiler. Inlining is always
2603 effective, independent of the order in which units are complied.
2604
2605 @item
2606 Compiling a unit never affects any other compilations. The editing of
2607 sources may cause previous compilations to be out of date if they
2608 depended on the source file being modified.
2609 @end itemize
2610
2611 @noindent
2612 The most important result of these differences is that order of compilation
2613 is never significant in GNAT. There is no situation in which one is
2614 required to do one compilation before another. What shows up as order of
2615 compilation requirements in the traditional Ada library becomes, in
2616 GNAT, simple source dependencies; in other words, there is only a set
2617 of rules saying what source files must be present when a file is
2618 compiled.
2619
2620 @node Compiling Using gcc
2621 @chapter Compiling Using @code{gcc}
2622
2623 @noindent
2624 This chapter discusses how to compile Ada programs using the @code{gcc}
2625 command. It also describes the set of switches
2626 that can be used to control the behavior of the compiler.
2627 @menu
2628 * Compiling Programs::
2629 * Switches for gcc::
2630 * Search Paths and the Run-Time Library (RTL)::
2631 * Order of Compilation Issues::
2632 * Examples::
2633 @end menu
2634
2635 @node Compiling Programs
2636 @section Compiling Programs
2637
2638 @noindent
2639 The first step in creating an executable program is to compile the units
2640 of the program using the @code{gcc} command. You must compile the
2641 following files:
2642
2643 @itemize @bullet
2644 @item
2645 the body file (@file{.adb}) for a library level subprogram or generic
2646 subprogram
2647
2648 @item
2649 the spec file (@file{.ads}) for a library level package or generic
2650 package that has no body
2651
2652 @item
2653 the body file (@file{.adb}) for a library level package
2654 or generic package that has a body
2655
2656 @end itemize
2657
2658 @noindent
2659 You need @emph{not} compile the following files
2660
2661 @itemize @bullet
2662
2663 @item
2664 the spec of a library unit which has a body
2665
2666 @item
2667 subunits
2668 @end itemize
2669
2670 @noindent
2671 because they are compiled as part of compiling related units. GNAT
2672 package specs
2673 when the corresponding body is compiled, and subunits when the parent is
2674 compiled.
2675 @cindex No code generated
2676 If you attempt to compile any of these files, you will get one of the
2677 following error messages (where fff is the name of the file you compiled):
2678
2679 @smallexample
2680 No code generated for file @var{fff} (@var{package spec})
2681 No code generated for file @var{fff} (@var{subunit})
2682 @end smallexample
2683
2684 @noindent
2685 The basic command for compiling a file containing an Ada unit is
2686
2687 @smallexample
2688 $ gcc -c [@var{switches}] @file{file name}
2689 @end smallexample
2690
2691 @noindent
2692 where @var{file name} is the name of the Ada file (usually
2693 having an extension
2694 @file{.ads} for a spec or @file{.adb} for a body).
2695 You specify the
2696 @code{-c} switch to tell @code{gcc} to compile, but not link, the file.
2697 The result of a successful compilation is an object file, which has the
2698 same name as the source file but an extension of @file{.o} and an Ada
2699 Library Information (ALI) file, which also has the same name as the
2700 source file, but with @file{.ali} as the extension. GNAT creates these
2701 two output files in the current directory, but you may specify a source
2702 file in any directory using an absolute or relative path specification
2703 containing the directory information.
2704
2705 @findex gnat1
2706 @code{gcc} is actually a driver program that looks at the extensions of
2707 the file arguments and loads the appropriate compiler. For example, the
2708 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
2709 These programs are in directories known to the driver program (in some
2710 configurations via environment variables you set), but need not be in
2711 your path. The @code{gcc} driver also calls the assembler and any other
2712 utilities needed to complete the generation of the required object
2713 files.
2714
2715 It is possible to supply several file names on the same @code{gcc}
2716 command. This causes @code{gcc} to call the appropriate compiler for
2717 each file. For example, the following command lists three separate
2718 files to be compiled:
2719
2720 @smallexample
2721 $ gcc -c x.adb y.adb z.c
2722 @end smallexample
2723
2724 @noindent
2725 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
2726 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
2727 The compiler generates three object files @file{x.o}, @file{y.o} and
2728 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
2729 Ada compilations. Any switches apply to all the files listed,
2730 except for
2731 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
2732
2733 @node Switches for gcc
2734 @section Switches for @code{gcc}
2735
2736 @noindent
2737 The @code{gcc} command accepts switches that control the
2738 compilation process. These switches are fully described in this section.
2739 First we briefly list all the switches, in alphabetical order, then we
2740 describe the switches in more detail in functionally grouped sections.
2741
2742 @menu
2743 * Output and Error Message Control::
2744 * Debugging and Assertion Control::
2745 * Run-Time Checks::
2746 * Stack Overflow Checking::
2747 * Run-Time Control::
2748 * Validity Checking::
2749 * Style Checking::
2750 * Using gcc for Syntax Checking::
2751 * Using gcc for Semantic Checking::
2752 * Compiling Ada 83 Programs::
2753 * Character Set Control::
2754 * File Naming Control::
2755 * Subprogram Inlining Control::
2756 * Auxiliary Output Control::
2757 * Debugging Control::
2758 * Units to Sources Mapping Files::
2759 @end menu
2760
2761 @table @code
2762 @cindex @code{-b} (@code{gcc})
2763 @item -b @var{target}
2764 Compile your program to run on @var{target}, which is the name of a
2765 system configuration. You must have a GNAT cross-compiler built if
2766 @var{target} is not the same as your host system.
2767
2768 @item -B@var{dir}
2769 @cindex @code{-B} (@code{gcc})
2770 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
2771 from @var{dir} instead of the default location. Only use this switch
2772 when multiple versions of the GNAT compiler are available. See the
2773 @code{gcc} manual page for further details. You would normally use the
2774 @code{-b} or @code{-V} switch instead.
2775
2776 @item -c
2777 @cindex @code{-c} (@code{gcc})
2778 Compile. Always use this switch when compiling Ada programs.
2779
2780 Note: for some other languages when using @code{gcc}, notably in
2781 the case of C and C++, it is possible to use
2782 use @code{gcc} without a @code{-c} switch to
2783 compile and link in one step. In the case of GNAT, you
2784 cannot use this approach, because the binder must be run
2785 and @code{gcc} cannot be used to run the GNAT binder.
2786
2787 @item -g
2788 @cindex @code{-g} (@code{gcc})
2789 Generate debugging information. This information is stored in the object
2790 file and copied from there to the final executable file by the linker,
2791 where it can be read by the debugger. You must use the
2792 @code{-g} switch if you plan on using the debugger.
2793
2794 @item -I@var{dir}
2795 @cindex @code{-I} (@code{gcc})
2796 @cindex RTL
2797 Direct GNAT to search the @var{dir} directory for source files needed by
2798 the current compilation
2799 (@pxref{Search Paths and the Run-Time Library (RTL)}).
2800
2801 @item -I-
2802 @cindex @code{-I-} (@code{gcc})
2803 @cindex RTL
2804 Except for the source file named in the command line, do not look for source files
2805 in the directory containing the source file named in the command line
2806 (@pxref{Search Paths and the Run-Time Library (RTL)}).
2807
2808 @item -o @var{file}
2809 @cindex @code{-o} (@code{gcc})
2810 This switch is used in @code{gcc} to redirect the generated object file
2811 and its associated ALI file. Beware of this switch with GNAT, because it may
2812 cause the object file and ALI file to have different names which in turn
2813 may confuse the binder and the linker.
2814
2815 @item -O[@var{n}]
2816 @cindex @code{-O} (@code{gcc})
2817 @var{n} controls the optimization level.
2818
2819 @table @asis
2820 @item n = 0
2821 No optimization, the default setting if no @code{-O} appears
2822
2823 @item n = 1
2824 Normal optimization, the default if you specify @code{-O} without
2825 an operand.
2826
2827 @item n = 2
2828 Extensive optimization
2829
2830 @item n = 3
2831 Extensive optimization with automatic inlining. This applies only to
2832 inlining within a unit. For details on control of inter-unit inlining
2833 see @xref{Subprogram Inlining Control}.
2834 @end table
2835
2836
2837 @item --RTS=@var{rts-path}
2838 @cindex @code{--RTS} (@code{gcc})
2839 Specifies the default location of the runtime library. Same meaning as the
2840 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
2841
2842 @item -S
2843 @cindex @code{-S} (@code{gcc})
2844 Used in place of @code{-c} to
2845 cause the assembler source file to be
2846 generated, using @file{.s} as the extension,
2847 instead of the object file.
2848 This may be useful if you need to examine the generated assembly code.
2849
2850 @item -v
2851 @cindex @code{-v} (@code{gcc})
2852 Show commands generated by the @code{gcc} driver. Normally used only for
2853 debugging purposes or if you need to be sure what version of the
2854 compiler you are executing.
2855
2856 @item -V @var{ver}
2857 @cindex @code{-V} (@code{gcc})
2858 Execute @var{ver} version of the compiler. This is the @code{gcc}
2859 version, not the GNAT version.
2860
2861 @item -gnata
2862 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
2863 activated.
2864
2865 @item -gnatA
2866 Avoid processing @file{gnat.adc}. If a gnat.adc file is present, it will be ignored.
2867
2868 @item -gnatb
2869 Generate brief messages to @file{stderr} even if verbose mode set.
2870
2871 @item -gnatc
2872 Check syntax and semantics only (no code generation attempted).
2873
2874 @item -gnatC
2875 Compress debug information and external symbol name table entries.
2876
2877 @item -gnatD
2878 Output expanded source files for source level debugging. This switch
2879 also suppress generation of cross-reference information (see -gnatx).
2880
2881 @item -gnatec@var{path}
2882 Specify a configuration pragma file. (see @ref{The Configuration Pragmas Files})
2883
2884 @item -gnatem@var{path}
2885 Specify a mapping file. (see @ref{Units to Sources Mapping Files})
2886
2887 @item -gnatE
2888 Full dynamic elaboration checks.
2889
2890 @item -gnatf
2891 Full errors. Multiple errors per line, all undefined references.
2892
2893 @item -gnatF
2894 Externals names are folded to all uppercase.
2895
2896 @item -gnatg
2897 Internal GNAT implementation mode. This should not be used for
2898 applications programs, it is intended only for use by the compiler
2899 and its run-time library. For documentation, see the GNAT sources.
2900
2901 @item -gnatG
2902 List generated expanded code in source form.
2903
2904 @item -gnati@var{c}
2905 Identifier character set
2906 (@var{c}=1/2/3/4/8/9/p/f/n/w).
2907
2908 @item -gnath
2909 Output usage information. The output is written to @file{stdout}.
2910
2911 @item -gnatk@var{n}
2912 Limit file names to @var{n} (1-999) characters (@code{k} = krunch).
2913
2914 @item -gnatl
2915 Output full source listing with embedded error messages.
2916
2917 @item -gnatm@var{n}
2918 Limit number of detected errors to @var{n} (1-999).
2919
2920 @item -gnatn
2921 Activate inlining across unit boundaries for subprograms for which
2922 pragma @code{inline} is specified.
2923
2924 @item -gnatN
2925 Activate front end inlining.
2926
2927 @item -fno-inline
2928 Suppresses all inlining, even if other optimization or inlining switches
2929 are set.
2930
2931 @item -fstack-check
2932 Activates stack checking. See separate section on stack checking for
2933 details of the use of this option.
2934
2935 @item -gnato
2936 Enable numeric overflow checking (which is not normally enabled by
2937 default). Not that division by zero is a separate check that is not
2938 controlled by this switch (division by zero checking is on by default).
2939
2940 @item -gnatp
2941 Suppress all checks.
2942
2943 @item -gnatq
2944 Don't quit; try semantics, even if parse errors.
2945
2946 @item -gnatQ
2947 Don't quit; generate @file{ali} and tree files even if illegalities.
2948
2949 @item -gnatP
2950 Enable polling. This is required on some systems (notably Windows NT) to
2951 obtain asynchronous abort and asynchronous transfer of control capability.
2952 See the description of pragma Polling in the GNAT Reference Manual for
2953 full details.
2954
2955 @item -gnatR[0/1/2/3][s]
2956 Output representation information for declared types and objects.
2957
2958 @item -gnats
2959 Syntax check only.
2960
2961 @item -gnatt
2962 Tree output file to be generated.
2963
2964 @item -gnatT nnn
2965 Set time slice to specified number of microseconds
2966
2967 @item -gnatu
2968 List units for this compilation.
2969
2970 @item -gnatU
2971 Tag all error messages with the unique string "error:"
2972
2973 @item -gnatv
2974 Verbose mode. Full error output with source lines to @file{stdout}.
2975
2976 @item -gnatV
2977 Control level of validity checking. See separate section describing
2978 this feature.
2979
2980 @item -gnatwxxx@var{xxx}
2981 Warning mode where
2982 @var{xxx} is a string of options describing the exact warnings that
2983 are enabled or disabled. See separate section on warning control.
2984
2985 @item -gnatW@var{e}
2986 Wide character encoding method
2987 (@var{e}=n/h/u/s/e/8).
2988
2989 @item -gnatx
2990 Suppress generation of cross-reference information.
2991
2992 @item -gnaty
2993 Enable built-in style checks. See separate section describing this feature.
2994
2995 @item -gnatz@var{m}
2996 Distribution stub generation and compilation
2997 (@var{m}=r/c for receiver/caller stubs).
2998
2999 @item -gnat83
3000 Enforce Ada 83 restrictions.
3001
3002 @item -pass-exit-codes
3003 Catch exit codes from the compiler and use the most meaningful as
3004 exit status.
3005 @end table
3006
3007 You may combine a sequence of GNAT switches into a single switch. For
3008 example, the combined switch
3009
3010 @cindex Combining GNAT switches
3011 @smallexample
3012 -gnatofi3
3013 @end smallexample
3014
3015 @noindent
3016 is equivalent to specifying the following sequence of switches:
3017
3018 @smallexample
3019 -gnato -gnatf -gnati3
3020 @end smallexample
3021
3022 @noindent
3023 The following restrictions apply to the combination of switches
3024 in this manner:
3025
3026 @itemize @bullet
3027 @item
3028 The switch @option{-gnatc} if combined with other switches must come
3029 first in the string.
3030
3031 @item
3032 The switch @option{-gnats} if combined with other switches must come
3033 first in the string.
3034
3035 @item
3036 Once a "y" appears in the string (that is a use of the @option{-gnaty}
3037 switch), then all further characters in the switch are interpreted
3038 as style modifiers (see description of @option{-gnaty}).
3039
3040 @item
3041 Once a "d" appears in the string (that is a use of the @option{-gnatd}
3042 switch), then all further characters in the switch are interpreted
3043 as debug flags (see description of @option{-gnatd}).
3044
3045 @item
3046 Once a "w" appears in the string (that is a use of the @option{-gnatw}
3047 switch), then all further characters in the switch are interpreted
3048 as warning mode modifiers (see description of @option{-gnatw}).
3049
3050 @item
3051 Once a "V" appears in the string (that is a use of the @option{-gnatV}
3052 switch), then all further characters in the switch are interpreted
3053 as validity checking options (see description of @option{-gnatV}).
3054
3055 @end itemize
3056
3057 @node Output and Error Message Control
3058 @subsection Output and Error Message Control
3059 @findex stderr
3060
3061 @noindent
3062 The standard default format for error messages is called "brief format."
3063 Brief format messages are written to @file{stderr} (the standard error
3064 file) and have the following form:
3065
3066 @smallexample
3067 @iftex
3068 @leftskip=.7cm
3069 @end iftex
3070 e.adb:3:04: Incorrect spelling of keyword "function"
3071 e.adb:4:20: ";" should be "is"
3072 @end smallexample
3073
3074 @noindent
3075 The first integer after the file name is the line number in the file,
3076 and the second integer is the column number within the line.
3077 @code{glide} can parse the error messages
3078 and point to the referenced character.
3079 The following switches provide control over the error message
3080 format:
3081
3082 @table @code
3083 @item -gnatv
3084 @cindex @option{-gnatv} (@code{gcc})
3085 @findex stdout
3086 The v stands for verbose.
3087 The effect of this setting is to write long-format error
3088 messages to @file{stdout} (the standard output file.
3089 The same program compiled with the
3090 @option{-gnatv} switch would generate:
3091
3092 @smallexample
3093 @group
3094 @cartouche
3095 3. funcion X (Q : Integer)
3096    |
3097 >>> Incorrect spelling of keyword "function"
3098 4. return Integer;
3099                  |
3100 >>> ";" should be "is"
3101 @end cartouche
3102 @end group
3103 @end smallexample
3104
3105 @noindent
3106 The vertical bar indicates the location of the error, and the @samp{>>>}
3107 prefix can be used to search for error messages. When this switch is
3108 used the only source lines output are those with errors.
3109
3110 @item -gnatl
3111 @cindex @option{-gnatl} (@code{gcc})
3112 The @code{l} stands for list.
3113 This switch causes a full listing of
3114 the file to be generated. The output might look as follows:
3115
3116 @smallexample
3117 @group
3118 @cartouche
3119  1. procedure E is
3120  2.    V : Integer;
3121  3.    funcion X (Q : Integer)
3122        |
3123     >>> Incorrect spelling of keyword "function"
3124  4.     return Integer;
3125                       |
3126     >>> ";" should be "is"
3127  5.    begin
3128  6.       return Q + Q;
3129  7.    end;
3130  8. begin
3131  9.    V := X + X;
3132 10.end E;
3133 @end cartouche
3134 @end group
3135 @end smallexample
3136
3137 @noindent
3138 @findex stderr
3139 When you specify the @option{-gnatv} or @option{-gnatl} switches and
3140 standard output is redirected, a brief summary is written to
3141 @file{stderr} (standard error) giving the number of error messages and
3142 warning messages generated.
3143
3144 @item -gnatU
3145 @cindex @option{-gnatU} (@code{gcc})
3146 This switch forces all error messages to be preceded by the unique
3147 string "error:". This means that error messages take a few more
3148 characters in space, but allows easy searching for and identification
3149 of error messages.
3150
3151 @item -gnatb
3152 @cindex @option{-gnatb} (@code{gcc})
3153 The @code{b} stands for brief.
3154 This switch causes GNAT to generate the
3155 brief format error messages to @file{stderr} (the standard error
3156 file) as well as the verbose
3157 format message or full listing (which as usual is written to
3158 @file{stdout} (the standard output file).
3159
3160 @item -gnatm@var{n}
3161 @cindex @option{-gnatm} (@code{gcc})
3162 The @code{m} stands for maximum.
3163 @var{n} is a decimal integer in the
3164 range of 1 to 999 and limits the number of error messages to be
3165 generated. For example, using @option{-gnatm2} might yield
3166
3167 @smallexample
3168 @iftex
3169 @leftskip=.7cm
3170 @end iftex
3171 e.adb:3:04: Incorrect spelling of keyword "function"
3172 e.adb:5:35: missing ".."
3173 fatal error: maximum errors reached
3174 compilation abandoned
3175 @end smallexample
3176
3177 @item -gnatf
3178 @cindex @option{-gnatf} (@code{gcc})
3179 @cindex Error messages, suppressing
3180 The @code{f} stands for full.
3181 Normally, the compiler suppresses error messages that are likely to be
3182 redundant. This switch causes all error
3183 messages to be generated. In particular, in the case of
3184 references to undefined variables. If a given variable is referenced
3185 several times, the normal format of messages is
3186 @smallexample
3187 @iftex
3188 @leftskip=.7cm
3189 @end iftex
3190 e.adb:7:07: "V" is undefined (more references follow)
3191 @end smallexample
3192
3193 @noindent
3194 where the parenthetical comment warns that there are additional
3195 references to the variable @code{V}. Compiling the same program with the
3196 @option{-gnatf} switch yields
3197
3198 @smallexample
3199 e.adb:7:07: "V" is undefined
3200 e.adb:8:07: "V" is undefined
3201 e.adb:8:12: "V" is undefined
3202 e.adb:8:16: "V" is undefined
3203 e.adb:9:07: "V" is undefined
3204 e.adb:9:12: "V" is undefined
3205 @end smallexample
3206
3207 @item -gnatq
3208 @cindex @option{-gnatq} (@code{gcc})
3209 The @code{q} stands for quit (really "don't quit").
3210 In normal operation mode, the compiler first parses the program and
3211 determines if there are any syntax errors. If there are, appropriate
3212 error messages are generated and compilation is immediately terminated.
3213 This switch tells
3214 GNAT to continue with semantic analysis even if syntax errors have been
3215 found. This may enable the detection of more errors in a single run. On
3216 the other hand, the semantic analyzer is more likely to encounter some
3217 internal fatal error when given a syntactically invalid tree.
3218
3219 @item -gnatQ
3220 In normal operation mode, the @file{ali} file is not generated if any
3221 illegalities are detected in the program. The use of @option{-gnatQ} forces
3222 generation of the @file{ali} file. This file is marked as being in
3223 error, so it cannot be used for binding purposes, but it does contain
3224 reasonably complete cross-reference information, and thus may be useful
3225 for use by tools (e.g. semantic browsing tools or integrated development
3226 environments) that are driven from the @file{ali} file.
3227
3228 In addition, if @option{-gnatt} is also specified, then the tree file is
3229 generated even if there are illegalities. It may be useful in this case
3230 to also specify @option{-gnatq} to ensure that full semantic processing
3231 occurs. The resulting tree file can be processed by ASIS, for the purpose
3232 of providing partial information about illegal units, but if the error
3233 causes the tree to be badly malformed, then ASIS may crash during the
3234 analysis.
3235
3236 @end table
3237
3238 @noindent
3239 In addition to error messages, which correspond to illegalities as defined
3240 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
3241 situations.
3242
3243 @cindex Warning messages
3244 First, the compiler considers some constructs suspicious and generates a
3245 warning message to alert you to a possible error. Second, if the
3246 compiler detects a situation that is sure to raise an exception at
3247 run time, it generates a warning message. The following shows an example
3248 of warning messages:
3249 @smallexample
3250 @iftex
3251 @leftskip=.2cm
3252 @end iftex
3253 e.adb:4:24: warning: creation of object may raise Storage_Error
3254 e.adb:10:17: warning: static value out of range
3255 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
3256
3257 @end smallexample
3258
3259 @noindent
3260 GNAT considers a large number of situations as appropriate
3261 for the generation of warning messages. As always, warnings are not
3262 definite indications of errors. For example, if you do an out-of-range
3263 assignment with the deliberate intention of raising a
3264 @code{Constraint_Error} exception, then the warning that may be
3265 issued does not indicate an error. Some of the situations for which GNAT
3266 issues warnings (at least some of the time) are given in the following
3267 list, which is not necessarily complete.
3268
3269 @itemize @bullet
3270 @item
3271 Possible infinitely recursive calls
3272
3273 @item
3274 Out-of-range values being assigned
3275
3276 @item
3277 Possible order of elaboration problems
3278
3279 @item
3280 Unreachable code
3281
3282 @item
3283 Fixed-point type declarations with a null range
3284
3285 @item
3286 Variables that are never assigned a value
3287
3288 @item
3289 Variables that are referenced before being initialized
3290
3291 @item
3292 Task entries with no corresponding accept statement
3293
3294 @item
3295 Duplicate accepts for the same task entry in a select
3296
3297 @item
3298 Objects that take too much storage
3299
3300 @item
3301 Unchecked conversion between types of differing sizes
3302
3303 @item
3304 Missing return statements along some execution paths in a function
3305
3306 @item
3307 Incorrect (unrecognized) pragmas
3308
3309 @item
3310 Incorrect external names
3311
3312 @item
3313 Allocation from empty storage pool
3314
3315 @item
3316 Potentially blocking operations in protected types
3317
3318 @item
3319 Suspicious parenthesization of expressions
3320
3321 @item
3322 Mismatching bounds in an aggregate
3323
3324 @item
3325 Attempt to return local value by reference
3326
3327 @item
3328 Unrecognized pragmas
3329
3330 @item
3331 Premature instantiation of a generic body
3332
3333 @item
3334 Attempt to pack aliased components
3335
3336 @item
3337 Out of bounds array subscripts
3338
3339 @item
3340 Wrong length on string assignment
3341
3342 @item
3343 Violations of style rules if style checking is enabled
3344
3345 @item
3346 Unused with clauses
3347
3348 @item
3349 Bit_Order usage that does not have any effect
3350
3351 @item
3352 Compile time biased rounding of floating-point constant
3353
3354 @item
3355 Standard.Duration used to resolve universal fixed expression
3356
3357 @item
3358 Dereference of possibly null value
3359
3360 @item
3361 Declaration that is likely to cause storage error
3362
3363 @item
3364 Internal GNAT unit with'ed by application unit
3365
3366 @item
3367 Values known to be out of range at compile time
3368
3369 @item
3370 Unreferenced labels and variables
3371
3372 @item
3373 Address overlays that could clobber memory
3374
3375 @item
3376 Unexpected initialization when address clause present
3377
3378 @item
3379 Bad alignment for address clause
3380
3381 @item
3382 Useless type conversions
3383
3384 @item
3385 Redundant assignment statements
3386
3387 @item
3388 Accidental hiding of name by child unit
3389
3390 @item
3391 Unreachable code
3392
3393 @item
3394 Access before elaboration detected at compile time
3395
3396 @item
3397 A range in a @code{for} loop that is known to be null or might be null
3398
3399 @end itemize
3400
3401 @noindent
3402 The following switches are available to control the handling of
3403 warning messages:
3404
3405 @table @code
3406 @item -gnatwa (activate all optional errors)
3407 @cindex @option{-gnatwa} (@code{gcc})
3408 This switch activates most optional warning messages, see remaining list
3409 in this section for details on optional warning messages that can be
3410 individually controlled. The warnings that are not turned on by this
3411 switch are @option{-gnatwb} (biased rounding),
3412 @option{-gnatwd} (implicit dereferencing),
3413 and @option{-gnatwh} (hiding). All other optional warnings are
3414 turned on.
3415
3416 @item -gnatwA (suppress all optional errors)
3417 @cindex @option{-gnatwA} (@code{gcc})
3418 This switch suppresses all optional warning messages, see remaining list
3419 in this section for details on optional warning messages that can be
3420 individually controlled.
3421
3422 @item -gnatwb (activate warnings on biased rounding)
3423 @cindex @option{-gnatwb} (@code{gcc})
3424 @cindex Rounding, biased
3425 @cindex Biased rounding
3426 If a static floating-point expression has a value that is exactly half
3427 way between two adjacent machine numbers, then the rules of Ada
3428 (Ada Reference Manual, section 4.9(38)) require that this rounding
3429 be done away from zero, even if the normal unbiased rounding rules
3430 at run time would require rounding towards zero. This warning message
3431 alerts you to such instances where compile-time rounding and run-time
3432 rounding are not equivalent. If it is important to get proper run-time
3433 rounding, then you can force this by making one of the operands into
3434 a variable. The default is that such warnings are not generated.
3435 Note that @option{-gnatwa} does not affect the setting of
3436 this warning option.
3437
3438 @item -gnatwB (suppress warnings on biased rounding)
3439 @cindex @option{-gnatwB} (@code{gcc})
3440 This switch disables warnings on biased rounding.
3441
3442 @item -gnatwc (activate warnings on conditionals)
3443 @cindex @option{-gnatwc} (@code{gcc})
3444 @cindex Conditionals, constant
3445 This switch activates warnings for conditional expressions used in
3446 tests that are known to be True or False at compile time. The default
3447 is that such warnings are not generated.
3448 This warning can also be turned on using @option{-gnatwa}.
3449
3450 @item -gnatwC (suppress warnings on conditionals)
3451 @cindex @option{-gnatwC} (@code{gcc})
3452 This switch suppresses warnings for conditional expressions used in
3453 tests that are known to be True or False at compile time.
3454
3455 @item -gnatwd (activate warnings on implicit dereferencing)
3456 @cindex @option{-gnatwd} (@code{gcc})
3457 If this switch is set, then the use of a prefix of an access type
3458 in an indexed component, slice, or selected component without an
3459 explicit @code{.all} will generate a warning. With this warning
3460 enabled, access checks occur only at points where an explicit
3461 @code{.all} appears in the source code (assuming no warnings are
3462 generated as a result of this switch). The default is that such
3463 warnings are not generated.
3464 Note that @option{-gnatwa} does not affect the setting of
3465 this warning option.
3466
3467 @item -gnatwD (suppress warnings on implicit dereferencing)
3468 @cindex @option{-gnatwD} (@code{gcc})
3469 @cindex Implicit dereferencing
3470 @cindex Dereferencing, implicit
3471 This switch suppresses warnings for implicit deferences in
3472 indexed components, slices, and selected components.
3473
3474 @item -gnatwe (treat warnings as errors)
3475 @cindex @option{-gnatwe} (@code{gcc})
3476 @cindex Warnings, treat as error
3477 This switch causes warning messages to be treated as errors.
3478 The warning string still appears, but the warning messages are counted
3479 as errors, and prevent the generation of an object file.
3480
3481 @item -gnatwf (activate warnings on unreferenced formals)
3482 @cindex @option{-gnatwf} (@code{gcc})
3483 @cindex Formals, unreferenced
3484 This switch causes a warning to be generated if a formal parameter
3485 is not referenced in the body of the subprogram. This warning can
3486 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
3487
3488 @item -gnatwF (suppress warnings on unreferenced formals)
3489 @cindex @option{-gnatwF} (@code{gcc})
3490 This switch suppresses warnings for unreferenced formal
3491 parameters. Note that the
3492 combination @option{-gnatwu} followed by @option{-gnatwF} has the
3493 effect of warning on unreferenced entities other than subprogram
3494 formals.
3495
3496 @item -gnatwh (activate warnings on hiding)
3497 @cindex @option{-gnatwh} (@code{gcc})
3498 @cindex Hiding of Declarations
3499 This switch activates warnings on hiding declarations.
3500 A declaration is considered hiding
3501 if it is for a non-overloadable entity, and it declares an entity with the
3502 same name as some other entity that is directly or use-visible. The default
3503 is that such warnings are not generated.
3504 Note that @option{-gnatwa} does not affect the setting of this warning option.
3505
3506 @item -gnatwH (suppress warnings on hiding)
3507 @cindex @option{-gnatwH} (@code{gcc})
3508 This switch suppresses warnings on hiding declarations.
3509
3510 @item -gnatwi (activate warnings on implementation units).
3511 @cindex @option{-gnatwi} (@code{gcc})
3512 This switch activates warnings for a @code{with} of an internal GNAT
3513 implementation unit, defined as any unit from the @code{Ada},
3514 @code{Interfaces}, @code{GNAT},
3515  or @code{System}
3516 hierarchies that is not
3517 documented in either the Ada Reference Manual or the GNAT
3518 Programmer's Reference Manual. Such units are intended only
3519 for internal implementation purposes and should not be @code{with}'ed
3520 by user programs. The default is that such warnings are generated
3521 This warning can also be turned on using @option{-gnatwa}.
3522
3523 @item -gnatwI (disable warnings on implementation units).
3524 @cindex @option{-gnatwI} (@code{gcc})
3525 This switch disables warnings for a @code{with} of an internal GNAT
3526 implementation unit.
3527
3528 @item -gnatwl (activate warnings on elaboration pragmas)
3529 @cindex @option{-gnatwl} (@code{gcc})
3530 @cindex Elaboration, warnings
3531 This switch activates warnings on missing pragma Elaborate_All statements.
3532 See the section in this guide on elaboration checking for details on
3533 when such pragma should be used. The default is that such warnings
3534 are not generated.
3535 This warning can also be turned on using @option{-gnatwa}.
3536
3537 @item -gnatwL (suppress warnings on elaboration pragmas)
3538 @cindex @option{-gnatwL} (@code{gcc})
3539 This switch suppresses warnings on missing pragma Elaborate_All statements.
3540 See the section in this guide on elaboration checking for details on
3541 when such pragma should be used.
3542
3543 @item -gnatwo (activate warnings on address clause overlays)
3544 @cindex @option{-gnatwo} (@code{gcc})
3545 @cindex Address Clauses, warnings
3546 This switch activates warnings for possibly unintended initialization
3547 effects of defining address clauses that cause one variable to overlap
3548 another. The default is that such warnings are generated.
3549 This warning can also be turned on using @option{-gnatwa}.
3550
3551 @item -gnatwO (suppress warnings on address clause overlays)
3552 @cindex @option{-gnatwO} (@code{gcc})
3553 This switch suppresses warnings on possibly unintended initialization
3554 effects of defining address clauses that cause one variable to overlap
3555 another.
3556
3557 @item -gnatwp (activate warnings on ineffective pragma Inlines)
3558 @cindex @option{-gnatwp} (@code{gcc})
3559 @cindex Inlining, warnings
3560 This switch activates warnings for failure of front end inlining
3561 (activated by @option{-gnatN}) to inline a particular call. There are
3562 many reasons for not being able to inline a call, including most
3563 commonly that the call is too complex to inline.
3564 This warning can also be turned on using @option{-gnatwa}.
3565
3566 @item -gnatwP (suppress warnings on ineffective pragma Inlines)
3567 @cindex @option{-gnatwP} (@code{gcc})
3568 This switch suppresses warnings on ineffective pragma Inlines. If the
3569 inlining mechanism cannot inline a call, it will simply ignore the
3570 request silently.
3571
3572 @item -gnatwr (activate warnings on redundant constructs)
3573 @cindex @option{-gnatwr} (@code{gcc})
3574 This switch activates warnings for redundant constructs. The following
3575 is the current list of constructs regarded as redundant:
3576 This warning can also be turned on using @option{-gnatwa}.
3577
3578 @itemize @bullet
3579 @item
3580 Assignment of an item to itself.
3581 @item
3582 Type conversion that converts an expression to its own type.
3583 @item
3584 Use of the attribute @code{Base} where @code{typ'Base} is the same
3585 as @code{typ}.
3586 @item
3587 Use of pragma @code{Pack} when all components are placed by a record
3588 representation clause.
3589 @end itemize
3590
3591 @item -gnatwR (suppress warnings on redundant constructs)
3592 @cindex @option{-gnatwR} (@code{gcc})
3593 This switch suppresses warnings for redundant constructs.
3594
3595 @item -gnatws (suppress all warnings)
3596 @cindex @option{-gnatws} (@code{gcc})
3597 This switch completely suppresses the
3598 output of all warning messages from the GNAT front end.
3599 Note that it does not suppress warnings from the @code{gcc} back end.
3600 To suppress these back end warnings as well, use the switch @code{-w}
3601 in addition to @option{-gnatws}.
3602
3603 @item -gnatwu (activate warnings on unused entities)
3604 @cindex @option{-gnatwu} (@code{gcc})
3605 This switch activates warnings to be generated for entities that
3606 are defined but not referenced, and for units that are @code{with}'ed
3607 and not
3608 referenced. In the case of packages, a warning is also generated if
3609 no entities in the package are referenced. This means that if the package
3610 is referenced but the only references are in @code{use}
3611 clauses or @code{renames}
3612 declarations, a warning is still generated. A warning is also generated
3613 for a generic package that is @code{with}'ed but never instantiated.
3614 In the case where a package or subprogram body is compiled, and there
3615 is a @code{with} on the corresponding spec
3616 that is only referenced in the body,
3617 a warning is also generated, noting that the
3618 @code{with} can be moved to the body. The default is that
3619 such warnings are not generated.
3620 This switch also activates warnings on unreferenced formals
3621 (it is includes the effect of @option{-gnatwf}).
3622 This warning can also be turned on using @option{-gnatwa}.
3623
3624 @item -gnatwU (suppress warnings on unused entities)
3625 @cindex @option{-gnatwU} (@code{gcc})
3626 This switch suppresses warnings for unused entities and packages.
3627 It also turns off warnings on unreferenced formals (and thus includes
3628 the effect of @option{-gnatwF}).
3629
3630 @noindent
3631 A string of warning parameters can be used in the same parameter. For example:
3632
3633 @smallexample
3634 -gnatwaLe
3635 @end smallexample
3636
3637 @noindent
3638 Would turn on all optional warnings except for elaboration pragma warnings,
3639 and also specify that warnings should be treated as errors.
3640
3641 @item -w
3642 @cindex @code{-w}
3643 This switch suppresses warnings from the @code{gcc} backend. It may be
3644 used in conjunction with @option{-gnatws} to ensure that all warnings
3645 are suppressed during the entire compilation process.
3646
3647 @end table
3648
3649 @node Debugging and Assertion Control
3650 @subsection Debugging and Assertion Control
3651
3652 @table @code
3653 @item -gnata
3654 @cindex @option{-gnata} (@code{gcc})
3655 @findex Assert
3656 @findex Debug
3657 @cindex Assertions
3658
3659 @noindent
3660 The pragmas @code{Assert} and @code{Debug} normally have no effect and
3661 are ignored. This switch, where @samp{a} stands for assert, causes
3662 @code{Assert} and @code{Debug} pragmas to be activated.
3663
3664 The pragmas have the form:
3665
3666 @smallexample
3667 @group
3668 @cartouche
3669    @b{pragma} Assert (@var{Boolean-expression} [,
3670                       @var{static-string-expression}])
3671    @b{pragma} Debug (@var{procedure call})
3672 @end cartouche
3673 @end group
3674 @end smallexample
3675
3676 @noindent
3677 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
3678 If the result is @code{True}, the pragma has no effect (other than
3679 possible side effects from evaluating the expression). If the result is
3680 @code{False}, the exception @code{Assert_Failure} declared in the package
3681 @code{System.Assertions} is
3682 raised (passing @var{static-string-expression}, if present, as the
3683 message associated with the exception). If no string expression is
3684 given the default is a string giving the file name and line number
3685 of the pragma.
3686
3687 The @code{Debug} pragma causes @var{procedure} to be called. Note that
3688 @code{pragma Debug} may appear within a declaration sequence, allowing
3689 debugging procedures to be called between declarations.
3690
3691 @end table
3692
3693 @node Validity Checking
3694 @subsection Validity Checking
3695 @findex Validity Checking
3696
3697 @noindent
3698 The Ada 95 Reference Manual has specific requirements for checking
3699 for invalid values. In particular, RM 13.9.1 requires that the
3700 evaluation of invalid values (for example from unchecked conversions),
3701 not result in erroneous execution. In GNAT, the result of such an
3702 evaluation in normal default mode is to either use the value
3703 unmodified, or to raise Constraint_Error in those cases where use
3704 of the unmodified value would cause erroneous execution. The cases
3705 where unmodified values might lead to erroneous execution are case
3706 statements (where a wild jump might result from an invalid value),
3707 and subscripts on the left hand side (where memory corruption could
3708 occur as a result of an invalid value).
3709
3710 The @option{-gnatVx} switch allows more control over the validity checking
3711 mode. The @code{x} argument here is a string of letters which control which
3712 validity checks are performed in addition to the default checks described
3713 above.
3714
3715 @itemize @bullet
3716 @item
3717 @option{-gnatVc} Validity checks for copies
3718
3719 The right hand side of assignments, and the initializing values of
3720 object declarations are validity checked.
3721
3722 @item
3723 @option{-gnatVd} Default (RM) validity checks
3724
3725 Some validity checks are done by default following normal Ada semantics
3726 (RM 13.9.1 (9-11)).
3727 A check is done in case statements that the expression is within the range
3728 of the subtype. If it is not, Constraint_Error is raised.
3729 For assignments to array components, a check is done that the expression used
3730 as index is within the range. If it is not, Constraint_Error is raised.
3731 Both these validity checks may be turned off using switch @option{-gnatVD}.
3732 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
3733 switch @option{-gnatVd} will leave the checks turned on.
3734 Switch @option{-gnatVD} should be used only if you are sure that all such
3735 expressions have valid values. If you use this switch and invalid values
3736 are present, then the program is erroneous, and wild jumps or memory
3737 overwriting may occur.
3738
3739 @item
3740 @option{-gnatVi} Validity checks for @code{in} mode parameters
3741
3742 Arguments for parameters of mode @code{in} are validity checked in function
3743 and procedure calls at the point of call.
3744
3745 @item
3746 @option{-gnatVm} Validity checks for @code{in out} mode parameters
3747
3748 Arguments for parameters of mode @code{in out} are validity checked in
3749 procedure calls at the point of call. The @code{'m'} here stands for
3750 modify, since this concerns parameters that can be modified by the call.
3751 Note that there is no specific option to test @code{out} parameters,
3752 but any reference within the subprogram will be tested in the usual
3753 manner, and if an invalid value is copied back, any reference to it
3754 will be subject to validity checking.
3755
3756 @item
3757 @option{-gnatVo} Validity checks for operator and attribute operands
3758
3759 Arguments for predefined operators and attributes are validity checked.
3760 This includes all operators in package @code{Standard},
3761 the shift operators defined as intrinsic in package @code{Interfaces}
3762 and operands for attributes such as @code{Pos}.
3763
3764 @item
3765 @option{-gnatVr} Validity checks for function returns
3766
3767 The expression in @code{return} statements in functions is validity
3768 checked.
3769
3770 @item
3771 @option{-gnatVs} Validity checks for subscripts
3772
3773 All subscripts expressions are checked for validity, whether they appear
3774 on the right side or left side (in default mode only left side subscripts
3775 are validity checked).
3776
3777 @item
3778 @option{-gnatVt} Validity checks for tests
3779
3780 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
3781 statements are checked, as well as guard expressions in entry calls.
3782
3783 @item
3784 @option{-gnatVf} Validity checks for floating-point values
3785
3786 In the absence of this switch, validity checking occurs only for discrete
3787 values. If @option{-gnatVf} is specified, then validity checking also applies
3788 for floating-point values, and NaN's and infinities are considered invalid,
3789 as well as out of range values for constrained types. Note that this means
3790 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
3791 in which floating-point values are checked depends on the setting of other
3792 options. For example @option{-gnatVif} or @option{-gnatVfi} (the order does
3793 not matter) specifies that floating-point parameters of mode @code{in} should
3794 be validity checked.
3795
3796 @item
3797 @option{-gnatVa} All validity checks
3798
3799 All the above validity checks are turned on. That is @option{-gnatVa} is
3800 equivalent to @code{gnatVcdfimorst}.
3801
3802 @item
3803 @option{-gnatVn} No validity checks
3804
3805 This switch turns off all validity checking, including the default checking
3806 for case statements and left hand side subscripts. Note that the use of
3807 the switch @option{-gnatp} supresses all run-time checks, including
3808 validity checks, and thus implies @option{-gnatVn}.
3809
3810 @end itemize
3811
3812 The @option{-gnatV} switch may be followed by a string of letters to turn on
3813 a series of validity checking options. For example, @option{-gnatVcr} specifies
3814 that in addition to the default validity checking, copies and function
3815 return expressions be validity checked. In order to make it easier to specify
3816 a set of options, the upper case letters @code{CDFIMORST} may be used to turn
3817 off the corresponding lower case option, so for example @option{-gnatVaM} turns
3818 on all validity checking options except for checking of @code{in out}
3819 procedure arguments.
3820
3821 The specification of additional validity checking generates extra code (and
3822 in the case of @option{-gnatva} the code expansion can be substantial. However,
3823 these additional checks can be very useful in smoking out cases of
3824 uninitialized variables, incorrect use of unchecked conversion, and other
3825 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
3826 is useful in conjunction with the extra validity checking, since this
3827 ensures that wherever possible uninitialized variables have invalid values.
3828
3829 See also the pragma @code{Validity_Checks} which allows modification of
3830 the validity checking mode at the program source level, and also allows for
3831 temporary disabling of validity checks.
3832
3833 @node Style Checking
3834 @subsection Style Checking
3835 @findex Style checking
3836
3837 @noindent
3838 The -gnaty@var{x} switch causes the compiler to
3839 enforce specified style rules. A limited set of style rules has been used
3840 in writing the GNAT sources themselves. This switch allows user programs
3841 to activate all or some of these checks. If the source program fails a
3842 specified style check, an appropriate warning message is given, preceded by
3843 the character sequence "(style)".
3844 The string @var{x} is a sequence of letters or digits
3845 indicating the particular style
3846 checks to be performed. The following checks are defined:
3847
3848 @table @code
3849 @item 1-9 (specify indentation level)
3850 If a digit from 1-9 appears in the string after @option{-gnaty} then proper
3851 indentation is checked, with the digit indicating the indentation level
3852 required. The general style of required indentation is as specified by
3853 the examples in the Ada Reference Manual. Full line comments must be
3854 aligned with the @code{--} starting on a column that is a multiple of
3855 the alignment level.
3856
3857 @item a (check attribute casing)
3858 If the letter a appears in the string after @option{-gnaty} then
3859 attribute names, including the case of keywords such as @code{digits}
3860 used as attributes names, must be written in mixed case, that is, the
3861 initial letter and any letter following an underscore must be uppercase.
3862 All other letters must be lowercase.
3863
3864 @item b (blanks not allowed at statement end)
3865 If the letter b appears in the string after @option{-gnaty} then
3866 trailing blanks are not allowed at the end of statements. The purpose of this
3867 rule, together with h (no horizontal tabs), is to enforce a canonical format
3868 for the use of blanks to separate source tokens.
3869
3870 @item c (check comments)
3871 If the letter c appears in the string after @option{-gnaty} then
3872 comments must meet the following set of rules:
3873
3874 @itemize @bullet
3875
3876 @item
3877 The "--" that starts the column must either start in column one, or else
3878 at least one blank must precede this sequence.
3879
3880 @item
3881 Comments that follow other tokens on a line must have at least one blank
3882 following the "--" at the start of the comment.
3883
3884 @item
3885 Full line comments must have two blanks following the "--" that starts
3886 the comment, with the following exceptions.
3887
3888 @item
3889 A line consisting only of the "--" characters, possibly preceded by blanks
3890 is permitted.
3891
3892 @item
3893 A comment starting with "--x" where x is a special character is permitted.
3894 This alows proper processing of the output generated by specialized tools
3895 including @code{gnatprep} (where --! is used) and the SPARK annnotation
3896 language (where --# is used). For the purposes of this rule, a special
3897 character is defined as being in one of the ASCII ranges
3898 16#21#..16#2F# or 16#3A#..16#3F#.
3899
3900 @item
3901 A line consisting entirely of minus signs, possibly preceded by blanks, is
3902 permitted. This allows the construction of box comments where lines of minus
3903 signs are used to form the top and bottom of the box.
3904
3905 @item
3906 If a comment starts and ends with "--" is permitted as long as at least
3907 one blank follows the initial "--". Together with the preceding rule,
3908 this allows the construction of box comments, as shown in the following
3909 example:
3910 @smallexample
3911 ---------------------------
3912 -- This is a box comment --
3913 -- with two text lines.  --
3914 ---------------------------
3915 @end smallexample
3916 @end itemize
3917
3918 @item e (check end/exit labels)
3919 If the letter e appears in the string after @option{-gnaty} then
3920 optional labels on @code{end} statements ending subprograms and on
3921 @code{exit} statements exiting named loops, are required to be present.
3922
3923 @item f (no form feeds or vertical tabs)
3924 If the letter f appears in the string after @option{-gnaty} then
3925 neither form feeds nor vertical tab characters are not permitted
3926 in the source text.
3927
3928 @item h (no horizontal tabs)
3929 If the letter h appears in the string after @option{-gnaty} then
3930 horizontal tab characters are not permitted in the source text.
3931 Together with the b (no blanks at end of line) check, this
3932 enforces a canonical form for the use of blanks to separate
3933 source tokens.
3934
3935 @item i (check if-then layout)
3936 If the letter i appears in the string after @option{-gnaty},
3937 then the keyword @code{then} must appear either on the same
3938 line as corresponding @code{if}, or on a line on its own, lined
3939 up under the @code{if} with at least one non-blank line in between
3940 containing all or part of the condition to be tested.
3941
3942 @item k (check keyword casing)
3943 If the letter k appears in the string after @option{-gnaty} then
3944 all keywords must be in lower case (with the exception of keywords
3945 such as @code{digits} used as attribute names to which this check
3946 does not apply).
3947
3948 @item l (check layout)
3949 If the letter l appears in the string after @option{-gnaty} then
3950 layout of statement and declaration constructs must follow the
3951 recommendations in the Ada Reference Manual, as indicated by the
3952 form of the syntax rules. For example an @code{else} keyword must
3953 be lined up with the corresponding @code{if} keyword.
3954
3955 There are two respects in which the style rule enforced by this check
3956 option are more liberal than those in the Ada Reference Manual. First
3957 in the case of record declarations, it is permissible to put the
3958 @code{record} keyword on the same line as the @code{type} keyword, and
3959 then the @code{end} in @code{end record} must line up under @code{type}.
3960 For example, either of the following two layouts is acceptable:
3961
3962 @smallexample
3963 @group
3964 @cartouche
3965 @b{type} q @b{is record}
3966    a : integer;
3967    b : integer;
3968 @b{end record};
3969
3970 @b{type} q @b{is}
3971    @b{record}
3972       a : integer;
3973       b : integer;
3974    @b{end record};
3975 @end cartouche
3976 @end group
3977 @end smallexample
3978
3979 @noindent
3980 Second, in the case of a block statement, a permitted alternative
3981 is to put the block label on the same line as the @code{declare} or
3982 @code{begin} keyword, and then line the @code{end} keyword up under
3983 the block label. For example both the following are permitted:
3984
3985 @smallexample
3986 @group
3987 @cartouche
3988 Block : @b{declare}
3989    A : Integer := 3;
3990 @b{begin}
3991    Proc (A, A);
3992 @b{end} Block;
3993
3994 Block :
3995    @b{declare}
3996       A : Integer := 3;
3997    @b{begin}
3998       Proc (A, A);
3999    @b{end} Block;
4000 @end cartouche
4001 @end group
4002 @end smallexample
4003
4004 @noindent
4005 The same alternative format is allowed for loops. For example, both of
4006 the following are permitted:
4007
4008 @smallexample
4009 @group
4010 @cartouche
4011 Clear : @b{while} J < 10 @b{loop}
4012    A (J) := 0;
4013 @b{end loop} Clear;
4014
4015 Clear :
4016    @b{while} J < 10 @b{loop}
4017       A (J) := 0;
4018    @b{end loop} Clear;
4019 @end cartouche
4020 @end group
4021 @end smallexample
4022
4023 @item m (check maximum line length)
4024 If the letter m appears in the string after @option{-gnaty}
4025 then the length of source lines must not exceed 79 characters, including
4026 any trailing blanks. The value of 79 allows convenient display on an
4027 80 character wide device or window, allowing for possible special
4028 treatment of 80 character lines.
4029
4030 @item Mnnn (set maximum line length)
4031 If the sequence Mnnn, where nnn is a decimal number, appears in
4032 the string after @option{-gnaty} then the length of lines must not exceed the
4033 given value.
4034
4035 @item n (check casing of entities in Standard)
4036 If the letter n appears in the string
4037 after @option{-gnaty} then any identifier from Standard must be cased
4038 to match the presentation in the Ada Reference Manual (for example,
4039 @code{Integer} and @code{ASCII.NUL}).
4040
4041 @item o (check order of subprogram bodies)
4042 If the letter o appears in the string
4043 after @option{-gnaty} then all subprogram bodies in a given scope
4044 (e.g. a package body) must be in alphabetical order. The ordering
4045 rule uses normal Ada rules for comparing strings, ignoring casing
4046 of letters, except that if there is a trailing numeric suffix, then
4047 the value of this suffix is used in the ordering (e.g. Junk2 comes
4048 before Junk10).
4049
4050 @item p (check pragma casing)
4051 If the letter p appears in the string after @option{-gnaty} then
4052 pragma names must be written in mixed case, that is, the
4053 initial letter and any letter following an underscore must be uppercase.
4054 All other letters must be lowercase.
4055
4056 @item r (check references)
4057 If the letter r appears in the string after @option{-gnaty}
4058 then all identifier references must be cased in the same way as the
4059 corresponding declaration. No specific casing style is imposed on
4060 identifiers. The only requirement is for consistency of references
4061 with declarations.
4062
4063 @item s (check separate specs)
4064 If the letter s appears in the string after @option{-gnaty} then
4065 separate declarations ("specs") are required for subprograms (a
4066 body is not allowed to serve as its own declaration). The only
4067 exception is that parameterless library level procedures are
4068 not required to have a separate declaration. This exception covers
4069 the most frequent form of main program procedures.
4070
4071 @item t (check token spacing)
4072 If the letter t appears in the string after @option{-gnaty} then
4073 the following token spacing rules are enforced:
4074
4075 @itemize @bullet
4076
4077 @item
4078 The keywords @code{abs} and @code{not} must be followed by a space.
4079
4080 @item
4081 The token @code{=>} must be surrounded by spaces.
4082
4083 @item
4084 The token @code{<>} must be preceded by a space or a left parenthesis.
4085
4086 @item
4087 Binary operators other than @code{**} must be surrounded by spaces.
4088 There is no restriction on the layout of the @code{**} binary operator.
4089
4090 @item
4091 Colon must be surrounded by spaces.
4092
4093 @item
4094 Colon-equal (assignment) must be surrounded by spaces.
4095
4096 @item
4097 Comma must be the first non-blank character on the line, or be
4098 immediately preceded by a non-blank character, and must be followed
4099 by a space.
4100
4101 @item
4102 If the token preceding a left paren ends with a letter or digit, then
4103 a space must separate the two tokens.
4104
4105 @item
4106 A right parenthesis must either be the first non-blank character on
4107 a line, or it must be preceded by a non-blank character.
4108
4109 @item
4110 A semicolon must not be preceded by a space, and must not be followed by
4111 a non-blank character.
4112
4113 @item
4114 A unary plus or minus may not be followed by a space.
4115
4116 @item
4117 A vertical bar must be surrounded by spaces.
4118 @end itemize
4119
4120 @noindent
4121 In the above rules, appearing in column one is always permitted, that is,
4122 counts as meeting either a requirement for a required preceding space,
4123 or as meeting a requirement for no preceding space.
4124
4125 Appearing at the end of a line is also always permitted, that is, counts
4126 as meeting either a requirement for a following space, or as meeting
4127 a requirement for no following space.
4128
4129 @end table
4130
4131 @noindent
4132 If any of these style rules is violated, a message is generated giving
4133 details on the violation. The initial characters of such messages are
4134 always "(style)". Note that these messages are treated as warning
4135 messages, so they normally do not prevent the generation of an object
4136 file. The @option{-gnatwe} switch can be used to treat warning messages,
4137 including style messages, as fatal errors.
4138
4139 @noindent
4140 The switch
4141 @option{-gnaty} on its own (that is not followed by any letters or digits),
4142 is equivalent to @code{gnaty3abcefhiklmprst}, that is all checking
4143 options are enabled with
4144 the exception of -gnatyo,
4145 with an indentation level of 3. This is the standard
4146 checking option that is used for the GNAT sources.
4147
4148 @node Run-Time Checks
4149 @subsection Run-Time Checks
4150 @cindex Division by zero
4151 @cindex Access before elaboration
4152 @cindex Checks, division by zero
4153 @cindex Checks, access before elaboration
4154
4155 @noindent
4156 If you compile with the default options, GNAT will insert many run-time
4157 checks into the compiled code, including code that performs range
4158 checking against constraints, but not arithmetic overflow checking for
4159 integer operations (including division by zero) or checks for access
4160 before elaboration on subprogram calls. All other run-time checks, as
4161 required by the Ada 95 Reference Manual, are generated by default.
4162 The following @code{gcc} switches refine this default behavior:
4163
4164 @table @code
4165 @item -gnatp
4166 @cindex @option{-gnatp} (@code{gcc})
4167 @cindex Suppressing checks
4168 @cindex Checks, suppressing
4169 @findex Suppress
4170 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
4171 had been present in the source. Validity checks are also suppressed (in
4172 other words @option{-gnatp} also implies @option{-gnatVn}.
4173 Use this switch to improve the performance
4174 of the code at the expense of safety in the presence of invalid data or
4175 program bugs.
4176
4177 @item -gnato
4178 @cindex @option{-gnato} (@code{gcc})
4179 @cindex Overflow checks
4180 @cindex Check, overflow
4181 Enables overflow checking for integer operations.
4182 This causes GNAT to generate slower and larger executable
4183 programs by adding code to check for overflow (resulting in raising
4184 @code{Constraint_Error} as required by standard Ada
4185 semantics). These overflow checks correspond to situations in which
4186 the true value of the result of an operation may be outside the base
4187 range of the result type. The following example shows the distinction:
4188
4189 @smallexample
4190 X1 : Integer := Integer'Last;
4191 X2 : Integer range 1 .. 5 := 5;
4192 ...
4193 X1 := X1 + 1;   -- @option{-gnato} required to catch the Constraint_Error
4194 X2 := X2 + 1;   -- range check, @option{-gnato} has no effect here
4195 @end smallexample
4196
4197 @noindent
4198 Here the first addition results in a value that is outside the base range
4199 of Integer, and hence requires an overflow check for detection of the
4200 constraint error. The second increment operation results in a violation
4201 of the explicit range constraint, and such range checks are always
4202 performed. Basically the compiler can assume that in the absence of
4203 the @option{-gnato} switch that any value of type @code{xxx} is
4204 in range of the base type of @code{xxx}.
4205
4206 @findex Machine_Overflows
4207 Note that the @option{-gnato} switch does not affect the code generated
4208 for any floating-point operations; it applies only to integer
4209 semantics).
4210 For floating-point, GNAT has the @code{Machine_Overflows}
4211 attribute set to @code{False} and the normal mode of operation is to
4212 generate IEEE NaN and infinite values on overflow or invalid operations
4213 (such as dividing 0.0 by 0.0).
4214
4215 The reason that we distinguish overflow checking from other kinds of
4216 range constraint checking is that a failure of an overflow check can
4217 generate an incorrect value, but cannot cause erroneous behavior. This
4218 is unlike the situation with a constraint check on an array subscript,
4219 where failure to perform the check can result in random memory description,
4220 or the range check on a case statement, where failure to perform the check
4221 can cause a wild jump.
4222
4223 Note again that @option{-gnato} is off by default, so overflow checking is
4224 not performed in default mode. This means that out of the box, with the
4225 default settings, GNAT does not do all the checks expected from the
4226 language description in the Ada Reference Manual. If you want all constraint
4227 checks to be performed, as described in this Manual, then you must
4228 explicitly use the -gnato switch either on the @code{gnatmake} or
4229 @code{gcc} command.
4230
4231 @item -gnatE
4232 @cindex @option{-gnatE} (@code{gcc})
4233 @cindex Elaboration checks
4234 @cindex Check, elaboration
4235 Enables dynamic checks for access-before-elaboration
4236 on subprogram calls and generic instantiations.
4237 For full details of the effect and use of this switch,
4238 @xref{Compiling Using gcc}.
4239 @end table
4240
4241 @findex Unsuppress
4242 @noindent
4243 The setting of these switches only controls the default setting of the
4244 checks. You may modify them using either @code{Suppress} (to remove
4245 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
4246 the program source.
4247
4248 @node Stack Overflow Checking
4249 @subsection Stack Overflow Checking
4250 @cindex Stack Overflow Checking
4251 @cindex -fstack-check
4252
4253 @noindent
4254 For most operating systems, @code{gcc} does not perform stack overflow
4255 checking by default. This means that if the main environment task or
4256 some other task exceeds the available stack space, then unpredictable
4257 behavior will occur.
4258
4259 To activate stack checking, compile all units with the gcc option
4260 @code{-fstack-check}. For example:
4261
4262 @smallexample
4263 gcc -c -fstack-check package1.adb
4264 @end smallexample
4265
4266 @noindent
4267 Units compiled with this option will generate extra instructions to check
4268 that any use of the stack (for procedure calls or for declaring local
4269 variables in declare blocks) do not exceed the available stack space.
4270 If the space is exceeded, then a @code{Storage_Error} exception is raised.
4271
4272 For declared tasks, the stack size is always controlled by the size
4273 given in an applicable @code{Storage_Size} pragma (or is set to
4274 the default size if no pragma is used.
4275
4276 For the environment task, the stack size depends on
4277 system defaults and is unknown to the compiler. The stack
4278 may even dynamically grow on some systems, precluding the
4279 normal Ada semantics for stack overflow. In the worst case,
4280 unbounded stack usage, causes unbounded stack expansion
4281 resulting in the system running out of virtual memory.
4282
4283 The stack checking may still work correctly if a fixed
4284 size stack is allocated, but this cannot be guaranteed.
4285 To ensure that a clean exception is signalled for stack
4286 overflow, set the environment variable
4287 @code{GNAT_STACK_LIMIT} to indicate the maximum
4288 stack area that can be used, as in:
4289 @cindex GNAT_STACK_LIMIT
4290
4291 @smallexample
4292 SET GNAT_STACK_LIMIT 1600
4293 @end smallexample
4294
4295 @noindent
4296 The limit is given in kilobytes, so the above declaration would
4297 set the stack limit of the environment task to 1.6 megabytes.
4298 Note that the only purpose of this usage is to limit the amount
4299 of stack used by the environment task. If it is necessary to
4300 increase the amount of stack for the environment task, then this
4301 is an operating systems issue, and must be addressed with the
4302 appropriate operating systems commands.
4303
4304 @node Run-Time Control
4305 @subsection Run-Time Control
4306
4307 @table @code
4308 @item -gnatT nnn
4309 @cindex @option{-gnatT} (@code{gcc})
4310 @cindex Time Slicing
4311
4312 @noindent
4313 The @code{gnatT} switch can be used to specify the time-slicing value
4314 to be used for task switching between equal priority tasks. The value
4315 @code{nnn} is given in microseconds as a decimal integer.
4316
4317 Setting the time-slicing value is only effective if the underlying thread
4318 control system can accommodate time slicing. Check the documentation of
4319 your operating system for details. Note that the time-slicing value can
4320 also be set by use of pragma @code{Time_Slice} or by use of the
4321 @code{t} switch in the gnatbind step. The pragma overrides a command
4322 line argument if both are present, and the @code{t} switch for gnatbind
4323 overrides both the pragma and the @code{gcc} command line switch.
4324 @end table
4325
4326 @node Using gcc for Syntax Checking
4327 @subsection Using @code{gcc} for Syntax Checking
4328 @table @code
4329 @item -gnats
4330 @cindex @option{-gnats} (@code{gcc})
4331
4332 @noindent
4333 The @code{s} stands for syntax.
4334
4335 Run GNAT in syntax checking only mode. For
4336 example, the command
4337
4338 @smallexample
4339 $ gcc -c -gnats x.adb
4340 @end smallexample
4341
4342 @noindent
4343 compiles file @file{x.adb} in syntax-check-only mode. You can check a
4344 series of files in a single command
4345 , and can use wild cards to specify such a group of files.
4346 Note that you must specify the @code{-c} (compile
4347 only) flag in addition to the @option{-gnats} flag.
4348 .
4349
4350 You may use other switches in conjunction with @option{-gnats}. In
4351 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
4352 format of any generated error messages.
4353
4354 The output is simply the error messages, if any. No object file or ALI
4355 file is generated by a syntax-only compilation. Also, no units other
4356 than the one specified are accessed. For example, if a unit @code{X}
4357 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
4358 check only mode does not access the source file containing unit
4359 @code{Y}.
4360
4361 @cindex Multiple units, syntax checking
4362 Normally, GNAT allows only a single unit in a source file. However, this
4363 restriction does not apply in syntax-check-only mode, and it is possible
4364 to check a file containing multiple compilation units concatenated
4365 together. This is primarily used by the @code{gnatchop} utility
4366 (@pxref{Renaming Files Using gnatchop}).
4367 @end table
4368
4369 @node Using gcc for Semantic Checking
4370 @subsection Using @code{gcc} for Semantic Checking
4371 @table @code
4372 @item -gnatc
4373 @cindex @option{-gnatc} (@code{gcc})
4374
4375 @noindent
4376 The @code{c} stands for check.
4377 Causes the compiler to operate in semantic check mode,
4378 with full checking for all illegalities specified in the
4379 Ada 95 Reference Manual, but without generation of any object code
4380 (no object file is generated).
4381
4382 Because dependent files must be accessed, you must follow the GNAT
4383 semantic restrictions on file structuring to operate in this mode:
4384
4385 @itemize @bullet
4386 @item
4387 The needed source files must be accessible
4388 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4389
4390 @item
4391 Each file must contain only one compilation unit.
4392
4393 @item
4394 The file name and unit name must match (@pxref{File Naming Rules}).
4395 @end itemize
4396
4397 The output consists of error messages as appropriate. No object file is
4398 generated. An @file{ALI} file is generated for use in the context of
4399 cross-reference tools, but this file is marked as not being suitable
4400 for binding (since no object file is generated).
4401 The checking corresponds exactly to the notion of
4402 legality in the Ada 95 Reference Manual.
4403
4404 Any unit can be compiled in semantics-checking-only mode, including
4405 units that would not normally be compiled (subunits,
4406 and specifications where a separate body is present).
4407 @end table
4408
4409 @node Compiling Ada 83 Programs
4410 @subsection Compiling Ada 83 Programs
4411 @table @code
4412 @cindex Ada 83 compatibility
4413 @item -gnat83
4414 @cindex @option{-gnat83} (@code{gcc})
4415 @cindex ACVC, Ada 83 tests
4416
4417 @noindent
4418 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
4419 specify that an Ada 83 program is to be compiled in Ada83 mode. If you specify
4420 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
4421 where this can be done easily.
4422 It is not possible to guarantee this switch does a perfect
4423 job; for example, some subtle tests, such as are
4424 found in earlier ACVC tests (that have been removed from the ACVC suite for Ada
4425 95), may not compile correctly. However, for most purposes, using
4426 this switch should help to ensure that programs that compile correctly
4427 under the @option{-gnat83} switch can be ported easily to an Ada 83
4428 compiler. This is the main use of the switch.
4429
4430 With few exceptions (most notably the need to use @code{<>} on
4431 @cindex Generic formal parameters
4432 unconstrained generic formal parameters, the use of the new Ada 95
4433 keywords, and the use of packages
4434 with optional bodies), it is not necessary to use the
4435 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
4436 exceptions, Ada 95 is upwardly compatible with Ada 83. This
4437 means that a correct Ada 83 program is usually also a correct Ada 95
4438 program.
4439
4440 @end table
4441
4442 @node Character Set Control
4443 @subsection Character Set Control
4444 @table @code
4445 @item -gnati@var{c}
4446 @cindex @code{-gnati} (@code{gcc})
4447
4448 @noindent
4449 Normally GNAT recognizes the Latin-1 character set in source program
4450 identifiers, as described in the Ada 95 Reference Manual.
4451 This switch causes
4452 GNAT to recognize alternate character sets in identifiers. @var{c} is a
4453 single character  indicating the character set, as follows:
4454
4455 @table @code
4456 @item 1
4457 Latin-1 identifiers
4458
4459 @item 2
4460 Latin-2 letters allowed in identifiers
4461
4462 @item 3
4463 Latin-3 letters allowed in identifiers
4464
4465 @item 4
4466 Latin-4 letters allowed in identifiers
4467
4468 @item 5
4469 Latin-5 (Cyrillic) letters allowed in identifiers
4470
4471 @item 9
4472 Latin-9 letters allowed in identifiers
4473
4474 @item p
4475 IBM PC letters (code page 437) allowed in identifiers
4476
4477 @item 8
4478 IBM PC letters (code page 850) allowed in identifiers
4479
4480 @item f
4481 Full upper-half codes allowed in identifiers
4482
4483 @item n
4484 No upper-half codes allowed in identifiers
4485
4486 @item w
4487 Wide-character codes (that is, codes greater than 255)
4488 allowed in identifiers
4489 @end table
4490
4491 @xref{Foreign Language Representation}, for full details on the
4492 implementation of these character sets.
4493
4494 @item -gnatW@var{e}
4495 @cindex @code{-gnatW} (@code{gcc})
4496 Specify the method of encoding for wide characters.
4497 @var{e} is one of the following:
4498
4499 @table @code
4500
4501 @item h
4502 Hex encoding (brackets coding also recognized)
4503
4504 @item u
4505 Upper half encoding (brackets encoding also recognized)
4506
4507 @item s
4508 Shift/JIS encoding (brackets encoding also recognized)
4509
4510 @item e
4511 EUC encoding (brackets encoding also recognized)
4512
4513 @item 8
4514 UTF-8 encoding (brackets encoding also recognized)
4515
4516 @item b
4517 Brackets encoding only (default value)
4518 @end table
4519 For full details on the these encoding
4520 methods see @xref{Wide Character Encodings}.
4521 Note that brackets coding is always accepted, even if one of the other
4522 options is specified, so for example @option{-gnatW8} specifies that both
4523 brackets and @code{UTF-8} encodings will be recognized. The units that are
4524 with'ed directly or indirectly will be scanned using the specified
4525 representation scheme, and so if one of the non-brackets scheme is
4526 used, it must be used consistently throughout the program. However,
4527 since brackets encoding is always recognized, it may be conveniently
4528 used in standard libraries, allowing these libraries to be used with
4529 any of the available coding schemes.
4530 scheme. If no @option{-gnatW?} parameter is present, then the default
4531 representation is Brackets encoding only.
4532
4533 Note that the wide character representation that is specified (explicitly
4534 or by default) for the main program also acts as the default encoding used
4535 for Wide_Text_IO files if not specifically overridden by a WCEM form
4536 parameter.
4537
4538 @end table
4539 @node File Naming Control
4540 @subsection File Naming Control
4541
4542 @table @code
4543 @item -gnatk@var{n}
4544 @cindex @option{-gnatk} (@code{gcc})
4545 Activates file name "krunching". @var{n}, a decimal integer in the range
4546 1-999, indicates the maximum allowable length of a file name (not
4547 including the @file{.ads} or @file{.adb} extension). The default is not
4548 to enable file name krunching.
4549
4550 For the source file naming rules, @xref{File Naming Rules}.
4551 @end table
4552
4553 @node Subprogram Inlining Control
4554 @subsection Subprogram Inlining Control
4555
4556 @table @code
4557 @item -gnatn
4558 @cindex @option{-gnatn} (@code{gcc})
4559 The @code{n} here is intended to suggest the first syllable of the
4560 word "inline".
4561 GNAT recognizes and processes @code{Inline} pragmas. However, for the
4562 inlining to actually occur, optimization must be enabled. To enable
4563 inlining across unit boundaries, this is, inlining a call in one unit of
4564 a subprogram declared in a @code{with}'ed unit, you must also specify
4565 this switch.
4566 In the absence of this switch, GNAT does not attempt
4567 inlining across units and does not need to access the bodies of
4568 subprograms for which @code{pragma Inline} is specified if they are not
4569 in the current unit.
4570
4571 If you specify this switch the compiler will access these bodies,
4572 creating an extra source dependency for the resulting object file, and
4573 where possible, the call will be inlined.
4574 For further details on when inlining is possible
4575 see @xref{Inlining of Subprograms}.
4576
4577 @item -gnatN
4578 @cindex @option{-gnatN} (@code{gcc})
4579 The front end inlining activated by this switch is generally more extensive,
4580 and quite often more effective than the standard @option{-gnatn} inlining mode.
4581 It will also generate additional dependencies.
4582
4583 @end table
4584
4585 @node Auxiliary Output Control
4586 @subsection Auxiliary Output Control
4587
4588 @table @code
4589 @item -gnatt
4590 @cindex @option{-gnatt} (@code{gcc})
4591 @cindex Writing internal trees
4592 @cindex Internal trees, writing to file
4593 Causes GNAT to write the internal tree for a unit to a file (with the
4594 extension @file{.adt}.
4595 This not normally required, but is used by separate analysis tools.
4596 Typically
4597 these tools do the necessary compilations automatically, so you should
4598 not have to specify this switch in normal operation.
4599
4600 @item -gnatu
4601 @cindex @option{-gnatu} (@code{gcc})
4602 Print a list of units required by this compilation on @file{stdout}.
4603 The listing includes all units on which the unit being compiled depends
4604 either directly or indirectly.
4605
4606 @item -pass-exit-codes
4607 @cindex @code{-pass-exit-codes} (@code{gcc})
4608 If this switch is not used, the exit code returned by @code{gcc} when
4609 compiling multiple files indicates whether all source files have
4610 been successfully used to generate object files or not.
4611
4612 When @code{-pass-exit-codes} is used, @code{gcc} exits with an extended
4613 exit status and allows an integrated development environment to better
4614 react to a compilation failure. Those exit status are:
4615
4616 @table @asis
4617 @item 5
4618 There was an error in at least one source file.
4619 @item 3
4620 At least one source file did not generate an object file.
4621 @item 2
4622 The compiler died unexpectedly (internal error for example).
4623 @item 0
4624 An object file has been generated for every source file.
4625 @end table
4626 @end table
4627
4628 @node Debugging Control
4629 @subsection Debugging Control
4630
4631 @table @code
4632 @cindex Debugging options
4633 @item -gnatd@var{x}
4634 Activate internal debugging switches. @var{x} is a letter or digit, or
4635 string of letters or digits, which specifies the type of debugging
4636 outputs desired. Normally these are used only for internal development
4637 or system debugging purposes. You can find full documentation for these
4638 switches in the body of the @code{Debug} unit in the compiler source
4639 file @file{debug.adb}.
4640
4641 @item -gnatG
4642 @cindex @option{-gnatG} (@code{gcc})
4643 This switch causes the compiler to generate auxiliary output containing
4644 a pseudo-source listing of the generated expanded code. Like most Ada
4645 compilers, GNAT works by first transforming the high level Ada code into
4646 lower level constructs. For example, tasking operations are transformed
4647 into calls to the tasking run-time routines. A unique capability of GNAT
4648 is to list this expanded code in a form very close to normal Ada source.
4649 This is very useful in understanding the implications of various Ada
4650 usage on the efficiency of the generated code. There are many cases in
4651 Ada (e.g. the use of controlled types), where simple Ada statements can
4652 generate a lot of run-time code. By using @option{-gnatG} you can identify
4653 these cases, and consider whether it may be desirable to modify the coding
4654 approach to improve efficiency.
4655
4656 The format of the output is very similar to standard Ada source, and is
4657 easily understood by an Ada programmer. The following special syntactic
4658 additions correspond to low level features used in the generated code that
4659 do not have any exact analogies in pure Ada source form. The following
4660 is a partial list of these special constructions. See the specification
4661 of package @code{Sprint} in file @file{sprint.ads} for a full list.
4662
4663 @table @code
4664 @item new @var{xxx} [storage_pool = @var{yyy}]
4665 Shows the storage pool being used for an allocator.
4666
4667 @item at end @var{procedure-name};
4668 Shows the finalization (cleanup) procedure for a scope.
4669
4670 @item (if @var{expr} then @var{expr} else @var{expr})
4671 Conditional expression equivalent to the @code{x?y:z} construction in C.
4672
4673 @item @var{target}^(@var{source})
4674 A conversion with floating-point truncation instead of rounding.
4675
4676 @item @var{target}?(@var{source})
4677 A conversion that bypasses normal Ada semantic checking. In particular
4678 enumeration types and fixed-point types are treated simply as integers.
4679
4680 @item @var{target}?^(@var{source})
4681 Combines the above two cases.
4682
4683 @item @var{x} #/ @var{y}
4684 @itemx @var{x} #mod @var{y}
4685 @itemx @var{x} #* @var{y}
4686 @itemx @var{x} #rem @var{y}
4687 A division or multiplication of fixed-point values which are treated as
4688 integers without any kind of scaling.
4689
4690 @item free @var{expr} [storage_pool = @var{xxx}]
4691 Shows the storage pool associated with a @code{free} statement.
4692
4693 @item freeze @var{typename} [@var{actions}]
4694 Shows the point at which @var{typename} is frozen, with possible
4695 associated actions to be performed at the freeze point.
4696
4697 @item reference @var{itype}
4698 Reference (and hence definition) to internal type @var{itype}.
4699
4700 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
4701 Intrinsic function call.
4702
4703 @item @var{labelname} : label
4704 Declaration of label @var{labelname}.
4705
4706 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
4707 A multiple concatenation (same effect as @var{expr} & @var{expr} &
4708 @var{expr}, but handled more efficiently).
4709
4710 @item [constraint_error]
4711 Raise the @code{Constraint_Error} exception.
4712
4713 @item @var{expression}'reference
4714 A pointer to the result of evaluating @var{expression}.
4715
4716 @item @var{target-type}!(@var{source-expression})
4717 An unchecked conversion of @var{source-expression} to @var{target-type}.
4718
4719 @item [@var{numerator}/@var{denominator}]
4720 Used to represent internal real literals (that) have no exact
4721 representation in base 2-16 (for example, the result of compile time
4722 evaluation of the expression 1.0/27.0).
4723
4724 @item -gnatD
4725 @cindex @option{-gnatD} (@code{gcc})
4726 This switch is used in conjunction with @option{-gnatG} to cause the expanded
4727 source, as described above to be written to files with names
4728 @file{xxx.dg}, where @file{xxx} is the normal file name,
4729 for example, if the source file name is @file{hello.adb},
4730 then a file @file{hello.adb.dg} will be written.
4731 The debugging information generated
4732 by the @code{gcc} @code{-g} switch will refer to the generated
4733 @file{xxx.dg} file. This allows you to do source level debugging using
4734 the generated code which is sometimes useful for complex code, for example
4735 to find out exactly which part of a complex construction raised an
4736 exception. This switch also suppress generation of cross-reference
4737 information (see -gnatx).
4738
4739 @item -gnatC
4740 @cindex @option{-gnatE} (@code{gcc})
4741 In the generated debugging information, and also in the case of long external
4742 names, the compiler uses a compression mechanism if the name is very long.
4743 This compression method uses a checksum, and avoids trouble on some operating
4744 systems which have difficulty with very long names. The @option{-gnatC} switch
4745 forces this compression approach to be used on all external names and names
4746 in the debugging information tables. This reduces the size of the generated
4747 executable, at the expense of making the naming scheme more complex. The
4748 compression only affects the qualification of the name. Thus a name in
4749 the source:
4750
4751 @smallexample
4752 Very_Long_Package.Very_Long_Inner_Package.Var
4753 @end smallexample
4754
4755 @noindent
4756 would normally appear in these tables as:
4757
4758 @smallexample
4759 very_long_package__very_long_inner_package__var
4760 @end smallexample
4761
4762 @noindent
4763 but if the @option{-gnatC} switch is used, then the name appears as
4764
4765 @smallexample
4766 XCb7e0c705__var
4767 @end smallexample
4768
4769 @noindent
4770 Here b7e0c705 is a compressed encoding of the qualification prefix.
4771 The GNAT Ada aware version of GDB understands these encoded prefixes, so if this
4772 debugger is used, the encoding is largely hidden from the user of the compiler.
4773
4774 @end table
4775
4776 @item -gnatR[0|1|2|3][s]
4777 @cindex @option{-gnatR} (@code{gcc})
4778 This switch controls output from the compiler of a listing showing
4779 representation information for declared types and objects. For
4780 @option{-gnatR0}, no information is output (equivalent to omitting
4781 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
4782 so @option{-gnatR} with no parameter has the same effect), size and alignment
4783 information is listed for declared array and record types. For
4784 @option{-gnatR2}, size and alignment information is listed for all
4785 expression information for values that are computed at run time for
4786 variant records. These symbolic expressions have a mostly obvious
4787 format with #n being used to represent the value of the n'th
4788 discriminant. See source files @file{repinfo.ads/adb} in the
4789 @code{GNAT} sources for full detalis on the format of @option{-gnatR3}
4790 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
4791 the output is to a file with the name @file{file.rep} where
4792 file is the name of the corresponding source file.
4793
4794 @item -gnatx
4795 @cindex @option{-gnatx} (@code{gcc})
4796 Normally the compiler generates full cross-referencing information in
4797 the @file{ALI} file. This information is used by a number of tools,
4798 including @code{gnatfind} and @code{gnatxref}. The -gnatx switch
4799 suppresses this information. This saves some space and may slightly
4800 speed up compilation, but means that these tools cannot be used.
4801 @end table
4802
4803 @node Units to Sources Mapping Files
4804 @subsection Units to Sources Mapping Files
4805
4806 @table @code
4807
4808 @item -gnatem@var{path}
4809 @cindex @option{-gnatem} (@code{gcc})
4810 A mapping file is a way to communicate to the compiler two mappings:
4811 from unit names to file names (without any directory information) and from
4812 file names to path names (with full directory information). These mappings
4813 are used by the compiler to short-circuit the path search.
4814
4815 A mapping file is a sequence of sets of three lines. In each set,
4816 the first line is the unit name, in lower case, with "%s" appended for
4817 specifications and "%b" appended for bodies; the second line is the file
4818 name; and the third line is the path name.
4819
4820 Example:
4821 @smallexample
4822    main%b
4823    main.2.ada
4824    /gnat/project1/sources/main.2.ada
4825 @end smallexample
4826
4827 When the switch @option{-gnatem} is specified, the compiler will create
4828 in memory the two mappings from the specified file. If there is any problem
4829 (non existent file, truncated file or duplicate entries), no mapping
4830 will be created.
4831
4832 Several @option{-gnatem} switches may be specified; however, only the last
4833 one on the command line will be taken into account.
4834
4835 When using a project file, @code{gnatmake} create a temporary mapping file
4836 and communicates it to the compiler using this switch.
4837
4838 @end table
4839
4840 @node Search Paths and the Run-Time Library (RTL)
4841 @section Search Paths and the Run-Time Library (RTL)
4842
4843 @noindent
4844 With the GNAT source-based library system, the compiler must be able to
4845 find source files for units that are needed by the unit being compiled.
4846 Search paths are used to guide this process.
4847
4848 The compiler compiles one source file whose name must be given
4849 explicitly on the command line. In other words, no searching is done
4850 for this file. To find all other source files that are needed (the most
4851 common being the specs of units), the compiler examines the following
4852 directories, in the following order:
4853
4854 @enumerate
4855 @item
4856 The directory containing the source file of the main unit being compiled
4857 (the file name on the command line).
4858
4859 @item
4860 Each directory named by an @code{-I} switch given on the @code{gcc}
4861 command line, in the order given.
4862
4863 @item
4864 @findex ADA_INCLUDE_PATH
4865 Each of the directories listed in the value of the
4866 @code{ADA_INCLUDE_PATH} environment variable.
4867 Construct this value
4868 exactly as the @code{PATH} environment variable: a list of directory
4869 names separated by colons (semicolons when working with the NT version).
4870 @item
4871 The content of the "ada_source_path" file which is part of the GNAT
4872 installation tree and is used to store standard libraries such as the
4873 GNAT Run Time Library (RTL) source files.
4874 @ref{Installing an Ada Library}
4875 @end enumerate
4876
4877 @noindent
4878 Specifying the switch @code{-I-}
4879 inhibits the use of the directory
4880 containing the source file named in the command line. You can still
4881 have this directory on your search path, but in this case it must be
4882 explicitly requested with a @code{-I} switch.
4883
4884 Specifying the switch @code{-nostdinc}
4885 inhibits the search of the default location for the GNAT Run Time
4886 Library (RTL) source files.
4887
4888 The compiler outputs its object files and ALI files in the current
4889 working directory.
4890 Caution: The object file can be redirected with the @code{-o} switch;
4891 however, @code{gcc} and @code{gnat1} have not been coordinated on this
4892 so the ALI file will not go to the right place. Therefore, you should
4893 avoid using the @code{-o} switch.
4894
4895 @findex System.IO
4896 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
4897 children make up the GNAT RTL, together with the simple @code{System.IO}
4898 package used in the "Hello World" example. The sources for these units
4899 are needed by the compiler and are kept together in one directory. Not
4900 all of the bodies are needed, but all of the sources are kept together
4901 anyway. In a normal installation, you need not specify these directory
4902 names when compiling or binding. Either the environment variables or
4903 the built-in defaults cause these files to be found.
4904
4905 In addition to the language-defined hierarchies (System, Ada and
4906 Interfaces), the GNAT distribution provides a fourth hierarchy,
4907 consisting of child units of GNAT. This is a collection of generally
4908 useful routines. See the GNAT Reference Manual for further details.
4909
4910 Besides simplifying access to the RTL, a major use of search paths is
4911 in compiling sources from multiple directories. This can make
4912 development environments much more flexible.
4913
4914 @node Order of Compilation Issues
4915 @section Order of Compilation Issues
4916
4917 @noindent
4918 If, in our earlier example, there was a spec for the @code{hello}
4919 procedure, it would be contained in the file @file{hello.ads}; yet this
4920 file would not have to be explicitly compiled. This is the result of the
4921 model we chose to implement library management. Some of the consequences
4922 of this model are as follows:
4923
4924 @itemize @bullet
4925 @item
4926 There is no point in compiling specs (except for package
4927 specs with no bodies) because these are compiled as needed by clients. If
4928 you attempt a useless compilation, you will receive an error message.
4929 It is also useless to compile subunits because they are compiled as needed
4930 by the parent.
4931
4932 @item
4933 There are no order of compilation requirements: performing a
4934 compilation never obsoletes anything. The only way you can obsolete
4935 something and require recompilations is to modify one of the
4936 source files on which it depends.
4937
4938 @item
4939 There is no library as such, apart from the ALI files
4940 (@pxref{The Ada Library Information Files}, for information on the format of these
4941 files). For now we find it convenient to create separate ALI files, but
4942 eventually the information therein may be incorporated into the object
4943 file directly.
4944
4945 @item
4946 When you compile a unit, the source files for the specs of all units
4947 that it @code{with}'s, all its subunits, and the bodies of any generics it
4948 instantiates must be available (reachable by the search-paths mechanism
4949 described above), or you will receive a fatal error message.
4950 @end itemize
4951
4952 @node Examples
4953 @section Examples
4954
4955 @noindent
4956 The following are some typical Ada compilation command line examples:
4957
4958 @table @code
4959 @item $ gcc -c xyz.adb
4960 Compile body in file @file{xyz.adb} with all default options.
4961
4962 @item $ gcc -c -O2 -gnata xyz-def.adb
4963
4964 Compile the child unit package in file @file{xyz-def.adb} with extensive
4965 optimizations, and pragma @code{Assert}/@code{Debug} statements
4966 enabled.
4967
4968 @item $ gcc -c -gnatc abc-def.adb
4969 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
4970 mode.
4971 @end table
4972
4973 @node Binding Using gnatbind
4974 @chapter Binding Using @code{gnatbind}
4975 @findex gnatbind
4976
4977 @menu
4978 * Running gnatbind::
4979 * Generating the Binder Program in C::
4980 * Consistency-Checking Modes::
4981 * Binder Error Message Control::
4982 * Elaboration Control::
4983 * Output Control::
4984 * Binding with Non-Ada Main Programs::
4985 * Binding Programs with No Main Subprogram::
4986 * Summary of Binder Switches::
4987 * Command-Line Access::
4988 * Search Paths for gnatbind::
4989 * Examples of gnatbind Usage::
4990 @end menu
4991
4992 @noindent
4993 This chapter describes the GNAT binder, @code{gnatbind}, which is used
4994 to bind compiled GNAT objects. The @code{gnatbind} program performs
4995 four separate functions:
4996
4997 @enumerate
4998 @item
4999 Checks that a program is consistent, in accordance with the rules in
5000 Chapter 10 of the Ada 95 Reference Manual. In particular, error
5001 messages are generated if a program uses inconsistent versions of a
5002 given unit.
5003
5004 @item
5005 Checks that an acceptable order of elaboration exists for the program
5006 and issues an error message if it cannot find an order of elaboration
5007 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
5008
5009 @item
5010 Generates a main program incorporating the given elaboration order.
5011 This program is a small Ada package (body and spec) that
5012 must be subsequently compiled
5013 using the GNAT compiler. The necessary compilation step is usually
5014 performed automatically by @code{gnatlink}. The two most important
5015 functions of this program
5016 are to call the elaboration routines of units in an appropriate order
5017 and to call the main program.
5018
5019 @item
5020 Determines the set of object files required by the given main program.
5021 This information is output in the forms of comments in the generated program,
5022 to be read by the @code{gnatlink} utility used to link the Ada application.
5023 @end enumerate
5024
5025 @node Running gnatbind
5026 @section Running @code{gnatbind}
5027
5028 @noindent
5029 The form of the @code{gnatbind} command is
5030
5031 @smallexample
5032 $ gnatbind [@var{switches}] @var{mainprog}[.ali] [@var{switches}]
5033 @end smallexample
5034
5035 @noindent
5036 where @var{mainprog}.adb is the Ada file containing the main program
5037 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
5038 package in two files which names are
5039 @file{b~@var{ada_main}.ads}, and @file{b~@var{ada_main}.adb}.
5040 For example, if given the
5041 parameter @samp{hello.ali}, for a main program contained in file
5042 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
5043 and @file{b~hello.adb}.
5044
5045 When doing consistency checking, the binder takes into consideration
5046 any source files it can locate. For example, if the binder determines
5047 that the given main program requires the package @code{Pack}, whose
5048 @file{.ali}
5049 file is @file{pack.ali} and whose corresponding source spec file is
5050 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
5051 (using the same search path conventions as previously described for the
5052 @code{gcc} command). If it can locate this source file, it checks that
5053 the time stamps
5054 or source checksums of the source and its references to in @file{ali} files
5055 match. In other words, any @file{ali} files that mentions this spec must have
5056 resulted from compiling this version of the source file (or in the case
5057 where the source checksums match, a version close enough that the
5058 difference does not matter).
5059
5060 @cindex Source files, use by binder
5061 The effect of this consistency checking, which includes source files, is
5062 that the binder ensures that the program is consistent with the latest
5063 version of the source files that can be located at bind time. Editing a
5064 source file without compiling files that depend on the source file cause
5065 error messages to be generated by the binder.
5066
5067 For example, suppose you have a main program @file{hello.adb} and a
5068 package @code{P}, from file @file{p.ads} and you perform the following
5069 steps:
5070
5071 @enumerate
5072 @item
5073 Enter @code{gcc -c hello.adb} to compile the main program.
5074
5075 @item
5076 Enter @code{gcc -c p.ads} to compile package @code{P}.
5077
5078 @item
5079 Edit file @file{p.ads}.
5080
5081 @item
5082 Enter @code{gnatbind hello}.
5083 @end enumerate
5084
5085 At this point, the file @file{p.ali} contains an out-of-date time stamp
5086 because the file @file{p.ads} has been edited. The attempt at binding
5087 fails, and the binder generates the following error messages:
5088
5089 @smallexample
5090 error: "hello.adb" must be recompiled ("p.ads" has been modified)
5091 error: "p.ads" has been modified and must be recompiled
5092 @end smallexample
5093
5094 @noindent
5095 Now both files must be recompiled as indicated, and then the bind can
5096 succeed, generating a main program. You need not normally be concerned
5097 with the contents of this file, but it is similar to the following which
5098 is the binder file generated for a simple "hello world" program.
5099
5100 @smallexample
5101 @iftex
5102 @leftskip=0cm
5103 @end iftex
5104 --  The package is called Ada_Main unless this name is actually used
5105 --  as a unit name in the partition, in which case some other unique
5106 --  name is used.
5107
5108 with System;
5109 package ada_main is
5110
5111    Elab_Final_Code : Integer;
5112    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
5113
5114    --  The main program saves the parameters (argument count,
5115    --  argument values, environment pointer) in global variables
5116    --  for later access by other units including
5117    --  Ada.Command_Line.
5118
5119    gnat_argc : Integer;
5120    gnat_argv : System.Address;
5121    gnat_envp : System.Address;
5122
5123    --  The actual variables are stored in a library routine. This
5124    --  is useful for some shared library situations, where there
5125    --  are problems if variables are not in the library.
5126
5127    pragma Import (C, gnat_argc);
5128    pragma Import (C, gnat_argv);
5129    pragma Import (C, gnat_envp);
5130
5131    --  The exit status is similarly an external location
5132
5133    gnat_exit_status : Integer;
5134    pragma Import (C, gnat_exit_status);
5135
5136    GNAT_Version : constant String :=
5137                     "GNAT Version: 3.15w (20010315)";
5138    pragma Export (C, GNAT_Version, "__gnat_version");
5139
5140    --  This is the generated adafinal routine that performs
5141    --  finalization at the end of execution. In the case where
5142    --  Ada is the main program, this main program makes a call
5143    --  to adafinal at program termination.
5144
5145    procedure adafinal;
5146    pragma Export (C, adafinal, "adafinal");
5147
5148    --  This is the generated adainit routine that performs
5149    --  initialization at the start of execution. In the case
5150    --  where Ada is the main program, this main program makes
5151    --  a call to adainit at program startup.
5152
5153    procedure adainit;
5154    pragma Export (C, adainit, "adainit");
5155
5156    --  This routine is called at the start of execution. It is
5157    --  a dummy routine that is used by the debugger to breakpoint
5158    --  at the start of execution.
5159
5160    procedure Break_Start;
5161    pragma Import (C, Break_Start, "__gnat_break_start");
5162
5163    --  This is the actual generated main program (it would be
5164    --  suppressed if the no main program switch were used). As
5165    --  required by standard system conventions, this program has
5166    --  the external name main.
5167
5168    function main
5169      (argc : Integer;
5170       argv : System.Address;
5171       envp : System.Address)
5172       return Integer;
5173    pragma Export (C, main, "main");
5174
5175    --  The following set of constants give the version
5176    --  identification values for every unit in the bound
5177    --  partition. This identification is computed from all
5178    --  dependent semantic units, and corresponds to the
5179    --  string that would be returned by use of the
5180    --  Body_Version or Version attributes.
5181
5182    type Version_32 is mod 2 ** 32;
5183    u00001 : constant Version_32 := 16#7880BEB3#;
5184    u00002 : constant Version_32 := 16#0D24CBD0#;
5185    u00003 : constant Version_32 := 16#3283DBEB#;
5186    u00004 : constant Version_32 := 16#2359F9ED#;
5187    u00005 : constant Version_32 := 16#664FB847#;
5188    u00006 : constant Version_32 := 16#68E803DF#;
5189    u00007 : constant Version_32 := 16#5572E604#;
5190    u00008 : constant Version_32 := 16#46B173D8#;
5191    u00009 : constant Version_32 := 16#156A40CF#;
5192    u00010 : constant Version_32 := 16#033DABE0#;
5193    u00011 : constant Version_32 := 16#6AB38FEA#;
5194    u00012 : constant Version_32 := 16#22B6217D#;
5195    u00013 : constant Version_32 := 16#68A22947#;
5196    u00014 : constant Version_32 := 16#18CC4A56#;
5197    u00015 : constant Version_32 := 16#08258E1B#;
5198    u00016 : constant Version_32 := 16#367D5222#;
5199    u00017 : constant Version_32 := 16#20C9ECA4#;
5200    u00018 : constant Version_32 := 16#50D32CB6#;
5201    u00019 : constant Version_32 := 16#39A8BB77#;
5202    u00020 : constant Version_32 := 16#5CF8FA2B#;
5203    u00021 : constant Version_32 := 16#2F1EB794#;
5204    u00022 : constant Version_32 := 16#31AB6444#;
5205    u00023 : constant Version_32 := 16#1574B6E9#;
5206    u00024 : constant Version_32 := 16#5109C189#;
5207    u00025 : constant Version_32 := 16#56D770CD#;
5208    u00026 : constant Version_32 := 16#02F9DE3D#;
5209    u00027 : constant Version_32 := 16#08AB6B2C#;
5210    u00028 : constant Version_32 := 16#3FA37670#;
5211    u00029 : constant Version_32 := 16#476457A0#;
5212    u00030 : constant Version_32 := 16#731E1B6E#;
5213    u00031 : constant Version_32 := 16#23C2E789#;
5214    u00032 : constant Version_32 := 16#0F1BD6A1#;
5215    u00033 : constant Version_32 := 16#7C25DE96#;
5216    u00034 : constant Version_32 := 16#39ADFFA2#;
5217    u00035 : constant Version_32 := 16#571DE3E7#;
5218    u00036 : constant Version_32 := 16#5EB646AB#;
5219    u00037 : constant Version_32 := 16#4249379B#;
5220    u00038 : constant Version_32 := 16#0357E00A#;
5221    u00039 : constant Version_32 := 16#3784FB72#;
5222    u00040 : constant Version_32 := 16#2E723019#;
5223    u00041 : constant Version_32 := 16#623358EA#;
5224    u00042 : constant Version_32 := 16#107F9465#;
5225    u00043 : constant Version_32 := 16#6843F68A#;
5226    u00044 : constant Version_32 := 16#63305874#;
5227    u00045 : constant Version_32 := 16#31E56CE1#;
5228    u00046 : constant Version_32 := 16#02917970#;
5229    u00047 : constant Version_32 := 16#6CCBA70E#;
5230    u00048 : constant Version_32 := 16#41CD4204#;
5231    u00049 : constant Version_32 := 16#572E3F58#;
5232    u00050 : constant Version_32 := 16#20729FF5#;
5233    u00051 : constant Version_32 := 16#1D4F93E8#;
5234    u00052 : constant Version_32 := 16#30B2EC3D#;
5235    u00053 : constant Version_32 := 16#34054F96#;
5236    u00054 : constant Version_32 := 16#5A199860#;
5237    u00055 : constant Version_32 := 16#0E7F912B#;
5238    u00056 : constant Version_32 := 16#5760634A#;
5239    u00057 : constant Version_32 := 16#5D851835#;
5240
5241    --  The following Export pragmas export the version numbers
5242    --  with symbolic names ending in B (for body) or S
5243    --  (for spec) so that they can be located in a link. The
5244    --  information provided here is sufficient to track down
5245    --  the exact versions of units used in a given build.
5246
5247    pragma Export (C, u00001, "helloB");
5248    pragma Export (C, u00002, "system__standard_libraryB");
5249    pragma Export (C, u00003, "system__standard_libraryS");
5250    pragma Export (C, u00004, "adaS");
5251    pragma Export (C, u00005, "ada__text_ioB");
5252    pragma Export (C, u00006, "ada__text_ioS");
5253    pragma Export (C, u00007, "ada__exceptionsB");
5254    pragma Export (C, u00008, "ada__exceptionsS");
5255    pragma Export (C, u00009, "gnatS");
5256    pragma Export (C, u00010, "gnat__heap_sort_aB");
5257    pragma Export (C, u00011, "gnat__heap_sort_aS");
5258    pragma Export (C, u00012, "systemS");
5259    pragma Export (C, u00013, "system__exception_tableB");
5260    pragma Export (C, u00014, "system__exception_tableS");
5261    pragma Export (C, u00015, "gnat__htableB");
5262    pragma Export (C, u00016, "gnat__htableS");
5263    pragma Export (C, u00017, "system__exceptionsS");
5264    pragma Export (C, u00018, "system__machine_state_operationsB");
5265    pragma Export (C, u00019, "system__machine_state_operationsS");
5266    pragma Export (C, u00020, "system__machine_codeS");
5267    pragma Export (C, u00021, "system__storage_elementsB");
5268    pragma Export (C, u00022, "system__storage_elementsS");
5269    pragma Export (C, u00023, "system__secondary_stackB");
5270    pragma Export (C, u00024, "system__secondary_stackS");
5271    pragma Export (C, u00025, "system__parametersB");
5272    pragma Export (C, u00026, "system__parametersS");
5273    pragma Export (C, u00027, "system__soft_linksB");
5274    pragma Export (C, u00028, "system__soft_linksS");
5275    pragma Export (C, u00029, "system__stack_checkingB");
5276    pragma Export (C, u00030, "system__stack_checkingS");
5277    pragma Export (C, u00031, "system__tracebackB");
5278    pragma Export (C, u00032, "system__tracebackS");
5279    pragma Export (C, u00033, "ada__streamsS");
5280    pragma Export (C, u00034, "ada__tagsB");
5281    pragma Export (C, u00035, "ada__tagsS");
5282    pragma Export (C, u00036, "system__string_opsB");
5283    pragma Export (C, u00037, "system__string_opsS");
5284    pragma Export (C, u00038, "interfacesS");
5285    pragma Export (C, u00039, "interfaces__c_streamsB");
5286    pragma Export (C, u00040, "interfaces__c_streamsS");
5287    pragma Export (C, u00041, "system__file_ioB");
5288    pragma Export (C, u00042, "system__file_ioS");
5289    pragma Export (C, u00043, "ada__finalizationB");
5290    pragma Export (C, u00044, "ada__finalizationS");
5291    pragma Export (C, u00045, "system__finalization_rootB");
5292    pragma Export (C, u00046, "system__finalization_rootS");
5293    pragma Export (C, u00047, "system__finalization_implementationB");
5294    pragma Export (C, u00048, "system__finalization_implementationS");
5295    pragma Export (C, u00049, "system__string_ops_concat_3B");
5296    pragma Export (C, u00050, "system__string_ops_concat_3S");
5297    pragma Export (C, u00051, "system__stream_attributesB");
5298    pragma Export (C, u00052, "system__stream_attributesS");
5299    pragma Export (C, u00053, "ada__io_exceptionsS");
5300    pragma Export (C, u00054, "system__unsigned_typesS");
5301    pragma Export (C, u00055, "system__file_control_blockS");
5302    pragma Export (C, u00056, "ada__finalization__list_controllerB");
5303    pragma Export (C, u00057, "ada__finalization__list_controllerS");
5304
5305    -- BEGIN ELABORATION ORDER
5306    -- ada (spec)
5307    -- gnat (spec)
5308    -- gnat.heap_sort_a (spec)
5309    -- gnat.heap_sort_a (body)
5310    -- gnat.htable (spec)
5311    -- gnat.htable (body)
5312    -- interfaces (spec)
5313    -- system (spec)
5314    -- system.machine_code (spec)
5315    -- system.parameters (spec)
5316    -- system.parameters (body)
5317    -- interfaces.c_streams (spec)
5318    -- interfaces.c_streams (body)
5319    -- system.standard_library (spec)
5320    -- ada.exceptions (spec)
5321    -- system.exception_table (spec)
5322    -- system.exception_table (body)
5323    -- ada.io_exceptions (spec)
5324    -- system.exceptions (spec)
5325    -- system.storage_elements (spec)
5326    -- system.storage_elements (body)
5327    -- system.machine_state_operations (spec)
5328    -- system.machine_state_operations (body)
5329    -- system.secondary_stack (spec)
5330    -- system.stack_checking (spec)
5331    -- system.soft_links (spec)
5332    -- system.soft_links (body)
5333    -- system.stack_checking (body)
5334    -- system.secondary_stack (body)
5335    -- system.standard_library (body)
5336    -- system.string_ops (spec)
5337    -- system.string_ops (body)
5338    -- ada.tags (spec)
5339    -- ada.tags (body)
5340    -- ada.streams (spec)
5341    -- system.finalization_root (spec)
5342    -- system.finalization_root (body)
5343    -- system.string_ops_concat_3 (spec)
5344    -- system.string_ops_concat_3 (body)
5345    -- system.traceback (spec)
5346    -- system.traceback (body)
5347    -- ada.exceptions (body)
5348    -- system.unsigned_types (spec)
5349    -- system.stream_attributes (spec)
5350    -- system.stream_attributes (body)
5351    -- system.finalization_implementation (spec)
5352    -- system.finalization_implementation (body)
5353    -- ada.finalization (spec)
5354    -- ada.finalization (body)
5355    -- ada.finalization.list_controller (spec)
5356    -- ada.finalization.list_controller (body)
5357    -- system.file_control_block (spec)
5358    -- system.file_io (spec)
5359    -- system.file_io (body)
5360    -- ada.text_io (spec)
5361    -- ada.text_io (body)
5362    -- hello (body)
5363    -- END ELABORATION ORDER
5364
5365 end ada_main;
5366
5367 --  The following source file name pragmas allow the generated file
5368 --  names to be unique for different main programs. They are needed
5369 --  since the package name will always be Ada_Main.
5370
5371 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
5372 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
5373
5374 --  Generated package body for Ada_Main starts here
5375
5376 package body ada_main is
5377
5378    --  The actual finalization is performed by calling the
5379    --  library routine in System.Standard_Library.Adafinal
5380
5381    procedure Do_Finalize;
5382    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
5383
5384    -------------
5385    -- adainit --
5386    -------------
5387
5388 @findex adainit
5389    procedure adainit is
5390
5391       --  These booleans are set to True once the associated unit has
5392       --  been elaborated. It is also used to avoid elaborating the
5393       --  same unit twice.
5394
5395       E040 : Boolean; pragma Import (Ada, E040, "interfaces__c_streams_E");
5396       E008 : Boolean; pragma Import (Ada, E008, "ada__exceptions_E");
5397       E014 : Boolean; pragma Import (Ada, E014, "system__exception_table_E");
5398       E053 : Boolean; pragma Import (Ada, E053, "ada__io_exceptions_E");
5399       E017 : Boolean; pragma Import (Ada, E017, "system__exceptions_E");
5400       E024 : Boolean; pragma Import (Ada, E024, "system__secondary_stack_E");
5401       E030 : Boolean; pragma Import (Ada, E030, "system__stack_checking_E");
5402       E028 : Boolean; pragma Import (Ada, E028, "system__soft_links_E");
5403       E035 : Boolean; pragma Import (Ada, E035, "ada__tags_E");
5404       E033 : Boolean; pragma Import (Ada, E033, "ada__streams_E");
5405       E046 : Boolean; pragma Import (Ada, E046, "system__finalization_root_E");
5406       E048 : Boolean; pragma Import (Ada, E048, "system__finalization_implementation_E");
5407       E044 : Boolean; pragma Import (Ada, E044, "ada__finalization_E");
5408       E057 : Boolean; pragma Import (Ada, E057, "ada__finalization__list_controller_E");
5409       E055 : Boolean; pragma Import (Ada, E055, "system__file_control_block_E");
5410       E042 : Boolean; pragma Import (Ada, E042, "system__file_io_E");
5411       E006 : Boolean; pragma Import (Ada, E006, "ada__text_io_E");
5412
5413       --  Set_Globals is a library routine that stores away the
5414       --  value of the indicated set of global values in global
5415       --  variables within the library.
5416
5417       procedure Set_Globals
5418         (Main_Priority            : Integer;
5419          Time_Slice_Value         : Integer;
5420          WC_Encoding              : Character;
5421          Locking_Policy           : Character;
5422          Queuing_Policy           : Character;
5423          Task_Dispatching_Policy  : Character;
5424          Adafinal                 : System.Address;
5425          Unreserve_All_Interrupts : Integer;
5426          Exception_Tracebacks     : Integer);
5427 @findex __gnat_set_globals
5428       pragma Import (C, Set_Globals, "__gnat_set_globals");
5429
5430       --  SDP_Table_Build is a library routine used to build the
5431       --  exception tables. See unit Ada.Exceptions in files
5432       --  a-except.ads/adb for full details of how zero cost
5433       --  exception handling works. This procedure, the call to
5434       --  it, and the two following tables are all omitted if the
5435       --  build is in longjmp/setjump exception mode.
5436
5437 @findex SDP_Table_Build
5438 @findex Zero Cost Exceptions
5439       procedure SDP_Table_Build
5440         (SDP_Addresses   : System.Address;
5441          SDP_Count       : Natural;
5442          Elab_Addresses  : System.Address;
5443          Elab_Addr_Count : Natural);
5444       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
5445
5446       --  Table of Unit_Exception_Table addresses. Used for zero
5447       --  cost exception handling to build the top level table.
5448
5449       ST : aliased constant array (1 .. 23) of System.Address := (
5450         Hello'UET_Address,
5451         Ada.Text_Io'UET_Address,
5452         Ada.Exceptions'UET_Address,
5453         Gnat.Heap_Sort_A'UET_Address,
5454         System.Exception_Table'UET_Address,
5455         System.Machine_State_Operations'UET_Address,
5456         System.Secondary_Stack'UET_Address,
5457         System.Parameters'UET_Address,
5458         System.Soft_Links'UET_Address,
5459         System.Stack_Checking'UET_Address,
5460         System.Traceback'UET_Address,
5461         Ada.Streams'UET_Address,
5462         Ada.Tags'UET_Address,
5463         System.String_Ops'UET_Address,
5464         Interfaces.C_Streams'UET_Address,
5465         System.File_Io'UET_Address,
5466         Ada.Finalization'UET_Address,
5467         System.Finalization_Root'UET_Address,
5468         System.Finalization_Implementation'UET_Address,
5469         System.String_Ops_Concat_3'UET_Address,
5470         System.Stream_Attributes'UET_Address,
5471         System.File_Control_Block'UET_Address,
5472         Ada.Finalization.List_Controller'UET_Address);
5473
5474       --  Table of addresses of elaboration routines. Used for
5475       --  zero cost exception handling to make sure these
5476       --  addresses are included in the top level procedure
5477       --  address table.
5478
5479       EA : aliased constant array (1 .. 23) of System.Address := (
5480         adainit'Code_Address,
5481         Do_Finalize'Code_Address,
5482         Ada.Exceptions'Elab_Spec'Address,
5483         System.Exceptions'Elab_Spec'Address,
5484         Interfaces.C_Streams'Elab_Spec'Address,
5485         System.Exception_Table'Elab_Body'Address,
5486         Ada.Io_Exceptions'Elab_Spec'Address,
5487         System.Stack_Checking'Elab_Spec'Address,
5488         System.Soft_Links'Elab_Body'Address,
5489         System.Secondary_Stack'Elab_Body'Address,
5490         Ada.Tags'Elab_Spec'Address,
5491         Ada.Tags'Elab_Body'Address,
5492         Ada.Streams'Elab_Spec'Address,
5493         System.Finalization_Root'Elab_Spec'Address,
5494         Ada.Exceptions'Elab_Body'Address,
5495         System.Finalization_Implementation'Elab_Spec'Address,
5496         System.Finalization_Implementation'Elab_Body'Address,
5497         Ada.Finalization'Elab_Spec'Address,
5498         Ada.Finalization.List_Controller'Elab_Spec'Address,
5499         System.File_Control_Block'Elab_Spec'Address,
5500         System.File_Io'Elab_Body'Address,
5501         Ada.Text_Io'Elab_Spec'Address,
5502         Ada.Text_Io'Elab_Body'Address);
5503
5504    --  Start of processing for adainit
5505
5506    begin
5507
5508       --  Call SDP_Table_Build to build the top level procedure
5509       --  table for zero cost exception handling (omitted in
5510       --  longjmp/setjump mode).
5511
5512       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
5513
5514       --  Call Set_Globals to record various information for
5515       --  this partition.  The values are derived by the binder
5516       --  from information stored in the ali files by the compiler.
5517
5518 @findex __gnat_set_globals
5519       Set_Globals
5520         (Main_Priority            => -1,
5521          --  Priority of main program, -1 if no pragma Priority used
5522
5523          Time_Slice_Value         => -1,
5524          --  Time slice from Time_Slice pragma, -1 if none used
5525
5526          WC_Encoding              => 'b',
5527          --  Wide_Character encoding used, default is brackets
5528
5529          Locking_Policy           => ' ',
5530          --  Locking_Policy used, default of space means not
5531          --  specified, otherwise it is the first character of
5532          --  the policy name.
5533
5534          Queuing_Policy           => ' ',
5535          --  Queuing_Policy used, default of space means not
5536          --  specified, otherwise it is the first character of
5537          --  the policy name.
5538
5539          Task_Dispatching_Policy  => ' ',
5540          --  Task_Dispatching_Policy used, default of space means
5541          --  not specified, otherwise first character of the
5542          --  policy name.
5543
5544          Adafinal                 => System.Null_Address,
5545          --  Address of Adafinal routine, not used anymore
5546
5547          Unreserve_All_Interrupts => 0,
5548          --  Set true if pragma Unreserve_All_Interrupts was used
5549
5550          Exception_Tracebacks     => 0);
5551          --  Indicates if exception tracebacks are enabled
5552
5553       Elab_Final_Code := 1;
5554
5555       --  Now we have the elaboration calls for all units in the partition.
5556       --  The Elab_Spec and Elab_Body attributes generate references to the
5557       --  implicit elaboration procedures generated by the compiler for
5558       --  each unit that requires elaboration.
5559
5560       if not E040 then
5561          Interfaces.C_Streams'Elab_Spec;
5562       end if;
5563       E040 := True;
5564       if not E008 then
5565          Ada.Exceptions'Elab_Spec;
5566       end if;
5567       if not E014 then
5568          System.Exception_Table'Elab_Body;
5569          E014 := True;
5570       end if;
5571       if not E053 then
5572          Ada.Io_Exceptions'Elab_Spec;
5573          E053 := True;
5574       end if;
5575       if not E017 then
5576          System.Exceptions'Elab_Spec;
5577          E017 := True;
5578       end if;
5579       if not E030 then
5580          System.Stack_Checking'Elab_Spec;
5581       end if;
5582       if not E028 then
5583          System.Soft_Links'Elab_Body;
5584          E028 := True;
5585       end if;
5586       E030 := True;
5587       if not E024 then
5588          System.Secondary_Stack'Elab_Body;
5589          E024 := True;
5590       end if;
5591       if not E035 then
5592          Ada.Tags'Elab_Spec;
5593       end if;
5594       if not E035 then
5595          Ada.Tags'Elab_Body;
5596          E035 := True;
5597       end if;
5598       if not E033 then
5599          Ada.Streams'Elab_Spec;
5600          E033 := True;
5601       end if;
5602       if not E046 then
5603          System.Finalization_Root'Elab_Spec;
5604       end if;
5605       E046 := True;
5606       if not E008 then
5607          Ada.Exceptions'Elab_Body;
5608          E008 := True;
5609       end if;
5610       if not E048 then
5611          System.Finalization_Implementation'Elab_Spec;
5612       end if;
5613       if not E048 then
5614          System.Finalization_Implementation'Elab_Body;
5615          E048 := True;
5616       end if;
5617       if not E044 then
5618          Ada.Finalization'Elab_Spec;
5619       end if;
5620       E044 := True;
5621       if not E057 then
5622          Ada.Finalization.List_Controller'Elab_Spec;
5623       end if;
5624       E057 := True;
5625       if not E055 then
5626          System.File_Control_Block'Elab_Spec;
5627          E055 := True;
5628       end if;
5629       if not E042 then
5630          System.File_Io'Elab_Body;
5631          E042 := True;
5632       end if;
5633       if not E006 then
5634          Ada.Text_Io'Elab_Spec;
5635       end if;
5636       if not E006 then
5637          Ada.Text_Io'Elab_Body;
5638          E006 := True;
5639       end if;
5640
5641       Elab_Final_Code := 0;
5642    end adainit;
5643
5644    --------------
5645    -- adafinal --
5646    --------------
5647
5648 @findex adafinal
5649    procedure adafinal is
5650    begin
5651       Do_Finalize;
5652    end adafinal;
5653
5654    ----------
5655    -- main --
5656    ----------
5657
5658    --  main is actually a function, as in the ANSI C standard,
5659    --  defined to return the exit status. The three parameters
5660    --  are the argument count, argument values and environment
5661    --  pointer.
5662
5663 @findex Main Program
5664    function main
5665      (argc : Integer;
5666       argv : System.Address;
5667       envp : System.Address)
5668       return Integer
5669    is
5670       --  The initialize routine performs low level system
5671       --  initialization using a standard library routine which
5672       --  sets up signal handling and performs any other
5673       --  required setup. The routine can be found in file
5674       --  a-init.c.
5675
5676 @findex __gnat_initialize
5677       procedure initialize;
5678       pragma Import (C, initialize, "__gnat_initialize");
5679
5680       --  The finalize routine performs low level system
5681       --  finalization using a standard library routine. The
5682       --  routine is found in file a-final.c and in the standard
5683       --  distribution is a dummy routine that does nothing, so
5684       --  really this is a hook for special user finalization.
5685
5686 @findex __gnat_finalize
5687       procedure finalize;
5688       pragma Import (C, finalize, "__gnat_finalize");
5689
5690       --  We get to the main program of the partition by using
5691       --  pragma Import because if we try to with the unit and
5692       --  call it Ada style, then not only do we waste time
5693       --  recompiling it, but also, we don't really know the right
5694       --  switches (e.g. identifier character set) to be used
5695       --  to compile it.
5696
5697       procedure Ada_Main_Program;
5698       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
5699
5700    --  Start of processing for main
5701
5702    begin
5703       --  Save global variables
5704
5705       gnat_argc := argc;
5706       gnat_argv := argv;
5707       gnat_envp := envp;
5708
5709       --  Call low level system initialization
5710
5711       Initialize;
5712
5713       --  Call our generated Ada initialization routine
5714
5715       adainit;
5716
5717       --  This is the point at which we want the debugger to get
5718       --  control
5719
5720       Break_Start;
5721
5722       --  Now we call the main program of the partition
5723
5724       Ada_Main_Program;
5725
5726       --  Perform Ada finalization
5727
5728       adafinal;
5729
5730       --  Perform low level system finalization
5731
5732       Finalize;
5733
5734       --  Return the proper exit status
5735       return (gnat_exit_status);
5736    end;
5737
5738 --  This section is entirely comments, so it has no effect on the
5739 --  compilation of the Ada_Main package. It provides the list of
5740 --  object files and linker options, as well as some standard
5741 --  libraries needed for the link. The gnatlink utility parses
5742 --  this b~hello.adb file to read these comment lines to generate
5743 --  the appropriate command line arguments for the call to the
5744 --  system linker. The BEGIN/END lines are used for sentinels for
5745 --  this parsing operation.
5746
5747 --  The exact file names will of course depend on the environment,
5748 --  host/target and location of files on the host system.
5749
5750 @findex Object file list
5751 -- BEGIN Object file/option list
5752    --   ./hello.o
5753    --   -L./
5754    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
5755    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
5756 -- END Object file/option list
5757
5758 end ada_main;
5759
5760 @end smallexample
5761
5762 @noindent
5763 The Ada code in the above example is exactly what is generated by the
5764 binder. We have added comments to more clearly indicate the function
5765 of each part of the generated @code{Ada_Main} package.
5766
5767 The code is standard Ada in all respects, and can be processed by any
5768 tools that handle Ada. In particular, it is possible to use the debugger
5769 in Ada mode to debug the generated Ada_Main package. For example, suppose
5770 that for reasons that you do not understand, your program is blowing up
5771 during elaboration of the body of @code{Ada.Text_IO}. To chase this bug
5772 down, you can place a breakpoint on the call:
5773
5774 @smallexample
5775 Ada.Text_Io'Elab_Body;
5776 @end smallexample
5777
5778 @noindent
5779 and trace the elaboration routine for this package to find out where
5780 the problem might be (more usually of course you would be debugging
5781 elaboration code in your own application).
5782
5783 @node Generating the Binder Program in C
5784 @section Generating the Binder Program in C
5785 @noindent
5786 In most normal usage, the default mode of @code{gnatbind} which is to
5787 generate the main package in Ada, as described in the previous section.
5788 In particular, this means that any Ada programmer can read and understand
5789 the generated main program. It can also be debugged just like any other
5790 Ada code provided the @code{-g} switch is used for @code{gnatbind}
5791 and @code{gnatlink}.
5792
5793 However for some purposes it may be convenient to generate the main
5794 program in C rather than Ada. This may for example be helpful when you
5795 are generating a mixed language program with the main program in C. The
5796 GNAT compiler itself is an example. The use of the @code{-C} switch
5797 for both @code{gnatbind} and @code{gnatlink} will cause the program to
5798 be generated in C (and compiled using the gnu C compiler). The
5799 following shows the C code generated for the same "Hello World"
5800 program:
5801
5802 @smallexample
5803
5804 #ifdef __STDC__
5805 #define PARAMS(paramlist) paramlist
5806 #else
5807 #define PARAMS(paramlist) ()
5808 #endif
5809
5810 extern void __gnat_set_globals
5811  PARAMS ((int, int, int, int, int, int,
5812           void (*) PARAMS ((void)), int, int));
5813 extern void adafinal PARAMS ((void));
5814 extern void adainit PARAMS ((void));
5815 extern void system__standard_library__adafinal PARAMS ((void));
5816 extern int main PARAMS ((int, char **, char **));
5817 extern void exit PARAMS ((int));
5818 extern void __gnat_break_start PARAMS ((void));
5819 extern void _ada_hello PARAMS ((void));
5820 extern void __gnat_initialize PARAMS ((void));
5821 extern void __gnat_finalize PARAMS ((void));
5822
5823 extern void ada__exceptions___elabs PARAMS ((void));
5824 extern void system__exceptions___elabs PARAMS ((void));
5825 extern void interfaces__c_streams___elabs PARAMS ((void));
5826 extern void system__exception_table___elabb PARAMS ((void));
5827 extern void ada__io_exceptions___elabs PARAMS ((void));
5828 extern void system__stack_checking___elabs PARAMS ((void));
5829 extern void system__soft_links___elabb PARAMS ((void));
5830 extern void system__secondary_stack___elabb PARAMS ((void));
5831 extern void ada__tags___elabs PARAMS ((void));
5832 extern void ada__tags___elabb PARAMS ((void));
5833 extern void ada__streams___elabs PARAMS ((void));
5834 extern void system__finalization_root___elabs PARAMS ((void));
5835 extern void ada__exceptions___elabb PARAMS ((void));
5836 extern void system__finalization_implementation___elabs PARAMS ((void));
5837 extern void system__finalization_implementation___elabb PARAMS ((void));
5838 extern void ada__finalization___elabs PARAMS ((void));
5839 extern void ada__finalization__list_controller___elabs PARAMS ((void));
5840 extern void system__file_control_block___elabs PARAMS ((void));
5841 extern void system__file_io___elabb PARAMS ((void));
5842 extern void ada__text_io___elabs PARAMS ((void));
5843 extern void ada__text_io___elabb PARAMS ((void));
5844
5845 extern int __gnat_inside_elab_final_code;
5846
5847 extern int gnat_argc;
5848 extern char **gnat_argv;
5849 extern char **gnat_envp;
5850 extern int gnat_exit_status;
5851
5852 char __gnat_version[] = "GNAT Version: 3.15w (20010315)";
5853 void adafinal () @{
5854    system__standard_library__adafinal ();
5855 @}
5856
5857 void adainit ()
5858 @{
5859    extern char ada__exceptions_E;
5860    extern char system__exceptions_E;
5861    extern char interfaces__c_streams_E;
5862    extern char system__exception_table_E;
5863    extern char ada__io_exceptions_E;
5864    extern char system__secondary_stack_E;
5865    extern char system__stack_checking_E;
5866    extern char system__soft_links_E;
5867    extern char ada__tags_E;
5868    extern char ada__streams_E;
5869    extern char system__finalization_root_E;
5870    extern char system__finalization_implementation_E;
5871    extern char ada__finalization_E;
5872    extern char ada__finalization__list_controller_E;
5873    extern char system__file_control_block_E;
5874    extern char system__file_io_E;
5875    extern char ada__text_io_E;
5876
5877    extern void *__gnat_hello__SDP;
5878    extern void *__gnat_ada__text_io__SDP;
5879    extern void *__gnat_ada__exceptions__SDP;
5880    extern void *__gnat_gnat__heap_sort_a__SDP;
5881    extern void *__gnat_system__exception_table__SDP;
5882    extern void *__gnat_system__machine_state_operations__SDP;
5883    extern void *__gnat_system__secondary_stack__SDP;
5884    extern void *__gnat_system__parameters__SDP;
5885    extern void *__gnat_system__soft_links__SDP;
5886    extern void *__gnat_system__stack_checking__SDP;
5887    extern void *__gnat_system__traceback__SDP;
5888    extern void *__gnat_ada__streams__SDP;
5889    extern void *__gnat_ada__tags__SDP;
5890    extern void *__gnat_system__string_ops__SDP;
5891    extern void *__gnat_interfaces__c_streams__SDP;
5892    extern void *__gnat_system__file_io__SDP;
5893    extern void *__gnat_ada__finalization__SDP;
5894    extern void *__gnat_system__finalization_root__SDP;
5895    extern void *__gnat_system__finalization_implementation__SDP;
5896    extern void *__gnat_system__string_ops_concat_3__SDP;
5897    extern void *__gnat_system__stream_attributes__SDP;
5898    extern void *__gnat_system__file_control_block__SDP;
5899    extern void *__gnat_ada__finalization__list_controller__SDP;
5900
5901    void **st[23] = @{
5902      &__gnat_hello__SDP,
5903      &__gnat_ada__text_io__SDP,
5904      &__gnat_ada__exceptions__SDP,
5905      &__gnat_gnat__heap_sort_a__SDP,
5906      &__gnat_system__exception_table__SDP,
5907      &__gnat_system__machine_state_operations__SDP,
5908      &__gnat_system__secondary_stack__SDP,
5909      &__gnat_system__parameters__SDP,
5910      &__gnat_system__soft_links__SDP,
5911      &__gnat_system__stack_checking__SDP,
5912      &__gnat_system__traceback__SDP,
5913      &__gnat_ada__streams__SDP,
5914      &__gnat_ada__tags__SDP,
5915      &__gnat_system__string_ops__SDP,
5916      &__gnat_interfaces__c_streams__SDP,
5917      &__gnat_system__file_io__SDP,
5918      &__gnat_ada__finalization__SDP,
5919      &__gnat_system__finalization_root__SDP,
5920      &__gnat_system__finalization_implementation__SDP,
5921      &__gnat_system__string_ops_concat_3__SDP,
5922      &__gnat_system__stream_attributes__SDP,
5923      &__gnat_system__file_control_block__SDP,
5924      &__gnat_ada__finalization__list_controller__SDP@};
5925
5926    extern void ada__exceptions___elabs ();
5927    extern void system__exceptions___elabs ();
5928    extern void interfaces__c_streams___elabs ();
5929    extern void system__exception_table___elabb ();
5930    extern void ada__io_exceptions___elabs ();
5931    extern void system__stack_checking___elabs ();
5932    extern void system__soft_links___elabb ();
5933    extern void system__secondary_stack___elabb ();
5934    extern void ada__tags___elabs ();
5935    extern void ada__tags___elabb ();
5936    extern void ada__streams___elabs ();
5937    extern void system__finalization_root___elabs ();
5938    extern void ada__exceptions___elabb ();
5939    extern void system__finalization_implementation___elabs ();
5940    extern void system__finalization_implementation___elabb ();
5941    extern void ada__finalization___elabs ();
5942    extern void ada__finalization__list_controller___elabs ();
5943    extern void system__file_control_block___elabs ();
5944    extern void system__file_io___elabb ();
5945    extern void ada__text_io___elabs ();
5946    extern void ada__text_io___elabb ();
5947
5948    void (*ea[23]) () = @{
5949      adainit,
5950      system__standard_library__adafinal,
5951      ada__exceptions___elabs,
5952      system__exceptions___elabs,
5953      interfaces__c_streams___elabs,
5954      system__exception_table___elabb,
5955      ada__io_exceptions___elabs,
5956      system__stack_checking___elabs,
5957      system__soft_links___elabb,
5958      system__secondary_stack___elabb,
5959      ada__tags___elabs,
5960      ada__tags___elabb,
5961      ada__streams___elabs,
5962      system__finalization_root___elabs,
5963      ada__exceptions___elabb,
5964      system__finalization_implementation___elabs,
5965      system__finalization_implementation___elabb,
5966      ada__finalization___elabs,
5967      ada__finalization__list_controller___elabs,
5968      system__file_control_block___elabs,
5969      system__file_io___elabb,
5970      ada__text_io___elabs,
5971      ada__text_io___elabb@};
5972
5973    __gnat_SDP_Table_Build (&st, 23, ea, 23);
5974    __gnat_set_globals (
5975       -1,      /* Main_Priority              */
5976       -1,      /* Time_Slice_Value           */
5977       'b',     /* WC_Encoding                */
5978       ' ',     /* Locking_Policy             */
5979       ' ',     /* Queuing_Policy             */
5980       ' ',     /* Tasking_Dispatching_Policy */
5981       0,       /* Finalization routine address, not used anymore */
5982       0,       /* Unreserve_All_Interrupts */
5983       0);      /* Exception_Tracebacks */
5984
5985    __gnat_inside_elab_final_code = 1;
5986
5987    if (ada__exceptions_E == 0) @{
5988       ada__exceptions___elabs ();
5989    @}
5990    if (system__exceptions_E == 0) @{
5991       system__exceptions___elabs ();
5992       system__exceptions_E++;
5993    @}
5994    if (interfaces__c_streams_E == 0) @{
5995       interfaces__c_streams___elabs ();
5996    @}
5997    interfaces__c_streams_E = 1;
5998    if (system__exception_table_E == 0) @{
5999       system__exception_table___elabb ();
6000       system__exception_table_E++;
6001    @}
6002    if (ada__io_exceptions_E == 0) @{
6003       ada__io_exceptions___elabs ();
6004       ada__io_exceptions_E++;
6005    @}
6006    if (system__stack_checking_E == 0) @{
6007       system__stack_checking___elabs ();
6008    @}
6009    if (system__soft_links_E == 0) @{
6010       system__soft_links___elabb ();
6011       system__soft_links_E++;
6012    @}
6013    system__stack_checking_E = 1;
6014    if (system__secondary_stack_E == 0) @{
6015       system__secondary_stack___elabb ();
6016       system__secondary_stack_E++;
6017    @}
6018    if (ada__tags_E == 0) @{
6019       ada__tags___elabs ();
6020    @}
6021    if (ada__tags_E == 0) @{
6022       ada__tags___elabb ();
6023       ada__tags_E++;
6024    @}
6025    if (ada__streams_E == 0) @{
6026       ada__streams___elabs ();
6027       ada__streams_E++;
6028    @}
6029    if (system__finalization_root_E == 0) @{
6030       system__finalization_root___elabs ();
6031    @}
6032    system__finalization_root_E = 1;
6033    if (ada__exceptions_E == 0) @{
6034       ada__exceptions___elabb ();
6035       ada__exceptions_E++;
6036    @}
6037    if (system__finalization_implementation_E == 0) @{
6038       system__finalization_implementation___elabs ();
6039    @}
6040    if (system__finalization_implementation_E == 0) @{
6041       system__finalization_implementation___elabb ();
6042       system__finalization_implementation_E++;
6043    @}
6044    if (ada__finalization_E == 0) @{
6045       ada__finalization___elabs ();
6046    @}
6047    ada__finalization_E = 1;
6048    if (ada__finalization__list_controller_E == 0) @{
6049       ada__finalization__list_controller___elabs ();
6050    @}
6051    ada__finalization__list_controller_E = 1;
6052    if (system__file_control_block_E == 0) @{
6053       system__file_control_block___elabs ();
6054       system__file_control_block_E++;
6055    @}
6056    if (system__file_io_E == 0) @{
6057       system__file_io___elabb ();
6058       system__file_io_E++;
6059    @}
6060    if (ada__text_io_E == 0) @{
6061       ada__text_io___elabs ();
6062    @}
6063    if (ada__text_io_E == 0) @{
6064       ada__text_io___elabb ();
6065       ada__text_io_E++;
6066    @}
6067
6068    __gnat_inside_elab_final_code = 0;
6069 @}
6070 int main (argc, argv, envp)
6071     int argc;
6072     char **argv;
6073     char **envp;
6074 @{
6075    gnat_argc = argc;
6076    gnat_argv = argv;
6077    gnat_envp = envp;
6078
6079    __gnat_initialize ();
6080    adainit ();
6081    __gnat_break_start ();
6082
6083    _ada_hello ();
6084
6085    system__standard_library__adafinal ();
6086    __gnat_finalize ();
6087    exit (gnat_exit_status);
6088 @}
6089 unsigned helloB = 0x7880BEB3;
6090 unsigned system__standard_libraryB = 0x0D24CBD0;
6091 unsigned system__standard_libraryS = 0x3283DBEB;
6092 unsigned adaS = 0x2359F9ED;
6093 unsigned ada__text_ioB = 0x47C85FC4;
6094 unsigned ada__text_ioS = 0x496FE45C;
6095 unsigned ada__exceptionsB = 0x74F50187;
6096 unsigned ada__exceptionsS = 0x6736945B;
6097 unsigned gnatS = 0x156A40CF;
6098 unsigned gnat__heap_sort_aB = 0x033DABE0;
6099 unsigned gnat__heap_sort_aS = 0x6AB38FEA;
6100 unsigned systemS = 0x0331C6FE;
6101 unsigned system__exceptionsS = 0x20C9ECA4;
6102 unsigned system__exception_tableB = 0x68A22947;
6103 unsigned system__exception_tableS = 0x394BADD5;
6104 unsigned gnat__htableB = 0x08258E1B;
6105 unsigned gnat__htableS = 0x367D5222;
6106 unsigned system__machine_state_operationsB = 0x4F3B7492;
6107 unsigned system__machine_state_operationsS = 0x182F5CF4;
6108 unsigned system__storage_elementsB = 0x2F1EB794;
6109 unsigned system__storage_elementsS = 0x102C83C7;
6110 unsigned system__secondary_stackB = 0x1574B6E9;
6111 unsigned system__secondary_stackS = 0x708E260A;
6112 unsigned system__parametersB = 0x56D770CD;
6113 unsigned system__parametersS = 0x237E39BE;
6114 unsigned system__soft_linksB = 0x08AB6B2C;
6115 unsigned system__soft_linksS = 0x1E2491F3;
6116 unsigned system__stack_checkingB = 0x476457A0;
6117 unsigned system__stack_checkingS = 0x5299FCED;
6118 unsigned system__tracebackB = 0x2971EBDE;
6119 unsigned system__tracebackS = 0x2E9C3122;
6120 unsigned ada__streamsS = 0x7C25DE96;
6121 unsigned ada__tagsB = 0x39ADFFA2;
6122 unsigned ada__tagsS = 0x769A0464;
6123 unsigned system__string_opsB = 0x5EB646AB;
6124 unsigned system__string_opsS = 0x63CED018;
6125 unsigned interfacesS = 0x0357E00A;
6126 unsigned interfaces__c_streamsB = 0x3784FB72;
6127 unsigned interfaces__c_streamsS = 0x2E723019;
6128 unsigned system__file_ioB = 0x623358EA;
6129 unsigned system__file_ioS = 0x31F873E6;
6130 unsigned ada__finalizationB = 0x6843F68A;
6131 unsigned ada__finalizationS = 0x63305874;
6132 unsigned system__finalization_rootB = 0x31E56CE1;
6133 unsigned system__finalization_rootS = 0x23169EF3;
6134 unsigned system__finalization_implementationB = 0x6CCBA70E;
6135 unsigned system__finalization_implementationS = 0x604AA587;
6136 unsigned system__string_ops_concat_3B = 0x572E3F58;
6137 unsigned system__string_ops_concat_3S = 0x01F57876;
6138 unsigned system__stream_attributesB = 0x1D4F93E8;
6139 unsigned system__stream_attributesS = 0x30B2EC3D;
6140 unsigned ada__io_exceptionsS = 0x34054F96;
6141 unsigned system__unsigned_typesS = 0x7B9E7FE3;
6142 unsigned system__file_control_blockS = 0x2FF876A8;
6143 unsigned ada__finalization__list_controllerB = 0x5760634A;
6144 unsigned ada__finalization__list_controllerS = 0x5D851835;
6145
6146 /* BEGIN ELABORATION ORDER
6147 ada (spec)
6148 gnat (spec)
6149 gnat.heap_sort_a (spec)
6150 gnat.htable (spec)
6151 gnat.htable (body)
6152 interfaces (spec)
6153 system (spec)
6154 system.parameters (spec)
6155 system.standard_library (spec)
6156 ada.exceptions (spec)
6157 system.exceptions (spec)
6158 system.parameters (body)
6159 gnat.heap_sort_a (body)
6160 interfaces.c_streams (spec)
6161 interfaces.c_streams (body)
6162 system.exception_table (spec)
6163 system.exception_table (body)
6164 ada.io_exceptions (spec)
6165 system.storage_elements (spec)
6166 system.storage_elements (body)
6167 system.machine_state_operations (spec)
6168 system.machine_state_operations (body)
6169 system.secondary_stack (spec)
6170 system.stack_checking (spec)
6171 system.soft_links (spec)
6172 system.soft_links (body)
6173 system.stack_checking (body)
6174 system.secondary_stack (body)
6175 system.standard_library (body)
6176 system.string_ops (spec)
6177 system.string_ops (body)
6178 ada.tags (spec)
6179 ada.tags (body)
6180 ada.streams (spec)
6181 system.finalization_root (spec)
6182 system.finalization_root (body)
6183 system.string_ops_concat_3 (spec)
6184 system.string_ops_concat_3 (body)
6185 system.traceback (spec)
6186 system.traceback (body)
6187 ada.exceptions (body)
6188 system.unsigned_types (spec)
6189 system.stream_attributes (spec)
6190 system.stream_attributes (body)
6191 system.finalization_implementation (spec)
6192 system.finalization_implementation (body)
6193 ada.finalization (spec)
6194 ada.finalization (body)
6195 ada.finalization.list_controller (spec)
6196 ada.finalization.list_controller (body)
6197 system.file_control_block (spec)
6198 system.file_io (spec)
6199 system.file_io (body)
6200 ada.text_io (spec)
6201 ada.text_io (body)
6202 hello (body)
6203    END ELABORATION ORDER */
6204
6205 /* BEGIN Object file/option list
6206 ./hello.o
6207 -L./
6208 -L/usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/
6209 /usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/libgnat.a
6210 -lexc
6211    END Object file/option list */
6212
6213 @end smallexample
6214
6215 @noindent
6216 Here again, the C code is exactly what is generated by the binder. The
6217 functions of the various parts of this code correspond in an obvious
6218 manner with the commented Ada code shown in the example in the previous
6219 section.
6220
6221 @node Consistency-Checking Modes
6222 @section Consistency-Checking Modes
6223
6224 @noindent
6225 As described in the previous section, by default @code{gnatbind} checks
6226 that object files are consistent with one another and are consistent
6227 with any source files it can locate. The following switches control binder
6228 access to sources.
6229
6230 @table @code
6231 @item -s
6232 @cindex @code{-s} (@code{gnatbind})
6233 Require source files to be present. In this mode, the binder must be
6234 able to locate all source files that are referenced, in order to check
6235 their consistency. In normal mode, if a source file cannot be located it
6236 is simply ignored. If you specify this switch, a missing source
6237 file is an error.
6238
6239 @item -x
6240 @cindex @code{-x} (@code{gnatbind})
6241 Exclude source files. In this mode, the binder only checks that ALI
6242 files are consistent with one another. Source files are not accessed.
6243 The binder runs faster in this mode, and there is still a guarantee that
6244 the resulting program is self-consistent.
6245 If a source file has been edited since it was last compiled, and you
6246 specify this switch, the binder will not detect that the object
6247 file is out of date with respect to the source file. Note that this is the
6248 mode that is automatically used by @code{gnatmake} because in this
6249 case the checking against sources has already been performed by
6250 @code{gnatmake} in the course of compilation (i.e. before binding).
6251
6252 @end table
6253
6254 @node Binder Error Message Control
6255 @section Binder Error Message Control
6256
6257 @noindent
6258 The following switches provide control over the generation of error
6259 messages from the binder:
6260
6261 @table @code
6262 @item -v
6263 @cindex @code{-v} (@code{gnatbind})
6264 Verbose mode. In the normal mode, brief error messages are generated to
6265 @file{stderr}. If this switch is present, a header is written
6266 to @file{stdout} and any error messages are directed to @file{stdout}.
6267 All that is written to @file{stderr} is a brief summary message.
6268
6269 @item -b
6270 @cindex @code{-b} (@code{gnatbind})
6271 Generate brief error messages to @file{stderr} even if verbose mode is
6272 specified. This is relevant only when used with the
6273 @code{-v} switch.
6274
6275 @item -m@var{n}
6276 @cindex @code{-m} (@code{gnatbind})
6277 Limits the number of error messages to @var{n}, a decimal integer in the
6278 range 1-999. The binder terminates immediately if this limit is reached.
6279
6280 @item -M@var{xxx}
6281 @cindex @code{-M} (@code{gnatbind})
6282 Renames the generated main program from @code{main} to @code{xxx}.
6283 This is useful in the case of some cross-building environments, where
6284 the actual main program is separate from the one generated
6285 by @code{gnatbind}.
6286
6287 @item -ws
6288 @cindex @code{-ws} (@code{gnatbind})
6289 @cindex Warnings
6290 Suppress all warning messages.
6291
6292 @item -we
6293 @cindex @code{-we} (@code{gnatbind})
6294 Treat any warning messages as fatal errors.
6295
6296
6297 @item -t
6298 @cindex @code{-t} (@code{gnatbind})
6299 @cindex Time stamp checks, in binder
6300 @cindex Binder consistency checks
6301 @cindex Consistency checks, in binder
6302 The binder performs a number of consistency checks including:
6303
6304 @itemize @bullet
6305 @item
6306 Check that time stamps of a given source unit are consistent
6307 @item
6308 Check that checksums of a given source unit are consistent
6309 @item
6310 Check that consistent versions of @code{GNAT} were used for compilation
6311 @item
6312 Check consistency of configuration pragmas as required
6313 @end itemize
6314
6315 @noindent
6316 Normally failure of such checks, in accordance with the consistency
6317 requirements of the Ada Reference Manual, causes error messages to be
6318 generated which abort the binder and prevent the output of a binder
6319 file and subsequent link to obtain an executable.
6320
6321 The @code{-t} switch converts these error messages
6322 into warnings, so that
6323 binding and linking can continue to completion even in the presence of such
6324 errors. The result may be a failed link (due to missing symbols), or a
6325 non-functional executable which has undefined semantics.
6326 @emph{This means that
6327 @code{-t} should be used only in unusual situations,
6328 with extreme care.}
6329 @end table
6330
6331 @node Elaboration Control
6332 @section Elaboration Control
6333
6334 @noindent
6335 The following switches provide additional control over the elaboration
6336 order. For full details see @xref{Elaboration Order Handling in GNAT}.
6337
6338 @table @code
6339 @item -p
6340 @cindex @code{-h} (@code{gnatbind})
6341 Normally the binder attempts to choose an elaboration order that is
6342 likely to minimize the likelihood of an elaboration order error resulting
6343 in raising a @code{Program_Error} exception. This switch reverses the
6344 action of the binder, and requests that it deliberately choose an order
6345 that is likely to maximize the likelihood of an elaboration error.
6346 This is useful in ensuring portability and avoiding dependence on
6347 accidental fortuitous elaboration ordering.
6348
6349 Normally it only makes sense to use the @code{-p} switch if dynamic
6350 elaboration checking is used (@option{-gnatE} switch used for compilation).
6351 This is because in the default static elaboration mode, all necessary
6352 @code{Elaborate_All} pragmas are implicitly inserted. These implicit
6353 pragmas are still respected by the binder in @code{-p} mode, so a
6354 safe elaboration order is assured.
6355 @end table
6356
6357 @node Output Control
6358 @section Output Control
6359
6360 @noindent
6361 The following switches allow additional control over the output
6362 generated by the binder.
6363
6364 @table @code
6365
6366 @item -A
6367 @cindex @code{-A} (@code{gnatbind})
6368 Generate binder program in Ada (default). The binder program is named
6369 @file{b~@var{mainprog}.adb} by default. This can be changed with
6370 @code{-o} @code{gnatbind} option.
6371
6372 @item -c
6373 @cindex @code{-c} (@code{gnatbind})
6374 Check only. Do not generate the binder output file. In this mode the
6375 binder performs all error checks but does not generate an output file.
6376
6377 @item -C
6378 @cindex @code{-C} (@code{gnatbind})
6379 Generate binder program in C. The binder program is named
6380 @file{b_@var{mainprog}.c}. This can be changed with @code{-o} @code{gnatbind}
6381 option.
6382
6383 @item -e
6384 @cindex @code{-e} (@code{gnatbind})
6385 Output complete list of elaboration-order dependencies, showing the
6386 reason for each dependency. This output can be rather extensive but may
6387 be useful in diagnosing problems with elaboration order. The output is
6388 written to @file{stdout}.
6389
6390 @item -h
6391 @cindex @code{-h} (@code{gnatbind})
6392 Output usage information. The output is written to @file{stdout}.
6393
6394 @item -K
6395 @cindex @code{-K} (@code{gnatbind})
6396 Output linker options to @file{stdout}. Includes library search paths,
6397 contents of pragmas Ident and Linker_Options, and libraries added
6398 by @code{gnatbind}.
6399
6400 @item -l
6401 @cindex @code{-l} (@code{gnatbind})
6402 Output chosen elaboration order. The output is written to @file{stdout}.
6403
6404 @item -O
6405 @cindex @code{-O} (@code{gnatbind})
6406 Output full names of all the object files that must be linked to provide
6407 the Ada component of the program. The output is written to @file{stdout}.
6408 This list includes the files explicitly supplied and referenced by the user
6409 as well as implicitly referenced run-time unit files. The latter are
6410 omitted if the corresponding units reside in shared libraries. The
6411 directory names for the run-time units depend on the system configuration.
6412
6413 @item -o @var{file}
6414 @cindex @code{-o} (@code{gnatbind})
6415 Set name of output file to @var{file} instead of the normal
6416 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
6417 binder generated body filename. In C mode you would normally give
6418 @var{file} an extension of @file{.c} because it will be a C source program.
6419 Note that if this option is used, then linking must be done manually.
6420 It is not possible to use gnatlink in this case, since it cannot locate
6421 the binder file.
6422
6423 @item -r
6424 @cindex @code{-r} (@code{gnatbind})
6425 Generate list of @code{pragma Rerstrictions} that could be applied to
6426 the current unit. This is useful for code audit purposes, and also may
6427 be used to improve code generation in some cases.
6428
6429 @end table
6430
6431 @node Binding with Non-Ada Main Programs
6432 @section Binding with Non-Ada Main Programs
6433
6434 @noindent
6435 In our description so far we have assumed that the main
6436 program is in Ada, and that the task of the binder is to generate a
6437 corresponding function @code{main} that invokes this Ada main
6438 program. GNAT also supports the building of executable programs where
6439 the main program is not in Ada, but some of the called routines are
6440 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
6441 The following switch is used in this situation:
6442
6443 @table @code
6444 @item -n
6445 @cindex @code{-n} (@code{gnatbind})
6446 No main program. The main program is not in Ada.
6447 @end table
6448
6449 @noindent
6450 In this case, most of the functions of the binder are still required,
6451 but instead of generating a main program, the binder generates a file
6452 containing the following callable routines:
6453
6454 @table @code
6455 @item adainit
6456 @findex adainit
6457 You must call this routine to initialize the Ada part of the program by
6458 calling the necessary elaboration routines. A call to @code{adainit} is
6459 required before the first call to an Ada subprogram.
6460
6461 Note that it is assumed that the basic execution environment must be setup
6462 to be appropriate for Ada execution at the point where the first Ada
6463 subprogram is called. In particular, if the Ada code will do any
6464 floating-point operations, then the FPU must be setup in an appropriate
6465 manner. For the case of the x86, for example, full precision mode is
6466 required. The procedure GNAT.Float_Control.Reset may be used to ensure
6467 that the FPU is in the right state.
6468
6469 @item adafinal
6470 @findex adafinal
6471 You must call this routine to perform any library-level finalization
6472 required by the Ada subprograms. A call to @code{adafinal} is required
6473 after the last call to an Ada subprogram, and before the program
6474 terminates.
6475 @end table
6476
6477 @noindent
6478 If the @code{-n} switch
6479 @cindex Binder, multiple input files
6480 is given, more than one ALI file may appear on
6481 the command line for @code{gnatbind}. The normal @dfn{closure}
6482 calculation is performed for each of the specified units. Calculating
6483 the closure means finding out the set of units involved by tracing
6484 @code{with} references. The reason it is necessary to be able to
6485 specify more than one ALI file is that a given program may invoke two or
6486 more quite separate groups of Ada units.
6487
6488 The binder takes the name of its output file from the last specified ALI
6489 file, unless overridden by the use of the @code{-o file}.
6490 The output is an Ada unit in source form that can
6491 be compiled with GNAT unless the -C switch is used in which case the
6492 output is a C source file, which must be compiled using the C compiler.
6493 This compilation occurs automatically as part of the @code{gnatlink}
6494 processing.
6495
6496 Currently the GNAT run time requires a FPU using 80 bits mode
6497 precision. Under targets where this is not the default it is required to
6498 call GNAT.Float_Control.Reset before using floating point numbers (this
6499 include float computation, float input and output) in the Ada code. A
6500 side effect is that this could be the wrong mode for the foreign code
6501 where floating point computation could be broken after this call.
6502
6503 @node Binding Programs with No Main Subprogram
6504 @section Binding Programs with No Main Subprogram
6505
6506 @noindent
6507 It is possible to have an Ada program which does not have a main
6508 subprogram. This program will call the elaboration routines of all the
6509 packages, then the finalization routines.
6510
6511 The following switch is used to bind programs organized in this manner:
6512
6513 @table @code
6514 @item -z
6515 @cindex @code{-z} (@code{gnatbind})
6516 Normally the binder checks that the unit name given on the command line
6517 corresponds to a suitable main subprogram. When this switch is used,
6518 a list of ALI files can be given, and the execution of the program
6519 consists of elaboration of these units in an appropriate order.
6520 @end table
6521
6522 @node Summary of Binder Switches
6523 @section Summary of Binder Switches
6524
6525 @noindent
6526 The following are the switches available with @code{gnatbind}:
6527
6528 @table @code
6529 @item -aO
6530 Specify directory to be searched for ALI files.
6531
6532 @item -aI
6533 Specify directory to be searched for source file.
6534
6535 @item -A
6536 Generate binder program in Ada (default)
6537
6538 @item -b
6539 Generate brief messages to @file{stderr} even if verbose mode set.
6540
6541 @item -c
6542 Check only, no generation of binder output file.
6543
6544 @item -C
6545 Generate binder program in C
6546
6547 @item -e
6548 Output complete list of elaboration-order dependencies.
6549
6550 @item -E
6551 Store tracebacks in exception occurrences when the target supports it.
6552 This is the default with the zero cost exception mechanism.
6553 This option is currently supported on the following targets:
6554 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
6555 See also the packages @code{GNAT.Traceback} and
6556 @code{GNAT.Traceback.Symbolic} for more information.
6557 Note that on x86 ports, you must not use @code{-fomit-frame-pointer}
6558 @code{gcc} option.
6559
6560 @item -h
6561 Output usage (help) information
6562
6563 @item -I
6564 Specify directory to be searched for source and ALI files.
6565
6566 @item -I-
6567 Do not look for sources in the current directory where @code{gnatbind} was
6568 invoked, and do not look for ALI files in the directory containing the
6569 ALI file named in the @code{gnatbind} command line.
6570
6571 @item -l
6572 Output chosen elaboration order.
6573
6574 @item -Lxxx
6575 Binds the units for library building. In this case the adainit and
6576 adafinal procedures (See @pxref{Binding with Non-Ada Main Programs})
6577 are renamed to xxxinit and xxxfinal. Implies -n.
6578 See @pxref{GNAT and Libraries} for more details.
6579
6580 @item -Mxyz
6581 Rename generated main program from main to xyz
6582
6583 @item -m@var{n}
6584 Limit number of detected errors to @var{n} (1-999).
6585
6586 @item -n
6587 No main program.
6588
6589 @item -nostdinc
6590 Do not look for sources in the system default directory.
6591
6592 @item -nostdlib
6593 Do not look for library files in the system default directory.
6594
6595 @item --RTS=@var{rts-path}
6596 @cindex @code{--RTS} (@code{gnatbind})
6597 Specifies the default location of the runtime library. Same meaning as the
6598 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
6599
6600 @item -o @var{file}
6601 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
6602 Note that if this option is used, then linking must be done manually,
6603 gnatlink cannot be used.
6604
6605 @item -O
6606 Output object list.
6607
6608 @item -p
6609 Pessimistic (worst-case) elaboration order
6610
6611 @item -s
6612 Require all source files to be present.
6613
6614 @item -static
6615 Link against a static GNAT run time.
6616
6617 @item -shared
6618 Link against a shared GNAT run time when available.
6619
6620 @item -t
6621 Tolerate time stamp and other consistency errors
6622
6623 @item -T@var{n}
6624 Set the time slice value to n microseconds. A value of zero means no time
6625 slicing and also indicates to the tasking run time to match as close as
6626 possible to the annex D requirements of the RM.
6627
6628 @item -v
6629 Verbose mode. Write error messages, header, summary output to
6630 @file{stdout}.
6631
6632 @item -w@var{x}
6633 Warning mode (@var{x}=s/e for suppress/treat as error)
6634
6635
6636 @item -x
6637 Exclude source files (check object consistency only).
6638
6639
6640 @item -z
6641 No main subprogram.
6642
6643 @end table
6644
6645 You may obtain this listing by running the program @code{gnatbind} with
6646 no arguments.
6647
6648 @node Command-Line Access
6649 @section Command-Line Access
6650
6651 @noindent
6652 The package @code{Ada.Command_Line} provides access to the command-line
6653 arguments and program name. In order for this interface to operate
6654 correctly, the two variables
6655
6656 @smallexample
6657 @group
6658 @cartouche
6659 int gnat_argc;
6660 char **gnat_argv;
6661 @end cartouche
6662 @end group
6663 @end smallexample
6664
6665 @noindent
6666 @findex gnat_argv
6667 @findex gnat_argc
6668 are declared in one of the GNAT library routines. These variables must
6669 be set from the actual @code{argc} and @code{argv} values passed to the
6670 main program. With no @code{n} present, @code{gnatbind}
6671 generates the C main program to automatically set these variables.
6672 If the @code{n} switch is used, there is no automatic way to
6673 set these variables. If they are not set, the procedures in
6674 @code{Ada.Command_Line} will not be available, and any attempt to use
6675 them will raise @code{Constraint_Error}. If command line access is
6676 required, your main program must set @code{gnat_argc} and
6677 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
6678 it.
6679
6680 @node Search Paths for gnatbind
6681 @section Search Paths for @code{gnatbind}
6682
6683 @noindent
6684 The binder takes the name of an ALI file as its argument and needs to
6685 locate source files as well as other ALI files to verify object consistency.
6686
6687 For source files, it follows exactly the same search rules as @code{gcc}
6688 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
6689 directories searched are:
6690
6691 @enumerate
6692 @item
6693 The directory containing the ALI file named in the command line, unless
6694 the switch @code{-I-} is specified.
6695
6696 @item
6697 All directories specified by @code{-I}
6698 switches on the @code{gnatbind}
6699 command line, in the order given.
6700
6701 @item
6702 @findex ADA_OBJECTS_PATH
6703 Each of the directories listed in the value of the
6704 @code{ADA_OBJECTS_PATH} environment variable.
6705 Construct this value
6706 exactly as the @code{PATH} environment variable: a list of directory
6707 names separated by colons (semicolons when working with the NT version
6708 of GNAT).
6709
6710 @item
6711 The content of the "ada_object_path" file which is part of the GNAT
6712 installation tree and is used to store standard libraries such as the
6713 GNAT Run Time Library (RTL) unless the switch @code{-nostdlib} is
6714 specified.
6715 @ref{Installing an Ada Library}
6716 @end enumerate
6717
6718 @noindent
6719 In the binder the switch @code{-I}
6720 is used to specify both source and
6721 library file paths. Use @code{-aI}
6722 instead if you want to specify
6723 source paths only, and @code{-aO}
6724 if you want to specify library paths
6725 only. This means that for the binder
6726 @code{-I}@var{dir} is equivalent to
6727 @code{-aI}@var{dir}
6728 @code{-aO}@var{dir}.
6729 The binder generates the bind file (a C language source file) in the
6730 current working directory.
6731
6732 @findex Ada
6733 @findex System
6734 @findex Interfaces
6735 @findex GNAT
6736 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
6737 children make up the GNAT Run-Time Library, together with the package
6738 GNAT and its children, which contain a set of useful additional
6739 library functions provided by GNAT. The sources for these units are
6740 needed by the compiler and are kept together in one directory. The ALI
6741 files and object files generated by compiling the RTL are needed by the
6742 binder and the linker and are kept together in one directory, typically
6743 different from the directory containing the sources. In a normal
6744 installation, you need not specify these directory names when compiling
6745 or binding. Either the environment variables or the built-in defaults
6746 cause these files to be found.
6747
6748 Besides simplifying access to the RTL, a major use of search paths is
6749 in compiling sources from multiple directories. This can make
6750 development environments much more flexible.
6751
6752 @node Examples of gnatbind Usage
6753 @section Examples of @code{gnatbind} Usage
6754
6755 @noindent
6756 This section contains a number of examples of using the GNAT binding
6757 utility @code{gnatbind}.
6758
6759 @table @code
6760 @item gnatbind hello
6761 The main program @code{Hello} (source program in @file{hello.adb}) is
6762 bound using the standard switch settings. The generated main program is
6763 @file{b~hello.adb}. This is the normal, default use of the binder.
6764
6765 @item gnatbind hello -o mainprog.adb
6766 The main program @code{Hello} (source program in @file{hello.adb}) is
6767 bound using the standard switch settings. The generated main program is
6768 @file{mainprog.adb} with the associated spec in
6769 @file{mainprog.ads}. Note that you must specify the body here not the
6770 spec, in the case where the output is in Ada. Note that if this option
6771 is used, then linking must be done manually, since gnatlink will not
6772 be able to find the generated file.
6773
6774 @item gnatbind main -C -o mainprog.c -x
6775 The main program @code{Main} (source program in
6776 @file{main.adb}) is bound, excluding source files from the
6777 consistency checking, generating
6778 the file @file{mainprog.c}.
6779
6780 @item gnatbind -x main_program -C -o mainprog.c
6781 This command is exactly the same as the previous example. Switches may
6782 appear anywhere in the command line, and single letter switches may be
6783 combined into a single switch.
6784
6785 @item gnatbind -n math dbase -C -o ada-control.c
6786 The main program is in a language other than Ada, but calls to
6787 subprograms in packages @code{Math} and @code{Dbase} appear. This call
6788 to @code{gnatbind} generates the file @file{ada-control.c} containing
6789 the @code{adainit} and @code{adafinal} routines to be called before and
6790 after accessing the Ada units.
6791 @end table
6792
6793 @node Linking Using gnatlink
6794 @chapter Linking Using @code{gnatlink}
6795 @findex gnatlink
6796
6797 @noindent
6798 This chapter discusses @code{gnatlink}, a utility program used to link
6799 Ada programs and build an executable file. This is a simple program
6800 that invokes the Unix linker (via the @code{gcc}
6801 command) with a correct list of object files and library references.
6802 @code{gnatlink} automatically determines the list of files and
6803 references for the Ada part of a program. It uses the binder file
6804 generated by the binder to determine this list.
6805
6806 @menu
6807 * Running gnatlink::
6808 * Switches for gnatlink::
6809 * Setting Stack Size from gnatlink::
6810 * Setting Heap Size from gnatlink::
6811 @end menu
6812
6813 @node Running gnatlink
6814 @section Running @code{gnatlink}
6815
6816 @noindent
6817 The form of the @code{gnatlink} command is
6818
6819 @smallexample
6820 $ gnatlink [@var{switches}] @var{mainprog}[.ali] [@var{non-Ada objects}]
6821       [@var{linker options}]
6822 @end smallexample
6823
6824 @noindent
6825 @file{@var{mainprog}.ali} references the ALI file of the main program.
6826 The @file{.ali} extension of this file can be omitted. From this
6827 reference, @code{gnatlink} locates the corresponding binder file
6828 @file{b~@var{mainprog}.adb} and, using the information in this file along
6829 with the list of non-Ada objects and linker options, constructs a Unix
6830 linker command file to create the executable.
6831
6832 The arguments following @file{@var{mainprog}.ali} are passed to the
6833 linker uninterpreted. They typically include the names of object files
6834 for units written in other languages than Ada and any library references
6835 required to resolve references in any of these foreign language units,
6836 or in @code{pragma Import} statements in any Ada units.
6837
6838 @var{linker options} is an optional list of linker specific
6839 switches. The default linker called by gnatlink is @var{gcc} which in
6840 turn calls the appropriate system linker usually called
6841 @var{ld}. Standard options for the linker such as @code{-lmy_lib} or
6842 @code{-Ldir} can be added as is. For options that are not recognized by
6843 @var{gcc} as linker options, the @var{gcc} switches @code{-Xlinker} or
6844 @code{-Wl,} shall be used. Refer to the GCC documentation for
6845 details. Here is an example showing how to generate a linker map
6846 assuming that the underlying linker is GNU ld:
6847
6848 @smallexample
6849 $ gnatlink my_prog -Wl,-Map,MAPFILE
6850 @end smallexample
6851
6852 Using @var{linker options} it is possible to set the program stack and
6853 heap size. See @pxref{Setting Stack Size from gnatlink} and
6854 @pxref{Setting Heap Size from gnatlink}.
6855
6856 @code{gnatlink} determines the list of objects required by the Ada
6857 program and prepends them to the list of objects passed to the linker.
6858 @code{gnatlink} also gathers any arguments set by the use of
6859 @code{pragma Linker_Options} and adds them to the list of arguments
6860 presented to the linker.
6861
6862
6863 @node Switches for gnatlink
6864 @section Switches for @code{gnatlink}
6865
6866 @noindent
6867 The following switches are available with the @code{gnatlink} utility:
6868
6869 @table @code
6870
6871 @item -A
6872 @cindex @code{-A} (@code{gnatlink})
6873 The binder has generated code in Ada. This is the default.
6874
6875 @item -C
6876 @cindex @code{-C} (@code{gnatlink})
6877 If instead of generating a file in Ada, the binder has generated one in
6878 C, then the linker needs to know about it. Use this switch to signal
6879 to @code{gnatlink} that the binder has generated C code rather than
6880 Ada code.
6881
6882 @item -f
6883 @cindex Command line length
6884 @cindex @code{-f} (@code{gnatlink})
6885 On some targets, the command line length is limited, and @code{gnatlink}
6886 will generate a separate file for the linker if the list of object files
6887 is too long. The @code{-f} flag forces this file to be generated even if
6888 the limit is not exceeded. This is useful in some cases to deal with
6889 special situations where the command line length is exceeded.
6890
6891 @item -g
6892 @cindex Debugging information, including
6893 @cindex @code{-g} (@code{gnatlink})
6894 The option to include debugging information causes the Ada bind file (in
6895 other words, @file{b~@var{mainprog}.adb}) to be compiled with
6896 @code{-g}.
6897 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
6898 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
6899 Without @code{-g}, the binder removes these files by
6900 default. The same procedure apply if a C bind file was generated using
6901 @code{-C} @code{gnatbind} option, in this case the filenames are
6902 @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
6903
6904 @item -n
6905 @cindex @code{-n} (@code{gnatlink})
6906 Do not compile the file generated by the binder. This may be used when
6907 a link is rerun with different options, but there is no need to recompile
6908 the binder file.
6909
6910 @item -v
6911 @cindex @code{-v} (@code{gnatlink})
6912 Causes additional information to be output, including a full list of the
6913 included object files. This switch option is most useful when you want
6914 to see what set of object files are being used in the link step.
6915
6916 @item -v -v
6917 @cindex @code{-v -v} (@code{gnatlink})
6918 Very verbose mode. Requests that the compiler operate in verbose mode when
6919 it compiles the binder file, and that the system linker run in verbose mode.
6920
6921 @item -o @var{exec-name}
6922 @cindex @code{-o} (@code{gnatlink})
6923 @var{exec-name} specifies an alternate name for the generated
6924 executable program. If this switch is omitted, the executable has the same
6925 name as the main unit. For example, @code{gnatlink try.ali} creates
6926 an executable called @file{try}.
6927
6928 @item -b @var{target}
6929 @cindex @code{-b} (@code{gnatlink})
6930 Compile your program to run on @var{target}, which is the name of a
6931 system configuration. You must have a GNAT cross-compiler built if
6932 @var{target} is not the same as your host system.
6933
6934 @item -B@var{dir}
6935 @cindex @code{-B} (@code{gnatlink})
6936 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
6937 from @var{dir} instead of the default location. Only use this switch
6938 when multiple versions of the GNAT compiler are available. See the
6939 @code{gcc} manual page for further details. You would normally use the
6940 @code{-b} or @code{-V} switch instead.
6941
6942 @item --GCC=@var{compiler_name}
6943 @cindex @code{--GCC=compiler_name} (@code{gnatlink})
6944 Program used for compiling the binder file. The default is
6945 `@code{gcc}'. You need to use quotes around @var{compiler_name} if
6946 @code{compiler_name} contains spaces or other separator characters. As
6947 an example @code{--GCC="foo -x -y"} will instruct @code{gnatlink} to use
6948 @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
6949 inserted after your command name. Thus in the above example the compiler
6950 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
6951 If several @code{--GCC=compiler_name} are used, only the last
6952 @var{compiler_name} is taken into account. However, all the additional
6953 switches are also taken into account. Thus,
6954 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
6955 @code{--GCC="bar -x -y -z -t"}.
6956
6957 @item --LINK=@var{name}
6958 @cindex @code{--LINK=} (@code{gnatlink})
6959 @var{name} is the name of the linker to be invoked. This is especially
6960 useful in mixed language programs since languages such as c++ require
6961 their own linker to be used. When this switch is omitted, the default
6962 name for the linker is (@file{gcc}). When this switch is used, the
6963 specified linker is called instead of (@file{gcc}) with exactly the same
6964 parameters that would have been passed to (@file{gcc}) so if the desired
6965 linker requires different parameters it is necessary to use a wrapper
6966 script that massages the parameters before invoking the real linker. It
6967 may be useful to control the exact invocation by using the verbose
6968 switch.
6969
6970
6971
6972 @end table
6973
6974 @node Setting Stack Size from gnatlink
6975 @section Setting Stack Size from @code{gnatlink}
6976
6977 @noindent
6978 It is possible to specify the program stack size from @code{gnatlink}.
6979 Assuming that the underlying linker is GNU ld there is two ways to do so:
6980
6981 @itemize @bullet
6982
6983 @item using @code{-Xlinker} linker option
6984
6985 @smallexample
6986 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
6987 @end smallexample
6988
6989 This set the stack reserve size to 0x10000 bytes and the stack commit
6990 size to 0x1000 bytes.
6991
6992 @item using @code{-Wl} linker option
6993
6994 @smallexample
6995 $ gnatlink hello -Wl,--stack=0x1000000
6996 @end smallexample
6997
6998 This set the stack reserve size to 0x1000000 bytes. Note that with
6999 @code{-Wl} option it is not possible to set the stack commit size
7000 because the coma is a separator for this option.
7001
7002 @end itemize
7003
7004 @node Setting Heap Size from gnatlink
7005 @section Setting Heap Size from @code{gnatlink}
7006
7007 @noindent
7008 It is possible to specify the program heap size from @code{gnatlink}.
7009 Assuming that the underlying linker is GNU ld there is two ways to do so:
7010
7011 @itemize @bullet
7012
7013 @item using @code{-Xlinker} linker option
7014
7015 @smallexample
7016 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
7017 @end smallexample
7018
7019 This set the heap reserve size to 0x10000 bytes and the heap commit
7020 size to 0x1000 bytes.
7021
7022 @item using @code{-Wl} linker option
7023
7024 @smallexample
7025 $ gnatlink hello -Wl,--heap=0x1000000
7026 @end smallexample
7027
7028 This set the heap reserve size to 0x1000000 bytes. Note that with
7029 @code{-Wl} option it is not possible to set the heap commit size
7030 because the coma is a separator for this option.
7031
7032 @end itemize
7033
7034 @node The GNAT Make Program gnatmake
7035 @chapter The GNAT Make Program @code{gnatmake}
7036 @findex gnatmake
7037
7038 @menu
7039 * Running gnatmake::
7040 * Switches for gnatmake::
7041 * Mode Switches for gnatmake::
7042 * Notes on the Command Line::
7043 * How gnatmake Works::
7044 * Examples of gnatmake Usage::
7045 @end menu
7046 @noindent
7047 A typical development cycle when working on an Ada program consists of
7048 the following steps:
7049
7050 @enumerate
7051 @item
7052 Edit some sources to fix bugs.
7053
7054 @item
7055 Add enhancements.
7056
7057 @item
7058 Compile all sources affected.
7059
7060 @item
7061 Rebind and relink.
7062
7063 @item
7064 Test.
7065 @end enumerate
7066
7067 @noindent
7068 The third step can be tricky, because not only do the modified files
7069 @cindex Dependency rules
7070 have to be compiled, but any files depending on these files must also be
7071 recompiled. The dependency rules in Ada can be quite complex, especially
7072 in the presence of overloading, @code{use} clauses, generics and inlined
7073 subprograms.
7074
7075 @code{gnatmake} automatically takes care of the third and fourth steps
7076 of this process. It determines which sources need to be compiled,
7077 compiles them, and binds and links the resulting object files.
7078
7079 Unlike some other Ada make programs, the dependencies are always
7080 accurately recomputed from the new sources. The source based approach of
7081 the GNAT compilation model makes this possible. This means that if
7082 changes to the source program cause corresponding changes in
7083 dependencies, they will always be tracked exactly correctly by
7084 @code{gnatmake}.
7085
7086 @node Running gnatmake
7087 @section Running @code{gnatmake}
7088
7089 @noindent
7090 The usual form of the @code{gnatmake} command is
7091
7092 @smallexample
7093 $ gnatmake [@var{switches}] @var{file_name} [@var{file_names}] [@var{mode_switches}]
7094 @end smallexample
7095
7096 @noindent
7097 The only required argument is one @var{file_name}, which specifies
7098 a compilation unit that is a main program. Several @var{file_names} can be
7099 specified: this will result in several executables being built.
7100 If @code{switches} are present, they can be placed before the first
7101 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
7102 If @var{mode_switches} are present, they must always be placed after
7103 the last @var{file_name} and all @code{switches}.
7104
7105 If you are using standard file extensions (.adb and .ads), then the
7106 extension may be omitted from the @var{file_name} arguments. However, if
7107 you are using non-standard extensions, then it is required that the
7108 extension be given. A relative or absolute directory path can be
7109 specified in a @var{file_name}, in which case, the input source file will
7110 be searched for in the specified directory only. Otherwise, the input
7111 source file will first be searched in the directory where
7112 @code{gnatmake} was invoked and if it is not found, it will be search on
7113 the source path of the compiler as described in
7114 @ref{Search Paths and the Run-Time Library (RTL)}.
7115
7116 When several @var{file_names} are specified, if an executable needs to be
7117 rebuilt and relinked, all subsequent executables will be rebuilt and
7118 relinked, even if this would not be absolutely necessary.
7119
7120 All @code{gnatmake} output (except when you specify
7121 @code{-M}) is to
7122 @file{stderr}. The output produced by the
7123 @code{-M} switch is send to
7124 @file{stdout}.
7125
7126 @node Switches for gnatmake
7127 @section Switches for @code{gnatmake}
7128
7129 @noindent
7130 You may specify any of the following switches to @code{gnatmake}:
7131
7132 @table @code
7133 @item --GCC=@var{compiler_name}
7134 @cindex @code{--GCC=compiler_name} (@code{gnatmake})
7135 Program used for compiling. The default is `@code{gcc}'. You need to use
7136 quotes around @var{compiler_name} if @code{compiler_name} contains
7137 spaces or other separator characters. As an example @code{--GCC="foo -x
7138 -y"} will instruct @code{gnatmake} to use @code{foo -x -y} as your
7139 compiler. Note that switch @code{-c} is always inserted after your
7140 command name. Thus in the above example the compiler command that will
7141 be used by @code{gnatmake} will be @code{foo -c -x -y}.
7142 If several @code{--GCC=compiler_name} are used, only the last
7143 @var{compiler_name} is taken into account. However, all the additional
7144 switches are also taken into account. Thus,
7145 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7146 @code{--GCC="bar -x -y -z -t"}.
7147
7148 @item --GNATBIND=@var{binder_name}
7149 @cindex @code{--GNATBIND=binder_name} (@code{gnatmake})
7150 Program used for binding. The default is `@code{gnatbind}'. You need to
7151 use quotes around @var{binder_name} if @var{binder_name} contains spaces
7152 or other separator characters. As an example @code{--GNATBIND="bar -x
7153 -y"} will instruct @code{gnatmake} to use @code{bar -x -y} as your
7154 binder. Binder switches that are normally appended by @code{gnatmake} to
7155 `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
7156
7157 @item --GNATLINK=@var{linker_name}
7158 @cindex @code{--GNATLINK=linker_name} (@code{gnatmake})
7159 Program used for linking. The default is `@code{gnatlink}'. You need to
7160 use quotes around @var{linker_name} if @var{linker_name} contains spaces
7161 or other separator characters. As an example @code{--GNATLINK="lan -x
7162 -y"} will instruct @code{gnatmake} to use @code{lan -x -y} as your
7163 linker. Linker switches that are normally appended by @code{gnatmake} to
7164 `@code{gnatlink}' are now appended to the end of @code{lan -x -y}.
7165
7166
7167 @item -a
7168 @cindex @code{-a} (@code{gnatmake})
7169 Consider all files in the make process, even the GNAT internal system
7170 files (for example, the predefined Ada library files), as well as any
7171 locked files. Locked files are files whose ALI file is write-protected.
7172 By default,
7173 @code{gnatmake} does not check these files,
7174 because the assumption is that the GNAT internal files are properly up
7175 to date, and also that any write protected ALI files have been properly
7176 installed. Note that if there is an installation problem, such that one
7177 of these files is not up to date, it will be properly caught by the
7178 binder.
7179 You may have to specify this switch if you are working on GNAT
7180 itself. @code{-a} is also useful in conjunction with
7181 @code{-f}
7182 if you need to recompile an entire application,
7183 including run-time files, using special configuration pragma settings,
7184 such as a non-standard @code{Float_Representation} pragma.
7185 By default
7186 @code{gnatmake -a} compiles all GNAT
7187 internal files with
7188 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
7189
7190 @item -b
7191 @cindex @code{-b} (@code{gnatmake})
7192 Bind only. Can be combined with @code{-c} to do compilation
7193 and binding, but no link. Can be combined with @code{-l}
7194 to do binding and linking. When not combined with @code{-c}
7195 all the units in the closure of the main program must have been previously
7196 compiled and must be up to date. The root unit specified by @var{file_name}
7197 may be given without extension, with the source extension or, if no GNAT
7198 Project File is specified, with the ALI file extension.
7199
7200 @item -c
7201 @cindex @code{-c} (@code{gnatmake})
7202 Compile only. Do not perform binding, except when @code{-b}
7203 is also specified. Do not perform linking, except if both
7204 @code{-b} and
7205  @code{-l} are also specified.
7206 If the root unit specified by @var{file_name} is not a main unit, this is the
7207 default. Otherwise @code{gnatmake} will attempt binding and linking
7208 unless all objects are up to date and the executable is more recent than
7209 the objects.
7210
7211 @item -C
7212 @cindex @code{-C} (@code{gnatmake})
7213 Use a mapping file. A mapping file is a way to communicate to the compiler
7214 two mappings: from unit names to file names (without any directory information)
7215 and from file names to path names (with full directory information).
7216 These mappings are used by the compiler to short-circuit the path search.
7217 When @code{gnatmake} is invoked with this switch, it will create a mapping
7218 file, initially populated by the project manager, if @code{-P} is used,
7219 otherwise initially empty. Each invocation of the compiler will add the newly
7220 accessed sources to the mapping file. This will improve the source search
7221 during the next invocation of the compiler.
7222
7223 @item -f
7224 @cindex @code{-f} (@code{gnatmake})
7225 Force recompilations. Recompile all sources, even though some object
7226 files may be up to date, but don't recompile predefined or GNAT internal
7227 files or locked files (files with a write-protected ALI file),
7228 unless the @code{-a} switch is also specified.
7229
7230 @item
7231 @item -i
7232 @cindex @code{-i} (@code{gnatmake})
7233 In normal mode, @code{gnatmake} compiles all object files and ALI files
7234 into the current directory. If the @code{-i} switch is used,
7235 then instead object files and ALI files that already exist are overwritten
7236 in place. This means that once a large project is organized into separate
7237 directories in the desired manner, then @code{gnatmake} will automatically
7238 maintain and update this organization. If no ALI files are found on the
7239 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
7240 the new object and ALI files are created in the
7241 directory containing the source being compiled. If another organization
7242 is desired, where objects and sources are kept in different directories,
7243 a useful technique is to create dummy ALI files in the desired directories.
7244 When detecting such a dummy file, @code{gnatmake} will be forced to recompile
7245 the corresponding source file, and it will be put the resulting object
7246 and ALI files in the directory where it found the dummy file.
7247
7248 @item -j@var{n}
7249 @cindex @code{-j} (@code{gnatmake})
7250 @cindex Parallel make
7251 Use @var{n} processes to carry out the (re)compilations. On a
7252 multiprocessor machine compilations will occur in parallel. In the
7253 event of compilation errors, messages from various compilations might
7254 get interspersed (but @code{gnatmake} will give you the full ordered
7255 list of failing compiles at the end). If this is problematic, rerun
7256 the make process with n set to 1 to get a clean list of messages.
7257
7258 @item -k
7259 @cindex @code{-k} (@code{gnatmake})
7260 Keep going. Continue as much as possible after a compilation error. To
7261 ease the programmer's task in case of compilation errors, the list of
7262 sources for which the compile fails is given when @code{gnatmake}
7263 terminates.
7264
7265 If @code{gnatmake} is invoked with several @file{file_names} and with this
7266 switch, if there are compilation errors when building an executable,
7267 @code{gnatmake} will not attempt to build the following executables.
7268
7269 @item -l
7270 @cindex @code{-l} (@code{gnatmake})
7271 Link only. Can be combined with @code{-b} to binding
7272 and linking. Linking will not be performed if combined with
7273 @code{-c}
7274 but not with @code{-b}.
7275 When not combined with @code{-b}
7276 all the units in the closure of the main program must have been previously
7277 compiled and must be up to date, and the main program need to have been bound.
7278 The root unit specified by @var{file_name}
7279 may be given without extension, with the source extension or, if no GNAT
7280 Project File is specified, with the ALI file extension.
7281
7282 @item -m
7283 @cindex @code{-m} (@code{gnatmake})
7284 Specifies that the minimum necessary amount of recompilations
7285 be performed. In this mode @code{gnatmake} ignores time
7286 stamp differences when the only
7287 modifications to a source file consist in adding/removing comments,
7288 empty lines, spaces or tabs. This means that if you have changed the
7289 comments in a source file or have simply reformatted it, using this
7290 switch will tell gnatmake not to recompile files that depend on it
7291 (provided other sources on which these files depend have undergone no
7292 semantic modifications). Note that the debugging information may be
7293 out of date with respect to the sources if the @code{-m} switch causes
7294 a compilation to be switched, so the use of this switch represents a
7295 trade-off between compilation time and accurate debugging information.
7296
7297 @item -M
7298 @cindex Dependencies, producing list
7299 @cindex @code{-M} (@code{gnatmake})
7300 Check if all objects are up to date. If they are, output the object
7301 dependences to @file{stdout} in a form that can be directly exploited in
7302 a @file{Makefile}. By default, each source file is prefixed with its
7303 (relative or absolute) directory name. This name is whatever you
7304 specified in the various @code{-aI}
7305 and @code{-I} switches. If you use
7306 @code{gnatmake -M}
7307 @code{-q}
7308 (see below), only the source file names,
7309 without relative paths, are output. If you just specify the
7310 @code{-M}
7311 switch, dependencies of the GNAT internal system files are omitted. This
7312 is typically what you want. If you also specify
7313 the @code{-a} switch,
7314 dependencies of the GNAT internal files are also listed. Note that
7315 dependencies of the objects in external Ada libraries (see switch
7316 @code{-aL}@var{dir} in the following list) are never reported.
7317
7318 @item -n
7319 @cindex @code{-n} (@code{gnatmake})
7320 Don't compile, bind, or link. Checks if all objects are up to date.
7321 If they are not, the full name of the first file that needs to be
7322 recompiled is printed.
7323 Repeated use of this option, followed by compiling the indicated source
7324 file, will eventually result in recompiling all required units.
7325
7326 @item -o @var{exec_name}
7327 @cindex @code{-o} (@code{gnatmake})
7328 Output executable name. The name of the final executable program will be
7329 @var{exec_name}. If the @code{-o} switch is omitted the default
7330 name for the executable will be the name of the input file in appropriate form
7331 for an executable file on the host system.
7332
7333 This switch cannot be used when invoking @code{gnatmake} with several
7334 @file{file_names}.
7335
7336 @item -q
7337 @cindex @code{-q} (@code{gnatmake})
7338 Quiet. When this flag is not set, the commands carried out by
7339 @code{gnatmake} are displayed.
7340
7341 @item -s
7342 @cindex @code{-s} (@code{gnatmake})
7343 Recompile if compiler switches have changed since last compilation.
7344 All compiler switches but -I and -o are taken into account in the
7345 following way:
7346 orders between different ``first letter'' switches are ignored, but
7347 orders between same switches are taken into account. For example,
7348 @code{-O -O2} is different than @code{-O2 -O}, but @code{-g -O} is equivalent
7349 to @code{-O -g}.
7350
7351 @item -u
7352 @cindex @code{-u} (@code{gnatmake})
7353 Unique. Recompile at most the main file. It implies -c. Combined with
7354 -f, it is equivalent to calling the compiler directly.
7355
7356 @item -v
7357 @cindex @code{-v} (@code{gnatmake})
7358 Verbose. Displays the reason for all recompilations @code{gnatmake}
7359 decides are necessary.
7360
7361 @item -z
7362 @cindex @code{-z} (@code{gnatmake})
7363 No main subprogram. Bind and link the program even if the unit name
7364 given on the command line is a package name. The resulting executable
7365 will execute the elaboration routines of the package and its closure,
7366 then the finalization routines.
7367
7368 @item @code{gcc} @asis{switches}
7369 The switch @code{-g} or any uppercase switch (other than @code{-A},
7370 @code{-L} or
7371 @code{-S}) or any switch that is more than one character is passed to
7372 @code{gcc} (e.g. @code{-O}, @option{-gnato,} etc.)
7373 @end table
7374
7375 @noindent
7376 Source and library search path switches:
7377
7378 @table @code
7379 @item -aI@var{dir}
7380 @cindex @code{-aI} (@code{gnatmake})
7381 When looking for source files also look in directory @var{dir}.
7382 The order in which source files search is undertaken is
7383 described in @ref{Search Paths and the Run-Time Library (RTL)}.
7384
7385 @item -aL@var{dir}
7386 @cindex @code{-aL} (@code{gnatmake})
7387 Consider @var{dir} as being an externally provided Ada library.
7388 Instructs @code{gnatmake} to skip compilation units whose @file{.ali}
7389 files have been located in directory @var{dir}. This allows you to have
7390 missing bodies for the units in @var{dir} and to ignore out of date bodies
7391 for the same units. You still need to specify
7392 the location of the specs for these units by using the switches
7393 @code{-aI@var{dir}}
7394 or @code{-I@var{dir}}.
7395 Note: this switch is provided for compatibility with previous versions
7396 of @code{gnatmake}. The easier method of causing standard libraries
7397 to be excluded from consideration is to write-protect the corresponding
7398 ALI files.
7399
7400 @item -aO@var{dir}
7401 @cindex @code{-aO} (@code{gnatmake})
7402 When searching for library and object files, look in directory
7403 @var{dir}. The order in which library files are searched is described in
7404 @ref{Search Paths for gnatbind}.
7405
7406 @item -A@var{dir}
7407 @cindex Search paths, for @code{gnatmake}
7408 @cindex @code{-A} (@code{gnatmake})
7409 Equivalent to @code{-aL@var{dir}
7410 -aI@var{dir}}.
7411
7412 @item -I@var{dir}
7413 @cindex @code{-I} (@code{gnatmake})
7414 Equivalent to @code{-aO@var{dir}
7415 -aI@var{dir}}.
7416
7417 @item -I-
7418 @cindex @code{-I-} (@code{gnatmake})
7419 @cindex Source files, suppressing search
7420 Do not look for source files in the directory containing the source
7421 file named in the command line.
7422 Do not look for ALI or object files in the directory
7423 where @code{gnatmake} was invoked.
7424
7425 @item -L@var{dir}
7426 @cindex @code{-L} (@code{gnatmake})
7427 @cindex Linker libraries
7428 Add directory @var{dir} to the list of directories in which the linker
7429 will search for libraries. This is equivalent to
7430 @code{-largs -L}@var{dir}.
7431
7432 @item -nostdinc
7433 @cindex @code{-nostdinc} (@code{gnatmake})
7434 Do not look for source files in the system default directory.
7435
7436 @item -nostdlib
7437 @cindex @code{-nostdlib} (@code{gnatmake})
7438 Do not look for library files in the system default directory.
7439
7440 @item --RTS=@var{rts-path}
7441 @cindex @code{--RTS} (@code{gnatmake})
7442 Specifies the default location of the runtime library. We look for the runtime
7443 in the following directories, and stop as soon as a valid runtime is found
7444 ("adainclude" or "ada_source_path", and "adalib" or "ada_object_path" present):
7445
7446 @itemize @bullet
7447 @item <current directory>/$rts_path
7448
7449 @item <default-search-dir>/$rts_path
7450
7451 @item <default-search-dir>/rts-$rts_path
7452 @end itemize
7453
7454 @noindent
7455 The selected path is handled like a normal RTS path.
7456
7457 @end table
7458
7459 @node Mode Switches for gnatmake
7460 @section Mode Switches for @code{gnatmake}
7461
7462 @noindent
7463 The mode switches (referred to as @code{mode_switches}) allow the
7464 inclusion of switches that are to be passed to the compiler itself, the
7465 binder or the linker. The effect of a mode switch is to cause all
7466 subsequent switches up to the end of the switch list, or up to the next
7467 mode switch, to be interpreted as switches to be passed on to the
7468 designated component of GNAT.
7469
7470 @table @code
7471 @item -cargs @var{switches}
7472 @cindex @code{-cargs} (@code{gnatmake})
7473 Compiler switches. Here @var{switches} is a list of switches
7474 that are valid switches for @code{gcc}. They will be passed on to
7475 all compile steps performed by @code{gnatmake}.
7476
7477 @item -bargs @var{switches}
7478 @cindex @code{-bargs} (@code{gnatmake})
7479 Binder switches. Here @var{switches} is a list of switches
7480 that are valid switches for @code{gcc}. They will be passed on to
7481 all bind steps performed by @code{gnatmake}.
7482
7483 @item -largs @var{switches}
7484 @cindex @code{-largs} (@code{gnatmake})
7485 Linker switches. Here @var{switches} is a list of switches
7486 that are valid switches for @code{gcc}. They will be passed on to
7487 all link steps performed by @code{gnatmake}.
7488 @end table
7489
7490 @node Notes on the Command Line
7491 @section Notes on the Command Line
7492
7493 @noindent
7494 This section contains some additional useful notes on the operation
7495 of the @code{gnatmake} command.
7496
7497 @itemize @bullet
7498 @item
7499 @cindex Recompilation, by @code{gnatmake}
7500 If @code{gnatmake} finds no ALI files, it recompiles the main program
7501 and all other units required by the main program.
7502 This means that @code{gnatmake}
7503 can be used for the initial compile, as well as during subsequent steps of
7504 the development cycle.
7505
7506 @item
7507 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
7508 is a subunit or body of a generic unit, @code{gnatmake} recompiles
7509 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
7510 warning.
7511
7512 @item
7513 In @code{gnatmake} the switch @code{-I}
7514 is used to specify both source and
7515 library file paths. Use @code{-aI}
7516 instead if you just want to specify
7517 source paths only and @code{-aO}
7518 if you want to specify library paths
7519 only.
7520
7521 @item
7522 @code{gnatmake} examines both an ALI file and its corresponding object file
7523 for consistency. If an ALI is more recent than its corresponding object,
7524 or if the object file is missing, the corresponding source will be recompiled.
7525 Note that @code{gnatmake} expects an ALI and the corresponding object file
7526 to be in the same directory.
7527
7528 @item
7529 @code{gnatmake} will ignore any files whose ALI file is write-protected.
7530 This may conveniently be used to exclude standard libraries from
7531 consideration and in particular it means that the use of the
7532 @code{-f} switch will not recompile these files
7533 unless @code{-a} is also specified.
7534
7535 @item
7536 @code{gnatmake} has been designed to make the use of Ada libraries
7537 particularly convenient. Assume you have an Ada library organized
7538 as follows: @var{obj-dir} contains the objects and ALI files for
7539 of your Ada compilation units,
7540 whereas @var{include-dir} contains the
7541 specs of these units, but no bodies. Then to compile a unit
7542 stored in @code{main.adb}, which uses this Ada library you would just type
7543
7544 @smallexample
7545 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
7546 @end smallexample
7547
7548 @item
7549 Using @code{gnatmake} along with the
7550 @code{-m (minimal recompilation)}
7551 switch provides a mechanism for avoiding unnecessary rcompilations. Using
7552 this switch,
7553 you can update the comments/format of your
7554 source files without having to recompile everything. Note, however, that
7555 adding or deleting lines in a source files may render its debugging
7556 info obsolete. If the file in question is a spec, the impact is rather
7557 limited, as that debugging info will only be useful during the
7558 elaboration phase of your program. For bodies the impact can be more
7559 significant. In all events, your debugger will warn you if a source file
7560 is more recent than the corresponding object, and alert you to the fact
7561 that the debugging information may be out of date.
7562 @end itemize
7563
7564 @node How gnatmake Works
7565 @section How @code{gnatmake} Works
7566
7567 @noindent
7568 Generally @code{gnatmake} automatically performs all necessary
7569 recompilations and you don't need to worry about how it works. However,
7570 it may be useful to have some basic understanding of the @code{gnatmake}
7571 approach and in particular to understand how it uses the results of
7572 previous compilations without incorrectly depending on them.
7573
7574 First a definition: an object file is considered @dfn{up to date} if the
7575 corresponding ALI file exists and its time stamp predates that of the
7576 object file and if all the source files listed in the
7577 dependency section of this ALI file have time stamps matching those in
7578 the ALI file. This means that neither the source file itself nor any
7579 files that it depends on have been modified, and hence there is no need
7580 to recompile this file.
7581
7582 @code{gnatmake} works by first checking if the specified main unit is up
7583 to date. If so, no compilations are required for the main unit. If not,
7584 @code{gnatmake} compiles the main program to build a new ALI file that
7585 reflects the latest sources. Then the ALI file of the main unit is
7586 examined to find all the source files on which the main program depends,
7587 and @code{gnatmake} recursively applies the above procedure on all these files.
7588
7589 This process ensures that @code{gnatmake} only trusts the dependencies
7590 in an existing ALI file if they are known to be correct. Otherwise it
7591 always recompiles to determine a new, guaranteed accurate set of
7592 dependencies. As a result the program is compiled "upside down" from what may
7593 be more familiar as the required order of compilation in some other Ada
7594 systems. In particular, clients are compiled before the units on which
7595 they depend. The ability of GNAT to compile in any order is critical in
7596 allowing an order of compilation to be chosen that guarantees that
7597 @code{gnatmake} will recompute a correct set of new dependencies if
7598 necessary.
7599
7600 When invoking @code{gnatmake} with several @var{file_names}, if a unit is
7601 imported by several of the executables, it will be recompiled at most once.
7602
7603 @node Examples of gnatmake Usage
7604 @section Examples of @code{gnatmake} Usage
7605
7606 @table @code
7607 @item gnatmake hello.adb
7608 Compile all files necessary to bind and link the main program
7609 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
7610 resulting object files to generate an executable file @file{hello}.
7611
7612 @item gnatmake main1 main2 main3
7613 Compile all files necessary to bind and link the main programs
7614 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
7615 (containing unit @code{Main2}) and @file{main3.adb}
7616 (containing unit @code{Main3}) and bind and link the resulting object files
7617 to generate three executable files @file{main1},
7618 @file{main2}
7619 and @file{main3}.
7620
7621 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
7622
7623 Compile all files necessary to bind and link the main program unit
7624 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
7625 be done with optimization level 2 and the order of elaboration will be
7626 listed by the binder. @code{gnatmake} will operate in quiet mode, not
7627 displaying commands it is executing.
7628 @end table
7629
7630 @node Renaming Files Using gnatchop
7631 @chapter Renaming Files Using @code{gnatchop}
7632 @findex gnatchop
7633
7634 @noindent
7635 This chapter discusses how to handle files with multiple units by using
7636 the @code{gnatchop} utility. This utility is also useful in renaming
7637 files to meet the standard GNAT default file naming conventions.
7638
7639 @menu
7640 * Handling Files with Multiple Units::
7641 * Operating gnatchop in Compilation Mode::
7642 * Command Line for gnatchop::
7643 * Switches for gnatchop::
7644 * Examples of gnatchop Usage::
7645 @end menu
7646
7647 @node Handling Files with Multiple Units
7648 @section Handling Files with Multiple Units
7649
7650 @noindent
7651 The basic compilation model of GNAT requires that a file submitted to the
7652 compiler have only one unit and there be a strict correspondence
7653 between the file name and the unit name.
7654
7655 The @code{gnatchop} utility allows both of these rules to be relaxed,
7656 allowing GNAT to process files which contain multiple compilation units
7657 and files with arbitrary file names. @code{gnatchop}
7658 reads the specified file and generates one or more output files,
7659 containing one unit per file. The unit and the file name correspond,
7660 as required by GNAT.
7661
7662 If you want to permanently restructure a set of "foreign" files so that
7663 they match the GNAT rules, and do the remaining development using the
7664 GNAT structure, you can simply use @code{gnatchop} once, generate the
7665 new set of files and work with them from that point on.
7666
7667 Alternatively, if you want to keep your files in the "foreign" format,
7668 perhaps to maintain compatibility with some other Ada compilation
7669 system, you can set up a procedure where you use @code{gnatchop} each
7670 time you compile, regarding the source files that it writes as temporary
7671 files that you throw away.
7672
7673 @node Operating gnatchop in Compilation Mode
7674 @section Operating gnatchop in Compilation Mode
7675
7676 @noindent
7677 The basic function of @code{gnatchop} is to take a file with multiple units
7678 and split it into separate files. The boundary between files is reasonably
7679 clear, except for the issue of comments and pragmas. In default mode, the
7680 rule is that any pragmas between units belong to the previous unit, except
7681 that configuration pragmas always belong to the following unit. Any comments
7682 belong to the following unit. These rules
7683 almost always result in the right choice of
7684 the split point without needing to mark it explicitly and most users will
7685 find this default to be what they want. In this default mode it is incorrect to
7686 submit a file containing only configuration pragmas, or one that ends in
7687 configuration pragmas, to @code{gnatchop}.
7688
7689 However, using a special option to activate "compilation mode",
7690 @code{gnatchop}
7691 can perform another function, which is to provide exactly the semantics
7692 required by the RM for handling of configuration pragmas in a compilation.
7693 In the absence of configuration pragmas (at the main file level), this
7694 option has no effect, but it causes such configuration pragmas to be handled
7695 in a quite different manner.
7696
7697 First, in compilation mode, if @code{gnatchop} is given a file that consists of
7698 only configuration pragmas, then this file is appended to the
7699 @file{gnat.adc} file in the current directory. This behavior provides
7700 the required behavior described in the RM for the actions to be taken
7701 on submitting such a file to the compiler, namely that these pragmas
7702 should apply to all subsequent compilations in the same compilation
7703 environment. Using GNAT, the current directory, possibly containing a
7704 @file{gnat.adc} file is the representation
7705 of a compilation environment. For more information on the
7706 @file{gnat.adc} file, see the section on handling of configuration
7707 pragmas @pxref{Handling of Configuration Pragmas}.
7708
7709 Second, in compilation mode, if @code{gnatchop}
7710 is given a file that starts with
7711 configuration pragmas, and contains one or more units, then these
7712 configuration pragmas are prepended to each of the chopped files. This
7713 behavior provides the required behavior described in the RM for the
7714 actions to be taken on compiling such a file, namely that the pragmas
7715 apply to all units in the compilation, but not to subsequently compiled
7716 units.
7717
7718 Finally, if configuration pragmas appear between units, they are appended
7719 to the previous unit. This results in the previous unit being illegal,
7720 since the compiler does not accept configuration pragmas that follow
7721 a unit. This provides the required RM behavior that forbids configuration
7722 pragmas other than those preceding the first compilation unit of a
7723 compilation.
7724
7725 For most purposes, @code{gnatchop} will be used in default mode. The
7726 compilation mode described above is used only if you need exactly
7727 accurate behavior with respect to compilations, and you have files
7728 that contain multiple units and configuration pragmas. In this
7729 circumstance the use of @code{gnatchop} with the compilation mode
7730 switch provides the required behavior, and is for example the mode
7731 in which GNAT processes the ACVC tests.
7732
7733 @node Command Line for gnatchop
7734 @section Command Line for @code{gnatchop}
7735
7736 @noindent
7737 The @code{gnatchop} command has the form:
7738
7739 @smallexample
7740 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
7741       [@var{directory}]
7742 @end smallexample
7743
7744 @noindent
7745 The only required argument is the file name of the file to be chopped.
7746 There are no restrictions on the form of this file name. The file itself
7747 contains one or more Ada units, in normal GNAT format, concatenated
7748 together. As shown, more than one file may be presented to be chopped.
7749
7750 When run in default mode, @code{gnatchop} generates one output file in
7751 the current directory for each unit in each of the files.
7752
7753 @var{directory}, if specified, gives the name of the directory to which
7754 the output files will be written. If it is not specified, all files are
7755 written to the current directory.
7756
7757 For example, given a
7758 file called @file{hellofiles} containing
7759
7760 @smallexample
7761 @group
7762 @cartouche
7763 @b{procedure} hello;
7764
7765 @b{with} Text_IO; @b{use} Text_IO;
7766 @b{procedure} hello @b{is}
7767 @b{begin}
7768    Put_Line ("Hello");
7769 @b{end} hello;
7770 @end cartouche
7771 @end group
7772 @end smallexample
7773
7774 @noindent
7775 the command
7776
7777 @smallexample
7778 $ gnatchop hellofiles
7779 @end smallexample
7780
7781 @noindent
7782 generates two files in the current directory, one called
7783 @file{hello.ads} containing the single line that is the procedure spec,
7784 and the other called @file{hello.adb} containing the remaining text. The
7785 original file is not affected. The generated files can be compiled in
7786 the normal manner.
7787
7788 @node Switches for gnatchop
7789 @section Switches for @code{gnatchop}
7790
7791 @noindent
7792 @code{gnatchop} recognizes the following switches:
7793
7794 @table @code
7795
7796 @item -c
7797 @cindex @code{-c} (@code{gnatchop})
7798 Causes @code{gnatchop} to operate in compilation mode, in which
7799 configuration pragmas are handled according to strict RM rules. See
7800 previous section for a full description of this mode.
7801
7802 @item -gnatxxx
7803 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
7804 used to parse the given file. Not all @code{xxx} options make sense,
7805 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
7806 process a source file that uses Latin-2 coding for identifiers.
7807
7808 @item -h
7809 Causes @code{gnatchop} to generate a brief help summary to the standard
7810 output file showing usage information.
7811
7812 @item -k@var{mm}
7813 @cindex @code{-k} (@code{gnatchop})
7814 Limit generated file names to the specified number @code{mm}
7815 of characters.
7816 This is useful if the
7817 resulting set of files is required to be interoperable with systems
7818 which limit the length of file names.
7819 No space is allowed between the @code{-k} and the numeric value. The numeric
7820 value may be omitted in which case a default of @code{-k8},
7821 suitable for use
7822 with DOS-like file systems, is used. If no @code{-k} switch
7823 is present then
7824 there is no limit on the length of file names.
7825
7826 @item -p
7827 @cindex @code{-p} (@code{gnatchop})
7828 Causes the file modification time stamp of the input file to be
7829 preserved and used for the time stamp of the output file(s). This may be
7830 useful for preserving coherency of time stamps in an enviroment where
7831 @code{gnatchop} is used as part of a standard build process.
7832
7833 @item -q
7834 @cindex @code{-q} (@code{gnatchop})
7835 Causes output of informational messages indicating the set of generated
7836 files to be suppressed. Warnings and error messages are unaffected.
7837
7838 @item -r
7839 @cindex @code{-r} (@code{gnatchop})
7840 @findex Source_Reference
7841 Generate @code{Source_Reference} pragmas. Use this switch if the output
7842 files are regarded as temporary and development is to be done in terms
7843 of the original unchopped file. This switch causes
7844 @code{Source_Reference} pragmas to be inserted into each of the
7845 generated files to refers back to the original file name and line number.
7846 The result is that all error messages refer back to the original
7847 unchopped file.
7848 In addition, the debugging information placed into the object file (when
7849 the @code{-g} switch of @code{gcc} or @code{gnatmake} is specified) also
7850 refers back to this original file so that tools like profilers and
7851 debuggers will give information in terms of the original unchopped file.
7852
7853 If the original file to be chopped itself contains
7854 a @code{Source_Reference}
7855 pragma referencing a third file, then gnatchop respects
7856 this pragma, and the generated @code{Source_Reference} pragmas
7857 in the chopped file refer to the original file, with appropriate
7858 line numbers. This is particularly useful when @code{gnatchop}
7859 is used in conjunction with @code{gnatprep} to compile files that
7860 contain preprocessing statements and multiple units.
7861
7862 @item -v
7863 @cindex @code{-v} (@code{gnatchop})
7864 Causes @code{gnatchop} to operate in verbose mode. The version
7865 number and copyright notice are output, as well as exact copies of
7866 the gnat1 commands spawned to obtain the chop control information.
7867
7868 @item -w
7869 @cindex @code{-w} (@code{gnatchop})
7870 Overwrite existing file names. Normally @code{gnatchop} regards it as a
7871 fatal error if there is already a file with the same name as a
7872 file it would otherwise output, in other words if the files to be
7873 chopped contain duplicated units. This switch bypasses this
7874 check, and causes all but the last instance of such duplicated
7875 units to be skipped.
7876
7877 @item --GCC=xxxx
7878 @cindex @code{--GCC=} (@code{gnatchop})
7879 Specify the path of the GNAT parser to be used. When this switch is used,
7880 no attempt is made to add the prefix to the GNAT parser executable.
7881 @end table
7882
7883 @node Examples of gnatchop Usage
7884 @section Examples of @code{gnatchop} Usage
7885
7886 @table @code
7887 @item gnatchop -w hello_s.ada ichbiah/files
7888
7889 Chops the source file @file{hello_s.ada}. The output files will be
7890 placed in the directory @file{ichbiah/files},
7891 overwriting any
7892 files with matching names in that directory (no files in the current
7893 directory are modified).
7894
7895 @item gnatchop archive
7896 Chops the source file @file{archive}
7897 into the current directory. One
7898 useful application of @code{gnatchop} is in sending sets of sources
7899 around, for example in email messages. The required sources are simply
7900 concatenated (for example, using a Unix @code{cat}
7901 command), and then
7902 @code{gnatchop} is used at the other end to reconstitute the original
7903 file names.
7904
7905 @item gnatchop file1 file2 file3 direc
7906 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
7907 the resulting files in the directory @file{direc}. Note that if any units
7908 occur more than once anywhere within this set of files, an error message
7909 is generated, and no files are written. To override this check, use the
7910 @code{-w} switch,
7911 in which case the last occurrence in the last file will
7912 be the one that is output, and earlier duplicate occurrences for a given
7913 unit will be skipped.
7914 @end table
7915
7916 @node Configuration Pragmas
7917 @chapter Configuration Pragmas
7918 @cindex Configuration pragmas
7919 @cindex Pragmas, configuration
7920
7921 @noindent
7922 In Ada 95, configuration pragmas include those pragmas described as
7923 such in the Ada 95 Reference Manual, as well as
7924 implementation-dependent pragmas that are configuration pragmas. See the
7925 individual descriptions of pragmas in the GNAT Reference Manual for
7926 details on these additional GNAT-specific configuration pragmas. Most
7927 notably, the pragma @code{Source_File_Name}, which allows
7928 specifying non-default names for source files, is a configuration
7929 pragma. The following is a complete list of configuration pragmas
7930 recognized by @code{GNAT}:
7931
7932 @smallexample
7933    Ada_83
7934    Ada_95
7935    C_Pass_By_Copy
7936    Component_Alignment
7937    Discard_Names
7938    Elaboration_Checks
7939    Eliminate
7940    Extend_System
7941    Extensions_Allowed
7942    External_Name_Casing
7943    Float_Representation
7944    Initialize_Scalars
7945    License
7946    Locking_Policy
7947    Long_Float
7948    No_Run_Time
7949    Normalize_Scalars
7950    Polling
7951    Propagate_Exceptions
7952    Queuing_Policy
7953    Ravenscar
7954    Restricted_Run_Time
7955    Restrictions
7956    Reviewable
7957    Source_File_Name
7958    Style_Checks
7959    Suppress
7960    Task_Dispatching_Policy
7961    Unsuppress
7962    Use_VADS_Size
7963    Warnings
7964    Validity_Checks
7965 @end smallexample
7966
7967 @menu
7968 * Handling of Configuration Pragmas::
7969 * The Configuration Pragmas Files::
7970 @end menu
7971
7972 @node Handling of Configuration Pragmas
7973 @section Handling of Configuration Pragmas
7974
7975 Configuration pragmas may either appear at the start of a compilation
7976 unit, in which case they apply only to that unit, or they may apply to
7977 all compilations performed in a given compilation environment.
7978
7979 GNAT also provides the @code{gnatchop} utility to provide an automatic
7980 way to handle configuration pragmas following the semantics for
7981 compilations (that is, files with multiple units), described in the RM.
7982 See section @pxref{Operating gnatchop in Compilation Mode} for details.
7983 However, for most purposes, it will be more convenient to edit the
7984 @file{gnat.adc} file that contains configuration pragmas directly,
7985 as described in the following section.
7986
7987 @node The Configuration Pragmas Files
7988 @section The Configuration Pragmas Files
7989 @cindex @file{gnat.adc}
7990
7991 @noindent
7992 In GNAT a compilation environment is defined by the current
7993 directory at the time that a compile command is given. This current
7994 directory is searched for a file whose name is @file{gnat.adc}. If
7995 this file is present, it is expected to contain one or more
7996 configuration pragmas that will be applied to the current compilation.
7997 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
7998 considered.
7999
8000 Configuration pragmas may be entered into the @file{gnat.adc} file
8001 either by running @code{gnatchop} on a source file that consists only of
8002 configuration pragmas, or more conveniently  by
8003 direct editing of the @file{gnat.adc} file, which is a standard format
8004 source file.
8005
8006 In addition to @file{gnat.adc}, one additional file containing configuration
8007 pragmas may be applied to the current compilation using the switch
8008 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
8009 contains only configuration pragmas. These configuration pragmas are
8010 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
8011 is present and switch @option{-gnatA} is not used).
8012
8013 It is allowed to specify several switches @option{-gnatec}, however only
8014 the last one on the command line will be taken into account.
8015
8016
8017 @node Handling Arbitrary File Naming Conventions Using gnatname
8018 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
8019 @cindex Arbitrary File Naming Conventions
8020
8021 @menu
8022 * Arbitrary File Naming Conventions::
8023 * Running gnatname::
8024 * Switches for gnatname::
8025 * Examples of gnatname Usage::
8026 @end menu
8027
8028 @node Arbitrary File Naming Conventions
8029 @section Arbitrary File Naming Conventions
8030
8031 @noindent
8032 The GNAT compiler must be able to know the source file name of a compilation unit.
8033 When using the standard GNAT default file naming conventions (@code{.ads} for specs,
8034 @code{.adb} for bodies), the GNAT compiler does not need additional information.
8035
8036 @noindent
8037 When the source file names do not follow the standard GNAT default file naming
8038 conventions, the GNAT compiler must be given additional information through
8039 a configuration pragmas file (see @ref{Configuration Pragmas}) or a project file.
8040 When the non standard file naming conventions are well-defined, a small number of
8041 pragmas @code{Source_File_Name} specifying a naming pattern
8042 (see @ref{Alternative File Naming Schemes}) may be sufficient. However,
8043 if the file naming conventions are irregular or arbitrary, a number
8044 of pragma @code{Source_File_Name} for individual compilation units must be defined.
8045 To help maintain the correspondence between compilation unit names and
8046 source file names within the compiler,
8047 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
8048 set of files.
8049
8050 @node Running gnatname
8051 @section Running @code{gnatname}
8052
8053 @noindent
8054 The usual form of the @code{gnatname} command is
8055
8056 @smallexample
8057 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
8058 @end smallexample
8059
8060 @noindent
8061 All of the arguments are optional. If invoked without any argument,
8062 @code{gnatname} will display its usage.
8063
8064 @noindent
8065 When used with at least one naming pattern, @code{gnatname} will attempt to
8066 find all the compilation units in files that follow at least one of the
8067 naming patterns. To find these compilation units,
8068 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
8069 regular files.
8070
8071 @noindent
8072 One or several Naming Patterns may be given as arguments to @code{gnatname}.
8073 Each Naming Pattern is enclosed between double quotes.
8074 A Naming Pattern is a regular expression similar to the wildcard patterns
8075 used in file names by the Unix shells or the DOS prompt.
8076
8077 @noindent
8078 Examples of Naming Patterns are
8079
8080 @smallexample
8081    "*.[12].ada"
8082    "*.ad[sb]*"
8083    "body_*"    "spec_*"
8084 @end smallexample
8085
8086 @noindent
8087 For a more complete description of the syntax of Naming Patterns, see the second kind
8088 of regular expressions described in @file{g-regexp.ads} (the "Glob" regular
8089 expressions).
8090
8091 @noindent
8092 When invoked with no switches, @code{gnatname} will create a configuration
8093 pragmas file @file{gnat.adc} in the current working directory, with pragmas
8094 @code{Source_File_Name} for each file that contains a valid Ada unit.
8095
8096 @node Switches for gnatname
8097 @section Switches for @code{gnatname}
8098
8099 @noindent
8100 Switches for @code{gnatname} must precede any specified Naming Pattern.
8101
8102 @noindent
8103 You may specify any of the following switches to @code{gnatname}:
8104
8105 @table @code
8106
8107 @item -c@file{file}
8108 @cindex @code{-c} (@code{gnatname})
8109 Create a configuration pragmas file @file{file} (instead of the default
8110 @file{gnat.adc}). There may be zero, one or more space between @code{-c} and
8111 @file{file}. @file{file} may include directory information. @file{file} must be
8112 writeable. There may be only one switch @code{-c}. When a switch @code{-c} is
8113 specified, no switch @code{-P} may be specified (see below).
8114
8115 @item -d@file{dir}
8116 @cindex @code{-d} (@code{gnatname})
8117 Look for source files in directory @file{dir}. There may be zero, one or more spaces
8118 between @code{-d} and @file{dir}. When a switch @code{-d} is specified,
8119 the current working directory will not be searched for source files, unless it
8120 is explictly
8121 specified with a @code{-d} or @code{-D} switch. Several switches @code{-d} may be
8122 specified. If @file{dir} is a relative path, it is relative to the directory of
8123 the configuration pragmas file specified with switch @code{-c}, or to the directory
8124 of the project file specified with switch @code{-P} or, if neither switch @code{-c}
8125 nor switch @code{-P} are specified, it is relative to the current working
8126 directory. The directory
8127 specified with switch @code{-c} must exist and be readable.
8128
8129 @item -D@file{file}
8130 @cindex @code{-D} (@code{gnatname})
8131 Look for source files in all directories listed in text file @file{file}. There may be
8132 zero, one or more spaces between @code{-d} and @file{dir}. @file{file}
8133 must be an existing, readable text file. Each non empty line in @file{file} must be
8134 a directory. Specifying switch @code{-D} is equivalent to specifying as many switches
8135 @code{-d} as there are non empty lines in @file{file}.
8136
8137 @item -h
8138 @cindex @code{-h} (@code{gnatname})
8139 Output usage (help) information. The output is written to @file{stdout}.
8140
8141 @item -P@file{proj}
8142 @cindex @code{-P} (@code{gnatname})
8143 Create or update project file @file{proj}. There may be zero, one or more space
8144 between @code{-P} and @file{proj}. @file{proj} may include directory information.
8145 @file{proj} must be writeable. There may be only one switch @code{-P}.
8146 When a switch @code{-P} is specified, no switch @code{-c} may be specified.
8147
8148 @item -v
8149 @cindex @code{-v} (@code{gnatname})
8150 Verbose mode. Output detailed explanation of behavior to @file{stdout}. This includes
8151 name of the file written, the name of the directories to search and, for each file
8152 in those directories whose name matches at least one of the Naming Patterns, an
8153 indication of whether the file contains a unit, and if so the name of the unit.
8154
8155 @item -v -v
8156 Very Verbose mode. In addition to the output produced in verbose mode, for each file
8157 in the searched directories whose name matches none of the Naming Patterns, an
8158 indication is given that there is no match.
8159
8160 @item -x@file{pattern}
8161 Excluded patterns. Using this switch, it is possible to exclude some files
8162 that would match the name patterns. For example,
8163 @code{"gnatname -x "*_nt.ada" "*.ada"} will look for Ada units in all files
8164 with the @file{.ada} extension, except those whose names end with
8165 @file{_nt.ada}.
8166
8167 @end table
8168
8169 @node Examples of gnatname Usage
8170 @section Examples of @code{gnatname} Usage
8171
8172 @smallexample
8173 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
8174 @end smallexample
8175
8176 In this example, the directory @file{/home/me} must already exist and be
8177 writeable. In addition, the directory @file{/home/me/sources} (specified by
8178 @code{-d sources}) must exist and be readable. Note the optional spaces after
8179 @code{-c} and @code{-d}.
8180
8181 @smallexample
8182 $ gnatname -P/home/me/proj -x "*_nt_body.ada" -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
8183 @end smallexample
8184
8185 Note that several switches @code{-d} may be used, even in conjunction with one
8186 or several switches @code{-D}. Several Naming Patterns and one excluded pattern
8187 are used in this example.
8188
8189
8190 @c *****************************************
8191 @c * G N A T  P r o j e c t  M a n a g e r *
8192 @c *****************************************
8193 @node GNAT Project Manager
8194 @chapter GNAT Project Manager
8195
8196 @menu
8197 * Introduction::
8198 * Examples of Project Files::
8199 * Project File Syntax::
8200 * Objects and Sources in Project Files::
8201 * Importing Projects::
8202 * Project Extension::
8203 * External References in Project Files::
8204 * Packages in Project Files::
8205 * Variables from Imported Projects::
8206 * Naming Schemes::
8207 * Library Projects::
8208 * Switches Related to Project Files::
8209 * Tools Supporting Project Files::
8210 * An Extended Example::
8211 * Project File Complete Syntax::
8212 @end menu
8213
8214
8215 @c ****************
8216 @c * Introduction *
8217 @c ****************
8218
8219 @node Introduction
8220 @section Introduction
8221
8222 @noindent
8223 This chapter describes GNAT's @emph{Project Manager}, a facility that
8224 lets you configure various properties for a collection of source files.  In
8225 particular, you can specify:
8226 @itemize @bullet
8227 @item
8228 The directory or set of directories containing the source files, and/or the
8229 names of the specific source files themselves
8230 @item
8231 The directory in which the compiler's output
8232 (@file{ALI} files, object files, tree files) will be placed
8233 @item
8234 The directory in which the executable programs will be placed
8235 @item
8236 Switch settings for any of the project-enabled tools (@command{gnatmake},
8237 compiler, binder, linker, @code{gnatls}, @code{gnatxref}, @code{gnatfind});
8238 you can apply these settings either globally or to individual units
8239 @item
8240 The source files containing the main subprogram(s) to be built
8241 @item
8242 The source programming language(s) (currently Ada and/or C)
8243 @item
8244 Source file naming conventions; you can specify these either globally or for
8245 individual units
8246 @end itemize
8247
8248 @menu
8249 * Project Files::
8250 @end menu
8251
8252 @node Project Files
8253 @subsection Project Files
8254
8255 @noindent
8256 A @dfn{project} is a specific set of values for these properties.  You can
8257 define a project's settings in a @dfn{project file}, a text file with an
8258 Ada-like syntax; a property value is either a string or a list of strings.
8259 Properties that are not explicitly set receive default values.  A project
8260 file may interrogate the values of @dfn{external variables} (user-defined
8261 command-line switches or environment variables), and it may specify property
8262 settings conditionally, based on the value of such variables.
8263
8264 In simple cases, a project's source files depend only on other source files
8265 in the same project, or on the predefined libraries.  ("Dependence" is in
8266 the technical sense; for example, one Ada unit "with"ing another.)  However,
8267 the Project Manager also allows much more sophisticated arrangements,
8268 with the source files in one project depending on source files in other
8269 projects:
8270 @itemize @bullet
8271 @item
8272 One project can @emph{import} other projects containing needed source files.
8273 @item
8274 You can organize GNAT projects in a hierarchy: a @emph{child} project
8275 can extend a @emph{parent} project, inheriting the parent's source files and
8276 optionally overriding any of them with alternative versions
8277 @end itemize
8278
8279 @noindent
8280 More generally, the Project Manager lets you structure large development
8281 efforts into hierarchical subsystems, with build decisions deferred to the
8282 subsystem level and thus different compilation environments (switch settings)
8283 used for different subsystems.
8284
8285 The Project Manager is invoked through the @option{-P@emph{projectfile}}
8286 switch to @command{gnatmake} or to the @command{gnat} front driver.
8287 If you want to define (on the command line) an external variable that is
8288 queried by the project file, additionally use the
8289 @option{-X@emph{vbl}=@emph{value}} switch.
8290 The Project Manager parses and interprets the project file, and drives the
8291 invoked tool based on the project settings.
8292
8293 The Project Manager supports a wide range of development strategies,
8294 for systems of all sizes.  Some typical practices that are easily handled:
8295 @itemize @bullet
8296 @item
8297 Using a common set of source files, but generating object files in different
8298 directories via different switch settings
8299 @item
8300 Using a mostly-shared set of source files, but with different versions of
8301 some unit or units
8302 @end itemize
8303
8304 @noindent
8305 The destination of an executable can be controlled inside a project file
8306 using the @option{-o} switch. In the absence of such a switch either inside
8307 the project file or on the command line, any executable files generated by
8308 @command{gnatmake} will be placed in the directory @code{Exec_Dir} specified
8309 in the project file. If no @code{Exec_Dir} is specified, they will be placed
8310 in the object directory of the project.
8311
8312 You can use project files to achieve some of the effects of a source
8313 versioning system (for example, defining separate projects for
8314 the different sets of sources that comprise different releases) but the
8315 Project Manager is independent of any source configuration management tools
8316 that might be used by the developers.
8317
8318 The next section introduces the main features of GNAT's project facility
8319 through a sequence of examples; subsequent sections will present the syntax
8320 and semantics in more detail.
8321
8322
8323 @c *****************************
8324 @c * Examples of Project Files *
8325 @c *****************************
8326
8327 @node Examples of Project Files
8328 @section Examples of Project Files
8329 @noindent
8330 This section illustrates some of the typical uses of project files and
8331 explains their basic structure and behavior.
8332
8333 @menu
8334 * Common Sources with Different Switches and Different Output Directories::
8335 * Using External Variables::
8336 * Importing Other Projects::
8337 * Extending a Project::
8338 @end menu
8339
8340 @node Common Sources with Different Switches and Different Output Directories
8341 @subsection Common Sources with Different Switches and Different Output Directories
8342
8343 @menu
8344 * Source Files::
8345 * Specifying the Object Directory::
8346 * Specifying the Exec Directory::
8347 * Project File Packages::
8348 * Specifying Switch Settings::
8349 * Main Subprograms::
8350 * Source File Naming Conventions::
8351 * Source Language(s)::
8352 @end menu
8353
8354 @noindent
8355 Assume that the Ada source files @file{pack.ads}, @file{pack.adb}, and
8356 @file{proc.adb} are in the @file{/common} directory.  The file
8357 @file{proc.adb} contains an Ada main subprogram @code{Proc} that "with"s
8358 package @code{Pack}.  We want to compile these source files under two sets
8359 of switches:
8360 @itemize @bullet
8361 @item
8362 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
8363 and the @option{-gnata}, @option{-gnato}, and @option{-gnatE} switches to the
8364 compiler; the compiler's output is to appear in @file{/common/debug}
8365 @item
8366 When preparing a release version, we want to pass the @option{-O2} switch to
8367 the compiler; the compiler's output is to appear in @file{/common/release}
8368 @end itemize
8369
8370 @noindent
8371 The GNAT project files shown below, respectively @file{debug.gpr} and
8372 @file{release.gpr} in the @file{/common} directory, achieve these effects.
8373
8374 Diagrammatically:
8375 @smallexample
8376 @group
8377 /common
8378   debug.gpr
8379   release.gpr
8380   pack.ads
8381   pack.adb
8382   proc.adb
8383 @end group
8384 @group
8385 /common/debug @{-g, -gnata, -gnato, -gnatE@}
8386   proc.ali, proc.o
8387   pack.ali, pack.o
8388 @end group
8389 @group
8390 /common/release @{-O2@}
8391   proc.ali, proc.o
8392   pack.ali, pack.o
8393 @end group
8394 @end smallexample
8395 Here are the project files:
8396 @smallexample
8397 @group
8398 project Debug is
8399   for Object_Dir use "debug";
8400   for Main use ("proc");
8401
8402   package Builder is
8403     for Default_Switches ("Ada") use ("-g");
8404   end Builder;
8405 @end group
8406
8407 @group
8408   package Compiler is
8409     for Default_Switches ("Ada")
8410        use ("-fstack-check", "-gnata", "-gnato", "-gnatE");
8411   end Compiler;
8412 end Debug;
8413 @end group
8414 @end smallexample
8415
8416 @smallexample
8417 @group
8418 project Release is
8419   for Object_Dir use "release";
8420   for Exec_Dir use ".";
8421   for Main use ("proc");
8422
8423   package Compiler is
8424     for Default_Switches ("Ada") use ("-O2");
8425   end Compiler;
8426 end Release;
8427 @end group
8428 @end smallexample
8429
8430 @noindent
8431 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
8432 insensitive), and analogously the project defined by @file{release.gpr} is
8433 @code{"Release"}.  For consistency the file should have the same name as the
8434 project, and the project file's extension should be @code{"gpr"}. These
8435 conventions are not required, but a warning is issued if they are not followed.
8436
8437 If the current directory is @file{/temp}, then the command
8438 @smallexample
8439 gnatmake -P/common/debug.gpr
8440 @end smallexample
8441
8442 @noindent
8443 generates object and ALI files in @file{/common/debug}, and the @code{proc}
8444 executable also in @file{/common/debug}, using the switch settings defined in
8445 the project file.
8446
8447 Likewise, the command
8448 @smallexample
8449 gnatmake -P/common/release.gpr
8450 @end smallexample
8451
8452 @noindent
8453 generates object and ALI files in @file{/common/release}, and the @code{proc}
8454 executable in @file{/common}, using the switch settings from the project file.
8455
8456 @node Source Files
8457 @unnumberedsubsubsec Source Files
8458
8459 @noindent
8460 If a project file does not explicitly specify a set of source directories or
8461 a set of source files, then by default the project's source files are the
8462 Ada source files in the project file directory.  Thus @file{pack.ads},
8463 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
8464
8465 @node Specifying the Object Directory
8466 @unnumberedsubsubsec Specifying the Object Directory
8467
8468 @noindent
8469 Several project properties are modeled by Ada-style @emph{attributes};
8470 you define the property by supplying the equivalent of an Ada attribute
8471 definition clause in the project file.
8472 A project's object directory is such a property; the corresponding
8473 attribute is @code{Object_Dir}, and its value is a string expression.  A
8474 directory may be specified either as absolute or as relative; in the latter
8475 case, it is relative to the project file directory.  Thus the compiler's
8476 output is directed to @file{/common/debug} (for the @code{Debug} project)
8477 and to @file{/common/release} (for the @code{Release} project).  If
8478 @code{Object_Dir} is not specified, then the default is the project file
8479 directory.
8480
8481 @node Specifying the Exec Directory
8482 @unnumberedsubsubsec Specifying the Exec Directory
8483
8484 @noindent
8485 A project's exec directory is another property; the corresponding
8486 attribute is @code{Exec_Dir}, and its value is also a string expression,
8487 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
8488 then the default is the object directory (which may also be the project file
8489 directory if attribute @code{Object_Dir} is not specified). Thus the executable
8490 is placed in @file{/common/debug} for the @code{Debug} project (attribute
8491 @code{Exec_Dir} not specified) and in @file{/common} for the @code{Release}
8492 project.
8493
8494 @node Project File Packages
8495 @unnumberedsubsubsec Project File Packages
8496
8497 @noindent
8498 A GNAT tool integrated with the Project Manager is modeled by a
8499 corresponding package in the project file.
8500 The @code{Debug} project defines the packages @code{Builder}
8501 (for @command{gnatmake}) and @code{Compiler};
8502 the @code{Release} project defines only the @code{Compiler} package.
8503
8504 The Ada package syntax is not to be taken literally.  Although packages in
8505 project files bear a surface resemblance to packages in Ada source code, the
8506 notation is simply a way to convey a grouping of properties for a named
8507 entity.  Indeed, the package names permitted in project files are restricted
8508 to a predefined set, corresponding to the project-aware tools, and the contents
8509 of packages are limited to a small set of constructs.
8510 The packages in the example above contain attribute definitions.
8511
8512
8513 @node Specifying Switch Settings
8514 @unnumberedsubsubsec Specifying Switch Settings
8515
8516 @noindent
8517 Switch settings for a project-aware tool can be specified through attributes
8518 in the package corresponding to the tool.
8519 The example above illustrates one of the relevant attributes,
8520 @code{Default_Switches}, defined in the packages in both project files.
8521 Unlike simple attributes like @code{Source_Dirs}, @code{Default_Switches} is
8522 known as an @emph{associative array}.  When you define this attribute, you must
8523 supply an "index" (a literal string), and the effect of the attribute
8524 definition is to set the value of the "array" at the specified "index".
8525 For the @code{Default_Switches} attribute, the index is a programming
8526 language (in our case, Ada) , and the value specified (after @code{use})
8527 must be a list of string expressions.
8528
8529 The attributes permitted in project files are restricted to a predefined set.
8530 Some may appear at project level, others in packages.
8531 For any attribute that is an associate array, the index must always be a
8532 literal string, but the restrictions on this string (e.g., a file name or a
8533 language name) depend on the individual attribute.
8534 Also depending on the attribute, its specified value will need to be either a
8535 string or a string list.
8536
8537 In the @code{Debug} project, we set the switches for two tools,
8538 @command{gnatmake} and the compiler, and thus we include corresponding
8539 packages, with each package defining the @code{Default_Switches} attribute
8540 with index @code{"Ada"}.
8541 Note that the package corresponding to
8542 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
8543 similar, but with just the @code{Compiler} package.
8544
8545 In project @code{Debug} above the switches starting with @option{-gnat} that
8546 are specified in package @code{Compiler} could have been placed in package
8547 @code{Builder}, since @command{gnatmake} transmits all such switches to the
8548 compiler.
8549
8550 @node Main Subprograms
8551 @unnumberedsubsubsec Main Subprograms
8552
8553 @noindent
8554 One of the properties of a project is its list of main subprograms (actually
8555 a list of names of source files containing main subprograms, with the file
8556 extension optional.  This property is captured in the @code{Main} attribute,
8557 whose value is a list of strings.  If a project defines the @code{Main}
8558 attribute, then you do not need to identify the main subprogram(s) when
8559 invoking @command{gnatmake} (see @ref{gnatmake and Project Files}).
8560
8561 @node Source File Naming Conventions
8562 @unnumberedsubsubsec Source File Naming Conventions
8563
8564 @noindent
8565 Since the project files do not specify any source file naming conventions,
8566 the GNAT defaults are used.  The mechanism for defining source file naming
8567 conventions -- a package named @code{Naming} -- will be described below
8568 (@pxref{Naming Schemes}).
8569
8570 @node Source Language(s)
8571 @unnumberedsubsubsec Source Language(s)
8572
8573 @noindent
8574 Since the project files do not specify a @code{Languages} attribute, by
8575 default the GNAT tools assume that the language of the project file is Ada.
8576 More generally, a project can comprise source files
8577 in Ada, C, and/or other languages.
8578
8579 @node Using External Variables
8580 @subsection Using External Variables
8581
8582 @noindent
8583 Instead of supplying different project files for debug and release, we can
8584 define a single project file that queries an external variable (set either
8585 on the command line or via an environment variable) in order to
8586 conditionally define the appropriate settings.  Again, assume that the
8587 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
8588 located in directory @file{/common}.  The following project file,
8589 @file{build.gpr}, queries the external variable named @code{STYLE} and
8590 defines an object directory and switch settings based on whether the value
8591 is @code{"deb"} (debug) or @code{"rel"} (release), where the default is
8592 @code{"deb"}.
8593
8594 @smallexample
8595 @group
8596 project Build is
8597   for Main use ("proc");
8598
8599   type Style_Type is ("deb", "rel");
8600   Style : Style_Type := external ("STYLE", "deb");
8601
8602   case Style is
8603     when "deb" =>
8604       for Object_Dir use "debug";
8605
8606     when "rel" =>
8607       for Object_Dir use "release";
8608       for Exec_Dir use ".";
8609   end case;
8610 @end group
8611
8612 @group
8613   package Builder is
8614
8615     case Style is
8616       when "deb" =>
8617         for Default_Switches ("Ada") use ("-g");
8618     end case;
8619
8620   end Builder;
8621 @end group
8622
8623 @group
8624   package Compiler is
8625
8626     case Style is
8627       when "deb" =>
8628         for Default_Switches ("Ada") use ("-gnata", "-gnato", "-gnatE");
8629
8630       when "rel" =>
8631         for Default_Switches ("Ada") use ("-O2");
8632     end case;
8633
8634   end Compiler;
8635
8636 end Build;
8637 @end group
8638 @end smallexample
8639
8640 @noindent
8641 @code{Style_Type} is an example of a @emph{string type}, which is the project
8642 file analog of an Ada enumeration type but containing string literals rather
8643 than identifiers.  @code{Style} is declared as a variable of this type.
8644
8645 The form @code{external("STYLE", "deb")} is known as an
8646 @emph{external reference}; its first argument is the name of an
8647 @emph{external variable}, and the second argument is a default value to be
8648 used if the external variable doesn't exist.  You can define an external
8649 variable on the command line via the @option{-X} switch, or you can use an
8650 environment variable as an external variable.
8651
8652 Each @code{case} construct is expanded by the Project Manager based on the
8653 value of @code{Style}. Thus the command
8654 @smallexample
8655 gnatmake -P/common/build.gpr -XSTYLE=deb
8656 @end smallexample
8657
8658 @noindent
8659 is equivalent to the @command{gnatmake} invocation using the project file
8660 @file{debug.gpr} in the earlier example.  So is the command
8661 @smallexample
8662 gnatmake -P/common/build.gpr
8663 @end smallexample
8664
8665 @noindent
8666 since @code{"deb"} is the default for @code{STYLE}.
8667
8668 Analogously,
8669 @smallexample
8670 gnatmake -P/common/build.gpr -XSTYLE=rel
8671 @end smallexample
8672
8673 @noindent
8674 is equivalent to the @command{gnatmake} invocation using the project file
8675 @file{release.gpr} in the earlier example.
8676
8677
8678 @node Importing Other Projects
8679 @subsection Importing Other Projects
8680
8681 @noindent
8682 A compilation unit in a source file in one project may depend on compilation
8683 units in source files in other projects.  To obtain this behavior, the
8684 dependent project must @emph{import} the projects containing the needed source
8685 files.  This effect is embodied in syntax similar to an Ada @code{with} clause,
8686 but the "with"ed entities are strings denoting project files.
8687
8688 As an example, suppose that the two projects @code{GUI_Proj} and
8689 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
8690 @file{comm_proj.gpr} in directories @file{/gui} and @file{/comm},
8691 respectively.  Assume that the source files for @code{GUI_Proj} are
8692 @file{gui.ads} and @file{gui.adb}, and that the source files for
8693 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, with each set of
8694 files located in its respective project file directory.  Diagrammatically:
8695
8696 @smallexample
8697 @group
8698 /gui
8699   gui_proj.gpr
8700   gui.ads
8701   gui.adb
8702 @end group
8703
8704 @group
8705 /comm
8706   comm_proj.gpr
8707   comm.ads
8708   comm.adb
8709 @end group
8710 @end smallexample
8711
8712 @noindent
8713 We want to develop an application in directory @file{/app} that "with"s the
8714 packages @code{GUI} and @code{Comm}, using the properties of the
8715 corresponding project files (e.g. the switch settings and object directory).
8716 Skeletal code for a main procedure might be something like the following:
8717
8718 @smallexample
8719 @group
8720 with GUI, Comm;
8721 procedure App_Main is
8722    ...
8723 begin
8724    ...
8725 end App_Main;
8726 @end group
8727 @end smallexample
8728
8729 @noindent
8730 Here is a project file, @file{app_proj.gpr}, that achieves the desired
8731 effect:
8732
8733 @smallexample
8734 @group
8735 with "/gui/gui_proj", "/comm/comm_proj";
8736 project App_Proj is
8737    for Main use ("app_main");
8738 end App_Proj;
8739 @end group
8740 @end smallexample
8741
8742 @noindent
8743 Building an executable is achieved through the command:
8744 @smallexample
8745 gnatmake -P/app/app_proj
8746 @end smallexample
8747 @noindent
8748 which will generate the @code{app_main} executable in the directory where
8749 @file{app_proj.gpr} resides.
8750
8751 If an imported project file uses the standard extension (@code{gpr}) then
8752 (as illustrated above) the @code{with} clause can omit the extension.
8753
8754 Our example specified an absolute path for each imported project file.
8755 Alternatively, you can omit the directory if either
8756 @itemize @bullet
8757 @item
8758 The imported project file is in the same directory as the importing project
8759 file, or
8760 @item
8761 You have defined an environment variable @code{ADA_PROJECT_PATH} that
8762 includes the directory containing the needed project file.
8763 @end itemize
8764
8765 @noindent
8766 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{/gui} and
8767 @file{/comm}, then our project file @file{app_proj.gpr} could be written as
8768 follows:
8769
8770 @smallexample
8771 @group
8772 with "gui_proj", "comm_proj";
8773 project App_Proj is
8774    for Main use ("app_main");
8775 end App_Proj;
8776 @end group
8777 @end smallexample
8778
8779 @noindent
8780 Importing other projects raises the possibility of ambiguities.  For
8781 example, the same unit might be present in different imported projects, or
8782 it might be present in both the importing project and an imported project.
8783 Both of these conditions are errors.  Note that in the current version of
8784 the Project Manager, it is illegal to have an ambiguous unit even if the
8785 unit is never referenced by the importing project.  This restriction may be
8786 relaxed in a future release.
8787
8788 @node Extending a Project
8789 @subsection Extending a Project
8790
8791 @noindent
8792 A common situation in large software systems is to have multiple
8793 implementations for a common interface; in Ada terms, multiple versions of a
8794 package body for the same specification.  For example, one implementation
8795 might be safe for use in tasking programs, while another might only be used
8796 in sequential applications.  This can be modeled in GNAT using the concept
8797 of @emph{project extension}.  If one project (the "child") @emph{extends}
8798 another project (the "parent") then by default all source files of the
8799 parent project are inherited by the child, but the child project can
8800 override any of the parent's source files with new versions, and can also
8801 add new files.  This facility is the project analog of extension in
8802 Object-Oriented Programming.  Project hierarchies are permitted (a child
8803 project may be the parent of yet another project), and a project that
8804 inherits one project can also import other projects.
8805
8806 As an example, suppose that directory @file{/seq} contains the project file
8807 @file{seq_proj.gpr} and the source files @file{pack.ads}, @file{pack.adb},
8808 and @file{proc.adb}:
8809
8810 @smallexample
8811 @group
8812 /seq
8813   pack.ads
8814   pack.adb
8815   proc.adb
8816   seq_proj.gpr
8817 @end group
8818 @end smallexample
8819
8820 @noindent
8821 Note that the project file can simply be empty (that is, no attribute or
8822 package is defined):
8823
8824 @smallexample
8825 @group
8826 project Seq_Proj is
8827 end Seq_Proj;
8828 @end group
8829 @end smallexample
8830
8831 @noindent
8832 implying that its source files are all the Ada source files in the project
8833 directory.
8834
8835 Suppose we want to supply an alternate version of @file{pack.adb}, in
8836 directory @file{/tasking}, but use the existing versions of @file{pack.ads}
8837 and @file{proc.adb}.  We can define a project @code{Tasking_Proj} that
8838 inherits @code{Seq_Proj}:
8839
8840 @smallexample
8841 @group
8842 /tasking
8843   pack.adb
8844   tasking_proj.gpr
8845 @end group
8846
8847 @group
8848 project Tasking_Proj extends "/seq/seq_proj" is
8849 end Tasking_Proj;
8850 @end group
8851 @end smallexample
8852
8853 @noindent
8854 The version of @file{pack.adb} used in a build depends on which project file
8855 is specified.
8856
8857 Note that we could have designed this using project import rather than
8858 project inheritance; a @code{base} project would contain the sources for
8859 @file{pack.ads} and @file{proc.adb}, a sequential project would import
8860 @code{base} and add @file{pack.adb}, and likewise a tasking project would
8861 import @code{base} and add a different version of @file{pack.adb}.  The
8862 choice depends on whether other sources in the original project need to be
8863 overridden.  If they do, then project extension is necessary, otherwise,
8864 importing is sufficient.
8865
8866
8867 @c ***********************
8868 @c * Project File Syntax *
8869 @c ***********************
8870
8871 @node Project File Syntax
8872 @section Project File Syntax
8873
8874 @menu
8875 * Basic Syntax::
8876 * Packages::
8877 * Expressions::
8878 * String Types::
8879 * Variables::
8880 * Attributes::
8881 * Associative Array Attributes::
8882 * case Constructions::
8883 @end menu
8884
8885 @noindent
8886 This section describes the structure of project files.
8887
8888 A project may be an @emph{independent project}, entirely defined by a single
8889 project file. Any Ada source file in an independent project depends only
8890 on the predefined library and other Ada source files in the same project.
8891
8892 @noindent
8893 A project may also @dfn{depend on} other projects, in either or both of the following ways:
8894 @itemize @bullet
8895 @item It may import any number of projects
8896 @item It may extend at most one other project
8897 @end itemize
8898
8899 @noindent
8900 The dependence relation is a directed acyclic graph (the subgraph reflecting
8901 the "extends" relation is a tree).
8902
8903 A project's @dfn{immediate sources} are the source files directly defined by
8904 that project, either implicitly by residing in the project file's directory,
8905 or explicitly through any of the source-related attributes described below.
8906 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
8907 of @var{proj} together with the immediate sources (unless overridden) of any
8908 project on which @var{proj} depends (either directly or indirectly).
8909
8910 @node Basic Syntax
8911 @subsection Basic Syntax
8912
8913 @noindent
8914 As seen in the earlier examples, project files have an Ada-like syntax.
8915 The minimal project file is:
8916 @smallexample
8917 @group
8918 project Empty is
8919
8920 end Empty;
8921 @end group
8922 @end smallexample
8923
8924 @noindent
8925 The identifier @code{Empty} is the name of the project.
8926 This project name must be present after the reserved
8927 word @code{end} at the end of the project file, followed by a semi-colon.
8928
8929 Any name in a project file, such as the project name or a variable name,
8930 has the same syntax as an Ada identifier.
8931
8932 The reserved words of project files are the Ada reserved words plus
8933 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
8934 reserved words currently used in project file syntax are:
8935
8936 @itemize @bullet
8937 @item
8938 @code{case}
8939 @item
8940 @code{end}
8941 @item
8942 @code{for}
8943 @item
8944 @code{is}
8945 @item
8946 @code{others}
8947 @item
8948 @code{package}
8949 @item
8950 @code{renames}
8951 @item
8952 @code{type}
8953 @item
8954 @code{use}
8955 @item
8956 @code{when}
8957 @item
8958 @code{with}
8959 @end itemize
8960
8961 @noindent
8962 Comments in project files have the same syntax as in Ada, two consecutives
8963 hyphens through the end of the line.
8964
8965 @node Packages
8966 @subsection Packages
8967
8968 @noindent
8969 A project file may contain @emph{packages}. The name of a package must be one
8970 of the identifiers (case insensitive) from a predefined list, and a package
8971 with a given name may only appear once in a project file. The predefined list
8972 includes the following packages:
8973
8974 @itemize @bullet
8975 @item
8976 @code{Naming}
8977 @item
8978 @code{Builder}
8979 @item
8980 @code{Compiler}
8981 @item
8982 @code{Binder}
8983 @item
8984 @code{Linker}
8985 @item
8986 @code{Finder}
8987 @item
8988 @code{Cross_Reference}
8989 @item
8990 @code{gnatls}
8991 @end itemize
8992
8993 @noindent
8994 (The complete list of the package names and their attributes can be found
8995 in file @file{prj-attr.adb}).
8996
8997 @noindent
8998 In its simplest form, a package may be empty:
8999
9000 @smallexample
9001 @group
9002 project Simple is
9003   package Builder is
9004   end Builder;
9005 end Simple;
9006 @end group
9007 @end smallexample
9008
9009 @noindent
9010 A package may contain @emph{attribute declarations},
9011 @emph{variable declarations} and @emph{case constructions}, as will be
9012 described below.
9013
9014 When there is ambiguity between a project name and a package name,
9015 the name always designates the project. To avoid possible confusion, it is
9016 always a good idea to avoid naming a project with one of the
9017 names allowed for packages or any name that starts with @code{gnat}.
9018
9019
9020 @node Expressions
9021 @subsection Expressions
9022
9023 @noindent
9024 An @emph{expression} is either a @emph{string expression} or a
9025 @emph{string list expression}.
9026
9027 A @emph{string expression} is either a @emph{simple string expression} or a
9028 @emph{compound string expression}.
9029
9030 A @emph{simple string expression} is one of the following:
9031 @itemize @bullet
9032 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
9033 @item A string-valued variable reference (see @ref{Variables})
9034 @item A string-valued attribute reference (see @ref{Attributes})
9035 @item An external reference (see @ref{External References in Project Files})
9036 @end itemize
9037
9038 @noindent
9039 A @emph{compound string expression} is a concatenation of string expressions,
9040 using @code{"&"}
9041 @smallexample
9042        Path & "/" & File_Name & ".ads"
9043 @end smallexample
9044
9045 @noindent
9046 A @emph{string list expression} is either a
9047 @emph{simple string list expression} or a
9048 @emph{compound string list expression}.
9049
9050 A @emph{simple string list expression} is one of the following:
9051 @itemize @bullet
9052 @item A parenthesized list of zero or more string expressions, separated by commas
9053 @smallexample
9054    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
9055    Empty_List := ();
9056 @end smallexample
9057 @item A string list-valued variable reference
9058 @item A string list-valued attribute reference
9059 @end itemize
9060
9061 @noindent
9062 A @emph{compound string list expression} is the concatenation (using
9063 @code{"&"}) of a simple string list expression and an expression.  Note that
9064 each term in a compound string list expression, except the first, may be
9065 either a string expression or a string list expression.
9066
9067 @smallexample
9068 @group
9069    File_Name_List := () & File_Name; --  One string in this list
9070    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
9071    --  Two strings
9072    Big_List := File_Name_List & Extended_File_Name_List;
9073    --  Concatenation of two string lists: three strings
9074    Illegal_List := "gnat.adc" & Extended_File_Name_List;
9075    --  Illegal: must start with a string list
9076 @end group
9077 @end smallexample
9078
9079
9080 @node String Types
9081 @subsection String Types
9082
9083 @noindent
9084 The value of a variable may be restricted to a list of string literals.
9085 The restricted list of string literals is given in a
9086 @emph{string type declaration}.
9087
9088 Here is an example of a string type declaration:
9089
9090 @smallexample
9091    type OS is ("NT, "nt", "Unix", "Linux", "other OS");
9092 @end smallexample
9093
9094 @noindent
9095 Variables of a string type are called @emph{typed variables}; all other
9096 variables are called @emph{untyped variables}. Typed variables are
9097 particularly useful in @code{case} constructions
9098 (see @ref{case Constructions}).
9099
9100 A string type declaration starts with the reserved word @code{type}, followed
9101 by the name of the string type (case-insensitive), followed by the reserved
9102 word @code{is}, followed by a parenthesized list of one or more string literals
9103 separated by commas, followed by a semicolon.
9104
9105 The string literals in the list are case sensitive and must all be different.
9106 They may include any graphic characters allowed in Ada, including spaces.
9107
9108 A string type may only be declared at the project level, not inside a package.
9109
9110 A string type may be referenced by its name if it has been declared in the same
9111 project file, or by its project name, followed by a dot,
9112 followed by the string type name.
9113
9114
9115 @node Variables
9116 @subsection Variables
9117
9118 @noindent
9119 A variable may be declared at the project file level, or in a package.
9120 Here are some examples of variable declarations:
9121
9122 @smallexample
9123 @group
9124    This_OS : OS := external ("OS"); --  a typed variable declaration
9125    That_OS := "Linux";              --  an untyped variable declaration
9126 @end group
9127 @end smallexample
9128
9129 @noindent
9130 A @emph{typed variable declaration} includes the variable name, followed by a colon,
9131 followed by the name of a string type, followed by @code{:=}, followed by
9132 a simple string expression.
9133
9134 An @emph{untyped variable declaration} includes the variable name,
9135 followed by @code{:=}, followed by an expression.  Note that, despite the
9136 terminology, this form of "declaration" resembles more an assignment
9137 than a declaration in Ada.  It is a declaration in several senses:
9138 @itemize @bullet
9139 @item
9140 The variable name does not need to be defined previously
9141 @item
9142 The declaration establishes the @emph{kind} (string versus string list) of the
9143 variable, and later declarations of the same variable need to be consistent
9144 with this
9145 @end itemize
9146
9147 @noindent
9148 A string variable declaration (typed or untyped) declares a variable
9149 whose value is a string. This variable may be used as a string expression.
9150 @smallexample
9151    File_Name       := "readme.txt";
9152    Saved_File_Name := File_Name & ".saved";
9153 @end smallexample
9154
9155 @noindent
9156 A string list variable declaration declares a variable whose value is a list
9157 of strings. The list may contain any number (zero or more) of strings.
9158
9159 @smallexample
9160    Empty_List := ();
9161    List_With_One_Element := ("-gnaty");
9162    List_With_Two_Elements := List_With_One_Element & "-gnatg";
9163    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
9164                  "pack2.ada", "util_.ada", "util.ada");
9165 @end smallexample
9166
9167 @noindent
9168 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.
9169
9170 The same untyped variable may be declared several times.
9171 In this case, the new value replaces the old one,
9172 and any subsequent reference to the variable uses the new value.
9173 However, as noted above, if a variable has been declared as a string, all subsequent
9174 declarations must give it a string value. Similarly, if a variable has
9175 been declared as a string list, all subsequent declarations
9176 must give it a string list value.
9177
9178 A @emph{variable reference} may take several forms:
9179
9180 @itemize @bullet
9181 @item The simple variable name, for a variable in the current package (if any) or in the current project
9182 @item A context name, followed by a dot, followed by the variable name.
9183 @end itemize
9184
9185 @noindent
9186 A @emph{context} may be one of the following:
9187
9188 @itemize @bullet
9189 @item The name of an existing package in the current project
9190 @item The name of an imported project of the current project
9191 @item The name of an ancestor project (i.e., a project extended by the current project, either directly or indirectly)
9192 @item An imported/parent project name, followed by a dot, followed by a package name
9193 @end itemize
9194
9195 @noindent
9196 A variable reference may be used in an expression.
9197
9198
9199 @node Attributes
9200 @subsection Attributes
9201
9202 @noindent
9203 A project (and its packages) may have @emph{attributes} that define the project's properties.
9204 Some attributes have values that are strings;
9205 others have values that are string lists.
9206
9207 There are two categories of attributes: @emph{simple attributes} and @emph{associative arrays}
9208 (see @ref{Associative Array Attributes}).
9209
9210 The names of the attributes are restricted; there is a list of project
9211 attributes, and a list of package attributes for each package.
9212 The names are not case sensitive.
9213
9214 The project attributes are as follows (all are simple attributes):
9215
9216 @multitable @columnfractions .4 .3
9217 @item @emph{Attribute Name}
9218 @tab @emph{Value}
9219 @item @code{Source_Files}
9220 @tab string list
9221 @item @code{Source_Dirs}
9222 @tab string list
9223 @item @code{Source_List_File}
9224 @tab string
9225 @item @code{Object_Dir}
9226 @tab string
9227 @item @code{Exec_Dir}
9228 @tab string
9229 @item @code{Main}
9230 @tab string list
9231 @item @code{Languages}
9232 @tab string list
9233 @item @code{Library_Dir}
9234 @tab string
9235 @item @code{Library_Name}
9236 @tab string
9237 @item @code{Library_Kind}
9238 @tab string
9239 @item @code{Library_Elaboration}
9240 @tab string
9241 @item @code{Library_Version}
9242 @tab string
9243 @end multitable
9244
9245 @noindent
9246 The attributes for package @code{Naming} are as follows
9247 (see @ref{Naming Schemes}):
9248
9249 @multitable @columnfractions .4 .2 .2 .2
9250 @item Attribute Name @tab Category @tab Index @tab Value
9251 @item @code{Specification_Suffix}
9252 @tab associative array
9253 @tab language name
9254 @tab string
9255 @item @code{Implementation_Suffix}
9256 @tab associative array
9257 @tab language name
9258 @tab string
9259 @item @code{Separate_Suffix}
9260 @tab simple attribute
9261 @tab n/a
9262 @tab string
9263 @item @code{Casing}
9264 @tab simple attribute
9265 @tab n/a
9266 @tab string
9267 @item @code{Dot_Replacement}
9268 @tab simple attribute
9269 @tab n/a
9270 @tab string
9271 @item @code{Specification}
9272 @tab associative array
9273 @tab Ada unit name
9274 @tab string
9275 @item @code{Implementation}
9276 @tab associative array
9277 @tab Ada unit name
9278 @tab string
9279 @item @code{Specification_Exceptions}
9280 @tab associative array
9281 @tab language name
9282 @tab string list
9283 @item @code{Implementation_Exceptions}
9284 @tab associative array
9285 @tab language name
9286 @tab string list
9287 @end multitable
9288
9289 @noindent
9290 The attributes for package @code{Builder}, @code{Compiler}, @code{Binder},
9291 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
9292 are as follows (see @ref{Switches and Project Files}).
9293
9294 @multitable @columnfractions .4 .2 .2 .2
9295 @item Attribute Name @tab Category @tab Index @tab Value
9296 @item @code{Default_Switches}
9297 @tab associative array
9298 @tab language name
9299 @tab string list
9300 @item @code{Switches}
9301 @tab associative array
9302 @tab file name
9303 @tab string list
9304 @end multitable
9305
9306 @noindent
9307 In addition, package @code{Builder} has a single string attribute
9308 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
9309 string attribute @code{Global_Configuration_Pragmas}.
9310
9311 @noindent
9312 The attribute for package @code{Glide} are not documented: they are for
9313 internal use only.
9314
9315 @noindent
9316 Each simple attribute has a default value: the empty string (for string-valued
9317 attributes) and the empty list (for string list-valued attributes).
9318
9319 Similar to variable declarations, an attribute declaration defines a new value
9320 for an attribute.
9321
9322 Examples of simple attribute declarations:
9323
9324 @smallexample
9325    for Object_Dir use "objects";
9326    for Source_Dirs use ("units", "test/drivers");
9327 @end smallexample
9328
9329 @noindent
9330 A @dfn{simple attribute declaration} starts with the reserved word @code{for},
9331 followed by the name of the attribute, followed by the reserved word
9332 @code{use}, followed by an expression (whose kind depends on the attribute),
9333 followed by a semicolon.
9334
9335 Attributes may be referenced in expressions.
9336 The general form for such a reference is @code{<entity>'<attribute>}:
9337 the entity for which the attribute is defined,
9338 followed by an apostrophe, followed by the name of the attribute.
9339 For associative array attributes, a litteral string between parentheses
9340 need to be supplied as index.
9341
9342 Examples are:
9343
9344 @smallexample
9345   project'Object_Dir
9346   Naming'Dot_Replacement
9347   Imported_Project'Source_Dirs
9348   Imported_Project.Naming'Casing
9349   Builder'Default_Switches("Ada")
9350 @end smallexample
9351
9352 @noindent
9353 The entity may be:
9354 @itemize @bullet
9355 @item @code{project} for an attribute of the current project
9356 @item The name of an existing package of the current project
9357 @item The name of an imported project
9358 @item The name of a parent project (extended by the current project)
9359 @item An imported/parent project name, followed by a dot,
9360       followed by a package name
9361 @end itemize
9362
9363 @noindent
9364 Example:
9365 @smallexample
9366 @group
9367    project Prj is
9368      for Source_Dirs use project'Source_Dirs & "units";
9369      for Source_Dirs use project'Source_Dirs & "test/drivers"
9370    end Prj;
9371 @end group
9372 @end smallexample
9373
9374 @noindent
9375 In the first attribute declaration, initially the attribute @code{Source_Dirs}
9376 has the default value: an empty string list. After this declaration,
9377 @code{Source_Dirs} is a string list of one element: "units".
9378 After the second attribute declaration @code{Source_Dirs} is a string list of
9379 two elements: "units" and "test/drivers".
9380
9381 Note: this example is for illustration only. In practice,
9382 the project file would contain only one attribute declaration:
9383
9384 @smallexample
9385    for Source_Dirs use ("units", "test/drivers");
9386 @end smallexample
9387
9388
9389 @node Associative Array Attributes
9390 @subsection Associative Array Attributes
9391
9392 @noindent
9393 Some attributes are defined as @emph{associative arrays}. An associative
9394 array may be regarded as a function that takes a string as a parameter
9395 and delivers a string or string list value as its result.
9396
9397 Here are some examples of associative array attribute declarations:
9398
9399 @smallexample
9400    for Implementation ("main") use "Main.ada";
9401    for Switches ("main.ada") use ("-v", "-gnatv");
9402    for Switches ("main.ada") use Builder'Switches ("main.ada") & "-g";
9403 @end smallexample
9404
9405 @noindent
9406 Like untyped variables and simple attributes, associative array attributes may be declared several times. Each declaration supplies a new value for the
9407 attribute, replacing the previous setting.
9408
9409
9410 @node case Constructions
9411 @subsection @code{case} Constructions
9412
9413 @noindent
9414 A @code{case} construction is used in a project file to effect conditional
9415 behavior.
9416 Here is a typical example:
9417
9418 @smallexample
9419 @group
9420 project MyProj is
9421    type OS_Type is ("Linux", "Unix", "NT", "VMS");
9422
9423    OS : OS_Type := external ("OS", "Linux");
9424 @end group
9425
9426 @group
9427    package Compiler is
9428      case OS is
9429        when "Linux" | "Unix" =>
9430          for Default_Switches ("Ada") use ("-gnath");
9431        when "NT" =>
9432          for Default_Switches ("Ada") use ("-gnatP");
9433        when others =>
9434      end case;
9435    end Compiler;
9436 end MyProj;
9437 @end group
9438 @end smallexample
9439
9440 @noindent
9441 The syntax of a @code{case} construction is based on the Ada case statement
9442 (although there is no @code{null} construction for empty alternatives).
9443
9444 Following the reserved word @code{case} there is the case variable (a typed
9445 string variable), the reserved word @code{is}, and then a sequence of one or
9446 more alternatives.
9447 Each alternative comprises the reserved word @code{when}, either a list of
9448 literal strings separated by the @code{"|"} character or the reserved word
9449 @code{others},  and the @code{"=>"} token.
9450 Each literal string must belong to the string type that is the type of the
9451 case variable.
9452 An @code{others} alternative, if present, must occur last.
9453 The @code{end case;} sequence terminates the case construction.
9454
9455 After each @code{=>}, there are zero or more constructions.  The only
9456 constructions allowed in a case construction are other case constructions and
9457 attribute declarations. String type declarations, variable declarations and
9458 package declarations are not allowed.
9459
9460 The value of the case variable is often given by an external reference
9461 (see @ref{External References in Project Files}).
9462
9463
9464 @c ****************************************
9465 @c * Objects and Sources in Project Files *
9466 @c ****************************************
9467
9468 @node Objects and Sources in Project Files
9469 @section Objects and Sources in Project Files
9470
9471 @menu
9472 * Object Directory::
9473 * Exec Directory::
9474 * Source Directories::
9475 * Source File Names::
9476 @end menu
9477
9478 @noindent
9479 Each project has exactly one object directory and one or more source
9480 directories. The source directories must contain at least one source file,
9481 unless  the project file explicitly specifies that no source files are present
9482 (see @ref{Source File Names}).
9483
9484
9485 @node Object Directory
9486 @subsection Object Directory
9487
9488 @noindent
9489 The object directory for a project is the directory containing the compiler's
9490 output (such as @file{ALI} files and object files) for the project's immediate
9491 sources. Note that for inherited sources (when extending a parent project) the
9492 parent project's object directory is used.
9493
9494 The object directory is given by the value of the attribute @code{Object_Dir}
9495 in the project file.
9496
9497 @smallexample
9498    for Object_Dir use "objects";
9499 @end smallexample
9500
9501 @noindent
9502 The attribute @var{Object_Dir} has a string value, the path name of the object
9503 directory. The path name may be absolute or relative to the directory of the
9504 project file. This directory must already exist, and be readable and writable.
9505
9506 By default, when the attribute @code{Object_Dir} is not given an explicit value
9507 or when its value is the empty string, the object directory is the same as the
9508 directory containing the project file.
9509
9510
9511 @node Exec Directory
9512 @subsection Exec Directory
9513
9514 @noindent
9515 The exec directory for a project is the directory containing the executables
9516 for the project's main subprograms.
9517
9518 The exec directory is given by the value of the attribute @code{Exec_Dir}
9519 in the project file.
9520
9521 @smallexample
9522    for Exec_Dir use "executables";
9523 @end smallexample
9524
9525 @noindent
9526 The attribute @var{Exec_Dir} has a string value, the path name of the exec
9527 directory. The path name may be absolute or relative to the directory of the
9528 project file. This directory must already exist, and be writable.
9529
9530 By default, when the attribute @code{Exec_Dir} is not given an explicit value
9531 or when its value is the empty string, the exec directory is the same as the
9532 object directory of the project file.
9533
9534
9535 @node Source Directories
9536 @subsection Source Directories
9537
9538 @noindent
9539 The source directories of a project are specified by the project file
9540 attribute @code{Source_Dirs}.
9541
9542 This attribute's value is a string list. If the attribute is not given an
9543 explicit value, then there is only one source directory, the one where the
9544 project file resides.
9545
9546 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
9547 as in
9548
9549 @smallexample
9550     for Source_Dirs use ();
9551 @end smallexample
9552
9553 @noindent
9554 indicates that the project contains no source files.
9555
9556 Otherwise, each string in the string list designates one or more
9557 source directories.
9558
9559 @smallexample
9560    for Source_Dirs use ("sources", "test/drivers");
9561 @end smallexample
9562
9563 @noindent
9564 If a string in the list ends with @code{"/**"},  then the directory whose path
9565 name precedes the two asterisks, as well as all its subdirectories
9566 (recursively), are source directories.
9567
9568 @smallexample
9569    for Source_Dirs use ("/system/sources/**");
9570 @end smallexample
9571
9572 @noindent
9573 Here the directory @code{/system/sources} and all of its subdirectories
9574 (recursively) are source directories.
9575
9576 To specify that the source directories are the directory of the project file
9577 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
9578 @smallexample
9579    for Source_Dirs use ("./**");
9580 @end smallexample
9581
9582 @noindent
9583 Each of the source directories must exist and be readable.
9584
9585
9586 @node Source File Names
9587 @subsection Source File Names
9588
9589 @noindent
9590 In a project that contains source files, their names may be specified by the
9591 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
9592 (a string). Source file names never include any directory information.
9593
9594 If the attribute @code{Source_Files} is given an explicit value, then each
9595 element of the list is a source file name.
9596
9597 @smallexample
9598    for Source_Files use ("main.adb");
9599    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
9600 @end smallexample
9601
9602 @noindent
9603 If the attribute @code{Source_Files} is not given an explicit value,
9604 but the attribute @code{Source_List_File} is given a string value,
9605 then the source file names are contained in the text file whose path name
9606 (absolute or relative to the directory of the project file) is the
9607 value of the attribute @code{Source_List_File}.
9608
9609 Each line in the file that is not empty or is not a comment
9610 contains a source file name. A comment line starts with two hyphens.
9611
9612 @smallexample
9613    for Source_List_File use "source_list.txt";
9614 @end smallexample
9615
9616 @noindent
9617 By default, if neither the attribute @code{Source_Files} nor the attribute
9618 @code{Source_List_File} is given an explicit value, then each file in the
9619 source directories that conforms to the project's naming scheme
9620 (see @ref{Naming Schemes}) is an immediate source of the project.
9621
9622 A warning is issued if both attributes @code{Source_Files} and
9623 @code{Source_List_File} are given explicit values. In this case, the attribute
9624 @code{Source_Files} prevails.
9625
9626 Each source file name must be the name of one and only one existing source file
9627 in one of the source directories.
9628
9629 A @code{Source_Files} attribute defined with an empty list as its value
9630 indicates that there are no source files in the project.
9631
9632 Except for projects that are clearly specified as containing no Ada source
9633 files (@code{Source_Dirs} or @code{Source_Files} specified as an empty list,
9634 or @code{Languages} specified without @code{"Ada"} in the list)
9635 @smallexample
9636    for Source_Dirs use ();
9637    for Source_Files use ();
9638    for Languages use ("C", "C++");
9639 @end smallexample
9640
9641 @noindent
9642 a project must contain at least one immediate source.
9643
9644 Projects with no source files are useful as template packages
9645 (see @ref{Packages in Project Files}) for other projects; in particular to
9646 define a package @code{Naming} (see @ref{Naming Schemes}).
9647
9648
9649 @c ****************************
9650 @c * Importing Projects *
9651 @c ****************************
9652
9653 @node  Importing Projects
9654 @section Importing Projects
9655
9656 @noindent
9657 An immediate source of a project P may depend on source files that
9658 are neither immediate sources of P nor in the predefined library.
9659 To get this effect, P must @emph{import} the projects that contain the needed
9660 source files.
9661
9662 @smallexample
9663 @group
9664   with "project1", "utilities.gpr";
9665   with "/namings/apex.gpr";
9666   project Main is
9667     ...
9668 @end group
9669 @end smallexample
9670
9671 @noindent
9672 As can be seen in this example, the syntax for importing projects is similar
9673 to the syntax for importing compilation units in Ada. However, project files
9674 use literal strings instead of names, and the @code{with} clause identifies
9675 project files rather than packages.
9676
9677 Each literal string is the file name or path name (absolute or relative) of a
9678 project file. If a string is simply a file name, with no path, then its
9679 location is determined by the @emph{project path}:
9680
9681 @itemize @bullet
9682 @item
9683 If the environment variable @env{ADA_PROJECT_PATH} exists, then the project
9684 path includes all the directories in this environment variable, plus the
9685 directory of the project file.
9686
9687 @item
9688 If the environment variable @env{ADA_PROJECT_PATH} does not exist,
9689 then the project path contains only one directory, namely the one where
9690 the project file is located.
9691 @end itemize
9692
9693 @noindent
9694 If a relative pathname is used as in
9695
9696 @smallexample
9697   with "tests/proj";
9698 @end smallexample
9699
9700 @noindent
9701 then the path is relative to the directory where the importing project file is
9702 located. Any symbolic link will be fully resolved in the directory
9703 of the importing project file before the imported project file is looked up.
9704
9705 When the @code{with}'ed project file name does not have an extension,
9706 the default is @file{.gpr}. If a file with this extension is not found, then
9707 the file name as specified in the @code{with} clause (no extension) will be
9708 used. In the above example, if a file @code{project1.gpr} is found, then it
9709 will be used; otherwise, if a file @code{project1} exists then it will be used;
9710 if neither file exists, this is an error.
9711
9712 A warning is issued if the name of the project file does not match the
9713 name of the project; this check is case insensitive.
9714
9715 Any source file that is an immediate source of the imported project can be
9716 used by the immediate sources of the importing project, and recursively. Thus
9717 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
9718 sources of @code{A} may depend on the immediate sources of @code{C}, even if
9719 @code{A} does not import @code{C} explicitly. However, this is not recommended,
9720 because if and when @code{B} ceases to import @code{C}, some sources in
9721 @code{A} will no longer compile.
9722
9723 A side effect of this capability is that cyclic dependences are not permitted:
9724 if @code{A} imports @code{B} (directly or indirectly) then @code{B} is not
9725 allowed to import @code{A}.
9726
9727
9728 @c *********************
9729 @c * Project Extension *
9730 @c *********************
9731
9732 @node Project Extension
9733 @section Project Extension
9734
9735 @noindent
9736 During development of a large system, it is sometimes necessary to use
9737 modified versions of some of the source files without changing the original
9738 sources. This can be achieved through a facility known as
9739 @emph{project extension}.
9740
9741 @smallexample
9742    project Modified_Utilities extends "/baseline/utilities.gpr" is ...
9743 @end smallexample
9744
9745 @noindent
9746 The project file for the project being extended (the @emph{parent}) is
9747 identified by the literal string that follows the reserved word @code{extends},
9748 which itself follows the name of the extending project (the @emph{child}).
9749
9750 By default, a child project inherits all the sources of its parent.
9751 However, inherited sources can be overridden: a unit with the same name as one
9752 in the parent will hide the original unit.
9753 Inherited sources are considered to be sources (but not immediate sources)
9754 of the child project; see @ref{Project File Syntax}.
9755
9756 An inherited source file retains any switches specified in the parent project.
9757
9758 For example if the project @code{Utilities} contains the specification and the
9759 body of an Ada package @code{Util_IO}, then the project
9760 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
9761 The original body of @code{Util_IO} will not be considered in program builds.
9762 However, the package specification will still be found in the project
9763 @code{Utilities}.
9764
9765 A child project can have only one parent but it may import any number of other
9766 projects.
9767
9768 A project is not allowed to import directly or indirectly at the same time a
9769 child project and any of its ancestors.
9770
9771
9772 @c ****************************************
9773 @c * External References in Project Files *
9774 @c ****************************************
9775
9776 @node  External References in Project Files
9777 @section External References in Project Files
9778
9779 @noindent
9780 A project file may contain references to external variables; such references
9781 are called @emph{external references}.
9782
9783 An external variable is either defined as part of the environment (an
9784 environment variable in Unix, for example) or else specified on the command
9785 line via the @option{-X@emph{vbl}=@emph{value}} switch. If both, then the
9786 command line value is used.
9787
9788 An external reference is denoted by the built-in function
9789 @code{external}, which returns a string value.  This function has two forms:
9790 @itemize @bullet
9791 @item @code{external (external_variable_name)}
9792 @item @code{external (external_variable_name, default_value)}
9793 @end itemize
9794
9795 @noindent
9796 Each parameter must be a string literal.  For example:
9797
9798 @smallexample
9799    external ("USER")
9800    external ("OS", "Linux")
9801 @end smallexample
9802
9803 @noindent
9804 In the form with one parameter, the function returns the value of
9805 the external variable given as parameter. If this name is not present in the
9806 environment, then the returned value is an empty string.
9807
9808 In the form with two string parameters, the second parameter is
9809 the value returned when the variable given as the first parameter is not
9810 present in the environment. In the example above, if @code{"OS"} is not
9811 the name of an environment variable and is not passed on the command line,
9812 then the returned value will be @code{"Linux"}.
9813
9814 An external reference may be part of a string expression or of a string
9815 list expression, to define variables or attributes.
9816
9817 @smallexample
9818 @group
9819    type Mode_Type is ("Debug", "Release");
9820    Mode : Mode_Type := external ("MODE");
9821    case Mode is
9822      when "Debug" =>
9823         ...
9824 @end group
9825 @end smallexample
9826
9827
9828 @c *****************************
9829 @c * Packages in Project Files *
9830 @c *****************************
9831
9832 @node  Packages in Project Files
9833 @section Packages in Project Files
9834
9835 @noindent
9836 The @emph{package} is the project file feature that defines the settings for
9837 project-aware tools.
9838 For each such tool you can declare a corresponding package; the names for these
9839 packages are preset (see @ref{Packages}) but are not case sensitive.
9840 A package may contain variable declarations, attribute declarations, and case
9841 constructions.
9842
9843 @smallexample
9844 @group
9845    project Proj is
9846       package Builder is  -- used by gnatmake
9847          for Default_Switches ("Ada") use ("-v", "-g");
9848       end Builder;
9849    end Proj;
9850 @end group
9851 @end smallexample
9852
9853 @noindent
9854 A package declaration starts with the reserved word @code{package},
9855 followed by the package name (case insensitive), followed by the reserved word
9856 @code{is}. It ends with the reserved word @code{end}, followed by the package
9857 name, finally followed by a semi-colon.
9858
9859 Most of the packages have an attribute @code{Default_Switches}.
9860 This attribute is an associative array, and its value is a string list.
9861 The index of the associative array is the name of a programming language (case
9862 insensitive). This attribute indicates the switch or switches to be used
9863 with the corresponding tool.
9864
9865 Some packages also have another attribute, @code{Switches}, an associative
9866 array whose value is a string list. The index is the name of a source file.
9867 This attribute indicates the switch or switches to be used by the corresponding
9868 tool when dealing with this specific file.
9869
9870 Further information on these switch-related attributes is found in
9871 @ref{Switches and Project Files}.
9872
9873 A package may be declared as a @emph{renaming} of another package; e.g., from
9874 the project file for an imported project.
9875
9876 @smallexample
9877 @group
9878   with "/global/apex.gpr";
9879   project Example is
9880     package Naming renames Apex.Naming;
9881     ...
9882   end Example;
9883 @end group
9884 @end smallexample
9885
9886 @noindent
9887 Packages that are renamed in other project files often come from project files
9888 that have no sources: they are just used as templates. Any modification in the
9889 template will be reflected automatically in all the project files that rename
9890 a package from the template.
9891
9892 In addition to the tool-oriented packages, you can also declare a package
9893 named @code{Naming} to establish specialized source file naming conventions
9894 (see @ref{Naming Schemes}).
9895
9896
9897 @c ************************************
9898 @c * Variables from Imported Projects *
9899 @c ************************************
9900
9901 @node Variables from Imported Projects
9902 @section Variables from Imported Projects
9903
9904 @noindent
9905 An attribute or variable defined in an imported or parent project can
9906 be used in expressions in the importing / extending project.
9907 Such an attribute or variable is prefixed with the name of the project
9908 and (if relevant) the name of package where it is defined.
9909
9910 @smallexample
9911 @group
9912   with "imported";
9913   project Main extends "base" is
9914      Var1 := Imported.Var;
9915      Var2 := Base.Var & ".new";
9916 @end group
9917
9918 @group
9919      package Builder is
9920         for Default_Switches ("Ada") use Imported.Builder.Ada_Switches &
9921                          "-gnatg" & "-v";
9922      end Builder;
9923 @end group
9924
9925 @group
9926      package Compiler is
9927         for Default_Switches ("Ada") use Base.Compiler.Ada_Switches;
9928      end Compiler;
9929   end Main;
9930 @end group
9931 @end smallexample
9932
9933 @noindent
9934 In this example:
9935
9936 @itemize @bullet
9937 @item
9938 @code{Var1} is a copy of the variable @code{Var} defined in the project file
9939 @file{"imported.gpr"}
9940 @item
9941 the value of @code{Var2} is a copy of the value of variable @code{Var}
9942 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
9943 @item
9944 attribute @code{Default_Switches ("Ada")} in package @code{Builder}
9945 is a string list that includes in its value a copy of variable
9946 @code{Ada_Switches} defined in the @code{Builder} package in project file
9947 @file{imported.gpr} plus two new elements: @option{"-gnatg"} and @option{"-v"};
9948 @item
9949 attribute @code{Default_Switches ("Ada")} in package @code{Compiler}
9950 is a copy of the variable @code{Ada_Switches} defined in the @code{Compiler}
9951 package in project file @file{base.gpr}, the project being extended.
9952 @end itemize
9953
9954
9955 @c ******************
9956 @c * Naming Schemes *
9957 @c ******************
9958
9959 @node  Naming Schemes
9960 @section Naming Schemes
9961
9962 @noindent
9963 Sometimes an Ada software system is ported from a foreign compilation
9964 environment to GNAT, with file names that do not use the default GNAT
9965 conventions. Instead of changing all the file names (which for a variety of
9966 reasons might not be possible), you can define the relevant file naming scheme
9967 in the @code{Naming} package in your project file.  For example, the following
9968 package models the Apex file naming rules:
9969
9970 @smallexample
9971 @group
9972   package Naming is
9973     for Casing                        use "lowercase";
9974     for Dot_Replacement               use ".";
9975     for Specification_Suffix ("Ada")  use ".1.ada";
9976     for Implementation_Suffix ("Ada") use ".2.ada";
9977   end Naming;
9978 @end group
9979 @end smallexample
9980
9981 @noindent
9982 You can define the following attributes in package @code{Naming}:
9983
9984 @table @code
9985
9986 @item @var{Casing}
9987 This must be a string with one of the three values @code{"lowercase"},
9988 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
9989
9990 @noindent
9991 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
9992
9993 @item @var{Dot_Replacement}
9994 This must be a string whose value satisfies the following conditions:
9995
9996 @itemize @bullet
9997 @item It must not be empty
9998 @item It cannot start or end with an alphanumeric character
9999 @item It cannot be a single underscore
10000 @item It cannot start with an underscore followed by an alphanumeric
10001 @item It cannot contain a dot @code{'.'} except if it the entire string is @code{"."}
10002 @end itemize
10003
10004 @noindent
10005 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
10006
10007 @item @var{Specification_Suffix}
10008 This is an associative array (indexed by the programming language name, case
10009 insensitive) whose value is a string that must satisfy the following
10010 conditions:
10011
10012 @itemize @bullet
10013 @item It must not be empty
10014 @item It cannot start with an alphanumeric character
10015 @item It cannot start with an underscore followed by an alphanumeric character
10016 @end itemize
10017 @noindent
10018 If @code{Specification_Suffix ("Ada")} is not specified, then the default is
10019 @code{".ads"}.
10020
10021 @item @var{Implementation_Suffix}
10022 This is an associative array (indexed by the programming language name, case
10023 insensitive) whose value is a string that must satisfy the following
10024 conditions:
10025
10026 @itemize @bullet
10027 @item It must not be empty
10028 @item It cannot start with an alphanumeric character
10029 @item It cannot start with an underscore followed by an alphanumeric character
10030 @item It cannot be a suffix of @code{Specification_Suffix}
10031 @end itemize
10032 @noindent
10033 If @code{Implementation_Suffix ("Ada")} is not specified, then the default is
10034 @code{".adb"}.
10035
10036 @item @var{Separate_Suffix}
10037 This must be a string whose value satisfies the same conditions as
10038 @code{Implementation_Suffix}.
10039
10040 @noindent
10041 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
10042 value as @code{Implementation_Suffix ("Ada")}.
10043
10044 @item @var{Specification}
10045 @noindent
10046 You can use the @code{Specification} attribute, an associative array, to define
10047 the source file name for an individual Ada compilation unit's spec. The array
10048 index must be a string literal that identifies the Ada unit (case insensitive).
10049 The value of this attribute must be a string that identifies the file that
10050 contains this unit's spec (case sensitive or insensitive depending on the
10051 operating system).
10052
10053 @smallexample
10054    for Specification ("MyPack.MyChild") use "mypack.mychild.spec";
10055 @end smallexample
10056
10057 @item @var{Implementation}
10058
10059 You can use the @code{Implementation} attribute, an associative array, to
10060 define the source file name for an individual Ada compilation unit's body
10061 (possibly a subunit).  The array index must be a string literal that identifies
10062 the Ada unit (case insensitive).  The value of this attribute must be a string
10063 that identifies the file that contains this unit's body or subunit (case
10064 sensitive or insensitive depending on the operating system).
10065
10066 @smallexample
10067    for Implementation ("MyPack.MyChild") use "mypack.mychild.body";
10068 @end smallexample
10069 @end table
10070
10071
10072 @c ********************
10073 @c * Library Projects *
10074 @c ********************
10075
10076 @node Library Projects
10077 @section Library Projects
10078
10079 @noindent
10080 @emph{Library projects} are projects whose object code is placed in a library.
10081 (Note that this facility is not yet supported on all platforms)
10082
10083 To create a library project, you need to define in its project file
10084 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
10085 Additionally, you may define the library-related attributes
10086 @code{Library_Kind}, @code{Library_Version} and @code{Library_Elaboration}.
10087
10088 The @code{Library_Name} attribute has a string value that must start with a
10089 letter and include only letters and digits.
10090
10091 The @code{Library_Dir} attribute has a string value that designates the path
10092 (absolute or relative) of the directory where the library will reside.
10093 It must designate an existing directory, and this directory needs to be
10094 different from the project's object directory. It also needs to be writable.
10095
10096 If both @code{Library_Name} and @code{Library_Dir} are specified and
10097 are legal, then the project file defines a library project.  The optional
10098 library-related attributes are checked only for such project files.
10099
10100 The @code{Library_Kind} attribute has a string value that must be one of the
10101 following (case insensitive): @code{"static"}, @code{"dynamic"} or
10102 @code{"relocatable"}. If this attribute is not specified, the library is a
10103 static library. Otherwise, the library may be dynamic or relocatable.
10104 Depending on the operating system, there may or may not be a distinction
10105 between dynamic and relocatable libraries. For example, on Unix there is no
10106 such distinction.
10107
10108 The @code{Library_Version} attribute has a string value whose interpretation
10109 is platform dependent. On Unix, it is used only for dynamic/relocatable
10110 libraries as the internal name of the library (the @code{"soname"}). If the
10111 library file name (built from the @code{Library_Name}) is different from the
10112 @code{Library_Version}, then the library file will be a symbolic link to the
10113 actual file whose name will be @code{Library_Version}.
10114
10115 Example (on Unix):
10116
10117 @smallexample
10118 @group
10119 project Plib is
10120
10121    Version := "1";
10122
10123    for Library_Dir use "lib_dir";
10124    for Library_Name use "dummy";
10125    for Library_Kind use "relocatable";
10126    for Library_Version use "libdummy.so." & Version;
10127
10128 end Plib;
10129 @end group
10130 @end smallexample
10131
10132 @noindent
10133 Directory @file{lib_dir} will contain the internal library file whose name
10134 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
10135 @file{libdummy.so.1}.
10136
10137 When @command{gnatmake} detects that a project file (not the main project file)
10138 is a library project file, it will check all immediate sources of the project
10139 and rebuild the library if any of the sources have been recompiled.
10140 All @file{ALI} files will also be copied from the object directory to the
10141 library directory. To build executables, @command{gnatmake} will use the
10142 library rather than the individual object files.
10143
10144
10145 @c *************************************
10146 @c * Switches Related to Project Files *
10147 @c *************************************
10148 @node Switches Related to Project Files
10149 @section Switches Related to Project Files
10150
10151 @noindent
10152 The following switches are used by GNAT tools that support project files:
10153
10154 @table @code
10155
10156 @item @option{-P@var{project}}
10157 Indicates the name of a project file. This project file will be parsed with
10158 the verbosity indicated by @option{-vP@emph{x}}, if any, and using the external
10159 references indicated by @option{-X} switches, if any.
10160
10161 @noindent
10162 There must be only one @option{-P} switch on the command line.
10163
10164 @noindent
10165 Since the Project Manager parses the project file only after all the switches
10166 on the command line are checked, the order of the switches @option{-P},
10167 @option{-Vp@emph{x}} or @option{-X} is not significant.
10168
10169 @item @option{-X@var{name=value}}
10170 Indicates that external variable @var{name} has the value @var{value}.
10171 The Project Manager will use this value for occurrences of
10172 @code{external(name)} when parsing the project file.
10173
10174 @noindent
10175 If @var{name} or @var{value} includes a space, then @var{name=value} should be
10176 put between quotes.
10177 @smallexample
10178   -XOS=NT
10179   -X"user=John Doe"
10180 @end smallexample
10181
10182 @noindent
10183 Several @option{-X} switches can be used simultaneously.
10184 If several @option{-X} switches specify the same @var{name}, only the last one
10185 is used.
10186
10187 @noindent
10188 An external variable specified with a @option{-X} switch takes precedence
10189 over the value of the same name in the environment.
10190
10191 @item @option{-vP@emph{x}}
10192 Indicates the verbosity of the parsing of GNAT project files.
10193 @option{-vP0} means Default (no output for syntactically correct project
10194 files);
10195 @option{-vP1} means Medium;
10196 @option{-vP2} means High.
10197 @noindent
10198 The default is Default.
10199 @noindent
10200 If several @option{-vP@emph{x}} switches are present, only the last one is
10201 used.
10202
10203 @end table
10204
10205
10206 @c **********************************
10207 @c * Tools Supporting Project Files *
10208 @c **********************************
10209
10210 @node  Tools Supporting Project Files
10211 @section Tools Supporting Project Files
10212
10213 @menu
10214 * gnatmake and Project Files::
10215 * The GNAT Driver and Project Files::
10216 * Glide and Project Files::
10217 @end menu
10218
10219 @node gnatmake and Project Files
10220 @subsection gnatmake and Project Files
10221
10222 @noindent
10223 This section covers two topics related to @command{gnatmake} and project files:
10224 defining switches for @command{gnatmake} and for the tools that it invokes;
10225 and the use of the @code{Main} attribute.
10226
10227 @menu
10228 * Switches and Project Files::
10229 * Project Files and Main Subprograms::
10230 @end menu
10231
10232 @node Switches and Project Files
10233 @subsubsection Switches and Project Files
10234
10235 @noindent
10236 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
10237 @code{Linker}, you can specify a @code{Default_Switches} attribute, a
10238 @code{Switches} attribute, or both; as their names imply, these switch-related
10239 attributes affect which switches are used for which files when
10240 @command{gnatmake} is invoked.  As will be explained below, these
10241 package-contributed switches precede the switches passed on the
10242 @command{gnatmake} command line.
10243
10244 The @code{Default_Switches} attribute is an associative array indexed by
10245 language name (case insensitive) and returning a string list.  For example:
10246
10247 @smallexample
10248 @group
10249 package Compiler is
10250   for Default_Switches ("Ada") use ("-gnaty", "-v");
10251 end Compiler;
10252 @end group
10253 @end smallexample
10254
10255 @noindent
10256 The @code{Switches} attribute is also an associative array, indexed by a file
10257 name (which may or may not be case sensitive, depending on the operating
10258 system) and returning a string list.  For example:
10259
10260 @smallexample
10261 @group
10262 package Builder is
10263    for Switches ("main1.adb") use ("-O2");
10264    for Switches ("main2.adb") use ("-g");
10265 end Builder;
10266 @end group
10267 @end smallexample
10268
10269 @noindent
10270 For the @code{Builder} package, the file names should designate source files
10271 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
10272 file names should designate @file{ALI} or source files for main subprograms.
10273 In each case just the file name (without explicit extension) is acceptable.
10274
10275 For each tool used in a program build (@command{gnatmake}, the compiler, the
10276 binder, and the linker), its corresponding package @dfn{contributes} a set of
10277 switches for each file on which the tool is invoked, based on the
10278 switch-related attributes defined in the package. In particular, the switches
10279 that each of these packages contributes for a given file @var{f} comprise:
10280
10281 @itemize @bullet
10282 @item
10283 the value of attribute @code{Switches (@var{f})}, if it is specified in the
10284 package for the given file,
10285 @item
10286 otherwise, the value of @code{Default_Switches ("Ada")}, if it is specified in
10287 the package.
10288 @end itemize
10289
10290 @noindent
10291 If neither of these attributes is defined in the package, then the package does
10292 not contribute any switches for the given file.
10293
10294 When @command{gnatmake} is invoked on a file, the switches comprise two sets,
10295 in the following order: those contributed for the file by the @code{Builder}
10296 package; and the switches passed on the command line.
10297
10298 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
10299 the switches passed to the tool comprise three sets, in the following order:
10300
10301 @enumerate
10302 @item
10303 the applicable switches contributed for the file by the @code{Builder} package
10304 in the project file supplied on the command line;
10305
10306 @item
10307 those contributed for the file by the package (in the relevant project file --
10308 see below) corresponding to the tool; and
10309
10310 @item
10311 the applicable switches passed on the command line.
10312 @end enumerate
10313
10314 @noindent
10315 The term @emph{applicable switches} reflects the fact that @command{gnatmake}
10316 switches may or may not be passed to individual tools, depending on the
10317 individual switch.
10318
10319 @command{gnatmake} may invoke the compiler on source files from different
10320 projects. The Project Manager will use the appropriate project file to
10321 determine the @code{Compiler} package for each source file being compiled.
10322 Likewise for the @code{Binder} and @code{Linker} packages.
10323
10324 As an example, consider the following package in a project file:
10325
10326 @smallexample
10327 @group
10328 project Proj1 is
10329    package Compiler is
10330       for Default_Switches ("Ada") use ("-g");
10331       for Switches ("a.adb") use ("-O1");
10332       for Switches ("b.adb") use ("-O2", "-gnaty");
10333    end Compiler;
10334 end Proj1;
10335 @end group
10336 @end smallexample
10337
10338 @noindent
10339 If @command{gnatmake} is invoked with this project file, and it needs to
10340 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
10341 @file{a.adb} will be compiled with the switch @option{-O1}, @file{b.adb}
10342 with switches @option{-O2} and @option{-gnaty}, and @file{c.adb} with
10343 @option{-g}.
10344
10345 Another example illustrates the ordering of the switches contributed by
10346 different packages:
10347
10348 @smallexample
10349 @group
10350 project Proj2 is
10351    package Builder is
10352       for Switches ("main.adb") use ("-g", "-O1", "-f");
10353    end Builder;
10354 @end group
10355
10356 @group
10357    package Compiler is
10358       for Switches ("main.adb") use ("-O2");
10359    end Compiler;
10360 end Proj2;
10361 @end group
10362 @end smallexample
10363
10364 @noindent
10365 If you issue the command:
10366
10367 @smallexample
10368     gnatmake -PProj2 -O0 main
10369 @end smallexample
10370
10371 @noindent
10372 then the compiler will be invoked on @file{main.adb} with the following sequence of switches
10373
10374 @smallexample
10375    -g -O1 -O2 -O0
10376 @end smallexample
10377
10378 with the last @option{-O} switch having precedence over the earlier ones;
10379 several other switches (such as @option{-c}) are added implicitly.
10380
10381 The switches @option{-g} and @option{-O1} are contributed by package
10382 @code{Builder},  @option{-O2} is contributed by the package @code{Compiler}
10383 and @option{-O0} comes from the command line.
10384
10385 The @option{-g} switch will also be passed in the invocation of
10386 @command{gnatlink.}
10387
10388 A final example illustrates switch contributions from packages in different
10389 project files:
10390
10391 @smallexample
10392 @group
10393 project Proj3 is
10394    for Source_Files use ("pack.ads", "pack.adb");
10395    package Compiler is
10396       for Default_Switches ("Ada") use ("-gnata");
10397    end Compiler;
10398 end Proj3;
10399 @end group
10400
10401 @group
10402 with "Proj3";
10403 project Proj4 is
10404    for Source_Files use ("foo_main.adb", "bar_main.adb");
10405    package Builder is
10406       for Switches ("foo_main.adb") use ("-s", "-g");
10407    end Builder;
10408 end Proj4;
10409 @end group
10410
10411 @group
10412 -- Ada source file:
10413 with Pack;
10414 procedure Foo_Main is
10415    ...
10416 end Foo_Main;
10417 @end group
10418 @end smallexample
10419
10420 If the command is
10421 @smallexample
10422 gnatmake -PProj4 foo_main.adb -cargs -gnato
10423 @end smallexample
10424
10425 @noindent
10426 then the switches passed to the compiler for @file{foo_main.adb} are
10427 @option{-g} (contributed by the package @code{Proj4.Builder}) and
10428 @option{-gnato} (passed on the command line).
10429 When the imported package @code{Pack} is compiled, the switches used are
10430 @option{-g} from @code{Proj4.Builder}, @option{-gnata} (contributed from
10431 package @code{Proj3.Compiler}, and @option{-gnato} from the command line.
10432
10433
10434 @node Project Files and Main Subprograms
10435 @subsubsection Project Files and Main Subprograms
10436
10437 @noindent
10438 When using a project file, you can invoke @command{gnatmake}
10439 with several main subprograms, by specifying their source files on the command
10440 line.  Each of these needs to be an immediate source file of the project.
10441
10442 @smallexample
10443     gnatmake -Pprj main1 main2 main3
10444 @end smallexample
10445
10446 @noindent
10447 When using a project file, you can also invoke @command{gnatmake} without
10448 explicitly specifying any main, and the effect depends on whether you have
10449 defined the @code{Main} attribute.  This attribute has a string list value,
10450 where each element in the list is the name of a source file (the file
10451 extension is optional) containing a main subprogram.
10452
10453 If the @code{Main} attribute is defined in a project file as a non-empty
10454 string list and the switch @option{-u} is not used on the command line, then
10455 invoking @command{gnatmake} with this project file but without any main on the
10456 command line is equivalent to invoking @command{gnatmake} with all the file
10457 names in the @code{Main} attribute on the command line.
10458
10459 Example:
10460 @smallexample
10461 @group
10462    project Prj is
10463       for Main use ("main1", "main2", "main3");
10464    end Prj;
10465 @end group
10466 @end smallexample
10467
10468 @noindent
10469 With this project file, @code{"gnatmake -Pprj"} is equivalent to
10470 @code{"gnatmake -Pprj main1 main2 main3"}.
10471
10472 When the project attribute @code{Main} is not specified, or is specified
10473 as an empty string list, or when the switch @option{-u} is used on the command
10474 line, then invoking @command{gnatmake} with no main on the command line will
10475 result in all immediate sources of the project file being checked, and
10476 potentially recompiled. Depending on the presence of the switch @option{-u},
10477 sources from other project files on which the immediate sources of the main
10478 project file depend are also checked and potentially recompiled. In other
10479 words, the @option{-u} switch is applied to all of the immediate sources of themain project file.
10480
10481
10482 @node The GNAT Driver and Project Files
10483 @subsection The GNAT Driver and Project Files
10484
10485 @noindent
10486 A number of GNAT tools, other than @command{gnatmake} are project-aware:
10487 @command{gnatbind}, @command{gnatfind}, @command{gnatlink}, @command{gnatls}
10488 and @command{gnatxref}. However, none of these tools can be invoked directly
10489 with a project file switch (@code{-P}). They need to be invoke through the
10490 @command{gnat} driver.
10491
10492 The @command{gnat} driver is a front-end that accepts a number of commands and
10493 call the corresponding tool. It has been designed initially for VMS to convert
10494 VMS style qualifiers to Unix style switches, but it is now available to all
10495 the GNAT supported platforms.
10496
10497 On non VMS platforms, the @command{gnat} driver accepts the following commands
10498 (case insensitive):
10499
10500 @itemize @bullet
10501 @item
10502 BIND to invoke @command{gnatbind}
10503 @item
10504 CHOP to invoke @command{gnatchop}
10505 @item
10506 COMP or COMPILE to invoke the compiler
10507 @item
10508 ELIM to invoke @command{gnatelim}
10509 @item
10510 FIND to invoke @command{gnatfind}
10511 @item
10512 KR or KRUNCH to invoke @command{gnatkr}
10513 @item
10514 LINK to invoke @command{gnatlink}
10515 @item
10516 LS or LIST to invoke @command{gnatls}
10517 @item
10518 MAKE to invoke @command{gnatmake}
10519 @item
10520 NAME to invoke @command{gnatname}
10521 @item
10522 PREP or PREPROCESS to invoke @command{gnatprep}
10523 @item
10524 PSTA or STANDARD to invoke @command{gnatpsta}
10525 @item
10526 STUB to invoke @command{gnatstub}
10527 @item
10528 XREF to invoke @command{gnatxref}
10529 @end itemize
10530
10531 @noindent
10532 Note that the compiler is invoked using the command @command{gnatmake -f -u}.
10533
10534 @noindent
10535 Following the command, you may put switches and arguments for the invoked
10536 tool.
10537
10538 @smallexample
10539   gnat bind -C main.ali
10540   gnat ls -a main
10541   gnat chop foo.txt
10542 @end smallexample
10543
10544 @noindent
10545 In addition, for command BIND, FIND, LS or LIST, LINK and XREF, the project
10546 file related switches (@code{-P}, @code{-X} and @code{-vPx}) may be used in
10547 addition to the switches of the invoking tool.
10548
10549 @noindent
10550 For each of these command, there is possibly a package in the main project that
10551 corresponds to the invoked tool.
10552
10553 @itemize @bullet
10554 @item
10555 package @code{Binder} for command BIND (invoking @code{gnatbind})
10556
10557 @item
10558 package @code{Finder} for command FIND (invoking @code{gnatfind})
10559
10560 @item
10561 package @code{Gnatls} for command LS or LIST (invoking @code{gnatls})
10562
10563 @item
10564 package @code{Linker} for command LINK (invoking @code{gnatlink})
10565
10566 @item
10567 package @code{Cross_Reference} for command XREF (invoking @code{gnatlink})
10568
10569 @end itemize
10570
10571 @noindent
10572 Package @code{Gnatls} has a unique attribute @code{Switches}, a simple variable
10573 with a string list value. It contains switches for the invocation of
10574 @code{gnatls}.
10575
10576 @smallexample
10577 @group
10578 project Proj1 is
10579    package gnatls is
10580       for Switches use ("-a", "-v");
10581    end gnatls;
10582 end Proj1;
10583 @end group
10584 @end smallexample
10585
10586 @noindent
10587 All other packages contains a switch @code{Default_Switches}, an associative
10588 array, indexed by the programming language (case insensitive) and having a
10589 string list value. @code{Default_Switches ("Ada")} contains the switches for
10590 the invocation of the tool corresponding to the package.
10591
10592 @smallexample
10593 @group
10594 project Proj is
10595
10596    for Source_Dirs use ("./**");
10597
10598    package gnatls is
10599       for Switches use ("-a", "-v");
10600    end gnatls;
10601 @end group
10602 @group
10603
10604    package Binder is
10605       for Default_Switches ("Ada") use ("-C", "-e");
10606    end Binder;
10607 @end group
10608 @group
10609
10610    package Linker is
10611       for Default_Switches ("Ada") use ("-C");
10612    end Linker;
10613 @end group
10614 @group
10615
10616    package Finder is
10617       for Default_Switches ("Ada") use ("-a", "-f");
10618    end Finder;
10619 @end group
10620 @group
10621
10622    package Cross_Reference is
10623       for Default_Switches ("Ada") use ("-a", "-f", "-d", "-u");
10624    end Cross_Reference;
10625 end Proj;
10626 @end group
10627 @end smallexample
10628
10629 @noindent
10630 With the above project file, commands such as
10631
10632 @smallexample
10633    gnat ls -Pproj main
10634    gnat xref -Pproj main
10635    gnat bind -Pproj main.ali
10636 @end smallexample
10637
10638 @noindent
10639 will set up the environment properly and invoke the tool with the switches
10640 found in the package corresponding to the tool.
10641
10642
10643 @node Glide and Project Files
10644 @subsection Glide and Project Files
10645
10646 @noindent
10647 Glide will automatically recognize the @file{.gpr} extension for
10648 project files, and will
10649 convert them to its own internal format automatically. However, it
10650 doesn't provide a syntax-oriented editor for modifying these
10651 files.
10652 The project file will be loaded as text when you select the menu item
10653 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
10654 You can edit this text and save the @file{gpr} file;
10655 when you next select this project file in Glide it
10656 will be automatically reloaded.
10657
10658 Glide uses the @code{gnatlist} attribute in the @code{Ide} package, whose value
10659 is something like @code{powerpc-wrs-vxworks-gnatls}, to compute the
10660 cross-prefix.  From this information the correct location for the
10661 GNAT runtime, and thus also the correct cross-references, can be
10662 determined.
10663
10664
10665 @node An Extended Example
10666 @section An Extended Example
10667
10668 @noindent
10669 Suppose that we have two programs, @var{prog1} and @var{prog2}, with the sources
10670 in the respective directories. We would like to build them with a single
10671 @command{gnatmake} command, and we would like to place their object files into
10672 @file{.build} subdirectories of the source directories. Furthermore, we would
10673 like to have to have two separate subdirectories in @file{.build}  --
10674 @file{release} and @file{debug} -- which will contain the object files compiled with
10675 different set of compilation flags.
10676
10677 In other words, we have the following structure:
10678
10679 @smallexample
10680 @group
10681    main
10682      |- prog1
10683      |    |- .build
10684      |         | debug
10685      |         | release
10686      |- prog2
10687           |- .build
10688                | debug
10689                | release
10690 @end group
10691 @end smallexample
10692
10693 @noindent
10694 Here are the project files that we need to create in a directory @file{main}
10695 to maintain this structure:
10696
10697 @enumerate
10698
10699 @item We create a @code{Common} project with a package @code{Compiler} that
10700 specifies the compilation switches:
10701
10702 @smallexample
10703 File "common.gpr":
10704 @group
10705 @b{project} Common @b{is}
10706
10707    @b{for} Source_Dirs @b{use} (); -- No source files
10708 @end group
10709
10710 @group
10711    @b{type} Build_Type @b{is} ("release", "debug");
10712    Build : Build_Type := External ("BUILD", "debug");
10713 @end group
10714 @group
10715    @b{package} Compiler @b{is}
10716       @b{case} Build @b{is}
10717          @b{when} "release" =>
10718            @b{for} Default_Switches ("Ada") @b{use} ("-O2");
10719          @b{when} "debug"   =>
10720            @b{for} Default_Switches ("Ada") @b{use} ("-g");
10721       @b{end case};
10722    @b{end} Compiler;
10723
10724 @b{end} Common;
10725 @end group
10726 @end smallexample
10727
10728 @item We create separate projects for the two programs:
10729
10730 @smallexample
10731 @group
10732 File "prog1.gpr":
10733
10734 @b{with} "common";
10735 @b{project} Prog1 @b{is}
10736
10737     @b{for} Source_Dirs @b{use} ("prog1");
10738     @b{for} Object_Dir  @b{use} "prog1/.build/" & Common.Build;
10739
10740     @b{package} Compiler @b{renames} Common.Compiler;
10741
10742 @b{end} Prog1;
10743 @end group
10744 @end smallexample
10745
10746 @smallexample
10747 @group
10748 File "prog2.gpr":
10749
10750 @b{with} "common";
10751 @b{project} Prog2 @b{is}
10752
10753     @b{for} Source_Dirs @b{use} ("prog2");
10754     @b{for} Object_Dir  @b{use} "prog2/.build/" & Common.Build;
10755
10756     @b{package} Compiler @b{renames} Common.Compiler;
10757
10758 @end group
10759 @b{end} Prog2;
10760 @end smallexample
10761
10762 @item We create a wrapping project @var{Main}:
10763
10764 @smallexample
10765 @group
10766 File "main.gpr":
10767
10768 @b{with} "common";
10769 @b{with} "prog1";
10770 @b{with} "prog2";
10771 @b{project} Main @b{is}
10772
10773    @b{package} Compiler @b{renames} Common.Compiler;
10774
10775 @b{end} Main;
10776 @end group
10777 @end smallexample
10778
10779 @item Finally we need to create a dummy procedure that @code{with}s (either
10780 explicitly or implicitly) all the sources of our two programs.
10781
10782 @end enumerate
10783
10784 @noindent
10785 Now we can build the programs using the command
10786
10787 @smallexample
10788    gnatmake -Pmain dummy
10789 @end smallexample
10790
10791 @noindent
10792 for the Debug mode, or
10793
10794 @smallexample
10795    gnatmake -Pmain -XBUILD=release
10796 @end smallexample
10797
10798 @noindent
10799 for the Release mode.
10800
10801
10802 @c ********************************
10803 @c * Project File Complete Syntax *
10804 @c ********************************
10805
10806 @node Project File Complete Syntax
10807 @section Project File Complete Syntax
10808
10809 @smallexample
10810 project ::=
10811   context_clause project_declaration
10812
10813 context_clause ::=
10814   @{with_clause@}
10815
10816 with_clause ::=
10817   @b{with} literal_string @{ , literal_string @} ;
10818
10819 project_declaration ::=
10820   @b{project} <project_>simple_name [ @b{extends} literal_string ] @b{is}
10821     @{declarative_item@}
10822   @b{end} <project_>simple_name;
10823
10824 declarative_item ::=
10825   package_declaration |
10826   typed_string_declaration |
10827   other_declarative_item
10828
10829 package_declaration ::=
10830   @b{package} <package_>simple_name package_completion
10831
10832 package_completion ::=
10833   package_body | package_renaming
10834
10835 package body ::=
10836   @b{is}
10837     @{other_declarative_item@}
10838   @b{end} <package_>simple_name ;
10839
10840 package_renaming ::==
10841   @b{renames} <project_>simple_name.<package_>simple_name ;
10842
10843 typed_string_declaration ::=
10844   @b{type} <typed_string_>_simple_name @b{is}
10845    ( literal_string @{, literal_string@} );
10846
10847 other_declarative_item ::=
10848   attribute_declaration |
10849   typed_variable_declaration |
10850   variable_declaration |
10851   case_construction
10852
10853 attribute_declaration ::=
10854   @b{for} attribute @b{use} expression ;
10855
10856 attribute ::=
10857   <simple_attribute_>simple_name |
10858   <associative_array_attribute_>simple_name ( literal_string )
10859
10860 typed_variable_declaration ::=
10861   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
10862
10863 variable_declaration ::=
10864   <variable_>simple_name := expression;
10865
10866 expression ::=
10867   term @{& term@}
10868
10869 term ::=
10870   literal_string |
10871   string_list |
10872   <variable_>name |
10873   external_value |
10874   attribute_reference
10875
10876 literal_string ::=
10877   (same as Ada)
10878
10879 string_list ::=
10880   ( <string_>expression @{ , <string_>expression @} )
10881
10882 external_value ::=
10883   @b{external} ( literal_string [, literal_string] )
10884
10885 attribute_reference ::=
10886   attribute_parent ' <simple_attribute_>simple_name [ ( literal_string ) ]
10887
10888 attribute_parent ::=
10889   @b{project} |
10890   <project_or_package>simple_name |
10891   <project_>simple_name . <package_>simple_name
10892
10893 case_construction ::=
10894   @b{case} <typed_variable_>name @b{is}
10895     @{case_item@}
10896   @b{end case} ;
10897
10898 case_item ::=
10899   @b{when} discrete_choice_list => @{case_construction | attribute_declaration@}
10900
10901 discrete_choice_list ::=
10902   literal_string @{| literal_string@}
10903
10904 name ::=
10905   simple_name @{. simple_name@}
10906
10907 simple_name ::=
10908   identifier (same as Ada)
10909
10910 @end smallexample
10911
10912
10913 @node Elaboration Order Handling in GNAT
10914 @chapter Elaboration Order Handling in GNAT
10915 @cindex Order of elaboration
10916 @cindex Elaboration control
10917
10918 @menu
10919 * Elaboration Code in Ada 95::
10920 * Checking the Elaboration Order in Ada 95::
10921 * Controlling the Elaboration Order in Ada 95::
10922 * Controlling Elaboration in GNAT - Internal Calls::
10923 * Controlling Elaboration in GNAT - External Calls::
10924 * Default Behavior in GNAT - Ensuring Safety::
10925 * Elaboration Issues for Library Tasks::
10926 * Mixing Elaboration Models::
10927 * What to Do If the Default Elaboration Behavior Fails::
10928 * Elaboration for Access-to-Subprogram Values::
10929 * Summary of Procedures for Elaboration Control::
10930 * Other Elaboration Order Considerations::
10931 @end menu
10932
10933 @noindent
10934 This chapter describes the handling of elaboration code in Ada 95 and
10935 in GNAT, and discusses how the order of elaboration of program units can
10936 be controlled in GNAT, either automatically or with explicit programming
10937 features.
10938
10939 @node Elaboration Code in Ada 95
10940 @section Elaboration Code in Ada 95
10941
10942 @noindent
10943 Ada 95 provides rather general mechanisms for executing code at elaboration
10944 time, that is to say before the main program starts executing. Such code arises
10945 in three contexts:
10946
10947 @table @asis
10948 @item Initializers for variables.
10949 Variables declared at the library level, in package specs or bodies, can
10950 require initialization that is performed at elaboration time, as in:
10951 @smallexample
10952 @cartouche
10953 Sqrt_Half : Float := Sqrt (0.5);
10954 @end cartouche
10955 @end smallexample
10956
10957 @item Package initialization code
10958 Code in a @code{BEGIN-END} section at the outer level of a package body is
10959 executed as part of the package body elaboration code.
10960
10961 @item Library level task allocators
10962 Tasks that are declared using task allocators at the library level
10963 start executing immediately and hence can execute at elaboration time.
10964 @end table
10965
10966 @noindent
10967 Subprogram calls are possible in any of these contexts, which means that
10968 any arbitrary part of the program may be executed as part of the elaboration
10969 code. It is even possible to write a program which does all its work at
10970 elaboration time, with a null main program, although stylistically this
10971 would usually be considered an inappropriate way to structure
10972 a program.
10973
10974 An important concern arises in the context of elaboration code:
10975 we have to be sure that it is executed in an appropriate order. What we
10976 have is a series of elaboration code sections, potentially one section
10977 for each unit in the program. It is important that these execute
10978 in the correct order. Correctness here means that, taking the above
10979 example of the declaration of @code{Sqrt_Half},
10980 if some other piece of
10981 elaboration code references @code{Sqrt_Half},
10982 then it must run after the
10983 section of elaboration code that contains the declaration of
10984 @code{Sqrt_Half}.
10985
10986 There would never be any order of elaboration problem if we made a rule
10987 that whenever you @code{with} a unit, you must elaborate both the spec and body
10988 of that unit before elaborating the unit doing the @code{with}'ing:
10989
10990 @smallexample
10991 @group
10992 @cartouche
10993 @b{with} Unit_1;
10994 @b{package} Unit_2 @b{is} ...
10995 @end cartouche
10996 @end group
10997 @end smallexample
10998
10999 @noindent
11000 would require that both the body and spec of @code{Unit_1} be elaborated
11001 before the spec of @code{Unit_2}. However, a rule like that would be far too
11002 restrictive. In particular, it would make it impossible to have routines
11003 in separate packages that were mutually recursive.
11004
11005 You might think that a clever enough compiler could look at the actual
11006 elaboration code and determine an appropriate correct order of elaboration,
11007 but in the general case, this is not possible. Consider the following
11008 example.
11009
11010 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
11011 that references
11012 the variable @code{Sqrt_1}, which is declared in the elaboration code
11013 of the body of @code{Unit_1}:
11014
11015 @smallexample
11016 @cartouche
11017 Sqrt_1 : Float := Sqrt (0.1);
11018 @end cartouche
11019 @end smallexample
11020
11021 @noindent
11022 The elaboration code of the body of @code{Unit_1} also contains:
11023
11024 @smallexample
11025 @group
11026 @cartouche
11027 @b{if} expression_1 = 1 @b{then}
11028    Q := Unit_2.Func_2;
11029 @b{end if};
11030 @end cartouche
11031 @end group
11032 @end smallexample
11033
11034 @noindent
11035 @code{Unit_2} is exactly parallel,
11036 it has a procedure @code{Func_2} that references
11037 the variable @code{Sqrt_2}, which is declared in the elaboration code of
11038 the body @code{Unit_2}:
11039
11040 @smallexample
11041 @cartouche
11042 Sqrt_2 : Float := Sqrt (0.1);
11043 @end cartouche
11044 @end smallexample
11045
11046 @noindent
11047 The elaboration code of the body of @code{Unit_2} also contains:
11048
11049 @smallexample
11050 @group
11051 @cartouche
11052 @b{if} expression_2 = 2 @b{then}
11053    Q := Unit_1.Func_1;
11054 @b{end if};
11055 @end cartouche
11056 @end group
11057 @end smallexample
11058
11059 @noindent
11060 Now the question is, which of the following orders of elaboration is
11061 acceptable:
11062
11063 @smallexample
11064 @group
11065 Spec of Unit_1
11066 Spec of Unit_2
11067 Body of Unit_1
11068 Body of Unit_2
11069 @end group
11070 @end smallexample
11071
11072 @noindent
11073 or
11074
11075 @smallexample
11076 @group
11077 Spec of Unit_2
11078 Spec of Unit_1
11079 Body of Unit_2
11080 Body of Unit_1
11081 @end group
11082 @end smallexample
11083
11084 @noindent
11085 If you carefully analyze the flow here, you will see that you cannot tell
11086 at compile time the answer to this question.
11087 If @code{expression_1} is not equal to 1,
11088 and @code{expression_2} is not equal to 2,
11089 then either order is acceptable, because neither of the function calls is
11090 executed. If both tests evaluate to true, then neither order is acceptable
11091 and in fact there is no correct order.
11092
11093 If one of the two expressions is true, and the other is false, then one
11094 of the above orders is correct, and the other is incorrect. For example,
11095 if @code{expression_1} = 1 and @code{expression_2} /= 2,
11096 then the call to @code{Func_2}
11097 will occur, but not the call to @code{Func_1.}
11098 This means that it is essential
11099 to elaborate the body of @code{Unit_1} before
11100 the body of @code{Unit_2}, so the first
11101 order of elaboration is correct and the second is wrong.
11102
11103 By making @code{expression_1} and @code{expression_2}
11104 depend on input data, or perhaps
11105 the time of day, we can make it impossible for the compiler or binder
11106 to figure out which of these expressions will be true, and hence it
11107 is impossible to guarantee a safe order of elaboration at run time.
11108
11109 @node Checking the Elaboration Order in Ada 95
11110 @section Checking the Elaboration Order in Ada 95
11111
11112 @noindent
11113 In some languages that involve the same kind of elaboration problems,
11114 e.g. Java and C++, the programmer is expected to worry about these
11115 ordering problems himself, and it is common to
11116 write a program in which an incorrect elaboration order  gives
11117 surprising results, because it references variables before they
11118 are initialized.
11119 Ada 95 is designed to be a safe language, and a programmer-beware approach is
11120 clearly not sufficient. Consequently, the language provides three lines
11121 of defense:
11122
11123 @table @asis
11124 @item Standard rules
11125 Some standard rules restrict the possible choice of elaboration
11126 order. In particular, if you @code{with} a unit, then its spec is always
11127 elaborated before the unit doing the @code{with}. Similarly, a parent
11128 spec is always elaborated before the child spec, and finally
11129 a spec is always elaborated before its corresponding body.
11130
11131 @item Dynamic elaboration checks
11132 @cindex Elaboration checks
11133 @cindex Checks, elaboration
11134 Dynamic checks are made at run time, so that if some entity is accessed
11135 before it is elaborated (typically  by means of a subprogram call)
11136 then the exception (@code{Program_Error}) is raised.
11137
11138 @item Elaboration control
11139 Facilities are provided for the programmer to specify the desired order
11140 of elaboration.
11141 @end table
11142
11143 Let's look at these facilities in more detail. First, the rules for
11144 dynamic checking. One possible rule would be simply to say that the
11145 exception is raised if you access a variable which has not yet been
11146 elaborated. The trouble with this approach is that it could require
11147 expensive checks on every variable reference. Instead Ada 95 has two
11148 rules which are a little more restrictive, but easier to check, and
11149 easier to state:
11150
11151 @table @asis
11152 @item Restrictions on calls
11153 A subprogram can only be called at elaboration time if its body
11154 has been elaborated. The rules for elaboration given above guarantee
11155 that the spec of the subprogram has been elaborated before the
11156 call, but not the body. If this rule is violated, then the
11157 exception @code{Program_Error} is raised.
11158
11159 @item Restrictions on instantiations
11160 A generic unit can only be instantiated if the body of the generic
11161 unit has been elaborated. Again, the rules for elaboration given above
11162 guarantee that the spec of the generic unit has been elaborated
11163 before the instantiation, but not the body. If this rule is
11164 violated, then the exception @code{Program_Error} is raised.
11165 @end table
11166
11167 @noindent
11168 The idea is that if the body has been elaborated, then any variables
11169 it references must have been elaborated; by checking for the body being
11170 elaborated we guarantee that none of its references causes any
11171 trouble. As we noted above, this is a little too restrictive, because a
11172 subprogram that has no non-local references in its body may in fact be safe
11173 to call. However, it really would be unsafe to rely on this, because
11174 it would mean that the caller was aware of details of the implementation
11175 in the body. This goes against the basic tenets of Ada.
11176
11177 A plausible implementation can be described as follows.
11178 A Boolean variable is associated with each subprogram
11179 and each generic unit. This variable is initialized to False, and is set to
11180 True at the point body is elaborated. Every call or instantiation checks the
11181 variable, and raises @code{Program_Error} if the variable is False.
11182
11183 Note that one might think that it would be good enough to have one Boolean
11184 variable for each package, but that would not deal with cases of trying
11185 to call a body in the same package as the call
11186 that has not been elaborated yet.
11187 Of course a compiler may be able to do enough analysis to optimize away
11188 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
11189 does such optimizations, but still the easiest conceptual model is to
11190 think of there being one variable per subprogram.
11191
11192 @node Controlling the Elaboration Order in Ada 95
11193 @section Controlling the Elaboration Order in Ada 95
11194
11195 @noindent
11196 In the previous section we discussed the rules in Ada 95 which ensure
11197 that @code{Program_Error} is raised if an incorrect elaboration order is
11198 chosen. This prevents erroneous executions, but we need mechanisms to
11199 specify a correct execution and avoid the exception altogether.
11200 To achieve this, Ada 95 provides a number of features for controlling
11201 the order of elaboration. We discuss these features in this section.
11202
11203 First, there are several ways of indicating to the compiler that a given
11204 unit has no elaboration problems:
11205
11206 @table @asis
11207 @item packages that do not require a body
11208 In Ada 95, a library package that does not require a body does not permit
11209 a body. This means that if we have a such a package, as in:
11210
11211 @smallexample
11212 @group
11213 @cartouche
11214 @b{package} Definitions @b{is}
11215    @b{generic}
11216       @b{type} m @b{is new} integer;
11217    @b{package} Subp @b{is}
11218       @b{type} a @b{is array} (1 .. 10) @b{of} m;
11219       @b{type} b @b{is array} (1 .. 20) @b{of} m;
11220    @b{end} Subp;
11221 @b{end} Definitions;
11222 @end cartouche
11223 @end group
11224 @end smallexample
11225
11226 @noindent
11227 A package that @code{with}'s @code{Definitions} may safely instantiate
11228 @code{Definitions.Subp} because the compiler can determine that there
11229 definitely is no package body to worry about in this case
11230
11231 @item pragma Pure
11232 @cindex pragma Pure
11233 @findex Pure
11234 Places sufficient restrictions on a unit to guarantee that
11235 no call to any subprogram in the unit can result in an
11236 elaboration problem. This means that the compiler does not need
11237 to worry about the point of elaboration of such units, and in
11238 particular, does not need to check any calls to any subprograms
11239 in this unit.
11240
11241 @item pragma Preelaborate
11242 @findex Preelaborate
11243 @cindex pragma Preelaborate
11244 This pragma places slightly less stringent restrictions on a unit than
11245 does pragma Pure,
11246 but these restrictions are still sufficient to ensure that there
11247 are no elaboration problems with any calls to the unit.
11248
11249 @item pragma Elaborate_Body
11250 @findex Elaborate_Body
11251 @cindex pragma Elaborate_Body
11252 This pragma requires that the body of a unit be elaborated immediately
11253 after its spec. Suppose a unit @code{A} has such a pragma,
11254 and unit @code{B} does
11255 a @code{with} of unit @code{A}. Recall that the standard rules require
11256 the spec of unit @code{A}
11257 to be elaborated before the @code{with}'ing unit; given the pragma in
11258 @code{A}, we also know that the body of @code{A}
11259 will be elaborated before @code{B}, so
11260 that calls to @code{A} are safe and do not need a check.
11261 @end table
11262
11263 @noindent
11264 Note that,
11265 unlike pragma @code{Pure} and pragma @code{Preelaborate},
11266 the use of
11267 @code{Elaborate_Body} does not guarantee that the program is
11268 free of elaboration problems, because it may not be possible
11269 to satisfy the requested elaboration order.
11270 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
11271 If a programmer
11272 marks @code{Unit_1} as @code{Elaborate_Body},
11273 and not @code{Unit_2,} then the order of
11274 elaboration will be:
11275
11276 @smallexample
11277 @group
11278 Spec of Unit_2
11279 Spec of Unit_1
11280 Body of Unit_1
11281 Body of Unit_2
11282 @end group
11283 @end smallexample
11284
11285 @noindent
11286 Now that means that the call to @code{Func_1} in @code{Unit_2}
11287 need not be checked,
11288 it must be safe. But the call to @code{Func_2} in
11289 @code{Unit_1} may still fail if
11290 @code{Expression_1} is equal to 1,
11291 and the programmer must still take
11292 responsibility for this not being the case.
11293
11294 If all units carry a pragma @code{Elaborate_Body}, then all problems are
11295 eliminated, except for calls entirely within a body, which are
11296 in any case fully under programmer control. However, using the pragma
11297 everywhere is not always possible.
11298 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
11299 we marked both of them as having pragma @code{Elaborate_Body}, then
11300 clearly there would be no possible elaboration order.
11301
11302 The above pragmas allow a server to guarantee safe use by clients, and
11303 clearly this is the preferable approach. Consequently a good rule in
11304 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
11305 and if this is not possible,
11306 mark them as @code{Elaborate_Body} if possible.
11307 As we have seen, there are situations where neither of these
11308 three pragmas can be used.
11309 So we also provide methods for clients to control the
11310 order of elaboration of the servers on which they depend:
11311
11312 @table @asis
11313 @item pragma Elaborate (unit)
11314 @findex Elaborate
11315 @cindex pragma Elaborate
11316 This pragma is placed in the context clause, after a @code{with} clause,
11317 and it requires that the body of the named unit be elaborated before
11318 the unit in which the pragma occurs. The idea is to use this pragma
11319 if the current unit calls at elaboration time, directly or indirectly,
11320 some subprogram in the named unit.
11321
11322 @item pragma Elaborate_All (unit)
11323 @findex Elaborate_All
11324 @cindex pragma Elaborate_All
11325 This is a stronger version of the Elaborate pragma. Consider the
11326 following example:
11327
11328 @smallexample
11329 Unit A @code{with}'s unit B and calls B.Func in elab code
11330 Unit B @code{with}'s unit C, and B.Func calls C.Func
11331 @end smallexample
11332
11333 @noindent
11334 Now if we put a pragma @code{Elaborate (B)}
11335 in unit @code{A}, this ensures that the
11336 body of @code{B} is elaborated before the call, but not the
11337 body of @code{C}, so
11338 the call to @code{C.Func} could still cause @code{Program_Error} to
11339 be raised.
11340
11341 The effect of a pragma @code{Elaborate_All} is stronger, it requires
11342 not only that the body of the named unit be elaborated before the
11343 unit doing the @code{with}, but also the bodies of all units that the
11344 named unit uses, following @code{with} links transitively. For example,
11345 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
11346 then it requires
11347 not only that the body of @code{B} be elaborated before @code{A},
11348 but also the
11349 body of @code{C}, because @code{B} @code{with}'s @code{C}.
11350 @end table
11351
11352 @noindent
11353 We are now in a position to give a usage rule in Ada 95 for avoiding
11354 elaboration problems, at least if dynamic dispatching and access to
11355 subprogram values are not used. We will handle these cases separately
11356 later.
11357
11358 The rule is simple. If a unit has elaboration code that can directly or
11359 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
11360 a generic unit in a @code{with}'ed unit,
11361 then if the @code{with}'ed unit does not have
11362 pragma @code{Pure} or @code{Preelaborate}, then the client should have
11363 a pragma @code{Elaborate_All}
11364 for the @code{with}'ed unit. By following this rule a client is
11365 assured that calls can be made without risk of an exception.
11366 If this rule is not followed, then a program may be in one of four
11367 states:
11368
11369 @table @asis
11370 @item No order exists
11371 No order of elaboration exists which follows the rules, taking into
11372 account any @code{Elaborate}, @code{Elaborate_All},
11373 or @code{Elaborate_Body} pragmas. In
11374 this case, an Ada 95 compiler must diagnose the situation at bind
11375 time, and refuse to build an executable program.
11376
11377 @item One or more orders exist, all incorrect
11378 One or more acceptable elaboration orders exists, and all of them
11379 generate an elaboration order problem. In this case, the binder
11380 can build an executable program, but @code{Program_Error} will be raised
11381 when the program is run.
11382
11383 @item Several orders exist, some right, some incorrect
11384 One or more acceptable elaboration orders exists, and some of them
11385 work, and some do not. The programmer has not controlled
11386 the order of elaboration, so the binder may or may not pick one of
11387 the correct orders, and the program may or may not raise an
11388 exception when it is run. This is the worst case, because it means
11389 that the program may fail when moved to another compiler, or even
11390 another version of the same compiler.
11391
11392 @item One or more orders exists, all correct
11393 One ore more acceptable elaboration orders exist, and all of them
11394 work. In this case the program runs successfully. This state of
11395 affairs can be guaranteed by following the rule we gave above, but
11396 may be true even if the rule is not followed.
11397 @end table
11398
11399 @noindent
11400 Note that one additional advantage of following our Elaborate_All rule
11401 is that the program continues to stay in the ideal (all orders OK) state
11402 even if maintenance
11403 changes some bodies of some subprograms. Conversely, if a program that does
11404 not follow this rule happens to be safe at some point, this state of affairs
11405 may deteriorate silently as a result of maintenance changes.
11406
11407 You may have noticed that the above discussion did not mention
11408 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
11409 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
11410 code in the body makes calls to some other unit, so it is still necessary
11411 to use @code{Elaborate_All} on such units.
11412
11413 @node Controlling Elaboration in GNAT - Internal Calls
11414 @section Controlling Elaboration in GNAT - Internal Calls
11415
11416 @noindent
11417 In the case of internal calls, i.e. calls within a single package, the
11418 programmer has full control over the order of elaboration, and it is up
11419 to the programmer to elaborate declarations in an appropriate order. For
11420 example writing:
11421
11422 @smallexample
11423 @group
11424 @cartouche
11425 @b{function} One @b{return} Float;
11426
11427 Q : Float := One;
11428
11429 @b{function} One @b{return} Float @b{is}
11430 @b{begin}
11431      return 1.0;
11432 @b{end} One;
11433 @end cartouche
11434 @end group
11435 @end smallexample
11436
11437 @noindent
11438 will obviously raise @code{Program_Error} at run time, because function
11439 One will be called before its body is elaborated. In this case GNAT will
11440 generate a warning that the call will raise @code{Program_Error}:
11441
11442 @smallexample
11443 @group
11444 @cartouche
11445  1. procedure y is
11446  2.    function One return Float;
11447  3.
11448  4.    Q : Float := One;
11449                     |
11450     >>> warning: cannot call "One" before body is elaborated
11451     >>> warning: Program_Error will be raised at run time
11452
11453  5.
11454  6.    function One return Float is
11455  7.    begin
11456  8.         return 1.0;
11457  9.    end One;
11458 10.
11459 11. begin
11460 12.    null;
11461 13. end;
11462 @end cartouche
11463 @end group
11464 @end smallexample
11465
11466 @noindent
11467 Note that in this particular case, it is likely that the call is safe, because
11468 the function @code{One} does not access any global variables.
11469 Nevertheless in Ada 95, we do not want the validity of the check to depend on
11470 the contents of the body (think about the separate compilation case), so this
11471 is still wrong, as we discussed in the previous sections.
11472
11473 The error is easily corrected by rearranging the declarations so that the
11474 body of One appears before the declaration containing the call
11475 (note that in Ada 95,
11476 declarations can appear in any order, so there is no restriction that
11477 would prevent this reordering, and if we write:
11478
11479 @smallexample
11480 @group
11481 @cartouche
11482 @b{function} One @b{return} Float;
11483
11484 @b{function} One @b{return} Float @b{is}
11485 @b{begin}
11486      return 1.0;
11487 @b{end} One;
11488
11489 Q : Float := One;
11490 @end cartouche
11491 @end group
11492 @end smallexample
11493
11494 @noindent
11495 then all is well, no warning is generated, and no
11496 @code{Program_Error} exception
11497 will be raised.
11498 Things are more complicated when a chain of subprograms is executed:
11499
11500 @smallexample
11501 @group
11502 @cartouche
11503 @b{function} A @b{return} Integer;
11504 @b{function} B @b{return} Integer;
11505 @b{function} C @b{return} Integer;
11506
11507 @b{function} B @b{return} Integer @b{is begin return} A; @b{end};
11508 @b{function} C @b{return} Integer @b{is begin return} B; @b{end};
11509
11510 X : Integer := C;
11511
11512 @b{function} A @b{return} Integer @b{is begin return} 1; @b{end};
11513 @end cartouche
11514 @end group
11515 @end smallexample
11516
11517 @noindent
11518 Now the call to @code{C}
11519 at elaboration time in the declaration of @code{X} is correct, because
11520 the body of @code{C} is already elaborated,
11521 and the call to @code{B} within the body of
11522 @code{C} is correct, but the call
11523 to @code{A} within the body of @code{B} is incorrect, because the body
11524 of @code{A} has not been elaborated, so @code{Program_Error}
11525 will be raised on the call to @code{A}.
11526 In this case GNAT will generate a
11527 warning that @code{Program_Error} may be
11528 raised at the point of the call. Let's look at the warning:
11529
11530 @smallexample
11531 @group
11532 @cartouche
11533  1. procedure x is
11534  2.    function A return Integer;
11535  3.    function B return Integer;
11536  4.    function C return Integer;
11537  5.
11538  6.    function B return Integer is begin return A; end;
11539                                                     |
11540     >>> warning: call to "A" before body is elaborated may
11541                  raise Program_Error
11542     >>> warning: "B" called at line 7
11543     >>> warning: "C" called at line 9
11544
11545  7.    function C return Integer is begin return B; end;
11546  8.
11547  9.    X : Integer := C;
11548 10.
11549 11.    function A return Integer is begin return 1; end;
11550 12.
11551 13. begin
11552 14.    null;
11553 15. end;
11554 @end cartouche
11555 @end group
11556 @end smallexample
11557
11558 @noindent
11559 Note that the message here says "may raise", instead of the direct case,
11560 where the message says "will be raised". That's because whether
11561 @code{A} is
11562 actually called depends in general on run-time flow of control.
11563 For example, if the body of @code{B} said
11564
11565 @smallexample
11566 @group
11567 @cartouche
11568 @b{function} B @b{return} Integer @b{is}
11569 @b{begin}
11570    @b{if} some-condition-depending-on-input-data @b{then}
11571       @b{return} A;
11572    @b{else}
11573       @b{return} 1;
11574    @b{end if};
11575 @b{end} B;
11576 @end cartouche
11577 @end group
11578 @end smallexample
11579
11580 @noindent
11581 then we could not know until run time whether the incorrect call to A would
11582 actually occur, so @code{Program_Error} might
11583 or might not be raised. It is possible for a compiler to
11584 do a better job of analyzing bodies, to
11585 determine whether or not @code{Program_Error}
11586 might be raised, but it certainly
11587 couldn't do a perfect job (that would require solving the halting problem
11588 and is provably impossible), and because this is a warning anyway, it does
11589 not seem worth the effort to do the analysis. Cases in which it
11590 would be relevant are rare.
11591
11592 In practice, warnings of either of the forms given
11593 above will usually correspond to
11594 real errors, and should be examined carefully and eliminated.
11595 In the rare case where a warning is bogus, it can be suppressed by any of
11596 the following methods:
11597
11598 @itemize @bullet
11599 @item
11600 Compile with the @option{-gnatws} switch set
11601
11602 @item
11603 Suppress @code{Elaboration_Checks} for the called subprogram
11604
11605 @item
11606 Use pragma @code{Warnings_Off} to turn warnings off for the call
11607 @end itemize
11608
11609 @noindent
11610 For the internal elaboration check case,
11611 GNAT by default generates the
11612 necessary run-time checks to ensure
11613 that @code{Program_Error} is raised if any
11614 call fails an elaboration check. Of course this can only happen if a
11615 warning has been issued as described above. The use of pragma
11616 @code{Suppress (Elaboration_Checks)} may (but is not guaranteed to) suppress
11617 some of these checks, meaning that it may be possible (but is not
11618 guaranteed) for a program to be able to call a subprogram whose body
11619 is not yet elaborated, without raising a @code{Program_Error} exception.
11620
11621 @node Controlling Elaboration in GNAT - External Calls
11622 @section Controlling Elaboration in GNAT - External Calls
11623
11624 @noindent
11625 The previous section discussed the case in which the execution of a
11626 particular thread of elaboration code occurred entirely within a
11627 single unit. This is the easy case to handle, because a programmer
11628 has direct and total control over the order of elaboration, and
11629 furthermore, checks need only be generated in cases which are rare
11630 and which the compiler can easily detect.
11631 The situation is more complex when separate compilation is taken into account.
11632 Consider the following:
11633
11634 @smallexample
11635 @cartouche
11636 @group
11637 @b{package} Math @b{is}
11638    @b{function} Sqrt (Arg : Float) @b{return} Float;
11639 @b{end} Math;
11640
11641 @b{package body} Math @b{is}
11642    @b{function} Sqrt (Arg : Float) @b{return} Float @b{is}
11643    @b{begin}
11644          ...
11645    @b{end} Sqrt;
11646 @b{end} Math;
11647 @end group
11648 @group
11649 @b{with} Math;
11650 @b{package} Stuff @b{is}
11651    X : Float := Math.Sqrt (0.5);
11652 @b{end} Stuff;
11653
11654 @b{with} Stuff;
11655 @b{procedure} Main @b{is}
11656 @b{begin}
11657    ...
11658 @b{end} Main;
11659 @end group
11660 @end cartouche
11661 @end smallexample
11662
11663 @noindent
11664 where @code{Main} is the main program. When this program is executed, the
11665 elaboration code must first be executed, and one of the jobs of the
11666 binder is to determine the order in which the units of a program are
11667 to be elaborated. In this case we have four units: the spec and body
11668 of @code{Math},
11669 the spec of @code{Stuff} and the body of @code{Main}).
11670 In what order should the four separate sections of elaboration code
11671 be executed?
11672
11673 There are some restrictions in the order of elaboration that the binder
11674 can choose. In particular, if unit U has a @code{with}
11675 for a package @code{X}, then you
11676 are assured that the spec of @code{X}
11677 is elaborated before U , but you are
11678 not assured that the body of @code{X}
11679 is elaborated before U.
11680 This means that in the above case, the binder is allowed to choose the
11681 order:
11682
11683 @smallexample
11684 spec of Math
11685 spec of Stuff
11686 body of Math
11687 body of Main
11688 @end smallexample
11689
11690 @noindent
11691 but that's not good, because now the call to @code{Math.Sqrt}
11692 that happens during
11693 the elaboration of the @code{Stuff}
11694 spec happens before the body of @code{Math.Sqrt} is
11695 elaborated, and hence causes @code{Program_Error} exception to be raised.
11696 At first glance, one might say that the binder is misbehaving, because
11697 obviously you want to elaborate the body of something you @code{with}
11698 first, but
11699 that is not a general rule that can be followed in all cases. Consider
11700
11701 @smallexample
11702 @group
11703 @cartouche
11704 @b{package} X @b{is} ...
11705
11706 @b{package} Y @b{is} ...
11707
11708 @b{with} X;
11709 @b{package body} Y @b{is} ...
11710
11711 @b{with} Y;
11712 @b{package body} X @b{is} ...
11713 @end cartouche
11714 @end group
11715 @end smallexample
11716
11717 @noindent
11718 This is a common arrangement, and, apart from the order of elaboration
11719 problems that might arise in connection with elaboration code, this works fine.
11720 A rule that says that you must first elaborate the body of anything you
11721 @code{with} cannot work in this case:
11722 the body of @code{X} @code{with}'s @code{Y},
11723 which means you would have to
11724 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
11725 which means
11726 you have to elaborate the body of @code{X} first, but ... and we have a
11727 loop that cannot be broken.
11728
11729 It is true that the binder can in many cases guess an order of elaboration
11730 that is unlikely to cause a @code{Program_Error}
11731 exception to be raised, and it tries to do so (in the
11732 above example of @code{Math/Stuff/Spec}, the GNAT binder will
11733 by default
11734 elaborate the body of @code{Math} right after its spec, so all will be well).
11735
11736 However, a program that blindly relies on the binder to be helpful can
11737 get into trouble, as we discussed in the previous sections, so
11738 GNAT
11739 provides a number of facilities for assisting the programmer in
11740 developing programs that are robust with respect to elaboration order.
11741
11742 @node Default Behavior in GNAT - Ensuring Safety
11743 @section Default Behavior in GNAT - Ensuring Safety
11744
11745 @noindent
11746 The default behavior in GNAT ensures elaboration safety. In its
11747 default mode GNAT implements the
11748 rule we previously described as the right approach. Let's restate it:
11749
11750 @itemize
11751 @item
11752 @emph{If a unit has elaboration code that can directly or indirectly make a
11753 call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit
11754 in a @code{with}'ed unit, then if the @code{with}'ed unit
11755 does not have pragma @code{Pure} or
11756 @code{Preelaborate}, then the client should have an
11757 @code{Elaborate_All} for the @code{with}'ed unit.}
11758 @end itemize
11759
11760 @noindent
11761 By following this rule a client
11762 is assured that calls and instantiations can be made without risk of an exception.
11763
11764 In this mode GNAT traces all calls that are potentially made from
11765 elaboration code, and puts in any missing implicit @code{Elaborate_All}
11766 pragmas.
11767 The advantage of this approach is that no elaboration problems
11768 are possible if the binder can find an elaboration order that is
11769 consistent with these implicit @code{Elaborate_All} pragmas. The
11770 disadvantage of this approach is that no such order may exist.
11771
11772 If the binder does not generate any diagnostics, then it means that it
11773 has found an elaboration order that is guaranteed to be safe. However,
11774 the binder may still be relying on implicitly generated
11775 @code{Elaborate_All} pragmas so portability to other compilers than
11776 GNAT is not guaranteed.
11777
11778 If it is important to guarantee portability, then the compilations should
11779 use the
11780 @option{-gnatwl}
11781 (warn on elaboration problems) switch. This will cause warning messages
11782 to be generated indicating the missing @code{Elaborate_All} pragmas.
11783 Consider the following source program:
11784
11785 @smallexample
11786 @group
11787 @cartouche
11788 @b{with} k;
11789 @b{package} j @b{is}
11790   m : integer := k.r;
11791 @b{end};
11792 @end cartouche
11793 @end group
11794 @end smallexample
11795
11796 @noindent
11797 where it is clear that there
11798 should be a pragma @code{Elaborate_All}
11799 for unit @code{k}. An implicit pragma will be generated, and it is
11800 likely that the binder will be able to honor it. However,
11801 it is safer to include the pragma explicitly in the source. If this
11802 unit is compiled with the
11803 @option{-gnatwl}
11804 switch, then the compiler outputs a warning:
11805
11806 @smallexample
11807 @group
11808 @cartouche
11809 1. with k;
11810 2. package j is
11811 3.   m : integer := k.r;
11812                      |
11813    >>> warning: call to "r" may raise Program_Error
11814    >>> warning: missing pragma Elaborate_All for "k"
11815
11816 4. end;
11817 @end cartouche
11818 @end group
11819 @end smallexample
11820
11821 @noindent
11822 and these warnings can be used as a guide for supplying manually
11823 the missing pragmas.
11824
11825 This default mode is more restrictive than the Ada Reference
11826 Manual, and it is possible to construct programs which will compile
11827 using the dynamic model described there, but will run into a
11828 circularity using the safer static model we have described.
11829
11830 Of course any Ada compiler must be able to operate in a mode
11831 consistent with the requirements of the Ada Reference Manual,
11832 and in particular must have the capability of implementing the
11833 standard dynamic model of elaboration with run-time checks.
11834
11835 In GNAT, this standard mode can be achieved either by the use of
11836 the @option{-gnatE} switch on the compiler (@code{gcc} or @code{gnatmake})
11837 command, or by the use of the configuration pragma:
11838
11839 @smallexample
11840 pragma Elaboration_Checks (RM);
11841 @end smallexample
11842
11843 @noindent
11844 Either approach will cause the unit affected to be compiled using the
11845 standard dynamic run-time elaboration checks described in the Ada
11846 Reference Manual. The static model is generally preferable, since it
11847 is clearly safer to rely on compile and link time checks rather than
11848 run-time checks. However, in the case of legacy code, it may be
11849 difficult to meet the requirements of the static model. This
11850 issue is further discussed in
11851 @ref{What to Do If the Default Elaboration Behavior Fails}.
11852
11853 Note that the static model provides a strict subset of the allowed
11854 behavior and programs of the Ada Reference Manual, so if you do
11855 adhere to the static model and no circularities exist,
11856 then you are assured that your program will
11857 work using the dynamic model.
11858
11859 @node Elaboration Issues for Library Tasks
11860 @section Elaboration Issues for Library Tasks
11861 @cindex Library tasks, elaboration issues
11862 @cindex Elaboration of library tasks
11863
11864 @noindent
11865 In this section we examine special elaboration issues that arise for
11866 programs that declare library level tasks.
11867
11868 Generally the model of execution of an Ada program is that all units are
11869 elaborated, and then execution of the program starts. However, the
11870 declaration of library tasks definitely does not fit this model. The
11871 reason for this is that library tasks start as soon as they are declared
11872 (more precisely, as soon as the statement part of the enclosing package
11873 body is reached), that is to say before elaboration
11874 of the program is complete. This means that if such a task calls a
11875 subprogram, or an entry in another task, the callee may or may not be
11876 elaborated yet, and in the standard
11877 Reference Manual model of dynamic elaboration checks, you can even
11878 get timing dependent Program_Error exceptions, since there can be
11879 a race between the elaboration code and the task code.
11880
11881 The static model of elaboration in GNAT seeks to avoid all such
11882 dynamic behavior, by being conservative, and the conservative
11883 approach in this particular case is to assume that all the code
11884 in a task body is potentially executed at elaboration time if
11885 a task is declared at the library level.
11886
11887 This can definitely result in unexpected circularities. Consider
11888 the following example
11889
11890 @smallexample
11891 package Decls is
11892   task Lib_Task is
11893      entry Start;
11894   end Lib_Task;
11895
11896   type My_Int is new Integer;
11897
11898   function Ident (M : My_Int) return My_Int;
11899 end Decls;
11900
11901 with Utils;
11902 package body Decls is
11903   task body Lib_Task is
11904   begin
11905      accept Start;
11906      Utils.Put_Val (2);
11907   end Lib_Task;
11908
11909   function Ident (M : My_Int) return My_Int is
11910   begin
11911      return M;
11912   end Ident;
11913 end Decls;
11914
11915 with Decls;
11916 package Utils is
11917   procedure Put_Val (Arg : Decls.My_Int);
11918 end Utils;
11919
11920 with Text_IO;
11921 package body Utils is
11922   procedure Put_Val (Arg : Decls.My_Int) is
11923   begin
11924      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
11925   end Put_Val;
11926 end Utils;
11927
11928 with Decls;
11929 procedure Main is
11930 begin
11931    Decls.Lib_Task.Start;
11932 end;
11933 @end smallexample
11934
11935 @noindent
11936 If the above example is compiled in the default static elaboration
11937 mode, then a circularity occurs. The circularity comes from the call
11938 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
11939 this call occurs in elaboration code, we need an implicit pragma
11940 @code{Elaborate_All} for @code{Utils}. This means that not only must
11941 the spec and body of @code{Utils} be elaborated before the body
11942 of @code{Decls}, but also the spec and body of any unit that is
11943 @code{with'ed} by the body of @code{Utils} must also be elaborated before
11944 the body of @code{Decls}. This is the transitive implication of
11945 pragma @code{Elaborate_All} and it makes sense, because in general
11946 the body of @code{Put_Val} might have a call to something in a
11947 @code{with'ed} unit.
11948
11949 In this case, the body of Utils (actually its spec) @code{with's}
11950 @code{Decls}. Unfortunately this means that the body of @code{Decls}
11951 must be elaborated before itself, in case there is a call from the
11952 body of @code{Utils}.
11953
11954 Here is the exact chain of events we are worrying about:
11955
11956 @enumerate
11957 @item
11958 In the body of @code{Decls} a call is made from within the body of a library
11959 task to a subprogram in the package @code{Utils}. Since this call may
11960 occur at elaboration time (given that the task is activated at elaboration
11961 time), we have to assume the worst, i.e. that the
11962 call does happen at elaboration time.
11963
11964 @item
11965 This means that the body and spec of @code{Util} must be elaborated before
11966 the body of @code{Decls} so that this call does not cause an access before
11967 elaboration.
11968
11969 @item
11970 Within the body of @code{Util}, specifically within the body of
11971 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
11972 by this package.
11973
11974 @item
11975 One such @code{with}'ed package is package @code{Decls}, so there
11976 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
11977 In fact there is such a call in this example, but we would have to
11978 assume that there was such a call even if it were not there, since
11979 we are not supposed to write the body of @code{Decls} knowing what
11980 is in the body of @code{Utils}; certainly in the case of the
11981 static elaboration model, the compiler does not know what is in
11982 other bodies and must assume the worst.
11983
11984 @item
11985 This means that the spec and body of @code{Decls} must also be
11986 elaborated before we elaborate the unit containing the call, but
11987 that unit is @code{Decls}! This means that the body of @code{Decls}
11988 must be elaborated before itself, and that's a circularity.
11989 @end enumerate
11990
11991 @noindent
11992 Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in
11993 the body of @code{Decls} you will get a true Ada Reference Manual
11994 circularity that makes the program illegal.
11995
11996 In practice, we have found that problems with the static model of
11997 elaboration in existing code often arise from library tasks, so
11998 we must address this particular situation.
11999
12000 Note that if we compile and run the program above, using the dynamic model of
12001 elaboration (that is to say use the @option{-gnatE} switch),
12002 then it compiles, binds,
12003 links, and runs, printing the expected result of 2. Therefore in some sense
12004 the circularity here is only apparent, and we need to capture
12005 the properties of this program that  distinguish it from other library-level
12006 tasks that have real elaboration problems.
12007
12008 We have four possible answers to this question:
12009
12010 @itemize @bullet
12011
12012 @item
12013 Use the dynamic model of elaboration.
12014
12015 If we use the @option{-gnatE} switch, then as noted above, the program works.
12016 Why is this? If we examine the task body, it is apparent that the task cannot
12017 proceed past the
12018 @code{accept} statement until after elaboration has been completed, because
12019 the corresponding entry call comes from the main program, not earlier.
12020 This is why the dynamic model works here. But that's really giving
12021 up on a precise analysis, and we prefer to take this approach only if we cannot
12022 solve the
12023 problem in any other manner. So let us examine two ways to reorganize
12024 the program to avoid the potential elaboration problem.
12025
12026 @item
12027 Split library tasks into separate packages.
12028
12029 Write separate packages, so that library tasks are isolated from
12030 other declarations as much as possible. Let us look at a variation on
12031 the above program.
12032
12033 @smallexample
12034 package Decls1 is
12035   task Lib_Task is
12036      entry Start;
12037   end Lib_Task;
12038 end Decls1;
12039
12040 with Utils;
12041 package body Decls1 is
12042   task body Lib_Task is
12043   begin
12044      accept Start;
12045      Utils.Put_Val (2);
12046   end Lib_Task;
12047 end Decls1;
12048
12049 package Decls2 is
12050   type My_Int is new Integer;
12051   function Ident (M : My_Int) return My_Int;
12052 end Decls2;
12053
12054 with Utils;
12055 package body Decls2 is
12056   function Ident (M : My_Int) return My_Int is
12057   begin
12058      return M;
12059   end Ident;
12060 end Decls2;
12061
12062 with Decls2;
12063 package Utils is
12064   procedure Put_Val (Arg : Decls2.My_Int);
12065 end Utils;
12066
12067 with Text_IO;
12068 package body Utils is
12069   procedure Put_Val (Arg : Decls2.My_Int) is
12070   begin
12071      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
12072   end Put_Val;
12073 end Utils;
12074
12075 with Decls1;
12076 procedure Main is
12077 begin
12078    Decls1.Lib_Task.Start;
12079 end;
12080 @end smallexample
12081
12082 @noindent
12083 All we have done is to split @code{Decls} into two packages, one
12084 containing the library task, and one containing everything else. Now
12085 there is no cycle, and the program compiles, binds, links and executes
12086 using the default static model of elaboration.
12087
12088 @item
12089 Declare separate task types.
12090
12091 A significant part of the problem arises because of the use of the
12092 single task declaration form. This means that the elaboration of
12093 the task type, and the elaboration of the task itself (i.e. the
12094 creation of the task) happen at the same time. A good rule
12095 of style in Ada 95 is to always create explicit task types. By
12096 following the additional step of placing task objects in separate
12097 packages from the task type declaration, many elaboration problems
12098 are avoided. Here is another modified example of the example program:
12099
12100 @smallexample
12101 package Decls is
12102   task type Lib_Task_Type is
12103      entry Start;
12104   end Lib_Task_Type;
12105
12106   type My_Int is new Integer;
12107
12108   function Ident (M : My_Int) return My_Int;
12109 end Decls;
12110
12111 with Utils;
12112 package body Decls is
12113   task body Lib_Task_Type is
12114   begin
12115      accept Start;
12116      Utils.Put_Val (2);
12117   end Lib_Task_Type;
12118
12119   function Ident (M : My_Int) return My_Int is
12120   begin
12121      return M;
12122   end Ident;
12123 end Decls;
12124
12125 with Decls;
12126 package Utils is
12127   procedure Put_Val (Arg : Decls.My_Int);
12128 end Utils;
12129
12130 with Text_IO;
12131 package body Utils is
12132   procedure Put_Val (Arg : Decls.My_Int) is
12133   begin
12134      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
12135   end Put_Val;
12136 end Utils;
12137
12138 with Decls;
12139 package Declst is
12140    Lib_Task : Decls.Lib_Task_Type;
12141 end Declst;
12142
12143 with Declst;
12144 procedure Main is
12145 begin
12146    Declst.Lib_Task.Start;
12147 end;
12148 @end smallexample
12149
12150 @noindent
12151 What we have done here is to replace the @code{task} declaration in
12152 package @code{Decls} with a @code{task type} declaration. Then we
12153 introduce a separate package @code{Declst} to contain the actual
12154 task object. This separates the elaboration issues for
12155 the @code{task type}
12156 declaration, which causes no trouble, from the elaboration issues
12157 of the task object, which is also unproblematic, since it is now independent
12158 of the elaboration of  @code{Utils}.
12159 This separation of concerns also corresponds to
12160 a generally sound engineering principle of separating declarations
12161 from instances. This version of the program also compiles, binds, links,
12162 and executes, generating the expected output.
12163
12164 @item
12165 Use No_Entry_Calls_In_Elaboration_Code restriction.
12166 @cindex No_Entry_Calls_In_Elaboration_Code
12167
12168 The previous two approaches described how a program can be restructured
12169 to avoid the special problems caused by library task bodies. in practice,
12170 however, such restructuring may be difficult to apply to existing legacy code,
12171 so we must consider solutions that do not require massive rewriting.
12172
12173 Let us consider more carefully why our original sample program works
12174 under the dynamic model of elaboration. The reason is that the code
12175 in the task body blocks immediately on the @code{accept}
12176 statement. Now of course there is nothing to prohibit elaboration
12177 code from making entry calls (for example from another library level task),
12178 so we cannot tell in isolation that
12179 the task will not execute the accept statement  during elaboration.
12180
12181 However, in practice it is very unusual to see elaboration code
12182 make any entry calls, and the pattern of tasks starting
12183 at elaboration time and then immediately blocking on @code{accept} or
12184 @code{select} statements is very common. What this means is that
12185 the compiler is being too pessimistic when it analyzes the
12186 whole package body as though it might be executed at elaboration
12187 time.
12188
12189 If we know that the elaboration code contains no entry calls, (a very safe
12190 assumption most of the time, that could almost be made the default
12191 behavior), then we can compile all units of the program under control
12192 of the following configuration pragma:
12193
12194 @smallexample
12195 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
12196 @end smallexample
12197
12198 @noindent
12199 This pragma can be placed in the @file{gnat.adc} file in the usual
12200 manner. If we take our original unmodified program and compile it
12201 in the presence of a @file{gnat.adc} containing the above pragma,
12202 then once again, we can compile, bind, link, and execute, obtaining
12203 the expected result. In the presence of this pragma, the compiler does
12204 not trace calls in a task body, that appear after the first @code{accept}
12205 or @code{select} statement, and therefore does not report a potential
12206 circularity in the original program.
12207
12208 The compiler will check to the extent it can that the above
12209 restriction is not violated, but it is not always possible to do a
12210 complete check at compile time, so it is important to use this
12211 pragma only if the stated restriction is in fact met, that is to say
12212 no task receives an entry call before elaboration of all units is completed.
12213
12214 @end itemize
12215
12216 @node Mixing Elaboration Models
12217 @section Mixing Elaboration Models
12218 @noindent
12219 So far, we have assumed that the entire program is either compiled
12220 using the dynamic model or static model, ensuring consistency. It
12221 is possible to mix the two models, but rules have to be followed
12222 if this mixing is done to ensure that elaboration checks are not
12223 omitted.
12224
12225 The basic rule is that @emph{a unit compiled with the static model cannot
12226 be @code{with'ed} by a unit compiled with the dynamic model}. The
12227 reason for this is that in the static model, a unit assumes that
12228 its clients guarantee to use (the equivalent of) pragma
12229 @code{Elaborate_All} so that no elaboration checks are required
12230 in inner subprograms, and this assumption is violated if the
12231 client is compiled with dynamic checks.
12232
12233 The precise rule is as follows. A unit that is compiled with dynamic
12234 checks can only @code{with} a unit that meets at least one of the
12235 following criteria:
12236
12237 @itemize @bullet
12238
12239 @item
12240 The @code{with'ed} unit is itself compiled with dynamic elaboration
12241 checks (that is with the @option{-gnatE} switch.
12242
12243 @item
12244 The @code{with'ed} unit is an internal GNAT implementation unit from
12245 the System, Interfaces, Ada, or GNAT hierarchies.
12246
12247 @item
12248 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
12249
12250 @item
12251 The @code{with'ing} unit (that is the client) has an explicit pragma
12252 @code{Elaborate_All} for the @code{with'ed} unit.
12253
12254 @end itemize
12255
12256 @noindent
12257 If this rule is violated, that is if a unit with dynamic elaboration
12258 checks @code{with's} a unit that does not meet one of the above four
12259 criteria, then the binder (@code{gnatbind}) will issue a warning
12260 similar to that in the following example:
12261
12262 @smallexample
12263 warning: "x.ads" has dynamic elaboration checks and with's
12264 warning:   "y.ads" which has static elaboration checks
12265 @end smallexample
12266
12267 @noindent
12268 These warnings indicate that the rule has been violated, and that as a result
12269 elaboration checks may be missed in the resulting executable file.
12270 This warning may be suppressed using the @code{-ws} binder switch
12271 in the usual manner.
12272
12273 One useful application of this mixing rule is in the case of a subsystem
12274 which does not itself @code{with} units from the remainder of the
12275 application. In this case, the entire subsystem can be compiled with
12276 dynamic checks to resolve a circularity in the subsystem, while
12277 allowing the main application that uses this subsystem to be compiled
12278 using the more reliable default static model.
12279
12280 @node What to Do If the Default Elaboration Behavior Fails
12281 @section What to Do If the Default Elaboration Behavior Fails
12282
12283 @noindent
12284 If the binder cannot find an acceptable order, it outputs detailed
12285 diagnostics. For example:
12286 @smallexample
12287 @group
12288 @iftex
12289 @leftskip=0cm
12290 @end iftex
12291 error: elaboration circularity detected
12292 info:   "proc (body)" must be elaborated before "pack (body)"
12293 info:     reason: Elaborate_All probably needed in unit "pack (body)"
12294 info:     recompile "pack (body)" with -gnatwl
12295 info:                             for full details
12296 info:       "proc (body)"
12297 info:         is needed by its spec:
12298 info:       "proc (spec)"
12299 info:         which is withed by:
12300 info:       "pack (body)"
12301 info:  "pack (body)" must be elaborated before "proc (body)"
12302 info:     reason: pragma Elaborate in unit "proc (body)"
12303 @end group
12304
12305 @end smallexample
12306
12307 @noindent
12308 In this case we have a cycle that the binder cannot break. On the one
12309 hand, there is an explicit pragma Elaborate in @code{proc} for
12310 @code{pack}. This means that the body of @code{pack} must be elaborated
12311 before the body of @code{proc}. On the other hand, there is elaboration
12312 code in @code{pack} that calls a subprogram in @code{proc}. This means
12313 that for maximum safety, there should really be a pragma
12314 Elaborate_All in @code{pack} for @code{proc} which would require that
12315 the body of @code{proc} be elaborated before the body of
12316 @code{pack}. Clearly both requirements cannot be satisfied.
12317 Faced with a circularity of this kind, you have three different options.
12318
12319 @table @asis
12320 @item Fix the program
12321 The most desirable option from the point of view of long-term maintenance
12322 is to rearrange the program so that the elaboration problems are avoided.
12323 One useful technique is to place the elaboration code into separate
12324 child packages. Another is to move some of the initialization code to
12325 explicitly called subprograms, where the program controls the order
12326 of initialization explicitly. Although this is the most desirable option,
12327 it may be impractical and involve too much modification, especially in
12328 the case of complex legacy code.
12329
12330 @item Perform dynamic checks
12331 If the compilations are done using the
12332 @option{-gnatE}
12333 (dynamic elaboration check) switch, then GNAT behaves in
12334 a quite different manner. Dynamic checks are generated for all calls
12335 that could possibly result in raising an exception. With this switch,
12336 the compiler does not generate implicit @code{Elaborate_All} pragmas.
12337 The behavior then is exactly as specified in the Ada 95 Reference Manual.
12338 The binder will generate an executable program that may or may not
12339 raise @code{Program_Error}, and then it is the programmer's job to ensure
12340 that it does not raise an exception. Note that it is important to
12341 compile all units with the switch, it cannot be used selectively.
12342
12343 @item Suppress checks
12344 The drawback of dynamic checks is that they generate a
12345 significant overhead at run time, both in space and time. If you
12346 are absolutely sure that your program cannot raise any elaboration
12347 exceptions, and you still want to use the dynamic elaboration model,
12348 then you can use the configuration pragma
12349 @code{Suppress (Elaboration_Checks)} to suppress all such checks. For
12350 example this pragma could be placed in the @file{gnat.adc} file.
12351
12352 @item Suppress checks selectively
12353 When you know that certain calls in elaboration code cannot possibly
12354 lead to an elaboration error, and the binder nevertheless generates warnings
12355 on those calls and inserts Elaborate_All pragmas that lead to elaboration
12356 circularities, it is possible to remove those warnings locally and obtain
12357 a program that will bind. Clearly this can be unsafe, and it is the
12358 responsibility of the programmer to make sure that the resulting program has
12359 no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can
12360 be used with different granularity to suppress warnings and break
12361 elaboration circularities:
12362
12363 @itemize @bullet
12364 @item
12365 Place the pragma that names the called subprogram in the declarative part
12366 that contains the call.
12367
12368 @item
12369 Place the pragma in the declarative part, without naming an entity. This
12370 disables warnings on all calls in the corresponding  declarative region.
12371
12372 @item
12373 Place the pragma in the package spec that declares the called subprogram,
12374 and name the subprogram. This disables warnings on all elaboration calls to
12375 that subprogram.
12376
12377 @item
12378 Place the pragma in the package spec that declares the called subprogram,
12379 without naming any entity. This disables warnings on all elaboration calls to
12380 all subprograms declared in this spec.
12381 @end itemize
12382
12383 @noindent
12384 These four cases are listed in order of decreasing safety, and therefore
12385 require increasing programmer care in their application. Consider the
12386 following program:
12387 @smallexample
12388
12389 package Pack1 is
12390   function F1 return Integer;
12391   X1 : Integer;
12392 end Pack1;
12393
12394 package Pack2 is
12395   function F2 return Integer;
12396   function Pure (x : integer) return integer;
12397   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
12398   --  pragma Suppress (Elaboration_Check);              -- (4)
12399 end Pack2;
12400
12401 with Pack2;
12402 package body Pack1 is
12403   function F1 return Integer is
12404   begin
12405     return 100;
12406   end F1;
12407   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
12408 begin
12409   declare
12410     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
12411     --  pragma Suppress(Elaboration_Check);             -- (2)
12412   begin
12413     X1 := Pack2.F2 + 1;                --  Elab. call (2)
12414   end;
12415 end Pack1;
12416
12417 with Pack1;
12418 package body Pack2 is
12419   function F2 return Integer is
12420   begin
12421      return Pack1.F1;
12422   end F2;
12423   function Pure (x : integer) return integer is
12424   begin
12425      return x ** 3 - 3 * x;
12426   end;
12427 end Pack2;
12428
12429 with Pack1, Ada.Text_IO;
12430 procedure Proc3 is
12431 begin
12432   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
12433 end Proc3;
12434 @end smallexample
12435 In the absence of any pragmas, an attempt to bind this program produces
12436 the following diagnostics:
12437 @smallexample
12438 @group
12439 @iftex
12440 @leftskip=.5cm
12441 @end iftex
12442 error: elaboration circularity detected
12443 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
12444 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
12445 info:       recompile "pack1 (body)" with -gnatwl for full details
12446 info:          "pack1 (body)"
12447 info:             must be elaborated along with its spec:
12448 info:          "pack1 (spec)"
12449 info:             which is withed by:
12450 info:          "pack2 (body)"
12451 info:             which must be elaborated along with its spec:
12452 info:          "pack2 (spec)"
12453 info:             which is withed by:
12454 info:          "pack1 (body)"
12455 @end group
12456 @end smallexample
12457 The sources of the circularity are the two calls to @code{Pack2.Pure} and
12458 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
12459 F2 is safe, even though F2 calls F1, because the call appears after the
12460 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
12461 remove the warning on the call. It is also possible to use pragma (2)
12462 because there are no other potentially unsafe calls in the block.
12463
12464 @noindent
12465 The call to @code{Pure} is safe because this function does not depend on the
12466 state of @code{Pack2}. Therefore any call to this function is safe, and it
12467 is correct to place pragma (3) in the corresponding package spec.
12468
12469 @noindent
12470 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
12471 warnings on all calls to functions declared therein. Note that this is not
12472 necessarily safe, and requires more detailed examination of the subprogram
12473 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
12474 be already elaborated.
12475 @end table
12476
12477 @noindent
12478 It is hard to generalize on which of these four approaches should be
12479 taken. Obviously if it is possible to fix the program so that the default
12480 treatment works, this is preferable, but this may not always be practical.
12481 It is certainly simple enough to use
12482 @option{-gnatE}
12483 but the danger in this case is that, even if the GNAT binder
12484 finds a correct elaboration order, it may not always do so,
12485 and certainly a binder from another Ada compiler might not. A
12486 combination of testing and analysis (for which the warnings generated
12487 with the
12488 @option{-gnatwl}
12489 switch can be useful) must be used to ensure that the program is free
12490 of errors. One switch that is useful in this testing is the
12491 @code{-p (pessimistic elaboration order)}
12492 switch for
12493 @code{gnatbind}.
12494 Normally the binder tries to find an order that has the best chance of
12495 of avoiding elaboration problems. With this switch, the binder
12496 plays a devil's advocate role, and tries to choose the order that
12497 has the best chance of failing. If your program works even with this
12498 switch, then it has a better chance of being error free, but this is still
12499 not a guarantee.
12500
12501 For an example of this approach in action, consider the C-tests (executable
12502 tests) from the ACVC suite. If these are compiled and run with the default
12503 treatment, then all but one of them succeed without generating any error
12504 diagnostics from the binder. However, there is one test that fails, and
12505 this is not surprising, because the whole point of this test is to ensure
12506 that the compiler can handle cases where it is impossible to determine
12507 a correct order statically, and it checks that an exception is indeed
12508 raised at run time.
12509
12510 This one test must be compiled and run using the
12511 @option{-gnatE}
12512 switch, and then it passes. Alternatively, the entire suite can
12513 be run using this switch. It is never wrong to run with the dynamic
12514 elaboration switch if your code is correct, and we assume that the
12515 C-tests are indeed correct (it is less efficient, but efficiency is
12516 not a factor in running the ACVC tests.)
12517
12518 @node Elaboration for Access-to-Subprogram Values
12519 @section Elaboration for Access-to-Subprogram Values
12520 @cindex Access-to-subprogram
12521
12522 @noindent
12523 The introduction of access-to-subprogram types in Ada 95 complicates
12524 the handling of elaboration. The trouble is that it becomes
12525 impossible to tell at compile time which procedure
12526 is being called. This means that it is not possible for the binder
12527 to analyze the elaboration requirements in this case.
12528
12529 If at the point at which the access value is created
12530 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
12531 the body of the subprogram is
12532 known to have been elaborated, then the access value is safe, and its use
12533 does not require a check. This may be achieved by appropriate arrangement
12534 of the order of declarations if the subprogram is in the current unit,
12535 or, if the subprogram is in another unit, by using pragma
12536 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
12537 on the referenced unit.
12538
12539 If the referenced body is not known to have been elaborated at the point
12540 the access value is created, then any use of the access value must do a
12541 dynamic check, and this dynamic check will fail and raise a
12542 @code{Program_Error} exception if the body has not been elaborated yet.
12543 GNAT will generate the necessary checks, and in addition, if the
12544 @option{-gnatwl}
12545 switch is set, will generate warnings that such checks are required.
12546
12547 The use of dynamic dispatching for tagged types similarly generates
12548 a requirement for dynamic checks, and premature calls to any primitive
12549 operation of a tagged type before the body of the operation has been elaborated,
12550 will result in the raising of @code{Program_Error}.
12551
12552 @node Summary of Procedures for Elaboration Control
12553 @section Summary of Procedures for Elaboration Control
12554 @cindex Elaboration control
12555
12556 @noindent
12557 First, compile your program with the default options, using none of
12558 the special elaboration control switches. If the binder successfully
12559 binds your program, then you can be confident that, apart from issues
12560 raised by the use of access-to-subprogram types and dynamic dispatching,
12561 the program is free of elaboration errors. If it is important that the
12562 program be portable, then use the
12563 @option{-gnatwl}
12564 switch to generate warnings about missing @code{Elaborate_All}
12565 pragmas, and supply the missing pragmas.
12566
12567 If the program fails to bind using the default static elaboration
12568 handling, then you can fix the program to eliminate the binder
12569 message, or recompile the entire program with the
12570 @option{-gnatE} switch to generate dynamic elaboration checks,
12571 and, if you are sure there really are no elaboration problems,
12572 use a global pragma @code{Suppress (Elaboration_Checks)}.
12573
12574 @node Other Elaboration Order Considerations
12575 @section Other Elaboration Order Considerations
12576 @noindent
12577 This section has been entirely concerned with the issue of finding a valid
12578 elaboration order, as defined by the Ada Reference Manual. In a case
12579 where several elaboration orders are valid, the task is to find one
12580 of the possible valid elaboration orders (and the static model in GNAT
12581 will ensure that this is achieved).
12582
12583 The purpose of the elaboration rules in the Ada Reference Manual is to
12584 make sure that no entity is accessed before it has been elaborated. For
12585 a subprogram, this means that the spec and body must have been elaborated
12586 before the subprogram is called. For an object, this means that the object
12587 must have been elaborated before its value is read or written. A violation
12588 of either of these two requirements is an access before elaboration order,
12589 and this section has been all about avoiding such errors.
12590
12591 In the case where more than one order of elaboration is possible, in the
12592 sense that access before elaboration errors are avoided, then any one of
12593 the orders is "correct" in the sense that it meets the requirements of
12594 the Ada Reference Manual, and no such error occurs.
12595
12596 However, it may be the case for a given program, that there are
12597 constraints on the order of elaboration that come not from consideration
12598 of avoiding elaboration errors, but rather from extra-lingual logic
12599 requirements. Consider this example:
12600
12601 @smallexample
12602 with Init_Constants;
12603 package Constants is
12604    X : Integer := 0;
12605    Y : Integer := 0;
12606 end Constants;
12607
12608 package Init_Constants is
12609    procedure Calc;
12610 end Init_Constants;
12611
12612 with Constants;
12613 package body Init_Constants is
12614    procedure Calc is begin null; end;
12615 begin
12616    Constants.X := 3;
12617    Constants.Y := 4;
12618 end Init_Constants;
12619
12620 with Constants;
12621 package Calc is
12622    Z : Integer := Constants.X + Constants.Y;
12623 end Calc;
12624
12625 with Calc;
12626 with Text_IO; use Text_IO;
12627 procedure Main is
12628 begin
12629    Put_Line (Calc.Z'Img);
12630 end Main;
12631 @end smallexample
12632
12633 @noindent
12634 In this example, there is more than one valid order of elaboration. For
12635 example both the following are correct orders:
12636
12637 @smallexample
12638 Init_Constants spec
12639 Constants spec
12640 Calc spec
12641 Main body
12642 Init_Constants body
12643
12644   and
12645
12646 Init_Constants spec
12647 Init_Constants body
12648 Constants spec
12649 Calc spec
12650 Main body
12651 @end smallexample
12652
12653 @noindent
12654 There is no language rule to prefer one or the other, both are correct
12655 from an order of elaboration point of view. But the programmatic effects
12656 of the two orders are very different. In the first, the elaboration routine
12657 of @code{Calc} initializes @code{Z} to zero, and then the main program
12658 runs with this value of zero. But in the second order, the elaboration
12659 routine of @code{Calc} runs after the body of Init_Constants has set
12660 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
12661 runs.
12662
12663 One could perhaps by applying pretty clever non-artificial intelligence
12664 to the situation guess that it is more likely that the second order of
12665 elaboration is the one desired, but there is no formal linguistic reason
12666 to prefer one over the other. In fact in this particular case, GNAT will
12667 prefer the second order, because of the rule that bodies are elaborated
12668 as soon as possible, but it's just luck that this is what was wanted
12669 (if indeed the second order was preferred).
12670
12671 If the program cares about the order of elaboration routines in a case like
12672 this, it is important to specify the order required. In this particular
12673 case, that could have been achieved by adding to the spec of Calc:
12674
12675 @smallexample
12676 pragma Elaborate_All (Constants);
12677 @end smallexample
12678
12679 @noindent
12680 which requires that the body (if any) and spec of @code{Constants},
12681 as well as the body and spec of any unit @code{with}'ed by
12682 @code{Constants} be elaborated before @code{Calc} is elaborated.
12683
12684 Clearly no automatic method can always guess which alternative you require,
12685 and if you are working with legacy code that had constraints of this kind
12686 which were not properly specified by adding @code{Elaborate} or
12687 @code{Elaborate_All} pragmas, then indeed it is possible that two different
12688 compilers can choose different orders.
12689
12690 The @code{gnatbind}
12691 @code{-p} switch may be useful in smoking
12692 out problems. This switch causes bodies to be elaborated as late as possible
12693 instead of as early as possible. In the example above, it would have forced
12694 the choice of the first elaboration order. If you get different results
12695 when using this switch, and particularly if one set of results is right,
12696 and one is wrong as far as you are concerned, it shows that you have some
12697 missing @code{Elaborate} pragmas. For the example above, we have the
12698 following output:
12699
12700 @smallexample
12701 gnatmake -f -q main
12702 main
12703  7
12704 gnatmake -f -q main -bargs -p
12705 main
12706  0
12707 @end smallexample
12708
12709 @noindent
12710 It is of course quite unlikely that both these results are correct, so
12711 it is up to you in a case like this to investigate the source of the
12712 difference, by looking at the two elaboration orders that are chosen,
12713 and figuring out which is correct, and then adding the necessary
12714 @code{Elaborate_All} pragmas to ensure the desired order.
12715
12716 @node The Cross-Referencing Tools gnatxref and gnatfind
12717 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12718 @findex gnatxref
12719 @findex gnatfind
12720
12721 @noindent
12722 The compiler generates cross-referencing information (unless
12723 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12724 This information indicates where in the source each entity is declared and
12725 referenced. Note that entities in package Standard are not included, but
12726 entities in all other predefined units are included in the output.
12727
12728 Before using any of these two tools, you need to compile successfully your
12729 application, so that GNAT gets a chance to generate the cross-referencing
12730 information.
12731
12732 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12733 information to provide the user with the capability to easily locate the
12734 declaration and references to an entity. These tools are quite similar,
12735 the difference being that @code{gnatfind} is intended for locating
12736 definitions and/or references to a specified entity or entities, whereas
12737 @code{gnatxref} is oriented to generating a full report of all
12738 cross-references.
12739
12740 To use these tools, you must not compile your application using the
12741 @option{-gnatx} switch on the @file{gnatmake} command line (@inforef{The
12742 GNAT Make Program gnatmake,,gnat_ug}). Otherwise, cross-referencing
12743 information will not be generated.
12744
12745 @menu
12746 * gnatxref Switches::
12747 * gnatfind Switches::
12748 * Project Files for gnatxref and gnatfind::
12749 * Regular Expressions in gnatfind and gnatxref::
12750 * Examples of gnatxref Usage::
12751 * Examples of gnatfind Usage::
12752 @end menu
12753
12754 @node gnatxref Switches
12755 @section @code{gnatxref} Switches
12756
12757 @noindent
12758 The command lines for @code{gnatxref} is:
12759 @smallexample
12760 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
12761 @end smallexample
12762
12763 @noindent
12764 where
12765
12766 @table @code
12767 @item sourcefile1, sourcefile2
12768 identifies the source files for which a report is to be generated. The
12769 'with'ed units will be processed too. You must provide at least one file.
12770
12771 These file names are considered to be regular expressions, so for instance
12772 specifying 'source*.adb' is the same as giving every file in the current
12773 directory whose name starts with 'source' and whose extension is 'adb'.
12774
12775 @end table
12776
12777 @noindent
12778 The switches can be :
12779 @table @code
12780 @item -a
12781 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12782 the read-only files found in the library search path. Otherwise, these files
12783 will be ignored. This option can be used to protect Gnat sources or your own
12784 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12785 much faster, and their output much smaller.
12786
12787 @item -aIDIR
12788 When looking for source files also look in directory DIR. The order in which
12789 source file search is undertaken is the same as for @file{gnatmake}.
12790
12791 @item -aODIR
12792 When searching for library and object files, look in directory
12793 DIR. The order in which library files are searched is the same as for
12794 @file{gnatmake}.
12795
12796 @item -nostdinc
12797 Do not look for sources in the system default directory.
12798
12799 @item -nostdlib
12800 Do not look for library files in the system default directory.
12801
12802 @item --RTS=@var{rts-path}
12803 @cindex @code{--RTS} (@code{gnatxref})
12804 Specifies the default location of the runtime library. Same meaning as the
12805 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
12806
12807 @item -d
12808 If this switch is set @code{gnatxref} will output the parent type
12809 reference for each matching derived types.
12810
12811 @item -f
12812 If this switch is set, the output file names will be preceded by their
12813 directory (if the file was found in the search path). If this switch is
12814 not set, the directory will not be printed.
12815
12816 @item -g
12817 If this switch is set, information is output only for library-level
12818 entities, ignoring local entities. The use of this switch may accelerate
12819 @code{gnatfind} and @code{gnatxref}.
12820
12821 @item -IDIR
12822 Equivalent to @samp{-aODIR -aIDIR}.
12823
12824 @item -pFILE
12825 Specify a project file to use @xref{Project Files}.
12826 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12827 project file in the current directory.
12828
12829 If a project file is either specified or found by the tools, then the content
12830 of the source directory and object directory lines are added as if they
12831 had been specified respectively by @samp{-aI}
12832 and @samp{-aO}.
12833 @item -u
12834 Output only unused symbols. This may be really useful if you give your
12835 main compilation unit on the command line, as @code{gnatxref} will then
12836 display every unused entity and 'with'ed package.
12837
12838 @item -v
12839 Instead of producing the default output, @code{gnatxref} will generate a
12840 @file{tags} file that can be used by vi. For examples how to use this
12841 feature, see @xref{Examples of gnatxref Usage}. The tags file is output
12842 to the standard output, thus you will have to redirect it to a file.
12843
12844 @end table
12845
12846 All these switches may be in any order on the command line, and may even
12847 appear after the file names. They need not be separated by spaces, thus
12848 you can say @samp{gnatxref -ag} instead of
12849 @samp{gnatxref -a -g}.
12850
12851 @node gnatfind Switches
12852 @section @code{gnatfind} Switches
12853
12854 @noindent
12855 The command line for @code{gnatfind} is:
12856
12857 @smallexample
12858 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
12859       [file1 file2 ...]
12860 @end smallexample
12861
12862 @noindent
12863 where
12864
12865 @table @code
12866 @item pattern
12867 An entity will be output only if it matches the regular expression found
12868 in @samp{pattern}, see @xref{Regular Expressions in gnatfind and gnatxref}.
12869
12870 Omitting the pattern is equivalent to specifying @samp{*}, which
12871 will match any entity. Note that if you do not provide a pattern, you
12872 have to provide both a sourcefile and a line.
12873
12874 Entity names are given in Latin-1, with uppercase/lowercase equivalence
12875 for matching purposes. At the current time there is no support for
12876 8-bit codes other than Latin-1, or for wide characters in identifiers.
12877
12878 @item sourcefile
12879 @code{gnatfind} will look for references, bodies or declarations
12880 of symbols referenced in @file{sourcefile}, at line @samp{line}
12881 and column @samp{column}. See @pxref{Examples of gnatfind Usage}
12882 for syntax examples.
12883
12884 @item line
12885 is a decimal integer identifying the line number containing
12886 the reference to the entity (or entities) to be located.
12887
12888 @item column
12889 is a decimal integer identifying the exact location on the
12890 line of the first character of the identifier for the
12891 entity reference. Columns are numbered from 1.
12892
12893 @item file1 file2 ...
12894 The search will be restricted to these files. If none are given, then
12895 the search will be done for every library file in the search path.
12896 These file must appear only after the pattern or sourcefile.
12897
12898 These file names are considered to be regular expressions, so for instance
12899 specifying 'source*.adb' is the same as giving every file in the current
12900 directory whose name starts with 'source' and whose extension is 'adb'.
12901
12902 Not that if you specify at least one file in this part, @code{gnatfind} may
12903 sometimes not be able to find the body of the subprograms...
12904
12905 @end table
12906
12907 At least one of 'sourcefile' or 'pattern' has to be present on
12908 the command line.
12909
12910 The following switches are available:
12911 @table @code
12912
12913 @item -a
12914 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
12915 the read-only files found in the library search path. Otherwise, these files
12916 will be ignored. This option can be used to protect Gnat sources or your own
12917 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
12918 much faster, and their output much smaller.
12919
12920 @item -aIDIR
12921 When looking for source files also look in directory DIR. The order in which
12922 source file search is undertaken is the same as for @file{gnatmake}.
12923
12924 @item -aODIR
12925 When searching for library and object files, look in directory
12926 DIR. The order in which library files are searched is the same as for
12927 @file{gnatmake}.
12928
12929 @item -nostdinc
12930 Do not look for sources in the system default directory.
12931
12932 @item -nostdlib
12933 Do not look for library files in the system default directory.
12934
12935 @item --RTS=@var{rts-path}
12936 @cindex @code{--RTS} (@code{gnatfind})
12937 Specifies the default location of the runtime library. Same meaning as the
12938 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
12939
12940 @item -d
12941 If this switch is set, then @code{gnatfind} will output the parent type
12942 reference for each matching derived types.
12943
12944 @item -e
12945 By default, @code{gnatfind} accept the simple regular expression set for
12946 @samp{pattern}. If this switch is set, then the pattern will be
12947 considered as full Unix-style regular expression.
12948
12949 @item -f
12950 If this switch is set, the output file names will be preceded by their
12951 directory (if the file was found in the search path). If this switch is
12952 not set, the directory will not be printed.
12953
12954 @item -g
12955 If this switch is set, information is output only for library-level
12956 entities, ignoring local entities. The use of this switch may accelerate
12957 @code{gnatfind} and @code{gnatxref}.
12958
12959 @item -IDIR
12960 Equivalent to @samp{-aODIR -aIDIR}.
12961
12962 @item -pFILE
12963 Specify a project file (@pxref{Project Files}) to use.
12964 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
12965 project file in the current directory.
12966
12967 If a project file is either specified or found by the tools, then the content
12968 of the source directory and object directory lines are added as if they
12969 had been specified respectively by @samp{-aI} and
12970 @samp{-aO}.
12971
12972 @item -r
12973 By default, @code{gnatfind} will output only the information about the
12974 declaration, body or type completion of the entities. If this switch is
12975 set, the @code{gnatfind} will locate every reference to the entities in
12976 the files specified on the command line (or in every file in the search
12977 path if no file is given on the command line).
12978
12979 @item -s
12980 If this switch is set, then @code{gnatfind} will output the content
12981 of the Ada source file lines were the entity was found.
12982
12983 @item -t
12984 If this switch is set, then @code{gnatfind} will output the type hierarchy for
12985 the specified type. It act like -d option but recursively from parent
12986 type to parent type. When this switch is set it is not possible to
12987 specify more than one file.
12988
12989 @end table
12990
12991 All these switches may be in any order on the command line, and may even
12992 appear after the file names. They need not be separated by spaces, thus
12993 you can say @samp{gnatxref -ag} instead of
12994 @samp{gnatxref -a -g}.
12995
12996 As stated previously, gnatfind will search in every directory in the
12997 search path. You can force it to look only in the current directory if
12998 you specify @code{*} at the end of the command line.
12999
13000
13001 @node Project Files for gnatxref and gnatfind
13002 @section Project Files for @command{gnatxref} and @command{gnatfind}
13003
13004 @noindent
13005 Project files allow a programmer to specify how to compile its
13006 application, where to find sources,... These files are used primarily by
13007 the Glide Ada mode, but they can also be used by the two tools
13008 @code{gnatxref} and @code{gnatfind}.
13009
13010 A project file name must end with @file{.adp}. If a single one is
13011 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
13012 extract the information from it. If multiple project files are found, none of
13013 them is read, and you have to use the @samp{-p} switch to specify the one
13014 you want to use.
13015
13016 The following lines can be included, even though most of them have default
13017 values which can be used in most cases.
13018 The lines can be entered in any order in the file.
13019 Except for @samp{src_dir} and @samp{obj_dir}, you can only have one instance of
13020 each line. If you have multiple instances, only the last one is taken into
13021 account.
13022
13023 @table @code
13024 @item src_dir=DIR         [default: "./"]
13025 specifies a directory where to look for source files. Multiple src_dir lines
13026 can be specified and they will be searched in the order they
13027 are specified.
13028
13029 @item obj_dir=DIR         [default: "./"]
13030 specifies a directory where to look for object and library files. Multiple
13031 obj_dir lines can be specified and they will be searched in the order they
13032 are specified
13033
13034 @item comp_opt=SWITCHES   [default: ""]
13035 creates a variable which can be referred to subsequently by using
13036 the @samp{$@{comp_opt@}} notation. This is intended to store the default
13037 switches given to @file{gnatmake} and @file{gcc}.
13038
13039 @item bind_opt=SWITCHES   [default: ""]
13040 creates a variable which can be referred to subsequently by using
13041 the @samp{$@{bind_opt@}} notation. This is intended to store the default
13042 switches given to @file{gnatbind}.
13043
13044 @item link_opt=SWITCHES   [default: ""]
13045 creates a variable which can be referred to subsequently by using
13046 the @samp{$@{link_opt@}} notation. This is intended to store the default
13047 switches given to @file{gnatlink}.
13048
13049 @item main=EXECUTABLE     [default: ""]
13050 specifies the name of the executable for the application. This variable can
13051 be referred to in the following lines by using the @samp{$@{main@}} notation.
13052
13053 @item comp_cmd=COMMAND    [default: "gcc -c -I$@{src_dir@} -g -gnatq"]
13054 specifies the command used to compile a single file in the application.
13055
13056 @item make_cmd=COMMAND    [default: "gnatmake $@{main@} -aI$@{src_dir@} -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@} -bargs $@{bind_opt@} -largs $@{link_opt@}"]
13057 specifies the command used to recompile the whole application.
13058
13059 @item run_cmd=COMMAND     [default: "$@{main@}"]
13060 specifies the command used to run the application.
13061
13062 @item debug_cmd=COMMAND   [default: "gdb $@{main@}"]
13063 specifies the command used to debug the application
13064
13065 @end table
13066
13067 @code{gnatxref} and @code{gnatfind} only take into account the @samp{src_dir}
13068 and @samp{obj_dir} lines, and ignore the others.
13069
13070 @node Regular Expressions in gnatfind and gnatxref
13071 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
13072
13073 @noindent
13074 As specified in the section about @code{gnatfind}, the pattern can be a
13075 regular expression. Actually, there are to set of regular expressions
13076 which are recognized by the program :
13077
13078 @table @code
13079 @item globbing patterns
13080 These are the most usual regular expression. They are the same that you
13081 generally used in a Unix shell command line, or in a DOS session.
13082
13083 Here is a more formal grammar :
13084 @smallexample
13085 @group
13086 @iftex
13087 @leftskip=.5cm
13088 @end iftex
13089 regexp ::= term
13090 term   ::= elmt            -- matches elmt
13091 term   ::= elmt elmt       -- concatenation (elmt then elmt)
13092 term   ::= *               -- any string of 0 or more characters
13093 term   ::= ?               -- matches any character
13094 term   ::= [char @{char@}] -- matches any character listed
13095 term   ::= [char - char]   -- matches any character in range
13096 @end group
13097 @end smallexample
13098
13099 @item full regular expression
13100 The second set of regular expressions is much more powerful. This is the
13101 type of regular expressions recognized by utilities such a @file{grep}.
13102
13103 The following is the form of a regular expression, expressed in Ada
13104 reference manual style BNF is as follows
13105
13106 @smallexample
13107 @iftex
13108 @leftskip=.5cm
13109 @end iftex
13110 @group
13111 regexp ::= term @{| term@} -- alternation (term or term ...)
13112
13113 term ::= item @{item@}     -- concatenation (item then item)
13114
13115 item ::= elmt              -- match elmt
13116 item ::= elmt *            -- zero or more elmt's
13117 item ::= elmt +            -- one or more elmt's
13118 item ::= elmt ?            -- matches elmt or nothing
13119 @end group
13120 @group
13121 elmt ::= nschar            -- matches given character
13122 elmt ::= [nschar @{nschar@}]   -- matches any character listed
13123 elmt ::= [^ nschar @{nschar@}] -- matches any character not listed
13124 elmt ::= [char - char]     -- matches chars in given range
13125 elmt ::= \ char            -- matches given character
13126 elmt ::= .                 -- matches any single character
13127 elmt ::= ( regexp )        -- parens used for grouping
13128
13129 char ::= any character, including special characters
13130 nschar ::= any character except ()[].*+?^
13131 @end group
13132 @end smallexample
13133
13134 Following are a few examples :
13135
13136 @table @samp
13137 @item abcde|fghi
13138 will match any of the two strings 'abcde' and 'fghi'.
13139
13140 @item abc*d
13141 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
13142
13143 @item [a-z]+
13144 will match any string which has only lowercase characters in it (and at
13145 least one character
13146
13147 @end table
13148 @end table
13149
13150 @node Examples of gnatxref Usage
13151 @section Examples of @code{gnatxref} Usage
13152
13153 @subsection General Usage
13154
13155 @noindent
13156 For the following examples, we will consider the following units :
13157
13158 @smallexample
13159 @group
13160 @cartouche
13161 main.ads:
13162 1: @b{with} Bar;
13163 2: @b{package} Main @b{is}
13164 3:     @b{procedure} Foo (B : @b{in} Integer);
13165 4:     C : Integer;
13166 5: @b{private}
13167 6:     D : Integer;
13168 7: @b{end} Main;
13169
13170 main.adb:
13171 1: @b{package body} Main @b{is}
13172 2:     @b{procedure} Foo (B : @b{in} Integer) @b{is}
13173 3:     @b{begin}
13174 4:        C := B;
13175 5:        D := B;
13176 6:        Bar.Print (B);
13177 7:        Bar.Print (C);
13178 8:     @b{end} Foo;
13179 9: @b{end} Main;
13180
13181 bar.ads:
13182 1: @b{package} Bar @b{is}
13183 2:     @b{procedure} Print (B : Integer);
13184 3: @b{end} bar;
13185 @end cartouche
13186 @end group
13187 @end smallexample
13188
13189 @table @code
13190
13191 @noindent
13192 The first thing to do is to recompile your application (for instance, in
13193 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13194 the cross-referencing information.
13195 You can then issue any of the following commands:
13196
13197 @item gnatxref main.adb
13198 @code{gnatxref} generates cross-reference information for main.adb
13199 and every unit 'with'ed by main.adb.
13200
13201 The output would be:
13202 @smallexample
13203 @iftex
13204 @leftskip=0cm
13205 @end iftex
13206 B                                                      Type: Integer
13207   Decl: bar.ads           2:22
13208 B                                                      Type: Integer
13209   Decl: main.ads          3:20
13210   Body: main.adb          2:20
13211   Ref:  main.adb          4:13     5:13     6:19
13212 Bar                                                    Type: Unit
13213   Decl: bar.ads           1:9
13214   Ref:  main.adb          6:8      7:8
13215        main.ads           1:6
13216 C                                                      Type: Integer
13217   Decl: main.ads          4:5
13218   Modi: main.adb          4:8
13219   Ref:  main.adb          7:19
13220 D                                                      Type: Integer
13221   Decl: main.ads          6:5
13222   Modi: main.adb          5:8
13223 Foo                                                    Type: Unit
13224   Decl: main.ads          3:15
13225   Body: main.adb          2:15
13226 Main                                                    Type: Unit
13227   Decl: main.ads          2:9
13228   Body: main.adb          1:14
13229 Print                                                   Type: Unit
13230   Decl: bar.ads           2:15
13231   Ref:  main.adb          6:12     7:12
13232 @end smallexample
13233
13234 @noindent
13235 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13236 its body is in main.adb, line 1, column 14 and is not referenced any where.
13237
13238 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13239 it referenced in main.adb, line 6 column 12 and line 7 column 12.
13240
13241 @item gnatxref package1.adb package2.ads
13242 @code{gnatxref} will generates cross-reference information for
13243 package1.adb, package2.ads and any other package 'with'ed by any
13244 of these.
13245
13246 @end table
13247
13248 @subsection Using gnatxref with vi
13249
13250 @code{gnatxref} can generate a tags file output, which can be used
13251 directly from @file{vi}. Note that the standard version of @file{vi}
13252 will not work properly with overloaded symbols. Consider using another
13253 free implementation of @file{vi}, such as @file{vim}.
13254
13255 @smallexample
13256 $ gnatxref -v gnatfind.adb > tags
13257 @end smallexample
13258
13259 @noindent
13260 will generate the tags file for @code{gnatfind} itself (if the sources
13261 are in the search path!).
13262
13263 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
13264 (replacing @i{entity} by whatever you are looking for), and vi will
13265 display a new file with the corresponding declaration of entity.
13266
13267 @node Examples of gnatfind Usage
13268 @section Examples of @code{gnatfind} Usage
13269
13270 @table @code
13271
13272 @item gnatfind -f xyz:main.adb
13273 Find declarations for all entities xyz referenced at least once in
13274 main.adb. The references are search in every library file in the search
13275 path.
13276
13277 The directories will be printed as well (as the @samp{-f}
13278 switch is set)
13279
13280 The output will look like:
13281 @smallexample
13282 directory/main.ads:106:14: xyz <= declaration
13283 directory/main.adb:24:10: xyz <= body
13284 directory/foo.ads:45:23: xyz <= declaration
13285 @end smallexample
13286
13287 @noindent
13288 that is to say, one of the entities xyz found in main.adb is declared at
13289 line 12 of main.ads (and its body is in main.adb), and another one is
13290 declared at line 45 of foo.ads
13291
13292 @item gnatfind -fs xyz:main.adb
13293 This is the same command as the previous one, instead @code{gnatfind} will
13294 display the content of the Ada source file lines.
13295
13296 The output will look like:
13297
13298 @smallexample
13299 directory/main.ads:106:14: xyz <= declaration
13300    procedure xyz;
13301 directory/main.adb:24:10: xyz <= body
13302    procedure xyz is
13303 directory/foo.ads:45:23: xyz <= declaration
13304    xyz : Integer;
13305 @end smallexample
13306
13307 @noindent
13308 This can make it easier to find exactly the location your are looking
13309 for.
13310
13311 @item gnatfind -r "*x*":main.ads:123 foo.adb
13312 Find references to all entities containing an x that are
13313 referenced on line 123 of main.ads.
13314 The references will be searched only in main.adb and foo.adb.
13315
13316 @item gnatfind main.ads:123
13317 Find declarations and bodies for all entities that are referenced on
13318 line 123 of main.ads.
13319
13320 This is the same as @code{gnatfind "*":main.adb:123}.
13321
13322 @item gnatfind mydir/main.adb:123:45
13323 Find the declaration for the entity referenced at column 45 in
13324 line 123 of file main.adb in directory mydir. Note that it
13325 is usual to omit the identifier name when the column is given,
13326 since the column position identifies a unique reference.
13327
13328 The column has to be the beginning of the identifier, and should not
13329 point to any character in the middle of the identifier.
13330
13331 @end table
13332
13333 @node File Name Krunching Using gnatkr
13334 @chapter File Name Krunching Using @code{gnatkr}
13335 @findex gnatkr
13336
13337 @noindent
13338 This chapter discusses the method used by the compiler to shorten
13339 the default file names chosen for Ada units so that they do not
13340 exceed the maximum length permitted. It also describes the
13341 @code{gnatkr} utility that can be used to determine the result of
13342 applying this shortening.
13343 @menu
13344 * About gnatkr::
13345 * Using gnatkr::
13346 * Krunching Method::
13347 * Examples of gnatkr Usage::
13348 @end menu
13349
13350 @node About gnatkr
13351 @section About @code{gnatkr}
13352
13353 @noindent
13354 The default file naming rule in GNAT
13355 is that the file name must be derived from
13356 the unit name. The exact default rule is as follows:
13357 @itemize @bullet
13358 @item
13359 Take the unit name and replace all dots by hyphens.
13360 @item
13361 If such a replacement occurs in the
13362 second character position of a name, and the first character is
13363 a, g, s, or i then replace the dot by the character
13364 ~ (tilde)
13365 instead of a minus.
13366 @end itemize
13367 The reason for this exception is to avoid clashes
13368 with the standard names for children of System, Ada, Interfaces,
13369 and GNAT, which use the prefixes s- a- i- and g-
13370 respectively.
13371
13372 The @code{-gnatk@var{nn}}
13373 switch of the compiler activates a "krunching"
13374 circuit that limits file names to nn characters (where nn is a decimal
13375 integer). For example, using OpenVMS,
13376 where the maximum file name length is
13377 39, the value of nn is usually set to 39, but if you want to generate
13378 a set of files that would be usable if ported to a system with some
13379 different maximum file length, then a different value can be specified.
13380 The default value of 39 for OpenVMS need not be specified.
13381
13382 The @code{gnatkr} utility can be used to determine the krunched name for
13383 a given file, when krunched to a specified maximum length.
13384
13385 @node Using gnatkr
13386 @section Using @code{gnatkr}
13387
13388 @noindent
13389 The @code{gnatkr} command has the form
13390
13391 @smallexample
13392 $ gnatkr @var{name} [@var{length}]
13393 @end smallexample
13394
13395
13396 @noindent
13397 @var{name} can be an Ada name with dots or the GNAT name of the unit,
13398 where the dots representing child units or subunit are replaced by
13399 hyphens. The only confusion arises if a name ends in @code{.ads} or
13400 @code{.adb}. @code{gnatkr} takes this to be an extension if there are
13401 no other dots in the name and the whole name is in lowercase.
13402
13403 @var{length} represents the length of the krunched name. The default
13404 when no argument is given is 8 characters. A length of zero stands for
13405 unlimited, in other words do not chop except for system files which are
13406 always 8.
13407
13408 @noindent
13409 The output is the krunched name. The output has an extension only if the
13410 original argument was a file name with an extension.
13411
13412 @node Krunching Method
13413 @section Krunching Method
13414
13415 @noindent
13416 The initial file name is determined by the name of the unit that the file
13417 contains. The name is formed by taking the full expanded name of the
13418 unit and replacing the separating dots with hyphens and
13419 using lowercase
13420 for all letters, except that a hyphen in the second character position is
13421 replaced by a tilde if the first character is
13422 a, i, g, or s.
13423 The extension is @code{.ads} for a
13424 specification and @code{.adb} for a body.
13425 Krunching does not affect the extension, but the file name is shortened to
13426 the specified length by following these rules:
13427
13428 @itemize @bullet
13429 @item
13430 The name is divided into segments separated by hyphens, tildes or
13431 underscores and all hyphens, tildes, and underscores are
13432 eliminated. If this leaves the name short enough, we are done.
13433
13434 @item
13435 If the name is too long, the longest segment is located (left-most if there are two
13436 of equal length), and shortened by dropping its last character. This is
13437 repeated until the name is short enough.
13438
13439 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
13440 to fit the name into 8 characters as required by some operating systems.
13441
13442 @smallexample
13443 our-strings-wide_fixed 22
13444 our strings wide fixed 19
13445 our string  wide fixed 18
13446 our strin   wide fixed 17
13447 our stri    wide fixed 16
13448 our stri    wide fixe  15
13449 our str     wide fixe  14
13450 our str     wid  fixe  13
13451 our str     wid  fix   12
13452 ou  str     wid  fix   11
13453 ou  st      wid  fix   10
13454 ou  st      wi   fix   9
13455 ou  st      wi   fi    8
13456 Final file name: oustwifi.adb
13457 @end smallexample
13458
13459 @item
13460 The file names for all predefined units are always krunched to eight
13461 characters. The krunching of these predefined units uses the following
13462 special prefix replacements:
13463
13464 @table @file
13465 @item ada-
13466 replaced by @file{a-}
13467
13468 @item gnat-
13469 replaced by @file{g-}
13470
13471 @item interfaces-
13472 replaced by @file{i-}
13473
13474 @item system-
13475 replaced by @file{s-}
13476 @end table
13477
13478 These system files have a hyphen in the second character position. That
13479 is why normal user files replace such a character with a
13480 tilde, to
13481 avoid confusion with system file names.
13482
13483 As an example of this special rule, consider
13484 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
13485
13486 @smallexample
13487 ada-strings-wide_fixed 22
13488 a-  strings wide fixed 18
13489 a-  string  wide fixed 17
13490 a-  strin   wide fixed 16
13491 a-  stri    wide fixed 15
13492 a-  stri    wide fixe  14
13493 a-  str     wide fixe  13
13494 a-  str     wid  fixe  12
13495 a-  str     wid  fix   11
13496 a-  st      wid  fix   10
13497 a-  st      wi   fix   9
13498 a-  st      wi   fi    8
13499 Final file name: a-stwifi.adb
13500 @end smallexample
13501 @end itemize
13502
13503 Of course no file shortening algorithm can guarantee uniqueness over all
13504 possible unit names, and if file name krunching is used then it is your
13505 responsibility to ensure that no name clashes occur. The utility
13506 program @code{gnatkr} is supplied for conveniently determining the
13507 krunched name of a file.
13508
13509 @node Examples of gnatkr Usage
13510 @section Examples of @code{gnatkr} Usage
13511
13512 @smallexample
13513 @iftex
13514 @leftskip=0cm
13515 @end iftex
13516 $ gnatkr very_long_unit_name.ads      --> velounna.ads
13517 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
13518 $ gnatkr Grandparent.Parent.Child     --> grparchi
13519 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
13520 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
13521 @end smallexample
13522
13523 @node Preprocessing Using gnatprep
13524 @chapter Preprocessing Using @code{gnatprep}
13525 @findex gnatprep
13526
13527 @noindent
13528 The @code{gnatprep} utility provides
13529 a simple preprocessing capability for Ada programs.
13530 It is designed for use with GNAT, but is not dependent on any special
13531 features of GNAT.
13532
13533 @menu
13534 * Using gnatprep::
13535 * Switches for gnatprep::
13536 * Form of Definitions File::
13537 * Form of Input Text for gnatprep::
13538 @end menu
13539
13540 @node Using gnatprep
13541 @section Using @code{gnatprep}
13542
13543 @noindent
13544 To call @code{gnatprep} use
13545
13546 @smallexample
13547 $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
13548 @end smallexample
13549
13550 @noindent
13551 where
13552 @table @code
13553 @item infile
13554 is the full name of the input file, which is an Ada source
13555 file containing preprocessor directives.
13556
13557 @item outfile
13558 is the full name of the output file, which is an Ada source
13559 in standard Ada form. When used with GNAT, this file name will
13560 normally have an ads or adb suffix.
13561
13562 @item deffile
13563 is the full name of a text file containing definitions of
13564 symbols to be referenced by the preprocessor. This argument is
13565 optional, and can be replaced by the use of the @code{-D} switch.
13566
13567 @item switches
13568 is an optional sequence of switches as described in the next section.
13569 @end table
13570
13571 @node Switches for gnatprep
13572 @section Switches for @code{gnatprep}
13573
13574 @table @code
13575
13576 @item -b
13577 Causes both preprocessor lines and the lines deleted by
13578 preprocessing to be replaced by blank lines in the output source file,
13579 preserving line numbers in the output file.
13580
13581 @item -c
13582 Causes both preprocessor lines and the lines deleted
13583 by preprocessing to be retained in the output source as comments marked
13584 with the special string "--! ". This option will result in line numbers
13585 being preserved in the output file.
13586
13587 @item -Dsymbol=value
13588 Defines a new symbol, associated with value. If no value is given on the
13589 command line, then symbol is considered to be @code{True}. This switch
13590 can be used in place of a definition file.
13591
13592
13593 @item -r
13594 Causes a @code{Source_Reference} pragma to be generated that
13595 references the original input file, so that error messages will use
13596 the file name of this original file. The use of this switch implies
13597 that preprocessor lines are not to be removed from the file, so its
13598 use will force @code{-b} mode if
13599 @code{-c}
13600 has not been specified explicitly.
13601
13602 Note that if the file to be preprocessed contains multiple units, then
13603 it will be necessary to @code{gnatchop} the output file from
13604 @code{gnatprep}. If a @code{Source_Reference} pragma is present
13605 in the preprocessed file, it will be respected by
13606 @code{gnatchop -r}
13607 so that the final chopped files will correctly refer to the original
13608 input source file for @code{gnatprep}.
13609
13610 @item -s
13611 Causes a sorted list of symbol names and values to be
13612 listed on the standard output file.
13613
13614 @item -u
13615 Causes undefined symbols to be treated as having the value FALSE in the context
13616 of a preprocessor test. In the absence of this option, an undefined symbol in
13617 a @code{#if} or @code{#elsif} test will be treated as an error.
13618
13619 @end table
13620
13621 @noindent
13622 Note: if neither @code{-b} nor @code{-c} is present,
13623 then preprocessor lines and
13624 deleted lines are completely removed from the output, unless -r is
13625 specified, in which case -b is assumed.
13626
13627 @node Form of Definitions File
13628 @section Form of Definitions File
13629
13630 @noindent
13631 The definitions file contains lines of the form
13632
13633 @smallexample
13634 symbol := value
13635 @end smallexample
13636
13637 @noindent
13638 where symbol is an identifier, following normal Ada (case-insensitive)
13639 rules for its syntax, and value is one of the following:
13640
13641 @itemize @bullet
13642 @item
13643 Empty, corresponding to a null substitution
13644 @item
13645 A string literal using normal Ada syntax
13646 @item
13647 Any sequence of characters from the set
13648 (letters, digits, period, underline).
13649 @end itemize
13650
13651 @noindent
13652 Comment lines may also appear in the definitions file, starting with
13653 the usual @code{--},
13654 and comments may be added to the definitions lines.
13655
13656 @node Form of Input Text for gnatprep
13657 @section Form of Input Text for @code{gnatprep}
13658
13659 @noindent
13660 The input text may contain preprocessor conditional inclusion lines,
13661 as well as general symbol substitution sequences.
13662
13663 The preprocessor conditional inclusion commands have the form
13664
13665 @smallexample
13666 @group
13667 @cartouche
13668 #if @i{expression} [then]
13669    lines
13670 #elsif @i{expression} [then]
13671    lines
13672 #elsif @i{expression} [then]
13673    lines
13674 ...
13675 #else
13676    lines
13677 #end if;
13678 @end cartouche
13679 @end group
13680 @end smallexample
13681
13682 @noindent
13683 In this example, @i{expression} is defined by the following grammar:
13684 @smallexample
13685 @i{expression} ::=  <symbol>
13686 @i{expression} ::=  <symbol> = "<value>"
13687 @i{expression} ::=  <symbol> = <symbol>
13688 @i{expression} ::=  <symbol> 'Defined
13689 @i{expression} ::=  not @i{expression}
13690 @i{expression} ::=  @i{expression} and @i{expression}
13691 @i{expression} ::=  @i{expression} or @i{expression}
13692 @i{expression} ::=  @i{expression} and then @i{expression}
13693 @i{expression} ::=  @i{expression} or else @i{expression}
13694 @i{expression} ::=  ( @i{expression} )
13695 @end smallexample
13696
13697 @noindent
13698 For the first test (@i{expression} ::= <symbol>) the symbol must have
13699 either the value true or false, that is to say the right-hand of the
13700 symbol definition must be one of the (case-insensitive) literals
13701 @code{True} or @code{False}. If the value is true, then the
13702 corresponding lines are included, and if the value is false, they are
13703 excluded.
13704
13705 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
13706 the symbol has been defined in the definition file or by a @code{-D}
13707 switch on the command line. Otherwise, the test is false.
13708
13709 The equality tests are case insensitive, as are all the preprocessor lines.
13710
13711 If the symbol referenced is not defined in the symbol definitions file,
13712 then the effect depends on whether or not switch @code{-u}
13713 is specified. If so, then the symbol is treated as if it had the value
13714 false and the test fails. If this switch is not specified, then
13715 it is an error to reference an undefined symbol. It is also an error to
13716 reference a symbol that is defined with a value other than @code{True}
13717 or @code{False}.
13718
13719 The use of the @code{not} operator inverts the sense of this logical test, so
13720 that the lines are included only if the symbol is not defined.
13721 The @code{then} keyword is optional as shown
13722
13723 The @code{#} must be the first non-blank character on a line, but
13724 otherwise the format is free form. Spaces or tabs may appear between
13725 the @code{#} and the keyword. The keywords and the symbols are case
13726 insensitive as in normal Ada code. Comments may be used on a
13727 preprocessor line, but other than that, no other tokens may appear on a
13728 preprocessor line. Any number of @code{elsif} clauses can be present,
13729 including none at all. The @code{else} is optional, as in Ada.
13730
13731 The @code{#} marking the start of a preprocessor line must be the first
13732 non-blank character on the line, i.e. it must be preceded only by
13733 spaces or horizontal tabs.
13734
13735 Symbol substitution outside of preprocessor lines is obtained by using
13736 the sequence
13737
13738 @smallexample
13739 $symbol
13740 @end smallexample
13741
13742 @noindent
13743 anywhere within a source line, except in a comment or within a
13744 string literal. The identifier
13745 following the @code{$} must match one of the symbols defined in the symbol
13746 definition file, and the result is to substitute the value of the
13747 symbol in place of @code{$symbol} in the output file.
13748
13749 Note that although the substitution of strings within a string literal
13750 is not possible, it is possible to have a symbol whose defined value is
13751 a string literal. So instead of setting XYZ to @code{hello} and writing:
13752
13753 @smallexample
13754 Header : String := "$XYZ";
13755 @end smallexample
13756
13757 @noindent
13758 you should set XYZ to @code{"hello"} and write:
13759
13760 @smallexample
13761 Header : String := $XYZ;
13762 @end smallexample
13763
13764 @noindent
13765 and then the substitution will occur as desired.
13766
13767
13768 @node The GNAT Library Browser gnatls
13769 @chapter The GNAT Library Browser @code{gnatls}
13770 @findex gnatls
13771 @cindex Library browser
13772
13773 @noindent
13774 @code{gnatls} is a tool that outputs information about compiled
13775 units. It gives the relationship between objects, unit names and source
13776 files. It can also be used to check the source dependencies of a unit
13777 as well as various characteristics.
13778
13779 @menu
13780 * Running gnatls::
13781 * Switches for gnatls::
13782 * Examples of gnatls Usage::
13783 @end menu
13784
13785 @node Running gnatls
13786 @section Running @code{gnatls}
13787
13788 @noindent
13789 The @code{gnatls} command has the form
13790
13791 @smallexample
13792 $ gnatls switches @var{object_or_ali_file}
13793 @end smallexample
13794
13795 @noindent
13796 The main argument is the list of object or @file{ali} files
13797 (@pxref{The Ada Library Information Files})
13798 for which information is requested.
13799
13800 In normal mode, without additional option, @code{gnatls} produces a
13801 four-column listing. Each line represents information for a specific
13802 object. The first column gives the full path of the object, the second
13803 column gives the name of the principal unit in this object, the third
13804 column gives the status of the source and the fourth column gives the
13805 full path of the source representing this unit.
13806 Here is a simple example of use:
13807
13808 @smallexample
13809 $ gnatls *.o
13810 ./demo1.o            demo1            DIF demo1.adb
13811 ./demo2.o            demo2             OK demo2.adb
13812 ./hello.o            h1                OK hello.adb
13813 ./instr-child.o      instr.child      MOK instr-child.adb
13814 ./instr.o            instr             OK instr.adb
13815 ./tef.o              tef              DIF tef.adb
13816 ./text_io_example.o  text_io_example   OK text_io_example.adb
13817 ./tgef.o             tgef             DIF tgef.adb
13818 @end smallexample
13819
13820 @noindent
13821 The first line can be interpreted as follows: the main unit which is
13822 contained in
13823 object file @file{demo1.o} is demo1, whose main source is in
13824 @file{demo1.adb}. Furthermore, the version of the source used for the
13825 compilation of demo1 has been modified (DIF). Each source file has a status
13826 qualifier which can be:
13827
13828 @table @code
13829 @item OK (unchanged)
13830 The version of the source file used for the compilation of the
13831 specified unit corresponds exactly to the actual source file.
13832
13833 @item MOK (slightly modified)
13834 The version of the source file used for the compilation of the
13835 specified unit differs from the actual source file but not enough to
13836 require recompilation. If you use gnatmake with the qualifier
13837 @code{-m (minimal recompilation)}, a file marked
13838 MOK will not be recompiled.
13839
13840 @item DIF (modified)
13841 No version of the source found on the path corresponds to the source
13842 used to build this object.
13843
13844 @item ??? (file not found)
13845 No source file was found for this unit.
13846
13847 @item HID (hidden,  unchanged version not first on PATH)
13848 The version of the source that corresponds exactly to the source used
13849 for compilation has been found on the path but it is hidden by another
13850 version of the same source that has been modified.
13851
13852 @end table
13853
13854 @node Switches for gnatls
13855 @section Switches for @code{gnatls}
13856
13857 @noindent
13858 @code{gnatls} recognizes the following switches:
13859
13860 @table @code
13861 @item -a
13862 @cindex @code{-a} (@code{gnatls})
13863 Consider all units, including those of the predefined Ada library.
13864 Especially useful with @code{-d}.
13865
13866 @item -d
13867 @cindex @code{-d} (@code{gnatls})
13868 List sources from which specified units depend on.
13869
13870 @item -h
13871 @cindex @code{-h} (@code{gnatls})
13872 Output the list of options.
13873
13874 @item -o
13875 @cindex @code{-o} (@code{gnatls})
13876 Only output information about object files.
13877
13878 @item -s
13879 @cindex @code{-s} (@code{gnatls})
13880 Only output information about source files.
13881
13882 @item -u
13883 @cindex @code{-u} (@code{gnatls})
13884 Only output information about compilation units.
13885
13886 @item -aO@var{dir}
13887 @itemx -aI@var{dir}
13888 @itemx -I@var{dir}
13889 @itemx  -I-
13890 @itemx -nostdinc
13891 Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags
13892 (see @ref{Switches for gnatmake}).
13893
13894 @item --RTS=@var{rts-path}
13895 @cindex @code{--RTS} (@code{gnatls})
13896 Specifies the default location of the runtime library. Same meaning as the
13897 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13898
13899 @item -v
13900 @cindex @code{-s} (@code{gnatls})
13901 Verbose mode. Output the complete source and object paths. Do not use
13902 the default column layout but instead use long format giving as much as
13903 information possible on each requested units, including special
13904 characteristics such as:
13905
13906 @table @code
13907 @item  Preelaborable
13908 The unit is preelaborable in the Ada 95 sense.
13909
13910 @item No_Elab_Code
13911 No elaboration code has been produced by the compiler for this unit.
13912
13913 @item Pure
13914 The unit is pure in the Ada 95 sense.
13915
13916 @item Elaborate_Body
13917 The unit contains a pragma Elaborate_Body.
13918
13919 @item Remote_Types
13920 The unit contains a pragma Remote_Types.
13921
13922 @item Shared_Passive
13923 The unit contains a pragma Shared_Passive.
13924
13925 @item Predefined
13926 This unit is part of the predefined environment and cannot be modified
13927 by the user.
13928
13929 @item Remote_Call_Interface
13930 The unit contains a pragma Remote_Call_Interface.
13931
13932 @end table
13933
13934 @end table
13935
13936 @node Examples of gnatls Usage
13937 @section Example of @code{gnatls} Usage
13938
13939 @noindent
13940 Example of using the verbose switch. Note how the source and
13941 object paths are affected by the -I switch.
13942
13943 @smallexample
13944 $ gnatls -v -I.. demo1.o
13945
13946 GNATLS 3.10w (970212) Copyright 1999 Free Software Foundation, Inc.
13947
13948 Source Search Path:
13949    <Current_Directory>
13950    ../
13951    /home/comar/local/adainclude/
13952
13953 Object Search Path:
13954    <Current_Directory>
13955    ../
13956    /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/
13957
13958 ./demo1.o
13959    Unit =>
13960      Name   => demo1
13961      Kind   => subprogram body
13962      Flags  => No_Elab_Code
13963      Source => demo1.adb    modified
13964 @end smallexample
13965
13966 @noindent
13967 The following is an example of use of the dependency list.
13968 Note the use of the -s switch
13969 which gives a straight list of source files. This can be useful for
13970 building specialized scripts.
13971
13972 @smallexample
13973 $ gnatls -d demo2.o
13974 ./demo2.o   demo2        OK demo2.adb
13975                          OK gen_list.ads
13976                          OK gen_list.adb
13977                          OK instr.ads
13978                          OK instr-child.ads
13979
13980 $ gnatls -d -s -a demo1.o
13981 demo1.adb
13982 /home/comar/local/adainclude/ada.ads
13983 /home/comar/local/adainclude/a-finali.ads
13984 /home/comar/local/adainclude/a-filico.ads
13985 /home/comar/local/adainclude/a-stream.ads
13986 /home/comar/local/adainclude/a-tags.ads
13987 gen_list.ads
13988 gen_list.adb
13989 /home/comar/local/adainclude/gnat.ads
13990 /home/comar/local/adainclude/g-io.ads
13991 instr.ads
13992 /home/comar/local/adainclude/system.ads
13993 /home/comar/local/adainclude/s-exctab.ads
13994 /home/comar/local/adainclude/s-finimp.ads
13995 /home/comar/local/adainclude/s-finroo.ads
13996 /home/comar/local/adainclude/s-secsta.ads
13997 /home/comar/local/adainclude/s-stalib.ads
13998 /home/comar/local/adainclude/s-stoele.ads
13999 /home/comar/local/adainclude/s-stratt.ads
14000 /home/comar/local/adainclude/s-tasoli.ads
14001 /home/comar/local/adainclude/s-unstyp.ads
14002 /home/comar/local/adainclude/unchconv.ads
14003 @end smallexample
14004
14005
14006 @node GNAT and Libraries
14007 @chapter GNAT and Libraries
14008 @cindex Library, building, installing
14009
14010 @noindent
14011 This chapter addresses some of the issues related to building and using
14012 a library with GNAT. It also shows how the GNAT run-time library can be
14013 recompiled.
14014
14015 @menu
14016 * Creating an Ada Library::
14017 * Installing an Ada Library::
14018 * Using an Ada Library::
14019 * Creating an Ada Library to be Used in a Non-Ada Context::
14020 * Rebuilding the GNAT Run-Time Library::
14021 @end menu
14022
14023 @node Creating an Ada Library
14024 @section Creating an Ada Library
14025
14026 @noindent
14027 In the GNAT environment, a library has two components:
14028 @itemize @bullet
14029 @item
14030 Source files.
14031 @item
14032 Compiled code and Ali files. See @ref{The Ada Library Information Files}.
14033 @end itemize
14034
14035 @noindent
14036 In order to use other packages @ref{The GNAT Compilation Model}
14037 requires a certain number of sources to be available to the compiler.
14038 The minimal set of
14039 sources required includes the specs of all the packages that make up the
14040 visible part of the library as well as all the sources upon which they
14041 depend. The bodies of all visible generic units must also be provided.
14042 @noindent
14043 Although it is not strictly mandatory, it is recommended that all sources
14044 needed to recompile the library be provided, so that the user can make
14045 full use of inter-unit inlining and source-level debugging. This can also
14046 make the situation easier for users that need to upgrade their compilation
14047 toolchain and thus need to recompile the library from sources.
14048
14049 @noindent
14050 The compiled code can be provided in different ways. The simplest way is
14051 to provide directly the set of objects produced by the compiler during
14052 the compilation of the library. It is also possible to group the objects
14053 into an archive using whatever commands are provided by the operating
14054 system. Finally, it is also possible to create a shared library (see
14055 option -shared in the GCC manual).
14056
14057 @noindent
14058 There are various possibilities for compiling the units that make up the
14059 library: for example with a Makefile @ref{Using the GNU make Utility},
14060 or with a conventional script.
14061 For simple libraries, it is also possible to create a
14062 dummy main program which depends upon all the packages that comprise the
14063 interface of the library. This dummy main program can then be given to
14064 gnatmake, in order to build all the necessary objects. Here is an example
14065 of such a dummy program and the generic commands used to build an
14066 archive or a shared library.
14067
14068 @smallexample
14069 @iftex
14070 @leftskip=.7cm
14071 @end iftex
14072 @b{with} My_Lib.Service1;
14073 @b{with} My_Lib.Service2;
14074 @b{with} My_Lib.Service3;
14075 @b{procedure} My_Lib_Dummy @b{is}
14076 @b{begin}
14077    @b{null};
14078 @b{end};
14079
14080 # compiling the library
14081 $ gnatmake -c my_lib_dummy.adb
14082
14083 # we don't need the dummy object itself
14084 $ rm my_lib_dummy.o my_lib_dummy.ali
14085
14086 # create an archive with the remaining objects
14087 $ ar rc libmy_lib.a *.o
14088 # some systems may require "ranlib" to be run as well
14089
14090 # or create a shared library
14091 $ gcc -shared -o libmy_lib.so *.o
14092 # some systems may require the code to have been compiled with -fPIC
14093 @end smallexample
14094
14095 @noindent
14096 When the objects are grouped in an archive or a shared library, the user
14097 needs to specify the desired library at link time, unless a pragma
14098 linker_options has been used in one of the sources:
14099 @smallexample
14100 @b{pragma} Linker_Options ("-lmy_lib");
14101 @end smallexample
14102
14103 @node Installing an Ada Library
14104 @section Installing an Ada Library
14105
14106 @noindent
14107 In the GNAT model, installing a library consists in copying into a specific
14108 location the files that make up this library. It is possible to install
14109 the sources in a different directory from the other files (ALI, objects,
14110 archives) since the source path and the object path can easily be
14111 specified separately.
14112
14113 @noindent
14114 For general purpose libraries, it is possible for the system
14115 administrator to put those libraries in the default compiler paths. To
14116 achieve this, he must specify their location in the configuration files
14117 "ada_source_path" and "ada_object_path" that must be located in the GNAT
14118 installation tree at the same place as the gcc spec file. The location of
14119 the gcc spec file can be determined as follows:
14120 @smallexample
14121 $ gcc -v
14122 @end smallexample
14123
14124 @noindent
14125 The configuration files mentioned above have simple format: each line in them
14126 must contain one unique
14127 directory name. Those names are added to the corresponding path
14128 in their order of appearance in the file. The names can be either absolute
14129 or relative, in the latter case, they are relative to where theses files
14130 are located.
14131
14132 @noindent
14133 "ada_source_path" and "ada_object_path" might actually not be present in a
14134 GNAT installation, in which case, GNAT will look for its run-time library in
14135 the directories "adainclude" for the sources and "adalib" for the
14136 objects and ALI files. When the files exist, the compiler does not
14137 look in "adainclude" and "adalib" at all, and thus the "ada_source_path" file
14138 must contain the location for the GNAT run-time sources (which can simply
14139 be "adainclude"). In the same way, the "ada_object_path" file must contain
14140 the location for the GNAT run-time objects (which can simply
14141 be "adalib").
14142
14143 @noindent
14144 You can also specify a new default path to the runtime library at compilation
14145 time with the switch "--RTS=@var{rts-path}". You can easily choose and change
14146 the runtime you want your program to be compiled with. This switch is
14147 recognized by gcc, gnatmake, gnatbind, gnatls, gnatfind and gnatxref.
14148
14149 @noindent
14150 It is possible to install a library before or after the standard GNAT
14151 library, by reordering the lines in the configuration files. In general, a
14152 library must be installed before the GNAT library if it redefines any part of it.
14153
14154 @node Using an Ada Library
14155 @section Using an Ada Library
14156
14157 @noindent
14158 In order to use a Ada library, you need to make sure that this
14159 library is on both your source and object path
14160 @ref{Search Paths and the Run-Time Library (RTL)}
14161 and @ref{Search Paths for gnatbind}. For
14162 instance, you can use the library "mylib" installed in "/dir/my_lib_src"
14163 and "/dir/my_lib_obj" with the following commands:
14164
14165 @smallexample
14166 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
14167   -largs -lmy_lib
14168 @end smallexample
14169
14170 @noindent
14171 This can be simplified down to the following:
14172 @smallexample
14173 $ gnatmake my_appl
14174 @end smallexample
14175 when the following conditions are met:
14176 @itemize @bullet
14177 @item
14178 "/dir/my_lib_src" has been added by the user to the environment
14179 variable "ADA_INCLUDE_PATH", or by the administrator to the file
14180 "ada_source_path"
14181 @item
14182 "/dir/my_lib_obj" has been added by the user to the environment
14183 variable "ADA_OBJECTS_PATH", or by the administrator to the file
14184 "ada_object_path"
14185 @item
14186 a pragma linker_options, as mentioned in @ref{Creating an Ada Library}
14187 as been added to the sources.
14188 @end itemize
14189 @noindent
14190
14191 @node Creating an Ada Library to be Used in a Non-Ada Context
14192 @section Creating an Ada Library to be Used in a Non-Ada Context
14193
14194 @noindent
14195 The previous sections detailed how to create and install a library that
14196 was usable from an Ada main program. Using this library in a non-Ada
14197 context is not possible, because the elaboration of the library is
14198 automatically done as part of the main program elaboration.
14199
14200 GNAT also provides the ability to build libraries that can be used both
14201 in an Ada and non-Ada context.  This section describes how to build such
14202 a library, and then how to use it from a C program. The method for
14203 interfacing with the library from other languages such as Fortran for
14204 instance remains the same.
14205
14206 @subsection Creating the Library
14207
14208 @itemize @bullet
14209 @item Identify the units representing the interface of the library.
14210
14211 Here is an example of simple library interface:
14212
14213 @smallexample
14214 package Interface is
14215
14216    procedure Do_Something;
14217
14218    procedure Do_Something_Else;
14219
14220 end Interface;
14221 @end smallexample
14222
14223 @item Use @code{pragma Export} or @code{pragma Convention} for the
14224 exported entities.
14225
14226 Our package @code{Interface} is then updated as follow:
14227 @smallexample
14228 package Interface is
14229
14230    procedure Do_Something;
14231    pragma Export (C, Do_Something, "do_something");
14232
14233    procedure Do_Something_Else;
14234    pragma Export (C, Do_Something_Else, "do_something_else");
14235
14236 end Interface;
14237 @end smallexample
14238
14239 @item Compile all the units composing the library.
14240
14241 @item Bind the library objects.
14242
14243 This step is performed by invoking gnatbind with the @code{-L<prefix>}
14244 switch. @code{gnatbind} will then generate the library elaboration
14245 procedure (named @code{<prefix>init}) and the run-time finalization
14246 procedure (named @code{<prefix>final}).
14247
14248 @smallexample
14249 # generate the binder file in Ada
14250 $ gnatbind -Lmylib interface
14251
14252 # generate the binder file in C
14253 $ gnatbind -C -Lmylib interface
14254 @end smallexample
14255
14256 @item Compile the files generated by the binder
14257
14258 @smallexample
14259 $ gcc -c b~interface.adb
14260 @end smallexample
14261
14262 @item Create the library;
14263
14264 The procedure is identical to the procedure explained in
14265 @ref{Creating an Ada Library},
14266 except that @file{b~interface.o} needs to be added to
14267 the list of objects.
14268
14269 @smallexample
14270 # create an archive file
14271 $ ar cr libmylib.a b~interface.o <other object files>
14272
14273 # create a shared library
14274 $ gcc -shared -o libmylib.so b~interface.o <other object files>
14275 @end smallexample
14276
14277 @item Provide a "foreign" view of the library interface;
14278
14279 The example below shows the content of @code{mylib_interface.h} (note
14280 that there is no rule for the naming of this file, any name can be used)
14281 @smallexample
14282 /* the library elaboration procedure */
14283 extern void mylibinit (void);
14284
14285 /* the library finalization procedure */
14286 extern void mylibfinal (void);
14287
14288 /* the interface exported by the library */
14289 extern void do_something (void);
14290 extern void do_something_else (void);
14291 @end smallexample
14292 @end itemize
14293
14294 @subsection Using the Library
14295
14296 @noindent
14297 Libraries built as explained above can be used from any program, provided
14298 that the elaboration procedures (named @code{mylibinit} in the previous
14299 example) are called before the library services are used. Any number of
14300 libraries can be used simultaneously, as long as the elaboration
14301 procedure of each library is called.
14302
14303 Below is an example of C program that uses our @code{mylib} library.
14304
14305 @smallexample
14306 #include "mylib_interface.h"
14307
14308 int
14309 main (void)
14310 @{
14311    /* First, elaborate the library before using it */
14312    mylibinit ();
14313
14314    /* Main program, using the library exported entities */
14315    do_something ();
14316    do_something_else ();
14317
14318    /* Library finalization at the end of the program */
14319    mylibfinal ();
14320    return 0;
14321 @}
14322 @end smallexample
14323
14324 @noindent
14325 Note that this same library can be used from an equivalent Ada main
14326 program. In addition, if the libraries are installed as detailed in
14327 @ref{Installing an Ada Library}, it is not necessary to invoke the
14328 library elaboration and finalization routines. The binder will ensure
14329 that this is done as part of the main program elaboration and
14330 finalization phases.
14331
14332 @subsection The Finalization Phase
14333
14334 @noindent
14335 Invoking any library finalization procedure generated by @code{gnatbind}
14336 shuts down the Ada run time permanently. Consequently, the finalization
14337 of all Ada libraries must be performed at the end of the program. No
14338 call to these libraries nor the Ada run time should be made past the
14339 finalization phase.
14340
14341 @subsection Restrictions in Libraries
14342
14343 @noindent
14344 The pragmas listed below should be used with caution inside libraries,
14345 as they can create incompatibilities with other Ada libraries:
14346 @itemize @bullet
14347 @item pragma @code{Locking_Policy}
14348 @item pragma @code{Queuing_Policy}
14349 @item pragma @code{Task_Dispatching_Policy}
14350 @item pragma @code{Unreserve_All_Interrupts}
14351 @end itemize
14352 When using a library that contains such pragmas, the user must make sure
14353 that all libraries use the same pragmas with the same values. Otherwise,
14354 a @code{Program_Error} will
14355 be raised during the elaboration of the conflicting
14356 libraries. The usage of these pragmas and its consequences for the user
14357 should therefore be well documented.
14358
14359 Similarly, the traceback in exception occurrences mechanism should be
14360 enabled or disabled in a consistent manner across all libraries.
14361 Otherwise, a Program_Error will be raised during the elaboration of the
14362 conflicting libraries.
14363
14364 If the @code{'Version} and @code{'Body_Version}
14365 attributes are used inside a library, then it is necessary to
14366 perform a @code{gnatbind} step that mentions all ali files in all
14367 libraries, so that version identifiers can be properly computed.
14368 In practice these attributes are rarely used, so this is unlikely
14369 to be a consideration.
14370
14371 @node  Rebuilding the GNAT Run-Time Library
14372 @section Rebuilding the GNAT Run-Time Library
14373
14374 @noindent
14375 It may be useful to recompile the GNAT library in various contexts, the
14376 most important one being the use of partition-wide configuration pragmas
14377 such as Normalize_Scalar. A special Makefile called
14378 @code{Makefile.adalib} is provided to that effect and can be found in
14379 the directory containing the GNAT library. The location of this
14380 directory depends on the way the GNAT environment has been installed and can
14381 be determined by means of the command:
14382
14383 @smallexample
14384 $ gnatls -v
14385 @end smallexample
14386
14387 @noindent
14388 The last entry in the object search path usually contains the
14389 gnat library. This Makefile contains its own documentation and in
14390 particular the set of instructions needed to rebuild a new library and
14391 to use it.
14392
14393 @node Using the GNU make Utility
14394 @chapter Using the GNU @code{make} Utility
14395 @findex make
14396
14397 @noindent
14398 This chapter offers some examples of makefiles that solve specific
14399 problems. It does not explain how to write a makefile (see the GNU make
14400 documentation), nor does it try to replace the @code{gnatmake} utility
14401 (@pxref{The GNAT Make Program gnatmake}).
14402
14403 All the examples in this section are specific to the GNU version of
14404 make. Although @code{make} is a standard utility, and the basic language
14405 is the same, these examples use some advanced features found only in
14406 @code{GNU make}.
14407
14408 @menu
14409 * Using gnatmake in a Makefile::
14410 * Automatically Creating a List of Directories::
14411 * Generating the Command Line Switches::
14412 * Overcoming Command Line Length Limits::
14413 @end menu
14414
14415 @node Using gnatmake in a Makefile
14416 @section Using gnatmake in a Makefile
14417 @findex makefile
14418 @cindex GNU make
14419
14420 @noindent
14421 Complex project organizations can be handled in a very powerful way by
14422 using GNU make combined with gnatmake. For instance, here is a Makefile
14423 which allows you to build each subsystem of a big project into a separate
14424 shared library. Such a makefile allows you to significantly reduce the link
14425 time of very big applications while maintaining full coherence at
14426 each step of the build process.
14427
14428 The list of dependencies are handled automatically by
14429 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
14430 the appropriate directories.
14431
14432 Note that you should also read the example on how to automatically
14433 create the list of directories (@pxref{Automatically Creating a List of Directories})
14434 which might help you in case your project has a lot of
14435 subdirectories.
14436
14437 @smallexample
14438 @iftex
14439 @leftskip=0cm
14440 @font@heightrm=cmr8
14441 @heightrm
14442 @end iftex
14443 ## This Makefile is intended to be used with the following directory
14444 ## configuration:
14445 ##  - The sources are split into a series of csc (computer software components)
14446 ##    Each of these csc is put in its own directory.
14447 ##    Their name are referenced by the directory names.
14448 ##    They will be compiled into shared library (although this would also work
14449 ##    with static libraries
14450 ##  - The main program (and possibly other packages that do not belong to any
14451 ##    csc is put in the top level directory (where the Makefile is).
14452 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
14453 ##                    \_ second_csc (sources) __ lib (will contain the library)
14454 ##                    \_ ...
14455 ## Although this Makefile is build for shared library, it is easy to modify
14456 ## to build partial link objects instead (modify the lines with -shared and
14457 ## gnatlink below)
14458 ##
14459 ## With this makefile, you can change any file in the system or add any new
14460 ## file, and everything will be recompiled correctly (only the relevant shared
14461 ## objects will be recompiled, and the main program will be re-linked).
14462
14463 # The list of computer software component for your project. This might be
14464 # generated automatically.
14465 CSC_LIST=aa bb cc
14466
14467 # Name of the main program (no extension)
14468 MAIN=main
14469
14470 # If we need to build objects with -fPIC, uncomment the following line
14471 #NEED_FPIC=-fPIC
14472
14473 # The following variable should give the directory containing libgnat.so
14474 # You can get this directory through 'gnatls -v'. This is usually the last
14475 # directory in the Object_Path.
14476 GLIB=...
14477
14478 # The directories for the libraries
14479 # (This macro expands the list of CSC to the list of shared libraries, you
14480 # could simply use the expanded form :
14481 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
14482 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
14483
14484 $@{MAIN@}: objects $@{LIB_DIR@}
14485     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
14486     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
14487
14488 objects::
14489     # recompile the sources
14490     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
14491
14492 # Note: In a future version of GNAT, the following commands will be simplified
14493 # by a new tool, gnatmlib
14494 $@{LIB_DIR@}:
14495     mkdir -p $@{dir $@@ @}
14496     cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
14497     cd $@{dir $@@ @}; cp -f ../*.ali .
14498
14499 # The dependencies for the modules
14500 # Note that we have to force the expansion of *.o, since in some cases make won't
14501 # be able to do it itself.
14502 aa/lib/libaa.so: $@{wildcard aa/*.o@}
14503 bb/lib/libbb.so: $@{wildcard bb/*.o@}
14504 cc/lib/libcc.so: $@{wildcard cc/*.o@}
14505
14506 # Make sure all of the shared libraries are in the path before starting the
14507 # program
14508 run::
14509     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
14510
14511 clean::
14512     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
14513     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
14514     $@{RM@} $@{CSC_LIST:%=%/*.o@}
14515     $@{RM@} *.o *.ali $@{MAIN@}
14516 @end smallexample
14517
14518 @node Automatically Creating a List of Directories
14519 @section Automatically Creating a List of Directories
14520
14521 @noindent
14522 In most makefiles, you will have to specify a list of directories, and
14523 store it in a variable. For small projects, it is often easier to
14524 specify each of them by hand, since you then have full control over what
14525 is the proper order for these directories, which ones should be
14526 included...
14527
14528 However, in larger projects, which might involve hundreds of
14529 subdirectories, it might be more convenient to generate this list
14530 automatically.
14531
14532 The example below presents two methods. The first one, although less
14533 general, gives you more control over the list. It involves wildcard
14534 characters, that are automatically expanded by @code{make}. Its
14535 shortcoming is that you need to explicitly specify some of the
14536 organization of your project, such as for instance the directory tree
14537 depth, whether some directories are found in a separate tree,...
14538
14539 The second method is the most general one. It requires an external
14540 program, called @code{find}, which is standard on all Unix systems. All
14541 the directories found under a given root directory will be added to the
14542 list.
14543
14544 @smallexample
14545 @iftex
14546 @leftskip=0cm
14547 @font@heightrm=cmr8
14548 @heightrm
14549 @end iftex
14550 # The examples below are based on the following directory hierarchy:
14551 # All the directories can contain any number of files
14552 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
14553 #                       ->  ab
14554 #                       ->  ac
14555 #                ->  b  ->  ba  ->  baa
14556 #                       ->  bb
14557 #                       ->  bc
14558 # This Makefile creates a variable called DIRS, that can be reused any time
14559 # you need this list (see the other examples in this section)
14560
14561 # The root of your project's directory hierarchy
14562 ROOT_DIRECTORY=.
14563
14564 ####
14565 # First method: specify explicitly the list of directories
14566 # This allows you to specify any subset of all the directories you need.
14567 ####
14568
14569 DIRS := a/aa/ a/ab/ b/ba/
14570
14571 ####
14572 # Second method: use wildcards
14573 # Note that the argument(s) to wildcard below should end with a '/'.
14574 # Since wildcards also return file names, we have to filter them out
14575 # to avoid duplicate directory names.
14576 # We thus use make's @code{dir} and @code{sort} functions.
14577 # It sets DIRs to the following value (note that the directories aaa and baa
14578 # are not given, unless you change the arguments to wildcard).
14579 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
14580 ####
14581
14582 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/ $@{ROOT_DIRECTORY@}/*/*/@}@}@}
14583
14584 ####
14585 # Third method: use an external program
14586 # This command is much faster if run on local disks, avoiding NFS slowdowns.
14587 # This is the most complete command: it sets DIRs to the following value:
14588 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
14589 ####
14590
14591 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
14592
14593 @end smallexample
14594
14595 @node Generating the Command Line Switches
14596 @section Generating the Command Line Switches
14597
14598 @noindent
14599 Once you have created the list of directories as explained in the
14600 previous section (@pxref{Automatically Creating a List of Directories}),
14601 you can easily generate the command line arguments to pass to gnatmake.
14602
14603 For the sake of completeness, this example assumes that the source path
14604 is not the same as the object path, and that you have two separate lists
14605 of directories.
14606
14607 @smallexample
14608 # see "Automatically creating a list of directories" to create
14609 # these variables
14610 SOURCE_DIRS=
14611 OBJECT_DIRS=
14612
14613 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
14614 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
14615
14616 all:
14617         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
14618 @end smallexample
14619
14620 @node Overcoming Command Line Length Limits
14621 @section Overcoming Command Line Length Limits
14622
14623 @noindent
14624 One problem that might be encountered on big projects is that many
14625 operating systems limit the length of the command line. It is thus hard to give
14626 gnatmake the list of source and object directories.
14627
14628 This example shows how you can set up environment variables, which will
14629 make @code{gnatmake} behave exactly as if the directories had been
14630 specified on the command line, but have a much higher length limit (or
14631 even none on most systems).
14632
14633 It assumes that you have created a list of directories in your Makefile,
14634 using one of the methods presented in
14635 @ref{Automatically Creating a List of Directories}.
14636 For the sake of completeness, we assume that the object
14637 path (where the ALI files are found) is different from the sources patch.
14638
14639 Note a small trick in the Makefile below: for efficiency reasons, we
14640 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
14641 expanded immediately by @code{make}. This way we overcome the standard
14642 make behavior which is to expand the variables only when they are
14643 actually used.
14644
14645 @smallexample
14646 @iftex
14647 @leftskip=0cm
14648 @font@heightrm=cmr8
14649 @heightrm
14650 @end iftex
14651 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
14652 # This is the same thing as putting the -I arguments on the command line.
14653 # (the equivalent of using -aI on the command line would be to define
14654 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
14655 # You can of course have different values for these variables.
14656 #
14657 # Note also that we need to keep the previous values of these variables, since
14658 # they might have been set before running 'make' to specify where the GNAT
14659 # library is installed.
14660
14661 # see "Automatically creating a list of directories" to create these
14662 # variables
14663 SOURCE_DIRS=
14664 OBJECT_DIRS=
14665
14666 empty:=
14667 space:=$@{empty@} $@{empty@}
14668 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
14669 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
14670 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
14671 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
14672 export ADA_INCLUDE_PATH
14673 export ADA_OBJECT_PATH
14674
14675 all:
14676         gnatmake main_unit
14677 @end smallexample
14678
14679
14680 @node Finding Memory Problems with GNAT Debug Pool
14681 @chapter Finding Memory Problems with GNAT Debug Pool
14682 @findex Debug Pool
14683 @cindex storage, pool, memory corruption
14684
14685 @noindent
14686 The use of unchecked deallocation and unchecked conversion can easily
14687 lead to incorrect memory references. The problems generated by such
14688 references are usually difficult to tackle because the symptoms can be
14689 very remote from the origin of the problem. In such cases, it is
14690 very helpful to detect the problem as early as possible. This is the
14691 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
14692
14693 @noindent
14694 In order to use the GNAT specific debugging pool, the user must
14695 associate a debug pool object with each of the access types that may be
14696 related to suspected memory problems. See Ada Reference Manual
14697 13.11.
14698 @smallexample
14699 @b{type} Ptr @b{is} @b{access} Some_Type;
14700 Pool : GNAT.Debug_Pools.Debug_Pool;
14701 @b{for} Ptr'Storage_Pool @b{use} Pool;
14702 @end smallexample
14703
14704 @code{GNAT.Debug_Pools} is derived from of a GNAT-specific kind of
14705 pool: the Checked_Pool. Such pools, like standard Ada storage pools,
14706 allow the user to redefine allocation and deallocation strategies. They
14707 also provide a checkpoint for each dereference, through the use of
14708 the primitive operation @code{Dereference} which is implicitly called at
14709 each dereference of an access value.
14710
14711 Once an access type has been associated with a debug pool, operations on
14712 values of the type may raise four distinct exceptions,
14713 which correspond to four potential kinds of memory corruption:
14714 @itemize @bullet
14715 @item
14716 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
14717 @item
14718 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
14719 @item
14720 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
14721 @item
14722 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
14723 @end itemize
14724
14725 @noindent
14726 For types associated with a Debug_Pool, dynamic allocation is performed using
14727 the standard
14728 GNAT allocation routine. References to all allocated chunks of memory
14729 are kept in an internal dictionary. The deallocation strategy consists
14730 in not releasing the memory to the underlying system but rather to fill
14731 it with a memory pattern easily recognizable during debugging sessions:
14732 The memory pattern is the old IBM hexadecimal convention: 16#DEADBEEF#.
14733 Upon each dereference, a check is made that the access value denotes a properly
14734 allocated memory location. Here is a complete example of use of
14735 @code{Debug_Pools}, that includes typical instances of  memory corruption:
14736 @smallexample
14737 @iftex
14738 @leftskip=0cm
14739 @end iftex
14740 @b{with} Gnat.Io; @b{use} Gnat.Io;
14741 @b{with} Unchecked_Deallocation;
14742 @b{with} Unchecked_Conversion;
14743 @b{with} GNAT.Debug_Pools;
14744 @b{with} System.Storage_Elements;
14745 @b{with} Ada.Exceptions; @b{use} Ada.Exceptions;
14746 @b{procedure} Debug_Pool_Test @b{is}
14747
14748    @b{type} T @b{is} @b{access} Integer;
14749    @b{type} U @b{is} @b{access} @b{all} T;
14750
14751    P : GNAT.Debug_Pools.Debug_Pool;
14752    @b{for} T'Storage_Pool @b{use} P;
14753
14754    @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (Integer, T);
14755    @b{function} UC @b{is} @b{new} Unchecked_Conversion (U, T);
14756    A, B : @b{aliased} T;
14757
14758    @b{procedure} Info @b{is} @b{new} GNAT.Debug_Pools.Print_Info(Put_Line);
14759
14760 @b{begin}
14761    Info (P);
14762    A := @b{new} Integer;
14763    B := @b{new} Integer;
14764    B := A;
14765    Info (P);
14766    Free (A);
14767    @b{begin}
14768       Put_Line (Integer'Image(B.@b{all}));
14769    @b{exception}
14770       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
14771    @b{end};
14772    @b{begin}
14773       Free (B);
14774    @b{exception}
14775       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
14776    @b{end};
14777    B := UC(A'Access);
14778    @b{begin}
14779       Put_Line (Integer'Image(B.@b{all}));
14780    @b{exception}
14781       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
14782    @b{end};
14783    @b{begin}
14784       Free (B);
14785    @b{exception}
14786       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
14787    @b{end};
14788    Info (P);
14789 @b{end} Debug_Pool_Test;
14790 @end smallexample
14791 @noindent
14792 The debug pool mechanism provides the following precise diagnostics on the
14793 execution of this erroneous program:
14794 @smallexample
14795 Debug Pool info:
14796   Total allocated bytes :  0
14797   Total deallocated bytes :  0
14798   Current Water Mark:  0
14799   High Water Mark:  0
14800
14801 Debug Pool info:
14802   Total allocated bytes :  8
14803   Total deallocated bytes :  0
14804   Current Water Mark:  8
14805   High Water Mark:  8
14806
14807 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
14808 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
14809 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
14810 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
14811 Debug Pool info:
14812   Total allocated bytes :  8
14813   Total deallocated bytes :  4
14814   Current Water Mark:  4
14815   High Water Mark:  8
14816
14817 @end smallexample
14818
14819 @node Creating Sample Bodies Using gnatstub
14820 @chapter Creating Sample Bodies Using @code{gnatstub}
14821 @findex gnatstub
14822
14823 @noindent
14824 @code{gnatstub} creates body stubs, that is, empty but compilable bodies
14825 for library unit declarations.
14826
14827 To create a body stub, @code{gnatstub} has to compile the library
14828 unit declaration. Therefore, bodies can be created only for legal
14829 library units. Moreover, if a library unit depends semantically upon
14830 units located outside the current directory, you have to provide
14831 the source search path when calling @code{gnatstub}, see the description
14832 of @code{gnatstub} switches below.
14833
14834 @menu
14835 * Running gnatstub::
14836 * Switches for gnatstub::
14837 @end menu
14838
14839 @node Running gnatstub
14840 @section Running @code{gnatstub}
14841
14842 @noindent
14843 @code{gnatstub} has the command-line interface of the form
14844
14845 @smallexample
14846 $ gnatstub [switches] filename [directory]
14847 @end smallexample
14848
14849 @noindent
14850 where
14851 @table @code
14852 @item filename
14853 is the name of the source file that contains a library unit declaration
14854 for which a body must be created. This name should follow the GNAT file name
14855 conventions. No crunching is allowed for this file name. The file
14856 name may contain the path information.
14857
14858 @item directory
14859 indicates the directory to place a body stub (default is the
14860 current directory)
14861
14862 @item switches
14863 is an optional sequence of switches as described in the next section
14864 @end table
14865
14866 @node Switches for gnatstub
14867 @section Switches for @code{gnatstub}
14868
14869 @table @code
14870
14871 @item -f
14872 If the destination directory already contains a file with a name of the body file
14873 for the argument spec file, replace it with the generated body stub.
14874
14875 @item -hs
14876 Put the comment header (i.e. all the comments preceding the
14877 compilation unit) from the source of the library unit declaration
14878 into the body stub.
14879
14880 @item -hg
14881 Put a sample comment header into the body stub.
14882
14883 @item -IDIR
14884 @itemx -I-
14885 These switches have the same meaning as in calls to gcc.
14886 They define the source search path in the call to gcc issued
14887 by @code{gnatstub} to compile an argument source file.
14888
14889 @item -i@var{n}
14890 (@var{n} is a decimal natural number). Set the indentation level in the
14891 generated body sample to n, '-i0' means "no indentation",
14892 the default indentation is 3.
14893
14894 @item -k
14895 Do not remove the tree file (i.e. the snapshot of the compiler internal
14896 structures used by @code{gnatstub}) after creating the body stub.
14897
14898 @item -l@var{n}
14899 (@var{n} is a decimal positive number) Set the maximum line length in the
14900 body stub to n, the default is 78.
14901
14902 @item -q
14903 Quiet mode: do not generate a confirmation when a body is
14904 successfully created or a message when a body is not required for an
14905 argument unit.
14906
14907 @item -r
14908 Reuse the tree file (if it exists) instead of creating it: instead of
14909 creating the tree file for the library unit declaration, gnatstub
14910 tries to find it in the current directory and use it for creating
14911 a body. If the tree file is not found, no body is created. @code{-r}
14912 also implies @code{-k}, whether or not
14913 @code{-k} is set explicitly.
14914
14915 @item -t
14916 Overwrite the existing tree file: if the current directory already
14917 contains the file which, according to the GNAT file name rules should
14918 be considered as a tree file for the argument source file, gnatstub
14919 will refuse to create the tree file needed to create a body sampler,
14920 unless @code{-t} option is set
14921
14922 @item -v
14923 Verbose mode: generate version information.
14924
14925 @end table
14926
14927 @node Reducing the Size of Ada Executables with gnatelim
14928 @chapter Reducing the Size of Ada Executables with @code{gnatelim}
14929 @findex gnatelim
14930
14931 @menu
14932 * About gnatelim::
14933 * Eliminate Pragma::
14934 * Tree Files::
14935 * Preparing Tree and Bind Files for gnatelim::
14936 * Running gnatelim::
14937 * Correcting the List of Eliminate Pragmas::
14938 * Making Your Executables Smaller::
14939 * Summary of the gnatelim Usage Cycle::
14940 @end menu
14941
14942 @node About gnatelim
14943 @section About @code{gnatelim}
14944
14945 @noindent
14946 When a program shares a set of Ada
14947 packages with other programs, it may happen that this program uses
14948 only a fraction of the subprograms defined in these packages. The code
14949 created for these unused subprograms increases the size of the executable.
14950
14951 @code{gnatelim} tracks unused subprograms in an Ada program and
14952 outputs a list of GNAT-specific @code{Eliminate} pragmas (see next
14953 section) marking all the subprograms that are declared but never called.
14954 By placing the list of @code{Eliminate} pragmas in the GNAT configuration
14955 file @file{gnat.adc} and recompiling your program, you may decrease the
14956 size of its executable, because the compiler will not generate the code
14957 for 'eliminated' subprograms.
14958
14959 @code{gnatelim} needs as its input data a set of tree files
14960 (see @ref{Tree Files}) representing all the components of a program to
14961 process and a bind file for a main subprogram (see
14962 @ref{Preparing Tree and Bind Files for gnatelim}).
14963
14964 @node Eliminate Pragma
14965 @section @code{Eliminate} Pragma
14966 @findex Eliminate
14967
14968 @noindent
14969 The simplified syntax of the Eliminate pragma used by @code{gnatelim} is:
14970
14971 @smallexample
14972 @cartouche
14973 @b{pragma} Eliminate (Library_Unit_Name, Subprogram_Name);
14974 @end cartouche
14975 @end smallexample
14976
14977 @noindent
14978 where
14979 @table @code
14980 @item Library_Unit_Name
14981 full expanded Ada name of a library unit
14982
14983 @item Subprogram_Name
14984 a simple or expanded name of a subprogram declared within this
14985 compilation unit
14986
14987 @end table
14988
14989 @noindent
14990 The effect of an @code{Eliminate} pragma placed in the GNAT configuration
14991 file @file{gnat.adc} is:
14992
14993 @itemize @bullet
14994
14995 @item
14996 If the subprogram @code{Subprogram_Name} is declared within
14997 the library unit @code{Library_Unit_Name}, the compiler will not generate
14998 code for this subprogram. This applies to all overloaded subprograms denoted
14999 by @code{Subprogram_Name}.
15000
15001 @item
15002 If a subprogram marked by the pragma @code{Eliminate} is used (called)
15003 in a program, the compiler will produce an error message in the place where
15004 it is called.
15005 @end itemize
15006
15007 @node Tree Files
15008 @section Tree Files
15009 @cindex Tree file
15010
15011 @noindent
15012 A tree file stores a snapshot of the compiler internal data
15013 structures at the very end of a successful compilation. It contains all the
15014 syntactic and semantic information for the compiled unit and all the
15015 units upon which it depends semantically.
15016 To use tools that make use of tree files, you
15017 need to first produce the right set of tree files.
15018
15019 GNAT produces correct tree files when -gnatt -gnatc options are set
15020 in a gcc call. The tree files have an .adt extension.
15021 Therefore, to produce a tree file for the compilation unit contained in a file
15022 named @file{foo.adb}, you must use the command
15023
15024 @smallexample
15025 $ gcc -c -gnatc -gnatt foo.adb
15026 @end smallexample
15027
15028 @noindent
15029 and you will get the tree file @file{foo.adt}.
15030 compilation.
15031
15032 @node Preparing Tree and Bind Files for gnatelim
15033 @section Preparing Tree and Bind Files for @code{gnatelim}
15034
15035 @noindent
15036 A set of tree files covering the program to be analyzed with
15037 @code{gnatelim} and
15038 the bind file for the main subprogram does not have to
15039 be in the current directory.
15040 '-T' gnatelim option may be used to provide
15041 the search path for tree files, and '-b'
15042 option may be used to point to the bind
15043 file to process (see @ref{Running gnatelim})
15044
15045 If you do not have the appropriate set of tree
15046 files and the right bind file, you
15047 may create them in the current directory using the following procedure.
15048
15049 Let @code{Main_Prog} be the name of a main subprogram, and suppose
15050 this subprogram is in a file named @file{main_prog.adb}.
15051
15052 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
15053 the main subprogram. @code{gnatelim} can work with both Ada and C
15054 bind files; when both are present, it uses the Ada bind file.
15055 The following commands will build the program and create the bind file:
15056
15057 @smallexample
15058 $ gnatmake -c Main_Prog
15059 $ gnatbind main_prog
15060 @end smallexample
15061
15062 @noindent
15063 To create a minimal set of tree files covering the whole program, call
15064 @code{gnatmake} for this program as follows:
15065
15066 @smallexample
15067 $ gnatmake -f -c -gnatc -gnatt Main_Prog
15068 @end smallexample
15069
15070 @noindent
15071 The @code{-c} gnatmake option turns off the bind and link
15072 steps, that are useless anyway because the sources are compiled with
15073 @option{-gnatc} option which turns off code generation.
15074
15075 The @code{-f} gnatmake option forces
15076 recompilation of all the needed sources.
15077
15078 This sequence of actions will create all the data needed by @code{gnatelim}
15079 from scratch and therefore guarantee its consistency. If you would like to
15080 use some existing set of files as @code{gnatelim} output, you must make
15081 sure that the set of files is complete and consistent. You can use the
15082 @code{-m} switch to check if there are missed tree files
15083
15084 Note, that @code{gnatelim} needs neither object nor ALI files.
15085
15086 @node Running gnatelim
15087 @section Running @code{gnatelim}
15088
15089 @noindent
15090 @code{gnatelim} has the following command-line interface:
15091
15092 @smallexample
15093 $ gnatelim [options] name
15094 @end smallexample
15095
15096 @noindent
15097 @code{name} should be a full expanded Ada name of a main subprogram
15098 of a program (partition).
15099
15100 @code{gnatelim} options:
15101
15102 @table @code
15103 @item -q
15104 Quiet mode: by default @code{gnatelim} generates to the standard error
15105 stream a trace of the source file names of the compilation units being
15106 processed. This option turns this trace off.
15107
15108 @item -v
15109 Verbose mode: @code{gnatelim} version information is printed as Ada
15110 comments to the standard output stream.
15111
15112 @item -a
15113 Also look for subprograms from the GNAT run time that can be eliminated.
15114
15115 @item -m
15116 Check if any tree files are missing for an accurate result.
15117
15118 @item -T@var{dir}
15119 When looking for tree files also look in directory @var{dir}
15120
15121 @item -b@var{bind_file}
15122 Specifies @var{bind_file} as the bind file to process. If not set, the name
15123 of the bind file is computed from the full expanded Ada name of a main subprogram.
15124
15125 @item -d@var{x}
15126 Activate internal debugging switches. @var{x} is a letter or digit, or
15127 string of letters or digits, which specifies the type of debugging
15128 mode desired.  Normally these are used only for internal development
15129 or system debugging purposes. You can find full documentation for these
15130 switches in the body of the @code{Gnatelim.Options} unit in the compiler
15131 source file @file{gnatelim-options.adb}.
15132 @end table
15133
15134 @noindent
15135 @code{gnatelim} sends its output to the standard output stream, and all the
15136 tracing and debug information is sent to the standard error stream.
15137 In order to produce a proper GNAT configuration file
15138 @file{gnat.adc}, redirection must be used:
15139
15140 @smallexample
15141 $ gnatelim Main_Prog > gnat.adc
15142 @end smallexample
15143
15144 @noindent
15145 or
15146
15147 @smallexample
15148 $ gnatelim Main_Prog >> gnat.adc
15149 @end smallexample
15150
15151 @noindent
15152 In order to append the @code{gnatelim} output to the existing contents of
15153 @file{gnat.adc}.
15154
15155 @node Correcting the List of Eliminate Pragmas
15156 @section Correcting the List of Eliminate Pragmas
15157
15158 @noindent
15159 In some rare cases it may happen that @code{gnatelim} will try to eliminate
15160 subprograms which are actually called in the program. In this case, the
15161 compiler will generate an error message of the form:
15162
15163 @smallexample
15164 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
15165 @end smallexample
15166
15167 @noindent
15168 You will need to manually remove the wrong @code{Eliminate} pragmas from
15169 the @file{gnat.adc} file. It is advised that you recompile your program
15170 from scratch after that because you need a consistent @file{gnat.adc} file
15171 during the entire compilation.
15172
15173 @node Making Your Executables Smaller
15174 @section Making Your Executables Smaller
15175
15176 @noindent
15177 In order to get a smaller executable for your program you now have to
15178 recompile the program completely with the new @file{gnat.adc} file
15179 created by @code{gnatelim} in your current directory:
15180
15181 @smallexample
15182 $ gnatmake -f Main_Prog
15183 @end smallexample
15184
15185 @noindent
15186 (you will need @code{-f} option for gnatmake to
15187 recompile everything
15188 with the set of pragmas @code{Eliminate} you have obtained with
15189 @code{gnatelim}).
15190
15191 Be aware that the set of @code{Eliminate} pragmas is specific to each
15192 program. It is not recommended to merge sets of @code{Eliminate}
15193 pragmas created for different programs in one @file{gnat.adc} file.
15194
15195 @node Summary of the gnatelim Usage Cycle
15196 @section Summary of the gnatelim Usage Cycle
15197
15198 @noindent
15199 Here is a quick summary of the steps to be taken in order to reduce
15200 the size of your executables with @code{gnatelim}. You may use
15201 other GNAT options to control the optimization level,
15202 to produce the debugging information, to set search path, etc.
15203
15204 @enumerate
15205 @item
15206 Produce a bind file and a set of tree files
15207
15208 @smallexample
15209 $ gnatmake -c Main_Prog
15210 $ gnatbind main_prog
15211 $ gnatmake -f -c -gnatc -gnatt Main_Prog
15212 @end smallexample
15213
15214 @item
15215 Generate a list of @code{Eliminate} pragmas
15216 @smallexample
15217 $ gnatelim Main_Prog >[>] gnat.adc
15218 @end smallexample
15219
15220 @item
15221 Recompile the application
15222
15223 @smallexample
15224 $ gnatmake -f Main_Prog
15225 @end smallexample
15226
15227 @end enumerate
15228
15229 @node Other Utility Programs
15230 @chapter Other Utility Programs
15231
15232 @noindent
15233 This chapter discusses some other utility programs available in the Ada
15234 environment.
15235
15236 @menu
15237 * Using Other Utility Programs with GNAT::
15238 * The gnatpsta Utility Program::
15239 * The External Symbol Naming Scheme of GNAT::
15240 * Ada Mode for Glide::
15241 * Converting Ada Files to html with gnathtml::
15242 * Installing gnathtml::
15243 @end menu
15244
15245 @node Using Other Utility Programs with GNAT
15246 @section Using Other Utility Programs with GNAT
15247
15248 @noindent
15249 The object files generated by GNAT are in standard system format and in
15250 particular the debugging information uses this format. This means
15251 programs generated by GNAT can be used with existing utilities that
15252 depend on these formats.
15253
15254 In general, any utility program that works with C will also often work with
15255 Ada programs generated by GNAT. This includes software utilities such as
15256 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
15257 as Purify.
15258
15259 @node The gnatpsta Utility Program
15260 @section The @code{gnatpsta} Utility Program
15261
15262 @noindent
15263 Many of the definitions in package Standard are implementation-dependent.
15264 However, the source of this package does not exist as an Ada source
15265 file, so these values cannot be determined by inspecting the source.
15266 They can be determined by examining in detail the coding of
15267 @file{cstand.adb} which creates the image of Standard in the compiler,
15268 but this is awkward and requires a great deal of internal knowledge
15269 about the system.
15270
15271 The @code{gnatpsta} utility is designed to deal with this situation.
15272 It is an Ada program that dynamically determines the
15273 values of all the relevant parameters in Standard, and prints them
15274 out in the form of an Ada source listing for Standard, displaying all
15275 the values of interest. This output is generated to
15276 @file{stdout}.
15277
15278 To determine the value of any parameter in package Standard, simply
15279 run @code{gnatpsta} with no qualifiers or arguments, and examine
15280 the output. This is preferable to consulting documentation, because
15281 you know that the values you are getting are the actual ones provided
15282 by the executing system.
15283
15284 @node The External Symbol Naming Scheme of GNAT
15285 @section The External Symbol Naming Scheme of GNAT
15286
15287 @noindent
15288 In order to interpret the output from GNAT, when using tools that are
15289 originally intended for use with other languages, it is useful to
15290 understand the conventions used to generate link names from the Ada
15291 entity names.
15292
15293 All link names are in all lowercase letters. With the exception of library
15294 procedure names, the mechanism used is simply to use the full expanded
15295 Ada name with dots replaced by double underscores. For example, suppose
15296 we have the following package spec:
15297
15298 @smallexample
15299 @group
15300 @cartouche
15301 @b{package} QRS @b{is}
15302    MN : Integer;
15303 @b{end} QRS;
15304 @end cartouche
15305 @end group
15306 @end smallexample
15307
15308 @noindent
15309 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
15310 the corresponding link name is @code{qrs__mn}.
15311 @findex Export
15312 Of course if a @code{pragma Export} is used this may be overridden:
15313
15314 @smallexample
15315 @group
15316 @cartouche
15317 @b{package} Exports @b{is}
15318    Var1 : Integer;
15319    @b{pragma} Export (Var1, C, External_Name => "var1_name");
15320    Var2 : Integer;
15321    @b{pragma} Export (Var2, C, Link_Name => "var2_link_name");
15322 @b{end} Exports;
15323 @end cartouche
15324 @end group
15325 @end smallexample
15326
15327 @noindent
15328 In this case, the link name for @var{Var1} is whatever link name the
15329 C compiler would assign for the C function @var{var1_name}. This typically
15330 would be either @var{var1_name} or @var{_var1_name}, depending on operating
15331 system conventions, but other possibilities exist. The link name for
15332 @var{Var2} is @var{var2_link_name}, and this is not operating system
15333 dependent.
15334
15335 @findex _main
15336 One exception occurs for library level procedures. A potential ambiguity
15337 arises between the required name @code{_main} for the C main program,
15338 and the name we would otherwise assign to an Ada library level procedure
15339 called @code{Main} (which might well not be the main program).
15340
15341 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
15342 names. So if we have a library level procedure such as
15343
15344 @smallexample
15345 @group
15346 @cartouche
15347 @b{procedure} Hello (S : String);
15348 @end cartouche
15349 @end group
15350 @end smallexample
15351
15352 @noindent
15353 the external name of this procedure will be @var{_ada_hello}.
15354
15355 @node Ada Mode for Glide
15356 @section Ada Mode for @code{Glide}
15357
15358 @noindent
15359 The Glide mode for programming in Ada (both, Ada83 and Ada95) helps the
15360 user in understanding existing code and facilitates writing new code. It
15361 furthermore provides some utility functions for easier integration of
15362 standard Emacs features when programming in Ada.
15363
15364 @subsection General Features:
15365
15366 @itemize @bullet
15367 @item
15368 Full Integrated Development Environment :
15369
15370 @itemize @bullet
15371 @item
15372 support of 'project files' for the configuration (directories,
15373 compilation options,...)
15374
15375 @item
15376 compiling and stepping through error messages.
15377
15378 @item
15379 running and debugging your applications within Glide.
15380 @end itemize
15381
15382 @item
15383 easy to use for beginners by pull-down menus,
15384
15385 @item
15386 user configurable by many user-option variables.
15387 @end itemize
15388
15389 @subsection Ada Mode Features That Help Understanding Code:
15390
15391 @itemize @bullet
15392 @item
15393 functions for easy and quick stepping through Ada code,
15394
15395 @item
15396 getting cross reference information for identifiers (e.g. find the
15397 defining place by a keystroke),
15398
15399 @item
15400 displaying an index menu of types and subprograms and move point to
15401 the chosen one,
15402
15403 @item
15404 automatic color highlighting of the various entities in Ada code.
15405 @end itemize
15406
15407 @subsection Glide Support for Writing Ada Code:
15408
15409 @itemize @bullet
15410 @item
15411 switching between spec and body files with possible
15412 autogeneration of body files,
15413
15414 @item
15415 automatic formating of subprograms parameter lists.
15416
15417 @item
15418 automatic smart indentation according to Ada syntax,
15419
15420 @item
15421 automatic completion of identifiers,
15422
15423 @item
15424 automatic casing of identifiers, keywords, and attributes,
15425
15426 @item
15427 insertion of statement templates,
15428
15429 @item
15430 filling comment paragraphs like filling normal text,
15431 @end itemize
15432
15433 For more information, please refer to the online Glide documentation
15434 available in the Glide --> Help Menu.
15435
15436 @node Converting Ada Files to html with gnathtml
15437 @section Converting Ada Files to html with @code{gnathtml}
15438
15439 @noindent
15440 This @code{Perl} script allows Ada source files to be browsed using
15441 standard Web browsers. For installation procedure, see the section
15442 @xref{Installing gnathtml}.
15443
15444 Ada reserved keywords are highlighted in a bold font and Ada comments in
15445 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
15446 switch to suppress the generation of cross-referencing information, user
15447 defined variables and types will appear in a different color; you will
15448 be able to click on any identifier and go to its declaration.
15449
15450 The command line is as follow:
15451 @smallexample
15452 $ perl gnathtml.pl [switches] ada-files
15453 @end smallexample
15454
15455 You can pass it as many Ada files as you want. @code{gnathtml} will generate
15456 an html file for every ada file, and a global file called @file{index.htm}.
15457 This file is an index of every identifier defined in the files.
15458
15459 The available switches are the following ones :
15460
15461 @table @code
15462 @item -83
15463 @cindex @code{-83} (@code{gnathtml})
15464 Only the subset on the Ada 83 keywords will be highlighted, not the full
15465 Ada 95 keywords set.
15466
15467 @item -cc @var{color}
15468 This option allows you to change the color used for comments. The default
15469 value is green. The color argument can be any name accepted by html.
15470
15471 @item -d
15472 @cindex @code{-d} (@code{gnathtml})
15473 If the ada files depend on some other files (using for instance the
15474 @code{with} command, the latter will also be converted to html.
15475 Only the files in the user project will be converted to html, not the files
15476 in the run-time library itself.
15477
15478 @item -D
15479 This command is the same as -d above, but @code{gnathtml} will also look
15480 for files in the run-time library, and generate html files for them.
15481
15482 @item -f
15483 @cindex @code{-f} (@code{gnathtml})
15484 By default, gnathtml will generate html links only for global entities
15485 ('with'ed units, global variables and types,...). If you specify the
15486 @code{-f} on the command line, then links will be generated for local
15487 entities too.
15488
15489 @item -l @var{number}
15490 @cindex @code{-l} (@code{gnathtml})
15491 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
15492 will number the html files every @var{number} line.
15493
15494 @item -I @var{dir}
15495 @cindex @code{-I} (@code{gnathtml})
15496 Specify a directory to search for library files (@file{.ali} files) and
15497 source files. You can provide several -I switches on the command line,
15498 and the directories will be parsed in the order of the command line.
15499
15500 @item -o @var{dir}
15501 @cindex @code{-o} (@code{gnathtml})
15502 Specify the output directory for html files. By default, gnathtml will
15503 saved the generated html files in a subdirectory named @file{html/}.
15504
15505 @item -p @var{file}
15506 @cindex @code{-p} (@code{gnathtml})
15507 If you are using Emacs and the most recent Emacs Ada mode, which provides
15508 a full Integrated Development Environment for compiling, checking,
15509 running and debugging applications, you may be using @file{.adp} files
15510 to give the directories where Emacs can find sources and object files.
15511
15512 Using this switch, you can tell gnathtml to use these files. This allows
15513 you to get an html version of your application, even if it is spread
15514 over multiple directories.
15515
15516 @item -sc @var{color}
15517 @cindex @code{-sc} (@code{gnathtml})
15518 This option allows you to change the color used for symbol definitions.
15519 The default value is red. The color argument can be any name accepted by html.
15520
15521 @item -t @var{file}
15522 @cindex @code{-t} (@code{gnathtml})
15523 This switch provides the name of a file. This file contains a list of
15524 file names to be converted, and the effect is exactly as though they had
15525 appeared explicitly on the command line. This
15526 is the recommended way to work around the command line length limit on some
15527 systems.
15528
15529 @end table
15530
15531 @node Installing gnathtml
15532 @section Installing @code{gnathtml}
15533
15534 @noindent
15535 @code{Perl} needs to be installed on your machine to run this script.
15536 @code{Perl} is freely available for almost every architecture and
15537 Operating System via the Internet.
15538
15539 On Unix systems, you  may want to modify  the  first line of  the script
15540 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
15541 is. The syntax of this line is :
15542 @smallexample
15543 #!full_path_name_to_perl
15544 @end smallexample
15545
15546 @noindent
15547 Alternatively, you may run the script using the following command line:
15548
15549 @smallexample
15550 $ perl gnathtml.pl [switches] files
15551 @end smallexample
15552
15553
15554 @node Running and Debugging Ada Programs
15555 @chapter Running and Debugging Ada Programs
15556 @cindex Debugging
15557
15558 @noindent
15559 This chapter discusses how to debug Ada programs. An incorrect Ada program
15560 may be handled in three ways by the GNAT compiler:
15561
15562 @enumerate
15563 @item
15564 The illegality may be a violation of the static semantics of Ada. In
15565 that case GNAT diagnoses the constructs in the program that are illegal.
15566 It is then a straightforward matter for the user to modify those parts of
15567 the program.
15568
15569 @item
15570 The illegality may be a violation of the dynamic semantics of Ada. In
15571 that case the program compiles and executes, but may generate incorrect
15572 results, or may terminate abnormally with some exception.
15573
15574 @item
15575 When presented with a program that contains convoluted errors, GNAT
15576 itself may terminate abnormally without providing full diagnostics on
15577 the incorrect user program.
15578 @end enumerate
15579
15580 @menu
15581 * The GNAT Debugger GDB::
15582 * Running GDB::
15583 * Introduction to GDB Commands::
15584 * Using Ada Expressions::
15585 * Calling User-Defined Subprograms::
15586 * Using the Next Command in a Function::
15587 * Ada Exceptions::
15588 * Ada Tasks::
15589 * Debugging Generic Units::
15590 * GNAT Abnormal Termination or Failure to Terminate::
15591 * Naming Conventions for GNAT Source Files::
15592 * Getting Internal Debugging Information::
15593 * Stack Traceback::
15594 @end menu
15595
15596 @cindex Debugger
15597 @findex gdb
15598
15599 @node The GNAT Debugger GDB
15600 @section The GNAT Debugger GDB
15601
15602 @noindent
15603 @code{GDB} is a general purpose, platform-independent debugger that
15604 can be used to debug mixed-language programs compiled with @code{GCC},
15605 and in particular is capable of debugging Ada programs compiled with
15606 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
15607 complex Ada data structures.
15608
15609 The manual @cite{Debugging with GDB}
15610 contains full details on the usage of @code{GDB}, including a section on
15611 its usage on programs. This manual should be consulted for full
15612 details. The section that follows is a brief introduction to the
15613 philosophy and use of @code{GDB}.
15614
15615 When GNAT programs are compiled, the compiler optionally writes debugging
15616 information into the generated object file, including information on
15617 line numbers, and on declared types and variables. This information is
15618 separate from the generated code. It makes the object files considerably
15619 larger, but it does not add to the size of the actual executable that
15620 will be loaded into memory, and has no impact on run-time performance. The
15621 generation of debug information is triggered by the use of the
15622 -g switch in the gcc or gnatmake command used to carry out
15623 the compilations. It is important to emphasize that the use of these
15624 options does not change the generated code.
15625
15626 The debugging information is written in standard system formats that
15627 are used by many tools, including debuggers and profilers. The format
15628 of the information is typically designed to describe C types and
15629 semantics, but GNAT implements a translation scheme which allows full
15630 details about Ada types and variables to be encoded into these
15631 standard C formats. Details of this encoding scheme may be found in
15632 the file exp_dbug.ads in the GNAT source distribution. However, the
15633 details of this encoding are, in general, of no interest to a user,
15634 since @code{GDB} automatically performs the necessary decoding.
15635
15636 When a program is bound and linked, the debugging information is
15637 collected from the object files, and stored in the executable image of
15638 the program. Again, this process significantly increases the size of
15639 the generated executable file, but it does not increase the size of
15640 the executable program itself. Furthermore, if this program is run in
15641 the normal manner, it runs exactly as if the debug information were
15642 not present, and takes no more actual memory.
15643
15644 However, if the program is run under control of @code{GDB}, the
15645 debugger is activated.  The image of the program is loaded, at which
15646 point it is ready to run.  If a run command is given, then the program
15647 will run exactly as it would have if @code{GDB} were not present. This
15648 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
15649 entirely non-intrusive until a breakpoint is encountered.  If no
15650 breakpoint is ever hit, the program will run exactly as it would if no
15651 debugger were present. When a breakpoint is hit, @code{GDB} accesses
15652 the debugging information and can respond to user commands to inspect
15653 variables, and more generally to report on the state of execution.
15654
15655 @node Running GDB
15656 @section Running GDB
15657
15658
15659 Please refer to the debugging section of the chapter specific to your
15660 cross environment at the end of this manual.
15661
15662 @node Introduction to GDB Commands
15663 @section Introduction to GDB Commands
15664
15665 @noindent
15666 @code{GDB} contains a large repertoire of commands. The manual
15667 @cite{Debugging with GDB}
15668 includes extensive documentation on the use
15669 of these commands, together with examples of their use. Furthermore,
15670 the command @var{help} invoked from within @code{GDB} activates a simple help
15671 facility which summarizes the available commands and their options.
15672 In this section we summarize a few of the most commonly
15673 used commands to give an idea of what @code{GDB} is about. You should create
15674 a simple program with debugging information and experiment with the use of
15675 these @code{GDB} commands on the program as you read through the
15676 following section.
15677
15678 @table @code
15679 @item set args @var{arguments}
15680 The @var{arguments} list above is a list of arguments to be passed to
15681 the program on a subsequent run command, just as though the arguments
15682 had been entered on a normal invocation of the program. The @code{set args}
15683 command is not needed if the program does not require arguments.
15684
15685 @item run
15686 The @code{run} command causes execution of the program to start from
15687 the beginning. If the program is already running, that is to say if
15688 you are currently positioned at a breakpoint, then a prompt will ask
15689 for confirmation that you want to abandon the current execution and
15690 restart.
15691
15692 @item breakpoint @var{location}
15693 The breakpoint command sets a breakpoint, that is to say a point at which
15694 execution will halt and @code{GDB} will await further
15695 commands. @var{location} is
15696 either a line number within a file, given in the format @code{file:linenumber},
15697 or it is the name of a subprogram. If you request that a breakpoint be set on
15698 a subprogram that is overloaded, a prompt will ask you to specify on which of
15699 those subprograms you want to breakpoint. You can also
15700 specify that all of them should be breakpointed. If the program is run
15701 and execution encounters the breakpoint, then the program
15702 stops and @code{GDB} signals that the breakpoint was encountered by
15703 printing the line of code before which the program is halted.
15704
15705 @item breakpoint exception @var{name}
15706 A special form of the breakpoint command which breakpoints whenever
15707 exception @var{name} is raised.
15708 If @var{name} is omitted,
15709 then a breakpoint will occur when any exception is raised.
15710
15711 @item print @var{expression}
15712 This will print the value of the given expression. Most simple
15713 Ada expression formats are properly handled by @code{GDB}, so the expression
15714 can contain function calls, variables, operators, and attribute references.
15715
15716 @item continue
15717 Continues execution following a breakpoint, until the next breakpoint or the
15718 termination of the program.
15719
15720 @item step
15721 Executes a single line after a breakpoint. If the next statement is a subprogram
15722 call, execution continues into (the first statement of) the
15723 called subprogram.
15724
15725 @item next
15726 Executes a single line. If this line is a subprogram call, executes and
15727 returns from the call.
15728
15729 @item list
15730 Lists a few lines around the current source location. In practice, it
15731 is usually more convenient to have a separate edit window open with the
15732 relevant source file displayed. Successive applications of this command
15733 print subsequent lines. The command can be given an argument which is a
15734 line number, in which case it displays a few lines around the specified one.
15735
15736 @item backtrace
15737 Displays a backtrace of the call chain. This command is typically
15738 used after a breakpoint has occurred, to examine the sequence of calls that
15739 leads to the current breakpoint. The display includes one line for each
15740 activation record (frame) corresponding to an active subprogram.
15741
15742 @item up
15743 At a breakpoint, @code{GDB} can display the values of variables local
15744 to the current frame. The command @code{up} can be used to
15745 examine the contents of other active frames, by moving the focus up
15746 the stack, that is to say from callee to caller, one frame at a time.
15747
15748 @item down
15749 Moves the focus of @code{GDB} down from the frame currently being
15750 examined to the frame of its callee (the reverse of the previous command),
15751
15752 @item frame @var{n}
15753 Inspect the frame with the given number. The value 0 denotes the frame
15754 of the current breakpoint, that is to say the top of the call stack.
15755
15756 @end table
15757
15758 The above list is a very short introduction to the commands that
15759 @code{GDB} provides. Important additional capabilities, including conditional
15760 breakpoints, the ability to execute command sequences on a breakpoint,
15761 the ability to debug at the machine instruction level and many other
15762 features are described in detail in @cite{Debugging with GDB}.
15763 Note that most commands can be abbreviated
15764 (for example, c for continue, bt for backtrace).
15765
15766 @node Using Ada Expressions
15767 @section Using Ada Expressions
15768 @cindex Ada expressions
15769
15770 @noindent
15771 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
15772 extensions. The philosophy behind the design of this subset is
15773
15774 @itemize @bullet
15775 @item
15776 That @code{GDB} should provide basic literals and access to operations for
15777 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
15778 leaving more sophisticated computations to subprograms written into the
15779 program (which therefore may be called from @code{GDB}).
15780
15781 @item
15782 That type safety and strict adherence to Ada language restrictions
15783 are not particularly important to the @code{GDB} user.
15784
15785 @item
15786 That brevity is important to the @code{GDB} user.
15787 @end itemize
15788
15789 Thus, for brevity, the debugger acts as if there were
15790 implicit @code{with} and @code{use} clauses in effect for all user-written
15791 packages, thus making it unnecessary to fully qualify most names with
15792 their packages, regardless of context. Where this causes ambiguity,
15793 @code{GDB} asks the user's intent.
15794
15795 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
15796
15797 @node Calling User-Defined Subprograms
15798 @section Calling User-Defined Subprograms
15799
15800 @noindent
15801 An important capability of @code{GDB} is the ability to call user-defined
15802 subprograms while debugging. This is achieved simply by entering
15803 a subprogram call statement in the form:
15804
15805 @smallexample
15806 call subprogram-name (parameters)
15807 @end smallexample
15808
15809 @noindent
15810 The keyword @code{call} can be omitted in the normal case where the
15811 @code{subprogram-name} does not coincide with any of the predefined
15812 @code{GDB} commands.
15813
15814 The effect is to invoke the given subprogram, passing it the
15815 list of parameters that is supplied. The parameters can be expressions and
15816 can include variables from the program being debugged. The
15817 subprogram must be defined
15818 at the library level within your program, and @code{GDB} will call the
15819 subprogram within the environment of your program execution (which
15820 means that the subprogram is free to access or even modify variables
15821 within your program).
15822
15823 The most important use of this facility is in allowing the inclusion of
15824 debugging routines that are tailored to particular data structures
15825 in your program. Such debugging routines can be written to provide a suitably
15826 high-level description of an abstract type, rather than a low-level dump
15827 of its physical layout. After all, the standard
15828 @code{GDB print} command only knows the physical layout of your
15829 types, not their abstract meaning. Debugging routines can provide information
15830 at the desired semantic level and are thus enormously useful.
15831
15832 For example, when debugging GNAT itself, it is crucial to have access to
15833 the contents of the tree nodes used to represent the program internally.
15834 But tree nodes are represented simply by an integer value (which in turn
15835 is an index into a table of nodes).
15836 Using the @code{print} command on a tree node would simply print this integer
15837 value, which is not very useful. But the PN routine (defined in file
15838 treepr.adb in the GNAT sources) takes a tree node as input, and displays
15839 a useful high level representation of the tree node, which includes the
15840 syntactic category of the node, its position in the source, the integers
15841 that denote descendant nodes and parent node, as well as varied
15842 semantic information. To study this example in more detail, you might want to
15843 look at the body of the PN procedure in the stated file.
15844
15845 @node Using the Next Command in a Function
15846 @section Using the Next Command in a Function
15847
15848 @noindent
15849 When you use the @code{next} command in a function, the current source
15850 location will advance to the next statement as usual. A special case
15851 arises in the case of a @code{return} statement.
15852
15853 Part of the code for a return statement is the "epilog" of the function.
15854 This is the code that returns to the caller. There is only one copy of
15855 this epilog code, and it is typically associated with the last return
15856 statement in the function if there is more than one return. In some
15857 implementations, this epilog is associated with the first statement
15858 of the function.
15859
15860 The result is that if you use the @code{next} command from a return
15861 statement that is not the last return statement of the function you
15862 may see a strange apparent jump to the last return statement or to
15863 the start of the function. You should simply ignore this odd jump.
15864 The value returned is always that from the first return statement
15865 that was stepped through.
15866
15867 @node Ada Exceptions
15868 @section Breaking on Ada Exceptions
15869 @cindex Exceptions
15870
15871 @noindent
15872 You can set breakpoints that trip when your program raises
15873 selected exceptions.
15874
15875 @table @code
15876 @item break exception
15877 Set a breakpoint that trips whenever (any task in the) program raises
15878 any exception.
15879
15880 @item break exception @var{name}
15881 Set a breakpoint that trips whenever (any task in the) program raises
15882 the exception @var{name}.
15883
15884 @item break exception unhandled
15885 Set a breakpoint that trips whenever (any task in the) program raises an
15886 exception for which there is no handler.
15887
15888 @item info exceptions
15889 @itemx info exceptions @var{regexp}
15890 The @code{info exceptions} command permits the user to examine all defined
15891 exceptions within Ada programs. With a regular expression, @var{regexp}, as
15892 argument, prints out only those exceptions whose name matches @var{regexp}.
15893 @end table
15894
15895 @node Ada Tasks
15896 @section Ada Tasks
15897 @cindex Tasks
15898
15899 @noindent
15900 @code{GDB} allows the following task-related commands:
15901
15902 @table @code
15903 @item info tasks
15904 This command shows a list of current Ada tasks, as in the following example:
15905
15906 @smallexample
15907 @iftex
15908 @leftskip=0cm
15909 @end iftex
15910 (gdb) info tasks
15911   ID       TID P-ID   Thread Pri State                 Name
15912    1   8088000   0   807e000  15 Child Activation Wait main_task
15913    2   80a4000   1   80ae000  15 Accept/Select Wait    b
15914    3   809a800   1   80a4800  15 Child Activation Wait a
15915 *  4   80ae800   3   80b8000  15 Running               c
15916 @end smallexample
15917
15918 @noindent
15919 In this listing, the asterisk before the first task indicates it to be the
15920 currently running task. The first column lists the task ID that is used
15921 to refer to tasks in the following commands.
15922
15923 @item break @var{linespec} task @var{taskid}
15924 @itemx break @var{linespec} task @var{taskid} if @dots{}
15925 @cindex Breakpoints and tasks
15926 These commands are like the @code{break @dots{} thread @dots{}}.
15927 @var{linespec} specifies source lines.
15928
15929 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
15930 to specify that you only want @code{GDB} to stop the program when a
15931 particular Ada task reaches this breakpoint. @var{taskid} is one of the
15932 numeric task identifiers assigned by @code{GDB}, shown in the first
15933 column of the @samp{info tasks} display.
15934
15935 If you do not specify @samp{task @var{taskid}} when you set a
15936 breakpoint, the breakpoint applies to @emph{all} tasks of your
15937 program.
15938
15939 You can use the @code{task} qualifier on conditional breakpoints as
15940 well; in this case, place @samp{task @var{taskid}} before the
15941 breakpoint condition (before the @code{if}).
15942
15943 @item task @var{taskno}
15944 @cindex Task switching
15945
15946 This command allows to switch to the task referred by @var{taskno}. In
15947 particular, This allows to browse the backtrace of the specified
15948 task. It is advised to switch back to the original task before
15949 continuing execution otherwise the scheduling of the program may be
15950 perturbated.
15951 @end table
15952
15953 @noindent
15954 For more detailed information on the tasking support, see @cite{Debugging with GDB}.
15955
15956 @node Debugging Generic Units
15957 @section Debugging Generic Units
15958 @cindex Debugging Generic Units
15959 @cindex Generics
15960
15961 @noindent
15962 GNAT always uses code expansion for generic instantiation. This means that
15963 each time an instantiation occurs, a complete copy of the original code is
15964 made, with appropriate substitutions of formals by actuals.
15965
15966 It is not possible to refer to the original generic entities in
15967 @code{GDB}, but it is always possible to debug a particular instance of
15968 a generic, by using the appropriate expanded names. For example, if we have
15969
15970 @smallexample
15971 @group
15972 @cartouche
15973 @b{procedure} g @b{is}
15974
15975    @b{generic package} k @b{is}
15976       @b{procedure} kp (v1 : @b{in out} integer);
15977    @b{end} k;
15978
15979    @b{package body} k @b{is}
15980       @b{procedure} kp (v1 : @b{in out} integer) @b{is}
15981       @b{begin}
15982          v1 := v1 + 1;
15983       @b{end} kp;
15984    @b{end} k;
15985
15986    @b{package} k1 @b{is new} k;
15987    @b{package} k2 @b{is new} k;
15988
15989    var : integer := 1;
15990
15991 @b{begin}
15992    k1.kp (var);
15993    k2.kp (var);
15994    k1.kp (var);
15995    k2.kp (var);
15996 @b{end};
15997 @end cartouche
15998 @end group
15999 @end smallexample
16000
16001 @noindent
16002 Then to break on a call to procedure kp in the k2 instance, simply
16003 use the command:
16004
16005 @smallexample
16006 (gdb) break g.k2.kp
16007 @end smallexample
16008
16009 @noindent
16010 When the breakpoint occurs, you can step through the code of the
16011 instance in the normal manner and examine the values of local variables, as for
16012 other units.
16013
16014 @node GNAT Abnormal Termination or Failure to Terminate
16015 @section GNAT Abnormal Termination or Failure to Terminate
16016 @cindex GNAT Abnormal Termination or Failure to Terminate
16017
16018 @noindent
16019 When presented with programs that contain serious errors in syntax
16020 or semantics,
16021 GNAT may on rare occasions  experience problems in operation, such
16022 as aborting with a
16023 segmentation fault or illegal memory access, raising an internal
16024 exception, terminating abnormally, or failing to terminate at all.
16025 In such cases, you can activate
16026 various features of GNAT that can help you pinpoint the construct in your
16027 program that is the likely source of the problem.
16028
16029 The following strategies are presented in increasing order of
16030 difficulty, corresponding to your experience in using GNAT and your
16031 familiarity with compiler internals.
16032
16033 @enumerate
16034 @item
16035 Run @code{gcc} with the @option{-gnatf}. This first
16036 switch causes all errors on a given line to be reported. In its absence,
16037 only the first error on a line is displayed.
16038
16039 The @option{-gnatdO} switch causes errors to be displayed as soon as they
16040 are encountered, rather than after compilation is terminated. If GNAT
16041 terminates prematurely or goes into an infinite loop, the last error
16042 message displayed may help to pinpoint the culprit.
16043
16044 @item
16045 Run @code{gcc} with the @code{-v (verbose)} switch. In this mode,
16046 @code{gcc} produces ongoing information about the progress of the
16047 compilation and provides the name of each procedure as code is
16048 generated. This switch allows you to find which Ada procedure was being
16049 compiled when it encountered a code generation problem.
16050
16051 @item
16052 @cindex @option{-gnatdc} switch
16053 Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
16054 switch that does for the front-end what @code{-v} does for the back end.
16055 The system prints the name of each unit, either a compilation unit or
16056 nested unit, as it is being analyzed.
16057 @item
16058 Finally, you can start
16059 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
16060 front-end of GNAT, and can be run independently (normally it is just
16061 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
16062 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
16063 @code{where} command is the first line of attack; the variable
16064 @code{lineno} (seen by @code{print lineno}), used by the second phase of
16065 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
16066 which the execution stopped, and @code{input_file name} indicates the name of
16067 the source file.
16068 @end enumerate
16069
16070 @node Naming Conventions for GNAT Source Files
16071 @section Naming Conventions for GNAT Source Files
16072
16073 @noindent
16074 In order to examine the workings of the GNAT system, the following
16075 brief description of its organization may be helpful:
16076
16077 @itemize @bullet
16078 @item
16079 Files with prefix @file{sc} contain the lexical scanner.
16080
16081 @item
16082 All files prefixed with @file{par} are components of the parser. The
16083 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
16084 parsing of select statements can be found in @file{par-ch9.adb}.
16085
16086 @item
16087 All files prefixed with @file{sem} perform semantic analysis. The
16088 numbers correspond to chapters of the Ada standard. For example, all
16089 issues involving context clauses can be found in @file{sem_ch10.adb}. In
16090 addition, some features of the language require sufficient special processing
16091 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
16092 dynamic dispatching, etc.
16093
16094 @item
16095 All files prefixed with @file{exp} perform normalization and
16096 expansion of the intermediate representation (abstract syntax tree, or AST).
16097 these files use the same numbering scheme as the parser and semantics files.
16098 For example, the construction of record initialization procedures is done in
16099 @file{exp_ch3.adb}.
16100
16101 @item
16102 The files prefixed with @file{bind} implement the binder, which
16103 verifies the consistency of the compilation, determines an order of
16104 elaboration, and generates the bind file.
16105
16106 @item
16107 The files @file{atree.ads} and @file{atree.adb} detail the low-level
16108 data structures used by the front-end.
16109
16110 @item
16111 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
16112 the abstract syntax tree as produced by the parser.
16113
16114 @item
16115 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
16116 all entities, computed during semantic analysis.
16117
16118 @item
16119 Library management issues are dealt with in files with prefix
16120 @file{lib}.
16121
16122 @item
16123 @findex Ada
16124 @cindex Annex A
16125 Ada files with the prefix @file{a-} are children of @code{Ada}, as
16126 defined in Annex A.
16127
16128 @item
16129 @findex Interfaces
16130 @cindex Annex B
16131 Files with prefix @file{i-} are children of @code{Interfaces}, as
16132 defined in Annex B.
16133
16134 @item
16135 @findex System
16136 Files with prefix @file{s-} are children of @code{System}. This includes
16137 both language-defined children and GNAT run-time routines.
16138
16139 @item
16140 @findex GNAT
16141 Files with prefix @file{g-} are children of @code{GNAT}. These are useful
16142 general-purpose packages, fully documented in their specifications. All
16143 the other @file{.c} files are modifications of common @code{gcc} files.
16144 @end itemize
16145
16146 @node Getting Internal Debugging Information
16147 @section Getting Internal Debugging Information
16148
16149 @noindent
16150 Most compilers have internal debugging switches and modes. GNAT
16151 does also, except GNAT internal debugging switches and modes are not
16152 secret. A summary and full description of all the compiler and binder
16153 debug flags are in the file @file{debug.adb}. You must obtain the
16154 sources of the compiler to see the full detailed effects of these flags.
16155
16156 The switches that print the source of the program (reconstructed from
16157 the internal tree) are of general interest for user programs, as are the
16158 options to print
16159 the full internal tree, and the entity table (the symbol table
16160 information). The reconstructed source provides a readable version of the
16161 program after the front-end has completed analysis and  expansion, and is useful
16162 when studying the performance of specific constructs. For example, constraint
16163 checks are indicated, complex aggregates are replaced with loops and
16164 assignments, and tasking primitives are replaced with run-time calls.
16165
16166 @node Stack Traceback
16167 @section Stack Traceback
16168 @cindex traceback
16169 @cindex stack traceback
16170 @cindex stack unwinding
16171
16172 @noindent
16173 Traceback is a mechanism to display the sequence of subprogram calls that
16174 leads to a specified execution point in a program. Often (but not always)
16175 the execution point is an instruction at which an exception has been raised.
16176 This mechanism is also known as @i{stack unwinding} because it obtains
16177 its information by scanning the run-time stack and recovering the activation
16178 records of all active subprograms. Stack unwinding is one of the most
16179 important tools for program debugging.
16180
16181 @noindent
16182 The first entry stored in traceback corresponds to the deepest calling level,
16183 that is to say the subprogram currently executing the instruction
16184 from which we want to obtain the traceback.
16185
16186 @noindent
16187 Note that there is no runtime performance penalty when stack traceback
16188 is enabled and no exception are raised during program execution.
16189
16190 @menu
16191 * Non-Symbolic Traceback::
16192 * Symbolic Traceback::
16193 @end menu
16194
16195 @node Non-Symbolic Traceback
16196 @subsection Non-Symbolic Traceback
16197 @cindex traceback, non-symbolic
16198
16199 @noindent
16200 Note: this feature is not supported on all platforms. See
16201 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
16202 platforms.
16203
16204 @menu
16205 * Tracebacks From an Unhandled Exception::
16206 * Tracebacks From Exception Occurrences (non-symbolic)::
16207 * Tracebacks From Anywhere in a Program (non-symbolic)::
16208 @end menu
16209
16210 @node Tracebacks From an Unhandled Exception
16211 @subsubsection Tracebacks From an Unhandled Exception
16212
16213 @noindent
16214 A runtime non-symbolic traceback is a list of addresses of call instructions.
16215 To enable this feature you must use the @code{-E}
16216 @code{gnatbind}'s option. With this option a stack traceback is stored as part
16217 of exception information. It is possible to retrieve this information using the
16218 standard @code{Ada.Exception.Exception_Information} routine.
16219
16220 @noindent
16221 Let's have a look at a simple example:
16222
16223 @smallexample
16224 @cartouche
16225 @group
16226 procedure STB is
16227
16228    procedure P1 is
16229    begin
16230       raise Constraint_Error;
16231    end P1;
16232
16233    procedure P2 is
16234    begin
16235       P1;
16236    end P2;
16237
16238 begin
16239    P2;
16240 end STB;
16241 @end group
16242 @end cartouche
16243 @end smallexample
16244
16245 @smallexample
16246 $ gnatmake stb -bargs -E
16247 $ stb
16248
16249 Execution terminated by unhandled exception
16250 Exception name: CONSTRAINT_ERROR
16251 Message: stb.adb:5
16252 Call stack traceback locations:
16253 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
16254 @end smallexample
16255
16256 @noindent
16257 As we see the traceback lists a sequence of addresses for the unhandled
16258 exception @code{CONSTAINT_ERROR} raised in procedure P1. It is easy to
16259 guess that this exception come from procedure P1. To translate these
16260 addresses into the source lines where the calls appear, the
16261 @code{addr2line} tool, described below, is invaluable. The use of this tool
16262 requires the program to be compiled with debug information.
16263
16264 @smallexample
16265 $ gnatmake -g stb -bargs -E
16266 $ stb
16267
16268 Execution terminated by unhandled exception
16269 Exception name: CONSTRAINT_ERROR
16270 Message: stb.adb:5
16271 Call stack traceback locations:
16272 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
16273
16274 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
16275    0x4011f1 0x77e892a4
16276
16277 00401373 at d:/stb/stb.adb:5
16278 0040138B at d:/stb/stb.adb:10
16279 0040139C at d:/stb/stb.adb:14
16280 00401335 at d:/stb/b~stb.adb:104
16281 004011C4 at /build/.../crt1.c:200
16282 004011F1 at /build/.../crt1.c:222
16283 77E892A4 in ?? at ??:0
16284 @end smallexample
16285
16286 @noindent
16287 @code{addr2line} has a number of other useful options:
16288
16289 @table @code
16290 @item --functions
16291 to get the function name corresponding to any location
16292
16293 @item --demangle=gnat
16294 to use the @b{gnat} decoding mode for the function names. Note that
16295 for binutils version 2.9.x the option is simply @code{--demangle}.
16296 @end table
16297
16298 @smallexample
16299 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
16300    0x40139c 0x401335 0x4011c4 0x4011f1
16301
16302 00401373 in stb.p1 at d:/stb/stb.adb:5
16303 0040138B in stb.p2 at d:/stb/stb.adb:10
16304 0040139C in stb at d:/stb/stb.adb:14
16305 00401335 in main at d:/stb/b~stb.adb:104
16306 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
16307 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
16308 @end smallexample
16309
16310 @noindent
16311 From this traceback we can see that the exception was raised in
16312 @file{stb.adb} at line 5, which was reached from a procedure call in
16313 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
16314 which contains the call to the main program.
16315 @pxref{Running gnatbind}. The remaining entries are assorted runtime routines,
16316 and the output will vary from platform to platform.
16317
16318 @noindent
16319 It is also possible to use @code{GDB} with these traceback addresses to debug
16320 the program. For example, we can break at a given code location, as reported
16321 in the stack traceback:
16322
16323 @smallexample
16324 $ gdb -nw stb
16325
16326 (gdb) break *0x401373
16327 Breakpoint 1 at 0x401373: file stb.adb, line 5.
16328 @end smallexample
16329
16330 @noindent
16331 It is important to note that the stack traceback addresses
16332 do not change when debug information is included. This is particularly useful
16333 because it makes it possible to release software without debug information (to
16334 minimize object size), get a field report that includes a stack traceback
16335 whenever an internal bug occurs, and then be able to retrieve the sequence
16336 of calls with the same program compiled with debug information.
16337
16338 @node Tracebacks From Exception Occurrences (non-symbolic)
16339 @subsubsection Tracebacks From Exception Occurrences
16340
16341 @noindent
16342 Non-symbolic tracebacks are obtained by using the @code{-E} binder argument.
16343 The stack traceback is attached to the exception information string, and can
16344 be retrieved in an exception handler within the Ada program, by means of the
16345 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
16346
16347 @smallexample
16348 @cartouche
16349 @group
16350 with Ada.Text_IO;
16351 with Ada.Exceptions;
16352
16353 procedure STB is
16354
16355    use Ada;
16356    use Ada.Exceptions;
16357
16358    procedure P1 is
16359       K : Positive := 1;
16360    begin
16361       K := K - 1;
16362    exception
16363       when E : others =>
16364          Text_IO.Put_Line (Exception_Information (E));
16365    end P1;
16366
16367    procedure P2 is
16368    begin
16369       P1;
16370    end P2;
16371
16372 begin
16373    P2;
16374 end STB;
16375 @end group
16376 @end cartouche
16377 @end smallexample
16378
16379 @noindent
16380 This program will output:
16381
16382 @smallexample
16383 $ stb
16384
16385 Exception name: CONSTRAINT_ERROR
16386 Message: stb.adb:12
16387 Call stack traceback locations:
16388 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
16389 @end smallexample
16390
16391 @node Tracebacks From Anywhere in a Program (non-symbolic)
16392 @subsubsection Tracebacks From Anywhere in a Program
16393
16394 @noindent
16395 It is also possible to retrieve a stack traceback from anywhere in a
16396 program. For this you need to
16397 use the @code{GNAT.Traceback} API. This package includes a procedure called
16398 @code{Call_Chain} that computes a complete stack traceback, as well as useful
16399 display procedures described below. It is not necessary to use the
16400 @code{-E gnatbind} option in this case, because the stack traceback mechanism
16401 is invoked explicitly.
16402
16403 @noindent
16404 In the following example we compute a traceback at a specific location in
16405 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
16406 convert addresses to strings:
16407
16408 @smallexample
16409 @cartouche
16410 @group
16411 with Ada.Text_IO;
16412 with GNAT.Traceback;
16413 with GNAT.Debug_Utilities;
16414
16415 procedure STB is
16416
16417    use Ada;
16418    use GNAT;
16419    use GNAT.Traceback;
16420
16421    procedure P1 is
16422       TB  : Tracebacks_Array (1 .. 10);
16423       --  We are asking for a maximum of 10 stack frames.
16424       Len : Natural;
16425       --  Len will receive the actual number of stack frames returned.
16426    begin
16427       Call_Chain (TB, Len);
16428
16429       Text_IO.Put ("In STB.P1 : ");
16430
16431       for K in 1 .. Len loop
16432          Text_IO.Put (Debug_Utilities.Image (TB (K)));
16433          Text_IO.Put (' ');
16434       end loop;
16435
16436       Text_IO.New_Line;
16437    end P1;
16438
16439    procedure P2 is
16440    begin
16441       P1;
16442    end P2;
16443
16444 begin
16445    P2;
16446 end STB;
16447 @end group
16448 @end cartouche
16449 @end smallexample
16450
16451 @smallexample
16452 $ gnatmake stb
16453 $ stb
16454
16455 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
16456 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
16457 @end smallexample
16458
16459 @node Symbolic Traceback
16460 @subsection Symbolic Traceback
16461 @cindex traceback, symbolic
16462
16463 @noindent
16464 A symbolic traceback is a stack traceback in which procedure names are
16465 associated with each code location.
16466
16467 @noindent
16468 Note that this feature is not supported on all platforms. See
16469 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
16470 list of currently supported platforms.
16471
16472 @noindent
16473 Note that the symbolic traceback requires that the program be compiled
16474 with debug information. If it is not compiled with debug information
16475 only the non-symbolic information will be valid.
16476
16477 @menu
16478 * Tracebacks From Exception Occurrences (symbolic)::
16479 * Tracebacks From Anywhere in a Program (symbolic)::
16480 @end menu
16481
16482 @node Tracebacks From Exception Occurrences (symbolic)
16483 @subsubsection Tracebacks From Exception Occurrences
16484
16485 @smallexample
16486 @cartouche
16487 @group
16488 with Ada.Text_IO;
16489 with GNAT.Traceback.Symbolic;
16490
16491 procedure STB is
16492
16493    procedure P1 is
16494    begin
16495       raise Constraint_Error;
16496    end P1;
16497
16498    procedure P2 is
16499    begin
16500       P1;
16501    end P2;
16502
16503    procedure P3 is
16504    begin
16505       P2;
16506    end P3;
16507
16508 begin
16509    P3;
16510 exception
16511    when E : others =>
16512       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
16513 end STB;
16514 @end group
16515 @end cartouche
16516 @end smallexample
16517
16518 @smallexample
16519 $ gnatmake -g stb -bargs -E -largs -lgnat -laddr2line -lintl
16520 $ stb
16521
16522 0040149F in stb.p1 at stb.adb:8
16523 004014B7 in stb.p2 at stb.adb:13
16524 004014CF in stb.p3 at stb.adb:18
16525 004015DD in ada.stb at stb.adb:22
16526 00401461 in main at b~stb.adb:168
16527 004011C4 in __mingw_CRTStartup at crt1.c:200
16528 004011F1 in mainCRTStartup at crt1.c:222
16529 77E892A4 in ?? at ??:0
16530 @end smallexample
16531
16532 @noindent
16533 The exact sequence of linker options may vary from platform to platform.
16534 The above @code{-largs} section is for Windows platforms. By contrast,
16535 under Unix there is no need for the @code{-largs} section.
16536 Differences across platforms are due to details of linker implementation.
16537
16538 @node Tracebacks From Anywhere in a Program (symbolic)
16539 @subsubsection Tracebacks From Anywhere in a Program
16540
16541 @noindent
16542 It is possible to get a symbolic stack traceback
16543 from anywhere in a program, just as for non-symbolic tracebacks.
16544 The first step is to obtain a non-symbolic
16545 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
16546 information. Here is an example:
16547
16548 @smallexample
16549 @cartouche
16550 @group
16551 with Ada.Text_IO;
16552 with GNAT.Traceback;
16553 with GNAT.Traceback.Symbolic;
16554
16555 procedure STB is
16556
16557    use Ada;
16558    use GNAT.Traceback;
16559    use GNAT.Traceback.Symbolic;
16560
16561    procedure P1 is
16562       TB  : Tracebacks_Array (1 .. 10);
16563       --  We are asking for a maximum of 10 stack frames.
16564       Len : Natural;
16565       --  Len will receive the actual number of stack frames returned.
16566    begin
16567       Call_Chain (TB, Len);
16568       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
16569    end P1;
16570
16571    procedure P2 is
16572    begin
16573       P1;
16574    end P2;
16575
16576 begin
16577    P2;
16578 end STB;
16579 @end group
16580 @end cartouche
16581 @end smallexample
16582
16583
16584 @node Inline Assembler
16585 @chapter Inline Assembler
16586
16587 @noindent
16588 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:
16589
16590 @itemize @bullet
16591 @item No need to use non-Ada tools
16592 @item Consistent interface over different targets
16593 @item Automatic usage of the proper calling conventions
16594 @item Access to Ada constants and variables
16595 @item Definition of intrinsic routines
16596 @item Possibility of inlining a subprogram comprising assembler code
16597 @item Code optimizer can take Inline Assembler code into account
16598 @end itemize
16599
16600 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.
16601
16602 @menu
16603 * Basic Assembler Syntax::
16604 * A Simple Example of Inline Assembler::
16605 * Output Variables in Inline Assembler::
16606 * Input Variables in Inline Assembler::
16607 * Inlining Inline Assembler Code::
16608 * Other Asm Functionality::
16609 * A Complete Example::
16610 @end menu
16611
16612 @c ---------------------------------------------------------------------------
16613 @node Basic Assembler Syntax
16614 @section Basic Assembler Syntax
16615
16616 @noindent
16617 The assembler used by GNAT and gcc is based not on the Intel assembly language, but rather on a
16618 language that descends from the AT&T Unix assembler @emph{as} (and which is often
16619 referred to as ``AT&T syntax'').
16620 The following table summarizes the main features of @emph{as} syntax and points out the differences from the Intel conventions.
16621 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
16622 pre-processor) documentation for further information.
16623
16624 @table @asis
16625 @item Register names
16626 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
16627 @*
16628 Intel: No extra punctuation; for example @code{eax}
16629
16630 @item Immediate operand
16631 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
16632 @*
16633 Intel: No extra punctuation; for example @code{4}
16634
16635 @item Address
16636 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
16637 @*
16638 Intel: No extra punctuation; for example @code{loc}
16639
16640 @item Memory contents
16641 gcc / @emph{as}: No extra punctuation; for example @code{loc}
16642 @*
16643 Intel: Square brackets; for example @code{[loc]}
16644
16645 @item Register contents
16646 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
16647 @*
16648 Intel: Square brackets; for example @code{[eax]}
16649
16650 @item Hexadecimal numbers
16651 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
16652 @*
16653 Intel: Trailing ``h''; for example @code{A0h}
16654
16655 @item Operand size
16656 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move a 16-bit word
16657 @*
16658 Intel: Implicit, deduced by assembler; for example @code{mov}
16659
16660 @item Instruction repetition
16661 gcc / @emph{as}: Split into two lines; for example
16662 @*
16663 @code{rep}
16664 @*
16665 @code{stosl}
16666 @*
16667 Intel: Keep on one line; for example @code{rep stosl}
16668
16669 @item Order of operands
16670 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
16671 @*
16672 Intel: Destination first; for example @code{mov eax, 4}
16673 @end table
16674
16675 @c ---------------------------------------------------------------------------
16676 @node A Simple Example of Inline Assembler
16677 @section A Simple Example of Inline Assembler
16678
16679 @noindent
16680 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.
16681
16682 @smallexample
16683 @group
16684 with System.Machine_Code; use System.Machine_Code;
16685 procedure Nothing is
16686 begin
16687    Asm ("nop");
16688 end Nothing;
16689 @end group
16690 @end smallexample
16691
16692 @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.
16693 @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.
16694
16695 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}.
16696
16697 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:
16698 @smallexample
16699 gnatmake nothing
16700 @end smallexample
16701 However, the interesting aspect of this example is not its run-time behavior but rather the
16702 generated assembly code.  To see this output, invoke the compiler as follows:
16703 @smallexample
16704    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
16705 @end smallexample
16706 where the options are:
16707
16708 @table @code
16709 @item -c
16710 compile only (no bind or link)
16711 @item -S
16712 generate assembler listing
16713 @item -fomit-frame-pointer
16714 do not set up separate stack frames
16715 @item -gnatp
16716 do not add runtime checks
16717 @end table
16718
16719 This gives a human-readable assembler version of the code. The resulting
16720 file will have the same name as the Ada source file, but with a @code{.s} extension.
16721 In our example, the file @file{nothing.s} has the following contents:
16722
16723 @smallexample
16724 @group
16725 .file "nothing.adb"
16726 gcc2_compiled.:
16727 ___gnu_compiled_ada:
16728 .text
16729    .align 4
16730 .globl __ada_nothing
16731 __ada_nothing:
16732 #APP
16733    nop
16734 #NO_APP
16735    jmp L1
16736    .align 2,0x90
16737 L1:
16738    ret
16739 @end group
16740 @end smallexample
16741
16742 The assembly code you included is clearly indicated by
16743 the compiler, between the @code{#APP} and @code{#NO_APP}
16744 delimiters. The character before the 'APP' and 'NOAPP'
16745 can differ on different targets. For example, Linux uses '#APP' while
16746 on NT you will see '/APP'.
16747
16748 If you make a mistake in your assembler code (such as using the
16749 wrong size modifier, or using a wrong operand for the instruction) GNAT
16750 will report this error in a temporary file, which will be deleted when
16751 the compilation is finished.  Generating an assembler file will help
16752 in such cases, since you can assemble this file separately using the
16753 @emph{as} assembler that comes with gcc.
16754
16755 Assembling the file using the command
16756
16757 @smallexample
16758 as @file{nothing.s}
16759 @end smallexample
16760 @noindent
16761 will give you error messages whose lines correspond to the assembler
16762 input file, so you can easily find and correct any mistakes you made.
16763 If there are no errors, @emph{as} will generate an object file @file{nothing.out}.
16764
16765 @c ---------------------------------------------------------------------------
16766 @node Output Variables in Inline Assembler
16767 @section Output Variables in Inline Assembler
16768
16769 @noindent
16770 The examples in this section, showing how to access the processor flags, illustrate how to specify the destination operands for assembly language statements.
16771
16772 @smallexample
16773 @group
16774 with Interfaces; use Interfaces;
16775 with Ada.Text_IO; use Ada.Text_IO;
16776 with System.Machine_Code; use System.Machine_Code;
16777 procedure Get_Flags is
16778    Flags : Unsigned_32;
16779    use ASCII;
16780 begin
16781    Asm ("pushfl"          & LF & HT & -- push flags on stack
16782         "popl %%eax"      & LF & HT & -- load eax with flags
16783         "movl %%eax, %0",             -- store flags in variable
16784         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
16785    Put_Line ("Flags register:" & Flags'Img);
16786 end Get_Flags;
16787 @end group
16788 @end smallexample
16789
16790 In order to have a nicely aligned assembly listing, we have separated
16791 multiple assembler statements in the Asm template string with linefeed (ASCII.LF)
16792 and horizontal tab (ASCII.HT) characters.  The resulting section of the
16793 assembly output file is:
16794
16795 @smallexample
16796 @group
16797 #APP
16798    pushfl
16799    popl %eax
16800    movl %eax, -40(%ebp)
16801 #NO_APP
16802 @end group
16803 @end smallexample
16804
16805 It would have been legal to write the Asm invocation as:
16806
16807 @smallexample
16808 Asm ("pushfl popl %%eax movl %%eax, %0")
16809 @end smallexample
16810
16811 but in the generated assembler file, this would come out as:
16812
16813 @smallexample
16814 #APP
16815    pushfl popl %eax movl %eax, -40(%ebp)
16816 #NO_APP
16817 @end smallexample
16818
16819 which is not so convenient for the human reader.
16820
16821 We use Ada comments
16822 at the end of each line to explain what the assembler instructions
16823 actually do.  This is a useful convention.
16824
16825 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.
16826
16827 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}.
16828 An output variable is illustrated in
16829 the third statement in the Asm template string:
16830 @smallexample
16831 movl %%eax, %0
16832 @end smallexample
16833 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.
16834
16835 Information about the output variable is supplied in the @code{Outputs} parameter to @code{Asm}:
16836 @smallexample
16837 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
16838 @end smallexample
16839
16840 The output is defined by the @code{Asm_Output} attribute of the target type; the general format is
16841 @smallexample
16842 Type'Asm_Output (constraint_string, variable_name)
16843 @end smallexample
16844
16845 The constraint string directs the compiler how
16846 to store/access the associated variable.  In the example
16847 @smallexample
16848 Unsigned_32'Asm_Output ("=m", Flags);
16849 @end smallexample
16850 the @code{"m"} (memory) constraint tells the compiler that the variable
16851 @code{Flags} should be stored in a memory variable, thus preventing
16852 the optimizer from keeping it in a register.  In contrast,
16853 @smallexample
16854 Unsigned_32'Asm_Output ("=r", Flags);
16855 @end smallexample
16856 uses the @code{"r"} (register) constraint, telling the compiler to
16857 store the variable in a register.
16858
16859 If the constraint is preceded by the equal character (@strong{=}), it tells the
16860 compiler that the variable will be used to store data into it.
16861
16862 In the @code{Get_Flags} example, we used the "g" (global) constraint, allowing the optimizer
16863 to choose whatever it deems best.
16864
16865 There are a fairly large number of constraints, but the ones that are most useful (for the Intel x86 processor) are the following:
16866
16867 @table @code
16868 @item =
16869 output constraint
16870 @item g
16871 global (i.e. can be stored anywhere)
16872 @item m
16873 in memory
16874 @item I
16875 a constant
16876 @item a
16877 use eax
16878 @item b
16879 use ebx
16880 @item c
16881 use ecx
16882 @item d
16883 use edx
16884 @item S
16885 use esi
16886 @item D
16887 use edi
16888 @item r
16889 use one of eax, ebx, ecx or edx
16890 @item q
16891 use one of eax, ebx, ecx, edx, esi or edi
16892 @end table
16893
16894 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.
16895
16896 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
16897 @smallexample
16898 @group
16899 Asm ("pushfl"          & LF & HT & -- push flags on stack
16900      "popl %%eax"      & LF & HT & -- load eax with flags
16901      "movl %%eax, %0",             -- store flags in variable
16902      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
16903 @end group
16904 @end smallexample
16905 @noindent
16906 @code{%0} will be replaced in the expanded code by the appropriate operand,
16907 whatever
16908 the compiler decided for the @code{Flags} variable.
16909
16910 In general, you may have any number of output variables:
16911 @itemize @bullet
16912 @item
16913 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
16914 @item
16915 Specify the @code{Outputs} parameter as a parenthesized comma-separated list of @code{Asm_Output} attributes
16916 @end itemize
16917
16918 For example:
16919 @smallexample
16920 @group
16921 Asm ("movl %%eax, %0" & LF & HT &
16922      "movl %%ebx, %1" & LF & HT &
16923      "movl %%ecx, %2",
16924      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
16925                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
16926                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
16927 @end group
16928 @end smallexample
16929 @noindent
16930 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables in the Ada program.
16931
16932 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:
16933
16934 @smallexample
16935 @group
16936 with Interfaces; use Interfaces;
16937 with Ada.Text_IO; use Ada.Text_IO;
16938 with System.Machine_Code; use System.Machine_Code;
16939 procedure Get_Flags_2 is
16940    Flags : Unsigned_32;
16941    use ASCII;
16942 begin
16943    Asm ("pushfl"      & LF & HT & -- push flags on stack
16944         "popl %%eax",             -- save flags in eax
16945         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
16946    Put_Line ("Flags register:" & Flags'Img);
16947 end Get_Flags_2;
16948 @end group
16949 @end smallexample
16950
16951 @noindent
16952 The @code{"a"} constraint tells the compiler that the @code{Flags}
16953 variable will come from the eax register. Here is the resulting code:
16954
16955 @smallexample
16956 @group
16957 #APP
16958    pushfl
16959    popl %eax
16960 #NO_APP
16961    movl %eax,-40(%ebp)
16962 @end group
16963 @end smallexample
16964
16965 @noindent
16966 The compiler generated the store of eax into Flags after
16967 expanding the assembler code.
16968
16969 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:
16970
16971 @smallexample
16972 @group
16973 with Interfaces; use Interfaces;
16974 with Ada.Text_IO; use Ada.Text_IO;
16975 with System.Machine_Code; use System.Machine_Code;
16976 procedure Get_Flags_3 is
16977    Flags : Unsigned_32;
16978    use ASCII;
16979 begin
16980    Asm ("pushfl"  & LF & HT & -- push flags on stack
16981         "pop %0",             -- save flags in Flags
16982         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
16983    Put_Line ("Flags register:" & Flags'Img);
16984 end Get_Flags_3;
16985 @end group
16986 @end smallexample
16987
16988 @c ---------------------------------------------------------------------------
16989 @node Input Variables in Inline Assembler
16990 @section Input Variables in Inline Assembler
16991
16992 @noindent
16993 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:
16994
16995 @smallexample
16996 @group
16997 with Interfaces; use Interfaces;
16998 with Ada.Text_IO; use Ada.Text_IO;
16999 with System.Machine_Code; use System.Machine_Code;
17000 procedure Increment is
17001
17002    function Incr (Value : Unsigned_32) return Unsigned_32 is
17003       Result : Unsigned_32;
17004    begin
17005       Asm ("incl %0",
17006            Inputs  => Unsigned_32'Asm_Input ("a", Value),
17007            Outputs => Unsigned_32'Asm_Output ("=a", Result));
17008       return Result;
17009    end Incr;
17010
17011    Value : Unsigned_32;
17012
17013 begin
17014    Value := 5;
17015    Put_Line ("Value before is" & Value'Img);
17016    Value := Incr (Value);
17017    Put_Line ("Value after is" & Value'Img);
17018 end Increment;
17019 @end group
17020 @end smallexample
17021
17022 The @code{Outputs} parameter to @code{Asm} specifies
17023 that the result will be in the eax register and that it is to be stored in the @code{Result}
17024 variable.
17025
17026 The @code{Inputs} parameter looks much like the @code{Outputs} parameter, but with an
17027 @code{Asm_Input} attribute. The
17028 @code{"="} constraint, indicating an output value, is not present.
17029
17030 You can have multiple input variables, in the same way that you can have more
17031 than one output variable.
17032
17033 The parameter count (%0, %1) etc, now starts at the first input
17034 statement, and continues with the output statements.
17035 When both parameters use the same variable, the
17036 compiler will treat them as the same %n operand, which is the case here.
17037
17038 Just as the @code{Outputs} parameter causes the register to be stored into the
17039 target variable after execution of the assembler statements, so does the
17040 @code{Inputs} parameter cause its variable to be loaded into the register before execution
17041 of the
17042 assembler statements.
17043
17044 Thus the effect of the @code{Asm} invocation is:
17045 @enumerate
17046 @item load the 32-bit value of @code{Value} into eax
17047 @item execute the @code{incl %eax} instruction
17048 @item store the contents of eax into the @code{Result} variable
17049 @end enumerate
17050
17051 The resulting assembler file (with @code{-O2} optimization) contains:
17052 @smallexample
17053 @group
17054 _increment__incr.1:
17055    subl $4,%esp
17056    movl 8(%esp),%eax
17057 #APP
17058    incl %eax
17059 #NO_APP
17060    movl %eax,%edx
17061    movl %ecx,(%esp)
17062    addl $4,%esp
17063    ret
17064 @end group
17065 @end smallexample
17066
17067 @c ---------------------------------------------------------------------------
17068 @node Inlining Inline Assembler Code
17069 @section Inlining Inline Assembler Code
17070
17071 @noindent
17072 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)
17073 can be significant, compared to the amount of code in the subprogram body.
17074 A solution is to apply Ada's @code{Inline} pragma to the subprogram,
17075 which directs the compiler to expand invocations of the subprogram at the point(s)
17076 of call, instead of setting up a stack frame for out-of-line calls.
17077 Here is the resulting program:
17078
17079 @smallexample
17080 @group
17081 with Interfaces; use Interfaces;
17082 with Ada.Text_IO; use Ada.Text_IO;
17083 with System.Machine_Code; use System.Machine_Code;
17084 procedure Increment_2 is
17085
17086    function Incr (Value : Unsigned_32) return Unsigned_32 is
17087       Result : Unsigned_32;
17088    begin
17089       Asm ("incl %0",
17090            Inputs  => Unsigned_32'Asm_Input ("a", Value),
17091            Outputs => Unsigned_32'Asm_Output ("=a", Result));
17092       return Result;
17093    end Incr;
17094    pragma Inline (Increment);
17095
17096    Value : Unsigned_32;
17097
17098 begin
17099    Value := 5;
17100    Put_Line ("Value before is" & Value'Img);
17101    Value := Increment (Value);
17102    Put_Line ("Value after is" & Value'Img);
17103 end Increment_2;
17104 @end group
17105 @end smallexample
17106
17107 Compile the program with both optimization (@code{-O2}) and inlining
17108 enabled (@option{-gnatpn} instead of @option{-gnatp}).
17109
17110 The @code{Incr} function is still compiled as usual, but at the
17111 point in @code{Increment} where our function used to be called:
17112
17113 @smallexample
17114 @group
17115 pushl %edi
17116 call _increment__incr.1
17117 @end group
17118 @end smallexample
17119
17120 @noindent
17121 the code for the function body directly appears:
17122
17123 @smallexample
17124 @group
17125 movl %esi,%eax
17126 #APP
17127    incl %eax
17128 #NO_APP
17129    movl %eax,%edx
17130 @end group
17131 @end smallexample
17132
17133 @noindent
17134 thus saving the overhead of stack frame setup and an out-of-line call.
17135
17136 @c ---------------------------------------------------------------------------
17137 @node Other Asm Functionality
17138 @section Other @code{Asm} Functionality
17139
17140 @noindent
17141 This section describes two important parameters to the @code{Asm} procedure: @code{Clobber}, which identifies register usage; and @code{Volatile}, which inhibits unwanted optimizations.
17142
17143 @menu
17144 * The Clobber Parameter::
17145 * The Volatile Parameter::
17146 @end menu
17147
17148 @c ---------------------------------------------------------------------------
17149 @node The Clobber Parameter
17150 @subsection The @code{Clobber} Parameter
17151
17152 @noindent
17153 One of the dangers of intermixing assembly language and a compiled language such as Ada is
17154 that the compiler needs to be aware of which registers are being used by the assembly code.
17155 In some cases, such as the earlier examples, the constraint string is sufficient to
17156 indicate register usage (e.g. "a" for the eax register).  But more generally, the
17157 compiler needs an explicit identification of the registers that are used by the Inline
17158 Assembly statements.
17159
17160 Using a register that the compiler doesn't know about
17161 could be a side effect of an instruction (like @code{mull}
17162 storing its result in both eax and edx).
17163 It can also arise from explicit register usage in your
17164 assembly code; for example:
17165 @smallexample
17166 @group
17167 Asm ("movl %0, %%ebx" & LF & HT &
17168      "movl %%ebx, %1",
17169      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
17170      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
17171 @end group
17172 @end smallexample
17173 @noindent
17174 where the compiler (since it does not analyze the @code{Asm} template string)
17175 does not know you are using the ebx register.
17176
17177 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
17178 to identify the registers that will be used by your assembly code:
17179
17180 @smallexample
17181 @group
17182 Asm ("movl %0, %%ebx" & LF & HT &
17183      "movl %%ebx, %1",
17184      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
17185      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
17186      Clobber => "ebx");
17187 @end group
17188 @end smallexample
17189
17190 The Clobber parameter is a static string expression specifying the
17191 register(s) you are using.  Note that register names are @emph{not} prefixed by a percent sign.
17192 Also, if more than one register is used then their names are separated by commas; e.g., @code{"eax, ebx"}
17193
17194 The @code{Clobber} parameter has several additional uses:
17195 @enumerate
17196 @item Use the "register" name @code{cc} to indicate that flags might have changed
17197 @item Use the "register" name @code{memory} if you changed a memory location
17198 @end enumerate
17199
17200 @c ---------------------------------------------------------------------------
17201 @node The Volatile Parameter
17202 @subsection The @code{Volatile} Parameter
17203 @cindex Volatile parameter
17204
17205 @noindent
17206 Compiler optimizations in the presence of Inline Assembler may sometimes have unwanted effects.
17207 For example, when
17208 an @code{Asm} invocation with an input variable is inside a loop, the compiler might move
17209 the loading of the input variable outside the loop, regarding it as a
17210 one-time initialization.
17211
17212 If this effect is not desired, you can disable such optimizations by setting the
17213 @code{Volatile} parameter to @code{True}; for example:
17214
17215 @smallexample
17216 @group
17217 Asm ("movl %0, %%ebx" & LF & HT &
17218      "movl %%ebx, %1",
17219      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
17220      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
17221      Clobber  => "ebx",
17222      Volatile => True);
17223 @end group
17224 @end smallexample
17225
17226 By default, @code{Volatile} is set to @code{False} unless there is no @code{Outputs}
17227 parameter.
17228
17229 Although setting @code{Volatile} to @code{True} prevents unwanted optimizations,
17230 it will also disable other optimizations that might be important for efficiency.
17231 In general, you should set @code{Volatile} to @code{True} only if the compiler's
17232 optimizations have created problems.
17233
17234 @c ---------------------------------------------------------------------------
17235 @node A Complete Example
17236 @section A Complete Example
17237
17238 @noindent
17239 This section contains a complete program illustrating a realistic usage of GNAT's Inline Assembler
17240 capabilities.  It comprises a main procedure @code{Check_CPU} and a package @code{Intel_CPU}.
17241 The package declares a collection of functions that detect the properties of the 32-bit
17242 x86 processor that is running the program.  The main procedure invokes these functions
17243 and displays the information.
17244
17245 The Intel_CPU package could be enhanced by adding functions to
17246 detect the type of x386 co-processor, the processor caching options and
17247 special operations such as the SIMD extensions.
17248
17249 Although the Intel_CPU package has been written for 32-bit Intel
17250 compatible CPUs, it is OS neutral. It has been tested on DOS,
17251 Windows/NT and Linux.
17252
17253 @menu
17254 * Check_CPU Procedure::
17255 * Intel_CPU Package Specification::
17256 * Intel_CPU Package Body::
17257 @end menu
17258
17259 @c ---------------------------------------------------------------------------
17260 @node Check_CPU Procedure
17261 @subsection @code{Check_CPU} Procedure
17262 @cindex Check_CPU procedure
17263
17264 @smallexample
17265 ---------------------------------------------------------------------
17266 --                                                                 --
17267 --  Uses the Intel_CPU package to identify the CPU the program is  --
17268 --  running on, and some of the features it supports.              --
17269 --                                                                 --
17270 ---------------------------------------------------------------------
17271
17272 with Intel_CPU;                     --  Intel CPU detection functions
17273 with Ada.Text_IO;                   --  Standard text I/O
17274 with Ada.Command_Line;              --  To set the exit status
17275
17276 procedure Check_CPU is
17277
17278    Type_Found : Boolean := False;
17279    --  Flag to indicate that processor was identified
17280
17281    Features   : Intel_CPU.Processor_Features;
17282    --  The processor features
17283
17284    Signature  : Intel_CPU.Processor_Signature;
17285    --  The processor type signature
17286
17287 begin
17288
17289    -----------------------------------
17290    --  Display the program banner.  --
17291    -----------------------------------
17292
17293    Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name &
17294                          ": check Intel CPU version and features, v1.0");
17295    Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever");
17296    Ada.Text_IO.New_Line;
17297
17298    -----------------------------------------------------------------------
17299    --  We can safely start with the assumption that we are on at least  --
17300    --  a x386 processor. If the CPUID instruction is present, then we   --
17301    --  have a later processor type.                                     --
17302    -----------------------------------------------------------------------
17303
17304    if Intel_CPU.Has_CPUID = False then
17305
17306       --  No CPUID instruction, so we assume this is indeed a x386
17307       --  processor. We can still check if it has a FP co-processor.
17308       if Intel_CPU.Has_FPU then
17309          Ada.Text_IO.Put_Line
17310            ("x386-type processor with a FP co-processor");
17311       else
17312          Ada.Text_IO.Put_Line
17313            ("x386-type processor without a FP co-processor");
17314       end if;  --  check for FPU
17315
17316       --  Program done
17317       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
17318       return;
17319
17320    end if;  --  check for CPUID
17321
17322    -----------------------------------------------------------------------
17323    --  If CPUID is supported, check if this is a true Intel processor,  --
17324    --  if it is not, display a warning.                                 --
17325    -----------------------------------------------------------------------
17326
17327    if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then
17328       Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor");
17329       Ada.Text_IO.Put_Line ("*** Some information may be incorrect");
17330    end if;  --  check if Intel
17331
17332    ----------------------------------------------------------------------
17333    --  With the CPUID instruction present, we can assume at least a    --
17334    --  x486 processor. If the CPUID support level is < 1 then we have  --
17335    --  to leave it at that.                                            --
17336    ----------------------------------------------------------------------
17337
17338    if Intel_CPU.CPUID_Level < 1 then
17339
17340       --  Ok, this is a x486 processor. we still can get the Vendor ID
17341       Ada.Text_IO.Put_Line ("x486-type processor");
17342       Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID);
17343
17344       --  We can also check if there is a FPU present
17345       if Intel_CPU.Has_FPU then
17346          Ada.Text_IO.Put_Line ("Floating-Point support");
17347       else
17348          Ada.Text_IO.Put_Line ("No Floating-Point support");
17349       end if;  --  check for FPU
17350
17351       --  Program done
17352       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
17353       return;
17354
17355    end if;  --  check CPUID level
17356
17357    ---------------------------------------------------------------------
17358    --  With a CPUID level of 1 we can use the processor signature to  --
17359    --  determine it's exact type.                                     --
17360    ---------------------------------------------------------------------
17361
17362    Signature := Intel_CPU.Signature;
17363
17364    ----------------------------------------------------------------------
17365    --  Ok, now we go into a lot of messy comparisons to get the        --
17366    --  processor type. For clarity, no attememt to try to optimize the --
17367    --  comparisons has been made. Note that since Intel_CPU does not   --
17368    --  support getting cache info, we cannot distinguish between P5    --
17369    --  and Celeron types yet.                                          --
17370    ----------------------------------------------------------------------
17371
17372    --  x486SL
17373    if Signature.Processor_Type = 2#00#   and
17374      Signature.Family          = 2#0100# and
17375      Signature.Model           = 2#0100# then
17376       Type_Found := True;
17377       Ada.Text_IO.Put_Line ("x486SL processor");
17378    end if;
17379
17380    --  x486DX2 Write-Back
17381    if Signature.Processor_Type = 2#00#   and
17382      Signature.Family          = 2#0100# and
17383      Signature.Model           = 2#0111# then
17384       Type_Found := True;
17385       Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor");
17386    end if;
17387
17388    --  x486DX4
17389    if Signature.Processor_Type = 2#00#   and
17390      Signature.Family          = 2#0100# and
17391      Signature.Model           = 2#1000# then
17392       Type_Found := True;
17393       Ada.Text_IO.Put_Line ("x486DX4 processor");
17394    end if;
17395
17396    --  x486DX4 Overdrive
17397    if Signature.Processor_Type = 2#01#   and
17398      Signature.Family          = 2#0100# and
17399      Signature.Model           = 2#1000# then
17400       Type_Found := True;
17401       Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor");
17402    end if;
17403
17404    --  Pentium (60, 66)
17405    if Signature.Processor_Type = 2#00#   and
17406      Signature.Family          = 2#0101# and
17407      Signature.Model           = 2#0001# then
17408       Type_Found := True;
17409       Ada.Text_IO.Put_Line ("Pentium processor (60, 66)");
17410    end if;
17411
17412    --  Pentium (75, 90, 100, 120, 133, 150, 166, 200)
17413    if Signature.Processor_Type = 2#00#   and
17414      Signature.Family          = 2#0101# and
17415      Signature.Model           = 2#0010# then
17416       Type_Found := True;
17417       Ada.Text_IO.Put_Line
17418         ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)");
17419    end if;
17420
17421    --  Pentium OverDrive (60, 66)
17422    if Signature.Processor_Type = 2#01#   and
17423      Signature.Family          = 2#0101# and
17424      Signature.Model           = 2#0001# then
17425       Type_Found := True;
17426       Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)");
17427    end if;
17428
17429    --  Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200)
17430    if Signature.Processor_Type = 2#01#   and
17431      Signature.Family          = 2#0101# and
17432      Signature.Model           = 2#0010# then
17433       Type_Found := True;
17434       Ada.Text_IO.Put_Line
17435         ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)");
17436    end if;
17437
17438    --  Pentium OverDrive processor for x486 processor-based systems
17439    if Signature.Processor_Type = 2#01#   and
17440      Signature.Family          = 2#0101# and
17441      Signature.Model           = 2#0011# then
17442       Type_Found := True;
17443       Ada.Text_IO.Put_Line
17444         ("Pentium OverDrive processor for x486 processor-based systems");
17445    end if;
17446
17447    --  Pentium processor with MMX technology (166, 200)
17448    if Signature.Processor_Type = 2#00#   and
17449      Signature.Family          = 2#0101# and
17450      Signature.Model           = 2#0100# then
17451       Type_Found := True;
17452       Ada.Text_IO.Put_Line
17453         ("Pentium processor with MMX technology (166, 200)");
17454    end if;
17455
17456    --  Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133)
17457    if Signature.Processor_Type = 2#01#   and
17458      Signature.Family          = 2#0101# and
17459      Signature.Model           = 2#0100# then
17460       Type_Found := True;
17461       Ada.Text_IO.Put_Line
17462         ("Pentium OverDrive processor with MMX " &
17463          "technology for Pentium processor (75, 90, 100, 120, 133)");
17464    end if;
17465
17466    --  Pentium Pro processor
17467    if Signature.Processor_Type = 2#00#   and
17468      Signature.Family          = 2#0110# and
17469      Signature.Model           = 2#0001# then
17470       Type_Found := True;
17471       Ada.Text_IO.Put_Line ("Pentium Pro processor");
17472    end if;
17473
17474    --  Pentium II processor, model 3
17475    if Signature.Processor_Type = 2#00#   and
17476      Signature.Family          = 2#0110# and
17477      Signature.Model           = 2#0011# then
17478       Type_Found := True;
17479       Ada.Text_IO.Put_Line ("Pentium II processor, model 3");
17480    end if;
17481
17482    --  Pentium II processor, model 5 or Celeron processor
17483    if Signature.Processor_Type = 2#00#   and
17484      Signature.Family          = 2#0110# and
17485      Signature.Model           = 2#0101# then
17486       Type_Found := True;
17487       Ada.Text_IO.Put_Line
17488         ("Pentium II processor, model 5 or Celeron processor");
17489    end if;
17490
17491    --  Pentium Pro OverDrive processor
17492    if Signature.Processor_Type = 2#01#   and
17493      Signature.Family          = 2#0110# and
17494      Signature.Model           = 2#0011# then
17495       Type_Found := True;
17496       Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor");
17497    end if;
17498
17499    --  If no type recognized, we have an unknown. Display what
17500    --  we _do_ know
17501    if Type_Found = False then
17502       Ada.Text_IO.Put_Line ("Unknown processor");
17503    end if;
17504
17505    -----------------------------------------
17506    --  Display processor stepping level.  --
17507    -----------------------------------------
17508
17509    Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img);
17510
17511    ---------------------------------
17512    --  Display vendor ID string.  --
17513    ---------------------------------
17514
17515    Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID);
17516
17517    ------------------------------------
17518    --  Get the processors features.  --
17519    ------------------------------------
17520
17521    Features := Intel_CPU.Features;
17522
17523    -----------------------------
17524    --  Check for a FPU unit.  --
17525    -----------------------------
17526
17527    if Features.FPU = True then
17528       Ada.Text_IO.Put_Line ("Floating-Point unit available");
17529    else
17530       Ada.Text_IO.Put_Line ("no Floating-Point unit");
17531    end if;  --  check for FPU
17532
17533    --------------------------------
17534    --  List processor features.  --
17535    --------------------------------
17536
17537    Ada.Text_IO.Put_Line ("Supported features: ");
17538
17539    --  Virtual Mode Extension
17540    if Features.VME = True then
17541       Ada.Text_IO.Put_Line ("    VME    - Virtual Mode Extension");
17542    end if;
17543
17544    --  Debugging Extension
17545    if Features.DE = True then
17546       Ada.Text_IO.Put_Line ("    DE     - Debugging Extension");
17547    end if;
17548
17549    --  Page Size Extension
17550    if Features.PSE = True then
17551       Ada.Text_IO.Put_Line ("    PSE    - Page Size Extension");
17552    end if;
17553
17554    --  Time Stamp Counter
17555    if Features.TSC = True then
17556       Ada.Text_IO.Put_Line ("    TSC    - Time Stamp Counter");
17557    end if;
17558
17559    --  Model Specific Registers
17560    if Features.MSR = True then
17561       Ada.Text_IO.Put_Line ("    MSR    - Model Specific Registers");
17562    end if;
17563
17564    --  Physical Address Extension
17565    if Features.PAE = True then
17566       Ada.Text_IO.Put_Line ("    PAE    - Physical Address Extension");
17567    end if;
17568
17569    --  Machine Check Extension
17570    if Features.MCE = True then
17571       Ada.Text_IO.Put_Line ("    MCE    - Machine Check Extension");
17572    end if;
17573
17574    --  CMPXCHG8 instruction supported
17575    if Features.CX8 = True then
17576       Ada.Text_IO.Put_Line ("    CX8    - CMPXCHG8 instruction");
17577    end if;
17578
17579    --  on-chip APIC hardware support
17580    if Features.APIC = True then
17581       Ada.Text_IO.Put_Line ("    APIC   - on-chip APIC hardware support");
17582    end if;
17583
17584    --  Fast System Call
17585    if Features.SEP = True then
17586       Ada.Text_IO.Put_Line ("    SEP    - Fast System Call");
17587    end if;
17588
17589    --  Memory Type Range Registers
17590    if Features.MTRR = True then
17591       Ada.Text_IO.Put_Line ("    MTTR   - Memory Type Range Registers");
17592    end if;
17593
17594    --  Page Global Enable
17595    if Features.PGE = True then
17596       Ada.Text_IO.Put_Line ("    PGE    - Page Global Enable");
17597    end if;
17598
17599    --  Machine Check Architecture
17600    if Features.MCA = True then
17601       Ada.Text_IO.Put_Line ("    MCA    - Machine Check Architecture");
17602    end if;
17603
17604    --  Conditional Move Instruction Supported
17605    if Features.CMOV = True then
17606       Ada.Text_IO.Put_Line
17607         ("    CMOV   - Conditional Move Instruction Supported");
17608    end if;
17609
17610    --  Page Attribute Table
17611    if Features.PAT = True then
17612       Ada.Text_IO.Put_Line ("    PAT    - Page Attribute Table");
17613    end if;
17614
17615    --  36-bit Page Size Extension
17616    if Features.PSE_36 = True then
17617       Ada.Text_IO.Put_Line ("    PSE_36 - 36-bit Page Size Extension");
17618    end if;
17619
17620    --  MMX technology supported
17621    if Features.MMX = True then
17622       Ada.Text_IO.Put_Line ("    MMX    - MMX technology supported");
17623    end if;
17624
17625    --  Fast FP Save and Restore
17626    if Features.FXSR = True then
17627       Ada.Text_IO.Put_Line ("    FXSR   - Fast FP Save and Restore");
17628    end if;
17629
17630    ---------------------
17631    --  Program done.  --
17632    ---------------------
17633
17634    Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
17635
17636 exception
17637
17638    when others =>
17639       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
17640       raise;
17641
17642 end Check_CPU;
17643 @end smallexample
17644
17645 @c ---------------------------------------------------------------------------
17646 @node Intel_CPU Package Specification
17647 @subsection @code{Intel_CPU} Package Specification
17648 @cindex Intel_CPU package specification
17649
17650 @smallexample
17651 -------------------------------------------------------------------------
17652 --                                                                     --
17653 --  file: intel_cpu.ads                                                --
17654 --                                                                     --
17655 --           *********************************************             --
17656 --           * WARNING: for 32-bit Intel processors only *             --
17657 --           *********************************************             --
17658 --                                                                     --
17659 --  This package contains a number of subprograms that are useful in   --
17660 --  determining the Intel x86 CPU (and the features it supports) on    --
17661 --  which the program is running.                                      --
17662 --                                                                     --
17663 --  The package is based upon the information given in the Intel       --
17664 --  Application Note AP-485: "Intel Processor Identification and the   --
17665 --  CPUID Instruction" as of April 1998. This application note can be  --
17666 --  found on www.intel.com.                                            --
17667 --                                                                     --
17668 --  It currently deals with 32-bit processors only, will not detect    --
17669 --  features added after april 1998, and does not guarantee proper     --
17670 --  results on Intel-compatible processors.                            --
17671 --                                                                     --
17672 --  Cache info and x386 fpu type detection are not supported.          --
17673 --                                                                     --
17674 --  This package does not use any privileged instructions, so should   --
17675 --  work on any OS running on a 32-bit Intel processor.                --
17676 --                                                                     --
17677 -------------------------------------------------------------------------
17678
17679 with Interfaces;             use Interfaces;
17680 --  for using unsigned types
17681
17682 with System.Machine_Code;    use System.Machine_Code;
17683 --  for using inline assembler code
17684
17685 with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
17686 --  for inserting control characters
17687
17688 package Intel_CPU is
17689
17690    ----------------------
17691    --  Processor bits  --
17692    ----------------------
17693
17694    subtype Num_Bits is Natural range 0 .. 31;
17695    --  the number of processor bits (32)
17696
17697    --------------------------
17698    --  Processor register  --
17699    --------------------------
17700
17701    --  define a processor register type for easy access to
17702    --  the individual bits
17703
17704    type Processor_Register is array (Num_Bits) of Boolean;
17705    pragma Pack (Processor_Register);
17706    for Processor_Register'Size use 32;
17707
17708    -------------------------
17709    --  Unsigned register  --
17710    -------------------------
17711
17712    --  define a processor register type for easy access to
17713    --  the individual bytes
17714
17715    type Unsigned_Register is
17716       record
17717          L1 : Unsigned_8;
17718          H1 : Unsigned_8;
17719          L2 : Unsigned_8;
17720          H2 : Unsigned_8;
17721       end record;
17722
17723    for Unsigned_Register use
17724       record
17725          L1 at 0 range  0 ..  7;
17726          H1 at 0 range  8 .. 15;
17727          L2 at 0 range 16 .. 23;
17728          H2 at 0 range 24 .. 31;
17729       end record;
17730
17731    for Unsigned_Register'Size use 32;
17732
17733    ---------------------------------
17734    --  Intel processor vendor ID  --
17735    ---------------------------------
17736
17737    Intel_Processor : constant String (1 .. 12) := "GenuineIntel";
17738    --  indicates an Intel manufactured processor
17739
17740    ------------------------------------
17741    --  Processor signature register  --
17742    ------------------------------------
17743
17744    --  a register type to hold the processor signature
17745
17746    type Processor_Signature is
17747       record
17748          Stepping       : Natural range 0 .. 15;
17749          Model          : Natural range 0 .. 15;
17750          Family         : Natural range 0 .. 15;
17751          Processor_Type : Natural range 0 .. 3;
17752          Reserved       : Natural range 0 .. 262143;
17753       end record;
17754
17755    for Processor_Signature use
17756       record
17757          Stepping       at 0 range  0 ..  3;
17758          Model          at 0 range  4 ..  7;
17759          Family         at 0 range  8 .. 11;
17760          Processor_Type at 0 range 12 .. 13;
17761          Reserved       at 0 range 14 .. 31;
17762       end record;
17763
17764    for Processor_Signature'Size use 32;
17765
17766    -----------------------------------
17767    --  Processor features register  --
17768    -----------------------------------
17769
17770    --  a processor register to hold the processor feature flags
17771
17772    type Processor_Features is
17773       record
17774          FPU    : Boolean;                --  floating point unit on chip
17775          VME    : Boolean;                --  virtual mode extension
17776          DE     : Boolean;                --  debugging extension
17777          PSE    : Boolean;                --  page size extension
17778          TSC    : Boolean;                --  time stamp counter
17779          MSR    : Boolean;                --  model specific registers
17780          PAE    : Boolean;                --  physical address extension
17781          MCE    : Boolean;                --  machine check extension
17782          CX8    : Boolean;                --  cmpxchg8 instruction
17783          APIC   : Boolean;                --  on-chip apic hardware
17784          Res_1  : Boolean;                --  reserved for extensions
17785          SEP    : Boolean;                --  fast system call
17786          MTRR   : Boolean;                --  memory type range registers
17787          PGE    : Boolean;                --  page global enable
17788          MCA    : Boolean;                --  machine check architecture
17789          CMOV   : Boolean;                --  conditional move supported
17790          PAT    : Boolean;                --  page attribute table
17791          PSE_36 : Boolean;                --  36-bit page size extension
17792          Res_2  : Natural range 0 .. 31;  --  reserved for extensions
17793          MMX    : Boolean;                --  MMX technology supported
17794          FXSR   : Boolean;                --  fast FP save and restore
17795          Res_3  : Natural range 0 .. 127; --  reserved for extensions
17796       end record;
17797
17798    for Processor_Features use
17799       record
17800          FPU    at 0 range  0 ..  0;
17801          VME    at 0 range  1 ..  1;
17802          DE     at 0 range  2 ..  2;
17803          PSE    at 0 range  3 ..  3;
17804          TSC    at 0 range  4 ..  4;
17805          MSR    at 0 range  5 ..  5;
17806          PAE    at 0 range  6 ..  6;
17807          MCE    at 0 range  7 ..  7;
17808          CX8    at 0 range  8 ..  8;
17809          APIC   at 0 range  9 ..  9;
17810          Res_1  at 0 range 10 .. 10;
17811          SEP    at 0 range 11 .. 11;
17812          MTRR   at 0 range 12 .. 12;
17813          PGE    at 0 range 13 .. 13;
17814          MCA    at 0 range 14 .. 14;
17815          CMOV   at 0 range 15 .. 15;
17816          PAT    at 0 range 16 .. 16;
17817          PSE_36 at 0 range 17 .. 17;
17818          Res_2  at 0 range 18 .. 22;
17819          MMX    at 0 range 23 .. 23;
17820          FXSR   at 0 range 24 .. 24;
17821          Res_3  at 0 range 25 .. 31;
17822       end record;
17823
17824    for Processor_Features'Size use 32;
17825
17826    -------------------
17827    --  Subprograms  --
17828    -------------------
17829
17830    function Has_FPU return Boolean;
17831    --  return True if a FPU is found
17832    --  use only if CPUID is not supported
17833
17834    function Has_CPUID return Boolean;
17835    --  return True if the processor supports the CPUID instruction
17836
17837    function CPUID_Level return Natural;
17838    --  return the CPUID support level (0, 1 or 2)
17839    --  can only be called if the CPUID instruction is supported
17840
17841    function Vendor_ID return String;
17842    --  return the processor vendor identification string
17843    --  can only be called if the CPUID instruction is supported
17844
17845    function Signature return Processor_Signature;
17846    --  return the processor signature
17847    --  can only be called if the CPUID instruction is supported
17848
17849    function Features return Processor_Features;
17850    --  return the processors features
17851    --  can only be called if the CPUID instruction is supported
17852
17853 private
17854
17855    ------------------------
17856    --  EFLAGS bit names  --
17857    ------------------------
17858
17859    ID_Flag : constant Num_Bits := 21;
17860    --  ID flag bit
17861
17862 end Intel_CPU;
17863 @end smallexample
17864
17865 @c ---------------------------------------------------------------------------
17866 @node Intel_CPU Package Body
17867 @subsection @code{Intel_CPU} Package Body
17868 @cindex Intel_CPU package body
17869
17870 @smallexample
17871 package body Intel_CPU is
17872
17873    ---------------------------
17874    --  Detect FPU presence  --
17875    ---------------------------
17876
17877    --  There is a FPU present if we can set values to the FPU Status
17878    --  and Control Words.
17879
17880    function Has_FPU return Boolean is
17881
17882       Register : Unsigned_16;
17883       --  processor register to store a word
17884
17885    begin
17886
17887       --  check if we can change the status word
17888       Asm (
17889
17890            --  the assembler code
17891            "finit"              & LF & HT &    --  reset status word
17892            "movw $0x5A5A, %%ax" & LF & HT &    --  set value status word
17893            "fnstsw %0"          & LF & HT &    --  save status word
17894            "movw %%ax, %0",                    --  store status word
17895
17896            --  output stored in Register
17897            --  register must be a memory location
17898            Outputs => Unsigned_16'Asm_output ("=m", Register),
17899
17900            --  tell compiler that we used eax
17901            Clobber => "eax");
17902
17903       --  if the status word is zero, there is no FPU
17904       if Register = 0 then
17905          return False;   --  no status word
17906       end if;  --  check status word value
17907
17908       --  check if we can get the control word
17909       Asm (
17910
17911            --  the assembler code
17912            "fnstcw %0",   --  save the control word
17913
17914            --  output into Register
17915            --  register must be a memory location
17916            Outputs => Unsigned_16'Asm_output ("=m", Register));
17917
17918       --  check the relevant bits
17919       if (Register and 16#103F#) /= 16#003F# then
17920          return False;   --  no control word
17921       end if;  --  check control word value
17922
17923       --  FPU found
17924       return True;
17925
17926    end Has_FPU;
17927
17928    --------------------------------
17929    --  Detect CPUID instruction  --
17930    --------------------------------
17931
17932    --  The processor supports the CPUID instruction if it is possible
17933    --  to change the value of ID flag bit in the EFLAGS register.
17934
17935    function Has_CPUID return Boolean is
17936
17937       Original_Flags, Modified_Flags : Processor_Register;
17938       --  EFLAG contents before and after changing the ID flag
17939
17940    begin
17941
17942       --  try flipping the ID flag in the EFLAGS register
17943       Asm (
17944
17945            --  the assembler code
17946            "pushfl"               & LF & HT &     --  push EFLAGS on stack
17947            "pop %%eax"            & LF & HT &     --  pop EFLAGS into eax
17948            "movl %%eax, %0"       & LF & HT &     --  save EFLAGS content
17949            "xor $0x200000, %%eax" & LF & HT &     --  flip ID flag
17950            "push %%eax"           & LF & HT &     --  push EFLAGS on stack
17951            "popfl"                & LF & HT &     --  load EFLAGS register
17952            "pushfl"               & LF & HT &     --  push EFLAGS on stack
17953            "pop %1",                              --  save EFLAGS content
17954
17955            --  output values, may be anything
17956            --  Original_Flags is %0
17957            --  Modified_Flags is %1
17958            Outputs =>
17959               (Processor_Register'Asm_output ("=g", Original_Flags),
17960                Processor_Register'Asm_output ("=g", Modified_Flags)),
17961
17962            --  tell compiler eax is destroyed
17963            Clobber => "eax");
17964
17965       --  check if CPUID is supported
17966       if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then
17967          return True;   --  ID flag was modified
17968       else
17969          return False;  --  ID flag unchanged
17970       end if;  --  check for CPUID
17971
17972    end Has_CPUID;
17973
17974    -------------------------------
17975    --  Get CPUID support level  --
17976    -------------------------------
17977
17978    function CPUID_Level return Natural is
17979
17980       Level : Unsigned_32;
17981       --  returned support level
17982
17983    begin
17984
17985       --  execute CPUID, storing the results in the Level register
17986       Asm (
17987
17988            --  the assembler code
17989            "cpuid",    --  execute CPUID
17990
17991            --  zero is stored in eax
17992            --  returning the support level in eax
17993            Inputs => Unsigned_32'Asm_input ("a", 0),
17994
17995            --  eax is stored in Level
17996            Outputs => Unsigned_32'Asm_output ("=a", Level),
17997
17998            --  tell compiler ebx, ecx and edx registers are destroyed
17999            Clobber => "ebx, ecx, edx");
18000
18001       --  return the support level
18002       return Natural (Level);
18003
18004    end CPUID_Level;
18005
18006    --------------------------------
18007    --  Get CPU Vendor ID String  --
18008    --------------------------------
18009
18010    --  The vendor ID string is returned in the ebx, ecx and edx register
18011    --  after executing the CPUID instruction with eax set to zero.
18012    --  In case of a true Intel processor the string returned is
18013    --  "GenuineIntel"
18014
18015    function Vendor_ID return String is
18016
18017       Ebx, Ecx, Edx : Unsigned_Register;
18018       --  registers containing the vendor ID string
18019
18020       Vendor_ID : String (1 .. 12);
18021       -- the vendor ID string
18022
18023    begin
18024
18025       --  execute CPUID, storing the results in the processor registers
18026       Asm (
18027
18028            --  the assembler code
18029            "cpuid",    --  execute CPUID
18030
18031            --  zero stored in eax
18032            --  vendor ID string returned in ebx, ecx and edx
18033            Inputs => Unsigned_32'Asm_input ("a", 0),
18034
18035            --  ebx is stored in Ebx
18036            --  ecx is stored in Ecx
18037            --  edx is stored in Edx
18038            Outputs => (Unsigned_Register'Asm_output ("=b", Ebx),
18039                        Unsigned_Register'Asm_output ("=c", Ecx),
18040                        Unsigned_Register'Asm_output ("=d", Edx)));
18041
18042       --  now build the vendor ID string
18043       Vendor_ID( 1) := Character'Val (Ebx.L1);
18044       Vendor_ID( 2) := Character'Val (Ebx.H1);
18045       Vendor_ID( 3) := Character'Val (Ebx.L2);
18046       Vendor_ID( 4) := Character'Val (Ebx.H2);
18047       Vendor_ID( 5) := Character'Val (Edx.L1);
18048       Vendor_ID( 6) := Character'Val (Edx.H1);
18049       Vendor_ID( 7) := Character'Val (Edx.L2);
18050       Vendor_ID( 8) := Character'Val (Edx.H2);
18051       Vendor_ID( 9) := Character'Val (Ecx.L1);
18052       Vendor_ID(10) := Character'Val (Ecx.H1);
18053       Vendor_ID(11) := Character'Val (Ecx.L2);
18054       Vendor_ID(12) := Character'Val (Ecx.H2);
18055
18056       --  return string
18057       return Vendor_ID;
18058
18059    end Vendor_ID;
18060
18061    -------------------------------
18062    --  Get processor signature  --
18063    -------------------------------
18064
18065    function Signature return Processor_Signature is
18066
18067       Result : Processor_Signature;
18068       --  processor signature returned
18069
18070    begin
18071
18072       --  execute CPUID, storing the results in the Result variable
18073       Asm (
18074
18075            --  the assembler code
18076            "cpuid",    --  execute CPUID
18077
18078            --  one is stored in eax
18079            --  processor signature returned in eax
18080            Inputs => Unsigned_32'Asm_input ("a", 1),
18081
18082            --  eax is stored in Result
18083            Outputs => Processor_Signature'Asm_output ("=a", Result),
18084
18085            --  tell compiler that ebx, ecx and edx are also destroyed
18086            Clobber => "ebx, ecx, edx");
18087
18088       --  return processor signature
18089       return Result;
18090
18091    end Signature;
18092
18093    ------------------------------
18094    --  Get processor features  --
18095    ------------------------------
18096
18097    function Features return Processor_Features is
18098
18099       Result : Processor_Features;
18100       --  processor features returned
18101
18102    begin
18103
18104       --  execute CPUID, storing the results in the Result variable
18105       Asm (
18106
18107            --  the assembler code
18108            "cpuid",    --  execute CPUID
18109
18110            --  one stored in eax
18111            --  processor features returned in edx
18112            Inputs => Unsigned_32'Asm_input ("a", 1),
18113
18114            --  edx is stored in Result
18115            Outputs => Processor_Features'Asm_output ("=d", Result),
18116
18117            --  tell compiler that ebx and ecx are also destroyed
18118            Clobber => "ebx, ecx");
18119
18120       --  return processor signature
18121       return Result;
18122
18123    end Features;
18124
18125 end Intel_CPU;
18126 @end smallexample
18127 @c END OF INLINE ASSEMBLER CHAPTER
18128 @c ===============================
18129
18130
18131 @node VxWorks Topics
18132 @chapter VxWorks Topics
18133
18134 @noindent
18135 This chapter describes topics that are specific to the GNAT for VxWorks
18136 configurations.
18137
18138 @menu
18139 * Kernel Configuration for VxWorks::
18140 * Kernel Compilation Issues for VxWorks::
18141 * Handling Relocation Issues for PowerPc Targets::
18142 * Support for Software Floating Point on PowerPC Processors::
18143 * Interrupt Handling for VxWorks::
18144 * Simulating Command Line Arguments for VxWorks::
18145 * Debugging Issues for VxWorks::
18146 * Using GNAT from the Tornado 2 Project Facility::
18147 * Frequently Asked Questions for VxWorks::
18148 @end menu
18149
18150 @node Kernel Configuration for VxWorks
18151 @section Kernel Configuration for VxWorks
18152
18153 @noindent
18154 When configuring your VxWorks kernel we recommend including the target
18155 shell. If you omit it from the configuration, you may get undefined
18156 symbols at load time, e.g.
18157
18158 @smallexample
18159 -> ld < hello.exe
18160 Loading hello.exe
18161 Undefined symbols:
18162 mkdir
18163 @end smallexample
18164
18165 @noindent
18166 Generally, such undefined symbols are harmless since these are used by
18167 optional parts of the GNAT run time. However if running your application
18168 generates a VxWorks exception or illegal instruction, you should reconfigure
18169 your kernel to resolve these symbols.
18170
18171 @node Kernel Compilation Issues for VxWorks
18172 @section Kernel Compilation Issues for VxWorks
18173
18174 @noindent
18175 If you plan to link an Ada module with a Tornado 2 Kernel, follow these steps.
18176 (Note that these recommendations apply to @file{cygnus-2.7.2-960126},
18177 shipped with Tornado 2 as the C compiler toolchain.)
18178
18179 @itemize @bullet
18180 @item
18181 Compile your Ada module without linking it with the VxWorks Library:
18182 @smallexample
18183 gnatmake foo.adb -largs -nostdlib
18184 @end smallexample
18185
18186 @item
18187 Edit your makefile and add on the @code{LIBS} line the exact path and name
18188 of the GCC library file provided with GNAT.
18189 @smallexample
18190 LIBS             = $(WIND_BASE)/target/lib/libPPC604gnuvx.a \
18191 /opt/gnu/gnat/lib/gcc-lib/powerpc-wrs-vxworks/2.8.1/libgcc.a
18192 @end smallexample
18193
18194 @noindent
18195 To know the exact name and location of this file, type
18196 @code{<arch>-gcc -print-libgcc-file-name} in a console. Note that this version of GCC is the
18197 one provided with GNAT.
18198 @smallexample
18199 ~ >powerpc-wrs-vxworks-gcc -print-libgcc-file-name
18200 /opt/gnu/gnat/lib/gcc-lib/powerpc-wrs-vxworks/2.8.1/libgcc.a
18201 @end smallexample
18202 @end itemize
18203
18204
18205 @node Handling Relocation Issues for PowerPc Targets
18206 @section Handling Relocation Issues for PowerPc Targets
18207 @cindex Relocation issues for PowerPc VxWorks targets
18208 @cindex PowerPc VxWorks, relocation issues
18209 @cindex VxWorks PowerPc, relocation issues
18210
18211 @noindent
18212 Under certain circumstances, loading a program onto a PowerPC
18213 board will fail with the message
18214 @emph{Relocation value does not fit in 24 bits}.
18215
18216 For some background on this issue, please refer to WRS' SPRs
18217 6040, 20257, and 22767.
18218 In summary,
18219 VxWorks on the PowerPC follows the variation of the SVR4 ABI known
18220 as the Embedded ABI (@emph{EABI}).
18221 @cindex Embedded ABI (for VxWorks on PowerPc)
18222 @cindex EABI (for VxWorks on PowerPc)
18223 In order to save space and time in
18224 embedded applications, the EABI specifies that the default for
18225 subprogram calls should be the branch instruction with relative
18226 addressing using an immediate operand.  The immediate operand
18227 to this instruction (relative address) is 24 bits wide.  It
18228 is sign extended and 2#00# is appended for the last 2 bits (all
18229 instructions must be on a 4 byte boundary).
18230 The resulting
18231 26 bit offset means that the target of the branch must be within
18232 +/- 32 Mbytes of the relative branch instruction.  When VxWorks
18233 is loading a program it completes the linking phase by
18234 resolving all of the unresolved references in the object being
18235 loaded.  When one of those references is a relative address in
18236 a branch instruction, and the linker determines that the target
18237 is more than 32 Mbytes away from the branch, the error occurs.
18238
18239 This only happens when the BSP is configured to use
18240 more than 32 MBytes of memory.  The VxWorks kernel is loaded into
18241 low memory addresses, and the error usually occurs when the target
18242 loader is used (because it loads objects into high memory, and thus
18243 calls from the program to the VxWorks kernel can be too far).
18244 @cindex VxWorks kernel (relocation issues on PowerPc)
18245
18246 One way to solve this problem is to use the Tornado
18247 host loader; this will place programs in low memory, close to the kernel.
18248
18249 Another approach is to make use of the @code{-mlongcall} option to the
18250 compiler;
18251 @cindex @code{-mlongcall} (gcc)
18252 GNAT has incorporated WRS'
18253 gcc modification that implements this option.
18254 If a subprogram call is
18255 compiled with the @code{-mlongcall} option, then the generated code
18256 constructs an absolute address in a register and uses a branch
18257 instruction with absolute addressing mode.
18258
18259 Starting with release 3.15, the GNAT runtime libraries that are
18260 distributed are compiled with the @code{-mlongcall} option.  In many
18261 cases the use of these libraries is sufficient to avoid the
18262 relocation problem, since it is the runtime library that contains
18263 calls to the VxWorks kernel that need to span the address space gap.
18264 If you are using an earlier GNAT release or a manually-built runtime,
18265 you should recompile the GNAT runtime library with @code{-mlongcall};
18266 you can use the
18267 @file{Makefile.adalib} file from the @file{adalib} directory.
18268
18269 Application code may need to be compiled with @code{-mlongcall} if there
18270 are calls directly to the kernel, the application is very large,
18271 or in some specialized linking/loading scenarios.
18272
18273 You can compile individual files with @code{-mlongcall} by placing this
18274 option on the @code{gcc} command line (for brevity we are omitting the
18275 @code{powerpc-wrs-vxworks-} prefix on the commands shown in this
18276 paragraph).
18277 If you provide @code{-mlongcall} as an option for @code{gnatmake}, it will be
18278 passed to all invocations of @code{gcc} that @code{gnatmake} directly performs.
18279 Note that one other compilation is made by @code{gnatlink}, on the file created
18280 by @code{gnatbind} for the elaboration package body
18281 (see @ref{Binding Using gnatbind}).
18282 Passing @code{-mlongcall} to @code{gnatlink}, either directly
18283 on the @code{gnatlink} command line or by including @code{-mlongcall} in the
18284 @code{-largs} list of @code{gnatmake}, will direct @code{gnatlink} to compile the
18285 binder file with the @code{-mlongcall} option.
18286
18287 To see the effect of @code{-mlongcall}, consider the following small example:
18288
18289 @smallexample
18290    procedure Proc is
18291       procedure Imported_Proc;
18292       pragma Import (Ada, Imported_Proc);
18293    begin
18294       Imported_Proc;
18295    end;
18296 @end smallexample
18297
18298 @noindent
18299 If you compile @code{Proc} with the default options (no @code{-mlongcall}), the following code is generated:
18300
18301 @smallexample
18302    _ada_proc:
18303            ...
18304            bl imported_proc
18305            ...
18306 @end smallexample
18307
18308 @noindent
18309 In contrast, here is the result with the @code{-mlongcall} option:
18310
18311 @smallexample
18312    _ada_proc:
18313            ...
18314            addis 9,0,imported_proc@@ha
18315            addi 0,9,imported_proc@@l
18316            mtlr 0
18317            blrl
18318            ...
18319 @end smallexample
18320
18321
18322 @node Support for Software Floating Point on PowerPC Processors
18323 @section Support for Software Floating Point on PowerPC Processors
18324
18325 @noindent
18326 The PowerPC 860 processor does not have hardware floating-point support.
18327 In order to build and run GNAT modules properly, you need to install and
18328 invoke software-emulated floating-point support as follows:
18329
18330 @itemize @bullet
18331 @item
18332 At installation time:
18333 @itemize @bullet
18334 @item
18335 Create a file @file{ada_object_path} under the directory
18336 @file{BASE\lib\gcc-lib\powerpc-wrs-vxworks\2.8.1}
18337 (by default @file{BASE}=@file{c:\gnatpro})
18338 containing the following line:
18339 @smallexample
18340 rts-soft-float\adalib
18341 @end smallexample
18342
18343 @item
18344 Create a file @file{ada_source_path} under the directory
18345 @file{BASE\lib\gcc-lib\powerpc-wrs-vxworks\2.8.1}
18346 (by default @file{BASE}=@file{c:\gnatpro})
18347 containing the following line:
18348 @smallexample
18349 rts-soft-float\adainclude
18350 @end smallexample
18351 @end itemize
18352
18353 @item
18354 When using the compiler, specify @option{-msoft-float}
18355 as a compiler and a linker option, e.g.:
18356 @smallexample
18357 $powerpc-wrs-vxworks-gnatmake -msoft-float module -largs -msoft-float
18358 @end smallexample
18359 @end itemize
18360
18361
18362 @node Interrupt Handling for VxWorks
18363 @section Interrupt Handling for VxWorks
18364
18365 @noindent
18366 GNAT offers a range of options for hardware interrupt handling. In rough
18367 order of latency and lack of restrictions:
18368
18369 @itemize @bullet
18370 @item Directly vectored interrupt procedure handlers
18371 @item Directly vectored interrupt procedures that signal a task using
18372 a suspension object
18373 @item Ada 95 protected procedure handlers for interrupts
18374 @item Ada 83 style interrupt entry handlers for interrupts
18375 @end itemize
18376
18377 @noindent
18378 In general, the range of possible solutions trades off latency versus
18379 restrictions in the handler code.  Restrictions in direct vectored
18380 interrupt handlers  are documented in the @cite{VxWorks Programmer's Guide}.
18381 Protected procedure handlers have only the
18382 restriction that no potentially blocking operations are performed within
18383 the handler.  Interrupt entries have no restrictions.  We recommend the
18384 use of the protected procedure mechanism as providing the best balance
18385 of these considerations for most applications.
18386
18387 All handler types must explicitly perform any required hardware cleanups,
18388 such as issuing an end-of-interrupt if necessary.
18389
18390 For VxWorks/AE, applications that handle interrupts must be loaded into
18391 the kernel protection domain.
18392
18393 @itemize @bullet
18394 @item Direct Vectored Interrupt Routines
18395
18396 @noindent
18397 This approach provides the lowest interrupt latency, but has the most
18398 restrictions on what VxWorks and Ada runtime calls can be made, as well
18399 as on what Ada entities are accessible to the handler code.  Such handlers
18400 are most useful when there are stringent latency requirements, and very
18401 little processing is to be performed in the handler.   Access to the
18402 necessary VxWorks routines for setting up such handlers is provided in
18403 the package @code{Interfaces.VxWorks}.
18404
18405 VxWorks restrictions are described in the @cite{VxWorks Programmer's Manual}.
18406 Note in particular that floating point context is not automatically saved and
18407 restored when interrupts are vectored to the handler.  If the handler is
18408 to execute floating point instructions, the statements involved must be
18409 bracketed by a pair of calls to @code{fppSave} and @code{fppRestore} defined
18410 in @code{Interfaces.VxWorks}.
18411
18412 In general, it is a good idea to save and restore the handler that was
18413 installed prior to application startup.  The routines @code{intVecGet}
18414 and @code{intVecSet} are used for this purpose.  The Ada handler code
18415 is installed into the vector table using routine @code{intConnect},
18416 which generates wrapper code to save and restore registers.
18417
18418 Example:
18419
18420 @smallexample
18421 with Interfaces.VxWorks; use Interfaces.VxWorks;
18422 with System;
18423
18424 package P is
18425
18426    Count : Natural := 0;
18427    pragma Atomic (Count);
18428
18429    --  Interrupt level used by this example
18430    Level : constant := 1;
18431
18432    --  Be sure to use a reasonable interrupt number for the target
18433    --  board!  Refer to the BSP for details.
18434    Interrupt : constant := 16#14#;
18435
18436    procedure Handler (Parameter : System.Address);
18437
18438 end P;
18439
18440 package body P is
18441
18442    procedure Handler (parameter : System.Address) is
18443       S : Status;
18444    begin
18445       Count := Count + 1;
18446       --  Acknowledge interrupt.  Not necessary for all interrupts.
18447       S := sysBusIntAck (intLevel => Level);
18448    end Handler;
18449 end P;
18450
18451 with Interfaces.VxWorks; use Interfaces.VxWorks;
18452 with Ada.Text_IO; use Ada.Text_IO;
18453
18454 with P; use P;
18455 procedure Useint is
18456    task T;
18457
18458    S : Status;
18459
18460    task body T is
18461    begin
18462       for I in 1 .. 10 loop
18463          Put_Line ("Generating an interrupt...");
18464          delay 1.0;
18465
18466          --  Generate interrupt, using interrupt number
18467          S := sysBusIntGen (Level, Interrupt);
18468       end loop;
18469    end T;
18470
18471    --  Save old handler
18472    Old_Handler : VOIDFUNCPTR := intVecGet (INUM_TO_IVEC (Interrupt));
18473 begin
18474    S := intConnect (INUM_TO_IVEC (Interrupt), Handler'Access);
18475    S := sysIntEnable (intLevel => Level);
18476
18477    for I in 1 .. 10 loop
18478       delay 2.0;
18479       Put_Line ("value of count:" & P.Count'Img);
18480    end loop;
18481
18482    --  Restore previous handler
18483    S := sysIntDisable (intLevel => Level);
18484    intVecSet (INUM_TO_IVEC (Interrupt), Old_Handler);
18485 end Useint;
18486 @end smallexample
18487
18488 @item Direct Vectored Interrupt Routines
18489
18490 @noindent
18491 A variation on the direct vectored routine that allows for less restrictive
18492 handler code is to separate the interrupt processing into two levels.
18493
18494 The first level is the same as in the previous section.  Here we perform
18495 simple hardware actions and signal a task pending on a Suspension_Object
18496 (defined in @code{Ada.Synchronous_Task_Control}) to perform the more complex
18497 and time-consuming operations.  The routine @code{Set_True} signals a task
18498 whose body loops and pends on the suspension object using @code{Suspend_Until_True}.
18499 The suspension object is declared in a scope global to both the handler and
18500 the task. This approach can be thought of as a slightly higher-level
18501 application of the @code{C} example using a binary semaphore given in the
18502 VxWorks Programmer's Manual.  In fact, the implementation of
18503 @code{Ada.Synchronous_Task_Control} is a very thin wrapper around a VxWorks
18504 binary semaphore.
18505
18506 This approach has a latency between the direct vectored approach and the
18507 protected procedure approach.  There are no restrictions in the Ada task
18508 code, while the handler code has the same restrictions as any other
18509 direct interrupt handler.
18510
18511 Example:
18512
18513 @smallexample
18514 with System;
18515 package Sem_Handler is
18516
18517    Count : Natural := 0;
18518    pragma Atomic (Count);
18519
18520    --  Interrupt level used by this example
18521    Level : constant := 1;
18522    Interrupt : constant := 16#14#;
18523
18524    --  Interrupt handler providing "immediate" handling
18525    procedure Handler (Param : System.Address);
18526
18527    --  Task whose body provides "deferred" handling
18528    task Receiver is
18529        pragma Interrupt_Priority
18530           (System.Interrupt_Priority'First + Level + 1);
18531     end Receiver;
18532
18533 end Sem_Handler;
18534
18535 with Ada.Synchronous_Task_Control; use Ada.Synchronous_Task_Control;
18536 with Interfaces.VxWorks; use Interfaces.VxWorks;
18537 package body Sema_Handler is
18538
18539    SO : Suspension_Object;
18540
18541    task body Receiver is
18542    begin
18543       loop
18544          --  Wait for notification from immediate handler
18545          Suspend_Until_True (SO);
18546
18547          --  Interrupt processing
18548          Count := Count + 1;
18549       end loop;
18550    end Receiver;
18551
18552    procedure Handler (Param : System.Address) is
18553       S : STATUS;
18554    begin
18555       --  Hardware cleanup, if necessary
18556       S := sysBusIntAck (Level);
18557
18558       --  Signal the task
18559       Set_True (SO);
18560    end Handler;
18561
18562 end Sem_Handler;
18563
18564 with Interfaces.VxWorks; use Interfaces.VxWorks;
18565 with Ada.Text_IO; use Ada.Text_IO;
18566 with Sem_Handler; use Sem_Handler;
18567 procedure Useint is
18568
18569    S : STATUS;
18570
18571    task T;
18572
18573    task body T is
18574    begin
18575       for I in 1 .. 10 loop
18576          Put_Line ("Generating an interrupt...");
18577          delay 1.0;
18578
18579          --  Generate interrupt, using interrupt number
18580          S := sysBusIntGen (Level, Interrupt);
18581       end loop;
18582    end T;
18583
18584    --  Save old handler
18585    Old_Handler : VOIDFUNCPTR := intVecGet (INUM_TO_IVEC (Interrupt));
18586 begin
18587    S := intConnect (INUM_TO_IVEC (Interrupt), Handler'Access);
18588    S := sysIntEnable (intLevel => Level);
18589
18590    for I in 1 .. 10 loop
18591       delay 2.0;
18592       Put_Line ("value of Count:" & Sem_Handler.Count'Img);
18593    end loop;
18594
18595    --  Restore handler
18596    S := sysIntDisable (intLevel => Level);
18597    intVecSet (INUM_TO_IVEC (Interrupt), Old_Handler);
18598    abort Receiver;
18599 end Useint;
18600 @end smallexample
18601
18602 @item Protected Procedure Handlers for Interrupts
18603
18604 @noindent
18605 This is the recommended default mechanism for interrupt handling.
18606 It essentially wraps the hybrid handler / task mechanism in a higher-level
18607 abstraction, and provides a good balance between latency and capability.
18608
18609 Vectored interrupts are designated by their interrupt number, starting from
18610 0 and ranging to the number of entries in the interrupt vector table - 1.
18611
18612 In the GNAT VxWorks implementation, the following priority mappings are used:
18613 @itemize @bullet
18614 @item Normal task priorities are in the range 0 .. 245.
18615 @item Interrupt priority 246 is used by the GNAT @code{Interrupt_Manager}
18616 task.
18617 @item Interrupt priority 247 is used for vectored interrupts
18618 that do not correspond to those generated via an interrupt controller.
18619 @item Interrupt priorities 248 .. 255 correspond to PIC interrupt levels
18620 0 .. 7.
18621 @item Priority 256 is reserved to the VxWorks kernel.
18622 @end itemize
18623
18624 Except for reserved priorities, the above are recommendations for setting the
18625 ceiling priority of a protected object that handles interrupts, or the
18626 priority of a task with interrupt entries.  It's a very good idea to follow
18627 these recommendations for vectored interrupts that come in through the PIC
18628 as it will determine the priority of execution of the code in the protected
18629 procedure or interrupt entry.
18630
18631 No vectored interrupt numbers are reserved in this implementation, because
18632 dedicated interrupts are determined by the board support package. Obviously,
18633 careful consideration of the hardware is necessary when handling interrupts.
18634 The VxWorks BSP for the board is the definitive reference for interrupt
18635 assignments.
18636
18637 Example:
18638
18639 @smallexample
18640 package PO_Handler is
18641
18642    --  Interrupt level used by this example
18643    Level : constant := 1;
18644
18645    Interrupt : constant := 16#14#;
18646
18647    protected Protected_Handler is
18648       procedure Handler;
18649       pragma Attach_Handler (Handler, Interrupt);
18650
18651       function Count return Natural;
18652
18653       pragma Interrupt_Priority (248);
18654    private
18655       The_Count : Natural := 0;
18656    end Protected_Handler;
18657
18658 end PO_Handler;
18659
18660 with Interfaces.VxWorks; use Interfaces.VxWorks;
18661 package body PO_Handler is
18662
18663    protected body Protected_Handler is
18664
18665       procedure Handler is
18666          S : Status;
18667       begin
18668          --  Hardware cleanup if necessary
18669          S := sysBusIntAck (Level);
18670
18671          --  Interrupt processing
18672          The_Count := The_Count + 1;
18673       end Handler;
18674
18675       function Count return Natural is
18676       begin
18677          return The_Count;
18678       end Count;
18679    end Protected_Handler;
18680
18681 end PO_Handler;
18682
18683 with Interfaces.VxWorks; use Interfaces.VxWorks;
18684 with Ada.Text_IO; use Ada.Text_IO;
18685
18686 with PO_Handler; use PO_Handler;
18687 procedure Useint is
18688
18689    task T;
18690
18691    S : STATUS;
18692
18693    task body T is
18694    begin
18695       for I in 1 .. 10 loop
18696          Put_Line ("Generating an interrupt...");
18697          delay 1.0;
18698
18699          --  Generate interrupt, using interrupt number
18700          S := sysBusIntGen (Level, Interrupt);
18701       end loop;
18702    end T;
18703
18704 begin
18705    S := sysIntEnable (intLevel => Level);
18706
18707    for I in 1 .. 10 loop
18708       delay 2.0;
18709       Put_Line ("value of count:" & Protected_Handler.Count'Img);
18710    end loop;
18711
18712    S := sysIntDisable (intLevel => Level);
18713 end Useint;
18714 @end smallexample
18715
18716 @noindent
18717 This is obviously significantly higher-level and easier to write than the
18718 previous examples.
18719
18720 @item Ada 83 Style Interrupt Entries
18721
18722 GNAT provides a full implementation of the Ada 83 interrupt entry mechanism
18723 for vectored interrupts.  However, due to latency issues,
18724 we only recommend using these for backward compatibility.  The comments in
18725 the previous section regarding interrupt priorities and reserved interrupts
18726 apply here.
18727
18728 In order to associate an interrupt with an entry, GNAT provides the
18729 standard Ada convenience routine @code{Ada.Interrupts.Reference}.  It is used
18730 as follows:
18731
18732 @smallexample
18733 Interrupt_Address : constant System.Address :=
18734    Ada.Interrupts.Reference (Int_Num);
18735
18736 task Handler_Task is
18737    pragma Interrupt_Priority (248);  -- For instance
18738    entry Handler;
18739    for Handler'Address use Interrupt_Address;
18740 end Handler_Task;
18741 @end smallexample
18742
18743 @noindent
18744 Since there is no restriction within an interrupt entry on blocking operations,
18745 be sure to perform any hardware interrupt controller related operations before
18746 executing a call that could block within the entry's accept statements.  It
18747 is assumed that interrupt entries are always open alternatives when they
18748 appear within a selective wait statement.  The presence of a guard gives
18749 undefined behavior.
18750
18751 Example:
18752
18753 @smallexample
18754 with Ada.Interrupts;
18755 with System;
18756 package Task_Handler is
18757
18758    --  Interrupt level used by this example
18759    Level : constant := 1;
18760
18761    Interrupt : constant := 16#14#;
18762
18763    Interrupt_Address : constant System.Address :=
18764       Ada.Interrupts.Reference (Int_Num);
18765
18766    task Handler_Task is
18767       pragma Interrupt_Priority (248);  -- For instance
18768       entry Handler;
18769       for Handler'Address use Interrupt_Address;
18770
18771       entry Count (Value : out Natural);
18772    end Handler_Task;
18773 end Task_Handler;
18774
18775 with Interfaces.VxWorks; use Interfaces.VxWorks;
18776 package body Task_Handler is
18777
18778    task body Handler_Task is
18779       The_Count : Natural := 0;
18780       S : STATUS;
18781    begin
18782       loop
18783          select
18784             accept Handler do
18785                --  Hardware cleanup if necessary
18786                S := sysBusIntAck (Level);
18787
18788                --  Interrupt processing
18789                The_Count := The_Count + 1;
18790             end Handler;
18791          or
18792             accept Count (Value : out Natural) do
18793                Value := The_Count;
18794             end Count;
18795          end select;
18796       end loop;
18797    end Handler_Task;
18798
18799 end Handler_Task;
18800
18801 with Interfaces.VxWorks; use Interfaces.VxWorks;
18802 with Ada.Text_IO; use Ada.Text_IO;
18803
18804 with Handler_Task; use Handler_Task;
18805 procedure Useint is
18806
18807    task T;
18808
18809    S : STATUS;
18810    Current_Count : Natural := 0;
18811
18812    task body T is
18813    begin
18814       for I in 1 .. 10 loop
18815          Put_Line ("Generating an interrupt...");
18816          delay 1.0;
18817
18818          --  Generate interrupt, using interrupt number
18819          S := sysBusIntGen (Level, Interrupt);
18820       end loop;
18821    end T;
18822
18823 begin
18824    S := sysIntEnable (intLevel => Level);
18825
18826    for I in 1 .. 10 loop
18827       delay 2.0;
18828       Handler_Task.Count (Current_Count);
18829       Put_Line ("value of count:" & Current_Count'Img);
18830    end loop;
18831
18832    S := sysIntDisable (intLevel => Level);
18833    abort Handler_Task;
18834 end Useint;
18835 @end smallexample
18836 @end itemize
18837
18838
18839 @node Simulating Command Line Arguments for VxWorks
18840 @section Simulating Command Line Arguments for VxWorks
18841
18842 @noindent
18843 The GNAT implementation of @code{Ada.Command_Line} relies on the standard C
18844 symbols @code{argv} and @code{argc}.  The model for invoking "programs" under
18845 VxWorks does not provide these symbols.  The typical method for invoking a
18846 program under VxWorks is to call the @code{sp} function in order to spawn a
18847 thread in which to execute a designated function (in GNAT, this is the implicit
18848 main generated by gnatbind. @code{sp} provides the capability to push a variable
18849 number of arguments onto the stack when the function is invoked.  But this does
18850 not work for the implicit Ada main, because it has no way of knowing how many
18851 arguments might be required.  This eliminates the possibility to use
18852 @code{Ada.Command_Line}.
18853
18854 One way to solve this problem is to define symbols in the VxWorks environment,
18855 then import them into the Ada application.  For example, we could define the
18856 following package that imports two symbols, one an int and the other a string:
18857
18858 @smallexample
18859 with Interfaces.C.Strings;
18860 use Interfaces.C.Strings;
18861 package Args is
18862    --  Define and import a variable for each argument
18863    Int_Arg : Interfaces.C.Int;
18864    String_Arg : Chars_Ptr;
18865 private
18866    pragma Import (C, Int_Arg, "intarg");
18867    pragma Import (C, String_Arg, "stringarg");
18868 end Args;
18869 @end smallexample
18870
18871 @noindent
18872 An Ada unit could then use the two imported variables @code{Int_Arg} and
18873 @code{String_Arg} as follows:
18874
18875 @smallexample
18876 with Args; use Args;
18877 with Interfaces.C.Strings;
18878 use Interfaces.C, Interfaces.C.Strings;
18879 with Ada.Text_IO; use Ada.Text_IO;
18880 procedure Argtest is
18881 begin
18882    Put_Line (Int'Image (Int_Arg));
18883    Put_Line (Value (String_Arg));
18884 end Argtest;
18885 @end smallexample
18886
18887 @noindent
18888 When invoking the application from the shell, one will then set the values
18889 to be imported, and spawn the application, as follows:
18890
18891 @smallexample
18892 -> intarg=10
18893 -> stringarg="Hello"
18894 -> sp (argtest)
18895 @end smallexample
18896
18897
18898 @node Debugging Issues for VxWorks
18899 @section Debugging Issues for VxWorks
18900
18901 @noindent
18902 The debugger can be launched directly from the Tornado environment or from @code{glide}
18903 through its graphical interface: @code{gvd}. It can also be used
18904 directly in text mode as shown below:
18905 @noindent
18906 The command to run @code{GDB} in text mode is
18907
18908 @smallexample
18909 $ @i{target}-gdb
18910 @end smallexample
18911
18912 @noindent
18913 where @i{target} is the name of target of the cross GNAT
18914 compiler. In contrast with native @code{gdb}, it is not useful to give the name of
18915 the program to debug on the command line. Before starting a debugging
18916 session, one needs to connect to the VxWorks-configured board and load
18917 the relocatable object produced by @code{gnatlink}. This can be achieved
18918 by the following commands:
18919
18920 @smallexample
18921 (vxgdb) target wtx myboard
18922 (vxgdb) load program
18923 @end smallexample
18924
18925 @noindent
18926 where @code{myboard} is the host name or IP number of the target board, and
18927 @code{wtx} is the name of debugging protocol used to communicate
18928 with the VxWorks board. Early versions of VxWorks, up tp 5.2, only
18929 support the @code{<vxworks>} protocol whereas starting with VxWorks 5.3
18930 and Tornado, another protocol called  @code{<wtx>} was made available. The
18931 choice of the protocol can be made when configuring the VxWorks
18932 kernel itself. When available, the @code{<wtx>} is greatly preferable
18933 and actually the only supported protocol with GNAT. When the debugger
18934 is  launched directly from Tornado, the proper @code{target} command
18935 is automatically generated by the environment.
18936
18937 The GNAT debugger can be used for debugging multitasking programs in two
18938 different modes and some minimal understanding of these modes is
18939 necessary in order to use the debugger effectively. The two modes are:
18940
18941 @itemize @bullet
18942 @item Monotask mode: attach to, and debug, a single task.
18943 This mode is equivalent to the capabilities offered by CrossWind. The
18944 debugger interacts with a single task, while not affecting other tasks
18945 (insofar as possible). This is the DEFAULT mode.
18946
18947 @item Multitask mode:
18948 The debugger has control over all Ada tasks in an application. It is
18949 possible to gather information about all application tasks, and to
18950 switch from one to another within a single debugging session.
18951 @end itemize
18952
18953 @noindent
18954 It is not advised to switch between the two modes within a debugging
18955 session. A third mode called System mode is also available and can be
18956 used in place of the Multitask mode. Consult the Tornado documentation
18957 for this.
18958
18959 Among the criteria for selecting the appropriate mode is the effect of
18960 task synchronization on the application's behavior. Debugging a
18961 tasking application affects the timing of the application; minimizing
18962 such effects may be critical in certain situations. The two modes have
18963 different effects: monotask mode only affects the attached task:
18964 others will run normally (if possible). Multitask mode stops all tasks
18965 at each breakpoint and restarts them on single-step, next, finish or
18966 continue; this may help avoid deadlocks in the presence of task
18967 synchronization despite the inherent latency of stopping and
18968 restarting the tasks.
18969
18970 @subsection Using the debugger in monotask mode
18971
18972 @noindent
18973 There are two ways to begin your debugging session:
18974
18975 @itemize @bullet
18976 @item The program is already running on the board.
18977
18978 @noindent
18979 The sequence of commands to use this mode is:
18980 @itemize @bullet
18981 @item Launch GVD (possibly from the Tornado menu)
18982
18983 @noindent
18984 Verify that the debugger has access to the debug information of both
18985 your program and the kernel. The Console window should have a message
18986 "Looking for all loaded modules:" followed by the names of the modules
18987 on the board and "ok". If you have some error messages here instead of
18988 "ok", the debugging session may not work as expected.
18989
18990 @item Attach to the desired task using
18991 @smallexample
18992         File --> Attach...
18993 @end smallexample
18994 @noindent
18995 This task is stopped by the debugger. Other tasks continue to operate
18996 normally (unless they are blocked by synchronization with the stopped
18997 task). The source window should display the code on which the task has
18998 been stopped, and if the stack display is enabled, it should reflect
18999 the stack of the task.
19000 @end itemize
19001
19002 @item The program hasn't been loaded yet on the board
19003 @itemize @bullet
19004 @item Launch GVD (possibly from the Tornado menu)
19005 @item Load your program to the board:
19006 @smallexample
19007 File --> Open Program...
19008 @end smallexample
19009
19010 @noindent
19011 GVD should display:
19012 @smallexample
19013 Downloading your_program ...done.
19014 Reading symbols from your_program...expanding to full symbols...done.
19015 @end smallexample
19016
19017 @item Set breakpoints in your program.
19018
19019 @noindent
19020 WARNING: they must be set in the main task (if your program runs
19021 several tasks)
19022
19023 @item Run your program using one of the three methods below:
19024 @itemize @bullet
19025 @item
19026 Click on button <run> or <start>
19027
19028 @item Menu
19029 @smallexample
19030 Program --> Run/Start
19031 @end smallexample
19032
19033 @item
19034 Type in GVD's Console window
19035 @smallexample
19036 (gdb) run your_program
19037 @end smallexample
19038 @end itemize
19039 @end itemize
19040
19041 @item Whichever method you chose to start your debugging session,
19042 you can use the following commands at this point:
19043 @itemize @bullet
19044 @item  Browse sources and set breakpoints
19045 @item  Examine the call stack (Data --> call stack)
19046 @item  Go "up" and "down" in the call stack ("up" & "down" buttons)
19047 @item  Examine data
19048 (Data --> Display local variables, or any of the other methods for viewing data in GVD)
19049 @item Continue/finish
19050 @end itemize
19051
19052 Next/step/finish will only work if the top frame in the call stack has
19053 debug information.  This is almost never the case when first attaching
19054 to the task since the task is usually stopped by the attach operation
19055 in the GNAT runtime. You can verify which frames of the call stack
19056 have debug information by:
19057 @smallexample
19058 Data --> call stack
19059 <right Button> (contextual menu inside the call stack window)
19060  add "file location"
19061 @end smallexample
19062
19063 @noindent
19064 If the current frame does not have a "file location", then there is no
19065 debug information for the frame.  We strongly recommended that you set
19066 breakpoints in the source where debug information can be found and
19067 "continue" until a breakpoint is reached before using
19068 "next/step". Another convenient possibility is to use the "continue
19069 until" capability available from the contextual menu of the Source
19070 window.
19071
19072 You can also examine the state of other tasks using
19073 @smallexample
19074 Data -> tasks
19075 @end smallexample
19076
19077 @noindent
19078 but you can't "switch" to another task by clicking on the
19079 elements of the task list. If you try to, you will get an error
19080 message in GVD's console:
19081 @smallexample
19082 "Task switching is not allowed when multi-tasks mode is not active"
19083 @end smallexample
19084
19085 @noindent
19086 Once you have completed your debugging session on the attached
19087 task, you can detach from the task:
19088 @smallexample
19089 File --> detach
19090 @end smallexample
19091
19092 @noindent
19093 The task resumes normal execution at this stage.  WARNING: when you
19094 detach from a task, be sure that you are in a frame where there is
19095 debug information. Otherwise, the task won't resume properly. You can
19096 then start another attach/detach cycle if you wish.
19097
19098 Note that it is possible to launch several GVD sessions and
19099 simultaneously attach each to a distinct task in monotask mode:
19100 @smallexample
19101 File --> New Debugger...  (uncheck the box: Replace Current Debugger)
19102 File --> Attach...     (in the new window)
19103 File --> detach
19104 @end smallexample
19105 @end itemize
19106
19107
19108 @subsection Using the debugger in Multitask mode
19109
19110 @noindent
19111 The steps are as follows
19112
19113 @itemize @bullet
19114 @item
19115 Launch GVD (possibly from the Tornado menu)
19116
19117 @noindent
19118 There are two possibilities:
19119 @itemize @bullet
19120 @item
19121 If the program is already loaded on the target board, you need only verify
19122 that debug information has been found by the debugger as described
19123 above.
19124
19125 @item
19126 Otherwise, load the program on the board using
19127 @smallexample
19128 File --> Open program
19129 @end smallexample
19130 @end itemize
19131
19132 @item Set breakpoints in the desired parts of the program
19133
19134 @item Start the program
19135
19136 @noindent
19137 The simplest way to start the debugger in multitask mode is to use the
19138 menu
19139 @smallexample
19140 Program --> Run/Start
19141 @end smallexample
19142
19143 @noindent
19144 and check the box "enable vxWorks multi-tasks mode".
19145 You can also use the following gdb commands in the console window
19146 @smallexample
19147         (gdb) set multi-tasks-mode on
19148         (gdb) run your_program
19149 @end smallexample
19150
19151 @item Debug the stopped program
19152
19153 @noindent
19154 Once stopped at a breakpoint
19155 (or if you pressed the "stop" button), you can use all the standard
19156 commands listed for monotask mode + task switching (using Data -->
19157 tasks). Using next/step under this mode is possible with the same
19158 restrictions as for monotask mode, but is not recommended because all
19159 tasks are restarted, leading to the possibility that a different task
19160 hits a breakpoint before the stepping operation has completed.  Such
19161 an occurrence can result in a confusing state for both the user and
19162 the debugger. So we strongly suggest the use of only breakpoints and
19163 "continue" in this mode.
19164 @end itemize
19165
19166 A final reminder: whatever the mode, whether you are debugging or not,
19167 the program has to be reloaded before each new execution, so that data
19168 initialized by the loader is set correctly. For instance, if you wish
19169 to restart the same execution of the same program, you can use the
19170 following sequence of gdb commands in the console window:
19171 @smallexample
19172 (gdb) detach
19173 (gdb) unload your_program(.exe)
19174 (gdb) load your_program(.exe)
19175 (gdb) run your_program
19176 @end smallexample
19177
19178
19179 @node Using GNAT from the Tornado 2 Project Facility
19180 @section Using GNAT from the Tornado 2 Project Facility
19181 @cindex Tornado II Project
19182
19183 @menu
19184 * The GNAT Toolchain as Used from the Tornado 2 Project Facility::
19185 * Building a Simple Application::
19186 * Mixing C and Ada Code in a Tornado 2 Project::
19187 * Compilation Switches::
19188 * Autoscale and Minimal Kernel Configuration::
19189 * Adapting BSPs to GNAT::
19190 * Using GNAT Project Files in a Tornado 2 Project::
19191 @end menu
19192
19193 @noindent
19194 This section describes how to add an Ada module in a Tornado project
19195 using the Tornado 2 Project facility described in
19196 @cite{Tornado User's Guide}, Chapter 4.
19197 All recommendations apply for both 'Downloadable Modules' and 'Kernel'
19198 project types.
19199
19200
19201 @node The GNAT Toolchain as Used from the Tornado 2 Project Facility
19202 @subsection The GNAT Toolchain as Used from the Tornado 2 Project Facility
19203
19204 @noindent
19205 Tornado 2 allows you to integrate third-party C toolchains.
19206 (@cite{Tornado 2 API Programmer's Guide}, Chapter 7).
19207 Thus the GNAT toolchain will be seen as a new C toolchain when used from
19208 the Tornado 2 Project Facility. For each processor you can compile for,
19209 you will find a <proc>gnat toolchain, e.g. PPC604gnat. These toolchains will
19210 allow you to include Ada modules into your projects, and simply build them.
19211
19212 The name of the so-called C compiler is @emph{cc_gnat_<arch>}, the name
19213 of the 'linker' is @emph{ld_gnat_<arch>}, where <arch> is an architecture; e.g.,
19214 PPC. These scripts will call the correct executables during the compilation or
19215 link processes, thus the C compiler, the C linker, or the GNAT toolchain,
19216 depending on the context.
19217
19218
19219 @node  Building a Simple Application
19220 @subsection  Building a Simple Application
19221
19222 @noindent
19223 First, create a new project, using one of the gnat toolchains.
19224
19225 To add an Ada source file to the current project, just click on
19226 @code{Project -> Add/Include}, browse to the relevant file, and include it.
19227 The Ada source file included should be the Ada entry point. Only
19228 one Ada entry point is allowed in a project. Any other required Ada source
19229 files will be automatically compiled and linked by the underlying tools.
19230
19231 You can now compile the project, @code{Build->Rebuild all}.
19232 A log of the compilation process can be found in the build directory, in
19233 @file{gnatbuild.log}. It contains all the calls executed by the scripts, and
19234 associated information.
19235
19236
19237 @node Mixing C and Ada Code in a Tornado 2 Project
19238 @subsection Mixing C and Ada Code in a Tornado 2 Project
19239
19240 @noindent
19241 You can mix C and Ada code in your projects. Your source files and the build
19242 options should comply with the recommendations from the section
19243 @cite{Interfacing to C}.
19244 This means that you can have several or no C source files, and one or no Ada entry
19245 point in your Tornado 2 Project.
19246
19247
19248 @node Compilation Switches
19249 @subsection Compilation Switches
19250 @noindent
19251 Once you have included all your source files, you may modify some compilation
19252 and linking options.
19253 To pass specific options to the GNAT toolchain, go to the Project's build
19254 settings, on the @code{C/C++ Compiler} tab, and add your arguments in the
19255 input window.
19256
19257 You must comply with several rules to pass arguments to GNAT.
19258 Arguments to be passed should be
19259
19260 @itemize @bullet
19261
19262 @item after any arguments passed to the C toolchain.
19263
19264 @item prefixed depending on the tool that uses them, with the following syntax
19265
19266 @itemize @bullet
19267 @item @code{-cargs @emph{gnatmake-options}} to pass arguments to gnatmake
19268 @item @code{-bargs @emph{gnatbind-options}} to pass arguments to gnatbind
19269 @item @code{-largs @emph{gnatlink-options}} to pass arguments to gnatlink
19270 @end itemize
19271 @end itemize
19272
19273 @noindent
19274 You will find more information on the compilation process of Ada source files
19275 in the section @cite{The GNAT Compilation Model}.
19276 For a list of all available switches, refer to the sections describing
19277 @code{gnatmake}, @code{gnatbind} and @code{gnatlink}.
19278
19279 Here is an example that passes the option @code{-v} to the GNAT compiler :
19280 @smallexample
19281 -g -mstrict-align -prjtype $(PRJ_TYPE) -ansi -nostdinc -DRW_MULTI_THREAD -D_REENTRANT
19282 -fno-builtin -fno-for-scope -I. -I/usr/windppc-2.0/target/h -DCPU=PPC604
19283 -cargs -v
19284 @end smallexample
19285
19286 @noindent
19287 Here is an example that passes the option @code{-v} to the GNAT compiler, binder and linker,
19288 and @code{-v} and @code{-g} to the compiler :
19289 @smallexample
19290 -g -mstrict-align -prjtype $(PRJ_TYPE) -ansi -nostdinc -DRW_MULTI_THREAD -D_REENTRANT
19291 -fno-builtin -fno-for-scope -I. -I/usr/windppc-2.0/target/h -DCPU=PPC604
19292 -cargs -v -g -O2 -bargs -v -largs -v
19293 @end smallexample
19294
19295 @noindent
19296 In both examples, the following arguments have been automatically added by the Project
19297 Facility, and will be used by the C compiler.
19298 @smallexample
19299 -g -mstrict-align -prjtype $(PRJ_TYPE) -ansi -nostdinc -DRW_MULTI_THREAD -D_REENTRANT
19300 -fno-builtin -fno-for-scope -I. -I/usr/windppc-2.0/target/h -DCPU=PPC604
19301 @end smallexample
19302
19303 @noindent
19304 Note: The @code{-prjtype $(PRJ_TYPE)} option present in a few input
19305 boxes is used by the GNAT toolchain. It is required for the compilation
19306 process. You should not remove it from any input box.
19307
19308
19309 @node Autoscale and Minimal Kernel Configuration
19310 @subsection Autoscale and Minimal Kernel Configuration
19311
19312 @noindent
19313 The Autoscale feature, present in the Project Facility  can be used on your
19314 VxWorks Kernel projects to determine the minimum set of components required
19315 for your kernel to work.
19316 (Please refer to the @cite{Tornado II User's Guide} Section 4.4 for more details.)
19317 This feature is also available for projects involving Ada code. Just click on
19318 @code{Project->Autoscale} to launch a check and determine the minimal kernel
19319 configuration.
19320
19321
19322 @node Adapting BSPs to GNAT
19323 @subsection Adapting BSPs to GNAT
19324
19325 @noindent
19326 To use your Board Support Packages with the GNAT toolchain, you will have to adapt them,
19327 either manually or using the @code{adaptbsp4gnat} script.
19328 This procedure is described in the @cite{Tornado API Programmer's Guide},
19329 Chapter 7.
19330 Here is a summary of this setup, depending on the context.
19331
19332 @itemize @bullet
19333 @item To do the adaptation manually:
19334
19335 @itemize @bullet
19336
19337 @item Copy your BSP directory contents into a new directory
19338
19339 @item Go to this directory
19340
19341 @item Edit the file @file{Makefile},
19342
19343 @itemize @bullet
19344 @item Set tool to gnat, @code{TOOL=gnat}
19345
19346 @item Reverse the order of the following lines
19347 @itemize @bullet
19348 @item @code{include $(TGT_DIR)/h/make/make.$(CPU)$(TOOL)}
19349 @item @code{include $(TGT_DIR)/h/make/defs.$(WIND_HOST_TYPE)}
19350 @end itemize
19351
19352 @end itemize
19353
19354 @end itemize
19355
19356 @item To do the adaptation automatically, you may use the @code{adaptbsp4gnat}
19357 script. Its syntax is @code{adaptbsp4gnat <path_to_bsp>}.
19358
19359 @noindent
19360 This script follows the different steps described above to perform the
19361 adaptation.
19362 The name of the new bsp is given after the modification.  By default, if
19363 @file{<bsp>} is the name of your BSP, @file{<bsp>-gnat}, will be the name of
19364 the BSP created.
19365 @end itemize
19366
19367
19368 @node Using GNAT Project Files in a Tornado 2 Project
19369 @subsection Using GNAT Project Files in a Tornado 2 Project
19370
19371 @noindent
19372 You can use GNAT Project files to compile your Ada files.
19373 To do so, you need to use the @option{-Pproject_file.gpr} option from @command{gnatmake}.
19374 The path to the project file can be either absolute, or relative to the build
19375 directory, i.e. where the executable will be placed (e.g. @file{~/myproject/PPC604gnat}).
19376 Your project file should set the @code{Object_Dir} variable to a specific
19377 value.
19378 @smallexample
19379 project Sample is
19380
19381    Target := external ("TARGET_DIR");
19382    for Object_Dir use Target;
19383
19384 end Sample;
19385 @end smallexample
19386
19387
19388 @node Frequently Asked Questions for VxWorks
19389 @section Frequently Asked Questions for VxWorks
19390
19391 @itemize @bullet
19392
19393 @item
19394 When I run my program twice on the board, it does not work, why?
19395
19396 @noindent
19397 Usually, Ada programs require elaboration and finalization, so the
19398 compiler creates a wrapper procedure whose name is the same as the Ada
19399 name of the main subprogram, which takes care of calling the elaboration
19400 and finalization routines before and after your program. But the static
19401 part of the elaboration is taken care of while loading the program
19402 itself and thus if you launch it twice this part of the elaboration will
19403 not be performed. This affects the proper elaboration of the
19404 GNAT runtime and thus it is mandatory to reload your program before
19405 relaunching it.
19406
19407 @item
19408 Can I load a collection of subprograms rather than a standalone program?
19409
19410 @noindent
19411 It is possible to write Ada programs with multiple entry points which
19412 can be called from the VxWorks shell; you just need to consider your
19413 main program as the VxWorks shell itself and generate an Ada subsystem
19414 callable from outside @xref{Binding with Non-Ada Main Programs}. If you
19415 use this method, you need to call @code{adainit} manually before calling
19416 any Ada entry point.
19417
19418 @item
19419 When I use the @code{break exception} command, I get the message
19420 @code{"exception" is not a function}, why?
19421
19422 You are not in the proper language mode. Issue the command:
19423 @smallexample
19424 (vxgdb) set language ada
19425 @end smallexample
19426
19427 @item
19428 When I load a large application from the VxWorks shell using the "ld"
19429 command, the load hangs and never finishes. How can I load large
19430 executables?
19431
19432 This is a classic VxWorks problem when using the default "rsh" communication
19433 method. Using NFS instead should work. Use the @code{nfsShowMount} command to
19434 verify that your program is in a NFS mounted directory.
19435
19436 @item
19437 When I load a large application from the debugger using the wtx target
19438 connection, the load never finishes, why?
19439
19440 Make sure that the memory cache size parameter of the target server is
19441 large enough. (@code{target -m big_enough_size}, or Memory cache size box in GUI.)
19442 See @cite{Tornado 1.01 API Programming Guide}, Section 3.6.2.
19443
19444 @item
19445 When I spawn my program under the VxWorks shell, interactive input does
19446 not work, why?
19447
19448 Only programs directly launched from the shell can have interactive
19449 input. For a program spawned with the @code{sp} or @code{taskSpawn}
19450 command, you need to have file redirection for input:
19451 @smallexample
19452 ->    # here you can have interactive input
19453 -> main
19454 ->    # here you cannot
19455 -> sp main
19456 ->    # neither here
19457 -> taskSpawn("ess",100,0,8000000,main)
19458 ->    # but you can input from a file:
19459 -> taskSpawn("Bae",100,0,8000000,main) < input_file
19460 @end smallexample
19461 @end itemize
19462
19463
19464 @node LynxOS Topics
19465 @chapter LynxOS Topics
19466 @noindent
19467 This chapter describes topics that are specific to the GNAT for LynxOS
19468 cross configurations.
19469
19470 @menu
19471 * Getting Started with GNAT on LynxOS::
19472 * Kernel Configuration for LynxOS::
19473 * Patch Level Issues for LynxOS::
19474 * Debugging Issues for LynxOS::
19475 * An Example Debugging Session for LynxOS::
19476 @end menu
19477
19478 @node Getting Started with GNAT on LynxOS
19479 @section Getting Started with GNAT on LynxOS
19480
19481 @noindent
19482 This section is a starting point for using GNAT to develop and
19483 execute Ada 95 programs for LynuxWorks' LynxOS target environment from a
19484 Unix host environment.
19485 We assume that you know how to use GNAT in a native environment
19486 and how to start a telnet or other login session to connect to your LynxOS board.
19487
19488 To compile code for a LynxOS system running on a PowerPC
19489 board, the basic compiler command is
19490 @command{powerpc-xcoff-lynxos-gcc}.
19491
19492 With GNAT, the easiest way to build the basic @code{Hello World} program is
19493 with @code{gnatmake}. For the LynxOS PowerPC target this would look
19494 like:
19495
19496 @smallexample
19497 $ powerpc-xcoff-lynxos-gnatmake hello
19498 @i{powerpc-xcoff-lynxos-gcc -c hello.adb
19499 powerpc-xcoff-lynxos-gnatbind -x hello.ali
19500 powerpc-xcoff-lynxos-gnatlink hello.ali}
19501 @end smallexample
19502
19503 @noindent
19504 (The first line is the command entered by the user -- the subseqent three
19505 are the programs run by @code{gnatmake}.)
19506
19507 This creates the executable @command{hello}" which you then need to load on the
19508 board (using ftp or an NFS directory for example) to run it.
19509
19510
19511 @node Kernel Configuration for LynxOS
19512 @section Kernel Configuration for LynxOS
19513
19514 @noindent
19515 The appropriate configuration for your LynxOS kernel depends
19516 on the target system and the requirements of your application. GNAT itself
19517 adds no additional demands; however in some situations it may be appropriate
19518 to increase the conservative
19519 resource assumptions made by the default configuration.
19520
19521 Kernel parameters limiting the maximum number of file descriptors,
19522 kernel and user threads, synchronization objects, etc., may be set in the
19523 file @file{uparam.h}. You may also wish to modify the file
19524 @file{/etc/starttab}, which places limits on data, stack, and core file
19525 size. See the documentation provided by LynuxWorks for more information.
19526
19527
19528 @node Patch Level Issues for LynxOS
19529 @section Patch Level Issues for LynxOS
19530
19531 @noindent
19532 The GNAT runtime requires that your system run at patch level 040 or
19533 later. Please see the file @file{PatchCompatibility.txt} from the
19534 distribution for more information.
19535
19536
19537 @node Debugging Issues for LynxOS
19538 @section Debugging Issues for LynxOS
19539
19540 @noindent
19541 GNAT's debugger is based on the same GNU gdb technology as the debugger
19542 provided by LynxOS, though with a great number of extensions and
19543 enhancements to support the Ada language and GNAT. The LynxOS
19544 documentation is relevant to understanding how to get the debugger
19545 started if you run into difficulties.
19546
19547 To demonstrate a debugging session, we will use a slightly more complex
19548 program called @file{demo1.adb}, which can be found in the @file{examples}
19549 directory of the GNAT distribution. This program is compiled with
19550 debugging information as follows:
19551
19552 @smallexample
19553 $ powerpc-xcoff-lynxos-gnatmake -g demo1
19554 powerpc-xcoff-lynxos-gcc -c -g demo1.adb
19555 powerpc-xcoff-lynxos-gcc -c -g gen_list.adb
19556 powerpc-xcoff-lynxos-gcc -c -g instr.adb
19557 powerpc-xcoff-lynxos-gnatbind -x demo1.ali
19558 powerpc-xcoff-lynxos-gnatlink -g demo1.ali
19559 @end smallexample
19560
19561 @noindent
19562 Once the executable is created, copy it to your working directory on the
19563 board. In this directory, you will have to launch the gdb server and
19564 choose a free port number on your TCP/IP socket. Presuming the Internet
19565 hostname of the board is @file{myboard} and the port chosen is 2345,
19566 issue the following command:
19567
19568 @smallexample
19569 myboard> gdbserver myboard:2345 demo1
19570 @end smallexample
19571
19572 @noindent
19573 Then return to your host environment.
19574
19575 The graphical debugger interface, @command{gvd}, supports both native
19576 and cross environments at the same time. @command{gvd} can be launched from
19577 @command{Glide} (see @file{README.Glide} for more information on customizing
19578 @command{Glide} for LynxOS) or it can be launched from the command line as
19579 follows:
19580
19581 @smallexample
19582 $ gvd --debugger powerpc-xcoff-lynxos-gdb
19583 @end smallexample
19584
19585 @noindent
19586 Then to attach to the target, enter in @command{gvd}'s command line window:
19587
19588 @smallexample
19589 (gdb) target remote myboard:2345
19590 @end smallexample
19591
19592 @noindent
19593 For more information see the GVD documentation.
19594
19595 The comments below concern debugging directly from the command line but
19596 they also apply to @command{gvd}, though in most cases an equivalent
19597 graphical command is also available.
19598
19599 To run the cross debugger from the command line without the visual
19600 interface use the command @code{powerpc-xcoff-lynxos-gdb}.
19601
19602 You will see something like:
19603
19604 @smallexample
19605 GNU gdb 4.17.gnat.3.14a1
19606 Copyright 1998 Free Software Foundation, Inc.
19607 GDB is free software, covered by the GNU General Public License, and you are
19608 welcome to change it and/or distribute copies of it under certain conditions.
19609 Type "show copying" to see the conditions.
19610 There is absolutely no warranty for GDB.  Type "show warranty" for details.
19611 This GDB was configured as "--host=sparc-sun-solaris2.5.1 --target=powerpc-xc
19612 off-lynxos".
19613 (gdb)
19614 @end smallexample
19615
19616 @noindent
19617 Where @command{(gdb)} is the debugger's prompt. The first thing to do at the
19618 prompt from within @command{gdb} is to load the symbol table from the
19619 executable:
19620
19621 @smallexample
19622 (gdb) file demo1
19623 Reading symbols from demo1...done.
19624 (gdb)
19625 @end smallexample
19626
19627 @noindent
19628 You then have to attach to the server running on the board. Issue the command:
19629
19630 @smallexample
19631 (gdb) target remote myboard:2345
19632 @end smallexample
19633
19634 @noindent
19635 After the server has been started and attached from the host, the program is
19636 running on the target but has halted execution at the very beginning.
19637 The following commands set a breakpoint and continue execution:
19638
19639 @smallexample
19640 (gdb) break demo1.adb:37
19641 Breakpoint 1 at 0x100064d0: file demo1.adb, line 37.
19642 (gdb) cont
19643 Continuing.
19644
19645 Breakpoint 1, demo1 () at demo1.adb:37
19646 37         Set_Name (Fuel, "Fuel");
19647 (gdb)
19648 @end smallexample
19649
19650 @noindent
19651 Here the execution has stopped at the breakpoint set above. Now
19652 you can use the standard @code{gdb} commands to examine the stack and
19653 program variables.
19654
19655 Note that once execution has completed, the server on the board must be
19656 restarted before a new debugging session may begin.
19657
19658 @node An Example Debugging Session for LynxOS
19659 @section An Example Debugging Session for LynxOS
19660
19661 @noindent
19662 Carrying on a little further with the debugging session, the following
19663 example illustrates some of the usual debugging commands for moving
19664 around and seeing where you are:
19665
19666 @smallexample
19667 (gdb) next
19668 38         Set_Name (Water, "Water");
19669 (gdb) bt
19670 #0  demo1 () at demo1.adb:38
19671 #1  0x10001218 in main (argc=1, argv=2147483640, envp=2147483520) at
19672 b~demo1.adb:118
19673 #2  0x10017538 in runmainthread ()
19674 #3  0x10001048 in __start ()
19675 (gdb) up
19676 #1  0x10001218 in main (argc=1, argv=2147483640, envp=2147483520) at
19677 b~demo1.adb:118
19678 118       Ada_Main_Program;
19679 (gdb) down
19680 #0  demo1 () at demo1.adb:38
19681 38         Set_Name (Water, "Water");
19682 (gdb)
19683 @end smallexample
19684
19685 @noindent
19686 To examine and modify variables (of a tagged type here):
19687
19688 @smallexample
19689 (gdb) print speed
19690 $1 = (name => "Speed         ", value => -286331154)
19691 (gdb) ptype speed
19692 type = new instr.instrument with record
19693     value: instr.speed;
19694 end record
19695 (gdb) speed.value := 3
19696 $2 = 3
19697 (gdb) print speed
19698 $3 = (name => "Speed         ", value => 3)
19699 (gdb) info local
19700 speed = (name => "Speed         ", value => 3)
19701 fuel = (name => "Fuel          ", value => -286331154)
19702 oil = (name => ' ' <repeats 14 times>, value => -286331154, size => 20,
19703   fill => 42 '*', empty => 46 '.')
19704 water = (name => ' ' <repeats 14 times>, value => -286331154, size => 20,
19705   fill => 42 '*', empty => 46 '.')
19706 time = (name => ' ' <repeats 14 times>, seconds => 0, minutes => 0, hours =>
19707 0)
19708 chrono = (name => ' ' <repeats 14 times>, seconds => 0, minutes => 0,
19709   hours => 0)
19710 db = (access demo1.dash_board.internal) 0x0
19711 (gdb)
19712 @end smallexample
19713
19714 @noindent
19715 And finally letting the program it run to completion:
19716
19717 @smallexample
19718 (gdb) c
19719 Continuing.
19720
19721 Program exited normally.
19722 (gdb)
19723 @end smallexample
19724
19725
19726 @node Performance Considerations
19727 @chapter Performance Considerations
19728 @cindex Performance
19729
19730 @noindent
19731 The GNAT system provides a number of options that allow a trade-off
19732 between
19733
19734 @itemize @bullet
19735 @item
19736 performance of the generated code
19737
19738 @item
19739 speed of compilation
19740
19741 @item
19742 minimization of dependences and recompilation
19743
19744 @item
19745 the degree of run-time checking.
19746 @end itemize
19747
19748 @noindent
19749 The defaults (if no options are selected) aim at improving the speed
19750 of compilation and minimizing dependences, at the expense of performance
19751 of the generated code:
19752
19753 @itemize @bullet
19754 @item
19755 no optimization
19756
19757 @item
19758 no inlining of subprogram calls
19759
19760 @item
19761 all run-time checks enabled except overflow and elaboration checks
19762 @end itemize
19763
19764 @noindent
19765 These options are suitable for most program development purposes. This
19766 chapter describes how you can modify these choices, and also provides
19767 some guidelines on debugging optimized code.
19768
19769 @menu
19770 * Controlling Run-Time Checks::
19771 * Optimization Levels::
19772 * Debugging Optimized Code::
19773 * Inlining of Subprograms::
19774 @end menu
19775
19776 @node Controlling Run-Time Checks
19777 @section Controlling Run-Time Checks
19778
19779 @noindent
19780 By default, GNAT generates all run-time checks, except arithmetic overflow
19781 checking for integer operations and checks for access before elaboration on
19782 subprogram calls. The latter are not required in default mode, because all
19783 necessary checking is done at compile time.
19784 @cindex @option{-gnatp} (@code{gcc})
19785 @cindex @option{-gnato} (@code{gcc})
19786 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
19787 be modified. @xref{Run-Time Checks}.
19788
19789 Our experience is that the default is suitable for most development
19790 purposes.
19791
19792 We treat integer overflow specially because these
19793 are quite expensive and in our experience are not as important as other
19794 run-time checks in the development process. Note that division by zero
19795 is not considered an overflow check, and divide by zero checks are
19796 generated where required by default.
19797
19798 Elaboration checks are off by default, and also not needed by default, since
19799 GNAT uses a static elaboration analysis approach that avoids the need for
19800 run-time checking. This manual contains a full chapter discussing the issue
19801 of elaboration checks, and if the default is not satisfactory for your use,
19802 you should read this chapter.
19803
19804 For validity checks, the minimal checks required by the Ada Reference
19805 Manual (for case statements and assignments to array elements) are on
19806 by default. These can be suppressed by use of the @option{-gnatVn} switch.
19807 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
19808 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
19809 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
19810 are also suppressed entirely if @option{-gnatp} is used.
19811
19812 @cindex Overflow checks
19813 @cindex Checks, overflow
19814 @findex Suppress
19815 @findex Unsuppress
19816 @cindex pragma Suppress
19817 @cindex pragma Unsuppress
19818 Note that the setting of the switches controls the default setting of
19819 the checks. They may be modified using either @code{pragma Suppress} (to
19820 remove checks) or @code{pragma Unsuppress} (to add back suppressed
19821 checks) in the program source.
19822
19823 @node Optimization Levels
19824 @section Optimization Levels
19825 @cindex @code{-O} (@code{gcc})
19826
19827 @noindent
19828 The default is optimization off. This results in the fastest compile
19829 times, but GNAT makes absolutely no attempt to optimize, and the
19830 generated programs are considerably larger and slower than when
19831 optimization is enabled. You can use the
19832 @code{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
19833 on the @code{gcc} command line to control the optimization level:
19834
19835 @table @code
19836 @item -O0
19837 no optimization (the default)
19838
19839 @item -O1
19840 medium level optimization
19841
19842 @item -O2
19843 full optimization
19844
19845 @item -O3
19846 full optimization, and also attempt automatic inlining of small
19847 subprograms within a unit (@pxref{Inlining of Subprograms}).
19848 @end table
19849
19850 Higher optimization levels perform more global transformations on the
19851 program and apply more expensive analysis algorithms in order to generate
19852 faster and more compact code. The price in compilation time, and the
19853 resulting improvement in execution time,
19854 both depend on the particular application and the hardware environment.
19855 You should experiment to find the best level for your application.
19856
19857 Note: Unlike some other compilation systems, @code{gcc} has
19858 been tested extensively at all optimization levels. There are some bugs
19859 which appear only with optimization turned on, but there have also been
19860 bugs which show up only in @emph{unoptimized} code. Selecting a lower
19861 level of optimization does not improve the reliability of the code
19862 generator, which in practice is highly reliable at all optimization
19863 levels.
19864
19865 Note regarding the use of @code{-O3}: The use of this optimization level
19866 is generally discouraged with GNAT, since it often results in larger
19867 executables which run more slowly. See further discussion of this point
19868 in @pxref{Inlining of Subprograms}.
19869
19870 @node Debugging Optimized Code
19871 @section Debugging Optimized Code
19872
19873 @noindent
19874 Since the compiler generates debugging tables for a compilation unit before
19875 it performs optimizations, the optimizing transformations may invalidate some
19876 of the debugging data.  You therefore need to anticipate certain
19877 anomalous situations that may arise while debugging optimized code.  This
19878 section describes the most common cases.
19879
19880 @enumerate
19881 @item
19882 @i{The "hopping Program Counter":}  Repeated 'step' or 'next' commands show the PC
19883 bouncing back and forth in the code.  This may result from any of the following
19884 optimizations:
19885
19886 @itemize @bullet
19887 @item
19888 @i{Common subexpression elimination:} using a single instance of code for a
19889 quantity that the source computes several times.  As a result you
19890 may not be able to stop on what looks like a statement.
19891
19892 @item
19893 @i{Invariant code motion:} moving an expression that does not change within a
19894 loop, to the beginning of the loop.
19895
19896 @item
19897 @i{Instruction scheduling:} moving instructions so as to
19898 overlap loads and stores (typically) with other code, or in
19899 general to move computations of values closer to their uses. Often
19900 this causes you to pass an assignment statement without the assignment
19901 happening and then later bounce back to the statement when the
19902 value is actually needed.  Placing a breakpoint on a line of code
19903 and then stepping over it may, therefore, not always cause all the
19904 expected side-effects.
19905 @end itemize
19906
19907 @item
19908 @i{The "big leap":} More commonly known as @i{cross-jumping}, in which two
19909 identical pieces of code are merged and the program counter suddenly
19910 jumps to a statement that is not supposed to be executed, simply because
19911 it (and the code following) translates to the same thing as the code
19912 that @emph{was} supposed to be executed.  This effect is typically seen in
19913 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
19914 a @code{break} in a C @code{switch} statement.
19915
19916 @item
19917 @i{The "roving variable":} The symptom is an unexpected value in a variable.
19918 There are various reasons for this effect:
19919
19920 @itemize @bullet
19921 @item
19922 In a subprogram prologue, a parameter may not yet have been moved to its
19923 "home".
19924
19925 @item
19926 A variable may be dead, and its register re-used.  This is
19927 probably the most common cause.
19928
19929 @item
19930 As mentioned above, the assignment of a value to a variable may
19931 have been moved.
19932
19933 @item
19934 A variable may be eliminated entirely by value propagation or
19935 other means.  In this case, GCC may incorrectly generate debugging
19936 information for the variable
19937 @end itemize
19938
19939 @noindent
19940 In general, when an unexpected value appears for a local variable or parameter
19941 you should first ascertain if that value was actually computed by
19942 your program, as opposed to being incorrectly reported by the debugger.
19943 Record fields or
19944 array elements in an object designated by an access value
19945 are generally less of a problem, once you have ascertained that the access value
19946 is sensible.
19947 Typically, this means checking variables in the preceding code and in the
19948 calling subprogram to verify that the value observed is explainable from other
19949 values (one must apply the procedure recursively to those
19950 other values); or re-running the code and stopping a little earlier
19951 (perhaps before the call) and stepping to better see how the variable obtained
19952 the value in question; or continuing to step @emph{from} the point of the
19953 strange value to see if code motion had simply moved the variable's
19954 assignments later.
19955 @end enumerate
19956
19957 @node Inlining of Subprograms
19958 @section Inlining of Subprograms
19959
19960 @noindent
19961 A call to a subprogram in the current unit is inlined if all the
19962 following conditions are met:
19963
19964 @itemize @bullet
19965 @item
19966 The optimization level is at least @code{-O1}.
19967
19968 @item
19969 The called subprogram is suitable for inlining: It must be small enough
19970 and not contain nested subprograms or anything else that @code{gcc}
19971 cannot support in inlined subprograms.
19972
19973 @item
19974 The call occurs after the definition of the body of the subprogram.
19975
19976 @item
19977 @cindex pragma Inline
19978 @findex Inline
19979 Either @code{pragma Inline} applies to the subprogram or it is
19980 small and automatic inlining (optimization level @code{-O3}) is
19981 specified.
19982 @end itemize
19983
19984 @noindent
19985 Calls to subprograms in @code{with}'ed units are normally not inlined.
19986 To achieve this level of inlining, the following conditions must all be
19987 true:
19988
19989 @itemize @bullet
19990 @item
19991 The optimization level is at least @code{-O1}.
19992
19993 @item
19994 The called subprogram is suitable for inlining: It must be small enough
19995 and not contain nested subprograms or anything else @code{gcc} cannot
19996 support in inlined subprograms.
19997
19998 @item
19999 The call appears in a body (not in a package spec).
20000
20001 @item
20002 There is a @code{pragma Inline} for the subprogram.
20003
20004 @item
20005 @cindex @option{-gnatn} (@code{gcc})
20006 The @code{-gnatn} switch
20007 is used in the @code{gcc} command line
20008 @end itemize
20009
20010 Note that specifying the @option{-gnatn} switch causes additional
20011 compilation dependencies. Consider the following:
20012
20013 @smallexample
20014 @group
20015 @cartouche
20016 @b{package} R @b{is}
20017    @b{procedure} Q;
20018    @b{pragma} Inline (Q);
20019 @b{end} R;
20020 @b{package body} R @b{is}
20021    ...
20022 @b{end} R;
20023
20024 @b{with} R;
20025 @b{procedure} Main @b{is}
20026 @b{begin}
20027    ...
20028    R.Q;
20029 @b{end} Main;
20030 @end cartouche
20031 @end group
20032 @end smallexample
20033
20034 @noindent
20035 With the default behavior (no @option{-gnatn} switch specified), the
20036 compilation of the @code{Main} procedure depends only on its own source,
20037 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
20038 means that editing the body of @code{R} does not require recompiling
20039 @code{Main}.
20040
20041 On the other hand, the call @code{R.Q} is not inlined under these
20042 circumstances. If the @option{-gnatn} switch is present when @code{Main}
20043 is compiled, the call will be inlined if the body of @code{Q} is small
20044 enough, but now @code{Main} depends on the body of @code{R} in
20045 @file{r.adb} as well as on the spec. This means that if this body is edited,
20046 the main program must be recompiled. Note that this extra dependency
20047 occurs whether or not the call is in fact inlined by @code{gcc}.
20048
20049 The use of front end inlining with @option{-gnatN} generates similar
20050 additional dependencies.
20051
20052 @cindex @code{-fno-inline} (@code{gcc})
20053 Note: The @code{-fno-inline} switch
20054 can be used to prevent
20055 all inlining. This switch overrides all other conditions and ensures
20056 that no inlining occurs. The extra dependences resulting from
20057 @option{-gnatn} will still be active, even if
20058 this switch is used to suppress the resulting inlining actions.
20059
20060 Note regarding the use of @code{-O3}: There is no difference in inlining
20061 behavior between @code{-O2} and @code{-O3} for subprograms with an explicit
20062 pragma @code{Inline} assuming the use of @option{-gnatn}
20063 or @option{-gnatN} (the switches that activate inlining). If you have used
20064 pragma @code{Inline} in appropriate cases, then it is usually much better
20065 to use @code{-O2} and @option{-gnatn} and avoid the use of @code{-O3} which
20066 in this case only has the effect of inlining subprograms you did not
20067 think should be inlined. We often find that the use of @code{-O3} slows
20068 down code by performing excessive inlining, leading to increased instruction
20069 cache pressure from the increased code size. So the bottom line here is
20070 that you should not automatically assume that @code{-O3} is better than
20071 @code{-O2}, and indeed you should use @code{-O3} only if tests show that
20072 it actually improves performance.
20073
20074
20075 @include fdl.texi
20076 @c GNU Free Documentation License
20077
20078 @node Index,,GNU Free Documentation License, Top
20079 @unnumbered Index
20080
20081 @printindex cp
20082
20083 @contents
20084
20085 @bye