OSDN Git Service

* gnat_ugn.texi: Correct argument to @setfilename.
[pf3gnuchains/gcc-fork.git] / gcc / ada / gnat_ugn.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 N                                o
9 @c                                                                            o
10 @c          Copyright (C) 1992-2004 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_UGN 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     a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
44 @c        context.  These can interfere with the readability of the texi
45 @c        source file.  Instead, use one of the following annotated
46 @c        @smallexample commands, and preprocess the texi file with the
47 @c        ada2texi tool (which generates appropriate highlighting):
48 @c        @smallexample @c ada
49 @c        @smallexample @c adanocomment
50 @c        @smallexample @c projectfile
51 @c     b) The "@c ada" markup will result in boldface for reserved words
52 @c        and italics for comments
53 @c     c) The "@c adanocomment" markup will result only in boldface for
54 @c        reserved words (comments are left alone)
55 @c     d) The "@c projectfile" markup is like "@c ada" except that the set
56 @c        of reserved words include the new reserved words for project files
57 @c
58 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
59 @c     command must be preceded by two empty lines
60 @c
61 @c  4. The @item command should be on a line of its own if it is in an
62 @c     @itemize or @enumerate command.
63 @c
64 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
65 @c     or "ali".
66 @c
67 @c  6. DO NOT put trailing spaces at the end of a line.  Such spaces will
68 @c     cause the document build to fail.
69 @c
70 @c  7. DO NOT use @cartouche for examples that are longer than around 10 lines.
71 @c     This command inhibits page breaks, so long examples in a @cartouche can
72 @c     lead to large, ugly patches of empty space on a page.
73 @c
74 @c  NOTE: This file should be submitted to xgnatugn with either the vms flag
75 @c        or the unw flag set.  The unw flag covers topics for both Unix and
76 @c        Windows.
77 @c
78 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
79
80 @ifset vms
81 @setfilename gnat_ugn_vms.info
82 @end ifset
83
84 @ifset unw
85 @setfilename gnat_ugn_unw.info
86 @end ifset
87
88 @ifset vms
89 @settitle GNAT User's Guide for Native Platforms / OpenVMS Alpha
90 @dircategory GNU Ada tools
91 @direntry
92 * GNAT User's Guide (gnat_ugn_vms) for Native Platforms / OpenVMS Alpha
93 @end direntry
94 @end ifset
95
96 @ifset unw
97 @settitle GNAT User's Guide for Native Platforms / Unix and Windows
98 @direntry
99 * GNAT User's Guide (gnat_ugn_unw) for Native Platforms / Unix and Windows
100 @end direntry
101 @end ifset
102
103 @include gcc-common.texi
104
105 @setchapternewpage odd
106 @syncodeindex fn cp
107 @c %**end of header
108
109 @copying
110 Copyright @copyright{} 1995-2004, Free Software Foundation
111
112 Permission is granted to copy, distribute and/or modify this document
113 under the terms of the GNU Free Documentation License, Version 1.2
114 or any later version published by the Free Software Foundation;
115 with the Invariant Sections being ``GNU Free Documentation License'', with the
116 Front-Cover Texts being
117 @ifset vms
118 ``GNAT User's Guide for Native Platforms / OpenVMS Alpha'',
119 @end ifset
120 @ifset unw
121 ``GNAT User's Guide for Native Platforms / Unix and Windows'',
122 @end ifset
123 and with no Back-Cover Texts.
124 A copy of the license is included in the section entitled
125 ``GNU Free Documentation License''.
126 @end copying
127
128 @titlepage
129
130 @title GNAT User's Guide
131 @center @titlefont{for Native Platforms}
132 @sp 1
133
134 @flushright
135 @ifset unw
136 @titlefont{@i{Unix and Windows}}
137 @end ifset
138 @ifset vms
139 @titlefont{@i{OpenVMS Alpha}}
140 @end ifset
141 @end flushright
142 @sp 2
143
144 @subtitle GNAT, The GNU Ada 95 Compiler
145 @subtitle GCC version @value{version-GCC}
146
147 @author Ada Core Technologies, Inc.
148
149 @page
150 @vskip 0pt plus 1filll
151
152 @insertcopying
153
154 @end titlepage
155
156
157 @ifnottex
158 @node Top, About This Guide, (dir), (dir)
159 @top GNAT User's Guide
160
161 @ifset vms
162 @noindent
163 GNAT User's Guide for Native Platforms / OpenVMS Alpha
164 @end ifset
165
166 @ifset unw
167 @noindent
168 GNAT User's Guide for Native Platforms / Unix and Windows
169 @end ifset
170
171 @noindent
172 GNAT, The GNU Ada 95 Compiler@*
173 GCC version @value{version-GCC}@*
174
175 @noindent
176 Ada Core Technologies, Inc.@*
177
178 @menu
179 * About This Guide::
180 * Getting Started with GNAT::
181 * The GNAT Compilation Model::
182 * Compiling Using gcc::
183 * Binding Using gnatbind::
184 * Linking Using gnatlink::
185 * The GNAT Make Program gnatmake::
186 * Improving Performance::
187 * Renaming Files Using gnatchop::
188 * Configuration Pragmas::
189 * Handling Arbitrary File Naming Conventions Using gnatname::
190 * GNAT Project Manager::
191 * The Cross-Referencing Tools gnatxref and gnatfind::
192 * The GNAT Pretty-Printer gnatpp::
193 * File Name Krunching Using gnatkr::
194 * Preprocessing Using gnatprep::
195 @ifset vms
196 * The GNAT Run-Time Library Builder gnatlbr::
197 @end ifset
198 * The GNAT Library Browser gnatls::
199 * Cleaning Up Using gnatclean::
200 @ifclear vms
201 * GNAT and Libraries::
202 * Using the GNU make Utility::
203 @end ifclear
204 * Finding Memory Problems::
205 * Creating Sample Bodies Using gnatstub::
206 * Other Utility Programs::
207 * Running and Debugging Ada Programs::
208 @ifset vms
209 * Compatibility with DEC Ada::
210 @end ifset
211 * Platform-Specific Information for the Run-Time Libraries::
212 * Example of Binder Output File::
213 * Elaboration Order Handling in GNAT::
214 * Inline Assembler::
215 * Compatibility and Porting Guide::
216 @ifset unw
217 * Microsoft Windows Topics::
218 @end ifset
219 * GNU Free Documentation License::
220 * Index::
221
222  --- The Detailed Node Listing ---
223
224 About This Guide
225
226 * What This Guide Contains::
227 * What You Should Know before Reading This Guide::
228 * Related Information::
229 * Conventions::
230
231 Getting Started with GNAT
232
233 * Running GNAT::
234 * Running a Simple Ada Program::
235 * Running a Program with Multiple Units::
236 * Using the gnatmake Utility::
237 @ifset vms
238 * Editing with Emacs::
239 @end ifset
240 @ifclear vms
241 * Introduction to GPS::
242 * Introduction to Glide and GVD::
243 @end ifclear
244
245 The GNAT Compilation Model
246
247 * Source Representation::
248 * Foreign Language Representation::
249 * File Naming Rules::
250 * Using Other File Names::
251 * Alternative File Naming Schemes::
252 * Generating Object Files::
253 * Source Dependencies::
254 * The Ada Library Information Files::
255 * Binding an Ada Program::
256 * Mixed Language Programming::
257 * Building Mixed Ada & C++ Programs::
258 * Comparison between GNAT and C/C++ Compilation Models::
259 * Comparison between GNAT and Conventional Ada Library Models::
260 @ifset vms
261 * Placement of temporary files::
262 @end ifset
263
264 Foreign Language Representation
265
266 * Latin-1::
267 * Other 8-Bit Codes::
268 * Wide Character Encodings::
269
270 Compiling Ada Programs With gcc
271
272 * Compiling Programs::
273 * Switches for gcc::
274 * Search Paths and the Run-Time Library (RTL)::
275 * Order of Compilation Issues::
276 * Examples::
277
278 Switches for gcc
279
280 * Output and Error Message Control::
281 * Warning Message Control::
282 * Debugging and Assertion Control::
283 * Run-Time Checks::
284 * Stack Overflow Checking::
285 * Validity Checking::
286 * Style Checking::
287 * Using gcc for Syntax Checking::
288 * Using gcc for Semantic Checking::
289 * Compiling Ada 83 Programs::
290 * Character Set Control::
291 * File Naming Control::
292 * Subprogram Inlining Control::
293 * Auxiliary Output Control::
294 * Debugging Control::
295 * Exception Handling Control::
296 * Units to Sources Mapping Files::
297 * Integrated Preprocessing::
298 @ifset vms
299 * Return Codes::
300 @end ifset
301
302 Binding Ada Programs With gnatbind
303
304 * Running gnatbind::
305 * Switches for gnatbind::
306 * Command-Line Access::
307 * Search Paths for gnatbind::
308 * Examples of gnatbind Usage::
309
310 Switches for gnatbind
311
312 * Consistency-Checking Modes::
313 * Binder Error Message Control::
314 * Elaboration Control::
315 * Output Control::
316 * Binding with Non-Ada Main Programs::
317 * Binding Programs with No Main Subprogram::
318
319 Linking Using gnatlink
320
321 * Running gnatlink::
322 * Switches for gnatlink::
323 * Setting Stack Size from gnatlink::
324 * Setting Heap Size from gnatlink::
325
326 The GNAT Make Program gnatmake
327
328 * Running gnatmake::
329 * Switches for gnatmake::
330 * Mode Switches for gnatmake::
331 * Notes on the Command Line::
332 * How gnatmake Works::
333 * Examples of gnatmake Usage::
334
335
336 Improving Performance
337 * Performance Considerations::
338 * Reducing the Size of Ada Executables with gnatelim::
339
340 Performance Considerations
341 * Controlling Run-Time Checks::
342 * Use of Restrictions::
343 * Optimization Levels::
344 * Debugging Optimized Code::
345 * Inlining of Subprograms::
346 * Optimization and Strict Aliasing::
347 @ifset vms
348 * Coverage Analysis::
349 @end ifset
350
351 Reducing the Size of Ada Executables with gnatelim
352 * About gnatelim::
353 * Running gnatelim::
354 * Correcting the List of Eliminate Pragmas::
355 * Making Your Executables Smaller::
356 * Summary of the gnatelim Usage Cycle::
357
358 Renaming Files Using gnatchop
359
360 * Handling Files with Multiple Units::
361 * Operating gnatchop in Compilation Mode::
362 * Command Line for gnatchop::
363 * Switches for gnatchop::
364 * Examples of gnatchop Usage::
365
366 Configuration Pragmas
367
368 * Handling of Configuration Pragmas::
369 * The Configuration Pragmas Files::
370
371 Handling Arbitrary File Naming Conventions Using gnatname
372
373 * Arbitrary File Naming Conventions::
374 * Running gnatname::
375 * Switches for gnatname::
376 * Examples of gnatname Usage::
377
378 GNAT Project Manager
379
380 * Introduction::
381 * Examples of Project Files::
382 * Project File Syntax::
383 * Objects and Sources in Project Files::
384 * Importing Projects::
385 * Project Extension::
386 * External References in Project Files::
387 * Packages in Project Files::
388 * Variables from Imported Projects::
389 * Naming Schemes::
390 * Library Projects::
391 * Using Third-Party Libraries through Projects::
392 * Stand-alone Library Projects::
393 * Switches Related to Project Files::
394 * Tools Supporting Project Files::
395 * An Extended Example::
396 * Project File Complete Syntax::
397
398
399 The Cross-Referencing Tools gnatxref and gnatfind
400
401 * gnatxref Switches::
402 * gnatfind Switches::
403 * Project Files for gnatxref and gnatfind::
404 * Regular Expressions in gnatfind and gnatxref::
405 * Examples of gnatxref Usage::
406 * Examples of gnatfind Usage::
407
408
409 The GNAT Pretty-Printer gnatpp
410
411 * Switches for gnatpp::
412 * Formatting Rules::
413
414
415 File Name Krunching Using gnatkr
416
417 * About gnatkr::
418 * Using gnatkr::
419 * Krunching Method::
420 * Examples of gnatkr Usage::
421
422 Preprocessing Using gnatprep
423
424 * Using gnatprep::
425 * Switches for gnatprep::
426 * Form of Definitions File::
427 * Form of Input Text for gnatprep::
428
429 @ifset vms
430 The GNAT Run-Time Library Builder gnatlbr
431
432 * Running gnatlbr::
433 * Switches for gnatlbr::
434 * Examples of gnatlbr Usage::
435 @end ifset
436
437 The GNAT Library Browser gnatls
438
439 * Running gnatls::
440 * Switches for gnatls::
441 * Examples of gnatls Usage::
442
443 Cleaning Up Using gnatclean
444
445 * Running gnatclean::
446 * Switches for gnatclean::
447 * Examples of gnatclean Usage::
448
449 @ifclear vms
450
451 GNAT and Libraries
452
453 * Creating an Ada Library::
454 * Installing an Ada Library::
455 * Using an Ada Library::
456 * Creating an Ada Library to be Used in a Non-Ada Context::
457 * Rebuilding the GNAT Run-Time Library::
458
459 Using the GNU make Utility
460
461 * Using gnatmake in a Makefile::
462 * Automatically Creating a List of Directories::
463 * Generating the Command Line Switches::
464 * Overcoming Command Line Length Limits::
465 @end ifclear
466
467 Finding Memory Problems
468
469 @ifclear vms
470 * The gnatmem Tool::
471 @end ifclear
472 * The GNAT Debug Pool Facility::
473
474 @ifclear vms
475 The gnatmem Tool
476
477 * Running gnatmem::
478 * Switches for gnatmem::
479 * Example of gnatmem Usage::
480 @end ifclear
481
482 The GNAT Debug Pool Facility
483
484 Creating Sample Bodies Using gnatstub
485
486 * Running gnatstub::
487 * Switches for gnatstub::
488
489 Other Utility Programs
490
491 * Using Other Utility Programs with GNAT::
492 * The External Symbol Naming Scheme of GNAT::
493 @ifclear vms
494 * Ada Mode for Glide::
495 @end ifclear
496 * Converting Ada Files to html with gnathtml::
497
498 Running and Debugging Ada Programs
499
500 * The GNAT Debugger GDB::
501 * Running GDB::
502 * Introduction to GDB Commands::
503 * Using Ada Expressions::
504 * Calling User-Defined Subprograms::
505 * Using the Next Command in a Function::
506 * Ada Exceptions::
507 * Ada Tasks::
508 * Debugging Generic Units::
509 * GNAT Abnormal Termination or Failure to Terminate::
510 * Naming Conventions for GNAT Source Files::
511 * Getting Internal Debugging Information::
512 * Stack Traceback::
513
514 @ifset vms
515 * LSE::
516 @end ifset
517
518 @ifset vms
519 Compatibility with DEC Ada
520
521 * Ada 95 Compatibility::
522 * Differences in the Definition of Package System::
523 * Language-Related Features::
524 * The Package STANDARD::
525 * The Package SYSTEM::
526 * Tasking and Task-Related Features::
527 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
528 * Pragmas and Pragma-Related Features::
529 * Library of Predefined Units::
530 * Bindings::
531 * Main Program Definition::
532 * Implementation-Defined Attributes::
533 * Compiler and Run-Time Interfacing::
534 * Program Compilation and Library Management::
535 * Input-Output::
536 * Implementation Limits::
537 * Tools::
538
539 Language-Related Features
540
541 * Integer Types and Representations::
542 * Floating-Point Types and Representations::
543 * Pragmas Float_Representation and Long_Float::
544 * Fixed-Point Types and Representations::
545 * Record and Array Component Alignment::
546 * Address Clauses::
547 * Other Representation Clauses::
548
549 Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
550
551 * Assigning Task IDs::
552 * Task IDs and Delays::
553 * Task-Related Pragmas::
554 * Scheduling and Task Priority::
555 * The Task Stack::
556 * External Interrupts::
557
558 Pragmas and Pragma-Related Features
559
560 * Restrictions on the Pragma INLINE::
561 * Restrictions on the Pragma INTERFACE::
562 * Restrictions on the Pragma SYSTEM_NAME::
563
564 Library of Predefined Units
565
566 * Changes to DECLIB::
567
568 Bindings
569
570 * Shared Libraries and Options Files::
571 * Interfaces to C::
572 @end ifset
573
574 Platform-Specific Information for the Run-Time Libraries
575
576 * Summary of Run-Time Configurations::
577 * Specifying a Run-Time Library::
578 * Choosing between Native and FSU Threads Libraries::
579 * Choosing the Scheduling Policy::
580 * Solaris-Specific Considerations::
581 * IRIX-Specific Considerations::
582 * Linux-Specific Considerations::
583
584 Example of Binder Output File
585
586 Elaboration Order Handling in GNAT
587
588 * Elaboration Code in Ada 95::
589 * Checking the Elaboration Order in Ada 95::
590 * Controlling the Elaboration Order in Ada 95::
591 * Controlling Elaboration in GNAT - Internal Calls::
592 * Controlling Elaboration in GNAT - External Calls::
593 * Default Behavior in GNAT - Ensuring Safety::
594 * Treatment of Pragma Elaborate::
595 * Elaboration Issues for Library Tasks::
596 * Mixing Elaboration Models::
597 * What to Do If the Default Elaboration Behavior Fails::
598 * Elaboration for Access-to-Subprogram Values::
599 * Summary of Procedures for Elaboration Control::
600 * Other Elaboration Order Considerations::
601
602 Inline Assembler
603
604 * Basic Assembler Syntax::
605 * A Simple Example of Inline Assembler::
606 * Output Variables in Inline Assembler::
607 * Input Variables in Inline Assembler::
608 * Inlining Inline Assembler Code::
609 * Other Asm Functionality::
610 * A Complete Example::
611
612 Compatibility and Porting Guide
613
614 * Compatibility with Ada 83::
615 * Implementation-dependent characteristics::
616 * Compatibility with DEC Ada 83::
617 * Compatibility with Other Ada 95 Systems::
618 * Representation Clauses::
619
620 @ifset unw
621 Microsoft Windows Topics
622
623 * Using GNAT on Windows::
624 * CONSOLE and WINDOWS subsystems::
625 * Temporary Files::
626 * Mixed-Language Programming on Windows::
627 * Windows Calling Conventions::
628 * Introduction to Dynamic Link Libraries (DLLs)::
629 * Using DLLs with GNAT::
630 * Building DLLs with GNAT::
631 * GNAT and Windows Resources::
632 * Debugging a DLL::
633 * GNAT and COM/DCOM Objects::
634 @end ifset
635
636
637 * Index::
638 @end menu
639 @end ifnottex
640
641 @node About This Guide
642 @unnumbered About This Guide
643
644 @noindent
645 @ifset vms
646 This guide describes the use of of GNAT, a full language compiler for the Ada
647 95 programming language, implemented on HP OpenVMS Alpha platforms.
648 @end ifset
649 @ifclear vms
650 This guide describes the use of GNAT, a compiler and software development
651 toolset for the full Ada 95 programming language.
652 @end ifclear
653 It describes the features of the compiler and tools, and details
654 how to use them to build Ada 95 applications.
655
656 @menu
657 * What This Guide Contains::
658 * What You Should Know before Reading This Guide::
659 * Related Information::
660 * Conventions::
661 @end menu
662
663 @node What This Guide Contains
664 @unnumberedsec What This Guide Contains
665
666 @noindent
667 This guide contains the following chapters:
668 @itemize @bullet
669
670 @item
671 @ref{Getting Started with GNAT}, describes how to get started compiling
672 and running Ada programs with the GNAT Ada programming environment.
673 @item
674 @ref{The GNAT Compilation Model}, describes the compilation model used
675 by GNAT.
676
677 @item
678 @ref{Compiling Using gcc}, describes how to compile
679 Ada programs with @code{gcc}, the Ada compiler.
680
681 @item
682 @ref{Binding Using gnatbind}, describes how to
683 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
684 utility.
685
686 @item
687 @ref{Linking Using gnatlink},
688 describes @code{gnatlink}, a
689 program that provides for linking using the GNAT run-time library to
690 construct a program. @code{gnatlink} can also incorporate foreign language
691 object units into the executable.
692
693 @item
694 @ref{The GNAT Make Program gnatmake}, describes @code{gnatmake}, a
695 utility that automatically determines the set of sources
696 needed by an Ada compilation unit, and executes the necessary compilations
697 binding and link.
698
699 @item
700 @ref{Improving Performance}, shows various techniques for making your
701 Ada program run faster or take less space.
702 It discusses the effect of the compiler's optimization switch and
703 also describes the @command{gnatelim} tool.
704
705 @item
706 @ref{Renaming Files Using gnatchop}, describes
707 @code{gnatchop}, a utility that allows you to preprocess a file that
708 contains Ada source code, and split it into one or more new files, one
709 for each compilation unit.
710
711 @item
712 @ref{Configuration Pragmas}, describes the configuration pragmas
713 handled by GNAT.
714
715 @item
716 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
717 shows how to override the default GNAT file naming conventions,
718 either for an individual unit or globally.
719
720 @item
721 @ref{GNAT Project Manager}, describes how to use project files
722 to organize large projects.
723
724 @item
725 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
726 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
727 way to navigate through sources.
728
729 @item
730 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
731 version of an Ada source file with control over casing, indentation,
732 comment placement, and other elements of program presentation style.
733
734
735 @item
736 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
737 file name krunching utility, used to handle shortened
738 file names on operating systems with a limit on the length of names.
739
740 @item
741 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
742 preprocessor utility that allows a single source file to be used to
743 generate multiple or parameterized source files, by means of macro
744 substitution.
745
746 @ifset vms
747 @item
748 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
749 a tool for rebuilding the GNAT run time with user-supplied
750 configuration pragmas.
751 @end ifset
752
753 @item
754 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
755 utility that displays information about compiled units, including dependences
756 on the corresponding sources files, and consistency of compilations.
757
758 @item
759 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
760 to delete files that are produced by the compiler, binder and linker.
761
762 @ifclear vms
763 @item
764 @ref{GNAT and Libraries}, describes the process of creating and using
765 Libraries with GNAT. It also describes how to recompile the GNAT run-time
766 library.
767
768 @item
769 @ref{Using the GNU make Utility}, describes some techniques for using
770 the GNAT toolset in Makefiles.
771 @end ifclear
772
773 @item
774 @ref{Finding Memory Problems}, describes
775 @ifclear vms
776 @command{gnatmem}, a utility that monitors dynamic allocation and deallocation
777 and helps detect ``memory leaks'', and
778 @end ifclear
779 the GNAT Debug Pool facility, which helps detect incorrect memory references.
780
781 @item
782 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
783 a utility that generates empty but compilable bodies for library units.
784
785 @item
786 @ref{Other Utility Programs}, discusses several other GNAT utilities,
787 including @code{gnathtml}.
788
789 @item
790 @ref{Running and Debugging Ada Programs}, describes how to run and debug
791 Ada programs.
792
793 @ifset vms
794 @item
795 @ref{Compatibility with DEC Ada}, details the compatibility of GNAT with
796 DEC Ada 83 @footnote{``DEC Ada'' refers to the legacy product originally
797 developed by Digital Equipment Corporation and currently supported by HP.}
798 for OpenVMS Alpha.
799 @end ifset
800
801 @item
802 @ref{Platform-Specific Information for the Run-Time Libraries},
803 describes the various run-time
804 libraries supported by GNAT on various platforms and explains how to
805 choose a particular library.
806
807 @item
808 @ref{Example of Binder Output File}, shows the source code for the binder
809 output file for a sample program.
810
811 @item
812 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
813 you deal with elaboration order issues.
814
815 @item
816 @ref{Inline Assembler}, shows how to use the inline assembly facility
817 in an Ada program.
818
819 @item
820 @ref{Compatibility and Porting Guide}, includes sections on compatibility
821 of GNAT with other Ada 83 and Ada 95 compilation systems, to assist
822 in porting code from other environments.
823
824 @ifset unw
825 @item
826 @ref{Microsoft Windows Topics}, presents information relevant to the
827 Microsoft Windows platform.
828 @end ifset
829 @end itemize
830
831
832 @c *************************************************
833 @node What You Should Know before Reading This Guide
834 @c *************************************************
835 @unnumberedsec What You Should Know before Reading This Guide
836
837 @cindex Ada 95 Language Reference Manual
838 @noindent
839 This user's guide assumes that you are familiar with Ada 95 language, as
840 described in the International Standard ANSI/ISO/IEC-8652:1995, January
841 1995.
842
843 @node Related Information
844 @unnumberedsec Related Information
845
846 @noindent
847 For further information about related tools, refer to the following
848 documents:
849
850 @itemize @bullet
851 @item
852 @cite{GNAT Reference Manual}, which contains all reference
853 material for the GNAT implementation of Ada 95.
854
855 @ifset unw
856 @item
857 @cite{Using the GNAT Programming System}, which describes the GPS
858 integrated development environment.
859
860 @item
861 @cite{GNAT Programming System Tutorial}, which introduces the
862 main GPS features through examples.
863 @end ifset
864
865 @item
866 @cite{Ada 95 Language Reference Manual}, which contains all reference
867 material for the Ada 95 programming language.
868
869 @item
870 @cite{Debugging with GDB}
871 @ifset vms
872 , located in the GNU:[DOCS] directory,
873 @end ifset
874 contains all details on the use of the GNU source-level debugger.
875
876 @item
877 @cite{GNU Emacs Manual}
878 @ifset vms
879 , located in the GNU:[DOCS] directory if the EMACS kit is installed,
880 @end ifset
881 contains full information on the extensible editor and programming
882 environment Emacs.
883
884 @end itemize
885
886 @c **************
887 @node Conventions
888 @unnumberedsec Conventions
889 @cindex Conventions
890 @cindex Typographical conventions
891
892 @noindent
893 Following are examples of the typographical and graphic conventions used
894 in this guide:
895
896 @itemize @bullet
897 @item
898 @code{Functions}, @code{utility program names}, @code{standard names},
899 and @code{classes}.
900
901 @item
902 @samp{Option flags}
903
904 @item
905 @file{File Names}, @file{button names}, and @file{field names}.
906
907 @item
908 @var{Variables}.
909
910 @item
911 @emph{Emphasis}.
912
913 @item
914 [optional information or parameters]
915
916 @item
917 Examples are described by text
918 @smallexample
919 and then shown this way.
920 @end smallexample
921 @end itemize
922
923 @noindent
924 Commands that are entered by the user are preceded in this manual by the
925 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
926 uses this sequence as a prompt, then the commands will appear exactly as
927 you see them in the manual. If your system uses some other prompt, then
928 the command will appear with the @code{$} replaced by whatever prompt
929 character you are using.
930
931 @ifset unw
932 Full file names are shown with the ``@code{/}'' character
933 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
934 If you are using GNAT on a Windows platform, please note that
935 the ``@code{\}'' character should be used instead.
936 @end ifset
937
938
939
940 @c ****************************
941 @node Getting Started with GNAT
942 @chapter Getting Started with GNAT
943
944 @noindent
945 This chapter describes some simple ways of using GNAT to build
946 executable Ada programs.
947 @ifset unw
948 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
949 show how to use the command line environment.
950 @ref{Introduction to Glide and GVD}, provides a brief
951 introduction to the visually-oriented IDE for GNAT.
952 Supplementing Glide on some platforms is GPS, the
953 GNAT Programming System, which offers a richer graphical
954 ``look and feel'', enhanced configurability, support for
955 development in other programming language, comprehensive
956 browsing features, and many other capabilities.
957 For information on GPS please refer to
958 @cite{Using the GNAT Programming System}.
959 @end ifset
960
961 @menu
962 * Running GNAT::
963 * Running a Simple Ada Program::
964 * Running a Program with Multiple Units::
965 * Using the gnatmake Utility::
966 @ifset vms
967 * Editing with Emacs::
968 @end ifset
969 @ifclear vms
970 * Introduction to GPS::
971 * Introduction to Glide and GVD::
972 @end ifclear
973 @end menu
974
975 @node Running GNAT
976 @section Running GNAT
977
978 @noindent
979 Three steps are needed to create an executable file from an Ada source
980 file:
981
982 @enumerate
983 @item
984 The source file(s) must be compiled.
985 @item
986 The file(s) must be bound using the GNAT binder.
987 @item
988 All appropriate object files must be linked to produce an executable.
989 @end enumerate
990
991 @noindent
992 All three steps are most commonly handled by using the @code{gnatmake}
993 utility program that, given the name of the main program, automatically
994 performs the necessary compilation, binding and linking steps.
995
996
997 @node Running a Simple Ada Program
998 @section Running a Simple Ada Program
999
1000 @noindent
1001 Any text editor may be used to prepare an Ada program.
1002 @ifclear vms
1003 If @code{Glide} is
1004 used, the optional Ada mode may be helpful in laying out the program.
1005 @end ifclear
1006 The
1007 program text is a normal text file. We will suppose in our initial
1008 example that you have used your editor to prepare the following
1009 standard format text file:
1010
1011 @smallexample @c ada
1012 @cartouche
1013 with Ada.Text_IO; use Ada.Text_IO;
1014 procedure Hello is
1015 begin
1016    Put_Line ("Hello WORLD!");
1017 end Hello;
1018 @end cartouche
1019 @end smallexample
1020
1021 @noindent
1022 This file should be named @file{hello.adb}.
1023 With the normal default file naming conventions, GNAT requires
1024 that each file
1025 contain a single compilation unit whose file name is the
1026 unit name,
1027 with periods replaced by hyphens; the
1028 extension is @file{ads} for a
1029 spec and @file{adb} for a body.
1030 You can override this default file naming convention by use of the
1031 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1032 Alternatively, if you want to rename your files according to this default
1033 convention, which is probably more convenient if you will be using GNAT
1034 for all your compilations, then the @code{gnatchop} utility
1035 can be used to generate correctly-named source files
1036 (@pxref{Renaming Files Using gnatchop}).
1037
1038 You can compile the program using the following command (@code{$} is used
1039 as the command prompt in the examples in this document):
1040
1041 @smallexample
1042 $ gcc -c hello.adb
1043 @end smallexample
1044
1045 @noindent
1046 @code{gcc} is the command used to run the compiler. This compiler is
1047 capable of compiling programs in several languages, including Ada 95 and
1048 C. It assumes that you have given it an Ada program if the file extension is
1049 either @file{.ads} or @file{.adb}, and it will then call
1050 the GNAT compiler to compile the specified file.
1051
1052 @ifclear vms
1053 The @option{-c} switch is required. It tells @command{gcc} to only do a
1054 compilation. (For C programs, @command{gcc} can also do linking, but this
1055 capability is not used directly for Ada programs, so the @option{-c}
1056 switch must always be present.)
1057 @end ifclear
1058
1059 This compile command generates a file
1060 @file{hello.o}, which is the object
1061 file corresponding to your Ada program. It also generates
1062 an ``Ada Library Information'' file @file{hello.ali},
1063 which contains additional information used to check
1064 that an Ada program is consistent.
1065 To build an executable file,
1066 use @code{gnatbind} to bind the program
1067 and @code{gnatlink} to link it. The
1068 argument to both @code{gnatbind} and @code{gnatlink} is the name of the
1069 @file{ALI} file, but the default extension of @file{.ali} can
1070 be omitted. This means that in the most common case, the argument
1071 is simply the name of the main program:
1072
1073 @smallexample
1074 $ gnatbind hello
1075 $ gnatlink hello
1076 @end smallexample
1077
1078 @noindent
1079 A simpler method of carrying out these steps is to use
1080 @command{gnatmake},
1081 a master program that invokes all the required
1082 compilation, binding and linking tools in the correct order. In particular,
1083 @command{gnatmake} automatically recompiles any sources that have been
1084 modified since they were last compiled, or sources that depend
1085 on such modified sources, so that ``version skew'' is avoided.
1086 @cindex Version skew (avoided by @command{gnatmake})
1087
1088 @smallexample
1089 $ gnatmake hello.adb
1090 @end smallexample
1091
1092 @noindent
1093 The result is an executable program called @file{hello}, which can be
1094 run by entering:
1095
1096 @c The following should be removed (BMB 2001-01-23)
1097 @c @smallexample
1098 @c $ ^./hello^$ RUN HELLO^
1099 @c @end smallexample
1100
1101 @smallexample
1102 $ hello
1103 @end smallexample
1104
1105 @noindent
1106 assuming that the current directory is on the search path
1107 for executable programs.
1108
1109 @noindent
1110 and, if all has gone well, you will see
1111
1112 @smallexample
1113 Hello WORLD!
1114 @end smallexample
1115
1116 @noindent
1117 appear in response to this command.
1118
1119
1120 @c ****************************************
1121 @node Running a Program with Multiple Units
1122 @section Running a Program with Multiple Units
1123
1124 @noindent
1125 Consider a slightly more complicated example that has three files: a
1126 main program, and the spec and body of a package:
1127
1128 @smallexample @c ada
1129 @cartouche
1130 @group
1131 package Greetings is
1132    procedure Hello;
1133    procedure Goodbye;
1134 end Greetings;
1135
1136 with Ada.Text_IO; use Ada.Text_IO;
1137 package body Greetings is
1138    procedure Hello is
1139    begin
1140       Put_Line ("Hello WORLD!");
1141    end Hello;
1142
1143    procedure Goodbye is
1144    begin
1145       Put_Line ("Goodbye WORLD!");
1146    end Goodbye;
1147 end Greetings;
1148 @end group
1149
1150 @group
1151 with Greetings;
1152 procedure Gmain is
1153 begin
1154    Greetings.Hello;
1155    Greetings.Goodbye;
1156 end Gmain;
1157 @end group
1158 @end cartouche
1159 @end smallexample
1160
1161 @noindent
1162 Following the one-unit-per-file rule, place this program in the
1163 following three separate files:
1164
1165 @table @file
1166 @item greetings.ads
1167 spec of package @code{Greetings}
1168
1169 @item greetings.adb
1170 body of package @code{Greetings}
1171
1172 @item gmain.adb
1173 body of main program
1174 @end table
1175
1176 @noindent
1177 To build an executable version of
1178 this program, we could use four separate steps to compile, bind, and link
1179 the program, as follows:
1180
1181 @smallexample
1182 $ gcc -c gmain.adb
1183 $ gcc -c greetings.adb
1184 $ gnatbind gmain
1185 $ gnatlink gmain
1186 @end smallexample
1187
1188 @noindent
1189 Note that there is no required order of compilation when using GNAT.
1190 In particular it is perfectly fine to compile the main program first.
1191 Also, it is not necessary to compile package specs in the case where
1192 there is an accompanying body; you only need to compile the body. If you want
1193 to submit these files to the compiler for semantic checking and not code
1194 generation, then use the
1195 @option{-gnatc} switch:
1196
1197 @smallexample
1198 $ gcc -c greetings.ads -gnatc
1199 @end smallexample
1200
1201 @noindent
1202 Although the compilation can be done in separate steps as in the
1203 above example, in practice it is almost always more convenient
1204 to use the @code{gnatmake} tool. All you need to know in this case
1205 is the name of the main program's source file. The effect of the above four
1206 commands can be achieved with a single one:
1207
1208 @smallexample
1209 $ gnatmake gmain.adb
1210 @end smallexample
1211
1212 @noindent
1213 In the next section we discuss the advantages of using @code{gnatmake} in
1214 more detail.
1215
1216 @c *****************************
1217 @node Using the gnatmake Utility
1218 @section Using the @command{gnatmake} Utility
1219
1220 @noindent
1221 If you work on a program by compiling single components at a time using
1222 @code{gcc}, you typically keep track of the units you modify. In order to
1223 build a consistent system, you compile not only these units, but also any
1224 units that depend on the units you have modified.
1225 For example, in the preceding case,
1226 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1227 you edit @file{greetings.ads}, you must recompile both
1228 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1229 units that depend on @file{greetings.ads}.
1230
1231 @code{gnatbind} will warn you if you forget one of these compilation
1232 steps, so that it is impossible to generate an inconsistent program as a
1233 result of forgetting to do a compilation. Nevertheless it is tedious and
1234 error-prone to keep track of dependencies among units.
1235 One approach to handle the dependency-bookkeeping is to use a
1236 makefile. However, makefiles present maintenance problems of their own:
1237 if the dependencies change as you change the program, you must make
1238 sure that the makefile is kept up-to-date manually, which is also an
1239 error-prone process.
1240
1241 The @code{gnatmake} utility takes care of these details automatically.
1242 Invoke it using either one of the following forms:
1243
1244 @smallexample
1245 $ gnatmake gmain.adb
1246 $ gnatmake ^gmain^GMAIN^
1247 @end smallexample
1248
1249 @noindent
1250 The argument is the name of the file containing the main program;
1251 you may omit the extension. @code{gnatmake}
1252 examines the environment, automatically recompiles any files that need
1253 recompiling, and binds and links the resulting set of object files,
1254 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1255 In a large program, it
1256 can be extremely helpful to use @code{gnatmake}, because working out by hand
1257 what needs to be recompiled can be difficult.
1258
1259 Note that @code{gnatmake}
1260 takes into account all the Ada 95 rules that
1261 establish dependencies among units. These include dependencies that result
1262 from inlining subprogram bodies, and from
1263 generic instantiation. Unlike some other
1264 Ada make tools, @code{gnatmake} does not rely on the dependencies that were
1265 found by the compiler on a previous compilation, which may possibly
1266 be wrong when sources change. @code{gnatmake} determines the exact set of
1267 dependencies from scratch each time it is run.
1268
1269 @ifset vms
1270 @node Editing with Emacs
1271 @section Editing with Emacs
1272 @cindex Emacs
1273
1274 @noindent
1275 Emacs is an extensible self-documenting text editor that is available in a
1276 separate VMSINSTAL kit.
1277
1278 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1279 click on the Emacs Help menu and run the Emacs Tutorial.
1280 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1281 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1282
1283 Documentation on Emacs and other tools is available in Emacs under the
1284 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1285 use the middle mouse button to select a topic (e.g. Emacs).
1286
1287 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1288 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1289 get to the Emacs manual.
1290 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1291 prompt.
1292
1293 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1294 which is sufficiently extensible to provide for a complete programming
1295 environment and shell for the sophisticated user.
1296 @end ifset
1297
1298 @ifclear vms
1299 @node Introduction to GPS
1300 @section Introduction to GPS
1301 @cindex GPS (GNAT Programming System)
1302 @cindex GNAT Programming System (GPS)
1303 @noindent
1304 Although the command line interface (@command{gnatmake}, etc.) alone
1305 is sufficient, a graphical Interactive Development
1306 Environment can make it easier for you to compose, navigate, and debug
1307 programs.  This section describes the main features of GPS
1308 (``GNAT Programming System''), the GNAT graphical IDE.
1309 You will see how to use GPS to build and debug an executable, and
1310 you will also learn some of the basics of the GNAT ``project'' facility.
1311
1312 GPS enables you to do much more than is presented here;
1313 e.g., you can produce a call graph, interface to a third-party
1314 Version Control System, and inspect the generated assembly language
1315 for a program.
1316 Indeed, GPS also supports languages other than Ada.
1317 Such additional information, and an explanation of all of the GPS menu
1318 items. may be found in the on-line help, which includes
1319 a user's guide and a tutorial (these are also accessible from the GNAT
1320 startup menu).
1321
1322 @menu
1323 * Building a New Program with GPS::
1324 * Simple Debugging with GPS::
1325 @end menu
1326
1327
1328 @node Building a New Program with GPS
1329 @subsection Building a New Program with GPS
1330 @noindent
1331 GPS invokes the GNAT compilation tools using information
1332 contained in a @emph{project} (also known as a @emph{project file}):
1333 a collection of properties such
1334 as source directories, identities of main subprograms, tool switches, etc.,
1335 and their associated values.
1336 (See @ref{GNAT Project Manager}, for details.)
1337 In order to run GPS, you will need to either create a new project
1338 or else open an existing one.
1339
1340 This section will explain how you can use GPS to create a project,
1341 to associate Ada source files with a project, and to build and run
1342 programs.
1343
1344 @enumerate
1345 @item @emph{Creating a project}
1346
1347 Invoke GPS, either from the command line or the platform's IDE.
1348 After it starts, GPS will display a ``Welcome'' screen with three
1349 radio buttons:
1350
1351 @itemize @bullet
1352 @item
1353 @code{Start with default project in directory}
1354
1355 @item
1356 @code{Create new project with wizard}
1357
1358 @item
1359 @code{Open existing project}
1360 @end itemize
1361
1362 @noindent
1363 Select @code{Create new project with wizard} and press @code{OK}.
1364 A new window will appear.  In the text box labeled with
1365 @code{Enter the name of the project to create}, type @file{sample}
1366 as the project name.
1367 In the next box, browse to choose the directory in which you
1368 would like to create the project file.
1369 After selecting an appropriate directory, press @code{Forward}.
1370
1371 A window will appear with the title
1372 @code{Version Control System Configuration}.
1373 Simply press @code{Forward}.
1374
1375 A window will appear with the title
1376 @code{Please select the source directories for this project}.
1377 The directory that you specified for the project file will be selected
1378 by default as the one to use for sources; simply press @code{Forward}.
1379
1380 A window will appear with the title
1381 @code{Please select the build directory for this project}.
1382 The directory that you specified for the project file will be selected
1383 by default for object files and executables;
1384 simply press @code{Forward}.
1385
1386 A window will appear with the title
1387 @code{Please select the main units for this project}.
1388 You will supply this information later, after creating the source file.
1389 Simply press @code{Forward} for now.
1390
1391 A window will appear with the title
1392 @code{Please select the switches to build the project}.
1393 Press @code{Apply}.  This will create a project file named
1394 @file{sample.prj} in the directory that you had specified.
1395
1396 @item @emph{Creating and saving the source file}
1397
1398 After you create the new project, a GPS window will appear, which is
1399 partitioned into two main sections:
1400
1401 @itemize @bullet
1402 @item
1403 A @emph{Workspace area}, initially greyed out, which you will use for
1404 creating and editing source files
1405
1406 @item
1407 Directly below, a @emph{Messages area}, which initially displays a
1408 ``Welcome'' message.
1409 (If the Messages area is not visible, drag its border upward to expand it.)
1410 @end itemize
1411
1412 @noindent
1413 Select @code{File} on the menu bar, and then the @code{New} command.
1414 The Workspace area will become white, and you can now
1415 enter the source program explicitly.
1416 Type the following text
1417
1418 @smallexample @c ada
1419 @group
1420 with Ada.Text_IO; use Ada.Text_IO;
1421 procedure Hello is
1422 begin
1423   Put_Line("Hello from GPS!");
1424 end Hello;
1425 @end group
1426 @end smallexample
1427
1428 @noindent
1429 Select @code{File}, then @code{Save As}, and enter the source file name
1430 @file{hello.adb}.
1431 The file will be saved in the same directory you specified as the
1432 location of the default project file.
1433
1434
1435 @item @emph{Updating the project file}
1436
1437 You need to add the new source file to the project.
1438 To do this, select
1439 the @code{Project} menu and then @code{Edit project properties}.
1440 Click the @code{Main files} tab on the left, and then the
1441 @code{Add} button.
1442 Choose @file{hello.adb} from the list, and press @code{Open}.
1443 The project settings window will reflect this action.
1444 Click @code{OK}.
1445
1446 @item @emph{Building and running the program}
1447
1448 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1449 and select @file{hello.adb}.
1450 The Messages window will display the resulting invocations of @command{gcc},
1451 @command{gnatbind}, and @command{gnatlink}
1452 (reflecting the default switch settings from the
1453 project file that you created) and then a ``successful compilation/build''
1454 message.
1455
1456 To run the program, choose the @code{Build} menu, then @code{Run}, and
1457 select @command{hello}.
1458 An @emph{Arguments Selection} window will appear.
1459 There are no command line arguments, so just click @code{OK}.
1460
1461 The Messages window will now display the program's output (the string
1462 @code{Hello from GPS}), and at the bottom of the GPS window a status
1463 update is displayed (@code{Run: hello}).
1464 Close the GPS window (or select @code{File}, then @code{Exit}) to
1465 terminate this GPS session.
1466 @end enumerate
1467
1468
1469
1470 @node Simple Debugging with GPS
1471 @subsection Simple Debugging with GPS
1472 @noindent
1473 This section illustrates basic debugging techniques (setting breakpoints,
1474 examining/modifying variables, single stepping).
1475
1476 @enumerate
1477 @item @emph{Opening a project}
1478
1479 Start GPS and select @code{Open existing project}; browse to
1480 specify the project file @file{sample.prj} that you had created in the
1481 earlier example.
1482
1483 @item @emph{Creating a source file}
1484
1485 Select @code{File}, then @code{New}, and type in the following program:
1486
1487 @smallexample @c ada
1488 @group
1489 with Ada.Text_IO; use Ada.Text_IO;
1490 procedure Example is
1491    Line : String (1..80);
1492    N    : Natural;
1493 begin
1494    Put_Line("Type a line of text at each prompt; an empty line to exit");
1495    loop
1496       Put(": ");
1497       Get_Line (Line, N);
1498       Put_Line (Line (1..N) );
1499       exit when N=0;
1500    end loop;
1501 end Example;
1502 @end group
1503 @end smallexample
1504
1505 @noindent
1506 Select @code{File}, then @code{Save as}, and enter the file name
1507 @file{example.adb}.
1508
1509 @item @emph{Updating the project file}
1510
1511 Add @code{Example} as a new main unit for the project:
1512 @enumerate a
1513 @item
1514 Select @code{Project}, then @code{Edit Project Properties}.
1515
1516 @item
1517 Select the @code{Main files} tab, click @code{Add}, then
1518 select the file @file{example.adb} from the list, and
1519 click @code{Open}.
1520 You will see the file name appear in the list of main units
1521
1522 @item
1523 Click @code{OK}
1524 @end enumerate
1525
1526 @item @emph{Building/running the executable}
1527
1528 To build the executable
1529 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1530
1531 Run the program to see its effect (in the Messages area).
1532 Each line that you enter is displayed; an empty line will
1533 cause the loop to exit and the program to terminate.
1534
1535 @item @emph{Debugging the program}
1536
1537 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1538 which are required for debugging, are on by default when you create
1539 a new project.
1540 Thus unless you intentionally remove these settings, you will be able
1541 to debug any program that you develop using GPS.
1542
1543 @enumerate a
1544 @item @emph{Initializing}
1545
1546 Select @code{Debug}, then @code{Initialize}, then @file{example}
1547
1548 @item @emph{Setting a breakpoint}
1549
1550 After performing the initialization step, you will observe a small
1551 icon to the right of each line number.
1552 This serves as a toggle for breakpoints; clicking the icon will
1553 set a breakpoint at the corresponding line (the icon will change to
1554 a red circle with an ``x''), and clicking it again
1555 will remove the breakpoint / reset the icon.
1556
1557 For purposes of this example, set a breakpoint at line 10 (the
1558 statement @code{Put_Line@ (Line@ (1..N));}
1559
1560 @item @emph{Starting program execution}
1561
1562 Select @code{Debug}, then @code{Run}.  When the
1563 @code{Program Arguments} window appears, click @code{OK}.
1564 A console window will appear; enter some line of text,
1565 e.g. @code{abcde}, at the prompt.
1566 The program will pause execution when it gets to the
1567 breakpoint, and the corresponding line is highlighted.
1568
1569 @item @emph{Examining a variable}
1570
1571 Move the mouse over one of the occurrences of the variable @code{N}.
1572 You will see the value (5) displayed, in ``tool tip'' fashion.
1573 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1574 You will see information about @code{N} appear in the @code{Debugger Data}
1575 pane, showing the value as 5.
1576
1577
1578 @item @emph{Assigning a new value to a variable}
1579
1580 Right click on the @code{N} in the @code{Debugger Data} pane, and
1581 select @code{Set value of N}.
1582 When the input window appears, enter the value @code{4} and click
1583 @code{OK}.
1584 This value does not automatically appear in the @code{Debugger Data}
1585 pane; to see it, right click again on the @code{N} in the
1586 @code{Debugger Data} pane and select @code{Update value}.
1587 The new value, 4, will appear in red.
1588
1589 @item @emph{Single stepping}
1590
1591 Select @code{Debug}, then @code{Next}.
1592 This will cause the next statement to be executed, in this case the
1593 call of @code{Put_Line} with the string slice.
1594 Notice in the console window that the displayed string is simply
1595 @code{abcd} and not @code{abcde} which you had entered.
1596 This is because the upper bound of the slice is now 4 rather than 5.
1597
1598 @item @emph{Removing a breakpoint}
1599
1600 Toggle the breakpoint icon at line 10.
1601
1602 @item @emph{Resuming execution from a breakpoint}
1603
1604 Select @code{Debug}, then @code{Continue}.
1605 The program will reach the next iteration of the loop, and
1606 wait for input after displaying the prompt.
1607 This time, just hit the @kbd{Enter} key.
1608 The value of @code{N} will be 0, and the program will terminate.
1609 The console window will disappear.
1610 @end enumerate
1611 @end enumerate
1612
1613
1614 @node Introduction to Glide and GVD
1615 @section Introduction to Glide and GVD
1616 @cindex Glide
1617 @cindex GVD
1618 @noindent
1619 This section describes the main features of Glide,
1620 a GNAT graphical IDE, and also shows how to use the basic commands in GVD,
1621 the GNU Visual Debugger.
1622 These tools may be present in addition to, or in place of, GPS on some
1623 platforms.
1624 Additional information on Glide and GVD may be found
1625 in the on-line help for these tools.
1626
1627 @menu
1628 * Building a New Program with Glide::
1629 * Simple Debugging with GVD::
1630 * Other Glide Features::
1631 @end menu
1632
1633 @node Building a New Program with Glide
1634 @subsection Building a New Program with Glide
1635 @noindent
1636 The simplest way to invoke Glide is to enter @command{glide}
1637 at the command prompt.  It will generally be useful to issue this
1638 as a background command, thus allowing you to continue using
1639 your command window for other purposes while Glide is running:
1640
1641 @smallexample
1642 $ glide&
1643 @end smallexample
1644
1645 @noindent
1646 Glide will start up with an initial screen displaying the top-level menu items
1647 as well as some other information.  The menu selections are as follows
1648 @itemize @bullet
1649 @item @code{Buffers}
1650 @item @code{Files}
1651 @item @code{Tools}
1652 @item @code{Edit}
1653 @item @code{Search}
1654 @item @code{Mule}
1655 @item @code{Glide}
1656 @item @code{Help}
1657 @end itemize
1658
1659 @noindent
1660 For this introductory example, you will need to create a new Ada source file.
1661 First, select the @code{Files} menu.  This will pop open a menu with around
1662 a dozen or so items.  To create a file, select the @code{Open file...} choice.
1663 Depending on the platform, you may see a pop-up window where you can browse
1664 to an appropriate directory and then enter the file name, or else simply
1665 see a line at the bottom of the Glide window where you can likewise enter
1666 the file name.  Note that in Glide, when you attempt to open a non-existent
1667 file, the effect is to create a file with that name.  For this example enter
1668 @file{hello.adb} as the name of the file.
1669
1670 A new buffer will now appear, occupying the entire Glide window,
1671 with the file name at the top.  The menu selections are slightly different
1672 from the ones you saw on the opening screen; there is an @code{Entities} item,
1673 and in place of @code{Glide} there is now an @code{Ada} item.  Glide uses
1674 the file extension to identify the source language, so @file{adb} indicates
1675 an Ada source file.
1676
1677 You will enter some of the source program lines explicitly,
1678 and use the syntax-oriented template mechanism to enter other lines.
1679 First, type the following text:
1680 @smallexample
1681 with Ada.Text_IO; use Ada.Text_IO;
1682 procedure Hello is
1683 begin
1684 @end smallexample
1685
1686 @noindent
1687 Observe that Glide uses different colors to distinguish reserved words from
1688 identifiers.  Also, after the @code{procedure Hello is} line, the cursor is
1689 automatically indented in anticipation of declarations.  When you enter
1690 @code{begin}, Glide recognizes that there are no declarations and thus places
1691 @code{begin} flush left.  But after the @code{begin} line the cursor is again
1692 indented, where the statement(s) will be placed.
1693
1694 The main part of the program will be a @code{for} loop.  Instead of entering
1695 the text explicitly, however, use a statement template.  Select the @code{Ada}
1696 item on the top menu bar, move the mouse to the @code{Statements} item,
1697 and you will see a large selection of alternatives.  Choose @code{for loop}.
1698 You will be prompted (at the bottom of the buffer) for a loop name;
1699 simply press the @key{Enter} key since a loop name is not needed.
1700 You should see the beginning of a @code{for} loop appear in the source
1701 program window.  You will now be prompted for the name of the loop variable;
1702 enter a line with the identifier @code{ind} (lower case).  Note that,
1703 by default, Glide capitalizes the name (you can override such behavior
1704 if you wish, although this is outside the scope of this introduction).
1705 Next, Glide prompts you for the loop range; enter a line containing
1706 @code{1..5} and you will see this also appear in the source program,
1707 together with the remaining elements of the @code{for} loop syntax.
1708
1709 Next enter the statement (with an intentional error, a missing semicolon)
1710 that will form the body of the loop:
1711 @smallexample
1712 Put_Line("Hello, World" & Integer'Image(I))
1713 @end smallexample
1714
1715 @noindent
1716 Finally, type @code{end Hello;} as the last line in the program.
1717 Now save the file: choose the @code{File} menu item, and then the
1718 @code{Save buffer} selection.  You will see a message at the bottom
1719 of the buffer confirming that the file has been saved.
1720
1721 You are now ready to attempt to build the program.  Select the @code{Ada}
1722 item from the top menu bar.  Although we could choose simply to compile
1723 the file, we will instead attempt to do a build (which invokes
1724 @command{gnatmake}) since, if the compile is successful, we want to build
1725 an executable.  Thus select @code{Ada build}.  This will fail because of the
1726 compilation error, and you will notice that the Glide window has been split:
1727 the top window contains the source file, and the bottom window contains the
1728 output from the GNAT tools. Glide allows you to navigate from a compilation
1729 error to the source file position corresponding to the error: click the
1730 middle mouse button (or simultaneously press the left and right buttons,
1731 on a two-button mouse) on the diagnostic line in the tool window.  The
1732 focus will shift to the source window, and the cursor will be positioned
1733 on the character at which the error was detected.
1734
1735 Correct the error: type in a semicolon to terminate the statement.
1736 Although you can again save the file explicitly, you can also simply invoke
1737 @code{Ada} @result{} @code{Build} and you will be prompted to save the file.
1738 This time the build will succeed; the tool output window shows you the
1739 options that are supplied by default.  The GNAT tools' output (e.g.
1740 object and ALI files, executable) will go in the directory from which
1741 Glide was launched.
1742
1743 To execute the program, choose @code{Ada} and then @code{Run}.
1744 You should see the program's output displayed in the bottom window:
1745
1746 @smallexample
1747 Hello, world 1
1748 Hello, world 2
1749 Hello, world 3
1750 Hello, world 4
1751 Hello, world 5
1752 @end smallexample
1753
1754 @node Simple Debugging with GVD
1755 @subsection Simple Debugging with GVD
1756
1757 @noindent
1758 This section describes how to set breakpoints, examine/modify variables,
1759 and step through execution.
1760
1761 In order to enable debugging, you need to pass the @option{-g} switch
1762 to both the compiler and to @command{gnatlink}.  If you are using
1763 the command line, passing @option{-g} to @command{gnatmake} will have
1764 this effect.  You can then launch GVD, e.g. on the @code{hello} program,
1765 by issuing the command:
1766
1767 @smallexample
1768 $ gvd hello
1769 @end smallexample
1770
1771 @noindent
1772 If you are using Glide, then @option{-g} is passed to the relevant tools
1773 by default when you do a build.  Start the debugger by selecting the
1774 @code{Ada} menu item, and then @code{Debug}.
1775
1776 GVD comes up in a multi-part window.  One pane shows the names of files
1777 comprising your executable; another pane shows the source code of the current
1778 unit (initially your main subprogram), another pane shows the debugger output
1779 and user interactions, and the fourth pane (the data canvas at the top
1780 of the window) displays data objects that you have selected.
1781
1782 To the left of the source file pane, you will notice green dots adjacent
1783 to some lines.  These are lines for which object code exists and where
1784 breakpoints can thus be set.  You set/reset a breakpoint by clicking
1785 the green dot.  When a breakpoint is set, the dot is replaced by an @code{X}
1786 in a red circle.  Clicking the circle toggles the breakpoint off,
1787 and the red circle is replaced by the green dot.
1788
1789 For this example, set a breakpoint at the statement where @code{Put_Line}
1790 is invoked.
1791
1792 Start program execution by selecting the @code{Run} button on the top menu bar.
1793 (The @code{Start} button will also start your program, but it will
1794 cause program execution to break at the entry to your main subprogram.)
1795 Evidence of reaching the breakpoint will appear: the source file line will be
1796 highlighted, and the debugger interactions pane will display
1797 a relevant message.
1798
1799 You can examine the values of variables in several ways.  Move the mouse
1800 over an occurrence of @code{Ind} in the @code{for} loop, and you will see
1801 the value (now @code{1}) displayed.  Alternatively, right-click on @code{Ind}
1802 and select @code{Display Ind}; a box showing the variable's name and value
1803 will appear in the data canvas.
1804
1805 Although a loop index is a constant with respect to Ada semantics,
1806 you can change its value in the debugger.  Right-click in the box
1807 for @code{Ind}, and select the @code{Set Value of Ind} item.
1808 Enter @code{2} as the new value, and press @command{OK}.
1809 The box for @code{Ind} shows the update.
1810
1811 Press the @code{Step} button on the top menu bar; this will step through
1812 one line of program text (the invocation of @code{Put_Line}), and you can
1813 observe the effect of having modified @code{Ind} since the value displayed
1814 is @code{2}.
1815
1816 Remove the breakpoint, and resume execution by selecting the @code{Cont}
1817 button.  You will see the remaining output lines displayed in the debugger
1818 interaction window, along with a message confirming normal program
1819 termination.
1820
1821 @node Other Glide Features
1822 @subsection Other Glide Features
1823
1824 @noindent
1825 You may have observed that some of the menu selections contain abbreviations;
1826 e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu.
1827 These are @emph{shortcut keys} that you can use instead of selecting
1828 menu items.  The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means
1829 @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead
1830 of selecting @code{Files} and then @code{Open file...}.
1831
1832 To abort a Glide command, type @key{Ctrl-g}.
1833
1834 If you want Glide to start with an existing source file, you can either
1835 launch Glide as above and then open the file via @code{Files} @result{}
1836 @code{Open file...}, or else simply pass the name of the source file
1837 on the command line:
1838
1839 @smallexample
1840 $ glide hello.adb&
1841 @end smallexample
1842
1843 @noindent
1844 While you are using Glide, a number of @emph{buffers} exist.
1845 You create some explicitly; e.g., when you open/create a file.
1846 Others arise as an effect of the commands that you issue; e.g., the buffer
1847 containing the output of the tools invoked during a build.  If a buffer
1848 is hidden, you can bring it into a visible window by first opening
1849 the @code{Buffers} menu and then selecting the desired entry.
1850
1851 If a buffer occupies only part of the Glide screen and you want to expand it
1852 to fill the entire screen, then click in the buffer and then select
1853 @code{Files} @result{} @code{One Window}.
1854
1855 If a window is occupied by one buffer and you want to split the window
1856 to bring up a second buffer, perform the following steps:
1857 @itemize @bullet
1858 @item Select @code{Files} @result{} @code{Split Window};
1859 this will produce two windows each of which holds the original buffer
1860 (these are not copies, but rather different views of the same buffer contents)
1861
1862 @item With the focus in one of the windows,
1863 select the desired buffer from the @code{Buffers} menu
1864 @end itemize
1865
1866 @noindent
1867 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1868 @end ifclear
1869
1870 @node The GNAT Compilation Model
1871 @chapter The GNAT Compilation Model
1872 @cindex GNAT compilation model
1873 @cindex Compilation model
1874
1875 @menu
1876 * Source Representation::
1877 * Foreign Language Representation::
1878 * File Naming Rules::
1879 * Using Other File Names::
1880 * Alternative File Naming Schemes::
1881 * Generating Object Files::
1882 * Source Dependencies::
1883 * The Ada Library Information Files::
1884 * Binding an Ada Program::
1885 * Mixed Language Programming::
1886 * Building Mixed Ada & C++ Programs::
1887 * Comparison between GNAT and C/C++ Compilation Models::
1888 * Comparison between GNAT and Conventional Ada Library Models::
1889 @ifset vms
1890 * Placement of temporary files::
1891 @end ifset
1892 @end menu
1893
1894 @noindent
1895 This chapter describes the compilation model used by GNAT. Although
1896 similar to that used by other languages, such as C and C++, this model
1897 is substantially different from the traditional Ada compilation models,
1898 which are based on a library. The model is initially described without
1899 reference to the library-based model. If you have not previously used an
1900 Ada compiler, you need only read the first part of this chapter. The
1901 last section describes and discusses the differences between the GNAT
1902 model and the traditional Ada compiler models. If you have used other
1903 Ada compilers, this section will help you to understand those
1904 differences, and the advantages of the GNAT model.
1905
1906 @node Source Representation
1907 @section Source Representation
1908 @cindex Latin-1
1909
1910 @noindent
1911 Ada source programs are represented in standard text files, using
1912 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1913 7-bit ASCII set, plus additional characters used for
1914 representing foreign languages (@pxref{Foreign Language Representation}
1915 for support of non-USA character sets). The format effector characters
1916 are represented using their standard ASCII encodings, as follows:
1917
1918 @table @code
1919 @item VT
1920 @findex VT
1921 Vertical tab, @code{16#0B#}
1922
1923 @item HT
1924 @findex HT
1925 Horizontal tab, @code{16#09#}
1926
1927 @item CR
1928 @findex CR
1929 Carriage return, @code{16#0D#}
1930
1931 @item LF
1932 @findex LF
1933 Line feed, @code{16#0A#}
1934
1935 @item FF
1936 @findex FF
1937 Form feed, @code{16#0C#}
1938 @end table
1939
1940 @noindent
1941 Source files are in standard text file format. In addition, GNAT will
1942 recognize a wide variety of stream formats, in which the end of physical
1943 physical lines is marked by any of the following sequences:
1944 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1945 in accommodating files that are imported from other operating systems.
1946
1947 @cindex End of source file
1948 @cindex Source file, end
1949 @findex SUB
1950 The end of a source file is normally represented by the physical end of
1951 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1952 recognized as signalling the end of the source file. Again, this is
1953 provided for compatibility with other operating systems where this
1954 code is used to represent the end of file.
1955
1956 Each file contains a single Ada compilation unit, including any pragmas
1957 associated with the unit. For example, this means you must place a
1958 package declaration (a package @dfn{spec}) and the corresponding body in
1959 separate files. An Ada @dfn{compilation} (which is a sequence of
1960 compilation units) is represented using a sequence of files. Similarly,
1961 you will place each subunit or child unit in a separate file.
1962
1963 @node Foreign Language Representation
1964 @section Foreign Language Representation
1965
1966 @noindent
1967 GNAT supports the standard character sets defined in Ada 95 as well as
1968 several other non-standard character sets for use in localized versions
1969 of the compiler (@pxref{Character Set Control}).
1970 @menu
1971 * Latin-1::
1972 * Other 8-Bit Codes::
1973 * Wide Character Encodings::
1974 @end menu
1975
1976 @node Latin-1
1977 @subsection Latin-1
1978 @cindex Latin-1
1979
1980 @noindent
1981 The basic character set is Latin-1. This character set is defined by ISO
1982 standard 8859, part 1. The lower half (character codes @code{16#00#}
1983 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1984 is used to represent additional characters. These include extended letters
1985 used by European languages, such as French accents, the vowels with umlauts
1986 used in German, and the extra letter A-ring used in Swedish.
1987
1988 @findex Ada.Characters.Latin_1
1989 For a complete list of Latin-1 codes and their encodings, see the source
1990 file of library unit @code{Ada.Characters.Latin_1} in file
1991 @file{a-chlat1.ads}.
1992 You may use any of these extended characters freely in character or
1993 string literals. In addition, the extended characters that represent
1994 letters can be used in identifiers.
1995
1996 @node Other 8-Bit Codes
1997 @subsection Other 8-Bit Codes
1998
1999 @noindent
2000 GNAT also supports several other 8-bit coding schemes:
2001
2002 @table @asis
2003 @item ISO 8859-2 (Latin-2)
2004 @cindex Latin-2
2005 @cindex ISO 8859-2
2006 Latin-2 letters allowed in identifiers, with uppercase and lowercase
2007 equivalence.
2008
2009 @item ISO 8859-3 (Latin-3)
2010 @cindex Latin-3
2011 @cindex ISO 8859-3
2012 Latin-3 letters allowed in identifiers, with uppercase and lowercase
2013 equivalence.
2014
2015 @item ISO 8859-4 (Latin-4)
2016 @cindex Latin-4
2017 @cindex ISO 8859-4
2018 Latin-4 letters allowed in identifiers, with uppercase and lowercase
2019 equivalence.
2020
2021 @item ISO 8859-5 (Cyrillic)
2022 @cindex ISO 8859-5
2023 @cindex Cyrillic
2024 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
2025 lowercase equivalence.
2026
2027 @item ISO 8859-15 (Latin-9)
2028 @cindex ISO 8859-15
2029 @cindex Latin-9
2030 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
2031 lowercase equivalence
2032
2033 @item IBM PC (code page 437)
2034 @cindex code page 437
2035 This code page is the normal default for PCs in the U.S. It corresponds
2036 to the original IBM PC character set. This set has some, but not all, of
2037 the extended Latin-1 letters, but these letters do not have the same
2038 encoding as Latin-1. In this mode, these letters are allowed in
2039 identifiers with uppercase and lowercase equivalence.
2040
2041 @item IBM PC (code page 850)
2042 @cindex code page 850
2043 This code page is a modification of 437 extended to include all the
2044 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
2045 mode, all these letters are allowed in identifiers with uppercase and
2046 lowercase equivalence.
2047
2048 @item Full Upper 8-bit
2049 Any character in the range 80-FF allowed in identifiers, and all are
2050 considered distinct. In other words, there are no uppercase and lowercase
2051 equivalences in this range. This is useful in conjunction with
2052 certain encoding schemes used for some foreign character sets (e.g.
2053 the typical method of representing Chinese characters on the PC).
2054
2055 @item No Upper-Half
2056 No upper-half characters in the range 80-FF are allowed in identifiers.
2057 This gives Ada 83 compatibility for identifier names.
2058 @end table
2059
2060 @noindent
2061 For precise data on the encodings permitted, and the uppercase and lowercase
2062 equivalences that are recognized, see the file @file{csets.adb} in
2063 the GNAT compiler sources. You will need to obtain a full source release
2064 of GNAT to obtain this file.
2065
2066 @node Wide Character Encodings
2067 @subsection Wide Character Encodings
2068
2069 @noindent
2070 GNAT allows wide character codes to appear in character and string
2071 literals, and also optionally in identifiers, by means of the following
2072 possible encoding schemes:
2073
2074 @table @asis
2075
2076 @item Hex Coding
2077 In this encoding, a wide character is represented by the following five
2078 character sequence:
2079
2080 @smallexample
2081 ESC a b c d
2082 @end smallexample
2083
2084 @noindent
2085 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2086 characters (using uppercase letters) of the wide character code. For
2087 example, ESC A345 is used to represent the wide character with code
2088 @code{16#A345#}.
2089 This scheme is compatible with use of the full Wide_Character set.
2090
2091 @item Upper-Half Coding
2092 @cindex Upper-Half Coding
2093 The wide character with encoding @code{16#abcd#} where the upper bit is on
2094 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
2095 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
2096 character, but is not required to be in the upper half. This method can
2097 be also used for shift-JIS or EUC, where the internal coding matches the
2098 external coding.
2099
2100 @item Shift JIS Coding
2101 @cindex Shift JIS Coding
2102 A wide character is represented by a two-character sequence,
2103 @code{16#ab#} and
2104 @code{16#cd#}, with the restrictions described for upper-half encoding as
2105 described above. The internal character code is the corresponding JIS
2106 character according to the standard algorithm for Shift-JIS
2107 conversion. Only characters defined in the JIS code set table can be
2108 used with this encoding method.
2109
2110 @item EUC Coding
2111 @cindex EUC Coding
2112 A wide character is represented by a two-character sequence
2113 @code{16#ab#} and
2114 @code{16#cd#}, with both characters being in the upper half. The internal
2115 character code is the corresponding JIS character according to the EUC
2116 encoding algorithm. Only characters defined in the JIS code set table
2117 can be used with this encoding method.
2118
2119 @item UTF-8 Coding
2120 A wide character is represented using
2121 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
2122 10646-1/Am.2. Depending on the character value, the representation
2123 is a one, two, or three byte sequence:
2124 @smallexample
2125 @iftex
2126 @leftskip=.7cm
2127 @end iftex
2128 16#0000#-16#007f#: 2#0xxxxxxx#
2129 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
2130 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
2131
2132 @end smallexample
2133
2134 @noindent
2135 where the xxx bits correspond to the left-padded bits of the
2136 16-bit character value. Note that all lower half ASCII characters
2137 are represented as ASCII bytes and all upper half characters and
2138 other wide characters are represented as sequences of upper-half
2139 (The full UTF-8 scheme allows for encoding 31-bit characters as
2140 6-byte sequences, but in this implementation, all UTF-8 sequences
2141 of four or more bytes length will be treated as illegal).
2142 @item Brackets Coding
2143 In this encoding, a wide character is represented by the following eight
2144 character sequence:
2145
2146 @smallexample
2147 [ " a b c d " ]
2148 @end smallexample
2149
2150 @noindent
2151 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2152 characters (using uppercase letters) of the wide character code. For
2153 example, [``A345''] is used to represent the wide character with code
2154 @code{16#A345#}. It is also possible (though not required) to use the
2155 Brackets coding for upper half characters. For example, the code
2156 @code{16#A3#} can be represented as @code{[``A3'']}.
2157
2158 This scheme is compatible with use of the full Wide_Character set,
2159 and is also the method used for wide character encoding in the standard
2160 ACVC (Ada Compiler Validation Capability) test suite distributions.
2161
2162 @end table
2163
2164 @noindent
2165 Note: Some of these coding schemes do not permit the full use of the
2166 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
2167 use of the upper half of the Latin-1 set.
2168
2169 @node File Naming Rules
2170 @section File Naming Rules
2171
2172 @noindent
2173 The default file name is determined by the name of the unit that the
2174 file contains. The name is formed by taking the full expanded name of
2175 the unit and replacing the separating dots with hyphens and using
2176 ^lowercase^uppercase^ for all letters.
2177
2178 An exception arises if the file name generated by the above rules starts
2179 with one of the characters
2180 @ifset vms
2181 A,G,I, or S,
2182 @end ifset
2183 @ifclear vms
2184 a,g,i, or s,
2185 @end ifclear
2186 and the second character is a
2187 minus. In this case, the character ^tilde^dollar sign^ is used in place
2188 of the minus. The reason for this special rule is to avoid clashes with
2189 the standard names for child units of the packages System, Ada,
2190 Interfaces, and GNAT, which use the prefixes
2191 @ifset vms
2192 S- A- I- and G-
2193 @end ifset
2194 @ifclear vms
2195 s- a- i- and g-
2196 @end ifclear
2197 respectively.
2198
2199 The file extension is @file{.ads} for a spec and
2200 @file{.adb} for a body. The following list shows some
2201 examples of these rules.
2202
2203 @table @file
2204 @item main.ads
2205 Main (spec)
2206 @item main.adb
2207 Main (body)
2208 @item arith_functions.ads
2209 Arith_Functions (package spec)
2210 @item arith_functions.adb
2211 Arith_Functions (package body)
2212 @item func-spec.ads
2213 Func.Spec (child package spec)
2214 @item func-spec.adb
2215 Func.Spec (child package body)
2216 @item main-sub.adb
2217 Sub (subunit of Main)
2218 @item ^a~bad.adb^A$BAD.ADB^
2219 A.Bad (child package body)
2220 @end table
2221
2222 @noindent
2223 Following these rules can result in excessively long
2224 file names if corresponding
2225 unit names are long (for example, if child units or subunits are
2226 heavily nested). An option is available to shorten such long file names
2227 (called file name ``krunching''). This may be particularly useful when
2228 programs being developed with GNAT are to be used on operating systems
2229 with limited file name lengths. @xref{Using gnatkr}.
2230
2231 Of course, no file shortening algorithm can guarantee uniqueness over
2232 all possible unit names; if file name krunching is used, it is your
2233 responsibility to ensure no name clashes occur. Alternatively you
2234 can specify the exact file names that you want used, as described
2235 in the next section. Finally, if your Ada programs are migrating from a
2236 compiler with a different naming convention, you can use the gnatchop
2237 utility to produce source files that follow the GNAT naming conventions.
2238 (For details @pxref{Renaming Files Using gnatchop}.)
2239
2240 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2241 systems, case is not significant. So for example on @code{Windows XP}
2242 if the canonical name is @code{main-sub.adb}, you can use the file name
2243 @code{Main-Sub.adb} instead. However, case is significant for other
2244 operating systems, so for example, if you want to use other than
2245 canonically cased file names on a Unix system, you need to follow
2246 the procedures described in the next section.
2247
2248 @node Using Other File Names
2249 @section Using Other File Names
2250 @cindex File names
2251
2252 @noindent
2253 In the previous section, we have described the default rules used by
2254 GNAT to determine the file name in which a given unit resides. It is
2255 often convenient to follow these default rules, and if you follow them,
2256 the compiler knows without being explicitly told where to find all
2257 the files it needs.
2258
2259 However, in some cases, particularly when a program is imported from
2260 another Ada compiler environment, it may be more convenient for the
2261 programmer to specify which file names contain which units. GNAT allows
2262 arbitrary file names to be used by means of the Source_File_Name pragma.
2263 The form of this pragma is as shown in the following examples:
2264 @cindex Source_File_Name pragma
2265
2266 @smallexample @c ada
2267 @cartouche
2268 pragma Source_File_Name (My_Utilities.Stacks,
2269   Spec_File_Name => "myutilst_a.ada");
2270 pragma Source_File_name (My_Utilities.Stacks,
2271   Body_File_Name => "myutilst.ada");
2272 @end cartouche
2273 @end smallexample
2274
2275 @noindent
2276 As shown in this example, the first argument for the pragma is the unit
2277 name (in this example a child unit). The second argument has the form
2278 of a named association. The identifier
2279 indicates whether the file name is for a spec or a body;
2280 the file name itself is given by a string literal.
2281
2282 The source file name pragma is a configuration pragma, which means that
2283 normally it will be placed in the @file{gnat.adc}
2284 file used to hold configuration
2285 pragmas that apply to a complete compilation environment.
2286 For more details on how the @file{gnat.adc} file is created and used
2287 @pxref{Handling of Configuration Pragmas}
2288 @cindex @file{gnat.adc}
2289
2290 @ifclear vms
2291 GNAT allows completely arbitrary file names to be specified using the
2292 source file name pragma. However, if the file name specified has an
2293 extension other than @file{.ads} or @file{.adb} it is necessary to use
2294 a special syntax when compiling the file. The name in this case must be
2295 preceded by the special sequence @code{-x} followed by a space and the name
2296 of the language, here @code{ada}, as in:
2297
2298 @smallexample
2299 $ gcc -c -x ada peculiar_file_name.sim
2300 @end smallexample
2301 @end ifclear
2302
2303 @noindent
2304 @code{gnatmake} handles non-standard file names in the usual manner (the
2305 non-standard file name for the main program is simply used as the
2306 argument to gnatmake). Note that if the extension is also non-standard,
2307 then it must be included in the gnatmake command, it may not be omitted.
2308
2309 @node Alternative File Naming Schemes
2310 @section Alternative File Naming Schemes
2311 @cindex File naming schemes, alternative
2312 @cindex File names
2313
2314 In the previous section, we described the use of the @code{Source_File_Name}
2315 pragma to allow arbitrary names to be assigned to individual source files.
2316 However, this approach requires one pragma for each file, and especially in
2317 large systems can result in very long @file{gnat.adc} files, and also create
2318 a maintenance problem.
2319
2320 GNAT also provides a facility for specifying systematic file naming schemes
2321 other than the standard default naming scheme previously described. An
2322 alternative scheme for naming is specified by the use of
2323 @code{Source_File_Name} pragmas having the following format:
2324 @cindex Source_File_Name pragma
2325
2326 @smallexample @c ada
2327 pragma Source_File_Name (
2328    Spec_File_Name  => FILE_NAME_PATTERN
2329  [,Casing          => CASING_SPEC]
2330  [,Dot_Replacement => STRING_LITERAL]);
2331
2332 pragma Source_File_Name (
2333    Body_File_Name  => FILE_NAME_PATTERN
2334  [,Casing          => CASING_SPEC]
2335  [,Dot_Replacement => STRING_LITERAL]);
2336
2337 pragma Source_File_Name (
2338    Subunit_File_Name  => FILE_NAME_PATTERN
2339  [,Casing             => CASING_SPEC]
2340  [,Dot_Replacement    => STRING_LITERAL]);
2341
2342 FILE_NAME_PATTERN ::= STRING_LITERAL
2343 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2344 @end smallexample
2345
2346 @noindent
2347 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2348 It contains a single asterisk character, and the unit name is substituted
2349 systematically for this asterisk. The optional parameter
2350 @code{Casing} indicates
2351 whether the unit name is to be all upper-case letters, all lower-case letters,
2352 or mixed-case. If no
2353 @code{Casing} parameter is used, then the default is all
2354 ^lower-case^upper-case^.
2355
2356 The optional @code{Dot_Replacement} string is used to replace any periods
2357 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2358 argument is used then separating dots appear unchanged in the resulting
2359 file name.
2360 Although the above syntax indicates that the
2361 @code{Casing} argument must appear
2362 before the @code{Dot_Replacement} argument, but it
2363 is also permissible to write these arguments in the opposite order.
2364
2365 As indicated, it is possible to specify different naming schemes for
2366 bodies, specs, and subunits. Quite often the rule for subunits is the
2367 same as the rule for bodies, in which case, there is no need to give
2368 a separate @code{Subunit_File_Name} rule, and in this case the
2369 @code{Body_File_name} rule is used for subunits as well.
2370
2371 The separate rule for subunits can also be used to implement the rather
2372 unusual case of a compilation environment (e.g. a single directory) which
2373 contains a subunit and a child unit with the same unit name. Although
2374 both units cannot appear in the same partition, the Ada Reference Manual
2375 allows (but does not require) the possibility of the two units coexisting
2376 in the same environment.
2377
2378 The file name translation works in the following steps:
2379
2380 @itemize @bullet
2381
2382 @item
2383 If there is a specific @code{Source_File_Name} pragma for the given unit,
2384 then this is always used, and any general pattern rules are ignored.
2385
2386 @item
2387 If there is a pattern type @code{Source_File_Name} pragma that applies to
2388 the unit, then the resulting file name will be used if the file exists. If
2389 more than one pattern matches, the latest one will be tried first, and the
2390 first attempt resulting in a reference to a file that exists will be used.
2391
2392 @item
2393 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2394 for which the corresponding file exists, then the standard GNAT default
2395 naming rules are used.
2396
2397 @end itemize
2398
2399 @noindent
2400 As an example of the use of this mechanism, consider a commonly used scheme
2401 in which file names are all lower case, with separating periods copied
2402 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2403 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2404 two pragmas appear:
2405
2406 @smallexample @c ada
2407 pragma Source_File_Name
2408   (Spec_File_Name => "*.1.ada");
2409 pragma Source_File_Name
2410   (Body_File_Name => "*.2.ada");
2411 @end smallexample
2412
2413 @noindent
2414 The default GNAT scheme is actually implemented by providing the following
2415 default pragmas internally:
2416
2417 @smallexample @c ada
2418 pragma Source_File_Name
2419   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2420 pragma Source_File_Name
2421   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2422 @end smallexample
2423
2424 @noindent
2425 Our final example implements a scheme typically used with one of the
2426 Ada 83 compilers, where the separator character for subunits was ``__''
2427 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2428 by adding @file{.ADA}, and subunits by
2429 adding @file{.SEP}. All file names were
2430 upper case. Child units were not present of course since this was an
2431 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2432 the same double underscore separator for child units.
2433
2434 @smallexample @c ada
2435 pragma Source_File_Name
2436   (Spec_File_Name => "*_.ADA",
2437    Dot_Replacement => "__",
2438    Casing = Uppercase);
2439 pragma Source_File_Name
2440   (Body_File_Name => "*.ADA",
2441    Dot_Replacement => "__",
2442    Casing = Uppercase);
2443 pragma Source_File_Name
2444   (Subunit_File_Name => "*.SEP",
2445    Dot_Replacement => "__",
2446    Casing = Uppercase);
2447 @end smallexample
2448
2449 @node Generating Object Files
2450 @section Generating Object Files
2451
2452 @noindent
2453 An Ada program consists of a set of source files, and the first step in
2454 compiling the program is to generate the corresponding object files.
2455 These are generated by compiling a subset of these source files.
2456 The files you need to compile are the following:
2457
2458 @itemize @bullet
2459 @item
2460 If a package spec has no body, compile the package spec to produce the
2461 object file for the package.
2462
2463 @item
2464 If a package has both a spec and a body, compile the body to produce the
2465 object file for the package. The source file for the package spec need
2466 not be compiled in this case because there is only one object file, which
2467 contains the code for both the spec and body of the package.
2468
2469 @item
2470 For a subprogram, compile the subprogram body to produce the object file
2471 for the subprogram. The spec, if one is present, is as usual in a
2472 separate file, and need not be compiled.
2473
2474 @item
2475 @cindex Subunits
2476 In the case of subunits, only compile the parent unit. A single object
2477 file is generated for the entire subunit tree, which includes all the
2478 subunits.
2479
2480 @item
2481 Compile child units independently of their parent units
2482 (though, of course, the spec of all the ancestor unit must be present in order
2483 to compile a child unit).
2484
2485 @item
2486 @cindex Generics
2487 Compile generic units in the same manner as any other units. The object
2488 files in this case are small dummy files that contain at most the
2489 flag used for elaboration checking. This is because GNAT always handles generic
2490 instantiation by means of macro expansion. However, it is still necessary to
2491 compile generic units, for dependency checking and elaboration purposes.
2492 @end itemize
2493
2494 @noindent
2495 The preceding rules describe the set of files that must be compiled to
2496 generate the object files for a program. Each object file has the same
2497 name as the corresponding source file, except that the extension is
2498 @file{.o} as usual.
2499
2500 You may wish to compile other files for the purpose of checking their
2501 syntactic and semantic correctness. For example, in the case where a
2502 package has a separate spec and body, you would not normally compile the
2503 spec. However, it is convenient in practice to compile the spec to make
2504 sure it is error-free before compiling clients of this spec, because such
2505 compilations will fail if there is an error in the spec.
2506
2507 GNAT provides an option for compiling such files purely for the
2508 purposes of checking correctness; such compilations are not required as
2509 part of the process of building a program. To compile a file in this
2510 checking mode, use the @option{-gnatc} switch.
2511
2512 @node Source Dependencies
2513 @section Source Dependencies
2514
2515 @noindent
2516 A given object file clearly depends on the source file which is compiled
2517 to produce it. Here we are using @dfn{depends} in the sense of a typical
2518 @code{make} utility; in other words, an object file depends on a source
2519 file if changes to the source file require the object file to be
2520 recompiled.
2521 In addition to this basic dependency, a given object may depend on
2522 additional source files as follows:
2523
2524 @itemize @bullet
2525 @item
2526 If a file being compiled @code{with}'s a unit @var{X}, the object file
2527 depends on the file containing the spec of unit @var{X}. This includes
2528 files that are @code{with}'ed implicitly either because they are parents
2529 of @code{with}'ed child units or they are run-time units required by the
2530 language constructs used in a particular unit.
2531
2532 @item
2533 If a file being compiled instantiates a library level generic unit, the
2534 object file depends on both the spec and body files for this generic
2535 unit.
2536
2537 @item
2538 If a file being compiled instantiates a generic unit defined within a
2539 package, the object file depends on the body file for the package as
2540 well as the spec file.
2541
2542 @item
2543 @findex Inline
2544 @cindex @option{-gnatn} switch
2545 If a file being compiled contains a call to a subprogram for which
2546 pragma @code{Inline} applies and inlining is activated with the
2547 @option{-gnatn} switch, the object file depends on the file containing the
2548 body of this subprogram as well as on the file containing the spec. Note
2549 that for inlining to actually occur as a result of the use of this switch,
2550 it is necessary to compile in optimizing mode.
2551
2552 @cindex @option{-gnatN} switch
2553 The use of @option{-gnatN} activates a more extensive inlining optimization
2554 that is performed by the front end of the compiler. This inlining does
2555 not require that the code generation be optimized. Like @option{-gnatn},
2556 the use of this switch generates additional dependencies.
2557 Note that
2558 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2559 to specify both options.
2560
2561 @item
2562 If an object file O  depends on the proper body of a subunit through inlining
2563 or instantiation, it depends on the parent unit of the subunit. This means that
2564 any modification of the parent unit or one of its subunits affects the
2565 compilation of O.
2566
2567 @item
2568 The object file for a parent unit depends on all its subunit body files.
2569
2570 @item
2571 The previous two rules meant that for purposes of computing dependencies and
2572 recompilation, a body and all its subunits are treated as an indivisible whole.
2573
2574 @noindent
2575 These rules are applied transitively: if unit @code{A} @code{with}'s
2576 unit @code{B}, whose elaboration calls an inlined procedure in package
2577 @code{C}, the object file for unit @code{A} will depend on the body of
2578 @code{C}, in file @file{c.adb}.
2579
2580 The set of dependent files described by these rules includes all the
2581 files on which the unit is semantically dependent, as described in the
2582 Ada 95 Language Reference Manual. However, it is a superset of what the
2583 ARM describes, because it includes generic, inline, and subunit dependencies.
2584
2585 An object file must be recreated by recompiling the corresponding source
2586 file if any of the source files on which it depends are modified. For
2587 example, if the @code{make} utility is used to control compilation,
2588 the rule for an Ada object file must mention all the source files on
2589 which the object file depends, according to the above definition.
2590 The determination of the necessary
2591 recompilations is done automatically when one uses @code{gnatmake}.
2592 @end itemize
2593
2594 @node The Ada Library Information Files
2595 @section The Ada Library Information Files
2596 @cindex Ada Library Information files
2597 @cindex @file{ALI} files
2598
2599 @noindent
2600 Each compilation actually generates two output files. The first of these
2601 is the normal object file that has a @file{.o} extension. The second is a
2602 text file containing full dependency information. It has the same
2603 name as the source file, but an @file{.ali} extension.
2604 This file is known as the Ada Library Information (@file{ALI}) file.
2605 The following information is contained in the @file{ALI} file.
2606
2607 @itemize @bullet
2608 @item
2609 Version information (indicates which version of GNAT was used to compile
2610 the unit(s) in question)
2611
2612 @item
2613 Main program information (including priority and time slice settings,
2614 as well as the wide character encoding used during compilation).
2615
2616 @item
2617 List of arguments used in the @code{gcc} command for the compilation
2618
2619 @item
2620 Attributes of the unit, including configuration pragmas used, an indication
2621 of whether the compilation was successful, exception model used etc.
2622
2623 @item
2624 A list of relevant restrictions applying to the unit (used for consistency)
2625 checking.
2626
2627 @item
2628 Categorization information (e.g. use of pragma @code{Pure}).
2629
2630 @item
2631 Information on all @code{with}'ed units, including presence of
2632 @code{Elaborate} or @code{Elaborate_All} pragmas.
2633
2634 @item
2635 Information from any @code{Linker_Options} pragmas used in the unit
2636
2637 @item
2638 Information on the use of @code{Body_Version} or @code{Version}
2639 attributes in the unit.
2640
2641 @item
2642 Dependency information. This is a list of files, together with
2643 time stamp and checksum information. These are files on which
2644 the unit depends in the sense that recompilation is required
2645 if any of these units are modified.
2646
2647 @item
2648 Cross-reference data. Contains information on all entities referenced
2649 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2650 provide cross-reference information.
2651
2652 @end itemize
2653
2654 @noindent
2655 For a full detailed description of the format of the @file{ALI} file,
2656 see the source of the body of unit @code{Lib.Writ}, contained in file
2657 @file{lib-writ.adb} in the GNAT compiler sources.
2658
2659 @node Binding an Ada Program
2660 @section Binding an Ada Program
2661
2662 @noindent
2663 When using languages such as C and C++, once the source files have been
2664 compiled the only remaining step in building an executable program
2665 is linking the object modules together. This means that it is possible to
2666 link an inconsistent version of a program, in which two units have
2667 included different versions of the same header.
2668
2669 The rules of Ada do not permit such an inconsistent program to be built.
2670 For example, if two clients have different versions of the same package,
2671 it is illegal to build a program containing these two clients.
2672 These rules are enforced by the GNAT binder, which also determines an
2673 elaboration order consistent with the Ada rules.
2674
2675 The GNAT binder is run after all the object files for a program have
2676 been created. It is given the name of the main program unit, and from
2677 this it determines the set of units required by the program, by reading the
2678 corresponding ALI files. It generates error messages if the program is
2679 inconsistent or if no valid order of elaboration exists.
2680
2681 If no errors are detected, the binder produces a main program, in Ada by
2682 default, that contains calls to the elaboration procedures of those
2683 compilation unit that require them, followed by
2684 a call to the main program. This Ada program is compiled to generate the
2685 object file for the main program. The name of
2686 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2687 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2688 main program unit.
2689
2690 Finally, the linker is used to build the resulting executable program,
2691 using the object from the main program from the bind step as well as the
2692 object files for the Ada units of the program.
2693
2694 @node Mixed Language Programming
2695 @section Mixed Language Programming
2696 @cindex Mixed Language Programming
2697
2698 @noindent
2699 This section describes how to develop a mixed-language program,
2700 specifically one that comprises units in both Ada and C.
2701
2702 @menu
2703 * Interfacing to C::
2704 * Calling Conventions::
2705 @end menu
2706
2707 @node Interfacing to C
2708 @subsection Interfacing to C
2709 @noindent
2710 Interfacing Ada with a foreign language such as C involves using
2711 compiler directives to import and/or export entity definitions in each
2712 language---using @code{extern} statements in C, for instance, and the
2713 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.  For
2714 a full treatment of these topics, read Appendix B, section 1 of the Ada
2715 95 Language Reference Manual.
2716
2717 There are two ways to build a program using GNAT that contains some Ada
2718 sources and some foreign language sources, depending on whether or not
2719 the main subprogram is written in Ada.  Here is a source example with
2720 the main subprogram in Ada:
2721
2722 @smallexample
2723 /* file1.c */
2724 #include <stdio.h>
2725
2726 void print_num (int num)
2727 @{
2728   printf ("num is %d.\n", num);
2729   return;
2730 @}
2731
2732 /* file2.c */
2733
2734 /* num_from_Ada is declared in my_main.adb */
2735 extern int num_from_Ada;
2736
2737 int get_num (void)
2738 @{
2739   return num_from_Ada;
2740 @}
2741 @end smallexample
2742
2743 @smallexample @c ada
2744 --  my_main.adb
2745 procedure My_Main is
2746
2747    --  Declare then export an Integer entity called num_from_Ada
2748    My_Num : Integer := 10;
2749    pragma Export (C, My_Num, "num_from_Ada");
2750
2751    --  Declare an Ada function spec for Get_Num, then use
2752    --  C function get_num for the implementation.
2753    function Get_Num return Integer;
2754    pragma Import (C, Get_Num, "get_num");
2755
2756    --  Declare an Ada procedure spec for Print_Num, then use
2757    --  C function print_num for the implementation.
2758    procedure Print_Num (Num : Integer);
2759    pragma Import (C, Print_Num, "print_num");
2760
2761 begin
2762    Print_Num (Get_Num);
2763 end My_Main;
2764 @end smallexample
2765
2766 @enumerate
2767 @item
2768 To build this example, first compile the foreign language files to
2769 generate object files:
2770 @smallexample
2771 gcc -c file1.c
2772 gcc -c file2.c
2773 @end smallexample
2774
2775 @item
2776 Then, compile the Ada units to produce a set of object files and ALI
2777 files:
2778 @smallexample
2779 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2780 @end smallexample
2781
2782 @item
2783 Run the Ada binder on the Ada main program:
2784 @smallexample
2785 gnatbind my_main.ali
2786 @end smallexample
2787
2788 @item
2789 Link the Ada main program, the Ada objects and the other language
2790 objects:
2791 @smallexample
2792 gnatlink my_main.ali file1.o file2.o
2793 @end smallexample
2794 @end enumerate
2795
2796 The last three steps can be grouped in a single command:
2797 @smallexample
2798 gnatmake my_main.adb -largs file1.o file2.o
2799 @end smallexample
2800
2801 @cindex Binder output file
2802 @noindent
2803 If the main program is in a language other than Ada, then you may have
2804 more than one entry point into the Ada subsystem. You must use a special
2805 binder option to generate callable routines that initialize and
2806 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2807 Calls to the initialization and finalization routines must be inserted
2808 in the main program, or some other appropriate point in the code. The
2809 call to initialize the Ada units must occur before the first Ada
2810 subprogram is called, and the call to finalize the Ada units must occur
2811 after the last Ada subprogram returns. The binder will place the
2812 initialization and finalization subprograms into the
2813 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2814 sources.  To illustrate, we have the following example:
2815
2816 @smallexample
2817 /* main.c */
2818 extern void adainit (void);
2819 extern void adafinal (void);
2820 extern int add (int, int);
2821 extern int sub (int, int);
2822
2823 int main (int argc, char *argv[])
2824 @{
2825   int a = 21, b = 7;
2826
2827   adainit();
2828
2829   /* Should print "21 + 7 = 28" */
2830   printf ("%d + %d = %d\n", a, b, add (a, b));
2831   /* Should print "21 - 7 = 14" */
2832   printf ("%d - %d = %d\n", a, b, sub (a, b));
2833
2834   adafinal();
2835 @}
2836 @end smallexample
2837
2838 @smallexample @c ada
2839 --  unit1.ads
2840 package Unit1 is
2841    function Add (A, B : Integer) return Integer;
2842    pragma Export (C, Add, "add");
2843 end Unit1;
2844
2845 --  unit1.adb
2846 package body Unit1 is
2847    function Add (A, B : Integer) return Integer is
2848    begin
2849       return A + B;
2850    end Add;
2851 end Unit1;
2852
2853 --  unit2.ads
2854 package Unit2 is
2855    function Sub (A, B : Integer) return Integer;
2856    pragma Export (C, Sub, "sub");
2857 end Unit2;
2858
2859 --  unit2.adb
2860 package body Unit2 is
2861    function Sub (A, B : Integer) return Integer is
2862    begin
2863       return A - B;
2864    end Sub;
2865 end Unit2;
2866 @end smallexample
2867
2868 @enumerate
2869 @item
2870 The build procedure for this application is similar to the last
2871 example's.  First, compile the foreign language files to generate object
2872 files:
2873 @smallexample
2874 gcc -c main.c
2875 @end smallexample
2876
2877 @item
2878 Next, compile the Ada units to produce a set of object files and ALI
2879 files:
2880 @smallexample
2881 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2882 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2883 @end smallexample
2884
2885 @item
2886 Run the Ada binder on every generated ALI file.  Make sure to use the
2887 @option{-n} option to specify a foreign main program:
2888 @smallexample
2889 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2890 @end smallexample
2891
2892 @item
2893 Link the Ada main program, the Ada objects and the foreign language
2894 objects. You need only list the last ALI file here:
2895 @smallexample
2896 gnatlink unit2.ali main.o -o exec_file
2897 @end smallexample
2898
2899 This procedure yields a binary executable called @file{exec_file}.
2900 @end enumerate
2901
2902 @node Calling Conventions
2903 @subsection Calling Conventions
2904 @cindex Foreign Languages
2905 @cindex Calling Conventions
2906 GNAT follows standard calling sequence conventions and will thus interface
2907 to any other language that also follows these conventions. The following
2908 Convention identifiers are recognized by GNAT:
2909
2910 @table @code
2911 @cindex Interfacing to Ada
2912 @cindex Other Ada compilers
2913 @cindex Convention Ada
2914 @item Ada
2915 This indicates that the standard Ada calling sequence will be
2916 used and all Ada data items may be passed without any limitations in the
2917 case where GNAT is used to generate both the caller and callee. It is also
2918 possible to mix GNAT generated code and code generated by another Ada
2919 compiler. In this case, the data types should be restricted to simple
2920 cases, including primitive types. Whether complex data types can be passed
2921 depends on the situation. Probably it is safe to pass simple arrays, such
2922 as arrays of integers or floats. Records may or may not work, depending
2923 on whether both compilers lay them out identically. Complex structures
2924 involving variant records, access parameters, tasks, or protected types,
2925 are unlikely to be able to be passed.
2926
2927 Note that in the case of GNAT running
2928 on a platform that supports DEC Ada 83, a higher degree of compatibility
2929 can be guaranteed, and in particular records are layed out in an identical
2930 manner in the two compilers. Note also that if output from two different
2931 compilers is mixed, the program is responsible for dealing with elaboration
2932 issues. Probably the safest approach is to write the main program in the
2933 version of Ada other than GNAT, so that it takes care of its own elaboration
2934 requirements, and then call the GNAT-generated adainit procedure to ensure
2935 elaboration of the GNAT components. Consult the documentation of the other
2936 Ada compiler for further details on elaboration.
2937
2938 However, it is not possible to mix the tasking run time of GNAT and
2939 DEC Ada 83, All the tasking operations must either be entirely within
2940 GNAT compiled sections of the program, or entirely within DEC Ada 83
2941 compiled sections of the program.
2942
2943 @cindex Interfacing to Assembly
2944 @cindex Convention Assembler
2945 @item Assembler
2946 Specifies assembler as the convention. In practice this has the
2947 same effect as convention Ada (but is not equivalent in the sense of being
2948 considered the same convention).
2949
2950 @cindex Convention Asm
2951 @findex Asm
2952 @item Asm
2953 Equivalent to Assembler.
2954
2955 @cindex Interfacing to COBOL
2956 @cindex Convention COBOL
2957 @findex COBOL
2958 @item COBOL
2959 Data will be passed according to the conventions described
2960 in section B.4 of the Ada 95 Reference Manual.
2961
2962 @findex C
2963 @cindex Interfacing to C
2964 @cindex Convention C
2965 @item C
2966 Data will be passed according to the conventions described
2967 in section B.3 of the Ada 95 Reference Manual.
2968
2969 @findex C varargs function
2970 @cindex Intefacing to C varargs function
2971 @cindex varargs function intefacs
2972 @item C varargs function
2973 In C, @code{varargs} allows a function to take a variable number of
2974 arguments. There is no direct equivalent in this to Ada. One
2975 approach that can be used is to create a C wrapper for each
2976 different profile and then interface to this C wrapper. For
2977 example, to print an @code{int} value using @code{printf},
2978 create a C function @code{printfi} that takes two arguments, a
2979 pointer to a string and an int, and calls @code{printf}.
2980 Then in the Ada program, use pragma @code{Import} to
2981 interface to printfi.
2982
2983 It may work on some platforms to directly interface to
2984 a @code{varargs} function by providing a specific Ada profile
2985 for a a particular call. However, this does not work on
2986 all platforms, since there is no guarantee that the
2987 calling sequence for a two argument normal C function
2988 is the same as for calling a @code{varargs} C function with
2989 the same two arguments.
2990
2991 @cindex Convention Default
2992 @findex Default
2993 @item Default
2994 Equivalent to C.
2995
2996 @cindex Convention External
2997 @findex External
2998 @item External
2999 Equivalent to C.
3000
3001 @findex C++
3002 @cindex Interfacing to C++
3003 @cindex Convention C++
3004 @item CPP
3005 This stands for C++. For most purposes this is identical to C.
3006 See the separate description of the specialized GNAT pragmas relating to
3007 C++ interfacing for further details.
3008
3009 @findex Fortran
3010 @cindex Interfacing to Fortran
3011 @cindex Convention Fortran
3012 @item Fortran
3013 Data will be passed according to the conventions described
3014 in section B.5 of the Ada 95 Reference Manual.
3015
3016 @item Intrinsic
3017 This applies to an intrinsic operation, as defined in the Ada 95
3018 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
3019 this means that the body of the subprogram is provided by the compiler itself,
3020 usually by means of an efficient code sequence, and that the user does not
3021 supply an explicit body for it. In an application program, the pragma can
3022 only be applied to the following two sets of names, which the GNAT compiler
3023 recognizes.
3024
3025 @itemize @bullet
3026 @item
3027 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
3028 Arithmetic.  The corresponding subprogram declaration must have
3029 two formal parameters. The
3030 first one must be a signed integer type or a modular type with a binary
3031 modulus, and the second parameter must be of type Natural.
3032 The return type must be the same as the type of the first argument. The size
3033 of this type can only be 8, 16, 32, or 64.
3034 @item binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
3035 The corresponding operator declaration must have parameters and result type
3036 that have the same root numeric type (for example, all three are long_float
3037 types). This simplifies the definition of operations that use type checking
3038 to perform dimensional checks:
3039
3040 @smallexample @c ada
3041 type Distance is new Long_Float;
3042 type Time     is new Long_Float;
3043 type Velocity is new Long_Float;
3044 function "/" (D : Distance; T : Time)
3045   return Velocity;
3046 pragma Import (Intrinsic, "/");
3047 @end smallexample
3048
3049 @noindent
3050 This common idiom is often programmed with a generic definition and an
3051 explicit body. The pragma makes it simpler to introduce such declarations.
3052 It incurs no overhead in compilation time or code size, because it is
3053 implemented as a single machine instruction.
3054 @end itemize
3055 @noindent
3056
3057 @ifset unw
3058 @findex Stdcall
3059 @cindex Convention Stdcall
3060 @item Stdcall
3061 This is relevant only to NT/Win95 implementations of GNAT,
3062 and specifies that the Stdcall calling sequence will be used, as defined
3063 by the NT API.
3064
3065 @findex DLL
3066 @cindex Convention DLL
3067 @item DLL
3068 This is equivalent to Stdcall.
3069
3070 @findex Win32
3071 @cindex Convention Win32
3072 @item Win32
3073 This is equivalent to Stdcall.
3074 @end ifset
3075
3076 @findex Stubbed
3077 @cindex Convention Stubbed
3078 @item Stubbed
3079 This is a special convention that indicates that the compiler
3080 should provide a stub body that raises @code{Program_Error}.
3081 @end table
3082
3083 @noindent
3084 GNAT additionally provides a useful pragma @code{Convention_Identifier}
3085 that can be used to parametrize conventions and allow additional synonyms
3086 to be specified. For example if you have legacy code in which the convention
3087 identifier Fortran77 was used for Fortran, you can use the configuration
3088 pragma:
3089
3090 @smallexample @c ada
3091 pragma Convention_Identifier (Fortran77, Fortran);
3092 @end smallexample
3093
3094 @noindent
3095 And from now on the identifier Fortran77 may be used as a convention
3096 identifier (for example in an @code{Import} pragma) with the same
3097 meaning as Fortran.
3098
3099 @node Building Mixed Ada & C++ Programs
3100 @section Building Mixed Ada & C++ Programs
3101
3102 @noindent
3103 A programmer inexperienced with mixed-language development may find that
3104 building an application containing both Ada and C++ code can be a
3105 challenge. As a matter of fact, interfacing with C++ has not been
3106 standardized in the Ada 95 Reference Manual due to the immaturity of --
3107 and lack of standards for -- C++ at the time. This section gives a few
3108 hints that should make this task easier. The first section addresses
3109 the differences regarding interfacing with C. The second section
3110 looks into the delicate problem of linking the complete application from
3111 its Ada and C++ parts. The last section gives some hints on how the GNAT
3112 run time can be adapted in order to allow inter-language dispatching
3113 with a new C++ compiler.
3114
3115 @menu
3116 * Interfacing to C++::
3117 * Linking a Mixed C++ & Ada Program::
3118 * A Simple Example::
3119 * Adapting the Run Time to a New C++ Compiler::
3120 @end menu
3121
3122 @node Interfacing to C++
3123 @subsection Interfacing to C++
3124
3125 @noindent
3126 GNAT supports interfacing with C++ compilers generating code that is
3127 compatible with the standard Application Binary Interface of the given
3128 platform.
3129
3130 @noindent
3131 Interfacing can be done at 3 levels: simple data, subprograms, and
3132 classes. In the first two cases, GNAT offers a specific @var{Convention
3133 CPP} that behaves exactly like @var{Convention C}. Usually, C++ mangles
3134 the names of subprograms, and currently, GNAT does not provide any help
3135 to solve the demangling problem. This problem can be addressed in two
3136 ways:
3137 @itemize @bullet
3138 @item
3139 by modifying the C++ code in order to force a C convention using
3140 the @code{extern "C"} syntax.
3141
3142 @item
3143 by figuring out the mangled name and use it as the Link_Name argument of
3144 the pragma import.
3145 @end itemize
3146
3147 @noindent
3148 Interfacing at the class level can be achieved by using the GNAT specific
3149 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
3150 Reference Manual for additional information.
3151
3152 @node Linking a Mixed C++ & Ada Program
3153 @subsection Linking a Mixed C++ & Ada Program
3154
3155 @noindent
3156 Usually the linker of the C++ development system must be used to link
3157 mixed applications because most C++ systems will resolve elaboration
3158 issues (such as calling constructors on global class instances)
3159 transparently during the link phase. GNAT has been adapted to ease the
3160 use of a foreign linker for the last phase. Three cases can be
3161 considered:
3162 @enumerate
3163
3164 @item
3165 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3166 The C++ linker can simply be called by using the C++ specific driver
3167 called @code{c++}. Note that this setup is not very common because it
3168 may involve recompiling the whole GCC tree from sources, which makes it
3169 harder to upgrade the compilation system for one language without
3170 destabilizing the other.
3171
3172 @smallexample
3173 $ c++ -c file1.C
3174 $ c++ -c file2.C
3175 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3176 @end smallexample
3177
3178 @item
3179 Using GNAT and G++ from two different GCC installations: If both
3180 compilers are on the PATH, the previous method may be used. It is
3181 important to note that environment variables such as C_INCLUDE_PATH,
3182 GCC_EXEC_PREFIX, BINUTILS_ROOT, and GCC_ROOT will affect both compilers
3183 at the same time and may make one of the two compilers operate
3184 improperly if set during invocation of the wrong compiler.  It is also
3185 very important that the linker uses the proper @file{libgcc.a} GCC
3186 library -- that is, the one from the C++ compiler installation. The
3187 implicit link command as suggested in the gnatmake command from the
3188 former example can be replaced by an explicit link command with the
3189 full-verbosity option in order to verify which library is used:
3190 @smallexample
3191 $ gnatbind ada_unit
3192 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3193 @end smallexample
3194 If there is a problem due to interfering environment variables, it can
3195 be worked around by using an intermediate script. The following example
3196 shows the proper script to use when GNAT has not been installed at its
3197 default location and g++ has been installed at its default location:
3198
3199 @smallexample
3200 $ cat ./my_script
3201 #!/bin/sh
3202 unset BINUTILS_ROOT
3203 unset GCC_ROOT
3204 c++ $*
3205 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3206 @end smallexample
3207
3208 @item
3209 Using a non-GNU C++ compiler: The commands previously described can be
3210 used to insure that the C++ linker is used. Nonetheless, you need to add
3211 the path to libgcc explicitly, since some libraries needed by GNAT are
3212 located in this directory:
3213
3214 @smallexample
3215 $ cat ./my_script
3216 #!/bin/sh
3217 CC $* `gcc -print-libgcc-file-name`
3218 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3219 @end smallexample
3220
3221 Where CC is the name of the non-GNU C++ compiler.
3222
3223 @end enumerate
3224
3225 @node A Simple Example
3226 @subsection  A Simple Example
3227 @noindent
3228 The following example, provided as part of the GNAT examples, shows how
3229 to achieve procedural interfacing between Ada and C++ in both
3230 directions. The C++ class A has two methods. The first method is exported
3231 to Ada by the means of an extern C wrapper function. The second method
3232 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3233 a limited record with a layout comparable to the C++ class. The Ada
3234 subprogram, in turn, calls the C++ method. So, starting from the C++
3235 main program, the process passes back and forth between the two
3236 languages.
3237
3238 @noindent
3239 Here are the compilation commands:
3240 @smallexample
3241 $ gnatmake -c simple_cpp_interface
3242 $ c++ -c cpp_main.C
3243 $ c++ -c ex7.C
3244 $ gnatbind -n simple_cpp_interface
3245 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3246       -lstdc++ ex7.o cpp_main.o
3247 @end smallexample
3248
3249 @noindent
3250 Here are the corresponding sources:
3251 @smallexample
3252
3253 //cpp_main.C
3254
3255 #include "ex7.h"
3256
3257 extern "C" @{
3258   void adainit (void);
3259   void adafinal (void);
3260   void method1 (A *t);
3261 @}
3262
3263 void method1 (A *t)
3264 @{
3265   t->method1 ();
3266 @}
3267
3268 int main ()
3269 @{
3270   A obj;
3271   adainit ();
3272   obj.method2 (3030);
3273   adafinal ();
3274 @}
3275
3276 //ex7.h
3277
3278 class Origin @{
3279  public:
3280   int o_value;
3281 @};
3282 class A : public Origin @{
3283  public:
3284   void method1 (void);
3285   virtual void method2 (int v);
3286   A();
3287   int   a_value;
3288 @};
3289
3290 //ex7.C
3291
3292 #include "ex7.h"
3293 #include <stdio.h>
3294
3295 extern "C" @{ void ada_method2 (A *t, int v);@}
3296
3297 void A::method1 (void)
3298 @{
3299   a_value = 2020;
3300   printf ("in A::method1, a_value = %d \n",a_value);
3301
3302 @}
3303
3304 void A::method2 (int v)
3305 @{
3306    ada_method2 (this, v);
3307    printf ("in A::method2, a_value = %d \n",a_value);
3308
3309 @}
3310
3311 A::A(void)
3312 @{
3313    a_value = 1010;
3314   printf ("in A::A, a_value = %d \n",a_value);
3315 @}
3316
3317 -- Ada sources
3318 @b{package} @b{body} Simple_Cpp_Interface @b{is}
3319
3320    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
3321    @b{begin}
3322       Method1 (This);
3323       This.A_Value := V;
3324    @b{end} Ada_Method2;
3325
3326 @b{end} Simple_Cpp_Interface;
3327
3328 @b{package} Simple_Cpp_Interface @b{is}
3329    @b{type} A @b{is} @b{limited}
3330       @b{record}
3331          O_Value : Integer;
3332          A_Value : Integer;
3333       @b{end} @b{record};
3334    @b{pragma} Convention (C, A);
3335
3336    @b{procedure} Method1 (This : @b{in} @b{out} A);
3337    @b{pragma} Import (C, Method1);
3338
3339    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
3340    @b{pragma} Export (C, Ada_Method2);
3341
3342 @b{end} Simple_Cpp_Interface;
3343 @end smallexample
3344
3345 @node Adapting the Run Time to a New C++ Compiler
3346 @subsection Adapting the Run Time to a New C++ Compiler
3347 @noindent
3348 GNAT offers the capability to derive Ada 95 tagged types directly from
3349 preexisting C++ classes and . See ``Interfacing with C++'' in the
3350 @cite{GNAT Reference Manual}. The mechanism used by GNAT for achieving
3351 such a goal
3352 has been made user configurable through a GNAT library unit
3353 @code{Interfaces.CPP}. The default version of this file is adapted to
3354 the GNU C++ compiler. Internal knowledge of the virtual
3355 table layout used by the new C++ compiler is needed to configure
3356 properly this unit. The Interface of this unit is known by the compiler
3357 and cannot be changed except for the value of the constants defining the
3358 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
3359 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
3360 of this unit for more details.
3361
3362 @node Comparison between GNAT and C/C++ Compilation Models
3363 @section Comparison between GNAT and C/C++ Compilation Models
3364
3365 @noindent
3366 The GNAT model of compilation is close to the C and C++ models. You can
3367 think of Ada specs as corresponding to header files in C. As in C, you
3368 don't need to compile specs; they are compiled when they are used. The
3369 Ada @code{with} is similar in effect to the @code{#include} of a C
3370 header.
3371
3372 One notable difference is that, in Ada, you may compile specs separately
3373 to check them for semantic and syntactic accuracy. This is not always
3374 possible with C headers because they are fragments of programs that have
3375 less specific syntactic or semantic rules.
3376
3377 The other major difference is the requirement for running the binder,
3378 which performs two important functions. First, it checks for
3379 consistency. In C or C++, the only defense against assembling
3380 inconsistent programs lies outside the compiler, in a makefile, for
3381 example. The binder satisfies the Ada requirement that it be impossible
3382 to construct an inconsistent program when the compiler is used in normal
3383 mode.
3384
3385 @cindex Elaboration order control
3386 The other important function of the binder is to deal with elaboration
3387 issues. There are also elaboration issues in C++ that are handled
3388 automatically. This automatic handling has the advantage of being
3389 simpler to use, but the C++ programmer has no control over elaboration.
3390 Where @code{gnatbind} might complain there was no valid order of
3391 elaboration, a C++ compiler would simply construct a program that
3392 malfunctioned at run time.
3393
3394 @node Comparison between GNAT and Conventional Ada Library Models
3395 @section Comparison between GNAT and Conventional Ada Library Models
3396
3397 @noindent
3398 This section is intended to be useful to Ada programmers who have
3399 previously used an Ada compiler implementing the traditional Ada library
3400 model, as described in the Ada 95 Language Reference Manual. If you
3401 have not used such a system, please go on to the next section.
3402
3403 @cindex GNAT library
3404 In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
3405 source files themselves acts as the library. Compiling Ada programs does
3406 not generate any centralized information, but rather an object file and
3407 a ALI file, which are of interest only to the binder and linker.
3408 In a traditional system, the compiler reads information not only from
3409 the source file being compiled, but also from the centralized library.
3410 This means that the effect of a compilation depends on what has been
3411 previously compiled. In particular:
3412
3413 @itemize @bullet
3414 @item
3415 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3416 to the version of the unit most recently compiled into the library.
3417
3418 @item
3419 Inlining is effective only if the necessary body has already been
3420 compiled into the library.
3421
3422 @item
3423 Compiling a unit may obsolete other units in the library.
3424 @end itemize
3425
3426 @noindent
3427 In GNAT, compiling one unit never affects the compilation of any other
3428 units because the compiler reads only source files. Only changes to source
3429 files can affect the results of a compilation. In particular:
3430
3431 @itemize @bullet
3432 @item
3433 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3434 to the source version of the unit that is currently accessible to the
3435 compiler.
3436
3437 @item
3438 @cindex Inlining
3439 Inlining requires the appropriate source files for the package or
3440 subprogram bodies to be available to the compiler. Inlining is always
3441 effective, independent of the order in which units are complied.
3442
3443 @item
3444 Compiling a unit never affects any other compilations. The editing of
3445 sources may cause previous compilations to be out of date if they
3446 depended on the source file being modified.
3447 @end itemize
3448
3449 @noindent
3450 The most important result of these differences is that order of compilation
3451 is never significant in GNAT. There is no situation in which one is
3452 required to do one compilation before another. What shows up as order of
3453 compilation requirements in the traditional Ada library becomes, in
3454 GNAT, simple source dependencies; in other words, there is only a set
3455 of rules saying what source files must be present when a file is
3456 compiled.
3457
3458 @ifset vms
3459 @node Placement of temporary files
3460 @section Placement of temporary files
3461 @cindex Temporary files (user control over placement)
3462
3463 @noindent
3464 GNAT creates temporary files in the directory designated by the environment
3465 variable @env{TMPDIR}.
3466 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3467 for detailed information on how environment variables are resolved.
3468 For most users the easiest way to make use of this feature is to simply
3469 define @env{TMPDIR} as a job level logical name).
3470 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3471 for compiler temporary files, then you can include something like the
3472 following command in your @file{LOGIN.COM} file:
3473
3474 @smallexample
3475 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3476 @end smallexample
3477
3478 @noindent
3479 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3480 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3481 designated by @env{TEMP}.
3482 If none of these environment variables are defined then GNAT uses the
3483 directory designated by the logical name @code{SYS$SCRATCH:}
3484 (by default the user's home directory). If all else fails
3485 GNAT uses the current directory for temporary files.
3486 @end ifset
3487
3488
3489 @c *************************
3490 @node Compiling Using gcc
3491 @chapter Compiling Using @code{gcc}
3492
3493 @noindent
3494 This chapter discusses how to compile Ada programs using the @code{gcc}
3495 command. It also describes the set of switches
3496 that can be used to control the behavior of the compiler.
3497 @menu
3498 * Compiling Programs::
3499 * Switches for gcc::
3500 * Search Paths and the Run-Time Library (RTL)::
3501 * Order of Compilation Issues::
3502 * Examples::
3503 @end menu
3504
3505 @node Compiling Programs
3506 @section Compiling Programs
3507
3508 @noindent
3509 The first step in creating an executable program is to compile the units
3510 of the program using the @code{gcc} command. You must compile the
3511 following files:
3512
3513 @itemize @bullet
3514 @item
3515 the body file (@file{.adb}) for a library level subprogram or generic
3516 subprogram
3517
3518 @item
3519 the spec file (@file{.ads}) for a library level package or generic
3520 package that has no body
3521
3522 @item
3523 the body file (@file{.adb}) for a library level package
3524 or generic package that has a body
3525
3526 @end itemize
3527
3528 @noindent
3529 You need @emph{not} compile the following files
3530
3531 @itemize @bullet
3532
3533 @item
3534 the spec of a library unit which has a body
3535
3536 @item
3537 subunits
3538 @end itemize
3539
3540 @noindent
3541 because they are compiled as part of compiling related units. GNAT
3542 package specs
3543 when the corresponding body is compiled, and subunits when the parent is
3544 compiled.
3545
3546 @cindex cannot generate code
3547 If you attempt to compile any of these files, you will get one of the
3548 following error messages (where fff is the name of the file you compiled):
3549
3550 @smallexample
3551 cannot generate code for file @var{fff} (package spec)
3552 to check package spec, use -gnatc
3553
3554 cannot generate code for file @var{fff} (missing subunits)
3555 to check parent unit, use -gnatc
3556
3557 cannot generate code for file @var{fff} (subprogram spec)
3558 to check subprogram spec, use -gnatc
3559
3560 cannot generate code for file @var{fff} (subunit)
3561 to check subunit, use -gnatc
3562 @end smallexample
3563
3564 @noindent
3565 As indicated by the above error messages, if you want to submit
3566 one of these files to the compiler to check for correct semantics
3567 without generating code, then use the @option{-gnatc} switch.
3568
3569 The basic command for compiling a file containing an Ada unit is
3570
3571 @smallexample
3572 $ gcc -c [@var{switches}] @file{file name}
3573 @end smallexample
3574
3575 @noindent
3576 where @var{file name} is the name of the Ada file (usually
3577 having an extension
3578 @file{.ads} for a spec or @file{.adb} for a body).
3579 @ifclear vms
3580 You specify the
3581 @option{-c} switch to tell @code{gcc} to compile, but not link, the file.
3582 @end ifclear
3583 The result of a successful compilation is an object file, which has the
3584 same name as the source file but an extension of @file{.o} and an Ada
3585 Library Information (ALI) file, which also has the same name as the
3586 source file, but with @file{.ali} as the extension. GNAT creates these
3587 two output files in the current directory, but you may specify a source
3588 file in any directory using an absolute or relative path specification
3589 containing the directory information.
3590
3591 @findex gnat1
3592 @code{gcc} is actually a driver program that looks at the extensions of
3593 the file arguments and loads the appropriate compiler. For example, the
3594 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3595 These programs are in directories known to the driver program (in some
3596 configurations via environment variables you set), but need not be in
3597 your path. The @code{gcc} driver also calls the assembler and any other
3598 utilities needed to complete the generation of the required object
3599 files.
3600
3601 It is possible to supply several file names on the same @code{gcc}
3602 command. This causes @code{gcc} to call the appropriate compiler for
3603 each file. For example, the following command lists three separate
3604 files to be compiled:
3605
3606 @smallexample
3607 $ gcc -c x.adb y.adb z.c
3608 @end smallexample
3609
3610 @noindent
3611 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3612 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3613 The compiler generates three object files @file{x.o}, @file{y.o} and
3614 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3615 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3616 @ifclear vms
3617 except for
3618 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3619 @end ifclear
3620
3621 @node Switches for gcc
3622 @section Switches for @code{gcc}
3623
3624 @noindent
3625 The @code{gcc} command accepts switches that control the
3626 compilation process. These switches are fully described in this section.
3627 First we briefly list all the switches, in alphabetical order, then we
3628 describe the switches in more detail in functionally grouped sections.
3629
3630 @menu
3631 * Output and Error Message Control::
3632 * Warning Message Control::
3633 * Debugging and Assertion Control::
3634 * Run-Time Checks::
3635 * Stack Overflow Checking::
3636 * Validity Checking::
3637 * Style Checking::
3638 * Using gcc for Syntax Checking::
3639 * Using gcc for Semantic Checking::
3640 * Compiling Ada 83 Programs::
3641 * Character Set Control::
3642 * File Naming Control::
3643 * Subprogram Inlining Control::
3644 * Auxiliary Output Control::
3645 * Debugging Control::
3646 * Exception Handling Control::
3647 * Units to Sources Mapping Files::
3648 * Integrated Preprocessing::
3649 @ifset vms
3650 * Return Codes::
3651 @end ifset
3652 @end menu
3653
3654 @table @option
3655 @c !sort!
3656 @ifclear vms
3657 @cindex @option{-b} (@code{gcc})
3658 @item -b @var{target}
3659 Compile your program to run on @var{target}, which is the name of a
3660 system configuration. You must have a GNAT cross-compiler built if
3661 @var{target} is not the same as your host system.
3662
3663 @item -B@var{dir}
3664 @cindex @option{-B} (@code{gcc})
3665 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3666 from @var{dir} instead of the default location. Only use this switch
3667 when multiple versions of the GNAT compiler are available. See the
3668 @code{gcc} manual page for further details. You would normally use the
3669 @option{-b} or @option{-V} switch instead.
3670
3671 @item -c
3672 @cindex @option{-c} (@code{gcc})
3673 Compile. Always use this switch when compiling Ada programs.
3674
3675 Note: for some other languages when using @code{gcc}, notably in
3676 the case of C and C++, it is possible to use
3677 use @code{gcc} without a @option{-c} switch to
3678 compile and link in one step. In the case of GNAT, you
3679 cannot use this approach, because the binder must be run
3680 and @code{gcc} cannot be used to run the GNAT binder.
3681 @end ifclear
3682
3683 @item -fno-inline
3684 @cindex @option{-fno-inline} (@code{gcc})
3685 Suppresses all back-end inlining, even if other optimization or inlining
3686 switches are set.
3687 This includes suppression of inlining that results
3688 from the use of the pragma @code{Inline_Always}.
3689 See also @option{-gnatn} and @option{-gnatN}.
3690
3691 @item -fno-strict-aliasing
3692 @cindex @option{-fno-strict-aliasing} (@code{gcc})
3693 Causes the compiler to avoid assumptions regarding non-aliasing
3694 of objects of different types. See section
3695 @pxref{Optimization and Strict Aliasing} for details.
3696
3697 @item -fstack-check
3698 @cindex @option{-fstack-check} (@code{gcc})
3699 Activates stack checking.
3700 See @ref{Stack Overflow Checking} for details of the use of this option.
3701
3702 @item ^-g^/DEBUG^
3703 @cindex @option{^-g^/DEBUG^} (@code{gcc})
3704 Generate debugging information. This information is stored in the object
3705 file and copied from there to the final executable file by the linker,
3706 where it can be read by the debugger. You must use the
3707 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3708
3709 @item -gnat83
3710 @cindex @option{-gnat83} (@code{gcc})
3711 Enforce Ada 83 restrictions.
3712
3713 @item -gnata
3714 @cindex @option{-gnata} (@code{gcc})
3715 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3716 activated.
3717
3718 @item -gnatA
3719 @cindex @option{-gnatA} (@code{gcc})
3720 Avoid processing @file{gnat.adc}. If a gnat.adc file is present,
3721 it will be ignored.
3722
3723 @item -gnatb
3724 @cindex @option{-gnatb} (@code{gcc})
3725 Generate brief messages to @file{stderr} even if verbose mode set.
3726
3727 @item -gnatc
3728 @cindex @option{-gnatc} (@code{gcc})
3729 Check syntax and semantics only (no code generation attempted).
3730
3731 @item -gnatd
3732 @cindex @option{-gnatd} (@code{gcc})
3733 Specify debug options for the compiler. The string of characters after
3734 the @option{-gnatd} specify the specific debug options. The possible
3735 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3736 compiler source file @file{debug.adb} for details of the implemented
3737 debug options. Certain debug options are relevant to applications
3738 programmers, and these are documented at appropriate points in this
3739 users guide.
3740
3741 @item -gnatD
3742 @cindex @option{-gnatD} (@code{gcc})
3743 Create expanded source files for source level debugging. This switch
3744 also suppress generation of cross-reference information
3745 (see @option{-gnatx}).
3746
3747 @item -gnatec=@var{path}
3748 @cindex @option{-gnatec} (@code{gcc})
3749 Specify a configuration pragma file
3750 @ifclear vms
3751 (the equal sign is optional)
3752 @end ifclear
3753 (see @ref{The Configuration Pragmas Files}).
3754
3755 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
3756 @cindex @option{-gnateD} (@code{gcc})
3757 Defines a symbol, associated with value, for preprocessing.
3758 (see @ref{Integrated Preprocessing})
3759
3760 @item -gnatef
3761 @cindex @option{-gnatef} (@code{gcc})
3762 Display full source path name in brief error messages.
3763
3764 @item -gnatem=@var{path}
3765 @cindex @option{-gnatem} (@code{gcc})
3766 Specify a mapping file
3767 @ifclear vms
3768 (the equal sign is optional)
3769 @end ifclear
3770 (see @ref{Units to Sources Mapping Files}).
3771
3772 @item -gnatep=@var{file}
3773 @cindex @option{-gnatep} (@code{gcc})
3774 Specify a preprocessing data file
3775 @ifclear vms
3776 (the equal sign is optional)
3777 @end ifclear
3778 (see @ref{Integrated Preprocessing}).
3779
3780 @item -gnatE
3781 @cindex @option{-gnatE} (@code{gcc})
3782 Full dynamic elaboration checks.
3783
3784 @item -gnatf
3785 @cindex @option{-gnatf} (@code{gcc})
3786 Full errors. Multiple errors per line, all undefined references, do not
3787 attempt to suppress cascaded errors.
3788
3789 @item -gnatF
3790 @cindex @option{-gnatF} (@code{gcc})
3791 Externals names are folded to all uppercase.
3792
3793 @item -gnatg
3794 @cindex @option{-gnatg} (@code{gcc})
3795 Internal GNAT implementation mode. This should not be used for
3796 applications programs, it is intended only for use by the compiler
3797 and its run-time library. For documentation, see the GNAT sources.
3798 Note that @option{-gnatg} implies @option{-gnatwu} so that warnings
3799 are generated on unreferenced entities, and all warnings are treated
3800 as errors.
3801
3802 @item -gnatG
3803 @cindex @option{-gnatG} (@code{gcc})
3804 List generated expanded code in source form.
3805
3806 @item ^-gnath^/HELP^
3807 @cindex @option{^-gnath^/HELP^} (@code{gcc})
3808 Output usage information. The output is written to @file{stdout}.
3809
3810 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3811 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc})
3812 Identifier character set
3813 @ifclear vms
3814 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3815 @end ifclear
3816 @ifset vms
3817 For details of the possible selections for @var{c},
3818 see @xref{Character Set Control}.
3819 @end ifset
3820
3821 @item -gnatk=@var{n}
3822 @cindex @option{-gnatk} (@code{gcc})
3823 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3824
3825 @item -gnatl
3826 @cindex @option{-gnatl} (@code{gcc})
3827 Output full source listing with embedded error messages.
3828
3829 @item -gnatL
3830 @cindex @option{-gnatL} (@code{gcc})
3831 Use the longjmp/setjmp method for exception handling
3832
3833 @item -gnatm=@var{n}
3834 @cindex @option{-gnatm} (@code{gcc})
3835 Limit number of detected error or warning messages to @var{n}
3836 where @var{n} is in the range 1..999_999. The default setting if
3837 no switch is given is 9999. Compilation is terminated if this
3838 limit is exceeded.
3839
3840 @item -gnatn
3841 @cindex @option{-gnatn} (@code{gcc})
3842 Activate inlining for subprograms for which
3843 pragma @code{inline} is specified. This inlining is performed
3844 by the GCC back-end.
3845
3846 @item -gnatN
3847 @cindex @option{-gnatN} (@code{gcc})
3848 Activate front end inlining for subprograms for which
3849 pragma @code{Inline} is specified. This inlining is performed
3850 by the front end and will be visible in the
3851 @option{-gnatG} output.
3852 In some cases, this has proved more effective than the back end
3853 inlining resulting from the use of
3854 @option{-gnatn}.
3855 Note that
3856 @option{-gnatN} automatically implies
3857 @option{-gnatn} so it is not necessary
3858 to specify both options. There are a few cases that the back-end inlining
3859 catches that cannot be dealt with in the front-end.
3860
3861 @item -gnato
3862 @cindex @option{-gnato} (@code{gcc})
3863 Enable numeric overflow checking (which is not normally enabled by
3864 default). Not that division by zero is a separate check that is not
3865 controlled by this switch (division by zero checking is on by default).
3866
3867 @item -gnatp
3868 @cindex @option{-gnatp} (@code{gcc})
3869 Suppress all checks.
3870
3871 @item -gnatP
3872 @cindex @option{-gnatP} (@code{gcc})
3873 Enable polling. This is required on some systems (notably Windows NT) to
3874 obtain asynchronous abort and asynchronous transfer of control capability.
3875 See the description of pragma Polling in the GNAT Reference Manual for
3876 full details.
3877
3878 @item -gnatq
3879 @cindex @option{-gnatq} (@code{gcc})
3880 Don't quit; try semantics, even if parse errors.
3881
3882 @item -gnatQ
3883 @cindex @option{-gnatQ} (@code{gcc})
3884 Don't quit; generate @file{ALI} and tree files even if illegalities.
3885
3886 @item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^
3887 @cindex @option{-gnatR} (@code{gcc})
3888 Output representation information for declared types and objects.
3889
3890 @item -gnats
3891 @cindex @option{-gnats} (@code{gcc})
3892 Syntax check only.
3893
3894 @item -gnatS
3895 @cindex @option{-gnatS} (@code{gcc})
3896 Print package Standard.
3897
3898 @item -gnatt
3899 @cindex @option{-gnatt} (@code{gcc})
3900 Generate tree output file.
3901
3902 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
3903 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@code{gcc})
3904 All compiler tables start at @var{nnn} times usual starting size.
3905
3906 @item -gnatu
3907 @cindex @option{-gnatu} (@code{gcc})
3908 List units for this compilation.
3909
3910 @item -gnatU
3911 @cindex @option{-gnatU} (@code{gcc})
3912 Tag all error messages with the unique string ``error:''
3913
3914 @item -gnatv
3915 @cindex @option{-gnatv} (@code{gcc})
3916 Verbose mode. Full error output with source lines to @file{stdout}.
3917
3918 @item -gnatV
3919 @cindex @option{-gnatV} (@code{gcc})
3920 Control level of validity checking. See separate section describing
3921 this feature.
3922
3923 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,...])^
3924 @cindex @option{^-gnatw^/WARNINGS^} (@code{gcc})
3925 Warning mode where
3926 ^@var{xxx} is a string of option letters that^the list of options^ denotes
3927 the exact warnings that
3928 are enabled or disabled. (see @ref{Warning Message Control})
3929
3930 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
3931 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc})
3932 Wide character encoding method
3933 @ifclear vms
3934 (@var{e}=n/h/u/s/e/8).
3935 @end ifclear
3936 @ifset vms
3937 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
3938 @end ifset
3939
3940 @item -gnatx
3941 @cindex @option{-gnatx} (@code{gcc})
3942 Suppress generation of cross-reference information.
3943
3944 @item ^-gnaty^/STYLE_CHECKS=(option,option..)^
3945 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@code{gcc})
3946 Enable built-in style checks. (see @ref{Style Checking})
3947
3948 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
3949 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@code{gcc})
3950 Distribution stub generation and compilation
3951 @ifclear vms
3952 (@var{m}=r/c for receiver/caller stubs).
3953 @end ifclear
3954 @ifset vms
3955 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
3956 to be generated and compiled).
3957 @end ifset
3958
3959 @item -gnatZ
3960 Use the zero cost method for exception handling
3961
3962 @item ^-I^/SEARCH=^@var{dir}
3963 @cindex @option{^-I^/SEARCH^} (@code{gcc})
3964 @cindex RTL
3965 Direct GNAT to search the @var{dir} directory for source files needed by
3966 the current compilation
3967 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3968
3969 @item ^-I-^/NOCURRENT_DIRECTORY^
3970 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gcc})
3971 @cindex RTL
3972 Except for the source file named in the command line, do not look for source
3973 files in the directory containing the source file named in the command line
3974 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3975
3976 @ifclear vms
3977 @item -mbig-switch
3978 @cindex @option{-mbig-switch} (@command{gcc})
3979 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
3980 This standard gcc switch causes the compiler to use larger offsets in its
3981 jump table representation for @code{case} statements.
3982 This may result in less efficient code, but is sometimes necessary
3983 (for example on HP-UX targets)
3984 @cindex HP-UX and @option{-mbig-switch} option
3985 in order to compile large and/or nested @code{case} statements.
3986
3987 @item -o @var{file}
3988 @cindex @option{-o} (@code{gcc})
3989 This switch is used in @code{gcc} to redirect the generated object file
3990 and its associated ALI file. Beware of this switch with GNAT, because it may
3991 cause the object file and ALI file to have different names which in turn
3992 may confuse the binder and the linker.
3993 @end ifclear
3994
3995 @item -nostdinc
3996 @cindex @option{-nostdinc} (@command{gcc})
3997 Inhibit the search of the default location for the GNAT Run Time
3998 Library (RTL) source files.
3999
4000 @item -nostdlib
4001 @cindex @option{-nostdlib} (@command{gcc})
4002 Inhibit the search of the default location for the GNAT Run Time
4003 Library (RTL) ALI files.
4004
4005 @ifclear vms
4006 @item -O[@var{n}]
4007 @cindex @option{-O} (@code{gcc})
4008 @var{n} controls the optimization level.
4009
4010 @table @asis
4011 @item n = 0
4012 No optimization, the default setting if no @option{-O} appears
4013
4014 @item n = 1
4015 Normal optimization, the default if you specify @option{-O} without
4016 an operand.
4017
4018 @item n = 2
4019 Extensive optimization
4020
4021 @item n = 3
4022 Extensive optimization with automatic inlining of subprograms not
4023 specified by pragma @code{Inline}. This applies only to
4024 inlining within a unit. For details on control of inlining
4025 see @xref{Subprogram Inlining Control}.
4026 @end table
4027 @end ifclear
4028
4029 @ifset vms
4030 @item  /NOOPTIMIZE
4031 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4032 Equivalent to @option{/OPTIMIZE=NONE}.
4033 This is the default behavior in the absence of an @option{/OPTMIZE}
4034 qualifier.
4035
4036 @item /OPTIMIZE[=(keyword[,...])]
4037 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4038 Selects the level of optimization for your program. The supported
4039 keywords are as follows:
4040 @table @code
4041 @item   ALL
4042 Perform most optimizations, including those that
4043 are expensive.
4044 This is the default if the @option{/OPTMIZE} qualifier is supplied
4045 without keyword options.
4046
4047 @item   NONE
4048 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4049
4050 @item SOME
4051 Perform some optimizations, but omit ones that are costly.
4052
4053 @item   DEVELOPMENT
4054 Same as @code{SOME}.
4055
4056 @item   INLINING
4057 Full optimization, and also attempt automatic inlining of small
4058 subprograms within a unit even when pragma @code{Inline}
4059 is not specified (@pxref{Inlining of Subprograms}).
4060
4061 @item   UNROLL_LOOPS
4062 Try to unroll loops. This keyword may be specified together with
4063 any keyword above other than @code{NONE}. Loop unrolling
4064 usually, but not always, improves the performance of programs.
4065 @end table
4066 @end ifset
4067
4068 @ifclear vms
4069 @item -pass-exit-codes
4070 @cindex @option{-pass-exit-codes} (@code{gcc})
4071 Catch exit codes from the compiler and use the most meaningful as
4072 exit status.
4073 @end ifclear
4074
4075 @item --RTS=@var{rts-path}
4076 @cindex @option{--RTS} (@code{gcc})
4077 Specifies the default location of the runtime library. Same meaning as the
4078 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
4079
4080 @item ^-S^/ASM^
4081 @cindex @option{^-S^/ASM^} (@code{gcc})
4082 ^Used in place of @option{-c} to^Used to^
4083 cause the assembler source file to be
4084 generated, using @file{^.s^.S^} as the extension,
4085 instead of the object file.
4086 This may be useful if you need to examine the generated assembly code.
4087
4088 @item ^-v^/VERBOSE^
4089 @cindex @option{^-v^/VERBOSE^} (@code{gcc})
4090 Show commands generated by the @code{gcc} driver. Normally used only for
4091 debugging purposes or if you need to be sure what version of the
4092 compiler you are executing.
4093
4094 @ifclear vms
4095 @item -V @var{ver}
4096 @cindex @option{-V} (@code{gcc})
4097 Execute @var{ver} version of the compiler. This is the @code{gcc}
4098 version, not the GNAT version.
4099 @end ifclear
4100
4101 @end table
4102
4103 @ifclear vms
4104 You may combine a sequence of GNAT switches into a single switch. For
4105 example, the combined switch
4106
4107 @cindex Combining GNAT switches
4108 @smallexample
4109 -gnatofi3
4110 @end smallexample
4111
4112 @noindent
4113 is equivalent to specifying the following sequence of switches:
4114
4115 @smallexample
4116 -gnato -gnatf -gnati3
4117 @end smallexample
4118 @end ifclear
4119
4120
4121 @c NEED TO CHECK THIS FOR VMS
4122
4123 @noindent
4124 The following restrictions apply to the combination of switches
4125 in this manner:
4126
4127 @itemize @bullet
4128 @item
4129 The switch @option{-gnatc} if combined with other switches must come
4130 first in the string.
4131
4132 @item
4133 The switch @option{-gnats} if combined with other switches must come
4134 first in the string.
4135
4136 @item
4137 The switches
4138 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4139 may not be combined with any other switches.
4140
4141 @ifclear vms
4142 @item
4143 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4144 switch), then all further characters in the switch are interpreted
4145 as style modifiers (see description of @option{-gnaty}).
4146
4147 @item
4148 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4149 switch), then all further characters in the switch are interpreted
4150 as debug flags (see description of @option{-gnatd}).
4151
4152 @item
4153 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4154 switch), then all further characters in the switch are interpreted
4155 as warning mode modifiers (see description of @option{-gnatw}).
4156
4157 @item
4158 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4159 switch), then all further characters in the switch are interpreted
4160 as validity checking options (see description of @option{-gnatV}).
4161 @end ifclear
4162 @end itemize
4163
4164
4165 @node Output and Error Message Control
4166 @subsection Output and Error Message Control
4167 @findex stderr
4168
4169 @noindent
4170 The standard default format for error messages is called ``brief format''.
4171 Brief format messages are written to @file{stderr} (the standard error
4172 file) and have the following form:
4173
4174 @smallexample
4175 e.adb:3:04: Incorrect spelling of keyword "function"
4176 e.adb:4:20: ";" should be "is"
4177 @end smallexample
4178
4179 @noindent
4180 The first integer after the file name is the line number in the file,
4181 and the second integer is the column number within the line.
4182 @code{glide} can parse the error messages
4183 and point to the referenced character.
4184 The following switches provide control over the error message
4185 format:
4186
4187 @table @option
4188 @c !sort!
4189 @item -gnatv
4190 @cindex @option{-gnatv} (@code{gcc})
4191 @findex stdout
4192 @ifclear vms
4193 The v stands for verbose.
4194 @end ifclear
4195 The effect of this setting is to write long-format error
4196 messages to @file{stdout} (the standard output file.
4197 The same program compiled with the
4198 @option{-gnatv} switch would generate:
4199
4200 @smallexample
4201 @cartouche
4202 3. funcion X (Q : Integer)
4203    |
4204 >>> Incorrect spelling of keyword "function"
4205 4. return Integer;
4206                  |
4207 >>> ";" should be "is"
4208 @end cartouche
4209 @end smallexample
4210
4211 @noindent
4212 The vertical bar indicates the location of the error, and the @samp{>>>}
4213 prefix can be used to search for error messages. When this switch is
4214 used the only source lines output are those with errors.
4215
4216 @item -gnatl
4217 @cindex @option{-gnatl} (@code{gcc})
4218 @ifclear vms
4219 The @code{l} stands for list.
4220 @end ifclear
4221 This switch causes a full listing of
4222 the file to be generated. The output might look as follows:
4223
4224 @smallexample
4225 @cartouche
4226  1. procedure E is
4227  2.    V : Integer;
4228  3.    funcion X (Q : Integer)
4229        |
4230     >>> Incorrect spelling of keyword "function"
4231  4.     return Integer;
4232                       |
4233     >>> ";" should be "is"
4234  5.    begin
4235  6.       return Q + Q;
4236  7.    end;
4237  8. begin
4238  9.    V := X + X;
4239 10.end E;
4240 @end cartouche
4241 @end smallexample
4242
4243 @noindent
4244 @findex stderr
4245 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4246 standard output is redirected, a brief summary is written to
4247 @file{stderr} (standard error) giving the number of error messages and
4248 warning messages generated.
4249
4250 @item -gnatU
4251 @cindex @option{-gnatU} (@code{gcc})
4252 This switch forces all error messages to be preceded by the unique
4253 string ``error:''. This means that error messages take a few more
4254 characters in space, but allows easy searching for and identification
4255 of error messages.
4256
4257 @item -gnatb
4258 @cindex @option{-gnatb} (@code{gcc})
4259 @ifclear vms
4260 The @code{b} stands for brief.
4261 @end ifclear
4262 This switch causes GNAT to generate the
4263 brief format error messages to @file{stderr} (the standard error
4264 file) as well as the verbose
4265 format message or full listing (which as usual is written to
4266 @file{stdout} (the standard output file).
4267
4268 @item -gnatm^^=^@var{n}
4269 @cindex @option{-gnatm} (@code{gcc})
4270 @ifclear vms
4271 The @code{m} stands for maximum.
4272 @end ifclear
4273 @var{n} is a decimal integer in the
4274 range of 1 to 999 and limits the number of error messages to be
4275 generated. For example, using @option{-gnatm2} might yield
4276
4277 @smallexample
4278 e.adb:3:04: Incorrect spelling of keyword "function"
4279 e.adb:5:35: missing ".."
4280 fatal error: maximum errors reached
4281 compilation abandoned
4282 @end smallexample
4283
4284 @item -gnatf
4285 @cindex @option{-gnatf} (@code{gcc})
4286 @cindex Error messages, suppressing
4287 @ifclear vms
4288 The @code{f} stands for full.
4289 @end ifclear
4290 Normally, the compiler suppresses error messages that are likely to be
4291 redundant. This switch causes all error
4292 messages to be generated. In particular, in the case of
4293 references to undefined variables. If a given variable is referenced
4294 several times, the normal format of messages is
4295 @smallexample
4296 e.adb:7:07: "V" is undefined (more references follow)
4297 @end smallexample
4298
4299 @noindent
4300 where the parenthetical comment warns that there are additional
4301 references to the variable @code{V}. Compiling the same program with the
4302 @option{-gnatf} switch yields
4303
4304 @smallexample
4305 e.adb:7:07: "V" is undefined
4306 e.adb:8:07: "V" is undefined
4307 e.adb:8:12: "V" is undefined
4308 e.adb:8:16: "V" is undefined
4309 e.adb:9:07: "V" is undefined
4310 e.adb:9:12: "V" is undefined
4311 @end smallexample
4312
4313 @noindent
4314 The @option{-gnatf} switch also generates additional information for
4315 some error messages.  Some examples are:
4316
4317 @itemize @bullet
4318 @item
4319 Full details on entities not available in high integrity mode
4320 @item
4321 Details on possibly non-portable unchecked conversion
4322 @item
4323 List possible interpretations for ambiguous calls
4324 @item
4325 Additional details on incorrect parameters
4326 @end itemize
4327
4328
4329 @item -gnatq
4330 @cindex @option{-gnatq} (@code{gcc})
4331 @ifclear vms
4332 The @code{q} stands for quit (really ``don't quit'').
4333 @end ifclear
4334 In normal operation mode, the compiler first parses the program and
4335 determines if there are any syntax errors. If there are, appropriate
4336 error messages are generated and compilation is immediately terminated.
4337 This switch tells
4338 GNAT to continue with semantic analysis even if syntax errors have been
4339 found. This may enable the detection of more errors in a single run. On
4340 the other hand, the semantic analyzer is more likely to encounter some
4341 internal fatal error when given a syntactically invalid tree.
4342
4343 @item -gnatQ
4344 @cindex @option{-gnatQ} (@code{gcc})
4345 In normal operation mode, the @file{ALI} file is not generated if any
4346 illegalities are detected in the program. The use of @option{-gnatQ} forces
4347 generation of the @file{ALI} file. This file is marked as being in
4348 error, so it cannot be used for binding purposes, but it does contain
4349 reasonably complete cross-reference information, and thus may be useful
4350 for use by tools (e.g. semantic browsing tools or integrated development
4351 environments) that are driven from the @file{ALI} file. This switch
4352 implies @option{-gnatq}, since the semantic phase must be run to get a
4353 meaningful ALI file.
4354
4355 In addition, if @option{-gnatt} is also specified, then the tree file is
4356 generated even if there are illegalities. It may be useful in this case
4357 to also specify @option{-gnatq} to ensure that full semantic processing
4358 occurs. The resulting tree file can be processed by ASIS, for the purpose
4359 of providing partial information about illegal units, but if the error
4360 causes the tree to be badly malformed, then ASIS may crash during the
4361 analysis.
4362
4363 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4364 being in error, @code{gnatmake} will attempt to recompile the source when it
4365 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4366
4367 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4368 since ALI files are never generated if @option{-gnats} is set.
4369
4370 @end table
4371
4372
4373 @node Warning Message Control
4374 @subsection Warning Message Control
4375 @cindex Warning messages
4376 @noindent
4377 In addition to error messages, which correspond to illegalities as defined
4378 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
4379 situations.
4380
4381 First, the compiler considers some constructs suspicious and generates a
4382 warning message to alert you to a possible error. Second, if the
4383 compiler detects a situation that is sure to raise an exception at
4384 run time, it generates a warning message. The following shows an example
4385 of warning messages:
4386 @smallexample
4387 e.adb:4:24: warning: creation of object may raise Storage_Error
4388 e.adb:10:17: warning: static value out of range
4389 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4390 @end smallexample
4391
4392 @noindent
4393 GNAT considers a large number of situations as appropriate
4394 for the generation of warning messages. As always, warnings are not
4395 definite indications of errors. For example, if you do an out-of-range
4396 assignment with the deliberate intention of raising a
4397 @code{Constraint_Error} exception, then the warning that may be
4398 issued does not indicate an error. Some of the situations for which GNAT
4399 issues warnings (at least some of the time) are given in the following
4400 list. This list is not complete, and new warnings are often added to
4401 subsequent versions of GNAT. The list is intended to give a general idea
4402 of the kinds of warnings that are generated.
4403
4404 @itemize @bullet
4405 @item
4406 Possible infinitely recursive calls
4407
4408 @item
4409 Out-of-range values being assigned
4410
4411 @item
4412 Possible order of elaboration problems
4413
4414 @item
4415 Unreachable code
4416
4417 @item
4418 Fixed-point type declarations with a null range
4419
4420 @item
4421 Variables that are never assigned a value
4422
4423 @item
4424 Variables that are referenced before being initialized
4425
4426 @item
4427 Task entries with no corresponding @code{accept} statement
4428
4429 @item
4430 Duplicate accepts for the same task entry in a @code{select}
4431
4432 @item
4433 Objects that take too much storage
4434
4435 @item
4436 Unchecked conversion between types of differing sizes
4437
4438 @item
4439 Missing @code{return} statement along some execution path in a function
4440
4441 @item
4442 Incorrect (unrecognized) pragmas
4443
4444 @item
4445 Incorrect external names
4446
4447 @item
4448 Allocation from empty storage pool
4449
4450 @item
4451 Potentially blocking operation in protected type
4452
4453 @item
4454 Suspicious parenthesization of expressions
4455
4456 @item
4457 Mismatching bounds in an aggregate
4458
4459 @item
4460 Attempt to return local value by reference
4461
4462
4463 @item
4464 Premature instantiation of a generic body
4465
4466 @item
4467 Attempt to pack aliased components
4468
4469 @item
4470 Out of bounds array subscripts
4471
4472 @item
4473 Wrong length on string assignment
4474
4475 @item
4476 Violations of style rules if style checking is enabled
4477
4478 @item
4479 Unused @code{with} clauses
4480
4481 @item
4482 @code{Bit_Order} usage that does not have any effect
4483
4484 @item
4485 @code{Standard.Duration} used to resolve universal fixed expression
4486
4487 @item
4488 Dereference of possibly null value
4489
4490 @item
4491 Declaration that is likely to cause storage error
4492
4493 @item
4494 Internal GNAT unit @code{with}'ed by application unit
4495
4496 @item
4497 Values known to be out of range at compile time
4498
4499 @item
4500 Unreferenced labels and variables
4501
4502 @item
4503 Address overlays that could clobber memory
4504
4505 @item
4506 Unexpected initialization when address clause present
4507
4508 @item
4509 Bad alignment for address clause
4510
4511 @item
4512 Useless type conversions
4513
4514 @item
4515 Redundant assignment statements and other redundant constructs
4516
4517 @item
4518 Useless exception handlers
4519
4520 @item
4521 Accidental hiding of name by child unit
4522
4523
4524 @item
4525 Access before elaboration detected at compile time
4526
4527 @item
4528 A range in a @code{for} loop that is known to be null or might be null
4529
4530 @end itemize
4531
4532 @noindent
4533 The following switches are available to control the handling of
4534 warning messages:
4535
4536 @table @option
4537 @c !sort!
4538 @item -gnatwa
4539 @emph{Activate all optional errors.}
4540 @cindex @option{-gnatwa} (@code{gcc})
4541 This switch activates most optional warning messages, see remaining list
4542 in this section for details on optional warning messages that can be
4543 individually controlled.  The warnings that are not turned on by this
4544 switch are
4545 @option{-gnatwd} (implicit dereferencing),
4546 @option{-gnatwh} (hiding),
4547 and @option{-gnatwl} (elaboration warnings).
4548 All other optional warnings are turned on.
4549
4550 @item -gnatwA
4551 @emph{Suppress all optional errors.}
4552 @cindex @option{-gnatwA} (@code{gcc})
4553 This switch suppresses all optional warning messages, see remaining list
4554 in this section for details on optional warning messages that can be
4555 individually controlled.
4556
4557 @item -gnatwc
4558 @emph{Activate warnings on conditionals.}
4559 @cindex @option{-gnatwc} (@code{gcc})
4560 @cindex Conditionals, constant
4561 This switch activates warnings for conditional expressions used in
4562 tests that are known to be True or False at compile time. The default
4563 is that such warnings are not generated.
4564 Note that this warning does
4565 not get issued for the use of boolean variables or constants whose
4566 values are known at compile time, since this is a standard technique
4567 for conditional compilation in Ada, and this would generate too many
4568 ``false positive'' warnings.
4569 This warning can also be turned on using @option{-gnatwa}.
4570
4571 @item -gnatwC
4572 @emph{Suppress warnings on conditionals.}
4573 @cindex @option{-gnatwC} (@code{gcc})
4574 This switch suppresses warnings for conditional expressions used in
4575 tests that are known to be True or False at compile time.
4576
4577 @item -gnatwd
4578 @emph{Activate warnings on implicit dereferencing.}
4579 @cindex @option{-gnatwd} (@code{gcc})
4580 If this switch is set, then the use of a prefix of an access type
4581 in an indexed component, slice, or selected component without an
4582 explicit @code{.all} will generate a warning. With this warning
4583 enabled, access checks occur only at points where an explicit
4584 @code{.all} appears in the source code (assuming no warnings are
4585 generated as a result of this switch). The default is that such
4586 warnings are not generated.
4587 Note that @option{-gnatwa} does not affect the setting of
4588 this warning option.
4589
4590 @item -gnatwD
4591 @emph{Suppress warnings on implicit dereferencing.}
4592 @cindex @option{-gnatwD} (@code{gcc})
4593 @cindex Implicit dereferencing
4594 @cindex Dereferencing, implicit
4595 This switch suppresses warnings for implicit dereferences in
4596 indexed components, slices, and selected components.
4597
4598 @item -gnatwe
4599 @emph{Treat warnings as errors.}
4600 @cindex @option{-gnatwe} (@code{gcc})
4601 @cindex Warnings, treat as error
4602 This switch causes warning messages to be treated as errors.
4603 The warning string still appears, but the warning messages are counted
4604 as errors, and prevent the generation of an object file.
4605
4606 @item -gnatwf
4607 @emph{Activate warnings on unreferenced formals.}
4608 @cindex @option{-gnatwf} (@code{gcc})
4609 @cindex Formals, unreferenced
4610 This switch causes a warning to be generated if a formal parameter
4611 is not referenced in the body of the subprogram. This warning can
4612 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
4613
4614 @item -gnatwF
4615 @emph{Suppress warnings on unreferenced formals.}
4616 @cindex @option{-gnatwF} (@code{gcc})
4617 This switch suppresses warnings for unreferenced formal
4618 parameters. Note that the
4619 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4620 effect of warning on unreferenced entities other than subprogram
4621 formals.
4622
4623 @item -gnatwg
4624 @emph{Activate warnings on unrecognized pragmas.}
4625 @cindex @option{-gnatwg} (@code{gcc})
4626 @cindex Pragmas, unrecognized
4627 This switch causes a warning to be generated if an unrecognized
4628 pragma is encountered. Apart from issuing this warning, the
4629 pragma is ignored and has no effect. This warning can
4630 also be turned on using @option{-gnatwa}. The default
4631 is that such warnings are issued (satisfying the Ada Reference
4632 Manual requirement that such warnings appear).
4633
4634 @item -gnatwG
4635 @emph{Suppress warnings on unrecognized pragmas.}
4636 @cindex @option{-gnatwG} (@code{gcc})
4637 This switch suppresses warnings for unrecognized pragmas.
4638
4639 @item -gnatwh
4640 @emph{Activate warnings on hiding.}
4641 @cindex @option{-gnatwh} (@code{gcc})
4642 @cindex Hiding of Declarations
4643 This switch activates warnings on hiding declarations.
4644 A declaration is considered hiding
4645 if it is for a non-overloadable entity, and it declares an entity with the
4646 same name as some other entity that is directly or use-visible. The default
4647 is that such warnings are not generated.
4648 Note that @option{-gnatwa} does not affect the setting of this warning option.
4649
4650 @item -gnatwH
4651 @emph{Suppress warnings on hiding.}
4652 @cindex @option{-gnatwH} (@code{gcc})
4653 This switch suppresses warnings on hiding declarations.
4654
4655 @item -gnatwi
4656 @emph{Activate warnings on implementation units.}
4657 @cindex @option{-gnatwi} (@code{gcc})
4658 This switch activates warnings for a @code{with} of an internal GNAT
4659 implementation unit, defined as any unit from the @code{Ada},
4660 @code{Interfaces}, @code{GNAT},
4661 ^^@code{DEC},^ or @code{System}
4662 hierarchies that is not
4663 documented in either the Ada Reference Manual or the GNAT
4664 Programmer's Reference Manual. Such units are intended only
4665 for internal implementation purposes and should not be @code{with}'ed
4666 by user programs. The default is that such warnings are generated
4667 This warning can also be turned on using @option{-gnatwa}.
4668
4669 @item -gnatwI
4670 @emph{Disable warnings on implementation units.}
4671 @cindex @option{-gnatwI} (@code{gcc})
4672 This switch disables warnings for a @code{with} of an internal GNAT
4673 implementation unit.
4674
4675 @item -gnatwj
4676 @emph{Activate warnings on obsolescent features (Annex J).}
4677 @cindex @option{-gnatwj} (@code{gcc})
4678 @cindex Features, obsolescent
4679 @cindex Obsolescent features
4680 If this warning option is activated, then warnings are generated for
4681 calls to subprograms marked with @code{pragma Obsolescent} and
4682 for use of features in Annex J of the Ada Reference Manual. In the
4683 case of Annex J, not all features are flagged. In particular use
4684 of the renamed packages (like @code{Text_IO}) and use of package
4685 @code{ASCII} are not flagged, since these are very common and
4686 would generate many annoying positive warnings. The default is that
4687 such warnings are not generated.
4688
4689 @item -gnatwJ
4690 @emph{Suppress warnings on obsolescent features (Annex J).}
4691 @cindex @option{-gnatwJ} (@code{gcc})
4692 This switch disables warnings on use of obsolescent features.
4693
4694 @item -gnatwk
4695 @emph{Activate warnings on variables that could be constants.}
4696 @cindex @option{-gnatwk} (@code{gcc})
4697 This switch activates warnings for variables that are initialized but
4698 never modified, and then could be declared constants.
4699
4700 @item -gnatwK
4701 @emph{Suppress warnings on variables that could be constants.}
4702 @cindex @option{-gnatwK} (@code{gcc})
4703 This switch disables warnings on variables that could be declared constants.
4704
4705 @item -gnatwl
4706 @emph{Activate warnings for missing elaboration pragmas.}
4707 @cindex @option{-gnatwl} (@code{gcc})
4708 @cindex Elaboration, warnings
4709 This switch activates warnings on missing
4710 @code{pragma Elaborate_All} statements.
4711 See the section in this guide on elaboration checking for details on
4712 when such pragma should be used. Warnings are also generated if you
4713 are using the static mode of elaboration, and a @code{pragma Elaborate}
4714 is encountered. The default is that such warnings
4715 are not generated.
4716 This warning is not automatically turned on by the use of @option{-gnatwa}.
4717
4718 @item -gnatwL
4719 @emph{Suppress warnings for missing elaboration pragmas.}
4720 @cindex @option{-gnatwL} (@code{gcc})
4721 This switch suppresses warnings on missing pragma Elaborate_All statements.
4722 See the section in this guide on elaboration checking for details on
4723 when such pragma should be used.
4724
4725 @item -gnatwm
4726 @emph{Activate warnings on modified but unreferenced variables.}
4727 @cindex @option{-gnatwm} (@code{gcc})
4728 This switch activates warnings for variables that are assigned (using
4729 an initialization value or with one or more assignment statements) but
4730 whose value is never read. The warning is suppressed for volatile
4731 variables and also for variables that are renamings of other variables
4732 or for which an address clause is given.
4733 This warning can also be turned on using @option{-gnatwa}.
4734
4735 @item -gnatwM
4736 @emph{Disable warnings on modified but unreferenced variables.}
4737 @cindex @option{-gnatwM} (@code{gcc})
4738 This switch disables warnings for variables that are assigned or
4739 initialized, but never read.
4740
4741 @item -gnatwn
4742 @emph{Set normal warnings mode.}
4743 @cindex @option{-gnatwn} (@code{gcc})
4744 This switch sets normal warning mode, in which enabled warnings are
4745 issued and treated as warnings rather than errors. This is the default
4746 mode. the switch @option{-gnatwn} can be used to cancel the effect of
4747 an explicit @option{-gnatws} or
4748 @option{-gnatwe}. It also cancels the effect of the
4749 implicit @option{-gnatwe} that is activated by the
4750 use of @option{-gnatg}.
4751
4752 @item -gnatwo
4753 @emph{Activate warnings on address clause overlays.}
4754 @cindex @option{-gnatwo} (@code{gcc})
4755 @cindex Address Clauses, warnings
4756 This switch activates warnings for possibly unintended initialization
4757 effects of defining address clauses that cause one variable to overlap
4758 another. The default is that such warnings are generated.
4759 This warning can also be turned on using @option{-gnatwa}.
4760
4761 @item -gnatwO
4762 @emph{Suppress warnings on address clause overlays.}
4763 @cindex @option{-gnatwO} (@code{gcc})
4764 This switch suppresses warnings on possibly unintended initialization
4765 effects of defining address clauses that cause one variable to overlap
4766 another.
4767
4768 @item -gnatwp
4769 @emph{Activate warnings on ineffective pragma Inlines.}
4770 @cindex @option{-gnatwp} (@code{gcc})
4771 @cindex Inlining, warnings
4772 This switch activates warnings for failure of front end inlining
4773 (activated by @option{-gnatN}) to inline a particular call. There are
4774 many reasons for not being able to inline a call, including most
4775 commonly that the call is too complex to inline.
4776 This warning can also be turned on using @option{-gnatwa}.
4777
4778 @item -gnatwP
4779 @emph{Suppress warnings on ineffective pragma Inlines.}
4780 @cindex @option{-gnatwP} (@code{gcc})
4781 This switch suppresses warnings on ineffective pragma Inlines. If the
4782 inlining mechanism cannot inline a call, it will simply ignore the
4783 request silently.
4784
4785 @item -gnatwr
4786 @emph{Activate warnings on redundant constructs.}
4787 @cindex @option{-gnatwr} (@code{gcc})
4788 This switch activates warnings for redundant constructs. The following
4789 is the current list of constructs regarded as redundant:
4790 This warning can also be turned on using @option{-gnatwa}.
4791
4792 @itemize @bullet
4793 @item
4794 Assignment of an item to itself.
4795 @item
4796 Type conversion that converts an expression to its own type.
4797 @item
4798 Use of the attribute @code{Base} where @code{typ'Base} is the same
4799 as @code{typ}.
4800 @item
4801 Use of pragma @code{Pack} when all components are placed by a record
4802 representation clause.
4803 @item
4804 Exception handler containing only a reraise statement (raise with no
4805 operand) which has no effect.
4806 @item
4807 Use of the operator abs on an operand that is known at compile time
4808 to be non-negative
4809 @item
4810 Use of an unnecessary extra level of parentheses (C-style) around conditions
4811 in @code{if} statements, @code{while} statements and @code{exit} statements.
4812 @item
4813 Comparison of boolean expressions to an explicit True value.
4814 @end itemize
4815
4816 @item -gnatwR
4817 @emph{Suppress warnings on redundant constructs.}
4818 @cindex @option{-gnatwR} (@code{gcc})
4819 This switch suppresses warnings for redundant constructs.
4820
4821 @item -gnatws
4822 @emph{Suppress all warnings.}
4823 @cindex @option{-gnatws} (@code{gcc})
4824 This switch completely suppresses the
4825 output of all warning messages from the GNAT front end.
4826 Note that it does not suppress warnings from the @code{gcc} back end.
4827 To suppress these back end warnings as well, use the switch @option{-w}
4828 in addition to @option{-gnatws}.
4829
4830 @item -gnatwu
4831 @emph{Activate warnings on unused entities.}
4832 @cindex @option{-gnatwu} (@code{gcc})
4833 This switch activates warnings to be generated for entities that
4834 are declared but not referenced, and for units that are @code{with}'ed
4835 and not
4836 referenced. In the case of packages, a warning is also generated if
4837 no entities in the package are referenced. This means that if the package
4838 is referenced but the only references are in @code{use}
4839 clauses or @code{renames}
4840 declarations, a warning is still generated. A warning is also generated
4841 for a generic package that is @code{with}'ed but never instantiated.
4842 In the case where a package or subprogram body is compiled, and there
4843 is a @code{with} on the corresponding spec
4844 that is only referenced in the body,
4845 a warning is also generated, noting that the
4846 @code{with} can be moved to the body. The default is that
4847 such warnings are not generated.
4848 This switch also activates warnings on unreferenced formals
4849 (it is includes the effect of @option{-gnatwf}).
4850 This warning can also be turned on using @option{-gnatwa}.
4851
4852 @item -gnatwU
4853 @emph{Suppress warnings on unused entities.}
4854 @cindex @option{-gnatwU} (@code{gcc})
4855 This switch suppresses warnings for unused entities and packages.
4856 It also turns off warnings on unreferenced formals (and thus includes
4857 the effect of @option{-gnatwF}).
4858
4859 @item -gnatwv
4860 @emph{Activate warnings on unassigned variables.}
4861 @cindex @option{-gnatwv} (@code{gcc})
4862 @cindex Unassigned variable warnings
4863 This switch activates warnings for access to variables which
4864 may not be properly initialized. The default is that
4865 such warnings are generated.
4866
4867 @item -gnatwV
4868 @emph{Suppress warnings on unassigned variables.}
4869 @cindex @option{-gnatwV} (@code{gcc})
4870 This switch suppresses warnings for access to variables which
4871 may not be properly initialized.
4872
4873 @item -gnatwx
4874 @emph{Activate warnings on Export/Import pragmas.}
4875 @cindex @option{-gnatwx} (@code{gcc})
4876 @cindex Export/Import pragma warnings
4877 This switch activates warnings on Export/Import pragmas when
4878 the compiler detects a possible conflict between the Ada and
4879 foreign language calling sequences. For example, the use of
4880 default parameters in a convention C procedure is dubious
4881 because the C compiler cannot supply the proper default, so
4882 a warning is issued. The default is that such warnings are
4883 generated.
4884
4885 @item -gnatwX
4886 @emph{Suppress warnings on Export/Import pragmas.}
4887 @cindex @option{-gnatwX} (@code{gcc})
4888 This switch suppresses warnings on Export/Import pragmas.
4889 The sense of this is that you are telling the compiler that
4890 you know what you are doing in writing the pragma, and it
4891 should not complain at you.
4892
4893 @item -gnatwz
4894 @emph{Activate warnings on unchecked conversions.}
4895 @cindex @option{-gnatwz} (@code{gcc})
4896 @cindex Unchecked_Conversion warnings
4897 This switch activates warnings for unchecked conversions
4898 where the types are known at compile time to have different
4899 sizes. The default
4900 is that such warnings are generated.
4901
4902 @item -gnatwZ
4903 @emph{Suppress warnings on unchecked conversions.}
4904 @cindex @option{-gnatwZ} (@code{gcc})
4905 This switch suppresses warnings for unchecked conversions
4906 where the types are known at compile time to have different
4907 sizes.
4908
4909 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
4910 @cindex @option{-Wuninitialized}
4911 The warnings controlled by the @option{-gnatw} switch are generated by the
4912 front end of the compiler. In some cases, the @option{^gcc^GCC^} back end
4913 can provide additional warnings. One such useful warning is provided by
4914 @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^}. This must be used in
4915 conjunction with tunrning on optimization mode. This causes the flow
4916 analysis circuits of the back end optimizer to output additional
4917 warnings about uninitialized variables.
4918
4919 @item ^-w^/NO_BACK_END_WARNINGS^
4920 @cindex @option{-w}
4921 This switch suppresses warnings from the @option{^gcc^GCC^} back end. It may
4922 be used in conjunction with @option{-gnatws} to ensure that all warnings
4923 are suppressed during the entire compilation process.
4924
4925 @end table
4926
4927 @noindent
4928 @ifclear vms
4929 A string of warning parameters can be used in the same parameter. For example:
4930
4931 @smallexample
4932 -gnatwaLe
4933 @end smallexample
4934
4935 @noindent
4936 will turn on all optional warnings except for elaboration pragma warnings,
4937 and also specify that warnings should be treated as errors.
4938 @end ifclear
4939 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
4940
4941 @table @option
4942 @c !sort!
4943 @item -gnatwC
4944 @item -gnatwD
4945 @item -gnatwF
4946 @item -gnatwg
4947 @item -gnatwH
4948 @item -gnatwi
4949 @item -gnatwJ
4950 @item -gnatwK
4951 @item -gnatwL
4952 @item -gnatwM
4953 @item -gnatwn
4954 @item -gnatwo
4955 @item -gnatwP
4956 @item -gnatwR
4957 @item -gnatwU
4958 @item -gnatwv
4959 @item -gnatwz
4960 @item -gnatwx
4961
4962 @end table
4963
4964
4965 @node Debugging and Assertion Control
4966 @subsection Debugging and Assertion Control
4967
4968 @table @option
4969 @item -gnata
4970 @cindex @option{-gnata} (@code{gcc})
4971 @findex Assert
4972 @findex Debug
4973 @cindex Assertions
4974
4975 @noindent
4976 The pragmas @code{Assert} and @code{Debug} normally have no effect and
4977 are ignored. This switch, where @samp{a} stands for assert, causes
4978 @code{Assert} and @code{Debug} pragmas to be activated.
4979
4980 The pragmas have the form:
4981
4982 @smallexample
4983 @cartouche
4984    @b{pragma} Assert (@var{Boolean-expression} [,
4985                       @var{static-string-expression}])
4986    @b{pragma} Debug (@var{procedure call})
4987 @end cartouche
4988 @end smallexample
4989
4990 @noindent
4991 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
4992 If the result is @code{True}, the pragma has no effect (other than
4993 possible side effects from evaluating the expression). If the result is
4994 @code{False}, the exception @code{Assert_Failure} declared in the package
4995 @code{System.Assertions} is
4996 raised (passing @var{static-string-expression}, if present, as the
4997 message associated with the exception). If no string expression is
4998 given the default is a string giving the file name and line number
4999 of the pragma.
5000
5001 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5002 @code{pragma Debug} may appear within a declaration sequence, allowing
5003 debugging procedures to be called between declarations.
5004
5005 @ifset vms
5006 @item /DEBUG[=debug-level]
5007 @itemx  /NODEBUG
5008 Specifies how much debugging information is to be included in
5009 the resulting object file where 'debug-level' is one of the following:
5010 @table @code
5011 @item   TRACEBACK
5012 Include both debugger symbol records and traceback
5013 the object file.
5014 This is the default setting.
5015 @item   ALL
5016 Include both debugger symbol records and traceback in
5017 object file.
5018 @item   NONE
5019 Excludes both debugger symbol records and traceback
5020 the object file. Same as /NODEBUG.
5021 @item   SYMBOLS
5022 Includes only debugger symbol records in the object
5023 file. Note that this doesn't include traceback information.
5024 @end table
5025 @end ifset
5026 @end table
5027
5028 @node Validity Checking
5029 @subsection Validity Checking
5030 @findex Validity Checking
5031
5032 @noindent
5033 The Ada 95 Reference Manual has specific requirements for checking
5034 for invalid values. In particular, RM 13.9.1 requires that the
5035 evaluation of invalid values (for example from unchecked conversions),
5036 not result in erroneous execution. In GNAT, the result of such an
5037 evaluation in normal default mode is to either use the value
5038 unmodified, or to raise Constraint_Error in those cases where use
5039 of the unmodified value would cause erroneous execution. The cases
5040 where unmodified values might lead to erroneous execution are case
5041 statements (where a wild jump might result from an invalid value),
5042 and subscripts on the left hand side (where memory corruption could
5043 occur as a result of an invalid value).
5044
5045 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5046 checking mode.
5047 @ifclear vms
5048 The @code{x} argument is a string of letters that
5049 indicate validity checks that are performed or not performed in addition
5050 to the default checks described above.
5051 @end ifclear
5052 @ifset vms
5053 The options allowed for this qualifier
5054 indicate validity checks that are performed or not performed in addition
5055 to the default checks described above.
5056 @end ifset
5057
5058
5059 @table @option
5060 @c !sort!
5061 @item -gnatVa
5062 @emph{All validity checks.}
5063 @cindex @option{-gnatVa} (@code{gcc})
5064 All validity checks are turned on.
5065 @ifclear vms
5066 That is, @option{-gnatVa} is
5067 equivalent to @option{gnatVcdfimorst}.
5068 @end ifclear
5069
5070 @item -gnatVc
5071 @emph{Validity checks for copies.}
5072 @cindex @option{-gnatVc} (@code{gcc})
5073 The right hand side of assignments, and the initializing values of
5074 object declarations are validity checked.
5075
5076 @item -gnatVd
5077 @emph{Default (RM) validity checks.}
5078 @cindex @option{-gnatVd} (@code{gcc})
5079 Some validity checks are done by default following normal Ada semantics
5080 (RM 13.9.1 (9-11)).
5081 A check is done in case statements that the expression is within the range
5082 of the subtype. If it is not, Constraint_Error is raised.
5083 For assignments to array components, a check is done that the expression used
5084 as index is within the range. If it is not, Constraint_Error is raised.
5085 Both these validity checks may be turned off using switch @option{-gnatVD}.
5086 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5087 switch @option{-gnatVd} will leave the checks turned on.
5088 Switch @option{-gnatVD} should be used only if you are sure that all such
5089 expressions have valid values. If you use this switch and invalid values
5090 are present, then the program is erroneous, and wild jumps or memory
5091 overwriting may occur.
5092
5093 @item -gnatVf
5094 @emph{Validity checks for floating-point values.}
5095 @cindex @option{-gnatVf} (@code{gcc})
5096 In the absence of this switch, validity checking occurs only for discrete
5097 values. If @option{-gnatVf} is specified, then validity checking also applies
5098 for floating-point values, and NaN's and infinities are considered invalid,
5099 as well as out of range values for constrained types. Note that this means
5100 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
5101 in which floating-point values are checked depends on the setting of other
5102 options. For example,
5103 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5104 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5105 (the order does not matter) specifies that floating-point parameters of mode
5106 @code{in} should be validity checked.
5107
5108 @item -gnatVi
5109 @emph{Validity checks for @code{in} mode parameters}
5110 @cindex @option{-gnatVi} (@code{gcc})
5111 Arguments for parameters of mode @code{in} are validity checked in function
5112 and procedure calls at the point of call.
5113
5114 @item -gnatVm
5115 @emph{Validity checks for @code{in out} mode parameters.}
5116 @cindex @option{-gnatVm} (@code{gcc})
5117 Arguments for parameters of mode @code{in out} are validity checked in
5118 procedure calls at the point of call. The @code{'m'} here stands for
5119 modify, since this concerns parameters that can be modified by the call.
5120 Note that there is no specific option to test @code{out} parameters,
5121 but any reference within the subprogram will be tested in the usual
5122 manner, and if an invalid value is copied back, any reference to it
5123 will be subject to validity checking.
5124
5125 @item -gnatVn
5126 @emph{No validity checks.}
5127 @cindex @option{-gnatVn} (@code{gcc})
5128 This switch turns off all validity checking, including the default checking
5129 for case statements and left hand side subscripts. Note that the use of
5130 the switch @option{-gnatp} suppresses all run-time checks, including
5131 validity checks, and thus implies @option{-gnatVn}. When this switch
5132 is used, it cancels any other @option{-gnatV} previously issued.
5133
5134 @item -gnatVo
5135 @emph{Validity checks for operator and attribute operands.}
5136 @cindex @option{-gnatVo} (@code{gcc})
5137 Arguments for predefined operators and attributes are validity checked.
5138 This includes all operators in package @code{Standard},
5139 the shift operators defined as intrinsic in package @code{Interfaces}
5140 and operands for attributes such as @code{Pos}. Checks are also made
5141 on individual component values for composite comparisons.
5142
5143 @item -gnatVp
5144 @emph{Validity checks for parameters.}
5145 @cindex @option{-gnatVp} (@code{gcc})
5146 This controls the treatment of parameters within a subprogram (as opposed
5147 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5148 of parameters on a call. If either of these call options is used, then
5149 normally an assumption is made within a subprogram that the input arguments
5150 have been validity checking at the point of call, and do not need checking
5151 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5152 is not made, and parameters are not assumed to be valid, so their validity
5153 will be checked (or rechecked) within the subprogram.
5154
5155 @item -gnatVr
5156 @emph{Validity checks for function returns.}
5157 @cindex @option{-gnatVr} (@code{gcc})
5158 The expression in @code{return} statements in functions is validity
5159 checked.
5160
5161 @item -gnatVs
5162 @emph{Validity checks for subscripts.}
5163 @cindex @option{-gnatVs} (@code{gcc})
5164 All subscripts expressions are checked for validity, whether they appear
5165 on the right side or left side (in default mode only left side subscripts
5166 are validity checked).
5167
5168 @item -gnatVt
5169 @emph{Validity checks for tests.}
5170 @cindex @option{-gnatVt} (@code{gcc})
5171 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5172 statements are checked, as well as guard expressions in entry calls.
5173
5174 @end table
5175
5176 @noindent
5177 The @option{-gnatV} switch may be followed by
5178 ^a string of letters^a list of options^
5179 to turn on a series of validity checking options.
5180 For example,
5181 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5182 specifies that in addition to the default validity checking, copies and
5183 function return expressions are to be validity checked.
5184 In order to make it easier
5185 to specify the desired combination of effects,
5186 @ifclear vms
5187 the upper case letters @code{CDFIMORST} may
5188 be used to turn off the corresponding lower case option.
5189 @end ifclear
5190 @ifset vms
5191 the prefix @code{NO} on an option turns off the corresponding validity
5192 checking:
5193 @itemize @bullet
5194 @item @code{NOCOPIES}
5195 @item @code{NODEFAULT}
5196 @item @code{NOFLOATS}
5197 @item @code{NOIN_PARAMS}
5198 @item @code{NOMOD_PARAMS}
5199 @item @code{NOOPERANDS}
5200 @item @code{NORETURNS}
5201 @item @code{NOSUBSCRIPTS}
5202 @item @code{NOTESTS}
5203 @end itemize
5204 @end ifset
5205 Thus
5206 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5207 turns on all validity checking options except for
5208 checking of @code{@b{in out}} procedure arguments.
5209
5210 The specification of additional validity checking generates extra code (and
5211 in the case of @option{-gnatVa} the code expansion can be substantial.
5212 However, these additional checks can be very useful in detecting
5213 uninitialized variables, incorrect use of unchecked conversion, and other
5214 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5215 is useful in conjunction with the extra validity checking, since this
5216 ensures that wherever possible uninitialized variables have invalid values.
5217
5218 See also the pragma @code{Validity_Checks} which allows modification of
5219 the validity checking mode at the program source level, and also allows for
5220 temporary disabling of validity checks.
5221
5222
5223 @node Style Checking
5224 @subsection Style Checking
5225 @findex Style checking
5226
5227 @noindent
5228 The @option{-gnaty^x^(option,option,...)^} switch
5229 @cindex @option{-gnaty} (@code{gcc})
5230 causes the compiler to
5231 enforce specified style rules. A limited set of style rules has been used
5232 in writing the GNAT sources themselves. This switch allows user programs
5233 to activate all or some of these checks. If the source program fails a
5234 specified style check, an appropriate warning message is given, preceded by
5235 the character sequence ``(style)''.
5236 @ifset vms
5237 @code{(option,option,...)} is a sequence of keywords
5238 @end ifset
5239 @ifclear vms
5240 The string @var{x} is a sequence of letters or digits
5241 @end ifclear
5242 indicating the particular style
5243 checks to be performed. The following checks are defined:
5244
5245 @table @option
5246 @c !sort!
5247 @item 1-9
5248 @emph{Specify indentation level.}
5249 If a digit from 1-9 appears
5250 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5251 then proper indentation is checked, with the digit indicating the
5252 indentation level required.
5253 The general style of required indentation is as specified by
5254 the examples in the Ada Reference Manual. Full line comments must be
5255 aligned with the @code{--} starting on a column that is a multiple of
5256 the alignment level.
5257
5258 @item ^a^ATTRIBUTE^
5259 @emph{Check attribute casing.}
5260 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty}
5261 then attribute names, including the case of keywords such as @code{digits}
5262 used as attributes names, must be written in mixed case, that is, the
5263 initial letter and any letter following an underscore must be uppercase.
5264 All other letters must be lowercase.
5265
5266 @item ^b^BLANKS^
5267 @emph{Blanks not allowed at statement end.}
5268 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
5269 trailing blanks are not allowed at the end of statements. The purpose of this
5270 rule, together with h (no horizontal tabs), is to enforce a canonical format
5271 for the use of blanks to separate source tokens.
5272
5273 @item ^c^COMMENTS^
5274 @emph{Check comments.}
5275 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty}
5276 then comments must meet the following set of rules:
5277
5278 @itemize @bullet
5279
5280 @item
5281 The ``@code{--}'' that starts the column must either start in column one,
5282 or else at least one blank must precede this sequence.
5283
5284 @item
5285 Comments that follow other tokens on a line must have at least one blank
5286 following the ``@code{--}'' at the start of the comment.
5287
5288 @item
5289 Full line comments must have two blanks following the ``@code{--}'' that
5290 starts the comment, with the following exceptions.
5291
5292 @item
5293 A line consisting only of the ``@code{--}'' characters, possibly preceded
5294 by blanks is permitted.
5295
5296 @item
5297 A comment starting with ``@code{--x}'' where @code{x} is a special character
5298 is permitted.
5299 This allows proper processing of the output generated by specialized tools
5300 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5301 annotation
5302 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5303 special character is defined as being in one of the ASCII ranges
5304 @code{16#21#..16#2F#} or @code{16#3A#..16#3F#}.
5305 Note that this usage is not permitted
5306 in GNAT implementation units (i.e. when @option{-gnatg} is used).
5307
5308 @item
5309 A line consisting entirely of minus signs, possibly preceded by blanks, is
5310 permitted. This allows the construction of box comments where lines of minus
5311 signs are used to form the top and bottom of the box.
5312
5313 @item
5314 If a comment starts and ends with ``@code{--}'' is permitted as long as at
5315 least one blank follows the initial ``@code{--}''. Together with the preceding
5316 rule, this allows the construction of box comments, as shown in the following
5317 example:
5318 @smallexample
5319 ---------------------------
5320 -- This is a box comment --
5321 -- with two text lines.  --
5322 ---------------------------
5323 @end smallexample
5324 @end itemize
5325
5326 @item ^e^END^
5327 @emph{Check end/exit labels.}
5328 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
5329 optional labels on @code{end} statements ending subprograms and on
5330 @code{exit} statements exiting named loops, are required to be present.
5331
5332 @item ^f^VTABS^
5333 @emph{No form feeds or vertical tabs.}
5334 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
5335 neither form feeds nor vertical tab characters are not permitted
5336 in the source text.
5337
5338 @item ^h^HTABS^
5339 @emph{No horizontal tabs.}
5340 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
5341 horizontal tab characters are not permitted in the source text.
5342 Together with the b (no blanks at end of line) check, this
5343 enforces a canonical form for the use of blanks to separate
5344 source tokens.
5345
5346 @item ^i^IF_THEN^
5347 @emph{Check if-then layout.}
5348 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
5349 then the keyword @code{then} must appear either on the same
5350 line as corresponding @code{if}, or on a line on its own, lined
5351 up under the @code{if} with at least one non-blank line in between
5352 containing all or part of the condition to be tested.
5353
5354 @item ^k^KEYWORD^
5355 @emph{Check keyword casing.}
5356 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
5357 all keywords must be in lower case (with the exception of keywords
5358 such as @code{digits} used as attribute names to which this check
5359 does not apply).
5360
5361 @item ^l^LAYOUT^
5362 @emph{Check layout.}
5363 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
5364 layout of statement and declaration constructs must follow the
5365 recommendations in the Ada Reference Manual, as indicated by the
5366 form of the syntax rules. For example an @code{else} keyword must
5367 be lined up with the corresponding @code{if} keyword.
5368
5369 There are two respects in which the style rule enforced by this check
5370 option are more liberal than those in the Ada Reference Manual. First
5371 in the case of record declarations, it is permissible to put the
5372 @code{record} keyword on the same line as the @code{type} keyword, and
5373 then the @code{end} in @code{end record} must line up under @code{type}.
5374 For example, either of the following two layouts is acceptable:
5375
5376 @smallexample @c ada
5377 @cartouche
5378 type q is record
5379    a : integer;
5380    b : integer;
5381 end record;
5382
5383 type q is
5384    record
5385       a : integer;
5386       b : integer;
5387    end record;
5388 @end cartouche
5389 @end smallexample
5390
5391 @noindent
5392 Second, in the case of a block statement, a permitted alternative
5393 is to put the block label on the same line as the @code{declare} or
5394 @code{begin} keyword, and then line the @code{end} keyword up under
5395 the block label. For example both the following are permitted:
5396
5397 @smallexample @c ada
5398 @cartouche
5399 Block : declare
5400    A : Integer := 3;
5401 begin
5402    Proc (A, A);
5403 end Block;
5404
5405 Block :
5406    declare
5407       A : Integer := 3;
5408    begin
5409       Proc (A, A);
5410    end Block;
5411 @end cartouche
5412 @end smallexample
5413
5414 @noindent
5415 The same alternative format is allowed for loops. For example, both of
5416 the following are permitted:
5417
5418 @smallexample @c ada
5419 @cartouche
5420 Clear : while J < 10 loop
5421    A (J) := 0;
5422 end loop Clear;
5423
5424 Clear :
5425    while J < 10 loop
5426       A (J) := 0;
5427    end loop Clear;
5428 @end cartouche
5429 @end smallexample
5430
5431 @item ^m^LINE_LENGTH^
5432 @emph{Check maximum line length.}
5433 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
5434 then the length of source lines must not exceed 79 characters, including
5435 any trailing blanks. The value of 79 allows convenient display on an
5436 80 character wide device or window, allowing for possible special
5437 treatment of 80 character lines. Note that this count is of raw
5438 characters in the source text. This means that a tab character counts
5439 as one character in this count and a wide character sequence counts as
5440 several characters (however many are needed in the encoding).
5441
5442 @item ^Mnnn^MAX_LENGTH=nnn^
5443 @emph{Set maximum line length.}
5444 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
5445 the string after @option{-gnaty} then the length of lines must not exceed the
5446 given value.
5447
5448 @item ^n^STANDARD_CASING^
5449 @emph{Check casing of entities in Standard.}
5450 If the ^letter n^word STANDARD_CASING^ appears in the string
5451 after @option{-gnaty} then any identifier from Standard must be cased
5452 to match the presentation in the Ada Reference Manual (for example,
5453 @code{Integer} and @code{ASCII.NUL}).
5454
5455 @item ^o^ORDERED_SUBPROGRAMS^
5456 @emph{Check order of subprogram bodies.}
5457 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
5458 after @option{-gnaty} then all subprogram bodies in a given scope
5459 (e.g. a package body) must be in alphabetical order. The ordering
5460 rule uses normal Ada rules for comparing strings, ignoring casing
5461 of letters, except that if there is a trailing numeric suffix, then
5462 the value of this suffix is used in the ordering (e.g. Junk2 comes
5463 before Junk10).
5464
5465 @item ^p^PRAGMA^
5466 @emph{Check pragma casing.}
5467 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
5468 pragma names must be written in mixed case, that is, the
5469 initial letter and any letter following an underscore must be uppercase.
5470 All other letters must be lowercase.
5471
5472 @item ^r^REFERENCES^
5473 @emph{Check references.}
5474 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
5475 then all identifier references must be cased in the same way as the
5476 corresponding declaration. No specific casing style is imposed on
5477 identifiers. The only requirement is for consistency of references
5478 with declarations.
5479
5480 @item ^s^SPECS^
5481 @emph{Check separate specs.}
5482 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
5483 separate declarations (``specs'') are required for subprograms (a
5484 body is not allowed to serve as its own declaration). The only
5485 exception is that parameterless library level procedures are
5486 not required to have a separate declaration. This exception covers
5487 the most frequent form of main program procedures.
5488
5489 @item ^t^TOKEN^
5490 @emph{Check token spacing.}
5491 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
5492 the following token spacing rules are enforced:
5493
5494 @itemize @bullet
5495
5496 @item
5497 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
5498
5499 @item
5500 The token @code{=>} must be surrounded by spaces.
5501
5502 @item
5503 The token @code{<>} must be preceded by a space or a left parenthesis.
5504
5505 @item
5506 Binary operators other than @code{**} must be surrounded by spaces.
5507 There is no restriction on the layout of the @code{**} binary operator.
5508
5509 @item
5510 Colon must be surrounded by spaces.
5511
5512 @item
5513 Colon-equal (assignment, initialization) must be surrounded by spaces.
5514
5515 @item
5516 Comma must be the first non-blank character on the line, or be
5517 immediately preceded by a non-blank character, and must be followed
5518 by a space.
5519
5520 @item
5521 If the token preceding a left parenthesis ends with a letter or digit, then
5522 a space must separate the two tokens.
5523
5524 @item
5525 A right parenthesis must either be the first non-blank character on
5526 a line, or it must be preceded by a non-blank character.
5527
5528 @item
5529 A semicolon must not be preceded by a space, and must not be followed by
5530 a non-blank character.
5531
5532 @item
5533 A unary plus or minus may not be followed by a space.
5534
5535 @item
5536 A vertical bar must be surrounded by spaces.
5537 @end itemize
5538
5539 @noindent
5540 In the above rules, appearing in column one is always permitted, that is,
5541 counts as meeting either a requirement for a required preceding space,
5542 or as meeting a requirement for no preceding space.
5543
5544 Appearing at the end of a line is also always permitted, that is, counts
5545 as meeting either a requirement for a following space, or as meeting
5546 a requirement for no following space.
5547
5548 @end table
5549
5550 @noindent
5551 If any of these style rules is violated, a message is generated giving
5552 details on the violation. The initial characters of such messages are
5553 always ``@code{(style)}''. Note that these messages are treated as warning
5554 messages, so they normally do not prevent the generation of an object
5555 file. The @option{-gnatwe} switch can be used to treat warning messages,
5556 including style messages, as fatal errors.
5557
5558 The switch
5559 @ifclear vms
5560 @option{-gnaty} on its own (that is not
5561 followed by any letters or digits),
5562 is equivalent to @code{gnaty3abcefhiklmprst}, that is all checking
5563 options enabled with the exception of -gnatyo,
5564 @end ifclear
5565 @ifset vms
5566 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
5567 the exception of ORDERED_SUBPROGRAMS,
5568 @end ifset
5569 with an indentation level of 3. This is the standard
5570 checking option that is used for the GNAT sources.
5571
5572 The switch
5573 @ifclear vms
5574 @option{-gnatyN}
5575 @end ifclear
5576 @ifset vms
5577 /STYLE_CHECKS=NONE
5578 @end ifset
5579 clears any previously set style checks.
5580
5581 @node Run-Time Checks
5582 @subsection Run-Time Checks
5583 @cindex Division by zero
5584 @cindex Access before elaboration
5585 @cindex Checks, division by zero
5586 @cindex Checks, access before elaboration
5587
5588 @noindent
5589 If you compile with the default options, GNAT will insert many run-time
5590 checks into the compiled code, including code that performs range
5591 checking against constraints, but not arithmetic overflow checking for
5592 integer operations (including division by zero) or checks for access
5593 before elaboration on subprogram calls. All other run-time checks, as
5594 required by the Ada 95 Reference Manual, are generated by default.
5595 The following @code{gcc} switches refine this default behavior:
5596
5597 @table @option
5598 @c !sort!
5599 @item -gnatp
5600 @cindex @option{-gnatp} (@code{gcc})
5601 @cindex Suppressing checks
5602 @cindex Checks, suppressing
5603 @findex Suppress
5604 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
5605 had been present in the source. Validity checks are also suppressed (in
5606 other words @option{-gnatp} also implies @option{-gnatVn}.
5607 Use this switch to improve the performance
5608 of the code at the expense of safety in the presence of invalid data or
5609 program bugs.
5610
5611 @item -gnato
5612 @cindex @option{-gnato} (@code{gcc})
5613 @cindex Overflow checks
5614 @cindex Check, overflow
5615 Enables overflow checking for integer operations.
5616 This causes GNAT to generate slower and larger executable
5617 programs by adding code to check for overflow (resulting in raising
5618 @code{Constraint_Error} as required by standard Ada
5619 semantics). These overflow checks correspond to situations in which
5620 the true value of the result of an operation may be outside the base
5621 range of the result type. The following example shows the distinction:
5622
5623 @smallexample @c ada
5624 X1 : Integer := Integer'Last;
5625 X2 : Integer range 1 .. 5 := 5;
5626 X3 : Integer := Integer'Last;
5627 X4 : Integer range 1 .. 5 := 5;
5628 F  : Float := 2.0E+20;
5629 ...
5630 X1 := X1 + 1;
5631 X2 := X2 + 1;
5632 X3 := Integer (F);
5633 X4 := Integer (F);
5634 @end smallexample
5635
5636 @noindent
5637 Here the first addition results in a value that is outside the base range
5638 of Integer, and hence requires an overflow check for detection of the
5639 constraint error. Thus the first assignment to @code{X1} raises a
5640 @code{Constraint_Error} exception only if @option{-gnato} is set.
5641
5642 The second increment operation results in a violation
5643 of the explicit range constraint, and such range checks are always
5644 performed (unless specifically suppressed with a pragma @code{suppress}
5645 or the use of @option{-gnatp}).
5646
5647 The two conversions of @code{F} both result in values that are outside
5648 the base range of type @code{Integer} and thus will raise
5649 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
5650 The fact that the result of the second conversion is assigned to
5651 variable @code{X4} with a restricted range is irrelevant, since the problem
5652 is in the conversion, not the assignment.
5653
5654 Basically the rule is that in the default mode (@option{-gnato} not
5655 used), the generated code assures that all integer variables stay
5656 within their declared ranges, or within the base range if there is
5657 no declared range. This prevents any serious problems like indexes
5658 out of range for array operations.
5659
5660 What is not checked in default mode is an overflow that results in
5661 an in-range, but incorrect value. In the above example, the assignments
5662 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
5663 range of the target variable, but the result is wrong in the sense that
5664 it is too large to be represented correctly. Typically the assignment
5665 to @code{X1} will result in wrap around to the largest negative number.
5666 The conversions of @code{F} will result in some @code{Integer} value
5667 and if that integer value is out of the @code{X4} range then the
5668 subsequent assignment would generate an exception.
5669
5670 @findex Machine_Overflows
5671 Note that the @option{-gnato} switch does not affect the code generated
5672 for any floating-point operations; it applies only to integer
5673 semantics).
5674 For floating-point, GNAT has the @code{Machine_Overflows}
5675 attribute set to @code{False} and the normal mode of operation is to
5676 generate IEEE NaN and infinite values on overflow or invalid operations
5677 (such as dividing 0.0 by 0.0).
5678
5679 The reason that we distinguish overflow checking from other kinds of
5680 range constraint checking is that a failure of an overflow check can
5681 generate an incorrect value, but cannot cause erroneous behavior. This
5682 is unlike the situation with a constraint check on an array subscript,
5683 where failure to perform the check can result in random memory description,
5684 or the range check on a case statement, where failure to perform the check
5685 can cause a wild jump.
5686
5687 Note again that @option{-gnato} is off by default, so overflow checking is
5688 not performed in default mode. This means that out of the box, with the
5689 default settings, GNAT does not do all the checks expected from the
5690 language description in the Ada Reference Manual. If you want all constraint
5691 checks to be performed, as described in this Manual, then you must
5692 explicitly use the -gnato switch either on the @code{gnatmake} or
5693 @code{gcc} command.
5694
5695 @item -gnatE
5696 @cindex @option{-gnatE} (@code{gcc})
5697 @cindex Elaboration checks
5698 @cindex Check, elaboration
5699 Enables dynamic checks for access-before-elaboration
5700 on subprogram calls and generic instantiations.
5701 For full details of the effect and use of this switch,
5702 @xref{Compiling Using gcc}.
5703 @end table
5704
5705 @findex Unsuppress
5706 @noindent
5707 The setting of these switches only controls the default setting of the
5708 checks. You may modify them using either @code{Suppress} (to remove
5709 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
5710 the program source.
5711
5712 @node Stack Overflow Checking
5713 @subsection Stack Overflow Checking
5714 @cindex Stack Overflow Checking
5715 @cindex -fstack-check
5716
5717 @noindent
5718 For most operating systems, @code{gcc} does not perform stack overflow
5719 checking by default. This means that if the main environment task or
5720 some other task exceeds the available stack space, then unpredictable
5721 behavior will occur.
5722
5723 To activate stack checking, compile all units with the gcc option
5724 @option{-fstack-check}. For example:
5725
5726 @smallexample
5727 gcc -c -fstack-check package1.adb
5728 @end smallexample
5729
5730 @noindent
5731 Units compiled with this option will generate extra instructions to check
5732 that any use of the stack (for procedure calls or for declaring local
5733 variables in declare blocks) do not exceed the available stack space.
5734 If the space is exceeded, then a @code{Storage_Error} exception is raised.
5735
5736 For declared tasks, the stack size is always controlled by the size
5737 given in an applicable @code{Storage_Size} pragma (or is set to
5738 the default size if no pragma is used.
5739
5740 For the environment task, the stack size depends on
5741 system defaults and is unknown to the compiler. The stack
5742 may even dynamically grow on some systems, precluding the
5743 normal Ada semantics for stack overflow. In the worst case,
5744 unbounded stack usage, causes unbounded stack expansion
5745 resulting in the system running out of virtual memory.
5746
5747 The stack checking may still work correctly if a fixed
5748 size stack is allocated, but this cannot be guaranteed.
5749 To ensure that a clean exception is signalled for stack
5750 overflow, set the environment variable
5751 @code{GNAT_STACK_LIMIT} to indicate the maximum
5752 stack area that can be used, as in:
5753 @cindex GNAT_STACK_LIMIT
5754
5755 @smallexample
5756 SET GNAT_STACK_LIMIT 1600
5757 @end smallexample
5758
5759 @noindent
5760 The limit is given in kilobytes, so the above declaration would
5761 set the stack limit of the environment task to 1.6 megabytes.
5762 Note that the only purpose of this usage is to limit the amount
5763 of stack used by the environment task. If it is necessary to
5764 increase the amount of stack for the environment task, then this
5765 is an operating systems issue, and must be addressed with the
5766 appropriate operating systems commands.
5767
5768
5769 @node Using gcc for Syntax Checking
5770 @subsection Using @code{gcc} for Syntax Checking
5771 @table @option
5772 @item -gnats
5773 @cindex @option{-gnats} (@code{gcc})
5774 @ifclear vms
5775
5776 @noindent
5777 The @code{s} stands for ``syntax''.
5778 @end ifclear
5779
5780 Run GNAT in syntax checking only mode. For
5781 example, the command
5782
5783 @smallexample
5784 $ gcc -c -gnats x.adb
5785 @end smallexample
5786
5787 @noindent
5788 compiles file @file{x.adb} in syntax-check-only mode. You can check a
5789 series of files in a single command
5790 @ifclear vms
5791 , and can use wild cards to specify such a group of files.
5792 Note that you must specify the @option{-c} (compile
5793 only) flag in addition to the @option{-gnats} flag.
5794 @end ifclear
5795 .
5796 You may use other switches in conjunction with @option{-gnats}. In
5797 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
5798 format of any generated error messages.
5799
5800 When the source file is empty or contains only empty lines and/or comments,
5801 the output is a warning:
5802
5803 @smallexample
5804 $ gcc -c -gnats -x ada toto.txt
5805 toto.txt:1:01: warning: empty file, contains no compilation units
5806 $
5807 @end smallexample
5808
5809 Otherwise, the output is simply the error messages, if any. No object file or
5810 ALI file is generated by a syntax-only compilation. Also, no units other
5811 than the one specified are accessed. For example, if a unit @code{X}
5812 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
5813 check only mode does not access the source file containing unit
5814 @code{Y}.
5815
5816 @cindex Multiple units, syntax checking
5817 Normally, GNAT allows only a single unit in a source file. However, this
5818 restriction does not apply in syntax-check-only mode, and it is possible
5819 to check a file containing multiple compilation units concatenated
5820 together. This is primarily used by the @code{gnatchop} utility
5821 (@pxref{Renaming Files Using gnatchop}).
5822 @end table
5823
5824
5825 @node Using gcc for Semantic Checking
5826 @subsection Using @code{gcc} for Semantic Checking
5827 @table @option
5828 @item -gnatc
5829 @cindex @option{-gnatc} (@code{gcc})
5830
5831 @ifclear vms
5832 @noindent
5833 The @code{c} stands for ``check''.
5834 @end ifclear
5835 Causes the compiler to operate in semantic check mode,
5836 with full checking for all illegalities specified in the
5837 Ada 95 Reference Manual, but without generation of any object code
5838 (no object file is generated).
5839
5840 Because dependent files must be accessed, you must follow the GNAT
5841 semantic restrictions on file structuring to operate in this mode:
5842
5843 @itemize @bullet
5844 @item
5845 The needed source files must be accessible
5846 (@pxref{Search Paths and the Run-Time Library (RTL)}).
5847
5848 @item
5849 Each file must contain only one compilation unit.
5850
5851 @item
5852 The file name and unit name must match (@pxref{File Naming Rules}).
5853 @end itemize
5854
5855 The output consists of error messages as appropriate. No object file is
5856 generated. An @file{ALI} file is generated for use in the context of
5857 cross-reference tools, but this file is marked as not being suitable
5858 for binding (since no object file is generated).
5859 The checking corresponds exactly to the notion of
5860 legality in the Ada 95 Reference Manual.
5861
5862 Any unit can be compiled in semantics-checking-only mode, including
5863 units that would not normally be compiled (subunits,
5864 and specifications where a separate body is present).
5865 @end table
5866
5867 @node Compiling Ada 83 Programs
5868 @subsection Compiling Ada 83 Programs
5869 @table @option
5870 @cindex Ada 83 compatibility
5871 @item -gnat83
5872 @cindex @option{-gnat83} (@code{gcc})
5873 @cindex ACVC, Ada 83 tests
5874
5875 @noindent
5876 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
5877 specify that an Ada 83 program is to be compiled in Ada 83 mode. If you specify
5878 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
5879 where this can be done easily.
5880 It is not possible to guarantee this switch does a perfect
5881 job; for example, some subtle tests, such as are
5882 found in earlier ACVC tests (and that have been removed from the ACATS suite
5883 for Ada 95), might not compile correctly.
5884 Nevertheless, this switch may be useful in some circumstances, for example
5885 where, due to contractual reasons, legacy code needs to be maintained
5886 using only Ada 83 features.
5887
5888 With few exceptions (most notably the need to use @code{<>} on
5889 @cindex Generic formal parameters
5890 unconstrained generic formal parameters, the use of the new Ada 95
5891 reserved words, and the use of packages
5892 with optional bodies), it is not necessary to use the
5893 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
5894 exceptions, Ada 95 is upwardly compatible with Ada 83. This
5895 means that a correct Ada 83 program is usually also a correct Ada 95
5896 program.
5897 For further information, please refer to @ref{Compatibility and Porting Guide}.
5898
5899 @end table
5900
5901 @node Character Set Control
5902 @subsection Character Set Control
5903 @table @option
5904 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
5905 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc})
5906
5907 @noindent
5908 Normally GNAT recognizes the Latin-1 character set in source program
5909 identifiers, as described in the Ada 95 Reference Manual.
5910 This switch causes
5911 GNAT to recognize alternate character sets in identifiers. @var{c} is a
5912 single character ^^or word^ indicating the character set, as follows:
5913
5914 @table @code
5915 @item 1
5916 ISO 8859-1 (Latin-1) identifiers
5917
5918 @item 2
5919 ISO 8859-2 (Latin-2) letters allowed in identifiers
5920
5921 @item 3
5922 ISO 8859-3 (Latin-3) letters allowed in identifiers
5923
5924 @item 4
5925 ISO 8859-4 (Latin-4) letters allowed in identifiers
5926
5927 @item 5
5928 ISO 8859-5 (Cyrillic) letters allowed in identifiers
5929
5930 @item 9
5931 ISO 8859-15 (Latin-9) letters allowed in identifiers
5932
5933 @item ^p^PC^
5934 IBM PC letters (code page 437) allowed in identifiers
5935
5936 @item ^8^PC850^
5937 IBM PC letters (code page 850) allowed in identifiers
5938
5939 @item ^f^FULL_UPPER^
5940 Full upper-half codes allowed in identifiers
5941
5942 @item ^n^NO_UPPER^
5943 No upper-half codes allowed in identifiers
5944
5945 @item ^w^WIDE^
5946 Wide-character codes (that is, codes greater than 255)
5947 allowed in identifiers
5948 @end table
5949
5950 @xref{Foreign Language Representation}, for full details on the
5951 implementation of these character sets.
5952
5953 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
5954 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc})
5955 Specify the method of encoding for wide characters.
5956 @var{e} is one of the following:
5957
5958 @table @code
5959
5960 @item ^h^HEX^
5961 Hex encoding (brackets coding also recognized)
5962
5963 @item ^u^UPPER^
5964 Upper half encoding (brackets encoding also recognized)
5965
5966 @item ^s^SHIFT_JIS^
5967 Shift/JIS encoding (brackets encoding also recognized)
5968
5969 @item ^e^EUC^
5970 EUC encoding (brackets encoding also recognized)
5971
5972 @item ^8^UTF8^
5973 UTF-8 encoding (brackets encoding also recognized)
5974
5975 @item ^b^BRACKETS^
5976 Brackets encoding only (default value)
5977 @end table
5978 For full details on the these encoding
5979 methods see @xref{Wide Character Encodings}.
5980 Note that brackets coding is always accepted, even if one of the other
5981 options is specified, so for example @option{-gnatW8} specifies that both
5982 brackets and @code{UTF-8} encodings will be recognized. The units that are
5983 with'ed directly or indirectly will be scanned using the specified
5984 representation scheme, and so if one of the non-brackets scheme is
5985 used, it must be used consistently throughout the program. However,
5986 since brackets encoding is always recognized, it may be conveniently
5987 used in standard libraries, allowing these libraries to be used with
5988 any of the available coding schemes.
5989 scheme. If no @option{-gnatW?} parameter is present, then the default
5990 representation is Brackets encoding only.
5991
5992 Note that the wide character representation that is specified (explicitly
5993 or by default) for the main program also acts as the default encoding used
5994 for Wide_Text_IO files if not specifically overridden by a WCEM form
5995 parameter.
5996
5997 @end table
5998 @node File Naming Control
5999 @subsection File Naming Control
6000
6001 @table @option
6002 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6003 @cindex @option{-gnatk} (@code{gcc})
6004 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6005 1-999, indicates the maximum allowable length of a file name (not
6006 including the @file{.ads} or @file{.adb} extension). The default is not
6007 to enable file name krunching.
6008
6009 For the source file naming rules, @xref{File Naming Rules}.
6010 @end table
6011
6012
6013 @node Subprogram Inlining Control
6014 @subsection Subprogram Inlining Control
6015
6016 @table @option
6017 @c !sort!
6018 @item -gnatn
6019 @cindex @option{-gnatn} (@code{gcc})
6020 @ifclear vms
6021 The @code{n} here is intended to suggest the first syllable of the
6022 word ``inline''.
6023 @end ifclear
6024 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6025 inlining to actually occur, optimization must be enabled. To enable
6026 inlining of subprograms specified by pragma @code{Inline},
6027 you must also specify this switch.
6028 In the absence of this switch, GNAT does not attempt
6029 inlining and does not need to access the bodies of
6030 subprograms for which @code{pragma Inline} is specified if they are not
6031 in the current unit.
6032
6033 If you specify this switch the compiler will access these bodies,
6034 creating an extra source dependency for the resulting object file, and
6035 where possible, the call will be inlined.
6036 For further details on when inlining is possible
6037 see @xref{Inlining of Subprograms}.
6038
6039 @item -gnatN
6040 @cindex @option{-gnatN} (@code{gcc})
6041 The front end inlining activated by this switch is generally more extensive,
6042 and quite often more effective than the standard @option{-gnatn} inlining mode.
6043 It will also generate additional dependencies.
6044 Note that
6045 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6046 to specify both options.
6047 @end table
6048
6049 @node Auxiliary Output Control
6050 @subsection Auxiliary Output Control
6051
6052 @table @option
6053 @item -gnatt
6054 @cindex @option{-gnatt} (@code{gcc})
6055 @cindex Writing internal trees
6056 @cindex Internal trees, writing to file
6057 Causes GNAT to write the internal tree for a unit to a file (with the
6058 extension @file{.adt}.
6059 This not normally required, but is used by separate analysis tools.
6060 Typically
6061 these tools do the necessary compilations automatically, so you should
6062 not have to specify this switch in normal operation.
6063
6064 @item -gnatu
6065 @cindex @option{-gnatu} (@code{gcc})
6066 Print a list of units required by this compilation on @file{stdout}.
6067 The listing includes all units on which the unit being compiled depends
6068 either directly or indirectly.
6069
6070 @ifclear vms
6071 @item -pass-exit-codes
6072 @cindex @option{-pass-exit-codes} (@code{gcc})
6073 If this switch is not used, the exit code returned by @code{gcc} when
6074 compiling multiple files indicates whether all source files have
6075 been successfully used to generate object files or not.
6076
6077 When @option{-pass-exit-codes} is used, @code{gcc} exits with an extended
6078 exit status and allows an integrated development environment to better
6079 react to a compilation failure. Those exit status are:
6080
6081 @table @asis
6082 @item 5
6083 There was an error in at least one source file.
6084 @item 3
6085 At least one source file did not generate an object file.
6086 @item 2
6087 The compiler died unexpectedly (internal error for example).
6088 @item 0
6089 An object file has been generated for every source file.
6090 @end table
6091 @end ifclear
6092 @end table
6093
6094 @node Debugging Control
6095 @subsection Debugging Control
6096
6097 @table @option
6098 @c !sort!
6099 @cindex Debugging options
6100 @ifclear vms
6101 @item -gnatd@var{x}
6102 @cindex @option{-gnatd} (@code{gcc})
6103 Activate internal debugging switches. @var{x} is a letter or digit, or
6104 string of letters or digits, which specifies the type of debugging
6105 outputs desired. Normally these are used only for internal development
6106 or system debugging purposes. You can find full documentation for these
6107 switches in the body of the @code{Debug} unit in the compiler source
6108 file @file{debug.adb}.
6109 @end ifclear
6110
6111 @item -gnatG
6112 @cindex @option{-gnatG} (@code{gcc})
6113 This switch causes the compiler to generate auxiliary output containing
6114 a pseudo-source listing of the generated expanded code. Like most Ada
6115 compilers, GNAT works by first transforming the high level Ada code into
6116 lower level constructs. For example, tasking operations are transformed
6117 into calls to the tasking run-time routines. A unique capability of GNAT
6118 is to list this expanded code in a form very close to normal Ada source.
6119 This is very useful in understanding the implications of various Ada
6120 usage on the efficiency of the generated code. There are many cases in
6121 Ada (e.g. the use of controlled types), where simple Ada statements can
6122 generate a lot of run-time code. By using @option{-gnatG} you can identify
6123 these cases, and consider whether it may be desirable to modify the coding
6124 approach to improve efficiency.
6125
6126 The format of the output is very similar to standard Ada source, and is
6127 easily understood by an Ada programmer. The following special syntactic
6128 additions correspond to low level features used in the generated code that
6129 do not have any exact analogies in pure Ada source form. The following
6130 is a partial list of these special constructions. See the specification
6131 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6132
6133 @table @code
6134 @item new @var{xxx} [storage_pool = @var{yyy}]
6135 Shows the storage pool being used for an allocator.
6136
6137 @item at end @var{procedure-name};
6138 Shows the finalization (cleanup) procedure for a scope.
6139
6140 @item (if @var{expr} then @var{expr} else @var{expr})
6141 Conditional expression equivalent to the @code{x?y:z} construction in C.
6142
6143 @item @var{target}^^^(@var{source})
6144 A conversion with floating-point truncation instead of rounding.
6145
6146 @item @var{target}?(@var{source})
6147 A conversion that bypasses normal Ada semantic checking. In particular
6148 enumeration types and fixed-point types are treated simply as integers.
6149
6150 @item @var{target}?^^^(@var{source})
6151 Combines the above two cases.
6152
6153 @item @var{x} #/ @var{y}
6154 @itemx @var{x} #mod @var{y}
6155 @itemx @var{x} #* @var{y}
6156 @itemx @var{x} #rem @var{y}
6157 A division or multiplication of fixed-point values which are treated as
6158 integers without any kind of scaling.
6159
6160 @item free @var{expr} [storage_pool = @var{xxx}]
6161 Shows the storage pool associated with a @code{free} statement.
6162
6163 @item freeze @var{typename} [@var{actions}]
6164 Shows the point at which @var{typename} is frozen, with possible
6165 associated actions to be performed at the freeze point.
6166
6167 @item reference @var{itype}
6168 Reference (and hence definition) to internal type @var{itype}.
6169
6170 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6171 Intrinsic function call.
6172
6173 @item @var{labelname} : label
6174 Declaration of label @var{labelname}.
6175
6176 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
6177 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6178 @var{expr}, but handled more efficiently).
6179
6180 @item [constraint_error]
6181 Raise the @code{Constraint_Error} exception.
6182
6183 @item @var{expression}'reference
6184 A pointer to the result of evaluating @var{expression}.
6185
6186 @item @var{target-type}!(@var{source-expression})
6187 An unchecked conversion of @var{source-expression} to @var{target-type}.
6188
6189 @item [@var{numerator}/@var{denominator}]
6190 Used to represent internal real literals (that) have no exact
6191 representation in base 2-16 (for example, the result of compile time
6192 evaluation of the expression 1.0/27.0).
6193 @end table
6194
6195 @item -gnatD
6196 @cindex @option{-gnatD} (@code{gcc})
6197 When used in conjunction with @option{-gnatG}, this switch causes
6198 the expanded source, as described above for
6199 @option{-gnatG} to be written to files with names
6200 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6201 instead of to the standard ooutput file. For
6202 example, if the source file name is @file{hello.adb}, then a file
6203 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
6204 information generated by the @code{gcc} @option{^-g^/DEBUG^} switch
6205 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6206 you to do source level debugging using the generated code which is
6207 sometimes useful for complex code, for example to find out exactly
6208 which part of a complex construction raised an exception. This switch
6209 also suppress generation of cross-reference information (see
6210 @option{-gnatx}) since otherwise the cross-reference information
6211 would refer to the @file{^.dg^.DG^} file, which would cause
6212 confusion since this is not the original source file.
6213
6214 Note that @option{-gnatD} actually implies @option{-gnatG}
6215 automatically, so it is not necessary to give both options.
6216 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6217
6218 @ifclear vms
6219 @item -gnatR[0|1|2|3[s]]
6220 @cindex @option{-gnatR} (@code{gcc})
6221 This switch controls output from the compiler of a listing showing
6222 representation information for declared types and objects. For
6223 @option{-gnatR0}, no information is output (equivalent to omitting
6224 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6225 so @option{-gnatR} with no parameter has the same effect), size and alignment
6226 information is listed for declared array and record types. For
6227 @option{-gnatR2}, size and alignment information is listed for all
6228 expression information for values that are computed at run time for
6229 variant records. These symbolic expressions have a mostly obvious
6230 format with #n being used to represent the value of the n'th
6231 discriminant. See source files @file{repinfo.ads/adb} in the
6232 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6233 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
6234 the output is to a file with the name @file{^file.rep^file_REP^} where
6235 file is the name of the corresponding source file.
6236 @end ifclear
6237 @ifset vms
6238 @item /REPRESENTATION_INFO
6239 @cindex @option{/REPRESENTATION_INFO} (@code{gcc})
6240 This qualifier controls output from the compiler of a listing showing
6241 representation information for declared types and objects. For
6242 @option{/REPRESENTATION_INFO=NONE}, no information is output
6243 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6244 @option{/REPRESENTATION_INFO} without option is equivalent to
6245 @option{/REPRESENTATION_INFO=ARRAYS}.
6246 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6247 information is listed for declared array and record types. For
6248 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6249 is listed for all expression information for values that are computed
6250 at run time for variant records. These symbolic expressions have a mostly
6251 obvious format with #n being used to represent the value of the n'th
6252 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6253 @code{GNAT} sources for full details on the format of
6254 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6255 If _FILE is added at the end of an option
6256 (e.g. @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6257 then the output is to a file with the name @file{file_REP} where
6258 file is the name of the corresponding source file.
6259 @end ifset
6260
6261 @item -gnatS
6262 @cindex @option{-gnatS} (@code{gcc})
6263 The use of the switch @option{-gnatS} for an
6264 Ada compilation will cause the compiler to output a
6265 representation of package Standard in a form very
6266 close to standard Ada. It is not quite possible to
6267 do this and remain entirely Standard (since new
6268 numeric base types cannot be created in standard
6269 Ada), but the output is easily
6270 readable to any Ada programmer, and is useful to
6271 determine the characteristics of target dependent
6272 types in package Standard.
6273
6274 @item -gnatx
6275 @cindex @option{-gnatx} (@code{gcc})
6276 Normally the compiler generates full cross-referencing information in
6277 the @file{ALI} file. This information is used by a number of tools,
6278 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
6279 suppresses this information. This saves some space and may slightly
6280 speed up compilation, but means that these tools cannot be used.
6281 @end table
6282
6283 @node Exception Handling Control
6284 @subsection Exception Handling Control
6285
6286 @noindent
6287 GNAT uses two methods for handling exceptions at run-time. The
6288 @code{longjmp/setjmp} method saves the context when entering
6289 a frame with an exception handler. Then when an exception is
6290 raised, the context can be restored immediately, without the
6291 need for tracing stack frames. This method provides very fast
6292 exception propagation, but introduces significant overhead for
6293 the use of exception handlers, even if no exception is raised.
6294
6295 The other approach is called ``zero cost'' exception handling.
6296 With this method, the compiler builds static tables to describe
6297 the exception ranges. No dynamic code is required when entering
6298 a frame containing an exception handler. When an exception is
6299 raised, the tables are used to control a back trace of the
6300 subprogram invocation stack to locate the required exception
6301 handler. This method has considerably poorer performance for
6302 the propagation of exceptions, but there is no overhead for
6303 exception handlers if no exception is raised.
6304
6305 The following switches can be used to control which of the
6306 two exception handling methods is used.
6307
6308 @table @option
6309 @c !sort!
6310
6311 @item -gnatL
6312 @cindex @option{-gnatL} (@code{gcc})
6313 This switch causes the longjmp/setjmp approach to be used
6314 for exception handling. If this is the default mechanism for the
6315 target (see below), then this has no effect. If the default
6316 mechanism for the target is zero cost exceptions, then
6317 this switch can be used to modify this default, but it must be
6318 used for all units in the partition, including all run-time
6319 library units. One way to achieve this is to use the
6320 @option{-a} and @option{-f} switches for @code{gnatmake}.
6321 This option is rarely used. One case in which it may be
6322 advantageous is if you have an application where exception
6323 raising is common and the overall performance of the
6324 application is improved by favoring exception propagation.
6325
6326 @item -gnatZ
6327 @cindex @option{-gnatZ} (@code{gcc})
6328 @cindex Zero Cost Exceptions
6329 This switch causes the zero cost approach to be sed
6330 for exception handling. If this is the default mechanism for the
6331 target (see below), then this has no effect. If the default
6332 mechanism for the target is longjmp/setjmp exceptions, then
6333 this switch can be used to modify this default, but it must be
6334 used for all units in the partition, including all run-time
6335 library units. One way to achieve this is to use the
6336 @option{-a} and @option{-f} switches for @code{gnatmake}.
6337 This option can only be used if the zero cost approach
6338 is available for the target in use (see below).
6339 @end table
6340
6341 @noindent
6342 The @code{longjmp/setjmp} approach is available on all targets, but
6343 the @code{zero cost} approach is only available on selected targets.
6344 To determine whether zero cost exceptions can be used for a
6345 particular target, look at the private part of the file system.ads.
6346 Either @code{GCC_ZCX_Support} or @code{Front_End_ZCX_Support} must
6347 be True to use the zero cost approach. If both of these switches
6348 are set to False, this means that zero cost exception handling
6349 is not yet available for that target. The switch
6350 @code{ZCX_By_Default} indicates the default approach. If this
6351 switch is set to True, then the @code{zero cost} approach is
6352 used by default.
6353
6354 @node Units to Sources Mapping Files
6355 @subsection Units to Sources Mapping Files
6356
6357 @table @option
6358
6359 @item -gnatem^^=^@var{path}
6360 @cindex @option{-gnatem} (@code{gcc})
6361 A mapping file is a way to communicate to the compiler two mappings:
6362 from unit names to file names (without any directory information) and from
6363 file names to path names (with full directory information). These mappings
6364 are used by the compiler to short-circuit the path search.
6365
6366 The use of mapping files is not required for correct operation of the
6367 compiler, but mapping files can improve efficiency, particularly when
6368 sources are read over a slow network connection. In normal operation,
6369 you need not be concerned with the format or use of mapping files,
6370 and the @option{-gnatem} switch is not a switch that you would use
6371 explicitly. it is intended only for use by automatic tools such as
6372 @code{gnatmake} running under the project file facility. The
6373 description here of the format of mapping files is provided
6374 for completeness and for possible use by other tools.
6375
6376 A mapping file is a sequence of sets of three lines. In each set,
6377 the first line is the unit name, in lower case, with ``@code{%s}''
6378 appended for
6379 specifications and ``@code{%b}'' appended for bodies; the second line is the
6380 file name; and the third line is the path name.
6381
6382 Example:
6383 @smallexample
6384    main%b
6385    main.2.ada
6386    /gnat/project1/sources/main.2.ada
6387 @end smallexample
6388
6389 When the switch @option{-gnatem} is specified, the compiler will create
6390 in memory the two mappings from the specified file. If there is any problem
6391 (non existent file, truncated file or duplicate entries), no mapping
6392 will be created.
6393
6394 Several @option{-gnatem} switches may be specified; however, only the last
6395 one on the command line will be taken into account.
6396
6397 When using a project file, @code{gnatmake} create a temporary mapping file
6398 and communicates it to the compiler using this switch.
6399
6400 @end table
6401
6402
6403 @node Integrated Preprocessing
6404 @subsection Integrated Preprocessing
6405
6406 @noindent
6407 GNAT sources may be preprocessed immediately before compilation; the actual
6408 text of the source is not the text of the source file, but is derived from it
6409 through a process called preprocessing. Integrated preprocessing is specified
6410 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
6411 indicates, through a text file, the preprocessing data to be used.
6412 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
6413
6414 @noindent
6415 It is recommended that @code{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
6416 used when Integrated Preprocessing is used. The reason is that preprocessing
6417 with another Preprocessing Data file without changing the sources will
6418 not trigger recompilation without this switch.
6419
6420 @noindent
6421 Note that @code{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
6422 always trigger recompilation for sources that are preprocessed,
6423 because @code{gnatmake} cannot compute the checksum of the source after
6424 preprocessing.
6425
6426 @noindent
6427 The actual preprocessing function is described in details in section
6428 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
6429 preprocessing is triggered and parameterized.
6430
6431 @table @code
6432
6433 @item -gnatep=@var{file}
6434 @cindex @option{-gnatep} (@code{gcc})
6435 This switch indicates to the compiler the file name (without directory
6436 information) of the preprocessor data file to use. The preprocessor data file
6437 should be found in the source directories.
6438
6439 @noindent
6440 A preprocessing data file is a text file with significant lines indicating
6441 how should be preprocessed either a specific source or all sources not
6442 mentioned in other lines. A significant line is a non empty, non comment line.
6443 Comments are similar to Ada comments.
6444
6445 @noindent
6446 Each significant line starts with either a literal string or the character '*'.
6447 A literal string is the file name (without directory information) of the source
6448 to preprocess. A character '*' indicates the preprocessing for all the sources
6449 that are not specified explicitly on other lines (order of the lines is not
6450 significant). It is an error to have two lines with the same file name or two
6451 lines starting with the character '*'.
6452
6453 @noindent
6454 After the file name or the character '*', another optional literal string
6455 indicating the file name of the definition file to be used for preprocessing.
6456 (see @ref{Form of Definitions File}. The definition files are found by the
6457 compiler in one of the source directories. In some cases, when compiling
6458 a source in a directory other than the current directory, if the definition
6459 file is in the current directory, it may be necessary to add the current
6460 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
6461 the compiler would not find the definition file.
6462
6463 @noindent
6464 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
6465 be found. Those ^switches^switches^ are:
6466
6467 @table @code
6468
6469 @item -b
6470 Causes both preprocessor lines and the lines deleted by
6471 preprocessing to be replaced by blank lines, preserving the line number.
6472 This ^switch^switch^ is always implied; however, if specified after @option{-c}
6473 it cancels the effect of @option{-c}.
6474
6475 @item -c
6476 Causes both preprocessor lines and the lines deleted
6477 by preprocessing to be retained as comments marked
6478 with the special string ``@code{--! }''.
6479
6480 @item -Dsymbol=value
6481 Define or redefine a symbol, associated with value. A symbol is an Ada
6482 identifier, or an Ada reserved word, with the exception of @code{if},
6483 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6484 @code{value} is either a literal string, an Ada identifier or any Ada reserved
6485 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
6486 same name defined in a definition file.
6487
6488 @item -s
6489 Causes a sorted list of symbol names and values to be
6490 listed on the standard output file.
6491
6492 @item -u
6493 Causes undefined symbols to be treated as having the value @code{FALSE}
6494 in the context
6495 of a preprocessor test. In the absence of this option, an undefined symbol in
6496 a @code{#if} or @code{#elsif} test will be treated as an error.
6497
6498 @end table
6499
6500 @noindent
6501 Examples of valid lines in a preprocessor data file:
6502
6503 @smallexample
6504   "toto.adb"  "prep.def" -u
6505   --  preprocess "toto.adb", using definition file "prep.def",
6506   --  undefined symbol are False.
6507
6508   * -c -DVERSION=V101
6509   --  preprocess all other sources without a definition file;
6510   --  suppressed lined are commented; symbol VERSION has the value V101.
6511
6512   "titi.adb" "prep2.def" -s
6513   --  preprocess "titi.adb", using definition file "prep2.def";
6514   --  list all symbols with their values.
6515 @end smallexample
6516
6517 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
6518 @cindex @option{-gnateD} (@code{gcc})
6519 Define or redefine a preprocessing symbol, associated with value. If no value
6520 is given on the command line, then the value of the symbol is @code{True}.
6521 A symbol is an identifier, following normal Ada (case-insensitive)
6522 rules for its syntax, and value is any sequence (including an empty sequence)
6523 of characters from the set (letters, digits, period, underline).
6524 Ada reserved words may be used as symbols, with the exceptions of @code{if},
6525 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6526
6527 @noindent
6528 A symbol declared with this ^switch^switch^ on the command line replaces a
6529 symbol with the same name either in a definition file or specified with a
6530 ^switch^switch^ -D in the preprocessor data file.
6531
6532 @noindent
6533 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
6534
6535 @end table
6536
6537 @ifset vms
6538 @node Return Codes
6539 @subsection Return Codes
6540 @cindex Return Codes
6541 @cindex @option{/RETURN_CODES=VMS}
6542
6543 @noindent
6544 On VMS, GNAT compiled programs return POSIX-style codes by default,
6545 e.g. @option{/RETURN_CODES=POSIX}.
6546
6547 To enable VMS style return codes, GNAT LINK with the option
6548 @option{/RETURN_CODES=VMS}. For example:
6549
6550 @smallexample
6551 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
6552 @end smallexample
6553
6554 @noindent
6555 Programs built with /RETURN_CODES=VMS are suitable to be called in
6556 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
6557 are suitable for spawning with appropriate GNAT RTL routines.
6558
6559 @end ifset
6560
6561
6562 @node Search Paths and the Run-Time Library (RTL)
6563 @section Search Paths and the Run-Time Library (RTL)
6564
6565 @noindent
6566 With the GNAT source-based library system, the compiler must be able to
6567 find source files for units that are needed by the unit being compiled.
6568 Search paths are used to guide this process.
6569
6570 The compiler compiles one source file whose name must be given
6571 explicitly on the command line. In other words, no searching is done
6572 for this file. To find all other source files that are needed (the most
6573 common being the specs of units), the compiler examines the following
6574 directories, in the following order:
6575
6576 @enumerate
6577 @item
6578 The directory containing the source file of the main unit being compiled
6579 (the file name on the command line).
6580
6581 @item
6582 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
6583 @code{gcc} command line, in the order given.
6584
6585 @item
6586 @findex ADA_INCLUDE_PATH
6587 Each of the directories listed in the value of the
6588 @code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
6589 @ifclear vms
6590 Construct this value
6591 exactly as the @code{PATH} environment variable: a list of directory
6592 names separated by colons (semicolons when working with the NT version).
6593 @end ifclear
6594 @ifset vms
6595 Normally, define this value as a logical name containing a comma separated
6596 list of directory names.
6597
6598 This variable can also be defined by means of an environment string
6599 (an argument to the DEC C exec* set of functions).
6600
6601 Logical Name:
6602 @smallexample
6603 DEFINE ANOTHER_PATH FOO:[BAG]
6604 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
6605 @end smallexample
6606
6607 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
6608 first, followed by the standard Ada 95
6609 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
6610 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
6611 (Text_IO, Sequential_IO, etc)
6612 instead of the Ada95 packages. Thus, in order to get the Ada 95
6613 packages by default, ADA_INCLUDE_PATH must be redefined.
6614 @end ifset
6615
6616 @item
6617 @findex ADA_PRJ_INCLUDE_FILE
6618 Each of the directories listed in the text file whose name is given
6619 by the @code{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
6620
6621 @noindent
6622 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
6623 driver when project files are used. It should not normally be set
6624 by other means.
6625
6626 @item
6627 The content of the @file{ada_source_path} file which is part of the GNAT
6628 installation tree and is used to store standard libraries such as the
6629 GNAT Run Time Library (RTL) source files.
6630 @ifclear vms
6631 @ref{Installing an Ada Library}
6632 @end ifclear
6633 @end enumerate
6634
6635 @noindent
6636 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
6637 inhibits the use of the directory
6638 containing the source file named in the command line. You can still
6639 have this directory on your search path, but in this case it must be
6640 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
6641
6642 Specifying the switch @option{-nostdinc}
6643 inhibits the search of the default location for the GNAT Run Time
6644 Library (RTL) source files.
6645
6646 The compiler outputs its object files and ALI files in the current
6647 working directory.
6648 @ifclear vms
6649 Caution: The object file can be redirected with the @option{-o} switch;
6650 however, @code{gcc} and @code{gnat1} have not been coordinated on this
6651 so the @file{ALI} file will not go to the right place. Therefore, you should
6652 avoid using the @option{-o} switch.
6653 @end ifclear
6654
6655 @findex System.IO
6656 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
6657 children make up the GNAT RTL, together with the simple @code{System.IO}
6658 package used in the @code{"Hello World"} example. The sources for these units
6659 are needed by the compiler and are kept together in one directory. Not
6660 all of the bodies are needed, but all of the sources are kept together
6661 anyway. In a normal installation, you need not specify these directory
6662 names when compiling or binding. Either the environment variables or
6663 the built-in defaults cause these files to be found.
6664
6665 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
6666 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
6667 consisting of child units of @code{GNAT}. This is a collection of generally
6668 useful types, subprograms, etc. See the @cite{GNAT Reference Manual} for
6669 further details.
6670
6671 Besides simplifying access to the RTL, a major use of search paths is
6672 in compiling sources from multiple directories. This can make
6673 development environments much more flexible.
6674
6675
6676 @node Order of Compilation Issues
6677 @section Order of Compilation Issues
6678
6679 @noindent
6680 If, in our earlier example, there was a spec for the @code{hello}
6681 procedure, it would be contained in the file @file{hello.ads}; yet this
6682 file would not have to be explicitly compiled. This is the result of the
6683 model we chose to implement library management. Some of the consequences
6684 of this model are as follows:
6685
6686 @itemize @bullet
6687 @item
6688 There is no point in compiling specs (except for package
6689 specs with no bodies) because these are compiled as needed by clients. If
6690 you attempt a useless compilation, you will receive an error message.
6691 It is also useless to compile subunits because they are compiled as needed
6692 by the parent.
6693
6694 @item
6695 There are no order of compilation requirements: performing a
6696 compilation never obsoletes anything. The only way you can obsolete
6697 something and require recompilations is to modify one of the
6698 source files on which it depends.
6699
6700 @item
6701 There is no library as such, apart from the ALI files
6702 (@pxref{The Ada Library Information Files}, for information on the format
6703 of these files). For now we find it convenient to create separate ALI files,
6704 but eventually the information therein may be incorporated into the object
6705 file directly.
6706
6707 @item
6708 When you compile a unit, the source files for the specs of all units
6709 that it @code{with}'s, all its subunits, and the bodies of any generics it
6710 instantiates must be available (reachable by the search-paths mechanism
6711 described above), or you will receive a fatal error message.
6712 @end itemize
6713
6714 @node Examples
6715 @section Examples
6716
6717 @noindent
6718 The following are some typical Ada compilation command line examples:
6719
6720 @table @code
6721 @item $ gcc -c xyz.adb
6722 Compile body in file @file{xyz.adb} with all default options.
6723
6724 @ifclear vms
6725 @item $ gcc -c -O2 -gnata xyz-def.adb
6726 @end ifclear
6727 @ifset vms
6728 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
6729 @end ifset
6730
6731 Compile the child unit package in file @file{xyz-def.adb} with extensive
6732 optimizations, and pragma @code{Assert}/@code{Debug} statements
6733 enabled.
6734
6735 @item $ gcc -c -gnatc abc-def.adb
6736 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
6737 mode.
6738 @end table
6739
6740 @node Binding Using gnatbind
6741 @chapter Binding Using @code{gnatbind}
6742 @findex gnatbind
6743
6744 @menu
6745 * Running gnatbind::
6746 * Switches for gnatbind::
6747 * Command-Line Access::
6748 * Search Paths for gnatbind::
6749 * Examples of gnatbind Usage::
6750 @end menu
6751
6752 @noindent
6753 This chapter describes the GNAT binder, @code{gnatbind}, which is used
6754 to bind compiled GNAT objects. The @code{gnatbind} program performs
6755 four separate functions:
6756
6757 @enumerate
6758 @item
6759 Checks that a program is consistent, in accordance with the rules in
6760 Chapter 10 of the Ada 95 Reference Manual. In particular, error
6761 messages are generated if a program uses inconsistent versions of a
6762 given unit.
6763
6764 @item
6765 Checks that an acceptable order of elaboration exists for the program
6766 and issues an error message if it cannot find an order of elaboration
6767 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
6768
6769 @item
6770 Generates a main program incorporating the given elaboration order.
6771 This program is a small Ada package (body and spec) that
6772 must be subsequently compiled
6773 using the GNAT compiler. The necessary compilation step is usually
6774 performed automatically by @code{gnatlink}. The two most important
6775 functions of this program
6776 are to call the elaboration routines of units in an appropriate order
6777 and to call the main program.
6778
6779 @item
6780 Determines the set of object files required by the given main program.
6781 This information is output in the forms of comments in the generated program,
6782 to be read by the @code{gnatlink} utility used to link the Ada application.
6783 @end enumerate
6784
6785
6786 @node Running gnatbind
6787 @section Running @code{gnatbind}
6788
6789 @noindent
6790 The form of the @code{gnatbind} command is
6791
6792 @smallexample
6793 $ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}]
6794 @end smallexample
6795
6796 @noindent
6797 where @file{@i{mainprog}.adb} is the Ada file containing the main program
6798 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
6799 package in two files whose names are
6800 @file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}.
6801 For example, if given the
6802 parameter @file{hello.ali}, for a main program contained in file
6803 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
6804 and @file{b~hello.adb}.
6805
6806 When doing consistency checking, the binder takes into consideration
6807 any source files it can locate. For example, if the binder determines
6808 that the given main program requires the package @code{Pack}, whose
6809 @file{.ALI}
6810 file is @file{pack.ali} and whose corresponding source spec file is
6811 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
6812 (using the same search path conventions as previously described for the
6813 @code{gcc} command). If it can locate this source file, it checks that
6814 the time stamps
6815 or source checksums of the source and its references to in @file{ALI} files
6816 match. In other words, any @file{ALI} files that mentions this spec must have
6817 resulted from compiling this version of the source file (or in the case
6818 where the source checksums match, a version close enough that the
6819 difference does not matter).
6820
6821 @cindex Source files, use by binder
6822 The effect of this consistency checking, which includes source files, is
6823 that the binder ensures that the program is consistent with the latest
6824 version of the source files that can be located at bind time. Editing a
6825 source file without compiling files that depend on the source file cause
6826 error messages to be generated by the binder.
6827
6828 For example, suppose you have a main program @file{hello.adb} and a
6829 package @code{P}, from file @file{p.ads} and you perform the following
6830 steps:
6831
6832 @enumerate
6833 @item
6834 Enter @code{gcc -c hello.adb} to compile the main program.
6835
6836 @item
6837 Enter @code{gcc -c p.ads} to compile package @code{P}.
6838
6839 @item
6840 Edit file @file{p.ads}.
6841
6842 @item
6843 Enter @code{gnatbind hello}.
6844 @end enumerate
6845
6846 @noindent
6847 At this point, the file @file{p.ali} contains an out-of-date time stamp
6848 because the file @file{p.ads} has been edited. The attempt at binding
6849 fails, and the binder generates the following error messages:
6850
6851 @smallexample
6852 error: "hello.adb" must be recompiled ("p.ads" has been modified)
6853 error: "p.ads" has been modified and must be recompiled
6854 @end smallexample
6855
6856 @noindent
6857 Now both files must be recompiled as indicated, and then the bind can
6858 succeed, generating a main program. You need not normally be concerned
6859 with the contents of this file, but for reference purposes a sample
6860 binder output file is given in @ref{Example of Binder Output File}.
6861
6862 In most normal usage, the default mode of @command{gnatbind} which is to
6863 generate the main package in Ada, as described in the previous section.
6864 In particular, this means that any Ada programmer can read and understand
6865 the generated main program. It can also be debugged just like any other
6866 Ada code provided the @option{^-g^/DEBUG^} switch is used for
6867 @command{gnatbind} and @command{gnatlink}.
6868
6869 However for some purposes it may be convenient to generate the main
6870 program in C rather than Ada. This may for example be helpful when you
6871 are generating a mixed language program with the main program in C. The
6872 GNAT compiler itself is an example.
6873 The use of the @option{^-C^/BIND_FILE=C^} switch
6874 for both @code{gnatbind} and @code{gnatlink} will cause the program to
6875 be generated in C (and compiled using the gnu C compiler).
6876
6877
6878 @node Switches for gnatbind
6879 @section Switches for @command{gnatbind}
6880
6881 @noindent
6882 The following switches are available with @code{gnatbind}; details will
6883 be presented in subsequent sections.
6884
6885 @menu
6886 * Consistency-Checking Modes::
6887 * Binder Error Message Control::
6888 * Elaboration Control::
6889 * Output Control::
6890 * Binding with Non-Ada Main Programs::
6891 * Binding Programs with No Main Subprogram::
6892 @end menu
6893
6894 @table @option
6895 @c !sort!
6896 @item ^-aO^/OBJECT_SEARCH^
6897 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
6898 Specify directory to be searched for ALI files.
6899
6900 @item ^-aI^/SOURCE_SEARCH^
6901 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
6902 Specify directory to be searched for source file.
6903
6904 @item ^-A^/BIND_FILE=ADA^
6905 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
6906 Generate binder program in Ada (default)
6907
6908 @item ^-b^/REPORT_ERRORS=BRIEF^
6909 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
6910 Generate brief messages to @file{stderr} even if verbose mode set.
6911
6912 @item ^-c^/NOOUTPUT^
6913 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
6914 Check only, no generation of binder output file.
6915
6916 @item ^-C^/BIND_FILE=C^
6917 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
6918 Generate binder program in C
6919
6920 @item ^-e^/ELABORATION_DEPENDENCIES^
6921 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
6922 Output complete list of elaboration-order dependencies.
6923
6924 @item ^-E^/STORE_TRACEBACKS^
6925 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
6926 Store tracebacks in exception occurrences when the target supports it.
6927 This is the default with the zero cost exception mechanism.
6928 @ignore
6929 @c The following may get moved to an appendix
6930 This option is currently supported on the following targets:
6931 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
6932 @end ignore
6933 See also the packages @code{GNAT.Traceback} and
6934 @code{GNAT.Traceback.Symbolic} for more information.
6935 @ifclear vms
6936 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
6937 @code{gcc} option.
6938 @end ifclear vms
6939
6940 @item ^-F^/FORCE_ELABS_FLAGS^
6941 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
6942 Force the checks of elaboration flags. @command{gnatbind} does not normally
6943 generate checks of elaboration flags for the main executable, except when
6944 a Stand-Alone Library is used. However, there are cases when this cannot be
6945 detected by gnatbind. An example is importing an interface of a Stand-Alone
6946 Library through a pragma Import and only specifying through a linker switch
6947 this Stand-Alone Library. This switch is used to guarantee that elaboration
6948 flag checks are generated.
6949
6950 @item ^-h^/HELP^
6951 @cindex @option{^-h^/HELP^} (@command{gnatbind})
6952 Output usage (help) information
6953
6954 @item ^-I^/SEARCH^
6955 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
6956 Specify directory to be searched for source and ALI files.
6957
6958 @item ^-I-^/NOCURRENT_DIRECTORY^
6959 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
6960 Do not look for sources in the current directory where @code{gnatbind} was
6961 invoked, and do not look for ALI files in the directory containing the
6962 ALI file named in the @code{gnatbind} command line.
6963
6964 @item ^-l^/ORDER_OF_ELABORATION^
6965 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
6966 Output chosen elaboration order.
6967
6968 @item ^-Lxxx^/BUILD_LIBRARY=xxx^
6969 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
6970 Binds the units for library building. In this case the adainit and
6971 adafinal procedures (See @pxref{Binding with Non-Ada Main Programs})
6972 are renamed to ^xxxinit^XXXINIT^ and
6973 ^xxxfinal^XXXFINAL^.
6974 Implies ^-n^/NOCOMPILE^.
6975 @ifclear vms
6976 (@pxref{GNAT and Libraries}, for more details.)
6977 @end ifclear
6978 @ifset vms
6979 On OpenVMS, these init and final procedures are exported in uppercase
6980 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
6981 the init procedure will be "TOTOINIT" and the exported name of the final
6982 procedure will be "TOTOFINAL".
6983 @end ifset
6984
6985 @item ^-Mxyz^/RENAME_MAIN=xyz^
6986 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
6987 Rename generated main program from main to xyz
6988
6989 @item ^-m^/ERROR_LIMIT=^@var{n}
6990 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
6991 Limit number of detected errors to @var{n}, where @var{n} is
6992 in the range 1..999_999. The default value if no switch is
6993 given is 9999. Binding is terminated if the limit is exceeded.
6994 @ifset unw
6995 Furthermore, under Windows, the sources pointed to by the libraries path
6996 set in the registry are not searched for.
6997 @end ifset
6998
6999 @item ^-n^/NOMAIN^
7000 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7001 No main program.
7002
7003 @item -nostdinc
7004 @cindex @option{-nostdinc} (@command{gnatbind})
7005 Do not look for sources in the system default directory.
7006
7007 @item -nostdlib
7008 @cindex @option{-nostdlib} (@command{gnatbind})
7009 Do not look for library files in the system default directory.
7010
7011 @item --RTS=@var{rts-path}
7012 @cindex @option{--RTS} (@code{gnatbind})
7013 Specifies the default location of the runtime library. Same meaning as the
7014 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
7015
7016 @item ^-o ^/OUTPUT=^@var{file}
7017 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7018 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7019 Note that if this option is used, then linking must be done manually,
7020 gnatlink cannot be used.
7021
7022 @item ^-O^/OBJECT_LIST^
7023 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7024 Output object list.
7025
7026 @item ^-p^/PESSIMISTIC_ELABORATION^
7027 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7028 Pessimistic (worst-case) elaboration order
7029
7030 @item ^-s^/READ_SOURCES=ALL^
7031 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7032 Require all source files to be present.
7033
7034 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7035 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7036 Specifies the value to be used when detecting uninitialized scalar
7037 objects with pragma Initialize_Scalars.
7038 The @var{xxx} ^string specified with the switch^option^ may be either
7039 @itemize @bullet
7040 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7041 @item ``@option{^lo^LOW^}'' for the lowest possible value
7042 possible, and the low
7043 @item ``@option{^hi^HIGH^}'' for the highest possible value
7044 @item ``@option{xx}'' for a value consisting of repeated bytes with the
7045 value 16#xx# (i.e. xx is a string of two hexadecimal digits).
7046 @end itemize
7047
7048 In addition, you can specify @option{-Sev} to indicate that the value is
7049 to be set at run time. In this case, the program will look for an environment
7050 @cindex GNAT_INIT_SCALARS
7051 variable of the form @code{GNAT_INIT_SCALARS=xx}, where xx is one
7052 of @option{in/lo/hi/xx} with the same meanings as above.
7053 If no environment variable is found, or if it does not have a valid value,
7054 then the default is @option{in} (invalid values).
7055
7056 @ifclear vms
7057 @item -static
7058 @cindex @option{-static} (@code{gnatbind})
7059 Link against a static GNAT run time.
7060
7061 @item -shared
7062 @cindex @option{-shared} (@code{gnatbind})
7063 Link against a shared GNAT run time when available.
7064 @end ifclear
7065
7066 @item ^-t^/NOTIME_STAMP_CHECK^
7067 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7068 Tolerate time stamp and other consistency errors
7069
7070 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7071 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7072 Set the time slice value to @var{n} milliseconds. If the system supports
7073 the specification of a specific time slice value, then the indicated value
7074 is used. If the system does not support specific time slice values, but
7075 does support some general notion of round-robin scheduling, then any
7076 non-zero value will activate round-robin scheduling.
7077
7078 A value of zero is treated specially. It turns off time
7079 slicing, and in addition, indicates to the tasking run time that the
7080 semantics should match as closely as possible the Annex D
7081 requirements of the Ada RM, and in particular sets the default
7082 scheduling policy to @code{FIFO_Within_Priorities}.
7083
7084 @item ^-v^/REPORT_ERRORS=VERBOSE^
7085 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7086 Verbose mode. Write error messages, header, summary output to
7087 @file{stdout}.
7088
7089 @ifclear vms
7090 @item -w@var{x}
7091 @cindex @option{-w} (@code{gnatbind})
7092 Warning mode (@var{x}=s/e for suppress/treat as error)
7093 @end ifclear
7094
7095 @ifset vms
7096 @item /WARNINGS=NORMAL
7097 @cindex @option{/WARNINGS} (@code{gnatbind})
7098 Normal warnings mode. Warnings are issued but ignored
7099
7100 @item /WARNINGS=SUPPRESS
7101 @cindex @option{/WARNINGS} (@code{gnatbind})
7102 All warning messages are suppressed
7103
7104 @item /WARNINGS=ERROR
7105 @cindex @option{/WARNINGS} (@code{gnatbind})
7106 Warning messages are treated as fatal errors
7107 @end ifset
7108
7109 @item ^-x^/READ_SOURCES=NONE^
7110 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7111 Exclude source files (check object consistency only).
7112
7113 @ifset vms
7114 @item /READ_SOURCES=AVAILABLE
7115 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7116 Default mode, in which sources are checked for consistency only if
7117 they are available.
7118 @end ifset
7119
7120 @item ^-z^/ZERO_MAIN^
7121 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7122 No main subprogram.
7123 @end table
7124
7125 @ifclear vms
7126 @noindent
7127 You may obtain this listing of switches by running @code{gnatbind} with
7128 no arguments.
7129 @end ifclear
7130
7131
7132 @node Consistency-Checking Modes
7133 @subsection Consistency-Checking Modes
7134
7135 @noindent
7136 As described earlier, by default @code{gnatbind} checks
7137 that object files are consistent with one another and are consistent
7138 with any source files it can locate. The following switches control binder
7139 access to sources.
7140
7141 @table @option
7142 @c !sort!
7143 @item ^-s^/READ_SOURCES=ALL^
7144 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7145 Require source files to be present. In this mode, the binder must be
7146 able to locate all source files that are referenced, in order to check
7147 their consistency. In normal mode, if a source file cannot be located it
7148 is simply ignored. If you specify this switch, a missing source
7149 file is an error.
7150
7151 @item ^-x^/READ_SOURCES=NONE^
7152 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7153 Exclude source files. In this mode, the binder only checks that ALI
7154 files are consistent with one another. Source files are not accessed.
7155 The binder runs faster in this mode, and there is still a guarantee that
7156 the resulting program is self-consistent.
7157 If a source file has been edited since it was last compiled, and you
7158 specify this switch, the binder will not detect that the object
7159 file is out of date with respect to the source file. Note that this is the
7160 mode that is automatically used by @code{gnatmake} because in this
7161 case the checking against sources has already been performed by
7162 @code{gnatmake} in the course of compilation (i.e. before binding).
7163
7164 @ifset vms
7165 @item /READ_SOURCES=AVAILABLE
7166 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
7167 This is the default mode in which source files are checked if they are
7168 available, and ignored if they are not available.
7169 @end ifset
7170 @end table
7171
7172 @node Binder Error Message Control
7173 @subsection Binder Error Message Control
7174
7175 @noindent
7176 The following switches provide control over the generation of error
7177 messages from the binder:
7178
7179 @table @option
7180 @c !sort!
7181 @item ^-v^/REPORT_ERRORS=VERBOSE^
7182 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7183 Verbose mode. In the normal mode, brief error messages are generated to
7184 @file{stderr}. If this switch is present, a header is written
7185 to @file{stdout} and any error messages are directed to @file{stdout}.
7186 All that is written to @file{stderr} is a brief summary message.
7187
7188 @item ^-b^/REPORT_ERRORS=BRIEF^
7189 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
7190 Generate brief error messages to @file{stderr} even if verbose mode is
7191 specified. This is relevant only when used with the
7192 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
7193
7194 @ifclear vms
7195 @item -m@var{n}
7196 @cindex @option{-m} (@code{gnatbind})
7197 Limits the number of error messages to @var{n}, a decimal integer in the
7198 range 1-999. The binder terminates immediately if this limit is reached.
7199
7200 @item -M@var{xxx}
7201 @cindex @option{-M} (@code{gnatbind})
7202 Renames the generated main program from @code{main} to @code{xxx}.
7203 This is useful in the case of some cross-building environments, where
7204 the actual main program is separate from the one generated
7205 by @code{gnatbind}.
7206 @end ifclear
7207
7208 @item ^-ws^/WARNINGS=SUPPRESS^
7209 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
7210 @cindex Warnings
7211 Suppress all warning messages.
7212
7213 @item ^-we^/WARNINGS=ERROR^
7214 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
7215 Treat any warning messages as fatal errors.
7216
7217 @ifset vms
7218 @item /WARNINGS=NORMAL
7219 Standard mode with warnings generated, but warnings do not get treated
7220 as errors.
7221 @end ifset
7222
7223 @item ^-t^/NOTIME_STAMP_CHECK^
7224 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7225 @cindex Time stamp checks, in binder
7226 @cindex Binder consistency checks
7227 @cindex Consistency checks, in binder
7228 The binder performs a number of consistency checks including:
7229
7230 @itemize @bullet
7231 @item
7232 Check that time stamps of a given source unit are consistent
7233 @item
7234 Check that checksums of a given source unit are consistent
7235 @item
7236 Check that consistent versions of @code{GNAT} were used for compilation
7237 @item
7238 Check consistency of configuration pragmas as required
7239 @end itemize
7240
7241 @noindent
7242 Normally failure of such checks, in accordance with the consistency
7243 requirements of the Ada Reference Manual, causes error messages to be
7244 generated which abort the binder and prevent the output of a binder
7245 file and subsequent link to obtain an executable.
7246
7247 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
7248 into warnings, so that
7249 binding and linking can continue to completion even in the presence of such
7250 errors. The result may be a failed link (due to missing symbols), or a
7251 non-functional executable which has undefined semantics.
7252 @emph{This means that
7253 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
7254 with extreme care.}
7255 @end table
7256
7257 @node Elaboration Control
7258 @subsection Elaboration Control
7259
7260 @noindent
7261 The following switches provide additional control over the elaboration
7262 order. For full details see @xref{Elaboration Order Handling in GNAT}.
7263
7264 @table @option
7265 @item ^-p^/PESSIMISTIC_ELABORATION^
7266 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
7267 Normally the binder attempts to choose an elaboration order that is
7268 likely to minimize the likelihood of an elaboration order error resulting
7269 in raising a @code{Program_Error} exception. This switch reverses the
7270 action of the binder, and requests that it deliberately choose an order
7271 that is likely to maximize the likelihood of an elaboration error.
7272 This is useful in ensuring portability and avoiding dependence on
7273 accidental fortuitous elaboration ordering.
7274
7275 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
7276 switch if dynamic
7277 elaboration checking is used (@option{-gnatE} switch used for compilation).
7278 This is because in the default static elaboration mode, all necessary
7279 @code{Elaborate_All} pragmas are implicitly inserted.
7280 These implicit pragmas are still respected by the binder in
7281 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
7282 safe elaboration order is assured.
7283 @end table
7284
7285 @node Output Control
7286 @subsection Output Control
7287
7288 @noindent
7289 The following switches allow additional control over the output
7290 generated by the binder.
7291
7292 @table @option
7293 @c !sort!
7294
7295 @item ^-A^/BIND_FILE=ADA^
7296 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
7297 Generate binder program in Ada (default). The binder program is named
7298 @file{b~@var{mainprog}.adb} by default. This can be changed with
7299 @option{^-o^/OUTPUT^} @code{gnatbind} option.
7300
7301 @item ^-c^/NOOUTPUT^
7302 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
7303 Check only. Do not generate the binder output file. In this mode the
7304 binder performs all error checks but does not generate an output file.
7305
7306 @item ^-C^/BIND_FILE=C^
7307 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
7308 Generate binder program in C. The binder program is named
7309 @file{b_@var{mainprog}.c}.
7310 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
7311 option.
7312
7313 @item ^-e^/ELABORATION_DEPENDENCIES^
7314 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
7315 Output complete list of elaboration-order dependencies, showing the
7316 reason for each dependency. This output can be rather extensive but may
7317 be useful in diagnosing problems with elaboration order. The output is
7318 written to @file{stdout}.
7319
7320 @item ^-h^/HELP^
7321 @cindex @option{^-h^/HELP^} (@code{gnatbind})
7322 Output usage information. The output is written to @file{stdout}.
7323
7324 @item ^-K^/LINKER_OPTION_LIST^
7325 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
7326 Output linker options to @file{stdout}. Includes library search paths,
7327 contents of pragmas Ident and Linker_Options, and libraries added
7328 by @code{gnatbind}.
7329
7330 @item ^-l^/ORDER_OF_ELABORATION^
7331 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
7332 Output chosen elaboration order. The output is written to @file{stdout}.
7333
7334 @item ^-O^/OBJECT_LIST^
7335 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
7336 Output full names of all the object files that must be linked to provide
7337 the Ada component of the program. The output is written to @file{stdout}.
7338 This list includes the files explicitly supplied and referenced by the user
7339 as well as implicitly referenced run-time unit files. The latter are
7340 omitted if the corresponding units reside in shared libraries. The
7341 directory names for the run-time units depend on the system configuration.
7342
7343 @item ^-o ^/OUTPUT=^@var{file}
7344 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
7345 Set name of output file to @var{file} instead of the normal
7346 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
7347 binder generated body filename. In C mode you would normally give
7348 @var{file} an extension of @file{.c} because it will be a C source program.
7349 Note that if this option is used, then linking must be done manually.
7350 It is not possible to use gnatlink in this case, since it cannot locate
7351 the binder file.
7352
7353 @item ^-r^/RESTRICTION_LIST^
7354 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
7355 Generate list of @code{pragma Restrictions} that could be applied to
7356 the current unit. This is useful for code audit purposes, and also may
7357 be used to improve code generation in some cases.
7358
7359 @end table
7360
7361 @node Binding with Non-Ada Main Programs
7362 @subsection Binding with Non-Ada Main Programs
7363
7364 @noindent
7365 In our description so far we have assumed that the main
7366 program is in Ada, and that the task of the binder is to generate a
7367 corresponding function @code{main} that invokes this Ada main
7368 program. GNAT also supports the building of executable programs where
7369 the main program is not in Ada, but some of the called routines are
7370 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
7371 The following switch is used in this situation:
7372
7373 @table @option
7374 @item ^-n^/NOMAIN^
7375 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
7376 No main program. The main program is not in Ada.
7377 @end table
7378
7379 @noindent
7380 In this case, most of the functions of the binder are still required,
7381 but instead of generating a main program, the binder generates a file
7382 containing the following callable routines:
7383
7384 @table @code
7385 @item adainit
7386 @findex adainit
7387 You must call this routine to initialize the Ada part of the program by
7388 calling the necessary elaboration routines. A call to @code{adainit} is
7389 required before the first call to an Ada subprogram.
7390
7391 Note that it is assumed that the basic execution environment must be setup
7392 to be appropriate for Ada execution at the point where the first Ada
7393 subprogram is called. In particular, if the Ada code will do any
7394 floating-point operations, then the FPU must be setup in an appropriate
7395 manner. For the case of the x86, for example, full precision mode is
7396 required. The procedure GNAT.Float_Control.Reset may be used to ensure
7397 that the FPU is in the right state.
7398
7399 @item adafinal
7400 @findex adafinal
7401 You must call this routine to perform any library-level finalization
7402 required by the Ada subprograms. A call to @code{adafinal} is required
7403 after the last call to an Ada subprogram, and before the program
7404 terminates.
7405 @end table
7406
7407 @noindent
7408 If the @option{^-n^/NOMAIN^} switch
7409 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7410 @cindex Binder, multiple input files
7411 is given, more than one ALI file may appear on
7412 the command line for @code{gnatbind}. The normal @dfn{closure}
7413 calculation is performed for each of the specified units. Calculating
7414 the closure means finding out the set of units involved by tracing
7415 @code{with} references. The reason it is necessary to be able to
7416 specify more than one ALI file is that a given program may invoke two or
7417 more quite separate groups of Ada units.
7418
7419 The binder takes the name of its output file from the last specified ALI
7420 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
7421 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
7422 The output is an Ada unit in source form that can
7423 be compiled with GNAT unless the -C switch is used in which case the
7424 output is a C source file, which must be compiled using the C compiler.
7425 This compilation occurs automatically as part of the @code{gnatlink}
7426 processing.
7427
7428 Currently the GNAT run time requires a FPU using 80 bits mode
7429 precision. Under targets where this is not the default it is required to
7430 call GNAT.Float_Control.Reset before using floating point numbers (this
7431 include float computation, float input and output) in the Ada code. A
7432 side effect is that this could be the wrong mode for the foreign code
7433 where floating point computation could be broken after this call.
7434
7435 @node Binding Programs with No Main Subprogram
7436 @subsection Binding Programs with No Main Subprogram
7437
7438 @noindent
7439 It is possible to have an Ada program which does not have a main
7440 subprogram. This program will call the elaboration routines of all the
7441 packages, then the finalization routines.
7442
7443 The following switch is used to bind programs organized in this manner:
7444
7445 @table @option
7446 @item ^-z^/ZERO_MAIN^
7447 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7448 Normally the binder checks that the unit name given on the command line
7449 corresponds to a suitable main subprogram. When this switch is used,
7450 a list of ALI files can be given, and the execution of the program
7451 consists of elaboration of these units in an appropriate order.
7452 @end table
7453
7454
7455 @node Command-Line Access
7456 @section Command-Line Access
7457
7458 @noindent
7459 The package @code{Ada.Command_Line} provides access to the command-line
7460 arguments and program name. In order for this interface to operate
7461 correctly, the two variables
7462
7463 @smallexample
7464 @group
7465 int gnat_argc;
7466 char **gnat_argv;
7467 @end group
7468 @end smallexample
7469
7470 @noindent
7471 @findex gnat_argv
7472 @findex gnat_argc
7473 are declared in one of the GNAT library routines. These variables must
7474 be set from the actual @code{argc} and @code{argv} values passed to the
7475 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
7476 generates the C main program to automatically set these variables.
7477 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
7478 set these variables. If they are not set, the procedures in
7479 @code{Ada.Command_Line} will not be available, and any attempt to use
7480 them will raise @code{Constraint_Error}. If command line access is
7481 required, your main program must set @code{gnat_argc} and
7482 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
7483 it.
7484
7485
7486 @node Search Paths for gnatbind
7487 @section Search Paths for @code{gnatbind}
7488
7489 @noindent
7490 The binder takes the name of an ALI file as its argument and needs to
7491 locate source files as well as other ALI files to verify object consistency.
7492
7493 For source files, it follows exactly the same search rules as @code{gcc}
7494 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
7495 directories searched are:
7496
7497 @enumerate
7498 @item
7499 The directory containing the ALI file named in the command line, unless
7500 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
7501
7502 @item
7503 All directories specified by @option{^-I^/SEARCH^}
7504 switches on the @code{gnatbind}
7505 command line, in the order given.
7506
7507 @item
7508 @findex ADA_OBJECTS_PATH
7509 Each of the directories listed in the value of the
7510 @code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
7511 @ifset unw
7512 Construct this value
7513 exactly as the @code{PATH} environment variable: a list of directory
7514 names separated by colons (semicolons when working with the NT version
7515 of GNAT).
7516 @end ifset
7517 @ifset vms
7518 Normally, define this value as a logical name containing a comma separated
7519 list of directory names.
7520
7521 This variable can also be defined by means of an environment string
7522 (an argument to the DEC C exec* set of functions).
7523
7524 Logical Name:
7525 @smallexample
7526 DEFINE ANOTHER_PATH FOO:[BAG]
7527 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7528 @end smallexample
7529
7530 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7531 first, followed by the standard Ada 95
7532 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
7533 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
7534 (Text_IO, Sequential_IO, etc)
7535 instead of the Ada95 packages. Thus, in order to get the Ada 95
7536 packages by default, ADA_OBJECTS_PATH must be redefined.
7537 @end ifset
7538
7539 @item
7540 @findex ADA_PRJ_OBJECTS_FILE
7541 Each of the directories listed in the text file whose name is given
7542 by the @code{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
7543
7544 @noindent
7545 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7546 driver when project files are used. It should not normally be set
7547 by other means.
7548
7549 @item
7550 The content of the @file{ada_object_path} file which is part of the GNAT
7551 installation tree and is used to store standard libraries such as the
7552 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
7553 specified.
7554 @ifclear vms
7555 @ref{Installing an Ada Library}
7556 @end ifclear
7557 @end enumerate
7558
7559 @noindent
7560 In the binder the switch @option{^-I^/SEARCH^}
7561 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7562 is used to specify both source and
7563 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
7564 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7565 instead if you want to specify
7566 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
7567 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
7568 if you want to specify library paths
7569 only. This means that for the binder
7570 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
7571 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
7572 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
7573 The binder generates the bind file (a C language source file) in the
7574 current working directory.
7575
7576 @findex Ada
7577 @findex System
7578 @findex Interfaces
7579 @findex GNAT
7580 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7581 children make up the GNAT Run-Time Library, together with the package
7582 GNAT and its children, which contain a set of useful additional
7583 library functions provided by GNAT. The sources for these units are
7584 needed by the compiler and are kept together in one directory. The ALI
7585 files and object files generated by compiling the RTL are needed by the
7586 binder and the linker and are kept together in one directory, typically
7587 different from the directory containing the sources. In a normal
7588 installation, you need not specify these directory names when compiling
7589 or binding. Either the environment variables or the built-in defaults
7590 cause these files to be found.
7591
7592 Besides simplifying access to the RTL, a major use of search paths is
7593 in compiling sources from multiple directories. This can make
7594 development environments much more flexible.
7595
7596 @node Examples of gnatbind Usage
7597 @section Examples of @code{gnatbind} Usage
7598
7599 @noindent
7600 This section contains a number of examples of using the GNAT binding
7601 utility @code{gnatbind}.
7602
7603 @table @code
7604 @item gnatbind hello
7605 The main program @code{Hello} (source program in @file{hello.adb}) is
7606 bound using the standard switch settings. The generated main program is
7607 @file{b~hello.adb}. This is the normal, default use of the binder.
7608
7609 @ifclear vms
7610 @item gnatbind hello -o mainprog.adb
7611 @end ifclear
7612 @ifset vms
7613 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
7614 @end ifset
7615 The main program @code{Hello} (source program in @file{hello.adb}) is
7616 bound using the standard switch settings. The generated main program is
7617 @file{mainprog.adb} with the associated spec in
7618 @file{mainprog.ads}. Note that you must specify the body here not the
7619 spec, in the case where the output is in Ada. Note that if this option
7620 is used, then linking must be done manually, since gnatlink will not
7621 be able to find the generated file.
7622
7623 @ifclear vms
7624 @item gnatbind main -C -o mainprog.c -x
7625 @end ifclear
7626 @ifset vms
7627 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
7628 @end ifset
7629 The main program @code{Main} (source program in
7630 @file{main.adb}) is bound, excluding source files from the
7631 consistency checking, generating
7632 the file @file{mainprog.c}.
7633
7634 @ifclear vms
7635 @item gnatbind -x main_program -C -o mainprog.c
7636 This command is exactly the same as the previous example. Switches may
7637 appear anywhere in the command line, and single letter switches may be
7638 combined into a single switch.
7639 @end ifclear
7640
7641 @ifclear vms
7642 @item gnatbind -n math dbase -C -o ada-control.c
7643 @end ifclear
7644 @ifset vms
7645 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
7646 @end ifset
7647 The main program is in a language other than Ada, but calls to
7648 subprograms in packages @code{Math} and @code{Dbase} appear. This call
7649 to @code{gnatbind} generates the file @file{ada-control.c} containing
7650 the @code{adainit} and @code{adafinal} routines to be called before and
7651 after accessing the Ada units.
7652 @end table
7653
7654
7655 @c ------------------------------------
7656 @node Linking Using gnatlink
7657 @chapter Linking Using @code{gnatlink}
7658 @c ------------------------------------
7659 @findex gnatlink
7660
7661 @noindent
7662 This chapter discusses @code{gnatlink}, a tool that links
7663 an Ada program and builds an executable file. This utility
7664 invokes the system linker ^(via the @code{gcc} command)^^
7665 with a correct list of object files and library references.
7666 @code{gnatlink} automatically determines the list of files and
7667 references for the Ada part of a program. It uses the binder file
7668 generated by the @command{gnatbind} to determine this list.
7669
7670 @menu
7671 * Running gnatlink::
7672 * Switches for gnatlink::
7673 * Setting Stack Size from gnatlink::
7674 * Setting Heap Size from gnatlink::
7675 @end menu
7676
7677 @node Running gnatlink
7678 @section Running @code{gnatlink}
7679
7680 @noindent
7681 The form of the @code{gnatlink} command is
7682
7683 @smallexample
7684 $ gnatlink [@var{switches}] @var{mainprog}[.ali]
7685            [@var{non-Ada objects}] [@var{linker options}]
7686 @end smallexample
7687
7688 @noindent
7689 The arguments of @code{gnatlink} (switches, main @file{ALI} file,
7690 non-Ada objects
7691 or linker options) may be in any order, provided that no non-Ada object may
7692 be mistaken for a main @file{ALI} file.
7693 Any file name @file{F} without the @file{.ali}
7694 extension will be taken as the main @file{ALI} file if a file exists
7695 whose name is the concatenation of @file{F} and @file{.ali}.
7696
7697 @noindent
7698 @file{@var{mainprog}.ali} references the ALI file of the main program.
7699 The @file{.ali} extension of this file can be omitted. From this
7700 reference, @code{gnatlink} locates the corresponding binder file
7701 @file{b~@var{mainprog}.adb} and, using the information in this file along
7702 with the list of non-Ada objects and linker options, constructs a
7703 linker command file to create the executable.
7704
7705 The arguments other than the @code{gnatlink} switches and the main @file{ALI}
7706 file are passed to the linker uninterpreted.
7707 They typically include the names of
7708 object files for units written in other languages than Ada and any library
7709 references required to resolve references in any of these foreign language
7710 units, or in @code{Import} pragmas in any Ada units.
7711
7712 @var{linker options} is an optional list of linker specific
7713 switches.
7714 The default linker called by gnatlink is @var{gcc} which in
7715 turn calls the appropriate system linker.
7716 Standard options for the linker such as @option{-lmy_lib} or
7717 @option{-Ldir} can be added as is.
7718 For options that are not recognized by
7719 @var{gcc} as linker options, use the @var{gcc} switches @option{-Xlinker} or
7720 @option{-Wl,}.
7721 Refer to the GCC documentation for
7722 details. Here is an example showing how to generate a linker map:
7723
7724 @ifclear vms
7725 @smallexample
7726 $ gnatlink my_prog -Wl,-Map,MAPFILE
7727 @end smallexample
7728 @end ifclear
7729
7730 @ifset vms
7731 <<Need example for VMS>>
7732 @end ifset
7733
7734 Using @var{linker options} it is possible to set the program stack and
7735 heap size. See @ref{Setting Stack Size from gnatlink}, and
7736 @ref{Setting Heap Size from gnatlink}.
7737
7738 @code{gnatlink} determines the list of objects required by the Ada
7739 program and prepends them to the list of objects passed to the linker.
7740 @code{gnatlink} also gathers any arguments set by the use of
7741 @code{pragma Linker_Options} and adds them to the list of arguments
7742 presented to the linker.
7743
7744 @ifset vms
7745 @code{gnatlink} accepts the following types of extra files on the command
7746 line: objects (.OBJ), libraries (.OLB), sharable images (.EXE), and
7747 options files (.OPT). These are recognized and handled according to their
7748 extension.
7749 @end ifset
7750
7751 @node Switches for gnatlink
7752 @section Switches for @code{gnatlink}
7753
7754 @noindent
7755 The following switches are available with the @code{gnatlink} utility:
7756
7757 @table @option
7758 @c !sort!
7759
7760 @item ^-A^/BIND_FILE=ADA^
7761 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatlink})
7762 The binder has generated code in Ada. This is the default.
7763
7764 @item ^-C^/BIND_FILE=C^
7765 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatlink})
7766 If instead of generating a file in Ada, the binder has generated one in
7767 C, then the linker needs to know about it. Use this switch to signal
7768 to @code{gnatlink} that the binder has generated C code rather than
7769 Ada code.
7770
7771 @item ^-f^/FORCE_OBJECT_FILE_LIST^
7772 @cindex Command line length
7773 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@code{gnatlink})
7774 On some targets, the command line length is limited, and @code{gnatlink}
7775 will generate a separate file for the linker if the list of object files
7776 is too long.
7777 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
7778 to be generated even if
7779 the limit is not exceeded. This is useful in some cases to deal with
7780 special situations where the command line length is exceeded.
7781
7782 @item ^-g^/DEBUG^
7783 @cindex Debugging information, including
7784 @cindex @option{^-g^/DEBUG^} (@code{gnatlink})
7785 The option to include debugging information causes the Ada bind file (in
7786 other words, @file{b~@var{mainprog}.adb}) to be compiled with
7787 @option{^-g^/DEBUG^}.
7788 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
7789 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
7790 Without @option{^-g^/DEBUG^}, the binder removes these files by
7791 default. The same procedure apply if a C bind file was generated using
7792 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
7793 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
7794
7795 @item ^-n^/NOCOMPILE^
7796 @cindex @option{^-n^/NOCOMPILE^} (@code{gnatlink})
7797 Do not compile the file generated by the binder. This may be used when
7798 a link is rerun with different options, but there is no need to recompile
7799 the binder file.
7800
7801 @item ^-v^/VERBOSE^
7802 @cindex @option{^-v^/VERBOSE^} (@code{gnatlink})
7803 Causes additional information to be output, including a full list of the
7804 included object files. This switch option is most useful when you want
7805 to see what set of object files are being used in the link step.
7806
7807 @item ^-v -v^/VERBOSE/VERBOSE^
7808 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@code{gnatlink})
7809 Very verbose mode. Requests that the compiler operate in verbose mode when
7810 it compiles the binder file, and that the system linker run in verbose mode.
7811
7812 @item ^-o ^/EXECUTABLE=^@var{exec-name}
7813 @cindex @option{^-o^/EXECUTABLE^} (@code{gnatlink})
7814 @var{exec-name} specifies an alternate name for the generated
7815 executable program. If this switch is omitted, the executable has the same
7816 name as the main unit. For example, @code{gnatlink try.ali} creates
7817 an executable called @file{^try^TRY.EXE^}.
7818
7819 @ifclear vms
7820 @item -b @var{target}
7821 @cindex @option{-b} (@code{gnatlink})
7822 Compile your program to run on @var{target}, which is the name of a
7823 system configuration. You must have a GNAT cross-compiler built if
7824 @var{target} is not the same as your host system.
7825
7826 @item -B@var{dir}
7827 @cindex @option{-B} (@code{gnatlink})
7828 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
7829 from @var{dir} instead of the default location. Only use this switch
7830 when multiple versions of the GNAT compiler are available. See the
7831 @code{gcc} manual page for further details. You would normally use the
7832 @option{-b} or @option{-V} switch instead.
7833
7834 @item --GCC=@var{compiler_name}
7835 @cindex @option{--GCC=compiler_name} (@code{gnatlink})
7836 Program used for compiling the binder file. The default is
7837 `@code{gcc}'. You need to use quotes around @var{compiler_name} if
7838 @code{compiler_name} contains spaces or other separator characters. As
7839 an example @option{--GCC="foo -x -y"} will instruct @code{gnatlink} to use
7840 @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
7841 inserted after your command name. Thus in the above example the compiler
7842 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
7843 If several @option{--GCC=compiler_name} are used, only the last
7844 @var{compiler_name} is taken into account. However, all the additional
7845 switches are also taken into account. Thus,
7846 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7847 @option{--GCC="bar -x -y -z -t"}.
7848
7849 @item --LINK=@var{name}
7850 @cindex @option{--LINK=} (@code{gnatlink})
7851 @var{name} is the name of the linker to be invoked. This is especially
7852 useful in mixed language programs since languages such as C++ require
7853 their own linker to be used. When this switch is omitted, the default
7854 name for the linker is (@file{gcc}). When this switch is used, the
7855 specified linker is called instead of (@file{gcc}) with exactly the same
7856 parameters that would have been passed to (@file{gcc}) so if the desired
7857 linker requires different parameters it is necessary to use a wrapper
7858 script that massages the parameters before invoking the real linker. It
7859 may be useful to control the exact invocation by using the verbose
7860 switch.
7861
7862 @end ifclear
7863
7864 @ifset vms
7865 @item /DEBUG=TRACEBACK
7866 @cindex @code{/DEBUG=TRACEBACK} (@code{gnatlink})
7867 This qualifier causes sufficient information to be included in the
7868 executable file to allow a traceback, but does not include the full
7869 symbol information needed by the debugger.
7870
7871 @item /IDENTIFICATION="<string>"
7872 @code{"<string>"} specifies the string to be stored in the image file
7873 identification field in the image header.
7874 It overrides any pragma @code{Ident} specified string.
7875
7876 @item /NOINHIBIT-EXEC
7877 Generate the executable file even if there are linker warnings.
7878
7879 @item /NOSTART_FILES
7880 Don't link in the object file containing the ``main'' transfer address.
7881 Used when linking with a foreign language main program compiled with a
7882 Digital compiler.
7883
7884 @item /STATIC
7885 Prefer linking with object libraries over sharable images, even without
7886 /DEBUG.
7887 @end ifset
7888
7889 @end table
7890
7891 @node Setting Stack Size from gnatlink
7892 @section Setting Stack Size from @code{gnatlink}
7893
7894 @noindent
7895 Under Windows systems, it is possible to specify the program stack size from
7896 @code{gnatlink} using either:
7897
7898 @itemize @bullet
7899
7900 @item using @option{-Xlinker} linker option
7901
7902 @smallexample
7903 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
7904 @end smallexample
7905
7906 This sets the stack reserve size to 0x10000 bytes and the stack commit
7907 size to 0x1000 bytes.
7908
7909 @item using @option{-Wl} linker option
7910
7911 @smallexample
7912 $ gnatlink hello -Wl,--stack=0x1000000
7913 @end smallexample
7914
7915 This sets the stack reserve size to 0x1000000 bytes. Note that with
7916 @option{-Wl} option it is not possible to set the stack commit size
7917 because the coma is a separator for this option.
7918
7919 @end itemize
7920
7921 @node Setting Heap Size from gnatlink
7922 @section Setting Heap Size from @code{gnatlink}
7923
7924 @noindent
7925 Under Windows systems, it is possible to specify the program heap size from
7926 @code{gnatlink} using either:
7927
7928 @itemize @bullet
7929
7930 @item using @option{-Xlinker} linker option
7931
7932 @smallexample
7933 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
7934 @end smallexample
7935
7936 This sets the heap reserve size to 0x10000 bytes and the heap commit
7937 size to 0x1000 bytes.
7938
7939 @item using @option{-Wl} linker option
7940
7941 @smallexample
7942 $ gnatlink hello -Wl,--heap=0x1000000
7943 @end smallexample
7944
7945 This sets the heap reserve size to 0x1000000 bytes. Note that with
7946 @option{-Wl} option it is not possible to set the heap commit size
7947 because the coma is a separator for this option.
7948
7949 @end itemize
7950
7951 @node The GNAT Make Program gnatmake
7952 @chapter The GNAT Make Program @code{gnatmake}
7953 @findex gnatmake
7954
7955 @menu
7956 * Running gnatmake::
7957 * Switches for gnatmake::
7958 * Mode Switches for gnatmake::
7959 * Notes on the Command Line::
7960 * How gnatmake Works::
7961 * Examples of gnatmake Usage::
7962 @end menu
7963 @noindent
7964 A typical development cycle when working on an Ada program consists of
7965 the following steps:
7966
7967 @enumerate
7968 @item
7969 Edit some sources to fix bugs.
7970
7971 @item
7972 Add enhancements.
7973
7974 @item
7975 Compile all sources affected.
7976
7977 @item
7978 Rebind and relink.
7979
7980 @item
7981 Test.
7982 @end enumerate
7983
7984 @noindent
7985 The third step can be tricky, because not only do the modified files
7986 @cindex Dependency rules
7987 have to be compiled, but any files depending on these files must also be
7988 recompiled. The dependency rules in Ada can be quite complex, especially
7989 in the presence of overloading, @code{use} clauses, generics and inlined
7990 subprograms.
7991
7992 @code{gnatmake} automatically takes care of the third and fourth steps
7993 of this process. It determines which sources need to be compiled,
7994 compiles them, and binds and links the resulting object files.
7995
7996 Unlike some other Ada make programs, the dependencies are always
7997 accurately recomputed from the new sources. The source based approach of
7998 the GNAT compilation model makes this possible. This means that if
7999 changes to the source program cause corresponding changes in
8000 dependencies, they will always be tracked exactly correctly by
8001 @code{gnatmake}.
8002
8003 @node Running gnatmake
8004 @section Running @code{gnatmake}
8005
8006 @noindent
8007 The usual form of the @code{gnatmake} command is
8008
8009 @smallexample
8010 $ gnatmake [@var{switches}] @var{file_name}
8011       [@var{file_names}] [@var{mode_switches}]
8012 @end smallexample
8013
8014 @noindent
8015 The only required argument is one @var{file_name}, which specifies
8016 a compilation unit that is a main program. Several @var{file_names} can be
8017 specified: this will result in several executables being built.
8018 If @code{switches} are present, they can be placed before the first
8019 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8020 If @var{mode_switches} are present, they must always be placed after
8021 the last @var{file_name} and all @code{switches}.
8022
8023 If you are using standard file extensions (.adb and .ads), then the
8024 extension may be omitted from the @var{file_name} arguments. However, if
8025 you are using non-standard extensions, then it is required that the
8026 extension be given. A relative or absolute directory path can be
8027 specified in a @var{file_name}, in which case, the input source file will
8028 be searched for in the specified directory only. Otherwise, the input
8029 source file will first be searched in the directory where
8030 @code{gnatmake} was invoked and if it is not found, it will be search on
8031 the source path of the compiler as described in
8032 @ref{Search Paths and the Run-Time Library (RTL)}.
8033
8034 All @code{gnatmake} output (except when you specify
8035 @option{^-M^/DEPENDENCIES_LIST^}) is to
8036 @file{stderr}. The output produced by the
8037 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8038 @file{stdout}.
8039
8040 @node Switches for gnatmake
8041 @section Switches for @code{gnatmake}
8042
8043 @noindent
8044 You may specify any of the following switches to @code{gnatmake}:
8045
8046 @table @option
8047 @c !sort!
8048 @ifclear vms
8049 @item --GCC=@var{compiler_name}
8050 @cindex @option{--GCC=compiler_name} (@code{gnatmake})
8051 Program used for compiling. The default is `@code{gcc}'. You need to use
8052 quotes around @var{compiler_name} if @code{compiler_name} contains
8053 spaces or other separator characters. As an example @option{--GCC="foo -x
8054 -y"} will instruct @code{gnatmake} to use @code{foo -x -y} as your
8055 compiler. Note that switch @option{-c} is always inserted after your
8056 command name. Thus in the above example the compiler command that will
8057 be used by @code{gnatmake} will be @code{foo -c -x -y}.
8058 If several @option{--GCC=compiler_name} are used, only the last
8059 @var{compiler_name} is taken into account. However, all the additional
8060 switches are also taken into account. Thus,
8061 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8062 @option{--GCC="bar -x -y -z -t"}.
8063
8064 @item --GNATBIND=@var{binder_name}
8065 @cindex @option{--GNATBIND=binder_name} (@code{gnatmake})
8066 Program used for binding. The default is `@code{gnatbind}'. You need to
8067 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8068 or other separator characters. As an example @option{--GNATBIND="bar -x
8069 -y"} will instruct @code{gnatmake} to use @code{bar -x -y} as your
8070 binder. Binder switches that are normally appended by @code{gnatmake} to
8071 `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8072
8073 @item --GNATLINK=@var{linker_name}
8074 @cindex @option{--GNATLINK=linker_name} (@code{gnatmake})
8075 Program used for linking. The default is `@code{gnatlink}'. You need to
8076 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8077 or other separator characters. As an example @option{--GNATLINK="lan -x
8078 -y"} will instruct @code{gnatmake} to use @code{lan -x -y} as your
8079 linker. Linker switches that are normally appended by @code{gnatmake} to
8080 `@code{gnatlink}' are now appended to the end of @code{lan -x -y}.
8081
8082 @end ifclear
8083
8084 @item ^-a^/ALL_FILES^
8085 @cindex @option{^-a^/ALL_FILES^} (@code{gnatmake})
8086 Consider all files in the make process, even the GNAT internal system
8087 files (for example, the predefined Ada library files), as well as any
8088 locked files. Locked files are files whose ALI file is write-protected.
8089 By default,
8090 @code{gnatmake} does not check these files,
8091 because the assumption is that the GNAT internal files are properly up
8092 to date, and also that any write protected ALI files have been properly
8093 installed. Note that if there is an installation problem, such that one
8094 of these files is not up to date, it will be properly caught by the
8095 binder.
8096 You may have to specify this switch if you are working on GNAT
8097 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8098 in conjunction with @option{^-f^/FORCE_COMPILE^}
8099 if you need to recompile an entire application,
8100 including run-time files, using special configuration pragmas,
8101 such as a @code{Normalize_Scalars} pragma.
8102
8103 By default
8104 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8105 internal files with
8106 @ifclear vms
8107 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8108 @end ifclear
8109 @ifset vms
8110 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8111 @end ifset
8112
8113 @item ^-b^/ACTIONS=BIND^
8114 @cindex @option{^-b^/ACTIONS=BIND^} (@code{gnatmake})
8115 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8116 compilation and binding, but no link.
8117 Can be combined with @option{^-l^/ACTIONS=LINK^}
8118 to do binding and linking. When not combined with
8119 @option{^-c^/ACTIONS=COMPILE^}
8120 all the units in the closure of the main program must have been previously
8121 compiled and must be up to date. The root unit specified by @var{file_name}
8122 may be given without extension, with the source extension or, if no GNAT
8123 Project File is specified, with the ALI file extension.
8124
8125 @item ^-c^/ACTIONS=COMPILE^
8126 @cindex @option{^-c^/ACTIONS=COMPILE^} (@code{gnatmake})
8127 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8128 is also specified. Do not perform linking, except if both
8129 @option{^-b^/ACTIONS=BIND^} and
8130  @option{^-l^/ACTIONS=LINK^} are also specified.
8131 If the root unit specified by @var{file_name} is not a main unit, this is the
8132 default. Otherwise @code{gnatmake} will attempt binding and linking
8133 unless all objects are up to date and the executable is more recent than
8134 the objects.
8135
8136 @item ^-C^/MAPPING^
8137 @cindex @option{^-C^/MAPPING^} (@code{gnatmake})
8138 Use a temporary mapping file. A mapping file is a way to communicate to the
8139 compiler two mappings: from unit names to file names (without any directory
8140 information) and from file names to path names (with full directory
8141 information). These mappings are used by the compiler to short-circuit the path
8142 search. When @code{gnatmake} is invoked with this switch, it will create
8143 a temporary mapping file, initially populated by the project manager,
8144 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8145 Each invocation of the compiler will add the newly accessed sources to the
8146 mapping file. This will improve the source search during the next invocation
8147 of the compiler.
8148
8149 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8150 @cindex @option{^-C=^/USE_MAPPING^} (@code{gnatmake})
8151 Use a specific mapping file. The file, specified as a path name (absolute or
8152 relative) by this switch, should already exist, otherwise the switch is
8153 ineffective. The specified mapping file will be communicated to the compiler.
8154 This switch is not compatible with a project file
8155 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8156 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8157
8158 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8159 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatmake})
8160 Put all object files and ALI file in directory @var{dir}.
8161 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8162 and ALI files go in the current working directory.
8163
8164 This switch cannot be used when using a project file.
8165
8166 @ifclear vms
8167 @item -eL
8168 @cindex @option{-eL} (@code{gnatmake})
8169 Follow all symbolic links when processing project files.
8170 @end ifclear
8171
8172 @item ^-f^/FORCE_COMPILE^
8173 @cindex @option{^-f^/FORCE_COMPILE^} (@code{gnatmake})
8174 Force recompilations. Recompile all sources, even though some object
8175 files may be up to date, but don't recompile predefined or GNAT internal
8176 files or locked files (files with a write-protected ALI file),
8177 unless the @option{^-a^/ALL_FILES^} switch is also specified.
8178
8179 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
8180 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatmake})
8181 When using project files, if some errors or warnings are detected during
8182 parsing and verbose mode is not in effect (no use of switch
8183 ^-v^/VERBOSE^), then error lines start with the full path name of the project
8184 file, rather than its simple file name.
8185
8186 @item ^-i^/IN_PLACE^
8187 @cindex @option{^-i^/IN_PLACE^} (@code{gnatmake})
8188 In normal mode, @code{gnatmake} compiles all object files and ALI files
8189 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
8190 then instead object files and ALI files that already exist are overwritten
8191 in place. This means that once a large project is organized into separate
8192 directories in the desired manner, then @code{gnatmake} will automatically
8193 maintain and update this organization. If no ALI files are found on the
8194 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
8195 the new object and ALI files are created in the
8196 directory containing the source being compiled. If another organization
8197 is desired, where objects and sources are kept in different directories,
8198 a useful technique is to create dummy ALI files in the desired directories.
8199 When detecting such a dummy file, @code{gnatmake} will be forced to recompile
8200 the corresponding source file, and it will be put the resulting object
8201 and ALI files in the directory where it found the dummy file.
8202
8203 @item ^-j^/PROCESSES=^@var{n}
8204 @cindex @option{^-j^/PROCESSES^} (@code{gnatmake})
8205 @cindex Parallel make
8206 Use @var{n} processes to carry out the (re)compilations. On a
8207 multiprocessor machine compilations will occur in parallel. In the
8208 event of compilation errors, messages from various compilations might
8209 get interspersed (but @code{gnatmake} will give you the full ordered
8210 list of failing compiles at the end). If this is problematic, rerun
8211 the make process with n set to 1 to get a clean list of messages.
8212
8213 @item ^-k^/CONTINUE_ON_ERROR^
8214 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@code{gnatmake})
8215 Keep going. Continue as much as possible after a compilation error. To
8216 ease the programmer's task in case of compilation errors, the list of
8217 sources for which the compile fails is given when @code{gnatmake}
8218 terminates.
8219
8220 If @code{gnatmake} is invoked with several @file{file_names} and with this
8221 switch, if there are compilation errors when building an executable,
8222 @code{gnatmake} will not attempt to build the following executables.
8223
8224 @item ^-l^/ACTIONS=LINK^
8225 @cindex @option{^-l^/ACTIONS=LINK^} (@code{gnatmake})
8226 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
8227 and linking. Linking will not be performed if combined with
8228 @option{^-c^/ACTIONS=COMPILE^}
8229 but not with @option{^-b^/ACTIONS=BIND^}.
8230 When not combined with @option{^-b^/ACTIONS=BIND^}
8231 all the units in the closure of the main program must have been previously
8232 compiled and must be up to date, and the main program need to have been bound.
8233 The root unit specified by @var{file_name}
8234 may be given without extension, with the source extension or, if no GNAT
8235 Project File is specified, with the ALI file extension.
8236
8237 @item ^-m^/MINIMAL_RECOMPILATION^
8238 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@code{gnatmake})
8239 Specifies that the minimum necessary amount of recompilations
8240 be performed. In this mode @code{gnatmake} ignores time
8241 stamp differences when the only
8242 modifications to a source file consist in adding/removing comments,
8243 empty lines, spaces or tabs. This means that if you have changed the
8244 comments in a source file or have simply reformatted it, using this
8245 switch will tell gnatmake not to recompile files that depend on it
8246 (provided other sources on which these files depend have undergone no
8247 semantic modifications). Note that the debugging information may be
8248 out of date with respect to the sources if the @option{-m} switch causes
8249 a compilation to be switched, so the use of this switch represents a
8250 trade-off between compilation time and accurate debugging information.
8251
8252 @item ^-M^/DEPENDENCIES_LIST^
8253 @cindex Dependencies, producing list
8254 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@code{gnatmake})
8255 Check if all objects are up to date. If they are, output the object
8256 dependences to @file{stdout} in a form that can be directly exploited in
8257 a @file{Makefile}. By default, each source file is prefixed with its
8258 (relative or absolute) directory name. This name is whatever you
8259 specified in the various @option{^-aI^/SOURCE_SEARCH^}
8260 and @option{^-I^/SEARCH^} switches. If you use
8261 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
8262 @option{^-q^/QUIET^}
8263 (see below), only the source file names,
8264 without relative paths, are output. If you just specify the
8265 @option{^-M^/DEPENDENCIES_LIST^}
8266 switch, dependencies of the GNAT internal system files are omitted. This
8267 is typically what you want. If you also specify
8268 the @option{^-a^/ALL_FILES^} switch,
8269 dependencies of the GNAT internal files are also listed. Note that
8270 dependencies of the objects in external Ada libraries (see switch
8271 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
8272 are never reported.
8273
8274 @item ^-n^/DO_OBJECT_CHECK^
8275 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@code{gnatmake})
8276 Don't compile, bind, or link. Checks if all objects are up to date.
8277 If they are not, the full name of the first file that needs to be
8278 recompiled is printed.
8279 Repeated use of this option, followed by compiling the indicated source
8280 file, will eventually result in recompiling all required units.
8281
8282 @item ^-o ^/EXECUTABLE=^@var{exec_name}
8283 @cindex @option{^-o^/EXECUTABLE^} (@code{gnatmake})
8284 Output executable name. The name of the final executable program will be
8285 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
8286 name for the executable will be the name of the input file in appropriate form
8287 for an executable file on the host system.
8288
8289 This switch cannot be used when invoking @code{gnatmake} with several
8290 @file{file_names}.
8291
8292 @item ^-P^/PROJECT_FILE=^@var{project}
8293 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatmake})
8294 Use project file @var{project}. Only one such switch can be used.
8295 See @ref{gnatmake and Project Files}.
8296
8297 @item ^-q^/QUIET^
8298 @cindex @option{^-q^/QUIET^} (@code{gnatmake})
8299 Quiet. When this flag is not set, the commands carried out by
8300 @code{gnatmake} are displayed.
8301
8302 @item ^-s^/SWITCH_CHECK/^
8303 @cindex @option{^-s^/SWITCH_CHECK^} (@code{gnatmake})
8304 Recompile if compiler switches have changed since last compilation.
8305 All compiler switches but -I and -o are taken into account in the
8306 following way:
8307 orders between different ``first letter'' switches are ignored, but
8308 orders between same switches are taken into account. For example,
8309 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
8310 is equivalent to @option{-O -g}.
8311
8312 This switch is recommended when Integrated Preprocessing is used.
8313
8314 @item ^-u^/UNIQUE^
8315 @cindex @option{^-u^/UNIQUE^} (@code{gnatmake})
8316 Unique. Recompile at most the main files. It implies -c. Combined with
8317 -f, it is equivalent to calling the compiler directly. Note that using
8318 ^-u^/UNIQUE^ with a project file and no main has a special meaning
8319 (see @ref{Project Files and Main Subprograms}).
8320
8321 @item ^-U^/ALL_PROJECTS^
8322 @cindex @option{^-U^/ALL_PROJECTS^} (@code{gnatmake})
8323 When used without a project file or with one or several mains on the command
8324 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
8325 on the command line, all sources of all project files are checked and compiled
8326 if not up to date, and libraries are rebuilt, if necessary.
8327
8328 @item ^-v^/REASONS^
8329 @cindex @option{^-v^/REASONS^} (@code{gnatmake})
8330 Verbose. Displays the reason for all recompilations @code{gnatmake}
8331 decides are necessary.
8332
8333 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
8334 Indicates the verbosity of the parsing of GNAT project files.
8335 See @ref{Switches Related to Project Files}.
8336
8337 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
8338 Indicates that external variable @var{name} has the value @var{value}.
8339 The Project Manager will use this value for occurrences of
8340 @code{external(name)} when parsing the project file.
8341 See @ref{Switches Related to Project Files}.
8342
8343 @item ^-z^/NOMAIN^
8344 @cindex @option{^-z^/NOMAIN^} (@code{gnatmake})
8345 No main subprogram. Bind and link the program even if the unit name
8346 given on the command line is a package name. The resulting executable
8347 will execute the elaboration routines of the package and its closure,
8348 then the finalization routines.
8349
8350 @item ^-g^/DEBUG^
8351 @cindex @option{^-g^/DEBUG^} (@code{gnatmake})
8352 Enable debugging. This switch is simply passed to the compiler and to the
8353 linker.
8354
8355 @end table
8356
8357 @table @asis
8358 @item @code{gcc} @asis{switches}
8359 @ifclear vms
8360 Any uppercase or multi-character switch that is not a @code{gnatmake} switch
8361 is passed to @code{gcc} (e.g. @option{-O}, @option{-gnato,} etc.)
8362 @end ifclear
8363 @ifset vms
8364 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8365 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8366 automatically treated as a compiler switch, and passed on to all
8367 compilations that are carried out.
8368 @end ifset
8369 @end table
8370
8371 @noindent
8372 Source and library search path switches:
8373
8374 @table @option
8375 @c !sort!
8376 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8377 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatmake})
8378 When looking for source files also look in directory @var{dir}.
8379 The order in which source files search is undertaken is
8380 described in @ref{Search Paths and the Run-Time Library (RTL)}.
8381
8382 @item ^-aL^/SKIP_MISSING=^@var{dir}
8383 @cindex @option{^-aL^/SKIP_MISSING^} (@code{gnatmake})
8384 Consider @var{dir} as being an externally provided Ada library.
8385 Instructs @code{gnatmake} to skip compilation units whose @file{.ALI}
8386 files have been located in directory @var{dir}. This allows you to have
8387 missing bodies for the units in @var{dir} and to ignore out of date bodies
8388 for the same units. You still need to specify
8389 the location of the specs for these units by using the switches
8390 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
8391 or @option{^-I^/SEARCH=^@var{dir}}.
8392 Note: this switch is provided for compatibility with previous versions
8393 of @code{gnatmake}. The easier method of causing standard libraries
8394 to be excluded from consideration is to write-protect the corresponding
8395 ALI files.
8396
8397 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
8398 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatmake})
8399 When searching for library and object files, look in directory
8400 @var{dir}. The order in which library files are searched is described in
8401 @ref{Search Paths for gnatbind}.
8402
8403 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
8404 @cindex Search paths, for @code{gnatmake}
8405 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@code{gnatmake})
8406 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
8407 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8408
8409 @item ^-I^/SEARCH=^@var{dir}
8410 @cindex @option{^-I^/SEARCH^} (@code{gnatmake})
8411 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
8412 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8413
8414 @item ^-I-^/NOCURRENT_DIRECTORY^
8415 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatmake})
8416 @cindex Source files, suppressing search
8417 Do not look for source files in the directory containing the source
8418 file named in the command line.
8419 Do not look for ALI or object files in the directory
8420 where @code{gnatmake} was invoked.
8421
8422 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
8423 @cindex @option{^-L^/LIBRARY_SEARCH^} (@code{gnatmake})
8424 @cindex Linker libraries
8425 Add directory @var{dir} to the list of directories in which the linker
8426 will search for libraries. This is equivalent to
8427 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
8428 @ifclear vms
8429 Furthermore, under Windows, the sources pointed to by the libraries path
8430 set in the registry are not searched for.
8431 @end ifclear
8432
8433 @item -nostdinc
8434 @cindex @option{-nostdinc} (@code{gnatmake})
8435 Do not look for source files in the system default directory.
8436
8437 @item -nostdlib
8438 @cindex @option{-nostdlib} (@code{gnatmake})
8439 Do not look for library files in the system default directory.
8440
8441 @item --RTS=@var{rts-path}
8442 @cindex @option{--RTS} (@code{gnatmake})
8443 Specifies the default location of the runtime library. GNAT looks for the
8444 runtime
8445 in the following directories, and stops as soon as a valid runtime is found
8446 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
8447 @file{ada_object_path} present):
8448
8449 @itemize @bullet
8450 @item <current directory>/$rts_path
8451
8452 @item <default-search-dir>/$rts_path
8453
8454 @item <default-search-dir>/rts-$rts_path
8455 @end itemize
8456
8457 @noindent
8458 The selected path is handled like a normal RTS path.
8459
8460 @end table
8461
8462 @node Mode Switches for gnatmake
8463 @section Mode Switches for @code{gnatmake}
8464
8465 @noindent
8466 The mode switches (referred to as @code{mode_switches}) allow the
8467 inclusion of switches that are to be passed to the compiler itself, the
8468 binder or the linker. The effect of a mode switch is to cause all
8469 subsequent switches up to the end of the switch list, or up to the next
8470 mode switch, to be interpreted as switches to be passed on to the
8471 designated component of GNAT.
8472
8473 @table @option
8474 @c !sort!
8475 @item -cargs @var{switches}
8476 @cindex @option{-cargs} (@code{gnatmake})
8477 Compiler switches. Here @var{switches} is a list of switches
8478 that are valid switches for @code{gcc}. They will be passed on to
8479 all compile steps performed by @code{gnatmake}.
8480
8481 @item -bargs @var{switches}
8482 @cindex @option{-bargs} (@code{gnatmake})
8483 Binder switches. Here @var{switches} is a list of switches
8484 that are valid switches for @code{gnatbind}. They will be passed on to
8485 all bind steps performed by @code{gnatmake}.
8486
8487 @item -largs @var{switches}
8488 @cindex @option{-largs} (@code{gnatmake})
8489 Linker switches. Here @var{switches} is a list of switches
8490 that are valid switches for @code{gnatlink}. They will be passed on to
8491 all link steps performed by @code{gnatmake}.
8492
8493 @item -margs @var{switches}
8494 @cindex @option{-margs} (@code{gnatmake})
8495 Make switches. The switches are directly interpreted by @code{gnatmake},
8496 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
8497 or @option{-largs}.
8498 @end table
8499
8500 @node Notes on the Command Line
8501 @section Notes on the Command Line
8502
8503 @noindent
8504 This section contains some additional useful notes on the operation
8505 of the @code{gnatmake} command.
8506
8507 @itemize @bullet
8508 @item
8509 @cindex Recompilation, by @code{gnatmake}
8510 If @code{gnatmake} finds no ALI files, it recompiles the main program
8511 and all other units required by the main program.
8512 This means that @code{gnatmake}
8513 can be used for the initial compile, as well as during subsequent steps of
8514 the development cycle.
8515
8516 @item
8517 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
8518 is a subunit or body of a generic unit, @code{gnatmake} recompiles
8519 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
8520 warning.
8521
8522 @item
8523 In @code{gnatmake} the switch @option{^-I^/SEARCH^}
8524 is used to specify both source and
8525 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8526 instead if you just want to specify
8527 source paths only and @option{^-aO^/OBJECT_SEARCH^}
8528 if you want to specify library paths
8529 only.
8530
8531 @item
8532 @code{gnatmake} examines both an ALI file and its corresponding object file
8533 for consistency. If an ALI is more recent than its corresponding object,
8534 or if the object file is missing, the corresponding source will be recompiled.
8535 Note that @code{gnatmake} expects an ALI and the corresponding object file
8536 to be in the same directory.
8537
8538 @item
8539 @code{gnatmake} will ignore any files whose ALI file is write-protected.
8540 This may conveniently be used to exclude standard libraries from
8541 consideration and in particular it means that the use of the
8542 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
8543 unless @option{^-a^/ALL_FILES^} is also specified.
8544
8545 @item
8546 @code{gnatmake} has been designed to make the use of Ada libraries
8547 particularly convenient. Assume you have an Ada library organized
8548 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
8549 of your Ada compilation units,
8550 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
8551 specs of these units, but no bodies. Then to compile a unit
8552 stored in @code{main.adb}, which uses this Ada library you would just type
8553
8554 @smallexample
8555 @ifclear vms
8556 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
8557 @end ifclear
8558 @ifset vms
8559 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
8560            /SKIP_MISSING=@i{[OBJ_DIR]} main
8561 @end ifset
8562 @end smallexample
8563
8564 @item
8565 Using @code{gnatmake} along with the
8566 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
8567 switch provides a mechanism for avoiding unnecessary rcompilations. Using
8568 this switch,
8569 you can update the comments/format of your
8570 source files without having to recompile everything. Note, however, that
8571 adding or deleting lines in a source files may render its debugging
8572 info obsolete. If the file in question is a spec, the impact is rather
8573 limited, as that debugging info will only be useful during the
8574 elaboration phase of your program. For bodies the impact can be more
8575 significant. In all events, your debugger will warn you if a source file
8576 is more recent than the corresponding object, and alert you to the fact
8577 that the debugging information may be out of date.
8578 @end itemize
8579
8580 @node How gnatmake Works
8581 @section How @code{gnatmake} Works
8582
8583 @noindent
8584 Generally @code{gnatmake} automatically performs all necessary
8585 recompilations and you don't need to worry about how it works. However,
8586 it may be useful to have some basic understanding of the @code{gnatmake}
8587 approach and in particular to understand how it uses the results of
8588 previous compilations without incorrectly depending on them.
8589
8590 First a definition: an object file is considered @dfn{up to date} if the
8591 corresponding ALI file exists and its time stamp predates that of the
8592 object file and if all the source files listed in the
8593 dependency section of this ALI file have time stamps matching those in
8594 the ALI file. This means that neither the source file itself nor any
8595 files that it depends on have been modified, and hence there is no need
8596 to recompile this file.
8597
8598 @code{gnatmake} works by first checking if the specified main unit is up
8599 to date. If so, no compilations are required for the main unit. If not,
8600 @code{gnatmake} compiles the main program to build a new ALI file that
8601 reflects the latest sources. Then the ALI file of the main unit is
8602 examined to find all the source files on which the main program depends,
8603 and @code{gnatmake} recursively applies the above procedure on all these files.
8604
8605 This process ensures that @code{gnatmake} only trusts the dependencies
8606 in an existing ALI file if they are known to be correct. Otherwise it
8607 always recompiles to determine a new, guaranteed accurate set of
8608 dependencies. As a result the program is compiled ``upside down'' from what may
8609 be more familiar as the required order of compilation in some other Ada
8610 systems. In particular, clients are compiled before the units on which
8611 they depend. The ability of GNAT to compile in any order is critical in
8612 allowing an order of compilation to be chosen that guarantees that
8613 @code{gnatmake} will recompute a correct set of new dependencies if
8614 necessary.
8615
8616 When invoking @code{gnatmake} with several @var{file_names}, if a unit is
8617 imported by several of the executables, it will be recompiled at most once.
8618
8619 Note: when using non-standard naming conventions
8620 (See @ref{Using Other File Names}), changing through a configuration pragmas
8621 file the version of a source and invoking @code{gnatmake} to recompile may
8622 have no effect, if the previous version of the source is still accessible
8623 by @code{gnatmake}. It may be necessary to use the switch ^-f^/FORCE_COMPILE^.
8624
8625 @node Examples of gnatmake Usage
8626 @section Examples of @code{gnatmake} Usage
8627
8628 @table @code
8629 @item gnatmake hello.adb
8630 Compile all files necessary to bind and link the main program
8631 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
8632 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
8633
8634 @item gnatmake main1 main2 main3
8635 Compile all files necessary to bind and link the main programs
8636 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
8637 (containing unit @code{Main2}) and @file{main3.adb}
8638 (containing unit @code{Main3}) and bind and link the resulting object files
8639 to generate three executable files @file{^main1^MAIN1.EXE^},
8640 @file{^main2^MAIN2.EXE^}
8641 and @file{^main3^MAIN3.EXE^}.
8642
8643 @ifclear vms
8644 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
8645 @end ifclear
8646
8647 @ifset vms
8648 @item gnatmake Main_Unit /QUIET
8649    /COMPILER_QUALIFIERS /OPTIMIZE=ALL
8650    /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
8651 @end ifset
8652 Compile all files necessary to bind and link the main program unit
8653 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
8654 be done with optimization level 2 and the order of elaboration will be
8655 listed by the binder. @code{gnatmake} will operate in quiet mode, not
8656 displaying commands it is executing.
8657 @end table
8658
8659
8660 @c *************************
8661 @node Improving Performance
8662 @chapter Improving Performance
8663 @cindex Improving performance
8664
8665 @noindent
8666 This chapter presents several topics related to program performance.
8667 It first describes some of the tradeoffs that need to be considered
8668 and some of the techniques for making your program run faster.
8669 It then documents the @command{gnatelim} tool, which can reduce
8670 the size of program executables.
8671
8672 @ifnottex
8673 @menu
8674 * Performance Considerations::
8675 * Reducing the Size of Ada Executables with gnatelim::
8676 @end menu
8677 @end ifnottex
8678
8679
8680 @c *****************************
8681 @node Performance Considerations
8682 @section Performance Considerations
8683
8684 @noindent
8685 The GNAT system provides a number of options that allow a trade-off
8686 between
8687
8688 @itemize @bullet
8689 @item
8690 performance of the generated code
8691
8692 @item
8693 speed of compilation
8694
8695 @item
8696 minimization of dependences and recompilation
8697
8698 @item
8699 the degree of run-time checking.
8700 @end itemize
8701
8702 @noindent
8703 The defaults (if no options are selected) aim at improving the speed
8704 of compilation and minimizing dependences, at the expense of performance
8705 of the generated code:
8706
8707 @itemize @bullet
8708 @item
8709 no optimization
8710
8711 @item
8712 no inlining of subprogram calls
8713
8714 @item
8715 all run-time checks enabled except overflow and elaboration checks
8716 @end itemize
8717
8718 @noindent
8719 These options are suitable for most program development purposes. This
8720 chapter describes how you can modify these choices, and also provides
8721 some guidelines on debugging optimized code.
8722
8723 @menu
8724 * Controlling Run-Time Checks::
8725 * Use of Restrictions::
8726 * Optimization Levels::
8727 * Debugging Optimized Code::
8728 * Inlining of Subprograms::
8729 * Optimization and Strict Aliasing::
8730 @ifset vms
8731 * Coverage Analysis::
8732 @end ifset
8733 @end menu
8734
8735 @node Controlling Run-Time Checks
8736 @subsection Controlling Run-Time Checks
8737
8738 @noindent
8739 By default, GNAT generates all run-time checks, except arithmetic overflow
8740 checking for integer operations and checks for access before elaboration on
8741 subprogram calls. The latter are not required in default mode, because all
8742 necessary checking is done at compile time.
8743 @cindex @option{-gnatp} (@code{gcc})
8744 @cindex @option{-gnato} (@code{gcc})
8745 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
8746 be modified. @xref{Run-Time Checks}.
8747
8748 Our experience is that the default is suitable for most development
8749 purposes.
8750
8751 We treat integer overflow specially because these
8752 are quite expensive and in our experience are not as important as other
8753 run-time checks in the development process. Note that division by zero
8754 is not considered an overflow check, and divide by zero checks are
8755 generated where required by default.
8756
8757 Elaboration checks are off by default, and also not needed by default, since
8758 GNAT uses a static elaboration analysis approach that avoids the need for
8759 run-time checking. This manual contains a full chapter discussing the issue
8760 of elaboration checks, and if the default is not satisfactory for your use,
8761 you should read this chapter.
8762
8763 For validity checks, the minimal checks required by the Ada Reference
8764 Manual (for case statements and assignments to array elements) are on
8765 by default. These can be suppressed by use of the @option{-gnatVn} switch.
8766 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
8767 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
8768 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
8769 are also suppressed entirely if @option{-gnatp} is used.
8770
8771 @cindex Overflow checks
8772 @cindex Checks, overflow
8773 @findex Suppress
8774 @findex Unsuppress
8775 @cindex pragma Suppress
8776 @cindex pragma Unsuppress
8777 Note that the setting of the switches controls the default setting of
8778 the checks. They may be modified using either @code{pragma Suppress} (to
8779 remove checks) or @code{pragma Unsuppress} (to add back suppressed
8780 checks) in the program source.
8781
8782 @node Use of Restrictions
8783 @subsection Use of Restrictions
8784
8785 @noindent
8786 The use of pragma Restrictions allows you to control which features are
8787 permitted in your program. Apart from the obvious point that if you avoid
8788 relatively expensive features like finalization (enforceable by the use
8789 of pragma Restrictions (No_Finalization), the use of this pragma does not
8790 affect the generated code in most cases.
8791
8792 One notable exception to this rule is that the possibility of task abort
8793 results in some distributed overhead, particularly if finalization or
8794 exception handlers are used. The reason is that certain sections of code
8795 have to be marked as non-abortable.
8796
8797 If you use neither the @code{abort} statement, nor asynchronous transfer
8798 of control (@code{select .. then abort}), then this distributed overhead
8799 is removed, which may have a general positive effect in improving
8800 overall performance.  Especially code involving frequent use of tasking
8801 constructs and controlled types will show much improved performance.
8802 The relevant restrictions pragmas are
8803
8804 @smallexample
8805    pragma Restrictions (No_Abort_Statements);
8806    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
8807 @end smallexample
8808
8809 @noindent
8810 It is recommended that these restriction pragmas be used if possible. Note
8811 that this also means that you can write code without worrying about the
8812 possibility of an immediate abort at any point.
8813
8814 @node Optimization Levels
8815 @subsection Optimization Levels
8816 @cindex @option{^-O^/OPTIMIZE^} (@code{gcc})
8817
8818 @noindent
8819 The default is optimization off. This results in the fastest compile
8820 times, but GNAT makes absolutely no attempt to optimize, and the
8821 generated programs are considerably larger and slower than when
8822 optimization is enabled. You can use the
8823 @ifclear vms
8824 @option{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
8825 @end ifclear
8826 @ifset vms
8827 @code{OPTIMIZE} qualifier
8828 @end ifset
8829 to @code{gcc} to control the optimization level:
8830
8831 @table @option
8832 @item ^-O0^/OPTIMIZE=NONE^
8833 No optimization (the default);
8834 generates unoptimized code but has
8835 the fastest compilation time.
8836
8837 @item ^-O1^/OPTIMIZE=SOME^
8838 Medium level optimization;
8839 optimizes reasonably well but does not
8840 degrade compilation time significantly.
8841
8842 @item ^-O2^/OPTIMIZE=ALL^
8843 @ifset vms
8844 @itemx /OPTIMIZE=DEVELOPMENT
8845 @end ifset
8846 Full optimization;
8847 generates highly optimized code and has
8848 the slowest compilation time.
8849
8850 @item ^-O3^/OPTIMIZE=INLINING^
8851 Full optimization as in @option{-O2},
8852 and also attempts automatic inlining of small
8853 subprograms within a unit (@pxref{Inlining of Subprograms}).
8854 @end table
8855
8856 @noindent
8857 Higher optimization levels perform more global transformations on the
8858 program and apply more expensive analysis algorithms in order to generate
8859 faster and more compact code. The price in compilation time, and the
8860 resulting improvement in execution time,
8861 both depend on the particular application and the hardware environment.
8862 You should experiment to find the best level for your application.
8863
8864 Since the precise set of optimizations done at each level will vary from
8865 release to release (and sometime from target to target), it is best to think
8866 of the optimization settings in general terms.
8867 The @cite{Using GNU GCC} manual contains details about
8868 ^the @option{-O} settings and a number of @option{-f} options that^how to^
8869 individually enable or disable specific optimizations.
8870
8871 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
8872 been tested extensively at all optimization levels. There are some bugs
8873 which appear only with optimization turned on, but there have also been
8874 bugs which show up only in @emph{unoptimized} code. Selecting a lower
8875 level of optimization does not improve the reliability of the code
8876 generator, which in practice is highly reliable at all optimization
8877 levels.
8878
8879 Note regarding the use of @option{-O3}: The use of this optimization level
8880 is generally discouraged with GNAT, since it often results in larger
8881 executables which run more slowly. See further discussion of this point
8882 in @pxref{Inlining of Subprograms}.
8883
8884
8885 @node Debugging Optimized Code
8886 @subsection Debugging Optimized Code
8887 @cindex Debugging optimized code
8888 @cindex Optimization and debugging
8889
8890 @noindent
8891 Although it is possible to do a reasonable amount of debugging at
8892 @ifclear vms
8893 non-zero optimization levels,
8894 the higher the level the more likely that
8895 @end ifclear
8896 @ifset vms
8897 @option{/OPTIMIZE} settings other than @code{NONE},
8898 such settings will make it more likely that
8899 @end ifset
8900 source-level constructs will have been eliminated by optimization.
8901 For example, if a loop is strength-reduced, the loop
8902 control variable may be completely eliminated and thus cannot be
8903 displayed in the debugger.
8904 This can only happen at @option{-O2} or @option{-O3}.
8905 Explicit temporary variables that you code might be eliminated at
8906 ^level^setting^ @option{-O1} or higher.
8907
8908 The use of the @option{^-g^/DEBUG^} switch,
8909 @cindex @option{^-g^/DEBUG^} (@code{gcc})
8910 which is needed for source-level debugging,
8911 affects the size of the program executable on disk,
8912 and indeed the debugging information can be quite large.
8913 However, it has no effect on the generated code (and thus does not
8914 degrade performance)
8915
8916 Since the compiler generates debugging tables for a compilation unit before
8917 it performs optimizations, the optimizing transformations may invalidate some
8918 of the debugging data.  You therefore need to anticipate certain
8919 anomalous situations that may arise while debugging optimized code.
8920 These are the most common cases:
8921
8922 @enumerate
8923 @item
8924 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
8925 commands show
8926 the PC bouncing back and forth in the code.  This may result from any of
8927 the following optimizations:
8928
8929 @itemize @bullet
8930 @item
8931 @i{Common subexpression elimination:} using a single instance of code for a
8932 quantity that the source computes several times.  As a result you
8933 may not be able to stop on what looks like a statement.
8934
8935 @item
8936 @i{Invariant code motion:} moving an expression that does not change within a
8937 loop, to the beginning of the loop.
8938
8939 @item
8940 @i{Instruction scheduling:} moving instructions so as to
8941 overlap loads and stores (typically) with other code, or in
8942 general to move computations of values closer to their uses. Often
8943 this causes you to pass an assignment statement without the assignment
8944 happening and then later bounce back to the statement when the
8945 value is actually needed.  Placing a breakpoint on a line of code
8946 and then stepping over it may, therefore, not always cause all the
8947 expected side-effects.
8948 @end itemize
8949
8950 @item
8951 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
8952 two identical pieces of code are merged and the program counter suddenly
8953 jumps to a statement that is not supposed to be executed, simply because
8954 it (and the code following) translates to the same thing as the code
8955 that @emph{was} supposed to be executed.  This effect is typically seen in
8956 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
8957 a @code{break} in a C @code{^switch^switch^} statement.
8958
8959 @item
8960 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
8961 There are various reasons for this effect:
8962
8963 @itemize @bullet
8964 @item
8965 In a subprogram prologue, a parameter may not yet have been moved to its
8966 ``home''.
8967
8968 @item
8969 A variable may be dead, and its register re-used.  This is
8970 probably the most common cause.
8971
8972 @item
8973 As mentioned above, the assignment of a value to a variable may
8974 have been moved.
8975
8976 @item
8977 A variable may be eliminated entirely by value propagation or
8978 other means.  In this case, GCC may incorrectly generate debugging
8979 information for the variable
8980 @end itemize
8981
8982 @noindent
8983 In general, when an unexpected value appears for a local variable or parameter
8984 you should first ascertain if that value was actually computed by
8985 your program, as opposed to being incorrectly reported by the debugger.
8986 Record fields or
8987 array elements in an object designated by an access value
8988 are generally less of a problem, once you have ascertained that the access
8989 value is sensible.
8990 Typically, this means checking variables in the preceding code and in the
8991 calling subprogram to verify that the value observed is explainable from other
8992 values (one must apply the procedure recursively to those
8993 other values); or re-running the code and stopping a little earlier
8994 (perhaps before the call) and stepping to better see how the variable obtained
8995 the value in question; or continuing to step @emph{from} the point of the
8996 strange value to see if code motion had simply moved the variable's
8997 assignments later.
8998 @end enumerate
8999
9000 @noindent
9001 In light of such anomalies, a recommended technique is to use @option{-O0}
9002 early in the software development cycle, when extensive debugging capabilities
9003 are most needed, and then move to @option{-O1} and later @option{-O2} as
9004 the debugger becomes less critical.
9005 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9006 a release management issue.
9007 @ifclear vms
9008 Note that if you use @option{-g} you can then use the @command{strip} program
9009 on the resulting executable,
9010 which removes both debugging information and global symbols.
9011 @end ifclear
9012
9013
9014 @node Inlining of Subprograms
9015 @subsection Inlining of Subprograms
9016
9017 @noindent
9018 A call to a subprogram in the current unit is inlined if all the
9019 following conditions are met:
9020
9021 @itemize @bullet
9022 @item
9023 The optimization level is at least @option{-O1}.
9024
9025 @item
9026 The called subprogram is suitable for inlining: It must be small enough
9027 and not contain nested subprograms or anything else that @code{gcc}
9028 cannot support in inlined subprograms.
9029
9030 @item
9031 The call occurs after the definition of the body of the subprogram.
9032
9033 @item
9034 @cindex pragma Inline
9035 @findex Inline
9036 Either @code{pragma Inline} applies to the subprogram or it is
9037 small and automatic inlining (optimization level @option{-O3}) is
9038 specified.
9039 @end itemize
9040
9041 @noindent
9042 Calls to subprograms in @code{with}'ed units are normally not inlined.
9043 To achieve this level of inlining, the following conditions must all be
9044 true:
9045
9046 @itemize @bullet
9047 @item
9048 The optimization level is at least @option{-O1}.
9049
9050 @item
9051 The called subprogram is suitable for inlining: It must be small enough
9052 and not contain nested subprograms or anything else @code{gcc} cannot
9053 support in inlined subprograms.
9054
9055 @item
9056 The call appears in a body (not in a package spec).
9057
9058 @item
9059 There is a @code{pragma Inline} for the subprogram.
9060
9061 @item
9062 @cindex @option{-gnatn} (@code{gcc})
9063 The @option{^-gnatn^/INLINE^} switch
9064 is used in the @code{gcc} command line
9065 @end itemize
9066
9067 Note that specifying the @option{-gnatn} switch causes additional
9068 compilation dependencies. Consider the following:
9069
9070 @smallexample @c ada
9071 @cartouche
9072 package R is
9073    procedure Q;
9074    pragma Inline (Q);
9075 end R;
9076 package body R is
9077    ...
9078 end R;
9079
9080 with R;
9081 procedure Main is
9082 begin
9083    ...
9084    R.Q;
9085 end Main;
9086 @end cartouche
9087 @end smallexample
9088
9089 @noindent
9090 With the default behavior (no @option{-gnatn} switch specified), the
9091 compilation of the @code{Main} procedure depends only on its own source,
9092 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9093 means that editing the body of @code{R} does not require recompiling
9094 @code{Main}.
9095
9096 On the other hand, the call @code{R.Q} is not inlined under these
9097 circumstances. If the @option{-gnatn} switch is present when @code{Main}
9098 is compiled, the call will be inlined if the body of @code{Q} is small
9099 enough, but now @code{Main} depends on the body of @code{R} in
9100 @file{r.adb} as well as on the spec. This means that if this body is edited,
9101 the main program must be recompiled. Note that this extra dependency
9102 occurs whether or not the call is in fact inlined by @code{gcc}.
9103
9104 The use of front end inlining with @option{-gnatN} generates similar
9105 additional dependencies.
9106
9107 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@code{gcc})
9108 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9109 can be used to prevent
9110 all inlining. This switch overrides all other conditions and ensures
9111 that no inlining occurs. The extra dependences resulting from
9112 @option{-gnatn} will still be active, even if
9113 this switch is used to suppress the resulting inlining actions.
9114
9115 Note regarding the use of @option{-O3}: There is no difference in inlining
9116 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
9117 pragma @code{Inline} assuming the use of @option{-gnatn}
9118 or @option{-gnatN} (the switches that activate inlining). If you have used
9119 pragma @code{Inline} in appropriate cases, then it is usually much better
9120 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
9121 in this case only has the effect of inlining subprograms you did not
9122 think should be inlined. We often find that the use of @option{-O3} slows
9123 down code by performing excessive inlining, leading to increased instruction
9124 cache pressure from the increased code size. So the bottom line here is
9125 that you should not automatically assume that @option{-O3} is better than
9126 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
9127 it actually improves performance.
9128
9129 @node Optimization and Strict Aliasing
9130 @subsection Optimization and Strict Aliasing
9131 @cindex Aliasing
9132 @cindex Strict Aliasing
9133 @cindex No_Strict_Aliasing
9134
9135 @noindent
9136 The strong typing capabilities of Ada allow an optimizer to generate
9137 efficient code in situations where other languages would be forced to
9138 make worst case assumptions preventing such optimizations. Consider
9139 the following example:
9140
9141 @smallexample @c ada
9142 @cartouche
9143 procedure R is
9144    type Int1 is new Integer;
9145    type Int2 is new Integer;
9146    type Int1A is access Int1;
9147    type Int2A is access Int2;
9148    Int1V : Int1A;
9149    Int2V : Int2A;
9150    ...
9151
9152 begin
9153    ...
9154    for J in Data'Range loop
9155       if Data (J) = Int1V.all then
9156          Int2V.all := Int2V.all + 1;
9157       end if;
9158    end loop;
9159    ...
9160 end R;
9161 @end cartouche
9162 @end smallexample
9163
9164 @noindent
9165 In this example, since the variable @code{Int1V} can only access objects
9166 of type @code{Int1}, and @code{Int2V} can only access objects of type
9167 @code{Int2}, there is no possibility that the assignment to
9168 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
9169 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
9170 for all iterations of the loop and avoid the extra memory reference
9171 required to dereference it each time through the loop.
9172
9173 This kind of optimziation, called strict aliasing analysis, is
9174 triggered by specifying an optimization level of @option{-O2} or
9175 higher and allows @code{GNAT} to generate more efficient code
9176 when access values are involved.
9177
9178 However, although this optimization is always correct in terms of
9179 the formal semantics of the Ada Reference Manual, difficulties can
9180 arise if features like @code{Unchecked_Conversion} are used to break
9181 the typing system. Consider the following complete program example:
9182
9183 @smallexample @c ada
9184 @cartouche
9185 package p1 is
9186    type int1 is new integer;
9187    type int2 is new integer;
9188    type a1 is access int1;
9189    type a2 is access int2;
9190 end p1;
9191
9192 with p1; use p1;
9193 package p2 is
9194    function to_a2 (Input : a1) return a2;
9195 end p2;
9196
9197 with Unchecked_Conversion;
9198 package body p2 is
9199    function to_a2 (Input : a1) return a2 is
9200       function to_a2u is
9201         new Unchecked_Conversion (a1, a2);
9202    begin
9203       return to_a2u (Input);
9204    end to_a2;
9205 end p2;
9206
9207 with p2; use p2;
9208 with p1; use p1;
9209 with Text_IO; use Text_IO;
9210 procedure m is
9211    v1 : a1 := new int1;
9212    v2 : a2 := to_a2 (v1);
9213 begin
9214    v1.all := 1;
9215    v2.all := 0;
9216    put_line (int1'image (v1.all));
9217 end;
9218 @end cartouche
9219 @end smallexample
9220
9221 @noindent
9222 This program prints out 0 in @code{-O0} or @code{-O1}
9223 mode, but it prints out 1 in @code{-O2} mode. That's
9224 because in strict aliasing mode, the compiler can and
9225 does assume that the assignment to @code{v2.all} could not
9226 affect the value of @code{v1.all}, since different types
9227 are involved.
9228
9229 This behavior is not a case of non-conformance with the standard, since
9230 the Ada RM specifies that an unchecked conversion where the resulting
9231 bit pattern is not a correct value of the target type can result in an
9232 abnormal value and attempting to reference an abnormal value makes the
9233 execution of a program erroneous.  That's the case here since the result
9234 does not point to an object of type @code{int2}.  This means that the
9235 effect is entirely unpredictable.
9236
9237 However, although that explanation may satisfy a language
9238 lawyer, in practice an applications programmer expects an
9239 unchecked conversion involving pointers to create true
9240 aliases and the behavior of printing 1 seems plain wrong.
9241 In this case, the strict aliasing optimization is unwelcome.
9242
9243 Indeed the compiler recognizes this possibility, and the
9244 unchecked conversion generates a warning:
9245
9246 @smallexample
9247 p2.adb:5:07: warning: possible aliasing problem with type "a2"
9248 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
9249 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
9250 @end smallexample
9251
9252 @noindent
9253 Unfortunately the problem is recognized when compiling the body of
9254 package @code{p2}, but the actual "bad" code is generated while
9255 compiling the body of @code{m} and this latter compilation does not see
9256 the suspicious @code{Unchecked_Conversion}.
9257
9258 As implied by the warning message, there are approaches you can use to
9259 avoid the unwanted strict aliasing optimization in a case like this.
9260
9261 One possibility is to simply avoid the use of @code{-O2}, but
9262 that is a bit drastic, since it throws away a number of useful
9263 optimizations that do not involve strict aliasing assumptions.
9264
9265 A less drastic approach is to compile the program using the
9266 option @code{-fno-strict-aliasing}. Actually it is only the
9267 unit containing the dereferencing of the suspicious pointer
9268 that needs to be compiled. So in this case, if we compile
9269 unit @code{m} with this switch, then we get the expected
9270 value of zero printed. Analyzing which units might need
9271 the switch can be painful, so a more reasonable approach
9272 is to compile the entire program with options @code{-O2}
9273 and @code{-fno-strict-aliasing}. If the performance is
9274 satisfactory with this combination of options, then the
9275 advantage is that the entire issue of possible "wrong"
9276 optimization due to strict aliasing is avoided.
9277
9278 To avoid the use of compiler switches, the configuration
9279 pragma @code{No_Strict_Aliasing} with no parameters may be
9280 used to specify that for all access types, the strict
9281 aliasing optimization should be suppressed.
9282
9283 However, these approaches are still overkill, in that they causes
9284 all manipulations of all access values to be deoptimized. A more
9285 refined approach is to concentrate attention on the specific
9286 access type identified as problematic.
9287
9288 First, if a careful analysis of uses of the pointer shows
9289 that there are no possible problematic references, then
9290 the warning can be suppressed by bracketing the
9291 instantiation of @code{Unchecked_Conversion} to turn
9292 the warning off:
9293
9294 @smallexample @c ada
9295    pragma Warnings (Off);
9296    function to_a2u is
9297      new Unchecked_Conversion (a1, a2);
9298    pragma Warnings (On);
9299 @end smallexample
9300
9301 @noindent
9302 Of course that approach is not appropriate for this particular
9303 example, since indeed there is a problematic reference. In this
9304 case we can take one of two other approaches.
9305
9306 The first possibility is to move the instantiation of unchecked
9307 conversion to the unit in which the type is declared. In
9308 this example, we would move the instantiation of
9309 @code{Unchecked_Conversion} from the body of package
9310 @code{p2} to the spec of package @code{p1}. Now the
9311 warning disappears. That's because any use of the
9312 access type knows there is a suspicious unchecked
9313 conversion, and the strict aliasing optimization
9314 is automatically suppressed for the type.
9315
9316 If it is not practical to move the unchecked conversion to the same unit
9317 in which the destination access type is declared (perhaps because the
9318 source type is not visible in that unit), you may use pragma
9319 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
9320 same declarative sequence as the declaration of the access type:
9321
9322 @smallexample @c ada
9323    type a2 is access int2;
9324    pragma No_Strict_Aliasing (a2);
9325 @end smallexample
9326
9327 @noindent
9328 Here again, the compiler now knows that the strict aliasing optimization
9329 should be suppressed for any reference to type @code{a2} and the
9330 expected behavior is obtained.
9331
9332 Finally, note that although the compiler can generate warnings for
9333 simple cases of unchecked conversions, there are tricker and more
9334 indirect ways of creating type incorrect aliases which the compiler
9335 cannot detect. Examples are the use of address overlays and unchecked
9336 conversions involving composite types containing access types as
9337 components. In such cases, no warnings are generated, but there can
9338 still be aliasing problems. One safe coding practice is to forbid the
9339 use of address clauses for type overlaying, and to allow unchecked
9340 conversion only for primitive types. This is not really a significant
9341 restriction since any possible desired effect can be achieved by
9342 unchecked conversion of access values.
9343
9344 @ifset vms
9345 @node Coverage Analysis
9346 @subsection Coverage Analysis
9347
9348 @noindent
9349 GNAT supports the Digital Performance Coverage Analyzer (PCA), which allows
9350 the user to determine the distribution of execution time across a program,
9351 @pxref{Profiling} for details of usage.
9352 @end ifset
9353
9354 @node Reducing the Size of Ada Executables with gnatelim
9355 @section Reducing the Size of Ada Executables with @code{gnatelim}
9356 @findex gnatelim
9357
9358 @noindent
9359 This section describes @command{gnatelim}, a tool which detects unused
9360 subprograms and helps the compiler to create a smaller executable for your
9361 program.
9362
9363 @menu
9364 * About gnatelim::
9365 * Running gnatelim::
9366 * Correcting the List of Eliminate Pragmas::
9367 * Making Your Executables Smaller::
9368 * Summary of the gnatelim Usage Cycle::
9369 @end menu
9370
9371 @node About gnatelim
9372 @subsection About @code{gnatelim}
9373
9374 @noindent
9375 When a program shares a set of Ada
9376 packages with other programs, it may happen that this program uses
9377 only a fraction of the subprograms defined in these packages. The code
9378 created for these unused subprograms increases the size of the executable.
9379
9380 @code{gnatelim} tracks unused subprograms in an Ada program and
9381 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
9382 subprograms that are declared but never called. By placing the list of
9383 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
9384 recompiling your program, you may decrease the size of its executable,
9385 because the compiler will not generate the code for 'eliminated' subprograms.
9386 See GNAT Reference Manual for more information about this pragma.
9387
9388 @code{gnatelim} needs as its input data the name of the main subprogram
9389 and a bind file for a main subprogram.
9390
9391 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
9392 the main subprogram. @code{gnatelim} can work with both Ada and C
9393 bind files; when both are present, it uses the Ada bind file.
9394 The following commands will build the program and create the bind file:
9395
9396 @smallexample
9397 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
9398 $ gnatbind main_prog
9399 @end smallexample
9400
9401 Note that @code{gnatelim} needs neither object nor ALI files.
9402
9403 @node Running gnatelim
9404 @subsection Running @code{gnatelim}
9405
9406 @noindent
9407 @code{gnatelim} has the following command-line interface:
9408
9409 @smallexample
9410 $ gnatelim [options] name
9411 @end smallexample
9412
9413 @noindent
9414 @code{name} should be a name of a source file that contains the main subprogram
9415 of a program (partition).
9416
9417 @code{gnatelim} has the following switches:
9418
9419 @table @option
9420 @c !sort!
9421 @item ^-q^/QUIET^
9422 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
9423 Quiet mode: by default @code{gnatelim} outputs to the standard error
9424 stream the number of program units left to be processed. This option turns
9425 this trace off.
9426
9427 @item ^-v^/VERBOSE^
9428 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
9429 Verbose mode: @code{gnatelim} version information is printed as Ada
9430 comments to the standard output stream. Also, in addition to the number of
9431 program units left @code{gnatelim} will output the name of the current unit
9432 being processed.
9433
9434 @item ^-a^/ALL^
9435 @cindex @option{^-a^/ALL^} (@command{gnatelim})
9436 Also look for subprograms from the GNAT run time that can be eliminated. Note
9437 that when @file{gnat.adc} is produced using this switch, the entire program
9438 must be recompiled with switch @option{^-a^/ALL_FILES^} to @code{gnatmake}.
9439
9440 @item ^-I^/INCLUDE_DIRS=^@var{dir}
9441 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
9442 When looking for source files also look in directory @var{dir}. Specifying
9443 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
9444 sources in the current directory.
9445
9446 @item ^-b^/BIND_FILE=^@var{bind_file}
9447 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
9448 Specifies @var{bind_file} as the bind file to process. If not set, the name
9449 of the bind file is computed from the full expanded Ada name
9450 of a main subprogram.
9451
9452 @item ^-C^/CONFIG_FILE=^@var{config_file}
9453 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
9454 Specifies a file @var{config_file} that contains configuration pragmas. The
9455 file must be specified with full path.
9456
9457 @item ^--GCC^/COMPILER^=@var{compiler_name}
9458 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
9459 Instructs @code{gnatelim} to use specific @code{gcc} compiler instead of one
9460 available on the path.
9461
9462 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
9463 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
9464 Instructs @code{gnatelim} to use specific @code{gnatmake} instead of one
9465 available on the path.
9466
9467 @item -d@var{x}
9468 @cindex @option{-d@var{x}} (@command{gnatelim})
9469 Activate internal debugging switches. @var{x} is a letter or digit, or
9470 string of letters or digits, which specifies the type of debugging
9471 mode desired.  Normally these are used only for internal development
9472 or system debugging purposes. You can find full documentation for these
9473 switches in the spec of the @code{Gnatelim} unit in the compiler
9474 source file @file{gnatelim.ads}.
9475 @end table
9476
9477 @noindent
9478 @code{gnatelim} sends its output to the standard output stream, and all the
9479 tracing and debug information is sent to the standard error stream.
9480 In order to produce a proper GNAT configuration file
9481 @file{gnat.adc}, redirection must be used:
9482
9483 @smallexample
9484 @ifset vms
9485 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
9486 @end ifset
9487 @ifclear vms
9488 $ gnatelim main_prog.adb > gnat.adc
9489 @end ifclear
9490 @end smallexample
9491
9492 @ifclear vms
9493 @noindent
9494 or
9495
9496 @smallexample
9497 $ gnatelim main_prog.adb >> gnat.adc
9498 @end smallexample
9499
9500 @noindent
9501 in order to append the @code{gnatelim} output to the existing contents of
9502 @file{gnat.adc}.
9503 @end ifclear
9504
9505 @node Correcting the List of Eliminate Pragmas
9506 @subsection Correcting the List of Eliminate Pragmas
9507
9508 @noindent
9509 In some rare cases @code{gnatelim} may try to eliminate
9510 subprograms that are actually called in the program. In this case, the
9511 compiler will generate an error message of the form:
9512
9513 @smallexample
9514 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
9515 @end smallexample
9516
9517 @noindent
9518 You will need to manually remove the wrong @code{Eliminate} pragmas from
9519 the @file{gnat.adc} file. You should recompile your program
9520 from scratch after that, because you need a consistent @file{gnat.adc} file
9521 during the entire compilation.
9522
9523
9524 @node Making Your Executables Smaller
9525 @subsection Making Your Executables Smaller
9526
9527 @noindent
9528 In order to get a smaller executable for your program you now have to
9529 recompile the program completely with the new @file{gnat.adc} file
9530 created by @code{gnatelim} in your current directory:
9531
9532 @smallexample
9533 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9534 @end smallexample
9535
9536 @noindent
9537 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
9538 recompile everything
9539 with the set of pragmas @code{Eliminate} that you have obtained with
9540 @command{gnatelim}).
9541
9542 Be aware that the set of @code{Eliminate} pragmas is specific to each
9543 program. It is not recommended to merge sets of @code{Eliminate}
9544 pragmas created for different programs in one @file{gnat.adc} file.
9545
9546 @node Summary of the gnatelim Usage Cycle
9547 @subsection Summary of the gnatelim Usage Cycle
9548
9549 @noindent
9550 Here is a quick summary of the steps to be taken in order to reduce
9551 the size of your executables with @code{gnatelim}. You may use
9552 other GNAT options to control the optimization level,
9553 to produce the debugging information, to set search path, etc.
9554
9555 @enumerate
9556 @item
9557 Produce a bind file
9558
9559 @smallexample
9560 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
9561 $ gnatbind main_prog
9562 @end smallexample
9563
9564 @item
9565 Generate a list of @code{Eliminate} pragmas
9566 @smallexample
9567 @ifset vms
9568 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
9569 @end ifset
9570 @ifclear vms
9571 $ gnatelim main_prog >[>] gnat.adc
9572 @end ifclear
9573 @end smallexample
9574
9575 @item
9576 Recompile the application
9577
9578 @smallexample
9579 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9580 @end smallexample
9581
9582 @end enumerate
9583
9584
9585
9586
9587 @c ********************************
9588 @node Renaming Files Using gnatchop
9589 @chapter Renaming Files Using @code{gnatchop}
9590 @findex gnatchop
9591
9592 @noindent
9593 This chapter discusses how to handle files with multiple units by using
9594 the @code{gnatchop} utility. This utility is also useful in renaming
9595 files to meet the standard GNAT default file naming conventions.
9596
9597 @menu
9598 * Handling Files with Multiple Units::
9599 * Operating gnatchop in Compilation Mode::
9600 * Command Line for gnatchop::
9601 * Switches for gnatchop::
9602 * Examples of gnatchop Usage::
9603 @end menu
9604
9605 @node Handling Files with Multiple Units
9606 @section Handling Files with Multiple Units
9607
9608 @noindent
9609 The basic compilation model of GNAT requires that a file submitted to the
9610 compiler have only one unit and there be a strict correspondence
9611 between the file name and the unit name.
9612
9613 The @code{gnatchop} utility allows both of these rules to be relaxed,
9614 allowing GNAT to process files which contain multiple compilation units
9615 and files with arbitrary file names. @code{gnatchop}
9616 reads the specified file and generates one or more output files,
9617 containing one unit per file. The unit and the file name correspond,
9618 as required by GNAT.
9619
9620 If you want to permanently restructure a set of ``foreign'' files so that
9621 they match the GNAT rules, and do the remaining development using the
9622 GNAT structure, you can simply use @command{gnatchop} once, generate the
9623 new set of files and work with them from that point on.
9624
9625 Alternatively, if you want to keep your files in the ``foreign'' format,
9626 perhaps to maintain compatibility with some other Ada compilation
9627 system, you can set up a procedure where you use @command{gnatchop} each
9628 time you compile, regarding the source files that it writes as temporary
9629 files that you throw away.
9630
9631
9632 @node Operating gnatchop in Compilation Mode
9633 @section Operating gnatchop in Compilation Mode
9634
9635 @noindent
9636 The basic function of @code{gnatchop} is to take a file with multiple units
9637 and split it into separate files. The boundary between files is reasonably
9638 clear, except for the issue of comments and pragmas. In default mode, the
9639 rule is that any pragmas between units belong to the previous unit, except
9640 that configuration pragmas always belong to the following unit. Any comments
9641 belong to the following unit. These rules
9642 almost always result in the right choice of
9643 the split point without needing to mark it explicitly and most users will
9644 find this default to be what they want. In this default mode it is incorrect to
9645 submit a file containing only configuration pragmas, or one that ends in
9646 configuration pragmas, to @code{gnatchop}.
9647
9648 However, using a special option to activate ``compilation mode'',
9649 @code{gnatchop}
9650 can perform another function, which is to provide exactly the semantics
9651 required by the RM for handling of configuration pragmas in a compilation.
9652 In the absence of configuration pragmas (at the main file level), this
9653 option has no effect, but it causes such configuration pragmas to be handled
9654 in a quite different manner.
9655
9656 First, in compilation mode, if @code{gnatchop} is given a file that consists of
9657 only configuration pragmas, then this file is appended to the
9658 @file{gnat.adc} file in the current directory. This behavior provides
9659 the required behavior described in the RM for the actions to be taken
9660 on submitting such a file to the compiler, namely that these pragmas
9661 should apply to all subsequent compilations in the same compilation
9662 environment. Using GNAT, the current directory, possibly containing a
9663 @file{gnat.adc} file is the representation
9664 of a compilation environment. For more information on the
9665 @file{gnat.adc} file, see the section on handling of configuration
9666 pragmas @pxref{Handling of Configuration Pragmas}.
9667
9668 Second, in compilation mode, if @code{gnatchop}
9669 is given a file that starts with
9670 configuration pragmas, and contains one or more units, then these
9671 configuration pragmas are prepended to each of the chopped files. This
9672 behavior provides the required behavior described in the RM for the
9673 actions to be taken on compiling such a file, namely that the pragmas
9674 apply to all units in the compilation, but not to subsequently compiled
9675 units.
9676
9677 Finally, if configuration pragmas appear between units, they are appended
9678 to the previous unit. This results in the previous unit being illegal,
9679 since the compiler does not accept configuration pragmas that follow
9680 a unit. This provides the required RM behavior that forbids configuration
9681 pragmas other than those preceding the first compilation unit of a
9682 compilation.
9683
9684 For most purposes, @code{gnatchop} will be used in default mode. The
9685 compilation mode described above is used only if you need exactly
9686 accurate behavior with respect to compilations, and you have files
9687 that contain multiple units and configuration pragmas. In this
9688 circumstance the use of @code{gnatchop} with the compilation mode
9689 switch provides the required behavior, and is for example the mode
9690 in which GNAT processes the ACVC tests.
9691
9692 @node Command Line for gnatchop
9693 @section Command Line for @code{gnatchop}
9694
9695 @noindent
9696 The @code{gnatchop} command has the form:
9697
9698 @smallexample
9699 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
9700       [@var{directory}]
9701 @end smallexample
9702
9703 @noindent
9704 The only required argument is the file name of the file to be chopped.
9705 There are no restrictions on the form of this file name. The file itself
9706 contains one or more Ada units, in normal GNAT format, concatenated
9707 together. As shown, more than one file may be presented to be chopped.
9708
9709 When run in default mode, @code{gnatchop} generates one output file in
9710 the current directory for each unit in each of the files.
9711
9712 @var{directory}, if specified, gives the name of the directory to which
9713 the output files will be written. If it is not specified, all files are
9714 written to the current directory.
9715
9716 For example, given a
9717 file called @file{hellofiles} containing
9718
9719 @smallexample @c ada
9720 @group
9721 @cartouche
9722 procedure hello;
9723
9724 with Text_IO; use Text_IO;
9725 procedure hello is
9726 begin
9727    Put_Line ("Hello");
9728 end hello;
9729 @end cartouche
9730 @end group
9731 @end smallexample
9732
9733 @noindent
9734 the command
9735
9736 @smallexample
9737 $ gnatchop ^hellofiles^HELLOFILES.^
9738 @end smallexample
9739
9740 @noindent
9741 generates two files in the current directory, one called
9742 @file{hello.ads} containing the single line that is the procedure spec,
9743 and the other called @file{hello.adb} containing the remaining text. The
9744 original file is not affected. The generated files can be compiled in
9745 the normal manner.
9746
9747 @noindent
9748 When gnatchop is invoked on a file that is empty or that contains only empty
9749 lines and/or comments, gnatchop will not fail, but will not produce any
9750 new sources.
9751
9752 For example, given a
9753 file called @file{toto.txt} containing
9754
9755 @smallexample @c ada
9756 @group
9757 @cartouche
9758 --  Just a comment
9759 @end cartouche
9760 @end group
9761 @end smallexample
9762
9763 @noindent
9764 the command
9765
9766 @smallexample
9767 $ gnatchop ^toto.txt^TOT.TXT^
9768 @end smallexample
9769
9770 @noindent
9771 will not produce any new file and will result in the following warnings:
9772
9773 @smallexample
9774 toto.txt:1:01: warning: empty file, contains no compilation units
9775 no compilation units found
9776 no source files written
9777 @end smallexample
9778
9779 @node Switches for gnatchop
9780 @section Switches for @code{gnatchop}
9781
9782 @noindent
9783 @command{gnatchop} recognizes the following switches:
9784
9785 @table @option
9786 @c !sort!
9787
9788 @item ^-c^/COMPILATION^
9789 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
9790 Causes @code{gnatchop} to operate in compilation mode, in which
9791 configuration pragmas are handled according to strict RM rules. See
9792 previous section for a full description of this mode.
9793
9794 @ifclear vms
9795 @item -gnatxxx
9796 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
9797 used to parse the given file. Not all @code{xxx} options make sense,
9798 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
9799 process a source file that uses Latin-2 coding for identifiers.
9800 @end ifclear
9801
9802 @item ^-h^/HELP^
9803 Causes @code{gnatchop} to generate a brief help summary to the standard
9804 output file showing usage information.
9805
9806 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
9807 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
9808 Limit generated file names to the specified number @code{mm}
9809 of characters.
9810 This is useful if the
9811 resulting set of files is required to be interoperable with systems
9812 which limit the length of file names.
9813 @ifset vms
9814 If no value is given, or
9815 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
9816 a default of 39, suitable for OpenVMS Alpha
9817 Systems, is assumed
9818 @end ifset
9819 @ifclear vms
9820 No space is allowed between the @option{-k} and the numeric value. The numeric
9821 value may be omitted in which case a default of @option{-k8},
9822 suitable for use
9823 with DOS-like file systems, is used. If no @option{-k} switch
9824 is present then
9825 there is no limit on the length of file names.
9826 @end ifclear
9827
9828 @item ^-p^/PRESERVE^
9829 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
9830 Causes the file ^modification^creation^ time stamp of the input file to be
9831 preserved and used for the time stamp of the output file(s). This may be
9832 useful for preserving coherency of time stamps in an environment where
9833 @code{gnatchop} is used as part of a standard build process.
9834
9835 @item ^-q^/QUIET^
9836 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
9837 Causes output of informational messages indicating the set of generated
9838 files to be suppressed. Warnings and error messages are unaffected.
9839
9840 @item ^-r^/REFERENCE^
9841 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
9842 @findex Source_Reference
9843 Generate @code{Source_Reference} pragmas. Use this switch if the output
9844 files are regarded as temporary and development is to be done in terms
9845 of the original unchopped file. This switch causes
9846 @code{Source_Reference} pragmas to be inserted into each of the
9847 generated files to refers back to the original file name and line number.
9848 The result is that all error messages refer back to the original
9849 unchopped file.
9850 In addition, the debugging information placed into the object file (when
9851 the @option{^-g^/DEBUG^} switch of @code{gcc} or @code{gnatmake} is specified)
9852 also refers back to this original file so that tools like profilers and
9853 debuggers will give information in terms of the original unchopped file.
9854
9855 If the original file to be chopped itself contains
9856 a @code{Source_Reference}
9857 pragma referencing a third file, then gnatchop respects
9858 this pragma, and the generated @code{Source_Reference} pragmas
9859 in the chopped file refer to the original file, with appropriate
9860 line numbers. This is particularly useful when @code{gnatchop}
9861 is used in conjunction with @code{gnatprep} to compile files that
9862 contain preprocessing statements and multiple units.
9863
9864 @item ^-v^/VERBOSE^
9865 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
9866 Causes @code{gnatchop} to operate in verbose mode. The version
9867 number and copyright notice are output, as well as exact copies of
9868 the gnat1 commands spawned to obtain the chop control information.
9869
9870 @item ^-w^/OVERWRITE^
9871 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
9872 Overwrite existing file names. Normally @code{gnatchop} regards it as a
9873 fatal error if there is already a file with the same name as a
9874 file it would otherwise output, in other words if the files to be
9875 chopped contain duplicated units. This switch bypasses this
9876 check, and causes all but the last instance of such duplicated
9877 units to be skipped.
9878
9879 @ifclear vms
9880 @item --GCC=xxxx
9881 @cindex @option{--GCC=} (@code{gnatchop})
9882 Specify the path of the GNAT parser to be used. When this switch is used,
9883 no attempt is made to add the prefix to the GNAT parser executable.
9884 @end ifclear
9885 @end table
9886
9887 @node Examples of gnatchop Usage
9888 @section Examples of @code{gnatchop} Usage
9889
9890 @table @code
9891 @ifset vms
9892 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
9893 @end ifset
9894 @ifclear vms
9895 @item gnatchop -w hello_s.ada prerelease/files
9896 @end ifclear
9897
9898 Chops the source file @file{hello_s.ada}. The output files will be
9899 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
9900 overwriting any
9901 files with matching names in that directory (no files in the current
9902 directory are modified).
9903
9904 @item gnatchop ^archive^ARCHIVE.^
9905 Chops the source file @file{^archive^ARCHIVE.^}
9906 into the current directory. One
9907 useful application of @code{gnatchop} is in sending sets of sources
9908 around, for example in email messages. The required sources are simply
9909 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
9910 command), and then
9911 @code{gnatchop} is used at the other end to reconstitute the original
9912 file names.
9913
9914 @item gnatchop file1 file2 file3 direc
9915 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
9916 the resulting files in the directory @file{direc}. Note that if any units
9917 occur more than once anywhere within this set of files, an error message
9918 is generated, and no files are written. To override this check, use the
9919 @option{^-w^/OVERWRITE^} switch,
9920 in which case the last occurrence in the last file will
9921 be the one that is output, and earlier duplicate occurrences for a given
9922 unit will be skipped.
9923 @end table
9924
9925 @node Configuration Pragmas
9926 @chapter Configuration Pragmas
9927 @cindex Configuration pragmas
9928 @cindex Pragmas, configuration
9929
9930 @noindent
9931 In Ada 95, configuration pragmas include those pragmas described as
9932 such in the Ada 95 Reference Manual, as well as
9933 implementation-dependent pragmas that are configuration pragmas. See the
9934 individual descriptions of pragmas in the GNAT Reference Manual for
9935 details on these additional GNAT-specific configuration pragmas. Most
9936 notably, the pragma @code{Source_File_Name}, which allows
9937 specifying non-default names for source files, is a configuration
9938 pragma. The following is a complete list of configuration pragmas
9939 recognized by @code{GNAT}:
9940
9941 @smallexample
9942    Ada_83
9943    Ada_95
9944    C_Pass_By_Copy
9945    Component_Alignment
9946    Discard_Names
9947    Elaboration_Checks
9948    Eliminate
9949    Extend_System
9950    Extensions_Allowed
9951    External_Name_Casing
9952    Float_Representation
9953    Initialize_Scalars
9954    License
9955    Locking_Policy
9956    Long_Float
9957    Normalize_Scalars
9958    Polling
9959    Propagate_Exceptions
9960    Queuing_Policy
9961    Ravenscar
9962    Restricted_Run_Time
9963    Restrictions
9964    Reviewable
9965    Source_File_Name
9966    Style_Checks
9967    Suppress
9968    Task_Dispatching_Policy
9969    Universal_Data
9970    Unsuppress
9971    Use_VADS_Size
9972    Warnings
9973    Validity_Checks
9974 @end smallexample
9975
9976 @menu
9977 * Handling of Configuration Pragmas::
9978 * The Configuration Pragmas Files::
9979 @end menu
9980
9981 @node Handling of Configuration Pragmas
9982 @section Handling of Configuration Pragmas
9983
9984 Configuration pragmas may either appear at the start of a compilation
9985 unit, in which case they apply only to that unit, or they may apply to
9986 all compilations performed in a given compilation environment.
9987
9988 GNAT also provides the @code{gnatchop} utility to provide an automatic
9989 way to handle configuration pragmas following the semantics for
9990 compilations (that is, files with multiple units), described in the RM.
9991 See section @pxref{Operating gnatchop in Compilation Mode} for details.
9992 However, for most purposes, it will be more convenient to edit the
9993 @file{gnat.adc} file that contains configuration pragmas directly,
9994 as described in the following section.
9995
9996 @node The Configuration Pragmas Files
9997 @section The Configuration Pragmas Files
9998 @cindex @file{gnat.adc}
9999
10000 @noindent
10001 In GNAT a compilation environment is defined by the current
10002 directory at the time that a compile command is given. This current
10003 directory is searched for a file whose name is @file{gnat.adc}. If
10004 this file is present, it is expected to contain one or more
10005 configuration pragmas that will be applied to the current compilation.
10006 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
10007 considered.
10008
10009 Configuration pragmas may be entered into the @file{gnat.adc} file
10010 either by running @code{gnatchop} on a source file that consists only of
10011 configuration pragmas, or more conveniently  by
10012 direct editing of the @file{gnat.adc} file, which is a standard format
10013 source file.
10014
10015 In addition to @file{gnat.adc}, one additional file containing configuration
10016 pragmas may be applied to the current compilation using the switch
10017 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
10018 contains only configuration pragmas. These configuration pragmas are
10019 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
10020 is present and switch @option{-gnatA} is not used).
10021
10022 It is allowed to specify several switches @option{-gnatec}, however only
10023 the last one on the command line will be taken into account.
10024
10025 If you are using project file, a separate mechanism is provided using
10026 project attributes, see @ref{Specifying Configuration Pragmas} for more
10027 details.
10028
10029 @ifset vms
10030 Of special interest to GNAT OpenVMS Alpha is the following
10031 configuration pragma:
10032
10033 @smallexample @c ada
10034 @cartouche
10035 pragma Extend_System (Aux_DEC);
10036 @end cartouche
10037 @end smallexample
10038
10039 @noindent
10040 In the presence of this pragma, GNAT adds to the definition of the
10041 predefined package SYSTEM all the additional types and subprograms that are
10042 defined in DEC Ada. See @pxref{Compatibility with DEC Ada} for details.
10043 @end ifset
10044
10045 @node Handling Arbitrary File Naming Conventions Using gnatname
10046 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
10047 @cindex Arbitrary File Naming Conventions
10048
10049 @menu
10050 * Arbitrary File Naming Conventions::
10051 * Running gnatname::
10052 * Switches for gnatname::
10053 * Examples of gnatname Usage::
10054 @end menu
10055
10056 @node Arbitrary File Naming Conventions
10057 @section Arbitrary File Naming Conventions
10058
10059 @noindent
10060 The GNAT compiler must be able to know the source file name of a compilation
10061 unit.  When using the standard GNAT default file naming conventions
10062 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
10063 does not need additional information.
10064
10065 @noindent
10066 When the source file names do not follow the standard GNAT default file naming
10067 conventions, the GNAT compiler must be given additional information through
10068 a configuration pragmas file (see @ref{Configuration Pragmas})
10069 or a project file.
10070 When the non standard file naming conventions are well-defined,
10071 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
10072 (see @ref{Alternative File Naming Schemes}) may be sufficient. However,
10073 if the file naming conventions are irregular or arbitrary, a number
10074 of pragma @code{Source_File_Name} for individual compilation units
10075 must be defined.
10076 To help maintain the correspondence between compilation unit names and
10077 source file names within the compiler,
10078 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
10079 set of files.
10080
10081 @node Running gnatname
10082 @section Running @code{gnatname}
10083
10084 @noindent
10085 The usual form of the @code{gnatname} command is
10086
10087 @smallexample
10088 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
10089 @end smallexample
10090
10091 @noindent
10092 All of the arguments are optional. If invoked without any argument,
10093 @code{gnatname} will display its usage.
10094
10095 @noindent
10096 When used with at least one naming pattern, @code{gnatname} will attempt to
10097 find all the compilation units in files that follow at least one of the
10098 naming patterns. To find these compilation units,
10099 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
10100 regular files.
10101
10102 @noindent
10103 One or several Naming Patterns may be given as arguments to @code{gnatname}.
10104 Each Naming Pattern is enclosed between double quotes.
10105 A Naming Pattern is a regular expression similar to the wildcard patterns
10106 used in file names by the Unix shells or the DOS prompt.
10107
10108 @noindent
10109 Examples of Naming Patterns are
10110
10111 @smallexample
10112    "*.[12].ada"
10113    "*.ad[sb]*"
10114    "body_*"    "spec_*"
10115 @end smallexample
10116
10117 @noindent
10118 For a more complete description of the syntax of Naming Patterns,
10119 see the second kind of regular expressions described in @file{g-regexp.ads}
10120 (the ``Glob'' regular expressions).
10121
10122 @noindent
10123 When invoked with no switches, @code{gnatname} will create a configuration
10124 pragmas file @file{gnat.adc} in the current working directory, with pragmas
10125 @code{Source_File_Name} for each file that contains a valid Ada unit.
10126
10127 @node Switches for gnatname
10128 @section Switches for @code{gnatname}
10129
10130 @noindent
10131 Switches for @code{gnatname} must precede any specified Naming Pattern.
10132
10133 @noindent
10134 You may specify any of the following switches to @code{gnatname}:
10135
10136 @table @option
10137 @c !sort!
10138
10139 @item ^-c^/CONFIG_FILE=^@file{file}
10140 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
10141 Create a configuration pragmas file @file{file} (instead of the default
10142 @file{gnat.adc}).
10143 @ifclear vms
10144 There may be zero, one or more space between @option{-c} and
10145 @file{file}.
10146 @end ifclear
10147 @file{file} may include directory information. @file{file} must be
10148 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
10149 When a switch @option{^-c^/CONFIG_FILE^} is
10150 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
10151
10152 @item ^-d^/SOURCE_DIRS=^@file{dir}
10153 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
10154 Look for source files in directory @file{dir}. There may be zero, one or more
10155 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
10156 When a switch @option{^-d^/SOURCE_DIRS^}
10157 is specified, the current working directory will not be searched for source
10158 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
10159 or @option{^-D^/DIR_FILES^} switch.
10160 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
10161 If @file{dir} is a relative path, it is relative to the directory of
10162 the configuration pragmas file specified with switch
10163 @option{^-c^/CONFIG_FILE^},
10164 or to the directory of the project file specified with switch
10165 @option{^-P^/PROJECT_FILE^} or,
10166 if neither switch @option{^-c^/CONFIG_FILE^}
10167 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
10168 current working directory. The directory
10169 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
10170
10171 @item ^-D^/DIRS_FILE=^@file{file}
10172 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
10173 Look for source files in all directories listed in text file @file{file}.
10174 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
10175 and @file{file}.
10176 @file{file} must be an existing, readable text file.
10177 Each non empty line in @file{file} must be a directory.
10178 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
10179 switches @option{^-d^/SOURCE_DIRS^} as there are non empty lines in
10180 @file{file}.
10181
10182 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
10183 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
10184 Foreign patterns. Using this switch, it is possible to add sources of languages
10185 other than Ada to the list of sources of a project file.
10186 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
10187 For example,
10188 @smallexample
10189 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
10190 @end smallexample
10191 @noindent
10192 will look for Ada units in all files with the @file{.ada} extension,
10193 and will add to the list of file for project @file{prj.gpr} the C files
10194 with extension ".^c^C^".
10195
10196 @item ^-h^/HELP^
10197 @cindex @option{^-h^/HELP^} (@code{gnatname})
10198 Output usage (help) information. The output is written to @file{stdout}.
10199
10200 @item ^-P^/PROJECT_FILE=^@file{proj}
10201 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
10202 Create or update project file @file{proj}. There may be zero, one or more space
10203 between @option{-P} and @file{proj}. @file{proj} may include directory
10204 information. @file{proj} must be writable.
10205 There may be only one switch @option{^-P^/PROJECT_FILE^}.
10206 When a switch @option{^-P^/PROJECT_FILE^} is specified,
10207 no switch @option{^-c^/CONFIG_FILE^} may be specified.
10208
10209 @item ^-v^/VERBOSE^
10210 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
10211 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
10212 This includes name of the file written, the name of the directories to search
10213 and, for each file in those directories whose name matches at least one of
10214 the Naming Patterns, an indication of whether the file contains a unit,
10215 and if so the name of the unit.
10216
10217 @item ^-v -v^/VERBOSE /VERBOSE^
10218 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
10219 Very Verbose mode. In addition to the output produced in verbose mode,
10220 for each file in the searched directories whose name matches none of
10221 the Naming Patterns, an indication is given that there is no match.
10222
10223 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
10224 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
10225 Excluded patterns. Using this switch, it is possible to exclude some files
10226 that would match the name patterns. For example,
10227 @smallexample
10228 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
10229 @end smallexample
10230 @noindent
10231 will look for Ada units in all files with the @file{.ada} extension,
10232 except those whose names end with @file{_nt.ada}.
10233
10234 @end table
10235
10236 @node Examples of gnatname Usage
10237 @section Examples of @code{gnatname} Usage
10238
10239 @ifset vms
10240 @smallexample
10241 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
10242 @end smallexample
10243 @end ifset
10244
10245 @ifclear vms
10246 @smallexample
10247 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
10248 @end smallexample
10249 @end ifclear
10250
10251 @noindent
10252 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
10253 and be writable. In addition, the directory
10254 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
10255 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
10256
10257 @ifclear vms
10258 Note the optional spaces after @option{-c} and @option{-d}.
10259 @end ifclear
10260
10261 @smallexample
10262 @ifclear vms
10263 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
10264   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
10265 @end ifclear
10266 @ifset vms
10267 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
10268   /EXCLUDED_PATTERN=*_nt_body.ada
10269   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
10270   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
10271 @end ifset
10272 @end smallexample
10273
10274 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
10275 even in conjunction with one or several switches
10276 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
10277 are used in this example.
10278
10279
10280 @c *****************************************
10281 @c * G N A T  P r o j e c t  M a n a g e r *
10282 @c *****************************************
10283 @node GNAT Project Manager
10284 @chapter GNAT Project Manager
10285
10286 @menu
10287 * Introduction::
10288 * Examples of Project Files::
10289 * Project File Syntax::
10290 * Objects and Sources in Project Files::
10291 * Importing Projects::
10292 * Project Extension::
10293 * External References in Project Files::
10294 * Packages in Project Files::
10295 * Variables from Imported Projects::
10296 * Naming Schemes::
10297 * Library Projects::
10298 * Using Third-Party Libraries through Projects::
10299 * Stand-alone Library Projects::
10300 * Switches Related to Project Files::
10301 * Tools Supporting Project Files::
10302 * An Extended Example::
10303 * Project File Complete Syntax::
10304 @end menu
10305
10306 @c ****************
10307 @c * Introduction *
10308 @c ****************
10309
10310 @node Introduction
10311 @section Introduction
10312
10313 @noindent
10314 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
10315 you to manage complex builds involving a number of source files, directories,
10316 and compilation options for different system configurations. In particular,
10317 project files allow you to specify:
10318 @itemize @bullet
10319 @item
10320 The directory or set of directories containing the source files, and/or the
10321 names of the specific source files themselves
10322 @item
10323 The directory in which the compiler's output
10324 (@file{ALI} files, object files, tree files) is to be placed
10325 @item
10326 The directory in which the executable programs is to be placed
10327 @item
10328 ^Switch^Switch^ settings for any of the project-enabled tools
10329 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
10330 @code{gnatfind}); you can apply these settings either globally or to individual
10331 compilation units.
10332 @item
10333 The source files containing the main subprogram(s) to be built
10334 @item
10335 The source programming language(s) (currently Ada and/or C)
10336 @item
10337 Source file naming conventions; you can specify these either globally or for
10338 individual compilation units
10339 @end itemize
10340
10341 @menu
10342 * Project Files::
10343 @end menu
10344
10345 @node Project Files
10346 @subsection Project Files
10347
10348 @noindent
10349 Project files are written in a syntax close to that of Ada, using  familiar
10350 notions such as packages, context clauses, declarations, default values,
10351 assignments, and inheritance. Finally, project files can be built
10352 hierarchically from other project files, simplifying complex system
10353 integration and project reuse.
10354
10355 A @dfn{project} is a specific set of values for various compilation properties.
10356 The settings for a given project are described by means of
10357 a @dfn{project file}, which is a text file written in an Ada-like syntax.
10358 Property values in project files are either strings or lists of strings.
10359 Properties that are not explicitly set receive default values.  A project
10360 file may interrogate the values of @dfn{external variables} (user-defined
10361 command-line switches or environment variables), and it may specify property
10362 settings conditionally, based on the value of such variables.
10363
10364 In simple cases, a project's source files depend only on other source files
10365 in the same project, or on the predefined libraries.  (@emph{Dependence} is
10366 used in
10367 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
10368 the Project Manager also allows more sophisticated arrangements,
10369 where the source files in one project depend on source files in other
10370 projects:
10371 @itemize @bullet
10372 @item
10373 One project can @emph{import} other projects containing needed source files.
10374 @item
10375 You can organize GNAT projects in a hierarchy: a @emph{child} project
10376 can extend a @emph{parent} project, inheriting the parent's source files and
10377 optionally overriding any of them with alternative versions
10378 @end itemize
10379
10380 @noindent
10381 More generally, the Project Manager lets you structure large development
10382 efforts into hierarchical subsystems, where build decisions are delegated
10383 to the subsystem level, and thus different compilation environments
10384 (^switch^switch^ settings) used for different subsystems.
10385
10386 The Project Manager is invoked through the
10387 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
10388 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
10389 @ifclear vms
10390 There may be zero, one or more spaces between @option{-P} and
10391 @option{@emph{projectfile}}.
10392 @end ifclear
10393 If you want to define (on the command line) an external variable that is
10394 queried by the project file, you must use the
10395 @option{^-X^/EXTERNAT_REFERENCE=^@emph{vbl}=@emph{value}} switch.
10396 The Project Manager parses and interprets the project file, and drives the
10397 invoked tool based on the project settings.
10398
10399 The Project Manager supports a wide range of development strategies,
10400 for systems of all sizes.  Here are some typical practices that are
10401 easily handled:
10402 @itemize @bullet
10403 @item
10404 Using a common set of source files, but generating object files in different
10405 directories via different ^switch^switch^ settings
10406 @item
10407 Using a mostly-shared set of source files, but with different versions of
10408 some unit or units
10409 @end itemize
10410
10411 @noindent
10412 The destination of an executable can be controlled inside a project file
10413 using the @option{^-o^-o^}
10414 ^switch^switch^.
10415 In the absence of such a ^switch^switch^ either inside
10416 the project file or on the command line, any executable files generated by
10417 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
10418 in the project file. If no @code{Exec_Dir} is specified, they will be placed
10419 in the object directory of the project.
10420
10421 You can use project files to achieve some of the effects of a source
10422 versioning system (for example, defining separate projects for
10423 the different sets of sources that comprise different releases) but the
10424 Project Manager is independent of any source configuration management tools
10425 that might be used by the developers.
10426
10427 The next section introduces the main features of GNAT's project facility
10428 through a sequence of examples; subsequent sections will present the syntax
10429 and semantics in more detail. A more formal description of the project
10430 facility appears in the GNAT Reference Manual.
10431
10432 @c *****************************
10433 @c * Examples of Project Files *
10434 @c *****************************
10435
10436 @node Examples of Project Files
10437 @section Examples of Project Files
10438 @noindent
10439 This section illustrates some of the typical uses of project files and
10440 explains their basic structure and behavior.
10441
10442 @menu
10443 * Common Sources with Different ^Switches^Switches^ and Directories::
10444 * Using External Variables::
10445 * Importing Other Projects::
10446 * Extending a Project::
10447 @end menu
10448
10449 @node Common Sources with Different ^Switches^Switches^ and Directories
10450 @subsection Common Sources with Different ^Switches^Switches^ and Directories
10451
10452 @menu
10453 * Source Files::
10454 * Specifying the Object Directory::
10455 * Specifying the Exec Directory::
10456 * Project File Packages::
10457 * Specifying ^Switch^Switch^ Settings::
10458 * Main Subprograms::
10459 * Executable File Names::
10460 * Source File Naming Conventions::
10461 * Source Language(s)::
10462 @end menu
10463
10464 @noindent
10465 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
10466 @file{proc.adb} are in the @file{/common} directory.  The file
10467 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
10468 package @code{Pack}.  We want to compile these source files under two sets
10469 of ^switches^switches^:
10470 @itemize @bullet
10471 @item
10472 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
10473 and the @option{^-gnata^-gnata^},
10474 @option{^-gnato^-gnato^},
10475 and @option{^-gnatE^-gnatE^} switches to the
10476 compiler; the compiler's output is to appear in @file{/common/debug}
10477 @item
10478 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
10479 to the compiler; the compiler's output is to appear in @file{/common/release}
10480 @end itemize
10481
10482 @noindent
10483 The GNAT project files shown below, respectively @file{debug.gpr} and
10484 @file{release.gpr} in the @file{/common} directory, achieve these effects.
10485
10486 Schematically:
10487 @smallexample
10488 @group
10489 ^/common^[COMMON]^
10490   debug.gpr
10491   release.gpr
10492   pack.ads
10493   pack.adb
10494   proc.adb
10495 @end group
10496 @group
10497 ^/common/debug^[COMMON.DEBUG]^
10498   proc.ali, proc.o
10499   pack.ali, pack.o
10500 @end group
10501 @group
10502 ^/common/release^[COMMON.RELEASE]^
10503   proc.ali, proc.o
10504   pack.ali, pack.o
10505 @end group
10506 @end smallexample
10507 Here are the corresponding project files:
10508
10509 @smallexample @c projectfile
10510 @group
10511 project Debug is
10512   for Object_Dir use "debug";
10513   for Main use ("proc");
10514
10515   package Builder is
10516     for ^Default_Switches^Default_Switches^ ("Ada")
10517         use ("^-g^-g^");
10518     for Executable ("proc.adb") use "proc1";
10519   end Builder;
10520 @end group
10521
10522 @group
10523   package Compiler is
10524     for ^Default_Switches^Default_Switches^ ("Ada")
10525        use ("-fstack-check",
10526             "^-gnata^-gnata^",
10527             "^-gnato^-gnato^",
10528             "^-gnatE^-gnatE^");
10529   end Compiler;
10530 end Debug;
10531 @end group
10532 @end smallexample
10533
10534 @smallexample @c projectfile
10535 @group
10536 project Release is
10537   for Object_Dir use "release";
10538   for Exec_Dir use ".";
10539   for Main use ("proc");
10540
10541   package Compiler is
10542     for ^Default_Switches^Default_Switches^ ("Ada")
10543         use ("^-O2^-O2^");
10544   end Compiler;
10545 end Release;
10546 @end group
10547 @end smallexample
10548
10549 @noindent
10550 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
10551 insensitive), and analogously the project defined by @file{release.gpr} is
10552 @code{"Release"}.  For consistency the file should have the same name as the
10553 project, and the project file's extension should be @code{"gpr"}. These
10554 conventions are not required, but a warning is issued if they are not followed.
10555
10556 If the current directory is @file{^/temp^[TEMP]^}, then the command
10557 @smallexample
10558 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
10559 @end smallexample
10560
10561 @noindent
10562 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
10563 as well as the @code{^proc1^PROC1.EXE^} executable,
10564 using the ^switch^switch^ settings defined in the project file.
10565
10566 Likewise, the command
10567 @smallexample
10568 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
10569 @end smallexample
10570
10571 @noindent
10572 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
10573 and the @code{^proc^PROC.EXE^}
10574 executable in @file{^/common^[COMMON]^},
10575 using the ^switch^switch^ settings from the project file.
10576
10577 @node Source Files
10578 @unnumberedsubsubsec Source Files
10579
10580 @noindent
10581 If a project file does not explicitly specify a set of source directories or
10582 a set of source files, then by default the project's source files are the
10583 Ada source files in the project file directory.  Thus @file{pack.ads},
10584 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
10585
10586 @node Specifying the Object Directory
10587 @unnumberedsubsubsec Specifying the Object Directory
10588
10589 @noindent
10590 Several project properties are modeled by Ada-style @emph{attributes};
10591 a property is defined by supplying the equivalent of an Ada attribute
10592 definition clause in the project file.
10593 A project's object directory is another such a property; the corresponding
10594 attribute is @code{Object_Dir}, and its value is also a string expression,
10595 specified either as absolute or relative. In the later case,
10596 it is relative to the project file directory. Thus the compiler's
10597 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
10598 (for the @code{Debug} project)
10599 and to @file{^/common/release^[COMMON.RELEASE]^}
10600 (for the @code{Release} project).
10601 If @code{Object_Dir} is not specified, then the default is the project file
10602 directory itself.
10603
10604 @node Specifying the Exec Directory
10605 @unnumberedsubsubsec Specifying the Exec Directory
10606
10607 @noindent
10608 A project's exec directory is another property; the corresponding
10609 attribute is @code{Exec_Dir}, and its value is also a string expression,
10610 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
10611 then the default is the object directory (which may also be the project file
10612 directory if attribute @code{Object_Dir} is not specified). Thus the executable
10613 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
10614 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
10615 and in @file{^/common^[COMMON]^} for the @code{Release} project.
10616
10617 @node Project File Packages
10618 @unnumberedsubsubsec Project File Packages
10619
10620 @noindent
10621 A GNAT tool that is integrated with the Project Manager is modeled by a
10622 corresponding package in the project file. In the example above,
10623 The @code{Debug} project defines the packages @code{Builder}
10624 (for @command{gnatmake}) and @code{Compiler};
10625 the @code{Release} project defines only the @code{Compiler} package.
10626
10627 The Ada-like package syntax is not to be taken literally.  Although packages in
10628 project files bear a surface resemblance to packages in Ada source code, the
10629 notation is simply a way to convey a grouping of properties for a named
10630 entity.  Indeed, the package names permitted in project files are restricted
10631 to a predefined set, corresponding to the project-aware tools, and the contents
10632 of packages are limited to a small set of constructs.
10633 The packages in the example above contain attribute definitions.
10634
10635 @node Specifying ^Switch^Switch^ Settings
10636 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
10637
10638 @noindent
10639 ^Switch^Switch^ settings for a project-aware tool can be specified through
10640 attributes in the package that corresponds to the tool.
10641 The example above illustrates one of the relevant attributes,
10642 @code{^Default_Switches^Default_Switches^}, which is defined in packages
10643 in both project files.
10644 Unlike simple attributes like @code{Source_Dirs},
10645 @code{^Default_Switches^Default_Switches^} is
10646 known as an @emph{associative array}.  When you define this attribute, you must
10647 supply an ``index'' (a literal string), and the effect of the attribute
10648 definition is to set the value of the array at the specified index.
10649 For the @code{^Default_Switches^Default_Switches^} attribute,
10650 the index is a programming language (in our case, Ada),
10651 and the value specified (after @code{use}) must be a list
10652 of string expressions.
10653
10654 The attributes permitted in project files are restricted to a predefined set.
10655 Some may appear at project level, others in packages.
10656 For any attribute that is an associative array, the index must always be a
10657 literal string, but the restrictions on this string (e.g., a file name or a
10658 language name) depend on the individual attribute.
10659 Also depending on the attribute, its specified value will need to be either a
10660 string or a string list.
10661
10662 In the @code{Debug} project, we set the switches for two tools,
10663 @command{gnatmake} and the compiler, and thus we include the two corresponding
10664 packages; each package defines the @code{^Default_Switches^Default_Switches^}
10665 attribute with index @code{"Ada"}.
10666 Note that the package corresponding to
10667 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
10668 similar, but only includes the @code{Compiler} package.
10669
10670 In project @code{Debug} above, the ^switches^switches^ starting with
10671 @option{-gnat} that are specified in package @code{Compiler}
10672 could have been placed in package @code{Builder}, since @command{gnatmake}
10673 transmits all such ^switches^switches^ to the compiler.
10674
10675 @node Main Subprograms
10676 @unnumberedsubsubsec Main Subprograms
10677
10678 @noindent
10679 One of the specifiable properties of a project is a list of files that contain
10680 main subprograms.  This property is captured in the @code{Main} attribute,
10681 whose value is a list of strings.  If a project defines the @code{Main}
10682 attribute, it is not necessary to identify the main subprogram(s) when
10683 invoking @command{gnatmake} (see @ref{gnatmake and Project Files}).
10684
10685 @node Executable File Names
10686 @unnumberedsubsubsec Executable File Names
10687
10688 @noindent
10689 By default, the executable file name corresponding to a main source is
10690 deducted from the main source file name. Through the attributes
10691 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
10692 it is possible to change this default.
10693 In project @code{Debug} above, the executable file name
10694 for main source @file{^proc.adb^PROC.ADB^} is
10695 @file{^proc1^PROC1.EXE^}.
10696 Attribute @code{Executable_Suffix}, when specified, may change the suffix
10697 of the the executable files, when no attribute @code{Executable} applies:
10698 its value replace the platform-specific executable suffix.
10699 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
10700 specify a non default executable file name when several mains are built at once
10701 in a single @command{gnatmake} command.
10702
10703 @node Source File Naming Conventions
10704 @unnumberedsubsubsec Source File Naming Conventions
10705
10706 @noindent
10707 Since the project files above do not specify any source file naming
10708 conventions, the GNAT defaults are used.  The mechanism for defining source
10709 file naming conventions -- a package named @code{Naming} --
10710 is described below (@pxref{Naming Schemes}).
10711
10712 @node Source Language(s)
10713 @unnumberedsubsubsec Source Language(s)
10714
10715 @noindent
10716 Since the project files do not specify a @code{Languages} attribute, by
10717 default the GNAT tools assume that the language of the project file is Ada.
10718 More generally, a project can comprise source files
10719 in Ada, C, and/or other languages.
10720
10721 @node Using External Variables
10722 @subsection Using External Variables
10723
10724 @noindent
10725 Instead of supplying different project files for debug and release, we can
10726 define a single project file that queries an external variable (set either
10727 on the command line or via an ^environment variable^logical name^) in order to
10728 conditionally define the appropriate settings.  Again, assume that the
10729 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
10730 located in directory @file{^/common^[COMMON]^}.  The following project file,
10731 @file{build.gpr}, queries the external variable named @code{STYLE} and
10732 defines an object directory and ^switch^switch^ settings based on whether
10733 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
10734 the default is @code{"deb"}.
10735
10736 @smallexample @c projectfile
10737 @group
10738 project Build is
10739   for Main use ("proc");
10740
10741   type Style_Type is ("deb", "rel");
10742   Style : Style_Type := external ("STYLE", "deb");
10743
10744   case Style is
10745     when "deb" =>
10746       for Object_Dir use "debug";
10747
10748     when "rel" =>
10749       for Object_Dir use "release";
10750       for Exec_Dir use ".";
10751   end case;
10752 @end group
10753
10754 @group
10755   package Builder is
10756
10757     case Style is
10758       when "deb" =>
10759         for ^Default_Switches^Default_Switches^ ("Ada")
10760             use ("^-g^-g^");
10761         for Executable ("proc") use "proc1";
10762     end case;
10763
10764   end Builder;
10765 @end group
10766
10767 @group
10768   package Compiler is
10769
10770     case Style is
10771       when "deb" =>
10772         for ^Default_Switches^Default_Switches^ ("Ada")
10773             use ("^-gnata^-gnata^",
10774                  "^-gnato^-gnato^",
10775                  "^-gnatE^-gnatE^");
10776
10777       when "rel" =>
10778         for ^Default_Switches^Default_Switches^ ("Ada")
10779             use ("^-O2^-O2^");
10780     end case;
10781
10782   end Compiler;
10783
10784 end Build;
10785 @end group
10786 @end smallexample
10787
10788 @noindent
10789 @code{Style_Type} is an example of a @emph{string type}, which is the project
10790 file analog of an Ada enumeration type but whose components are string literals
10791 rather than identifiers.  @code{Style} is declared as a variable of this type.
10792
10793 The form @code{external("STYLE", "deb")} is known as an
10794 @emph{external reference}; its first argument is the name of an
10795 @emph{external variable}, and the second argument is a default value to be
10796 used if the external variable doesn't exist.  You can define an external
10797 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
10798 or you can use ^an environment variable^a logical name^
10799 as an external variable.
10800
10801 Each @code{case} construct is expanded by the Project Manager based on the
10802 value of @code{Style}. Thus the command
10803 @ifclear vms
10804 @smallexample
10805 gnatmake -P/common/build.gpr -XSTYLE=deb
10806 @end smallexample
10807 @end ifclear
10808
10809 @ifset vms
10810 @smallexample
10811 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
10812 @end smallexample
10813 @end ifset
10814
10815 @noindent
10816 is equivalent to the @command{gnatmake} invocation using the project file
10817 @file{debug.gpr} in the earlier example.  So is the command
10818 @smallexample
10819 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
10820 @end smallexample
10821
10822 @noindent
10823 since @code{"deb"} is the default for @code{STYLE}.
10824
10825 Analogously,
10826
10827 @ifclear vms
10828 @smallexample
10829 gnatmake -P/common/build.gpr -XSTYLE=rel
10830 @end smallexample
10831 @end ifclear
10832
10833 @ifset vms
10834 @smallexample
10835 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
10836 @end smallexample
10837 @end ifset
10838
10839 @noindent
10840 is equivalent to the @command{gnatmake} invocation using the project file
10841 @file{release.gpr} in the earlier example.
10842
10843 @node Importing Other Projects
10844 @subsection Importing Other Projects
10845
10846 @noindent
10847 A compilation unit in a source file in one project may depend on compilation
10848 units in source files in other projects.  To compile this unit under
10849 control of a project file, the
10850 dependent project must @emph{import} the projects containing the needed source
10851 files.
10852 This effect is obtained using syntax similar to an Ada @code{with} clause,
10853 but where @code{with}ed entities are strings that denote project files.
10854
10855 As an example, suppose that the two projects @code{GUI_Proj} and
10856 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
10857 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
10858 and @file{^/comm^[COMM]^}, respectively.
10859 Suppose that the source files for @code{GUI_Proj} are
10860 @file{gui.ads} and @file{gui.adb}, and that the source files for
10861 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
10862 files is located in its respective project file directory.  Schematically:
10863
10864 @smallexample
10865 @group
10866 ^/gui^[GUI]^
10867   gui_proj.gpr
10868   gui.ads
10869   gui.adb
10870 @end group
10871
10872 @group
10873 ^/comm^[COMM]^
10874   comm_proj.gpr
10875   comm.ads
10876   comm.adb
10877 @end group
10878 @end smallexample
10879
10880 @noindent
10881 We want to develop an application in directory @file{^/app^[APP]^} that
10882 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
10883 the corresponding project files (e.g. the ^switch^switch^ settings
10884 and object directory).
10885 Skeletal code for a main procedure might be something like the following:
10886
10887 @smallexample @c ada
10888 @group
10889 with GUI, Comm;
10890 procedure App_Main is
10891    ...
10892 begin
10893    ...
10894 end App_Main;
10895 @end group
10896 @end smallexample
10897
10898 @noindent
10899 Here is a project file, @file{app_proj.gpr}, that achieves the desired
10900 effect:
10901
10902 @smallexample @c projectfile
10903 @group
10904 with "/gui/gui_proj", "/comm/comm_proj";
10905 project App_Proj is
10906    for Main use ("app_main");
10907 end App_Proj;
10908 @end group
10909 @end smallexample
10910
10911 @noindent
10912 Building an executable is achieved through the command:
10913 @smallexample
10914 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
10915 @end smallexample
10916 @noindent
10917 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
10918 in the directory where @file{app_proj.gpr} resides.
10919
10920 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
10921 (as illustrated above) the @code{with} clause can omit the extension.
10922
10923 Our example specified an absolute path for each imported project file.
10924 Alternatively, the directory name of an imported object can be omitted
10925 if either
10926 @itemize @bullet
10927 @item
10928 The imported project file is in the same directory as the importing project
10929 file, or
10930 @item
10931 You have defined ^an environment variable^a logical name^
10932 that includes the directory containing
10933 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
10934 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
10935 directory names separated by colons (semicolons on Windows).
10936 @end itemize
10937
10938 @noindent
10939 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
10940 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
10941 as follows:
10942
10943 @smallexample @c projectfile
10944 @group
10945 with "gui_proj", "comm_proj";
10946 project App_Proj is
10947    for Main use ("app_main");
10948 end App_Proj;
10949 @end group
10950 @end smallexample
10951
10952 @noindent
10953 Importing other projects can create ambiguities.
10954 For example, the same unit might be present in different imported projects, or
10955 it might be present in both the importing project and in an imported project.
10956 Both of these conditions are errors.  Note that in the current version of
10957 the Project Manager, it is illegal to have an ambiguous unit even if the
10958 unit is never referenced by the importing project.  This restriction may be
10959 relaxed in a future release.
10960
10961 @node Extending a Project
10962 @subsection Extending a Project
10963
10964 @noindent
10965 In large software systems it is common to have multiple
10966 implementations of a common interface; in Ada terms, multiple versions of a
10967 package body for the same specification.  For example, one implementation
10968 might be safe for use in tasking programs, while another might only be used
10969 in sequential applications.  This can be modeled in GNAT using the concept
10970 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
10971 another project (the ``parent'') then by default all source files of the
10972 parent project are inherited by the child, but the child project can
10973 override any of the parent's source files with new versions, and can also
10974 add new files.  This facility is the project analog of a type extension in
10975 Object-Oriented Programming.  Project hierarchies are permitted (a child
10976 project may be the parent of yet another project), and a project that
10977 inherits one project can also import other projects.
10978
10979 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
10980 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
10981 @file{pack.adb}, and @file{proc.adb}:
10982
10983 @smallexample
10984 @group
10985 ^/seq^[SEQ]^
10986   pack.ads
10987   pack.adb
10988   proc.adb
10989   seq_proj.gpr
10990 @end group
10991 @end smallexample
10992
10993 @noindent
10994 Note that the project file can simply be empty (that is, no attribute or
10995 package is defined):
10996
10997 @smallexample @c projectfile
10998 @group
10999 project Seq_Proj is
11000 end Seq_Proj;
11001 @end group
11002 @end smallexample
11003
11004 @noindent
11005 implying that its source files are all the Ada source files in the project
11006 directory.
11007
11008 Suppose we want to supply an alternate version of @file{pack.adb}, in
11009 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
11010 @file{pack.ads} and @file{proc.adb}.  We can define a project
11011 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
11012
11013 @smallexample
11014 @group
11015 ^/tasking^[TASKING]^
11016   pack.adb
11017   tasking_proj.gpr
11018 @end group
11019
11020 @group
11021 project Tasking_Proj extends "/seq/seq_proj" is
11022 end Tasking_Proj;
11023 @end group
11024 @end smallexample
11025
11026 @noindent
11027 The version of @file{pack.adb} used in a build depends on which project file
11028 is specified.
11029
11030 Note that we could have obtained the desired behavior using project import
11031 rather than project inheritance; a @code{base} project would contain the
11032 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
11033 import @code{base} and add @file{pack.adb}, and likewise a tasking project
11034 would import @code{base} and add a different version of @file{pack.adb}.  The
11035 choice depends on whether other sources in the original project need to be
11036 overridden.  If they do, then project extension is necessary, otherwise,
11037 importing is sufficient.
11038
11039 @noindent
11040 In a project file that extends another project file, it is possible to
11041 indicate that an inherited source is not part of the sources of the extending
11042 project. This is necessary sometimes when a package spec has been overloaded
11043 and no longer requires a body: in this case, it is necessary to indicate that
11044 the inherited body is not part of the sources of the project, otherwise there
11045 will be a compilation error when compiling the spec.
11046
11047 For that purpose, the attribute @code{Locally_Removed_Files} is used.
11048 Its value is a string list: a list of file names.
11049
11050 @smallexample @c @projectfile
11051 project B extends "a" is
11052    for Source_Files use ("pkg.ads");
11053    --  New spec of Pkg does not need a completion
11054    for Locally_Removed_Files use ("pkg.adb");
11055 end B;
11056 @end smallexample
11057
11058 Attribute @code{Locally_Removed_Files} may also be used to check if a source
11059 is still needed: if it is possible to build using @code{gnatmake} when such
11060 a source is put in attribute @code{Locally_Removed_Files} of a project P, then
11061 it is possible to remove the source completely from a system that includes
11062 project P.
11063
11064 @c ***********************
11065 @c * Project File Syntax *
11066 @c ***********************
11067
11068 @node Project File Syntax
11069 @section Project File Syntax
11070
11071 @menu
11072 * Basic Syntax::
11073 * Packages::
11074 * Expressions::
11075 * String Types::
11076 * Variables::
11077 * Attributes::
11078 * Associative Array Attributes::
11079 * case Constructions::
11080 @end menu
11081
11082 @noindent
11083 This section describes the structure of project files.
11084
11085 A project may be an @emph{independent project}, entirely defined by a single
11086 project file. Any Ada source file in an independent project depends only
11087 on the predefined library and other Ada source files in the same project.
11088
11089 @noindent
11090 A project may also @dfn{depend on} other projects, in either or both of
11091 the following ways:
11092 @itemize @bullet
11093 @item It may import any number of projects
11094 @item It may extend at most one other project
11095 @end itemize
11096
11097 @noindent
11098 The dependence relation is a directed acyclic graph (the subgraph reflecting
11099 the ``extends'' relation is a tree).
11100
11101 A project's @dfn{immediate sources} are the source files directly defined by
11102 that project, either implicitly by residing in the project file's directory,
11103 or explicitly through any of the source-related attributes described below.
11104 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
11105 of @var{proj} together with the immediate sources (unless overridden) of any
11106 project on which @var{proj} depends (either directly or indirectly).
11107
11108 @node Basic Syntax
11109 @subsection Basic Syntax
11110
11111 @noindent
11112 As seen in the earlier examples, project files have an Ada-like syntax.
11113 The minimal project file is:
11114 @smallexample @c projectfile
11115 @group
11116 project Empty is
11117
11118 end Empty;
11119 @end group
11120 @end smallexample
11121
11122 @noindent
11123 The identifier @code{Empty} is the name of the project.
11124 This project name must be present after the reserved
11125 word @code{end} at the end of the project file, followed by a semi-colon.
11126
11127 Any name in a project file, such as the project name or a variable name,
11128 has the same syntax as an Ada identifier.
11129
11130 The reserved words of project files are the Ada reserved words plus
11131 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
11132 reserved words currently used in project file syntax are:
11133
11134 @itemize @bullet
11135 @item
11136 @code{case}
11137 @item
11138 @code{end}
11139 @item
11140 @code{for}
11141 @item
11142 @code{is}
11143 @item
11144 @code{others}
11145 @item
11146 @code{package}
11147 @item
11148 @code{renames}
11149 @item
11150 @code{type}
11151 @item
11152 @code{use}
11153 @item
11154 @code{when}
11155 @item
11156 @code{with}
11157 @end itemize
11158
11159 @noindent
11160 Comments in project files have the same syntax as in Ada, two consecutives
11161 hyphens through the end of the line.
11162
11163 @node Packages
11164 @subsection Packages
11165
11166 @noindent
11167 A project file may contain @emph{packages}. The name of a package must be one
11168 of the identifiers from the following list. A package
11169 with a given name may only appear once in a project file. Package names are
11170 case insensitive. The following package names are legal:
11171
11172 @itemize @bullet
11173 @item
11174 @code{Naming}
11175 @item
11176 @code{Builder}
11177 @item
11178 @code{Compiler}
11179 @item
11180 @code{Binder}
11181 @item
11182 @code{Linker}
11183 @item
11184 @code{Finder}
11185 @item
11186 @code{Cross_Reference}
11187 @item
11188 @code{Eliminate}
11189 @item
11190 @code{gnatls}
11191 @item
11192 @code{gnatstub}
11193 @item
11194 @code{IDE}
11195 @end itemize
11196
11197 @noindent
11198 In its simplest form, a package may be empty:
11199
11200 @smallexample @c projectfile
11201 @group
11202 project Simple is
11203   package Builder is
11204   end Builder;
11205 end Simple;
11206 @end group
11207 @end smallexample
11208
11209 @noindent
11210 A package may contain @emph{attribute declarations},
11211 @emph{variable declarations} and @emph{case constructions}, as will be
11212 described below.
11213
11214 When there is ambiguity between a project name and a package name,
11215 the name always designates the project. To avoid possible confusion, it is
11216 always a good idea to avoid naming a project with one of the
11217 names allowed for packages or any name that starts with @code{gnat}.
11218
11219 @node Expressions
11220 @subsection Expressions
11221
11222 @noindent
11223 An @emph{expression} is either a @emph{string expression} or a
11224 @emph{string list expression}.
11225
11226 A @emph{string expression} is either a @emph{simple string expression} or a
11227 @emph{compound string expression}.
11228
11229 A @emph{simple string expression} is one of the following:
11230 @itemize @bullet
11231 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
11232 @item A string-valued variable reference (see @ref{Variables})
11233 @item A string-valued attribute reference (see @ref{Attributes})
11234 @item An external reference (see @ref{External References in Project Files})
11235 @end itemize
11236
11237 @noindent
11238 A @emph{compound string expression} is a concatenation of string expressions,
11239 using the operator @code{"&"}
11240 @smallexample
11241        Path & "/" & File_Name & ".ads"
11242 @end smallexample
11243
11244 @noindent
11245 A @emph{string list expression} is either a
11246 @emph{simple string list expression} or a
11247 @emph{compound string list expression}.
11248
11249 A @emph{simple string list expression} is one of the following:
11250 @itemize @bullet
11251 @item A parenthesized list of zero or more string expressions,
11252 separated by commas
11253 @smallexample
11254    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
11255    Empty_List := ();
11256 @end smallexample
11257 @item A string list-valued variable reference
11258 @item A string list-valued attribute reference
11259 @end itemize
11260
11261 @noindent
11262 A @emph{compound string list expression} is the concatenation (using
11263 @code{"&"}) of a simple string list expression and an expression.  Note that
11264 each term in a compound string list expression, except the first, may be
11265 either a string expression or a string list expression.
11266
11267 @smallexample @c projectfile
11268 @group
11269    File_Name_List := () & File_Name; --  One string in this list
11270    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
11271    --  Two strings
11272    Big_List := File_Name_List & Extended_File_Name_List;
11273    --  Concatenation of two string lists: three strings
11274    Illegal_List := "gnat.adc" & Extended_File_Name_List;
11275    --  Illegal: must start with a string list
11276 @end group
11277 @end smallexample
11278
11279 @node String Types
11280 @subsection String Types
11281
11282 @noindent
11283 A @emph{string type declaration} introduces a discrete set of string literals.
11284 If a string variable is declared to have this type, its value
11285 is restricted to the given set of literals.
11286
11287 Here is an example of a string type declaration:
11288
11289 @smallexample @c projectfile
11290    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
11291 @end smallexample
11292
11293 @noindent
11294 Variables of a string type are called @emph{typed variables}; all other
11295 variables are called @emph{untyped variables}. Typed variables are
11296 particularly useful in @code{case} constructions, to support conditional
11297 attribute declarations.
11298 (see @ref{case Constructions}).
11299
11300 The string literals in the list are case sensitive and must all be different.
11301 They may include any graphic characters allowed in Ada, including spaces.
11302
11303 A string type may only be declared at the project level, not inside a package.
11304
11305 A string type may be referenced by its name if it has been declared in the same
11306 project file, or by an expanded name whose prefix is the name of the project
11307 in which it is declared.
11308
11309 @node Variables
11310 @subsection Variables
11311
11312 @noindent
11313 A variable may be declared at the project file level, or within a package.
11314 Here are some examples of variable declarations:
11315
11316 @smallexample @c projectfile
11317 @group
11318    This_OS : OS := external ("OS"); --  a typed variable declaration
11319    That_OS := "GNU/Linux";          --  an untyped variable declaration
11320 @end group
11321 @end smallexample
11322
11323 @noindent
11324 The syntax of a @emph{typed variable declaration} is identical to the Ada
11325 syntax for an object declaration. By contrast, the syntax of an untyped
11326 variable declaration is identical to an Ada assignment statement. In fact,
11327 variable declarations in project files have some of the characteristics of
11328 an assignment, in that successive declarations for the same variable are
11329 allowed. Untyped variable declarations do establish the expected kind of the
11330 variable (string or string list), and successive declarations for it must
11331 respect the initial kind.
11332
11333 @noindent
11334 A string variable declaration (typed or untyped) declares a variable
11335 whose value is a string. This variable may be used as a string expression.
11336 @smallexample @c projectfile
11337    File_Name       := "readme.txt";
11338    Saved_File_Name := File_Name & ".saved";
11339 @end smallexample
11340
11341 @noindent
11342 A string list variable declaration declares a variable whose value is a list
11343 of strings. The list may contain any number (zero or more) of strings.
11344
11345 @smallexample @c projectfile
11346    Empty_List := ();
11347    List_With_One_Element := ("^-gnaty^-gnaty^");
11348    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
11349    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
11350                  "pack2.ada", "util_.ada", "util.ada");
11351 @end smallexample
11352
11353 @noindent
11354 The same typed variable may not be declared more than once at project level,
11355 and it may not be declared more than once in any package; it is in effect
11356 a constant.
11357
11358 The same untyped variable may be declared several times. Declarations are
11359 elaborated in the order in which they appear, so  the new value replaces
11360 the old one, and any subsequent reference to the variable uses the new value.
11361 However, as noted above, if a variable has been declared as a string, all
11362 subsequent
11363 declarations must give it a string value. Similarly, if a variable has
11364 been declared as a string list, all subsequent declarations
11365 must give it a string list value.
11366
11367 A @emph{variable reference} may take several forms:
11368
11369 @itemize @bullet
11370 @item The simple variable name, for a variable in the current package (if any)
11371 or in the current project
11372 @item An expanded name, whose prefix is a context name.
11373 @end itemize
11374
11375 @noindent
11376 A @emph{context} may be one of the following:
11377
11378 @itemize @bullet
11379 @item The name of an existing package in the current project
11380 @item The name of an imported project of the current project
11381 @item The name of an ancestor project (i.e., a project extended by the current
11382 project, either directly or indirectly)
11383 @item An expanded name whose prefix is an imported/parent project name, and
11384 whose selector is a package name in that project.
11385 @end itemize
11386
11387 @noindent
11388 A variable reference may be used in an expression.
11389
11390 @node Attributes
11391 @subsection Attributes
11392
11393 @noindent
11394 A project (and its packages) may have @emph{attributes} that define
11395 the project's properties.  Some attributes have values that are strings;
11396 others have values that are string lists.
11397
11398 There are two categories of attributes: @emph{simple attributes}
11399 and @emph{associative arrays} (see @ref{Associative Array Attributes}).
11400
11401 Legal project attribute names, and attribute names for each legal package are
11402 listed below. Attributes names are case-insensitive.
11403
11404 The following attributes are defined on projects (all are simple attributes):
11405
11406 @multitable @columnfractions .4 .3
11407 @item @emph{Attribute Name}
11408 @tab @emph{Value}
11409 @item @code{Source_Files}
11410 @tab string list
11411 @item @code{Source_Dirs}
11412 @tab string list
11413 @item @code{Source_List_File}
11414 @tab string
11415 @item @code{Object_Dir}
11416 @tab string
11417 @item @code{Exec_Dir}
11418 @tab string
11419 @item @code{Locally_Removed_Files}
11420 @tab string list
11421 @item @code{Main}
11422 @tab string list
11423 @item @code{Languages}
11424 @tab string list
11425 @item @code{Main_Language}
11426 @tab string
11427 @item @code{Library_Dir}
11428 @tab string
11429 @item @code{Library_Name}
11430 @tab string
11431 @item @code{Library_Kind}
11432 @tab string
11433 @item @code{Library_Version}
11434 @tab string
11435 @item @code{Library_Interface}
11436 @tab string
11437 @item @code{Library_Auto_Init}
11438 @tab string
11439 @item @code{Library_Options}
11440 @tab string list
11441 @item @code{Library_GCC}
11442 @tab string
11443 @end multitable
11444
11445 @noindent
11446 The following attributes are defined for package  @code{Naming}
11447 (see @ref{Naming Schemes}):
11448
11449 @multitable @columnfractions .4 .2 .2 .2
11450 @item Attribute Name @tab Category @tab Index @tab Value
11451 @item @code{Spec_Suffix}
11452 @tab associative array
11453 @tab language name
11454 @tab string
11455 @item @code{Body_Suffix}
11456 @tab associative array
11457 @tab language name
11458 @tab string
11459 @item @code{Separate_Suffix}
11460 @tab simple attribute
11461 @tab n/a
11462 @tab string
11463 @item @code{Casing}
11464 @tab simple attribute
11465 @tab n/a
11466 @tab string
11467 @item @code{Dot_Replacement}
11468 @tab simple attribute
11469 @tab n/a
11470 @tab string
11471 @item @code{Spec}
11472 @tab associative array
11473 @tab Ada unit name
11474 @tab string
11475 @item @code{Body}
11476 @tab associative array
11477 @tab Ada unit name
11478 @tab string
11479 @item @code{Specification_Exceptions}
11480 @tab associative array
11481 @tab language name
11482 @tab string list
11483 @item @code{Implementation_Exceptions}
11484 @tab associative array
11485 @tab language name
11486 @tab string list
11487 @end multitable
11488
11489 @noindent
11490 The following attributes are defined for packages @code{Builder},
11491 @code{Compiler}, @code{Binder},
11492 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
11493 (see @ref{^Switches^Switches^ and Project Files}).
11494
11495 @multitable @columnfractions .4 .2 .2 .2
11496 @item Attribute Name @tab Category @tab Index @tab Value
11497 @item @code{^Default_Switches^Default_Switches^}
11498 @tab associative array
11499 @tab language name
11500 @tab string list
11501 @item @code{^Switches^Switches^}
11502 @tab associative array
11503 @tab file name
11504 @tab string list
11505 @end multitable
11506
11507 @noindent
11508 In addition, package @code{Compiler} has a single string attribute
11509 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
11510 string attribute @code{Global_Configuration_Pragmas}.
11511
11512 @noindent
11513 Each simple attribute has a default value: the empty string (for string-valued
11514 attributes) and the empty list (for string list-valued attributes).
11515
11516 An attribute declaration defines a new value for an attribute.
11517
11518 Examples of simple attribute declarations:
11519
11520 @smallexample @c projectfile
11521    for Object_Dir use "objects";
11522    for Source_Dirs use ("units", "test/drivers");
11523 @end smallexample
11524
11525 @noindent
11526 The syntax of a @dfn{simple attribute declaration} is similar to that of an
11527 attribute definition clause in Ada.
11528
11529 Attributes references may be appear in expressions.
11530 The general form for such a reference is @code{<entity>'<attribute>}:
11531 Associative array attributes are functions. Associative
11532 array attribute references must have an argument that is a string literal.
11533
11534 Examples are:
11535
11536 @smallexample @c projectfile
11537   project'Object_Dir
11538   Naming'Dot_Replacement
11539   Imported_Project'Source_Dirs
11540   Imported_Project.Naming'Casing
11541   Builder'^Default_Switches^Default_Switches^("Ada")
11542 @end smallexample
11543
11544 @noindent
11545 The prefix of an attribute may be:
11546 @itemize @bullet
11547 @item @code{project} for an attribute of the current project
11548 @item The name of an existing package of the current project
11549 @item The name of an imported project
11550 @item The name of a parent project that is extended by the current project
11551 @item An expanded name whose prefix is imported/parent project name,
11552       and whose selector is a package name
11553 @end itemize
11554
11555 @noindent
11556 Example:
11557 @smallexample @c projectfile
11558 @group
11559    project Prj is
11560      for Source_Dirs use project'Source_Dirs & "units";
11561      for Source_Dirs use project'Source_Dirs & "test/drivers"
11562    end Prj;
11563 @end group
11564 @end smallexample
11565
11566 @noindent
11567 In the first attribute declaration, initially the attribute @code{Source_Dirs}
11568 has the default value: an empty string list. After this declaration,
11569 @code{Source_Dirs} is a string list of one element: @code{"units"}.
11570 After the second attribute declaration @code{Source_Dirs} is a string list of
11571 two elements: @code{"units"} and @code{"test/drivers"}.
11572
11573 Note: this example is for illustration only. In practice,
11574 the project file would contain only one attribute declaration:
11575
11576 @smallexample @c projectfile
11577    for Source_Dirs use ("units", "test/drivers");
11578 @end smallexample
11579
11580 @node Associative Array Attributes
11581 @subsection Associative Array Attributes
11582
11583 @noindent
11584 Some attributes are defined as @emph{associative arrays}. An associative
11585 array may be regarded as a function that takes a string as a parameter
11586 and delivers a string or string list value as its result.
11587
11588 Here are some examples of single associative array attribute associations:
11589
11590 @smallexample @c projectfile
11591    for Body ("main") use "Main.ada";
11592    for ^Switches^Switches^ ("main.ada")
11593        use ("^-v^-v^",
11594             "^-gnatv^-gnatv^");
11595    for ^Switches^Switches^ ("main.ada")
11596             use Builder'^Switches^Switches^ ("main.ada")
11597               & "^-g^-g^";
11598 @end smallexample
11599
11600 @noindent
11601 Like untyped variables and simple attributes, associative array attributes
11602 may be declared several times. Each declaration supplies a new value for the
11603 attribute, and replaces the previous setting.
11604
11605 @noindent
11606 An associative array attribute may be declared as a full associative array
11607 declaration, with the value of the same attribute in an imported or extended
11608 project.
11609
11610 @smallexample @c projectfile
11611    package Builder is
11612       for Default_Switches use Default.Builder'Default_Switches;
11613    end Builder;
11614 @end smallexample
11615
11616 @noindent
11617 In this example, @code{Default} must be either an project imported by the
11618 current project, or the project that the current project extends. If the
11619 attribute is in a package (in this case, in package @code{Builder}), the same
11620 package needs to be specified.
11621
11622 @noindent
11623 A full associative array declaration replaces any other declaration for the
11624 attribute, including other full associative array declaration. Single
11625 associative array associations may be declare after a full associative
11626 declaration, modifying the value for a single association of the attribute.
11627
11628 @node case Constructions
11629 @subsection @code{case} Constructions
11630
11631 @noindent
11632 A @code{case} construction is used in a project file to effect conditional
11633 behavior.
11634 Here is a typical example:
11635
11636 @smallexample @c projectfile
11637 @group
11638 project MyProj is
11639    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
11640
11641    OS : OS_Type := external ("OS", "GNU/Linux");
11642 @end group
11643
11644 @group
11645    package Compiler is
11646      case OS is
11647        when "GNU/Linux" | "Unix" =>
11648          for ^Default_Switches^Default_Switches^ ("Ada")
11649              use ("^-gnath^-gnath^");
11650        when "NT" =>
11651          for ^Default_Switches^Default_Switches^ ("Ada")
11652              use ("^-gnatP^-gnatP^");
11653        when others =>
11654      end case;
11655    end Compiler;
11656 end MyProj;
11657 @end group
11658 @end smallexample
11659
11660 @noindent
11661 The syntax of a @code{case} construction is based on the Ada case statement
11662 (although there is no @code{null} construction for empty alternatives).
11663
11664 The case expression must a typed string variable.
11665 Each alternative comprises the reserved word @code{when}, either a list of
11666 literal strings separated by the @code{"|"} character or the reserved word
11667 @code{others},  and the @code{"=>"} token.
11668 Each literal string must belong to the string type that is the type of the
11669 case variable.
11670 An @code{others} alternative, if present, must occur last.
11671
11672 After each @code{=>}, there are zero or more constructions.  The only
11673 constructions allowed in a case construction are other case constructions and
11674 attribute declarations. String type declarations, variable declarations and
11675 package declarations are not allowed.
11676
11677 The value of the case variable is often given by an external reference
11678 (see @ref{External References in Project Files}).
11679
11680 @c ****************************************
11681 @c * Objects and Sources in Project Files *
11682 @c ****************************************
11683
11684 @node Objects and Sources in Project Files
11685 @section Objects and Sources in Project Files
11686
11687 @menu
11688 * Object Directory::
11689 * Exec Directory::
11690 * Source Directories::
11691 * Source File Names::
11692 @end menu
11693
11694 @noindent
11695 Each project has exactly one object directory and one or more source
11696 directories. The source directories must contain at least one source file,
11697 unless  the project file explicitly specifies that no source files are present
11698 (see @ref{Source File Names}).
11699
11700 @node Object Directory
11701 @subsection Object Directory
11702
11703 @noindent
11704 The object directory for a project is the directory containing the compiler's
11705 output (such as @file{ALI} files and object files) for the project's immediate
11706 sources.
11707
11708 The object directory is given by the value of the attribute @code{Object_Dir}
11709 in the project file.
11710
11711 @smallexample @c projectfile
11712    for Object_Dir use "objects";
11713 @end smallexample
11714
11715 @noindent
11716 The attribute @var{Object_Dir} has a string value, the path name of the object
11717 directory. The path name may be absolute or relative to the directory of the
11718 project file. This directory must already exist, and be readable and writable.
11719
11720 By default, when the attribute @code{Object_Dir} is not given an explicit value
11721 or when its value is the empty string, the object directory is the same as the
11722 directory containing the project file.
11723
11724 @node Exec Directory
11725 @subsection Exec Directory
11726
11727 @noindent
11728 The exec directory for a project is the directory containing the executables
11729 for the project's main subprograms.
11730
11731 The exec directory is given by the value of the attribute @code{Exec_Dir}
11732 in the project file.
11733
11734 @smallexample @c projectfile
11735    for Exec_Dir use "executables";
11736 @end smallexample
11737
11738 @noindent
11739 The attribute @var{Exec_Dir} has a string value, the path name of the exec
11740 directory. The path name may be absolute or relative to the directory of the
11741 project file. This directory must already exist, and be writable.
11742
11743 By default, when the attribute @code{Exec_Dir} is not given an explicit value
11744 or when its value is the empty string, the exec directory is the same as the
11745 object directory of the project file.
11746
11747 @node Source Directories
11748 @subsection Source Directories
11749
11750 @noindent
11751 The source directories of a project are specified by the project file
11752 attribute @code{Source_Dirs}.
11753
11754 This attribute's value is a string list. If the attribute is not given an
11755 explicit value, then there is only one source directory, the one where the
11756 project file resides.
11757
11758 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
11759 as in
11760
11761 @smallexample @c projectfile
11762     for Source_Dirs use ();
11763 @end smallexample
11764
11765 @noindent
11766 indicates that the project contains no source files.
11767
11768 Otherwise, each string in the string list designates one or more
11769 source directories.
11770
11771 @smallexample @c projectfile
11772    for Source_Dirs use ("sources", "test/drivers");
11773 @end smallexample
11774
11775 @noindent
11776 If a string in the list ends with @code{"/**"},  then the directory whose path
11777 name precedes the two asterisks, as well as all its subdirectories
11778 (recursively), are source directories.
11779
11780 @smallexample @c projectfile
11781    for Source_Dirs use ("/system/sources/**");
11782 @end smallexample
11783
11784 @noindent
11785 Here the directory @code{/system/sources} and all of its subdirectories
11786 (recursively) are source directories.
11787
11788 To specify that the source directories are the directory of the project file
11789 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
11790 @smallexample @c projectfile
11791    for Source_Dirs use ("./**");
11792 @end smallexample
11793
11794 @noindent
11795 Each of the source directories must exist and be readable.
11796
11797 @node Source File Names
11798 @subsection Source File Names
11799
11800 @noindent
11801 In a project that contains source files, their names may be specified by the
11802 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
11803 (a string). Source file names never include any directory information.
11804
11805 If the attribute @code{Source_Files} is given an explicit value, then each
11806 element of the list is a source file name.
11807
11808 @smallexample @c projectfile
11809    for Source_Files use ("main.adb");
11810    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
11811 @end smallexample
11812
11813 @noindent
11814 If the attribute @code{Source_Files} is not given an explicit value,
11815 but the attribute @code{Source_List_File} is given a string value,
11816 then the source file names are contained in the text file whose path name
11817 (absolute or relative to the directory of the project file) is the
11818 value of the attribute @code{Source_List_File}.
11819
11820 Each line in the file that is not empty or is not a comment
11821 contains a source file name.
11822
11823 @smallexample @c projectfile
11824    for Source_List_File use "source_list.txt";
11825 @end smallexample
11826
11827 @noindent
11828 By default, if neither the attribute @code{Source_Files} nor the attribute
11829 @code{Source_List_File} is given an explicit value, then each file in the
11830 source directories that conforms to the project's naming scheme
11831 (see @ref{Naming Schemes}) is an immediate source of the project.
11832
11833 A warning is issued if both attributes @code{Source_Files} and
11834 @code{Source_List_File} are given explicit values. In this case, the attribute
11835 @code{Source_Files} prevails.
11836
11837 Each source file name must be the name of one existing source file
11838 in one of the source directories.
11839
11840 A @code{Source_Files} attribute whose value is an empty list
11841 indicates that there are no source files in the project.
11842
11843 If the order of the source directories is known statically, that is if
11844 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
11845 be several files with the same source file name. In this case, only the file
11846 in the first directory is considered as an immediate source of the project
11847 file. If the order of the source directories is not known statically, it is
11848 an error to have several files with the same source file name.
11849
11850 Projects can be specified to have no Ada source
11851 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
11852 list, or the @code{"Ada"} may be absent from @code{Languages}:
11853
11854 @smallexample @c projectfile
11855    for Source_Dirs use ();
11856    for Source_Files use ();
11857    for Languages use ("C", "C++");
11858 @end smallexample
11859
11860 @noindent
11861 Otherwise, a project must contain at least one immediate source.
11862
11863 Projects with no source files are useful as template packages
11864 (see @ref{Packages in Project Files}) for other projects; in particular to
11865 define a package @code{Naming} (see @ref{Naming Schemes}).
11866
11867 @c ****************************
11868 @c * Importing Projects *
11869 @c ****************************
11870
11871 @node  Importing Projects
11872 @section Importing Projects
11873
11874 @noindent
11875 An immediate source of a project P may depend on source files that
11876 are neither immediate sources of P nor in the predefined library.
11877 To get this effect, P must @emph{import} the projects that contain the needed
11878 source files.
11879
11880 @smallexample @c projectfile
11881 @group
11882   with "project1", "utilities.gpr";
11883   with "/namings/apex.gpr";
11884   project Main is
11885     ...
11886 @end group
11887 @end smallexample
11888
11889 @noindent
11890 As can be seen in this example, the syntax for importing projects is similar
11891 to the syntax for importing compilation units in Ada. However, project files
11892 use literal strings instead of names, and the @code{with} clause identifies
11893 project files rather than packages.
11894
11895 Each literal string is the file name or path name (absolute or relative) of a
11896 project file. If a string is simply a file name, with no path, then its
11897 location is determined by the @emph{project path}:
11898
11899 @itemize @bullet
11900 @item
11901 If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} exists,
11902 then the project path includes all the directories in this
11903 ^environment variable^logical name^, plus the directory of the project file.
11904
11905 @item
11906 If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} does not
11907 exist, then the project path contains only one directory, namely the one where
11908 the project file is located.
11909 @end itemize
11910
11911 @noindent
11912 If a relative pathname is used, as in
11913
11914 @smallexample @c projectfile
11915   with "tests/proj";
11916 @end smallexample
11917
11918 @noindent
11919 then the path is relative to the directory where the importing project file is
11920 located. Any symbolic link will be fully resolved in the directory
11921 of the importing project file before the imported project file is examined.
11922
11923 If the @code{with}'ed project file name does not have an extension,
11924 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
11925 then the file name as specified in the @code{with} clause (no extension) will
11926 be used. In the above example, if a file @code{project1.gpr} is found, then it
11927 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
11928 then it will be used; if neither file exists, this is an error.
11929
11930 A warning is issued if the name of the project file does not match the
11931 name of the project; this check is case insensitive.
11932
11933 Any source file that is an immediate source of the imported project can be
11934 used by the immediate sources of the importing project, transitively. Thus
11935 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
11936 sources of @code{A} may depend on the immediate sources of @code{C}, even if
11937 @code{A} does not import @code{C} explicitly. However, this is not recommended,
11938 because if and when @code{B} ceases to import @code{C}, some sources in
11939 @code{A} will no longer compile.
11940
11941 A side effect of this capability is that normally cyclic dependencies are not
11942 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
11943 is not allowed to import @code{A}. However, there are cases when cyclic
11944 dependencies would be beneficial. For these cases, another form of import
11945 between projects exists, the @code{limited with}: a project @code{A} that
11946 imports a project @code{B} with a straigh @code{with} may also be imported,
11947 directly or indirectly, by @code{B} on the condition that imports from @code{B}
11948 to @code{A} include at least one @code{limited with}.
11949
11950 @smallexample @c 0projectfile
11951 with "../b/b.gpr";
11952 with "../c/c.gpr";
11953 project A is
11954 end A;
11955
11956 limited with "../a/a.gpr";
11957 project B is
11958 end B;
11959
11960 with "../d/d.gpr";
11961 project C is
11962 end C;
11963
11964 limited with "../a/a.gpr";
11965 project D is
11966 end D;
11967 @end smallexample
11968
11969 @noindent
11970 In the above legal example, there are two project cycles:
11971 @itemize @bullet
11972 @item A-> B-> A
11973 @item A -> C -> D -> A
11974 @end itemize
11975
11976 @noindent
11977 In each of these cycle there is one @code{limited with}: import of @code{A}
11978 from @code{B} and import of @code{A} from @code{D}.
11979
11980 The difference between straight @code{with} and @code{limited with} is that
11981 the name of a project imported with a @code{limited with} cannot be used in the
11982 project that imports it. In particular, its packages cannot be renamed and
11983 its variables cannot be referred to.
11984
11985 An exception to the above rules for @code{limited with} is that for the main
11986 project specified to @command{gnatmake} or to the @command{GNAT} driver a
11987 @code{limited with} is equivalent to a straight @code{with}. For example,
11988 in the example above, projects @code{B} and @code{D} could not be main
11989 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
11990 each have a @code{limited with} that is the only one in a cycle of importing
11991 projects.
11992
11993 @c *********************
11994 @c * Project Extension *
11995 @c *********************
11996
11997 @node Project Extension
11998 @section Project Extension
11999
12000 @noindent
12001 During development of a large system, it is sometimes necessary to use
12002 modified versions of some of the source files, without changing the original
12003 sources. This can be achieved through the @emph{project extension} facility.
12004
12005 @smallexample @c projectfile
12006    project Modified_Utilities extends "/baseline/utilities.gpr" is ...
12007 @end smallexample
12008
12009 @noindent
12010 A project extension declaration introduces an extending project
12011 (the @emph{child}) and a project being extended (the @emph{parent}).
12012
12013 By default, a child project inherits all the sources of its parent.
12014 However, inherited sources can be overridden: a unit in a parent is hidden
12015 by a unit of the same name in the child.
12016
12017 Inherited sources are considered to be sources (but not immediate sources)
12018 of the child project; see @ref{Project File Syntax}.
12019
12020 An inherited source file retains any switches specified in the parent project.
12021
12022 For example if the project @code{Utilities} contains the specification and the
12023 body of an Ada package @code{Util_IO}, then the project
12024 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
12025 The original body of @code{Util_IO} will not be considered in program builds.
12026 However, the package specification will still be found in the project
12027 @code{Utilities}.
12028
12029 A child project can have only one parent but it may import any number of other
12030 projects.
12031
12032 A project is not allowed to import directly or indirectly at the same time a
12033 child project and any of its ancestors.
12034
12035 @c ****************************************
12036 @c * External References in Project Files *
12037 @c ****************************************
12038
12039 @node  External References in Project Files
12040 @section External References in Project Files
12041
12042 @noindent
12043 A project file may contain references to external variables; such references
12044 are called @emph{external references}.
12045
12046 An external variable is either defined as part of the environment (an
12047 environment variable in Unix, for example) or else specified on the command
12048 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
12049 If both, then the command line value is used.
12050
12051 The value of an external reference is obtained by means of the built-in
12052 function @code{external}, which returns a string value.
12053 This function has two forms:
12054 @itemize @bullet
12055 @item @code{external (external_variable_name)}
12056 @item @code{external (external_variable_name, default_value)}
12057 @end itemize
12058
12059 @noindent
12060 Each parameter must be a string literal.  For example:
12061
12062 @smallexample @c projectfile
12063    external ("USER")
12064    external ("OS", "GNU/Linux")
12065 @end smallexample
12066
12067 @noindent
12068 In the form with one parameter, the function returns the value of
12069 the external variable given as parameter. If this name is not present in the
12070 environment, the function returns an empty string.
12071
12072 In the form with two string parameters, the second argument is
12073 the value returned when the variable given as the first argument is not
12074 present in the environment. In the example above, if @code{"OS"} is not
12075 the name of ^an environment variable^a logical name^ and is not passed on
12076 the command line, then the returned value is @code{"GNU/Linux"}.
12077
12078 An external reference may be part of a string expression or of a string
12079 list expression, and can therefore appear in a variable declaration or
12080 an attribute declaration.
12081
12082 @smallexample @c projectfile
12083 @group
12084    type Mode_Type is ("Debug", "Release");
12085    Mode : Mode_Type := external ("MODE");
12086    case Mode is
12087      when "Debug" =>
12088         ...
12089 @end group
12090 @end smallexample
12091
12092 @c *****************************
12093 @c * Packages in Project Files *
12094 @c *****************************
12095
12096 @node  Packages in Project Files
12097 @section Packages in Project Files
12098
12099 @noindent
12100 A @emph{package} defines the settings for project-aware tools within a
12101 project.
12102 For each such tool one can declare a package; the names for these
12103 packages are preset (see @ref{Packages}).
12104 A package may contain variable declarations, attribute declarations, and case
12105 constructions.
12106
12107 @smallexample @c projectfile
12108 @group
12109    project Proj is
12110       package Builder is  -- used by gnatmake
12111          for ^Default_Switches^Default_Switches^ ("Ada")
12112              use ("^-v^-v^",
12113                   "^-g^-g^");
12114       end Builder;
12115    end Proj;
12116 @end group
12117 @end smallexample
12118
12119 @noindent
12120 The syntax of package declarations mimics that of package in Ada.
12121
12122 Most of the packages have an attribute
12123 @code{^Default_Switches^Default_Switches^}.
12124 This attribute is an associative array, and its value is a string list.
12125 The index of the associative array is the name of a programming language (case
12126 insensitive). This attribute indicates the ^switch^switch^
12127 or ^switches^switches^ to be used
12128 with the corresponding tool.
12129
12130 Some packages also have another attribute, @code{^Switches^Switches^},
12131 an associative array whose value is a string list.
12132 The index is the name of a source file.
12133 This attribute indicates the ^switch^switch^
12134 or ^switches^switches^ to be used by the corresponding
12135 tool when dealing with this specific file.
12136
12137 Further information on these ^switch^switch^-related attributes is found in
12138 @ref{^Switches^Switches^ and Project Files}.
12139
12140 A package may be declared as a @emph{renaming} of another package; e.g., from
12141 the project file for an imported project.
12142
12143 @smallexample @c projectfile
12144 @group
12145   with "/global/apex.gpr";
12146   project Example is
12147     package Naming renames Apex.Naming;
12148     ...
12149   end Example;
12150 @end group
12151 @end smallexample
12152
12153 @noindent
12154 Packages that are renamed in other project files often come from project files
12155 that have no sources: they are just used as templates. Any modification in the
12156 template will be reflected automatically in all the project files that rename
12157 a package from the template.
12158
12159 In addition to the tool-oriented packages, you can also declare a package
12160 named @code{Naming} to establish specialized source file naming conventions
12161 (see @ref{Naming Schemes}).
12162
12163 @c ************************************
12164 @c * Variables from Imported Projects *
12165 @c ************************************
12166
12167 @node Variables from Imported Projects
12168 @section Variables from Imported Projects
12169
12170 @noindent
12171 An attribute or variable defined in an imported or parent project can
12172 be used in expressions in the importing / extending project.
12173 Such an attribute or variable is denoted by an expanded name whose prefix
12174 is either the name of the project or the expanded name of a package within
12175 a project.
12176
12177 @smallexample @c projectfile
12178 @group
12179   with "imported";
12180   project Main extends "base" is
12181      Var1 := Imported.Var;
12182      Var2 := Base.Var & ".new";
12183 @end group
12184
12185 @group
12186      package Builder is
12187         for ^Default_Switches^Default_Switches^ ("Ada")
12188             use Imported.Builder.Ada_^Switches^Switches^ &
12189                 "^-gnatg^-gnatg^" &
12190                 "^-v^-v^";
12191      end Builder;
12192 @end group
12193
12194 @group
12195      package Compiler is
12196         for ^Default_Switches^Default_Switches^ ("Ada")
12197             use Base.Compiler.Ada_^Switches^Switches^;
12198      end Compiler;
12199   end Main;
12200 @end group
12201 @end smallexample
12202
12203 @noindent
12204 In this example:
12205
12206 @itemize @bullet
12207 @item
12208 The value of @code{Var1} is a copy of the variable @code{Var} defined
12209 in the project file @file{"imported.gpr"}
12210 @item
12211 the value of @code{Var2} is a copy of the value of variable @code{Var}
12212 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
12213 @item
12214 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12215 @code{Builder} is a string list that includes in its value a copy of the value
12216 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
12217 in project file @file{imported.gpr} plus two new elements:
12218 @option{"^-gnatg^-gnatg^"}
12219 and @option{"^-v^-v^"};
12220 @item
12221 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12222 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
12223 defined in the @code{Compiler} package in project file @file{base.gpr},
12224 the project being extended.
12225 @end itemize
12226
12227 @c ******************
12228 @c * Naming Schemes *
12229 @c ******************
12230
12231 @node  Naming Schemes
12232 @section Naming Schemes
12233
12234 @noindent
12235 Sometimes an Ada software system is ported from a foreign compilation
12236 environment to GNAT, and the file names do not use the default GNAT
12237 conventions. Instead of changing all the file names (which for a variety
12238 of reasons might not be possible), you can define the relevant file
12239 naming scheme in the @code{Naming} package in your project file.
12240
12241 @noindent
12242 Note that the use of pragmas described in @ref{Alternative
12243 File Naming Schemes} by mean of a configuration pragmas file is not
12244 supported when using project files. You must use the features described
12245 in this paragraph. You can however use specify other configuration
12246 pragmas (see @ref{Specifying Configuration Pragmas}).
12247
12248 @ifclear vms
12249 For example, the following
12250 package models the Apex file naming rules:
12251
12252 @smallexample @c projectfile
12253 @group
12254   package Naming is
12255     for Casing               use "lowercase";
12256     for Dot_Replacement      use ".";
12257     for Spec_Suffix ("Ada")  use ".1.ada";
12258     for Body_Suffix ("Ada")  use ".2.ada";
12259   end Naming;
12260 @end group
12261 @end smallexample
12262 @end ifclear
12263
12264 @ifset vms
12265 For example, the following package models the DEC Ada file naming rules:
12266
12267 @smallexample @c projectfile
12268 @group
12269   package Naming is
12270     for Casing               use "lowercase";
12271     for Dot_Replacement      use "__";
12272     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
12273     for Body_Suffix ("Ada")  use ".^ada^ada^";
12274   end Naming;
12275 @end group
12276 @end smallexample
12277
12278 @noindent
12279 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
12280 names in lower case)
12281 @end ifset
12282
12283 @noindent
12284 You can define the following attributes in package @code{Naming}:
12285
12286 @table @code
12287
12288 @item @var{Casing}
12289 This must be a string with one of the three values @code{"lowercase"},
12290 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
12291
12292 @noindent
12293 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
12294
12295 @item @var{Dot_Replacement}
12296 This must be a string whose value satisfies the following conditions:
12297
12298 @itemize @bullet
12299 @item It must not be empty
12300 @item It cannot start or end with an alphanumeric character
12301 @item It cannot be a single underscore
12302 @item It cannot start with an underscore followed by an alphanumeric
12303 @item It cannot contain a dot @code{'.'} except if the entire string
12304 is @code{"."}
12305 @end itemize
12306
12307 @noindent
12308 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
12309
12310 @item @var{Spec_Suffix}
12311 This is an associative array (indexed by the programming language name, case
12312 insensitive) whose value is a string that must satisfy the following
12313 conditions:
12314
12315 @itemize @bullet
12316 @item It must not be empty
12317 @item It must include at least one dot
12318 @end itemize
12319 @noindent
12320 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
12321 @code{"^.ads^.ADS^"}.
12322
12323 @item @var{Body_Suffix}
12324 This is an associative array (indexed by the programming language name, case
12325 insensitive) whose value is a string that must satisfy the following
12326 conditions:
12327
12328 @itemize @bullet
12329 @item It must not be empty
12330 @item It must include at least one dot
12331 @item It cannot end with the same string as @code{Spec_Suffix ("Ada")}
12332 @end itemize
12333 @noindent
12334 If @code{Body_Suffix ("Ada")} is not specified, then the default is
12335 @code{"^.adb^.ADB^"}.
12336
12337 @item @var{Separate_Suffix}
12338 This must be a string whose value satisfies the same conditions as
12339 @code{Body_Suffix}.
12340
12341 @noindent
12342 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
12343 value as @code{Body_Suffix ("Ada")}.
12344
12345 @item @var{Spec}
12346 @noindent
12347 You can use the associative array attribute @code{Spec}  to define
12348 the source file name for an individual Ada compilation unit's spec. The array
12349 index must be a string literal that identifies the Ada unit (case insensitive).
12350 The value of this attribute must be a string that identifies the file that
12351 contains this unit's spec (case sensitive or insensitive depending on the
12352 operating system).
12353
12354 @smallexample @c projectfile
12355    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
12356 @end smallexample
12357
12358 @item @var{Body}
12359
12360 You can use the associative array attribute @code{Body} to
12361 define the source file name for an individual Ada compilation unit's body
12362 (possibly a subunit).  The array index must be a string literal that identifies
12363 the Ada unit (case insensitive).  The value of this attribute must be a string
12364 that identifies the file that contains this unit's body or subunit (case
12365 sensitive or insensitive depending on the operating system).
12366
12367 @smallexample @c projectfile
12368    for Body ("MyPack.MyChild") use "mypack.mychild.body";
12369 @end smallexample
12370 @end table
12371
12372 @c ********************
12373 @c * Library Projects *
12374 @c ********************
12375
12376 @node Library Projects
12377 @section Library Projects
12378
12379 @noindent
12380 @emph{Library projects} are projects whose object code is placed in a library.
12381 (Note that this facility is not yet supported on all platforms)
12382
12383 To create a library project, you need to define in its project file
12384 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
12385 Additionally, you may define the library-related attributes
12386 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
12387 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
12388
12389 The @code{Library_Name} attribute has a string value. There is no restriction
12390 on the name of a library. It is the responsability of the developer to
12391 choose a name that will be accepted by the platform. It is recommanded to
12392 choose names that could be Ada identifiers; such names are almost guaranteed
12393 to be acceptable on all platforms.
12394
12395 The @code{Library_Dir} attribute has a string value that designates the path
12396 (absolute or relative) of the directory where the library will reside.
12397 It must designate an existing directory, and this directory must be
12398 different from the project's object directory. It also needs to be writable.
12399
12400 If both @code{Library_Name} and @code{Library_Dir} are specified and
12401 are legal, then the project file defines a library project.  The optional
12402 library-related attributes are checked only for such project files.
12403
12404 The @code{Library_Kind} attribute has a string value that must be one of the
12405 following (case insensitive): @code{"static"}, @code{"dynamic"} or
12406 @code{"relocatable"}. If this attribute is not specified, the library is a
12407 static library, that is an archive of object files that can be potentially
12408 linked into an static executable. Otherwise, the library may be dynamic or
12409 relocatable, that is a library that is loaded only at the start of execution.
12410 Depending on the operating system, there may or may not be a distinction
12411 between dynamic and relocatable libraries. For Unix and VMS Unix there is no
12412 such distinction.
12413
12414 If you need to build both a static and a dynamic library, you should use two
12415 different object directories, since in some cases some extra code needs to
12416 be generated for the latter. For such cases, it is recommended to either use
12417 two different project files, or a single one which uses external variables
12418 to indicate what kind of library should be build.
12419
12420 The @code{Library_Version} attribute has a string value whose interpretation
12421 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
12422 used only for dynamic/relocatable libraries as the internal name of the
12423 library (the @code{"soname"}). If the library file name (built from the
12424 @code{Library_Name}) is different from the @code{Library_Version}, then the
12425 library file will be a symbolic link to the actual file whose name will be
12426 @code{Library_Version}.
12427
12428 Example (on Unix):
12429
12430 @smallexample @c projectfile
12431 @group
12432 project Plib is
12433
12434    Version := "1";
12435
12436    for Library_Dir use "lib_dir";
12437    for Library_Name use "dummy";
12438    for Library_Kind use "relocatable";
12439    for Library_Version use "libdummy.so." & Version;
12440
12441 end Plib;
12442 @end group
12443 @end smallexample
12444
12445 @noindent
12446 Directory @file{lib_dir} will contain the internal library file whose name
12447 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
12448 @file{libdummy.so.1}.
12449
12450 When @command{gnatmake} detects that a project file
12451 is a library project file, it will check all immediate sources of the project
12452 and rebuild the library if any of the sources have been recompiled.
12453
12454 Standard project files can import library project files. In such cases,
12455 the libraries will only be rebuild if some of its sources are recompiled
12456 because they are in the closure of some other source in an importing project.
12457 Sources of the library project files that are not in such a closure will
12458 not be checked, unless the full library is checked, because one of its sources
12459 needs to be recompiled.
12460
12461 For instance, assume the project file @code{A} imports the library project file
12462 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
12463 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
12464 @file{l2.ads}, @file{l2.adb}.
12465
12466 If @file{l1.adb} has been modified, then the library associated with @code{L}
12467 will be rebuild when compiling all the immediate sources of @code{A} only
12468 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
12469 @code{"with L1;"}.
12470
12471 To be sure that all the sources in the library associated with @code{L} are
12472 up to date, and that all the sources of parject @code{A} are also up to date,
12473 the following two commands needs to be used:
12474
12475 @smallexample
12476 gnatmake -Pl.gpr
12477 gnatmake -Pa.gpr
12478 @end smallexample
12479
12480 When a library is built or rebuilt, an attempt is made first to delete all
12481 files in the library directory.
12482 All @file{ALI} files will also be copied from the object directory to the
12483 library directory. To build executables, @command{gnatmake} will use the
12484 library rather than the individual object files.
12485
12486
12487 @c **********************************************
12488 @c * Using Third-Party Libraries through Projects
12489 @c **********************************************
12490 @node Using Third-Party Libraries through Projects
12491 @section Using Third-Party Libraries through Projects
12492
12493 Whether you are exporting your own library to make it available to
12494 clients, or you are using a library provided by a third party, it is
12495 convenient to have project files that automatically set the correct
12496 command line switches for the compiler and linker.
12497
12498 Such project files are very similar to the library project files;
12499 @xref{Library Projects}. The only difference is that you set the
12500 @code{Source_Dirs} and @code{Object_Dir} attribute so that they point to the
12501 directories where, respectively, the sources and the read-only ALI files have
12502 been installed.
12503
12504 If you need to interface with a set of libraries, as opposed to a
12505 single one, you need to create one library project for each of the
12506 libraries. In addition, a top-level project that imports all these
12507 library projects should be provided, so that the user of your library
12508 has a single @code{with} clause to add to his own projects.
12509
12510 For instance, let's assume you are providing two static libraries
12511 @file{liba.a} and @file{libb.a}. The user needs to link with
12512 both of these libraries. Each of these is associated with its
12513 own set of header files. Let's assume furthermore that all the
12514 header files for the two libraries have been installed in the same
12515 directory @file{headers}. The @file{ALI} files are found in the same
12516 @file{headers} directory.
12517
12518 In this case, you should provide the following three projects:
12519
12520 @smallexample @c projectfile
12521 @group
12522 with "liba", "libb";
12523 project My_Library is
12524   for Source_Dirs use ("headers");
12525   for Object_Dir  use "headers";
12526 end My_Library;
12527 @end group
12528
12529 @group
12530 project Liba is
12531    for Source_Dirs use ();
12532    for Library_Dir use "lib";
12533    for Library_Name use "a";
12534    for Library_Kind use "static";
12535 end Liba;
12536 @end group
12537
12538 @group
12539 project Libb is
12540    for Source_Dirs use ();
12541    for Library_Dir use "lib";
12542    for Library_Name use "b";
12543    for Library_Kind use "static";
12544 end Libb;
12545 @end group
12546 @end smallexample
12547
12548 @c *******************************
12549 @c * Stand-alone Library Projects *
12550 @c *******************************
12551
12552 @node Stand-alone Library Projects
12553 @section Stand-alone Library Projects
12554
12555 @noindent
12556 A Stand-alone Library is a library that contains the necessary code to
12557 elaborate the Ada units that are included in the library. A Stand-alone
12558 Library is suitable to be used in an executable when the main is not
12559 in Ada. However, Stand-alone Libraries may also be used with an Ada main
12560 subprogram.
12561
12562 A Stand-alone Library Project is a Library Project where the library is
12563 a Stand-alone Library.
12564
12565 To be a Stand-alone Library Project, in addition to the two attributes
12566 that make a project a Library Project (@code{Library_Name} and
12567 @code{Library_Dir}, see @ref{Library Projects}), the attribute
12568 @code{Library_Interface} must be defined.
12569
12570 @smallexample @c projectfile
12571 @group
12572    for Library_Dir use "lib_dir";
12573    for Library_Name use "dummy";
12574    for Library_Interface use ("int1", "int1.child");
12575 @end group
12576 @end smallexample
12577
12578 Attribute @code{Library_Interface} has a non empty string list value,
12579 each string in the list designating a unit contained in an immediate source
12580 of the project file.
12581
12582 When a Stand-alone Library is built, first the binder is invoked to build
12583 a package whose name depends on the library name
12584 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
12585 This binder-generated package includes initialization and
12586 finalization procedures whose
12587 names depend on the library name (dummyinit and dummyfinal in the example
12588 above). The object corresponding to this package is included in the library.
12589
12590 A dynamic or relocatable Stand-alone Library is automatically initialized
12591 if automatic initialization of Stand-alone Libraries is supported on the
12592 platform and if attribute @code{Library_Auto_Init} is not specified or
12593 is specified with the value "true". A static Stand-alone Library is never
12594 automatically initialized.
12595
12596 Single string attribute @code{Library_Auto_Init} may be specified with only
12597 two possible values: "false" or "true" (case-insensitive). Specifying
12598 "false" for attribute @code{Library_Auto_Init} will prevent automatic
12599 initialization of dynamic or relocatable libraries.
12600
12601 When a non automatically initialized Stand-alone Library is used
12602 in an executable, its initialization procedure must be called before
12603 any service of the library is used.
12604 When the main subprogram is in Ada, it may mean that the initialization
12605 procedure has to be called during elaboration of another package.
12606
12607 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
12608 (those that are listed in attribute @code{Library_Interface}) are copied to
12609 the Library Directory. As a consequence, only the Interface Units may be
12610 imported from Ada units outside of the library. If other units are imported,
12611 the binding phase will fail.
12612
12613 When a Stand-Alone Library is bound, the switches that are specified in
12614 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
12615 used in the call to @command{gnatbind}.
12616
12617 The string list attribute @code{Library_Options} may be used to specified
12618 additional switches to the call to @command{gcc} to link the library.
12619
12620 The attribute @code{Library_Src_Dir}, may be specified for a
12621 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
12622 single string value. Its value must be the path (absolute or relative to the
12623 project directory) of an existing directory. This directory cannot be the
12624 object directory or one of the source directories, but it can be the same as
12625 the library directory. The sources of the Interface
12626 Units of the library, necessary to an Ada client of the library, will be
12627 copied to the designated directory, called Interface Copy directory.
12628 These sources includes the specs of the Interface Units, but they may also
12629 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
12630 are used, or when there is a generic units in the spec. Before the sources
12631 are copied to the Interface Copy directory, an attempt is made to delete all
12632 files in the Interface Copy directory.
12633
12634 @c *************************************
12635 @c * Switches Related to Project Files *
12636 @c *************************************
12637 @node Switches Related to Project Files
12638 @section Switches Related to Project Files
12639
12640 @noindent
12641 The following switches are used by GNAT tools that support project files:
12642
12643 @table @option
12644
12645 @item ^-P^/PROJECT_FILE=^@var{project}
12646 @cindex @option{^-P^/PROJECT_FILE^} (any tool supporting project files)
12647 Indicates the name of a project file. This project file will be parsed with
12648 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12649 if any, and using the external references indicated
12650 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12651 @ifclear vms
12652 There may zero, one or more spaces between @option{-P} and @var{project}.
12653 @end ifclear
12654
12655 @noindent
12656 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12657
12658 @noindent
12659 Since the Project Manager parses the project file only after all the switches
12660 on the command line are checked, the order of the switches
12661 @option{^-P^/PROJECT_FILE^},
12662 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12663 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12664
12665 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12666 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any tool supporting project files)
12667 Indicates that external variable @var{name} has the value @var{value}.
12668 The Project Manager will use this value for occurrences of
12669 @code{external(name)} when parsing the project file.
12670
12671 @ifclear vms
12672 @noindent
12673 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12674 put between quotes.
12675 @smallexample
12676   -XOS=NT
12677   -X"user=John Doe"
12678 @end smallexample
12679 @end ifclear
12680
12681 @noindent
12682 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12683 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12684 @var{name}, only the last one is used.
12685
12686 @noindent
12687 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12688 takes precedence over the value of the same name in the environment.
12689
12690 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12691 @cindex @code{^-vP^/MESSAGES_PROJECT_FILE^} (any tool supporting project files)
12692 @c Previous line uses code vs option command, to stay less than 80 chars
12693 Indicates the verbosity of the parsing of GNAT project files.
12694
12695 @ifclear vms
12696 @option{-vP0} means Default;
12697 @option{-vP1} means Medium;
12698 @option{-vP2} means High.
12699 @end ifclear
12700
12701 @ifset vms
12702 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12703 HIGH.
12704 @end ifset
12705
12706 @noindent
12707 The default is ^Default^DEFAULT^: no output for syntactically correct
12708 project files.
12709 @noindent
12710 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12711 only the last one is used.
12712
12713 @end table
12714
12715 @c **********************************
12716 @c * Tools Supporting Project Files *
12717 @c **********************************
12718
12719 @node  Tools Supporting Project Files
12720 @section Tools Supporting Project Files
12721
12722 @menu
12723 * gnatmake and Project Files::
12724 * The GNAT Driver and Project Files::
12725 @ifclear vms
12726 * Glide and Project Files::
12727 @end ifclear
12728 @end menu
12729
12730 @node gnatmake and Project Files
12731 @subsection gnatmake and Project Files
12732
12733 @noindent
12734 This section covers several topics related to @command{gnatmake} and
12735 project files: defining ^switches^switches^ for @command{gnatmake}
12736 and for the tools that it invokes; specifying configuration pragmas;
12737 the use of the @code{Main} attribute; building and rebuilding library project
12738 files.
12739
12740 @menu
12741 * ^Switches^Switches^ and Project Files::
12742 * Specifying Configuration Pragmas::
12743 * Project Files and Main Subprograms::
12744 * Library Project Files::
12745 @end menu
12746
12747 @node ^Switches^Switches^ and Project Files
12748 @subsubsection ^Switches^Switches^ and Project Files
12749
12750 @ifset vms
12751 It is not currently possible to specify VMS style qualifiers in the project
12752 files; only Unix style ^switches^switches^ may be specified.
12753 @end ifset
12754
12755 @noindent
12756 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12757 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12758 attribute, a @code{^Switches^Switches^} attribute, or both;
12759 as their names imply, these ^switch^switch^-related
12760 attributes affect the ^switches^switches^ that are used for each of these GNAT
12761 components when
12762 @command{gnatmake} is invoked.  As will be explained below, these
12763 component-specific ^switches^switches^ precede
12764 the ^switches^switches^ provided on the @command{gnatmake} command line.
12765
12766 The @code{^Default_Switches^Default_Switches^} attribute is an associative
12767 array indexed by language name (case insensitive) whose value is a string list.
12768 For example:
12769
12770 @smallexample @c projectfile
12771 @group
12772 package Compiler is
12773   for ^Default_Switches^Default_Switches^ ("Ada")
12774       use ("^-gnaty^-gnaty^",
12775            "^-v^-v^");
12776 end Compiler;
12777 @end group
12778 @end smallexample
12779
12780 @noindent
12781 The @code{^Switches^Switches^} attribute is also an associative array,
12782 indexed by a file name (which may or may not be case sensitive, depending
12783 on the operating system) whose value is a string list.  For example:
12784
12785 @smallexample @c projectfile
12786 @group
12787 package Builder is
12788    for ^Switches^Switches^ ("main1.adb")
12789        use ("^-O2^-O2^");
12790    for ^Switches^Switches^ ("main2.adb")
12791        use ("^-g^-g^");
12792 end Builder;
12793 @end group
12794 @end smallexample
12795
12796 @noindent
12797 For the @code{Builder} package, the file names must designate source files
12798 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
12799 file names must designate @file{ALI} or source files for main subprograms.
12800 In each case just the file name without an explicit extension is acceptable.
12801
12802 For each tool used in a program build (@command{gnatmake}, the compiler, the
12803 binder, and the linker), the corresponding package @dfn{contributes} a set of
12804 ^switches^switches^ for each file on which the tool is invoked, based on the
12805 ^switch^switch^-related attributes defined in the package.
12806 In particular, the ^switches^switches^
12807 that each of these packages contributes for a given file @var{f} comprise:
12808
12809 @itemize @bullet
12810 @item
12811 the value of attribute @code{^Switches^Switches^ (@var{f})},
12812 if it is specified in the package for the given file,
12813 @item
12814 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
12815 if it is specified in the package.
12816 @end itemize
12817
12818 @noindent
12819 If neither of these attributes is defined in the package, then the package does
12820 not contribute any ^switches^switches^ for the given file.
12821
12822 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
12823 two sets, in the following order: those contributed for the file
12824 by the @code{Builder} package;
12825 and the switches passed on the command line.
12826
12827 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12828 the ^switches^switches^ passed to the tool comprise three sets,
12829 in the following order:
12830
12831 @enumerate
12832 @item
12833 the applicable ^switches^switches^ contributed for the file
12834 by the @code{Builder} package in the project file supplied on the command line;
12835
12836 @item
12837 those contributed for the file by the package (in the relevant project file --
12838 see below) corresponding to the tool; and
12839
12840 @item
12841 the applicable switches passed on the command line.
12842 @end enumerate
12843
12844 @noindent
12845 The term @emph{applicable ^switches^switches^} reflects the fact that
12846 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
12847 tools, depending on the individual ^switch^switch^.
12848
12849 @command{gnatmake} may invoke the compiler on source files from different
12850 projects. The Project Manager will use the appropriate project file to
12851 determine the @code{Compiler} package for each source file being compiled.
12852 Likewise for the @code{Binder} and @code{Linker} packages.
12853
12854 As an example, consider the following package in a project file:
12855
12856 @smallexample @c projectfile
12857 @group
12858 project Proj1 is
12859    package Compiler is
12860       for ^Default_Switches^Default_Switches^ ("Ada")
12861           use ("^-g^-g^");
12862       for ^Switches^Switches^ ("a.adb")
12863           use ("^-O1^-O1^");
12864       for ^Switches^Switches^ ("b.adb")
12865           use ("^-O2^-O2^",
12866                "^-gnaty^-gnaty^");
12867    end Compiler;
12868 end Proj1;
12869 @end group
12870 @end smallexample
12871
12872 @noindent
12873 If @command{gnatmake} is invoked with this project file, and it needs to
12874 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12875 @file{a.adb} will be compiled with the ^switch^switch^
12876 @option{^-O1^-O1^},
12877 @file{b.adb} with ^switches^switches^
12878 @option{^-O2^-O2^}
12879 and @option{^-gnaty^-gnaty^},
12880 and @file{c.adb} with @option{^-g^-g^}.
12881
12882 The following example illustrates the ordering of the ^switches^switches^
12883 contributed by different packages:
12884
12885 @smallexample @c projectfile
12886 @group
12887 project Proj2 is
12888    package Builder is
12889       for ^Switches^Switches^ ("main.adb")
12890           use ("^-g^-g^",
12891                "^-O1^-)1^",
12892                "^-f^-f^");
12893    end Builder;
12894 @end group
12895
12896 @group
12897    package Compiler is
12898       for ^Switches^Switches^ ("main.adb")
12899           use ("^-O2^-O2^");
12900    end Compiler;
12901 end Proj2;
12902 @end group
12903 @end smallexample
12904
12905 @noindent
12906 If you issue the command:
12907
12908 @smallexample
12909     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
12910 @end smallexample
12911
12912 @noindent
12913 then the compiler will be invoked on @file{main.adb} with the following
12914 sequence of ^switches^switches^
12915
12916 @smallexample
12917    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
12918 @end smallexample
12919
12920 with the last @option{^-O^-O^}
12921 ^switch^switch^ having precedence over the earlier ones;
12922 several other ^switches^switches^
12923 (such as @option{^-c^-c^}) are added implicitly.
12924
12925 The ^switches^switches^
12926 @option{^-g^-g^}
12927 and @option{^-O1^-O1^} are contributed by package
12928 @code{Builder},  @option{^-O2^-O2^} is contributed
12929 by the package @code{Compiler}
12930 and @option{^-O0^-O0^} comes from the command line.
12931
12932 The @option{^-g^-g^}
12933 ^switch^switch^ will also be passed in the invocation of
12934 @command{Gnatlink.}
12935
12936 A final example illustrates switch contributions from packages in different
12937 project files:
12938
12939 @smallexample @c projectfile
12940 @group
12941 project Proj3 is
12942    for Source_Files use ("pack.ads", "pack.adb");
12943    package Compiler is
12944       for ^Default_Switches^Default_Switches^ ("Ada")
12945           use ("^-gnata^-gnata^");
12946    end Compiler;
12947 end Proj3;
12948 @end group
12949
12950 @group
12951 with "Proj3";
12952 project Proj4 is
12953    for Source_Files use ("foo_main.adb", "bar_main.adb");
12954    package Builder is
12955       for ^Switches^Switches^ ("foo_main.adb")
12956           use ("^-s^-s^",
12957                "^-g^-g^");
12958    end Builder;
12959 end Proj4;
12960 @end group
12961
12962 @group
12963 -- Ada source file:
12964 with Pack;
12965 procedure Foo_Main is
12966    ...
12967 end Foo_Main;
12968 @end group
12969 @end smallexample
12970
12971 If the command is
12972 @smallexample
12973 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
12974 @end smallexample
12975
12976 @noindent
12977 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
12978 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
12979 @option{^-gnato^-gnato^} (passed on the command line).
12980 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
12981 are @option{^-g^-g^} from @code{Proj4.Builder},
12982 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
12983 and @option{^-gnato^-gnato^} from the command line.
12984
12985 @noindent
12986 When using @command{gnatmake} with project files, some ^switches^switches^ or
12987 arguments may be expressed as relative paths. As the working directory where
12988 compilation occurs may change, these relative paths are converted to absolute
12989 paths. For the ^switches^switches^ found in a project file, the relative paths
12990 are relative to the project file directory, for the switches on the command
12991 line, they are relative to the directory where @command{gnatmake} is invoked.
12992 The ^switches^switches^ for which this occurs are:
12993 ^-I^-I^,
12994 ^-A^-A^,
12995 ^-L^-L^,
12996 ^-aO^-aO^,
12997 ^-aL^-aL^,
12998 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
12999 ^switch^switch^
13000 ^-o^-o^, object files specified in package @code{Linker} or after
13001 -largs on the command line). The exception to this rule is the ^switch^switch^
13002 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
13003
13004 @node Specifying Configuration Pragmas
13005 @subsubsection Specifying Configuration Pragmas
13006
13007 When using @command{gnatmake} with project files, if there exists a file
13008 @file{gnat.adc} that contains configuration pragmas, this file will be
13009 ignored.
13010
13011 Configuration pragmas can be defined by means of the following attributes in
13012 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
13013 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
13014
13015 Both these attributes are single string attributes. Their values is the path
13016 name of a file containing configuration pragmas. If a path name is relative,
13017 then it is relative to the project directory of the project file where the
13018 attribute is defined.
13019
13020 When compiling a source, the configuration pragmas used are, in order,
13021 those listed in the file designated by attribute
13022 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
13023 project file, if it is specified, and those listed in the file designated by
13024 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
13025 the project file of the source, if it exists.
13026
13027 @node Project Files and Main Subprograms
13028 @subsubsection Project Files and Main Subprograms
13029
13030 @noindent
13031 When using a project file, you can invoke @command{gnatmake}
13032 with one or several main subprograms, by specifying their source files on the
13033 command line.
13034
13035 @smallexample
13036     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
13037 @end smallexample
13038
13039 @noindent
13040 Each of these needs to be a source file of the same project, except
13041 when the switch ^-u^/UNIQUE^ is used.
13042
13043 @noindent
13044 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13045 same project, one of the project in the tree rooted at the project specified
13046 on the command line. The package @code{Builder} of this common project, the
13047 "main project" is the one that is considered by @command{gnatmake}.
13048
13049 @noindent
13050 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13051 imported directly or indirectly by the project specified on the command line.
13052 Note that if such a source file is not part of the project specified on the
13053 command line, the ^switches^switches^ found in package @code{Builder} of the
13054 project specified on the command line, if any, that are transmitted
13055 to the compiler will still be used, not those found in the project file of
13056 the source file.
13057
13058 @noindent
13059 When using a project file, you can also invoke @command{gnatmake} without
13060 explicitly specifying any main, and the effect depends on whether you have
13061 defined the @code{Main} attribute.  This attribute has a string list value,
13062 where each element in the list is the name of a source file (the file
13063 extension is optional) that contains a unit that can be a main subprogram.
13064
13065 If the @code{Main} attribute is defined in a project file as a non-empty
13066 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13067 line, then invoking @command{gnatmake} with this project file but without any
13068 main on the command line is equivalent to invoking @command{gnatmake} with all
13069 the file names in the @code{Main} attribute on the command line.
13070
13071 Example:
13072 @smallexample @c projectfile
13073 @group
13074    project Prj is
13075       for Main use ("main1", "main2", "main3");
13076    end Prj;
13077 @end group
13078 @end smallexample
13079
13080 @noindent
13081 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13082 is equivalent to
13083 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
13084
13085 When the project attribute @code{Main} is not specified, or is specified
13086 as an empty string list, or when the switch @option{-u} is used on the command
13087 line, then invoking @command{gnatmake} with no main on the command line will
13088 result in all immediate sources of the project file being checked, and
13089 potentially recompiled. Depending on the presence of the switch @option{-u},
13090 sources from other project files on which the immediate sources of the main
13091 project file depend are also checked and potentially recompiled. In other
13092 words, the @option{-u} switch is applied to all of the immediate sources of the
13093 main project file.
13094
13095 When no main is specified on the command line and attribute @code{Main} exists
13096 and includes several mains, or when several mains are specified on the
13097 command line, the default ^switches^switches^ in package @code{Builder} will
13098 be used for all mains, even if there are specific ^switches^switches^
13099 specified for one or several mains.
13100
13101 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13102 the specific ^switches^switches^ for each main, if they are specified.
13103
13104 @node Library Project Files
13105 @subsubsection Library Project Files
13106
13107 @noindent
13108 When @command{gnatmake} is invoked with a main project file that is a library
13109 project file, it is not allowed to specify one or more mains on the command
13110 line.
13111
13112 @noindent
13113 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13114 ^-l^/ACTION=LINK^ have special meanings.
13115
13116 @itemize @bullet
13117 @item ^-b^/ACTION=BIND^ is only allwed for stand-alone libraries. It indicates
13118 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13119 library.
13120
13121 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13122 to @command{gnatmake} that the binder generated file should be compiled
13123 (in the case of a stand-alone library) and that the library should be built.
13124
13125 @end itemize
13126
13127 @node The GNAT Driver and Project Files
13128 @subsection The GNAT Driver and Project Files
13129
13130 @noindent
13131 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13132 are project-aware:
13133 @command{^gnatbind^gnatbind^},
13134 @command{^gnatfind^gnatfind^},
13135 @command{^gnatlink^gnatlink^},
13136 @command{^gnatls^gnatls^},
13137 @command{^gnatelim^gnatelim^},
13138 @command{^gnatpp^gnatpp^},
13139 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
13140 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13141 They must be invoked through the @command{gnat} driver.
13142
13143 The @command{gnat} driver is a front-end that accepts a number of commands and
13144 call the corresponding tool. It has been designed initially for VMS to convert
13145 VMS style qualifiers to Unix style switches, but it is now available to all
13146 the GNAT supported platforms.
13147
13148 On non VMS platforms, the @command{gnat} driver accepts the following commands
13149 (case insensitive):
13150
13151 @itemize @bullet
13152 @item
13153 BIND to invoke @command{^gnatbind^gnatbind^}
13154 @item
13155 CHOP to invoke @command{^gnatchop^gnatchop^}
13156 @item
13157 CLEAN to invoke @command{^gnatclean^gnatclean^}
13158 @item
13159 COMP or COMPILE to invoke the compiler
13160 @item
13161 ELIM to invoke @command{^gnatelim^gnatelim^}
13162 @item
13163 FIND to invoke @command{^gnatfind^gnatfind^}
13164 @item
13165 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
13166 @item
13167 LINK to invoke @command{^gnatlink^gnatlink^}
13168 @item
13169 LS or LIST to invoke @command{^gnatls^gnatls^}
13170 @item
13171 MAKE to invoke @command{^gnatmake^gnatmake^}
13172 @item
13173 NAME to invoke @command{^gnatname^gnatname^}
13174 @item
13175 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
13176 @item
13177 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
13178 @item
13179 STUB to invoke @command{^gnatstub^gnatstub^}
13180 @item
13181 XREF to invoke @command{^gnatxref^gnatxref^}
13182 @end itemize
13183
13184 @noindent
13185 Note that the compiler is invoked using the command
13186 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}.
13187
13188 @noindent
13189 The command may be followed by switches and arguments for the invoked
13190 tool.
13191
13192 @smallexample
13193   gnat bind -C main.ali
13194   gnat ls -a main
13195   gnat chop foo.txt
13196 @end smallexample
13197
13198 @noindent
13199 Switches may also be put in text files, one switch per line, and the text
13200 files may be specified with their path name preceded by '@@'.
13201
13202 @smallexample
13203    gnat bind @@args.txt main.ali
13204 @end smallexample
13205
13206 @noindent
13207 In addition, for command BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
13208 PP or PRETTY and XREF, the project file related switches
13209 (@option{^-P^/PROJECT_FILE^},
13210 @option{^-X^/EXTERNAL_REFERENCE^} and
13211 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
13212 the switches of the invoking tool.
13213
13214 @noindent
13215 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
13216 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
13217 the immediate sources of the specified project file.
13218
13219 @noindent
13220 For each of these commands, there is optionally a corresponding  package
13221 in the main project.
13222
13223 @itemize @bullet
13224 @item
13225 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
13226
13227 @item
13228 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
13229
13230 @item
13231 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
13232
13233 @item
13234 package @code{Eliminate} for command ELIM (invoking
13235 @code{^gnatelim^gnatelim^})
13236
13237 @item
13238 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
13239
13240 @item
13241 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
13242
13243 @item
13244 package @code{Pretty_Printer} for command PP or PRETTY
13245 (invoking @code{^gnatpp^gnatpp^})
13246
13247 @item
13248 package @code{Cross_Reference} for command XREF (invoking
13249 @code{^gnatxref^gnatxref^})
13250
13251 @end itemize
13252
13253 @noindent
13254 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
13255 a simple variable with a string list value. It contains ^switches^switches^
13256 for the invocation of @code{^gnatls^gnatls^}.
13257
13258 @smallexample @c projectfile
13259 @group
13260 project Proj1 is
13261    package gnatls is
13262       for ^Switches^Switches^
13263           use ("^-a^-a^",
13264                "^-v^-v^");
13265    end gnatls;
13266 end Proj1;
13267 @end group
13268 @end smallexample
13269
13270 @noindent
13271 All other packages have two attribute @code{^Switches^Switches^} and
13272 @code{^Default_Switches^Default_Switches^}.
13273
13274 @noindent
13275 @code{^Switches^Switches^} is an associated array attribute, indexed by the
13276 source file name, that has a string list value: the ^switches^switches^ to be
13277 used when the tool corresponding to the package is invoked for the specific
13278 source file.
13279
13280 @noindent
13281 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
13282 indexed by  the programming language that has a string list value.
13283 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
13284 ^switches^switches^ for the invocation of the tool corresponding
13285 to the package, except if a specific @code{^Switches^Switches^} attribute
13286 is specified for the source file.
13287
13288 @smallexample @c projectfile
13289 @group
13290 project Proj is
13291
13292    for Source_Dirs use ("./**");
13293
13294    package gnatls is
13295       for ^Switches^Switches^ use
13296           ("^-a^-a^",
13297            "^-v^-v^");
13298    end gnatls;
13299 @end group
13300 @group
13301
13302    package Compiler is
13303       for ^Default_Switches^Default_Switches^ ("Ada")
13304           use ("^-gnatv^-gnatv^",
13305                "^-gnatwa^-gnatwa^");
13306    end Binder;
13307 @end group
13308 @group
13309
13310    package Binder is
13311       for ^Default_Switches^Default_Switches^ ("Ada")
13312           use ("^-C^-C^",
13313                "^-e^-e^");
13314    end Binder;
13315 @end group
13316 @group
13317
13318    package Linker is
13319       for ^Default_Switches^Default_Switches^ ("Ada")
13320           use ("^-C^-C^");
13321       for ^Switches^Switches^ ("main.adb")
13322           use ("^-C^-C^",
13323                "^-v^-v^",
13324                "^-v^-v^");
13325    end Linker;
13326 @end group
13327 @group
13328
13329    package Finder is
13330       for ^Default_Switches^Default_Switches^ ("Ada")
13331            use ("^-a^-a^",
13332                 "^-f^-f^");
13333    end Finder;
13334 @end group
13335 @group
13336
13337    package Cross_Reference is
13338       for ^Default_Switches^Default_Switches^ ("Ada")
13339           use ("^-a^-a^",
13340                "^-f^-f^",
13341                "^-d^-d^",
13342                "^-u^-u^");
13343    end Cross_Reference;
13344 end Proj;
13345 @end group
13346 @end smallexample
13347
13348 @noindent
13349 With the above project file, commands such as
13350
13351 @smallexample
13352    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13353    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13354    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13355    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13356    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13357 @end smallexample
13358
13359 @noindent
13360 will set up the environment properly and invoke the tool with the switches
13361 found in the package corresponding to the tool:
13362 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13363 except @code{^Switches^Switches^ ("main.adb")}
13364 for @code{^gnatlink^gnatlink^}.
13365
13366 @ifclear vms
13367 @node Glide and Project Files
13368 @subsection Glide and Project Files
13369
13370 @noindent
13371 Glide will automatically recognize the @file{.gpr} extension for
13372 project files, and will
13373 convert them to its own internal format automatically. However, it
13374 doesn't provide a syntax-oriented editor for modifying these
13375 files.
13376 The project file will be loaded as text when you select the menu item
13377 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
13378 You can edit this text and save the @file{gpr} file;
13379 when you next select this project file in Glide it
13380 will be automatically reloaded.
13381 @end ifclear
13382
13383 @c **********************
13384 @node An Extended Example
13385 @section An Extended Example
13386
13387 @noindent
13388 Suppose that we have two programs, @var{prog1} and @var{prog2},
13389 whose sources are in corresponding directories. We would like
13390 to build them with a single @command{gnatmake} command, and we want to place
13391 their object files into @file{build} subdirectories of the source directories.
13392 Furthermore, we want to have to have two separate subdirectories
13393 in @file{build}  -- @file{release} and @file{debug} -- which will contain
13394 the object files compiled with different set of compilation flags.
13395
13396 In other words, we have the following structure:
13397
13398 @smallexample
13399 @group
13400    main
13401      |- prog1
13402      |    |- build
13403      |         | debug
13404      |         | release
13405      |- prog2
13406           |- build
13407                | debug
13408                | release
13409 @end group
13410 @end smallexample
13411
13412 @noindent
13413 Here are the project files that we must place in a directory @file{main}
13414 to maintain this structure:
13415
13416 @enumerate
13417
13418 @item We create a @code{Common} project with a package @code{Compiler} that
13419 specifies the compilation ^switches^switches^:
13420
13421 @smallexample
13422 File "common.gpr":
13423 @group
13424 @b{project} Common @b{is}
13425
13426    @b{for} Source_Dirs @b{use} (); -- No source files
13427 @end group
13428
13429 @group
13430    @b{type} Build_Type @b{is} ("release", "debug");
13431    Build : Build_Type := External ("BUILD", "debug");
13432 @end group
13433 @group
13434    @b{package} Compiler @b{is}
13435       @b{case} Build @b{is}
13436          @b{when} "release" =>
13437            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13438                    @b{use} ("^-O2^-O2^");
13439          @b{when} "debug"   =>
13440            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13441                    @b{use} ("^-g^-g^");
13442       @b{end case};
13443    @b{end} Compiler;
13444
13445 @b{end} Common;
13446 @end group
13447 @end smallexample
13448
13449 @item We create separate projects for the two programs:
13450
13451 @smallexample
13452 @group
13453 File "prog1.gpr":
13454
13455 @b{with} "common";
13456 @b{project} Prog1 @b{is}
13457
13458     @b{for} Source_Dirs @b{use} ("prog1");
13459     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
13460
13461     @b{package} Compiler @b{renames} Common.Compiler;
13462
13463 @b{end} Prog1;
13464 @end group
13465 @end smallexample
13466
13467 @smallexample
13468 @group
13469 File "prog2.gpr":
13470
13471 @b{with} "common";
13472 @b{project} Prog2 @b{is}
13473
13474     @b{for} Source_Dirs @b{use} ("prog2");
13475     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
13476
13477     @b{package} Compiler @b{renames} Common.Compiler;
13478
13479 @end group
13480 @b{end} Prog2;
13481 @end smallexample
13482
13483 @item We create a wrapping project @code{Main}:
13484
13485 @smallexample
13486 @group
13487 File "main.gpr":
13488
13489 @b{with} "common";
13490 @b{with} "prog1";
13491 @b{with} "prog2";
13492 @b{project} Main @b{is}
13493
13494    @b{package} Compiler @b{renames} Common.Compiler;
13495
13496 @b{end} Main;
13497 @end group
13498 @end smallexample
13499
13500 @item Finally we need to create a dummy procedure that @code{with}s (either
13501 explicitly or implicitly) all the sources of our two programs.
13502
13503 @end enumerate
13504
13505 @noindent
13506 Now we can build the programs using the command
13507
13508 @smallexample
13509    gnatmake ^-P^/PROJECT_FILE=^main dummy
13510 @end smallexample
13511
13512 @noindent
13513 for the Debug mode, or
13514
13515 @ifclear vms
13516 @smallexample
13517    gnatmake -Pmain -XBUILD=release
13518 @end smallexample
13519 @end ifclear
13520
13521 @ifset vms
13522 @smallexample
13523    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
13524 @end smallexample
13525 @end ifset
13526
13527 @noindent
13528 for the Release mode.
13529
13530 @c ********************************
13531 @c * Project File Complete Syntax *
13532 @c ********************************
13533
13534 @node Project File Complete Syntax
13535 @section Project File Complete Syntax
13536
13537 @smallexample
13538 project ::=
13539   context_clause project_declaration
13540
13541 context_clause ::=
13542   @{with_clause@}
13543
13544 with_clause ::=
13545   @b{with} path_name @{ , path_name @} ;
13546
13547 path_name ::=
13548    string_literal
13549
13550 project_declaration ::=
13551   simple_project_declaration | project_extension
13552
13553 simple_project_declaration ::=
13554   @b{project} <project_>simple_name @b{is}
13555     @{declarative_item@}
13556   @b{end} <project_>simple_name;
13557
13558 project_extension ::=
13559   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
13560     @{declarative_item@}
13561   @b{end} <project_>simple_name;
13562
13563 declarative_item ::=
13564   package_declaration |
13565   typed_string_declaration |
13566   other_declarative_item
13567
13568 package_declaration ::=
13569   package_specification | package_renaming
13570
13571 package_specification ::=
13572   @b{package} package_identifier @b{is}
13573     @{simple_declarative_item@}
13574   @b{end} package_identifier ;
13575
13576 package_identifier ::=
13577   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
13578   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
13579   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
13580
13581 package_renaming ::==
13582   @b{package} package_identifier @b{renames}
13583        <project_>simple_name.package_identifier ;
13584
13585 typed_string_declaration ::=
13586   @b{type} <typed_string_>_simple_name @b{is}
13587    ( string_literal @{, string_literal@} );
13588
13589 other_declarative_item ::=
13590   attribute_declaration |
13591   typed_variable_declaration |
13592   variable_declaration |
13593   case_construction
13594
13595 attribute_declaration ::=
13596   full_associative_array_declaration |
13597   @b{for} attribute_designator @b{use} expression ;
13598
13599 full_associative_array_declaration ::=
13600   @b{for} <associative_array_attribute_>simple_name @b{use}
13601   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
13602
13603 attribute_designator ::=
13604   <simple_attribute_>simple_name |
13605   <associative_array_attribute_>simple_name ( string_literal )
13606
13607 typed_variable_declaration ::=
13608   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
13609
13610 variable_declaration ::=
13611   <variable_>simple_name := expression;
13612
13613 expression ::=
13614   term @{& term@}
13615
13616 term ::=
13617   literal_string |
13618   string_list |
13619   <variable_>name |
13620   external_value |
13621   attribute_reference
13622
13623 string_literal ::=
13624   (same as Ada)
13625
13626 string_list ::=
13627   ( <string_>expression @{ , <string_>expression @} )
13628
13629 external_value ::=
13630   @b{external} ( string_literal [, string_literal] )
13631
13632 attribute_reference ::=
13633   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
13634
13635 attribute_prefix ::=
13636   @b{project} |
13637   <project_>simple_name | package_identifier |
13638   <project_>simple_name . package_identifier
13639
13640 case_construction ::=
13641   @b{case} <typed_variable_>name @b{is}
13642     @{case_item@}
13643   @b{end case} ;
13644
13645 case_item ::=
13646   @b{when} discrete_choice_list =>
13647       @{case_construction | attribute_declaration@}
13648
13649 discrete_choice_list ::=
13650   string_literal @{| string_literal@} |
13651   @b{others}
13652
13653 name ::=
13654   simple_name @{. simple_name@}
13655
13656 simple_name ::=
13657   identifier (same as Ada)
13658
13659 @end smallexample
13660
13661
13662 @node The Cross-Referencing Tools gnatxref and gnatfind
13663 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13664 @findex gnatxref
13665 @findex gnatfind
13666
13667 @noindent
13668 The compiler generates cross-referencing information (unless
13669 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13670 This information indicates where in the source each entity is declared and
13671 referenced. Note that entities in package Standard are not included, but
13672 entities in all other predefined units are included in the output.
13673
13674 Before using any of these two tools, you need to compile successfully your
13675 application, so that GNAT gets a chance to generate the cross-referencing
13676 information.
13677
13678 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13679 information to provide the user with the capability to easily locate the
13680 declaration and references to an entity. These tools are quite similar,
13681 the difference being that @code{gnatfind} is intended for locating
13682 definitions and/or references to a specified entity or entities, whereas
13683 @code{gnatxref} is oriented to generating a full report of all
13684 cross-references.
13685
13686 To use these tools, you must not compile your application using the
13687 @option{-gnatx} switch on the @file{gnatmake} command line
13688 (see @ref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
13689 information will not be generated.
13690
13691 @menu
13692 * gnatxref Switches::
13693 * gnatfind Switches::
13694 * Project Files for gnatxref and gnatfind::
13695 * Regular Expressions in gnatfind and gnatxref::
13696 * Examples of gnatxref Usage::
13697 * Examples of gnatfind Usage::
13698 @end menu
13699
13700 @node gnatxref Switches
13701 @section @code{gnatxref} Switches
13702
13703 @noindent
13704 The command invocation for @code{gnatxref} is:
13705 @smallexample
13706 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
13707 @end smallexample
13708
13709 @noindent
13710 where
13711
13712 @table @code
13713 @item sourcefile1, sourcefile2
13714 identifies the source files for which a report is to be generated. The
13715 ``with''ed units will be processed too. You must provide at least one file.
13716
13717 These file names are considered to be regular expressions, so for instance
13718 specifying @file{source*.adb} is the same as giving every file in the current
13719 directory whose name starts with @file{source} and whose extension is
13720 @file{adb}.
13721
13722 @end table
13723
13724 @noindent
13725 The switches can be :
13726 @table @option
13727 @c !sort!
13728 @item ^-a^/ALL_FILES^
13729 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13730 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13731 the read-only files found in the library search path. Otherwise, these files
13732 will be ignored. This option can be used to protect Gnat sources or your own
13733 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13734 much faster, and their output much smaller. Read-only here refers to access
13735 or permissions status in the file system for the current user.
13736
13737 @item -aIDIR
13738 @cindex @option{-aIDIR} (@command{gnatxref})
13739 When looking for source files also look in directory DIR. The order in which
13740 source file search is undertaken is the same as for @file{gnatmake}.
13741
13742 @item -aODIR
13743 @cindex @option{-aODIR} (@command{gnatxref})
13744 When searching for library and object files, look in directory
13745 DIR. The order in which library files are searched is the same as for
13746 @file{gnatmake}.
13747
13748 @item -nostdinc
13749 @cindex @option{-nostdinc} (@command{gnatxref})
13750 Do not look for sources in the system default directory.
13751
13752 @item -nostdlib
13753 @cindex @option{-nostdlib} (@command{gnatxref})
13754 Do not look for library files in the system default directory.
13755
13756 @item --RTS=@var{rts-path}
13757 @cindex @option{--RTS} (@command{gnatxref})
13758 Specifies the default location of the runtime library. Same meaning as the
13759 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13760
13761 @item ^-d^/DERIVED_TYPES^
13762 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
13763 If this switch is set @code{gnatxref} will output the parent type
13764 reference for each matching derived types.
13765
13766 @item ^-f^/FULL_PATHNAME^
13767 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
13768 If this switch is set, the output file names will be preceded by their
13769 directory (if the file was found in the search path). If this switch is
13770 not set, the directory will not be printed.
13771
13772 @item ^-g^/IGNORE_LOCALS^
13773 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
13774 If this switch is set, information is output only for library-level
13775 entities, ignoring local entities. The use of this switch may accelerate
13776 @code{gnatfind} and @code{gnatxref}.
13777
13778 @item -IDIR
13779 @cindex @option{-IDIR} (@command{gnatxref})
13780 Equivalent to @samp{-aODIR -aIDIR}.
13781
13782 @item -pFILE
13783 @cindex @option{-pFILE} (@command{gnatxref})
13784 Specify a project file to use @xref{Project Files}. These project files are
13785 the @file{.adp} files used by Glide. If you need to use the @file{.gpr}
13786 project files, you should use gnatxref through the GNAT driver
13787 (@command{gnat xref -Pproject}).
13788
13789 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13790 project file in the current directory.
13791
13792 If a project file is either specified or found by the tools, then the content
13793 of the source directory and object directory lines are added as if they
13794 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13795 and @samp{^-aO^OBJECT_SEARCH^}.
13796 @item ^-u^/UNUSED^
13797 Output only unused symbols. This may be really useful if you give your
13798 main compilation unit on the command line, as @code{gnatxref} will then
13799 display every unused entity and 'with'ed package.
13800
13801 @ifclear vms
13802 @item -v
13803 Instead of producing the default output, @code{gnatxref} will generate a
13804 @file{tags} file that can be used by vi. For examples how to use this
13805 feature, see @xref{Examples of gnatxref Usage}. The tags file is output
13806 to the standard output, thus you will have to redirect it to a file.
13807 @end ifclear
13808
13809 @end table
13810
13811 @noindent
13812 All these switches may be in any order on the command line, and may even
13813 appear after the file names. They need not be separated by spaces, thus
13814 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13815 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13816
13817 @node gnatfind Switches
13818 @section @code{gnatfind} Switches
13819
13820 @noindent
13821 The command line for @code{gnatfind} is:
13822
13823 @smallexample
13824 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
13825       [file1 file2 ...]
13826 @end smallexample
13827
13828 @noindent
13829 where
13830
13831 @table @code
13832 @item pattern
13833 An entity will be output only if it matches the regular expression found
13834 in @samp{pattern}, see @xref{Regular Expressions in gnatfind and gnatxref}.
13835
13836 Omitting the pattern is equivalent to specifying @samp{*}, which
13837 will match any entity. Note that if you do not provide a pattern, you
13838 have to provide both a sourcefile and a line.
13839
13840 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13841 for matching purposes. At the current time there is no support for
13842 8-bit codes other than Latin-1, or for wide characters in identifiers.
13843
13844 @item sourcefile
13845 @code{gnatfind} will look for references, bodies or declarations
13846 of symbols referenced in @file{sourcefile}, at line @samp{line}
13847 and column @samp{column}. See @pxref{Examples of gnatfind Usage}
13848 for syntax examples.
13849
13850 @item line
13851 is a decimal integer identifying the line number containing
13852 the reference to the entity (or entities) to be located.
13853
13854 @item column
13855 is a decimal integer identifying the exact location on the
13856 line of the first character of the identifier for the
13857 entity reference. Columns are numbered from 1.
13858
13859 @item file1 file2 ...
13860 The search will be restricted to these source files. If none are given, then
13861 the search will be done for every library file in the search path.
13862 These file must appear only after the pattern or sourcefile.
13863
13864 These file names are considered to be regular expressions, so for instance
13865 specifying 'source*.adb' is the same as giving every file in the current
13866 directory whose name starts with 'source' and whose extension is 'adb'.
13867
13868 The location of the spec of the entity will always be displayed, even if it
13869 isn't in one of file1, file2,... The occurrences of the entity in the
13870 separate units of the ones given on the command line will also be displayed.
13871
13872 Note that if you specify at least one file in this part, @code{gnatfind} may
13873 sometimes not be able to find the body of the subprograms...
13874
13875 @end table
13876
13877 @noindent
13878 At least one of 'sourcefile' or 'pattern' has to be present on
13879 the command line.
13880
13881 The following switches are available:
13882 @table @option
13883 @c !sort!
13884
13885 @item ^-a^/ALL_FILES^
13886 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
13887 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13888 the read-only files found in the library search path. Otherwise, these files
13889 will be ignored. This option can be used to protect Gnat sources or your own
13890 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13891 much faster, and their output much smaller. Read-only here refers to access
13892 or permission status in the file system for the current user.
13893
13894 @item -aIDIR
13895 @cindex @option{-aIDIR} (@command{gnatfind})
13896 When looking for source files also look in directory DIR. The order in which
13897 source file search is undertaken is the same as for @file{gnatmake}.
13898
13899 @item -aODIR
13900 @cindex @option{-aODIR} (@command{gnatfind})
13901 When searching for library and object files, look in directory
13902 DIR. The order in which library files are searched is the same as for
13903 @file{gnatmake}.
13904
13905 @item -nostdinc
13906 @cindex @option{-nostdinc} (@command{gnatfind})
13907 Do not look for sources in the system default directory.
13908
13909 @item -nostdlib
13910 @cindex @option{-nostdlib} (@command{gnatfind})
13911 Do not look for library files in the system default directory.
13912
13913 @item --RTS=@var{rts-path}
13914 @cindex @option{--RTS} (@command{gnatfind})
13915 Specifies the default location of the runtime library. Same meaning as the
13916 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13917
13918 @item ^-d^/DERIVED_TYPE_INFORMATION^
13919 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
13920 If this switch is set, then @code{gnatfind} will output the parent type
13921 reference for each matching derived types.
13922
13923 @item ^-e^/EXPRESSIONS^
13924 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
13925 By default, @code{gnatfind} accept the simple regular expression set for
13926 @samp{pattern}. If this switch is set, then the pattern will be
13927 considered as full Unix-style regular expression.
13928
13929 @item ^-f^/FULL_PATHNAME^
13930 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
13931 If this switch is set, the output file names will be preceded by their
13932 directory (if the file was found in the search path). If this switch is
13933 not set, the directory will not be printed.
13934
13935 @item ^-g^/IGNORE_LOCALS^
13936 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
13937 If this switch is set, information is output only for library-level
13938 entities, ignoring local entities. The use of this switch may accelerate
13939 @code{gnatfind} and @code{gnatxref}.
13940
13941 @item -IDIR
13942 @cindex @option{-IDIR} (@command{gnatfind})
13943 Equivalent to @samp{-aODIR -aIDIR}.
13944
13945 @item -pFILE
13946 @cindex @option{-pFILE} (@command{gnatfind})
13947 Specify a project file (@pxref{Project Files}) to use.
13948 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13949 project file in the current directory.
13950
13951 If a project file is either specified or found by the tools, then the content
13952 of the source directory and object directory lines are added as if they
13953 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
13954 @samp{^-aO^/OBJECT_SEARCH^}.
13955
13956 @item ^-r^/REFERENCES^
13957 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
13958 By default, @code{gnatfind} will output only the information about the
13959 declaration, body or type completion of the entities. If this switch is
13960 set, the @code{gnatfind} will locate every reference to the entities in
13961 the files specified on the command line (or in every file in the search
13962 path if no file is given on the command line).
13963
13964 @item ^-s^/PRINT_LINES^
13965 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
13966 If this switch is set, then @code{gnatfind} will output the content
13967 of the Ada source file lines were the entity was found.
13968
13969 @item ^-t^/TYPE_HIERARCHY^
13970 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
13971 If this switch is set, then @code{gnatfind} will output the type hierarchy for
13972 the specified type. It act like -d option but recursively from parent
13973 type to parent type. When this switch is set it is not possible to
13974 specify more than one file.
13975
13976 @end table
13977
13978 @noindent
13979 All these switches may be in any order on the command line, and may even
13980 appear after the file names. They need not be separated by spaces, thus
13981 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13982 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13983
13984 As stated previously, gnatfind will search in every directory in the
13985 search path. You can force it to look only in the current directory if
13986 you specify @code{*} at the end of the command line.
13987
13988 @node Project Files for gnatxref and gnatfind
13989 @section Project Files for @command{gnatxref} and @command{gnatfind}
13990
13991 @noindent
13992 Project files allow a programmer to specify how to compile its
13993 application, where to find sources, etc.  These files are used
13994 @ifclear vms
13995 primarily by the Glide Ada mode, but they can also be used
13996 @end ifclear
13997 by the two tools
13998 @code{gnatxref} and @code{gnatfind}.
13999
14000 A project file name must end with @file{.gpr}. If a single one is
14001 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
14002 extract the information from it. If multiple project files are found, none of
14003 them is read, and you have to use the @samp{-p} switch to specify the one
14004 you want to use.
14005
14006 The following lines can be included, even though most of them have default
14007 values which can be used in most cases.
14008 The lines can be entered in any order in the file.
14009 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
14010 each line. If you have multiple instances, only the last one is taken into
14011 account.
14012
14013 @table @code
14014 @item src_dir=DIR
14015 [default: @code{"^./^[]^"}]
14016 specifies a directory where to look for source files. Multiple @code{src_dir}
14017 lines can be specified and they will be searched in the order they
14018 are specified.
14019
14020 @item obj_dir=DIR
14021 [default: @code{"^./^[]^"}]
14022 specifies a directory where to look for object and library files. Multiple
14023 @code{obj_dir} lines can be specified, and they will be searched in the order
14024 they are specified
14025
14026 @item comp_opt=SWITCHES
14027 [default: @code{""}]
14028 creates a variable which can be referred to subsequently by using
14029 the @code{$@{comp_opt@}} notation. This is intended to store the default
14030 switches given to @command{gnatmake} and @command{gcc}.
14031
14032 @item bind_opt=SWITCHES
14033 [default: @code{""}]
14034 creates a variable which can be referred to subsequently by using
14035 the @samp{$@{bind_opt@}} notation. This is intended to store the default
14036 switches given to @command{gnatbind}.
14037
14038 @item link_opt=SWITCHES
14039 [default: @code{""}]
14040 creates a variable which can be referred to subsequently by using
14041 the @samp{$@{link_opt@}} notation. This is intended to store the default
14042 switches given to @command{gnatlink}.
14043
14044 @item main=EXECUTABLE
14045 [default: @code{""}]
14046 specifies the name of the executable for the application. This variable can
14047 be referred to in the following lines by using the @samp{$@{main@}} notation.
14048
14049 @ifset vms
14050 @item comp_cmd=COMMAND
14051 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
14052 @end ifset
14053 @ifclear vms
14054 @item comp_cmd=COMMAND
14055 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
14056 @end ifclear
14057 specifies the command used to compile a single file in the application.
14058
14059 @ifset vms
14060 @item make_cmd=COMMAND
14061 [default: @code{"GNAT MAKE $@{main@}
14062 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
14063 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
14064 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
14065 @end ifset
14066 @ifclear vms
14067 @item make_cmd=COMMAND
14068 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
14069  -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
14070  -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
14071 @end ifclear
14072 specifies the command used to recompile the whole application.
14073
14074 @item run_cmd=COMMAND
14075 [default: @code{"$@{main@}"}]
14076 specifies the command used to run the application.
14077
14078 @item debug_cmd=COMMAND
14079 [default: @code{"gdb $@{main@}"}]
14080 specifies the command used to debug the application
14081
14082 @end table
14083
14084 @noindent
14085 @command{gnatxref} and @command{gnatfind} only take into account the
14086 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
14087
14088 @node Regular Expressions in gnatfind and gnatxref
14089 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
14090
14091 @noindent
14092 As specified in the section about @command{gnatfind}, the pattern can be a
14093 regular expression. Actually, there are to set of regular expressions
14094 which are recognized by the program :
14095
14096 @table @code
14097 @item globbing patterns
14098 These are the most usual regular expression. They are the same that you
14099 generally used in a Unix shell command line, or in a DOS session.
14100
14101 Here is a more formal grammar :
14102 @smallexample
14103 @group
14104 @iftex
14105 @leftskip=.5cm
14106 @end iftex
14107 regexp ::= term
14108 term   ::= elmt            -- matches elmt
14109 term   ::= elmt elmt       -- concatenation (elmt then elmt)
14110 term   ::= *               -- any string of 0 or more characters
14111 term   ::= ?               -- matches any character
14112 term   ::= [char @{char@}] -- matches any character listed
14113 term   ::= [char - char]   -- matches any character in range
14114 @end group
14115 @end smallexample
14116
14117 @item full regular expression
14118 The second set of regular expressions is much more powerful. This is the
14119 type of regular expressions recognized by utilities such a @file{grep}.
14120
14121 The following is the form of a regular expression, expressed in Ada
14122 reference manual style BNF is as follows
14123
14124 @smallexample
14125 @iftex
14126 @leftskip=.5cm
14127 @end iftex
14128 @group
14129 regexp ::= term @{| term@} -- alternation (term or term ...)
14130
14131 term ::= item @{item@}     -- concatenation (item then item)
14132
14133 item ::= elmt              -- match elmt
14134 item ::= elmt *            -- zero or more elmt's
14135 item ::= elmt +            -- one or more elmt's
14136 item ::= elmt ?            -- matches elmt or nothing
14137 @end group
14138 @group
14139 elmt ::= nschar            -- matches given character
14140 elmt ::= [nschar @{nschar@}]   -- matches any character listed
14141 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
14142 elmt ::= [char - char]     -- matches chars in given range
14143 elmt ::= \ char            -- matches given character
14144 elmt ::= .                 -- matches any single character
14145 elmt ::= ( regexp )        -- parens used for grouping
14146
14147 char ::= any character, including special characters
14148 nschar ::= any character except ()[].*+?^^^
14149 @end group
14150 @end smallexample
14151
14152 Following are a few examples :
14153
14154 @table @samp
14155 @item abcde|fghi
14156 will match any of the two strings 'abcde' and 'fghi'.
14157
14158 @item abc*d
14159 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
14160
14161 @item [a-z]+
14162 will match any string which has only lowercase characters in it (and at
14163 least one character
14164
14165 @end table
14166 @end table
14167
14168 @node Examples of gnatxref Usage
14169 @section Examples of @code{gnatxref} Usage
14170
14171 @subsection General Usage
14172
14173 @noindent
14174 For the following examples, we will consider the following units :
14175
14176 @smallexample @c ada
14177 @group
14178 @cartouche
14179 main.ads:
14180 1: with Bar;
14181 2: package Main is
14182 3:     procedure Foo (B : in Integer);
14183 4:     C : Integer;
14184 5: private
14185 6:     D : Integer;
14186 7: end Main;
14187
14188 main.adb:
14189 1: package body Main is
14190 2:     procedure Foo (B : in Integer) is
14191 3:     begin
14192 4:        C := B;
14193 5:        D := B;
14194 6:        Bar.Print (B);
14195 7:        Bar.Print (C);
14196 8:     end Foo;
14197 9: end Main;
14198
14199 bar.ads:
14200 1: package Bar is
14201 2:     procedure Print (B : Integer);
14202 3: end bar;
14203 @end cartouche
14204 @end group
14205 @end smallexample
14206
14207 @table @code
14208
14209 @noindent
14210 The first thing to do is to recompile your application (for instance, in
14211 that case just by doing a @samp{gnatmake main}, so that GNAT generates
14212 the cross-referencing information.
14213 You can then issue any of the following commands:
14214
14215 @item gnatxref main.adb
14216 @code{gnatxref} generates cross-reference information for main.adb
14217 and every unit 'with'ed by main.adb.
14218
14219 The output would be:
14220 @smallexample
14221 @iftex
14222 @leftskip=0cm
14223 @end iftex
14224 B                                                      Type: Integer
14225   Decl: bar.ads           2:22
14226 B                                                      Type: Integer
14227   Decl: main.ads          3:20
14228   Body: main.adb          2:20
14229   Ref:  main.adb          4:13     5:13     6:19
14230 Bar                                                    Type: Unit
14231   Decl: bar.ads           1:9
14232   Ref:  main.adb          6:8      7:8
14233        main.ads           1:6
14234 C                                                      Type: Integer
14235   Decl: main.ads          4:5
14236   Modi: main.adb          4:8
14237   Ref:  main.adb          7:19
14238 D                                                      Type: Integer
14239   Decl: main.ads          6:5
14240   Modi: main.adb          5:8
14241 Foo                                                    Type: Unit
14242   Decl: main.ads          3:15
14243   Body: main.adb          2:15
14244 Main                                                    Type: Unit
14245   Decl: main.ads          2:9
14246   Body: main.adb          1:14
14247 Print                                                   Type: Unit
14248   Decl: bar.ads           2:15
14249   Ref:  main.adb          6:12     7:12
14250 @end smallexample
14251
14252 @noindent
14253 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
14254 its body is in main.adb, line 1, column 14 and is not referenced any where.
14255
14256 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
14257 it referenced in main.adb, line 6 column 12 and line 7 column 12.
14258
14259 @item gnatxref package1.adb package2.ads
14260 @code{gnatxref} will generates cross-reference information for
14261 package1.adb, package2.ads and any other package 'with'ed by any
14262 of these.
14263
14264 @end table
14265
14266 @ifclear vms
14267 @subsection Using gnatxref with vi
14268
14269 @code{gnatxref} can generate a tags file output, which can be used
14270 directly from @file{vi}. Note that the standard version of @file{vi}
14271 will not work properly with overloaded symbols. Consider using another
14272 free implementation of @file{vi}, such as @file{vim}.
14273
14274 @smallexample
14275 $ gnatxref -v gnatfind.adb > tags
14276 @end smallexample
14277
14278 @noindent
14279 will generate the tags file for @code{gnatfind} itself (if the sources
14280 are in the search path!).
14281
14282 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
14283 (replacing @i{entity} by whatever you are looking for), and vi will
14284 display a new file with the corresponding declaration of entity.
14285 @end ifclear
14286
14287 @node Examples of gnatfind Usage
14288 @section Examples of @code{gnatfind} Usage
14289
14290 @table @code
14291
14292 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
14293 Find declarations for all entities xyz referenced at least once in
14294 main.adb. The references are search in every library file in the search
14295 path.
14296
14297 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14298 switch is set)
14299
14300 The output will look like:
14301 @smallexample
14302 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14303 ^directory/^[directory]^main.adb:24:10: xyz <= body
14304 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14305 @end smallexample
14306
14307 @noindent
14308 that is to say, one of the entities xyz found in main.adb is declared at
14309 line 12 of main.ads (and its body is in main.adb), and another one is
14310 declared at line 45 of foo.ads
14311
14312 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14313 This is the same command as the previous one, instead @code{gnatfind} will
14314 display the content of the Ada source file lines.
14315
14316 The output will look like:
14317
14318 @smallexample
14319 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14320    procedure xyz;
14321 ^directory/^[directory]^main.adb:24:10: xyz <= body
14322    procedure xyz is
14323 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14324    xyz : Integer;
14325 @end smallexample
14326
14327 @noindent
14328 This can make it easier to find exactly the location your are looking
14329 for.
14330
14331 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14332 Find references to all entities containing an x that are
14333 referenced on line 123 of main.ads.
14334 The references will be searched only in main.ads and foo.adb.
14335
14336 @item gnatfind main.ads:123
14337 Find declarations and bodies for all entities that are referenced on
14338 line 123 of main.ads.
14339
14340 This is the same as @code{gnatfind "*":main.adb:123}.
14341
14342 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14343 Find the declaration for the entity referenced at column 45 in
14344 line 123 of file main.adb in directory mydir. Note that it
14345 is usual to omit the identifier name when the column is given,
14346 since the column position identifies a unique reference.
14347
14348 The column has to be the beginning of the identifier, and should not
14349 point to any character in the middle of the identifier.
14350
14351 @end table
14352
14353
14354 @c *********************************
14355 @node The GNAT Pretty-Printer gnatpp
14356 @chapter The GNAT Pretty-Printer @command{gnatpp}
14357 @findex gnatpp
14358 @cindex Pretty-Printer
14359
14360 @noindent
14361 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
14362 for source reformatting / pretty-printing.
14363 It takes an Ada source file as input and generates a reformatted
14364 version as output.
14365 You can specify various style directives via switches; e.g.,
14366 identifier case conventions, rules of indentation, and comment layout.
14367
14368 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
14369 tree for the input source and thus requires the input to be syntactically and
14370 semantically legal.
14371 If this condition is not met, @command{gnatpp} will terminate with an
14372 error message; no output file will be generated.
14373
14374 If the compilation unit
14375 contained in the input source depends semantically upon units located
14376 outside the current directory, you have to provide the source search path
14377 when invoking @command{gnatpp}; see the description of the @command{gnatpp}
14378 switches below.
14379
14380 The @command{gnatpp} command has the form
14381
14382 @smallexample
14383 $ gnatpp [@var{switches}] @var{filename}
14384 @end smallexample
14385
14386 @noindent
14387 where
14388 @itemize @bullet
14389 @item
14390 @var{switches} is an optional sequence of switches defining such properties as
14391 the formatting rules, the source search path, and the destination for the
14392 output source file
14393
14394 @item
14395 @var{filename} is the name (including the extension) of the source file to
14396 reformat; ``wildcards'' or several file names on the same gnatpp command are
14397 allowed.  The file name may contain path information; it does not have to follow
14398 the GNAT file naming rules
14399 @end itemize
14400
14401
14402 @menu
14403 * Switches for gnatpp::
14404 * Formatting Rules::
14405 @end menu
14406
14407 @node Switches for gnatpp
14408 @section Switches for @command{gnatpp}
14409
14410 @noindent
14411 The following subsections describe the various switches accepted by
14412 @command{gnatpp}, organized by category.
14413
14414 @ifclear vms
14415 You specify a switch by supplying a name and generally also a value.
14416 In many cases the values for a switch with a given name are incompatible with
14417 each other
14418 (for example the switch that controls the casing of a reserved word may have
14419 exactly one value: upper case, lower case, or
14420 mixed case) and thus exactly one such switch can be in effect for an
14421 invocation of @command{gnatpp}.
14422 If more than one is supplied, the last one is used.
14423 However, some values for the same switch are mutually compatible.
14424 You may supply several such switches to @command{gnatpp}, but then
14425 each must be specified in full, with both the name and the value.
14426 Abbreviated forms (the name appearing once, followed by each value) are
14427 not permitted.
14428 For example, to set
14429 the alignment of the assignment delimiter both in declarations and in
14430 assignment statements, you must write @option{-A2A3}
14431 (or @option{-A2 -A3}), but not @option{-A23}.
14432 @end ifclear
14433
14434 @ifset vms
14435 In many cases the set of options for a given qualifier are incompatible with
14436 each other (for example the qualifier that controls the casing of a reserved
14437 word may have exactly one option, which specifies either upper case, lower
14438 case, or mixed case), and thus exactly one such option can be in effect for
14439 an invocation of @command{gnatpp}.
14440 If more than one is supplied, the last one is used.
14441 However, some qualifiers have options that are mutually compatible,
14442 and then you may then supply several such options when invoking
14443 @command{gnatpp}.
14444 @end ifset
14445
14446 In most cases, it is obvious whether or not the
14447 ^values for a switch with a given name^options for a given qualifier^
14448 are compatible with each other.
14449 When the semantics might not be evident, the summaries below explicitly
14450 indicate the effect.
14451
14452 @menu
14453 * Alignment Control::
14454 * Casing Control::
14455 * Construct Layout Control::
14456 * General Text Layout Control::
14457 * Other Formatting Options::
14458 * Setting the Source Search Path::
14459 * Output File Control::
14460 * Other gnatpp Switches::
14461 @end menu
14462
14463
14464 @node Alignment Control
14465 @subsection Alignment Control
14466 @cindex Alignment control in @command{gnatpp}
14467
14468 @noindent
14469 Programs can be easier to read if certain constructs are vertically aligned.
14470 By default all alignments are set ON.
14471 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
14472 OFF, and then use one or more of the other
14473 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
14474 to activate alignment for specific constructs.
14475
14476 @table @option
14477 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
14478
14479 @ifset vms
14480 @item /ALIGN=ON
14481 Set all alignments to ON
14482 @end ifset
14483
14484 @item ^-A0^/ALIGN=OFF^
14485 Set all alignments to OFF
14486
14487 @item ^-A1^/ALIGN=COLONS^
14488 Align @code{:} in declarations
14489
14490 @item ^-A2^/ALIGN=DECLARATIONS^
14491 Align @code{:=} in initializations in declarations
14492
14493 @item ^-A3^/ALIGN=STATEMENTS^
14494 Align @code{:=} in assignment statements
14495
14496 @item ^-A4^/ALIGN=ARROWS^
14497 Align @code{=>} in associations
14498 @end table
14499
14500 @noindent
14501 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
14502 is allowed.
14503
14504
14505 @node Casing Control
14506 @subsection Casing Control
14507 @cindex Casing control in @command{gnatpp}
14508
14509 @noindent
14510 @command{gnatpp} allows you to specify the casing for reserved words,
14511 pragma names, attribute designators and identifiers.
14512 For identifiers you may define a
14513 general rule for name casing but also override this rule
14514 via a set of dictionary files.
14515
14516 Three types of casing are supported: lower case, upper case, and mixed case.
14517 Lower and upper case are self-explanatory (but since some letters in
14518 Latin1 and other GNAT-supported character sets
14519 exist only in lower-case form, an upper case conversion will have no
14520 effect on them.)
14521 ``Mixed case'' means that the first letter, and also each letter immediately
14522 following an underscore, are converted to their uppercase forms;
14523 all the other letters are converted to their lowercase forms.
14524
14525 @table @option
14526 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
14527 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14528 Attribute designators are lower case
14529
14530 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14531 Attribute designators are upper case
14532
14533 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14534 Attribute designators are mixed case (this is the default)
14535
14536 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14537 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14538 Keywords (technically, these are known in Ada as @emph{reserved words}) are
14539 lower case (this is the default)
14540
14541 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14542 Keywords are upper case
14543
14544 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14545 @item ^-nD^/NAME_CASING=AS_DECLARED^
14546 Name casing for defining occurrences are as they appear in the source file
14547 (this is the default)
14548
14549 @item ^-nU^/NAME_CASING=UPPER_CASE^
14550 Names are in upper case
14551
14552 @item ^-nL^/NAME_CASING=LOWER_CASE^
14553 Names are in lower case
14554
14555 @item ^-nM^/NAME_CASING=MIXED_CASE^
14556 Names are in mixed case
14557
14558 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14559 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14560 Pragma names are lower case
14561
14562 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14563 Pragma names are upper case
14564
14565 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14566 Pragma names are mixed case (this is the default)
14567
14568 @item ^-D@var{file}^/DICTIONARY=@var{file}^
14569 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14570 Use @var{file} as a @emph{dictionary file} that defines
14571 the casing for a set of specified names,
14572 thereby overriding the effect on these names by
14573 any explicit or implicit
14574 ^-n^/NAME_CASING^ switch.
14575 To supply more than one dictionary file,
14576 use ^several @option{-D} switches^a list of files as options^.
14577
14578 @noindent
14579 @option{gnatpp} implicitly uses a @emph{default dictionary file}
14580 to define the casing for the Ada predefined names and
14581 the names declared in the GNAT libraries.
14582
14583 @item ^-D-^/SPECIFIC_CASING^
14584 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14585 Do not use the default dictionary file;
14586 instead, use the casing
14587 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14588 dictionary file(s)
14589 @end table
14590
14591 @noindent
14592 The structure of a dictionary file, and details on the conventions
14593 used in the default dictionary file, are defined in @ref{Name Casing}.
14594
14595 The @option{^-D-^/SPECIFIC_CASING^} and
14596 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14597 compatible.
14598
14599
14600 @node Construct Layout Control
14601 @subsection Construct Layout Control
14602 @cindex Layout control in @command{gnatpp}
14603
14604 @noindent
14605 This group of @command{gnatpp} switches controls the layout of comments and
14606 complex syntactic constructs.  See @ref{Formatting Comments}, for details
14607 on their effect.
14608
14609 @table @option
14610 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14611 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14612 GNAT-style comment line indentation (this is the default).
14613
14614 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
14615 Reference-manual comment line indentation.
14616
14617 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14618 GNAT-style comment beginning
14619
14620 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14621 Reformat comment blocks
14622
14623 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
14624 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
14625 GNAT-style layout (this is the default)
14626
14627 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
14628 Compact layout
14629
14630 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
14631 Uncompact layout
14632
14633 @item ^-notab^/NOTABS^
14634 All the VT characters are removed from the comment text. All the HT characters are
14635 expanded with the sequences of space characters to get to the next tab stops.
14636
14637 @end table
14638
14639 @ifclear vms
14640 @noindent
14641 The @option{-c1} and @option{-c2} switches are incompatible.
14642 The @option{-c3} and @option{-c4} switches are compatible with each other and
14643 also with @option{-c1} and @option{-c2}.
14644
14645 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
14646 @end ifclear
14647
14648 @ifset vms
14649 @noindent
14650 For the @option{/COMMENTS_LAYOUT} qualifier:
14651 @itemize @bullet
14652 @item
14653 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
14654 @item
14655 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
14656 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
14657 @end itemize
14658
14659 @noindent
14660 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
14661 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
14662 @end ifset
14663
14664 @node General Text Layout Control
14665 @subsection General Text Layout Control
14666
14667 @noindent
14668 These switches allow control over line length and indentation.
14669
14670 @table @option
14671 @item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^
14672 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14673 Maximum line length, @i{nnn} from 32 ..256, the default value is 79
14674
14675 @item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^
14676 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14677 Indentation level, @i{nnn} from 1 .. 9, the default value is 3
14678
14679 @item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^
14680 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14681 Indentation level for continuation lines (relative to the line being
14682 continued), @i{nnn} from 1 .. 9.
14683 The default
14684 value is one less then the (normal) indentation level, unless the
14685 indentation is set to 1 (in which case the default value for continuation
14686 line indentation is also 1)
14687 @end table
14688
14689
14690 @node Other Formatting Options
14691 @subsection Other Formatting Options
14692
14693 @noindent
14694 These switches control the inclusion of missing end/exit labels, and
14695 the indentation level in @b{case} statements.
14696
14697 @table @option
14698 @item ^-e^/NO_MISSED_LABELS^
14699 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
14700 Do not insert missing end/exit labels. An end label is the name of
14701 a construct that may optionally be repeated at the end of the
14702 construct's declaration;
14703 e.g., the names of packages, subprograms, and tasks.
14704 An exit label is the name of a loop that may appear as target
14705 of an exit statement within the loop.
14706 By default, @command{gnatpp} inserts these end/exit labels when
14707 they are absent from the original source. This option suppresses such
14708 insertion, so that the formatted source reflects the original.
14709
14710 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14711 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14712 Insert a Form Feed character after a pragma Page.
14713
14714 @item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^
14715 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
14716 Do not use an additional indentation level for @b{case} alternatives
14717 and variants if there are @i{nnn} or more (the default
14718 value is 10).
14719 If @i{nnn} is 0, an additional indentation level is
14720 used for @b{case} alternatives and variants regardless of their number.
14721 @end table
14722
14723 @node Setting the Source Search Path
14724 @subsection Setting the Source Search Path
14725
14726 @noindent
14727 To define the search path for the input source file, @command{gnatpp}
14728 uses the same switches as the GNAT compiler, with the same effects.
14729
14730 @table @option
14731 @item ^-I^/SEARCH=^@var{dir}
14732 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
14733 The same as the corresponding gcc switch
14734
14735 @item ^-I-^/NOCURRENT_DIRECTORY^
14736 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
14737 The same as the corresponding gcc switch
14738
14739 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
14740 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
14741 The same as the corresponding gcc switch
14742
14743 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
14744 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
14745 The same as the corresponding gcc switch
14746
14747 @end table
14748
14749
14750 @node Output File Control
14751 @subsection Output File Control
14752
14753 @noindent
14754 By default the output is sent to the file whose name is obtained by appending
14755 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
14756 (if the file with this name already exists, it is unconditionally overwritten).
14757 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
14758 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
14759 as output file.
14760 The output may be redirected by the following switches:
14761
14762 @table @option
14763 @item ^-pipe^/STANDARD_OUTPUT^
14764 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
14765 Send the output to @code{Standard_Output}
14766
14767 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
14768 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
14769 Write the output into @var{output_file}.
14770 If @var{output_file} already exists, @command{gnatpp} terminates without
14771 reading or processing the input file.
14772
14773 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
14774 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
14775 Write the output into @var{output_file}, overwriting the existing file
14776 (if one is present).
14777
14778 @item ^-r^/REPLACE^
14779 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
14780 Replace the input source file with the reformatted output, and copy the
14781 original input source into the file whose name is obtained by appending the
14782 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
14783 If a file with this name already exists, @command{gnatpp} terminates without
14784 reading or processing the input file.
14785
14786 @item ^-rf^/OVERRIDING_REPLACE^
14787 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
14788 Like @option{^-r^/REPLACE^} except that if the file with the specified name
14789 already exists, it is overwritten.
14790 @end table
14791
14792 @noindent
14793 Options @option{^-pipe^/STANDARD_OUTPUT^},
14794 @option{^-o^/OUTPUT^} and
14795 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
14796 contains only one file to reformat
14797
14798 @node Other gnatpp Switches
14799 @subsection Other @code{gnatpp} Switches
14800
14801 @noindent
14802 The additional @command{gnatpp} switches are defined in this subsection.
14803
14804 @table @option
14805 @item ^-v^/VERBOSE^
14806 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
14807 Verbose mode;
14808 @command{gnatpp} generates version information and then
14809 a trace of the actions it takes to produce or obtain the ASIS tree.
14810
14811 @item ^-w^/WARNINGS^
14812 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
14813 Warning mode;
14814 @command{gnatpp} generates a warning whenever it can not provide
14815 a required layout in the result source.
14816 @end table
14817
14818
14819 @node Formatting Rules
14820 @section Formatting Rules
14821
14822 @noindent
14823 The following subsections show how @command{gnatpp} treats ``white space'',
14824 comments, program layout, and name casing.
14825 They provide the detailed descriptions of the switches shown above.
14826
14827 @menu
14828 * White Space and Empty Lines::
14829 * Formatting Comments::
14830 * Construct Layout::
14831 * Name Casing::
14832 @end menu
14833
14834
14835 @node White Space and Empty Lines
14836 @subsection White Space and Empty Lines
14837
14838 @noindent
14839 @command{gnatpp} does not have an option to control space characters.
14840 It will add or remove spaces according to the style illustrated by the
14841 examples in the @cite{Ada Reference Manual}.
14842
14843 The only format effectors
14844 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
14845 that will appear in the output file are platform-specific line breaks,
14846 and also format effectors within (but not at the end of) comments.
14847 In particular, each horizontal tab character that is not inside
14848 a comment will be treated as a space and thus will appear in the
14849 output file as zero or more spaces depending on
14850 the reformatting of the line in which it appears.
14851 The only exception is a Form Feed character, which is inserted after a
14852 pragma @code{Page} when @option{-ff} is set.
14853
14854 The output file will contain no lines with trailing ``white space'' (spaces,
14855 format effectors).
14856
14857 Empty lines in the original source are preserved
14858 only if they separate declarations or statements.
14859 In such contexts, a
14860 sequence of two or more empty lines is replaced by exactly one empty line.
14861 Note that a blank line will be removed if it separates two ``comment blocks''
14862 (a comment block is a sequence of whole-line comments).
14863 In order to preserve a visual separation between comment blocks, use an
14864 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
14865 Likewise, if for some reason you wish to have a sequence of empty lines,
14866 use a sequence of empty comments instead.
14867
14868
14869 @node Formatting Comments
14870 @subsection Formatting Comments
14871
14872 @noindent
14873 Comments in Ada code are of two kinds:
14874 @itemize @bullet
14875 @item
14876 a @emph{whole-line comment}, which appears by itself (possibly preceded by
14877 ``white space'') on a line
14878
14879 @item
14880 an @emph{end-of-line comment}, which follows some other Ada lexical element
14881 on the same line.
14882 @end itemize
14883
14884 @noindent
14885 The indentation of a whole-line comment is that of either
14886 the preceding or following line in
14887 the formatted source, depending on switch settings as will be described below.
14888
14889 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
14890 between the end of the preceding Ada lexical element and the beginning
14891 of the comment as appear in the original source,
14892 unless either the comment has to be split to
14893 satisfy the line length limitation, or else the next line contains a
14894 whole line comment that is considered a continuation of this end-of-line
14895 comment (because it starts at the same position).
14896 In the latter two
14897 cases, the start of the end-of-line comment is moved right to the nearest
14898 multiple of the indentation level.
14899 This may result in a ``line overflow'' (the right-shifted comment extending
14900 beyond the maximum line length), in which case the comment is split as
14901 described below.
14902
14903 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
14904 (GNAT-style comment line indentation)
14905 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
14906 (reference-manual comment line indentation).
14907 With reference-manual style, a whole-line comment is indented as if it
14908 were a declaration or statement at the same place
14909 (i.e., according to the indentation of the preceding line(s)).
14910 With GNAT style, a whole-line comment that is immediately followed by an
14911 @b{if} or @b{case} statement alternative, a record variant, or the reserved
14912 word @b{begin}, is indented based on the construct that follows it.
14913
14914 For example:
14915 @smallexample @c ada
14916 @cartouche
14917 if A then
14918     null;
14919        -- some comment
14920 else
14921    null;
14922 end if;
14923 @end cartouche
14924 @end smallexample
14925
14926 @noindent
14927 Reference-manual indentation produces:
14928
14929 @smallexample @c ada
14930 @cartouche
14931 if A then
14932    null;
14933    --  some comment
14934 else
14935    null;
14936 end if;
14937 @end cartouche
14938 @end smallexample
14939
14940 @noindent
14941 while GNAT-style indentation produces:
14942
14943 @smallexample @c ada
14944 @cartouche
14945 if A then
14946    null;
14947 --  some comment
14948 else
14949    null;
14950 end if;
14951 @end cartouche
14952 @end smallexample
14953
14954 @noindent
14955 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
14956 (GNAT style comment beginning) has the following
14957 effect:
14958
14959 @itemize @bullet
14960 @item
14961 For each whole-line comment that does not end with two hyphens,
14962 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
14963 to ensure that there are at least two spaces between these hyphens and the
14964 first non-blank character of the comment.
14965 @end itemize
14966
14967 @noindent
14968 For an end-of-line comment, if in the original source the next line is a
14969 whole-line comment that starts at the same position
14970 as the end-of-line comment,
14971 then the whole-line comment (and all whole-line comments
14972 that follow it and that start at the same position)
14973 will start at this position in the output file.
14974
14975 @noindent
14976 That is, if in the original source we have:
14977
14978 @smallexample @c ada
14979 @cartouche
14980 begin
14981 A := B + C;            --  B must be in the range Low1..High1
14982                        --  C must be in the range Low2..High2
14983              --B+C will be in the range Low1+Low2..High1+High2
14984 X := X + 1;
14985 @end cartouche
14986 @end smallexample
14987
14988 @noindent
14989 Then in the formatted source we get
14990
14991 @smallexample @c ada
14992 @cartouche
14993 begin
14994    A := B + C;            --  B must be in the range Low1..High1
14995                           --  C must be in the range Low2..High2
14996    --  B+C will be in the range Low1+Low2..High1+High2
14997    X := X + 1;
14998 @end cartouche
14999 @end smallexample
15000
15001 @noindent
15002 A comment that exceeds the line length limit will be split.
15003 Unless switch
15004 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
15005 the line belongs to a reformattable block, splitting the line generates a
15006 @command{gnatpp} warning.
15007 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
15008 comments may be reformatted in typical
15009 word processor style (that is, moving words between lines and putting as
15010 many words in a line as possible).
15011
15012
15013 @node Construct Layout
15014 @subsection Construct Layout
15015
15016 @noindent
15017 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
15018 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
15019 layout on the one hand, and uncompact layout
15020 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
15021 can be illustrated by the following examples:
15022
15023 @iftex
15024 @cartouche
15025 @multitable @columnfractions .5 .5
15026 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
15027
15028 @item
15029 @smallexample @c ada
15030 type q is record
15031    a : integer;
15032    b : integer;
15033 end record;
15034 @end smallexample
15035 @tab
15036 @smallexample @c ada
15037 type q is
15038    record
15039       a : integer;
15040       b : integer;
15041    end record;
15042 @end smallexample
15043
15044 @item
15045 @smallexample @c ada
15046 Block : declare
15047    A : Integer := 3;
15048 begin
15049    Proc (A, A);
15050 end Block;
15051 @end smallexample
15052 @tab
15053 @smallexample @c ada
15054 Block :
15055    declare
15056       A : Integer := 3;
15057    begin
15058       Proc (A, A);
15059    end Block;
15060 @end smallexample
15061
15062 @item
15063 @smallexample @c ada
15064 Clear : for J in 1 .. 10 loop
15065    A (J) := 0;
15066 end loop Clear;
15067 @end smallexample
15068 @tab
15069 @smallexample @c ada
15070 Clear :
15071    for J in 1 .. 10 loop
15072       A (J) := 0;
15073    end loop Clear;
15074 @end smallexample
15075 @end multitable
15076 @end cartouche
15077 @end iftex
15078
15079 @ifnottex
15080 @smallexample
15081 @cartouche
15082 GNAT style, compact layout              Uncompact layout
15083
15084 type q is record                        type q is
15085    a : integer;                            record
15086    b : integer;                               a : integer;
15087 end record;                                   b : integer;
15088                                            end record;
15089
15090
15091 Block : declare                         Block :
15092    A : Integer := 3;                       declare
15093 begin                                         A : Integer := 3;
15094    Proc (A, A);                            begin
15095 end Block;                                    Proc (A, A);
15096                                            end Block;
15097
15098 Clear : for J in 1 .. 10 loop           Clear :
15099    A (J) := 0;                             for J in 1 .. 10 loop
15100 end loop Clear;                               A (J) := 0;
15101                                            end loop Clear;
15102 @end cartouche
15103 @end smallexample
15104 @end ifnottex
15105
15106 @noindent
15107 A further difference between GNAT style layout and compact layout is that
15108 GNAT style layout inserts empty lines as separation for
15109 compound statements, return statements and bodies.
15110
15111
15112 @node Name Casing
15113 @subsection Name Casing
15114
15115 @noindent
15116 @command{gnatpp} always converts the usage occurrence of a (simple) name to
15117 the same casing as the corresponding defining identifier.
15118
15119 You control the casing for defining occurrences via the
15120 @option{^-n^/NAME_CASING^} switch.
15121 @ifclear vms
15122 With @option{-nD} (``as declared'', which is the default),
15123 @end ifclear
15124 @ifset vms
15125 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
15126 @end ifset
15127 defining occurrences appear exactly as in the source file
15128 where they are declared.
15129 The other ^values for this switch^options for this qualifier^ ---
15130 @option{^-nU^UPPER_CASE^},
15131 @option{^-nL^LOWER_CASE^},
15132 @option{^-nM^MIXED_CASE^} ---
15133 result in
15134 ^upper, lower, or mixed case, respectively^the corresponding casing^.
15135 If @command{gnatpp} changes the casing of a defining
15136 occurrence, it analogously changes the casing of all the
15137 usage occurrences of this name.
15138
15139 If the defining occurrence of a name is not in the source compilation unit
15140 currently being processed by @command{gnatpp}, the casing of each reference to
15141 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
15142 switch (subject to the dictionary file mechanism described below).
15143 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
15144 had affected the
15145 casing for the defining occurrence of the name.
15146
15147 Some names may need to be spelled with casing conventions that are not
15148 covered by the upper-, lower-, and mixed-case transformations.
15149 You can arrange correct casing by placing such names in a
15150 @emph{dictionary file},
15151 and then supplying a @option{^-D^/DICTIONARY^} switch.
15152 The casing of names from dictionary files overrides
15153 any @option{^-n^/NAME_CASING^} switch.
15154
15155 To handle the casing of Ada predefined names and the names from GNAT libraries,
15156 @command{gnatpp} assumes a default dictionary file.
15157 The name of each predefined entity is spelled with the same casing as is used
15158 for the entity in the @cite{Ada Reference Manual}.
15159 The name of each entity in the GNAT libraries is spelled with the same casing
15160 as is used in the declaration of that entity.
15161
15162 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
15163 default dictionary file.
15164 Instead, the casing for predefined and GNAT-defined names will be established
15165 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
15166 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
15167 will appear as just shown,
15168 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
15169 To ensure that even such names are rendered in uppercase,
15170 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
15171 (or else, less conveniently, place these names in upper case in a dictionary
15172 file).
15173
15174 A dictionary file is
15175 a plain text file; each line in this file can be either a blank line
15176 (containing only space characters and ASCII.HT characters), an Ada comment
15177 line, or the specification of exactly one @emph{casing schema}.
15178
15179 A casing schema is a string that has the following syntax:
15180
15181 @smallexample
15182 @cartouche
15183   @var{casing_schema} ::= @var{identifier} | [*]@var{simple_identifier}[*]
15184
15185   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
15186 @end cartouche
15187 @end smallexample
15188
15189 @noindent
15190 (The @code{[]} metanotation stands for an optional part;
15191 see @cite{Ada Reference Manual}, Section 2.3) for the definition of the
15192 @var{identifier} lexical element and the @var{letter_or_digit} category).
15193
15194 The casing schema string can be followed by white space and/or an Ada-style
15195 comment; any amount of white space is allowed before the string.
15196
15197 If a dictionary file is passed as
15198 @ifclear vms
15199 the value of a @option{-D@var{file}} switch
15200 @end ifclear
15201 @ifset vms
15202 an option to the @option{/DICTIONARY} qualifier
15203 @end ifset
15204 then for every
15205 simple name and every identifier, @command{gnatpp} checks if the dictionary
15206 defines the casing for the name or for some of its parts (the term ``subword''
15207 is used below to denote the part of a name which is delimited by ``_'' or by
15208 the beginning or end of the word and which does not contain any ``_'' inside):
15209
15210 @itemize @bullet
15211 @item
15212 if the whole name is in the dictionary, @command{gnatpp} uses for this name
15213 the casing defined by the dictionary; no subwords are checked for this word
15214
15215 @item
15216 for the first subword (that is, for the subword preceding the leftmost
15217 ``_''), @command{gnatpp} checks if the dictionary contains the corresponding
15218 string of the form @code{@var{simple_identifier}*}, and if it does, the
15219 casing of this @var{simple_identifier} is used for this subword
15220
15221 @item
15222 for the last subword (following the rightmost ``_'') @command{gnatpp}
15223 checks if the dictionary contains the corresponding string of the form
15224 @code{*@var{simple_identifier}}, and if it does, the casing of this
15225 @var{simple_identifier} is used for this subword
15226
15227 @item
15228 for every intermediate subword (surrounded by two'_') @command{gnatpp} checks
15229 if the dictionary contains the corresponding string of the form
15230 @code{*@var{simple_identifier}*}, and if it does, the casing of this
15231 simple_identifier is used for this subword
15232
15233 @item
15234 if more than one dictionary file is passed as @command{gnatpp} switches, each
15235 dictionary adds new casing exceptions and overrides all the existing casing
15236 exceptions set by the previous dictionaries
15237
15238 @item
15239 when @command{gnatpp} checks if the word or subword is in the dictionary,
15240 this check is not case sensitive
15241 @end itemize
15242
15243 @noindent
15244 For example, suppose we have the following source to reformat:
15245
15246 @smallexample @c ada
15247 @cartouche
15248 procedure test is
15249    name1 : integer := 1;
15250    name4_name3_name2 : integer := 2;
15251    name2_name3_name4 : Boolean;
15252    name1_var : Float;
15253 begin
15254    name2_name3_name4 := name4_name3_name2 > name1;
15255 end;
15256 @end cartouche
15257 @end smallexample
15258
15259 @noindent
15260 And suppose we have two dictionaries:
15261
15262 @smallexample
15263 @cartouche
15264 @i{dict1:}
15265    NAME1
15266    *NaMe3*
15267    *NAME2
15268 @end cartouche
15269
15270 @cartouche
15271 @i{dict2:}
15272   *NAME3*
15273 @end cartouche
15274 @end smallexample
15275
15276 @noindent
15277 If @command{gnatpp} is called with the following switches:
15278
15279 @smallexample
15280 @ifclear vms
15281 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
15282 @end ifclear
15283 @ifset vms
15284 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
15285 @end ifset
15286 @end smallexample
15287
15288 @noindent
15289 then we will get the following name casing in the @command{gnatpp} output:
15290
15291 @smallexample @c ada
15292 @cartouche
15293 procedure Test is
15294    NAME1             : Integer := 1;
15295    Name4_NAME3_NAME2 : integer := 2;
15296    Name2_NAME3_Name4 : Boolean;
15297    Name1_Var         : Float;
15298 begin
15299    Name2_NAME3_Name4 := Name4_NAME3_NAME2 > NAME1;
15300 end Test;
15301 @end cartouche
15302 @end smallexample
15303
15304
15305
15306 @c ***********************************
15307 @node File Name Krunching Using gnatkr
15308 @chapter File Name Krunching Using @code{gnatkr}
15309 @findex gnatkr
15310
15311 @noindent
15312 This chapter discusses the method used by the compiler to shorten
15313 the default file names chosen for Ada units so that they do not
15314 exceed the maximum length permitted. It also describes the
15315 @code{gnatkr} utility that can be used to determine the result of
15316 applying this shortening.
15317 @menu
15318 * About gnatkr::
15319 * Using gnatkr::
15320 * Krunching Method::
15321 * Examples of gnatkr Usage::
15322 @end menu
15323
15324 @node About gnatkr
15325 @section About @code{gnatkr}
15326
15327 @noindent
15328 The default file naming rule in GNAT
15329 is that the file name must be derived from
15330 the unit name. The exact default rule is as follows:
15331 @itemize @bullet
15332 @item
15333 Take the unit name and replace all dots by hyphens.
15334 @item
15335 If such a replacement occurs in the
15336 second character position of a name, and the first character is
15337 ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
15338 ^~ (tilde)^$ (dollar sign)^
15339 instead of a minus.
15340 @end itemize
15341 The reason for this exception is to avoid clashes
15342 with the standard names for children of System, Ada, Interfaces,
15343 and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
15344 respectively.
15345
15346 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
15347 switch of the compiler activates a ``krunching''
15348 circuit that limits file names to nn characters (where nn is a decimal
15349 integer). For example, using OpenVMS,
15350 where the maximum file name length is
15351 39, the value of nn is usually set to 39, but if you want to generate
15352 a set of files that would be usable if ported to a system with some
15353 different maximum file length, then a different value can be specified.
15354 The default value of 39 for OpenVMS need not be specified.
15355
15356 The @code{gnatkr} utility can be used to determine the krunched name for
15357 a given file, when krunched to a specified maximum length.
15358
15359 @node Using gnatkr
15360 @section Using @code{gnatkr}
15361
15362 @noindent
15363 The @code{gnatkr} command has the form
15364
15365 @ifclear vms
15366 @smallexample
15367 $ gnatkr @var{name} [@var{length}]
15368 @end smallexample
15369 @end ifclear
15370
15371 @ifset vms
15372 @smallexample
15373 $ gnatkr @var{name} /COUNT=nn
15374 @end smallexample
15375 @end ifset
15376
15377 @noindent
15378 @var{name} is the uncrunched file name, derived from the name of the unit
15379 in the standard manner described in the previous section (i.e. in particular
15380 all dots are replaced by hyphens). The file name may or may not have an
15381 extension (defined as a suffix of the form period followed by arbitrary
15382 characters other than period). If an extension is present then it will
15383 be preserved in the output. For example, when krunching @file{hellofile.ads}
15384 to eight characters, the result will be hellofil.ads.
15385
15386 Note: for compatibility with previous versions of @code{gnatkr} dots may
15387 appear in the name instead of hyphens, but the last dot will always be
15388 taken as the start of an extension. So if @code{gnatkr} is given an argument
15389 such as @file{Hello.World.adb} it will be treated exactly as if the first
15390 period had been a hyphen, and for example krunching to eight characters
15391 gives the result @file{hellworl.adb}.
15392
15393 Note that the result is always all lower case (except on OpenVMS where it is
15394 all upper case). Characters of the other case are folded as required.
15395
15396 @var{length} represents the length of the krunched name. The default
15397 when no argument is given is ^8^39^ characters. A length of zero stands for
15398 unlimited, in other words do not chop except for system files where the
15399 impled crunching length is always eight characters.
15400
15401 @noindent
15402 The output is the krunched name. The output has an extension only if the
15403 original argument was a file name with an extension.
15404
15405 @node Krunching Method
15406 @section Krunching Method
15407
15408 @noindent
15409 The initial file name is determined by the name of the unit that the file
15410 contains. The name is formed by taking the full expanded name of the
15411 unit and replacing the separating dots with hyphens and
15412 using ^lowercase^uppercase^
15413 for all letters, except that a hyphen in the second character position is
15414 replaced by a ^tilde^dollar sign^ if the first character is
15415 ^a, i, g, or s^A, I, G, or S^.
15416 The extension is @code{.ads} for a
15417 specification and @code{.adb} for a body.
15418 Krunching does not affect the extension, but the file name is shortened to
15419 the specified length by following these rules:
15420
15421 @itemize @bullet
15422 @item
15423 The name is divided into segments separated by hyphens, tildes or
15424 underscores and all hyphens, tildes, and underscores are
15425 eliminated. If this leaves the name short enough, we are done.
15426
15427 @item
15428 If the name is too long, the longest segment is located (left-most
15429 if there are two of equal length), and shortened by dropping
15430 its last character. This is repeated until the name is short enough.
15431
15432 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
15433 to fit the name into 8 characters as required by some operating systems.
15434
15435 @smallexample
15436 our-strings-wide_fixed 22
15437 our strings wide fixed 19
15438 our string  wide fixed 18
15439 our strin   wide fixed 17
15440 our stri    wide fixed 16
15441 our stri    wide fixe  15
15442 our str     wide fixe  14
15443 our str     wid  fixe  13
15444 our str     wid  fix   12
15445 ou  str     wid  fix   11
15446 ou  st      wid  fix   10
15447 ou  st      wi   fix   9
15448 ou  st      wi   fi    8
15449 Final file name: oustwifi.adb
15450 @end smallexample
15451
15452 @item
15453 The file names for all predefined units are always krunched to eight
15454 characters. The krunching of these predefined units uses the following
15455 special prefix replacements:
15456
15457 @table @file
15458 @item ada-
15459 replaced by @file{^a^A^-}
15460
15461 @item gnat-
15462 replaced by @file{^g^G^-}
15463
15464 @item interfaces-
15465 replaced by @file{^i^I^-}
15466
15467 @item system-
15468 replaced by @file{^s^S^-}
15469 @end table
15470
15471 These system files have a hyphen in the second character position. That
15472 is why normal user files replace such a character with a
15473 ^tilde^dollar sign^, to
15474 avoid confusion with system file names.
15475
15476 As an example of this special rule, consider
15477 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
15478
15479 @smallexample
15480 ada-strings-wide_fixed 22
15481 a-  strings wide fixed 18
15482 a-  string  wide fixed 17
15483 a-  strin   wide fixed 16
15484 a-  stri    wide fixed 15
15485 a-  stri    wide fixe  14
15486 a-  str     wide fixe  13
15487 a-  str     wid  fixe  12
15488 a-  str     wid  fix   11
15489 a-  st      wid  fix   10
15490 a-  st      wi   fix   9
15491 a-  st      wi   fi    8
15492 Final file name: a-stwifi.adb
15493 @end smallexample
15494 @end itemize
15495
15496 Of course no file shortening algorithm can guarantee uniqueness over all
15497 possible unit names, and if file name krunching is used then it is your
15498 responsibility to ensure that no name clashes occur. The utility
15499 program @code{gnatkr} is supplied for conveniently determining the
15500 krunched name of a file.
15501
15502 @node Examples of gnatkr Usage
15503 @section Examples of @code{gnatkr} Usage
15504
15505 @smallexample
15506 @iftex
15507 @leftskip=0cm
15508 @end iftex
15509 @ifclear vms
15510 $ gnatkr very_long_unit_name.ads      --> velounna.ads
15511 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
15512 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
15513 $ gnatkr grandparent-parent-child     --> grparchi
15514 @end ifclear
15515 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
15516 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
15517 @end smallexample
15518
15519 @node Preprocessing Using gnatprep
15520 @chapter Preprocessing Using @code{gnatprep}
15521 @findex gnatprep
15522
15523 @noindent
15524 The @code{gnatprep} utility provides
15525 a simple preprocessing capability for Ada programs.
15526 It is designed for use with GNAT, but is not dependent on any special
15527 features of GNAT.
15528
15529 @menu
15530 * Using gnatprep::
15531 * Switches for gnatprep::
15532 * Form of Definitions File::
15533 * Form of Input Text for gnatprep::
15534 @end menu
15535
15536 @node Using gnatprep
15537 @section Using @code{gnatprep}
15538
15539 @noindent
15540 To call @code{gnatprep} use
15541
15542 @smallexample
15543 $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
15544 @end smallexample
15545
15546 @noindent
15547 where
15548 @table @code
15549 @item infile
15550 is the full name of the input file, which is an Ada source
15551 file containing preprocessor directives.
15552
15553 @item outfile
15554 is the full name of the output file, which is an Ada source
15555 in standard Ada form. When used with GNAT, this file name will
15556 normally have an ads or adb suffix.
15557
15558 @item deffile
15559 is the full name of a text file containing definitions of
15560 symbols to be referenced by the preprocessor. This argument is
15561 optional, and can be replaced by the use of the @option{-D} switch.
15562
15563 @item switches
15564 is an optional sequence of switches as described in the next section.
15565 @end table
15566
15567 @node Switches for gnatprep
15568 @section Switches for @code{gnatprep}
15569
15570 @table @option
15571 @c !sort!
15572
15573 @item ^-b^/BLANK_LINES^
15574 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
15575 Causes both preprocessor lines and the lines deleted by
15576 preprocessing to be replaced by blank lines in the output source file,
15577 preserving line numbers in the output file.
15578
15579 @item ^-c^/COMMENTS^
15580 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
15581 Causes both preprocessor lines and the lines deleted
15582 by preprocessing to be retained in the output source as comments marked
15583 with the special string @code{"--! "}. This option will result in line numbers
15584 being preserved in the output file.
15585
15586 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
15587 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
15588 Defines a new symbol, associated with value. If no value is given on the
15589 command line, then symbol is considered to be @code{True}. This switch
15590 can be used in place of a definition file.
15591
15592 @ifset vms
15593 @item /REMOVE
15594 @cindex @option{/REMOVE} (@command{gnatprep})
15595 This is the default setting which causes lines deleted by preprocessing
15596 to be entirely removed from the output file.
15597 @end ifset
15598
15599 @item ^-r^/REFERENCE^
15600 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
15601 Causes a @code{Source_Reference} pragma to be generated that
15602 references the original input file, so that error messages will use
15603 the file name of this original file. The use of this switch implies
15604 that preprocessor lines are not to be removed from the file, so its
15605 use will force @option{^-b^/BLANK_LINES^} mode if
15606 @option{^-c^/COMMENTS^}
15607 has not been specified explicitly.
15608
15609 Note that if the file to be preprocessed contains multiple units, then
15610 it will be necessary to @code{gnatchop} the output file from
15611 @code{gnatprep}. If a @code{Source_Reference} pragma is present
15612 in the preprocessed file, it will be respected by
15613 @code{gnatchop ^-r^/REFERENCE^}
15614 so that the final chopped files will correctly refer to the original
15615 input source file for @code{gnatprep}.
15616
15617 @item ^-s^/SYMBOLS^
15618 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
15619 Causes a sorted list of symbol names and values to be
15620 listed on the standard output file.
15621
15622 @item ^-u^/UNDEFINED^
15623 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
15624 Causes undefined symbols to be treated as having the value FALSE in the context
15625 of a preprocessor test. In the absence of this option, an undefined symbol in
15626 a @code{#if} or @code{#elsif} test will be treated as an error.
15627
15628 @end table
15629
15630 @ifclear vms
15631 @noindent
15632 Note: if neither @option{-b} nor @option{-c} is present,
15633 then preprocessor lines and
15634 deleted lines are completely removed from the output, unless -r is
15635 specified, in which case -b is assumed.
15636 @end ifclear
15637
15638 @node Form of Definitions File
15639 @section Form of Definitions File
15640
15641 @noindent
15642 The definitions file contains lines of the form
15643
15644 @smallexample
15645 symbol := value
15646 @end smallexample
15647
15648 @noindent
15649 where symbol is an identifier, following normal Ada (case-insensitive)
15650 rules for its syntax, and value is one of the following:
15651
15652 @itemize @bullet
15653 @item
15654 Empty, corresponding to a null substitution
15655 @item
15656 A string literal using normal Ada syntax
15657 @item
15658 Any sequence of characters from the set
15659 (letters, digits, period, underline).
15660 @end itemize
15661
15662 @noindent
15663 Comment lines may also appear in the definitions file, starting with
15664 the usual @code{--},
15665 and comments may be added to the definitions lines.
15666
15667 @node Form of Input Text for gnatprep
15668 @section Form of Input Text for @code{gnatprep}
15669
15670 @noindent
15671 The input text may contain preprocessor conditional inclusion lines,
15672 as well as general symbol substitution sequences.
15673
15674 The preprocessor conditional inclusion commands have the form
15675
15676 @smallexample
15677 @group
15678 @cartouche
15679 #if @i{expression} [then]
15680    lines
15681 #elsif @i{expression} [then]
15682    lines
15683 #elsif @i{expression} [then]
15684    lines
15685 ...
15686 #else
15687    lines
15688 #end if;
15689 @end cartouche
15690 @end group
15691 @end smallexample
15692
15693 @noindent
15694 In this example, @i{expression} is defined by the following grammar:
15695 @smallexample
15696 @i{expression} ::=  <symbol>
15697 @i{expression} ::=  <symbol> = "<value>"
15698 @i{expression} ::=  <symbol> = <symbol>
15699 @i{expression} ::=  <symbol> 'Defined
15700 @i{expression} ::=  not @i{expression}
15701 @i{expression} ::=  @i{expression} and @i{expression}
15702 @i{expression} ::=  @i{expression} or @i{expression}
15703 @i{expression} ::=  @i{expression} and then @i{expression}
15704 @i{expression} ::=  @i{expression} or else @i{expression}
15705 @i{expression} ::=  ( @i{expression} )
15706 @end smallexample
15707
15708 @noindent
15709 For the first test (@i{expression} ::= <symbol>) the symbol must have
15710 either the value true or false, that is to say the right-hand of the
15711 symbol definition must be one of the (case-insensitive) literals
15712 @code{True} or @code{False}. If the value is true, then the
15713 corresponding lines are included, and if the value is false, they are
15714 excluded.
15715
15716 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
15717 the symbol has been defined in the definition file or by a @option{-D}
15718 switch on the command line. Otherwise, the test is false.
15719
15720 The equality tests are case insensitive, as are all the preprocessor lines.
15721
15722 If the symbol referenced is not defined in the symbol definitions file,
15723 then the effect depends on whether or not switch @option{-u}
15724 is specified. If so, then the symbol is treated as if it had the value
15725 false and the test fails. If this switch is not specified, then
15726 it is an error to reference an undefined symbol. It is also an error to
15727 reference a symbol that is defined with a value other than @code{True}
15728 or @code{False}.
15729
15730 The use of the @code{not} operator inverts the sense of this logical test, so
15731 that the lines are included only if the symbol is not defined.
15732 The @code{then} keyword is optional as shown
15733
15734 The @code{#} must be the first non-blank character on a line, but
15735 otherwise the format is free form. Spaces or tabs may appear between
15736 the @code{#} and the keyword. The keywords and the symbols are case
15737 insensitive as in normal Ada code. Comments may be used on a
15738 preprocessor line, but other than that, no other tokens may appear on a
15739 preprocessor line. Any number of @code{elsif} clauses can be present,
15740 including none at all. The @code{else} is optional, as in Ada.
15741
15742 The @code{#} marking the start of a preprocessor line must be the first
15743 non-blank character on the line, i.e. it must be preceded only by
15744 spaces or horizontal tabs.
15745
15746 Symbol substitution outside of preprocessor lines is obtained by using
15747 the sequence
15748
15749 @smallexample
15750 $symbol
15751 @end smallexample
15752
15753 @noindent
15754 anywhere within a source line, except in a comment or within a
15755 string literal. The identifier
15756 following the @code{$} must match one of the symbols defined in the symbol
15757 definition file, and the result is to substitute the value of the
15758 symbol in place of @code{$symbol} in the output file.
15759
15760 Note that although the substitution of strings within a string literal
15761 is not possible, it is possible to have a symbol whose defined value is
15762 a string literal. So instead of setting XYZ to @code{hello} and writing:
15763
15764 @smallexample
15765 Header : String := "$XYZ";
15766 @end smallexample
15767
15768 @noindent
15769 you should set XYZ to @code{"hello"} and write:
15770
15771 @smallexample
15772 Header : String := $XYZ;
15773 @end smallexample
15774
15775 @noindent
15776 and then the substitution will occur as desired.
15777
15778 @ifset vms
15779 @node The GNAT Run-Time Library Builder gnatlbr
15780 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
15781 @findex gnatlbr
15782 @cindex Library builder
15783
15784 @noindent
15785 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
15786 supplied configuration pragmas.
15787
15788 @menu
15789 * Running gnatlbr::
15790 * Switches for gnatlbr::
15791 * Examples of gnatlbr Usage::
15792 @end menu
15793
15794 @node Running gnatlbr
15795 @section Running @code{gnatlbr}
15796
15797 @noindent
15798 The @code{gnatlbr} command has the form
15799
15800 @smallexample
15801 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
15802 @end smallexample
15803
15804 @node Switches for gnatlbr
15805 @section Switches for @code{gnatlbr}
15806
15807 @noindent
15808 @code{gnatlbr} recognizes the following switches:
15809
15810 @table @option
15811 @c !sort!
15812 @item /CREATE=directory
15813 @cindex @code{/CREATE} (@code{gnatlbr})
15814      Create the new run-time library in the specified directory.
15815
15816 @item /SET=directory
15817 @cindex @code{/SET} (@code{gnatlbr})
15818      Make the library in the specified directory the current run-time
15819      library.
15820
15821 @item /DELETE=directory
15822 @cindex @code{/DELETE} (@code{gnatlbr})
15823      Delete the run-time library in the specified directory.
15824
15825 @item /CONFIG=file
15826 @cindex @code{/CONFIG} (@code{gnatlbr})
15827      With /CREATE:
15828      Use the configuration pragmas in the specified file when building
15829      the library.
15830
15831      With /SET:
15832      Use the configuration pragmas in the specified file when compiling.
15833
15834 @end table
15835
15836 @node Examples of gnatlbr Usage
15837 @section Example of @code{gnatlbr} Usage
15838
15839 @smallexample
15840 Contents of VAXFLOAT.ADC:
15841 pragma Float_Representation (VAX_Float);
15842
15843 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
15844
15845 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
15846
15847 @end smallexample
15848 @end ifset
15849
15850 @node The GNAT Library Browser gnatls
15851 @chapter The GNAT Library Browser @code{gnatls}
15852 @findex gnatls
15853 @cindex Library browser
15854
15855 @noindent
15856 @code{gnatls} is a tool that outputs information about compiled
15857 units. It gives the relationship between objects, unit names and source
15858 files. It can also be used to check the source dependencies of a unit
15859 as well as various characteristics.
15860
15861 @menu
15862 * Running gnatls::
15863 * Switches for gnatls::
15864 * Examples of gnatls Usage::
15865 @end menu
15866
15867 @node Running gnatls
15868 @section Running @code{gnatls}
15869
15870 @noindent
15871 The @code{gnatls} command has the form
15872
15873 @smallexample
15874 $ gnatls switches @var{object_or_ali_file}
15875 @end smallexample
15876
15877 @noindent
15878 The main argument is the list of object or @file{ali} files
15879 (@pxref{The Ada Library Information Files})
15880 for which information is requested.
15881
15882 In normal mode, without additional option, @code{gnatls} produces a
15883 four-column listing. Each line represents information for a specific
15884 object. The first column gives the full path of the object, the second
15885 column gives the name of the principal unit in this object, the third
15886 column gives the status of the source and the fourth column gives the
15887 full path of the source representing this unit.
15888 Here is a simple example of use:
15889
15890 @smallexample
15891 $ gnatls *.o
15892 ^./^[]^demo1.o            demo1            DIF demo1.adb
15893 ^./^[]^demo2.o            demo2             OK demo2.adb
15894 ^./^[]^hello.o            h1                OK hello.adb
15895 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
15896 ^./^[]^instr.o            instr             OK instr.adb
15897 ^./^[]^tef.o              tef              DIF tef.adb
15898 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
15899 ^./^[]^tgef.o             tgef             DIF tgef.adb
15900 @end smallexample
15901
15902 @noindent
15903 The first line can be interpreted as follows: the main unit which is
15904 contained in
15905 object file @file{demo1.o} is demo1, whose main source is in
15906 @file{demo1.adb}. Furthermore, the version of the source used for the
15907 compilation of demo1 has been modified (DIF). Each source file has a status
15908 qualifier which can be:
15909
15910 @table @code
15911 @item OK (unchanged)
15912 The version of the source file used for the compilation of the
15913 specified unit corresponds exactly to the actual source file.
15914
15915 @item MOK (slightly modified)
15916 The version of the source file used for the compilation of the
15917 specified unit differs from the actual source file but not enough to
15918 require recompilation. If you use gnatmake with the qualifier
15919 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
15920 MOK will not be recompiled.
15921
15922 @item DIF (modified)
15923 No version of the source found on the path corresponds to the source
15924 used to build this object.
15925
15926 @item ??? (file not found)
15927 No source file was found for this unit.
15928
15929 @item HID (hidden,  unchanged version not first on PATH)
15930 The version of the source that corresponds exactly to the source used
15931 for compilation has been found on the path but it is hidden by another
15932 version of the same source that has been modified.
15933
15934 @end table
15935
15936 @node Switches for gnatls
15937 @section Switches for @code{gnatls}
15938
15939 @noindent
15940 @code{gnatls} recognizes the following switches:
15941
15942 @table @option
15943 @c !sort!
15944 @item ^-a^/ALL_UNITS^
15945 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
15946 Consider all units, including those of the predefined Ada library.
15947 Especially useful with @option{^-d^/DEPENDENCIES^}.
15948
15949 @item ^-d^/DEPENDENCIES^
15950 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
15951 List sources from which specified units depend on.
15952
15953 @item ^-h^/OUTPUT=OPTIONS^
15954 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
15955 Output the list of options.
15956
15957 @item ^-o^/OUTPUT=OBJECTS^
15958 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
15959 Only output information about object files.
15960
15961 @item ^-s^/OUTPUT=SOURCES^
15962 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
15963 Only output information about source files.
15964
15965 @item ^-u^/OUTPUT=UNITS^
15966 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
15967 Only output information about compilation units.
15968
15969 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
15970 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
15971 @itemx ^-I^/SEARCH=^@var{dir}
15972 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
15973 @itemx -nostdinc
15974 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
15975 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
15976 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
15977 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
15978 Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags
15979 (see @ref{Switches for gnatmake}).
15980
15981 @item --RTS=@var{rts-path}
15982 @cindex @option{--RTS} (@code{gnatls})
15983 Specifies the default location of the runtime library. Same meaning as the
15984 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
15985
15986 @item ^-v^/OUTPUT=VERBOSE^
15987 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
15988 Verbose mode. Output the complete source and object paths. Do not use
15989 the default column layout but instead use long format giving as much as
15990 information possible on each requested units, including special
15991 characteristics such as:
15992
15993 @table @code
15994 @item  Preelaborable
15995 The unit is preelaborable in the Ada 95 sense.
15996
15997 @item No_Elab_Code
15998 No elaboration code has been produced by the compiler for this unit.
15999
16000 @item Pure
16001 The unit is pure in the Ada 95 sense.
16002
16003 @item Elaborate_Body
16004 The unit contains a pragma Elaborate_Body.
16005
16006 @item Remote_Types
16007 The unit contains a pragma Remote_Types.
16008
16009 @item Shared_Passive
16010 The unit contains a pragma Shared_Passive.
16011
16012 @item Predefined
16013 This unit is part of the predefined environment and cannot be modified
16014 by the user.
16015
16016 @item Remote_Call_Interface
16017 The unit contains a pragma Remote_Call_Interface.
16018
16019 @end table
16020
16021 @end table
16022
16023 @node Examples of gnatls Usage
16024 @section Example of @code{gnatls} Usage
16025 @ifclear vms
16026
16027 @noindent
16028 Example of using the verbose switch. Note how the source and
16029 object paths are affected by the -I switch.
16030
16031 @smallexample
16032 $ gnatls -v -I.. demo1.o
16033
16034 GNATLS 3.10w (970212) Copyright 1999 Free Software Foundation, Inc.
16035
16036 Source Search Path:
16037    <Current_Directory>
16038    ../
16039    /home/comar/local/adainclude/
16040
16041 Object Search Path:
16042    <Current_Directory>
16043    ../
16044    /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/
16045
16046 ./demo1.o
16047    Unit =>
16048      Name   => demo1
16049      Kind   => subprogram body
16050      Flags  => No_Elab_Code
16051      Source => demo1.adb    modified
16052 @end smallexample
16053
16054 @noindent
16055 The following is an example of use of the dependency list.
16056 Note the use of the -s switch
16057 which gives a straight list of source files. This can be useful for
16058 building specialized scripts.
16059
16060 @smallexample
16061 $ gnatls -d demo2.o
16062 ./demo2.o   demo2        OK demo2.adb
16063                          OK gen_list.ads
16064                          OK gen_list.adb
16065                          OK instr.ads
16066                          OK instr-child.ads
16067
16068 $ gnatls -d -s -a demo1.o
16069 demo1.adb
16070 /home/comar/local/adainclude/ada.ads
16071 /home/comar/local/adainclude/a-finali.ads
16072 /home/comar/local/adainclude/a-filico.ads
16073 /home/comar/local/adainclude/a-stream.ads
16074 /home/comar/local/adainclude/a-tags.ads
16075 gen_list.ads
16076 gen_list.adb
16077 /home/comar/local/adainclude/gnat.ads
16078 /home/comar/local/adainclude/g-io.ads
16079 instr.ads
16080 /home/comar/local/adainclude/system.ads
16081 /home/comar/local/adainclude/s-exctab.ads
16082 /home/comar/local/adainclude/s-finimp.ads
16083 /home/comar/local/adainclude/s-finroo.ads
16084 /home/comar/local/adainclude/s-secsta.ads
16085 /home/comar/local/adainclude/s-stalib.ads
16086 /home/comar/local/adainclude/s-stoele.ads
16087 /home/comar/local/adainclude/s-stratt.ads
16088 /home/comar/local/adainclude/s-tasoli.ads
16089 /home/comar/local/adainclude/s-unstyp.ads
16090 /home/comar/local/adainclude/unchconv.ads
16091 @end smallexample
16092 @end ifclear
16093
16094 @ifset vms
16095 @smallexample
16096 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
16097
16098 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
16099 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
16100 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
16101 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
16102 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
16103 demo1.adb
16104 gen_list.ads
16105 gen_list.adb
16106 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
16107 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
16108 instr.ads
16109 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
16110 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
16111 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
16112 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
16113 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
16114 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
16115 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
16116 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
16117 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
16118 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
16119 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
16120 @end smallexample
16121 @end ifset
16122
16123 @node Cleaning Up Using gnatclean
16124 @chapter Cleaning Up Using @code{gnatclean}
16125 @findex gnatclean
16126 @cindex Cleaning tool
16127
16128 @noindent
16129 @code{gnatclean} is a tool that allows the deletion of files produced by the
16130 compiler, binder and linker, including ALI files, object files, tree files,
16131 expanded source files, library files, interface copy source files, binder
16132 generated files and executable files.
16133
16134 @menu
16135 * Running gnatclean::
16136 * Switches for gnatclean::
16137 * Examples of gnatclean Usage::
16138 @end menu
16139
16140 @node Running gnatclean
16141 @section Running @code{gnatclean}
16142
16143 @noindent
16144 The @code{gnatclean} command has the form:
16145
16146 @smallexample
16147 $ gnatclean switches @var{names}
16148 @end smallexample
16149
16150 @noindent
16151 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
16152 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
16153 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
16154
16155 @noindent
16156 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
16157 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
16158 the linker. In informative-only mode, specified by switch
16159 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
16160 normal mode is listed, but no file is actually deleted.
16161
16162 @node Switches for gnatclean
16163 @section Switches for @code{gnatclean}
16164
16165 @noindent
16166 @code{gnatclean} recognizes the following switches:
16167
16168 @table @option
16169 @c !sort!
16170 @item ^-c^/COMPILER_FILES_ONLY^
16171 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
16172 Only attempt to delete the files produced by the compiler, not those produced
16173 by the binder or the linker. The files that are not to be deleted are library
16174 files, interface copy files, binder generated files and executable files.
16175
16176 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
16177 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
16178 Indicate that ALI and object files should normally be found in directory
16179 @var{dir}.
16180
16181 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
16182 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
16183 When using project files, if some errors or warnings are detected during
16184 parsing and verbose mode is not in effect (no use of switch
16185 ^-v^/VERBOSE^), then error lines start with the full path name of the project
16186 file, rather than its simple file name.
16187
16188 @item ^-h^/HELP^
16189 @cindex @option{^-h^/HELP^} (@code{gnatclean})
16190 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
16191
16192 @item ^-n^/NODELETE^
16193 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
16194 Informative-only mode. Do not delete any files. Output the list of the files
16195 that would have been deleted if this switch was not specified.
16196
16197 @item ^-P^/PROJECT_FILE=^@var{project}
16198 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
16199 Use project file @var{project}. Only one such switch can be used.
16200 When cleaning a project file, the files produced by the compilation of the
16201 immediate sources or inherited sources of the project files are to be
16202 deleted. This is not depending on the presence or not of executable names
16203 on the command line.
16204
16205 @item ^-q^/QUIET^
16206 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
16207 Quiet output. If there are no error, do not ouuput anything, except in
16208 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
16209 (switch ^-n^/NODELETE^).
16210
16211 @item ^-r^/RECURSIVE^
16212 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
16213 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
16214 clean all imported and extended project files, recursively. If this switch
16215 is not specified, only the files related to the main project file are to be
16216 deleted. This switch has no effect if no project file is specified.
16217
16218 @item ^-v^/VERBOSE^
16219 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
16220 Verbose mode.
16221
16222 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
16223 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
16224 Indicates the verbosity of the parsing of GNAT project files.
16225 See @ref{Switches Related to Project Files}.
16226
16227 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
16228 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
16229 Indicates that external variable @var{name} has the value @var{value}.
16230 The Project Manager will use this value for occurrences of
16231 @code{external(name)} when parsing the project file.
16232 See @ref{Switches Related to Project Files}.
16233
16234 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16235 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
16236 When searching for ALI and object files, look in directory
16237 @var{dir}.
16238
16239 @item ^-I^/SEARCH=^@var{dir}
16240 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
16241 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
16242
16243 @item ^-I-^/NOCURRENT_DIRECTORY^
16244 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
16245 @cindex Source files, suppressing search
16246 Do not look for ALI or object files in the directory
16247 where @code{gnatclean} was invoked.
16248
16249 @end table
16250
16251 @node Examples of gnatclean Usage
16252 @section Examples of @code{gnatclean} Usage
16253
16254 @ifclear vms
16255 @node GNAT and Libraries
16256 @chapter GNAT and Libraries
16257 @cindex Library, building, installing
16258
16259 @noindent
16260 This chapter addresses some of the issues related to building and using
16261 a library with GNAT. It also shows how the GNAT run-time library can be
16262 recompiled.
16263
16264 @menu
16265 * Creating an Ada Library::
16266 * Installing an Ada Library::
16267 * Using an Ada Library::
16268 * Creating an Ada Library to be Used in a Non-Ada Context::
16269 * Rebuilding the GNAT Run-Time Library::
16270 @end menu
16271
16272 @node Creating an Ada Library
16273 @section Creating an Ada Library
16274
16275 @noindent
16276 In the GNAT environment, a library has two components:
16277 @itemize @bullet
16278 @item
16279 Source files.
16280 @item
16281 Compiled code and Ali files. See @ref{The Ada Library Information Files}.
16282 @end itemize
16283
16284 @noindent
16285 In order to use other packages @ref{The GNAT Compilation Model}
16286 requires a certain number of sources to be available to the compiler.
16287 The minimal set of
16288 sources required includes the specs of all the packages that make up the
16289 visible part of the library as well as all the sources upon which they
16290 depend. The bodies of all visible generic units must also be provided.
16291 @noindent
16292 Although it is not strictly mandatory, it is recommended that all sources
16293 needed to recompile the library be provided, so that the user can make
16294 full use of inter-unit inlining and source-level debugging. This can also
16295 make the situation easier for users that need to upgrade their compilation
16296 toolchain and thus need to recompile the library from sources.
16297
16298 @noindent
16299 The compiled code can be provided in different ways. The simplest way is
16300 to provide directly the set of objects produced by the compiler during
16301 the compilation of the library. It is also possible to group the objects
16302 into an archive using whatever commands are provided by the operating
16303 system. Finally, it is also possible to create a shared library (see
16304 option -shared in the GCC manual).
16305
16306 @noindent
16307 There are various possibilities for compiling the units that make up the
16308 library: for example with a Makefile @ref{Using the GNU make Utility},
16309 or with a conventional script.
16310 For simple libraries, it is also possible to create a
16311 dummy main program which depends upon all the packages that comprise the
16312 interface of the library. This dummy main program can then be given to
16313 gnatmake, in order to build all the necessary objects. Here is an example
16314 of such a dummy program and the generic commands used to build an
16315 archive or a shared library.
16316
16317 @smallexample @c ada
16318 @iftex
16319 @leftskip=.7cm
16320 @end iftex
16321 with My_Lib.Service1;
16322 with My_Lib.Service2;
16323 with My_Lib.Service3;
16324 procedure My_Lib_Dummy is
16325 begin
16326    null;
16327 end;
16328 @end smallexample
16329
16330 @smallexample
16331 # compiling the library
16332 $ gnatmake -c my_lib_dummy.adb
16333
16334 # we don't need the dummy object itself
16335 $ rm my_lib_dummy.o my_lib_dummy.ali
16336
16337 # create an archive with the remaining objects
16338 $ ar rc libmy_lib.a *.o
16339 # some systems may require "ranlib" to be run as well
16340
16341 # or create a shared library
16342 $ gcc -shared -o libmy_lib.so *.o
16343 # some systems may require the code to have been compiled with -fPIC
16344
16345 # remove the object files that are now in the library
16346 $ rm *.o
16347
16348 # Make the ALI files read-only so that gnatmake will not try to
16349 # regenerate the objects that are in the library
16350 $ chmod -w *.ali
16351
16352 @end smallexample
16353
16354 @noindent
16355 When the objects are grouped in an archive or a shared library, the user
16356 needs to specify the desired library at link time, unless a pragma
16357 linker_options has been used in one of the sources:
16358 @smallexample @c ada
16359 pragma Linker_Options ("-lmy_lib");
16360 @end smallexample
16361
16362 @noindent
16363 Please note that the library must have a name of the form libxxx.a or
16364 libxxx.so in order to be accessed by the directive -lxxx at link
16365 time.
16366
16367 @node Installing an Ada Library
16368 @section Installing an Ada Library
16369
16370 @noindent
16371 In the GNAT model, installing a library consists in copying into a specific
16372 location the files that make up this library. It is possible to install
16373 the sources in a different directory from the other files (ALI, objects,
16374 archives) since the source path and the object path can easily be
16375 specified separately.
16376
16377 @noindent
16378 For general purpose libraries, it is possible for the system
16379 administrator to put those libraries in the default compiler paths. To
16380 achieve this, he must specify their location in the configuration files
16381 @file{ada_source_path} and @file{ada_object_path} that must be located in
16382 the GNAT
16383 installation tree at the same place as the gcc spec file. The location of
16384 the gcc spec file can be determined as follows:
16385 @smallexample
16386 $ gcc -v
16387 @end smallexample
16388
16389 @noindent
16390 The configuration files mentioned above have simple format: each line in them
16391 must contain one unique
16392 directory name. Those names are added to the corresponding path
16393 in their order of appearance in the file. The names can be either absolute
16394 or relative, in the latter case, they are relative to where theses files
16395 are located.
16396
16397 @noindent
16398 @file{ada_source_path} and @file{ada_object_path} might actually not be
16399 present in a
16400 GNAT installation, in which case, GNAT will look for its run-time library in
16401 he directories @file{adainclude} for the sources and @file{adalib} for the
16402 objects and @file{ALI} files. When the files exist, the compiler does not
16403 look in @file{adainclude} and @file{adalib} at all, and thus the
16404 @file{ada_source_path} file
16405 must contain the location for the GNAT run-time sources (which can simply
16406 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
16407 contain the location for the GNAT run-time objects (which can simply
16408 be @file{adalib}).
16409
16410 @noindent
16411 You can also specify a new default path to the runtime library at compilation
16412 time with the switch @option{--RTS=rts-path}. You can easily choose and change
16413 the runtime you want your program to be compiled with. This switch is
16414 recognized by gcc, gnatmake, gnatbind, gnatls, gnatfind and gnatxref.
16415
16416 @noindent
16417 It is possible to install a library before or after the standard GNAT
16418 library, by reordering the lines in the configuration files. In general, a
16419 library must be installed before the GNAT library if it redefines
16420 any part of it.
16421
16422 @node Using an Ada Library
16423 @section Using an Ada Library
16424
16425 @noindent
16426 In order to use a Ada library, you need to make sure that this
16427 library is on both your source and object path
16428 @ref{Search Paths and the Run-Time Library (RTL)}
16429 and @ref{Search Paths for gnatbind}. For
16430 instance, you can use the library @file{mylib} installed in
16431 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
16432
16433 @smallexample
16434 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
16435   -largs -lmy_lib
16436 @end smallexample
16437
16438 @noindent
16439 This can be simplified down to the following:
16440 @smallexample
16441 $ gnatmake my_appl
16442 @end smallexample
16443 when the following conditions are met:
16444 @itemize @bullet
16445 @item
16446 @file{/dir/my_lib_src} has been added by the user to the environment
16447 variable @code{ADA_INCLUDE_PATH}, or by the administrator to the file
16448 @file{ada_source_path}
16449 @item
16450 @file{/dir/my_lib_obj} has been added by the user to the environment
16451 variable @code{ADA_OBJECTS_PATH}, or by the administrator to the file
16452 @file{ada_object_path}
16453 @item
16454 a pragma @code{Linker_Options}, as mentioned in @ref{Creating an Ada Library},
16455 has been added to the sources.
16456 @end itemize
16457 @noindent
16458
16459 @node Creating an Ada Library to be Used in a Non-Ada Context
16460 @section Creating an Ada Library to be Used in a Non-Ada Context
16461
16462 @noindent
16463 The previous sections detailed how to create and install a library that
16464 was usable from an Ada main program. Using this library in a non-Ada
16465 context is not possible, because the elaboration of the library is
16466 automatically done as part of the main program elaboration.
16467
16468 GNAT also provides the ability to build libraries that can be used both
16469 in an Ada and non-Ada context.  This section describes how to build such
16470 a library, and then how to use it from a C program. The method for
16471 interfacing with the library from other languages such as Fortran for
16472 instance remains the same.
16473
16474 @subsection Creating the Library
16475
16476 @itemize @bullet
16477 @item Identify the units representing the interface of the library.
16478
16479 Here is an example of simple library interface:
16480
16481 @smallexample @c ada
16482 package Interface is
16483
16484    procedure Do_Something;
16485
16486    procedure Do_Something_Else;
16487
16488 end Interface;
16489 @end smallexample
16490
16491 @item Use @code{pragma Export} or @code{pragma Convention} for the
16492 exported entities.
16493
16494 Our package @code{Interface} is then updated as follow:
16495 @smallexample @c ada
16496 package Interface is
16497
16498    procedure Do_Something;
16499    pragma Export (C, Do_Something, "do_something");
16500
16501    procedure Do_Something_Else;
16502    pragma Export (C, Do_Something_Else, "do_something_else");
16503
16504 end Interface;
16505 @end smallexample
16506
16507 @item Compile all the units composing the library.
16508
16509 @item Bind the library objects.
16510
16511 This step is performed by invoking gnatbind with the @option{-L<prefix>}
16512 switch. @code{gnatbind} will then generate the library elaboration
16513 procedure (named @code{<prefix>init}) and the run-time finalization
16514 procedure (named @code{<prefix>final}).
16515
16516 @smallexample
16517 # generate the binder file in Ada
16518 $ gnatbind -Lmylib interface
16519
16520 # generate the binder file in C
16521 $ gnatbind -C -Lmylib interface
16522 @end smallexample
16523
16524 @item Compile the files generated by the binder
16525
16526 @smallexample
16527 $ gcc -c b~interface.adb
16528 @end smallexample
16529
16530 @item Create the library;
16531
16532 The procedure is identical to the procedure explained in
16533 @ref{Creating an Ada Library},
16534 except that @file{b~interface.o} needs to be added to
16535 the list of objects.
16536
16537 @smallexample
16538 # create an archive file
16539 $ ar cr libmylib.a b~interface.o <other object files>
16540
16541 # create a shared library
16542 $ gcc -shared -o libmylib.so b~interface.o <other object files>
16543 @end smallexample
16544
16545 @item Provide a ``foreign'' view of the library interface;
16546
16547 The example below shows the content of @code{mylib_interface.h} (note
16548 that there is no rule for the naming of this file, any name can be used)
16549 @smallexample
16550 /* the library elaboration procedure */
16551 extern void mylibinit (void);
16552
16553 /* the library finalization procedure */
16554 extern void mylibfinal (void);
16555
16556 /* the interface exported by the library */
16557 extern void do_something (void);
16558 extern void do_something_else (void);
16559 @end smallexample
16560 @end itemize
16561
16562 @subsection Using the Library
16563
16564 @noindent
16565 Libraries built as explained above can be used from any program, provided
16566 that the elaboration procedures (named @code{mylibinit} in the previous
16567 example) are called before the library services are used. Any number of
16568 libraries can be used simultaneously, as long as the elaboration
16569 procedure of each library is called.
16570
16571 Below is an example of C program that uses our @code{mylib} library.
16572
16573 @smallexample
16574 #include "mylib_interface.h"
16575
16576 int
16577 main (void)
16578 @{
16579    /* First, elaborate the library before using it */
16580    mylibinit ();
16581
16582    /* Main program, using the library exported entities */
16583    do_something ();
16584    do_something_else ();
16585
16586    /* Library finalization at the end of the program */
16587    mylibfinal ();
16588    return 0;
16589 @}
16590 @end smallexample
16591
16592 @noindent
16593 Note that this same library can be used from an equivalent Ada main
16594 program. In addition, if the libraries are installed as detailed in
16595 @ref{Installing an Ada Library}, it is not necessary to invoke the
16596 library elaboration and finalization routines. The binder will ensure
16597 that this is done as part of the main program elaboration and
16598 finalization phases.
16599
16600 @subsection The Finalization Phase
16601
16602 @noindent
16603 Invoking any library finalization procedure generated by @code{gnatbind}
16604 shuts down the Ada run time permanently. Consequently, the finalization
16605 of all Ada libraries must be performed at the end of the program. No
16606 call to these libraries nor the Ada run time should be made past the
16607 finalization phase.
16608
16609 @subsection Restrictions in Libraries
16610
16611 @noindent
16612 The pragmas listed below should be used with caution inside libraries,
16613 as they can create incompatibilities with other Ada libraries:
16614 @itemize @bullet
16615 @item pragma @code{Locking_Policy}
16616 @item pragma @code{Queuing_Policy}
16617 @item pragma @code{Task_Dispatching_Policy}
16618 @item pragma @code{Unreserve_All_Interrupts}
16619 @end itemize
16620 When using a library that contains such pragmas, the user must make sure
16621 that all libraries use the same pragmas with the same values. Otherwise,
16622 a @code{Program_Error} will
16623 be raised during the elaboration of the conflicting
16624 libraries. The usage of these pragmas and its consequences for the user
16625 should therefore be well documented.
16626
16627 Similarly, the traceback in exception occurrences mechanism should be
16628 enabled or disabled in a consistent manner across all libraries.
16629 Otherwise, a Program_Error will be raised during the elaboration of the
16630 conflicting libraries.
16631
16632 If the @code{'Version} and @code{'Body_Version}
16633 attributes are used inside a library, then it is necessary to
16634 perform a @code{gnatbind} step that mentions all @file{ALI} files in all
16635 libraries, so that version identifiers can be properly computed.
16636 In practice these attributes are rarely used, so this is unlikely
16637 to be a consideration.
16638
16639 @node  Rebuilding the GNAT Run-Time Library
16640 @section Rebuilding the GNAT Run-Time Library
16641
16642 @noindent
16643 It may be useful to recompile the GNAT library in various contexts, the
16644 most important one being the use of partition-wide configuration pragmas
16645 such as Normalize_Scalar. A special Makefile called
16646 @code{Makefile.adalib} is provided to that effect and can be found in
16647 the directory containing the GNAT library. The location of this
16648 directory depends on the way the GNAT environment has been installed and can
16649 be determined by means of the command:
16650
16651 @smallexample
16652 $ gnatls -v
16653 @end smallexample
16654
16655 @noindent
16656 The last entry in the object search path usually contains the
16657 gnat library. This Makefile contains its own documentation and in
16658 particular the set of instructions needed to rebuild a new library and
16659 to use it.
16660
16661 @node Using the GNU make Utility
16662 @chapter Using the GNU @code{make} Utility
16663 @findex make
16664
16665 @noindent
16666 This chapter offers some examples of makefiles that solve specific
16667 problems. It does not explain how to write a makefile (see the GNU make
16668 documentation), nor does it try to replace the @code{gnatmake} utility
16669 (@pxref{The GNAT Make Program gnatmake}).
16670
16671 All the examples in this section are specific to the GNU version of
16672 make. Although @code{make} is a standard utility, and the basic language
16673 is the same, these examples use some advanced features found only in
16674 @code{GNU make}.
16675
16676 @menu
16677 * Using gnatmake in a Makefile::
16678 * Automatically Creating a List of Directories::
16679 * Generating the Command Line Switches::
16680 * Overcoming Command Line Length Limits::
16681 @end menu
16682
16683 @node Using gnatmake in a Makefile
16684 @section Using gnatmake in a Makefile
16685 @findex makefile
16686 @cindex GNU make
16687
16688 @noindent
16689 Complex project organizations can be handled in a very powerful way by
16690 using GNU make combined with gnatmake. For instance, here is a Makefile
16691 which allows you to build each subsystem of a big project into a separate
16692 shared library. Such a makefile allows you to significantly reduce the link
16693 time of very big applications while maintaining full coherence at
16694 each step of the build process.
16695
16696 The list of dependencies are handled automatically by
16697 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
16698 the appropriate directories.
16699
16700 Note that you should also read the example on how to automatically
16701 create the list of directories
16702 (@pxref{Automatically Creating a List of Directories})
16703 which might help you in case your project has a lot of subdirectories.
16704
16705 @smallexample
16706 @iftex
16707 @leftskip=0cm
16708 @font@heightrm=cmr8
16709 @heightrm
16710 @end iftex
16711 ## This Makefile is intended to be used with the following directory
16712 ## configuration:
16713 ##  - The sources are split into a series of csc (computer software components)
16714 ##    Each of these csc is put in its own directory.
16715 ##    Their name are referenced by the directory names.
16716 ##    They will be compiled into shared library (although this would also work
16717 ##    with static libraries
16718 ##  - The main program (and possibly other packages that do not belong to any
16719 ##    csc is put in the top level directory (where the Makefile is).
16720 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16721 ##                    \_ second_csc (sources) __ lib (will contain the library)
16722 ##                    \_ ...
16723 ## Although this Makefile is build for shared library, it is easy to modify
16724 ## to build partial link objects instead (modify the lines with -shared and
16725 ## gnatlink below)
16726 ##
16727 ## With this makefile, you can change any file in the system or add any new
16728 ## file, and everything will be recompiled correctly (only the relevant shared
16729 ## objects will be recompiled, and the main program will be re-linked).
16730
16731 # The list of computer software component for your project. This might be
16732 # generated automatically.
16733 CSC_LIST=aa bb cc
16734
16735 # Name of the main program (no extension)
16736 MAIN=main
16737
16738 # If we need to build objects with -fPIC, uncomment the following line
16739 #NEED_FPIC=-fPIC
16740
16741 # The following variable should give the directory containing libgnat.so
16742 # You can get this directory through 'gnatls -v'. This is usually the last
16743 # directory in the Object_Path.
16744 GLIB=...
16745
16746 # The directories for the libraries
16747 # (This macro expands the list of CSC to the list of shared libraries, you
16748 # could simply use the expanded form :
16749 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16750 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16751
16752 $@{MAIN@}: objects $@{LIB_DIR@}
16753     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16754     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16755
16756 objects::
16757     # recompile the sources
16758     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16759
16760 # Note: In a future version of GNAT, the following commands will be simplified
16761 # by a new tool, gnatmlib
16762 $@{LIB_DIR@}:
16763     mkdir -p $@{dir $@@ @}
16764     cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16765     cd $@{dir $@@ @}; cp -f ../*.ali .
16766
16767 # The dependencies for the modules
16768 # Note that we have to force the expansion of *.o, since in some cases
16769 # make won't be able to do it itself.
16770 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16771 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16772 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16773
16774 # Make sure all of the shared libraries are in the path before starting the
16775 # program
16776 run::
16777     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16778
16779 clean::
16780     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16781     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16782     $@{RM@} $@{CSC_LIST:%=%/*.o@}
16783     $@{RM@} *.o *.ali $@{MAIN@}
16784 @end smallexample
16785
16786 @node Automatically Creating a List of Directories
16787 @section Automatically Creating a List of Directories
16788
16789 @noindent
16790 In most makefiles, you will have to specify a list of directories, and
16791 store it in a variable. For small projects, it is often easier to
16792 specify each of them by hand, since you then have full control over what
16793 is the proper order for these directories, which ones should be
16794 included...
16795
16796 However, in larger projects, which might involve hundreds of
16797 subdirectories, it might be more convenient to generate this list
16798 automatically.
16799
16800 The example below presents two methods. The first one, although less
16801 general, gives you more control over the list. It involves wildcard
16802 characters, that are automatically expanded by @code{make}. Its
16803 shortcoming is that you need to explicitly specify some of the
16804 organization of your project, such as for instance the directory tree
16805 depth, whether some directories are found in a separate tree,...
16806
16807 The second method is the most general one. It requires an external
16808 program, called @code{find}, which is standard on all Unix systems. All
16809 the directories found under a given root directory will be added to the
16810 list.
16811
16812 @smallexample
16813 @iftex
16814 @leftskip=0cm
16815 @font@heightrm=cmr8
16816 @heightrm
16817 @end iftex
16818 # The examples below are based on the following directory hierarchy:
16819 # All the directories can contain any number of files
16820 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
16821 #                       ->  ab
16822 #                       ->  ac
16823 #                ->  b  ->  ba  ->  baa
16824 #                       ->  bb
16825 #                       ->  bc
16826 # This Makefile creates a variable called DIRS, that can be reused any time
16827 # you need this list (see the other examples in this section)
16828
16829 # The root of your project's directory hierarchy
16830 ROOT_DIRECTORY=.
16831
16832 ####
16833 # First method: specify explicitly the list of directories
16834 # This allows you to specify any subset of all the directories you need.
16835 ####
16836
16837 DIRS := a/aa/ a/ab/ b/ba/
16838
16839 ####
16840 # Second method: use wildcards
16841 # Note that the argument(s) to wildcard below should end with a '/'.
16842 # Since wildcards also return file names, we have to filter them out
16843 # to avoid duplicate directory names.
16844 # We thus use make's @code{dir} and @code{sort} functions.
16845 # It sets DIRs to the following value (note that the directories aaa and baa
16846 # are not given, unless you change the arguments to wildcard).
16847 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16848 ####
16849
16850 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16851                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16852
16853 ####
16854 # Third method: use an external program
16855 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16856 # This is the most complete command: it sets DIRs to the following value:
16857 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16858 ####
16859
16860 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16861
16862 @end smallexample
16863
16864 @node Generating the Command Line Switches
16865 @section Generating the Command Line Switches
16866
16867 @noindent
16868 Once you have created the list of directories as explained in the
16869 previous section (@pxref{Automatically Creating a List of Directories}),
16870 you can easily generate the command line arguments to pass to gnatmake.
16871
16872 For the sake of completeness, this example assumes that the source path
16873 is not the same as the object path, and that you have two separate lists
16874 of directories.
16875
16876 @smallexample
16877 # see "Automatically creating a list of directories" to create
16878 # these variables
16879 SOURCE_DIRS=
16880 OBJECT_DIRS=
16881
16882 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16883 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16884
16885 all:
16886         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16887 @end smallexample
16888
16889 @node Overcoming Command Line Length Limits
16890 @section Overcoming Command Line Length Limits
16891
16892 @noindent
16893 One problem that might be encountered on big projects is that many
16894 operating systems limit the length of the command line. It is thus hard to give
16895 gnatmake the list of source and object directories.
16896
16897 This example shows how you can set up environment variables, which will
16898 make @code{gnatmake} behave exactly as if the directories had been
16899 specified on the command line, but have a much higher length limit (or
16900 even none on most systems).
16901
16902 It assumes that you have created a list of directories in your Makefile,
16903 using one of the methods presented in
16904 @ref{Automatically Creating a List of Directories}.
16905 For the sake of completeness, we assume that the object
16906 path (where the ALI files are found) is different from the sources patch.
16907
16908 Note a small trick in the Makefile below: for efficiency reasons, we
16909 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16910 expanded immediately by @code{make}. This way we overcome the standard
16911 make behavior which is to expand the variables only when they are
16912 actually used.
16913
16914 On Windows, if you are using the standard Windows command shell, you must
16915 replace colons with semicolons in the assignments to these variables.
16916
16917 @smallexample
16918 @iftex
16919 @leftskip=0cm
16920 @font@heightrm=cmr8
16921 @heightrm
16922 @end iftex
16923 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
16924 # This is the same thing as putting the -I arguments on the command line.
16925 # (the equivalent of using -aI on the command line would be to define
16926 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
16927 # You can of course have different values for these variables.
16928 #
16929 # Note also that we need to keep the previous values of these variables, since
16930 # they might have been set before running 'make' to specify where the GNAT
16931 # library is installed.
16932
16933 # see "Automatically creating a list of directories" to create these
16934 # variables
16935 SOURCE_DIRS=
16936 OBJECT_DIRS=
16937
16938 empty:=
16939 space:=$@{empty@} $@{empty@}
16940 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16941 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16942 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16943 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
16944 export ADA_INCLUDE_PATH
16945 export ADA_OBJECT_PATH
16946
16947 all:
16948         gnatmake main_unit
16949 @end smallexample
16950 @end ifclear
16951
16952
16953 @node Finding Memory Problems
16954 @chapter Finding Memory Problems
16955
16956 @noindent
16957 This chapter describes
16958 @ifclear vms
16959 the @command{gnatmem} tool, which can be used to track down
16960 ``memory leaks'', and
16961 @end ifclear
16962 the GNAT Debug Pool facility, which can be used to detect incorrect uses of
16963 access values (including ``dangling references'').
16964
16965 @menu
16966 @ifclear vms
16967 * The gnatmem Tool::
16968 @end ifclear
16969 * The GNAT Debug Pool Facility::
16970 @end menu
16971
16972
16973 @ifclear vms
16974 @node The gnatmem Tool
16975 @section The @command{gnatmem} Tool
16976 @findex gnatmem
16977
16978 @noindent
16979 The @code{gnatmem} utility monitors dynamic allocation and
16980 deallocation activity in a program, and displays information about
16981 incorrect deallocations and possible sources of memory leaks.
16982 It provides three type of information:
16983 @itemize @bullet
16984 @item
16985 General information concerning memory management, such as the total
16986 number of allocations and deallocations, the amount of allocated
16987 memory and the high water mark, i.e. the largest amount of allocated
16988 memory in the course of program execution.
16989
16990 @item
16991 Backtraces for all incorrect deallocations, that is to say deallocations
16992 which do not correspond to a valid allocation.
16993
16994 @item
16995 Information on each allocation that is potentially the origin of a memory
16996 leak.
16997 @end itemize
16998
16999 @menu
17000 * Running gnatmem::
17001 * Switches for gnatmem::
17002 * Example of gnatmem Usage::
17003 @end menu
17004
17005 @node Running gnatmem
17006 @subsection Running @code{gnatmem}
17007
17008 @noindent
17009 @code{gnatmem} makes use of the output created by the special version of
17010 allocation and deallocation routines that record call information. This
17011 allows to obtain accurate dynamic memory usage history at a minimal cost to
17012 the execution speed. Note however, that @code{gnatmem} is not supported on
17013 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux x86,
17014 Solaris (sparc and x86) and Windows NT/2000/XP (x86).
17015
17016 @noindent
17017 The @code{gnatmem} command has the form
17018
17019 @smallexample
17020    $ gnatmem [switches] user_program
17021 @end smallexample
17022
17023 @noindent
17024 The program must have been linked with the instrumented version of the
17025 allocation and deallocation routines. This is done by linking with the
17026 @file{libgmem.a} library. For correct symbolic backtrace information,
17027 the user program should be compiled with debugging options
17028 @ref{Switches for gcc}. For example to build @file{my_program}:
17029
17030 @smallexample
17031 $ gnatmake -g my_program -largs -lgmem
17032 @end smallexample
17033
17034 @noindent
17035 When running @file{my_program} the file @file{gmem.out} is produced. This file
17036 contains information about all allocations and deallocations done by the
17037 program. It is produced by the instrumented allocations and
17038 deallocations routines and will be used by @code{gnatmem}.
17039
17040 @noindent
17041 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
17042 examine. If the location of @file{gmem.out} file was not explicitly supplied by
17043 @code{-i} switch, gnatmem will assume that this file can be found in the
17044 current directory. For example, after you have executed @file{my_program},
17045 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
17046
17047 @smallexample
17048 $ gnatmem my_program
17049 @end smallexample
17050
17051 @noindent
17052 This will produce the output with the following format:
17053
17054 *************** debut cc
17055 @smallexample
17056 $ gnatmem my_program
17057
17058 Global information
17059 ------------------
17060    Total number of allocations        :  45
17061    Total number of deallocations      :   6
17062    Final Water Mark (non freed mem)   :  11.29 Kilobytes
17063    High Water Mark                    :  11.40 Kilobytes
17064
17065 .
17066 .
17067 .
17068 Allocation Root # 2
17069 -------------------
17070  Number of non freed allocations    :  11
17071  Final Water Mark (non freed mem)   :   1.16 Kilobytes
17072  High Water Mark                    :   1.27 Kilobytes
17073  Backtrace                          :
17074    my_program.adb:23 my_program.alloc
17075 .
17076 .
17077 .
17078 @end smallexample
17079
17080 The first block of output gives general information. In this case, the
17081 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
17082 Unchecked_Deallocation routine occurred.
17083
17084 @noindent
17085 Subsequent paragraphs display  information on all allocation roots.
17086 An allocation root is a specific point in the execution of the program
17087 that generates some dynamic allocation, such as a ``@code{@b{new}}''
17088 construct. This root is represented by an execution backtrace (or subprogram
17089 call stack). By default the backtrace depth for allocations roots is 1, so
17090 that a root corresponds exactly to a source location. The backtrace can
17091 be made deeper, to make the root more specific.
17092
17093 @node Switches for gnatmem
17094 @subsection Switches for @code{gnatmem}
17095
17096 @noindent
17097 @code{gnatmem} recognizes the following switches:
17098
17099 @table @option
17100
17101 @item -q
17102 @cindex @option{-q} (@code{gnatmem})
17103 Quiet. Gives the minimum output needed to identify the origin of the
17104 memory leaks. Omits statistical information.
17105
17106 @item @var{N}
17107 @cindex @var{N} (@code{gnatmem})
17108 N is an integer literal (usually between 1 and 10) which controls the
17109 depth of the backtraces defining allocation root. The default value for
17110 N is 1. The deeper the backtrace, the more precise the localization of
17111 the root. Note that the total number of roots can depend on this
17112 parameter. This parameter must be specified @emph{before} the name of the
17113 executable to be analyzed, to avoid ambiguity.
17114
17115 @item -b n
17116 @cindex @option{-b} (@code{gnatmem})
17117 This switch has the same effect as just depth parameter.
17118
17119 @item -i @var{file}
17120 @cindex @option{-i} (@code{gnatmem})
17121 Do the @code{gnatmem} processing starting from @file{file}, rather than
17122 @file{gmem.out} in the current directory.
17123
17124 @item -m n
17125 @cindex @option{-m} (@code{gnatmem})
17126 This switch causes @code{gnatmem} to mask the allocation roots that have less
17127 than n leaks. The default value is 1. Specifying the value of 0 will allow to
17128 examine even the roots that didn't result in leaks.
17129
17130 @item -s order
17131 @cindex @option{-s} (@code{gnatmem})
17132 This switch causes @code{gnatmem} to sort the allocation roots according to the
17133 specified order of sort criteria, each identified by a single letter. The
17134 currently supported criteria are @code{n, h, w} standing respectively for
17135 number of unfreed allocations, high watermark, and final watermark
17136 corresponding to a specific root. The default order is @code{nwh}.
17137
17138 @end table
17139
17140 @node Example of gnatmem Usage
17141 @subsection Example of @code{gnatmem} Usage
17142
17143 @noindent
17144 The following example shows the use of @code{gnatmem}
17145 on a simple memory-leaking program.
17146 Suppose that we have the following Ada program:
17147
17148 @smallexample @c ada
17149 @group
17150 @cartouche
17151 with Unchecked_Deallocation;
17152 procedure Test_Gm is
17153
17154    type T is array (1..1000) of Integer;
17155    type Ptr is access T;
17156    procedure Free is new Unchecked_Deallocation (T, Ptr);
17157    A : Ptr;
17158
17159    procedure My_Alloc is
17160    begin
17161       A := new T;
17162    end My_Alloc;
17163
17164    procedure My_DeAlloc is
17165       B : Ptr := A;
17166    begin
17167       Free (B);
17168    end My_DeAlloc;
17169
17170 begin
17171    My_Alloc;
17172    for I in 1 .. 5 loop
17173       for J in I .. 5 loop
17174          My_Alloc;
17175       end loop;
17176       My_Dealloc;
17177    end loop;
17178 end;
17179 @end cartouche
17180 @end group
17181 @end smallexample
17182
17183 @noindent
17184 The program needs to be compiled with debugging option and linked with
17185 @code{gmem} library:
17186
17187 @smallexample
17188 $ gnatmake -g test_gm -largs -lgmem
17189 @end smallexample
17190
17191 @noindent
17192 Then we execute the program as usual:
17193
17194 @smallexample
17195 $ test_gm
17196 @end smallexample
17197
17198 @noindent
17199 Then @code{gnatmem} is invoked simply with
17200 @smallexample
17201 $ gnatmem test_gm
17202 @end smallexample
17203
17204 @noindent
17205 which produces the following output (result may vary on different platforms):
17206
17207 @smallexample
17208 Global information
17209 ------------------
17210    Total number of allocations        :  18
17211    Total number of deallocations      :   5
17212    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17213    High Water Mark                    :  56.90 Kilobytes
17214
17215 Allocation Root # 1
17216 -------------------
17217  Number of non freed allocations    :  11
17218  Final Water Mark (non freed mem)   :  42.97 Kilobytes
17219  High Water Mark                    :  46.88 Kilobytes
17220  Backtrace                          :
17221    test_gm.adb:11 test_gm.my_alloc
17222
17223 Allocation Root # 2
17224 -------------------
17225  Number of non freed allocations    :   1
17226  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17227  High Water Mark                    :  10.02 Kilobytes
17228  Backtrace                          :
17229    s-secsta.adb:81 system.secondary_stack.ss_init
17230
17231 Allocation Root # 3
17232 -------------------
17233  Number of non freed allocations    :   1
17234  Final Water Mark (non freed mem)   :  12 Bytes
17235  High Water Mark                    :  12 Bytes
17236  Backtrace                          :
17237    s-secsta.adb:181 system.secondary_stack.ss_init
17238 @end smallexample
17239
17240 @noindent
17241 Note that the GNAT run time contains itself a certain number of
17242 allocations that have no  corresponding deallocation,
17243 as shown here for root #2 and root
17244 #3. This is a normal behavior when the number of non freed allocations
17245 is one, it allocates dynamic data structures that the run time needs for
17246 the complete lifetime of the program. Note also that there is only one
17247 allocation root in the user program with a single line back trace:
17248 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
17249 program shows that 'My_Alloc' is called at 2 different points in the
17250 source (line 21 and line 24). If those two allocation roots need to be
17251 distinguished, the backtrace depth parameter can be used:
17252
17253 @smallexample
17254 $ gnatmem 3 test_gm
17255 @end smallexample
17256
17257 @noindent
17258 which will give the following output:
17259
17260 @smallexample
17261 Global information
17262 ------------------
17263    Total number of allocations        :  18
17264    Total number of deallocations      :   5
17265    Final Water Mark (non freed mem)   :  53.00 Kilobytes
17266    High Water Mark                    :  56.90 Kilobytes
17267
17268 Allocation Root # 1
17269 -------------------
17270  Number of non freed allocations    :  10
17271  Final Water Mark (non freed mem)   :  39.06 Kilobytes
17272  High Water Mark                    :  42.97 Kilobytes
17273  Backtrace                          :
17274    test_gm.adb:11 test_gm.my_alloc
17275    test_gm.adb:24 test_gm
17276    b_test_gm.c:52 main
17277
17278 Allocation Root # 2
17279 -------------------
17280  Number of non freed allocations    :   1
17281  Final Water Mark (non freed mem)   :  10.02 Kilobytes
17282  High Water Mark                    :  10.02 Kilobytes
17283  Backtrace                          :
17284    s-secsta.adb:81  system.secondary_stack.ss_init
17285    s-secsta.adb:283 <system__secondary_stack___elabb>
17286    b_test_gm.c:33   adainit
17287
17288 Allocation Root # 3
17289 -------------------
17290  Number of non freed allocations    :   1
17291  Final Water Mark (non freed mem)   :   3.91 Kilobytes
17292  High Water Mark                    :   3.91 Kilobytes
17293  Backtrace                          :
17294    test_gm.adb:11 test_gm.my_alloc
17295    test_gm.adb:21 test_gm
17296    b_test_gm.c:52 main
17297
17298 Allocation Root # 4
17299 -------------------
17300  Number of non freed allocations    :   1
17301  Final Water Mark (non freed mem)   :  12 Bytes
17302  High Water Mark                    :  12 Bytes
17303  Backtrace                          :
17304    s-secsta.adb:181 system.secondary_stack.ss_init
17305    s-secsta.adb:283 <system__secondary_stack___elabb>
17306    b_test_gm.c:33   adainit
17307 @end smallexample
17308
17309 @noindent
17310 The allocation root #1 of the first example has been split in 2 roots #1
17311 and #3 thanks to the more precise associated backtrace.
17312
17313 @end ifclear
17314
17315
17316 @node The GNAT Debug Pool Facility
17317 @section The GNAT Debug Pool Facility
17318 @findex Debug Pool
17319 @cindex storage, pool, memory corruption
17320
17321 @noindent
17322 The use of unchecked deallocation and unchecked conversion can easily
17323 lead to incorrect memory references. The problems generated by such
17324 references are usually difficult to tackle because the symptoms can be
17325 very remote from the origin of the problem. In such cases, it is
17326 very helpful to detect the problem as early as possible. This is the
17327 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
17328
17329 In order to use the GNAT specific debugging pool, the user must
17330 associate a debug pool object with each of the access types that may be
17331 related to suspected memory problems. See Ada Reference Manual 13.11.
17332 @smallexample @c ada
17333 type Ptr is access Some_Type;
17334 Pool : GNAT.Debug_Pools.Debug_Pool;
17335 for Ptr'Storage_Pool use Pool;
17336 @end smallexample
17337
17338 @noindent
17339 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
17340 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
17341 allow the user to redefine allocation and deallocation strategies. They
17342 also provide a checkpoint for each dereference, through the use of
17343 the primitive operation @code{Dereference} which is implicitly called at
17344 each dereference of an access value.
17345
17346 Once an access type has been associated with a debug pool, operations on
17347 values of the type may raise four distinct exceptions,
17348 which correspond to four potential kinds of memory corruption:
17349 @itemize @bullet
17350 @item
17351 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
17352 @item
17353 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
17354 @item
17355 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
17356 @item
17357 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
17358 @end itemize
17359
17360 @noindent
17361 For types associated with a Debug_Pool, dynamic allocation is performed using
17362 the standard
17363 GNAT allocation routine. References to all allocated chunks of memory
17364 are kept in an internal dictionary.
17365 Several deallocation strategies are provided, whereupon the user can choose
17366 to release the memory to the system, keep it allocated for further invalid
17367 access checks, or fill it with an easily recognizable pattern for debug
17368 sessions.
17369 The memory pattern is the old IBM hexadecimal convention: @code{16#DEADBEEF#}.
17370
17371 See the documentation in the file g-debpoo.ads for more information on the
17372 various strategies.
17373
17374 Upon each dereference, a check is made that the access value denotes a
17375 properly allocated memory location. Here is a complete example of use of
17376 @code{Debug_Pools}, that includes typical instances of  memory corruption:
17377 @smallexample @c ada
17378 @iftex
17379 @leftskip=0cm
17380 @end iftex
17381 with Gnat.Io; use Gnat.Io;
17382 with Unchecked_Deallocation;
17383 with Unchecked_Conversion;
17384 with GNAT.Debug_Pools;
17385 with System.Storage_Elements;
17386 with Ada.Exceptions; use Ada.Exceptions;
17387 procedure Debug_Pool_Test is
17388
17389    type T is access Integer;
17390    type U is access all T;
17391
17392    P : GNAT.Debug_Pools.Debug_Pool;
17393    for T'Storage_Pool use P;
17394
17395    procedure Free is new Unchecked_Deallocation (Integer, T);
17396    function UC is new Unchecked_Conversion (U, T);
17397    A, B : aliased T;
17398
17399    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
17400
17401 begin
17402    Info (P);
17403    A := new Integer;
17404    B := new Integer;
17405    B := A;
17406    Info (P);
17407    Free (A);
17408    begin
17409       Put_Line (Integer'Image(B.all));
17410    exception
17411       when E : others => Put_Line ("raised: " & Exception_Name (E));
17412    end;
17413    begin
17414       Free (B);
17415    exception
17416       when E : others => Put_Line ("raised: " & Exception_Name (E));
17417    end;
17418    B := UC(A'Access);
17419    begin
17420       Put_Line (Integer'Image(B.all));
17421    exception
17422       when E : others => Put_Line ("raised: " & Exception_Name (E));
17423    end;
17424    begin
17425       Free (B);
17426    exception
17427       when E : others => Put_Line ("raised: " & Exception_Name (E));
17428    end;
17429    Info (P);
17430 end Debug_Pool_Test;
17431 @end smallexample
17432
17433 @noindent
17434 The debug pool mechanism provides the following precise diagnostics on the
17435 execution of this erroneous program:
17436 @smallexample
17437 Debug Pool info:
17438   Total allocated bytes :  0
17439   Total deallocated bytes :  0
17440   Current Water Mark:  0
17441   High Water Mark:  0
17442
17443 Debug Pool info:
17444   Total allocated bytes :  8
17445   Total deallocated bytes :  0
17446   Current Water Mark:  8
17447   High Water Mark:  8
17448
17449 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
17450 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
17451 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
17452 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
17453 Debug Pool info:
17454   Total allocated bytes :  8
17455   Total deallocated bytes :  4
17456   Current Water Mark:  4
17457   High Water Mark:  8
17458 @end smallexample
17459
17460
17461 @node Creating Sample Bodies Using gnatstub
17462 @chapter Creating Sample Bodies Using @command{gnatstub}
17463 @findex gnatstub
17464
17465 @noindent
17466 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
17467 for library unit declarations.
17468
17469 To create a body stub, @command{gnatstub} has to compile the library
17470 unit declaration. Therefore, bodies can be created only for legal
17471 library units. Moreover, if a library unit depends semantically upon
17472 units located outside the current directory, you have to provide
17473 the source search path when calling @command{gnatstub}, see the description
17474 of @command{gnatstub} switches below.
17475
17476 @menu
17477 * Running gnatstub::
17478 * Switches for gnatstub::
17479 @end menu
17480
17481 @node Running gnatstub
17482 @section Running @command{gnatstub}
17483
17484 @noindent
17485 @command{gnatstub} has the command-line interface of the form
17486
17487 @smallexample
17488 $ gnatstub [switches] filename [directory]
17489 @end smallexample
17490
17491 @noindent
17492 where
17493 @table @emph
17494 @item filename
17495 is the name of the source file that contains a library unit declaration
17496 for which a body must be created. The file name may contain the path
17497 information.
17498 The file name does not have to follow the GNAT file name conventions. If the
17499 name
17500 does not follow GNAT file naming conventions, the name of the body file must
17501 be provided
17502 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
17503 If the file name follows the GNAT file naming
17504 conventions and the name of the body file is not provided,
17505 @command{gnatstub}
17506 creates the name
17507 of the body file from the argument file name by replacing the @file{.ads}
17508 suffix
17509 with the @file{.adb} suffix.
17510
17511 @item directory
17512 indicates the directory in which the body stub is to be placed (the default
17513 is the
17514 current directory)
17515
17516 @item switches
17517 is an optional sequence of switches as described in the next section
17518 @end table
17519
17520 @node Switches for gnatstub
17521 @section Switches for @command{gnatstub}
17522
17523 @table @option
17524 @c !sort!
17525
17526 @item ^-f^/FULL^
17527 @cindex @option{^-f^/FULL^} (@command{gnatstub})
17528 If the destination directory already contains a file with the name of the
17529 body file
17530 for the argument spec file, replace it with the generated body stub.
17531
17532 @item ^-hs^/HEADER=SPEC^
17533 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
17534 Put the comment header (i.e., all the comments preceding the
17535 compilation unit) from the source of the library unit declaration
17536 into the body stub.
17537
17538 @item ^-hg^/HEADER=GENERAL^
17539 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
17540 Put a sample comment header into the body stub.
17541
17542 @ifclear vms
17543 @item -IDIR
17544 @cindex @option{-IDIR} (@command{gnatstub})
17545 @itemx -I-
17546 @cindex @option{-I-} (@command{gnatstub})
17547 @end ifclear
17548 @ifset vms
17549 @item /NOCURRENT_DIRECTORY
17550 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
17551 @end ifset
17552 ^These switches have ^This switch has^ the same meaning as in calls to
17553 @command{gcc}.
17554 ^They define ^It defines ^ the source search path in the call to
17555 @command{gcc} issued
17556 by @command{gnatstub} to compile an argument source file.
17557
17558 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
17559 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
17560 This switch has the same meaning as in calls to @command{gcc}.
17561 It defines the additional configuration file to be passed to the call to
17562 @command{gcc} issued
17563 by @command{gnatstub} to compile an argument source file.
17564
17565 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
17566 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
17567 (@var{n} is a non-negative integer). Set the maximum line length in the
17568 body stub to @var{n}; the default is 79. The maximum value that can be
17569 specified is 32767.
17570
17571 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
17572 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
17573 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
17574 the generated body sample to @var{n}.
17575 The default indentation is 3.
17576
17577 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
17578 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
17579 Order local bodies alphabetically. (By default local bodies are ordered
17580 in the same way as the corresponding local specs in the argument spec file.)
17581
17582 @item ^-i^/INDENTATION=^@var{n}
17583 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
17584 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
17585
17586 @item ^-k^/TREE_FILE=SAVE^
17587 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
17588 Do not remove the tree file (i.e., the snapshot of the compiler internal
17589 structures used by @command{gnatstub}) after creating the body stub.
17590
17591 @item ^-l^/LINE_LENGTH=^@var{n}
17592 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
17593 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
17594
17595 @item ^-o^/BODY=^@var{body-name}
17596 @cindex @option{^-o^/BODY^} (@command{gnatstub})
17597 Body file name.  This should be set if the argument file name does not
17598 follow
17599 the GNAT file naming
17600 conventions. If this switch is omitted the default name for the body will be
17601 obtained
17602 from the argument file name according to the GNAT file naming conventions.
17603
17604 @item ^-q^/QUIET^
17605 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
17606 Quiet mode: do not generate a confirmation when a body is
17607 successfully created, and do not generate a message when a body is not
17608 required for an
17609 argument unit.
17610
17611 @item ^-r^/TREE_FILE=REUSE^
17612 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
17613 Reuse the tree file (if it exists) instead of creating it.  Instead of
17614 creating the tree file for the library unit declaration, @command{gnatstub}
17615 tries to find it in the current directory and use it for creating
17616 a body. If the tree file is not found, no body is created. This option
17617 also implies @option{^-k^/SAVE^}, whether or not
17618 the latter is set explicitly.
17619
17620 @item ^-t^/TREE_FILE=OVERWRITE^
17621 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
17622 Overwrite the existing tree file.  If the current directory already
17623 contains the file which, according to the GNAT file naming rules should
17624 be considered as a tree file for the argument source file,
17625 @command{gnatstub}
17626 will refuse to create the tree file needed to create a sample body
17627 unless this option is set.
17628
17629 @item ^-v^/VERBOSE^
17630 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
17631 Verbose mode: generate version information.
17632
17633 @end table
17634
17635
17636 @node Other Utility Programs
17637 @chapter Other Utility Programs
17638
17639 @noindent
17640 This chapter discusses some other utility programs available in the Ada
17641 environment.
17642
17643 @menu
17644 * Using Other Utility Programs with GNAT::
17645 * The External Symbol Naming Scheme of GNAT::
17646 @ifclear vms
17647 * Ada Mode for Glide::
17648 @end ifclear
17649 * Converting Ada Files to html with gnathtml::
17650 * Installing gnathtml::
17651 @ifset vms
17652 * LSE::
17653 * Profiling::
17654 @end ifset
17655 @end menu
17656
17657 @node Using Other Utility Programs with GNAT
17658 @section Using Other Utility Programs with GNAT
17659
17660 @noindent
17661 The object files generated by GNAT are in standard system format and in
17662 particular the debugging information uses this format. This means
17663 programs generated by GNAT can be used with existing utilities that
17664 depend on these formats.
17665
17666 @ifclear vms
17667 In general, any utility program that works with C will also often work with
17668 Ada programs generated by GNAT. This includes software utilities such as
17669 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
17670 as Purify.
17671 @end ifclear
17672
17673 @node The External Symbol Naming Scheme of GNAT
17674 @section The External Symbol Naming Scheme of GNAT
17675
17676 @noindent
17677 In order to interpret the output from GNAT, when using tools that are
17678 originally intended for use with other languages, it is useful to
17679 understand the conventions used to generate link names from the Ada
17680 entity names.
17681
17682 All link names are in all lowercase letters. With the exception of library
17683 procedure names, the mechanism used is simply to use the full expanded
17684 Ada name with dots replaced by double underscores. For example, suppose
17685 we have the following package spec:
17686
17687 @smallexample @c ada
17688 @group
17689 @cartouche
17690 package QRS is
17691    MN : Integer;
17692 end QRS;
17693 @end cartouche
17694 @end group
17695 @end smallexample
17696
17697 @noindent
17698 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
17699 the corresponding link name is @code{qrs__mn}.
17700 @findex Export
17701 Of course if a @code{pragma Export} is used this may be overridden:
17702
17703 @smallexample @c ada
17704 @group
17705 @cartouche
17706 package Exports is
17707    Var1 : Integer;
17708    pragma Export (Var1, C, External_Name => "var1_name");
17709    Var2 : Integer;
17710    pragma Export (Var2, C, Link_Name => "var2_link_name");
17711 end Exports;
17712 @end cartouche
17713 @end group
17714 @end smallexample
17715
17716 @noindent
17717 In this case, the link name for @var{Var1} is whatever link name the
17718 C compiler would assign for the C function @var{var1_name}. This typically
17719 would be either @var{var1_name} or @var{_var1_name}, depending on operating
17720 system conventions, but other possibilities exist. The link name for
17721 @var{Var2} is @var{var2_link_name}, and this is not operating system
17722 dependent.
17723
17724 @findex _main
17725 One exception occurs for library level procedures. A potential ambiguity
17726 arises between the required name @code{_main} for the C main program,
17727 and the name we would otherwise assign to an Ada library level procedure
17728 called @code{Main} (which might well not be the main program).
17729
17730 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
17731 names. So if we have a library level procedure such as
17732
17733 @smallexample @c ada
17734 @group
17735 @cartouche
17736 procedure Hello (S : String);
17737 @end cartouche
17738 @end group
17739 @end smallexample
17740
17741 @noindent
17742 the external name of this procedure will be @var{_ada_hello}.
17743
17744 @ifclear vms
17745 @node Ada Mode for Glide
17746 @section Ada Mode for @code{Glide}
17747 @cindex Ada mode (for Glide)
17748
17749 @noindent
17750 The Glide mode for programming in Ada (both Ada83 and Ada95) helps the
17751 user to understand and navigate existing code, and facilitates writing
17752 new code. It furthermore provides some utility functions for easier
17753 integration of standard Emacs features when programming in Ada.
17754
17755 Its general features include:
17756
17757 @itemize @bullet
17758 @item
17759 An Integrated Development Environment with functionality such as the
17760 following
17761
17762 @itemize @bullet
17763 @item
17764 ``Project files'' for configuration-specific aspects
17765 (e.g. directories and compilation options)
17766
17767 @item
17768 Compiling and stepping through error messages.
17769
17770 @item
17771 Running and debugging an applications within Glide.
17772 @end itemize
17773
17774 @item
17775 Pull-down menus
17776
17777 @item
17778 User configurability
17779 @end itemize
17780
17781 Some of the specific Ada mode features are:
17782
17783 @itemize @bullet
17784 @item
17785 Functions for easy and quick stepping through Ada code
17786
17787 @item
17788 Getting cross reference information for identifiers (e.g., finding a
17789 defining occurrence)
17790
17791 @item
17792 Displaying an index menu of types and subprograms, allowing
17793 direct selection for browsing
17794
17795 @item
17796 Automatic color highlighting of the various Ada entities
17797 @end itemize
17798
17799 Glide directly supports writing Ada code, via several facilities:
17800
17801 @itemize @bullet
17802 @item
17803 Switching between spec and body files with possible
17804 autogeneration of body files
17805
17806 @item
17807 Automatic formating of subprogram parameter lists
17808
17809 @item
17810 Automatic indentation according to Ada syntax
17811
17812 @item
17813 Automatic completion of identifiers
17814
17815 @item
17816 Automatic (and configurable) casing of identifiers, keywords, and attributes
17817
17818 @item
17819 Insertion of syntactic templates
17820
17821 @item
17822 Block commenting / uncommenting
17823 @end itemize
17824
17825 @noindent
17826 For more information, please refer to the online documentation
17827 available in the @code{Glide} @result{} @code{Help} menu.
17828 @end ifclear
17829
17830
17831 @node Converting Ada Files to html with gnathtml
17832 @section Converting Ada Files to HTML with @code{gnathtml}
17833
17834 @noindent
17835 This @code{Perl} script allows Ada source files to be browsed using
17836 standard Web browsers. For installation procedure, see the section
17837 @xref{Installing gnathtml}.
17838
17839 Ada reserved keywords are highlighted in a bold font and Ada comments in
17840 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
17841 switch to suppress the generation of cross-referencing information, user
17842 defined variables and types will appear in a different color; you will
17843 be able to click on any identifier and go to its declaration.
17844
17845 The command line is as follow:
17846 @smallexample
17847 $ perl gnathtml.pl [switches] ada-files
17848 @end smallexample
17849
17850 @noindent
17851 You can pass it as many Ada files as you want. @code{gnathtml} will generate
17852 an html file for every ada file, and a global file called @file{index.htm}.
17853 This file is an index of every identifier defined in the files.
17854
17855 The available switches are the following ones :
17856
17857 @table @option
17858 @item -83
17859 @cindex @option{-83} (@code{gnathtml})
17860 Only the subset on the Ada 83 keywords will be highlighted, not the full
17861 Ada 95 keywords set.
17862
17863 @item -cc @var{color}
17864 @cindex @option{-cc} (@code{gnathtml})
17865 This option allows you to change the color used for comments. The default
17866 value is green. The color argument can be any name accepted by html.
17867
17868 @item -d
17869 @cindex @option{-d} (@code{gnathtml})
17870 If the ada files depend on some other files (using for instance the
17871 @code{with} command, the latter will also be converted to html.
17872 Only the files in the user project will be converted to html, not the files
17873 in the run-time library itself.
17874
17875 @item -D
17876 @cindex @option{-D} (@code{gnathtml})
17877 This command is the same as @option{-d} above, but @command{gnathtml} will
17878 also look for files in the run-time library, and generate html files for them.
17879
17880 @item -ext @var{extension}
17881 @cindex @option{-ext} (@code{gnathtml})
17882 This option allows you to change the extension of the generated HTML files.
17883 If you do not specify an extension, it will default to @file{htm}.
17884
17885 @item -f
17886 @cindex @option{-f} (@code{gnathtml})
17887 By default, gnathtml will generate html links only for global entities
17888 ('with'ed units, global variables and types,...). If you specify the
17889 @option{-f} on the command line, then links will be generated for local
17890 entities too.
17891
17892 @item -l @var{number}
17893 @cindex @option{-l} (@code{gnathtml})
17894 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
17895 will number the html files every @var{number} line.
17896
17897 @item -I @var{dir}
17898 @cindex @option{-I} (@code{gnathtml})
17899 Specify a directory to search for library files (@file{.ALI} files) and
17900 source files. You can provide several -I switches on the command line,
17901 and the directories will be parsed in the order of the command line.
17902
17903 @item -o @var{dir}
17904 @cindex @option{-o} (@code{gnathtml})
17905 Specify the output directory for html files. By default, gnathtml will
17906 saved the generated html files in a subdirectory named @file{html/}.
17907
17908 @item -p @var{file}
17909 @cindex @option{-p} (@code{gnathtml})
17910 If you are using Emacs and the most recent Emacs Ada mode, which provides
17911 a full Integrated Development Environment for compiling, checking,
17912 running and debugging applications, you may use @file{.gpr} files
17913 to give the directories where Emacs can find sources and object files.
17914
17915 Using this switch, you can tell gnathtml to use these files. This allows
17916 you to get an html version of your application, even if it is spread
17917 over multiple directories.
17918
17919 @item -sc @var{color}
17920 @cindex @option{-sc} (@code{gnathtml})
17921 This option allows you to change the color used for symbol definitions.
17922 The default value is red. The color argument can be any name accepted by html.
17923
17924 @item -t @var{file}
17925 @cindex @option{-t} (@code{gnathtml})
17926 This switch provides the name of a file. This file contains a list of
17927 file names to be converted, and the effect is exactly as though they had
17928 appeared explicitly on the command line. This
17929 is the recommended way to work around the command line length limit on some
17930 systems.
17931
17932 @end table
17933
17934 @node Installing gnathtml
17935 @section Installing @code{gnathtml}
17936
17937 @noindent
17938 @code{Perl} needs to be installed on your machine to run this script.
17939 @code{Perl} is freely available for almost every architecture and
17940 Operating System via the Internet.
17941
17942 On Unix systems, you  may want to modify  the  first line of  the script
17943 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
17944 is. The syntax of this line is :
17945 @smallexample
17946 #!full_path_name_to_perl
17947 @end smallexample
17948
17949 @noindent
17950 Alternatively, you may run the script using the following command line:
17951
17952 @smallexample
17953 $ perl gnathtml.pl [switches] files
17954 @end smallexample
17955
17956 @ifset vms
17957 @node LSE
17958 @section LSE
17959 @findex LSE
17960
17961 @noindent
17962 The GNAT distribution provides an Ada 95 template for the Digital Language
17963 Sensitive Editor (LSE), a component of DECset. In order to
17964 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
17965
17966 @node Profiling
17967 @section Profiling
17968 @findex PCA
17969
17970 @noindent
17971 GNAT supports The Digital Performance Coverage Analyzer (PCA), a component
17972 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
17973 the collection phase with the /DEBUG qualifier.
17974
17975 @smallexample
17976 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
17977 $ DEFINE LIB$DEBUG PCA$COLLECTOR
17978 $ RUN/DEBUG <PROGRAM_NAME>
17979 @end smallexample
17980 @noindent
17981 @end ifset
17982
17983 @node Running and Debugging Ada Programs
17984 @chapter Running and Debugging Ada Programs
17985 @cindex Debugging
17986
17987 @noindent
17988 This chapter discusses how to debug Ada programs. An incorrect Ada program
17989 may be handled in three ways by the GNAT compiler:
17990
17991 @enumerate
17992 @item
17993 The illegality may be a violation of the static semantics of Ada. In
17994 that case GNAT diagnoses the constructs in the program that are illegal.
17995 It is then a straightforward matter for the user to modify those parts of
17996 the program.
17997
17998 @item
17999 The illegality may be a violation of the dynamic semantics of Ada. In
18000 that case the program compiles and executes, but may generate incorrect
18001 results, or may terminate abnormally with some exception.
18002
18003 @item
18004 When presented with a program that contains convoluted errors, GNAT
18005 itself may terminate abnormally without providing full diagnostics on
18006 the incorrect user program.
18007 @end enumerate
18008
18009 @menu
18010 * The GNAT Debugger GDB::
18011 * Running GDB::
18012 * Introduction to GDB Commands::
18013 * Using Ada Expressions::
18014 * Calling User-Defined Subprograms::
18015 * Using the Next Command in a Function::
18016 * Ada Exceptions::
18017 * Ada Tasks::
18018 * Debugging Generic Units::
18019 * GNAT Abnormal Termination or Failure to Terminate::
18020 * Naming Conventions for GNAT Source Files::
18021 * Getting Internal Debugging Information::
18022 * Stack Traceback::
18023 @end menu
18024
18025 @cindex Debugger
18026 @findex gdb
18027
18028 @node The GNAT Debugger GDB
18029 @section The GNAT Debugger GDB
18030
18031 @noindent
18032 @code{GDB} is a general purpose, platform-independent debugger that
18033 can be used to debug mixed-language programs compiled with @code{GCC},
18034 and in particular is capable of debugging Ada programs compiled with
18035 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18036 complex Ada data structures.
18037
18038 The manual @cite{Debugging with GDB}
18039 @ifset vms
18040 , located in the GNU:[DOCS] directory,
18041 @end ifset
18042 contains full details on the usage of @code{GDB}, including a section on
18043 its usage on programs. This manual should be consulted for full
18044 details. The section that follows is a brief introduction to the
18045 philosophy and use of @code{GDB}.
18046
18047 When GNAT programs are compiled, the compiler optionally writes debugging
18048 information into the generated object file, including information on
18049 line numbers, and on declared types and variables. This information is
18050 separate from the generated code. It makes the object files considerably
18051 larger, but it does not add to the size of the actual executable that
18052 will be loaded into memory, and has no impact on run-time performance. The
18053 generation of debug information is triggered by the use of the
18054 ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
18055 the compilations. It is important to emphasize that the use of these
18056 options does not change the generated code.
18057
18058 The debugging information is written in standard system formats that
18059 are used by many tools, including debuggers and profilers. The format
18060 of the information is typically designed to describe C types and
18061 semantics, but GNAT implements a translation scheme which allows full
18062 details about Ada types and variables to be encoded into these
18063 standard C formats. Details of this encoding scheme may be found in
18064 the file exp_dbug.ads in the GNAT source distribution. However, the
18065 details of this encoding are, in general, of no interest to a user,
18066 since @code{GDB} automatically performs the necessary decoding.
18067
18068 When a program is bound and linked, the debugging information is
18069 collected from the object files, and stored in the executable image of
18070 the program. Again, this process significantly increases the size of
18071 the generated executable file, but it does not increase the size of
18072 the executable program itself. Furthermore, if this program is run in
18073 the normal manner, it runs exactly as if the debug information were
18074 not present, and takes no more actual memory.
18075
18076 However, if the program is run under control of @code{GDB}, the
18077 debugger is activated.  The image of the program is loaded, at which
18078 point it is ready to run.  If a run command is given, then the program
18079 will run exactly as it would have if @code{GDB} were not present. This
18080 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
18081 entirely non-intrusive until a breakpoint is encountered.  If no
18082 breakpoint is ever hit, the program will run exactly as it would if no
18083 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18084 the debugging information and can respond to user commands to inspect
18085 variables, and more generally to report on the state of execution.
18086
18087 @c **************
18088 @node Running GDB
18089 @section Running GDB
18090
18091 @noindent
18092 The debugger can be launched directly and simply from @code{glide} or
18093 through its graphical interface: @code{gvd}. It can also be used
18094 directly in text mode. Here is described the basic use of @code{GDB}
18095 in text mode. All the commands described below can be used in the
18096 @code{gvd} console window even though there is usually other more
18097 graphical ways to achieve the same goals.
18098
18099 @ifclear vms
18100 @noindent
18101 The command to run the graphical interface of the debugger is
18102 @smallexample
18103 $ gvd program
18104 @end smallexample
18105 @end ifclear
18106
18107 @noindent
18108 The command to run @code{GDB} in text mode is
18109
18110 @smallexample
18111 $ ^gdb program^$ GDB PROGRAM^
18112 @end smallexample
18113
18114 @noindent
18115 where @code{^program^PROGRAM^} is the name of the executable file. This
18116 activates the debugger and results in a prompt for debugger commands.
18117 The simplest command is simply @code{run}, which causes the program to run
18118 exactly as if the debugger were not present. The following section
18119 describes some of the additional commands that can be given to @code{GDB}.
18120
18121
18122 @c *******************************
18123 @node Introduction to GDB Commands
18124 @section Introduction to GDB Commands
18125
18126 @noindent
18127 @code{GDB} contains a large repertoire of commands. The manual
18128 @cite{Debugging with GDB}
18129 @ifset vms
18130 , located in the GNU:[DOCS] directory,
18131 @end ifset
18132 includes extensive documentation on the use
18133 of these commands, together with examples of their use. Furthermore,
18134 the command @var{help} invoked from within @code{GDB} activates a simple help
18135 facility which summarizes the available commands and their options.
18136 In this section we summarize a few of the most commonly
18137 used commands to give an idea of what @code{GDB} is about. You should create
18138 a simple program with debugging information and experiment with the use of
18139 these @code{GDB} commands on the program as you read through the
18140 following section.
18141
18142 @table @code
18143 @item set args @var{arguments}
18144 The @var{arguments} list above is a list of arguments to be passed to
18145 the program on a subsequent run command, just as though the arguments
18146 had been entered on a normal invocation of the program. The @code{set args}
18147 command is not needed if the program does not require arguments.
18148
18149 @item run
18150 The @code{run} command causes execution of the program to start from
18151 the beginning. If the program is already running, that is to say if
18152 you are currently positioned at a breakpoint, then a prompt will ask
18153 for confirmation that you want to abandon the current execution and
18154 restart.
18155
18156 @item breakpoint @var{location}
18157 The breakpoint command sets a breakpoint, that is to say a point at which
18158 execution will halt and @code{GDB} will await further
18159 commands. @var{location} is
18160 either a line number within a file, given in the format @code{file:linenumber},
18161 or it is the name of a subprogram. If you request that a breakpoint be set on
18162 a subprogram that is overloaded, a prompt will ask you to specify on which of
18163 those subprograms you want to breakpoint. You can also
18164 specify that all of them should be breakpointed. If the program is run
18165 and execution encounters the breakpoint, then the program
18166 stops and @code{GDB} signals that the breakpoint was encountered by
18167 printing the line of code before which the program is halted.
18168
18169 @item breakpoint exception @var{name}
18170 A special form of the breakpoint command which breakpoints whenever
18171 exception @var{name} is raised.
18172 If @var{name} is omitted,
18173 then a breakpoint will occur when any exception is raised.
18174
18175 @item print @var{expression}
18176 This will print the value of the given expression. Most simple
18177 Ada expression formats are properly handled by @code{GDB}, so the expression
18178 can contain function calls, variables, operators, and attribute references.
18179
18180 @item continue
18181 Continues execution following a breakpoint, until the next breakpoint or the
18182 termination of the program.
18183
18184 @item step
18185 Executes a single line after a breakpoint. If the next statement
18186 is a subprogram call, execution continues into (the first statement of)
18187 the called subprogram.
18188
18189 @item next
18190 Executes a single line. If this line is a subprogram call, executes and
18191 returns from the call.
18192
18193 @item list
18194 Lists a few lines around the current source location. In practice, it
18195 is usually more convenient to have a separate edit window open with the
18196 relevant source file displayed. Successive applications of this command
18197 print subsequent lines. The command can be given an argument which is a
18198 line number, in which case it displays a few lines around the specified one.
18199
18200 @item backtrace
18201 Displays a backtrace of the call chain. This command is typically
18202 used after a breakpoint has occurred, to examine the sequence of calls that
18203 leads to the current breakpoint. The display includes one line for each
18204 activation record (frame) corresponding to an active subprogram.
18205
18206 @item up
18207 At a breakpoint, @code{GDB} can display the values of variables local
18208 to the current frame. The command @code{up} can be used to
18209 examine the contents of other active frames, by moving the focus up
18210 the stack, that is to say from callee to caller, one frame at a time.
18211
18212 @item down
18213 Moves the focus of @code{GDB} down from the frame currently being
18214 examined to the frame of its callee (the reverse of the previous command),
18215
18216 @item frame @var{n}
18217 Inspect the frame with the given number. The value 0 denotes the frame
18218 of the current breakpoint, that is to say the top of the call stack.
18219
18220 @end table
18221
18222 The above list is a very short introduction to the commands that
18223 @code{GDB} provides. Important additional capabilities, including conditional
18224 breakpoints, the ability to execute command sequences on a breakpoint,
18225 the ability to debug at the machine instruction level and many other
18226 features are described in detail in @cite{Debugging with GDB}.
18227 Note that most commands can be abbreviated
18228 (for example, c for continue, bt for backtrace).
18229
18230 @node Using Ada Expressions
18231 @section Using Ada Expressions
18232 @cindex Ada expressions
18233
18234 @noindent
18235 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
18236 extensions. The philosophy behind the design of this subset is
18237
18238 @itemize @bullet
18239 @item
18240 That @code{GDB} should provide basic literals and access to operations for
18241 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
18242 leaving more sophisticated computations to subprograms written into the
18243 program (which therefore may be called from @code{GDB}).
18244
18245 @item
18246 That type safety and strict adherence to Ada language restrictions
18247 are not particularly important to the @code{GDB} user.
18248
18249 @item
18250 That brevity is important to the @code{GDB} user.
18251 @end itemize
18252
18253 Thus, for brevity, the debugger acts as if there were
18254 implicit @code{with} and @code{use} clauses in effect for all user-written
18255 packages, thus making it unnecessary to fully qualify most names with
18256 their packages, regardless of context. Where this causes ambiguity,
18257 @code{GDB} asks the user's intent.
18258
18259 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
18260
18261 @node Calling User-Defined Subprograms
18262 @section Calling User-Defined Subprograms
18263
18264 @noindent
18265 An important capability of @code{GDB} is the ability to call user-defined
18266 subprograms while debugging. This is achieved simply by entering
18267 a subprogram call statement in the form:
18268
18269 @smallexample
18270 call subprogram-name (parameters)
18271 @end smallexample
18272
18273 @noindent
18274 The keyword @code{call} can be omitted in the normal case where the
18275 @code{subprogram-name} does not coincide with any of the predefined
18276 @code{GDB} commands.
18277
18278 The effect is to invoke the given subprogram, passing it the
18279 list of parameters that is supplied. The parameters can be expressions and
18280 can include variables from the program being debugged. The
18281 subprogram must be defined
18282 at the library level within your program, and @code{GDB} will call the
18283 subprogram within the environment of your program execution (which
18284 means that the subprogram is free to access or even modify variables
18285 within your program).
18286
18287 The most important use of this facility is in allowing the inclusion of
18288 debugging routines that are tailored to particular data structures
18289 in your program. Such debugging routines can be written to provide a suitably
18290 high-level description of an abstract type, rather than a low-level dump
18291 of its physical layout. After all, the standard
18292 @code{GDB print} command only knows the physical layout of your
18293 types, not their abstract meaning. Debugging routines can provide information
18294 at the desired semantic level and are thus enormously useful.
18295
18296 For example, when debugging GNAT itself, it is crucial to have access to
18297 the contents of the tree nodes used to represent the program internally.
18298 But tree nodes are represented simply by an integer value (which in turn
18299 is an index into a table of nodes).
18300 Using the @code{print} command on a tree node would simply print this integer
18301 value, which is not very useful. But the PN routine (defined in file
18302 treepr.adb in the GNAT sources) takes a tree node as input, and displays
18303 a useful high level representation of the tree node, which includes the
18304 syntactic category of the node, its position in the source, the integers
18305 that denote descendant nodes and parent node, as well as varied
18306 semantic information. To study this example in more detail, you might want to
18307 look at the body of the PN procedure in the stated file.
18308
18309 @node Using the Next Command in a Function
18310 @section Using the Next Command in a Function
18311
18312 @noindent
18313 When you use the @code{next} command in a function, the current source
18314 location will advance to the next statement as usual. A special case
18315 arises in the case of a @code{return} statement.
18316
18317 Part of the code for a return statement is the ``epilog'' of the function.
18318 This is the code that returns to the caller. There is only one copy of
18319 this epilog code, and it is typically associated with the last return
18320 statement in the function if there is more than one return. In some
18321 implementations, this epilog is associated with the first statement
18322 of the function.
18323
18324 The result is that if you use the @code{next} command from a return
18325 statement that is not the last return statement of the function you
18326 may see a strange apparent jump to the last return statement or to
18327 the start of the function. You should simply ignore this odd jump.
18328 The value returned is always that from the first return statement
18329 that was stepped through.
18330
18331 @node Ada Exceptions
18332 @section Breaking on Ada Exceptions
18333 @cindex Exceptions
18334
18335 @noindent
18336 You can set breakpoints that trip when your program raises
18337 selected exceptions.
18338
18339 @table @code
18340 @item break exception
18341 Set a breakpoint that trips whenever (any task in the) program raises
18342 any exception.
18343
18344 @item break exception @var{name}
18345 Set a breakpoint that trips whenever (any task in the) program raises
18346 the exception @var{name}.
18347
18348 @item break exception unhandled
18349 Set a breakpoint that trips whenever (any task in the) program raises an
18350 exception for which there is no handler.
18351
18352 @item info exceptions
18353 @itemx info exceptions @var{regexp}
18354 The @code{info exceptions} command permits the user to examine all defined
18355 exceptions within Ada programs. With a regular expression, @var{regexp}, as
18356 argument, prints out only those exceptions whose name matches @var{regexp}.
18357 @end table
18358
18359 @node Ada Tasks
18360 @section Ada Tasks
18361 @cindex Tasks
18362
18363 @noindent
18364 @code{GDB} allows the following task-related commands:
18365
18366 @table @code
18367 @item info tasks
18368 This command shows a list of current Ada tasks, as in the following example:
18369
18370 @smallexample
18371 @iftex
18372 @leftskip=0cm
18373 @end iftex
18374 (gdb) info tasks
18375   ID       TID P-ID   Thread Pri State                 Name
18376    1   8088000   0   807e000  15 Child Activation Wait main_task
18377    2   80a4000   1   80ae000  15 Accept/Select Wait    b
18378    3   809a800   1   80a4800  15 Child Activation Wait a
18379 *  4   80ae800   3   80b8000  15 Running               c
18380 @end smallexample
18381
18382 @noindent
18383 In this listing, the asterisk before the first task indicates it to be the
18384 currently running task. The first column lists the task ID that is used
18385 to refer to tasks in the following commands.
18386
18387 @item break @var{linespec} task @var{taskid}
18388 @itemx break @var{linespec} task @var{taskid} if @dots{}
18389 @cindex Breakpoints and tasks
18390 These commands are like the @code{break @dots{} thread @dots{}}.
18391 @var{linespec} specifies source lines.
18392
18393 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
18394 to specify that you only want @code{GDB} to stop the program when a
18395 particular Ada task reaches this breakpoint. @var{taskid} is one of the
18396 numeric task identifiers assigned by @code{GDB}, shown in the first
18397 column of the @samp{info tasks} display.
18398
18399 If you do not specify @samp{task @var{taskid}} when you set a
18400 breakpoint, the breakpoint applies to @emph{all} tasks of your
18401 program.
18402
18403 You can use the @code{task} qualifier on conditional breakpoints as
18404 well; in this case, place @samp{task @var{taskid}} before the
18405 breakpoint condition (before the @code{if}).
18406
18407 @item task @var{taskno}
18408 @cindex Task switching
18409
18410 This command allows to switch to the task referred by @var{taskno}. In
18411 particular, This allows to browse the backtrace of the specified
18412 task. It is advised to switch back to the original task before
18413 continuing execution otherwise the scheduling of the program may be
18414 perturbated.
18415 @end table
18416
18417 @noindent
18418 For more detailed information on the tasking support,
18419 see @cite{Debugging with GDB}.
18420
18421 @node Debugging Generic Units
18422 @section Debugging Generic Units
18423 @cindex Debugging Generic Units
18424 @cindex Generics
18425
18426 @noindent
18427 GNAT always uses code expansion for generic instantiation. This means that
18428 each time an instantiation occurs, a complete copy of the original code is
18429 made, with appropriate substitutions of formals by actuals.
18430
18431 It is not possible to refer to the original generic entities in
18432 @code{GDB}, but it is always possible to debug a particular instance of
18433 a generic, by using the appropriate expanded names. For example, if we have
18434
18435 @smallexample @c ada
18436 @group
18437 @cartouche
18438 procedure g is
18439
18440    generic package k is
18441       procedure kp (v1 : in out integer);
18442    end k;
18443
18444    package body k is
18445       procedure kp (v1 : in out integer) is
18446       begin
18447          v1 := v1 + 1;
18448       end kp;
18449    end k;
18450
18451    package k1 is new k;
18452    package k2 is new k;
18453
18454    var : integer := 1;
18455
18456 begin
18457    k1.kp (var);
18458    k2.kp (var);
18459    k1.kp (var);
18460    k2.kp (var);
18461 end;
18462 @end cartouche
18463 @end group
18464 @end smallexample
18465
18466 @noindent
18467 Then to break on a call to procedure kp in the k2 instance, simply
18468 use the command:
18469
18470 @smallexample
18471 (gdb) break g.k2.kp
18472 @end smallexample
18473
18474 @noindent
18475 When the breakpoint occurs, you can step through the code of the
18476 instance in the normal manner and examine the values of local variables, as for
18477 other units.
18478
18479 @node GNAT Abnormal Termination or Failure to Terminate
18480 @section GNAT Abnormal Termination or Failure to Terminate
18481 @cindex GNAT Abnormal Termination or Failure to Terminate
18482
18483 @noindent
18484 When presented with programs that contain serious errors in syntax
18485 or semantics,
18486 GNAT may on rare occasions  experience problems in operation, such
18487 as aborting with a
18488 segmentation fault or illegal memory access, raising an internal
18489 exception, terminating abnormally, or failing to terminate at all.
18490 In such cases, you can activate
18491 various features of GNAT that can help you pinpoint the construct in your
18492 program that is the likely source of the problem.
18493
18494 The following strategies are presented in increasing order of
18495 difficulty, corresponding to your experience in using GNAT and your
18496 familiarity with compiler internals.
18497
18498 @enumerate
18499 @item
18500 Run @code{gcc} with the @option{-gnatf}. This first
18501 switch causes all errors on a given line to be reported. In its absence,
18502 only the first error on a line is displayed.
18503
18504 The @option{-gnatdO} switch causes errors to be displayed as soon as they
18505 are encountered, rather than after compilation is terminated. If GNAT
18506 terminates prematurely or goes into an infinite loop, the last error
18507 message displayed may help to pinpoint the culprit.
18508
18509 @item
18510 Run @code{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this mode,
18511 @code{gcc} produces ongoing information about the progress of the
18512 compilation and provides the name of each procedure as code is
18513 generated. This switch allows you to find which Ada procedure was being
18514 compiled when it encountered a code generation problem.
18515
18516 @item
18517 @cindex @option{-gnatdc} switch
18518 Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
18519 switch that does for the front-end what @option{^-v^VERBOSE^} does
18520 for the back end. The system prints the name of each unit,
18521 either a compilation unit or nested unit, as it is being analyzed.
18522 @item
18523 Finally, you can start
18524 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
18525 front-end of GNAT, and can be run independently (normally it is just
18526 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
18527 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
18528 @code{where} command is the first line of attack; the variable
18529 @code{lineno} (seen by @code{print lineno}), used by the second phase of
18530 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
18531 which the execution stopped, and @code{input_file name} indicates the name of
18532 the source file.
18533 @end enumerate
18534
18535 @node Naming Conventions for GNAT Source Files
18536 @section Naming Conventions for GNAT Source Files
18537
18538 @noindent
18539 In order to examine the workings of the GNAT system, the following
18540 brief description of its organization may be helpful:
18541
18542 @itemize @bullet
18543 @item
18544 Files with prefix @file{^sc^SC^} contain the lexical scanner.
18545
18546 @item
18547 All files prefixed with @file{^par^PAR^} are components of the parser. The
18548 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
18549 parsing of select statements can be found in @file{par-ch9.adb}.
18550
18551 @item
18552 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
18553 numbers correspond to chapters of the Ada standard. For example, all
18554 issues involving context clauses can be found in @file{sem_ch10.adb}. In
18555 addition, some features of the language require sufficient special processing
18556 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
18557 dynamic dispatching, etc.
18558
18559 @item
18560 All files prefixed with @file{^exp^EXP^} perform normalization and
18561 expansion of the intermediate representation (abstract syntax tree, or AST).
18562 these files use the same numbering scheme as the parser and semantics files.
18563 For example, the construction of record initialization procedures is done in
18564 @file{exp_ch3.adb}.
18565
18566 @item
18567 The files prefixed with @file{^bind^BIND^} implement the binder, which
18568 verifies the consistency of the compilation, determines an order of
18569 elaboration, and generates the bind file.
18570
18571 @item
18572 The files @file{atree.ads} and @file{atree.adb} detail the low-level
18573 data structures used by the front-end.
18574
18575 @item
18576 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
18577 the abstract syntax tree as produced by the parser.
18578
18579 @item
18580 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
18581 all entities, computed during semantic analysis.
18582
18583 @item
18584 Library management issues are dealt with in files with prefix
18585 @file{^lib^LIB^}.
18586
18587 @item
18588 @findex Ada
18589 @cindex Annex A
18590 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
18591 defined in Annex A.
18592
18593 @item
18594 @findex Interfaces
18595 @cindex Annex B
18596 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
18597 defined in Annex B.
18598
18599 @item
18600 @findex System
18601 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
18602 both language-defined children and GNAT run-time routines.
18603
18604 @item
18605 @findex GNAT
18606 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
18607 general-purpose packages, fully documented in their specifications. All
18608 the other @file{.c} files are modifications of common @code{gcc} files.
18609 @end itemize
18610
18611 @node Getting Internal Debugging Information
18612 @section Getting Internal Debugging Information
18613
18614 @noindent
18615 Most compilers have internal debugging switches and modes. GNAT
18616 does also, except GNAT internal debugging switches and modes are not
18617 secret. A summary and full description of all the compiler and binder
18618 debug flags are in the file @file{debug.adb}. You must obtain the
18619 sources of the compiler to see the full detailed effects of these flags.
18620
18621 The switches that print the source of the program (reconstructed from
18622 the internal tree) are of general interest for user programs, as are the
18623 options to print
18624 the full internal tree, and the entity table (the symbol table
18625 information). The reconstructed source provides a readable version of the
18626 program after the front-end has completed analysis and  expansion,
18627 and is useful when studying the performance of specific constructs.
18628 For example, constraint checks are indicated, complex aggregates
18629 are replaced with loops and assignments, and tasking primitives
18630 are replaced with run-time calls.
18631
18632 @node Stack Traceback
18633 @section Stack Traceback
18634 @cindex traceback
18635 @cindex stack traceback
18636 @cindex stack unwinding
18637
18638 @noindent
18639 Traceback is a mechanism to display the sequence of subprogram calls that
18640 leads to a specified execution point in a program. Often (but not always)
18641 the execution point is an instruction at which an exception has been raised.
18642 This mechanism is also known as @i{stack unwinding} because it obtains
18643 its information by scanning the run-time stack and recovering the activation
18644 records of all active subprograms. Stack unwinding is one of the most
18645 important tools for program debugging.
18646
18647 The first entry stored in traceback corresponds to the deepest calling level,
18648 that is to say the subprogram currently executing the instruction
18649 from which we want to obtain the traceback.
18650
18651 Note that there is no runtime performance penalty when stack traceback
18652 is enabled, and no exception is raised during program execution.
18653
18654 @menu
18655 * Non-Symbolic Traceback::
18656 * Symbolic Traceback::
18657 @end menu
18658
18659 @node Non-Symbolic Traceback
18660 @subsection Non-Symbolic Traceback
18661 @cindex traceback, non-symbolic
18662
18663 @noindent
18664 Note: this feature is not supported on all platforms. See
18665 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
18666 platforms.
18667
18668 @menu
18669 * Tracebacks From an Unhandled Exception::
18670 * Tracebacks From Exception Occurrences (non-symbolic)::
18671 * Tracebacks From Anywhere in a Program (non-symbolic)::
18672 @end menu
18673
18674 @node Tracebacks From an Unhandled Exception
18675 @subsubsection Tracebacks From an Unhandled Exception
18676
18677 @noindent
18678 A runtime non-symbolic traceback is a list of addresses of call instructions.
18679 To enable this feature you must use the @option{-E}
18680 @code{gnatbind}'s option. With this option a stack traceback is stored as part
18681 of exception information. You can retrieve this information using the
18682 @code{addr2line} tool.
18683
18684 Here is a simple example:
18685
18686 @smallexample @c ada
18687 @cartouche
18688 procedure STB is
18689
18690    procedure P1 is
18691    begin
18692       raise Constraint_Error;
18693    end P1;
18694
18695    procedure P2 is
18696    begin
18697       P1;
18698    end P2;
18699
18700 begin
18701    P2;
18702 end STB;
18703 @end cartouche
18704 @end smallexample
18705
18706 @smallexample
18707 $ gnatmake stb -bargs -E
18708 $ stb
18709
18710 Execution terminated by unhandled exception
18711 Exception name: CONSTRAINT_ERROR
18712 Message: stb.adb:5
18713 Call stack traceback locations:
18714 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
18715 @end smallexample
18716
18717 @noindent
18718 As we see the traceback lists a sequence of addresses for the unhandled
18719 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
18720 guess that this exception come from procedure P1. To translate these
18721 addresses into the source lines where the calls appear, the
18722 @code{addr2line} tool, described below, is invaluable. The use of this tool
18723 requires the program to be compiled with debug information.
18724
18725 @smallexample
18726 $ gnatmake -g stb -bargs -E
18727 $ stb
18728
18729 Execution terminated by unhandled exception
18730 Exception name: CONSTRAINT_ERROR
18731 Message: stb.adb:5
18732 Call stack traceback locations:
18733 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
18734
18735 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
18736    0x4011f1 0x77e892a4
18737
18738 00401373 at d:/stb/stb.adb:5
18739 0040138B at d:/stb/stb.adb:10
18740 0040139C at d:/stb/stb.adb:14
18741 00401335 at d:/stb/b~stb.adb:104
18742 004011C4 at /build/.../crt1.c:200
18743 004011F1 at /build/.../crt1.c:222
18744 77E892A4 in ?? at ??:0
18745 @end smallexample
18746
18747 @noindent
18748 The @code{addr2line} tool has several other useful options:
18749
18750 @table @code
18751 @item --functions
18752 to get the function name corresponding to any location
18753
18754 @item --demangle=gnat
18755 to use the gnat decoding mode for the function names. Note that
18756 for binutils version 2.9.x the option is simply @option{--demangle}.
18757 @end table
18758
18759 @smallexample
18760 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
18761    0x40139c 0x401335 0x4011c4 0x4011f1
18762
18763 00401373 in stb.p1 at d:/stb/stb.adb:5
18764 0040138B in stb.p2 at d:/stb/stb.adb:10
18765 0040139C in stb at d:/stb/stb.adb:14
18766 00401335 in main at d:/stb/b~stb.adb:104
18767 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
18768 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
18769 @end smallexample
18770
18771 @noindent
18772 From this traceback we can see that the exception was raised in
18773 @file{stb.adb} at line 5, which was reached from a procedure call in
18774 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
18775 which contains the call to the main program.
18776 @pxref{Running gnatbind}. The remaining entries are assorted runtime routines,
18777 and the output will vary from platform to platform.
18778
18779 It is also possible to use @code{GDB} with these traceback addresses to debug
18780 the program. For example, we can break at a given code location, as reported
18781 in the stack traceback:
18782
18783 @smallexample
18784 $ gdb -nw stb
18785 @ifclear vms
18786 @noindent
18787 Furthermore, this feature is not implemented inside Windows DLL. Only
18788 the non-symbolic traceback is reported in this case.
18789 @end ifclear
18790
18791 (gdb) break *0x401373
18792 Breakpoint 1 at 0x401373: file stb.adb, line 5.
18793 @end smallexample
18794
18795 @noindent
18796 It is important to note that the stack traceback addresses
18797 do not change when debug information is included. This is particularly useful
18798 because it makes it possible to release software without debug information (to
18799 minimize object size), get a field report that includes a stack traceback
18800 whenever an internal bug occurs, and then be able to retrieve the sequence
18801 of calls with the same program compiled with debug information.
18802
18803 @node Tracebacks From Exception Occurrences (non-symbolic)
18804 @subsubsection Tracebacks From Exception Occurrences
18805
18806 @noindent
18807 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
18808 The stack traceback is attached to the exception information string, and can
18809 be retrieved in an exception handler within the Ada program, by means of the
18810 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
18811
18812 @smallexample @c ada
18813 with Ada.Text_IO;
18814 with Ada.Exceptions;
18815
18816 procedure STB is
18817
18818    use Ada;
18819    use Ada.Exceptions;
18820
18821    procedure P1 is
18822       K : Positive := 1;
18823    begin
18824       K := K - 1;
18825    exception
18826       when E : others =>
18827          Text_IO.Put_Line (Exception_Information (E));
18828    end P1;
18829
18830    procedure P2 is
18831    begin
18832       P1;
18833    end P2;
18834
18835 begin
18836    P2;
18837 end STB;
18838 @end smallexample
18839
18840 @noindent
18841 This program will output:
18842
18843 @smallexample
18844 $ stb
18845
18846 Exception name: CONSTRAINT_ERROR
18847 Message: stb.adb:12
18848 Call stack traceback locations:
18849 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
18850 @end smallexample
18851
18852 @node Tracebacks From Anywhere in a Program (non-symbolic)
18853 @subsubsection Tracebacks From Anywhere in a Program
18854
18855 @noindent
18856 It is also possible to retrieve a stack traceback from anywhere in a
18857 program. For this you need to
18858 use the @code{GNAT.Traceback} API. This package includes a procedure called
18859 @code{Call_Chain} that computes a complete stack traceback, as well as useful
18860 display procedures described below. It is not necessary to use the
18861 @option{-E gnatbind} option in this case, because the stack traceback mechanism
18862 is invoked explicitly.
18863
18864 @noindent
18865 In the following example we compute a traceback at a specific location in
18866 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
18867 convert addresses to strings:
18868
18869 @smallexample @c ada
18870 with Ada.Text_IO;
18871 with GNAT.Traceback;
18872 with GNAT.Debug_Utilities;
18873
18874 procedure STB is
18875
18876    use Ada;
18877    use GNAT;
18878    use GNAT.Traceback;
18879
18880    procedure P1 is
18881       TB  : Tracebacks_Array (1 .. 10);
18882       --  We are asking for a maximum of 10 stack frames.
18883       Len : Natural;
18884       --  Len will receive the actual number of stack frames returned.
18885    begin
18886       Call_Chain (TB, Len);
18887
18888       Text_IO.Put ("In STB.P1 : ");
18889
18890       for K in 1 .. Len loop
18891          Text_IO.Put (Debug_Utilities.Image (TB (K)));
18892          Text_IO.Put (' ');
18893       end loop;
18894
18895       Text_IO.New_Line;
18896    end P1;
18897
18898    procedure P2 is
18899    begin
18900       P1;
18901    end P2;
18902
18903 begin
18904    P2;
18905 end STB;
18906 @end smallexample
18907
18908 @smallexample
18909 $ gnatmake -g stb
18910 $ stb
18911
18912 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
18913 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
18914 @end smallexample
18915
18916 @noindent
18917 You can then get further information by invoking the @code{addr2line}
18918 tool as described earlier (note that the hexadecimal addresses
18919 need to be specified in C format, with a leading ``0x'').
18920
18921
18922 @node Symbolic Traceback
18923 @subsection Symbolic Traceback
18924 @cindex traceback, symbolic
18925
18926 @noindent
18927 A symbolic traceback is a stack traceback in which procedure names are
18928 associated with each code location.
18929
18930 @noindent
18931 Note that this feature is not supported on all platforms. See
18932 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
18933 list of currently supported platforms.
18934
18935 @noindent
18936 Note that the symbolic traceback requires that the program be compiled
18937 with debug information. If it is not compiled with debug information
18938 only the non-symbolic information will be valid.
18939
18940 @menu
18941 * Tracebacks From Exception Occurrences (symbolic)::
18942 * Tracebacks From Anywhere in a Program (symbolic)::
18943 @end menu
18944
18945 @node Tracebacks From Exception Occurrences (symbolic)
18946 @subsubsection Tracebacks From Exception Occurrences
18947
18948 @smallexample @c ada
18949 with Ada.Text_IO;
18950 with GNAT.Traceback.Symbolic;
18951
18952 procedure STB is
18953
18954    procedure P1 is
18955    begin
18956       raise Constraint_Error;
18957    end P1;
18958
18959    procedure P2 is
18960    begin
18961       P1;
18962    end P2;
18963
18964    procedure P3 is
18965    begin
18966       P2;
18967    end P3;
18968
18969 begin
18970    P3;
18971 exception
18972    when E : others =>
18973       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
18974 end STB;
18975 @end smallexample
18976
18977 @smallexample
18978 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
18979 $ stb
18980
18981 0040149F in stb.p1 at stb.adb:8
18982 004014B7 in stb.p2 at stb.adb:13
18983 004014CF in stb.p3 at stb.adb:18
18984 004015DD in ada.stb at stb.adb:22
18985 00401461 in main at b~stb.adb:168
18986 004011C4 in __mingw_CRTStartup at crt1.c:200
18987 004011F1 in mainCRTStartup at crt1.c:222
18988 77E892A4 in ?? at ??:0
18989 @end smallexample
18990
18991 @noindent
18992 In the above example the ``.\'' syntax in the @command{gnatmake} command
18993 is currently required by @command{addr2line} for files that are in
18994 the current working directory.
18995 Moreover, the exact sequence of linker options may vary from platform
18996 to platform.
18997 The above @option{-largs} section is for Windows platforms. By contrast,
18998 under Unix there is no need for the @option{-largs} section.
18999 Differences across platforms are due to details of linker implementation.
19000
19001 @node Tracebacks From Anywhere in a Program (symbolic)
19002 @subsubsection Tracebacks From Anywhere in a Program
19003
19004 @noindent
19005 It is possible to get a symbolic stack traceback
19006 from anywhere in a program, just as for non-symbolic tracebacks.
19007 The first step is to obtain a non-symbolic
19008 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19009 information. Here is an example:
19010
19011 @smallexample @c ada
19012 with Ada.Text_IO;
19013 with GNAT.Traceback;
19014 with GNAT.Traceback.Symbolic;
19015
19016 procedure STB is
19017
19018    use Ada;
19019    use GNAT.Traceback;
19020    use GNAT.Traceback.Symbolic;
19021
19022    procedure P1 is
19023       TB  : Tracebacks_Array (1 .. 10);
19024       --  We are asking for a maximum of 10 stack frames.
19025       Len : Natural;
19026       --  Len will receive the actual number of stack frames returned.
19027    begin
19028       Call_Chain (TB, Len);
19029       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
19030    end P1;
19031
19032    procedure P2 is
19033    begin
19034       P1;
19035    end P2;
19036
19037 begin
19038    P2;
19039 end STB;
19040 @end smallexample
19041
19042 @ifset vms
19043 @node Compatibility with DEC Ada
19044 @chapter Compatibility with DEC Ada
19045 @cindex Compatibility
19046
19047 @noindent
19048 This section of the manual compares DEC Ada for OpenVMS Alpha and GNAT
19049 OpenVMS Alpha. GNAT achieves a high level of compatibility
19050 with DEC Ada, and it should generally be straightforward to port code
19051 from the DEC Ada environment to GNAT. However, there are a few language
19052 and implementation differences of which the user must be aware. These
19053 differences are discussed in this section. In
19054 addition, the operating environment and command structure for the
19055 compiler are different, and these differences are also discussed.
19056
19057 Note that this discussion addresses specifically the implementation
19058 of Ada 83 for DIGITAL OpenVMS Alpha Systems. In cases where the implementation
19059 of DEC Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
19060 GNAT always follows the Alpha implementation.
19061
19062 @menu
19063 * Ada 95 Compatibility::
19064 * Differences in the Definition of Package System::
19065 * Language-Related Features::
19066 * The Package STANDARD::
19067 * The Package SYSTEM::
19068 * Tasking and Task-Related Features::
19069 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
19070 * Pragmas and Pragma-Related Features::
19071 * Library of Predefined Units::
19072 * Bindings::
19073 * Main Program Definition::
19074 * Implementation-Defined Attributes::
19075 * Compiler and Run-Time Interfacing::
19076 * Program Compilation and Library Management::
19077 * Input-Output::
19078 * Implementation Limits::
19079 * Tools::
19080 @end menu
19081
19082 @node Ada 95 Compatibility
19083 @section Ada 95 Compatibility
19084
19085 @noindent
19086 GNAT is an Ada 95 compiler, and DEC Ada is an Ada 83
19087 compiler. Ada 95 is almost completely upwards compatible
19088 with Ada 83, and therefore Ada 83 programs will compile
19089 and run under GNAT with
19090 no changes or only minor changes. The Ada 95 Reference
19091 Manual (ANSI/ISO/IEC-8652:1995) provides details on specific
19092 incompatibilities.
19093
19094 GNAT provides the switch /83 on the GNAT COMPILE command,
19095 as well as the pragma ADA_83, to force the compiler to
19096 operate in Ada 83 mode. This mode does not guarantee complete
19097 conformance to Ada 83, but in practice is sufficient to
19098 eliminate most sources of incompatibilities.
19099 In particular, it eliminates the recognition of the
19100 additional Ada 95 keywords, so that their use as identifiers
19101 in Ada83 program is legal, and handles the cases of packages
19102 with optional bodies, and generics that instantiate unconstrained
19103 types without the use of @code{(<>)}.
19104
19105 @node Differences in the Definition of Package System
19106 @section Differences in the Definition of Package System
19107
19108 @noindent
19109 Both the Ada 95 and Ada 83 reference manuals permit a compiler to add
19110 implementation-dependent declarations to package System. In normal mode,
19111 GNAT does not take advantage of this permission, and the version of System
19112 provided by GNAT exactly matches that in the Ada 95 Reference Manual.
19113
19114 However, DEC Ada adds an extensive set of declarations to package System,
19115 as fully documented in the DEC Ada manuals. To minimize changes required
19116 for programs that make use of these extensions, GNAT provides the pragma
19117 Extend_System for extending the definition of package System. By using:
19118
19119 @smallexample @c ada
19120 @group
19121 @cartouche
19122 pragma Extend_System (Aux_DEC);
19123 @end cartouche
19124 @end group
19125 @end smallexample
19126
19127 @noindent
19128 The set of definitions in System is extended to include those in package
19129 @code{System.Aux_DEC}.
19130 These definitions are incorporated directly into package
19131 System, as though they had been declared there in the first place. For a
19132 list of the declarations added, see the specification of this package,
19133 which can be found in the file @code{s-auxdec.ads} in the GNAT library.
19134 The pragma Extend_System is a configuration pragma, which means that
19135 it can be placed in the file @file{gnat.adc}, so that it will automatically
19136 apply to all subsequent compilations. See the section on Configuration
19137 Pragmas for further details.
19138
19139 An alternative approach that avoids the use of the non-standard
19140 Extend_System pragma is to add a context clause to the unit that
19141 references these facilities:
19142
19143 @smallexample @c ada
19144 @group
19145 @cartouche
19146 with System.Aux_DEC;
19147 use  System.Aux_DEC;
19148 @end cartouche
19149 @end group
19150 @end smallexample
19151
19152 @noindent
19153 The effect is not quite semantically identical to incorporating
19154 the declarations directly into package @code{System},
19155 but most programs will not notice a difference
19156 unless they use prefix notation (e.g. @code{System.Integer_8})
19157 to reference the
19158 entities directly in package @code{System}.
19159 For units containing such references,
19160 the prefixes must either be removed, or the pragma @code{Extend_System}
19161 must be used.
19162
19163 @node Language-Related Features
19164 @section Language-Related Features
19165
19166 @noindent
19167 The following sections highlight differences in types,
19168 representations of types, operations, alignment, and
19169 related topics.
19170
19171 @menu
19172 * Integer Types and Representations::
19173 * Floating-Point Types and Representations::
19174 * Pragmas Float_Representation and Long_Float::
19175 * Fixed-Point Types and Representations::
19176 * Record and Array Component Alignment::
19177 * Address Clauses::
19178 * Other Representation Clauses::
19179 @end menu
19180
19181 @node Integer Types and Representations
19182 @subsection Integer Types and Representations
19183
19184 @noindent
19185 The set of predefined integer types is identical in DEC Ada and GNAT.
19186 Furthermore the representation of these integer types is also identical,
19187 including the capability of size clauses forcing biased representation.
19188
19189 In addition,
19190 DEC Ada for OpenVMS Alpha systems has defined the
19191 following additional integer types in package System:
19192
19193 @itemize @bullet
19194
19195 @item
19196 INTEGER_8
19197
19198 @item
19199 INTEGER_16
19200
19201 @item
19202 INTEGER_32
19203
19204 @item
19205 INTEGER_64
19206
19207 @item
19208 LARGEST_INTEGER
19209 @end itemize
19210
19211 @noindent
19212 When using GNAT, the first four of these types may be obtained from the
19213 standard Ada 95 package @code{Interfaces}.
19214 Alternatively, by use of the pragma
19215 @code{Extend_System}, identical
19216 declarations can be referenced directly in package @code{System}.
19217 On both GNAT and DEC Ada, the maximum integer size is 64 bits.
19218
19219 @node Floating-Point Types and Representations
19220 @subsection Floating-Point Types and Representations
19221 @cindex Floating-Point types
19222
19223 @noindent
19224 The set of predefined floating-point types is identical in DEC Ada and GNAT.
19225 Furthermore the representation of these floating-point
19226 types is also identical. One important difference is that the default
19227 representation for DEC Ada is VAX_Float, but the default representation
19228 for GNAT is IEEE.
19229
19230 Specific types may be declared to be VAX_Float or IEEE, using the pragma
19231 @code{Float_Representation} as described in the DEC Ada documentation.
19232 For example, the declarations:
19233
19234 @smallexample @c ada
19235 @group
19236 @cartouche
19237 type F_Float is digits 6;
19238 pragma Float_Representation (VAX_Float, F_Float);
19239 @end cartouche
19240 @end group
19241 @end smallexample
19242
19243 @noindent
19244 declare a type F_Float that will be represented in VAX_Float format.
19245 This set of declarations actually appears in System.Aux_DEC, which provides
19246 the full set of additional floating-point declarations provided in
19247 the DEC Ada version of package
19248 System. This and similar declarations may be accessed in a user program
19249 by using pragma @code{Extend_System}. The use of this
19250 pragma, and the related pragma @code{Long_Float} is described in further
19251 detail in the following section.
19252
19253 @node Pragmas Float_Representation and Long_Float
19254 @subsection Pragmas Float_Representation and Long_Float
19255
19256 @noindent
19257 DEC Ada provides the pragma @code{Float_Representation}, which
19258 acts as a program library switch to allow control over
19259 the internal representation chosen for the predefined
19260 floating-point types declared in the package @code{Standard}.
19261 The format of this pragma is as follows:
19262
19263 @smallexample
19264 @group
19265 @cartouche
19266 @b{pragma} @code{Float_Representation}(VAX_Float | IEEE_Float);
19267 @end cartouche
19268 @end group
19269 @end smallexample
19270
19271 @noindent
19272 This pragma controls the representation of floating-point
19273 types as follows:
19274
19275 @itemize @bullet
19276 @item
19277 @code{VAX_Float} specifies that floating-point
19278 types are represented by default with the VAX hardware types
19279 F-floating, D-floating, G-floating. Note that the H-floating
19280 type is available only on DIGITAL Vax systems, and is not available
19281 in either DEC Ada or GNAT for Alpha systems.
19282
19283 @item
19284 @code{IEEE_Float} specifies that floating-point
19285 types are represented by default with the IEEE single and
19286 double floating-point types.
19287 @end itemize
19288
19289 @noindent
19290 GNAT provides an identical implementation of the pragma
19291 @code{Float_Representation}, except that it functions as a
19292 configuration pragma, as defined by Ada 95. Note that the
19293 notion of configuration pragma corresponds closely to the
19294 DEC Ada notion of a program library switch.
19295
19296 When no pragma is used in GNAT, the default is IEEE_Float, which is different
19297 from DEC Ada 83, where the default is VAX_Float. In addition, the
19298 predefined libraries in GNAT are built using IEEE_Float, so it is not
19299 advisable to change the format of numbers passed to standard library
19300 routines, and if necessary explicit type conversions may be needed.
19301
19302 The use of IEEE_Float is recommended in GNAT since it is more efficient,
19303 and (given that it conforms to an international standard) potentially more
19304 portable. The situation in which VAX_Float may be useful is in interfacing
19305 to existing code and data that expects the use of VAX_Float. There are
19306 two possibilities here. If the requirement for the use of VAX_Float is
19307 localized, then the best approach is to use the predefined VAX_Float
19308 types in package @code{System}, as extended by
19309 @code{Extend_System}. For example, use @code{System.F_Float}
19310 to specify the 32-bit @code{F-Float} format.
19311
19312 Alternatively, if an entire program depends heavily on the use of
19313 the @code{VAX_Float} and in particular assumes that the types in
19314 package @code{Standard} are in @code{Vax_Float} format, then it
19315 may be desirable to reconfigure GNAT to assume Vax_Float by default.
19316 This is done by using the GNAT LIBRARY command to rebuild the library, and
19317 then using the general form of the @code{Float_Representation}
19318 pragma to ensure that this default format is used throughout.
19319 The form of the GNAT LIBRARY command is:
19320
19321 @smallexample
19322 GNAT LIBRARY /CONFIG=@i{file} /CREATE=@i{directory}
19323 @end smallexample
19324
19325 @noindent
19326 where @i{file} contains the new configuration pragmas
19327 and @i{directory} is the directory to be created to contain
19328 the new library.
19329
19330 @noindent
19331 On OpenVMS systems, DEC Ada provides the pragma @code{Long_Float}
19332 to allow control over the internal representation chosen
19333 for the predefined type @code{Long_Float} and for floating-point
19334 type declarations with digits specified in the range 7 .. 15.
19335 The format of this pragma is as follows:
19336
19337 @smallexample @c ada
19338 @cartouche
19339 pragma Long_Float (D_FLOAT | G_FLOAT);
19340 @end cartouche
19341 @end smallexample
19342
19343 @node Fixed-Point Types and Representations
19344 @subsection Fixed-Point Types and Representations
19345
19346 @noindent
19347 On DEC Ada for OpenVMS Alpha systems, rounding is
19348 away from zero for both positive and negative numbers.
19349 Therefore, +0.5 rounds to 1 and -0.5 rounds to -1.
19350
19351 On GNAT for OpenVMS Alpha, the results of operations
19352 on fixed-point types are in accordance with the Ada 95
19353 rules. In particular, results of operations on decimal
19354 fixed-point types are truncated.
19355
19356 @node Record and Array Component Alignment
19357 @subsection Record and Array Component Alignment
19358
19359 @noindent
19360 On DEC Ada for OpenVMS Alpha, all non composite components
19361 are aligned on natural boundaries. For example, 1-byte
19362 components are aligned on byte boundaries, 2-byte
19363 components on 2-byte boundaries, 4-byte components on 4-byte
19364 byte boundaries, and so on. The OpenVMS Alpha hardware
19365 runs more efficiently with naturally aligned data.
19366
19367 ON GNAT for OpenVMS Alpha, alignment rules are compatible
19368 with DEC Ada for OpenVMS Alpha.
19369
19370 @node Address Clauses
19371 @subsection Address Clauses
19372
19373 @noindent
19374 In DEC Ada and GNAT, address clauses are supported for
19375 objects and imported subprograms.
19376 The predefined type @code{System.Address} is a private type
19377 in both compilers, with the same representation (it is simply
19378 a machine pointer). Addition, subtraction, and comparison
19379 operations are available in the standard Ada 95 package
19380 @code{System.Storage_Elements}, or in package @code{System}
19381 if it is extended to include @code{System.Aux_DEC} using a
19382 pragma @code{Extend_System} as previously described.
19383
19384 Note that code that with's both this extended package @code{System}
19385 and the package @code{System.Storage_Elements} should not @code{use}
19386 both packages, or ambiguities will result. In general it is better
19387 not to mix these two sets of facilities. The Ada 95 package was
19388 designed specifically to provide the kind of features that DEC Ada
19389 adds directly to package @code{System}.
19390
19391 GNAT is compatible with DEC Ada in its handling of address
19392 clauses, except for some limitations in
19393 the form of address clauses for composite objects with
19394 initialization. Such address clauses are easily replaced
19395 by the use of an explicitly-defined constant as described
19396 in the Ada 95 Reference Manual (13.1(22)). For example, the sequence
19397 of declarations:
19398
19399 @smallexample @c ada
19400 @cartouche
19401 X, Y : Integer := Init_Func;
19402 Q : String (X .. Y) := "abc";
19403 ...
19404 for Q'Address use Compute_Address;
19405 @end cartouche
19406 @end smallexample
19407
19408 @noindent
19409 will be rejected by GNAT, since the address cannot be computed at the time
19410 that Q is declared. To achieve the intended effect, write instead:
19411
19412 @smallexample @c ada
19413 @group
19414 @cartouche
19415 X, Y : Integer := Init_Func;
19416 Q_Address : constant Address := Compute_Address;
19417 Q : String (X .. Y) := "abc";
19418 ...
19419 for Q'Address use Q_Address;
19420 @end cartouche
19421 @end group
19422 @end smallexample
19423
19424 @noindent
19425 which will be accepted by GNAT (and other Ada 95 compilers), and is also
19426 backwards compatible with Ada 83. A fuller description of the restrictions
19427 on address specifications is found in the GNAT Reference Manual.
19428
19429 @node Other Representation Clauses
19430 @subsection Other Representation Clauses
19431
19432 @noindent
19433 GNAT supports in a compatible manner all the representation
19434 clauses supported by DEC Ada. In addition, it
19435 supports representation clause forms that are new in Ada 95
19436 including COMPONENT_SIZE and SIZE clauses for objects.
19437
19438 @node The Package STANDARD
19439 @section The Package STANDARD
19440
19441 @noindent
19442 The package STANDARD, as implemented by DEC Ada, is fully
19443 described in the Reference Manual for the Ada Programming
19444 Language (ANSI/MIL-STD-1815A-1983) and in the DEC Ada
19445 Language Reference Manual. As implemented by GNAT, the
19446 package STANDARD is described in the Ada 95 Reference
19447 Manual.
19448
19449 In addition, DEC Ada supports the Latin-1 character set in
19450 the type CHARACTER. GNAT supports the Latin-1 character set
19451 in the type CHARACTER and also Unicode (ISO 10646 BMP) in
19452 the type WIDE_CHARACTER.
19453
19454 The floating-point types supported by GNAT are those
19455 supported by DEC Ada, but defaults are different, and are controlled by
19456 pragmas. See @pxref{Floating-Point Types and Representations} for details.
19457
19458 @node The Package SYSTEM
19459 @section The Package SYSTEM
19460
19461 @noindent
19462 DEC Ada provides a system-specific version of the package
19463 SYSTEM for each platform on which the language ships.
19464 For the complete specification of the package SYSTEM, see
19465 Appendix F of the DEC Ada Language Reference Manual.
19466
19467 On DEC Ada, the package SYSTEM includes the following conversion functions:
19468 @itemize @bullet
19469 @item TO_ADDRESS(INTEGER)
19470
19471 @item  TO_ADDRESS(UNSIGNED_LONGWORD)
19472
19473 @item  TO_ADDRESS(universal_integer)
19474
19475 @item  TO_INTEGER(ADDRESS)
19476
19477 @item  TO_UNSIGNED_LONGWORD(ADDRESS)
19478
19479 @item  Function IMPORT_VALUE return UNSIGNED_LONGWORD and the
19480                  functions IMPORT_ADDRESS and IMPORT_LARGEST_VALUE
19481 @end itemize
19482
19483 @noindent
19484 By default, GNAT supplies a version of SYSTEM that matches
19485 the definition given in the Ada 95 Reference Manual.
19486 This
19487 is a subset of the DIGITAL system definitions, which is as
19488 close as possible to the original definitions. The only difference
19489 is that the definition of SYSTEM_NAME is different:
19490
19491 @smallexample @c ada
19492 @group
19493 @cartouche
19494 type Name is (SYSTEM_NAME_GNAT);
19495 System_Name : constant Name := SYSTEM_NAME_GNAT;
19496 @end cartouche
19497 @end group
19498 @end smallexample
19499
19500 @noindent
19501 Also, GNAT adds the new Ada 95 declarations for
19502 BIT_ORDER and DEFAULT_BIT_ORDER.
19503
19504 However, the use of the following pragma causes GNAT
19505 to extend the definition of package SYSTEM so that it
19506 encompasses the full set of DIGITAL-specific extensions,
19507 including the functions listed above:
19508
19509 @smallexample @c ada
19510 @cartouche
19511 pragma Extend_System (Aux_DEC);
19512 @end cartouche
19513 @end smallexample
19514
19515 @noindent
19516 The pragma Extend_System is a configuration pragma that
19517 is most conveniently placed in the @file{gnat.adc} file. See the
19518 GNAT Reference Manual for further details.
19519
19520 DEC Ada does not allow the recompilation of the package
19521 SYSTEM. Instead DEC Ada provides several pragmas (SYSTEM_
19522 NAME, STORAGE_UNIT, and MEMORY_SIZE) to modify values in
19523 the package SYSTEM. On OpenVMS Alpha systems, the pragma
19524 SYSTEM_NAME takes the enumeration literal OPENVMS_AXP as
19525 its single argument.
19526
19527 GNAT does permit the recompilation of package SYSTEM using
19528 a special switch (@option{-gnatg}) and this switch can be used if
19529 it is necessary to modify the definitions in SYSTEM. GNAT does
19530 not permit the specification of SYSTEM_NAME, STORAGE_UNIT
19531 or MEMORY_SIZE by any other means.
19532
19533 On GNAT systems, the pragma SYSTEM_NAME takes the
19534 enumeration literal SYSTEM_NAME_GNAT.
19535
19536 The definitions provided by the use of
19537
19538 @smallexample @c ada
19539 pragma Extend_System (AUX_Dec);
19540 @end smallexample
19541
19542 @noindent
19543 are virtually identical to those provided by the DEC Ada 83 package
19544 System. One important difference is that the name of the TO_ADDRESS
19545 function for type UNSIGNED_LONGWORD is changed to TO_ADDRESS_LONG.
19546 See the GNAT Reference manual for a discussion of why this change was
19547 necessary.
19548
19549 @noindent
19550 The version of TO_ADDRESS taking a universal integer argument is in fact
19551 an extension to Ada 83 not strictly compatible with the reference manual.
19552 In GNAT, we are constrained to be exactly compatible with the standard,
19553 and this means we cannot provide this capability. In DEC Ada 83, the
19554 point of this definition is to deal with a call like:
19555
19556 @smallexample @c ada
19557 TO_ADDRESS (16#12777#);
19558 @end smallexample
19559
19560 @noindent
19561 Normally, according to the Ada 83 standard, one would expect this to be
19562 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
19563 of TO_ADDRESS. However, in DEC Ada 83, there is no ambiguity, since the
19564 definition using universal_integer takes precedence.
19565
19566 In GNAT, since the version with universal_integer cannot be supplied, it is
19567 not possible to be 100% compatible. Since there are many programs using
19568 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
19569 to change the name of the function in the UNSIGNED_LONGWORD case, so the
19570 declarations provided in the GNAT version of AUX_Dec are:
19571
19572 @smallexample @c ada
19573 function To_Address (X : Integer) return Address;
19574 pragma Pure_Function (To_Address);
19575
19576 function To_Address_Long (X : Unsigned_Longword) return Address;
19577 pragma Pure_Function (To_Address_Long);
19578 @end smallexample
19579
19580 @noindent
19581 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
19582 change the name to TO_ADDRESS_LONG.
19583
19584 @node Tasking and Task-Related Features
19585 @section Tasking and Task-Related Features
19586
19587 @noindent
19588 The concepts relevant to a comparison of tasking on GNAT
19589 and on DEC Ada for OpenVMS Alpha systems are discussed in
19590 the following sections.
19591
19592 For detailed information on concepts related to tasking in
19593 DEC Ada, see the DEC Ada Language Reference Manual and the
19594 relevant run-time reference manual.
19595
19596 @node Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
19597 @section Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
19598
19599 @noindent
19600 On OpenVMS Alpha systems, each Ada task (except a passive
19601 task) is implemented as a single stream of execution
19602 that is created and managed by the kernel. On these
19603 systems, DEC Ada tasking support is based on DECthreads,
19604 an implementation of the POSIX standard for threads.
19605
19606 Although tasks are implemented as threads, all tasks in
19607 an Ada program are part of the same process. As a result,
19608 resources such as open files and virtual memory can be
19609 shared easily among tasks. Having all tasks in one process
19610 allows better integration with the programming environment
19611 (the shell and the debugger, for example).
19612
19613 Also, on OpenVMS Alpha systems, DEC Ada tasks and foreign
19614 code that calls DECthreads routines can be used together.
19615 The interaction between Ada tasks and DECthreads routines
19616 can have some benefits. For example when on OpenVMS Alpha,
19617 DEC Ada can call C code that is already threaded.
19618 GNAT on OpenVMS Alpha uses the facilities of DECthreads,
19619 and Ada tasks are mapped to threads.
19620
19621 @menu
19622 * Assigning Task IDs::
19623 * Task IDs and Delays::
19624 * Task-Related Pragmas::
19625 * Scheduling and Task Priority::
19626 * The Task Stack::
19627 * External Interrupts::
19628 @end menu
19629
19630 @node Assigning Task IDs
19631 @subsection Assigning Task IDs
19632
19633 @noindent
19634 The DEC Ada Run-Time Library always assigns %TASK 1 to
19635 the environment task that executes the main program. On
19636 OpenVMS Alpha systems, %TASK 0 is often used for tasks
19637 that have been created but are not yet activated.
19638
19639 On OpenVMS Alpha systems, task IDs are assigned at
19640 activation. On GNAT systems, task IDs are also assigned at
19641 task creation but do not have the same form or values as
19642 task ID values in DEC Ada. There is no null task, and the
19643 environment task does not have a specific task ID value.
19644
19645 @node Task IDs and Delays
19646 @subsection Task IDs and Delays
19647
19648 @noindent
19649 On OpenVMS Alpha systems, tasking delays are implemented
19650 using Timer System Services. The Task ID is used for the
19651 identification of the timer request (the REQIDT parameter).
19652 If Timers are used in the application take care not to use
19653 0 for the identification, because cancelling such a timer
19654 will cancel all timers and may lead to unpredictable results.
19655
19656 @node Task-Related Pragmas
19657 @subsection Task-Related Pragmas
19658
19659 @noindent
19660 Ada supplies the pragma TASK_STORAGE, which allows
19661 specification of the size of the guard area for a task
19662 stack. (The guard area forms an area of memory that has no
19663 read or write access and thus helps in the detection of
19664 stack overflow.) On OpenVMS Alpha systems, if the pragma
19665 TASK_STORAGE specifies a value of zero, a minimal guard
19666 area is created. In the absence of a pragma TASK_STORAGE, a default guard
19667 area is created.
19668
19669 GNAT supplies the following task-related pragmas:
19670
19671 @itemize @bullet
19672 @item  TASK_INFO
19673
19674               This pragma appears within a task definition and
19675               applies to the task in which it appears. The argument
19676               must be of type SYSTEM.TASK_INFO.TASK_INFO_TYPE.
19677
19678 @item  TASK_STORAGE
19679
19680               GNAT implements pragma TASK_STORAGE in the same way as
19681               DEC Ada.
19682               Both DEC Ada and GNAT supply the pragmas PASSIVE,
19683               SUPPRESS, and VOLATILE.
19684 @end itemize
19685 @node Scheduling and Task Priority
19686 @subsection Scheduling and Task Priority
19687
19688 @noindent
19689 DEC Ada implements the Ada language requirement that
19690 when two tasks are eligible for execution and they have
19691 different priorities, the lower priority task does not
19692 execute while the higher priority task is waiting. The DEC
19693 Ada Run-Time Library keeps a task running until either the
19694 task is suspended or a higher priority task becomes ready.
19695
19696 On OpenVMS Alpha systems, the default strategy is round-
19697 robin with preemption. Tasks of equal priority take turns
19698 at the processor. A task is run for a certain period of
19699 time and then placed at the rear of the ready queue for
19700 its priority level.
19701
19702 DEC Ada provides the implementation-defined pragma TIME_SLICE,
19703 which can be used to enable or disable round-robin
19704 scheduling of tasks with the same priority.
19705 See the relevant DEC Ada run-time reference manual for
19706 information on using the pragmas to control DEC Ada task
19707 scheduling.
19708
19709 GNAT follows the scheduling rules of Annex D (real-time
19710 Annex) of the Ada 95 Reference Manual. In general, this
19711 scheduling strategy is fully compatible with DEC Ada
19712 although it provides some additional constraints (as
19713 fully documented in Annex D).
19714 GNAT implements time slicing control in a manner compatible with
19715 DEC Ada 83, by means of the pragma Time_Slice, whose semantics are identical
19716 to the DEC Ada 83 pragma of the same name.
19717 Note that it is not possible to mix GNAT tasking and
19718 DEC Ada 83 tasking in the same program, since the two run times are
19719 not compatible.
19720
19721 @node The Task Stack
19722 @subsection The Task Stack
19723
19724 @noindent
19725 In DEC Ada, a task stack is allocated each time a
19726 non passive task is activated. As soon as the task is
19727 terminated, the storage for the task stack is deallocated.
19728 If you specify a size of zero (bytes) with T'STORAGE_SIZE,
19729 a default stack size is used. Also, regardless of the size
19730 specified, some additional space is allocated for task
19731 management purposes. On OpenVMS Alpha systems, at least
19732 one page is allocated.
19733
19734 GNAT handles task stacks in a similar manner. According to
19735 the Ada 95 rules, it provides the pragma STORAGE_SIZE as
19736 an alternative method for controlling the task stack size.
19737 The specification of the attribute T'STORAGE_SIZE is also
19738 supported in a manner compatible with DEC Ada.
19739
19740 @node External Interrupts
19741 @subsection External Interrupts
19742
19743 @noindent
19744 On DEC Ada, external interrupts can be associated with task entries.
19745 GNAT is compatible with DEC Ada in its handling of external interrupts.
19746
19747 @node Pragmas and Pragma-Related Features
19748 @section Pragmas and Pragma-Related Features
19749
19750 @noindent
19751 Both DEC Ada and GNAT supply all language-defined pragmas
19752 as specified by the Ada 83 standard. GNAT also supplies all
19753 language-defined pragmas specified in the Ada 95 Reference Manual.
19754 In addition, GNAT implements the implementation-defined pragmas
19755 from DEC Ada 83.
19756
19757 @itemize @bullet
19758 @item  AST_ENTRY
19759
19760 @item  COMMON_OBJECT
19761
19762 @item  COMPONENT_ALIGNMENT
19763
19764 @item  EXPORT_EXCEPTION
19765
19766 @item  EXPORT_FUNCTION
19767
19768 @item  EXPORT_OBJECT
19769
19770 @item  EXPORT_PROCEDURE
19771
19772 @item  EXPORT_VALUED_PROCEDURE
19773
19774 @item  FLOAT_REPRESENTATION
19775
19776 @item  IDENT
19777
19778 @item  IMPORT_EXCEPTION
19779
19780 @item  IMPORT_FUNCTION
19781
19782 @item  IMPORT_OBJECT
19783
19784 @item  IMPORT_PROCEDURE
19785
19786 @item  IMPORT_VALUED_PROCEDURE
19787
19788 @item  INLINE_GENERIC
19789
19790 @item  INTERFACE_NAME
19791
19792 @item  LONG_FLOAT
19793
19794 @item  MAIN_STORAGE
19795
19796 @item  PASSIVE
19797
19798 @item  PSET_OBJECT
19799
19800 @item  SHARE_GENERIC
19801
19802 @item  SUPPRESS_ALL
19803
19804 @item  TASK_STORAGE
19805
19806 @item  TIME_SLICE
19807
19808 @item  TITLE
19809 @end itemize
19810
19811 @noindent
19812 These pragmas are all fully implemented, with the exception of @code{Title},
19813 @code{Passive}, and @code{Share_Generic}, which are
19814 recognized, but which have no
19815 effect in GNAT. The effect of @code{Passive} may be obtained by the
19816 use of protected objects in Ada 95. In GNAT, all generics are inlined.
19817
19818 Unlike DEC Ada, the GNAT 'EXPORT_@i{subprogram}' pragmas require
19819 a separate subprogram specification which must appear before the
19820 subprogram body.
19821
19822 GNAT also supplies a number of implementation-defined pragmas as follows:
19823 @itemize @bullet
19824 @item  C_PASS_BY_COPY
19825
19826 @item  EXTEND_SYSTEM
19827
19828 @item  SOURCE_FILE_NAME
19829
19830 @item  UNSUPPRESS
19831
19832 @item  WARNINGS
19833
19834 @item  ABORT_DEFER
19835
19836 @item  ADA_83
19837
19838 @item  ADA_95
19839
19840 @item  ANNOTATE
19841
19842 @item  ASSERT
19843
19844 @item  CPP_CLASS
19845
19846 @item  CPP_CONSTRUCTOR
19847
19848 @item  CPP_DESTRUCTOR
19849
19850 @item  CPP_VIRTUAL
19851
19852 @item  CP_VTABLE
19853
19854 @item  DEBUG
19855
19856 @item  LINKER_ALIAS
19857
19858 @item  LINKER_SECTION
19859
19860 @item  MACHINE_ATTRIBUTE
19861
19862 @item  NO_RETURN
19863
19864 @item  PURE_FUNCTION
19865
19866 @item  SOURCE_REFERENCE
19867
19868 @item  TASK_INFO
19869
19870 @item  UNCHECKED_UNION
19871
19872 @item  UNIMPLEMENTED_UNIT
19873
19874 @item  UNIVERSAL_DATA
19875
19876 @item  WEAK_EXTERNAL
19877 @end itemize
19878
19879 @noindent
19880 For full details on these GNAT implementation-defined pragmas, see
19881 the GNAT Reference Manual.
19882
19883 @menu
19884 * Restrictions on the Pragma INLINE::
19885 * Restrictions on the Pragma INTERFACE::
19886 * Restrictions on the Pragma SYSTEM_NAME::
19887 @end menu
19888
19889 @node Restrictions on the Pragma INLINE
19890 @subsection Restrictions on the Pragma INLINE
19891
19892 @noindent
19893 DEC Ada applies the following restrictions to the pragma INLINE:
19894 @itemize @bullet
19895 @item  Parameters cannot be a task type.
19896
19897 @item  Function results cannot be task types, unconstrained
19898 array types, or unconstrained types with discriminants.
19899
19900 @item  Bodies cannot declare the following:
19901 @itemize @bullet
19902 @item  Subprogram body or stub (imported subprogram is allowed)
19903
19904 @item  Tasks
19905
19906 @item  Generic declarations
19907
19908 @item  Instantiations
19909
19910 @item  Exceptions
19911
19912 @item  Access types (types derived from access types allowed)
19913
19914 @item  Array or record types
19915
19916 @item  Dependent tasks
19917
19918 @item  Direct recursive calls of subprogram or containing
19919 subprogram, directly or via a renaming
19920
19921 @end itemize
19922 @end itemize
19923
19924 @noindent
19925 In GNAT, the only restriction on pragma INLINE is that the
19926 body must occur before the call if both are in the same
19927 unit, and the size must be appropriately small. There are
19928 no other specific restrictions which cause subprograms to
19929 be incapable of being inlined.
19930
19931 @node  Restrictions on the Pragma INTERFACE
19932 @subsection  Restrictions on the Pragma INTERFACE
19933
19934 @noindent
19935 The following lists and describes the restrictions on the
19936 pragma INTERFACE on DEC Ada and GNAT:
19937 @itemize @bullet
19938 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
19939 Default is the default on OpenVMS Alpha systems.
19940
19941 @item  Parameter passing: Language specifies default
19942 mechanisms but can be overridden with an EXPORT pragma.
19943
19944 @itemize @bullet
19945 @item  Ada: Use internal Ada rules.
19946
19947 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
19948 record or task type. Result cannot be a string, an
19949 array, or a record.
19950
19951 @item  Fortran: Parameters cannot be a task. Result cannot
19952 be a string, an array, or a record.
19953 @end itemize
19954 @end itemize
19955
19956 @noindent
19957 GNAT is entirely upwards compatible with DEC Ada, and in addition allows
19958 record parameters for all languages.
19959
19960 @node  Restrictions on the Pragma SYSTEM_NAME
19961 @subsection  Restrictions on the Pragma SYSTEM_NAME
19962
19963 @noindent
19964 For DEC Ada for OpenVMS Alpha, the enumeration literal
19965 for the type NAME is OPENVMS_AXP. In GNAT, the enumeration
19966 literal for the type NAME is SYSTEM_NAME_GNAT.
19967
19968 @node  Library of Predefined Units
19969 @section  Library of Predefined Units
19970
19971 @noindent
19972 A library of predefined units is provided as part of the
19973 DEC Ada and GNAT implementations. DEC Ada does not provide
19974 the package MACHINE_CODE but instead recommends importing
19975 assembler code.
19976
19977 The GNAT versions of the DEC Ada Run-Time Library (ADA$PREDEFINED:)
19978 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
19979 version. During GNAT installation, the DEC Ada Predefined
19980 Library units are copied into the GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
19981 (aka DECLIB) directory and patched to remove Ada 95 incompatibilities
19982 and to make them interoperable with GNAT, @pxref{Changes to DECLIB}
19983 for details.
19984
19985 The GNAT RTL is contained in
19986 the GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB] (aka ADALIB) directory and
19987 the default search path is set up to find DECLIB units in preference
19988 to ADALIB units with the same name (TEXT_IO, SEQUENTIAL_IO, and DIRECT_IO,
19989 for example).
19990
19991 However, it is possible to change the default so that the
19992 reverse is true, or even to mix them using child package
19993 notation. The DEC Ada 83 units are available as DEC.xxx where xxx
19994 is the package name, and the Ada units are available in the
19995 standard manner defined for Ada 95, that is to say as Ada.xxx. To
19996 change the default, set ADA_INCLUDE_PATH and ADA_OBJECTS_PATH
19997 appropriately. For example, to change the default to use the Ada95
19998 versions do:
19999
20000 @smallexample
20001 $ DEFINE ADA_INCLUDE_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADAINCLUDE],-
20002                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
20003 $ DEFINE ADA_OBJECTS_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB],-
20004                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
20005 @end smallexample
20006
20007 @menu
20008 * Changes to DECLIB::
20009 @end menu
20010
20011 @node Changes to DECLIB
20012 @subsection Changes to DECLIB
20013
20014 @noindent
20015 The changes made to the DEC Ada predefined library for GNAT and Ada 95
20016 compatibility are minor and include the following:
20017
20018 @itemize @bullet
20019 @item  Adjusting the location of pragmas and record representation
20020 clauses to obey Ada 95 rules
20021
20022 @item  Adding the proper notation to generic formal parameters
20023 that take unconstrained types in instantiation
20024
20025 @item  Adding pragma ELABORATE_BODY to package specifications
20026 that have package bodies not otherwise allowed
20027
20028 @item  Occurrences of the identifier @code{"PROTECTED"} are renamed to
20029 @code{"PROTECTD"}.
20030 Currently these are found only in the STARLET package spec.
20031 @end itemize
20032
20033 @noindent
20034 None of the above changes is visible to users.
20035
20036 @node Bindings
20037 @section Bindings
20038
20039 @noindent
20040 On OpenVMS Alpha, DEC Ada provides the following strongly-typed bindings:
20041 @itemize @bullet
20042
20043 @item  Command Language Interpreter (CLI interface)
20044
20045 @item  DECtalk Run-Time Library (DTK interface)
20046
20047 @item  Librarian utility routines (LBR interface)
20048
20049 @item  General Purpose Run-Time Library (LIB interface)
20050
20051 @item  Math Run-Time Library (MTH interface)
20052
20053 @item  National Character Set Run-Time Library (NCS interface)
20054
20055 @item  Compiled Code Support Run-Time Library (OTS interface)
20056
20057 @item  Parallel Processing Run-Time Library (PPL interface)
20058
20059 @item  Screen Management Run-Time Library (SMG interface)
20060
20061 @item  Sort Run-Time Library (SOR interface)
20062
20063 @item  String Run-Time Library (STR interface)
20064
20065 @item STARLET System Library
20066 @findex Starlet
20067
20068 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
20069
20070 @item  X Windows Toolkit (XT interface)
20071
20072 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
20073 @end itemize
20074
20075 @noindent
20076 GNAT provides implementations of these DEC bindings in the DECLIB directory.
20077
20078 The X/Motif bindings used to build DECLIB are whatever versions are in the
20079 DEC Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
20080 The build script will
20081 automatically add a pragma Linker_Options to packages @code{Xm}, @code{Xt},
20082 and @code{X_Lib}
20083 causing the default X/Motif sharable image libraries to be linked in. This
20084 is done via options files named @file{xm.opt}, @file{xt.opt}, and
20085 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
20086
20087 It may be necessary to edit these options files to update or correct the
20088 library names if, for example, the newer X/Motif bindings from
20089 @file{ADA$EXAMPLES}
20090 had been (previous to installing GNAT) copied and renamed to supersede the
20091 default @file{ADA$PREDEFINED} versions.
20092
20093 @menu
20094 * Shared Libraries and Options Files::
20095 * Interfaces to C::
20096 @end menu
20097
20098 @node Shared Libraries and Options Files
20099 @subsection Shared Libraries and Options Files
20100
20101 @noindent
20102 When using the DEC Ada
20103 predefined X and Motif bindings, the linking with their sharable images is
20104 done automatically by @command{GNAT LINK}.
20105 When using other X and Motif bindings, you need
20106 to add the corresponding sharable images to the command line for
20107 @code{GNAT LINK}. When linking with shared libraries, or with
20108 @file{.OPT} files, you must
20109 also add them to the command line for @command{GNAT LINK}.
20110
20111 A shared library to be used with GNAT is built in the same way as other
20112 libraries under VMS. The VMS Link command can be used in standard fashion.
20113
20114 @node Interfaces to C
20115 @subsection Interfaces to C
20116
20117 @noindent
20118 DEC Ada
20119 provides the following Ada types and operations:
20120
20121 @itemize @bullet
20122 @item C types package (C_TYPES)
20123
20124 @item C strings (C_TYPES.NULL_TERMINATED)
20125
20126 @item Other_types (SHORT_INT)
20127 @end itemize
20128
20129 @noindent
20130 Interfacing to C with GNAT, one can use the above approach
20131 described for DEC Ada or the facilities of Annex B of
20132 the Ada 95 Reference Manual (packages INTERFACES.C,
20133 INTERFACES.C.STRINGS and INTERFACES.C.POINTERS). For more
20134 information, see the section ``Interfacing to C'' in the
20135 @cite{GNAT Reference Manual}.
20136
20137 The @option{-gnatF} qualifier forces default and explicit
20138 @code{External_Name} parameters in pragmas Import and Export
20139 to be uppercased for compatibility with the default behavior
20140 of Compaq C. The qualifier has no effect on @code{Link_Name} parameters.
20141
20142 @node Main Program Definition
20143 @section Main Program Definition
20144
20145 @noindent
20146 The following section discusses differences in the
20147 definition of main programs on DEC Ada and GNAT.
20148 On DEC Ada, main programs are defined to meet the
20149 following conditions:
20150 @itemize @bullet
20151 @item  Procedure with no formal parameters (returns 0 upon
20152        normal completion)
20153
20154 @item  Procedure with no formal parameters (returns 42 when
20155        unhandled exceptions are raised)
20156
20157 @item  Function with no formal parameters whose returned value
20158        is of a discrete type
20159
20160 @item  Procedure with one OUT formal of a discrete type for
20161        which a specification of pragma EXPORT_VALUED_PROCEDURE is given.
20162
20163 @end itemize
20164
20165 @noindent
20166 When declared with the pragma EXPORT_VALUED_PROCEDURE,
20167 a main function or main procedure returns a discrete
20168 value whose size is less than 64 bits (32 on VAX systems),
20169 the value is zero- or sign-extended as appropriate.
20170 On GNAT, main programs are defined as follows:
20171 @itemize @bullet
20172 @item  Must be a non-generic, parameter-less subprogram that
20173 is either a procedure or function returning an Ada
20174 STANDARD.INTEGER (the predefined type)
20175
20176 @item  Cannot be a generic subprogram or an instantiation of a
20177 generic subprogram
20178 @end itemize
20179
20180 @node Implementation-Defined Attributes
20181 @section Implementation-Defined Attributes
20182
20183 @noindent
20184 GNAT provides all DEC Ada implementation-defined
20185 attributes.
20186
20187 @node Compiler and Run-Time Interfacing
20188 @section Compiler and Run-Time Interfacing
20189
20190 @noindent
20191 DEC Ada provides the following ways to pass options to the linker
20192 (ACS LINK):
20193 @itemize @bullet
20194 @item  /WAIT and /SUBMIT qualifiers
20195
20196 @item  /COMMAND qualifier
20197
20198 @item  /[NO]MAP qualifier
20199
20200 @item  /OUTPUT=file-spec
20201
20202 @item  /[NO]DEBUG and /[NO]TRACEBACK qualifiers
20203 @end itemize
20204
20205 @noindent
20206 To pass options to the linker, GNAT provides the following
20207 switches:
20208
20209 @itemize @bullet
20210 @item   @option{/EXECUTABLE=exec-name}
20211
20212 @item   @option{/VERBOSE qualifier}
20213
20214 @item   @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK} qualifiers
20215 @end itemize
20216
20217 @noindent
20218 For more information on these switches, see
20219 @ref{Switches for gnatlink}.
20220 In DEC Ada, the command-line switch @option{/OPTIMIZE} is available
20221 to control optimization. DEC Ada also supplies the
20222 following pragmas:
20223 @itemize @bullet
20224 @item  @code{OPTIMIZE}
20225
20226 @item  @code{INLINE}
20227
20228 @item  @code{INLINE_GENERIC}
20229
20230 @item  @code{SUPPRESS_ALL}
20231
20232 @item  @code{PASSIVE}
20233 @end itemize
20234
20235 @noindent
20236 In GNAT, optimization is controlled strictly by command
20237 line parameters, as described in the corresponding section of this guide.
20238 The DIGITAL pragmas for control of optimization are
20239 recognized but ignored.
20240
20241 Note that in GNAT, the default is optimization off, whereas in DEC Ada 83,
20242 the default is that optimization is turned on.
20243
20244 @node Program Compilation and Library Management
20245 @section Program Compilation and Library Management
20246
20247 @noindent
20248 DEC Ada and GNAT provide a comparable set of commands to
20249 build programs. DEC Ada also provides a program library,
20250 which is a concept that does not exist on GNAT. Instead,
20251 GNAT provides directories of sources that are compiled as
20252 needed.
20253
20254 The following table summarizes
20255 the DEC Ada commands and provides
20256 equivalent GNAT commands. In this table, some GNAT
20257 equivalents reflect the fact that GNAT does not use the
20258 concept of a program library. Instead, it uses a model
20259 in which collections of source and object files are used
20260 in a manner consistent with other languages like C and
20261 Fortran. Therefore, standard system file commands are used
20262 to manipulate these elements. Those GNAT commands are marked with
20263 an asterisk.
20264 Note that, unlike DEC Ada, none of the GNAT commands accepts wild cards.
20265
20266 @need 1500
20267 @multitable @columnfractions .35 .65
20268
20269 @item @emph{DEC Ada Command}
20270 @tab @emph{GNAT Equivalent / Description}
20271
20272 @item @command{ADA}
20273 @tab @command{GNAT COMPILE}@*
20274 Invokes the compiler to compile one or more Ada source files.
20275
20276 @item @command{ACS ATTACH}@*
20277 @tab [No equivalent]@*
20278 Switches control of terminal from current process running the program
20279 library manager.
20280
20281 @item @command{ACS CHECK}
20282 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
20283 Forms the execution closure of one
20284 or more compiled units and checks completeness and currency.
20285
20286 @item @command{ACS COMPILE}
20287 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
20288 Forms the execution closure of one or
20289 more specified units, checks completeness and currency,
20290 identifies units that have revised source files, compiles same,
20291 and recompiles units that are or will become obsolete.
20292 Also completes incomplete generic instantiations.
20293
20294 @item @command{ACS COPY FOREIGN}
20295 @tab Copy (*)@*
20296 Copies a foreign object file into the program library as a
20297 library unit body.
20298
20299 @item @command{ACS COPY UNIT}
20300 @tab Copy (*)@*
20301 Copies a compiled unit from one program library to another.
20302
20303 @item @command{ACS CREATE LIBRARY}
20304 @tab Create /directory (*)@*
20305 Creates a program library.
20306
20307 @item @command{ACS CREATE SUBLIBRARY}
20308 @tab Create /directory (*)@*
20309 Creates a program sublibrary.
20310
20311 @item @command{ACS DELETE LIBRARY}
20312 @tab @*
20313 Deletes a program library and its contents.
20314
20315 @item @command{ACS DELETE SUBLIBRARY}
20316 @tab @*
20317 Deletes a program sublibrary and its contents.
20318
20319 @item @command{ACS DELETE UNIT}
20320 @tab Delete file (*)@*
20321 On OpenVMS systems, deletes one or more compiled units from
20322 the current program library.
20323
20324 @item @command{ACS DIRECTORY}
20325 @tab Directory (*)@*
20326 On OpenVMS systems, lists units contained in the current
20327 program library.
20328
20329 @item @command{ACS ENTER FOREIGN}
20330 @tab Copy (*)@*
20331 Allows the import of a foreign body as an Ada library
20332 specification and enters a reference to a pointer.
20333
20334 @item @command{ACS ENTER UNIT}
20335 @tab Copy (*)@*
20336 Enters a reference (pointer) from the current program library to
20337 a unit compiled into another program library.
20338
20339 @item @command{ACS EXIT}
20340 @tab [No equivalent]@*
20341 Exits from the program library manager.
20342
20343 @item @command{ACS EXPORT}
20344 @tab Copy (*)@*
20345 Creates an object file that contains system-specific object code
20346 for one or more units. With GNAT, object files can simply be copied
20347 into the desired directory.
20348
20349 @item @command{ACS EXTRACT SOURCE}
20350 @tab Copy (*)@*
20351 Allows access to the copied source file for each Ada compilation unit
20352
20353 @item @command{ACS HELP}
20354 @tab @command{HELP GNAT}@*
20355 Provides online help.
20356
20357 @item @command{ACS LINK}
20358 @tab @command{GNAT LINK}@*
20359 Links an object file containing Ada units into an executable file.
20360
20361 @item @command{ACS LOAD}
20362 @tab Copy (*)@*
20363 Loads (partially compiles) Ada units into the program library.
20364 Allows loading a program from a collection of files into a library
20365 without knowing the relationship among units.
20366
20367 @item @command{ACS MERGE}
20368 @tab Copy (*)@*
20369 Merges into the current program library, one or more units from
20370 another library where they were modified.
20371
20372 @item @command{ACS RECOMPILE}
20373 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
20374 Recompiles from   external or copied source files any obsolete
20375 unit in the closure. Also, completes any incomplete generic
20376 instantiations.
20377
20378 @item @command{ACS REENTER}
20379 @tab @command{GNAT MAKE}@*
20380 Reenters current references to units compiled after last entered
20381 with the @command{ACS ENTER UNIT} command.
20382
20383 @item @command{ACS SET LIBRARY}
20384 @tab Set default (*)@*
20385 Defines a program library to be the compilation context as well
20386 as the target library for compiler output and commands in general.
20387
20388 @item @command{ACS SET PRAGMA}
20389 @tab Edit @file{gnat.adc} (*)@*
20390 Redefines specified  values of the library characteristics
20391 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
20392 and @code{Float_Representation}.
20393
20394 @item @command{ACS SET SOURCE}
20395 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
20396 Defines the source file search list for the @command{ACS COMPILE} command.
20397
20398 @item @command{ACS SHOW LIBRARY}
20399 @tab Directory (*)@*
20400 Lists information about one or more program libraries.
20401
20402 @item @command{ACS SHOW PROGRAM}
20403 @tab [No equivalent]@*
20404 Lists information about the execution closure of one or
20405 more units in the program library.
20406
20407 @item @command{ACS SHOW SOURCE}
20408 @tab Show logical @code{ADA_INCLUDE_PATH}@*
20409 Shows the source file search used when compiling units.
20410
20411 @item @command{ACS SHOW VERSION}
20412 @tab Compile with @option{VERBOSE} option
20413 Displays the version number of the compiler and program library
20414 manager used.
20415
20416 @item @command{ACS SPAWN}
20417 @tab [No equivalent]@*
20418 Creates a subprocess of the current process (same as @command{DCL SPAWN}
20419 command).
20420
20421 @item @command{ACS VERIFY}
20422 @tab [No equivalent]@*
20423 Performs a series of consistency checks on a program library to
20424 determine whether the library structure and library files are in
20425 valid form.
20426 @end multitable
20427
20428 @noindent
20429
20430 @node Input-Output
20431 @section Input-Output
20432
20433 @noindent
20434 On OpenVMS Alpha systems, DEC Ada uses OpenVMS Record
20435 Management Services (RMS) to perform operations on
20436 external files.
20437
20438 @noindent
20439 DEC Ada and GNAT predefine an identical set of input-
20440 output packages. To make the use of the
20441 generic TEXT_IO operations more convenient, DEC Ada
20442 provides predefined library packages that instantiate the
20443 integer and floating-point operations for the predefined
20444 integer and floating-point types as shown in the following table.
20445
20446 @multitable @columnfractions .45 .55
20447 @item @emph{Package Name} @tab Instantiation
20448
20449 @item @code{INTEGER_TEXT_IO}
20450 @tab @code{INTEGER_IO(INTEGER)}
20451
20452 @item @code{SHORT_INTEGER_TEXT_IO}
20453 @tab @code{INTEGER_IO(SHORT_INTEGER)}
20454
20455 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
20456 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
20457
20458 @item @code{FLOAT_TEXT_IO}
20459 @tab @code{FLOAT_IO(FLOAT)}
20460
20461 @item @code{LONG_FLOAT_TEXT_IO}
20462 @tab @code{FLOAT_IO(LONG_FLOAT)}
20463 @end multitable
20464
20465 @noindent
20466 The DEC Ada predefined packages and their operations
20467 are implemented using OpenVMS Alpha files and input-
20468 output facilities. DEC Ada supports asynchronous input-
20469 output on OpenVMS Alpha. Familiarity with the following is
20470 recommended:
20471 @itemize @bullet
20472 @item  RMS file organizations and access methods
20473
20474 @item  OpenVMS file specifications and directories
20475
20476 @item  OpenVMS File Definition Language (FDL)
20477 @end itemize
20478
20479 @noindent
20480 GNAT provides I/O facilities that are completely
20481 compatible with DEC Ada. The distribution includes the
20482 standard DEC Ada versions of all I/O packages, operating
20483 in a manner compatible with DEC Ada. In particular, the
20484 following packages are by default the DEC Ada (Ada 83)
20485 versions of these packages rather than the renamings
20486 suggested in annex J of the Ada 95 Reference Manual:
20487 @itemize @bullet
20488 @item  @code{TEXT_IO}
20489
20490 @item  @code{SEQUENTIAL_IO}
20491
20492 @item  @code{DIRECT_IO}
20493 @end itemize
20494
20495 @noindent
20496 The use of the standard Ada 95 syntax for child packages (for
20497 example, @code{ADA.TEXT_IO}) retrieves the Ada 95 versions of these
20498 packages, as defined in the Ada 95 Reference Manual.
20499 GNAT provides DIGITAL-compatible predefined instantiations
20500 of the @code{TEXT_IO} packages, and also
20501 provides the standard predefined instantiations required
20502 by the Ada 95 Reference Manual.
20503
20504 For further information on how GNAT interfaces to the file
20505 system or how I/O is implemented in programs written in
20506 mixed languages, see the chapter ``Implementation of the
20507 Standard I/O'' in the @cite{GNAT Reference Manual}.
20508 This chapter covers the following:
20509 @itemize @bullet
20510 @item  Standard I/O packages
20511
20512 @item  @code{FORM} strings
20513
20514 @item  @code{ADA.DIRECT_IO}
20515
20516 @item  @code{ADA.SEQUENTIAL_IO}
20517
20518 @item  @code{ADA.TEXT_IO}
20519
20520 @item  Stream pointer positioning
20521
20522 @item  Reading and writing non-regular files
20523
20524 @item  @code{GET_IMMEDIATE}
20525
20526 @item  Treating @code{TEXT_IO} files as streams
20527
20528 @item  Shared files
20529
20530 @item  Open modes
20531 @end itemize
20532
20533 @node Implementation Limits
20534 @section Implementation Limits
20535
20536 @noindent
20537 The following table lists implementation limits for DEC Ada
20538 and GNAT systems.
20539 @multitable @columnfractions .60 .20 .20
20540 @sp 1
20541 @item  @emph{Compilation Parameter}
20542 @tab   @emph{DEC Ada}
20543 @tab   @emph{GNAT}
20544 @sp 1
20545
20546 @item  In a subprogram or entry  declaration, maximum number of
20547        formal parameters that are of an unconstrained record type
20548 @tab   32
20549 @tab   No set limit
20550 @sp 1
20551
20552 @item  Maximum identifier length (number of characters)
20553 @tab   255
20554 @tab   255
20555 @sp 1
20556
20557 @item  Maximum number of characters in a source line
20558 @tab   255
20559 @tab   255
20560 @sp 1
20561
20562 @item  Maximum collection size   (number of bytes)
20563 @tab   2**31-1
20564 @tab   2**31-1
20565 @sp 1
20566
20567 @item  Maximum number of discriminants for a record type
20568 @tab   245
20569 @tab   No set limit
20570 @sp 1
20571
20572 @item  Maximum number of formal parameters in an entry or
20573        subprogram declaration
20574 @tab   246
20575 @tab    No set limit
20576 @sp 1
20577
20578 @item  Maximum number of dimensions in an array type
20579 @tab   255
20580 @tab   No set limit
20581 @sp 1
20582
20583 @item  Maximum number of library  units and subunits in a compilation.
20584 @tab   4095
20585 @tab   No set limit
20586 @sp 1
20587
20588 @item  Maximum number of library units and subunits in an execution.
20589 @tab   16383
20590 @tab   No set limit
20591 @sp 1
20592
20593 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
20594        or @code{PSECT_OBJECT}
20595 @tab   32757
20596 @tab   No set limit
20597 @sp 1
20598
20599 @item  Maximum number of enumeration literals in an enumeration type
20600        definition
20601 @tab   65535
20602 @tab   No set limit
20603 @sp 1
20604
20605 @item  Maximum number of lines in a source file
20606 @tab   65534
20607 @tab   No set limit
20608 @sp 1
20609
20610 @item  Maximum number of bits in any object
20611 @tab   2**31-1
20612 @tab   2**31-1
20613 @sp 1
20614
20615 @item  Maximum size of the static portion of a stack frame (approximate)
20616 @tab   2**31-1
20617 @tab   2**31-1
20618 @end multitable
20619
20620 @node  Tools
20621 @section Tools
20622
20623 @end ifset
20624
20625
20626 @c **************************************
20627 @node Platform-Specific Information for the Run-Time Libraries
20628 @appendix Platform-Specific Information for the Run-Time Libraries
20629 @cindex Tasking and threads libraries
20630 @cindex Threads libraries and tasking
20631 @cindex Run-time libraries (platform-specific information)
20632
20633 @noindent
20634 The GNAT run-time implementation
20635 may vary with respect to both the underlying threads library and
20636 the exception handling scheme.
20637 For threads support, one or more of the following are supplied:
20638 @itemize @bullet
20639 @item @b{native threads library}, a binding to the thread package from
20640 the underlying operating system
20641
20642 @item @b{FSU threads library}, a binding to the Florida State University
20643 threads implementation, which complies fully with the requirements of Annex D
20644
20645 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
20646 POSIX thread package
20647 @end itemize
20648
20649 @noindent
20650 For exception handling, either or both of two models are supplied:
20651 @itemize @bullet
20652 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
20653 Most programs should experience a substantial speed improvement by
20654 being compiled with a ZCX run-time.
20655 This is especially true for
20656 tasking applications or applications with many exception handlers.}
20657 @cindex Zero-Cost Exceptions
20658 @cindex ZCX (Zero-Cost Exceptions)
20659 which uses binder-generated tables that
20660 are interrogated at run time to locate a handler
20661
20662 @item @b{setjmp / longjmp} (``SJLJ''),
20663 @cindex setjmp/longjmp Exception Model
20664 @cindex SJLJ (setjmp/longjmp Exception Model)
20665 which uses dynamically-set data to establish
20666 the set of handlers
20667 @end itemize
20668
20669 @noindent
20670 This appendix summarizes which combinations of threads and exception support
20671 are supplied on various GNAT platforms.
20672 It then shows how to select a particular library either
20673 permanently or temporarily,
20674 explains the properties of (and tradeoffs among) the various threads
20675 libraries, and provides some additional
20676 information about several specific platforms.
20677
20678 @menu
20679 * Summary of Run-Time Configurations::
20680 * Specifying a Run-Time Library::
20681 * Choosing between Native and FSU Threads Libraries::
20682 * Choosing the Scheduling Policy::
20683 * Solaris-Specific Considerations::
20684 * IRIX-Specific Considerations::
20685 * Linux-Specific Considerations::
20686 @end menu
20687
20688
20689 @node Summary of Run-Time Configurations
20690 @section Summary of Run-Time Configurations
20691
20692
20693 @multitable @columnfractions .30 .70
20694 @item @b{alpha-openvms}
20695 @item @code{@ @ }@i{rts-native (default)}
20696 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
20697 @item @code{@ @ @ @ }Exceptions @tab ZCX
20698 @*
20699 @item @b{pa-hpux}
20700 @item @code{@ @ }@i{rts-native (default)}
20701 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
20702 @item @code{@ @ @ @ }Exceptions @tab ZCX
20703 @*
20704 @item @code{@ @ }@i{rts-sjlj}
20705 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
20706 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20707 @*
20708 @item @b{sparc-solaris}  @tab
20709 @item @code{@ @ }@i{rts-native (default)}
20710 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
20711 @item @code{@ @ @ @ }Exceptions @tab ZCX
20712 @*
20713 @item @code{@ @ }@i{rts-fsu}    @tab
20714 @item @code{@ @ @ @ }Tasking    @tab FSU threads library
20715 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20716 @*
20717 @item @code{@ @ }@i{rts-m64}
20718 @item @code{@ @ @ @ }Tasking     @tab native Solaris threads library
20719 @item @code{@ @ @ @ }Exceptions  @tab ZCX
20720 @item @code{@ @ @ @ }Constraints @tab Use only when compiling in 64-bit mode;
20721 @item    @tab Use only on Solaris 8 or later.
20722 @item    @tab @xref{Building and Debugging 64-bit Applications}, for details.
20723 @*
20724 @item @code{@ @ }@i{rts-pthread}
20725 @item @code{@ @ @ @ }Tasking    @tab pthreads library
20726 @item @code{@ @ @ @ }Exceptions @tab ZCX
20727 @*
20728 @item @code{@ @ }@i{rts-sjlj}
20729 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
20730 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20731 @*
20732 @item @b{x86-linux}
20733 @item @code{@ @ }@i{rts-native (default)}
20734 @item @code{@ @ @ @ }Tasking    @tab LinuxThread library
20735 @item @code{@ @ @ @ }Exceptions @tab ZCX
20736 @*
20737 @item @code{@ @ }@i{rts-fsu}
20738 @item @code{@ @ @ @ }Tasking    @tab FSU threads library
20739 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20740 @*
20741 @item @code{@ @ }@i{rts-sjlj}
20742 @item @code{@ @ @ @ }Tasking    @tab LinuxThread library
20743 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20744 @*
20745 @item @b{x86-windows}
20746 @item @code{@ @ }@i{rts-native (default)}
20747 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
20748 @item @code{@ @ @ @ }Exceptions @tab SJLJ
20749 @*
20750 @end multitable
20751
20752
20753
20754 @node Specifying a Run-Time Library
20755 @section Specifying a Run-Time Library
20756
20757 @noindent
20758 The @file{adainclude} subdirectory containing the sources of the GNAT
20759 run-time library, and the @file{adalib} subdirectory containing the
20760 @file{ALI} files and the static and/or shared GNAT library, are located
20761 in the gcc target-dependent area:
20762
20763 @smallexample
20764 target=$prefix/lib/gcc-lib/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
20765 @end smallexample
20766
20767 @noindent
20768 As indicated above, on some platforms several run-time libraries are supplied.
20769 These libraries are installed in the target dependent area and
20770 contain a complete source and binary subdirectory. The detailed description
20771 below explains the differences between the different libraries in terms of
20772 their thread support.
20773
20774 The default run-time library (when GNAT is installed) is @emph{rts-native}.
20775 This default run time is selected by the means of soft links.
20776 For example on x86-linux:
20777
20778 @smallexample
20779 @group
20780  $(target-dir)
20781      |
20782      +--- adainclude----------+
20783      |                        |
20784      +--- adalib-----------+  |
20785      |                     |  |
20786      +--- rts-native       |  |
20787      |    |                |  |
20788      |    +--- adainclude <---+
20789      |    |                |
20790      |    +--- adalib <----+
20791      |
20792      +--- rts-fsu
20793      |    |
20794      |    +--- adainclude
20795      |    |
20796      |    +--- adalib
20797      |
20798      +--- rts-sjlj
20799           |
20800           +--- adainclude
20801           |
20802           +--- adalib
20803 @end group
20804 @end smallexample
20805
20806 @noindent
20807 If the @i{rts-fsu} library is to be selected on a permanent basis,
20808 these soft links can be modified with the following commands:
20809
20810 @smallexample
20811 $ cd $target
20812 $ rm -f adainclude adalib
20813 $ ln -s rts-fsu/adainclude adainclude
20814 $ ln -s rts-fsu/adalib adalib
20815 @end smallexample
20816
20817 @noindent
20818 Alternatively, you can specify @file{rts-fsu/adainclude} in the file
20819 @file{$target/ada_source_path} and @file{rts-fsu/adalib} in
20820 @file{$target/ada_object_path}.
20821
20822 Selecting another run-time library temporarily can be
20823 achieved by the regular mechanism for GNAT object or source path selection:
20824
20825 @itemize @bullet
20826 @item
20827 Set the environment variables:
20828
20829 @smallexample
20830 $ ADA_INCLUDE_PATH=$target/rts-fsu/adainclude:$ADA_INCLUDE_PATH
20831 $ ADA_OBJECTS_PATH=$target/rts-fsu/adalib:$ADA_OBJECTS_PATH
20832 $ export ADA_INCLUDE_PATH ADA_OBJECTS_PATH
20833 @end smallexample
20834
20835 @item
20836 Use @option{-aI$target/rts-fsu/adainclude}
20837 and @option{-aO$target/rts-fsu/adalib}
20838 on the @command{gnatmake} command line
20839
20840 @item
20841 Use the switch @option{--RTS}; e.g., @option{--RTS=fsu}
20842 @cindex @option{--RTS} option
20843 @end itemize
20844
20845 @noindent
20846 You can similarly switch to @emph{rts-sjlj}.
20847
20848 @node Choosing between Native and FSU Threads Libraries
20849 @section Choosing between Native and FSU Threads Libraries
20850 @cindex Native threads library
20851 @cindex FSU threads library
20852
20853 @noindent
20854 Some GNAT implementations offer a choice between
20855 native threads and FSU threads.
20856
20857 @itemize @bullet
20858 @item
20859 The @emph{native threads} library correspond to the standard system threads
20860 implementation (e.g. LinuxThreads on GNU/Linux,
20861 @cindex LinuxThreads library
20862 POSIX threads on AIX, or
20863 Solaris threads on Solaris). When this option is chosen, GNAT provides
20864 a full and accurate implementation of the core language tasking model
20865 as described in Chapter 9 of the Ada Reference Manual,
20866 but might not (and probably does not) implement
20867 the exact semantics as specified in @w{Annex D} (the Real-Time Systems Annex).
20868 @cindex Annex D (Real-Time Systems Annex) compliance
20869 @cindex Real-Time Systems Annex compliance
20870 Indeed, the reason that a choice of libraries is offered
20871 on a given target is because some of the
20872 ACATS tests for @w{Annex D} fail using the native threads library.
20873 As far as possible, this library is implemented
20874 in accordance with Ada semantics (e.g., modifying priorities as required
20875 to simulate ceiling locking),
20876 but there are often slight inaccuracies, most often in the area of
20877 absolutely respecting the priority rules on a single
20878 processor.
20879 Moreover, it is not possible in general to define the exact behavior,
20880 because the native threads implementations
20881 are not well enough documented.
20882
20883 On systems where the @code{SCHED_FIFO} POSIX scheduling policy is supported,
20884 @cindex POSIX scheduling policies
20885 @cindex @code{SCHED_FIFO} scheduling policy
20886 native threads will provide a behavior very close to the @w{Annex D}
20887 requirements (i.e., a run-till-blocked scheduler with fixed priorities), but
20888 on some systems (in particular GNU/Linux and Solaris), you need to have root
20889 privileges to use the @code{SCHED_FIFO} policy.
20890
20891 @item
20892 The @emph{FSU threads} library provides a completely accurate implementation
20893 of @w{Annex D}.
20894 Thus, operating with this library, GNAT is 100% compliant with both the core
20895 and all @w{Annex D}
20896 requirements.
20897 The formal validations for implementations offering
20898 a choice of threads packages are always carried out using the FSU
20899 threads option.
20900 @end itemize
20901
20902 @noindent
20903 From these considerations, it might seem that FSU threads are the
20904 better choice,
20905 but that is by no means always the case. The FSU threads package
20906 operates with all Ada tasks appearing to the system to be a single
20907 thread. This is often considerably more efficient than operating
20908 with separate threads, since for example, switching between tasks
20909 can be accomplished without the (in some cases considerable)
20910 overhead of a context switch between two system threads. However,
20911 it means that you may well lose concurrency at the system
20912 level. Notably, some system operations (such as I/O) may block all
20913 tasks in a program and not just the calling task. More
20914 significantly, the FSU threads approach likely means you cannot
20915 take advantage of multiple processors, since for this you need
20916 separate threads (or even separate processes) to operate on
20917 different processors.
20918
20919 For most programs, the native threads library is
20920 usually the better choice. Use the FSU threads if absolute
20921 conformance to @w{Annex D} is important for your application, or if
20922 you find that the improved efficiency of FSU threads is significant to you.
20923
20924 Note also that to take full advantage of Florist and Glade, it is highly
20925 recommended that you use native threads.
20926
20927
20928 @node Choosing the Scheduling Policy
20929 @section Choosing the Scheduling Policy
20930
20931 @noindent
20932 When using a POSIX threads implementation, you have a choice of several
20933 scheduling policies: @code{SCHED_FIFO},
20934 @cindex @code{SCHED_FIFO} scheduling policy
20935 @code{SCHED_RR}
20936 @cindex @code{SCHED_RR} scheduling policy
20937 and @code{SCHED_OTHER}.
20938 @cindex @code{SCHED_OTHER} scheduling policy
20939 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
20940 or @code{SCHED_RR} requires special (e.g., root) privileges.
20941
20942 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
20943 @code{SCHED_FIFO},
20944 @cindex @code{SCHED_FIFO} scheduling policy
20945 you can use one of the following:
20946
20947 @itemize @bullet
20948 @item
20949 @code{pragma Time_Slice (0.0)}
20950 @cindex pragma Time_Slice
20951 @item
20952 the corresponding binder option @option{-T0}
20953 @cindex @option{-T0} option
20954 @item
20955 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
20956 @cindex pragma Task_Dispatching_Policy
20957 @end itemize
20958
20959 @noindent
20960 To specify @code{SCHED_RR},
20961 @cindex @code{SCHED_RR} scheduling policy
20962 you should use @code{pragma Time_Slice} with a
20963 value greater than @code{0.0}, or else use the corresponding @option{-T}
20964 binder option.
20965
20966
20967
20968 @node Solaris-Specific Considerations
20969 @section Solaris-Specific Considerations
20970 @cindex Solaris Sparc threads libraries
20971
20972 @noindent
20973 This section addresses some topics related to the various threads libraries
20974 on Sparc Solaris and then provides some information on building and
20975 debugging 64-bit applications.
20976
20977 @menu
20978 * Solaris Threads Issues::
20979 * Building and Debugging 64-bit Applications::
20980 @end menu
20981
20982
20983 @node Solaris Threads Issues
20984 @subsection Solaris Threads Issues
20985
20986 @noindent
20987 Starting with version 3.14, GNAT under Solaris comes with a new tasking
20988 run-time library based on POSIX threads --- @emph{rts-pthread}.
20989 @cindex rts-pthread threads library
20990 This run-time library has the advantage of being mostly shared across all
20991 POSIX-compliant thread implementations, and it also provides under
20992 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
20993 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
20994 and @code{PTHREAD_PRIO_PROTECT}
20995 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
20996 semantics that can be selected using the predefined pragma
20997 @code{Locking_Policy}
20998 @cindex pragma Locking_Policy (under rts-pthread)
20999 with respectively
21000 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
21001 @cindex @code{Inheritance_Locking} (under rts-pthread)
21002 @cindex @code{Ceiling_Locking} (under rts-pthread)
21003
21004 As explained above, the native run-time library is based on the Solaris thread
21005 library (@code{libthread}) and is the default library.
21006 The FSU run-time library is based on the FSU threads.
21007 @cindex FSU threads library
21008
21009 Starting with Solaris 2.5.1, when the Solaris threads library is used
21010 (this is the default), programs
21011 compiled with GNAT can automatically take advantage of
21012 and can thus execute on multiple processors.
21013 The user can alternatively specify a processor on which the program should run
21014 to emulate a single-processor system. The multiprocessor / uniprocessor choice
21015 is made by
21016 setting the environment variable @code{GNAT_PROCESSOR}
21017 @cindex @code{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
21018 to one of the following:
21019
21020 @table @code
21021 @item -2
21022 Use the default configuration (run the program on all
21023          available processors) - this is the same as having
21024          @code{GNAT_PROCESSOR} unset
21025
21026 @item -1
21027 Let the run-time implementation choose one processor and run the program on
21028          that processor
21029
21030 @item 0 .. Last_Proc
21031 Run the program on the specified processor.
21032   @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
21033 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
21034 @end table
21035
21036
21037 @node Building and Debugging 64-bit Applications
21038 @subsection Building and Debugging 64-bit Applications
21039
21040 @noindent
21041 In a 64-bit application, all the sources involved must be compiled with the
21042 @option{-m64} command-line option, and a specific GNAT library (compiled with
21043 this option) is required.
21044 The easiest way to build a 64bit application is to add
21045 @option{-m64 --RTS=m64} to the @command{gnatmake} flags.
21046
21047 To debug these applications, dwarf-2 debug information is required, so you
21048 have to add @option{-gdwarf-2} to your gnatmake arguments.
21049 In addition, a special
21050 version of gdb, called @command{gdb64}, needs to be used.
21051
21052 To summarize, building and debugging a ``Hello World'' program in 64-bit mode
21053 amounts to:
21054
21055 @smallexample
21056      $ gnatmake -m64 -gdwarf-2 --RTS=m64 hello.adb
21057      $ gdb64 hello
21058 @end smallexample
21059
21060
21061
21062 @node IRIX-Specific Considerations
21063 @section IRIX-Specific Considerations
21064 @cindex IRIX thread library
21065
21066 @noindent
21067 On SGI IRIX, the thread library depends on which compiler is used.
21068 The @emph{o32 ABI} compiler comes with a run-time library based on the
21069 user-level @code{athread}
21070 library. Thus kernel-level capabilities such as nonblocking system
21071 calls or time slicing can only be achieved reliably by specifying different
21072 @code{sprocs} via the pragma @code{Task_Info}
21073 @cindex pragma Task_Info (and IRIX threads)
21074 and the
21075 @code{System.Task_Info} package.
21076 @cindex @code{System.Task_Info} package (and IRIX threads)
21077 See the @cite{GNAT Reference Manual} for further information.
21078
21079 The @emph{n32 ABI} compiler comes with a run-time library based on the
21080 kernel POSIX threads and thus does not have the limitations mentioned above.
21081
21082
21083 @node Linux-Specific Considerations
21084 @section Linux-Specific Considerations
21085 @cindex Linux threads libraries
21086
21087 @noindent
21088 The default thread library under GNU/Linux has the following disadvantages
21089 compared to other native thread libraries:
21090
21091 @itemize @bullet
21092 @item The size of the task's stack is limited to 2 megabytes.
21093 @item  The signal model is not POSIX compliant, which means that to send a
21094   signal to the process, you need to send the signal to all threads,
21095   e.g. by using @code{killpg()}.
21096 @end itemize
21097
21098
21099
21100 @c *******************************
21101 @node Example of Binder Output File
21102 @appendix Example of Binder Output File
21103
21104 @noindent
21105 This Appendix displays the source code for @command{gnatbind}'s output
21106 file generated for a simple ``Hello World'' program.
21107 Comments have been added for clarification purposes.
21108
21109
21110 @smallexample @c adanocomment
21111 @iftex
21112 @leftskip=0cm
21113 @end iftex
21114 --  The package is called Ada_Main unless this name is actually used
21115 --  as a unit name in the partition, in which case some other unique
21116 --  name is used.
21117
21118 with System;
21119 package ada_main is
21120
21121    Elab_Final_Code : Integer;
21122    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
21123
21124    --  The main program saves the parameters (argument count,
21125    --  argument values, environment pointer) in global variables
21126    --  for later access by other units including
21127    --  Ada.Command_Line.
21128
21129    gnat_argc : Integer;
21130    gnat_argv : System.Address;
21131    gnat_envp : System.Address;
21132
21133    --  The actual variables are stored in a library routine. This
21134    --  is useful for some shared library situations, where there
21135    --  are problems if variables are not in the library.
21136
21137    pragma Import (C, gnat_argc);
21138    pragma Import (C, gnat_argv);
21139    pragma Import (C, gnat_envp);
21140
21141    --  The exit status is similarly an external location
21142
21143    gnat_exit_status : Integer;
21144    pragma Import (C, gnat_exit_status);
21145
21146    GNAT_Version : constant String :=
21147                     "GNAT Version: 3.15w (20010315)";
21148    pragma Export (C, GNAT_Version, "__gnat_version");
21149
21150    --  This is the generated adafinal routine that performs
21151    --  finalization at the end of execution. In the case where
21152    --  Ada is the main program, this main program makes a call
21153    --  to adafinal at program termination.
21154
21155    procedure adafinal;
21156    pragma Export (C, adafinal, "adafinal");
21157
21158    --  This is the generated adainit routine that performs
21159    --  initialization at the start of execution. In the case
21160    --  where Ada is the main program, this main program makes
21161    --  a call to adainit at program startup.
21162
21163    procedure adainit;
21164    pragma Export (C, adainit, "adainit");
21165
21166    --  This routine is called at the start of execution. It is
21167    --  a dummy routine that is used by the debugger to breakpoint
21168    --  at the start of execution.
21169
21170    procedure Break_Start;
21171    pragma Import (C, Break_Start, "__gnat_break_start");
21172
21173    --  This is the actual generated main program (it would be
21174    --  suppressed if the no main program switch were used). As
21175    --  required by standard system conventions, this program has
21176    --  the external name main.
21177
21178    function main
21179      (argc : Integer;
21180       argv : System.Address;
21181       envp : System.Address)
21182       return Integer;
21183    pragma Export (C, main, "main");
21184
21185    --  The following set of constants give the version
21186    --  identification values for every unit in the bound
21187    --  partition. This identification is computed from all
21188    --  dependent semantic units, and corresponds to the
21189    --  string that would be returned by use of the
21190    --  Body_Version or Version attributes.
21191
21192    type Version_32 is mod 2 ** 32;
21193    u00001 : constant Version_32 := 16#7880BEB3#;
21194    u00002 : constant Version_32 := 16#0D24CBD0#;
21195    u00003 : constant Version_32 := 16#3283DBEB#;
21196    u00004 : constant Version_32 := 16#2359F9ED#;
21197    u00005 : constant Version_32 := 16#664FB847#;
21198    u00006 : constant Version_32 := 16#68E803DF#;
21199    u00007 : constant Version_32 := 16#5572E604#;
21200    u00008 : constant Version_32 := 16#46B173D8#;
21201    u00009 : constant Version_32 := 16#156A40CF#;
21202    u00010 : constant Version_32 := 16#033DABE0#;
21203    u00011 : constant Version_32 := 16#6AB38FEA#;
21204    u00012 : constant Version_32 := 16#22B6217D#;
21205    u00013 : constant Version_32 := 16#68A22947#;
21206    u00014 : constant Version_32 := 16#18CC4A56#;
21207    u00015 : constant Version_32 := 16#08258E1B#;
21208    u00016 : constant Version_32 := 16#367D5222#;
21209    u00017 : constant Version_32 := 16#20C9ECA4#;
21210    u00018 : constant Version_32 := 16#50D32CB6#;
21211    u00019 : constant Version_32 := 16#39A8BB77#;
21212    u00020 : constant Version_32 := 16#5CF8FA2B#;
21213    u00021 : constant Version_32 := 16#2F1EB794#;
21214    u00022 : constant Version_32 := 16#31AB6444#;
21215    u00023 : constant Version_32 := 16#1574B6E9#;
21216    u00024 : constant Version_32 := 16#5109C189#;
21217    u00025 : constant Version_32 := 16#56D770CD#;
21218    u00026 : constant Version_32 := 16#02F9DE3D#;
21219    u00027 : constant Version_32 := 16#08AB6B2C#;
21220    u00028 : constant Version_32 := 16#3FA37670#;
21221    u00029 : constant Version_32 := 16#476457A0#;
21222    u00030 : constant Version_32 := 16#731E1B6E#;
21223    u00031 : constant Version_32 := 16#23C2E789#;
21224    u00032 : constant Version_32 := 16#0F1BD6A1#;
21225    u00033 : constant Version_32 := 16#7C25DE96#;
21226    u00034 : constant Version_32 := 16#39ADFFA2#;
21227    u00035 : constant Version_32 := 16#571DE3E7#;
21228    u00036 : constant Version_32 := 16#5EB646AB#;
21229    u00037 : constant Version_32 := 16#4249379B#;
21230    u00038 : constant Version_32 := 16#0357E00A#;
21231    u00039 : constant Version_32 := 16#3784FB72#;
21232    u00040 : constant Version_32 := 16#2E723019#;
21233    u00041 : constant Version_32 := 16#623358EA#;
21234    u00042 : constant Version_32 := 16#107F9465#;
21235    u00043 : constant Version_32 := 16#6843F68A#;
21236    u00044 : constant Version_32 := 16#63305874#;
21237    u00045 : constant Version_32 := 16#31E56CE1#;
21238    u00046 : constant Version_32 := 16#02917970#;
21239    u00047 : constant Version_32 := 16#6CCBA70E#;
21240    u00048 : constant Version_32 := 16#41CD4204#;
21241    u00049 : constant Version_32 := 16#572E3F58#;
21242    u00050 : constant Version_32 := 16#20729FF5#;
21243    u00051 : constant Version_32 := 16#1D4F93E8#;
21244    u00052 : constant Version_32 := 16#30B2EC3D#;
21245    u00053 : constant Version_32 := 16#34054F96#;
21246    u00054 : constant Version_32 := 16#5A199860#;
21247    u00055 : constant Version_32 := 16#0E7F912B#;
21248    u00056 : constant Version_32 := 16#5760634A#;
21249    u00057 : constant Version_32 := 16#5D851835#;
21250
21251    --  The following Export pragmas export the version numbers
21252    --  with symbolic names ending in B (for body) or S
21253    --  (for spec) so that they can be located in a link. The
21254    --  information provided here is sufficient to track down
21255    --  the exact versions of units used in a given build.
21256
21257    pragma Export (C, u00001, "helloB");
21258    pragma Export (C, u00002, "system__standard_libraryB");
21259    pragma Export (C, u00003, "system__standard_libraryS");
21260    pragma Export (C, u00004, "adaS");
21261    pragma Export (C, u00005, "ada__text_ioB");
21262    pragma Export (C, u00006, "ada__text_ioS");
21263    pragma Export (C, u00007, "ada__exceptionsB");
21264    pragma Export (C, u00008, "ada__exceptionsS");
21265    pragma Export (C, u00009, "gnatS");
21266    pragma Export (C, u00010, "gnat__heap_sort_aB");
21267    pragma Export (C, u00011, "gnat__heap_sort_aS");
21268    pragma Export (C, u00012, "systemS");
21269    pragma Export (C, u00013, "system__exception_tableB");
21270    pragma Export (C, u00014, "system__exception_tableS");
21271    pragma Export (C, u00015, "gnat__htableB");
21272    pragma Export (C, u00016, "gnat__htableS");
21273    pragma Export (C, u00017, "system__exceptionsS");
21274    pragma Export (C, u00018, "system__machine_state_operationsB");
21275    pragma Export (C, u00019, "system__machine_state_operationsS");
21276    pragma Export (C, u00020, "system__machine_codeS");
21277    pragma Export (C, u00021, "system__storage_elementsB");
21278    pragma Export (C, u00022, "system__storage_elementsS");
21279    pragma Export (C, u00023, "system__secondary_stackB");
21280    pragma Export (C, u00024, "system__secondary_stackS");
21281    pragma Export (C, u00025, "system__parametersB");
21282    pragma Export (C, u00026, "system__parametersS");
21283    pragma Export (C, u00027, "system__soft_linksB");
21284    pragma Export (C, u00028, "system__soft_linksS");
21285    pragma Export (C, u00029, "system__stack_checkingB");
21286    pragma Export (C, u00030, "system__stack_checkingS");
21287    pragma Export (C, u00031, "system__tracebackB");
21288    pragma Export (C, u00032, "system__tracebackS");
21289    pragma Export (C, u00033, "ada__streamsS");
21290    pragma Export (C, u00034, "ada__tagsB");
21291    pragma Export (C, u00035, "ada__tagsS");
21292    pragma Export (C, u00036, "system__string_opsB");
21293    pragma Export (C, u00037, "system__string_opsS");
21294    pragma Export (C, u00038, "interfacesS");
21295    pragma Export (C, u00039, "interfaces__c_streamsB");
21296    pragma Export (C, u00040, "interfaces__c_streamsS");
21297    pragma Export (C, u00041, "system__file_ioB");
21298    pragma Export (C, u00042, "system__file_ioS");
21299    pragma Export (C, u00043, "ada__finalizationB");
21300    pragma Export (C, u00044, "ada__finalizationS");
21301    pragma Export (C, u00045, "system__finalization_rootB");
21302    pragma Export (C, u00046, "system__finalization_rootS");
21303    pragma Export (C, u00047, "system__finalization_implementationB");
21304    pragma Export (C, u00048, "system__finalization_implementationS");
21305    pragma Export (C, u00049, "system__string_ops_concat_3B");
21306    pragma Export (C, u00050, "system__string_ops_concat_3S");
21307    pragma Export (C, u00051, "system__stream_attributesB");
21308    pragma Export (C, u00052, "system__stream_attributesS");
21309    pragma Export (C, u00053, "ada__io_exceptionsS");
21310    pragma Export (C, u00054, "system__unsigned_typesS");
21311    pragma Export (C, u00055, "system__file_control_blockS");
21312    pragma Export (C, u00056, "ada__finalization__list_controllerB");
21313    pragma Export (C, u00057, "ada__finalization__list_controllerS");
21314
21315    -- BEGIN ELABORATION ORDER
21316    -- ada (spec)
21317    -- gnat (spec)
21318    -- gnat.heap_sort_a (spec)
21319    -- gnat.heap_sort_a (body)
21320    -- gnat.htable (spec)
21321    -- gnat.htable (body)
21322    -- interfaces (spec)
21323    -- system (spec)
21324    -- system.machine_code (spec)
21325    -- system.parameters (spec)
21326    -- system.parameters (body)
21327    -- interfaces.c_streams (spec)
21328    -- interfaces.c_streams (body)
21329    -- system.standard_library (spec)
21330    -- ada.exceptions (spec)
21331    -- system.exception_table (spec)
21332    -- system.exception_table (body)
21333    -- ada.io_exceptions (spec)
21334    -- system.exceptions (spec)
21335    -- system.storage_elements (spec)
21336    -- system.storage_elements (body)
21337    -- system.machine_state_operations (spec)
21338    -- system.machine_state_operations (body)
21339    -- system.secondary_stack (spec)
21340    -- system.stack_checking (spec)
21341    -- system.soft_links (spec)
21342    -- system.soft_links (body)
21343    -- system.stack_checking (body)
21344    -- system.secondary_stack (body)
21345    -- system.standard_library (body)
21346    -- system.string_ops (spec)
21347    -- system.string_ops (body)
21348    -- ada.tags (spec)
21349    -- ada.tags (body)
21350    -- ada.streams (spec)
21351    -- system.finalization_root (spec)
21352    -- system.finalization_root (body)
21353    -- system.string_ops_concat_3 (spec)
21354    -- system.string_ops_concat_3 (body)
21355    -- system.traceback (spec)
21356    -- system.traceback (body)
21357    -- ada.exceptions (body)
21358    -- system.unsigned_types (spec)
21359    -- system.stream_attributes (spec)
21360    -- system.stream_attributes (body)
21361    -- system.finalization_implementation (spec)
21362    -- system.finalization_implementation (body)
21363    -- ada.finalization (spec)
21364    -- ada.finalization (body)
21365    -- ada.finalization.list_controller (spec)
21366    -- ada.finalization.list_controller (body)
21367    -- system.file_control_block (spec)
21368    -- system.file_io (spec)
21369    -- system.file_io (body)
21370    -- ada.text_io (spec)
21371    -- ada.text_io (body)
21372    -- hello (body)
21373    -- END ELABORATION ORDER
21374
21375 end ada_main;
21376
21377 --  The following source file name pragmas allow the generated file
21378 --  names to be unique for different main programs. They are needed
21379 --  since the package name will always be Ada_Main.
21380
21381 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
21382 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
21383
21384 --  Generated package body for Ada_Main starts here
21385
21386 package body ada_main is
21387
21388    --  The actual finalization is performed by calling the
21389    --  library routine in System.Standard_Library.Adafinal
21390
21391    procedure Do_Finalize;
21392    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
21393
21394    -------------
21395    -- adainit --
21396    -------------
21397
21398 @findex adainit
21399    procedure adainit is
21400
21401       --  These booleans are set to True once the associated unit has
21402       --  been elaborated. It is also used to avoid elaborating the
21403       --  same unit twice.
21404
21405       E040 : Boolean;
21406       pragma Import (Ada, E040, "interfaces__c_streams_E");
21407
21408       E008 : Boolean;
21409       pragma Import (Ada, E008, "ada__exceptions_E");
21410
21411       E014 : Boolean;
21412       pragma Import (Ada, E014, "system__exception_table_E");
21413
21414       E053 : Boolean;
21415       pragma Import (Ada, E053, "ada__io_exceptions_E");
21416
21417       E017 : Boolean;
21418       pragma Import (Ada, E017, "system__exceptions_E");
21419
21420       E024 : Boolean;
21421       pragma Import (Ada, E024, "system__secondary_stack_E");
21422
21423       E030 : Boolean;
21424       pragma Import (Ada, E030, "system__stack_checking_E");
21425
21426       E028 : Boolean;
21427       pragma Import (Ada, E028, "system__soft_links_E");
21428
21429       E035 : Boolean;
21430       pragma Import (Ada, E035, "ada__tags_E");
21431
21432       E033 : Boolean;
21433       pragma Import (Ada, E033, "ada__streams_E");
21434
21435       E046 : Boolean;
21436       pragma Import (Ada, E046, "system__finalization_root_E");
21437
21438       E048 : Boolean;
21439       pragma Import (Ada, E048, "system__finalization_implementation_E");
21440
21441       E044 : Boolean;
21442       pragma Import (Ada, E044, "ada__finalization_E");
21443
21444       E057 : Boolean;
21445       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
21446
21447       E055 : Boolean;
21448       pragma Import (Ada, E055, "system__file_control_block_E");
21449
21450       E042 : Boolean;
21451       pragma Import (Ada, E042, "system__file_io_E");
21452
21453       E006 : Boolean;
21454       pragma Import (Ada, E006, "ada__text_io_E");
21455
21456       --  Set_Globals is a library routine that stores away the
21457       --  value of the indicated set of global values in global
21458       --  variables within the library.
21459
21460       procedure Set_Globals
21461         (Main_Priority            : Integer;
21462          Time_Slice_Value         : Integer;
21463          WC_Encoding              : Character;
21464          Locking_Policy           : Character;
21465          Queuing_Policy           : Character;
21466          Task_Dispatching_Policy  : Character;
21467          Adafinal                 : System.Address;
21468          Unreserve_All_Interrupts : Integer;
21469          Exception_Tracebacks     : Integer);
21470 @findex __gnat_set_globals
21471       pragma Import (C, Set_Globals, "__gnat_set_globals");
21472
21473       --  SDP_Table_Build is a library routine used to build the
21474       --  exception tables. See unit Ada.Exceptions in files
21475       --  a-except.ads/adb for full details of how zero cost
21476       --  exception handling works. This procedure, the call to
21477       --  it, and the two following tables are all omitted if the
21478       --  build is in longjmp/setjump exception mode.
21479
21480 @findex SDP_Table_Build
21481 @findex Zero Cost Exceptions
21482       procedure SDP_Table_Build
21483         (SDP_Addresses   : System.Address;
21484          SDP_Count       : Natural;
21485          Elab_Addresses  : System.Address;
21486          Elab_Addr_Count : Natural);
21487       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
21488
21489       --  Table of Unit_Exception_Table addresses. Used for zero
21490       --  cost exception handling to build the top level table.
21491
21492       ST : aliased constant array (1 .. 23) of System.Address := (
21493         Hello'UET_Address,
21494         Ada.Text_Io'UET_Address,
21495         Ada.Exceptions'UET_Address,
21496         Gnat.Heap_Sort_A'UET_Address,
21497         System.Exception_Table'UET_Address,
21498         System.Machine_State_Operations'UET_Address,
21499         System.Secondary_Stack'UET_Address,
21500         System.Parameters'UET_Address,
21501         System.Soft_Links'UET_Address,
21502         System.Stack_Checking'UET_Address,
21503         System.Traceback'UET_Address,
21504         Ada.Streams'UET_Address,
21505         Ada.Tags'UET_Address,
21506         System.String_Ops'UET_Address,
21507         Interfaces.C_Streams'UET_Address,
21508         System.File_Io'UET_Address,
21509         Ada.Finalization'UET_Address,
21510         System.Finalization_Root'UET_Address,
21511         System.Finalization_Implementation'UET_Address,
21512         System.String_Ops_Concat_3'UET_Address,
21513         System.Stream_Attributes'UET_Address,
21514         System.File_Control_Block'UET_Address,
21515         Ada.Finalization.List_Controller'UET_Address);
21516
21517       --  Table of addresses of elaboration routines. Used for
21518       --  zero cost exception handling to make sure these
21519       --  addresses are included in the top level procedure
21520       --  address table.
21521
21522       EA : aliased constant array (1 .. 23) of System.Address := (
21523         adainit'Code_Address,
21524         Do_Finalize'Code_Address,
21525         Ada.Exceptions'Elab_Spec'Address,
21526         System.Exceptions'Elab_Spec'Address,
21527         Interfaces.C_Streams'Elab_Spec'Address,
21528         System.Exception_Table'Elab_Body'Address,
21529         Ada.Io_Exceptions'Elab_Spec'Address,
21530         System.Stack_Checking'Elab_Spec'Address,
21531         System.Soft_Links'Elab_Body'Address,
21532         System.Secondary_Stack'Elab_Body'Address,
21533         Ada.Tags'Elab_Spec'Address,
21534         Ada.Tags'Elab_Body'Address,
21535         Ada.Streams'Elab_Spec'Address,
21536         System.Finalization_Root'Elab_Spec'Address,
21537         Ada.Exceptions'Elab_Body'Address,
21538         System.Finalization_Implementation'Elab_Spec'Address,
21539         System.Finalization_Implementation'Elab_Body'Address,
21540         Ada.Finalization'Elab_Spec'Address,
21541         Ada.Finalization.List_Controller'Elab_Spec'Address,
21542         System.File_Control_Block'Elab_Spec'Address,
21543         System.File_Io'Elab_Body'Address,
21544         Ada.Text_Io'Elab_Spec'Address,
21545         Ada.Text_Io'Elab_Body'Address);
21546
21547    --  Start of processing for adainit
21548
21549    begin
21550
21551       --  Call SDP_Table_Build to build the top level procedure
21552       --  table for zero cost exception handling (omitted in
21553       --  longjmp/setjump mode).
21554
21555       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
21556
21557       --  Call Set_Globals to record various information for
21558       --  this partition.  The values are derived by the binder
21559       --  from information stored in the ali files by the compiler.
21560
21561 @findex __gnat_set_globals
21562       Set_Globals
21563         (Main_Priority            => -1,
21564          --  Priority of main program, -1 if no pragma Priority used
21565
21566          Time_Slice_Value         => -1,
21567          --  Time slice from Time_Slice pragma, -1 if none used
21568
21569          WC_Encoding              => 'b',
21570          --  Wide_Character encoding used, default is brackets
21571
21572          Locking_Policy           => ' ',
21573          --  Locking_Policy used, default of space means not
21574          --  specified, otherwise it is the first character of
21575          --  the policy name.
21576
21577          Queuing_Policy           => ' ',
21578          --  Queuing_Policy used, default of space means not
21579          --  specified, otherwise it is the first character of
21580          --  the policy name.
21581
21582          Task_Dispatching_Policy  => ' ',
21583          --  Task_Dispatching_Policy used, default of space means
21584          --  not specified, otherwise first character of the
21585          --  policy name.
21586
21587          Adafinal                 => System.Null_Address,
21588          --  Address of Adafinal routine, not used anymore
21589
21590          Unreserve_All_Interrupts => 0,
21591          --  Set true if pragma Unreserve_All_Interrupts was used
21592
21593          Exception_Tracebacks     => 0);
21594          --  Indicates if exception tracebacks are enabled
21595
21596       Elab_Final_Code := 1;
21597
21598       --  Now we have the elaboration calls for all units in the partition.
21599       --  The Elab_Spec and Elab_Body attributes generate references to the
21600       --  implicit elaboration procedures generated by the compiler for
21601       --  each unit that requires elaboration.
21602
21603       if not E040 then
21604          Interfaces.C_Streams'Elab_Spec;
21605       end if;
21606       E040 := True;
21607       if not E008 then
21608          Ada.Exceptions'Elab_Spec;
21609       end if;
21610       if not E014 then
21611          System.Exception_Table'Elab_Body;
21612          E014 := True;
21613       end if;
21614       if not E053 then
21615          Ada.Io_Exceptions'Elab_Spec;
21616          E053 := True;
21617       end if;
21618       if not E017 then
21619          System.Exceptions'Elab_Spec;
21620          E017 := True;
21621       end if;
21622       if not E030 then
21623          System.Stack_Checking'Elab_Spec;
21624       end if;
21625       if not E028 then
21626          System.Soft_Links'Elab_Body;
21627          E028 := True;
21628       end if;
21629       E030 := True;
21630       if not E024 then
21631          System.Secondary_Stack'Elab_Body;
21632          E024 := True;
21633       end if;
21634       if not E035 then
21635          Ada.Tags'Elab_Spec;
21636       end if;
21637       if not E035 then
21638          Ada.Tags'Elab_Body;
21639          E035 := True;
21640       end if;
21641       if not E033 then
21642          Ada.Streams'Elab_Spec;
21643          E033 := True;
21644       end if;
21645       if not E046 then
21646          System.Finalization_Root'Elab_Spec;
21647       end if;
21648       E046 := True;
21649       if not E008 then
21650          Ada.Exceptions'Elab_Body;
21651          E008 := True;
21652       end if;
21653       if not E048 then
21654          System.Finalization_Implementation'Elab_Spec;
21655       end if;
21656       if not E048 then
21657          System.Finalization_Implementation'Elab_Body;
21658          E048 := True;
21659       end if;
21660       if not E044 then
21661          Ada.Finalization'Elab_Spec;
21662       end if;
21663       E044 := True;
21664       if not E057 then
21665          Ada.Finalization.List_Controller'Elab_Spec;
21666       end if;
21667       E057 := True;
21668       if not E055 then
21669          System.File_Control_Block'Elab_Spec;
21670          E055 := True;
21671       end if;
21672       if not E042 then
21673          System.File_Io'Elab_Body;
21674          E042 := True;
21675       end if;
21676       if not E006 then
21677          Ada.Text_Io'Elab_Spec;
21678       end if;
21679       if not E006 then
21680          Ada.Text_Io'Elab_Body;
21681          E006 := True;
21682       end if;
21683
21684       Elab_Final_Code := 0;
21685    end adainit;
21686
21687    --------------
21688    -- adafinal --
21689    --------------
21690
21691 @findex adafinal
21692    procedure adafinal is
21693    begin
21694       Do_Finalize;
21695    end adafinal;
21696
21697    ----------
21698    -- main --
21699    ----------
21700
21701    --  main is actually a function, as in the ANSI C standard,
21702    --  defined to return the exit status. The three parameters
21703    --  are the argument count, argument values and environment
21704    --  pointer.
21705
21706 @findex Main Program
21707    function main
21708      (argc : Integer;
21709       argv : System.Address;
21710       envp : System.Address)
21711       return Integer
21712    is
21713       --  The initialize routine performs low level system
21714       --  initialization using a standard library routine which
21715       --  sets up signal handling and performs any other
21716       --  required setup. The routine can be found in file
21717       --  a-init.c.
21718
21719 @findex __gnat_initialize
21720       procedure initialize;
21721       pragma Import (C, initialize, "__gnat_initialize");
21722
21723       --  The finalize routine performs low level system
21724       --  finalization using a standard library routine. The
21725       --  routine is found in file a-final.c and in the standard
21726       --  distribution is a dummy routine that does nothing, so
21727       --  really this is a hook for special user finalization.
21728
21729 @findex __gnat_finalize
21730       procedure finalize;
21731       pragma Import (C, finalize, "__gnat_finalize");
21732
21733       --  We get to the main program of the partition by using
21734       --  pragma Import because if we try to with the unit and
21735       --  call it Ada style, then not only do we waste time
21736       --  recompiling it, but also, we don't really know the right
21737       --  switches (e.g. identifier character set) to be used
21738       --  to compile it.
21739
21740       procedure Ada_Main_Program;
21741       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
21742
21743    --  Start of processing for main
21744
21745    begin
21746       --  Save global variables
21747
21748       gnat_argc := argc;
21749       gnat_argv := argv;
21750       gnat_envp := envp;
21751
21752       --  Call low level system initialization
21753
21754       Initialize;
21755
21756       --  Call our generated Ada initialization routine
21757
21758       adainit;
21759
21760       --  This is the point at which we want the debugger to get
21761       --  control
21762
21763       Break_Start;
21764
21765       --  Now we call the main program of the partition
21766
21767       Ada_Main_Program;
21768
21769       --  Perform Ada finalization
21770
21771       adafinal;
21772
21773       --  Perform low level system finalization
21774
21775       Finalize;
21776
21777       --  Return the proper exit status
21778       return (gnat_exit_status);
21779    end;
21780
21781 --  This section is entirely comments, so it has no effect on the
21782 --  compilation of the Ada_Main package. It provides the list of
21783 --  object files and linker options, as well as some standard
21784 --  libraries needed for the link. The gnatlink utility parses
21785 --  this b~hello.adb file to read these comment lines to generate
21786 --  the appropriate command line arguments for the call to the
21787 --  system linker. The BEGIN/END lines are used for sentinels for
21788 --  this parsing operation.
21789
21790 --  The exact file names will of course depend on the environment,
21791 --  host/target and location of files on the host system.
21792
21793 @findex Object file list
21794 -- BEGIN Object file/option list
21795    --   ./hello.o
21796    --   -L./
21797    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
21798    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
21799 -- END Object file/option list
21800
21801 end ada_main;
21802 @end smallexample
21803
21804 @noindent
21805 The Ada code in the above example is exactly what is generated by the
21806 binder. We have added comments to more clearly indicate the function
21807 of each part of the generated @code{Ada_Main} package.
21808
21809 The code is standard Ada in all respects, and can be processed by any
21810 tools that handle Ada. In particular, it is possible to use the debugger
21811 in Ada mode to debug the generated @code{Ada_Main} package. For example,
21812 suppose that for reasons that you do not understand, your program is crashing
21813 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
21814 you can place a breakpoint on the call:
21815
21816 @smallexample @c ada
21817 Ada.Text_Io'Elab_Body;
21818 @end smallexample
21819
21820 @noindent
21821 and trace the elaboration routine for this package to find out where
21822 the problem might be (more usually of course you would be debugging
21823 elaboration code in your own application).
21824
21825
21826 @node Elaboration Order Handling in GNAT
21827 @appendix Elaboration Order Handling in GNAT
21828 @cindex Order of elaboration
21829 @cindex Elaboration control
21830
21831 @menu
21832 * Elaboration Code in Ada 95::
21833 * Checking the Elaboration Order in Ada 95::
21834 * Controlling the Elaboration Order in Ada 95::
21835 * Controlling Elaboration in GNAT - Internal Calls::
21836 * Controlling Elaboration in GNAT - External Calls::
21837 * Default Behavior in GNAT - Ensuring Safety::
21838 * Treatment of Pragma Elaborate::
21839 * Elaboration Issues for Library Tasks::
21840 * Mixing Elaboration Models::
21841 * What to Do If the Default Elaboration Behavior Fails::
21842 * Elaboration for Access-to-Subprogram Values::
21843 * Summary of Procedures for Elaboration Control::
21844 * Other Elaboration Order Considerations::
21845 @end menu
21846
21847 @noindent
21848 This chapter describes the handling of elaboration code in Ada 95 and
21849 in GNAT, and discusses how the order of elaboration of program units can
21850 be controlled in GNAT, either automatically or with explicit programming
21851 features.
21852
21853 @node Elaboration Code in Ada 95
21854 @section Elaboration Code in Ada 95
21855
21856 @noindent
21857 Ada 95 provides rather general mechanisms for executing code at elaboration
21858 time, that is to say before the main program starts executing. Such code arises
21859 in three contexts:
21860
21861 @table @asis
21862 @item Initializers for variables.
21863 Variables declared at the library level, in package specs or bodies, can
21864 require initialization that is performed at elaboration time, as in:
21865 @smallexample @c ada
21866 @cartouche
21867 Sqrt_Half : Float := Sqrt (0.5);
21868 @end cartouche
21869 @end smallexample
21870
21871 @item Package initialization code
21872 Code in a @code{BEGIN-END} section at the outer level of a package body is
21873 executed as part of the package body elaboration code.
21874
21875 @item Library level task allocators
21876 Tasks that are declared using task allocators at the library level
21877 start executing immediately and hence can execute at elaboration time.
21878 @end table
21879
21880 @noindent
21881 Subprogram calls are possible in any of these contexts, which means that
21882 any arbitrary part of the program may be executed as part of the elaboration
21883 code. It is even possible to write a program which does all its work at
21884 elaboration time, with a null main program, although stylistically this
21885 would usually be considered an inappropriate way to structure
21886 a program.
21887
21888 An important concern arises in the context of elaboration code:
21889 we have to be sure that it is executed in an appropriate order. What we
21890 have is a series of elaboration code sections, potentially one section
21891 for each unit in the program. It is important that these execute
21892 in the correct order. Correctness here means that, taking the above
21893 example of the declaration of @code{Sqrt_Half},
21894 if some other piece of
21895 elaboration code references @code{Sqrt_Half},
21896 then it must run after the
21897 section of elaboration code that contains the declaration of
21898 @code{Sqrt_Half}.
21899
21900 There would never be any order of elaboration problem if we made a rule
21901 that whenever you @code{with} a unit, you must elaborate both the spec and body
21902 of that unit before elaborating the unit doing the @code{with}'ing:
21903
21904 @smallexample @c ada
21905 @group
21906 @cartouche
21907 with Unit_1;
21908 package Unit_2 is ...
21909 @end cartouche
21910 @end group
21911 @end smallexample
21912
21913 @noindent
21914 would require that both the body and spec of @code{Unit_1} be elaborated
21915 before the spec of @code{Unit_2}. However, a rule like that would be far too
21916 restrictive. In particular, it would make it impossible to have routines
21917 in separate packages that were mutually recursive.
21918
21919 You might think that a clever enough compiler could look at the actual
21920 elaboration code and determine an appropriate correct order of elaboration,
21921 but in the general case, this is not possible. Consider the following
21922 example.
21923
21924 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
21925 that references
21926 the variable @code{Sqrt_1}, which is declared in the elaboration code
21927 of the body of @code{Unit_1}:
21928
21929 @smallexample @c ada
21930 @cartouche
21931 Sqrt_1 : Float := Sqrt (0.1);
21932 @end cartouche
21933 @end smallexample
21934
21935 @noindent
21936 The elaboration code of the body of @code{Unit_1} also contains:
21937
21938 @smallexample @c ada
21939 @group
21940 @cartouche
21941 if expression_1 = 1 then
21942    Q := Unit_2.Func_2;
21943 end if;
21944 @end cartouche
21945 @end group
21946 @end smallexample
21947
21948 @noindent
21949 @code{Unit_2} is exactly parallel,
21950 it has a procedure @code{Func_2} that references
21951 the variable @code{Sqrt_2}, which is declared in the elaboration code of
21952 the body @code{Unit_2}:
21953
21954 @smallexample @c ada
21955 @cartouche
21956 Sqrt_2 : Float := Sqrt (0.1);
21957 @end cartouche
21958 @end smallexample
21959
21960 @noindent
21961 The elaboration code of the body of @code{Unit_2} also contains:
21962
21963 @smallexample @c ada
21964 @group
21965 @cartouche
21966 if expression_2 = 2 then
21967    Q := Unit_1.Func_1;
21968 end if;
21969 @end cartouche
21970 @end group
21971 @end smallexample
21972
21973 @noindent
21974 Now the question is, which of the following orders of elaboration is
21975 acceptable:
21976
21977 @smallexample
21978 @group
21979 Spec of Unit_1
21980 Spec of Unit_2
21981 Body of Unit_1
21982 Body of Unit_2
21983 @end group
21984 @end smallexample
21985
21986 @noindent
21987 or
21988
21989 @smallexample
21990 @group
21991 Spec of Unit_2
21992 Spec of Unit_1
21993 Body of Unit_2
21994 Body of Unit_1
21995 @end group
21996 @end smallexample
21997
21998 @noindent
21999 If you carefully analyze the flow here, you will see that you cannot tell
22000 at compile time the answer to this question.
22001 If @code{expression_1} is not equal to 1,
22002 and @code{expression_2} is not equal to 2,
22003 then either order is acceptable, because neither of the function calls is
22004 executed. If both tests evaluate to true, then neither order is acceptable
22005 and in fact there is no correct order.
22006
22007 If one of the two expressions is true, and the other is false, then one
22008 of the above orders is correct, and the other is incorrect. For example,
22009 if @code{expression_1} = 1 and @code{expression_2} /= 2,
22010 then the call to @code{Func_2}
22011 will occur, but not the call to @code{Func_1.}
22012 This means that it is essential
22013 to elaborate the body of @code{Unit_1} before
22014 the body of @code{Unit_2}, so the first
22015 order of elaboration is correct and the second is wrong.
22016
22017 By making @code{expression_1} and @code{expression_2}
22018 depend on input data, or perhaps
22019 the time of day, we can make it impossible for the compiler or binder
22020 to figure out which of these expressions will be true, and hence it
22021 is impossible to guarantee a safe order of elaboration at run time.
22022
22023 @node Checking the Elaboration Order in Ada 95
22024 @section Checking the Elaboration Order in Ada 95
22025
22026 @noindent
22027 In some languages that involve the same kind of elaboration problems,
22028 e.g. Java and C++, the programmer is expected to worry about these
22029 ordering problems himself, and it is common to
22030 write a program in which an incorrect elaboration order  gives
22031 surprising results, because it references variables before they
22032 are initialized.
22033 Ada 95 is designed to be a safe language, and a programmer-beware approach is
22034 clearly not sufficient. Consequently, the language provides three lines
22035 of defense:
22036
22037 @table @asis
22038 @item Standard rules
22039 Some standard rules restrict the possible choice of elaboration
22040 order. In particular, if you @code{with} a unit, then its spec is always
22041 elaborated before the unit doing the @code{with}. Similarly, a parent
22042 spec is always elaborated before the child spec, and finally
22043 a spec is always elaborated before its corresponding body.
22044
22045 @item Dynamic elaboration checks
22046 @cindex Elaboration checks
22047 @cindex Checks, elaboration
22048 Dynamic checks are made at run time, so that if some entity is accessed
22049 before it is elaborated (typically  by means of a subprogram call)
22050 then the exception (@code{Program_Error}) is raised.
22051
22052 @item Elaboration control
22053 Facilities are provided for the programmer to specify the desired order
22054 of elaboration.
22055 @end table
22056
22057 Let's look at these facilities in more detail. First, the rules for
22058 dynamic checking. One possible rule would be simply to say that the
22059 exception is raised if you access a variable which has not yet been
22060 elaborated. The trouble with this approach is that it could require
22061 expensive checks on every variable reference. Instead Ada 95 has two
22062 rules which are a little more restrictive, but easier to check, and
22063 easier to state:
22064
22065 @table @asis
22066 @item Restrictions on calls
22067 A subprogram can only be called at elaboration time if its body
22068 has been elaborated. The rules for elaboration given above guarantee
22069 that the spec of the subprogram has been elaborated before the
22070 call, but not the body. If this rule is violated, then the
22071 exception @code{Program_Error} is raised.
22072
22073 @item Restrictions on instantiations
22074 A generic unit can only be instantiated if the body of the generic
22075 unit has been elaborated. Again, the rules for elaboration given above
22076 guarantee that the spec of the generic unit has been elaborated
22077 before the instantiation, but not the body. If this rule is
22078 violated, then the exception @code{Program_Error} is raised.
22079 @end table
22080
22081 @noindent
22082 The idea is that if the body has been elaborated, then any variables
22083 it references must have been elaborated; by checking for the body being
22084 elaborated we guarantee that none of its references causes any
22085 trouble. As we noted above, this is a little too restrictive, because a
22086 subprogram that has no non-local references in its body may in fact be safe
22087 to call. However, it really would be unsafe to rely on this, because
22088 it would mean that the caller was aware of details of the implementation
22089 in the body. This goes against the basic tenets of Ada.
22090
22091 A plausible implementation can be described as follows.
22092 A Boolean variable is associated with each subprogram
22093 and each generic unit. This variable is initialized to False, and is set to
22094 True at the point body is elaborated. Every call or instantiation checks the
22095 variable, and raises @code{Program_Error} if the variable is False.
22096
22097 Note that one might think that it would be good enough to have one Boolean
22098 variable for each package, but that would not deal with cases of trying
22099 to call a body in the same package as the call
22100 that has not been elaborated yet.
22101 Of course a compiler may be able to do enough analysis to optimize away
22102 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
22103 does such optimizations, but still the easiest conceptual model is to
22104 think of there being one variable per subprogram.
22105
22106 @node Controlling the Elaboration Order in Ada 95
22107 @section Controlling the Elaboration Order in Ada 95
22108
22109 @noindent
22110 In the previous section we discussed the rules in Ada 95 which ensure
22111 that @code{Program_Error} is raised if an incorrect elaboration order is
22112 chosen. This prevents erroneous executions, but we need mechanisms to
22113 specify a correct execution and avoid the exception altogether.
22114 To achieve this, Ada 95 provides a number of features for controlling
22115 the order of elaboration. We discuss these features in this section.
22116
22117 First, there are several ways of indicating to the compiler that a given
22118 unit has no elaboration problems:
22119
22120 @table @asis
22121 @item packages that do not require a body
22122 In Ada 95, a library package that does not require a body does not permit
22123 a body. This means that if we have a such a package, as in:
22124
22125 @smallexample @c ada
22126 @group
22127 @cartouche
22128 package Definitions is
22129    generic
22130       type m is new integer;
22131    package Subp is
22132       type a is array (1 .. 10) of m;
22133       type b is array (1 .. 20) of m;
22134    end Subp;
22135 end Definitions;
22136 @end cartouche
22137 @end group
22138 @end smallexample
22139
22140 @noindent
22141 A package that @code{with}'s @code{Definitions} may safely instantiate
22142 @code{Definitions.Subp} because the compiler can determine that there
22143 definitely is no package body to worry about in this case
22144
22145 @item pragma Pure
22146 @cindex pragma Pure
22147 @findex Pure
22148 Places sufficient restrictions on a unit to guarantee that
22149 no call to any subprogram in the unit can result in an
22150 elaboration problem. This means that the compiler does not need
22151 to worry about the point of elaboration of such units, and in
22152 particular, does not need to check any calls to any subprograms
22153 in this unit.
22154
22155 @item pragma Preelaborate
22156 @findex Preelaborate
22157 @cindex pragma Preelaborate
22158 This pragma places slightly less stringent restrictions on a unit than
22159 does pragma Pure,
22160 but these restrictions are still sufficient to ensure that there
22161 are no elaboration problems with any calls to the unit.
22162
22163 @item pragma Elaborate_Body
22164 @findex Elaborate_Body
22165 @cindex pragma Elaborate_Body
22166 This pragma requires that the body of a unit be elaborated immediately
22167 after its spec. Suppose a unit @code{A} has such a pragma,
22168 and unit @code{B} does
22169 a @code{with} of unit @code{A}. Recall that the standard rules require
22170 the spec of unit @code{A}
22171 to be elaborated before the @code{with}'ing unit; given the pragma in
22172 @code{A}, we also know that the body of @code{A}
22173 will be elaborated before @code{B}, so
22174 that calls to @code{A} are safe and do not need a check.
22175 @end table
22176
22177 @noindent
22178 Note that,
22179 unlike pragma @code{Pure} and pragma @code{Preelaborate},
22180 the use of
22181 @code{Elaborate_Body} does not guarantee that the program is
22182 free of elaboration problems, because it may not be possible
22183 to satisfy the requested elaboration order.
22184 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
22185 If a programmer
22186 marks @code{Unit_1} as @code{Elaborate_Body},
22187 and not @code{Unit_2,} then the order of
22188 elaboration will be:
22189
22190 @smallexample
22191 @group
22192 Spec of Unit_2
22193 Spec of Unit_1
22194 Body of Unit_1
22195 Body of Unit_2
22196 @end group
22197 @end smallexample
22198
22199 @noindent
22200 Now that means that the call to @code{Func_1} in @code{Unit_2}
22201 need not be checked,
22202 it must be safe. But the call to @code{Func_2} in
22203 @code{Unit_1} may still fail if
22204 @code{Expression_1} is equal to 1,
22205 and the programmer must still take
22206 responsibility for this not being the case.
22207
22208 If all units carry a pragma @code{Elaborate_Body}, then all problems are
22209 eliminated, except for calls entirely within a body, which are
22210 in any case fully under programmer control. However, using the pragma
22211 everywhere is not always possible.
22212 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
22213 we marked both of them as having pragma @code{Elaborate_Body}, then
22214 clearly there would be no possible elaboration order.
22215
22216 The above pragmas allow a server to guarantee safe use by clients, and
22217 clearly this is the preferable approach. Consequently a good rule in
22218 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
22219 and if this is not possible,
22220 mark them as @code{Elaborate_Body} if possible.
22221 As we have seen, there are situations where neither of these
22222 three pragmas can be used.
22223 So we also provide methods for clients to control the
22224 order of elaboration of the servers on which they depend:
22225
22226 @table @asis
22227 @item pragma Elaborate (unit)
22228 @findex Elaborate
22229 @cindex pragma Elaborate
22230 This pragma is placed in the context clause, after a @code{with} clause,
22231 and it requires that the body of the named unit be elaborated before
22232 the unit in which the pragma occurs. The idea is to use this pragma
22233 if the current unit calls at elaboration time, directly or indirectly,
22234 some subprogram in the named unit.
22235
22236 @item pragma Elaborate_All (unit)
22237 @findex Elaborate_All
22238 @cindex pragma Elaborate_All
22239 This is a stronger version of the Elaborate pragma. Consider the
22240 following example:
22241
22242 @smallexample
22243 Unit A @code{with}'s unit B and calls B.Func in elab code
22244 Unit B @code{with}'s unit C, and B.Func calls C.Func
22245 @end smallexample
22246
22247 @noindent
22248 Now if we put a pragma @code{Elaborate (B)}
22249 in unit @code{A}, this ensures that the
22250 body of @code{B} is elaborated before the call, but not the
22251 body of @code{C}, so
22252 the call to @code{C.Func} could still cause @code{Program_Error} to
22253 be raised.
22254
22255 The effect of a pragma @code{Elaborate_All} is stronger, it requires
22256 not only that the body of the named unit be elaborated before the
22257 unit doing the @code{with}, but also the bodies of all units that the
22258 named unit uses, following @code{with} links transitively. For example,
22259 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
22260 then it requires
22261 not only that the body of @code{B} be elaborated before @code{A},
22262 but also the
22263 body of @code{C}, because @code{B} @code{with}'s @code{C}.
22264 @end table
22265
22266 @noindent
22267 We are now in a position to give a usage rule in Ada 95 for avoiding
22268 elaboration problems, at least if dynamic dispatching and access to
22269 subprogram values are not used. We will handle these cases separately
22270 later.
22271
22272 The rule is simple. If a unit has elaboration code that can directly or
22273 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
22274 a generic unit in a @code{with}'ed unit,
22275 then if the @code{with}'ed unit does not have
22276 pragma @code{Pure} or @code{Preelaborate}, then the client should have
22277 a pragma @code{Elaborate_All}
22278 for the @code{with}'ed unit. By following this rule a client is
22279 assured that calls can be made without risk of an exception.
22280 If this rule is not followed, then a program may be in one of four
22281 states:
22282
22283 @table @asis
22284 @item No order exists
22285 No order of elaboration exists which follows the rules, taking into
22286 account any @code{Elaborate}, @code{Elaborate_All},
22287 or @code{Elaborate_Body} pragmas. In
22288 this case, an Ada 95 compiler must diagnose the situation at bind
22289 time, and refuse to build an executable program.
22290
22291 @item One or more orders exist, all incorrect
22292 One or more acceptable elaboration orders exists, and all of them
22293 generate an elaboration order problem. In this case, the binder
22294 can build an executable program, but @code{Program_Error} will be raised
22295 when the program is run.
22296
22297 @item Several orders exist, some right, some incorrect
22298 One or more acceptable elaboration orders exists, and some of them
22299 work, and some do not. The programmer has not controlled
22300 the order of elaboration, so the binder may or may not pick one of
22301 the correct orders, and the program may or may not raise an
22302 exception when it is run. This is the worst case, because it means
22303 that the program may fail when moved to another compiler, or even
22304 another version of the same compiler.
22305
22306 @item One or more orders exists, all correct
22307 One ore more acceptable elaboration orders exist, and all of them
22308 work. In this case the program runs successfully. This state of
22309 affairs can be guaranteed by following the rule we gave above, but
22310 may be true even if the rule is not followed.
22311 @end table
22312
22313 @noindent
22314 Note that one additional advantage of following our Elaborate_All rule
22315 is that the program continues to stay in the ideal (all orders OK) state
22316 even if maintenance
22317 changes some bodies of some subprograms. Conversely, if a program that does
22318 not follow this rule happens to be safe at some point, this state of affairs
22319 may deteriorate silently as a result of maintenance changes.
22320
22321 You may have noticed that the above discussion did not mention
22322 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
22323 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
22324 code in the body makes calls to some other unit, so it is still necessary
22325 to use @code{Elaborate_All} on such units.
22326
22327 @node Controlling Elaboration in GNAT - Internal Calls
22328 @section Controlling Elaboration in GNAT - Internal Calls
22329
22330 @noindent
22331 In the case of internal calls, i.e. calls within a single package, the
22332 programmer has full control over the order of elaboration, and it is up
22333 to the programmer to elaborate declarations in an appropriate order. For
22334 example writing:
22335
22336 @smallexample @c ada
22337 @group
22338 @cartouche
22339 function One return Float;
22340
22341 Q : Float := One;
22342
22343 function One return Float is
22344 begin
22345      return 1.0;
22346 end One;
22347 @end cartouche
22348 @end group
22349 @end smallexample
22350
22351 @noindent
22352 will obviously raise @code{Program_Error} at run time, because function
22353 One will be called before its body is elaborated. In this case GNAT will
22354 generate a warning that the call will raise @code{Program_Error}:
22355
22356 @smallexample
22357 @group
22358 @cartouche
22359  1. procedure y is
22360  2.    function One return Float;
22361  3.
22362  4.    Q : Float := One;
22363                     |
22364     >>> warning: cannot call "One" before body is elaborated
22365     >>> warning: Program_Error will be raised at run time
22366
22367  5.
22368  6.    function One return Float is
22369  7.    begin
22370  8.         return 1.0;
22371  9.    end One;
22372 10.
22373 11. begin
22374 12.    null;
22375 13. end;
22376 @end cartouche
22377 @end group
22378 @end smallexample
22379
22380 @noindent
22381 Note that in this particular case, it is likely that the call is safe, because
22382 the function @code{One} does not access any global variables.
22383 Nevertheless in Ada 95, we do not want the validity of the check to depend on
22384 the contents of the body (think about the separate compilation case), so this
22385 is still wrong, as we discussed in the previous sections.
22386
22387 The error is easily corrected by rearranging the declarations so that the
22388 body of One appears before the declaration containing the call
22389 (note that in Ada 95,
22390 declarations can appear in any order, so there is no restriction that
22391 would prevent this reordering, and if we write:
22392
22393 @smallexample @c ada
22394 @group
22395 @cartouche
22396 function One return Float;
22397
22398 function One return Float is
22399 begin
22400      return 1.0;
22401 end One;
22402
22403 Q : Float := One;
22404 @end cartouche
22405 @end group
22406 @end smallexample
22407
22408 @noindent
22409 then all is well, no warning is generated, and no
22410 @code{Program_Error} exception
22411 will be raised.
22412 Things are more complicated when a chain of subprograms is executed:
22413
22414 @smallexample @c ada
22415 @group
22416 @cartouche
22417 function A return Integer;
22418 function B return Integer;
22419 function C return Integer;
22420
22421 function B return Integer is begin return A; end;
22422 function C return Integer is begin return B; end;
22423
22424 X : Integer := C;
22425
22426 function A return Integer is begin return 1; end;
22427 @end cartouche
22428 @end group
22429 @end smallexample
22430
22431 @noindent
22432 Now the call to @code{C}
22433 at elaboration time in the declaration of @code{X} is correct, because
22434 the body of @code{C} is already elaborated,
22435 and the call to @code{B} within the body of
22436 @code{C} is correct, but the call
22437 to @code{A} within the body of @code{B} is incorrect, because the body
22438 of @code{A} has not been elaborated, so @code{Program_Error}
22439 will be raised on the call to @code{A}.
22440 In this case GNAT will generate a
22441 warning that @code{Program_Error} may be
22442 raised at the point of the call. Let's look at the warning:
22443
22444 @smallexample
22445 @group
22446 @cartouche
22447  1. procedure x is
22448  2.    function A return Integer;
22449  3.    function B return Integer;
22450  4.    function C return Integer;
22451  5.
22452  6.    function B return Integer is begin return A; end;
22453                                                     |
22454     >>> warning: call to "A" before body is elaborated may
22455                  raise Program_Error
22456     >>> warning: "B" called at line 7
22457     >>> warning: "C" called at line 9
22458
22459  7.    function C return Integer is begin return B; end;
22460  8.
22461  9.    X : Integer := C;
22462 10.
22463 11.    function A return Integer is begin return 1; end;
22464 12.
22465 13. begin
22466 14.    null;
22467 15. end;
22468 @end cartouche
22469 @end group
22470 @end smallexample
22471
22472 @noindent
22473 Note that the message here says ``may raise'', instead of the direct case,
22474 where the message says ``will be raised''. That's because whether
22475 @code{A} is
22476 actually called depends in general on run-time flow of control.
22477 For example, if the body of @code{B} said
22478
22479 @smallexample @c ada
22480 @group
22481 @cartouche
22482 function B return Integer is
22483 begin
22484    if some-condition-depending-on-input-data then
22485       return A;
22486    else
22487       return 1;
22488    end if;
22489 end B;
22490 @end cartouche
22491 @end group
22492 @end smallexample
22493
22494 @noindent
22495 then we could not know until run time whether the incorrect call to A would
22496 actually occur, so @code{Program_Error} might
22497 or might not be raised. It is possible for a compiler to
22498 do a better job of analyzing bodies, to
22499 determine whether or not @code{Program_Error}
22500 might be raised, but it certainly
22501 couldn't do a perfect job (that would require solving the halting problem
22502 and is provably impossible), and because this is a warning anyway, it does
22503 not seem worth the effort to do the analysis. Cases in which it
22504 would be relevant are rare.
22505
22506 In practice, warnings of either of the forms given
22507 above will usually correspond to
22508 real errors, and should be examined carefully and eliminated.
22509 In the rare case where a warning is bogus, it can be suppressed by any of
22510 the following methods:
22511
22512 @itemize @bullet
22513 @item
22514 Compile with the @option{-gnatws} switch set
22515
22516 @item
22517 Suppress @code{Elaboration_Check} for the called subprogram
22518
22519 @item
22520 Use pragma @code{Warnings_Off} to turn warnings off for the call
22521 @end itemize
22522
22523 @noindent
22524 For the internal elaboration check case,
22525 GNAT by default generates the
22526 necessary run-time checks to ensure
22527 that @code{Program_Error} is raised if any
22528 call fails an elaboration check. Of course this can only happen if a
22529 warning has been issued as described above. The use of pragma
22530 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
22531 some of these checks, meaning that it may be possible (but is not
22532 guaranteed) for a program to be able to call a subprogram whose body
22533 is not yet elaborated, without raising a @code{Program_Error} exception.
22534
22535 @node Controlling Elaboration in GNAT - External Calls
22536 @section Controlling Elaboration in GNAT - External Calls
22537
22538 @noindent
22539 The previous section discussed the case in which the execution of a
22540 particular thread of elaboration code occurred entirely within a
22541 single unit. This is the easy case to handle, because a programmer
22542 has direct and total control over the order of elaboration, and
22543 furthermore, checks need only be generated in cases which are rare
22544 and which the compiler can easily detect.
22545 The situation is more complex when separate compilation is taken into account.
22546 Consider the following:
22547
22548 @smallexample @c ada
22549 @cartouche
22550 @group
22551 package Math is
22552    function Sqrt (Arg : Float) return Float;
22553 end Math;
22554
22555 package body Math is
22556    function Sqrt (Arg : Float) return Float is
22557    begin
22558          ...
22559    end Sqrt;
22560 end Math;
22561 @end group
22562 @group
22563 with Math;
22564 package Stuff is
22565    X : Float := Math.Sqrt (0.5);
22566 end Stuff;
22567
22568 with Stuff;
22569 procedure Main is
22570 begin
22571    ...
22572 end Main;
22573 @end group
22574 @end cartouche
22575 @end smallexample
22576
22577 @noindent
22578 where @code{Main} is the main program. When this program is executed, the
22579 elaboration code must first be executed, and one of the jobs of the
22580 binder is to determine the order in which the units of a program are
22581 to be elaborated. In this case we have four units: the spec and body
22582 of @code{Math},
22583 the spec of @code{Stuff} and the body of @code{Main}).
22584 In what order should the four separate sections of elaboration code
22585 be executed?
22586
22587 There are some restrictions in the order of elaboration that the binder
22588 can choose. In particular, if unit U has a @code{with}
22589 for a package @code{X}, then you
22590 are assured that the spec of @code{X}
22591 is elaborated before U , but you are
22592 not assured that the body of @code{X}
22593 is elaborated before U.
22594 This means that in the above case, the binder is allowed to choose the
22595 order:
22596
22597 @smallexample
22598 spec of Math
22599 spec of Stuff
22600 body of Math
22601 body of Main
22602 @end smallexample
22603
22604 @noindent
22605 but that's not good, because now the call to @code{Math.Sqrt}
22606 that happens during
22607 the elaboration of the @code{Stuff}
22608 spec happens before the body of @code{Math.Sqrt} is
22609 elaborated, and hence causes @code{Program_Error} exception to be raised.
22610 At first glance, one might say that the binder is misbehaving, because
22611 obviously you want to elaborate the body of something you @code{with}
22612 first, but
22613 that is not a general rule that can be followed in all cases. Consider
22614
22615 @smallexample @c ada
22616 @group
22617 @cartouche
22618 package X is ...
22619
22620 package Y is ...
22621
22622 with X;
22623 package body Y is ...
22624
22625 with Y;
22626 package body X is ...
22627 @end cartouche
22628 @end group
22629 @end smallexample
22630
22631 @noindent
22632 This is a common arrangement, and, apart from the order of elaboration
22633 problems that might arise in connection with elaboration code, this works fine.
22634 A rule that says that you must first elaborate the body of anything you
22635 @code{with} cannot work in this case:
22636 the body of @code{X} @code{with}'s @code{Y},
22637 which means you would have to
22638 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
22639 which means
22640 you have to elaborate the body of @code{X} first, but ... and we have a
22641 loop that cannot be broken.
22642
22643 It is true that the binder can in many cases guess an order of elaboration
22644 that is unlikely to cause a @code{Program_Error}
22645 exception to be raised, and it tries to do so (in the
22646 above example of @code{Math/Stuff/Spec}, the GNAT binder will
22647 by default
22648 elaborate the body of @code{Math} right after its spec, so all will be well).
22649
22650 However, a program that blindly relies on the binder to be helpful can
22651 get into trouble, as we discussed in the previous sections, so
22652 GNAT
22653 provides a number of facilities for assisting the programmer in
22654 developing programs that are robust with respect to elaboration order.
22655
22656 @node Default Behavior in GNAT - Ensuring Safety
22657 @section Default Behavior in GNAT - Ensuring Safety
22658
22659 @noindent
22660 The default behavior in GNAT ensures elaboration safety. In its
22661 default mode GNAT implements the
22662 rule we previously described as the right approach. Let's restate it:
22663
22664 @itemize
22665 @item
22666 @emph{If a unit has elaboration code that can directly or indirectly make a
22667 call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit
22668 in a @code{with}'ed unit, then if the @code{with}'ed unit
22669 does not have pragma @code{Pure} or
22670 @code{Preelaborate}, then the client should have an
22671 @code{Elaborate_All} for the @code{with}'ed unit.}
22672 @end itemize
22673
22674 @noindent
22675 By following this rule a client is assured that calls and instantiations
22676 can be made without risk of an exception.
22677
22678 In this mode GNAT traces all calls that are potentially made from
22679 elaboration code, and puts in any missing implicit @code{Elaborate_All}
22680 pragmas.
22681 The advantage of this approach is that no elaboration problems
22682 are possible if the binder can find an elaboration order that is
22683 consistent with these implicit @code{Elaborate_All} pragmas. The
22684 disadvantage of this approach is that no such order may exist.
22685
22686 If the binder does not generate any diagnostics, then it means that it
22687 has found an elaboration order that is guaranteed to be safe. However,
22688 the binder may still be relying on implicitly generated
22689 @code{Elaborate_All} pragmas so portability to other compilers than
22690 GNAT is not guaranteed.
22691
22692 If it is important to guarantee portability, then the compilations should
22693 use the
22694 @option{-gnatwl}
22695 (warn on elaboration problems) switch. This will cause warning messages
22696 to be generated indicating the missing @code{Elaborate_All} pragmas.
22697 Consider the following source program:
22698
22699 @smallexample @c ada
22700 @group
22701 @cartouche
22702 with k;
22703 package j is
22704   m : integer := k.r;
22705 end;
22706 @end cartouche
22707 @end group
22708 @end smallexample
22709
22710 @noindent
22711 where it is clear that there
22712 should be a pragma @code{Elaborate_All}
22713 for unit @code{k}. An implicit pragma will be generated, and it is
22714 likely that the binder will be able to honor it. However, if you want
22715 to port this program to some other Ada compiler than GNAT.
22716 it is safer to include the pragma explicitly in the source. If this
22717 unit is compiled with the
22718 @option{-gnatwl}
22719 switch, then the compiler outputs a warning:
22720
22721 @smallexample
22722 @group
22723 @cartouche
22724 1. with k;
22725 2. package j is
22726 3.   m : integer := k.r;
22727                      |
22728    >>> warning: call to "r" may raise Program_Error
22729    >>> warning: missing pragma Elaborate_All for "k"
22730
22731 4. end;
22732 @end cartouche
22733 @end group
22734 @end smallexample
22735
22736 @noindent
22737 and these warnings can be used as a guide for supplying manually
22738 the missing pragmas. It is usually a bad idea to use this warning
22739 option during development. That's because it will warn you when
22740 you need to put in a pragma, but cannot warn you when it is time
22741 to take it out. So the use of pragma Elaborate_All may lead to
22742 unnecessary dependencies and even false circularities.
22743
22744 This default mode is more restrictive than the Ada Reference
22745 Manual, and it is possible to construct programs which will compile
22746 using the dynamic model described there, but will run into a
22747 circularity using the safer static model we have described.
22748
22749 Of course any Ada compiler must be able to operate in a mode
22750 consistent with the requirements of the Ada Reference Manual,
22751 and in particular must have the capability of implementing the
22752 standard dynamic model of elaboration with run-time checks.
22753
22754 In GNAT, this standard mode can be achieved either by the use of
22755 the @option{-gnatE} switch on the compiler (@code{gcc} or @code{gnatmake})
22756 command, or by the use of the configuration pragma:
22757
22758 @smallexample @c ada
22759 pragma Elaboration_Checks (RM);
22760 @end smallexample
22761
22762 @noindent
22763 Either approach will cause the unit affected to be compiled using the
22764 standard dynamic run-time elaboration checks described in the Ada
22765 Reference Manual. The static model is generally preferable, since it
22766 is clearly safer to rely on compile and link time checks rather than
22767 run-time checks. However, in the case of legacy code, it may be
22768 difficult to meet the requirements of the static model. This
22769 issue is further discussed in
22770 @ref{What to Do If the Default Elaboration Behavior Fails}.
22771
22772 Note that the static model provides a strict subset of the allowed
22773 behavior and programs of the Ada Reference Manual, so if you do
22774 adhere to the static model and no circularities exist,
22775 then you are assured that your program will
22776 work using the dynamic model, providing that you remove any
22777 pragma Elaborate statements from the source.
22778
22779 @node Treatment of Pragma Elaborate
22780 @section Treatment of Pragma Elaborate
22781 @cindex Pragma Elaborate
22782
22783 @noindent
22784 The use of @code{pragma Elaborate}
22785 should generally be avoided in Ada 95 programs.
22786 The reason for this is that there is no guarantee that transitive calls
22787 will be properly handled. Indeed at one point, this pragma was placed
22788 in Annex J (Obsolescent Features), on the grounds that it is never useful.
22789
22790 Now that's a bit restrictive. In practice, the case in which
22791 @code{pragma Elaborate} is useful is when the caller knows that there
22792 are no transitive calls, or that the called unit contains all necessary
22793 transitive @code{pragma Elaborate} statements, and legacy code often
22794 contains such uses.
22795
22796 Strictly speaking the static mode in GNAT should ignore such pragmas,
22797 since there is no assurance at compile time that the necessary safety
22798 conditions are met. In practice, this would cause GNAT to be incompatible
22799 with correctly written Ada 83 code that had all necessary
22800 @code{pragma Elaborate} statements in place. Consequently, we made the
22801 decision that GNAT in its default mode will believe that if it encounters
22802 a @code{pragma Elaborate} then the programmer knows what they are doing,
22803 and it will trust that no elaboration errors can occur.
22804
22805 The result of this decision is two-fold. First to be safe using the
22806 static mode, you should remove all @code{pragma Elaborate} statements.
22807 Second, when fixing circularities in existing code, you can selectively
22808 use @code{pragma Elaborate} statements to convince the static mode of
22809 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
22810 statement.
22811
22812 When using the static mode with @option{-gnatwl}, any use of
22813 @code{pragma Elaborate} will generate a warning about possible
22814 problems.
22815
22816 @node Elaboration Issues for Library Tasks
22817 @section Elaboration Issues for Library Tasks
22818 @cindex Library tasks, elaboration issues
22819 @cindex Elaboration of library tasks
22820
22821 @noindent
22822 In this section we examine special elaboration issues that arise for
22823 programs that declare library level tasks.
22824
22825 Generally the model of execution of an Ada program is that all units are
22826 elaborated, and then execution of the program starts. However, the
22827 declaration of library tasks definitely does not fit this model. The
22828 reason for this is that library tasks start as soon as they are declared
22829 (more precisely, as soon as the statement part of the enclosing package
22830 body is reached), that is to say before elaboration
22831 of the program is complete. This means that if such a task calls a
22832 subprogram, or an entry in another task, the callee may or may not be
22833 elaborated yet, and in the standard
22834 Reference Manual model of dynamic elaboration checks, you can even
22835 get timing dependent Program_Error exceptions, since there can be
22836 a race between the elaboration code and the task code.
22837
22838 The static model of elaboration in GNAT seeks to avoid all such
22839 dynamic behavior, by being conservative, and the conservative
22840 approach in this particular case is to assume that all the code
22841 in a task body is potentially executed at elaboration time if
22842 a task is declared at the library level.
22843
22844 This can definitely result in unexpected circularities. Consider
22845 the following example
22846
22847 @smallexample @c ada
22848 package Decls is
22849   task Lib_Task is
22850      entry Start;
22851   end Lib_Task;
22852
22853   type My_Int is new Integer;
22854
22855   function Ident (M : My_Int) return My_Int;
22856 end Decls;
22857
22858 with Utils;
22859 package body Decls is
22860   task body Lib_Task is
22861   begin
22862      accept Start;
22863      Utils.Put_Val (2);
22864   end Lib_Task;
22865
22866   function Ident (M : My_Int) return My_Int is
22867   begin
22868      return M;
22869   end Ident;
22870 end Decls;
22871
22872 with Decls;
22873 package Utils is
22874   procedure Put_Val (Arg : Decls.My_Int);
22875 end Utils;
22876
22877 with Text_IO;
22878 package body Utils is
22879   procedure Put_Val (Arg : Decls.My_Int) is
22880   begin
22881      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
22882   end Put_Val;
22883 end Utils;
22884
22885 with Decls;
22886 procedure Main is
22887 begin
22888    Decls.Lib_Task.Start;
22889 end;
22890 @end smallexample
22891
22892 @noindent
22893 If the above example is compiled in the default static elaboration
22894 mode, then a circularity occurs. The circularity comes from the call
22895 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
22896 this call occurs in elaboration code, we need an implicit pragma
22897 @code{Elaborate_All} for @code{Utils}. This means that not only must
22898 the spec and body of @code{Utils} be elaborated before the body
22899 of @code{Decls}, but also the spec and body of any unit that is
22900 @code{with'ed} by the body of @code{Utils} must also be elaborated before
22901 the body of @code{Decls}. This is the transitive implication of
22902 pragma @code{Elaborate_All} and it makes sense, because in general
22903 the body of @code{Put_Val} might have a call to something in a
22904 @code{with'ed} unit.
22905
22906 In this case, the body of Utils (actually its spec) @code{with's}
22907 @code{Decls}. Unfortunately this means that the body of @code{Decls}
22908 must be elaborated before itself, in case there is a call from the
22909 body of @code{Utils}.
22910
22911 Here is the exact chain of events we are worrying about:
22912
22913 @enumerate
22914 @item
22915 In the body of @code{Decls} a call is made from within the body of a library
22916 task to a subprogram in the package @code{Utils}. Since this call may
22917 occur at elaboration time (given that the task is activated at elaboration
22918 time), we have to assume the worst, i.e. that the
22919 call does happen at elaboration time.
22920
22921 @item
22922 This means that the body and spec of @code{Util} must be elaborated before
22923 the body of @code{Decls} so that this call does not cause an access before
22924 elaboration.
22925
22926 @item
22927 Within the body of @code{Util}, specifically within the body of
22928 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
22929 by this package.
22930
22931 @item
22932 One such @code{with}'ed package is package @code{Decls}, so there
22933 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
22934 In fact there is such a call in this example, but we would have to
22935 assume that there was such a call even if it were not there, since
22936 we are not supposed to write the body of @code{Decls} knowing what
22937 is in the body of @code{Utils}; certainly in the case of the
22938 static elaboration model, the compiler does not know what is in
22939 other bodies and must assume the worst.
22940
22941 @item
22942 This means that the spec and body of @code{Decls} must also be
22943 elaborated before we elaborate the unit containing the call, but
22944 that unit is @code{Decls}! This means that the body of @code{Decls}
22945 must be elaborated before itself, and that's a circularity.
22946 @end enumerate
22947
22948 @noindent
22949 Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in
22950 the body of @code{Decls} you will get a true Ada Reference Manual
22951 circularity that makes the program illegal.
22952
22953 In practice, we have found that problems with the static model of
22954 elaboration in existing code often arise from library tasks, so
22955 we must address this particular situation.
22956
22957 Note that if we compile and run the program above, using the dynamic model of
22958 elaboration (that is to say use the @option{-gnatE} switch),
22959 then it compiles, binds,
22960 links, and runs, printing the expected result of 2. Therefore in some sense
22961 the circularity here is only apparent, and we need to capture
22962 the properties of this program that  distinguish it from other library-level
22963 tasks that have real elaboration problems.
22964
22965 We have four possible answers to this question:
22966
22967 @itemize @bullet
22968
22969 @item
22970 Use the dynamic model of elaboration.
22971
22972 If we use the @option{-gnatE} switch, then as noted above, the program works.
22973 Why is this? If we examine the task body, it is apparent that the task cannot
22974 proceed past the
22975 @code{accept} statement until after elaboration has been completed, because
22976 the corresponding entry call comes from the main program, not earlier.
22977 This is why the dynamic model works here. But that's really giving
22978 up on a precise analysis, and we prefer to take this approach only if we cannot
22979 solve the
22980 problem in any other manner. So let us examine two ways to reorganize
22981 the program to avoid the potential elaboration problem.
22982
22983 @item
22984 Split library tasks into separate packages.
22985
22986 Write separate packages, so that library tasks are isolated from
22987 other declarations as much as possible. Let us look at a variation on
22988 the above program.
22989
22990 @smallexample @c ada
22991 package Decls1 is
22992   task Lib_Task is
22993      entry Start;
22994   end Lib_Task;
22995 end Decls1;
22996
22997 with Utils;
22998 package body Decls1 is
22999   task body Lib_Task is
23000   begin
23001      accept Start;
23002      Utils.Put_Val (2);
23003   end Lib_Task;
23004 end Decls1;
23005
23006 package Decls2 is
23007   type My_Int is new Integer;
23008   function Ident (M : My_Int) return My_Int;
23009 end Decls2;
23010
23011 with Utils;
23012 package body Decls2 is
23013   function Ident (M : My_Int) return My_Int is
23014   begin
23015      return M;
23016   end Ident;
23017 end Decls2;
23018
23019 with Decls2;
23020 package Utils is
23021   procedure Put_Val (Arg : Decls2.My_Int);
23022 end Utils;
23023
23024 with Text_IO;
23025 package body Utils is
23026   procedure Put_Val (Arg : Decls2.My_Int) is
23027   begin
23028      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
23029   end Put_Val;
23030 end Utils;
23031
23032 with Decls1;
23033 procedure Main is
23034 begin
23035    Decls1.Lib_Task.Start;
23036 end;
23037 @end smallexample
23038
23039 @noindent
23040 All we have done is to split @code{Decls} into two packages, one
23041 containing the library task, and one containing everything else. Now
23042 there is no cycle, and the program compiles, binds, links and executes
23043 using the default static model of elaboration.
23044
23045 @item
23046 Declare separate task types.
23047
23048 A significant part of the problem arises because of the use of the
23049 single task declaration form. This means that the elaboration of
23050 the task type, and the elaboration of the task itself (i.e. the
23051 creation of the task) happen at the same time. A good rule
23052 of style in Ada 95 is to always create explicit task types. By
23053 following the additional step of placing task objects in separate
23054 packages from the task type declaration, many elaboration problems
23055 are avoided. Here is another modified example of the example program:
23056
23057 @smallexample @c ada
23058 package Decls is
23059   task type Lib_Task_Type is
23060      entry Start;
23061   end Lib_Task_Type;
23062
23063   type My_Int is new Integer;
23064
23065   function Ident (M : My_Int) return My_Int;
23066 end Decls;
23067
23068 with Utils;
23069 package body Decls is
23070   task body Lib_Task_Type is
23071   begin
23072      accept Start;
23073      Utils.Put_Val (2);
23074   end Lib_Task_Type;
23075
23076   function Ident (M : My_Int) return My_Int is
23077   begin
23078      return M;
23079   end Ident;
23080 end Decls;
23081
23082 with Decls;
23083 package Utils is
23084   procedure Put_Val (Arg : Decls.My_Int);
23085 end Utils;
23086
23087 with Text_IO;
23088 package body Utils is
23089   procedure Put_Val (Arg : Decls.My_Int) is
23090   begin
23091      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23092   end Put_Val;
23093 end Utils;
23094
23095 with Decls;
23096 package Declst is
23097    Lib_Task : Decls.Lib_Task_Type;
23098 end Declst;
23099
23100 with Declst;
23101 procedure Main is
23102 begin
23103    Declst.Lib_Task.Start;
23104 end;
23105 @end smallexample
23106
23107 @noindent
23108 What we have done here is to replace the @code{task} declaration in
23109 package @code{Decls} with a @code{task type} declaration. Then we
23110 introduce a separate package @code{Declst} to contain the actual
23111 task object. This separates the elaboration issues for
23112 the @code{task type}
23113 declaration, which causes no trouble, from the elaboration issues
23114 of the task object, which is also unproblematic, since it is now independent
23115 of the elaboration of  @code{Utils}.
23116 This separation of concerns also corresponds to
23117 a generally sound engineering principle of separating declarations
23118 from instances. This version of the program also compiles, binds, links,
23119 and executes, generating the expected output.
23120
23121 @item
23122 Use No_Entry_Calls_In_Elaboration_Code restriction.
23123 @cindex No_Entry_Calls_In_Elaboration_Code
23124
23125 The previous two approaches described how a program can be restructured
23126 to avoid the special problems caused by library task bodies. in practice,
23127 however, such restructuring may be difficult to apply to existing legacy code,
23128 so we must consider solutions that do not require massive rewriting.
23129
23130 Let us consider more carefully why our original sample program works
23131 under the dynamic model of elaboration. The reason is that the code
23132 in the task body blocks immediately on the @code{accept}
23133 statement. Now of course there is nothing to prohibit elaboration
23134 code from making entry calls (for example from another library level task),
23135 so we cannot tell in isolation that
23136 the task will not execute the accept statement  during elaboration.
23137
23138 However, in practice it is very unusual to see elaboration code
23139 make any entry calls, and the pattern of tasks starting
23140 at elaboration time and then immediately blocking on @code{accept} or
23141 @code{select} statements is very common. What this means is that
23142 the compiler is being too pessimistic when it analyzes the
23143 whole package body as though it might be executed at elaboration
23144 time.
23145
23146 If we know that the elaboration code contains no entry calls, (a very safe
23147 assumption most of the time, that could almost be made the default
23148 behavior), then we can compile all units of the program under control
23149 of the following configuration pragma:
23150
23151 @smallexample
23152 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
23153 @end smallexample
23154
23155 @noindent
23156 This pragma can be placed in the @file{gnat.adc} file in the usual
23157 manner. If we take our original unmodified program and compile it
23158 in the presence of a @file{gnat.adc} containing the above pragma,
23159 then once again, we can compile, bind, link, and execute, obtaining
23160 the expected result. In the presence of this pragma, the compiler does
23161 not trace calls in a task body, that appear after the first @code{accept}
23162 or @code{select} statement, and therefore does not report a potential
23163 circularity in the original program.
23164
23165 The compiler will check to the extent it can that the above
23166 restriction is not violated, but it is not always possible to do a
23167 complete check at compile time, so it is important to use this
23168 pragma only if the stated restriction is in fact met, that is to say
23169 no task receives an entry call before elaboration of all units is completed.
23170
23171 @end itemize
23172
23173 @node Mixing Elaboration Models
23174 @section Mixing Elaboration Models
23175 @noindent
23176 So far, we have assumed that the entire program is either compiled
23177 using the dynamic model or static model, ensuring consistency. It
23178 is possible to mix the two models, but rules have to be followed
23179 if this mixing is done to ensure that elaboration checks are not
23180 omitted.
23181
23182 The basic rule is that @emph{a unit compiled with the static model cannot
23183 be @code{with'ed} by a unit compiled with the dynamic model}. The
23184 reason for this is that in the static model, a unit assumes that
23185 its clients guarantee to use (the equivalent of) pragma
23186 @code{Elaborate_All} so that no elaboration checks are required
23187 in inner subprograms, and this assumption is violated if the
23188 client is compiled with dynamic checks.
23189
23190 The precise rule is as follows. A unit that is compiled with dynamic
23191 checks can only @code{with} a unit that meets at least one of the
23192 following criteria:
23193
23194 @itemize @bullet
23195
23196 @item
23197 The @code{with'ed} unit is itself compiled with dynamic elaboration
23198 checks (that is with the @option{-gnatE} switch.
23199
23200 @item
23201 The @code{with'ed} unit is an internal GNAT implementation unit from
23202 the System, Interfaces, Ada, or GNAT hierarchies.
23203
23204 @item
23205 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
23206
23207 @item
23208 The @code{with'ing} unit (that is the client) has an explicit pragma
23209 @code{Elaborate_All} for the @code{with'ed} unit.
23210
23211 @end itemize
23212
23213 @noindent
23214 If this rule is violated, that is if a unit with dynamic elaboration
23215 checks @code{with's} a unit that does not meet one of the above four
23216 criteria, then the binder (@code{gnatbind}) will issue a warning
23217 similar to that in the following example:
23218
23219 @smallexample
23220 warning: "x.ads" has dynamic elaboration checks and with's
23221 warning:   "y.ads" which has static elaboration checks
23222 @end smallexample
23223
23224 @noindent
23225 These warnings indicate that the rule has been violated, and that as a result
23226 elaboration checks may be missed in the resulting executable file.
23227 This warning may be suppressed using the @option{-ws} binder switch
23228 in the usual manner.
23229
23230 One useful application of this mixing rule is in the case of a subsystem
23231 which does not itself @code{with} units from the remainder of the
23232 application. In this case, the entire subsystem can be compiled with
23233 dynamic checks to resolve a circularity in the subsystem, while
23234 allowing the main application that uses this subsystem to be compiled
23235 using the more reliable default static model.
23236
23237 @node What to Do If the Default Elaboration Behavior Fails
23238 @section What to Do If the Default Elaboration Behavior Fails
23239
23240 @noindent
23241 If the binder cannot find an acceptable order, it outputs detailed
23242 diagnostics. For example:
23243 @smallexample
23244 @group
23245 @iftex
23246 @leftskip=0cm
23247 @end iftex
23248 error: elaboration circularity detected
23249 info:   "proc (body)" must be elaborated before "pack (body)"
23250 info:     reason: Elaborate_All probably needed in unit "pack (body)"
23251 info:     recompile "pack (body)" with -gnatwl
23252 info:                             for full details
23253 info:       "proc (body)"
23254 info:         is needed by its spec:
23255 info:       "proc (spec)"
23256 info:         which is withed by:
23257 info:       "pack (body)"
23258 info:  "pack (body)" must be elaborated before "proc (body)"
23259 info:     reason: pragma Elaborate in unit "proc (body)"
23260 @end group
23261
23262 @end smallexample
23263
23264 @noindent
23265 In this case we have a cycle that the binder cannot break. On the one
23266 hand, there is an explicit pragma Elaborate in @code{proc} for
23267 @code{pack}. This means that the body of @code{pack} must be elaborated
23268 before the body of @code{proc}. On the other hand, there is elaboration
23269 code in @code{pack} that calls a subprogram in @code{proc}. This means
23270 that for maximum safety, there should really be a pragma
23271 Elaborate_All in @code{pack} for @code{proc} which would require that
23272 the body of @code{proc} be elaborated before the body of
23273 @code{pack}. Clearly both requirements cannot be satisfied.
23274 Faced with a circularity of this kind, you have three different options.
23275
23276 @table @asis
23277 @item Fix the program
23278 The most desirable option from the point of view of long-term maintenance
23279 is to rearrange the program so that the elaboration problems are avoided.
23280 One useful technique is to place the elaboration code into separate
23281 child packages. Another is to move some of the initialization code to
23282 explicitly called subprograms, where the program controls the order
23283 of initialization explicitly. Although this is the most desirable option,
23284 it may be impractical and involve too much modification, especially in
23285 the case of complex legacy code.
23286
23287 @item Perform dynamic checks
23288 If the compilations are done using the
23289 @option{-gnatE}
23290 (dynamic elaboration check) switch, then GNAT behaves in
23291 a quite different manner. Dynamic checks are generated for all calls
23292 that could possibly result in raising an exception. With this switch,
23293 the compiler does not generate implicit @code{Elaborate_All} pragmas.
23294 The behavior then is exactly as specified in the Ada 95 Reference Manual.
23295 The binder will generate an executable program that may or may not
23296 raise @code{Program_Error}, and then it is the programmer's job to ensure
23297 that it does not raise an exception. Note that it is important to
23298 compile all units with the switch, it cannot be used selectively.
23299
23300 @item Suppress checks
23301 The drawback of dynamic checks is that they generate a
23302 significant overhead at run time, both in space and time. If you
23303 are absolutely sure that your program cannot raise any elaboration
23304 exceptions, and you still want to use the dynamic elaboration model,
23305 then you can use the configuration pragma
23306 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
23307 example this pragma could be placed in the @file{gnat.adc} file.
23308
23309 @item Suppress checks selectively
23310 When you know that certain calls in elaboration code cannot possibly
23311 lead to an elaboration error, and the binder nevertheless generates warnings
23312 on those calls and inserts Elaborate_All pragmas that lead to elaboration
23313 circularities, it is possible to remove those warnings locally and obtain
23314 a program that will bind. Clearly this can be unsafe, and it is the
23315 responsibility of the programmer to make sure that the resulting program has
23316 no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can
23317 be used with different granularity to suppress warnings and break
23318 elaboration circularities:
23319
23320 @itemize @bullet
23321 @item
23322 Place the pragma that names the called subprogram in the declarative part
23323 that contains the call.
23324
23325 @item
23326 Place the pragma in the declarative part, without naming an entity. This
23327 disables warnings on all calls in the corresponding  declarative region.
23328
23329 @item
23330 Place the pragma in the package spec that declares the called subprogram,
23331 and name the subprogram. This disables warnings on all elaboration calls to
23332 that subprogram.
23333
23334 @item
23335 Place the pragma in the package spec that declares the called subprogram,
23336 without naming any entity. This disables warnings on all elaboration calls to
23337 all subprograms declared in this spec.
23338
23339 @item Use Pragma Elaborate
23340 As previously described in section @xref{Treatment of Pragma Elaborate},
23341 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
23342 that no elaboration checks are required on calls to the designated unit.
23343 There may be cases in which the caller knows that no transitive calls
23344 can occur, so that a @code{pragma Elaborate} will be sufficient in a
23345 case where @code{pragma Elaborate_All} would cause a circularity.
23346 @end itemize
23347
23348 @noindent
23349 These five cases are listed in order of decreasing safety, and therefore
23350 require increasing programmer care in their application. Consider the
23351 following program:
23352
23353 @smallexample @c adanocomment
23354 package Pack1 is
23355   function F1 return Integer;
23356   X1 : Integer;
23357 end Pack1;
23358
23359 package Pack2 is
23360   function F2 return Integer;
23361   function Pure (x : integer) return integer;
23362   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
23363   --  pragma Suppress (Elaboration_Check);              -- (4)
23364 end Pack2;
23365
23366 with Pack2;
23367 package body Pack1 is
23368   function F1 return Integer is
23369   begin
23370     return 100;
23371   end F1;
23372   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
23373 begin
23374   declare
23375     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
23376     --  pragma Suppress(Elaboration_Check);             -- (2)
23377   begin
23378     X1 := Pack2.F2 + 1;                --  Elab. call (2)
23379   end;
23380 end Pack1;
23381
23382 with Pack1;
23383 package body Pack2 is
23384   function F2 return Integer is
23385   begin
23386      return Pack1.F1;
23387   end F2;
23388   function Pure (x : integer) return integer is
23389   begin
23390      return x ** 3 - 3 * x;
23391   end;
23392 end Pack2;
23393
23394 with Pack1, Ada.Text_IO;
23395 procedure Proc3 is
23396 begin
23397   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
23398 end Proc3;
23399 @end smallexample
23400 In the absence of any pragmas, an attempt to bind this program produces
23401 the following diagnostics:
23402 @smallexample
23403 @group
23404 @iftex
23405 @leftskip=.5cm
23406 @end iftex
23407 error: elaboration circularity detected
23408 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
23409 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
23410 info:       recompile "pack1 (body)" with -gnatwl for full details
23411 info:          "pack1 (body)"
23412 info:             must be elaborated along with its spec:
23413 info:          "pack1 (spec)"
23414 info:             which is withed by:
23415 info:          "pack2 (body)"
23416 info:             which must be elaborated along with its spec:
23417 info:          "pack2 (spec)"
23418 info:             which is withed by:
23419 info:          "pack1 (body)"
23420 @end group
23421 @end smallexample
23422 The sources of the circularity are the two calls to @code{Pack2.Pure} and
23423 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
23424 F2 is safe, even though F2 calls F1, because the call appears after the
23425 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
23426 remove the warning on the call. It is also possible to use pragma (2)
23427 because there are no other potentially unsafe calls in the block.
23428
23429 @noindent
23430 The call to @code{Pure} is safe because this function does not depend on the
23431 state of @code{Pack2}. Therefore any call to this function is safe, and it
23432 is correct to place pragma (3) in the corresponding package spec.
23433
23434 @noindent
23435 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
23436 warnings on all calls to functions declared therein. Note that this is not
23437 necessarily safe, and requires more detailed examination of the subprogram
23438 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
23439 be already elaborated.
23440 @end table
23441
23442 @noindent
23443 It is hard to generalize on which of these four approaches should be
23444 taken. Obviously if it is possible to fix the program so that the default
23445 treatment works, this is preferable, but this may not always be practical.
23446 It is certainly simple enough to use
23447 @option{-gnatE}
23448 but the danger in this case is that, even if the GNAT binder
23449 finds a correct elaboration order, it may not always do so,
23450 and certainly a binder from another Ada compiler might not. A
23451 combination of testing and analysis (for which the warnings generated
23452 with the
23453 @option{-gnatwl}
23454 switch can be useful) must be used to ensure that the program is free
23455 of errors. One switch that is useful in this testing is the
23456 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
23457 switch for
23458 @code{gnatbind}.
23459 Normally the binder tries to find an order that has the best chance of
23460 of avoiding elaboration problems. With this switch, the binder
23461 plays a devil's advocate role, and tries to choose the order that
23462 has the best chance of failing. If your program works even with this
23463 switch, then it has a better chance of being error free, but this is still
23464 not a guarantee.
23465
23466 For an example of this approach in action, consider the C-tests (executable
23467 tests) from the ACVC suite. If these are compiled and run with the default
23468 treatment, then all but one of them succeed without generating any error
23469 diagnostics from the binder. However, there is one test that fails, and
23470 this is not surprising, because the whole point of this test is to ensure
23471 that the compiler can handle cases where it is impossible to determine
23472 a correct order statically, and it checks that an exception is indeed
23473 raised at run time.
23474
23475 This one test must be compiled and run using the
23476 @option{-gnatE}
23477 switch, and then it passes. Alternatively, the entire suite can
23478 be run using this switch. It is never wrong to run with the dynamic
23479 elaboration switch if your code is correct, and we assume that the
23480 C-tests are indeed correct (it is less efficient, but efficiency is
23481 not a factor in running the ACVC tests.)
23482
23483 @node Elaboration for Access-to-Subprogram Values
23484 @section Elaboration for Access-to-Subprogram Values
23485 @cindex Access-to-subprogram
23486
23487 @noindent
23488 The introduction of access-to-subprogram types in Ada 95 complicates
23489 the handling of elaboration. The trouble is that it becomes
23490 impossible to tell at compile time which procedure
23491 is being called. This means that it is not possible for the binder
23492 to analyze the elaboration requirements in this case.
23493
23494 If at the point at which the access value is created
23495 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
23496 the body of the subprogram is
23497 known to have been elaborated, then the access value is safe, and its use
23498 does not require a check. This may be achieved by appropriate arrangement
23499 of the order of declarations if the subprogram is in the current unit,
23500 or, if the subprogram is in another unit, by using pragma
23501 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
23502 on the referenced unit.
23503
23504 If the referenced body is not known to have been elaborated at the point
23505 the access value is created, then any use of the access value must do a
23506 dynamic check, and this dynamic check will fail and raise a
23507 @code{Program_Error} exception if the body has not been elaborated yet.
23508 GNAT will generate the necessary checks, and in addition, if the
23509 @option{-gnatwl}
23510 switch is set, will generate warnings that such checks are required.
23511
23512 The use of dynamic dispatching for tagged types similarly generates
23513 a requirement for dynamic checks, and premature calls to any primitive
23514 operation of a tagged type before the body of the operation has been
23515 elaborated, will result in the raising of @code{Program_Error}.
23516
23517 @node Summary of Procedures for Elaboration Control
23518 @section Summary of Procedures for Elaboration Control
23519 @cindex Elaboration control
23520
23521 @noindent
23522 First, compile your program with the default options, using none of
23523 the special elaboration control switches. If the binder successfully
23524 binds your program, then you can be confident that, apart from issues
23525 raised by the use of access-to-subprogram types and dynamic dispatching,
23526 the program is free of elaboration errors. If it is important that the
23527 program be portable, then use the
23528 @option{-gnatwl}
23529 switch to generate warnings about missing @code{Elaborate_All}
23530 pragmas, and supply the missing pragmas.
23531
23532 If the program fails to bind using the default static elaboration
23533 handling, then you can fix the program to eliminate the binder
23534 message, or recompile the entire program with the
23535 @option{-gnatE} switch to generate dynamic elaboration checks,
23536 and, if you are sure there really are no elaboration problems,
23537 use a global pragma @code{Suppress (Elaboration_Check)}.
23538
23539 @node Other Elaboration Order Considerations
23540 @section Other Elaboration Order Considerations
23541 @noindent
23542 This section has been entirely concerned with the issue of finding a valid
23543 elaboration order, as defined by the Ada Reference Manual. In a case
23544 where several elaboration orders are valid, the task is to find one
23545 of the possible valid elaboration orders (and the static model in GNAT
23546 will ensure that this is achieved).
23547
23548 The purpose of the elaboration rules in the Ada Reference Manual is to
23549 make sure that no entity is accessed before it has been elaborated. For
23550 a subprogram, this means that the spec and body must have been elaborated
23551 before the subprogram is called. For an object, this means that the object
23552 must have been elaborated before its value is read or written. A violation
23553 of either of these two requirements is an access before elaboration order,
23554 and this section has been all about avoiding such errors.
23555
23556 In the case where more than one order of elaboration is possible, in the
23557 sense that access before elaboration errors are avoided, then any one of
23558 the orders is ``correct'' in the sense that it meets the requirements of
23559 the Ada Reference Manual, and no such error occurs.
23560
23561 However, it may be the case for a given program, that there are
23562 constraints on the order of elaboration that come not from consideration
23563 of avoiding elaboration errors, but rather from extra-lingual logic
23564 requirements. Consider this example:
23565
23566 @smallexample @c ada
23567 with Init_Constants;
23568 package Constants is
23569    X : Integer := 0;
23570    Y : Integer := 0;
23571 end Constants;
23572
23573 package Init_Constants is
23574    procedure P; -- require a body
23575 end Init_Constants;
23576
23577 with Constants;
23578 package body Init_Constants is
23579    procedure P is begin null; end;
23580 begin
23581    Constants.X := 3;
23582    Constants.Y := 4;
23583 end Init_Constants;
23584
23585 with Constants;
23586 package Calc is
23587    Z : Integer := Constants.X + Constants.Y;
23588 end Calc;
23589
23590 with Calc;
23591 with Text_IO; use Text_IO;
23592 procedure Main is
23593 begin
23594    Put_Line (Calc.Z'Img);
23595 end Main;
23596 @end smallexample
23597
23598 @noindent
23599 In this example, there is more than one valid order of elaboration. For
23600 example both the following are correct orders:
23601
23602 @smallexample
23603 Init_Constants spec
23604 Constants spec
23605 Calc spec
23606 Init_Constants body
23607 Main body
23608
23609   and
23610
23611 Init_Constants spec
23612 Init_Constants body
23613 Constants spec
23614 Calc spec
23615 Main body
23616 @end smallexample
23617
23618 @noindent
23619 There is no language rule to prefer one or the other, both are correct
23620 from an order of elaboration point of view. But the programmatic effects
23621 of the two orders are very different. In the first, the elaboration routine
23622 of @code{Calc} initializes @code{Z} to zero, and then the main program
23623 runs with this value of zero. But in the second order, the elaboration
23624 routine of @code{Calc} runs after the body of Init_Constants has set
23625 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
23626 runs.
23627
23628 One could perhaps by applying pretty clever non-artificial intelligence
23629 to the situation guess that it is more likely that the second order of
23630 elaboration is the one desired, but there is no formal linguistic reason
23631 to prefer one over the other. In fact in this particular case, GNAT will
23632 prefer the second order, because of the rule that bodies are elaborated
23633 as soon as possible, but it's just luck that this is what was wanted
23634 (if indeed the second order was preferred).
23635
23636 If the program cares about the order of elaboration routines in a case like
23637 this, it is important to specify the order required. In this particular
23638 case, that could have been achieved by adding to the spec of Calc:
23639
23640 @smallexample @c ada
23641 pragma Elaborate_All (Constants);
23642 @end smallexample
23643
23644 @noindent
23645 which requires that the body (if any) and spec of @code{Constants},
23646 as well as the body and spec of any unit @code{with}'ed by
23647 @code{Constants} be elaborated before @code{Calc} is elaborated.
23648
23649 Clearly no automatic method can always guess which alternative you require,
23650 and if you are working with legacy code that had constraints of this kind
23651 which were not properly specified by adding @code{Elaborate} or
23652 @code{Elaborate_All} pragmas, then indeed it is possible that two different
23653 compilers can choose different orders.
23654
23655 The @code{gnatbind}
23656 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
23657 out problems. This switch causes bodies to be elaborated as late as possible
23658 instead of as early as possible. In the example above, it would have forced
23659 the choice of the first elaboration order. If you get different results
23660 when using this switch, and particularly if one set of results is right,
23661 and one is wrong as far as you are concerned, it shows that you have some
23662 missing @code{Elaborate} pragmas. For the example above, we have the
23663 following output:
23664
23665 @smallexample
23666 gnatmake -f -q main
23667 main
23668  7
23669 gnatmake -f -q main -bargs -p
23670 main
23671  0
23672 @end smallexample
23673
23674 @noindent
23675 It is of course quite unlikely that both these results are correct, so
23676 it is up to you in a case like this to investigate the source of the
23677 difference, by looking at the two elaboration orders that are chosen,
23678 and figuring out which is correct, and then adding the necessary
23679 @code{Elaborate_All} pragmas to ensure the desired order.
23680
23681
23682 @node Inline Assembler
23683 @appendix Inline Assembler
23684
23685 @noindent
23686 If you need to write low-level software that interacts directly
23687 with the hardware, Ada provides two ways to incorporate assembly
23688 language code into your program.  First, you can import and invoke
23689 external routines written in assembly language, an Ada feature fully
23690 supported by GNAT.  However, for small sections of code it may be simpler
23691 or more efficient to include assembly language statements directly
23692 in your Ada source program, using the facilities of the implementation-defined
23693 package @code{System.Machine_Code}, which incorporates the gcc
23694 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
23695 including the following:
23696
23697 @itemize @bullet
23698 @item No need to use non-Ada tools
23699 @item Consistent interface over different targets
23700 @item Automatic usage of the proper calling conventions
23701 @item Access to Ada constants and variables
23702 @item Definition of intrinsic routines
23703 @item Possibility of inlining a subprogram comprising assembler code
23704 @item Code optimizer can take Inline Assembler code into account
23705 @end itemize
23706
23707 This chapter presents a series of examples to show you how to use
23708 the Inline Assembler.  Although it focuses on the Intel x86,
23709 the general approach applies also to other processors.
23710 It is assumed that you are familiar with Ada
23711 and with assembly language programming.
23712
23713 @menu
23714 * Basic Assembler Syntax::
23715 * A Simple Example of Inline Assembler::
23716 * Output Variables in Inline Assembler::
23717 * Input Variables in Inline Assembler::
23718 * Inlining Inline Assembler Code::
23719 * Other Asm Functionality::
23720 * A Complete Example::
23721 @end menu
23722
23723 @c ---------------------------------------------------------------------------
23724 @node Basic Assembler Syntax
23725 @section Basic Assembler Syntax
23726
23727 @noindent
23728 The assembler used by GNAT and gcc is based not on the Intel assembly
23729 language, but rather on a language that descends from the AT&T Unix
23730 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
23731 The following table summarizes the main features of @emph{as} syntax
23732 and points out the differences from the Intel conventions.
23733 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
23734 pre-processor) documentation for further information.
23735
23736 @table @asis
23737 @item Register names
23738 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
23739 @*
23740 Intel: No extra punctuation; for example @code{eax}
23741
23742 @item Immediate operand
23743 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
23744 @*
23745 Intel: No extra punctuation; for example @code{4}
23746
23747 @item Address
23748 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
23749 @*
23750 Intel: No extra punctuation; for example @code{loc}
23751
23752 @item Memory contents
23753 gcc / @emph{as}: No extra punctuation; for example @code{loc}
23754 @*
23755 Intel: Square brackets; for example @code{[loc]}
23756
23757 @item Register contents
23758 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
23759 @*
23760 Intel: Square brackets; for example @code{[eax]}
23761
23762 @item Hexadecimal numbers
23763 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
23764 @*
23765 Intel: Trailing ``h''; for example @code{A0h}
23766
23767 @item Operand size
23768 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
23769 a 16-bit word
23770 @*
23771 Intel: Implicit, deduced by assembler; for example @code{mov}
23772
23773 @item Instruction repetition
23774 gcc / @emph{as}: Split into two lines; for example
23775 @*
23776 @code{rep}
23777 @*
23778 @code{stosl}
23779 @*
23780 Intel: Keep on one line; for example @code{rep stosl}
23781
23782 @item Order of operands
23783 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
23784 @*
23785 Intel: Destination first; for example @code{mov eax, 4}
23786 @end table
23787
23788 @c ---------------------------------------------------------------------------
23789 @node A Simple Example of Inline Assembler
23790 @section A Simple Example of Inline Assembler
23791
23792 @noindent
23793 The following example will generate a single assembly language statement,
23794 @code{nop}, which does nothing.  Despite its lack of run-time effect,
23795 the example will be useful in illustrating the basics of
23796 the Inline Assembler facility.
23797
23798 @smallexample @c ada
23799 @group
23800 with System.Machine_Code; use System.Machine_Code;
23801 procedure Nothing is
23802 begin
23803    Asm ("nop");
23804 end Nothing;
23805 @end group
23806 @end smallexample
23807
23808 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
23809 here it takes one parameter, a @emph{template string} that must be a static
23810 expression and that will form the generated instruction.
23811 @code{Asm} may be regarded as a compile-time procedure that parses
23812 the template string and additional parameters (none here),
23813 from which it generates a sequence of assembly language instructions.
23814
23815 The examples in this chapter will illustrate several of the forms
23816 for invoking @code{Asm}; a complete specification of the syntax
23817 is found in the @cite{GNAT Reference Manual}.
23818
23819 Under the standard GNAT conventions, the @code{Nothing} procedure
23820 should be in a file named @file{nothing.adb}.
23821 You can build the executable in the usual way:
23822 @smallexample
23823 gnatmake nothing
23824 @end smallexample
23825 However, the interesting aspect of this example is not its run-time behavior
23826 but rather the generated assembly code.
23827 To see this output, invoke the compiler as follows:
23828 @smallexample
23829    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
23830 @end smallexample
23831 where the options are:
23832
23833 @table @code
23834 @item -c
23835 compile only (no bind or link)
23836 @item -S
23837 generate assembler listing
23838 @item -fomit-frame-pointer
23839 do not set up separate stack frames
23840 @item -gnatp
23841 do not add runtime checks
23842 @end table
23843
23844 This gives a human-readable assembler version of the code. The resulting
23845 file will have the same name as the Ada source file, but with a @code{.s}
23846 extension. In our example, the file @file{nothing.s} has the following
23847 contents:
23848
23849 @smallexample
23850 @group
23851 .file "nothing.adb"
23852 gcc2_compiled.:
23853 ___gnu_compiled_ada:
23854 .text
23855    .align 4
23856 .globl __ada_nothing
23857 __ada_nothing:
23858 #APP
23859    nop
23860 #NO_APP
23861    jmp L1
23862    .align 2,0x90
23863 L1:
23864    ret
23865 @end group
23866 @end smallexample
23867
23868 The assembly code you included is clearly indicated by
23869 the compiler, between the @code{#APP} and @code{#NO_APP}
23870 delimiters. The character before the 'APP' and 'NOAPP'
23871 can differ on different targets. For example, GNU/Linux uses '#APP' while
23872 on NT you will see '/APP'.
23873
23874 If you make a mistake in your assembler code (such as using the
23875 wrong size modifier, or using a wrong operand for the instruction) GNAT
23876 will report this error in a temporary file, which will be deleted when
23877 the compilation is finished.  Generating an assembler file will help
23878 in such cases, since you can assemble this file separately using the
23879 @emph{as} assembler that comes with gcc.
23880
23881 Assembling the file using the command
23882
23883 @smallexample
23884 as @file{nothing.s}
23885 @end smallexample
23886 @noindent
23887 will give you error messages whose lines correspond to the assembler
23888 input file, so you can easily find and correct any mistakes you made.
23889 If there are no errors, @emph{as} will generate an object file
23890 @file{nothing.out}.
23891
23892 @c ---------------------------------------------------------------------------
23893 @node Output Variables in Inline Assembler
23894 @section Output Variables in Inline Assembler
23895
23896 @noindent
23897 The examples in this section, showing how to access the processor flags,
23898 illustrate how to specify the destination operands for assembly language
23899 statements.
23900
23901 @smallexample @c ada
23902 @group
23903 with Interfaces; use Interfaces;
23904 with Ada.Text_IO; use Ada.Text_IO;
23905 with System.Machine_Code; use System.Machine_Code;
23906 procedure Get_Flags is
23907    Flags : Unsigned_32;
23908    use ASCII;
23909 begin
23910    Asm ("pushfl"          & LF & HT & -- push flags on stack
23911         "popl %%eax"      & LF & HT & -- load eax with flags
23912         "movl %%eax, %0",             -- store flags in variable
23913         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
23914    Put_Line ("Flags register:" & Flags'Img);
23915 end Get_Flags;
23916 @end group
23917 @end smallexample
23918
23919 In order to have a nicely aligned assembly listing, we have separated
23920 multiple assembler statements in the Asm template string with linefeed
23921 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
23922 The resulting section of the assembly output file is:
23923
23924 @smallexample
23925 @group
23926 #APP
23927    pushfl
23928    popl %eax
23929    movl %eax, -40(%ebp)
23930 #NO_APP
23931 @end group
23932 @end smallexample
23933
23934 It would have been legal to write the Asm invocation as:
23935
23936 @smallexample
23937 Asm ("pushfl popl %%eax movl %%eax, %0")
23938 @end smallexample
23939
23940 but in the generated assembler file, this would come out as:
23941
23942 @smallexample
23943 #APP
23944    pushfl popl %eax movl %eax, -40(%ebp)
23945 #NO_APP
23946 @end smallexample
23947
23948 which is not so convenient for the human reader.
23949
23950 We use Ada comments
23951 at the end of each line to explain what the assembler instructions
23952 actually do.  This is a useful convention.
23953
23954 When writing Inline Assembler instructions, you need to precede each register
23955 and variable name with a percent sign.  Since the assembler already requires
23956 a percent sign at the beginning of a register name, you need two consecutive
23957 percent signs for such names in the Asm template string, thus @code{%%eax}.
23958 In the generated assembly code, one of the percent signs will be stripped off.
23959
23960 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
23961 variables: operands you later define using @code{Input} or @code{Output}
23962 parameters to @code{Asm}.
23963 An output variable is illustrated in
23964 the third statement in the Asm template string:
23965 @smallexample
23966 movl %%eax, %0
23967 @end smallexample
23968 The intent is to store the contents of the eax register in a variable that can
23969 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
23970 necessarily work, since the compiler might optimize by using a register
23971 to hold Flags, and the expansion of the @code{movl} instruction would not be
23972 aware of this optimization.  The solution is not to store the result directly
23973 but rather to advise the compiler to choose the correct operand form;
23974 that is the purpose of the @code{%0} output variable.
23975
23976 Information about the output variable is supplied in the @code{Outputs}
23977 parameter to @code{Asm}:
23978 @smallexample
23979 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
23980 @end smallexample
23981
23982 The output is defined by the @code{Asm_Output} attribute of the target type;
23983 the general format is
23984 @smallexample
23985 Type'Asm_Output (constraint_string, variable_name)
23986 @end smallexample
23987
23988 The constraint string directs the compiler how
23989 to store/access the associated variable.  In the example
23990 @smallexample
23991 Unsigned_32'Asm_Output ("=m", Flags);
23992 @end smallexample
23993 the @code{"m"} (memory) constraint tells the compiler that the variable
23994 @code{Flags} should be stored in a memory variable, thus preventing
23995 the optimizer from keeping it in a register.  In contrast,
23996 @smallexample
23997 Unsigned_32'Asm_Output ("=r", Flags);
23998 @end smallexample
23999 uses the @code{"r"} (register) constraint, telling the compiler to
24000 store the variable in a register.
24001
24002 If the constraint is preceded by the equal character (@strong{=}), it tells
24003 the compiler that the variable will be used to store data into it.
24004
24005 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
24006 allowing the optimizer to choose whatever it deems best.
24007
24008 There are a fairly large number of constraints, but the ones that are
24009 most useful (for the Intel x86 processor) are the following:
24010
24011 @table @code
24012 @item =
24013 output constraint
24014 @item g
24015 global (i.e. can be stored anywhere)
24016 @item m
24017 in memory
24018 @item I
24019 a constant
24020 @item a
24021 use eax
24022 @item b
24023 use ebx
24024 @item c
24025 use ecx
24026 @item d
24027 use edx
24028 @item S
24029 use esi
24030 @item D
24031 use edi
24032 @item r
24033 use one of eax, ebx, ecx or edx
24034 @item q
24035 use one of eax, ebx, ecx, edx, esi or edi
24036 @end table
24037
24038 The full set of constraints is described in the gcc and @emph{as}
24039 documentation; note that it is possible to combine certain constraints
24040 in one constraint string.
24041
24042 You specify the association of an output variable with an assembler operand
24043 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
24044 integer.  Thus in
24045 @smallexample @c ada
24046 @group
24047 Asm ("pushfl"          & LF & HT & -- push flags on stack
24048      "popl %%eax"      & LF & HT & -- load eax with flags
24049      "movl %%eax, %0",             -- store flags in variable
24050      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24051 @end group
24052 @end smallexample
24053 @noindent
24054 @code{%0} will be replaced in the expanded code by the appropriate operand,
24055 whatever
24056 the compiler decided for the @code{Flags} variable.
24057
24058 In general, you may have any number of output variables:
24059 @itemize @bullet
24060 @item
24061 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
24062 @item
24063 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
24064 of @code{Asm_Output} attributes
24065 @end itemize
24066
24067 For example:
24068 @smallexample @c ada
24069 @group
24070 Asm ("movl %%eax, %0" & LF & HT &
24071      "movl %%ebx, %1" & LF & HT &
24072      "movl %%ecx, %2",
24073      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
24074                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
24075                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
24076 @end group
24077 @end smallexample
24078 @noindent
24079 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
24080 in the Ada program.
24081
24082 As a variation on the @code{Get_Flags} example, we can use the constraints
24083 string to direct the compiler to store the eax register into the @code{Flags}
24084 variable, instead of including the store instruction explicitly in the
24085 @code{Asm} template string:
24086
24087 @smallexample @c ada
24088 @group
24089 with Interfaces; use Interfaces;
24090 with Ada.Text_IO; use Ada.Text_IO;
24091 with System.Machine_Code; use System.Machine_Code;
24092 procedure Get_Flags_2 is
24093    Flags : Unsigned_32;
24094    use ASCII;
24095 begin
24096    Asm ("pushfl"      & LF & HT & -- push flags on stack
24097         "popl %%eax",             -- save flags in eax
24098         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
24099    Put_Line ("Flags register:" & Flags'Img);
24100 end Get_Flags_2;
24101 @end group
24102 @end smallexample
24103
24104 @noindent
24105 The @code{"a"} constraint tells the compiler that the @code{Flags}
24106 variable will come from the eax register. Here is the resulting code:
24107
24108 @smallexample
24109 @group
24110 #APP
24111    pushfl
24112    popl %eax
24113 #NO_APP
24114    movl %eax,-40(%ebp)
24115 @end group
24116 @end smallexample
24117
24118 @noindent
24119 The compiler generated the store of eax into Flags after
24120 expanding the assembler code.
24121
24122 Actually, there was no need to pop the flags into the eax register;
24123 more simply, we could just pop the flags directly into the program variable:
24124
24125 @smallexample @c ada
24126 @group
24127 with Interfaces; use Interfaces;
24128 with Ada.Text_IO; use Ada.Text_IO;
24129 with System.Machine_Code; use System.Machine_Code;
24130 procedure Get_Flags_3 is
24131    Flags : Unsigned_32;
24132    use ASCII;
24133 begin
24134    Asm ("pushfl"  & LF & HT & -- push flags on stack
24135         "pop %0",             -- save flags in Flags
24136         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24137    Put_Line ("Flags register:" & Flags'Img);
24138 end Get_Flags_3;
24139 @end group
24140 @end smallexample
24141
24142 @c ---------------------------------------------------------------------------
24143 @node Input Variables in Inline Assembler
24144 @section Input Variables in Inline Assembler
24145
24146 @noindent
24147 The example in this section illustrates how to specify the source operands
24148 for assembly language statements.
24149 The program simply increments its input value by 1:
24150
24151 @smallexample @c ada
24152 @group
24153 with Interfaces; use Interfaces;
24154 with Ada.Text_IO; use Ada.Text_IO;
24155 with System.Machine_Code; use System.Machine_Code;
24156 procedure Increment is
24157
24158    function Incr (Value : Unsigned_32) return Unsigned_32 is
24159       Result : Unsigned_32;
24160    begin
24161       Asm ("incl %0",
24162            Inputs  => Unsigned_32'Asm_Input ("a", Value),
24163            Outputs => Unsigned_32'Asm_Output ("=a", Result));
24164       return Result;
24165    end Incr;
24166
24167    Value : Unsigned_32;
24168
24169 begin
24170    Value := 5;
24171    Put_Line ("Value before is" & Value'Img);
24172    Value := Incr (Value);
24173    Put_Line ("Value after is" & Value'Img);
24174 end Increment;
24175 @end group
24176 @end smallexample
24177
24178 The @code{Outputs} parameter to @code{Asm} specifies
24179 that the result will be in the eax register and that it is to be stored
24180 in the @code{Result} variable.
24181
24182 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
24183 but with an @code{Asm_Input} attribute.
24184 The @code{"="} constraint, indicating an output value, is not present.
24185
24186 You can have multiple input variables, in the same way that you can have more
24187 than one output variable.
24188
24189 The parameter count (%0, %1) etc, now starts at the first input
24190 statement, and continues with the output statements.
24191 When both parameters use the same variable, the
24192 compiler will treat them as the same %n operand, which is the case here.
24193
24194 Just as the @code{Outputs} parameter causes the register to be stored into the
24195 target variable after execution of the assembler statements, so does the
24196 @code{Inputs} parameter cause its variable to be loaded into the register
24197 before execution of the assembler statements.
24198
24199 Thus the effect of the @code{Asm} invocation is:
24200 @enumerate
24201 @item load the 32-bit value of @code{Value} into eax
24202 @item execute the @code{incl %eax} instruction
24203 @item store the contents of eax into the @code{Result} variable
24204 @end enumerate
24205
24206 The resulting assembler file (with @option{-O2} optimization) contains:
24207 @smallexample
24208 @group
24209 _increment__incr.1:
24210    subl $4,%esp
24211    movl 8(%esp),%eax
24212 #APP
24213    incl %eax
24214 #NO_APP
24215    movl %eax,%edx
24216    movl %ecx,(%esp)
24217    addl $4,%esp
24218    ret
24219 @end group
24220 @end smallexample
24221
24222 @c ---------------------------------------------------------------------------
24223 @node Inlining Inline Assembler Code
24224 @section Inlining Inline Assembler Code
24225
24226 @noindent
24227 For a short subprogram such as the @code{Incr} function in the previous
24228 section, the overhead of the call and return (creating / deleting the stack
24229 frame) can be significant, compared to the amount of code in the subprogram
24230 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
24231 which directs the compiler to expand invocations of the subprogram at the
24232 point(s) of call, instead of setting up a stack frame for out-of-line calls.
24233 Here is the resulting program:
24234
24235 @smallexample @c ada
24236 @group
24237 with Interfaces; use Interfaces;
24238 with Ada.Text_IO; use Ada.Text_IO;
24239 with System.Machine_Code; use System.Machine_Code;
24240 procedure Increment_2 is
24241
24242    function Incr (Value : Unsigned_32) return Unsigned_32 is
24243       Result : Unsigned_32;
24244    begin
24245       Asm ("incl %0",
24246            Inputs  => Unsigned_32'Asm_Input ("a", Value),
24247            Outputs => Unsigned_32'Asm_Output ("=a", Result));
24248       return Result;
24249    end Incr;
24250    pragma Inline (Increment);
24251
24252    Value : Unsigned_32;
24253
24254 begin
24255    Value := 5;
24256    Put_Line ("Value before is" & Value'Img);
24257    Value := Increment (Value);
24258    Put_Line ("Value after is" & Value'Img);
24259 end Increment_2;
24260 @end group
24261 @end smallexample
24262
24263 Compile the program with both optimization (@option{-O2}) and inlining
24264 enabled (@option{-gnatpn} instead of @option{-gnatp}).
24265
24266 The @code{Incr} function is still compiled as usual, but at the
24267 point in @code{Increment} where our function used to be called:
24268
24269 @smallexample
24270 @group
24271 pushl %edi
24272 call _increment__incr.1
24273 @end group
24274 @end smallexample
24275
24276 @noindent
24277 the code for the function body directly appears:
24278
24279 @smallexample
24280 @group
24281 movl %esi,%eax
24282 #APP
24283    incl %eax
24284 #NO_APP
24285    movl %eax,%edx
24286 @end group
24287 @end smallexample
24288
24289 @noindent
24290 thus saving the overhead of stack frame setup and an out-of-line call.
24291
24292 @c ---------------------------------------------------------------------------
24293 @node Other Asm Functionality
24294 @section Other @code{Asm} Functionality
24295
24296 @noindent
24297 This section describes two important parameters to the @code{Asm}
24298 procedure: @code{Clobber}, which identifies register usage;
24299 and @code{Volatile}, which inhibits unwanted optimizations.
24300
24301 @menu
24302 * The Clobber Parameter::
24303 * The Volatile Parameter::
24304 @end menu
24305
24306 @c ---------------------------------------------------------------------------
24307 @node The Clobber Parameter
24308 @subsection The @code{Clobber} Parameter
24309
24310 @noindent
24311 One of the dangers of intermixing assembly language and a compiled language
24312 such as Ada is that the compiler needs to be aware of which registers are
24313 being used by the assembly code.  In some cases, such as the earlier examples,
24314 the constraint string is sufficient to indicate register usage (e.g.,
24315 @code{"a"} for
24316 the eax register).  But more generally, the compiler needs an explicit
24317 identification of the registers that are used by the Inline Assembly
24318 statements.
24319
24320 Using a register that the compiler doesn't know about
24321 could be a side effect of an instruction (like @code{mull}
24322 storing its result in both eax and edx).
24323 It can also arise from explicit register usage in your
24324 assembly code; for example:
24325 @smallexample
24326 @group
24327 Asm ("movl %0, %%ebx" & LF & HT &
24328      "movl %%ebx, %1",
24329      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
24330      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
24331 @end group
24332 @end smallexample
24333 @noindent
24334 where the compiler (since it does not analyze the @code{Asm} template string)
24335 does not know you are using the ebx register.
24336
24337 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
24338 to identify the registers that will be used by your assembly code:
24339
24340 @smallexample
24341 @group
24342 Asm ("movl %0, %%ebx" & LF & HT &
24343      "movl %%ebx, %1",
24344      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
24345      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
24346      Clobber => "ebx");
24347 @end group
24348 @end smallexample
24349
24350 The Clobber parameter is a static string expression specifying the
24351 register(s) you are using.  Note that register names are @emph{not} prefixed
24352 by a percent sign. Also, if more than one register is used then their names
24353 are separated by commas; e.g., @code{"eax, ebx"}
24354
24355 The @code{Clobber} parameter has several additional uses:
24356 @enumerate
24357 @item Use ``register'' name @code{cc} to indicate that flags might have changed
24358 @item Use ``register'' name @code{memory} if you changed a memory location
24359 @end enumerate
24360
24361 @c ---------------------------------------------------------------------------
24362 @node The Volatile Parameter
24363 @subsection The @code{Volatile} Parameter
24364 @cindex Volatile parameter
24365
24366 @noindent
24367 Compiler optimizations in the presence of Inline Assembler may sometimes have
24368 unwanted effects.  For example, when an @code{Asm} invocation with an input
24369 variable is inside a loop, the compiler might move the loading of the input
24370 variable outside the loop, regarding it as a one-time initialization.
24371
24372 If this effect is not desired, you can disable such optimizations by setting
24373 the @code{Volatile} parameter to @code{True}; for example:
24374
24375 @smallexample @c ada
24376 @group
24377 Asm ("movl %0, %%ebx" & LF & HT &
24378      "movl %%ebx, %1",
24379      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
24380      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
24381      Clobber  => "ebx",
24382      Volatile => True);
24383 @end group
24384 @end smallexample
24385
24386 By default, @code{Volatile} is set to @code{False} unless there is no
24387 @code{Outputs} parameter.
24388
24389 Although setting @code{Volatile} to @code{True} prevents unwanted
24390 optimizations, it will also disable other optimizations that might be
24391 important for efficiency. In general, you should set @code{Volatile}
24392 to @code{True} only if the compiler's optimizations have created
24393 problems.
24394
24395 @c ---------------------------------------------------------------------------
24396 @node A Complete Example
24397 @section A Complete Example
24398
24399 @noindent
24400 This section contains a complete program illustrating a realistic usage
24401 of GNAT's Inline Assembler capabilities.  It comprises a main procedure
24402 @code{Check_CPU} and a package @code{Intel_CPU}.
24403 The package declares a collection of functions that detect the properties
24404 of the 32-bit x86 processor that is running the program.
24405 The main procedure invokes these functions and displays the information.
24406
24407 The Intel_CPU package could be enhanced by adding functions to
24408 detect the type of x386 co-processor, the processor caching options and
24409 special operations such as the SIMD extensions.
24410
24411 Although the Intel_CPU package has been written for 32-bit Intel
24412 compatible CPUs, it is OS neutral. It has been tested on DOS,
24413 Windows/NT and GNU/Linux.
24414
24415 @menu
24416 * Check_CPU Procedure::
24417 * Intel_CPU Package Specification::
24418 * Intel_CPU Package Body::
24419 @end menu
24420
24421 @c ---------------------------------------------------------------------------
24422 @node Check_CPU Procedure
24423 @subsection @code{Check_CPU} Procedure
24424 @cindex Check_CPU procedure
24425
24426 @smallexample @c adanocomment
24427 ---------------------------------------------------------------------
24428 --                                                                 --
24429 --  Uses the Intel_CPU package to identify the CPU the program is  --
24430 --  running on, and some of the features it supports.              --
24431 --                                                                 --
24432 ---------------------------------------------------------------------
24433
24434 with Intel_CPU;                     --  Intel CPU detection functions
24435 with Ada.Text_IO;                   --  Standard text I/O
24436 with Ada.Command_Line;              --  To set the exit status
24437
24438 procedure Check_CPU is
24439
24440    Type_Found : Boolean := False;
24441    --  Flag to indicate that processor was identified
24442
24443    Features   : Intel_CPU.Processor_Features;
24444    --  The processor features
24445
24446    Signature  : Intel_CPU.Processor_Signature;
24447    --  The processor type signature
24448
24449 begin
24450
24451    -----------------------------------
24452    --  Display the program banner.  --
24453    -----------------------------------
24454
24455    Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name &
24456                          ": check Intel CPU version and features, v1.0");
24457    Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever");
24458    Ada.Text_IO.New_Line;
24459
24460    -----------------------------------------------------------------------
24461    --  We can safely start with the assumption that we are on at least  --
24462    --  a x386 processor. If the CPUID instruction is present, then we   --
24463    --  have a later processor type.                                     --
24464    -----------------------------------------------------------------------
24465
24466    if Intel_CPU.Has_CPUID = False then
24467
24468       --  No CPUID instruction, so we assume this is indeed a x386
24469       --  processor. We can still check if it has a FP co-processor.
24470       if Intel_CPU.Has_FPU then
24471          Ada.Text_IO.Put_Line
24472            ("x386-type processor with a FP co-processor");
24473       else
24474          Ada.Text_IO.Put_Line
24475            ("x386-type processor without a FP co-processor");
24476       end if;  --  check for FPU
24477
24478       --  Program done
24479       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
24480       return;
24481
24482    end if;  --  check for CPUID
24483
24484    -----------------------------------------------------------------------
24485    --  If CPUID is supported, check if this is a true Intel processor,  --
24486    --  if it is not, display a warning.                                 --
24487    -----------------------------------------------------------------------
24488
24489    if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then
24490       Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor");
24491       Ada.Text_IO.Put_Line ("*** Some information may be incorrect");
24492    end if;  --  check if Intel
24493
24494    ----------------------------------------------------------------------
24495    --  With the CPUID instruction present, we can assume at least a    --
24496    --  x486 processor. If the CPUID support level is < 1 then we have  --
24497    --  to leave it at that.                                            --
24498    ----------------------------------------------------------------------
24499
24500    if Intel_CPU.CPUID_Level < 1 then
24501
24502       --  Ok, this is a x486 processor. we still can get the Vendor ID
24503       Ada.Text_IO.Put_Line ("x486-type processor");
24504       Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID);
24505
24506       --  We can also check if there is a FPU present
24507       if Intel_CPU.Has_FPU then
24508          Ada.Text_IO.Put_Line ("Floating-Point support");
24509       else
24510          Ada.Text_IO.Put_Line ("No Floating-Point support");
24511       end if;  --  check for FPU
24512
24513       --  Program done
24514       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
24515       return;
24516
24517    end if;  --  check CPUID level
24518
24519    ---------------------------------------------------------------------
24520    --  With a CPUID level of 1 we can use the processor signature to  --
24521    --  determine it's exact type.                                     --
24522    ---------------------------------------------------------------------
24523
24524    Signature := Intel_CPU.Signature;
24525
24526    ----------------------------------------------------------------------
24527    --  Ok, now we go into a lot of messy comparisons to get the        --
24528    --  processor type. For clarity, no attememt to try to optimize the --
24529    --  comparisons has been made. Note that since Intel_CPU does not   --
24530    --  support getting cache info, we cannot distinguish between P5    --
24531    --  and Celeron types yet.                                          --
24532    ----------------------------------------------------------------------
24533
24534    --  x486SL
24535    if Signature.Processor_Type = 2#00#   and
24536      Signature.Family          = 2#0100# and
24537      Signature.Model           = 2#0100# then
24538       Type_Found := True;
24539       Ada.Text_IO.Put_Line ("x486SL processor");
24540    end if;
24541
24542    --  x486DX2 Write-Back
24543    if Signature.Processor_Type = 2#00#   and
24544      Signature.Family          = 2#0100# and
24545      Signature.Model           = 2#0111# then
24546       Type_Found := True;
24547       Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor");
24548    end if;
24549
24550    --  x486DX4
24551    if Signature.Processor_Type = 2#00#   and
24552      Signature.Family          = 2#0100# and
24553      Signature.Model           = 2#1000# then
24554       Type_Found := True;
24555       Ada.Text_IO.Put_Line ("x486DX4 processor");
24556    end if;
24557
24558    --  x486DX4 Overdrive
24559    if Signature.Processor_Type = 2#01#   and
24560      Signature.Family          = 2#0100# and
24561      Signature.Model           = 2#1000# then
24562       Type_Found := True;
24563       Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor");
24564    end if;
24565
24566    --  Pentium (60, 66)
24567    if Signature.Processor_Type = 2#00#   and
24568      Signature.Family          = 2#0101# and
24569      Signature.Model           = 2#0001# then
24570       Type_Found := True;
24571       Ada.Text_IO.Put_Line ("Pentium processor (60, 66)");
24572    end if;
24573
24574    --  Pentium (75, 90, 100, 120, 133, 150, 166, 200)
24575    if Signature.Processor_Type = 2#00#   and
24576      Signature.Family          = 2#0101# and
24577      Signature.Model           = 2#0010# then
24578       Type_Found := True;
24579       Ada.Text_IO.Put_Line
24580         ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)");
24581    end if;
24582
24583    --  Pentium OverDrive (60, 66)
24584    if Signature.Processor_Type = 2#01#   and
24585      Signature.Family          = 2#0101# and
24586      Signature.Model           = 2#0001# then
24587       Type_Found := True;
24588       Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)");
24589    end if;
24590
24591    --  Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200)
24592    if Signature.Processor_Type = 2#01#   and
24593      Signature.Family          = 2#0101# and
24594      Signature.Model           = 2#0010# then
24595       Type_Found := True;
24596       Ada.Text_IO.Put_Line
24597         ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)");
24598    end if;
24599
24600    --  Pentium OverDrive processor for x486 processor-based systems
24601    if Signature.Processor_Type = 2#01#   and
24602      Signature.Family          = 2#0101# and
24603      Signature.Model           = 2#0011# then
24604       Type_Found := True;
24605       Ada.Text_IO.Put_Line
24606         ("Pentium OverDrive processor for x486 processor-based systems");
24607    end if;
24608
24609    --  Pentium processor with MMX technology (166, 200)
24610    if Signature.Processor_Type = 2#00#   and
24611      Signature.Family          = 2#0101# and
24612      Signature.Model           = 2#0100# then
24613       Type_Found := True;
24614       Ada.Text_IO.Put_Line
24615         ("Pentium processor with MMX technology (166, 200)");
24616    end if;
24617
24618    --  Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133)
24619    if Signature.Processor_Type = 2#01#   and
24620      Signature.Family          = 2#0101# and
24621      Signature.Model           = 2#0100# then
24622       Type_Found := True;
24623       Ada.Text_IO.Put_Line
24624         ("Pentium OverDrive processor with MMX " &
24625          "technology for Pentium processor (75, 90, 100, 120, 133)");
24626    end if;
24627
24628    --  Pentium Pro processor
24629    if Signature.Processor_Type = 2#00#   and
24630      Signature.Family          = 2#0110# and
24631      Signature.Model           = 2#0001# then
24632       Type_Found := True;
24633       Ada.Text_IO.Put_Line ("Pentium Pro processor");
24634    end if;
24635
24636    --  Pentium II processor, model 3
24637    if Signature.Processor_Type = 2#00#   and
24638      Signature.Family          = 2#0110# and
24639      Signature.Model           = 2#0011# then
24640       Type_Found := True;
24641       Ada.Text_IO.Put_Line ("Pentium II processor, model 3");
24642    end if;
24643
24644    --  Pentium II processor, model 5 or Celeron processor
24645    if Signature.Processor_Type = 2#00#   and
24646      Signature.Family          = 2#0110# and
24647      Signature.Model           = 2#0101# then
24648       Type_Found := True;
24649       Ada.Text_IO.Put_Line
24650         ("Pentium II processor, model 5 or Celeron processor");
24651    end if;
24652
24653    --  Pentium Pro OverDrive processor
24654    if Signature.Processor_Type = 2#01#   and
24655      Signature.Family          = 2#0110# and
24656      Signature.Model           = 2#0011# then
24657       Type_Found := True;
24658       Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor");
24659    end if;
24660
24661    --  If no type recognized, we have an unknown. Display what
24662    --  we _do_ know
24663    if Type_Found = False then
24664       Ada.Text_IO.Put_Line ("Unknown processor");
24665    end if;
24666
24667    -----------------------------------------
24668    --  Display processor stepping level.  --
24669    -----------------------------------------
24670
24671    Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img);
24672
24673    ---------------------------------
24674    --  Display vendor ID string.  --
24675    ---------------------------------
24676
24677    Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID);
24678
24679    ------------------------------------
24680    --  Get the processors features.  --
24681    ------------------------------------
24682
24683    Features := Intel_CPU.Features;
24684
24685    -----------------------------
24686    --  Check for a FPU unit.  --
24687    -----------------------------
24688
24689    if Features.FPU = True then
24690       Ada.Text_IO.Put_Line ("Floating-Point unit available");
24691    else
24692       Ada.Text_IO.Put_Line ("no Floating-Point unit");
24693    end if;  --  check for FPU
24694
24695    --------------------------------
24696    --  List processor features.  --
24697    --------------------------------
24698
24699    Ada.Text_IO.Put_Line ("Supported features: ");
24700
24701    --  Virtual Mode Extension
24702    if Features.VME = True then
24703       Ada.Text_IO.Put_Line ("    VME    - Virtual Mode Extension");
24704    end if;
24705
24706    --  Debugging Extension
24707    if Features.DE = True then
24708       Ada.Text_IO.Put_Line ("    DE     - Debugging Extension");
24709    end if;
24710
24711    --  Page Size Extension
24712    if Features.PSE = True then
24713       Ada.Text_IO.Put_Line ("    PSE    - Page Size Extension");
24714    end if;
24715
24716    --  Time Stamp Counter
24717    if Features.TSC = True then
24718       Ada.Text_IO.Put_Line ("    TSC    - Time Stamp Counter");
24719    end if;
24720
24721    --  Model Specific Registers
24722    if Features.MSR = True then
24723       Ada.Text_IO.Put_Line ("    MSR    - Model Specific Registers");
24724    end if;
24725
24726    --  Physical Address Extension
24727    if Features.PAE = True then
24728       Ada.Text_IO.Put_Line ("    PAE    - Physical Address Extension");
24729    end if;
24730
24731    --  Machine Check Extension
24732    if Features.MCE = True then
24733       Ada.Text_IO.Put_Line ("    MCE    - Machine Check Extension");
24734    end if;
24735
24736    --  CMPXCHG8 instruction supported
24737    if Features.CX8 = True then
24738       Ada.Text_IO.Put_Line ("    CX8    - CMPXCHG8 instruction");
24739    end if;
24740
24741    --  on-chip APIC hardware support
24742    if Features.APIC = True then
24743       Ada.Text_IO.Put_Line ("    APIC   - on-chip APIC hardware support");
24744    end if;
24745
24746    --  Fast System Call
24747    if Features.SEP = True then
24748       Ada.Text_IO.Put_Line ("    SEP    - Fast System Call");
24749    end if;
24750
24751    --  Memory Type Range Registers
24752    if Features.MTRR = True then
24753       Ada.Text_IO.Put_Line ("    MTTR   - Memory Type Range Registers");
24754    end if;
24755
24756    --  Page Global Enable
24757    if Features.PGE = True then
24758       Ada.Text_IO.Put_Line ("    PGE    - Page Global Enable");
24759    end if;
24760
24761    --  Machine Check Architecture
24762    if Features.MCA = True then
24763       Ada.Text_IO.Put_Line ("    MCA    - Machine Check Architecture");
24764    end if;
24765
24766    --  Conditional Move Instruction Supported
24767    if Features.CMOV = True then
24768       Ada.Text_IO.Put_Line
24769         ("    CMOV   - Conditional Move Instruction Supported");
24770    end if;
24771
24772    --  Page Attribute Table
24773    if Features.PAT = True then
24774       Ada.Text_IO.Put_Line ("    PAT    - Page Attribute Table");
24775    end if;
24776
24777    --  36-bit Page Size Extension
24778    if Features.PSE_36 = True then
24779       Ada.Text_IO.Put_Line ("    PSE_36 - 36-bit Page Size Extension");
24780    end if;
24781
24782    --  MMX technology supported
24783    if Features.MMX = True then
24784       Ada.Text_IO.Put_Line ("    MMX    - MMX technology supported");
24785    end if;
24786
24787    --  Fast FP Save and Restore
24788    if Features.FXSR = True then
24789       Ada.Text_IO.Put_Line ("    FXSR   - Fast FP Save and Restore");
24790    end if;
24791
24792    ---------------------
24793    --  Program done.  --
24794    ---------------------
24795
24796    Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
24797
24798 exception
24799
24800    when others =>
24801       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
24802       raise;
24803
24804 end Check_CPU;
24805 @end smallexample
24806
24807 @c ---------------------------------------------------------------------------
24808 @node Intel_CPU Package Specification
24809 @subsection @code{Intel_CPU} Package Specification
24810 @cindex Intel_CPU package specification
24811
24812 @smallexample @c adanocomment
24813 -------------------------------------------------------------------------
24814 --                                                                     --
24815 --  file: intel_cpu.ads                                                --
24816 --                                                                     --
24817 --           *********************************************             --
24818 --           * WARNING: for 32-bit Intel processors only *             --
24819 --           *********************************************             --
24820 --                                                                     --
24821 --  This package contains a number of subprograms that are useful in   --
24822 --  determining the Intel x86 CPU (and the features it supports) on    --
24823 --  which the program is running.                                      --
24824 --                                                                     --
24825 --  The package is based upon the information given in the Intel       --
24826 --  Application Note AP-485: "Intel Processor Identification and the   --
24827 --  CPUID Instruction" as of April 1998. This application note can be  --
24828 --  found on www.intel.com.                                            --
24829 --                                                                     --
24830 --  It currently deals with 32-bit processors only, will not detect    --
24831 --  features added after april 1998, and does not guarantee proper     --
24832 --  results on Intel-compatible processors.                            --
24833 --                                                                     --
24834 --  Cache info and x386 fpu type detection are not supported.          --
24835 --                                                                     --
24836 --  This package does not use any privileged instructions, so should   --
24837 --  work on any OS running on a 32-bit Intel processor.                --
24838 --                                                                     --
24839 -------------------------------------------------------------------------
24840
24841 with Interfaces;             use Interfaces;
24842 --  for using unsigned types
24843
24844 with System.Machine_Code;    use System.Machine_Code;
24845 --  for using inline assembler code
24846
24847 with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
24848 --  for inserting control characters
24849
24850 package Intel_CPU is
24851
24852    ----------------------
24853    --  Processor bits  --
24854    ----------------------
24855
24856    subtype Num_Bits is Natural range 0 .. 31;
24857    --  the number of processor bits (32)
24858
24859    --------------------------
24860    --  Processor register  --
24861    --------------------------
24862
24863    --  define a processor register type for easy access to
24864    --  the individual bits
24865
24866    type Processor_Register is array (Num_Bits) of Boolean;
24867    pragma Pack (Processor_Register);
24868    for Processor_Register'Size use 32;
24869
24870    -------------------------
24871    --  Unsigned register  --
24872    -------------------------
24873
24874    --  define a processor register type for easy access to
24875    --  the individual bytes
24876
24877    type Unsigned_Register is
24878       record
24879          L1 : Unsigned_8;
24880          H1 : Unsigned_8;
24881          L2 : Unsigned_8;
24882          H2 : Unsigned_8;
24883       end record;
24884
24885    for Unsigned_Register use
24886       record
24887          L1 at 0 range  0 ..  7;
24888          H1 at 0 range  8 .. 15;
24889          L2 at 0 range 16 .. 23;
24890          H2 at 0 range 24 .. 31;
24891       end record;
24892
24893    for Unsigned_Register'Size use 32;
24894
24895    ---------------------------------
24896    --  Intel processor vendor ID  --
24897    ---------------------------------
24898
24899    Intel_Processor : constant String (1 .. 12) := "GenuineIntel";
24900    --  indicates an Intel manufactured processor
24901
24902    ------------------------------------
24903    --  Processor signature register  --
24904    ------------------------------------
24905
24906    --  a register type to hold the processor signature
24907
24908    type Processor_Signature is
24909       record
24910          Stepping       : Natural range 0 .. 15;
24911          Model          : Natural range 0 .. 15;
24912          Family         : Natural range 0 .. 15;
24913          Processor_Type : Natural range 0 .. 3;
24914          Reserved       : Natural range 0 .. 262143;
24915       end record;
24916
24917    for Processor_Signature use
24918       record
24919          Stepping       at 0 range  0 ..  3;
24920          Model          at 0 range  4 ..  7;
24921          Family         at 0 range  8 .. 11;
24922          Processor_Type at 0 range 12 .. 13;
24923          Reserved       at 0 range 14 .. 31;
24924       end record;
24925
24926    for Processor_Signature'Size use 32;
24927
24928    -----------------------------------
24929    --  Processor features register  --
24930    -----------------------------------
24931
24932    --  a processor register to hold the processor feature flags
24933
24934    type Processor_Features is
24935       record
24936          FPU    : Boolean;                --  floating point unit on chip
24937          VME    : Boolean;                --  virtual mode extension
24938          DE     : Boolean;                --  debugging extension
24939          PSE    : Boolean;                --  page size extension
24940          TSC    : Boolean;                --  time stamp counter
24941          MSR    : Boolean;                --  model specific registers
24942          PAE    : Boolean;                --  physical address extension
24943          MCE    : Boolean;                --  machine check extension
24944          CX8    : Boolean;                --  cmpxchg8 instruction
24945          APIC   : Boolean;                --  on-chip apic hardware
24946          Res_1  : Boolean;                --  reserved for extensions
24947          SEP    : Boolean;                --  fast system call
24948          MTRR   : Boolean;                --  memory type range registers
24949          PGE    : Boolean;                --  page global enable
24950          MCA    : Boolean;                --  machine check architecture
24951          CMOV   : Boolean;                --  conditional move supported
24952          PAT    : Boolean;                --  page attribute table
24953          PSE_36 : Boolean;                --  36-bit page size extension
24954          Res_2  : Natural range 0 .. 31;  --  reserved for extensions
24955          MMX    : Boolean;                --  MMX technology supported
24956          FXSR   : Boolean;                --  fast FP save and restore
24957          Res_3  : Natural range 0 .. 127; --  reserved for extensions
24958       end record;
24959
24960    for Processor_Features use
24961       record
24962          FPU    at 0 range  0 ..  0;
24963          VME    at 0 range  1 ..  1;
24964          DE     at 0 range  2 ..  2;
24965          PSE    at 0 range  3 ..  3;
24966          TSC    at 0 range  4 ..  4;
24967          MSR    at 0 range  5 ..  5;
24968          PAE    at 0 range  6 ..  6;
24969          MCE    at 0 range  7 ..  7;
24970          CX8    at 0 range  8 ..  8;
24971          APIC   at 0 range  9 ..  9;
24972          Res_1  at 0 range 10 .. 10;
24973          SEP    at 0 range 11 .. 11;
24974          MTRR   at 0 range 12 .. 12;
24975          PGE    at 0 range 13 .. 13;
24976          MCA    at 0 range 14 .. 14;
24977          CMOV   at 0 range 15 .. 15;
24978          PAT    at 0 range 16 .. 16;
24979          PSE_36 at 0 range 17 .. 17;
24980          Res_2  at 0 range 18 .. 22;
24981          MMX    at 0 range 23 .. 23;
24982          FXSR   at 0 range 24 .. 24;
24983          Res_3  at 0 range 25 .. 31;
24984       end record;
24985
24986    for Processor_Features'Size use 32;
24987
24988    -------------------
24989    --  Subprograms  --
24990    -------------------
24991
24992    function Has_FPU return Boolean;
24993    --  return True if a FPU is found
24994    --  use only if CPUID is not supported
24995
24996    function Has_CPUID return Boolean;
24997    --  return True if the processor supports the CPUID instruction
24998
24999    function CPUID_Level return Natural;
25000    --  return the CPUID support level (0, 1 or 2)
25001    --  can only be called if the CPUID instruction is supported
25002
25003    function Vendor_ID return String;
25004    --  return the processor vendor identification string
25005    --  can only be called if the CPUID instruction is supported
25006
25007    function Signature return Processor_Signature;
25008    --  return the processor signature
25009    --  can only be called if the CPUID instruction is supported
25010
25011    function Features return Processor_Features;
25012    --  return the processors features
25013    --  can only be called if the CPUID instruction is supported
25014
25015 private
25016
25017    ------------------------
25018    --  EFLAGS bit names  --
25019    ------------------------
25020
25021    ID_Flag : constant Num_Bits := 21;
25022    --  ID flag bit
25023
25024 end Intel_CPU;
25025 @end smallexample
25026
25027 @c ---------------------------------------------------------------------------
25028 @node Intel_CPU Package Body
25029 @subsection @code{Intel_CPU} Package Body
25030 @cindex Intel_CPU package body
25031
25032 @smallexample @c adanocomment
25033 package body Intel_CPU is
25034
25035    ---------------------------
25036    --  Detect FPU presence  --
25037    ---------------------------
25038
25039    --  There is a FPU present if we can set values to the FPU Status
25040    --  and Control Words.
25041
25042    function Has_FPU return Boolean is
25043
25044       Register : Unsigned_16;
25045       --  processor register to store a word
25046
25047    begin
25048
25049       --  check if we can change the status word
25050       Asm (
25051
25052            --  the assembler code
25053            "finit"              & LF & HT &    --  reset status word
25054            "movw $0x5A5A, %%ax" & LF & HT &    --  set value status word
25055            "fnstsw %0"          & LF & HT &    --  save status word
25056            "movw %%ax, %0",                    --  store status word
25057
25058            --  output stored in Register
25059            --  register must be a memory location
25060            Outputs => Unsigned_16'Asm_output ("=m", Register),
25061
25062            --  tell compiler that we used eax
25063            Clobber => "eax");
25064
25065       --  if the status word is zero, there is no FPU
25066       if Register = 0 then
25067          return False;   --  no status word
25068       end if;  --  check status word value
25069
25070       --  check if we can get the control word
25071       Asm (
25072
25073            --  the assembler code
25074            "fnstcw %0",   --  save the control word
25075
25076            --  output into Register
25077            --  register must be a memory location
25078            Outputs => Unsigned_16'Asm_output ("=m", Register));
25079
25080       --  check the relevant bits
25081       if (Register and 16#103F#) /= 16#003F# then
25082          return False;   --  no control word
25083       end if;  --  check control word value
25084
25085       --  FPU found
25086       return True;
25087
25088    end Has_FPU;
25089
25090    --------------------------------
25091    --  Detect CPUID instruction  --
25092    --------------------------------
25093
25094    --  The processor supports the CPUID instruction if it is possible
25095    --  to change the value of ID flag bit in the EFLAGS register.
25096
25097    function Has_CPUID return Boolean is
25098
25099       Original_Flags, Modified_Flags : Processor_Register;
25100       --  EFLAG contents before and after changing the ID flag
25101
25102    begin
25103
25104       --  try flipping the ID flag in the EFLAGS register
25105       Asm (
25106
25107            --  the assembler code
25108            "pushfl"               & LF & HT &     --  push EFLAGS on stack
25109            "pop %%eax"            & LF & HT &     --  pop EFLAGS into eax
25110            "movl %%eax, %0"       & LF & HT &     --  save EFLAGS content
25111            "xor $0x200000, %%eax" & LF & HT &     --  flip ID flag
25112            "push %%eax"           & LF & HT &     --  push EFLAGS on stack
25113            "popfl"                & LF & HT &     --  load EFLAGS register
25114            "pushfl"               & LF & HT &     --  push EFLAGS on stack
25115            "pop %1",                              --  save EFLAGS content
25116
25117            --  output values, may be anything
25118            --  Original_Flags is %0
25119            --  Modified_Flags is %1
25120            Outputs =>
25121               (Processor_Register'Asm_output ("=g", Original_Flags),
25122                Processor_Register'Asm_output ("=g", Modified_Flags)),
25123
25124            --  tell compiler eax is destroyed
25125            Clobber => "eax");
25126
25127       --  check if CPUID is supported
25128       if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then
25129          return True;   --  ID flag was modified
25130       else
25131          return False;  --  ID flag unchanged
25132       end if;  --  check for CPUID
25133
25134    end Has_CPUID;
25135
25136    -------------------------------
25137    --  Get CPUID support level  --
25138    -------------------------------
25139
25140    function CPUID_Level return Natural is
25141
25142       Level : Unsigned_32;
25143       --  returned support level
25144
25145    begin
25146
25147       --  execute CPUID, storing the results in the Level register
25148       Asm (
25149
25150            --  the assembler code
25151            "cpuid",    --  execute CPUID
25152
25153            --  zero is stored in eax
25154            --  returning the support level in eax
25155            Inputs => Unsigned_32'Asm_input ("a", 0),
25156
25157            --  eax is stored in Level
25158            Outputs => Unsigned_32'Asm_output ("=a", Level),
25159
25160            --  tell compiler ebx, ecx and edx registers are destroyed
25161            Clobber => "ebx, ecx, edx");
25162
25163       --  return the support level
25164       return Natural (Level);
25165
25166    end CPUID_Level;
25167
25168    --------------------------------
25169    --  Get CPU Vendor ID String  --
25170    --------------------------------
25171
25172    --  The vendor ID string is returned in the ebx, ecx and edx register
25173    --  after executing the CPUID instruction with eax set to zero.
25174    --  In case of a true Intel processor the string returned is
25175    --  "GenuineIntel"
25176
25177    function Vendor_ID return String is
25178
25179       Ebx, Ecx, Edx : Unsigned_Register;
25180       --  registers containing the vendor ID string
25181
25182       Vendor_ID : String (1 .. 12);
25183       -- the vendor ID string
25184
25185    begin
25186
25187       --  execute CPUID, storing the results in the processor registers
25188       Asm (
25189
25190            --  the assembler code
25191            "cpuid",    --  execute CPUID
25192
25193            --  zero stored in eax
25194            --  vendor ID string returned in ebx, ecx and edx
25195            Inputs => Unsigned_32'Asm_input ("a", 0),
25196
25197            --  ebx is stored in Ebx
25198            --  ecx is stored in Ecx
25199            --  edx is stored in Edx
25200            Outputs => (Unsigned_Register'Asm_output ("=b", Ebx),
25201                        Unsigned_Register'Asm_output ("=c", Ecx),
25202                        Unsigned_Register'Asm_output ("=d", Edx)));
25203
25204       --  now build the vendor ID string
25205       Vendor_ID( 1) := Character'Val (Ebx.L1);
25206       Vendor_ID( 2) := Character'Val (Ebx.H1);
25207       Vendor_ID( 3) := Character'Val (Ebx.L2);
25208       Vendor_ID( 4) := Character'Val (Ebx.H2);
25209       Vendor_ID( 5) := Character'Val (Edx.L1);
25210       Vendor_ID( 6) := Character'Val (Edx.H1);
25211       Vendor_ID( 7) := Character'Val (Edx.L2);
25212       Vendor_ID( 8) := Character'Val (Edx.H2);
25213       Vendor_ID( 9) := Character'Val (Ecx.L1);
25214       Vendor_ID(10) := Character'Val (Ecx.H1);
25215       Vendor_ID(11) := Character'Val (Ecx.L2);
25216       Vendor_ID(12) := Character'Val (Ecx.H2);
25217
25218       --  return string
25219       return Vendor_ID;
25220
25221    end Vendor_ID;
25222
25223    -------------------------------
25224    --  Get processor signature  --
25225    -------------------------------
25226
25227    function Signature return Processor_Signature is
25228
25229       Result : Processor_Signature;
25230       --  processor signature returned
25231
25232    begin
25233
25234       --  execute CPUID, storing the results in the Result variable
25235       Asm (
25236
25237            --  the assembler code
25238            "cpuid",    --  execute CPUID
25239
25240            --  one is stored in eax
25241            --  processor signature returned in eax
25242            Inputs => Unsigned_32'Asm_input ("a", 1),
25243
25244            --  eax is stored in Result
25245            Outputs => Processor_Signature'Asm_output ("=a", Result),
25246
25247            --  tell compiler that ebx, ecx and edx are also destroyed
25248            Clobber => "ebx, ecx, edx");
25249
25250       --  return processor signature
25251       return Result;
25252
25253    end Signature;
25254
25255    ------------------------------
25256    --  Get processor features  --
25257    ------------------------------
25258
25259    function Features return Processor_Features is
25260
25261       Result : Processor_Features;
25262       --  processor features returned
25263
25264    begin
25265
25266       --  execute CPUID, storing the results in the Result variable
25267       Asm (
25268
25269            --  the assembler code
25270            "cpuid",    --  execute CPUID
25271
25272            --  one stored in eax
25273            --  processor features returned in edx
25274            Inputs => Unsigned_32'Asm_input ("a", 1),
25275
25276            --  edx is stored in Result
25277            Outputs => Processor_Features'Asm_output ("=d", Result),
25278
25279            --  tell compiler that ebx and ecx are also destroyed
25280            Clobber => "ebx, ecx");
25281
25282       --  return processor signature
25283       return Result;
25284
25285    end Features;
25286
25287 end Intel_CPU;
25288 @end smallexample
25289 @c END OF INLINE ASSEMBLER CHAPTER
25290 @c ===============================
25291
25292
25293
25294 @c ***********************************
25295 @c * Compatibility and Porting Guide *
25296 @c ***********************************
25297 @node Compatibility and Porting Guide
25298 @appendix Compatibility and Porting Guide
25299
25300 @noindent
25301 This chapter describes the compatibility issues that may arise between
25302 GNAT and other Ada 83 and Ada 95 compilation systems, and shows how GNAT
25303 can expedite porting
25304 applications developed in other Ada environments.
25305
25306 @menu
25307 * Compatibility with Ada 83::
25308 * Implementation-dependent characteristics::
25309 * Compatibility with DEC Ada 83::
25310 * Compatibility with Other Ada 95 Systems::
25311 * Representation Clauses::
25312 @end menu
25313
25314 @node Compatibility with Ada 83
25315 @section Compatibility with Ada 83
25316 @cindex Compatibility (between Ada 83 and Ada 95)
25317
25318 @noindent
25319 Ada 95 is designed to be highly upwards compatible with Ada 83.  In
25320 particular, the design intention is that the difficulties associated
25321 with moving from Ada 83 to Ada 95 should be no greater than those
25322 that occur when moving from one Ada 83 system to another.
25323
25324 However, there are a number of points at which there are minor
25325 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
25326 full details of these issues,
25327 and should be consulted for a complete treatment.
25328 In practice the
25329 following subsections treat the most likely issues to be encountered.
25330
25331 @menu
25332 * Legal Ada 83 programs that are illegal in Ada 95::
25333 * More deterministic semantics::
25334 * Changed semantics::
25335 * Other language compatibility issues::
25336 @end menu
25337
25338 @node Legal Ada 83 programs that are illegal in Ada 95
25339 @subsection Legal Ada 83 programs that are illegal in Ada 95
25340
25341 @table @asis
25342 @item Character literals
25343 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
25344 @code{Wide_Character} as a new predefined character type, some uses of
25345 character literals that were legal in Ada 83 are illegal in Ada 95.
25346 For example:
25347 @smallexample @c ada
25348    for Char in 'A' .. 'Z' loop ... end loop;
25349 @end smallexample
25350 @noindent
25351 The problem is that @code{'A'} and @code{'Z'} could be from either
25352 @code{Character} or @code{Wide_Character}.  The simplest correction
25353 is to make the type explicit; e.g.:
25354 @smallexample @c ada
25355    for Char in Character range 'A' .. 'Z' loop ... end loop;
25356 @end smallexample
25357
25358 @item New reserved words
25359 The identifiers @code{abstract}, @code{aliased}, @code{protected},
25360 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
25361 Existing Ada 83 code using any of these identifiers must be edited to
25362 use some alternative name.
25363
25364 @item Freezing rules
25365 The rules in Ada 95 are slightly different with regard to the point at
25366 which entities are frozen, and representation pragmas and clauses are
25367 not permitted past the freeze point.  This shows up most typically in
25368 the form of an error message complaining that a representation item
25369 appears too late, and the appropriate corrective action is to move
25370 the item nearer to the declaration of the entity to which it refers.
25371
25372 A particular case is that representation pragmas
25373 @ifset vms
25374 (including the
25375 extended DEC Ada 83 compatibility pragmas such as @code{Export_Procedure})
25376 @end ifset
25377 cannot be applied to a subprogram body.  If necessary, a separate subprogram
25378 declaration must be introduced to which the pragma can be applied.
25379
25380 @item Optional bodies for library packages
25381 In Ada 83, a package that did not require a package body was nevertheless
25382 allowed to have one.  This lead to certain surprises in compiling large
25383 systems (situations in which the body could be unexpectedly ignored by the
25384 binder).  In Ada 95, if a package does not require a body then it is not
25385 permitted to have a body.  To fix this problem, simply remove a redundant
25386 body if it is empty, or, if it is non-empty, introduce a dummy declaration
25387 into the spec that makes the body required.  One approach is to add a private
25388 part to the package declaration (if necessary), and define a parameterless
25389 procedure called @code{Requires_Body}, which must then be given a dummy
25390 procedure body in the package body, which then becomes required.
25391 Another approach (assuming that this does not introduce elaboration
25392 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
25393 since one effect of this pragma is to require the presence of a package body.
25394
25395 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
25396 In Ada 95, the exception @code{Numeric_Error} is a renaming of
25397 @code{Constraint_Error}.
25398 This means that it is illegal to have separate exception handlers for
25399 the two exceptions.  The fix is simply to remove the handler for the
25400 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
25401 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
25402
25403 @item Indefinite subtypes in generics
25404 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
25405 as the actual for a generic formal private type, but then the instantiation
25406 would be illegal if there were any instances of declarations of variables
25407 of this type in the generic body.  In Ada 95, to avoid this clear violation
25408 of the methodological principle known as the ``contract model'',
25409 the generic declaration explicitly indicates whether
25410 or not such instantiations are permitted.  If a generic formal parameter
25411 has explicit unknown discriminants, indicated by using @code{(<>)} after the
25412 type name, then it can be instantiated with indefinite types, but no
25413 stand-alone variables can be declared of this type.  Any attempt to declare
25414 such a variable will result in an illegality at the time the generic is
25415 declared.  If the @code{(<>)} notation is not used, then it is illegal
25416 to instantiate the generic with an indefinite type.
25417 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
25418 It will show up as a compile time error, and
25419 the fix is usually simply to add the @code{(<>)} to the generic declaration.
25420 @end table
25421
25422 @node More deterministic semantics
25423 @subsection More deterministic semantics
25424
25425 @table @asis
25426 @item Conversions
25427 Conversions from real types to integer types round away from 0.  In Ada 83
25428 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
25429 implementation freedom was intended to support unbiased rounding in
25430 statistical applications, but in practice it interfered with portability.
25431 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
25432 is required.  Numeric code may be affected by this change in semantics.
25433 Note, though, that this issue is no worse than already existed in Ada 83
25434 when porting code from one vendor to another.
25435
25436 @item Tasking
25437 The Real-Time Annex introduces a set of policies that define the behavior of
25438 features that were implementation dependent in Ada 83, such as the order in
25439 which open select branches are executed.
25440 @end table
25441
25442 @node Changed semantics
25443 @subsection Changed semantics
25444
25445 @noindent
25446 The worst kind of incompatibility is one where a program that is legal in
25447 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
25448 possible in Ada 83.  Fortunately this is extremely rare, but the one
25449 situation that you should be alert to is the change in the predefined type
25450 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
25451
25452 @table @asis
25453 @item range of @code{Character}
25454 The range of @code{Standard.Character} is now the full 256 characters
25455 of Latin-1, whereas in most Ada 83 implementations it was restricted
25456 to 128 characters. Although some of the effects of
25457 this change will be manifest in compile-time rejection of legal
25458 Ada 83 programs it is possible for a working Ada 83 program to have
25459 a different effect in Ada 95, one that was not permitted in Ada 83.
25460 As an example, the expression
25461 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
25462 delivers @code{255} as its value.
25463 In general, you should look at the logic of any
25464 character-processing Ada 83 program and see whether it needs to be adapted
25465 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
25466 character handling package that may be relevant if code needs to be adapted
25467 to account for the additional Latin-1 elements.
25468 The desirable fix is to
25469 modify the program to accommodate the full character set, but in some cases
25470 it may be convenient to define a subtype or derived type of Character that
25471 covers only the restricted range.
25472 @cindex Latin-1
25473 @end table
25474
25475 @node Other language compatibility issues
25476 @subsection Other language compatibility issues
25477 @table @asis
25478 @item @option{-gnat83 switch}
25479 All implementations of GNAT provide a switch that causes GNAT to operate
25480 in Ada 83 mode.  In this mode, some but not all compatibility problems
25481 of the type described above are handled automatically.  For example, the
25482 new Ada 95 reserved words are treated simply as identifiers as in Ada 83.
25483 However,
25484 in practice, it is usually advisable to make the necessary modifications
25485 to the program to remove the need for using this switch.
25486 See @ref{Compiling Ada 83 Programs}.
25487
25488 @item Support for removed Ada 83 pragmas and attributes
25489 A number of pragmas and attributes from Ada 83 have been removed from Ada 95,
25490 generally because they have been replaced by other mechanisms.  Ada 95
25491 compilers are allowed, but not required, to implement these missing
25492 elements.  In contrast with some other Ada 95 compilers, GNAT implements all
25493 such pragmas and attributes, eliminating this compatibility concern.  These
25494 include @code{pragma Interface} and the floating point type attributes
25495 (@code{Emax}, @code{Mantissa}, etc.), among other items.
25496 @end table
25497
25498
25499 @node Implementation-dependent characteristics
25500 @section Implementation-dependent characteristics
25501 @noindent
25502 Although the Ada language defines the semantics of each construct as
25503 precisely as practical, in some situations (for example for reasons of
25504 efficiency, or where the effect is heavily dependent on the host or target
25505 platform) the implementation is allowed some freedom.  In porting Ada 83
25506 code to GNAT, you need to be aware of whether / how the existing code
25507 exercised such implementation dependencies.  Such characteristics fall into
25508 several categories, and GNAT offers specific support in assisting the
25509 transition from certain Ada 83 compilers.
25510
25511 @menu
25512 * Implementation-defined pragmas::
25513 * Implementation-defined attributes::
25514 * Libraries::
25515 * Elaboration order::
25516 * Target-specific aspects::
25517 @end menu
25518
25519
25520 @node Implementation-defined pragmas
25521 @subsection Implementation-defined pragmas
25522
25523 @noindent
25524 Ada compilers are allowed to supplement the language-defined pragmas, and
25525 these are a potential source of non-portability.  All GNAT-defined pragmas
25526 are described in the GNAT Reference Manual, and these include several that
25527 are specifically intended to correspond to other vendors' Ada 83 pragmas.
25528 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
25529 For
25530 compatibility with DEC Ada 83, GNAT supplies the pragmas
25531 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
25532 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
25533 and @code{Volatile}.
25534 Other relevant pragmas include @code{External} and @code{Link_With}.
25535 Some vendor-specific
25536 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
25537 recognized, thus
25538 avoiding compiler rejection of units that contain such pragmas; they are not
25539 relevant in a GNAT context and hence are not otherwise implemented.
25540
25541 @node Implementation-defined attributes
25542 @subsection Implementation-defined attributes
25543
25544 Analogous to pragmas, the set of attributes may be extended by an
25545 implementation.  All GNAT-defined attributes are described in the
25546 @cite{GNAT Reference Manual}, and these include several that are specifically
25547 intended
25548 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
25549 the attribute @code{VADS_Size} may be useful.  For compatibility with DEC
25550 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
25551 @code{Type_Class}.
25552
25553 @node Libraries
25554 @subsection Libraries
25555 @noindent
25556 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
25557 code uses vendor-specific libraries then there are several ways to manage
25558 this in Ada 95:
25559 @enumerate
25560 @item
25561 If the source code for the libraries (specifications and bodies) are
25562 available, then the libraries can be migrated in the same way as the
25563 application.
25564 @item
25565 If the source code for the specifications but not the bodies are
25566 available, then you can reimplement the bodies.
25567 @item
25568 Some new Ada 95 features obviate the need for library support.  For
25569 example most Ada 83 vendors supplied a package for unsigned integers.  The
25570 Ada 95 modular type feature is the preferred way to handle this need, so
25571 instead of migrating or reimplementing the unsigned integer package it may
25572 be preferable to retrofit the application using modular types.
25573 @end enumerate
25574
25575 @node Elaboration order
25576 @subsection Elaboration order
25577 @noindent
25578 The implementation can choose any elaboration order consistent with the unit
25579 dependency relationship.  This freedom means that some orders can result in
25580 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
25581 to invoke a subprogram its body has been elaborated, or to instantiate a
25582 generic before the generic body has been elaborated.  By default GNAT
25583 attempts to choose a safe order (one that will not encounter access before
25584 elaboration problems) by implicitly inserting Elaborate_All pragmas where
25585 needed.  However, this can lead to the creation of elaboration circularities
25586 and a resulting rejection of the program by gnatbind.  This issue is
25587 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
25588 In brief, there are several
25589 ways to deal with this situation:
25590
25591 @itemize @bullet
25592 @item
25593 Modify the program to eliminate the circularities, e.g. by moving
25594 elaboration-time code into explicitly-invoked procedures
25595 @item
25596 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
25597 @code{Elaborate} pragmas, and then inhibit the generation of implicit
25598 @code{Elaborate_All}
25599 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
25600 (by selectively suppressing elaboration checks via pragma
25601 @code{Suppress(Elaboration_Check)} when it is safe to do so).
25602 @end itemize
25603
25604 @node Target-specific aspects
25605 @subsection Target-specific aspects
25606 @noindent
25607 Low-level applications need to deal with machine addresses, data
25608 representations, interfacing with assembler code, and similar issues.  If
25609 such an Ada 83 application is being ported to different target hardware (for
25610 example where the byte endianness has changed) then you will need to
25611 carefully examine the program logic; the porting effort will heavily depend
25612 on the robustness of the original design.  Moreover, Ada 95 is sometimes
25613 incompatible with typical Ada 83 compiler practices regarding implicit
25614 packing, the meaning of the Size attribute, and the size of access values.
25615 GNAT's approach to these issues is described in @ref{Representation Clauses}.
25616
25617
25618 @node Compatibility with Other Ada 95 Systems
25619 @section Compatibility with Other Ada 95 Systems
25620
25621 @noindent
25622 Providing that programs avoid the use of implementation dependent and
25623 implementation defined features of Ada 95, as documented in the Ada 95
25624 reference manual, there should be a high degree of portability between
25625 GNAT and other Ada 95 systems.  The following are specific items which
25626 have proved troublesome in moving GNAT programs to other Ada 95
25627 compilers, but do not affect porting code to GNAT@.
25628
25629 @table @asis
25630 @item Ada 83 Pragmas and Attributes
25631 Ada 95 compilers are allowed, but not required, to implement the missing
25632 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
25633 GNAT implements all such pragmas and attributes, eliminating this as
25634 a compatibility concern, but some other Ada 95 compilers reject these
25635 pragmas and attributes.
25636
25637 @item Special-needs Annexes
25638 GNAT implements the full set of special needs annexes.  At the
25639 current time, it is the only Ada 95 compiler to do so.  This means that
25640 programs making use of these features may not be portable to other Ada
25641 95 compilation systems.
25642
25643 @item Representation Clauses
25644 Some other Ada 95 compilers implement only the minimal set of
25645 representation clauses required by the Ada 95 reference manual.  GNAT goes
25646 far beyond this minimal set, as described in the next section.
25647 @end table
25648
25649 @node Representation Clauses
25650 @section Representation Clauses
25651
25652 @noindent
25653 The Ada 83 reference manual was quite vague in describing both the minimal
25654 required implementation of representation clauses, and also their precise
25655 effects.  The Ada 95 reference manual is much more explicit, but the minimal
25656 set of capabilities required in Ada 95 is quite limited.
25657
25658 GNAT implements the full required set of capabilities described in the
25659 Ada 95 reference manual, but also goes much beyond this, and in particular
25660 an effort has been made to be compatible with existing Ada 83 usage to the
25661 greatest extent possible.
25662
25663 A few cases exist in which Ada 83 compiler behavior is incompatible with
25664 requirements in the Ada 95 reference manual.  These are instances of
25665 intentional or accidental dependence on specific implementation dependent
25666 characteristics of these Ada 83 compilers.  The following is a list of
25667 the cases most likely to arise in existing legacy Ada 83 code.
25668
25669 @table @asis
25670 @item Implicit Packing
25671 Some Ada 83 compilers allowed a Size specification to cause implicit
25672 packing of an array or record.  This could cause expensive implicit
25673 conversions for change of representation in the presence of derived
25674 types, and the Ada design intends to avoid this possibility.
25675 Subsequent AI's were issued to make it clear that such implicit
25676 change of representation in response to a Size clause is inadvisable,
25677 and this recommendation is represented explicitly in the Ada 95 RM
25678 as implementation advice that is followed by GNAT@.
25679 The problem will show up as an error
25680 message rejecting the size clause.  The fix is simply to provide
25681 the explicit pragma @code{Pack}, or for more fine tuned control, provide
25682 a Component_Size clause.
25683
25684 @item Meaning of Size Attribute
25685 The Size attribute in Ada 95 for discrete types is defined as being the
25686 minimal number of bits required to hold values of the type.  For example,
25687 on a 32-bit machine, the size of Natural will typically be 31 and not
25688 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
25689 some 32 in this situation.  This problem will usually show up as a compile
25690 time error, but not always.  It is a good idea to check all uses of the
25691 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
25692 Object_Size can provide a useful way of duplicating the behavior of
25693 some Ada 83 compiler systems.
25694
25695 @item Size of Access Types
25696 A common assumption in Ada 83 code is that an access type is in fact a pointer,
25697 and that therefore it will be the same size as a System.Address value.  This
25698 assumption is true for GNAT in most cases with one exception.  For the case of
25699 a pointer to an unconstrained array type (where the bounds may vary from one
25700 value of the access type to another), the default is to use a ``fat pointer'',
25701 which is represented as two separate pointers, one to the bounds, and one to
25702 the array.  This representation has a number of advantages, including improved
25703 efficiency.  However, it may cause some difficulties in porting existing Ada 83
25704 code which makes the assumption that, for example, pointers fit in 32 bits on
25705 a machine with 32-bit addressing.
25706
25707 To get around this problem, GNAT also permits the use of ``thin pointers'' for
25708 access types in this case (where the designated type is an unconstrained array
25709 type).  These thin pointers are indeed the same size as a System.Address value.
25710 To specify a thin pointer, use a size clause for the type, for example:
25711
25712 @smallexample @c ada
25713 type X is access all String;
25714 for X'Size use Standard'Address_Size;
25715 @end smallexample
25716
25717 @noindent
25718 which will cause the type X to be represented using a single pointer.
25719 When using this representation, the bounds are right behind the array.
25720 This representation is slightly less efficient, and does not allow quite
25721 such flexibility in the use of foreign pointers or in using the
25722 Unrestricted_Access attribute to create pointers to non-aliased objects.
25723 But for any standard portable use of the access type it will work in
25724 a functionally correct manner and allow porting of existing code.
25725 Note that another way of forcing a thin pointer representation
25726 is to use a component size clause for the element size in an array,
25727 or a record representation clause for an access field in a record.
25728 @end table
25729
25730 @node Compatibility with DEC Ada 83
25731 @section Compatibility with DEC Ada 83
25732
25733 @noindent
25734 The VMS version of GNAT fully implements all the pragmas and attributes
25735 provided by DEC Ada 83, as well as providing the standard DEC Ada 83
25736 libraries, including Starlet.  In addition, data layouts and parameter
25737 passing conventions are highly compatible.  This means that porting
25738 existing DEC Ada 83 code to GNAT in VMS systems should be easier than
25739 most other porting efforts.  The following are some of the most
25740 significant differences between GNAT and DEC Ada 83.
25741
25742 @table @asis
25743 @item Default floating-point representation
25744 In GNAT, the default floating-point format is IEEE, whereas in DEC Ada 83,
25745 it is VMS format.  GNAT does implement the necessary pragmas
25746 (Long_Float, Float_Representation) for changing this default.
25747
25748 @item System
25749 The package System in GNAT exactly corresponds to the definition in the
25750 Ada 95 reference manual, which means that it excludes many of the
25751 DEC Ada 83 extensions.  However, a separate package Aux_DEC is provided
25752 that contains the additional definitions, and a special pragma,
25753 Extend_System allows this package to be treated transparently as an
25754 extension of package System.
25755
25756 @item To_Address
25757 The definitions provided by Aux_DEC are exactly compatible with those
25758 in the DEC Ada 83 version of System, with one exception.
25759 DEC Ada provides the following declarations:
25760
25761 @smallexample @c ada
25762 TO_ADDRESS (INTEGER)
25763 TO_ADDRESS (UNSIGNED_LONGWORD)
25764 TO_ADDRESS (universal_integer)
25765 @end smallexample
25766
25767 @noindent
25768 The version of TO_ADDRESS taking a universal integer argument is in fact
25769 an extension to Ada 83 not strictly compatible with the reference manual.
25770 In GNAT, we are constrained to be exactly compatible with the standard,
25771 and this means we cannot provide this capability.  In DEC Ada 83, the
25772 point of this definition is to deal with a call like:
25773
25774 @smallexample @c ada
25775 TO_ADDRESS (16#12777#);
25776 @end smallexample
25777
25778 @noindent
25779 Normally, according to the Ada 83 standard, one would expect this to be
25780 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
25781 of TO_ADDRESS@.  However, in DEC Ada 83, there is no ambiguity, since the
25782 definition using universal_integer takes precedence.
25783
25784 In GNAT, since the version with universal_integer cannot be supplied, it is
25785 not possible to be 100% compatible.  Since there are many programs using
25786 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
25787 to change the name of the function in the UNSIGNED_LONGWORD case, so the
25788 declarations provided in the GNAT version of AUX_Dec are:
25789
25790 @smallexample @c ada
25791 function To_Address (X : Integer) return Address;
25792 pragma Pure_Function (To_Address);
25793
25794 function To_Address_Long (X : Unsigned_Longword)
25795  return Address;
25796 pragma Pure_Function (To_Address_Long);
25797 @end smallexample
25798
25799 @noindent
25800 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
25801 change the name to TO_ADDRESS_LONG@.
25802
25803 @item Task_Id values
25804 The Task_Id values assigned will be different in the two systems, and GNAT
25805 does not provide a specified value for the Task_Id of the environment task,
25806 which in GNAT is treated like any other declared task.
25807 @end table
25808
25809 For full details on these and other less significant compatibility issues,
25810 see appendix E of the Digital publication entitled @cite{DEC Ada, Technical
25811 Overview and Comparison on DIGITAL Platforms}.
25812
25813 For GNAT running on other than VMS systems, all the DEC Ada 83 pragmas and
25814 attributes are recognized, although only a subset of them can sensibly
25815 be implemented.  The description of pragmas in this reference manual
25816 indicates whether or not they are applicable to non-VMS systems.
25817
25818
25819
25820 @ifset unw
25821 @node Microsoft Windows Topics
25822 @appendix Microsoft Windows Topics
25823 @cindex Windows NT
25824 @cindex Windows 95
25825 @cindex Windows 98
25826
25827 @noindent
25828 This chapter describes topics that are specific to the Microsoft Windows
25829 platforms (NT, 2000, and XP Professional).
25830
25831 @menu
25832 * Using GNAT on Windows::
25833 * Using a network installation of GNAT::
25834 * CONSOLE and WINDOWS subsystems::
25835 * Temporary Files::
25836 * Mixed-Language Programming on Windows::
25837 * Windows Calling Conventions::
25838 * Introduction to Dynamic Link Libraries (DLLs)::
25839 * Using DLLs with GNAT::
25840 * Building DLLs with GNAT::
25841 * GNAT and Windows Resources::
25842 * Debugging a DLL::
25843 * GNAT and COM/DCOM Objects::
25844 @end menu
25845
25846 @node Using GNAT on Windows
25847 @section Using GNAT on Windows
25848
25849 @noindent
25850 One of the strengths of the GNAT technology is that its tool set
25851 (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
25852 @code{gdb} debugger, etc.) is used in the same way regardless of the
25853 platform.
25854
25855 On Windows this tool set is complemented by a number of Microsoft-specific
25856 tools that have been provided to facilitate interoperability with Windows
25857 when this is required. With these tools:
25858
25859 @itemize @bullet
25860
25861 @item
25862 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
25863 subsystems.
25864
25865 @item
25866 You can use any Dynamically Linked Library (DLL) in your Ada code (both
25867 relocatable and non-relocatable DLLs are supported).
25868
25869 @item
25870 You can build Ada DLLs for use in other applications. These applications
25871 can be written in a language other than Ada (e.g., C, C++, etc). Again both
25872 relocatable and non-relocatable Ada DLLs are supported.
25873
25874 @item
25875 You can include Windows resources in your Ada application.
25876
25877 @item
25878 You can use or create COM/DCOM objects.
25879 @end itemize
25880
25881 @noindent
25882 Immediately below are listed all known general GNAT-for-Windows restrictions.
25883 Other restrictions about specific features like Windows Resources and DLLs
25884 are listed in separate sections below.
25885
25886 @itemize @bullet
25887
25888 @item
25889 It is not possible to use @code{GetLastError} and @code{SetLastError}
25890 when tasking, protected records, or exceptions are used. In these
25891 cases, in order to implement Ada semantics, the GNAT run-time system
25892 calls certain Win32 routines that set the last error variable to 0 upon
25893 success. It should be possible to use @code{GetLastError} and
25894 @code{SetLastError} when tasking, protected record, and exception
25895 features are not used, but it is not guaranteed to work.
25896
25897 @item
25898 It is not possible to link against Microsoft libraries except for
25899 import libraries. The library must be built to be compatible with
25900 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
25901 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
25902 not be compatible with the GNAT runtime. Even if the library is
25903 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
25904
25905 @item
25906 When the compilation environment is located on FAT32 drives, users may
25907 experience recompilations of the source files that have not changed if
25908 Daylight Saving Time (DST) state has changed since the last time files
25909 were compiled. NTFS drives do not have this problem.
25910
25911 @item
25912 No components of the GNAT toolset use any entries in the Windows
25913 registry. The only entries that can be created are file associations and
25914 PATH settings, provided the user has chosen to create them at installation
25915 time, as well as some minimal book-keeping information needed to correctly
25916 uninstall or integrate different GNAT products.
25917 @end itemize
25918
25919 @node Using a network installation of GNAT
25920 @section Using a network installation of GNAT
25921
25922 @noindent
25923 Make sure the system on which GNAT is installed is accessible from the
25924 current machine, i.e. the install location is shared over the network.
25925 Shared resources are accessed on Windows by means of UNC paths, which
25926 have the format @code{\\server\sharename\path}
25927
25928 In order to use such a network installation, simply add the UNC path of the
25929 @file{bin} directory of your GNAT installation in front of your PATH. For
25930 example, if GNAT is installed in @file{\GNAT} directory of a share location
25931 called @file{c-drive} on a machine @file{LOKI}, the following command will
25932 make it available:
25933
25934 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
25935
25936 Be aware that every compilation using the network installation results in the
25937 transfer of large amounts of data across the network and will likely cause
25938 serious performance penalty.
25939
25940 @node CONSOLE and WINDOWS subsystems
25941 @section CONSOLE and WINDOWS subsystems
25942 @cindex CONSOLE Subsystem
25943 @cindex WINDOWS Subsystem
25944 @cindex -mwindows
25945
25946 @noindent
25947 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
25948 (which is the default subsystem) will always create a console when
25949 launching the application. This is not something desirable when the
25950 application has a Windows GUI. To get rid of this console the
25951 application must be using the @code{WINDOWS} subsystem. To do so
25952 the @option{-mwindows} linker option must be specified.
25953
25954 @smallexample
25955 $ gnatmake winprog -largs -mwindows
25956 @end smallexample
25957
25958 @node Temporary Files
25959 @section Temporary Files
25960 @cindex Temporary files
25961
25962 @noindent
25963 It is possible to control where temporary files gets created by setting
25964 the TMP environment variable. The file will be created:
25965
25966 @itemize
25967 @item Under the directory pointed to by the TMP environment variable if
25968 this directory exists.
25969
25970 @item Under c:\temp, if the TMP environment variable is not set (or not
25971 pointing to a directory) and if this directory exists.
25972
25973 @item Under the current working directory otherwise.
25974 @end itemize
25975
25976 @noindent
25977 This allows you to determine exactly where the temporary
25978 file will be created. This is particularly useful in networked
25979 environments where you may not have write access to some
25980 directories.
25981
25982 @node Mixed-Language Programming on Windows
25983 @section Mixed-Language Programming on Windows
25984
25985 @noindent
25986 Developing pure Ada applications on Windows is no different than on
25987 other GNAT-supported platforms. However, when developing or porting an
25988 application that contains a mix of Ada and C/C++, the choice of your
25989 Windows C/C++ development environment conditions your overall
25990 interoperability strategy.
25991
25992 If you use @code{gcc} to compile the non-Ada part of your application,
25993 there are no Windows-specific restrictions that affect the overall
25994 interoperability with your Ada code. If you plan to use
25995 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
25996 the following limitations:
25997
25998 @itemize @bullet
25999 @item
26000 You cannot link your Ada code with an object or library generated with
26001 Microsoft tools if these use the @code{.tls} section (Thread Local
26002 Storage section) since the GNAT linker does not yet support this section.
26003
26004 @item
26005 You cannot link your Ada code with an object or library generated with
26006 Microsoft tools if these use I/O routines other than those provided in
26007 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
26008 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
26009 libraries can cause a conflict with @code{msvcrt.dll} services. For
26010 instance Visual C++ I/O stream routines conflict with those in
26011 @code{msvcrt.dll}.
26012 @end itemize
26013
26014 @noindent
26015 If you do want to use the Microsoft tools for your non-Ada code and hit one
26016 of the above limitations, you have two choices:
26017
26018 @enumerate
26019 @item
26020 Encapsulate your non Ada code in a DLL to be linked with your Ada
26021 application. In this case, use the Microsoft or whatever environment to
26022 build the DLL and use GNAT to build your executable
26023 (@pxref{Using DLLs with GNAT}).
26024
26025 @item
26026 Or you can encapsulate your Ada code in a DLL to be linked with the
26027 other part of your application. In this case, use GNAT to build the DLL
26028 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
26029 environment to build your executable.
26030 @end enumerate
26031
26032 @node Windows Calling Conventions
26033 @section Windows Calling Conventions
26034 @findex Stdcall
26035 @findex APIENTRY
26036
26037 @menu
26038 * C Calling Convention::
26039 * Stdcall Calling Convention::
26040 * DLL Calling Convention::
26041 @end menu
26042
26043 @noindent
26044 When a subprogram @code{F} (caller) calls a subprogram @code{G}
26045 (callee), there are several ways to push @code{G}'s parameters on the
26046 stack and there are several possible scenarios to clean up the stack
26047 upon @code{G}'s return. A calling convention is an agreed upon software
26048 protocol whereby the responsibilities between the caller (@code{F}) and
26049 the callee (@code{G}) are clearly defined. Several calling conventions
26050 are available for Windows:
26051
26052 @itemize @bullet
26053 @item
26054 @code{C} (Microsoft defined)
26055
26056 @item
26057 @code{Stdcall} (Microsoft defined)
26058
26059 @item
26060 @code{DLL} (GNAT specific)
26061 @end itemize
26062
26063 @node C Calling Convention
26064 @subsection @code{C} Calling Convention
26065
26066 @noindent
26067 This is the default calling convention used when interfacing to C/C++
26068 routines compiled with either @code{gcc} or Microsoft Visual C++.
26069
26070 In the @code{C} calling convention subprogram parameters are pushed on the
26071 stack by the caller from right to left. The caller itself is in charge of
26072 cleaning up the stack after the call. In addition, the name of a routine
26073 with @code{C} calling convention is mangled by adding a leading underscore.
26074
26075 The name to use on the Ada side when importing (or exporting) a routine
26076 with @code{C} calling convention is the name of the routine. For
26077 instance the C function:
26078
26079 @smallexample
26080 int get_val (long);
26081 @end smallexample
26082
26083 @noindent
26084 should be imported from Ada as follows:
26085
26086 @smallexample @c ada
26087 @group
26088 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26089 pragma Import (C, Get_Val, External_Name => "get_val");
26090 @end group
26091 @end smallexample
26092
26093 @noindent
26094 Note that in this particular case the @code{External_Name} parameter could
26095 have been omitted since, when missing, this parameter is taken to be the
26096 name of the Ada entity in lower case. When the @code{Link_Name} parameter
26097 is missing, as in the above example, this parameter is set to be the
26098 @code{External_Name} with a leading underscore.
26099
26100 When importing a variable defined in C, you should always use the @code{C}
26101 calling convention unless the object containing the variable is part of a
26102 DLL (in which case you should use the @code{DLL} calling convention,
26103 @pxref{DLL Calling Convention}).
26104
26105 @node Stdcall Calling Convention
26106 @subsection @code{Stdcall} Calling Convention
26107
26108 @noindent
26109 This convention, which was the calling convention used for Pascal
26110 programs, is used by Microsoft for all the routines in the Win32 API for
26111 efficiency reasons. It must be used to import any routine for which this
26112 convention was specified.
26113
26114 In the @code{Stdcall} calling convention subprogram parameters are pushed
26115 on the stack by the caller from right to left. The callee (and not the
26116 caller) is in charge of cleaning the stack on routine exit. In addition,
26117 the name of a routine with @code{Stdcall} calling convention is mangled by
26118 adding a leading underscore (as for the @code{C} calling convention) and a
26119 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
26120 bytes) of the parameters passed to the routine.
26121
26122 The name to use on the Ada side when importing a C routine with a
26123 @code{Stdcall} calling convention is the name of the C routine. The leading
26124 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
26125 the compiler. For instance the Win32 function:
26126
26127 @smallexample
26128 @b{APIENTRY} int get_val (long);
26129 @end smallexample
26130
26131 @noindent
26132 should be imported from Ada as follows:
26133
26134 @smallexample @c ada
26135 @group
26136 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26137 pragma Import (Stdcall, Get_Val);
26138 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
26139 @end group
26140 @end smallexample
26141
26142 @noindent
26143 As for the @code{C} calling convention, when the @code{External_Name}
26144 parameter is missing, it is taken to be the name of the Ada entity in lower
26145 case. If instead of writing the above import pragma you write:
26146
26147 @smallexample @c ada
26148 @group
26149 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26150 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
26151 @end group
26152 @end smallexample
26153
26154 @noindent
26155 then the imported routine is @code{_retrieve_val@@4}. However, if instead
26156 of specifying the @code{External_Name} parameter you specify the
26157 @code{Link_Name} as in the following example:
26158
26159 @smallexample @c ada
26160 @group
26161 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
26162 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
26163 @end group
26164 @end smallexample
26165
26166 @noindent
26167 then the imported routine is @code{retrieve_val@@4}, that is, there is no
26168 trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
26169 added at the end of the @code{Link_Name} by the compiler.
26170
26171 @noindent
26172 Note, that in some special cases a DLL's entry point name lacks a trailing
26173 @code{@@}@code{@i{nn}} while the exported name generated for a call has it.
26174 The @code{gnatdll} tool, which creates the import library for the DLL, is able
26175 to handle those cases (see the description of the switches in
26176 @pxref{Using gnatdll} section).
26177
26178 @node DLL Calling Convention
26179 @subsection @code{DLL} Calling Convention
26180
26181 @noindent
26182 This convention, which is GNAT-specific, must be used when you want to
26183 import in Ada a variables defined in a DLL. For functions and procedures
26184 this convention is equivalent to the @code{Stdcall} convention. As an
26185 example, if a DLL contains a variable defined as:
26186
26187 @smallexample
26188 int my_var;
26189 @end smallexample
26190
26191 @noindent
26192 then, to access this variable from Ada you should write:
26193
26194 @smallexample @c ada
26195 @group
26196 My_Var : Interfaces.C.int;
26197 pragma Import (DLL, My_Var);
26198 @end group
26199 @end smallexample
26200
26201 The remarks concerning the @code{External_Name} and @code{Link_Name}
26202 parameters given in the previous sections equally apply to the @code{DLL}
26203 calling convention.
26204
26205 @node Introduction to Dynamic Link Libraries (DLLs)
26206 @section Introduction to Dynamic Link Libraries (DLLs)
26207 @findex DLL
26208
26209 @noindent
26210 A Dynamically Linked Library (DLL) is a library that can be shared by
26211 several applications running under Windows. A DLL can contain any number of
26212 routines and variables.
26213
26214 One advantage of DLLs is that you can change and enhance them without
26215 forcing all the applications that depend on them to be relinked or
26216 recompiled. However, you should be aware than all calls to DLL routines are
26217 slower since, as you will understand below, such calls are indirect.
26218
26219 To illustrate the remainder of this section, suppose that an application
26220 wants to use the services of a DLL @file{API.dll}. To use the services
26221 provided by @file{API.dll} you must statically link against an import
26222 library which contains a jump table with an entry for each routine and
26223 variable exported by the DLL. In the Microsoft world this import library is
26224 called @file{API.lib}. When using GNAT this import library is called either
26225 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
26226
26227 After you have statically linked your application with the import library
26228 and you run your application, here is what happens:
26229
26230 @enumerate
26231 @item
26232 Your application is loaded into memory.
26233
26234 @item
26235 The DLL @file{API.dll} is mapped into the address space of your
26236 application. This means that:
26237
26238 @itemize @bullet
26239 @item
26240 The DLL will use the stack of the calling thread.
26241
26242 @item
26243 The DLL will use the virtual address space of the calling process.
26244
26245 @item
26246 The DLL will allocate memory from the virtual address space of the calling
26247 process.
26248
26249 @item
26250 Handles (pointers) can be safely exchanged between routines in the DLL
26251 routines and routines in the application using the DLL.
26252 @end itemize
26253
26254 @item
26255 The entries in the @file{libAPI.a} or @file{API.lib} jump table which is
26256 part of your application are initialized with the addresses of the routines
26257 and variables in @file{API.dll}.
26258
26259 @item
26260 If present in @file{API.dll}, routines @code{DllMain} or
26261 @code{DllMainCRTStartup} are invoked. These routines typically contain
26262 the initialization code needed for the well-being of the routines and
26263 variables exported by the DLL.
26264 @end enumerate
26265
26266 @noindent
26267 There is an additional point which is worth mentioning. In the Windows
26268 world there are two kind of DLLs: relocatable and non-relocatable
26269 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
26270 in the target application address space. If the addresses of two
26271 non-relocatable DLLs overlap and these happen to be used by the same
26272 application, a conflict will occur and the application will run
26273 incorrectly. Hence, when possible, it is always preferable to use and
26274 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
26275 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
26276 User's Guide) removes the debugging symbols from the DLL but the DLL can
26277 still be relocated.
26278
26279 As a side note, an interesting difference between Microsoft DLLs and
26280 Unix shared libraries, is the fact that on most Unix systems all public
26281 routines are exported by default in a Unix shared library, while under
26282 Windows the exported routines must be listed explicitly in a definition
26283 file (@pxref{The Definition File}).
26284
26285 @node Using DLLs with GNAT
26286 @section Using DLLs with GNAT
26287
26288 @menu
26289 * Creating an Ada Spec for the DLL Services::
26290 * Creating an Import Library::
26291 @end menu
26292
26293 @noindent
26294 To use the services of a DLL, say @file{API.dll}, in your Ada application
26295 you must have:
26296
26297 @enumerate
26298 @item
26299 The Ada spec for the routines and/or variables you want to access in
26300 @file{API.dll}. If not available this Ada spec must be built from the C/C++
26301 header files provided with the DLL.
26302
26303 @item
26304 The import library (@file{libAPI.a} or @file{API.lib}). As previously
26305 mentioned an import library is a statically linked library containing the
26306 import table which will be filled at load time to point to the actual
26307 @file{API.dll} routines. Sometimes you don't have an import library for the
26308 DLL you want to use. The following sections will explain how to build one.
26309
26310 @item
26311 The actual DLL, @file{API.dll}.
26312 @end enumerate
26313
26314 @noindent
26315 Once you have all the above, to compile an Ada application that uses the
26316 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
26317 you simply issue the command
26318
26319 @smallexample
26320 $ gnatmake my_ada_app -largs -lAPI
26321 @end smallexample
26322
26323 @noindent
26324 The argument @option{-largs -lAPI} at the end of the @code{gnatmake} command
26325 tells the GNAT linker to look first for a library named @file{API.lib}
26326 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
26327 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
26328 contains the following pragma
26329
26330 @smallexample @c ada
26331 pragma Linker_Options ("-lAPI");
26332 @end smallexample
26333
26334 @noindent
26335 you do not have to add @option{-largs -lAPI} at the end of the @code{gnatmake}
26336 command.
26337
26338 If any one of the items above is missing you will have to create it
26339 yourself. The following sections explain how to do so using as an
26340 example a fictitious DLL called @file{API.dll}.
26341
26342 @node Creating an Ada Spec for the DLL Services
26343 @subsection Creating an Ada Spec for the DLL Services
26344
26345 @noindent
26346 A DLL typically comes with a C/C++ header file which provides the
26347 definitions of the routines and variables exported by the DLL. The Ada
26348 equivalent of this header file is a package spec that contains definitions
26349 for the imported entities. If the DLL you intend to use does not come with
26350 an Ada spec you have to generate one such spec yourself. For example if
26351 the header file of @file{API.dll} is a file @file{api.h} containing the
26352 following two definitions:
26353
26354 @smallexample
26355 @group
26356 @cartouche
26357 int some_var;
26358 int get (char *);
26359 @end cartouche
26360 @end group
26361 @end smallexample
26362
26363 @noindent
26364 then the equivalent Ada spec could be:
26365
26366 @smallexample @c ada
26367 @group
26368 @cartouche
26369 with Interfaces.C.Strings;
26370 package API is
26371    use Interfaces;
26372
26373    Some_Var : C.int;
26374    function Get (Str : C.Strings.Chars_Ptr) return C.int;
26375
26376 private
26377    pragma Import (C, Get);
26378    pragma Import (DLL, Some_Var);
26379 end API;
26380 @end cartouche
26381 @end group
26382 @end smallexample
26383
26384 @noindent
26385 Note that a variable is @strong{always imported with a DLL convention}. A
26386 function can have @code{C}, @code{Stdcall} or @code{DLL} convention. For
26387 subprograms, the @code{DLL} convention is a synonym of @code{Stdcall}
26388 (@pxref{Windows Calling Conventions}).
26389
26390 @node Creating an Import Library
26391 @subsection Creating an Import Library
26392 @cindex Import library
26393
26394 @menu
26395 * The Definition File::
26396 * GNAT-Style Import Library::
26397 * Microsoft-Style Import Library::
26398 @end menu
26399
26400 @noindent
26401 If a Microsoft-style import library @file{API.lib} or a GNAT-style
26402 import library @file{libAPI.a} is available with @file{API.dll} you
26403 can skip this section. Otherwise read on.
26404
26405 @node The Definition File
26406 @subsubsection The Definition File
26407 @cindex Definition file
26408 @findex .def
26409
26410 @noindent
26411 As previously mentioned, and unlike Unix systems, the list of symbols
26412 that are exported from a DLL must be provided explicitly in Windows.
26413 The main goal of a definition file is precisely that: list the symbols
26414 exported by a DLL. A definition file (usually a file with a @code{.def}
26415 suffix) has the following structure:
26416
26417 @smallexample
26418 @group
26419 @cartouche
26420 [LIBRARY @i{name}]
26421 [DESCRIPTION @i{string}]
26422 EXPORTS
26423    @i{symbol1}
26424    @i{symbol2}
26425    ...
26426 @end cartouche
26427 @end group
26428 @end smallexample
26429
26430 @table @code
26431 @item LIBRARY @i{name}
26432 This section, which is optional, gives the name of the DLL.
26433
26434 @item DESCRIPTION @i{string}
26435 This section, which is optional, gives a description string that will be
26436 embedded in the import library.
26437
26438 @item EXPORTS
26439 This section gives the list of exported symbols (procedures, functions or
26440 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
26441 section of @file{API.def} looks like:
26442
26443 @smallexample
26444 @group
26445 @cartouche
26446 EXPORTS
26447    some_var
26448    get
26449 @end cartouche
26450 @end group
26451 @end smallexample
26452 @end table
26453
26454 @noindent
26455 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
26456 (@pxref{Windows Calling Conventions}) for a Stdcall
26457 calling convention function in the exported symbols list.
26458
26459 @noindent
26460 There can actually be other sections in a definition file, but these
26461 sections are not relevant to the discussion at hand.
26462
26463 @node GNAT-Style Import Library
26464 @subsubsection GNAT-Style Import Library
26465
26466 @noindent
26467 To create a static import library from @file{API.dll} with the GNAT tools
26468 you should proceed as follows:
26469
26470 @enumerate
26471 @item
26472 Create the definition file @file{API.def} (@pxref{The Definition File}).
26473 For that use the @code{dll2def} tool as follows:
26474
26475 @smallexample
26476 $ dll2def API.dll > API.def
26477 @end smallexample
26478
26479 @noindent
26480 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
26481 to standard output the list of entry points in the DLL. Note that if
26482 some routines in the DLL have the @code{Stdcall} convention
26483 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
26484 suffix then you'll have to edit @file{api.def} to add it.
26485
26486 @noindent
26487 Here are some hints to find the right @code{@@}@i{nn} suffix.
26488
26489 @enumerate
26490 @item
26491 If you have the Microsoft import library (.lib), it is possible to get
26492 the right symbols by using Microsoft @code{dumpbin} tool (see the
26493 corresponding Microsoft documentation for further details).
26494
26495 @smallexample
26496 $ dumpbin /exports api.lib
26497 @end smallexample
26498
26499 @item
26500 If you have a message about a missing symbol at link time the compiler
26501 tells you what symbol is expected. You just have to go back to the
26502 definition file and add the right suffix.
26503 @end enumerate
26504
26505 @item
26506 Build the import library @code{libAPI.a}, using @code{gnatdll}
26507 (@pxref{Using gnatdll}) as follows:
26508
26509 @smallexample
26510 $ gnatdll -e API.def -d API.dll
26511 @end smallexample
26512
26513 @noindent
26514 @code{gnatdll} takes as input a definition file @file{API.def} and the
26515 name of the DLL containing the services listed in the definition file
26516 @file{API.dll}. The name of the static import library generated is
26517 computed from the name of the definition file as follows: if the
26518 definition file name is @i{xyz}@code{.def}, the import library name will
26519 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
26520 @option{-e} could have been removed because the name of the definition
26521 file (before the ``@code{.def}'' suffix) is the same as the name of the
26522 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
26523 @end enumerate
26524
26525 @node Microsoft-Style Import Library
26526 @subsubsection Microsoft-Style Import Library
26527
26528 @noindent
26529 With GNAT you can either use a GNAT-style or Microsoft-style import
26530 library. A Microsoft import library is needed only if you plan to make an
26531 Ada DLL available to applications developed with Microsoft
26532 tools (@pxref{Mixed-Language Programming on Windows}).
26533
26534 To create a Microsoft-style import library for @file{API.dll} you
26535 should proceed as follows:
26536
26537 @enumerate
26538 @item
26539 Create the definition file @file{API.def} from the DLL. For this use either
26540 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
26541 tool (see the corresponding Microsoft documentation for further details).
26542
26543 @item
26544 Build the actual import library using Microsoft's @code{lib} utility:
26545
26546 @smallexample
26547 $ lib -machine:IX86 -def:API.def -out:API.lib
26548 @end smallexample
26549
26550 @noindent
26551 If you use the above command the definition file @file{API.def} must
26552 contain a line giving the name of the DLL:
26553
26554 @smallexample
26555 LIBRARY      "API"
26556 @end smallexample
26557
26558 @noindent
26559 See the Microsoft documentation for further details about the usage of
26560 @code{lib}.
26561 @end enumerate
26562
26563 @node Building DLLs with GNAT
26564 @section Building DLLs with GNAT
26565 @cindex DLLs, building
26566
26567 @menu
26568 * Limitations When Using Ada DLLs from Ada::
26569 * Exporting Ada Entities::
26570 * Ada DLLs and Elaboration::
26571 * Ada DLLs and Finalization::
26572 * Creating a Spec for Ada DLLs::
26573 * Creating the Definition File::
26574 * Using gnatdll::
26575 @end menu
26576
26577 @noindent
26578 This section explains how to build DLLs containing Ada code. These DLLs
26579 will be referred to as Ada DLLs in the remainder of this section.
26580
26581 The steps required to build an Ada DLL that is to be used by Ada as well as
26582 non-Ada applications are as follows:
26583
26584 @enumerate
26585 @item
26586 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
26587 @code{Stdcall} calling convention to avoid any Ada name mangling for the
26588 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
26589 skip this step if you plan to use the Ada DLL only from Ada applications.
26590
26591 @item
26592 Your Ada code must export an initialization routine which calls the routine
26593 @code{adainit} generated by @code{gnatbind} to perform the elaboration of
26594 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
26595 routine exported by the Ada DLL must be invoked by the clients of the DLL
26596 to initialize the DLL.
26597
26598 @item
26599 When useful, the DLL should also export a finalization routine which calls
26600 routine @code{adafinal} generated by @code{gnatbind} to perform the
26601 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
26602 The finalization routine exported by the Ada DLL must be invoked by the
26603 clients of the DLL when the DLL services are no further needed.
26604
26605 @item
26606 You must provide a spec for the services exported by the Ada DLL in each
26607 of the programming languages to which you plan to make the DLL available.
26608
26609 @item
26610 You must provide a definition file listing the exported entities
26611 (@pxref{The Definition File}).
26612
26613 @item
26614 Finally you must use @code{gnatdll} to produce the DLL and the import
26615 library (@pxref{Using gnatdll}).
26616 @end enumerate
26617
26618 @noindent
26619 Note that a relocatable DLL stripped using the @code{strip} binutils
26620 tool will not be relocatable anymore. To build a DLL without debug
26621 information pass @code{-largs -s} to @code{gnatdll}.
26622
26623 @node Limitations When Using Ada DLLs from Ada
26624 @subsection Limitations When Using Ada DLLs from Ada
26625
26626 @noindent
26627 When using Ada DLLs from Ada applications there is a limitation users
26628 should be aware of. Because on Windows the GNAT run time is not in a DLL of
26629 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
26630 each Ada DLL includes the services of the GNAT run time that are necessary
26631 to the Ada code inside the DLL. As a result, when an Ada program uses an
26632 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
26633 one in the main program.
26634
26635 It is therefore not possible to exchange GNAT run-time objects between the
26636 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
26637 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
26638 types, etc.
26639
26640 It is completely safe to exchange plain elementary, array or record types,
26641 Windows object handles, etc.
26642
26643 @node Exporting Ada Entities
26644 @subsection Exporting Ada Entities
26645 @cindex Export table
26646
26647 @noindent
26648 Building a DLL is a way to encapsulate a set of services usable from any
26649 application. As a result, the Ada entities exported by a DLL should be
26650 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
26651 any Ada name mangling. Please note that the @code{Stdcall} convention
26652 should only be used for subprograms, not for variables. As an example here
26653 is an Ada package @code{API}, spec and body, exporting two procedures, a
26654 function, and a variable:
26655
26656 @smallexample @c ada
26657 @group
26658 @cartouche
26659 with Interfaces.C; use Interfaces;
26660 package API is
26661    Count : C.int := 0;
26662    function Factorial (Val : C.int) return C.int;
26663
26664    procedure Initialize_API;
26665    procedure Finalize_API;
26666    --  Initialization & Finalization routines. More in the next section.
26667 private
26668    pragma Export (C, Initialize_API);
26669    pragma Export (C, Finalize_API);
26670    pragma Export (C, Count);
26671    pragma Export (C, Factorial);
26672 end API;
26673 @end cartouche
26674 @end group
26675 @end smallexample
26676
26677 @smallexample @c ada
26678 @group
26679 @cartouche
26680 package body API is
26681    function Factorial (Val : C.int) return C.int is
26682       Fact : C.int := 1;
26683    begin
26684       Count := Count + 1;
26685       for K in 1 .. Val loop
26686          Fact := Fact * K;
26687       end loop;
26688       return Fact;
26689    end Factorial;
26690
26691    procedure Initialize_API is
26692       procedure Adainit;
26693       pragma Import (C, Adainit);
26694    begin
26695       Adainit;
26696    end Initialize_API;
26697
26698    procedure Finalize_API is
26699       procedure Adafinal;
26700       pragma Import (C, Adafinal);
26701    begin
26702       Adafinal;
26703    end Finalize_API;
26704 end API;
26705 @end cartouche
26706 @end group
26707 @end smallexample
26708
26709 @noindent
26710 If the Ada DLL you are building will only be used by Ada applications
26711 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
26712 convention. As an example, the previous package could be written as
26713 follows:
26714
26715 @smallexample @c ada
26716 @group
26717 @cartouche
26718 package API is
26719    Count : Integer := 0;
26720    function Factorial (Val : Integer) return Integer;
26721
26722    procedure Initialize_API;
26723    procedure Finalize_API;
26724    --  Initialization and Finalization routines.
26725 end API;
26726 @end cartouche
26727 @end group
26728 @end smallexample
26729
26730 @smallexample @c ada
26731 @group
26732 @cartouche
26733 package body API is
26734    function Factorial (Val : Integer) return Integer is
26735       Fact : Integer := 1;
26736    begin
26737       Count := Count + 1;
26738       for K in 1 .. Val loop
26739          Fact := Fact * K;
26740       end loop;
26741       return Fact;
26742    end Factorial;
26743
26744    ...
26745    --  The remainder of this package body is unchanged.
26746 end API;
26747 @end cartouche
26748 @end group
26749 @end smallexample
26750
26751 @noindent
26752 Note that if you do not export the Ada entities with a @code{C} or
26753 @code{Stdcall} convention you will have to provide the mangled Ada names
26754 in the definition file of the Ada DLL
26755 (@pxref{Creating the Definition File}).
26756
26757 @node Ada DLLs and Elaboration
26758 @subsection Ada DLLs and Elaboration
26759 @cindex DLLs and elaboration
26760
26761 @noindent
26762 The DLL that you are building contains your Ada code as well as all the
26763 routines in the Ada library that are needed by it. The first thing a
26764 user of your DLL must do is elaborate the Ada code
26765 (@pxref{Elaboration Order Handling in GNAT}).
26766
26767 To achieve this you must export an initialization routine
26768 (@code{Initialize_API} in the previous example), which must be invoked
26769 before using any of the DLL services. This elaboration routine must call
26770 the Ada elaboration routine @code{adainit} generated by the GNAT binder
26771 (@pxref{Binding with Non-Ada Main Programs}). See the body of
26772 @code{Initialize_Api} for an example. Note that the GNAT binder is
26773 automatically invoked during the DLL build process by the @code{gnatdll}
26774 tool (@pxref{Using gnatdll}).
26775
26776 When a DLL is loaded, Windows systematically invokes a routine called
26777 @code{DllMain}. It would therefore be possible to call @code{adainit}
26778 directly from @code{DllMain} without having to provide an explicit
26779 initialization routine. Unfortunately, it is not possible to call
26780 @code{adainit} from the @code{DllMain} if your program has library level
26781 tasks because access to the @code{DllMain} entry point is serialized by
26782 the system (that is, only a single thread can execute ``through'' it at a
26783 time), which means that the GNAT run time will deadlock waiting for the
26784 newly created task to complete its initialization.
26785
26786 @node Ada DLLs and Finalization
26787 @subsection Ada DLLs and Finalization
26788 @cindex DLLs and finalization
26789
26790 @noindent
26791 When the services of an Ada DLL are no longer needed, the client code should
26792 invoke the DLL finalization routine, if available. The DLL finalization
26793 routine is in charge of releasing all resources acquired by the DLL. In the
26794 case of the Ada code contained in the DLL, this is achieved by calling
26795 routine @code{adafinal} generated by the GNAT binder
26796 (@pxref{Binding with Non-Ada Main Programs}).
26797 See the body of @code{Finalize_Api} for an
26798 example. As already pointed out the GNAT binder is automatically invoked
26799 during the DLL build process by the @code{gnatdll} tool
26800 (@pxref{Using gnatdll}).
26801
26802 @node Creating a Spec for Ada DLLs
26803 @subsection Creating a Spec for Ada DLLs
26804
26805 @noindent
26806 To use the services exported by the Ada DLL from another programming
26807 language (e.g. C), you have to translate the specs of the exported Ada
26808 entities in that language. For instance in the case of @code{API.dll},
26809 the corresponding C header file could look like:
26810
26811 @smallexample
26812 @group
26813 @cartouche
26814 extern int *_imp__count;
26815 #define count (*_imp__count)
26816 int factorial (int);
26817 @end cartouche
26818 @end group
26819 @end smallexample
26820
26821 @noindent
26822 It is important to understand that when building an Ada DLL to be used by
26823 other Ada applications, you need two different specs for the packages
26824 contained in the DLL: one for building the DLL and the other for using
26825 the DLL. This is because the @code{DLL} calling convention is needed to
26826 use a variable defined in a DLL, but when building the DLL, the variable
26827 must have either the @code{Ada} or @code{C} calling convention. As an
26828 example consider a DLL comprising the following package @code{API}:
26829
26830 @smallexample @c ada
26831 @group
26832 @cartouche
26833 package API is
26834    Count : Integer := 0;
26835    ...
26836    --  Remainder of the package omitted.
26837 end API;
26838 @end cartouche
26839 @end group
26840 @end smallexample
26841
26842 @noindent
26843 After producing a DLL containing package @code{API}, the spec that
26844 must be used to import @code{API.Count} from Ada code outside of the
26845 DLL is:
26846
26847 @smallexample @c ada
26848 @group
26849 @cartouche
26850 package API is
26851    Count : Integer;
26852    pragma Import (DLL, Count);
26853 end API;
26854 @end cartouche
26855 @end group
26856 @end smallexample
26857
26858 @node Creating the Definition File
26859 @subsection Creating the Definition File
26860
26861 @noindent
26862 The definition file is the last file needed to build the DLL. It lists
26863 the exported symbols. As an example, the definition file for a DLL
26864 containing only package @code{API} (where all the entities are exported
26865 with a @code{C} calling convention) is:
26866
26867 @smallexample
26868 @group
26869 @cartouche
26870 EXPORTS
26871     count
26872     factorial
26873     finalize_api
26874     initialize_api
26875 @end cartouche
26876 @end group
26877 @end smallexample
26878
26879 @noindent
26880 If the @code{C} calling convention is missing from package @code{API},
26881 then the definition file contains the mangled Ada names of the above
26882 entities, which in this case are:
26883
26884 @smallexample
26885 @group
26886 @cartouche
26887 EXPORTS
26888     api__count
26889     api__factorial
26890     api__finalize_api
26891     api__initialize_api
26892 @end cartouche
26893 @end group
26894 @end smallexample
26895
26896 @node Using gnatdll
26897 @subsection Using @code{gnatdll}
26898 @findex gnatdll
26899
26900 @menu
26901 * gnatdll Example::
26902 * gnatdll behind the Scenes::
26903 * Using dlltool::
26904 @end menu
26905
26906 @noindent
26907 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
26908 and non-Ada sources that make up your DLL have been compiled.
26909 @code{gnatdll} is actually in charge of two distinct tasks: build the
26910 static import library for the DLL and the actual DLL. The form of the
26911 @code{gnatdll} command is
26912
26913 @smallexample
26914 @cartouche
26915 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
26916 @end cartouche
26917 @end smallexample
26918
26919 @noindent
26920 where @i{list-of-files} is a list of ALI and object files. The object
26921 file list must be the exact list of objects corresponding to the non-Ada
26922 sources whose services are to be included in the DLL. The ALI file list
26923 must be the exact list of ALI files for the corresponding Ada sources
26924 whose services are to be included in the DLL. If @i{list-of-files} is
26925 missing, only the static import library is generated.
26926
26927 @noindent
26928 You may specify any of the following switches to @code{gnatdll}:
26929
26930 @table @code
26931 @item -a[@var{address}]
26932 @cindex @option{-a} (@code{gnatdll})
26933 Build a non-relocatable DLL at @var{address}. If @var{address} is not
26934 specified the default address @var{0x11000000} will be used. By default,
26935 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
26936 advise the reader to build relocatable DLL.
26937
26938 @item -b @var{address}
26939 @cindex @option{-b} (@code{gnatdll})
26940 Set the relocatable DLL base address. By default the address is
26941 @var{0x11000000}.
26942
26943 @item -bargs @var{opts}
26944 @cindex @option{-bargs} (@code{gnatdll})
26945 Binder options. Pass @var{opts} to the binder.
26946
26947 @item -d @var{dllfile}
26948 @cindex @option{-d} (@code{gnatdll})
26949 @var{dllfile} is the name of the DLL. This switch must be present for
26950 @code{gnatdll} to do anything. The name of the generated import library is
26951 obtained algorithmically from @var{dllfile} as shown in the following
26952 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
26953 @code{libxyz.a}. The name of the definition file to use (if not specified
26954 by option @option{-e}) is obtained algorithmically from @var{dllfile}
26955 as shown in the following example:
26956 if @var{dllfile} is @code{xyz.dll}, the definition
26957 file used is @code{xyz.def}.
26958
26959 @item -e @var{deffile}
26960 @cindex @option{-e} (@code{gnatdll})
26961 @var{deffile} is the name of the definition file.
26962
26963 @item -g
26964 @cindex @option{-g} (@code{gnatdll})
26965 Generate debugging information. This information is stored in the object
26966 file and copied from there to the final DLL file by the linker,
26967 where it can be read by the debugger. You must use the
26968 @option{-g} switch if you plan on using the debugger or the symbolic
26969 stack traceback.
26970
26971 @item -h
26972 @cindex @option{-h} (@code{gnatdll})
26973 Help mode. Displays @code{gnatdll} switch usage information.
26974
26975 @item -Idir
26976 @cindex @option{-I} (@code{gnatdll})
26977 Direct @code{gnatdll} to search the @var{dir} directory for source and
26978 object files needed to build the DLL.
26979 (@pxref{Search Paths and the Run-Time Library (RTL)}).
26980
26981 @item -k
26982 @cindex @option{-k} (@code{gnatdll})
26983 Removes the @code{@@}@i{nn} suffix from the import library's exported
26984 names. You must specified this option if you want to use a
26985 @code{Stdcall} function in a DLL for which the @code{@@}@i{nn} suffix
26986 has been removed. This is the case for most of the Windows NT DLL for
26987 example. This option has no effect when @option{-n} option is specified.
26988
26989 @item -l @var{file}
26990 @cindex @option{-l} (@code{gnatdll})
26991 The list of ALI and object files used to build the DLL are listed in
26992 @var{file}, instead of being given in the command line. Each line in
26993 @var{file} contains the name of an ALI or object file.
26994
26995 @item -n
26996 @cindex @option{-n} (@code{gnatdll})
26997 No Import. Do not create the import library.
26998
26999 @item -q
27000 @cindex @option{-q} (@code{gnatdll})
27001 Quiet mode. Do not display unnecessary messages.
27002
27003 @item -v
27004 @cindex @option{-v} (@code{gnatdll})
27005 Verbose mode. Display extra information.
27006
27007 @item -largs @var{opts}
27008 @cindex @option{-largs} (@code{gnatdll})
27009 Linker options. Pass @var{opts} to the linker.
27010 @end table
27011
27012 @node gnatdll Example
27013 @subsubsection @code{gnatdll} Example
27014
27015 @noindent
27016 As an example the command to build a relocatable DLL from @file{api.adb}
27017 once @file{api.adb} has been compiled and @file{api.def} created is
27018
27019 @smallexample
27020 $ gnatdll -d api.dll api.ali
27021 @end smallexample
27022
27023 @noindent
27024 The above command creates two files: @file{libapi.a} (the import
27025 library) and @file{api.dll} (the actual DLL). If you want to create
27026 only the DLL, just type:
27027
27028 @smallexample
27029 $ gnatdll -d api.dll -n api.ali
27030 @end smallexample
27031
27032 @noindent
27033 Alternatively if you want to create just the import library, type:
27034
27035 @smallexample
27036 $ gnatdll -d api.dll
27037 @end smallexample
27038
27039 @node gnatdll behind the Scenes
27040 @subsubsection @code{gnatdll} behind the Scenes
27041
27042 @noindent
27043 This section details the steps involved in creating a DLL. @code{gnatdll}
27044 does these steps for you. Unless you are interested in understanding what
27045 goes on behind the scenes, you should skip this section.
27046
27047 We use the previous example of a DLL containing the Ada package @code{API},
27048 to illustrate the steps necessary to build a DLL. The starting point is a
27049 set of objects that will make up the DLL and the corresponding ALI
27050 files. In the case of this example this means that @file{api.o} and
27051 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
27052 the following:
27053
27054 @enumerate
27055 @item
27056 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
27057 the information necessary to generate relocation information for the
27058 DLL.
27059
27060 @smallexample
27061 @group
27062 $ gnatbind -n api
27063 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
27064 @end group
27065 @end smallexample
27066
27067 @noindent
27068 In addition to the base file, the @code{gnatlink} command generates an
27069 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
27070 asks @code{gnatlink} to generate the routines @code{DllMain} and
27071 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
27072 is loaded into memory.
27073
27074 @item
27075 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
27076 export table (@file{api.exp}). The export table contains the relocation
27077 information in a form which can be used during the final link to ensure
27078 that the Windows loader is able to place the DLL anywhere in memory.
27079
27080 @smallexample
27081 @group
27082 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27083           --output-exp api.exp
27084 @end group
27085 @end smallexample
27086
27087 @item
27088 @code{gnatdll} builds the base file using the new export table. Note that
27089 @code{gnatbind} must be called once again since the binder generated file
27090 has been deleted during the previous call to @code{gnatlink}.
27091
27092 @smallexample
27093 @group
27094 $ gnatbind -n api
27095 $ gnatlink api -o api.jnk api.exp -mdll
27096       -Wl,--base-file,api.base
27097 @end group
27098 @end smallexample
27099
27100 @item
27101 @code{gnatdll} builds the new export table using the new base file and
27102 generates the DLL import library @file{libAPI.a}.
27103
27104 @smallexample
27105 @group
27106 $ dlltool --dllname api.dll --def api.def --base-file api.base \
27107           --output-exp api.exp --output-lib libAPI.a
27108 @end group
27109 @end smallexample
27110
27111 @item
27112 Finally @code{gnatdll} builds the relocatable DLL using the final export
27113 table.
27114
27115 @smallexample
27116 @group
27117 $ gnatbind -n api
27118 $ gnatlink api api.exp -o api.dll -mdll
27119 @end group
27120 @end smallexample
27121 @end enumerate
27122
27123 @node Using dlltool
27124 @subsubsection Using @code{dlltool}
27125
27126 @noindent
27127 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
27128 DLLs and static import libraries. This section summarizes the most
27129 common @code{dlltool} switches. The form of the @code{dlltool} command
27130 is
27131
27132 @smallexample
27133 $ dlltool [@var{switches}]
27134 @end smallexample
27135
27136 @noindent
27137 @code{dlltool} switches include:
27138
27139 @table @option
27140 @item --base-file @var{basefile}
27141 @cindex @option{--base-file} (@command{dlltool})
27142 Read the base file @var{basefile} generated by the linker. This switch
27143 is used to create a relocatable DLL.
27144
27145 @item --def @var{deffile}
27146 @cindex @option{--def} (@command{dlltool})
27147 Read the definition file.
27148
27149 @item --dllname @var{name}
27150 @cindex @option{--dllname} (@command{dlltool})
27151 Gives the name of the DLL. This switch is used to embed the name of the
27152 DLL in the static import library generated by @code{dlltool} with switch
27153 @option{--output-lib}.
27154
27155 @item -k
27156 @cindex @option{-k} (@command{dlltool})
27157 Kill @code{@@}@i{nn} from exported names
27158 (@pxref{Windows Calling Conventions}
27159 for a discussion about @code{Stdcall}-style symbols.
27160
27161 @item --help
27162 @cindex @option{--help} (@command{dlltool})
27163 Prints the @code{dlltool} switches with a concise description.
27164
27165 @item --output-exp @var{exportfile}
27166 @cindex @option{--output-exp} (@command{dlltool})
27167 Generate an export file @var{exportfile}. The export file contains the
27168 export table (list of symbols in the DLL) and is used to create the DLL.
27169
27170 @item --output-lib @i{libfile}
27171 @cindex @option{--output-lib} (@command{dlltool})
27172 Generate a static import library @var{libfile}.
27173
27174 @item -v
27175 @cindex @option{-v} (@command{dlltool})
27176 Verbose mode.
27177
27178 @item --as @i{assembler-name}
27179 @cindex @option{--as} (@command{dlltool})
27180 Use @i{assembler-name} as the assembler. The default is @code{as}.
27181 @end table
27182
27183 @node GNAT and Windows Resources
27184 @section GNAT and Windows Resources
27185 @cindex Resources, windows
27186
27187 @menu
27188 * Building Resources::
27189 * Compiling Resources::
27190 * Using Resources::
27191 @end menu
27192
27193 @noindent
27194 Resources are an easy way to add Windows specific objects to your
27195 application. The objects that can be added as resources include:
27196
27197 @itemize @bullet
27198 @item
27199 menus
27200
27201 @item
27202 accelerators
27203
27204 @item
27205 dialog boxes
27206
27207 @item
27208 string tables
27209
27210 @item
27211 bitmaps
27212
27213 @item
27214 cursors
27215
27216 @item
27217 icons
27218
27219 @item
27220 fonts
27221 @end itemize
27222
27223 @noindent
27224 This section explains how to build, compile and use resources.
27225
27226 @node Building Resources
27227 @subsection Building Resources
27228 @cindex Resources, building
27229
27230 @noindent
27231 A resource file is an ASCII file. By convention resource files have an
27232 @file{.rc} extension.
27233 The easiest way to build a resource file is to use Microsoft tools
27234 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
27235 @code{dlgedit.exe} to build dialogs.
27236 It is always possible to build an @file{.rc} file yourself by writing a
27237 resource script.
27238
27239 It is not our objective to explain how to write a resource file. A
27240 complete description of the resource script language can be found in the
27241 Microsoft documentation.
27242
27243 @node Compiling Resources
27244 @subsection Compiling Resources
27245 @findex rc
27246 @findex windres
27247 @cindex Resources, compiling
27248
27249 @noindent
27250 This section describes how to build a GNAT-compatible (COFF) object file
27251 containing the resources. This is done using the Resource Compiler
27252 @code{windres} as follows:
27253
27254 @smallexample
27255 $ windres -i myres.rc -o myres.o
27256 @end smallexample
27257
27258 @noindent
27259 By default @code{windres} will run @code{gcc} to preprocess the @file{.rc}
27260 file. You can specify an alternate preprocessor (usually named
27261 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
27262 parameter. A list of all possible options may be obtained by entering
27263 the command @code{windres} @option{--help}.
27264
27265 It is also possible to use the Microsoft resource compiler @code{rc.exe}
27266 to produce a @file{.res} file (binary resource file). See the
27267 corresponding Microsoft documentation for further details. In this case
27268 you need to use @code{windres} to translate the @file{.res} file to a
27269 GNAT-compatible object file as follows:
27270
27271 @smallexample
27272 $ windres -i myres.res -o myres.o
27273 @end smallexample
27274
27275 @node Using Resources
27276 @subsection Using Resources
27277 @cindex Resources, using
27278
27279 @noindent
27280 To include the resource file in your program just add the
27281 GNAT-compatible object file for the resource(s) to the linker
27282 arguments. With @code{gnatmake} this is done by using the @option{-largs}
27283 option:
27284
27285 @smallexample
27286 $ gnatmake myprog -largs myres.o
27287 @end smallexample
27288
27289 @node Debugging a DLL
27290 @section Debugging a DLL
27291 @cindex DLL debugging
27292
27293 @menu
27294 * Program and DLL Both Built with GCC/GNAT::
27295 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
27296 @end menu
27297
27298 @noindent
27299 Debugging a DLL is similar to debugging a standard program. But
27300 we have to deal with two different executable parts: the DLL and the
27301 program that uses it. We have the following four possibilities:
27302
27303 @enumerate 1
27304 @item
27305 The program and the DLL are built with @code{GCC/GNAT}.
27306 @item
27307 The program is built with foreign tools and the DLL is built with
27308 @code{GCC/GNAT}.
27309 @item
27310 The program is built with @code{GCC/GNAT} and the DLL is built with
27311 foreign tools.
27312 @item
27313 @end enumerate
27314
27315 @noindent
27316 In this section we address only cases one and two above.
27317 There is no point in trying to debug
27318 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
27319 information in it. To do so you must use a debugger compatible with the
27320 tools suite used to build the DLL.
27321
27322 @node Program and DLL Both Built with GCC/GNAT
27323 @subsection Program and DLL Both Built with GCC/GNAT
27324
27325 @noindent
27326 This is the simplest case. Both the DLL and the program have @code{GDB}
27327 compatible debugging information. It is then possible to break anywhere in
27328 the process. Let's suppose here that the main procedure is named
27329 @code{ada_main} and that in the DLL there is an entry point named
27330 @code{ada_dll}.
27331
27332 @noindent
27333 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
27334 program must have been built with the debugging information (see GNAT -g
27335 switch). Here are the step-by-step instructions for debugging it:
27336
27337 @enumerate 1
27338 @item Launch @code{GDB} on the main program.
27339
27340 @smallexample
27341 $ gdb -nw ada_main
27342 @end smallexample
27343
27344 @item Break on the main procedure and run the program.
27345
27346 @smallexample
27347 (gdb) break ada_main
27348 (gdb) run
27349 @end smallexample
27350
27351 @noindent
27352 This step is required to be able to set a breakpoint inside the DLL. As long
27353 as the program is not run, the DLL is not loaded. This has the
27354 consequence that the DLL debugging information is also not loaded, so it is not
27355 possible to set a breakpoint in the DLL.
27356
27357 @item Set a breakpoint inside the DLL
27358
27359 @smallexample
27360 (gdb) break ada_dll
27361 (gdb) run
27362 @end smallexample
27363
27364 @end enumerate
27365
27366 @noindent
27367 At this stage a breakpoint is set inside the DLL. From there on
27368 you can use the standard approach to debug the whole program
27369 (@pxref{Running and Debugging Ada Programs}).
27370
27371 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
27372 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
27373
27374 @menu
27375 * Debugging the DLL Directly::
27376 * Attaching to a Running Process::
27377 @end menu
27378
27379 @noindent
27380 In this case things are slightly more complex because it is not possible to
27381 start the main program and then break at the beginning to load the DLL and the
27382 associated DLL debugging information. It is not possible to break at the
27383 beginning of the program because there is no @code{GDB} debugging information,
27384 and therefore there is no direct way of getting initial control. This
27385 section addresses this issue by describing some methods that can be used
27386 to break somewhere in the DLL to debug it.
27387
27388 @noindent
27389 First suppose that the main procedure is named @code{main} (this is for
27390 example some C code built with Microsoft Visual C) and that there is a
27391 DLL named @code{test.dll} containing an Ada entry point named
27392 @code{ada_dll}.
27393
27394 @noindent
27395 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
27396 been built with debugging information (see GNAT -g option).
27397
27398 @node Debugging the DLL Directly
27399 @subsubsection Debugging the DLL Directly
27400
27401 @enumerate 1
27402 @item
27403 Launch the debugger on the DLL.
27404
27405 @smallexample
27406 $ gdb -nw test.dll
27407 @end smallexample
27408
27409 @item Set a breakpoint on a DLL subroutine.
27410
27411 @smallexample
27412 (gdb) break ada_dll
27413 @end smallexample
27414
27415 @item
27416 Specify the executable file to @code{GDB}.
27417
27418 @smallexample
27419 (gdb) exec-file main.exe
27420 @end smallexample
27421
27422 @item
27423 Run the program.
27424
27425 @smallexample
27426 (gdb) run
27427 @end smallexample
27428
27429 @noindent
27430 This will run the program until it reaches the breakpoint that has been
27431 set. From that point you can use the standard way to debug a program
27432 as described in (@pxref{Running and Debugging Ada Programs}).
27433
27434 @end enumerate
27435
27436 @noindent
27437 It is also possible to debug the DLL by attaching to a running process.
27438
27439 @node Attaching to a Running Process
27440 @subsubsection Attaching to a Running Process
27441 @cindex DLL debugging, attach to process
27442
27443 @noindent
27444 With @code{GDB} it is always possible to debug a running process by
27445 attaching to it. It is possible to debug a DLL this way. The limitation
27446 of this approach is that the DLL must run long enough to perform the
27447 attach operation. It may be useful for instance to insert a time wasting
27448 loop in the code of the DLL to meet this criterion.
27449
27450 @enumerate 1
27451
27452 @item Launch the main program @file{main.exe}.
27453
27454 @smallexample
27455 $ main
27456 @end smallexample
27457
27458 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
27459 that the process PID for @file{main.exe} is 208.
27460
27461 @item Launch gdb.
27462
27463 @smallexample
27464 $ gdb -nw
27465 @end smallexample
27466
27467 @item Attach to the running process to be debugged.
27468
27469 @smallexample
27470 (gdb) attach 208
27471 @end smallexample
27472
27473 @item Load the process debugging information.
27474
27475 @smallexample
27476 (gdb) symbol-file main.exe
27477 @end smallexample
27478
27479 @item Break somewhere in the DLL.
27480
27481 @smallexample
27482 (gdb) break ada_dll
27483 @end smallexample
27484
27485 @item Continue process execution.
27486
27487 @smallexample
27488 (gdb) continue
27489 @end smallexample
27490
27491 @end enumerate
27492
27493 @noindent
27494 This last step will resume the process execution, and stop at
27495 the breakpoint we have set. From there you can use the standard
27496 approach to debug a program as described in
27497 (@pxref{Running and Debugging Ada Programs}).
27498
27499 @node GNAT and COM/DCOM Objects
27500 @section GNAT and COM/DCOM Objects
27501 @findex COM
27502 @findex DCOM
27503
27504 @noindent
27505 This section is temporarily left blank.
27506
27507 @end ifset
27508
27509
27510 @c **********************************
27511 @c * GNU Free Documentation License *
27512 @c **********************************
27513 @include fdl.texi
27514 @c GNU Free Documentation License
27515
27516 @node Index,,GNU Free Documentation License, Top
27517 @unnumbered Index
27518
27519 @printindex cp
27520
27521 @contents
27522 @c Put table of contents at end, otherwise it precedes the "title page" in
27523 @c the .txt version
27524 @c Edit the pdf file to move the contents to the beginning, after the title
27525 @c page
27526
27527 @bye