OSDN Git Service

2009-04-09 Robert Dewar <dewar@adacore.com>
[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   GNAT is maintained by Ada Core Technologies Inc (http://www.gnat.com).   o
11 @c                                                                            o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
13
14 @setfilename gnat_ugn.info
15
16 @copying
17 Copyright @copyright{} 1995-2005, 2006, 2007, 2008 Free Software Foundation,
18 Inc.
19
20 Permission is granted to copy, distribute and/or modify this document
21 under the terms of the GNU Free Documentation License, Version 1.2 or
22 any later version published by the Free Software Foundation; with no
23 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
24 Texts.  A copy of the license is included in the section entitled
25 ``GNU Free Documentation License''.
26 @end copying
27
28 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
29 @c
30 @c                           GNAT_UGN Style Guide
31 @c
32 @c  1. Always put a @noindent on the line before the first paragraph
33 @c     after any of these commands:
34 @c
35 @c          @chapter
36 @c          @section
37 @c          @subsection
38 @c          @subsubsection
39 @c          @subsubsubsection
40 @c
41 @c          @end smallexample
42 @c          @end itemize
43 @c          @end enumerate
44 @c
45 @c  2. DO NOT use @example. Use @smallexample instead.
46 @c     a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
47 @c        context.  These can interfere with the readability of the texi
48 @c        source file.  Instead, use one of the following annotated
49 @c        @smallexample commands, and preprocess the texi file with the
50 @c        ada2texi tool (which generates appropriate highlighting):
51 @c        @smallexample @c ada
52 @c        @smallexample @c adanocomment
53 @c        @smallexample @c projectfile
54 @c     b) The "@c ada" markup will result in boldface for reserved words
55 @c        and italics for comments
56 @c     c) The "@c adanocomment" markup will result only in boldface for
57 @c        reserved words (comments are left alone)
58 @c     d) The "@c projectfile" markup is like "@c ada" except that the set
59 @c        of reserved words include the new reserved words for project files
60 @c
61 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
62 @c     command must be preceded by two empty lines
63 @c
64 @c  4. The @item command should be on a line of its own if it is in an
65 @c     @itemize or @enumerate command.
66 @c
67 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
68 @c     or "ali".
69 @c
70 @c  6. DO NOT put trailing spaces at the end of a line.  Such spaces will
71 @c     cause the document build to fail.
72 @c
73 @c  7. DO NOT use @cartouche for examples that are longer than around 10 lines.
74 @c     This command inhibits page breaks, so long examples in a @cartouche can
75 @c     lead to large, ugly patches of empty space on a page.
76 @c
77 @c  NOTE: This file should be submitted to xgnatugn with either the vms flag
78 @c        or the unw flag set.  The unw flag covers topics for both Unix and
79 @c        Windows.
80 @c
81 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
82
83 @set NOW January 2007
84 @c This flag is used where the text refers to conditions that exist when the
85 @c text was entered into the document but which may change over time.
86 @c Update the setting for the flag, and (if necessary) the text surrounding,
87 @c the references to the flag, on future doc revisions:
88 @c search for @value{NOW}.
89
90 @set FSFEDITION
91 @set EDITION GNAT
92 @set DEFAULTLANGUAGEVERSION Ada 2005
93 @set NONDEFAULTLANGUAGEVERSION Ada 95
94
95 @ifset unw
96 @set PLATFORM
97 @end ifset
98
99 @ifset vms
100 @set PLATFORM OpenVMS
101 @end ifset
102
103 @c @ovar(ARG)
104 @c ----------
105 @c The ARG is an optional argument.  To be used for macro arguments in
106 @c their documentation (@defmac).
107 @macro ovar{varname}
108 @r{[}@var{\varname\}@r{]}@c
109 @end macro
110
111 @settitle @value{EDITION} User's Guide @value{PLATFORM}
112 @dircategory GNU Ada tools
113 @direntry
114 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
115 @end direntry
116
117 @include gcc-common.texi
118
119 @setchapternewpage odd
120 @syncodeindex fn cp
121 @c %**end of header
122
123 @titlepage
124 @title @value{EDITION} User's Guide
125 @ifset vms
126 @sp 1
127 @flushright
128 @titlefont{@i{@value{PLATFORM}}}
129 @end flushright
130 @end ifset
131
132 @sp 2
133
134 @subtitle GNAT, The GNU Ada Compiler
135 @versionsubtitle
136 @author AdaCore
137
138 @page
139 @vskip 0pt plus 1filll
140
141 @insertcopying
142
143 @end titlepage
144
145 @ifnottex
146 @node Top, About This Guide, (dir), (dir)
147 @top @value{EDITION} User's Guide
148
149 @noindent
150 @value{EDITION} User's Guide @value{PLATFORM}
151
152 @noindent
153 GNAT, The GNU Ada Compiler@*
154 GCC version @value{version-GCC}@*
155
156 @noindent
157 AdaCore@*
158
159 @menu
160 * About This Guide::
161 * Getting Started with GNAT::
162 * The GNAT Compilation Model::
163 * Compiling Using gcc::
164 * Binding Using gnatbind::
165 * Linking Using gnatlink::
166 * The GNAT Make Program gnatmake::
167 * Improving Performance::
168 * Renaming Files Using gnatchop::
169 * Configuration Pragmas::
170 * Handling Arbitrary File Naming Conventions Using gnatname::
171 * GNAT Project Manager::
172 * The Cross-Referencing Tools gnatxref and gnatfind::
173 * The GNAT Pretty-Printer gnatpp::
174 * The GNAT Metric Tool gnatmetric::
175 * File Name Krunching Using gnatkr::
176 * Preprocessing Using gnatprep::
177 @ifset vms
178 * The GNAT Run-Time Library Builder gnatlbr::
179 @end ifset
180 * The GNAT Library Browser gnatls::
181 * Cleaning Up Using gnatclean::
182 @ifclear vms
183 * GNAT and Libraries::
184 * Using the GNU make Utility::
185 @end ifclear
186 * Memory Management Issues::
187 * Stack Related Facilities::
188 * Verifying Properties Using gnatcheck::
189 * Creating Sample Bodies Using gnatstub::
190 * Other Utility Programs::
191 * Running and Debugging Ada Programs::
192 @ifclear vms
193 * Code Coverage and Profiling::
194 @end ifclear
195 @ifset vms
196 * Compatibility with HP Ada::
197 @end ifset
198 * Platform-Specific Information for the Run-Time Libraries::
199 * Example of Binder Output File::
200 * Elaboration Order Handling in GNAT::
201 * Conditional Compilation::
202 * Inline Assembler::
203 * Compatibility and Porting Guide::
204 @ifset unw
205 * Microsoft Windows Topics::
206 @end ifset
207 * GNU Free Documentation License::
208 * Index::
209
210  --- The Detailed Node Listing ---
211
212 About This Guide
213
214 * What This Guide Contains::
215 * What You Should Know before Reading This Guide::
216 * Related Information::
217 * Conventions::
218
219 Getting Started with GNAT
220
221 * Running GNAT::
222 * Running a Simple Ada Program::
223 * Running a Program with Multiple Units::
224 * Using the gnatmake Utility::
225 @ifset vms
226 * Editing with Emacs::
227 @end ifset
228 @ifclear vms
229 * Introduction to GPS::
230 @end ifclear
231
232 The GNAT Compilation Model
233
234 * Source Representation::
235 * Foreign Language Representation::
236 * File Naming Rules::
237 * Using Other File Names::
238 * Alternative File Naming Schemes::
239 * Generating Object Files::
240 * Source Dependencies::
241 * The Ada Library Information Files::
242 * Binding an Ada Program::
243 * Mixed Language Programming::
244 @ifclear vms
245 * Building Mixed Ada & C++ Programs::
246 * Comparison between GNAT and C/C++ Compilation Models::
247 @end ifclear
248 * Comparison between GNAT and Conventional Ada Library Models::
249 @ifset vms
250 * Placement of temporary files::
251 @end ifset
252
253 Foreign Language Representation
254
255 * Latin-1::
256 * Other 8-Bit Codes::
257 * Wide Character Encodings::
258
259 Compiling Ada Programs With gcc
260
261 * Compiling Programs::
262 * Switches for gcc::
263 * Search Paths and the Run-Time Library (RTL)::
264 * Order of Compilation Issues::
265 * Examples::
266
267 Switches for gcc
268
269 * Output and Error Message Control::
270 * Warning Message Control::
271 * Debugging and Assertion Control::
272 * Validity Checking::
273 * Style Checking::
274 * Run-Time Checks::
275 * Using gcc for Syntax Checking::
276 * Using gcc for Semantic Checking::
277 * Compiling Different Versions of Ada::
278 * Character Set Control::
279 * File Naming Control::
280 * Subprogram Inlining Control::
281 * Auxiliary Output Control::
282 * Debugging Control::
283 * Exception Handling Control::
284 * Units to Sources Mapping Files::
285 * Integrated Preprocessing::
286 @ifset vms
287 * Return Codes::
288 @end ifset
289
290 Binding Ada Programs With gnatbind
291
292 * Running gnatbind::
293 * Switches for gnatbind::
294 * Command-Line Access::
295 * Search Paths for gnatbind::
296 * Examples of gnatbind Usage::
297
298 Switches for gnatbind
299
300 * Consistency-Checking Modes::
301 * Binder Error Message Control::
302 * Elaboration Control::
303 * Output Control::
304 * Binding with Non-Ada Main Programs::
305 * Binding Programs with No Main Subprogram::
306
307 Linking Using gnatlink
308
309 * Running gnatlink::
310 * Switches for gnatlink::
311
312 The GNAT Make Program gnatmake
313
314 * Running gnatmake::
315 * Switches for gnatmake::
316 * Mode Switches for gnatmake::
317 * Notes on the Command Line::
318 * How gnatmake Works::
319 * Examples of gnatmake Usage::
320
321 Improving Performance
322 * Performance Considerations::
323 * Text_IO Suggestions::
324 * Reducing Size of Ada Executables with gnatelim::
325 * Reducing Size of Executables with unused subprogram/data elimination::
326
327 Performance Considerations
328 * Controlling Run-Time Checks::
329 * Use of Restrictions::
330 * Optimization Levels::
331 * Debugging Optimized Code::
332 * Inlining of Subprograms::
333 * Other Optimization Switches::
334 * Optimization and Strict Aliasing::
335 @ifset vms
336 * Coverage Analysis::
337 @end ifset
338
339 Reducing Size of Ada Executables with gnatelim
340 * About gnatelim::
341 * Running gnatelim::
342 * Correcting the List of Eliminate Pragmas::
343 * Making Your Executables Smaller::
344 * Summary of the gnatelim Usage Cycle::
345
346 Reducing Size of Executables with unused subprogram/data elimination
347 * About unused subprogram/data elimination::
348 * Compilation options::
349
350 Renaming Files Using gnatchop
351
352 * Handling Files with Multiple Units::
353 * Operating gnatchop in Compilation Mode::
354 * Command Line for gnatchop::
355 * Switches for gnatchop::
356 * Examples of gnatchop Usage::
357
358 Configuration Pragmas
359
360 * Handling of Configuration Pragmas::
361 * The Configuration Pragmas Files::
362
363 Handling Arbitrary File Naming Conventions Using gnatname
364
365 * Arbitrary File Naming Conventions::
366 * Running gnatname::
367 * Switches for gnatname::
368 * Examples of gnatname Usage::
369
370 GNAT Project Manager
371
372 * Introduction::
373 * Examples of Project Files::
374 * Project File Syntax::
375 * Objects and Sources in Project Files::
376 * Importing Projects::
377 * Project Extension::
378 * Project Hierarchy Extension::
379 * External References in Project Files::
380 * Packages in Project Files::
381 * Variables from Imported Projects::
382 * Naming Schemes::
383 * Library Projects::
384 * Stand-alone Library Projects::
385 * Switches Related to Project Files::
386 * Tools Supporting Project Files::
387 * An Extended Example::
388 * Project File Complete Syntax::
389
390 The Cross-Referencing Tools gnatxref and gnatfind
391
392 * gnatxref Switches::
393 * gnatfind Switches::
394 * Project Files for gnatxref and gnatfind::
395 * Regular Expressions in gnatfind and gnatxref::
396 * Examples of gnatxref Usage::
397 * Examples of gnatfind Usage::
398
399 The GNAT Pretty-Printer gnatpp
400
401 * Switches for gnatpp::
402 * Formatting Rules::
403
404 The GNAT Metrics Tool gnatmetric
405
406 * Switches for gnatmetric::
407
408 File Name Krunching Using gnatkr
409
410 * About gnatkr::
411 * Using gnatkr::
412 * Krunching Method::
413 * Examples of gnatkr Usage::
414
415 Preprocessing Using gnatprep
416 * Preprocessing Symbols::
417 * Using gnatprep::
418 * Switches for gnatprep::
419 * Form of Definitions File::
420 * Form of Input Text for gnatprep::
421
422 @ifset vms
423 The GNAT Run-Time Library Builder gnatlbr
424
425 * Running gnatlbr::
426 * Switches for gnatlbr::
427 * Examples of gnatlbr Usage::
428 @end ifset
429
430 The GNAT Library Browser gnatls
431
432 * Running gnatls::
433 * Switches for gnatls::
434 * Examples of gnatls Usage::
435
436 Cleaning Up Using gnatclean
437
438 * Running gnatclean::
439 * Switches for gnatclean::
440 @c * Examples of gnatclean Usage::
441
442 @ifclear vms
443
444 GNAT and Libraries
445
446 * Introduction to Libraries in GNAT::
447 * General Ada Libraries::
448 * Stand-alone Ada Libraries::
449 * Rebuilding the GNAT Run-Time Library::
450
451 Using the GNU make Utility
452
453 * Using gnatmake in a Makefile::
454 * Automatically Creating a List of Directories::
455 * Generating the Command Line Switches::
456 * Overcoming Command Line Length Limits::
457 @end ifclear
458
459 Memory Management Issues
460
461 * Some Useful Memory Pools::
462 * The GNAT Debug Pool Facility::
463 @ifclear vms
464 * The gnatmem Tool::
465 @end ifclear
466
467 Stack Related Facilities
468
469 * Stack Overflow Checking::
470 * Static Stack Usage Analysis::
471 * Dynamic Stack Usage Analysis::
472
473 Some Useful Memory Pools
474
475 The GNAT Debug Pool Facility
476
477 @ifclear vms
478 The gnatmem Tool
479
480 * Running gnatmem::
481 * Switches for gnatmem::
482 * Example of gnatmem Usage::
483 @end ifclear
484
485 Verifying Properties Using gnatcheck
486
487 * Format of the Report File::
488 * General gnatcheck Switches::
489 * gnatcheck Rule Options::
490 * Adding the Results of Compiler Checks to gnatcheck Output::
491 * Project-Wide Checks::
492 * Predefined Rules::
493
494 Sample Bodies Using gnatstub
495
496 * Running gnatstub::
497 * Switches for gnatstub::
498
499 Other Utility Programs
500
501 * Using Other Utility Programs with GNAT::
502 * The External Symbol Naming Scheme of GNAT::
503 * Converting Ada Files to html with gnathtml::
504
505 @ifclear vms
506 Code Coverage and Profiling
507
508 * Code Coverage of Ada Programs using gcov::
509 * Profiling an Ada Program using gprof::
510 @end ifclear
511
512 Running and Debugging Ada Programs
513
514 * The GNAT Debugger GDB::
515 * Running GDB::
516 * Introduction to GDB Commands::
517 * Using Ada Expressions::
518 * Calling User-Defined Subprograms::
519 * Using the Next Command in a Function::
520 * Ada Exceptions::
521 * Ada Tasks::
522 * Debugging Generic Units::
523 * GNAT Abnormal Termination or Failure to Terminate::
524 * Naming Conventions for GNAT Source Files::
525 * Getting Internal Debugging Information::
526 * Stack Traceback::
527
528 @ifset vms
529 * LSE::
530 @end ifset
531
532 @ifset vms
533 Compatibility with HP Ada
534
535 * Ada Language Compatibility::
536 * Differences in the Definition of Package System::
537 * Language-Related Features::
538 * The Package STANDARD::
539 * The Package SYSTEM::
540 * Tasking and Task-Related Features::
541 * Pragmas and Pragma-Related Features::
542 * Library of Predefined Units::
543 * Bindings::
544 * Main Program Definition::
545 * Implementation-Defined Attributes::
546 * Compiler and Run-Time Interfacing::
547 * Program Compilation and Library Management::
548 * Input-Output::
549 * Implementation Limits::
550 * Tools and Utilities::
551
552 Language-Related Features
553
554 * Integer Types and Representations::
555 * Floating-Point Types and Representations::
556 * Pragmas Float_Representation and Long_Float::
557 * Fixed-Point Types and Representations::
558 * Record and Array Component Alignment::
559 * Address Clauses::
560 * Other Representation Clauses::
561
562 Tasking and Task-Related Features
563
564 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
565 * Assigning Task IDs::
566 * Task IDs and Delays::
567 * Task-Related Pragmas::
568 * Scheduling and Task Priority::
569 * The Task Stack::
570 * External Interrupts::
571
572 Pragmas and Pragma-Related Features
573
574 * Restrictions on the Pragma INLINE::
575 * Restrictions on the Pragma INTERFACE::
576 * Restrictions on the Pragma SYSTEM_NAME::
577
578 Library of Predefined Units
579
580 * Changes to DECLIB::
581
582 Bindings
583
584 * Shared Libraries and Options Files::
585 * Interfaces to C::
586 @end ifset
587
588 Platform-Specific Information for the Run-Time Libraries
589
590 * Summary of Run-Time Configurations::
591 * Specifying a Run-Time Library::
592 * Choosing the Scheduling Policy::
593 * Solaris-Specific Considerations::
594 * Linux-Specific Considerations::
595 * AIX-Specific Considerations::
596 * Irix-Specific Considerations::
597
598 Example of Binder Output File
599
600 Elaboration Order Handling in GNAT
601
602 * Elaboration Code::
603 * Checking the Elaboration Order::
604 * Controlling the Elaboration Order::
605 * Controlling Elaboration in GNAT - Internal Calls::
606 * Controlling Elaboration in GNAT - External Calls::
607 * Default Behavior in GNAT - Ensuring Safety::
608 * Treatment of Pragma Elaborate::
609 * Elaboration Issues for Library Tasks::
610 * Mixing Elaboration Models::
611 * What to Do If the Default Elaboration Behavior Fails::
612 * Elaboration for Access-to-Subprogram Values::
613 * Summary of Procedures for Elaboration Control::
614 * Other Elaboration Order Considerations::
615
616 Conditional Compilation
617 * Use of Boolean Constants::
618 * Debugging - A Special Case::
619 * Conditionalizing Declarations::
620 * Use of Alternative Implementations::
621 * Preprocessing::
622
623 Inline Assembler
624
625 * Basic Assembler Syntax::
626 * A Simple Example of Inline Assembler::
627 * Output Variables in Inline Assembler::
628 * Input Variables in Inline Assembler::
629 * Inlining Inline Assembler Code::
630 * Other Asm Functionality::
631
632 Compatibility and Porting Guide
633
634 * Compatibility with Ada 83::
635 * Compatibility between Ada 95 and Ada 2005::
636 * Implementation-dependent characteristics::
637 @ifclear vms
638 @c This brief section is only in the non-VMS version
639 @c The complete chapter on HP Ada issues is in the VMS version
640 * Compatibility with HP Ada 83::
641 @end ifclear
642 * Compatibility with Other Ada Systems::
643 * Representation Clauses::
644 @ifset vms
645 * Transitioning to 64-Bit GNAT for OpenVMS::
646 @end ifset
647
648 @ifset unw
649 Microsoft Windows Topics
650
651 * Using GNAT on Windows::
652 * CONSOLE and WINDOWS subsystems::
653 * Temporary Files::
654 * Mixed-Language Programming on Windows::
655 * Windows Calling Conventions::
656 * Introduction to Dynamic Link Libraries (DLLs)::
657 * Using DLLs with GNAT::
658 * Building DLLs with GNAT::
659 * GNAT and Windows Resources::
660 * Debugging a DLL::
661 * Setting Stack Size from gnatlink::
662 * Setting Heap Size from gnatlink::
663 @end ifset
664
665 * Index::
666 @end menu
667 @end ifnottex
668
669 @node About This Guide
670 @unnumbered About This Guide
671
672 @noindent
673 @ifset vms
674 This guide describes the use of @value{EDITION},
675 a compiler and software development toolset for the full Ada
676 programming language, implemented on OpenVMS for HP's Alpha and
677 Integrity server (I64) platforms.
678 @end ifset
679 @ifclear vms
680 This guide describes the use of @value{EDITION},
681 a compiler and software development
682 toolset for the full Ada programming language.
683 @end ifclear
684 It documents the features of the compiler and tools, and explains
685 how to use them to build Ada applications.
686
687 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
688 Ada 83 compatibility mode.
689 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
690 but you can override with a compiler switch
691 (@pxref{Compiling Different Versions of Ada})
692 to explicitly specify the language version.
693 Throughout this manual, references to ``Ada'' without a year suffix
694 apply to both the Ada 95 and Ada 2005 versions of the language.
695
696
697 @ifclear FSFEDITION
698 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
699 ``GNAT'' in the remainder of this document.
700 @end ifclear
701
702
703
704
705 @menu
706 * What This Guide Contains::
707 * What You Should Know before Reading This Guide::
708 * Related Information::
709 * Conventions::
710 @end menu
711
712 @node What This Guide Contains
713 @unnumberedsec What This Guide Contains
714
715 @noindent
716 This guide contains the following chapters:
717 @itemize @bullet
718
719 @item
720 @ref{Getting Started with GNAT}, describes how to get started compiling
721 and running Ada programs with the GNAT Ada programming environment.
722 @item
723 @ref{The GNAT Compilation Model}, describes the compilation model used
724 by GNAT.
725
726 @item
727 @ref{Compiling Using gcc}, describes how to compile
728 Ada programs with @command{gcc}, the Ada compiler.
729
730 @item
731 @ref{Binding Using gnatbind}, describes how to
732 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
733 utility.
734
735 @item
736 @ref{Linking Using gnatlink},
737 describes @command{gnatlink}, a
738 program that provides for linking using the GNAT run-time library to
739 construct a program. @command{gnatlink} can also incorporate foreign language
740 object units into the executable.
741
742 @item
743 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
744 utility that automatically determines the set of sources
745 needed by an Ada compilation unit, and executes the necessary compilations
746 binding and link.
747
748 @item
749 @ref{Improving Performance}, shows various techniques for making your
750 Ada program run faster or take less space.
751 It discusses the effect of the compiler's optimization switch and
752 also describes the @command{gnatelim} tool and unused subprogram/data
753 elimination.
754
755 @item
756 @ref{Renaming Files Using gnatchop}, describes
757 @code{gnatchop}, a utility that allows you to preprocess a file that
758 contains Ada source code, and split it into one or more new files, one
759 for each compilation unit.
760
761 @item
762 @ref{Configuration Pragmas}, describes the configuration pragmas
763 handled by GNAT.
764
765 @item
766 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
767 shows how to override the default GNAT file naming conventions,
768 either for an individual unit or globally.
769
770 @item
771 @ref{GNAT Project Manager}, describes how to use project files
772 to organize large projects.
773
774 @item
775 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
776 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
777 way to navigate through sources.
778
779 @item
780 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
781 version of an Ada source file with control over casing, indentation,
782 comment placement, and other elements of program presentation style.
783
784 @item
785 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
786 metrics for an Ada source file, such as the number of types and subprograms,
787 and assorted complexity measures.
788
789 @item
790 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
791 file name krunching utility, used to handle shortened
792 file names on operating systems with a limit on the length of names.
793
794 @item
795 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
796 preprocessor utility that allows a single source file to be used to
797 generate multiple or parameterized source files by means of macro
798 substitution.
799
800 @ifset vms
801 @item
802 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
803 a tool for rebuilding the GNAT run time with user-supplied
804 configuration pragmas.
805 @end ifset
806
807 @item
808 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
809 utility that displays information about compiled units, including dependences
810 on the corresponding sources files, and consistency of compilations.
811
812 @item
813 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
814 to delete files that are produced by the compiler, binder and linker.
815
816 @ifclear vms
817 @item
818 @ref{GNAT and Libraries}, describes the process of creating and using
819 Libraries with GNAT. It also describes how to recompile the GNAT run-time
820 library.
821
822 @item
823 @ref{Using the GNU make Utility}, describes some techniques for using
824 the GNAT toolset in Makefiles.
825 @end ifclear
826
827 @item
828 @ref{Memory Management Issues}, describes some useful predefined storage pools
829 and in particular the GNAT Debug Pool facility, which helps detect incorrect
830 memory references.
831 @ifclear vms
832 It also describes @command{gnatmem}, a utility that monitors dynamic
833 allocation and deallocation and helps detect ``memory leaks''.
834 @end ifclear
835
836 @item
837 @ref{Stack Related Facilities}, describes some useful tools associated with
838 stack checking and analysis.
839
840 @item
841 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
842 a utility that checks Ada code against a set of rules.
843
844 @item
845 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
846 a utility that generates empty but compilable bodies for library units.
847
848 @item
849 @ref{Other Utility Programs}, discusses several other GNAT utilities,
850 including @code{gnathtml}.
851
852 @ifclear vms
853 @item
854 @ref{Code Coverage and Profiling}, describes how to perform a structural
855 coverage and profile the execution of Ada programs.
856 @end ifclear
857
858 @item
859 @ref{Running and Debugging Ada Programs}, describes how to run and debug
860 Ada programs.
861
862 @ifset vms
863 @item
864 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
865 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
866 developed by Digital Equipment Corporation and currently supported by HP.}
867 for OpenVMS Alpha. This product was formerly known as DEC Ada,
868 @cindex DEC Ada
869 and for
870 historical compatibility reasons, the relevant libraries still use the
871 DEC prefix.
872 @end ifset
873
874 @item
875 @ref{Platform-Specific Information for the Run-Time Libraries},
876 describes the various run-time
877 libraries supported by GNAT on various platforms and explains how to
878 choose a particular library.
879
880 @item
881 @ref{Example of Binder Output File}, shows the source code for the binder
882 output file for a sample program.
883
884 @item
885 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
886 you deal with elaboration order issues.
887
888 @item
889 @ref{Conditional Compilation}, describes how to model conditional compilation,
890 both with Ada in general and with GNAT facilities in particular.
891
892 @item
893 @ref{Inline Assembler}, shows how to use the inline assembly facility
894 in an Ada program.
895
896 @item
897 @ref{Compatibility and Porting Guide}, contains sections on compatibility
898 of GNAT with other Ada development environments (including Ada 83 systems),
899 to assist in porting code from those environments.
900
901 @ifset unw
902 @item
903 @ref{Microsoft Windows Topics}, presents information relevant to the
904 Microsoft Windows platform.
905 @end ifset
906 @end itemize
907
908 @c *************************************************
909 @node What You Should Know before Reading This Guide
910 @c *************************************************
911 @unnumberedsec What You Should Know before Reading This Guide
912
913 @cindex Ada 95 Language Reference Manual
914 @cindex Ada 2005 Language Reference Manual
915 @noindent
916 This guide assumes a basic familiarity with the Ada 95 language, as
917 described in the International Standard ANSI/ISO/IEC-8652:1995, January
918 1995.
919 It does not require knowledge of the new features introduced by Ada 2005,
920 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
921 and Amendment 1).
922 Both reference manuals are included in the GNAT documentation
923 package.
924
925 @node Related Information
926 @unnumberedsec Related Information
927
928 @noindent
929 For further information about related tools, refer to the following
930 documents:
931
932 @itemize @bullet
933 @item
934 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
935 Reference Manual}, which contains all reference material for the GNAT
936 implementation of Ada.
937
938 @ifset unw
939 @item
940 @cite{Using the GNAT Programming Studio}, which describes the GPS
941 Integrated Development Environment.
942
943 @item
944 @cite{GNAT Programming Studio Tutorial}, which introduces the
945 main GPS features through examples.
946 @end ifset
947
948 @item
949 @cite{Ada 95 Reference Manual}, which contains reference
950 material for the Ada 95 programming language.
951
952 @item
953 @cite{Ada 2005 Reference Manual}, which contains reference
954 material for the Ada 2005 programming language.
955
956 @item
957 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
958 @ifset vms
959 in the GNU:[DOCS] directory,
960 @end ifset
961 for all details on the use of the GNU source-level debugger.
962
963 @item
964 @xref{Top,, The extensible self-documenting text editor, emacs,
965 GNU Emacs Manual},
966 @ifset vms
967 located in the GNU:[DOCS] directory if the EMACS kit is installed,
968 @end ifset
969 for full information on the extensible editor and programming
970 environment Emacs.
971
972 @end itemize
973
974 @c **************
975 @node Conventions
976 @unnumberedsec Conventions
977 @cindex Conventions
978 @cindex Typographical conventions
979
980 @noindent
981 Following are examples of the typographical and graphic conventions used
982 in this guide:
983
984 @itemize @bullet
985 @item
986 @code{Functions}, @command{utility program names}, @code{standard names},
987 and @code{classes}.
988
989 @item
990 @option{Option flags}
991
992 @item
993 @file{File names}, @samp{button names}, and @samp{field names}.
994
995 @item
996 @code{Variables}, @env{environment variables}, and @var{metasyntactic
997 variables}.
998
999 @item
1000 @emph{Emphasis}.
1001
1002 @item
1003 @r{[}optional information or parameters@r{]}
1004
1005 @item
1006 Examples are described by text
1007 @smallexample
1008 and then shown this way.
1009 @end smallexample
1010 @end itemize
1011
1012 @noindent
1013 Commands that are entered by the user are preceded in this manual by the
1014 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1015 uses this sequence as a prompt, then the commands will appear exactly as
1016 you see them in the manual. If your system uses some other prompt, then
1017 the command will appear with the @code{$} replaced by whatever prompt
1018 character you are using.
1019
1020 @ifset unw
1021 Full file names are shown with the ``@code{/}'' character
1022 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1023 If you are using GNAT on a Windows platform, please note that
1024 the ``@code{\}'' character should be used instead.
1025 @end ifset
1026
1027 @c ****************************
1028 @node Getting Started with GNAT
1029 @chapter Getting Started with GNAT
1030
1031 @noindent
1032 This chapter describes some simple ways of using GNAT to build
1033 executable Ada programs.
1034 @ifset unw
1035 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1036 show how to use the command line environment.
1037 @ref{Introduction to GPS}, provides a brief
1038 introduction to the GNAT Programming Studio, a visually-oriented
1039 Integrated Development Environment for GNAT.
1040 GPS offers a graphical ``look and feel'', support for development in
1041 other programming languages, comprehensive browsing features, and
1042 many other capabilities.
1043 For information on GPS please refer to
1044 @cite{Using the GNAT Programming Studio}.
1045 @end ifset
1046
1047 @menu
1048 * Running GNAT::
1049 * Running a Simple Ada Program::
1050 * Running a Program with Multiple Units::
1051 * Using the gnatmake Utility::
1052 @ifset vms
1053 * Editing with Emacs::
1054 @end ifset
1055 @ifclear vms
1056 * Introduction to GPS::
1057 @end ifclear
1058 @end menu
1059
1060 @node Running GNAT
1061 @section Running GNAT
1062
1063 @noindent
1064 Three steps are needed to create an executable file from an Ada source
1065 file:
1066
1067 @enumerate
1068 @item
1069 The source file(s) must be compiled.
1070 @item
1071 The file(s) must be bound using the GNAT binder.
1072 @item
1073 All appropriate object files must be linked to produce an executable.
1074 @end enumerate
1075
1076 @noindent
1077 All three steps are most commonly handled by using the @command{gnatmake}
1078 utility program that, given the name of the main program, automatically
1079 performs the necessary compilation, binding and linking steps.
1080
1081 @node Running a Simple Ada Program
1082 @section Running a Simple Ada Program
1083
1084 @noindent
1085 Any text editor may be used to prepare an Ada program.
1086 (If @code{Emacs} is
1087 used, the optional Ada mode may be helpful in laying out the program.)
1088 The
1089 program text is a normal text file. We will assume in our initial
1090 example that you have used your editor to prepare the following
1091 standard format text file:
1092
1093 @smallexample @c ada
1094 @cartouche
1095 with Ada.Text_IO; use Ada.Text_IO;
1096 procedure Hello is
1097 begin
1098    Put_Line ("Hello WORLD!");
1099 end Hello;
1100 @end cartouche
1101 @end smallexample
1102
1103 @noindent
1104 This file should be named @file{hello.adb}.
1105 With the normal default file naming conventions, GNAT requires
1106 that each file
1107 contain a single compilation unit whose file name is the
1108 unit name,
1109 with periods replaced by hyphens; the
1110 extension is @file{ads} for a
1111 spec and @file{adb} for a body.
1112 You can override this default file naming convention by use of the
1113 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1114 Alternatively, if you want to rename your files according to this default
1115 convention, which is probably more convenient if you will be using GNAT
1116 for all your compilations, then the @code{gnatchop} utility
1117 can be used to generate correctly-named source files
1118 (@pxref{Renaming Files Using gnatchop}).
1119
1120 You can compile the program using the following command (@code{$} is used
1121 as the command prompt in the examples in this document):
1122
1123 @smallexample
1124 $ gcc -c hello.adb
1125 @end smallexample
1126
1127 @noindent
1128 @command{gcc} is the command used to run the compiler. This compiler is
1129 capable of compiling programs in several languages, including Ada and
1130 C. It assumes that you have given it an Ada program if the file extension is
1131 either @file{.ads} or @file{.adb}, and it will then call
1132 the GNAT compiler to compile the specified file.
1133
1134 @ifclear vms
1135 The @option{-c} switch is required. It tells @command{gcc} to only do a
1136 compilation. (For C programs, @command{gcc} can also do linking, but this
1137 capability is not used directly for Ada programs, so the @option{-c}
1138 switch must always be present.)
1139 @end ifclear
1140
1141 This compile command generates a file
1142 @file{hello.o}, which is the object
1143 file corresponding to your Ada program. It also generates
1144 an ``Ada Library Information'' file @file{hello.ali},
1145 which contains additional information used to check
1146 that an Ada program is consistent.
1147 To build an executable file,
1148 use @code{gnatbind} to bind the program
1149 and @command{gnatlink} to link it. The
1150 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1151 @file{ALI} file, but the default extension of @file{.ali} can
1152 be omitted. This means that in the most common case, the argument
1153 is simply the name of the main program:
1154
1155 @smallexample
1156 $ gnatbind hello
1157 $ gnatlink hello
1158 @end smallexample
1159
1160 @noindent
1161 A simpler method of carrying out these steps is to use
1162 @command{gnatmake},
1163 a master program that invokes all the required
1164 compilation, binding and linking tools in the correct order. In particular,
1165 @command{gnatmake} automatically recompiles any sources that have been
1166 modified since they were last compiled, or sources that depend
1167 on such modified sources, so that ``version skew'' is avoided.
1168 @cindex Version skew (avoided by @command{gnatmake})
1169
1170 @smallexample
1171 $ gnatmake hello.adb
1172 @end smallexample
1173
1174 @noindent
1175 The result is an executable program called @file{hello}, which can be
1176 run by entering:
1177
1178 @smallexample
1179 $ ^hello^RUN HELLO^
1180 @end smallexample
1181
1182 @noindent
1183 assuming that the current directory is on the search path
1184 for executable programs.
1185
1186 @noindent
1187 and, if all has gone well, you will see
1188
1189 @smallexample
1190 Hello WORLD!
1191 @end smallexample
1192
1193 @noindent
1194 appear in response to this command.
1195
1196 @c ****************************************
1197 @node Running a Program with Multiple Units
1198 @section Running a Program with Multiple Units
1199
1200 @noindent
1201 Consider a slightly more complicated example that has three files: a
1202 main program, and the spec and body of a package:
1203
1204 @smallexample @c ada
1205 @cartouche
1206 @group
1207 package Greetings is
1208    procedure Hello;
1209    procedure Goodbye;
1210 end Greetings;
1211
1212 with Ada.Text_IO; use Ada.Text_IO;
1213 package body Greetings is
1214    procedure Hello is
1215    begin
1216       Put_Line ("Hello WORLD!");
1217    end Hello;
1218
1219    procedure Goodbye is
1220    begin
1221       Put_Line ("Goodbye WORLD!");
1222    end Goodbye;
1223 end Greetings;
1224 @end group
1225
1226 @group
1227 with Greetings;
1228 procedure Gmain is
1229 begin
1230    Greetings.Hello;
1231    Greetings.Goodbye;
1232 end Gmain;
1233 @end group
1234 @end cartouche
1235 @end smallexample
1236
1237 @noindent
1238 Following the one-unit-per-file rule, place this program in the
1239 following three separate files:
1240
1241 @table @file
1242 @item greetings.ads
1243 spec of package @code{Greetings}
1244
1245 @item greetings.adb
1246 body of package @code{Greetings}
1247
1248 @item gmain.adb
1249 body of main program
1250 @end table
1251
1252 @noindent
1253 To build an executable version of
1254 this program, we could use four separate steps to compile, bind, and link
1255 the program, as follows:
1256
1257 @smallexample
1258 $ gcc -c gmain.adb
1259 $ gcc -c greetings.adb
1260 $ gnatbind gmain
1261 $ gnatlink gmain
1262 @end smallexample
1263
1264 @noindent
1265 Note that there is no required order of compilation when using GNAT.
1266 In particular it is perfectly fine to compile the main program first.
1267 Also, it is not necessary to compile package specs in the case where
1268 there is an accompanying body; you only need to compile the body. If you want
1269 to submit these files to the compiler for semantic checking and not code
1270 generation, then use the
1271 @option{-gnatc} switch:
1272
1273 @smallexample
1274 $ gcc -c greetings.ads -gnatc
1275 @end smallexample
1276
1277 @noindent
1278 Although the compilation can be done in separate steps as in the
1279 above example, in practice it is almost always more convenient
1280 to use the @command{gnatmake} tool. All you need to know in this case
1281 is the name of the main program's source file. The effect of the above four
1282 commands can be achieved with a single one:
1283
1284 @smallexample
1285 $ gnatmake gmain.adb
1286 @end smallexample
1287
1288 @noindent
1289 In the next section we discuss the advantages of using @command{gnatmake} in
1290 more detail.
1291
1292 @c *****************************
1293 @node Using the gnatmake Utility
1294 @section Using the @command{gnatmake} Utility
1295
1296 @noindent
1297 If you work on a program by compiling single components at a time using
1298 @command{gcc}, you typically keep track of the units you modify. In order to
1299 build a consistent system, you compile not only these units, but also any
1300 units that depend on the units you have modified.
1301 For example, in the preceding case,
1302 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1303 you edit @file{greetings.ads}, you must recompile both
1304 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1305 units that depend on @file{greetings.ads}.
1306
1307 @code{gnatbind} will warn you if you forget one of these compilation
1308 steps, so that it is impossible to generate an inconsistent program as a
1309 result of forgetting to do a compilation. Nevertheless it is tedious and
1310 error-prone to keep track of dependencies among units.
1311 One approach to handle the dependency-bookkeeping is to use a
1312 makefile. However, makefiles present maintenance problems of their own:
1313 if the dependencies change as you change the program, you must make
1314 sure that the makefile is kept up-to-date manually, which is also an
1315 error-prone process.
1316
1317 The @command{gnatmake} utility takes care of these details automatically.
1318 Invoke it using either one of the following forms:
1319
1320 @smallexample
1321 $ gnatmake gmain.adb
1322 $ gnatmake ^gmain^GMAIN^
1323 @end smallexample
1324
1325 @noindent
1326 The argument is the name of the file containing the main program;
1327 you may omit the extension. @command{gnatmake}
1328 examines the environment, automatically recompiles any files that need
1329 recompiling, and binds and links the resulting set of object files,
1330 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1331 In a large program, it
1332 can be extremely helpful to use @command{gnatmake}, because working out by hand
1333 what needs to be recompiled can be difficult.
1334
1335 Note that @command{gnatmake}
1336 takes into account all the Ada rules that
1337 establish dependencies among units. These include dependencies that result
1338 from inlining subprogram bodies, and from
1339 generic instantiation. Unlike some other
1340 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1341 found by the compiler on a previous compilation, which may possibly
1342 be wrong when sources change. @command{gnatmake} determines the exact set of
1343 dependencies from scratch each time it is run.
1344
1345 @ifset vms
1346 @node Editing with Emacs
1347 @section Editing with Emacs
1348 @cindex Emacs
1349
1350 @noindent
1351 Emacs is an extensible self-documenting text editor that is available in a
1352 separate VMSINSTAL kit.
1353
1354 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1355 click on the Emacs Help menu and run the Emacs Tutorial.
1356 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1357 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1358
1359 Documentation on Emacs and other tools is available in Emacs under the
1360 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1361 use the middle mouse button to select a topic (e.g.@: Emacs).
1362
1363 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1364 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1365 get to the Emacs manual.
1366 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1367 prompt.
1368
1369 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1370 which is sufficiently extensible to provide for a complete programming
1371 environment and shell for the sophisticated user.
1372 @end ifset
1373
1374 @ifclear vms
1375 @node Introduction to GPS
1376 @section Introduction to GPS
1377 @cindex GPS (GNAT Programming Studio)
1378 @cindex GNAT Programming Studio (GPS)
1379 @noindent
1380 Although the command line interface (@command{gnatmake}, etc.) alone
1381 is sufficient, a graphical Interactive Development
1382 Environment can make it easier for you to compose, navigate, and debug
1383 programs.  This section describes the main features of GPS
1384 (``GNAT Programming Studio''), the GNAT graphical IDE.
1385 You will see how to use GPS to build and debug an executable, and
1386 you will also learn some of the basics of the GNAT ``project'' facility.
1387
1388 GPS enables you to do much more than is presented here;
1389 e.g., you can produce a call graph, interface to a third-party
1390 Version Control System, and inspect the generated assembly language
1391 for a program.
1392 Indeed, GPS also supports languages other than Ada.
1393 Such additional information, and an explanation of all of the GPS menu
1394 items. may be found in the on-line help, which includes
1395 a user's guide and a tutorial (these are also accessible from the GNAT
1396 startup menu).
1397
1398 @menu
1399 * Building a New Program with GPS::
1400 * Simple Debugging with GPS::
1401 @end menu
1402
1403 @node Building a New Program with GPS
1404 @subsection Building a New Program with GPS
1405 @noindent
1406 GPS invokes the GNAT compilation tools using information
1407 contained in a @emph{project} (also known as a @emph{project file}):
1408 a collection of properties such
1409 as source directories, identities of main subprograms, tool switches, etc.,
1410 and their associated values.
1411 See @ref{GNAT Project Manager} for details.
1412 In order to run GPS, you will need to either create a new project
1413 or else open an existing one.
1414
1415 This section will explain how you can use GPS to create a project,
1416 to associate Ada source files with a project, and to build and run
1417 programs.
1418
1419 @enumerate
1420 @item @emph{Creating a project}
1421
1422 Invoke GPS, either from the command line or the platform's IDE.
1423 After it starts, GPS will display a ``Welcome'' screen with three
1424 radio buttons:
1425
1426 @itemize @bullet
1427 @item
1428 @code{Start with default project in directory}
1429
1430 @item
1431 @code{Create new project with wizard}
1432
1433 @item
1434 @code{Open existing project}
1435 @end itemize
1436
1437 @noindent
1438 Select @code{Create new project with wizard} and press @code{OK}.
1439 A new window will appear.  In the text box labeled with
1440 @code{Enter the name of the project to create}, type @file{sample}
1441 as the project name.
1442 In the next box, browse to choose the directory in which you
1443 would like to create the project file.
1444 After selecting an appropriate directory, press @code{Forward}.
1445
1446 A window will appear with the title
1447 @code{Version Control System Configuration}.
1448 Simply press @code{Forward}.
1449
1450 A window will appear with the title
1451 @code{Please select the source directories for this project}.
1452 The directory that you specified for the project file will be selected
1453 by default as the one to use for sources; simply press @code{Forward}.
1454
1455 A window will appear with the title
1456 @code{Please select the build directory for this project}.
1457 The directory that you specified for the project file will be selected
1458 by default for object files and executables;
1459 simply press @code{Forward}.
1460
1461 A window will appear with the title
1462 @code{Please select the main units for this project}.
1463 You will supply this information later, after creating the source file.
1464 Simply press @code{Forward} for now.
1465
1466 A window will appear with the title
1467 @code{Please select the switches to build the project}.
1468 Press @code{Apply}.  This will create a project file named
1469 @file{sample.prj} in the directory that you had specified.
1470
1471 @item @emph{Creating and saving the source file}
1472
1473 After you create the new project, a GPS window will appear, which is
1474 partitioned into two main sections:
1475
1476 @itemize @bullet
1477 @item
1478 A @emph{Workspace area}, initially greyed out, which you will use for
1479 creating and editing source files
1480
1481 @item
1482 Directly below, a @emph{Messages area}, which initially displays a
1483 ``Welcome'' message.
1484 (If the Messages area is not visible, drag its border upward to expand it.)
1485 @end itemize
1486
1487 @noindent
1488 Select @code{File} on the menu bar, and then the @code{New} command.
1489 The Workspace area will become white, and you can now
1490 enter the source program explicitly.
1491 Type the following text
1492
1493 @smallexample @c ada
1494 @group
1495 with Ada.Text_IO; use Ada.Text_IO;
1496 procedure Hello is
1497 begin
1498   Put_Line("Hello from GPS!");
1499 end Hello;
1500 @end group
1501 @end smallexample
1502
1503 @noindent
1504 Select @code{File}, then @code{Save As}, and enter the source file name
1505 @file{hello.adb}.
1506 The file will be saved in the same directory you specified as the
1507 location of the default project file.
1508
1509 @item @emph{Updating the project file}
1510
1511 You need to add the new source file to the project.
1512 To do this, select
1513 the @code{Project} menu and then @code{Edit project properties}.
1514 Click the @code{Main files} tab on the left, and then the
1515 @code{Add} button.
1516 Choose @file{hello.adb} from the list, and press @code{Open}.
1517 The project settings window will reflect this action.
1518 Click @code{OK}.
1519
1520 @item @emph{Building and running the program}
1521
1522 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1523 and select @file{hello.adb}.
1524 The Messages window will display the resulting invocations of @command{gcc},
1525 @command{gnatbind}, and @command{gnatlink}
1526 (reflecting the default switch settings from the
1527 project file that you created) and then a ``successful compilation/build''
1528 message.
1529
1530 To run the program, choose the @code{Build} menu, then @code{Run}, and
1531 select @command{hello}.
1532 An @emph{Arguments Selection} window will appear.
1533 There are no command line arguments, so just click @code{OK}.
1534
1535 The Messages window will now display the program's output (the string
1536 @code{Hello from GPS}), and at the bottom of the GPS window a status
1537 update is displayed (@code{Run: hello}).
1538 Close the GPS window (or select @code{File}, then @code{Exit}) to
1539 terminate this GPS session.
1540 @end enumerate
1541
1542 @node Simple Debugging with GPS
1543 @subsection Simple Debugging with GPS
1544 @noindent
1545 This section illustrates basic debugging techniques (setting breakpoints,
1546 examining/modifying variables, single stepping).
1547
1548 @enumerate
1549 @item @emph{Opening a project}
1550
1551 Start GPS and select @code{Open existing project}; browse to
1552 specify the project file @file{sample.prj} that you had created in the
1553 earlier example.
1554
1555 @item @emph{Creating a source file}
1556
1557 Select @code{File}, then @code{New}, and type in the following program:
1558
1559 @smallexample @c ada
1560 @group
1561 with Ada.Text_IO; use Ada.Text_IO;
1562 procedure Example is
1563    Line : String (1..80);
1564    N    : Natural;
1565 begin
1566    Put_Line("Type a line of text at each prompt; an empty line to exit");
1567    loop
1568       Put(": ");
1569       Get_Line (Line, N);
1570       Put_Line (Line (1..N) );
1571       exit when N=0;
1572    end loop;
1573 end Example;
1574 @end group
1575 @end smallexample
1576
1577 @noindent
1578 Select @code{File}, then @code{Save as}, and enter the file name
1579 @file{example.adb}.
1580
1581 @item @emph{Updating the project file}
1582
1583 Add @code{Example} as a new main unit for the project:
1584 @enumerate a
1585 @item
1586 Select @code{Project}, then @code{Edit Project Properties}.
1587
1588 @item
1589 Select the @code{Main files} tab, click @code{Add}, then
1590 select the file @file{example.adb} from the list, and
1591 click @code{Open}.
1592 You will see the file name appear in the list of main units
1593
1594 @item
1595 Click @code{OK}
1596 @end enumerate
1597
1598 @item @emph{Building/running the executable}
1599
1600 To build the executable
1601 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1602
1603 Run the program to see its effect (in the Messages area).
1604 Each line that you enter is displayed; an empty line will
1605 cause the loop to exit and the program to terminate.
1606
1607 @item @emph{Debugging the program}
1608
1609 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1610 which are required for debugging, are on by default when you create
1611 a new project.
1612 Thus unless you intentionally remove these settings, you will be able
1613 to debug any program that you develop using GPS.
1614
1615 @enumerate a
1616 @item @emph{Initializing}
1617
1618 Select @code{Debug}, then @code{Initialize}, then @file{example}
1619
1620 @item @emph{Setting a breakpoint}
1621
1622 After performing the initialization step, you will observe a small
1623 icon to the right of each line number.
1624 This serves as a toggle for breakpoints; clicking the icon will
1625 set a breakpoint at the corresponding line (the icon will change to
1626 a red circle with an ``x''), and clicking it again
1627 will remove the breakpoint / reset the icon.
1628
1629 For purposes of this example, set a breakpoint at line 10 (the
1630 statement @code{Put_Line@ (Line@ (1..N));}
1631
1632 @item @emph{Starting program execution}
1633
1634 Select @code{Debug}, then @code{Run}.  When the
1635 @code{Program Arguments} window appears, click @code{OK}.
1636 A console window will appear; enter some line of text,
1637 e.g.@: @code{abcde}, at the prompt.
1638 The program will pause execution when it gets to the
1639 breakpoint, and the corresponding line is highlighted.
1640
1641 @item @emph{Examining a variable}
1642
1643 Move the mouse over one of the occurrences of the variable @code{N}.
1644 You will see the value (5) displayed, in ``tool tip'' fashion.
1645 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1646 You will see information about @code{N} appear in the @code{Debugger Data}
1647 pane, showing the value as 5.
1648
1649 @item @emph{Assigning a new value to a variable}
1650
1651 Right click on the @code{N} in the @code{Debugger Data} pane, and
1652 select @code{Set value of N}.
1653 When the input window appears, enter the value @code{4} and click
1654 @code{OK}.
1655 This value does not automatically appear in the @code{Debugger Data}
1656 pane; to see it, right click again on the @code{N} in the
1657 @code{Debugger Data} pane and select @code{Update value}.
1658 The new value, 4, will appear in red.
1659
1660 @item @emph{Single stepping}
1661
1662 Select @code{Debug}, then @code{Next}.
1663 This will cause the next statement to be executed, in this case the
1664 call of @code{Put_Line} with the string slice.
1665 Notice in the console window that the displayed string is simply
1666 @code{abcd} and not @code{abcde} which you had entered.
1667 This is because the upper bound of the slice is now 4 rather than 5.
1668
1669 @item @emph{Removing a breakpoint}
1670
1671 Toggle the breakpoint icon at line 10.
1672
1673 @item @emph{Resuming execution from a breakpoint}
1674
1675 Select @code{Debug}, then @code{Continue}.
1676 The program will reach the next iteration of the loop, and
1677 wait for input after displaying the prompt.
1678 This time, just hit the @kbd{Enter} key.
1679 The value of @code{N} will be 0, and the program will terminate.
1680 The console window will disappear.
1681 @end enumerate
1682 @end enumerate
1683 @end ifclear
1684
1685 @node The GNAT Compilation Model
1686 @chapter The GNAT Compilation Model
1687 @cindex GNAT compilation model
1688 @cindex Compilation model
1689
1690 @menu
1691 * Source Representation::
1692 * Foreign Language Representation::
1693 * File Naming Rules::
1694 * Using Other File Names::
1695 * Alternative File Naming Schemes::
1696 * Generating Object Files::
1697 * Source Dependencies::
1698 * The Ada Library Information Files::
1699 * Binding an Ada Program::
1700 * Mixed Language Programming::
1701 @ifclear vms
1702 * Building Mixed Ada & C++ Programs::
1703 * Comparison between GNAT and C/C++ Compilation Models::
1704 @end ifclear
1705 * Comparison between GNAT and Conventional Ada Library Models::
1706 @ifset vms
1707 * Placement of temporary files::
1708 @end ifset
1709 @end menu
1710
1711 @noindent
1712 This chapter describes the compilation model used by GNAT. Although
1713 similar to that used by other languages, such as C and C++, this model
1714 is substantially different from the traditional Ada compilation models,
1715 which are based on a library. The model is initially described without
1716 reference to the library-based model. If you have not previously used an
1717 Ada compiler, you need only read the first part of this chapter. The
1718 last section describes and discusses the differences between the GNAT
1719 model and the traditional Ada compiler models. If you have used other
1720 Ada compilers, this section will help you to understand those
1721 differences, and the advantages of the GNAT model.
1722
1723 @node Source Representation
1724 @section Source Representation
1725 @cindex Latin-1
1726
1727 @noindent
1728 Ada source programs are represented in standard text files, using
1729 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1730 7-bit ASCII set, plus additional characters used for
1731 representing foreign languages (@pxref{Foreign Language Representation}
1732 for support of non-USA character sets). The format effector characters
1733 are represented using their standard ASCII encodings, as follows:
1734
1735 @table @code
1736 @item VT
1737 @findex VT
1738 Vertical tab, @code{16#0B#}
1739
1740 @item HT
1741 @findex HT
1742 Horizontal tab, @code{16#09#}
1743
1744 @item CR
1745 @findex CR
1746 Carriage return, @code{16#0D#}
1747
1748 @item LF
1749 @findex LF
1750 Line feed, @code{16#0A#}
1751
1752 @item FF
1753 @findex FF
1754 Form feed, @code{16#0C#}
1755 @end table
1756
1757 @noindent
1758 Source files are in standard text file format. In addition, GNAT will
1759 recognize a wide variety of stream formats, in which the end of
1760 physical lines is marked by any of the following sequences:
1761 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1762 in accommodating files that are imported from other operating systems.
1763
1764 @cindex End of source file
1765 @cindex Source file, end
1766 @findex SUB
1767 The end of a source file is normally represented by the physical end of
1768 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1769 recognized as signalling the end of the source file. Again, this is
1770 provided for compatibility with other operating systems where this
1771 code is used to represent the end of file.
1772
1773 Each file contains a single Ada compilation unit, including any pragmas
1774 associated with the unit. For example, this means you must place a
1775 package declaration (a package @dfn{spec}) and the corresponding body in
1776 separate files. An Ada @dfn{compilation} (which is a sequence of
1777 compilation units) is represented using a sequence of files. Similarly,
1778 you will place each subunit or child unit in a separate file.
1779
1780 @node Foreign Language Representation
1781 @section Foreign Language Representation
1782
1783 @noindent
1784 GNAT supports the standard character sets defined in Ada as well as
1785 several other non-standard character sets for use in localized versions
1786 of the compiler (@pxref{Character Set Control}).
1787 @menu
1788 * Latin-1::
1789 * Other 8-Bit Codes::
1790 * Wide Character Encodings::
1791 @end menu
1792
1793 @node Latin-1
1794 @subsection Latin-1
1795 @cindex Latin-1
1796
1797 @noindent
1798 The basic character set is Latin-1. This character set is defined by ISO
1799 standard 8859, part 1. The lower half (character codes @code{16#00#}
1800 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1801 is used to represent additional characters. These include extended letters
1802 used by European languages, such as French accents, the vowels with umlauts
1803 used in German, and the extra letter A-ring used in Swedish.
1804
1805 @findex Ada.Characters.Latin_1
1806 For a complete list of Latin-1 codes and their encodings, see the source
1807 file of library unit @code{Ada.Characters.Latin_1} in file
1808 @file{a-chlat1.ads}.
1809 You may use any of these extended characters freely in character or
1810 string literals. In addition, the extended characters that represent
1811 letters can be used in identifiers.
1812
1813 @node Other 8-Bit Codes
1814 @subsection Other 8-Bit Codes
1815
1816 @noindent
1817 GNAT also supports several other 8-bit coding schemes:
1818
1819 @table @asis
1820 @item ISO 8859-2 (Latin-2)
1821 @cindex Latin-2
1822 @cindex ISO 8859-2
1823 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1824 equivalence.
1825
1826 @item ISO 8859-3 (Latin-3)
1827 @cindex Latin-3
1828 @cindex ISO 8859-3
1829 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1830 equivalence.
1831
1832 @item ISO 8859-4 (Latin-4)
1833 @cindex Latin-4
1834 @cindex ISO 8859-4
1835 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1836 equivalence.
1837
1838 @item ISO 8859-5 (Cyrillic)
1839 @cindex ISO 8859-5
1840 @cindex Cyrillic
1841 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1842 lowercase equivalence.
1843
1844 @item ISO 8859-15 (Latin-9)
1845 @cindex ISO 8859-15
1846 @cindex Latin-9
1847 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1848 lowercase equivalence
1849
1850 @item IBM PC (code page 437)
1851 @cindex code page 437
1852 This code page is the normal default for PCs in the U.S. It corresponds
1853 to the original IBM PC character set. This set has some, but not all, of
1854 the extended Latin-1 letters, but these letters do not have the same
1855 encoding as Latin-1. In this mode, these letters are allowed in
1856 identifiers with uppercase and lowercase equivalence.
1857
1858 @item IBM PC (code page 850)
1859 @cindex code page 850
1860 This code page is a modification of 437 extended to include all the
1861 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1862 mode, all these letters are allowed in identifiers with uppercase and
1863 lowercase equivalence.
1864
1865 @item Full Upper 8-bit
1866 Any character in the range 80-FF allowed in identifiers, and all are
1867 considered distinct. In other words, there are no uppercase and lowercase
1868 equivalences in this range. This is useful in conjunction with
1869 certain encoding schemes used for some foreign character sets (e.g.,
1870 the typical method of representing Chinese characters on the PC).
1871
1872 @item No Upper-Half
1873 No upper-half characters in the range 80-FF are allowed in identifiers.
1874 This gives Ada 83 compatibility for identifier names.
1875 @end table
1876
1877 @noindent
1878 For precise data on the encodings permitted, and the uppercase and lowercase
1879 equivalences that are recognized, see the file @file{csets.adb} in
1880 the GNAT compiler sources. You will need to obtain a full source release
1881 of GNAT to obtain this file.
1882
1883 @node Wide Character Encodings
1884 @subsection Wide Character Encodings
1885
1886 @noindent
1887 GNAT allows wide character codes to appear in character and string
1888 literals, and also optionally in identifiers, by means of the following
1889 possible encoding schemes:
1890
1891 @table @asis
1892
1893 @item Hex Coding
1894 In this encoding, a wide character is represented by the following five
1895 character sequence:
1896
1897 @smallexample
1898 ESC a b c d
1899 @end smallexample
1900
1901 @noindent
1902 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1903 characters (using uppercase letters) of the wide character code. For
1904 example, ESC A345 is used to represent the wide character with code
1905 @code{16#A345#}.
1906 This scheme is compatible with use of the full Wide_Character set.
1907
1908 @item Upper-Half Coding
1909 @cindex Upper-Half Coding
1910 The wide character with encoding @code{16#abcd#} where the upper bit is on
1911 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1912 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1913 character, but is not required to be in the upper half. This method can
1914 be also used for shift-JIS or EUC, where the internal coding matches the
1915 external coding.
1916
1917 @item Shift JIS Coding
1918 @cindex Shift JIS Coding
1919 A wide character is represented by a two-character sequence,
1920 @code{16#ab#} and
1921 @code{16#cd#}, with the restrictions described for upper-half encoding as
1922 described above. The internal character code is the corresponding JIS
1923 character according to the standard algorithm for Shift-JIS
1924 conversion. Only characters defined in the JIS code set table can be
1925 used with this encoding method.
1926
1927 @item EUC Coding
1928 @cindex EUC Coding
1929 A wide character is represented by a two-character sequence
1930 @code{16#ab#} and
1931 @code{16#cd#}, with both characters being in the upper half. The internal
1932 character code is the corresponding JIS character according to the EUC
1933 encoding algorithm. Only characters defined in the JIS code set table
1934 can be used with this encoding method.
1935
1936 @item UTF-8 Coding
1937 A wide character is represented using
1938 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1939 10646-1/Am.2. Depending on the character value, the representation
1940 is a one, two, or three byte sequence:
1941 @smallexample
1942 @iftex
1943 @leftskip=.7cm
1944 @end iftex
1945 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1946 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1947 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1948
1949 @end smallexample
1950
1951 @noindent
1952 where the @var{xxx} bits correspond to the left-padded bits of the
1953 16-bit character value. Note that all lower half ASCII characters
1954 are represented as ASCII bytes and all upper half characters and
1955 other wide characters are represented as sequences of upper-half
1956 (The full UTF-8 scheme allows for encoding 31-bit characters as
1957 6-byte sequences, but in this implementation, all UTF-8 sequences
1958 of four or more bytes length will be treated as illegal).
1959 @item Brackets Coding
1960 In this encoding, a wide character is represented by the following eight
1961 character sequence:
1962
1963 @smallexample
1964 [ " a b c d " ]
1965 @end smallexample
1966
1967 @noindent
1968 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1969 characters (using uppercase letters) of the wide character code. For
1970 example, [``A345''] is used to represent the wide character with code
1971 @code{16#A345#}. It is also possible (though not required) to use the
1972 Brackets coding for upper half characters. For example, the code
1973 @code{16#A3#} can be represented as @code{[``A3'']}.
1974
1975 This scheme is compatible with use of the full Wide_Character set,
1976 and is also the method used for wide character encoding in the standard
1977 ACVC (Ada Compiler Validation Capability) test suite distributions.
1978
1979 @end table
1980
1981 @noindent
1982 Note: Some of these coding schemes do not permit the full use of the
1983 Ada character set. For example, neither Shift JIS, nor EUC allow the
1984 use of the upper half of the Latin-1 set.
1985
1986 @node File Naming Rules
1987 @section File Naming Rules
1988
1989 @noindent
1990 The default file name is determined by the name of the unit that the
1991 file contains. The name is formed by taking the full expanded name of
1992 the unit and replacing the separating dots with hyphens and using
1993 ^lowercase^uppercase^ for all letters.
1994
1995 An exception arises if the file name generated by the above rules starts
1996 with one of the characters
1997 @ifset vms
1998 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
1999 @end ifset
2000 @ifclear vms
2001 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
2002 @end ifclear
2003 and the second character is a
2004 minus. In this case, the character ^tilde^dollar sign^ is used in place
2005 of the minus. The reason for this special rule is to avoid clashes with
2006 the standard names for child units of the packages System, Ada,
2007 Interfaces, and GNAT, which use the prefixes
2008 @ifset vms
2009 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2010 @end ifset
2011 @ifclear vms
2012 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2013 @end ifclear
2014 respectively.
2015
2016 The file extension is @file{.ads} for a spec and
2017 @file{.adb} for a body. The following list shows some
2018 examples of these rules.
2019
2020 @table @file
2021 @item main.ads
2022 Main (spec)
2023 @item main.adb
2024 Main (body)
2025 @item arith_functions.ads
2026 Arith_Functions (package spec)
2027 @item arith_functions.adb
2028 Arith_Functions (package body)
2029 @item func-spec.ads
2030 Func.Spec (child package spec)
2031 @item func-spec.adb
2032 Func.Spec (child package body)
2033 @item main-sub.adb
2034 Sub (subunit of Main)
2035 @item ^a~bad.adb^A$BAD.ADB^
2036 A.Bad (child package body)
2037 @end table
2038
2039 @noindent
2040 Following these rules can result in excessively long
2041 file names if corresponding
2042 unit names are long (for example, if child units or subunits are
2043 heavily nested). An option is available to shorten such long file names
2044 (called file name ``krunching''). This may be particularly useful when
2045 programs being developed with GNAT are to be used on operating systems
2046 with limited file name lengths. @xref{Using gnatkr}.
2047
2048 Of course, no file shortening algorithm can guarantee uniqueness over
2049 all possible unit names; if file name krunching is used, it is your
2050 responsibility to ensure no name clashes occur. Alternatively you
2051 can specify the exact file names that you want used, as described
2052 in the next section. Finally, if your Ada programs are migrating from a
2053 compiler with a different naming convention, you can use the gnatchop
2054 utility to produce source files that follow the GNAT naming conventions.
2055 (For details @pxref{Renaming Files Using gnatchop}.)
2056
2057 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2058 systems, case is not significant. So for example on @code{Windows XP}
2059 if the canonical name is @code{main-sub.adb}, you can use the file name
2060 @code{Main-Sub.adb} instead. However, case is significant for other
2061 operating systems, so for example, if you want to use other than
2062 canonically cased file names on a Unix system, you need to follow
2063 the procedures described in the next section.
2064
2065 @node Using Other File Names
2066 @section Using Other File Names
2067 @cindex File names
2068
2069 @noindent
2070 In the previous section, we have described the default rules used by
2071 GNAT to determine the file name in which a given unit resides. It is
2072 often convenient to follow these default rules, and if you follow them,
2073 the compiler knows without being explicitly told where to find all
2074 the files it needs.
2075
2076 However, in some cases, particularly when a program is imported from
2077 another Ada compiler environment, it may be more convenient for the
2078 programmer to specify which file names contain which units. GNAT allows
2079 arbitrary file names to be used by means of the Source_File_Name pragma.
2080 The form of this pragma is as shown in the following examples:
2081 @cindex Source_File_Name pragma
2082
2083 @smallexample @c ada
2084 @cartouche
2085 pragma Source_File_Name (My_Utilities.Stacks,
2086   Spec_File_Name => "myutilst_a.ada");
2087 pragma Source_File_name (My_Utilities.Stacks,
2088   Body_File_Name => "myutilst.ada");
2089 @end cartouche
2090 @end smallexample
2091
2092 @noindent
2093 As shown in this example, the first argument for the pragma is the unit
2094 name (in this example a child unit). The second argument has the form
2095 of a named association. The identifier
2096 indicates whether the file name is for a spec or a body;
2097 the file name itself is given by a string literal.
2098
2099 The source file name pragma is a configuration pragma, which means that
2100 normally it will be placed in the @file{gnat.adc}
2101 file used to hold configuration
2102 pragmas that apply to a complete compilation environment.
2103 For more details on how the @file{gnat.adc} file is created and used
2104 see @ref{Handling of Configuration Pragmas}.
2105 @cindex @file{gnat.adc}
2106
2107 @ifclear vms
2108 GNAT allows completely arbitrary file names to be specified using the
2109 source file name pragma. However, if the file name specified has an
2110 extension other than @file{.ads} or @file{.adb} it is necessary to use
2111 a special syntax when compiling the file. The name in this case must be
2112 preceded by the special sequence @option{-x} followed by a space and the name
2113 of the language, here @code{ada}, as in:
2114
2115 @smallexample
2116 $ gcc -c -x ada peculiar_file_name.sim
2117 @end smallexample
2118 @end ifclear
2119
2120 @noindent
2121 @command{gnatmake} handles non-standard file names in the usual manner (the
2122 non-standard file name for the main program is simply used as the
2123 argument to gnatmake). Note that if the extension is also non-standard,
2124 then it must be included in the @command{gnatmake} command, it may not
2125 be omitted.
2126
2127 @node Alternative File Naming Schemes
2128 @section Alternative File Naming Schemes
2129 @cindex File naming schemes, alternative
2130 @cindex File names
2131
2132 In the previous section, we described the use of the @code{Source_File_Name}
2133 pragma to allow arbitrary names to be assigned to individual source files.
2134 However, this approach requires one pragma for each file, and especially in
2135 large systems can result in very long @file{gnat.adc} files, and also create
2136 a maintenance problem.
2137
2138 GNAT also provides a facility for specifying systematic file naming schemes
2139 other than the standard default naming scheme previously described. An
2140 alternative scheme for naming is specified by the use of
2141 @code{Source_File_Name} pragmas having the following format:
2142 @cindex Source_File_Name pragma
2143
2144 @smallexample @c ada
2145 pragma Source_File_Name (
2146    Spec_File_Name  => FILE_NAME_PATTERN
2147  @r{[},Casing          => CASING_SPEC@r{]}
2148  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2149
2150 pragma Source_File_Name (
2151    Body_File_Name  => FILE_NAME_PATTERN
2152  @r{[},Casing          => CASING_SPEC@r{]}
2153  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2154
2155 pragma Source_File_Name (
2156    Subunit_File_Name  => FILE_NAME_PATTERN
2157  @r{[},Casing             => CASING_SPEC@r{]}
2158  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
2159
2160 FILE_NAME_PATTERN ::= STRING_LITERAL
2161 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2162 @end smallexample
2163
2164 @noindent
2165 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2166 It contains a single asterisk character, and the unit name is substituted
2167 systematically for this asterisk. The optional parameter
2168 @code{Casing} indicates
2169 whether the unit name is to be all upper-case letters, all lower-case letters,
2170 or mixed-case. If no
2171 @code{Casing} parameter is used, then the default is all
2172 ^lower-case^upper-case^.
2173
2174 The optional @code{Dot_Replacement} string is used to replace any periods
2175 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2176 argument is used then separating dots appear unchanged in the resulting
2177 file name.
2178 Although the above syntax indicates that the
2179 @code{Casing} argument must appear
2180 before the @code{Dot_Replacement} argument, but it
2181 is also permissible to write these arguments in the opposite order.
2182
2183 As indicated, it is possible to specify different naming schemes for
2184 bodies, specs, and subunits. Quite often the rule for subunits is the
2185 same as the rule for bodies, in which case, there is no need to give
2186 a separate @code{Subunit_File_Name} rule, and in this case the
2187 @code{Body_File_name} rule is used for subunits as well.
2188
2189 The separate rule for subunits can also be used to implement the rather
2190 unusual case of a compilation environment (e.g.@: a single directory) which
2191 contains a subunit and a child unit with the same unit name. Although
2192 both units cannot appear in the same partition, the Ada Reference Manual
2193 allows (but does not require) the possibility of the two units coexisting
2194 in the same environment.
2195
2196 The file name translation works in the following steps:
2197
2198 @itemize @bullet
2199
2200 @item
2201 If there is a specific @code{Source_File_Name} pragma for the given unit,
2202 then this is always used, and any general pattern rules are ignored.
2203
2204 @item
2205 If there is a pattern type @code{Source_File_Name} pragma that applies to
2206 the unit, then the resulting file name will be used if the file exists. If
2207 more than one pattern matches, the latest one will be tried first, and the
2208 first attempt resulting in a reference to a file that exists will be used.
2209
2210 @item
2211 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2212 for which the corresponding file exists, then the standard GNAT default
2213 naming rules are used.
2214
2215 @end itemize
2216
2217 @noindent
2218 As an example of the use of this mechanism, consider a commonly used scheme
2219 in which file names are all lower case, with separating periods copied
2220 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2221 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2222 two pragmas appear:
2223
2224 @smallexample @c ada
2225 pragma Source_File_Name
2226   (Spec_File_Name => "*.1.ada");
2227 pragma Source_File_Name
2228   (Body_File_Name => "*.2.ada");
2229 @end smallexample
2230
2231 @noindent
2232 The default GNAT scheme is actually implemented by providing the following
2233 default pragmas internally:
2234
2235 @smallexample @c ada
2236 pragma Source_File_Name
2237   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2238 pragma Source_File_Name
2239   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2240 @end smallexample
2241
2242 @noindent
2243 Our final example implements a scheme typically used with one of the
2244 Ada 83 compilers, where the separator character for subunits was ``__''
2245 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2246 by adding @file{.ADA}, and subunits by
2247 adding @file{.SEP}. All file names were
2248 upper case. Child units were not present of course since this was an
2249 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2250 the same double underscore separator for child units.
2251
2252 @smallexample @c ada
2253 pragma Source_File_Name
2254   (Spec_File_Name => "*_.ADA",
2255    Dot_Replacement => "__",
2256    Casing = Uppercase);
2257 pragma Source_File_Name
2258   (Body_File_Name => "*.ADA",
2259    Dot_Replacement => "__",
2260    Casing = Uppercase);
2261 pragma Source_File_Name
2262   (Subunit_File_Name => "*.SEP",
2263    Dot_Replacement => "__",
2264    Casing = Uppercase);
2265 @end smallexample
2266
2267 @node Generating Object Files
2268 @section Generating Object Files
2269
2270 @noindent
2271 An Ada program consists of a set of source files, and the first step in
2272 compiling the program is to generate the corresponding object files.
2273 These are generated by compiling a subset of these source files.
2274 The files you need to compile are the following:
2275
2276 @itemize @bullet
2277 @item
2278 If a package spec has no body, compile the package spec to produce the
2279 object file for the package.
2280
2281 @item
2282 If a package has both a spec and a body, compile the body to produce the
2283 object file for the package. The source file for the package spec need
2284 not be compiled in this case because there is only one object file, which
2285 contains the code for both the spec and body of the package.
2286
2287 @item
2288 For a subprogram, compile the subprogram body to produce the object file
2289 for the subprogram. The spec, if one is present, is as usual in a
2290 separate file, and need not be compiled.
2291
2292 @item
2293 @cindex Subunits
2294 In the case of subunits, only compile the parent unit. A single object
2295 file is generated for the entire subunit tree, which includes all the
2296 subunits.
2297
2298 @item
2299 Compile child units independently of their parent units
2300 (though, of course, the spec of all the ancestor unit must be present in order
2301 to compile a child unit).
2302
2303 @item
2304 @cindex Generics
2305 Compile generic units in the same manner as any other units. The object
2306 files in this case are small dummy files that contain at most the
2307 flag used for elaboration checking. This is because GNAT always handles generic
2308 instantiation by means of macro expansion. However, it is still necessary to
2309 compile generic units, for dependency checking and elaboration purposes.
2310 @end itemize
2311
2312 @noindent
2313 The preceding rules describe the set of files that must be compiled to
2314 generate the object files for a program. Each object file has the same
2315 name as the corresponding source file, except that the extension is
2316 @file{.o} as usual.
2317
2318 You may wish to compile other files for the purpose of checking their
2319 syntactic and semantic correctness. For example, in the case where a
2320 package has a separate spec and body, you would not normally compile the
2321 spec. However, it is convenient in practice to compile the spec to make
2322 sure it is error-free before compiling clients of this spec, because such
2323 compilations will fail if there is an error in the spec.
2324
2325 GNAT provides an option for compiling such files purely for the
2326 purposes of checking correctness; such compilations are not required as
2327 part of the process of building a program. To compile a file in this
2328 checking mode, use the @option{-gnatc} switch.
2329
2330 @node Source Dependencies
2331 @section Source Dependencies
2332
2333 @noindent
2334 A given object file clearly depends on the source file which is compiled
2335 to produce it. Here we are using @dfn{depends} in the sense of a typical
2336 @code{make} utility; in other words, an object file depends on a source
2337 file if changes to the source file require the object file to be
2338 recompiled.
2339 In addition to this basic dependency, a given object may depend on
2340 additional source files as follows:
2341
2342 @itemize @bullet
2343 @item
2344 If a file being compiled @code{with}'s a unit @var{X}, the object file
2345 depends on the file containing the spec of unit @var{X}. This includes
2346 files that are @code{with}'ed implicitly either because they are parents
2347 of @code{with}'ed child units or they are run-time units required by the
2348 language constructs used in a particular unit.
2349
2350 @item
2351 If a file being compiled instantiates a library level generic unit, the
2352 object file depends on both the spec and body files for this generic
2353 unit.
2354
2355 @item
2356 If a file being compiled instantiates a generic unit defined within a
2357 package, the object file depends on the body file for the package as
2358 well as the spec file.
2359
2360 @item
2361 @findex Inline
2362 @cindex @option{-gnatn} switch
2363 If a file being compiled contains a call to a subprogram for which
2364 pragma @code{Inline} applies and inlining is activated with the
2365 @option{-gnatn} switch, the object file depends on the file containing the
2366 body of this subprogram as well as on the file containing the spec. Note
2367 that for inlining to actually occur as a result of the use of this switch,
2368 it is necessary to compile in optimizing mode.
2369
2370 @cindex @option{-gnatN} switch
2371 The use of @option{-gnatN} activates  inlining optimization
2372 that is performed by the front end of the compiler. This inlining does
2373 not require that the code generation be optimized. Like @option{-gnatn},
2374 the use of this switch generates additional dependencies.
2375
2376 When using a gcc-based back end (in practice this means using any version
2377 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2378 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2379 Historically front end inlining was more extensive than the gcc back end
2380 inlining, but that is no longer the case.
2381
2382 @item
2383 If an object file @file{O} depends on the proper body of a subunit through
2384 inlining or instantiation, it depends on the parent unit of the subunit.
2385 This means that any modification of the parent unit or one of its subunits
2386 affects the compilation of @file{O}.
2387
2388 @item
2389 The object file for a parent unit depends on all its subunit body files.
2390
2391 @item
2392 The previous two rules meant that for purposes of computing dependencies and
2393 recompilation, a body and all its subunits are treated as an indivisible whole.
2394
2395 @noindent
2396 These rules are applied transitively: if unit @code{A} @code{with}'s
2397 unit @code{B}, whose elaboration calls an inlined procedure in package
2398 @code{C}, the object file for unit @code{A} will depend on the body of
2399 @code{C}, in file @file{c.adb}.
2400
2401 The set of dependent files described by these rules includes all the
2402 files on which the unit is semantically dependent, as dictated by the
2403 Ada language standard. However, it is a superset of what the
2404 standard describes, because it includes generic, inline, and subunit
2405 dependencies.
2406
2407 An object file must be recreated by recompiling the corresponding source
2408 file if any of the source files on which it depends are modified. For
2409 example, if the @code{make} utility is used to control compilation,
2410 the rule for an Ada object file must mention all the source files on
2411 which the object file depends, according to the above definition.
2412 The determination of the necessary
2413 recompilations is done automatically when one uses @command{gnatmake}.
2414 @end itemize
2415
2416 @node The Ada Library Information Files
2417 @section The Ada Library Information Files
2418 @cindex Ada Library Information files
2419 @cindex @file{ALI} files
2420
2421 @noindent
2422 Each compilation actually generates two output files. The first of these
2423 is the normal object file that has a @file{.o} extension. The second is a
2424 text file containing full dependency information. It has the same
2425 name as the source file, but an @file{.ali} extension.
2426 This file is known as the Ada Library Information (@file{ALI}) file.
2427 The following information is contained in the @file{ALI} file.
2428
2429 @itemize @bullet
2430 @item
2431 Version information (indicates which version of GNAT was used to compile
2432 the unit(s) in question)
2433
2434 @item
2435 Main program information (including priority and time slice settings,
2436 as well as the wide character encoding used during compilation).
2437
2438 @item
2439 List of arguments used in the @command{gcc} command for the compilation
2440
2441 @item
2442 Attributes of the unit, including configuration pragmas used, an indication
2443 of whether the compilation was successful, exception model used etc.
2444
2445 @item
2446 A list of relevant restrictions applying to the unit (used for consistency)
2447 checking.
2448
2449 @item
2450 Categorization information (e.g.@: use of pragma @code{Pure}).
2451
2452 @item
2453 Information on all @code{with}'ed units, including presence of
2454 @code{Elaborate} or @code{Elaborate_All} pragmas.
2455
2456 @item
2457 Information from any @code{Linker_Options} pragmas used in the unit
2458
2459 @item
2460 Information on the use of @code{Body_Version} or @code{Version}
2461 attributes in the unit.
2462
2463 @item
2464 Dependency information. This is a list of files, together with
2465 time stamp and checksum information. These are files on which
2466 the unit depends in the sense that recompilation is required
2467 if any of these units are modified.
2468
2469 @item
2470 Cross-reference data. Contains information on all entities referenced
2471 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2472 provide cross-reference information.
2473
2474 @end itemize
2475
2476 @noindent
2477 For a full detailed description of the format of the @file{ALI} file,
2478 see the source of the body of unit @code{Lib.Writ}, contained in file
2479 @file{lib-writ.adb} in the GNAT compiler sources.
2480
2481 @node Binding an Ada Program
2482 @section Binding an Ada Program
2483
2484 @noindent
2485 When using languages such as C and C++, once the source files have been
2486 compiled the only remaining step in building an executable program
2487 is linking the object modules together. This means that it is possible to
2488 link an inconsistent version of a program, in which two units have
2489 included different versions of the same header.
2490
2491 The rules of Ada do not permit such an inconsistent program to be built.
2492 For example, if two clients have different versions of the same package,
2493 it is illegal to build a program containing these two clients.
2494 These rules are enforced by the GNAT binder, which also determines an
2495 elaboration order consistent with the Ada rules.
2496
2497 The GNAT binder is run after all the object files for a program have
2498 been created. It is given the name of the main program unit, and from
2499 this it determines the set of units required by the program, by reading the
2500 corresponding ALI files. It generates error messages if the program is
2501 inconsistent or if no valid order of elaboration exists.
2502
2503 If no errors are detected, the binder produces a main program, in Ada by
2504 default, that contains calls to the elaboration procedures of those
2505 compilation unit that require them, followed by
2506 a call to the main program. This Ada program is compiled to generate the
2507 object file for the main program. The name of
2508 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2509 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2510 main program unit.
2511
2512 Finally, the linker is used to build the resulting executable program,
2513 using the object from the main program from the bind step as well as the
2514 object files for the Ada units of the program.
2515
2516 @node Mixed Language Programming
2517 @section Mixed Language Programming
2518 @cindex Mixed Language Programming
2519
2520 @noindent
2521 This section describes how to develop a mixed-language program,
2522 specifically one that comprises units in both Ada and C.
2523
2524 @menu
2525 * Interfacing to C::
2526 * Calling Conventions::
2527 @end menu
2528
2529 @node Interfacing to C
2530 @subsection Interfacing to C
2531 @noindent
2532 Interfacing Ada with a foreign language such as C involves using
2533 compiler directives to import and/or export entity definitions in each
2534 language---using @code{extern} statements in C, for instance, and the
2535 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2536 A full treatment of these topics is provided in Appendix B, section 1
2537 of the Ada Reference Manual.
2538
2539 There are two ways to build a program using GNAT that contains some Ada
2540 sources and some foreign language sources, depending on whether or not
2541 the main subprogram is written in Ada.  Here is a source example with
2542 the main subprogram in Ada:
2543
2544 @smallexample
2545 /* file1.c */
2546 #include <stdio.h>
2547
2548 void print_num (int num)
2549 @{
2550   printf ("num is %d.\n", num);
2551   return;
2552 @}
2553
2554 /* file2.c */
2555
2556 /* num_from_Ada is declared in my_main.adb */
2557 extern int num_from_Ada;
2558
2559 int get_num (void)
2560 @{
2561   return num_from_Ada;
2562 @}
2563 @end smallexample
2564
2565 @smallexample @c ada
2566 --  my_main.adb
2567 procedure My_Main is
2568
2569    --  Declare then export an Integer entity called num_from_Ada
2570    My_Num : Integer := 10;
2571    pragma Export (C, My_Num, "num_from_Ada");
2572
2573    --  Declare an Ada function spec for Get_Num, then use
2574    --  C function get_num for the implementation.
2575    function Get_Num return Integer;
2576    pragma Import (C, Get_Num, "get_num");
2577
2578    --  Declare an Ada procedure spec for Print_Num, then use
2579    --  C function print_num for the implementation.
2580    procedure Print_Num (Num : Integer);
2581    pragma Import (C, Print_Num, "print_num");
2582
2583 begin
2584    Print_Num (Get_Num);
2585 end My_Main;
2586 @end smallexample
2587
2588 @enumerate
2589 @item
2590 To build this example, first compile the foreign language files to
2591 generate object files:
2592 @smallexample
2593 ^gcc -c file1.c^gcc -c FILE1.C^
2594 ^gcc -c file2.c^gcc -c FILE2.C^
2595 @end smallexample
2596
2597 @item
2598 Then, compile the Ada units to produce a set of object files and ALI
2599 files:
2600 @smallexample
2601 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2602 @end smallexample
2603
2604 @item
2605 Run the Ada binder on the Ada main program:
2606 @smallexample
2607 gnatbind my_main.ali
2608 @end smallexample
2609
2610 @item
2611 Link the Ada main program, the Ada objects and the other language
2612 objects:
2613 @smallexample
2614 gnatlink my_main.ali file1.o file2.o
2615 @end smallexample
2616 @end enumerate
2617
2618 The last three steps can be grouped in a single command:
2619 @smallexample
2620 gnatmake my_main.adb -largs file1.o file2.o
2621 @end smallexample
2622
2623 @cindex Binder output file
2624 @noindent
2625 If the main program is in a language other than Ada, then you may have
2626 more than one entry point into the Ada subsystem. You must use a special
2627 binder option to generate callable routines that initialize and
2628 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2629 Calls to the initialization and finalization routines must be inserted
2630 in the main program, or some other appropriate point in the code. The
2631 call to initialize the Ada units must occur before the first Ada
2632 subprogram is called, and the call to finalize the Ada units must occur
2633 after the last Ada subprogram returns. The binder will place the
2634 initialization and finalization subprograms into the
2635 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2636 sources.  To illustrate, we have the following example:
2637
2638 @smallexample
2639 /* main.c */
2640 extern void adainit (void);
2641 extern void adafinal (void);
2642 extern int add (int, int);
2643 extern int sub (int, int);
2644
2645 int main (int argc, char *argv[])
2646 @{
2647   int a = 21, b = 7;
2648
2649   adainit();
2650
2651   /* Should print "21 + 7 = 28" */
2652   printf ("%d + %d = %d\n", a, b, add (a, b));
2653   /* Should print "21 - 7 = 14" */
2654   printf ("%d - %d = %d\n", a, b, sub (a, b));
2655
2656   adafinal();
2657 @}
2658 @end smallexample
2659
2660 @smallexample @c ada
2661 --  unit1.ads
2662 package Unit1 is
2663    function Add (A, B : Integer) return Integer;
2664    pragma Export (C, Add, "add");
2665 end Unit1;
2666
2667 --  unit1.adb
2668 package body Unit1 is
2669    function Add (A, B : Integer) return Integer is
2670    begin
2671       return A + B;
2672    end Add;
2673 end Unit1;
2674
2675 --  unit2.ads
2676 package Unit2 is
2677    function Sub (A, B : Integer) return Integer;
2678    pragma Export (C, Sub, "sub");
2679 end Unit2;
2680
2681 --  unit2.adb
2682 package body Unit2 is
2683    function Sub (A, B : Integer) return Integer is
2684    begin
2685       return A - B;
2686    end Sub;
2687 end Unit2;
2688 @end smallexample
2689
2690 @enumerate
2691 @item
2692 The build procedure for this application is similar to the last
2693 example's.  First, compile the foreign language files to generate object
2694 files:
2695 @smallexample
2696 ^gcc -c main.c^gcc -c main.c^
2697 @end smallexample
2698
2699 @item
2700 Next, compile the Ada units to produce a set of object files and ALI
2701 files:
2702 @smallexample
2703 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2704 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2705 @end smallexample
2706
2707 @item
2708 Run the Ada binder on every generated ALI file.  Make sure to use the
2709 @option{-n} option to specify a foreign main program:
2710 @smallexample
2711 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2712 @end smallexample
2713
2714 @item
2715 Link the Ada main program, the Ada objects and the foreign language
2716 objects. You need only list the last ALI file here:
2717 @smallexample
2718 gnatlink unit2.ali main.o -o exec_file
2719 @end smallexample
2720
2721 This procedure yields a binary executable called @file{exec_file}.
2722 @end enumerate
2723
2724 @noindent
2725 Depending on the circumstances (for example when your non-Ada main object
2726 does not provide symbol @code{main}), you may also need to instruct the
2727 GNAT linker not to include the standard startup objects by passing the
2728 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2729
2730 @node Calling Conventions
2731 @subsection Calling Conventions
2732 @cindex Foreign Languages
2733 @cindex Calling Conventions
2734 GNAT follows standard calling sequence conventions and will thus interface
2735 to any other language that also follows these conventions. The following
2736 Convention identifiers are recognized by GNAT:
2737
2738 @table @code
2739 @cindex Interfacing to Ada
2740 @cindex Other Ada compilers
2741 @cindex Convention Ada
2742 @item Ada
2743 This indicates that the standard Ada calling sequence will be
2744 used and all Ada data items may be passed without any limitations in the
2745 case where GNAT is used to generate both the caller and callee. It is also
2746 possible to mix GNAT generated code and code generated by another Ada
2747 compiler. In this case, the data types should be restricted to simple
2748 cases, including primitive types. Whether complex data types can be passed
2749 depends on the situation. Probably it is safe to pass simple arrays, such
2750 as arrays of integers or floats. Records may or may not work, depending
2751 on whether both compilers lay them out identically. Complex structures
2752 involving variant records, access parameters, tasks, or protected types,
2753 are unlikely to be able to be passed.
2754
2755 Note that in the case of GNAT running
2756 on a platform that supports HP Ada 83, a higher degree of compatibility
2757 can be guaranteed, and in particular records are layed out in an identical
2758 manner in the two compilers. Note also that if output from two different
2759 compilers is mixed, the program is responsible for dealing with elaboration
2760 issues. Probably the safest approach is to write the main program in the
2761 version of Ada other than GNAT, so that it takes care of its own elaboration
2762 requirements, and then call the GNAT-generated adainit procedure to ensure
2763 elaboration of the GNAT components. Consult the documentation of the other
2764 Ada compiler for further details on elaboration.
2765
2766 However, it is not possible to mix the tasking run time of GNAT and
2767 HP Ada 83, All the tasking operations must either be entirely within
2768 GNAT compiled sections of the program, or entirely within HP Ada 83
2769 compiled sections of the program.
2770
2771 @cindex Interfacing to Assembly
2772 @cindex Convention Assembler
2773 @item Assembler
2774 Specifies assembler as the convention. In practice this has the
2775 same effect as convention Ada (but is not equivalent in the sense of being
2776 considered the same convention).
2777
2778 @cindex Convention Asm
2779 @findex Asm
2780 @item Asm
2781 Equivalent to Assembler.
2782
2783 @cindex Interfacing to COBOL
2784 @cindex Convention COBOL
2785 @findex COBOL
2786 @item COBOL
2787 Data will be passed according to the conventions described
2788 in section B.4 of the Ada Reference Manual.
2789
2790 @findex C
2791 @cindex Interfacing to C
2792 @cindex Convention C
2793 @item C
2794 Data will be passed according to the conventions described
2795 in section B.3 of the Ada Reference Manual.
2796
2797 A note on interfacing to a C ``varargs'' function:
2798 @findex C varargs function
2799 @cindex Interfacing to C varargs function
2800 @cindex varargs function interfaces
2801
2802 @itemize @bullet
2803 @item
2804 In C, @code{varargs} allows a function to take a variable number of
2805 arguments. There is no direct equivalent in this to Ada. One
2806 approach that can be used is to create a C wrapper for each
2807 different profile and then interface to this C wrapper. For
2808 example, to print an @code{int} value using @code{printf},
2809 create a C function @code{printfi} that takes two arguments, a
2810 pointer to a string and an int, and calls @code{printf}.
2811 Then in the Ada program, use pragma @code{Import} to
2812 interface to @code{printfi}.
2813
2814 @item
2815 It may work on some platforms to directly interface to
2816 a @code{varargs} function by providing a specific Ada profile
2817 for a particular call. However, this does not work on
2818 all platforms, since there is no guarantee that the
2819 calling sequence for a two argument normal C function
2820 is the same as for calling a @code{varargs} C function with
2821 the same two arguments.
2822 @end itemize
2823
2824 @cindex Convention Default
2825 @findex Default
2826 @item Default
2827 Equivalent to C.
2828
2829 @cindex Convention External
2830 @findex External
2831 @item External
2832 Equivalent to C.
2833
2834 @ifclear vms
2835 @findex C++
2836 @cindex Interfacing to C++
2837 @cindex Convention C++
2838 @item C_Plus_Plus (or CPP)
2839 This stands for C++. For most purposes this is identical to C.
2840 See the separate description of the specialized GNAT pragmas relating to
2841 C++ interfacing for further details.
2842 @end ifclear
2843
2844 @findex Fortran
2845 @cindex Interfacing to Fortran
2846 @cindex Convention Fortran
2847 @item Fortran
2848 Data will be passed according to the conventions described
2849 in section B.5 of the Ada Reference Manual.
2850
2851 @item Intrinsic
2852 This applies to an intrinsic operation, as defined in the Ada
2853 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2854 this means that the body of the subprogram is provided by the compiler itself,
2855 usually by means of an efficient code sequence, and that the user does not
2856 supply an explicit body for it. In an application program, the pragma may
2857 be applied to the following sets of names:
2858
2859 @itemize @bullet
2860 @item
2861 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2862 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2863 two formal parameters. The
2864 first one must be a signed integer type or a modular type with a binary
2865 modulus, and the second parameter must be of type Natural.
2866 The return type must be the same as the type of the first argument. The size
2867 of this type can only be 8, 16, 32, or 64.
2868
2869 @item
2870 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2871 The corresponding operator declaration must have parameters and result type
2872 that have the same root numeric type (for example, all three are long_float
2873 types). This simplifies the definition of operations that use type checking
2874 to perform dimensional checks:
2875
2876 @smallexample @c ada
2877 type Distance is new Long_Float;
2878 type Time     is new Long_Float;
2879 type Velocity is new Long_Float;
2880 function "/" (D : Distance; T : Time)
2881   return Velocity;
2882 pragma Import (Intrinsic, "/");
2883 @end smallexample
2884
2885 @noindent
2886 This common idiom is often programmed with a generic definition and an
2887 explicit body. The pragma makes it simpler to introduce such declarations.
2888 It incurs no overhead in compilation time or code size, because it is
2889 implemented as a single machine instruction.
2890
2891 @item
2892 General subprogram entities, to bind an Ada subprogram declaration to
2893 a compiler builtin by name with back-ends where such interfaces are
2894 available. A typical example is the set of ``__builtin'' functions
2895 exposed by the GCC back-end, as in the following example:
2896
2897 @smallexample @c ada
2898    function builtin_sqrt (F : Float) return Float;
2899    pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2900 @end smallexample
2901
2902 Most of the GCC builtins are accessible this way, and as for other
2903 import conventions (e.g. C), it is the user's responsibility to ensure
2904 that the Ada subprogram profile matches the underlying builtin
2905 expectations.
2906 @end itemize
2907
2908 @noindent
2909
2910 @ifset unw
2911 @findex Stdcall
2912 @cindex Convention Stdcall
2913 @item Stdcall
2914 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2915 and specifies that the @code{Stdcall} calling sequence will be used,
2916 as defined by the NT API. Nevertheless, to ease building
2917 cross-platform bindings this convention will be handled as a @code{C} calling
2918 convention on non-Windows platforms.
2919
2920 @findex DLL
2921 @cindex Convention DLL
2922 @item DLL
2923 This is equivalent to @code{Stdcall}.
2924
2925 @findex Win32
2926 @cindex Convention Win32
2927 @item Win32
2928 This is equivalent to @code{Stdcall}.
2929 @end ifset
2930
2931 @findex Stubbed
2932 @cindex Convention Stubbed
2933 @item Stubbed
2934 This is a special convention that indicates that the compiler
2935 should provide a stub body that raises @code{Program_Error}.
2936 @end table
2937
2938 @noindent
2939 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2940 that can be used to parametrize conventions and allow additional synonyms
2941 to be specified. For example if you have legacy code in which the convention
2942 identifier Fortran77 was used for Fortran, you can use the configuration
2943 pragma:
2944
2945 @smallexample @c ada
2946 pragma Convention_Identifier (Fortran77, Fortran);
2947 @end smallexample
2948
2949 @noindent
2950 And from now on the identifier Fortran77 may be used as a convention
2951 identifier (for example in an @code{Import} pragma) with the same
2952 meaning as Fortran.
2953
2954 @ifclear vms
2955 @node Building Mixed Ada & C++ Programs
2956 @section Building Mixed Ada and C++ Programs
2957
2958 @noindent
2959 A programmer inexperienced with mixed-language development may find that
2960 building an application containing both Ada and C++ code can be a
2961 challenge.  This section gives a few
2962 hints that should make this task easier. The first section addresses
2963 the differences between interfacing with C and interfacing with C++.
2964 The second section
2965 looks into the delicate problem of linking the complete application from
2966 its Ada and C++ parts. The last section gives some hints on how the GNAT
2967 run-time library can be adapted in order to allow inter-language dispatching
2968 with a new C++ compiler.
2969
2970 @menu
2971 * Interfacing to C++::
2972 * Linking a Mixed C++ & Ada Program::
2973 * A Simple Example::
2974 * Interfacing with C++ at the Class Level::
2975 @end menu
2976
2977 @node Interfacing to C++
2978 @subsection Interfacing to C++
2979
2980 @noindent
2981 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2982 generating code that is compatible with the G++ Application Binary
2983 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2984
2985 @noindent
2986 Interfacing can be done at 3 levels: simple data, subprograms, and
2987 classes. In the first two cases, GNAT offers a specific @code{Convention
2988 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2989 Usually, C++ mangles the names of subprograms, and currently, GNAT does
2990 not provide any help to solve the demangling problem. This problem can be
2991 addressed in two ways:
2992 @itemize @bullet
2993 @item
2994 by modifying the C++ code in order to force a C convention using
2995 the @code{extern "C"} syntax.
2996
2997 @item
2998 by figuring out the mangled name and use it as the Link_Name argument of
2999 the pragma import.
3000 @end itemize
3001
3002 @noindent
3003 Interfacing at the class level can be achieved by using the GNAT specific
3004 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
3005 gnat_rm, GNAT Reference Manual}, for additional information.
3006
3007 @node Linking a Mixed C++ & Ada Program
3008 @subsection Linking a Mixed C++ & Ada Program
3009
3010 @noindent
3011 Usually the linker of the C++ development system must be used to link
3012 mixed applications because most C++ systems will resolve elaboration
3013 issues (such as calling constructors on global class instances)
3014 transparently during the link phase. GNAT has been adapted to ease the
3015 use of a foreign linker for the last phase. Three cases can be
3016 considered:
3017 @enumerate
3018
3019 @item
3020 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3021 The C++ linker can simply be called by using the C++ specific driver
3022 called @code{c++}. Note that this setup is not very common because it
3023 may involve recompiling the whole GCC tree from sources, which makes it
3024 harder to upgrade the compilation system for one language without
3025 destabilizing the other.
3026
3027 @smallexample
3028 $ c++ -c file1.C
3029 $ c++ -c file2.C
3030 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3031 @end smallexample
3032
3033 @item
3034 Using GNAT and G++ from two different GCC installations: If both
3035 compilers are on the @env{PATH}, the previous method may be used. It is
3036 important to note that environment variables such as
3037 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3038 @env{GCC_ROOT} will affect both compilers
3039 at the same time and may make one of the two compilers operate
3040 improperly if set during invocation of the wrong compiler.  It is also
3041 very important that the linker uses the proper @file{libgcc.a} GCC
3042 library -- that is, the one from the C++ compiler installation. The
3043 implicit link command as suggested in the @command{gnatmake} command
3044 from the former example can be replaced by an explicit link command with
3045 the full-verbosity option in order to verify which library is used:
3046 @smallexample
3047 $ gnatbind ada_unit
3048 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3049 @end smallexample
3050 If there is a problem due to interfering environment variables, it can
3051 be worked around by using an intermediate script. The following example
3052 shows the proper script to use when GNAT has not been installed at its
3053 default location and g++ has been installed at its default location:
3054
3055 @smallexample
3056 $ cat ./my_script
3057 #!/bin/sh
3058 unset BINUTILS_ROOT
3059 unset GCC_ROOT
3060 c++ $*
3061 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3062 @end smallexample
3063
3064 @item
3065 Using a non-GNU C++ compiler: The commands previously described can be
3066 used to insure that the C++ linker is used. Nonetheless, you need to add
3067 a few more parameters to the link command line, depending on the exception
3068 mechanism used.
3069
3070 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3071 to the libgcc libraries are required:
3072
3073 @smallexample
3074 $ cat ./my_script
3075 #!/bin/sh
3076 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3077 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3078 @end smallexample
3079
3080 Where CC is the name of the non-GNU C++ compiler.
3081
3082 If the @code{zero cost} exception mechanism is used, and the platform
3083 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3084 paths to more objects are required:
3085
3086 @smallexample
3087 $ cat ./my_script
3088 #!/bin/sh
3089 CC `gcc -print-file-name=crtbegin.o` $* \
3090 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3091 `gcc -print-file-name=crtend.o`
3092 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3093 @end smallexample
3094
3095 If the @code{zero cost} exception mechanism is used, and the platform
3096 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3097 Tru64 or AIX), the simple approach described above will not work and
3098 a pre-linking phase using GNAT will be necessary.
3099
3100 @end enumerate
3101
3102 @node A Simple Example
3103 @subsection  A Simple Example
3104 @noindent
3105 The following example, provided as part of the GNAT examples, shows how
3106 to achieve procedural interfacing between Ada and C++ in both
3107 directions. The C++ class A has two methods. The first method is exported
3108 to Ada by the means of an extern C wrapper function. The second method
3109 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3110 a limited record with a layout comparable to the C++ class. The Ada
3111 subprogram, in turn, calls the C++ method. So, starting from the C++
3112 main program, the process passes back and forth between the two
3113 languages.
3114
3115 @noindent
3116 Here are the compilation commands:
3117 @smallexample
3118 $ gnatmake -c simple_cpp_interface
3119 $ c++ -c cpp_main.C
3120 $ c++ -c ex7.C
3121 $ gnatbind -n simple_cpp_interface
3122 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3123       -lstdc++ ex7.o cpp_main.o
3124 @end smallexample
3125
3126 @noindent
3127 Here are the corresponding sources:
3128 @smallexample
3129
3130 //cpp_main.C
3131
3132 #include "ex7.h"
3133
3134 extern "C" @{
3135   void adainit (void);
3136   void adafinal (void);
3137   void method1 (A *t);
3138 @}
3139
3140 void method1 (A *t)
3141 @{
3142   t->method1 ();
3143 @}
3144
3145 int main ()
3146 @{
3147   A obj;
3148   adainit ();
3149   obj.method2 (3030);
3150   adafinal ();
3151 @}
3152
3153 //ex7.h
3154
3155 class Origin @{
3156  public:
3157   int o_value;
3158 @};
3159 class A : public Origin @{
3160  public:
3161   void method1 (void);
3162   void method2 (int v);
3163   A();
3164   int   a_value;
3165 @};
3166
3167 //ex7.C
3168
3169 #include "ex7.h"
3170 #include <stdio.h>
3171
3172 extern "C" @{ void ada_method2 (A *t, int v);@}
3173
3174 void A::method1 (void)
3175 @{
3176   a_value = 2020;
3177   printf ("in A::method1, a_value = %d \n",a_value);
3178
3179 @}
3180
3181 void A::method2 (int v)
3182 @{
3183    ada_method2 (this, v);
3184    printf ("in A::method2, a_value = %d \n",a_value);
3185
3186 @}
3187
3188 A::A(void)
3189 @{
3190    a_value = 1010;
3191   printf ("in A::A, a_value = %d \n",a_value);
3192 @}
3193 @end smallexample
3194
3195 @smallexample @c ada
3196 -- Ada sources
3197 package body Simple_Cpp_Interface is
3198
3199    procedure Ada_Method2 (This : in out A; V : Integer) is
3200    begin
3201       Method1 (This);
3202       This.A_Value := V;
3203    end Ada_Method2;
3204
3205 end Simple_Cpp_Interface;
3206
3207 with System;
3208 package Simple_Cpp_Interface is
3209    type A is limited
3210       record
3211          Vptr    : System.Address;
3212          O_Value : Integer;
3213          A_Value : Integer;
3214       end record;
3215    pragma Convention (C, A);
3216
3217    procedure Method1 (This : in out A);
3218    pragma Import (C, Method1);
3219
3220    procedure Ada_Method2 (This : in out A; V : Integer);
3221    pragma Export (C, Ada_Method2);
3222
3223 end Simple_Cpp_Interface;
3224 @end smallexample
3225
3226 @node Interfacing with C++ at the Class Level
3227 @subsection Interfacing with C++ at the Class Level
3228 @noindent
3229 In this section we demonstrate the GNAT features for interfacing with
3230 C++ by means of an example making use of Ada 2005 abstract interface
3231 types. This example consists of a classification of animals; classes
3232 have been used to model our main classification of animals, and
3233 interfaces provide support for the management of secondary
3234 classifications. We first demonstrate a case in which the types and
3235 constructors are defined on the C++ side and imported from the Ada
3236 side, and latter the reverse case.
3237
3238 The root of our derivation will be the @code{Animal} class, with a
3239 single private attribute (the @code{Age} of the animal) and two public
3240 primitives to set and get the value of this attribute.
3241
3242 @smallexample
3243 @b{class} Animal @{
3244  @b{public}:
3245    @b{virtual} void Set_Age (int New_Age);
3246    @b{virtual} int Age ();
3247  @b{private}:
3248    int Age_Count;
3249 @};
3250 @end smallexample
3251
3252 Abstract interface types are defined in C++ by means of classes with pure
3253 virtual functions and no data members. In our example we will use two
3254 interfaces that provide support for the common management of @code{Carnivore}
3255 and @code{Domestic} animals:
3256
3257 @smallexample
3258 @b{class} Carnivore @{
3259 @b{public}:
3260    @b{virtual} int Number_Of_Teeth () = 0;
3261 @};
3262
3263 @b{class} Domestic @{
3264 @b{public}:
3265    @b{virtual void} Set_Owner (char* Name) = 0;
3266 @};
3267 @end smallexample
3268
3269 Using these declarations, we can now say that a @code{Dog} is an animal that is
3270 both Carnivore and Domestic, that is:
3271
3272 @smallexample
3273 @b{class} Dog : Animal, Carnivore, Domestic @{
3274  @b{public}:
3275    @b{virtual} int  Number_Of_Teeth ();
3276    @b{virtual} void Set_Owner (char* Name);
3277
3278    Dog(); // Constructor
3279  @b{private}:
3280    int  Tooth_Count;
3281    char *Owner;
3282 @};
3283 @end smallexample
3284
3285 In the following examples we will assume that the previous declarations are
3286 located in a file named @code{animals.h}. The following package demonstrates
3287 how to import these C++ declarations from the Ada side:
3288
3289 @smallexample @c ada
3290 with Interfaces.C.Strings; use Interfaces.C.Strings;
3291 package Animals is
3292   type Carnivore is interface;
3293   pragma Convention (C_Plus_Plus, Carnivore);
3294   function Number_Of_Teeth (X : Carnivore)
3295      return Natural is abstract;
3296
3297   type Domestic is interface;
3298   pragma Convention (C_Plus_Plus, Set_Owner);
3299   procedure Set_Owner
3300     (X    : in out Domestic;
3301      Name : Chars_Ptr) is abstract;
3302
3303   type Animal is tagged record
3304     Age : Natural := 0;
3305   end record;
3306   pragma Import (C_Plus_Plus, Animal);
3307
3308   procedure Set_Age (X : in out Animal; Age : Integer);
3309   pragma Import (C_Plus_Plus, Set_Age);
3310
3311   function Age (X : Animal) return Integer;
3312   pragma Import (C_Plus_Plus, Age);
3313
3314   type Dog is new Animal and Carnivore and Domestic with record
3315     Tooth_Count : Natural;
3316     Owner       : String (1 .. 30);
3317   end record;
3318   pragma Import (C_Plus_Plus, Dog);
3319
3320   function Number_Of_Teeth (A : Dog) return Integer;
3321   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3322
3323   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3324   pragma Import (C_Plus_Plus, Set_Owner);
3325
3326   function New_Dog return Dog'Class;
3327   pragma CPP_Constructor (New_Dog);
3328   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3329 end Animals;
3330 @end smallexample
3331
3332 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3333 interfacing with these C++ classes is easy. The only requirement is that all
3334 the primitives and components must be declared exactly in the same order in
3335 the two languages.
3336
3337 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3338 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3339 the arguments to the called primitives will be the same as for C++. For the
3340 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3341 to indicate that they have been defined on the C++ side; this is required
3342 because the dispatch table associated with these tagged types will be built
3343 in the C++ side and therefore will not contain the predefined Ada primitives
3344 which Ada would otherwise expect.
3345
3346 As the reader can see there is no need to indicate the C++ mangled names
3347 associated with each subprogram because it is assumed that all the calls to
3348 these primitives will be dispatching calls. The only exception is the
3349 constructor, which must be registered with the compiler by means of
3350 @code{pragma CPP_Constructor} and needs to provide its associated C++
3351 mangled name because the Ada compiler generates direct calls to it.
3352
3353 With the above packages we can now declare objects of type Dog on the Ada side
3354 and dispatch calls to the corresponding subprograms on the C++ side. We can
3355 also extend the tagged type Dog with further fields and primitives, and
3356 override some of its C++ primitives on the Ada side. For example, here we have
3357 a type derivation defined on the Ada side that inherits all the dispatching
3358 primitives of the ancestor from the C++ side.
3359
3360 @smallexample
3361 @b{with} Animals; @b{use} Animals;
3362 @b{package} Vaccinated_Animals @b{is}
3363   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3364   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3365 @b{end} Vaccinated_Animals;
3366 @end smallexample
3367
3368 It is important to note that, because of the ABI compatibility, the programmer
3369 does not need to add any further information to indicate either the object
3370 layout or the dispatch table entry associated with each dispatching operation.
3371
3372 Now let us define all the types and constructors on the Ada side and export
3373 them to C++, using the same hierarchy of our previous example:
3374
3375 @smallexample @c ada
3376 with Interfaces.C.Strings;
3377 use Interfaces.C.Strings;
3378 package Animals is
3379   type Carnivore is interface;
3380   pragma Convention (C_Plus_Plus, Carnivore);
3381   function Number_Of_Teeth (X : Carnivore)
3382      return Natural is abstract;
3383
3384   type Domestic is interface;
3385   pragma Convention (C_Plus_Plus, Set_Owner);
3386   procedure Set_Owner
3387     (X    : in out Domestic;
3388      Name : Chars_Ptr) is abstract;
3389
3390   type Animal is tagged record
3391     Age : Natural := 0;
3392   end record;
3393   pragma Convention (C_Plus_Plus, Animal);
3394
3395   procedure Set_Age (X : in out Animal; Age : Integer);
3396   pragma Export (C_Plus_Plus, Set_Age);
3397
3398   function Age (X : Animal) return Integer;
3399   pragma Export (C_Plus_Plus, Age);
3400
3401   type Dog is new Animal and Carnivore and Domestic with record
3402     Tooth_Count : Natural;
3403     Owner       : String (1 .. 30);
3404   end record;
3405   pragma Convention (C_Plus_Plus, Dog);
3406
3407   function Number_Of_Teeth (A : Dog) return Integer;
3408   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3409
3410   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3411   pragma Export (C_Plus_Plus, Set_Owner);
3412
3413   function New_Dog return Dog'Class;
3414   pragma Export (C_Plus_Plus, New_Dog);
3415 end Animals;
3416 @end smallexample
3417
3418 Compared with our previous example the only difference is the use of
3419 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3420 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3421 nothing else to be done; as explained above, the only requirement is that all
3422 the primitives and components are declared in exactly the same order.
3423
3424 For completeness, let us see a brief C++ main program that uses the
3425 declarations available in @code{animals.h} (presented in our first example) to
3426 import and use the declarations from the Ada side, properly initializing and
3427 finalizing the Ada run-time system along the way:
3428
3429 @smallexample
3430 @b{#include} "animals.h"
3431 @b{#include} <iostream>
3432 @b{using namespace} std;
3433
3434 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3435 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3436 void Check_Animal (Animal *obj)       @{@dots{}@}
3437 void Check_Dog (Dog *obj)             @{@dots{}@}
3438
3439 @b{extern} "C" @{
3440   void adainit (void);
3441   void adafinal (void);
3442   Dog* new_dog ();
3443 @}
3444
3445 void test ()
3446 @{
3447   Dog *obj = new_dog();  // Ada constructor
3448   Check_Carnivore (obj); // Check secondary DT
3449   Check_Domestic (obj);  // Check secondary DT
3450   Check_Animal (obj);    // Check primary DT
3451   Check_Dog (obj);       // Check primary DT
3452 @}
3453
3454 int main ()
3455 @{
3456   adainit ();  test();  adafinal ();
3457   return 0;
3458 @}
3459 @end smallexample
3460
3461 @node Comparison between GNAT and C/C++ Compilation Models
3462 @section Comparison between GNAT and C/C++ Compilation Models
3463
3464 @noindent
3465 The GNAT model of compilation is close to the C and C++ models. You can
3466 think of Ada specs as corresponding to header files in C. As in C, you
3467 don't need to compile specs; they are compiled when they are used. The
3468 Ada @code{with} is similar in effect to the @code{#include} of a C
3469 header.
3470
3471 One notable difference is that, in Ada, you may compile specs separately
3472 to check them for semantic and syntactic accuracy. This is not always
3473 possible with C headers because they are fragments of programs that have
3474 less specific syntactic or semantic rules.
3475
3476 The other major difference is the requirement for running the binder,
3477 which performs two important functions. First, it checks for
3478 consistency. In C or C++, the only defense against assembling
3479 inconsistent programs lies outside the compiler, in a makefile, for
3480 example. The binder satisfies the Ada requirement that it be impossible
3481 to construct an inconsistent program when the compiler is used in normal
3482 mode.
3483
3484 @cindex Elaboration order control
3485 The other important function of the binder is to deal with elaboration
3486 issues. There are also elaboration issues in C++ that are handled
3487 automatically. This automatic handling has the advantage of being
3488 simpler to use, but the C++ programmer has no control over elaboration.
3489 Where @code{gnatbind} might complain there was no valid order of
3490 elaboration, a C++ compiler would simply construct a program that
3491 malfunctioned at run time.
3492 @end ifclear
3493
3494 @node Comparison between GNAT and Conventional Ada Library Models
3495 @section Comparison between GNAT and Conventional Ada Library Models
3496
3497 @noindent
3498 This section is intended for Ada programmers who have
3499 used an Ada compiler implementing the traditional Ada library
3500 model, as described in the Ada Reference Manual.
3501
3502 @cindex GNAT library
3503 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3504 source files themselves acts as the library. Compiling Ada programs does
3505 not generate any centralized information, but rather an object file and
3506 a ALI file, which are of interest only to the binder and linker.
3507 In a traditional system, the compiler reads information not only from
3508 the source file being compiled, but also from the centralized library.
3509 This means that the effect of a compilation depends on what has been
3510 previously compiled. In particular:
3511
3512 @itemize @bullet
3513 @item
3514 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3515 to the version of the unit most recently compiled into the library.
3516
3517 @item
3518 Inlining is effective only if the necessary body has already been
3519 compiled into the library.
3520
3521 @item
3522 Compiling a unit may obsolete other units in the library.
3523 @end itemize
3524
3525 @noindent
3526 In GNAT, compiling one unit never affects the compilation of any other
3527 units because the compiler reads only source files. Only changes to source
3528 files can affect the results of a compilation. In particular:
3529
3530 @itemize @bullet
3531 @item
3532 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3533 to the source version of the unit that is currently accessible to the
3534 compiler.
3535
3536 @item
3537 @cindex Inlining
3538 Inlining requires the appropriate source files for the package or
3539 subprogram bodies to be available to the compiler. Inlining is always
3540 effective, independent of the order in which units are complied.
3541
3542 @item
3543 Compiling a unit never affects any other compilations. The editing of
3544 sources may cause previous compilations to be out of date if they
3545 depended on the source file being modified.
3546 @end itemize
3547
3548 @noindent
3549 The most important result of these differences is that order of compilation
3550 is never significant in GNAT. There is no situation in which one is
3551 required to do one compilation before another. What shows up as order of
3552 compilation requirements in the traditional Ada library becomes, in
3553 GNAT, simple source dependencies; in other words, there is only a set
3554 of rules saying what source files must be present when a file is
3555 compiled.
3556
3557 @ifset vms
3558 @node Placement of temporary files
3559 @section Placement of temporary files
3560 @cindex Temporary files (user control over placement)
3561
3562 @noindent
3563 GNAT creates temporary files in the directory designated by the environment
3564 variable @env{TMPDIR}.
3565 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3566 for detailed information on how environment variables are resolved.
3567 For most users the easiest way to make use of this feature is to simply
3568 define @env{TMPDIR} as a job level logical name).
3569 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3570 for compiler temporary files, then you can include something like the
3571 following command in your @file{LOGIN.COM} file:
3572
3573 @smallexample
3574 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3575 @end smallexample
3576
3577 @noindent
3578 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3579 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3580 designated by @env{TEMP}.
3581 If none of these environment variables are defined then GNAT uses the
3582 directory designated by the logical name @code{SYS$SCRATCH:}
3583 (by default the user's home directory). If all else fails
3584 GNAT uses the current directory for temporary files.
3585 @end ifset
3586
3587 @c *************************
3588 @node Compiling Using gcc
3589 @chapter Compiling Using @command{gcc}
3590
3591 @noindent
3592 This chapter discusses how to compile Ada programs using the @command{gcc}
3593 command. It also describes the set of switches
3594 that can be used to control the behavior of the compiler.
3595 @menu
3596 * Compiling Programs::
3597 * Switches for gcc::
3598 * Search Paths and the Run-Time Library (RTL)::
3599 * Order of Compilation Issues::
3600 * Examples::
3601 @end menu
3602
3603 @node Compiling Programs
3604 @section Compiling Programs
3605
3606 @noindent
3607 The first step in creating an executable program is to compile the units
3608 of the program using the @command{gcc} command. You must compile the
3609 following files:
3610
3611 @itemize @bullet
3612 @item
3613 the body file (@file{.adb}) for a library level subprogram or generic
3614 subprogram
3615
3616 @item
3617 the spec file (@file{.ads}) for a library level package or generic
3618 package that has no body
3619
3620 @item
3621 the body file (@file{.adb}) for a library level package
3622 or generic package that has a body
3623
3624 @end itemize
3625
3626 @noindent
3627 You need @emph{not} compile the following files
3628
3629 @itemize @bullet
3630
3631 @item
3632 the spec of a library unit which has a body
3633
3634 @item
3635 subunits
3636 @end itemize
3637
3638 @noindent
3639 because they are compiled as part of compiling related units. GNAT
3640 package specs
3641 when the corresponding body is compiled, and subunits when the parent is
3642 compiled.
3643
3644 @cindex cannot generate code
3645 If you attempt to compile any of these files, you will get one of the
3646 following error messages (where @var{fff} is the name of the file you compiled):
3647
3648 @smallexample
3649 cannot generate code for file @var{fff} (package spec)
3650 to check package spec, use -gnatc
3651
3652 cannot generate code for file @var{fff} (missing subunits)
3653 to check parent unit, use -gnatc
3654
3655 cannot generate code for file @var{fff} (subprogram spec)
3656 to check subprogram spec, use -gnatc
3657
3658 cannot generate code for file @var{fff} (subunit)
3659 to check subunit, use -gnatc
3660 @end smallexample
3661
3662 @noindent
3663 As indicated by the above error messages, if you want to submit
3664 one of these files to the compiler to check for correct semantics
3665 without generating code, then use the @option{-gnatc} switch.
3666
3667 The basic command for compiling a file containing an Ada unit is
3668
3669 @smallexample
3670 $ gcc -c @ovar{switches} @file{file name}
3671 @end smallexample
3672
3673 @noindent
3674 where @var{file name} is the name of the Ada file (usually
3675 having an extension
3676 @file{.ads} for a spec or @file{.adb} for a body).
3677 @ifclear vms
3678 You specify the
3679 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3680 @end ifclear
3681 The result of a successful compilation is an object file, which has the
3682 same name as the source file but an extension of @file{.o} and an Ada
3683 Library Information (ALI) file, which also has the same name as the
3684 source file, but with @file{.ali} as the extension. GNAT creates these
3685 two output files in the current directory, but you may specify a source
3686 file in any directory using an absolute or relative path specification
3687 containing the directory information.
3688
3689 @findex gnat1
3690 @command{gcc} is actually a driver program that looks at the extensions of
3691 the file arguments and loads the appropriate compiler. For example, the
3692 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3693 These programs are in directories known to the driver program (in some
3694 configurations via environment variables you set), but need not be in
3695 your path. The @command{gcc} driver also calls the assembler and any other
3696 utilities needed to complete the generation of the required object
3697 files.
3698
3699 It is possible to supply several file names on the same @command{gcc}
3700 command. This causes @command{gcc} to call the appropriate compiler for
3701 each file. For example, the following command lists three separate
3702 files to be compiled:
3703
3704 @smallexample
3705 $ gcc -c x.adb y.adb z.c
3706 @end smallexample
3707
3708 @noindent
3709 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3710 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3711 The compiler generates three object files @file{x.o}, @file{y.o} and
3712 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3713 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3714 @ifclear vms
3715 except for
3716 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3717 @end ifclear
3718
3719 @node Switches for gcc
3720 @section Switches for @command{gcc}
3721
3722 @noindent
3723 The @command{gcc} command accepts switches that control the
3724 compilation process. These switches are fully described in this section.
3725 First we briefly list all the switches, in alphabetical order, then we
3726 describe the switches in more detail in functionally grouped sections.
3727
3728 More switches exist for GCC than those documented here, especially
3729 for specific targets. However, their use is not recommended as
3730 they may change code generation in ways that are incompatible with
3731 the Ada run-time library, or can cause inconsistencies between
3732 compilation units.
3733
3734 @menu
3735 * Output and Error Message Control::
3736 * Warning Message Control::
3737 * Debugging and Assertion Control::
3738 * Validity Checking::
3739 * Style Checking::
3740 * Run-Time Checks::
3741 * Using gcc for Syntax Checking::
3742 * Using gcc for Semantic Checking::
3743 * Compiling Different Versions of Ada::
3744 * Character Set Control::
3745 * File Naming Control::
3746 * Subprogram Inlining Control::
3747 * Auxiliary Output Control::
3748 * Debugging Control::
3749 * Exception Handling Control::
3750 * Units to Sources Mapping Files::
3751 * Integrated Preprocessing::
3752 * Code Generation Control::
3753 @ifset vms
3754 * Return Codes::
3755 @end ifset
3756 @end menu
3757
3758 @table @option
3759 @c !sort!
3760 @ifclear vms
3761 @cindex @option{-b} (@command{gcc})
3762 @item -b @var{target}
3763 Compile your program to run on @var{target}, which is the name of a
3764 system configuration. You must have a GNAT cross-compiler built if
3765 @var{target} is not the same as your host system.
3766
3767 @item -B@var{dir}
3768 @cindex @option{-B} (@command{gcc})
3769 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3770 from @var{dir} instead of the default location. Only use this switch
3771 when multiple versions of the GNAT compiler are available.
3772 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3773 GNU Compiler Collection (GCC)}, for further details. You would normally
3774 use the @option{-b} or @option{-V} switch instead.
3775
3776 @item -c
3777 @cindex @option{-c} (@command{gcc})
3778 Compile. Always use this switch when compiling Ada programs.
3779
3780 Note: for some other languages when using @command{gcc}, notably in
3781 the case of C and C++, it is possible to use
3782 use @command{gcc} without a @option{-c} switch to
3783 compile and link in one step. In the case of GNAT, you
3784 cannot use this approach, because the binder must be run
3785 and @command{gcc} cannot be used to run the GNAT binder.
3786 @end ifclear
3787
3788 @item -fno-inline
3789 @cindex @option{-fno-inline} (@command{gcc})
3790 Suppresses all back-end inlining, even if other optimization or inlining
3791 switches are set.
3792 This includes suppression of inlining that results
3793 from the use of the pragma @code{Inline_Always}.
3794 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3795 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3796 effect if this switch is present.
3797
3798 @item -fno-inline-functions
3799 @cindex @option{-fno-inline-functions} (@command{gcc})
3800 Suppresses automatic inlining of small subprograms, which is enabled
3801 if @option{-O3} is used.
3802
3803 @item -fno-inline-functions-called-once
3804 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3805 Suppresses inlining of subprograms local to the unit and called once
3806 from within it, which is enabled if @option{-O1} is used.
3807
3808 @item -fno-strict-aliasing
3809 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3810 Causes the compiler to avoid assumptions regarding non-aliasing
3811 of objects of different types. See
3812 @ref{Optimization and Strict Aliasing} for details.
3813
3814 @item -fstack-check
3815 @cindex @option{-fstack-check} (@command{gcc})
3816 Activates stack checking.
3817 See @ref{Stack Overflow Checking} for details.
3818
3819 @item -fstack-usage
3820 @cindex @option{-fstack-usage} (@command{gcc})
3821 Makes the compiler output stack usage information for the program, on a
3822 per-function basis. See @ref{Static Stack Usage Analysis} for details.
3823
3824 @item -fcallgraph-info@r{[}=su@r{]}
3825 @cindex @option{-fcallgraph-info} (@command{gcc})
3826 Makes the compiler output callgraph information for the program, on a
3827 per-file basis.  The information is generated in the VCG format.  It can
3828 be decorated with stack-usage per-node information.
3829
3830 @item ^-g^/DEBUG^
3831 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3832 Generate debugging information. This information is stored in the object
3833 file and copied from there to the final executable file by the linker,
3834 where it can be read by the debugger. You must use the
3835 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3836
3837 @item -gnat83
3838 @cindex @option{-gnat83} (@command{gcc})
3839 Enforce Ada 83 restrictions.
3840
3841 @item -gnat95
3842 @cindex @option{-gnat95} (@command{gcc})
3843 Enforce Ada 95 restrictions.
3844
3845 @item -gnat05
3846 @cindex @option{-gnat05} (@command{gcc})
3847 Allow full Ada 2005 features.
3848
3849 @item -gnata
3850 @cindex @option{-gnata} (@command{gcc})
3851 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3852 activated. Note that these pragmas can also be controlled using the
3853 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3854 It also activates pragmas @code{Check}, @code{Precondition}, and
3855 @code{Postcondition}. Note that these pragmas can also be controlled
3856 using the configuration pragma @code{Check_Policy}.
3857
3858 @item -gnatA
3859 @cindex @option{-gnatA} (@command{gcc})
3860 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
3861 it will be ignored.
3862
3863 @item -gnatb
3864 @cindex @option{-gnatb} (@command{gcc})
3865 Generate brief messages to @file{stderr} even if verbose mode set.
3866
3867 @item -gnatB
3868 @cindex @option{-gnatB} (@command{gcc})
3869 Assume no invalid (bad) values except for 'Valid attribute use.
3870
3871 @item -gnatc
3872 @cindex @option{-gnatc} (@command{gcc})
3873 Check syntax and semantics only (no code generation attempted).
3874
3875 @item -gnatd
3876 @cindex @option{-gnatd} (@command{gcc})
3877 Specify debug options for the compiler. The string of characters after
3878 the @option{-gnatd} specify the specific debug options. The possible
3879 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3880 compiler source file @file{debug.adb} for details of the implemented
3881 debug options. Certain debug options are relevant to applications
3882 programmers, and these are documented at appropriate points in this
3883 users guide.
3884
3885 @item -gnatD
3886 @cindex @option{-gnatD[nn]} (@command{gcc})
3887 Create expanded source files for source level debugging. This switch
3888 also suppress generation of cross-reference information
3889 (see @option{-gnatx}).
3890
3891 @item -gnatec=@var{path}
3892 @cindex @option{-gnatec} (@command{gcc})
3893 Specify a configuration pragma file
3894 @ifclear vms
3895 (the equal sign is optional)
3896 @end ifclear
3897 (@pxref{The Configuration Pragmas Files}).
3898
3899 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
3900 @cindex @option{-gnateD} (@command{gcc})
3901 Defines a symbol, associated with @var{value}, for preprocessing.
3902 (@pxref{Integrated Preprocessing}).
3903
3904 @item -gnatef
3905 @cindex @option{-gnatef} (@command{gcc})
3906 Display full source path name in brief error messages.
3907
3908 @item -gnateG
3909 @cindex @option{-gnateG} (@command{gcc})
3910 Save result of preprocessing in a text file.
3911
3912 @item -gnatem=@var{path}
3913 @cindex @option{-gnatem} (@command{gcc})
3914 Specify a mapping file
3915 @ifclear vms
3916 (the equal sign is optional)
3917 @end ifclear
3918 (@pxref{Units to Sources Mapping Files}).
3919
3920 @item -gnatep=@var{file}
3921 @cindex @option{-gnatep} (@command{gcc})
3922 Specify a preprocessing data file
3923 @ifclear vms
3924 (the equal sign is optional)
3925 @end ifclear
3926 (@pxref{Integrated Preprocessing}).
3927
3928 @item -gnatE
3929 @cindex @option{-gnatE} (@command{gcc})
3930 Full dynamic elaboration checks.
3931
3932 @item -gnatf
3933 @cindex @option{-gnatf} (@command{gcc})
3934 Full errors. Multiple errors per line, all undefined references, do not
3935 attempt to suppress cascaded errors.
3936
3937 @item -gnatF
3938 @cindex @option{-gnatF} (@command{gcc})
3939 Externals names are folded to all uppercase.
3940
3941 @item ^-gnatg^/GNAT_INTERNAL^
3942 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
3943 Internal GNAT implementation mode. This should not be used for
3944 applications programs, it is intended only for use by the compiler
3945 and its run-time library. For documentation, see the GNAT sources.
3946 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
3947 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
3948 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
3949 so that all standard warnings and all standard style options are turned on.
3950 All warnings and style error messages are treated as errors.
3951
3952 @item -gnatG=nn
3953 @cindex @option{-gnatG[nn]} (@command{gcc})
3954 List generated expanded code in source form.
3955
3956 @item ^-gnath^/HELP^
3957 @cindex @option{^-gnath^/HELP^} (@command{gcc})
3958 Output usage information. The output is written to @file{stdout}.
3959
3960 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3961 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
3962 Identifier character set
3963 @ifclear vms
3964 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3965 @end ifclear
3966 For details of the possible selections for @var{c},
3967 see @ref{Character Set Control}.
3968
3969 @item ^-gnatI^/IGNORE_REP_CLAUSES^
3970 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
3971 Ignore representation clauses. When this switch is used, all
3972 representation clauses are treated as comments. This is useful
3973 when initially porting code where you want to ignore rep clause
3974 problems, and also for compiling foreign code (particularly
3975 for use with ASIS).
3976
3977 @item -gnatjnn
3978 @cindex @option{-gnatjnn} (@command{gcc})
3979 Reformat error messages to fit on nn character lines
3980
3981 @item -gnatk=@var{n}
3982 @cindex @option{-gnatk} (@command{gcc})
3983 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3984
3985 @item -gnatl
3986 @cindex @option{-gnatl} (@command{gcc})
3987 Output full source listing with embedded error messages.
3988
3989 @item -gnatL
3990 @cindex @option{-gnatL} (@command{gcc})
3991 Used in conjunction with -gnatG or -gnatD to intersperse original
3992 source lines (as comment lines with line numbers) in the expanded
3993 source output.
3994
3995 @item -gnatm=@var{n}
3996 @cindex @option{-gnatm} (@command{gcc})
3997 Limit number of detected error or warning messages to @var{n}
3998 where @var{n} is in the range 1..999999. The default setting if
3999 no switch is given is 9999. If the number of warnings reaches this
4000 limit, then a message is output and further warnings are suppressed,
4001 but the compilation is continued. If the number of error messages
4002 reaches this limit, then a message is output and the compilation
4003 is abandoned. The equal sign here is optional. A value of zero
4004 means that no limit applies.
4005
4006 @item -gnatn
4007 @cindex @option{-gnatn} (@command{gcc})
4008 Activate inlining for subprograms for which
4009 pragma @code{inline} is specified. This inlining is performed
4010 by the GCC back-end.
4011
4012 @item -gnatN
4013 @cindex @option{-gnatN} (@command{gcc})
4014 Activate front end inlining for subprograms for which
4015 pragma @code{Inline} is specified. This inlining is performed
4016 by the front end and will be visible in the
4017 @option{-gnatG} output.
4018
4019 When using a gcc-based back end (in practice this means using any version
4020 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4021 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4022 Historically front end inlining was more extensive than the gcc back end
4023 inlining, but that is no longer the case.
4024
4025 @item -gnato
4026 @cindex @option{-gnato} (@command{gcc})
4027 Enable numeric overflow checking (which is not normally enabled by
4028 default). Note that division by zero is a separate check that is not
4029 controlled by this switch (division by zero checking is on by default).
4030
4031 @item -gnatp
4032 @cindex @option{-gnatp} (@command{gcc})
4033 Suppress all checks. See @ref{Run-Time Checks} for details.
4034
4035 @item -gnatP
4036 @cindex @option{-gnatP} (@command{gcc})
4037 Enable polling. This is required on some systems (notably Windows NT) to
4038 obtain asynchronous abort and asynchronous transfer of control capability.
4039 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4040 details.
4041
4042 @item -gnatq
4043 @cindex @option{-gnatq} (@command{gcc})
4044 Don't quit. Try semantics, even if parse errors.
4045
4046 @item -gnatQ
4047 @cindex @option{-gnatQ} (@command{gcc})
4048 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4049
4050 @item -gnatr
4051 @cindex @option{-gnatr} (@command{gcc})
4052 Treat pragma Restrictions as Restriction_Warnings.
4053
4054 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4055 @cindex @option{-gnatR} (@command{gcc})
4056 Output representation information for declared types and objects.
4057
4058 @item -gnats
4059 @cindex @option{-gnats} (@command{gcc})
4060 Syntax check only.
4061
4062 @item -gnatS
4063 @cindex @option{-gnatS} (@command{gcc})
4064 Print package Standard.
4065
4066 @item -gnatt
4067 @cindex @option{-gnatt} (@command{gcc})
4068 Generate tree output file.
4069
4070 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4071 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4072 All compiler tables start at @var{nnn} times usual starting size.
4073
4074 @item -gnatu
4075 @cindex @option{-gnatu} (@command{gcc})
4076 List units for this compilation.
4077
4078 @item -gnatU
4079 @cindex @option{-gnatU} (@command{gcc})
4080 Tag all error messages with the unique string ``error:''
4081
4082 @item -gnatv
4083 @cindex @option{-gnatv} (@command{gcc})
4084 Verbose mode. Full error output with source lines to @file{stdout}.
4085
4086 @item -gnatV
4087 @cindex @option{-gnatV} (@command{gcc})
4088 Control level of validity checking. See separate section describing
4089 this feature.
4090
4091 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4092 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4093 Warning mode where
4094 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4095 the exact warnings that
4096 are enabled or disabled (@pxref{Warning Message Control}).
4097
4098 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4099 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4100 Wide character encoding method
4101 @ifclear vms
4102 (@var{e}=n/h/u/s/e/8).
4103 @end ifclear
4104 @ifset vms
4105 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4106 @end ifset
4107
4108 @item -gnatx
4109 @cindex @option{-gnatx} (@command{gcc})
4110 Suppress generation of cross-reference information.
4111
4112 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4113 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4114 Enable built-in style checks (@pxref{Style Checking}).
4115
4116 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4117 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4118 Distribution stub generation and compilation
4119 @ifclear vms
4120 (@var{m}=r/c for receiver/caller stubs).
4121 @end ifclear
4122 @ifset vms
4123 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4124 to be generated and compiled).
4125 @end ifset
4126
4127 @item ^-I^/SEARCH=^@var{dir}
4128 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4129 @cindex RTL
4130 Direct GNAT to search the @var{dir} directory for source files needed by
4131 the current compilation
4132 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4133
4134 @item ^-I-^/NOCURRENT_DIRECTORY^
4135 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4136 @cindex RTL
4137 Except for the source file named in the command line, do not look for source
4138 files in the directory containing the source file named in the command line
4139 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4140
4141 @ifclear vms
4142 @item -mbig-switch
4143 @cindex @option{-mbig-switch} (@command{gcc})
4144 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4145 This standard gcc switch causes the compiler to use larger offsets in its
4146 jump table representation for @code{case} statements.
4147 This may result in less efficient code, but is sometimes necessary
4148 (for example on HP-UX targets)
4149 @cindex HP-UX and @option{-mbig-switch} option
4150 in order to compile large and/or nested @code{case} statements.
4151
4152 @item -o @var{file}
4153 @cindex @option{-o} (@command{gcc})
4154 This switch is used in @command{gcc} to redirect the generated object file
4155 and its associated ALI file. Beware of this switch with GNAT, because it may
4156 cause the object file and ALI file to have different names which in turn
4157 may confuse the binder and the linker.
4158 @end ifclear
4159
4160 @item -nostdinc
4161 @cindex @option{-nostdinc} (@command{gcc})
4162 Inhibit the search of the default location for the GNAT Run Time
4163 Library (RTL) source files.
4164
4165 @item -nostdlib
4166 @cindex @option{-nostdlib} (@command{gcc})
4167 Inhibit the search of the default location for the GNAT Run Time
4168 Library (RTL) ALI files.
4169
4170 @ifclear vms
4171 @item -O@ovar{n}
4172 @cindex @option{-O} (@command{gcc})
4173 @var{n} controls the optimization level.
4174
4175 @table @asis
4176 @item n = 0
4177 No optimization, the default setting if no @option{-O} appears
4178
4179 @item n = 1
4180 Normal optimization, the default if you specify @option{-O} without
4181 an operand. A good compromise between code quality and compilation
4182 time.
4183
4184 @item n = 2
4185 Extensive optimization, may improve execution time, possibly at the cost of
4186 substantially increased compilation time.
4187
4188 @item n = 3
4189 Same as @option{-O2}, and also includes inline expansion for small subprograms
4190 in the same unit.
4191
4192 @item n = s
4193 Optimize space usage
4194 @end table
4195
4196 @noindent
4197 See also @ref{Optimization Levels}.
4198 @end ifclear
4199
4200 @ifset vms
4201 @item  /NOOPTIMIZE
4202 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4203 Equivalent to @option{/OPTIMIZE=NONE}.
4204 This is the default behavior in the absence of an @option{/OPTIMIZE}
4205 qualifier.
4206
4207 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4208 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4209 Selects the level of optimization for your program. The supported
4210 keywords are as follows:
4211 @table @code
4212 @item   ALL
4213 Perform most optimizations, including those that
4214 are expensive.
4215 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4216 without keyword options.
4217
4218 @item   NONE
4219 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4220
4221 @item SOME
4222 Perform some optimizations, but omit ones that are costly.
4223
4224 @item   DEVELOPMENT
4225 Same as @code{SOME}.
4226
4227 @item INLINING
4228 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4229 automatic inlining of small subprograms within a unit
4230
4231 @item   UNROLL_LOOPS
4232 Try to unroll loops. This keyword may be specified together with
4233 any keyword above other than @code{NONE}. Loop unrolling
4234 usually, but not always, improves the performance of programs.
4235
4236 @item SPACE
4237 Optimize space usage
4238 @end table
4239
4240 @noindent
4241 See also @ref{Optimization Levels}.
4242 @end ifset
4243
4244 @ifclear vms
4245 @item -pass-exit-codes
4246 @cindex @option{-pass-exit-codes} (@command{gcc})
4247 Catch exit codes from the compiler and use the most meaningful as
4248 exit status.
4249 @end ifclear
4250
4251 @item --RTS=@var{rts-path}
4252 @cindex @option{--RTS} (@command{gcc})
4253 Specifies the default location of the runtime library. Same meaning as the
4254 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4255
4256 @item ^-S^/ASM^
4257 @cindex @option{^-S^/ASM^} (@command{gcc})
4258 ^Used in place of @option{-c} to^Used to^
4259 cause the assembler source file to be
4260 generated, using @file{^.s^.S^} as the extension,
4261 instead of the object file.
4262 This may be useful if you need to examine the generated assembly code.
4263
4264 @item ^-fverbose-asm^/VERBOSE_ASM^
4265 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4266 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4267 to cause the generated assembly code file to be annotated with variable
4268 names, making it significantly easier to follow.
4269
4270 @item ^-v^/VERBOSE^
4271 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4272 Show commands generated by the @command{gcc} driver. Normally used only for
4273 debugging purposes or if you need to be sure what version of the
4274 compiler you are executing.
4275
4276 @ifclear vms
4277 @item -V @var{ver}
4278 @cindex @option{-V} (@command{gcc})
4279 Execute @var{ver} version of the compiler. This is the @command{gcc}
4280 version, not the GNAT version.
4281 @end ifclear
4282
4283 @item ^-w^/NO_BACK_END_WARNINGS^
4284 @cindex @option{-w} (@command{gcc})
4285 Turn off warnings generated by the back end of the compiler. Use of
4286 this switch also causes the default for front end warnings to be set
4287 to suppress (as though @option{-gnatws} had appeared at the start of
4288 the options).
4289
4290 @end table
4291
4292 @ifclear vms
4293 @c Combining qualifiers does not work on VMS
4294 You may combine a sequence of GNAT switches into a single switch. For
4295 example, the combined switch
4296
4297 @cindex Combining GNAT switches
4298 @smallexample
4299 -gnatofi3
4300 @end smallexample
4301
4302 @noindent
4303 is equivalent to specifying the following sequence of switches:
4304
4305 @smallexample
4306 -gnato -gnatf -gnati3
4307 @end smallexample
4308 @end ifclear
4309
4310 @noindent
4311 The following restrictions apply to the combination of switches
4312 in this manner:
4313
4314 @itemize @bullet
4315 @item
4316 The switch @option{-gnatc} if combined with other switches must come
4317 first in the string.
4318
4319 @item
4320 The switch @option{-gnats} if combined with other switches must come
4321 first in the string.
4322
4323 @item
4324 The switches
4325 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4326 may not be combined with any other switches.
4327
4328 @ifclear vms
4329 @item
4330 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4331 switch), then all further characters in the switch are interpreted
4332 as style modifiers (see description of @option{-gnaty}).
4333
4334 @item
4335 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4336 switch), then all further characters in the switch are interpreted
4337 as debug flags (see description of @option{-gnatd}).
4338
4339 @item
4340 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4341 switch), then all further characters in the switch are interpreted
4342 as warning mode modifiers (see description of @option{-gnatw}).
4343
4344 @item
4345 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4346 switch), then all further characters in the switch are interpreted
4347 as validity checking options (see description of @option{-gnatV}).
4348 @end ifclear
4349 @end itemize
4350
4351 @node Output and Error Message Control
4352 @subsection Output and Error Message Control
4353 @findex stderr
4354
4355 @noindent
4356 The standard default format for error messages is called ``brief format''.
4357 Brief format messages are written to @file{stderr} (the standard error
4358 file) and have the following form:
4359
4360 @smallexample
4361 e.adb:3:04: Incorrect spelling of keyword "function"
4362 e.adb:4:20: ";" should be "is"
4363 @end smallexample
4364
4365 @noindent
4366 The first integer after the file name is the line number in the file,
4367 and the second integer is the column number within the line.
4368 @ifclear vms
4369 @code{GPS} can parse the error messages
4370 and point to the referenced character.
4371 @end ifclear
4372 The following switches provide control over the error message
4373 format:
4374
4375 @table @option
4376 @c !sort!
4377 @item -gnatv
4378 @cindex @option{-gnatv} (@command{gcc})
4379 @findex stdout
4380 @ifclear vms
4381 The v stands for verbose.
4382 @end ifclear
4383 The effect of this setting is to write long-format error
4384 messages to @file{stdout} (the standard output file.
4385 The same program compiled with the
4386 @option{-gnatv} switch would generate:
4387
4388 @smallexample
4389 @cartouche
4390 3. funcion X (Q : Integer)
4391    |
4392 >>> Incorrect spelling of keyword "function"
4393 4. return Integer;
4394                  |
4395 >>> ";" should be "is"
4396 @end cartouche
4397 @end smallexample
4398
4399 @noindent
4400 The vertical bar indicates the location of the error, and the @samp{>>>}
4401 prefix can be used to search for error messages. When this switch is
4402 used the only source lines output are those with errors.
4403
4404 @item -gnatl
4405 @cindex @option{-gnatl} (@command{gcc})
4406 @ifclear vms
4407 The @code{l} stands for list.
4408 @end ifclear
4409 This switch causes a full listing of
4410 the file to be generated. In the case where a body is
4411 compiled, the corresponding spec is also listed, along
4412 with any subunits. Typical output from compiling a package
4413 body @file{p.adb} might look like:
4414
4415 @smallexample @c ada
4416 @cartouche
4417  Compiling: p.adb
4418
4419      1. package body p is
4420      2.    procedure a;
4421      3.    procedure a is separate;
4422      4. begin
4423      5.    null
4424                |
4425         >>> missing ";"
4426
4427      6. end;
4428
4429 Compiling: p.ads
4430
4431      1. package p is
4432      2.    pragma Elaborate_Body
4433                                 |
4434         >>> missing ";"
4435
4436      3. end p;
4437
4438 Compiling: p-a.adb
4439
4440      1. separate p
4441                 |
4442         >>> missing "("
4443
4444      2. procedure a is
4445      3. begin
4446      4.    null
4447                |
4448         >>> missing ";"
4449
4450      5. end;
4451 @end cartouche
4452 @end smallexample
4453
4454 @noindent
4455 @findex stderr
4456 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4457 standard output is redirected, a brief summary is written to
4458 @file{stderr} (standard error) giving the number of error messages and
4459 warning messages generated.
4460
4461 @item -^gnatl^OUTPUT_FILE^=file
4462 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4463 This has the same effect as @option{-gnatl} except that the output is
4464 written to a file instead of to standard output. If the given name
4465 @file{fname} does not start with a period, then it is the full name
4466 of the file to be written. If @file{fname} is an extension, it is
4467 appended to the name of the file being compiled. For example, if
4468 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4469 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4470
4471 @item -gnatU
4472 @cindex @option{-gnatU} (@command{gcc})
4473 This switch forces all error messages to be preceded by the unique
4474 string ``error:''. This means that error messages take a few more
4475 characters in space, but allows easy searching for and identification
4476 of error messages.
4477
4478 @item -gnatb
4479 @cindex @option{-gnatb} (@command{gcc})
4480 @ifclear vms
4481 The @code{b} stands for brief.
4482 @end ifclear
4483 This switch causes GNAT to generate the
4484 brief format error messages to @file{stderr} (the standard error
4485 file) as well as the verbose
4486 format message or full listing (which as usual is written to
4487 @file{stdout} (the standard output file).
4488
4489 @item -gnatm=@var{n}
4490 @cindex @option{-gnatm} (@command{gcc})
4491 @ifclear vms
4492 The @code{m} stands for maximum.
4493 @end ifclear
4494 @var{n} is a decimal integer in the
4495 range of 1 to 999999 and limits the number of error or warning
4496 messages to be generated. For example, using
4497 @option{-gnatm2} might yield
4498
4499 @smallexample
4500 e.adb:3:04: Incorrect spelling of keyword "function"
4501 e.adb:5:35: missing ".."
4502 fatal error: maximum number of errors detected
4503 compilation abandoned
4504 @end smallexample
4505
4506 @noindent
4507 The default setting if
4508 no switch is given is 9999. If the number of warnings reaches this
4509 limit, then a message is output and further warnings are suppressed,
4510 but the compilation is continued. If the number of error messages
4511 reaches this limit, then a message is output and the compilation
4512 is abandoned. A value of zero means that no limit applies.
4513
4514 @noindent
4515 Note that the equal sign is optional, so the switches
4516 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4517
4518 @item -gnatf
4519 @cindex @option{-gnatf} (@command{gcc})
4520 @cindex Error messages, suppressing
4521 @ifclear vms
4522 The @code{f} stands for full.
4523 @end ifclear
4524 Normally, the compiler suppresses error messages that are likely to be
4525 redundant. This switch causes all error
4526 messages to be generated. In particular, in the case of
4527 references to undefined variables. If a given variable is referenced
4528 several times, the normal format of messages is
4529 @smallexample
4530 e.adb:7:07: "V" is undefined (more references follow)
4531 @end smallexample
4532
4533 @noindent
4534 where the parenthetical comment warns that there are additional
4535 references to the variable @code{V}. Compiling the same program with the
4536 @option{-gnatf} switch yields
4537
4538 @smallexample
4539 e.adb:7:07: "V" is undefined
4540 e.adb:8:07: "V" is undefined
4541 e.adb:8:12: "V" is undefined
4542 e.adb:8:16: "V" is undefined
4543 e.adb:9:07: "V" is undefined
4544 e.adb:9:12: "V" is undefined
4545 @end smallexample
4546
4547 @noindent
4548 The @option{-gnatf} switch also generates additional information for
4549 some error messages.  Some examples are:
4550
4551 @itemize @bullet
4552 @item
4553 Full details on entities not available in high integrity mode
4554 @item
4555 Details on possibly non-portable unchecked conversion
4556 @item
4557 List possible interpretations for ambiguous calls
4558 @item
4559 Additional details on incorrect parameters
4560 @end itemize
4561
4562 @item -gnatjnn
4563 @cindex @option{-gnatjnn} (@command{gcc})
4564 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4565 with continuation lines are treated as though the continuation lines were
4566 separate messages (and so a warning with two continuation lines counts as
4567 three warnings, and is listed as three separate messages).
4568
4569 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4570 messages are output in a different manner. A message and all its continuation
4571 lines are treated as a unit, and count as only one warning or message in the
4572 statistics totals. Furthermore, the message is reformatted so that no line
4573 is longer than nn characters.
4574
4575 @item -gnatq
4576 @cindex @option{-gnatq} (@command{gcc})
4577 @ifclear vms
4578 The @code{q} stands for quit (really ``don't quit'').
4579 @end ifclear
4580 In normal operation mode, the compiler first parses the program and
4581 determines if there are any syntax errors. If there are, appropriate
4582 error messages are generated and compilation is immediately terminated.
4583 This switch tells
4584 GNAT to continue with semantic analysis even if syntax errors have been
4585 found. This may enable the detection of more errors in a single run. On
4586 the other hand, the semantic analyzer is more likely to encounter some
4587 internal fatal error when given a syntactically invalid tree.
4588
4589 @item -gnatQ
4590 @cindex @option{-gnatQ} (@command{gcc})
4591 In normal operation mode, the @file{ALI} file is not generated if any
4592 illegalities are detected in the program. The use of @option{-gnatQ} forces
4593 generation of the @file{ALI} file. This file is marked as being in
4594 error, so it cannot be used for binding purposes, but it does contain
4595 reasonably complete cross-reference information, and thus may be useful
4596 for use by tools (e.g., semantic browsing tools or integrated development
4597 environments) that are driven from the @file{ALI} file. This switch
4598 implies @option{-gnatq}, since the semantic phase must be run to get a
4599 meaningful ALI file.
4600
4601 In addition, if @option{-gnatt} is also specified, then the tree file is
4602 generated even if there are illegalities. It may be useful in this case
4603 to also specify @option{-gnatq} to ensure that full semantic processing
4604 occurs. The resulting tree file can be processed by ASIS, for the purpose
4605 of providing partial information about illegal units, but if the error
4606 causes the tree to be badly malformed, then ASIS may crash during the
4607 analysis.
4608
4609 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4610 being in error, @command{gnatmake} will attempt to recompile the source when it
4611 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4612
4613 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4614 since ALI files are never generated if @option{-gnats} is set.
4615
4616 @end table
4617
4618 @node Warning Message Control
4619 @subsection Warning Message Control
4620 @cindex Warning messages
4621 @noindent
4622 In addition to error messages, which correspond to illegalities as defined
4623 in the Ada Reference Manual, the compiler detects two kinds of warning
4624 situations.
4625
4626 First, the compiler considers some constructs suspicious and generates a
4627 warning message to alert you to a possible error. Second, if the
4628 compiler detects a situation that is sure to raise an exception at
4629 run time, it generates a warning message. The following shows an example
4630 of warning messages:
4631 @smallexample
4632 e.adb:4:24: warning: creation of object may raise Storage_Error
4633 e.adb:10:17: warning: static value out of range
4634 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4635 @end smallexample
4636
4637 @noindent
4638 GNAT considers a large number of situations as appropriate
4639 for the generation of warning messages. As always, warnings are not
4640 definite indications of errors. For example, if you do an out-of-range
4641 assignment with the deliberate intention of raising a
4642 @code{Constraint_Error} exception, then the warning that may be
4643 issued does not indicate an error. Some of the situations for which GNAT
4644 issues warnings (at least some of the time) are given in the following
4645 list. This list is not complete, and new warnings are often added to
4646 subsequent versions of GNAT. The list is intended to give a general idea
4647 of the kinds of warnings that are generated.
4648
4649 @itemize @bullet
4650 @item
4651 Possible infinitely recursive calls
4652
4653 @item
4654 Out-of-range values being assigned
4655
4656 @item
4657 Possible order of elaboration problems
4658
4659 @item
4660 Assertions (pragma Assert) that are sure to fail
4661
4662 @item
4663 Unreachable code
4664
4665 @item
4666 Address clauses with possibly unaligned values, or where an attempt is
4667 made to overlay a smaller variable with a larger one.
4668
4669 @item
4670 Fixed-point type declarations with a null range
4671
4672 @item
4673 Direct_IO or Sequential_IO instantiated with a type that has access values
4674
4675 @item
4676 Variables that are never assigned a value
4677
4678 @item
4679 Variables that are referenced before being initialized
4680
4681 @item
4682 Task entries with no corresponding @code{accept} statement
4683
4684 @item
4685 Duplicate accepts for the same task entry in a @code{select}
4686
4687 @item
4688 Objects that take too much storage
4689
4690 @item
4691 Unchecked conversion between types of differing sizes
4692
4693 @item
4694 Missing @code{return} statement along some execution path in a function
4695
4696 @item
4697 Incorrect (unrecognized) pragmas
4698
4699 @item
4700 Incorrect external names
4701
4702 @item
4703 Allocation from empty storage pool
4704
4705 @item
4706 Potentially blocking operation in protected type
4707
4708 @item
4709 Suspicious parenthesization of expressions
4710
4711 @item
4712 Mismatching bounds in an aggregate
4713
4714 @item
4715 Attempt to return local value by reference
4716
4717 @item
4718 Premature instantiation of a generic body
4719
4720 @item
4721 Attempt to pack aliased components
4722
4723 @item
4724 Out of bounds array subscripts
4725
4726 @item
4727 Wrong length on string assignment
4728
4729 @item
4730 Violations of style rules if style checking is enabled
4731
4732 @item
4733 Unused @code{with} clauses
4734
4735 @item
4736 @code{Bit_Order} usage that does not have any effect
4737
4738 @item
4739 @code{Standard.Duration} used to resolve universal fixed expression
4740
4741 @item
4742 Dereference of possibly null value
4743
4744 @item
4745 Declaration that is likely to cause storage error
4746
4747 @item
4748 Internal GNAT unit @code{with}'ed by application unit
4749
4750 @item
4751 Values known to be out of range at compile time
4752
4753 @item
4754 Unreferenced labels and variables
4755
4756 @item
4757 Address overlays that could clobber memory
4758
4759 @item
4760 Unexpected initialization when address clause present
4761
4762 @item
4763 Bad alignment for address clause
4764
4765 @item
4766 Useless type conversions
4767
4768 @item
4769 Redundant assignment statements and other redundant constructs
4770
4771 @item
4772 Useless exception handlers
4773
4774 @item
4775 Accidental hiding of name by child unit
4776
4777 @item
4778 Access before elaboration detected at compile time
4779
4780 @item
4781 A range in a @code{for} loop that is known to be null or might be null
4782
4783 @end itemize
4784
4785 @noindent
4786 The following section lists compiler switches that are available
4787 to control the handling of warning messages. It is also possible
4788 to exercise much finer control over what warnings are issued and
4789 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
4790 gnat_rm, GNAT Reference manual}.
4791
4792 @table @option
4793 @c !sort!
4794 @item -gnatwa
4795 @emph{Activate all optional errors.}
4796 @cindex @option{-gnatwa} (@command{gcc})
4797 This switch activates most optional warning messages, see remaining list
4798 in this section for details on optional warning messages that can be
4799 individually controlled.  The warnings that are not turned on by this
4800 switch are
4801 @option{-gnatwd} (implicit dereferencing),
4802 @option{-gnatwh} (hiding),
4803 @option{-gnatwl} (elaboration warnings),
4804 @option{-gnatw.o} (warn on values set by out parameters ignored)
4805 and @option{-gnatwt} (tracking of deleted conditional code).
4806 All other optional warnings are turned on.
4807
4808 @item -gnatwA
4809 @emph{Suppress all optional errors.}
4810 @cindex @option{-gnatwA} (@command{gcc})
4811 This switch suppresses all optional warning messages, see remaining list
4812 in this section for details on optional warning messages that can be
4813 individually controlled.
4814
4815 @item -gnatw.a
4816 @emph{Activate warnings on failing assertions.}
4817 @cindex @option{-gnatw.a} (@command{gcc})
4818 @cindex Assert failures
4819 This switch activates warnings for assertions where the compiler can tell at
4820 compile time that the assertion will fail. Note that this warning is given
4821 even if assertions are disabled. The default is that such warnings are
4822 generated.
4823
4824 @item -gnatw.A
4825 @emph{Suppress warnings on failing assertions.}
4826 @cindex @option{-gnatw.A} (@command{gcc})
4827 @cindex Assert failures
4828 This switch suppresses warnings for assertions where the compiler can tell at
4829 compile time that the assertion will fail.
4830
4831 @item -gnatwb
4832 @emph{Activate warnings on bad fixed values.}
4833 @cindex @option{-gnatwb} (@command{gcc})
4834 @cindex Bad fixed values
4835 @cindex Fixed-point Small value
4836 @cindex Small value
4837 This switch activates warnings for static fixed-point expressions whose
4838 value is not an exact multiple of Small. Such values are implementation
4839 dependent, since an implementation is free to choose either of the multiples
4840 that surround the value. GNAT always chooses the closer one, but this is not
4841 required behavior, and it is better to specify a value that is an exact
4842 multiple, ensuring predictable execution. The default is that such warnings
4843 are not generated.
4844
4845 @item -gnatwB
4846 @emph{Suppress warnings on bad fixed values.}
4847 @cindex @option{-gnatwB} (@command{gcc})
4848 This switch suppresses warnings for static fixed-point expressions whose
4849 value is not an exact multiple of Small.
4850
4851 @item -gnatw.b
4852 @emph{Activate warnings on biased representation.}
4853 @cindex @option{-gnatw.b} (@command{gcc})
4854 @cindex Biased representation
4855 This switch activates warnings when a size clause, value size clause, component
4856 clause, or component size clause forces the use of biased representation for an
4857 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
4858 to represent 10/11). The default is that such warnings are generated.
4859
4860 @item -gnatw.B
4861 @emph{Suppress warnings on biased representation.}
4862 @cindex @option{-gnatwB} (@command{gcc})
4863 This switch suppresses warnings for representation clauses that force the use
4864 of biased representation.
4865
4866 @item -gnatwc
4867 @emph{Activate warnings on conditionals.}
4868 @cindex @option{-gnatwc} (@command{gcc})
4869 @cindex Conditionals, constant
4870 This switch activates warnings for conditional expressions used in
4871 tests that are known to be True or False at compile time. The default
4872 is that such warnings are not generated.
4873 Note that this warning does
4874 not get issued for the use of boolean variables or constants whose
4875 values are known at compile time, since this is a standard technique
4876 for conditional compilation in Ada, and this would generate too many
4877 false positive warnings.
4878
4879 This warning option also activates a special test for comparisons using
4880 the operators ``>='' and`` <=''.
4881 If the compiler can tell that only the equality condition is possible,
4882 then it will warn that the ``>'' or ``<'' part of the test
4883 is useless and that the operator could be replaced by ``=''.
4884 An example would be comparing a @code{Natural} variable <= 0.
4885
4886 This warning option also generates warnings if
4887 one or both tests is optimized away in a membership test for integer
4888 values if the result can be determined at compile time. Range tests on
4889 enumeration types are not included, since it is common for such tests
4890 to include an end point.
4891
4892 This warning can also be turned on using @option{-gnatwa}.
4893
4894 @item -gnatwC
4895 @emph{Suppress warnings on conditionals.}
4896 @cindex @option{-gnatwC} (@command{gcc})
4897 This switch suppresses warnings for conditional expressions used in
4898 tests that are known to be True or False at compile time.
4899
4900 @item -gnatw.c
4901 @emph{Activate warnings on missing component clauses.}
4902 @cindex @option{-gnatw.c} (@command{gcc})
4903 @cindex Component clause, missing
4904 This switch activates warnings for record components where a record
4905 representation clause is present and has component clauses for the
4906 majority, but not all, of the components. A warning is given for each
4907 component for which no component clause is present.
4908
4909 This warning can also be turned on using @option{-gnatwa}.
4910
4911 @item -gnatw.C
4912 @emph{Suppress warnings on missing component clauses.}
4913 @cindex @option{-gnatwC} (@command{gcc})
4914 This switch suppresses warnings for record components that are
4915 missing a component clause in the situation described above.
4916
4917 @item -gnatwd
4918 @emph{Activate warnings on implicit dereferencing.}
4919 @cindex @option{-gnatwd} (@command{gcc})
4920 If this switch is set, then the use of a prefix of an access type
4921 in an indexed component, slice, or selected component without an
4922 explicit @code{.all} will generate a warning. With this warning
4923 enabled, access checks occur only at points where an explicit
4924 @code{.all} appears in the source code (assuming no warnings are
4925 generated as a result of this switch). The default is that such
4926 warnings are not generated.
4927 Note that @option{-gnatwa} does not affect the setting of
4928 this warning option.
4929
4930 @item -gnatwD
4931 @emph{Suppress warnings on implicit dereferencing.}
4932 @cindex @option{-gnatwD} (@command{gcc})
4933 @cindex Implicit dereferencing
4934 @cindex Dereferencing, implicit
4935 This switch suppresses warnings for implicit dereferences in
4936 indexed components, slices, and selected components.
4937
4938 @item -gnatwe
4939 @emph{Treat warnings as errors.}
4940 @cindex @option{-gnatwe} (@command{gcc})
4941 @cindex Warnings, treat as error
4942 This switch causes warning messages to be treated as errors.
4943 The warning string still appears, but the warning messages are counted
4944 as errors, and prevent the generation of an object file.
4945
4946 @item -gnatw.e
4947 @emph{Activate every optional warning}
4948 @cindex @option{-gnatw.e} (@command{gcc})
4949 @cindex Warnings, activate every optional warning
4950 This switch activates all optional warnings, including those which
4951 are not activated by @code{-gnatwa}.
4952
4953 @item -gnatwf
4954 @emph{Activate warnings on unreferenced formals.}
4955 @cindex @option{-gnatwf} (@command{gcc})
4956 @cindex Formals, unreferenced
4957 This switch causes a warning to be generated if a formal parameter
4958 is not referenced in the body of the subprogram. This warning can
4959 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
4960 default is that these warnings are not generated.
4961
4962 @item -gnatwF
4963 @emph{Suppress warnings on unreferenced formals.}
4964 @cindex @option{-gnatwF} (@command{gcc})
4965 This switch suppresses warnings for unreferenced formal
4966 parameters. Note that the
4967 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4968 effect of warning on unreferenced entities other than subprogram
4969 formals.
4970
4971 @item -gnatwg
4972 @emph{Activate warnings on unrecognized pragmas.}
4973 @cindex @option{-gnatwg} (@command{gcc})
4974 @cindex Pragmas, unrecognized
4975 This switch causes a warning to be generated if an unrecognized
4976 pragma is encountered. Apart from issuing this warning, the
4977 pragma is ignored and has no effect. This warning can
4978 also be turned on using @option{-gnatwa}. The default
4979 is that such warnings are issued (satisfying the Ada Reference
4980 Manual requirement that such warnings appear).
4981
4982 @item -gnatwG
4983 @emph{Suppress warnings on unrecognized pragmas.}
4984 @cindex @option{-gnatwG} (@command{gcc})
4985 This switch suppresses warnings for unrecognized pragmas.
4986
4987 @item -gnatwh
4988 @emph{Activate warnings on hiding.}
4989 @cindex @option{-gnatwh} (@command{gcc})
4990 @cindex Hiding of Declarations
4991 This switch activates warnings on hiding declarations.
4992 A declaration is considered hiding
4993 if it is for a non-overloadable entity, and it declares an entity with the
4994 same name as some other entity that is directly or use-visible. The default
4995 is that such warnings are not generated.
4996 Note that @option{-gnatwa} does not affect the setting of this warning option.
4997
4998 @item -gnatwH
4999 @emph{Suppress warnings on hiding.}
5000 @cindex @option{-gnatwH} (@command{gcc})
5001 This switch suppresses warnings on hiding declarations.
5002
5003 @item -gnatwi
5004 @emph{Activate warnings on implementation units.}
5005 @cindex @option{-gnatwi} (@command{gcc})
5006 This switch activates warnings for a @code{with} of an internal GNAT
5007 implementation unit, defined as any unit from the @code{Ada},
5008 @code{Interfaces}, @code{GNAT},
5009 ^^@code{DEC},^ or @code{System}
5010 hierarchies that is not
5011 documented in either the Ada Reference Manual or the GNAT
5012 Programmer's Reference Manual. Such units are intended only
5013 for internal implementation purposes and should not be @code{with}'ed
5014 by user programs. The default is that such warnings are generated
5015 This warning can also be turned on using @option{-gnatwa}.
5016
5017 @item -gnatwI
5018 @emph{Disable warnings on implementation units.}
5019 @cindex @option{-gnatwI} (@command{gcc})
5020 This switch disables warnings for a @code{with} of an internal GNAT
5021 implementation unit.
5022
5023 @item -gnatwj
5024 @emph{Activate warnings on obsolescent features (Annex J).}
5025 @cindex @option{-gnatwj} (@command{gcc})
5026 @cindex Features, obsolescent
5027 @cindex Obsolescent features
5028 If this warning option is activated, then warnings are generated for
5029 calls to subprograms marked with @code{pragma Obsolescent} and
5030 for use of features in Annex J of the Ada Reference Manual. In the
5031 case of Annex J, not all features are flagged. In particular use
5032 of the renamed packages (like @code{Text_IO}) and use of package
5033 @code{ASCII} are not flagged, since these are very common and
5034 would generate many annoying positive warnings. The default is that
5035 such warnings are not generated. This warning is also turned on by
5036 the use of @option{-gnatwa}.
5037
5038 In addition to the above cases, warnings are also generated for
5039 GNAT features that have been provided in past versions but which
5040 have been superseded (typically by features in the new Ada standard).
5041 For example, @code{pragma Ravenscar} will be flagged since its
5042 function is replaced by @code{pragma Profile(Ravenscar)}.
5043
5044 Note that this warning option functions differently from the
5045 restriction @code{No_Obsolescent_Features} in two respects.
5046 First, the restriction applies only to annex J features.
5047 Second, the restriction does flag uses of package @code{ASCII}.
5048
5049 @item -gnatwJ
5050 @emph{Suppress warnings on obsolescent features (Annex J).}
5051 @cindex @option{-gnatwJ} (@command{gcc})
5052 This switch disables warnings on use of obsolescent features.
5053
5054 @item -gnatwk
5055 @emph{Activate warnings on variables that could be constants.}
5056 @cindex @option{-gnatwk} (@command{gcc})
5057 This switch activates warnings for variables that are initialized but
5058 never modified, and then could be declared constants. The default is that
5059 such warnings are not given.
5060 This warning can also be turned on using @option{-gnatwa}.
5061
5062 @item -gnatwK
5063 @emph{Suppress warnings on variables that could be constants.}
5064 @cindex @option{-gnatwK} (@command{gcc})
5065 This switch disables warnings on variables that could be declared constants.
5066
5067 @item -gnatwl
5068 @emph{Activate warnings for elaboration pragmas.}
5069 @cindex @option{-gnatwl} (@command{gcc})
5070 @cindex Elaboration, warnings
5071 This switch activates warnings on missing
5072 @code{Elaborate_All} and @code{Elaborate} pragmas.
5073 See the section in this guide on elaboration checking for details on
5074 when such pragmas should be used. In dynamic elaboration mode, this switch
5075 generations warnings about the need to add elaboration pragmas. Note however,
5076 that if you blindly follow these warnings, and add @code{Elaborate_All}
5077 warnings wherever they are recommended, you basically end up with the
5078 equivalent of the static elaboration model, which may not be what you want for
5079 legacy code for which the static model does not work.
5080
5081 For the static model, the messages generated are labeled "info:" (for
5082 information messages). They are not warnings to add elaboration pragmas,
5083 merely informational messages showing what implicit elaboration pragmas
5084 have been added, for use in analyzing elaboration circularity problems.
5085
5086 Warnings are also generated if you
5087 are using the static mode of elaboration, and a @code{pragma Elaborate}
5088 is encountered. The default is that such warnings
5089 are not generated.
5090 This warning is not automatically turned on by the use of @option{-gnatwa}.
5091
5092 @item -gnatwL
5093 @emph{Suppress warnings for elaboration pragmas.}
5094 @cindex @option{-gnatwL} (@command{gcc})
5095 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5096 See the section in this guide on elaboration checking for details on
5097 when such pragmas should be used.
5098
5099 @item -gnatwm
5100 @emph{Activate warnings on modified but unreferenced variables.}
5101 @cindex @option{-gnatwm} (@command{gcc})
5102 This switch activates warnings for variables that are assigned (using
5103 an initialization value or with one or more assignment statements) but
5104 whose value is never read. The warning is suppressed for volatile
5105 variables and also for variables that are renamings of other variables
5106 or for which an address clause is given.
5107 This warning can also be turned on using @option{-gnatwa}.
5108 The default is that these warnings are not given.
5109
5110 @item -gnatwM
5111 @emph{Disable warnings on modified but unreferenced variables.}
5112 @cindex @option{-gnatwM} (@command{gcc})
5113 This switch disables warnings for variables that are assigned or
5114 initialized, but never read.
5115
5116 @item -gnatwn
5117 @emph{Set normal warnings mode.}
5118 @cindex @option{-gnatwn} (@command{gcc})
5119 This switch sets normal warning mode, in which enabled warnings are
5120 issued and treated as warnings rather than errors. This is the default
5121 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5122 an explicit @option{-gnatws} or
5123 @option{-gnatwe}. It also cancels the effect of the
5124 implicit @option{-gnatwe} that is activated by the
5125 use of @option{-gnatg}.
5126
5127 @item -gnatwo
5128 @emph{Activate warnings on address clause overlays.}
5129 @cindex @option{-gnatwo} (@command{gcc})
5130 @cindex Address Clauses, warnings
5131 This switch activates warnings for possibly unintended initialization
5132 effects of defining address clauses that cause one variable to overlap
5133 another. The default is that such warnings are generated.
5134 This warning can also be turned on using @option{-gnatwa}.
5135
5136 @item -gnatwO
5137 @emph{Suppress warnings on address clause overlays.}
5138 @cindex @option{-gnatwO} (@command{gcc})
5139 This switch suppresses warnings on possibly unintended initialization
5140 effects of defining address clauses that cause one variable to overlap
5141 another.
5142
5143 @item -gnatw.o
5144 @emph{Activate warnings on modified but unreferenced out parameters.}
5145 @cindex @option{-gnatw.o} (@command{gcc})
5146 This switch activates warnings for variables that are modified by using
5147 them as actuals for a call to a procedure with an out mode formal, where
5148 the resulting assigned value is never read. It is applicable in the case
5149 where there is more than one out mode formal. If there is only one out
5150 mode formal, the warning is issued by default (controlled by -gnatwu).
5151 The warning is suppressed for volatile
5152 variables and also for variables that are renamings of other variables
5153 or for which an address clause is given.
5154 The default is that these warnings are not given. Note that this warning
5155 is not included in -gnatwa, it must be activated explicitly.
5156
5157 @item -gnatw.O
5158 @emph{Disable warnings on modified but unreferenced out parameters.}
5159 @cindex @option{-gnatw.O} (@command{gcc})
5160 This switch suppresses warnings for variables that are modified by using
5161 them as actuals for a call to a procedure with an out mode formal, where
5162 the resulting assigned value is never read.
5163
5164 @item -gnatwp
5165 @emph{Activate warnings on ineffective pragma Inlines.}
5166 @cindex @option{-gnatwp} (@command{gcc})
5167 @cindex Inlining, warnings
5168 This switch activates warnings for failure of front end inlining
5169 (activated by @option{-gnatN}) to inline a particular call. There are
5170 many reasons for not being able to inline a call, including most
5171 commonly that the call is too complex to inline. The default is
5172 that such warnings are not given.
5173 This warning can also be turned on using @option{-gnatwa}.
5174 Warnings on ineffective inlining by the gcc back-end can be activated
5175 separately, using the gcc switch -Winline.
5176
5177 @item -gnatwP
5178 @emph{Suppress warnings on ineffective pragma Inlines.}
5179 @cindex @option{-gnatwP} (@command{gcc})
5180 This switch suppresses warnings on ineffective pragma Inlines. If the
5181 inlining mechanism cannot inline a call, it will simply ignore the
5182 request silently.
5183
5184 @item -gnatw.p
5185 @emph{Activate warnings on parameter ordering.}
5186 @cindex @option{-gnatw.p} (@command{gcc})
5187 @cindex Parameter order, warnings
5188 This switch activates warnings for cases of suspicious parameter
5189 ordering when the list of arguments are all simple identifiers that
5190 match the names of the formals, but are in a different order. The
5191 warning is suppressed if any use of named parameter notation is used,
5192 so this is the appropriate way to suppress a false positive (and
5193 serves to emphasize that the "misordering" is deliberate). The
5194 default is
5195 that such warnings are not given.
5196 This warning can also be turned on using @option{-gnatwa}.
5197
5198 @item -gnatw.P
5199 @emph{Suppress warnings on parameter ordering.}
5200 @cindex @option{-gnatw.P} (@command{gcc})
5201 This switch suppresses warnings on cases of suspicious parameter
5202 ordering.
5203
5204 @item -gnatwq
5205 @emph{Activate warnings on questionable missing parentheses.}
5206 @cindex @option{-gnatwq} (@command{gcc})
5207 @cindex Parentheses, warnings
5208 This switch activates warnings for cases where parentheses are not used and
5209 the result is potential ambiguity from a readers point of view. For example
5210 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5211 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5212 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5213 follow the rule of always parenthesizing to make the association clear, and
5214 this warning switch warns if such parentheses are not present. The default
5215 is that these warnings are given.
5216 This warning can also be turned on using @option{-gnatwa}.
5217
5218 @item -gnatwQ
5219 @emph{Suppress warnings on questionable missing parentheses.}
5220 @cindex @option{-gnatwQ} (@command{gcc})
5221 This switch suppresses warnings for cases where the association is not
5222 clear and the use of parentheses is preferred.
5223
5224 @item -gnatwr
5225 @emph{Activate warnings on redundant constructs.}
5226 @cindex @option{-gnatwr} (@command{gcc})
5227 This switch activates warnings for redundant constructs. The following
5228 is the current list of constructs regarded as redundant:
5229
5230 @itemize @bullet
5231 @item
5232 Assignment of an item to itself.
5233 @item
5234 Type conversion that converts an expression to its own type.
5235 @item
5236 Use of the attribute @code{Base} where @code{typ'Base} is the same
5237 as @code{typ}.
5238 @item
5239 Use of pragma @code{Pack} when all components are placed by a record
5240 representation clause.
5241 @item
5242 Exception handler containing only a reraise statement (raise with no
5243 operand) which has no effect.
5244 @item
5245 Use of the operator abs on an operand that is known at compile time
5246 to be non-negative
5247 @item
5248 Comparison of boolean expressions to an explicit True value.
5249 @end itemize
5250
5251 This warning can also be turned on using @option{-gnatwa}.
5252 The default is that warnings for redundant constructs are not given.
5253
5254 @item -gnatwR
5255 @emph{Suppress warnings on redundant constructs.}
5256 @cindex @option{-gnatwR} (@command{gcc})
5257 This switch suppresses warnings for redundant constructs.
5258
5259 @item -gnatws
5260 @emph{Suppress all warnings.}
5261 @cindex @option{-gnatws} (@command{gcc})
5262 This switch completely suppresses the
5263 output of all warning messages from the GNAT front end.
5264 Note that it does not suppress warnings from the @command{gcc} back end.
5265 To suppress these back end warnings as well, use the switch @option{-w}
5266 in addition to @option{-gnatws}.
5267
5268 @item -gnatwt
5269 @emph{Activate warnings for tracking of deleted conditional code.}
5270 @cindex @option{-gnatwt} (@command{gcc})
5271 @cindex Deactivated code, warnings
5272 @cindex Deleted code, warnings
5273 This switch activates warnings for tracking of code in conditionals (IF and
5274 CASE statements) that is detected to be dead code which cannot be executed, and
5275 which is removed by the front end. This warning is off by default, and is not
5276 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5277 useful for detecting deactivated code in certified applications.
5278
5279 @item -gnatwT
5280 @emph{Suppress warnings for tracking of deleted conditional code.}
5281 @cindex @option{-gnatwT} (@command{gcc})
5282 This switch suppresses warnings for tracking of deleted conditional code.
5283
5284 @item -gnatwu
5285 @emph{Activate warnings on unused entities.}
5286 @cindex @option{-gnatwu} (@command{gcc})
5287 This switch activates warnings to be generated for entities that
5288 are declared but not referenced, and for units that are @code{with}'ed
5289 and not
5290 referenced. In the case of packages, a warning is also generated if
5291 no entities in the package are referenced. This means that if the package
5292 is referenced but the only references are in @code{use}
5293 clauses or @code{renames}
5294 declarations, a warning is still generated. A warning is also generated
5295 for a generic package that is @code{with}'ed but never instantiated.
5296 In the case where a package or subprogram body is compiled, and there
5297 is a @code{with} on the corresponding spec
5298 that is only referenced in the body,
5299 a warning is also generated, noting that the
5300 @code{with} can be moved to the body. The default is that
5301 such warnings are not generated.
5302 This switch also activates warnings on unreferenced formals
5303 (it includes the effect of @option{-gnatwf}).
5304 This warning can also be turned on using @option{-gnatwa}.
5305
5306 @item -gnatwU
5307 @emph{Suppress warnings on unused entities.}
5308 @cindex @option{-gnatwU} (@command{gcc})
5309 This switch suppresses warnings for unused entities and packages.
5310 It also turns off warnings on unreferenced formals (and thus includes
5311 the effect of @option{-gnatwF}).
5312
5313 @item -gnatwv
5314 @emph{Activate warnings on unassigned variables.}
5315 @cindex @option{-gnatwv} (@command{gcc})
5316 @cindex Unassigned variable warnings
5317 This switch activates warnings for access to variables which
5318 may not be properly initialized. The default is that
5319 such warnings are generated.
5320 This warning can also be turned on using @option{-gnatwa}.
5321
5322 @item -gnatwV
5323 @emph{Suppress warnings on unassigned variables.}
5324 @cindex @option{-gnatwV} (@command{gcc})
5325 This switch suppresses warnings for access to variables which
5326 may not be properly initialized.
5327 For variables of a composite type, the warning can also be suppressed in
5328 Ada 2005 by using a default initialization with a box. For example, if
5329 Table is an array of records whose components are only partially uninitialized,
5330 then the following code:
5331
5332 @smallexample @c ada
5333    Tab : Table := (others => <>);
5334 @end smallexample
5335
5336 will suppress warnings on subsequent statements that access components
5337 of variable Tab.
5338
5339 @item -gnatww
5340 @emph{Activate warnings on wrong low bound assumption.}
5341 @cindex @option{-gnatww} (@command{gcc})
5342 @cindex String indexing warnings
5343 This switch activates warnings for indexing an unconstrained string parameter
5344 with a literal or S'Length. This is a case where the code is assuming that the
5345 low bound is one, which is in general not true (for example when a slice is
5346 passed). The default is that such warnings are generated.
5347 This warning can also be turned on using @option{-gnatwa}.
5348
5349 @item -gnatwW
5350 @emph{Suppress warnings on wrong low bound assumption.}
5351 @cindex @option{-gnatwW} (@command{gcc})
5352 This switch suppresses warnings for indexing an unconstrained string parameter
5353 with a literal or S'Length. Note that this warning can also be suppressed
5354 in a particular case by adding an
5355 assertion that the lower bound is 1,
5356 as shown in the following example.
5357
5358 @smallexample @c ada
5359    procedure K (S : String) is
5360       pragma Assert (S'First = 1);
5361       @dots{}
5362 @end smallexample
5363
5364 @item -gnatw.w
5365 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5366 @cindex @option{-gnatw.w} (@command{gcc})
5367 @cindex Warnings Off control
5368 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5369 where either the pragma is entirely useless (because it suppresses no
5370 warnings), or it could be replaced by @code{pragma Unreferenced} or
5371 @code{pragma Unmodified}.The default is that these warnings are not given.
5372 Note that this warning is not included in -gnatwa, it must be
5373 activated explicitly.
5374
5375 @item -gnatw.W
5376 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5377 @cindex @option{-gnatw.W} (@command{gcc})
5378 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5379
5380 @item -gnatwx
5381 @emph{Activate warnings on Export/Import pragmas.}
5382 @cindex @option{-gnatwx} (@command{gcc})
5383 @cindex Export/Import pragma warnings
5384 This switch activates warnings on Export/Import pragmas when
5385 the compiler detects a possible conflict between the Ada and
5386 foreign language calling sequences. For example, the use of
5387 default parameters in a convention C procedure is dubious
5388 because the C compiler cannot supply the proper default, so
5389 a warning is issued. The default is that such warnings are
5390 generated.
5391 This warning can also be turned on using @option{-gnatwa}.
5392
5393 @item -gnatwX
5394 @emph{Suppress warnings on Export/Import pragmas.}
5395 @cindex @option{-gnatwX} (@command{gcc})
5396 This switch suppresses warnings on Export/Import pragmas.
5397 The sense of this is that you are telling the compiler that
5398 you know what you are doing in writing the pragma, and it
5399 should not complain at you.
5400
5401 @item -gnatw.x
5402 @emph{Activate warnings for No_Exception_Propagation mode.}
5403 @cindex @option{-gnatwm} (@command{gcc})
5404 This switch activates warnings for exception usage when pragma Restrictions
5405 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5406 explicit exception raises which are not covered by a local handler, and for
5407 exception handlers which do not cover a local raise. The default is that these
5408 warnings are not given.
5409
5410 @item -gnatw.X
5411 @emph{Disable warnings for No_Exception_Propagation mode.}
5412 This switch disables warnings for exception usage when pragma Restrictions
5413 (No_Exception_Propagation) is in effect.
5414
5415 @item -gnatwy
5416 @emph{Activate warnings for Ada 2005 compatibility issues.}
5417 @cindex @option{-gnatwy} (@command{gcc})
5418 @cindex Ada 2005 compatibility issues warnings
5419 For the most part Ada 2005 is upwards compatible with Ada 95,
5420 but there are some exceptions (for example the fact that
5421 @code{interface} is now a reserved word in Ada 2005). This
5422 switch activates several warnings to help in identifying
5423 and correcting such incompatibilities. The default is that
5424 these warnings are generated. Note that at one point Ada 2005
5425 was called Ada 0Y, hence the choice of character.
5426 This warning can also be turned on using @option{-gnatwa}.
5427
5428 @item -gnatwY
5429 @emph{Disable warnings for Ada 2005 compatibility issues.}
5430 @cindex @option{-gnatwY} (@command{gcc})
5431 @cindex Ada 2005 compatibility issues warnings
5432 This switch suppresses several warnings intended to help in identifying
5433 incompatibilities between Ada 95 and Ada 2005.
5434
5435 @item -gnatwz
5436 @emph{Activate warnings on unchecked conversions.}
5437 @cindex @option{-gnatwz} (@command{gcc})
5438 @cindex Unchecked_Conversion warnings
5439 This switch activates warnings for unchecked conversions
5440 where the types are known at compile time to have different
5441 sizes. The default
5442 is that such warnings are generated. Warnings are also
5443 generated for subprogram pointers with different conventions,
5444 and, on VMS only, for data pointers with different conventions.
5445 This warning can also be turned on using @option{-gnatwa}.
5446
5447 @item -gnatwZ
5448 @emph{Suppress warnings on unchecked conversions.}
5449 @cindex @option{-gnatwZ} (@command{gcc})
5450 This switch suppresses warnings for unchecked conversions
5451 where the types are known at compile time to have different
5452 sizes or conventions.
5453
5454 @item ^-Wunused^WARNINGS=UNUSED^
5455 @cindex @option{-Wunused}
5456 The warnings controlled by the @option{-gnatw} switch are generated by
5457 the front end of the compiler. The @option{GCC} back end can provide
5458 additional warnings and they are controlled by the @option{-W} switch.
5459 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5460 warnings for entities that are declared but not referenced.
5461
5462 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5463 @cindex @option{-Wuninitialized}
5464 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5465 the back end warning for uninitialized variables. This switch must be
5466 used in conjunction with an optimization level greater than zero.
5467
5468 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5469 @cindex @option{-Wall}
5470 This switch enables all the above warnings from the @option{GCC} back end.
5471 The code generator detects a number of warning situations that are missed
5472 by the @option{GNAT} front end, and this switch can be used to activate them.
5473 The use of this switch also sets the default front end warning mode to
5474 @option{-gnatwa}, that is, most front end warnings activated as well.
5475
5476 @item ^-w^/NO_BACK_END_WARNINGS^
5477 @cindex @option{-w}
5478 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5479 The use of this switch also sets the default front end warning mode to
5480 @option{-gnatws}, that is, front end warnings suppressed as well.
5481
5482 @end table
5483
5484 @noindent
5485 @ifclear vms
5486 A string of warning parameters can be used in the same parameter. For example:
5487
5488 @smallexample
5489 -gnatwaLe
5490 @end smallexample
5491
5492 @noindent
5493 will turn on all optional warnings except for elaboration pragma warnings,
5494 and also specify that warnings should be treated as errors.
5495 @end ifclear
5496 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5497
5498 @table @option
5499 @c !sort!
5500 @item -gnatwC
5501 @item -gnatwD
5502 @item -gnatwF
5503 @item -gnatwg
5504 @item -gnatwH
5505 @item -gnatwi
5506 @item -gnatwJ
5507 @item -gnatwK
5508 @item -gnatwL
5509 @item -gnatwM
5510 @item -gnatwn
5511 @item -gnatwo
5512 @item -gnatwP
5513 @item -gnatwR
5514 @item -gnatwU
5515 @item -gnatwv
5516 @item -gnatwz
5517 @item -gnatwx
5518
5519 @end table
5520
5521 @node Debugging and Assertion Control
5522 @subsection Debugging and Assertion Control
5523
5524 @table @option
5525 @item -gnata
5526 @cindex @option{-gnata} (@command{gcc})
5527 @findex Assert
5528 @findex Debug
5529 @cindex Assertions
5530
5531 @noindent
5532 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5533 are ignored. This switch, where @samp{a} stands for assert, causes
5534 @code{Assert} and @code{Debug} pragmas to be activated.
5535
5536 The pragmas have the form:
5537
5538 @smallexample
5539 @cartouche
5540    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5541                       @var{static-string-expression}@r{]})
5542    @b{pragma} Debug (@var{procedure call})
5543 @end cartouche
5544 @end smallexample
5545
5546 @noindent
5547 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5548 If the result is @code{True}, the pragma has no effect (other than
5549 possible side effects from evaluating the expression). If the result is
5550 @code{False}, the exception @code{Assert_Failure} declared in the package
5551 @code{System.Assertions} is
5552 raised (passing @var{static-string-expression}, if present, as the
5553 message associated with the exception). If no string expression is
5554 given the default is a string giving the file name and line number
5555 of the pragma.
5556
5557 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5558 @code{pragma Debug} may appear within a declaration sequence, allowing
5559 debugging procedures to be called between declarations.
5560
5561 @ifset vms
5562 @item /DEBUG@r{[}=debug-level@r{]}
5563 @itemx  /NODEBUG
5564 Specifies how much debugging information is to be included in
5565 the resulting object file where 'debug-level' is one of the following:
5566 @table @code
5567 @item   TRACEBACK
5568 Include both debugger symbol records and traceback
5569 the object file.
5570 This is the default setting.
5571 @item   ALL
5572 Include both debugger symbol records and traceback in
5573 object file.
5574 @item   NONE
5575 Excludes both debugger symbol records and traceback
5576 the object file. Same as /NODEBUG.
5577 @item   SYMBOLS
5578 Includes only debugger symbol records in the object
5579 file. Note that this doesn't include traceback information.
5580 @end table
5581 @end ifset
5582 @end table
5583
5584 @node Validity Checking
5585 @subsection Validity Checking
5586 @findex Validity Checking
5587
5588 @noindent
5589 The Ada Reference Manual has specific requirements for checking
5590 for invalid values. In particular, RM 13.9.1 requires that the
5591 evaluation of invalid values (for example from unchecked conversions),
5592 not result in erroneous execution. In GNAT, the result of such an
5593 evaluation in normal default mode is to either use the value
5594 unmodified, or to raise Constraint_Error in those cases where use
5595 of the unmodified value would cause erroneous execution. The cases
5596 where unmodified values might lead to erroneous execution are case
5597 statements (where a wild jump might result from an invalid value),
5598 and subscripts on the left hand side (where memory corruption could
5599 occur as a result of an invalid value).
5600
5601 The @option{-gnatB} switch tells the compiler to assume that all
5602 values are valid (that is, within their declared subtype range)
5603 except in the context of a use of the Valid attribute. This means
5604 the compiler can generate more efficient code, since the range
5605 of values is better known at compile time.
5606
5607 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5608 checking mode.
5609 @ifclear vms
5610 The @code{x} argument is a string of letters that
5611 indicate validity checks that are performed or not performed in addition
5612 to the default checks described above.
5613 @end ifclear
5614 @ifset vms
5615 The options allowed for this qualifier
5616 indicate validity checks that are performed or not performed in addition
5617 to the default checks described above.
5618 @end ifset
5619
5620 @table @option
5621 @c !sort!
5622 @item -gnatVa
5623 @emph{All validity checks.}
5624 @cindex @option{-gnatVa} (@command{gcc})
5625 All validity checks are turned on.
5626 @ifclear vms
5627 That is, @option{-gnatVa} is
5628 equivalent to @option{gnatVcdfimorst}.
5629 @end ifclear
5630
5631 @item -gnatVc
5632 @emph{Validity checks for copies.}
5633 @cindex @option{-gnatVc} (@command{gcc})
5634 The right hand side of assignments, and the initializing values of
5635 object declarations are validity checked.
5636
5637 @item -gnatVd
5638 @emph{Default (RM) validity checks.}
5639 @cindex @option{-gnatVd} (@command{gcc})
5640 Some validity checks are done by default following normal Ada semantics
5641 (RM 13.9.1 (9-11)).
5642 A check is done in case statements that the expression is within the range
5643 of the subtype. If it is not, Constraint_Error is raised.
5644 For assignments to array components, a check is done that the expression used
5645 as index is within the range. If it is not, Constraint_Error is raised.
5646 Both these validity checks may be turned off using switch @option{-gnatVD}.
5647 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5648 switch @option{-gnatVd} will leave the checks turned on.
5649 Switch @option{-gnatVD} should be used only if you are sure that all such
5650 expressions have valid values. If you use this switch and invalid values
5651 are present, then the program is erroneous, and wild jumps or memory
5652 overwriting may occur.
5653
5654 @item -gnatVe
5655 @emph{Validity checks for elementary components.}
5656 @cindex @option{-gnatVe} (@command{gcc})
5657 In the absence of this switch, assignments to record or array components are
5658 not validity checked, even if validity checks for assignments generally
5659 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5660 require valid data, but assignment of individual components does. So for
5661 example, there is a difference between copying the elements of an array with a
5662 slice assignment, compared to assigning element by element in a loop. This
5663 switch allows you to turn off validity checking for components, even when they
5664 are assigned component by component.
5665
5666 @item -gnatVf
5667 @emph{Validity checks for floating-point values.}
5668 @cindex @option{-gnatVf} (@command{gcc})
5669 In the absence of this switch, validity checking occurs only for discrete
5670 values. If @option{-gnatVf} is specified, then validity checking also applies
5671 for floating-point values, and NaNs and infinities are considered invalid,
5672 as well as out of range values for constrained types. Note that this means
5673 that standard IEEE infinity mode is not allowed. The exact contexts
5674 in which floating-point values are checked depends on the setting of other
5675 options. For example,
5676 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5677 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5678 (the order does not matter) specifies that floating-point parameters of mode
5679 @code{in} should be validity checked.
5680
5681 @item -gnatVi
5682 @emph{Validity checks for @code{in} mode parameters}
5683 @cindex @option{-gnatVi} (@command{gcc})
5684 Arguments for parameters of mode @code{in} are validity checked in function
5685 and procedure calls at the point of call.
5686
5687 @item -gnatVm
5688 @emph{Validity checks for @code{in out} mode parameters.}
5689 @cindex @option{-gnatVm} (@command{gcc})
5690 Arguments for parameters of mode @code{in out} are validity checked in
5691 procedure calls at the point of call. The @code{'m'} here stands for
5692 modify, since this concerns parameters that can be modified by the call.
5693 Note that there is no specific option to test @code{out} parameters,
5694 but any reference within the subprogram will be tested in the usual
5695 manner, and if an invalid value is copied back, any reference to it
5696 will be subject to validity checking.
5697
5698 @item -gnatVn
5699 @emph{No validity checks.}
5700 @cindex @option{-gnatVn} (@command{gcc})
5701 This switch turns off all validity checking, including the default checking
5702 for case statements and left hand side subscripts. Note that the use of
5703 the switch @option{-gnatp} suppresses all run-time checks, including
5704 validity checks, and thus implies @option{-gnatVn}. When this switch
5705 is used, it cancels any other @option{-gnatV} previously issued.
5706
5707 @item -gnatVo
5708 @emph{Validity checks for operator and attribute operands.}
5709 @cindex @option{-gnatVo} (@command{gcc})
5710 Arguments for predefined operators and attributes are validity checked.
5711 This includes all operators in package @code{Standard},
5712 the shift operators defined as intrinsic in package @code{Interfaces}
5713 and operands for attributes such as @code{Pos}. Checks are also made
5714 on individual component values for composite comparisons, and on the
5715 expressions in type conversions and qualified expressions. Checks are
5716 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
5717
5718 @item -gnatVp
5719 @emph{Validity checks for parameters.}
5720 @cindex @option{-gnatVp} (@command{gcc})
5721 This controls the treatment of parameters within a subprogram (as opposed
5722 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5723 of parameters on a call. If either of these call options is used, then
5724 normally an assumption is made within a subprogram that the input arguments
5725 have been validity checking at the point of call, and do not need checking
5726 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5727 is not made, and parameters are not assumed to be valid, so their validity
5728 will be checked (or rechecked) within the subprogram.
5729
5730 @item -gnatVr
5731 @emph{Validity checks for function returns.}
5732 @cindex @option{-gnatVr} (@command{gcc})
5733 The expression in @code{return} statements in functions is validity
5734 checked.
5735
5736 @item -gnatVs
5737 @emph{Validity checks for subscripts.}
5738 @cindex @option{-gnatVs} (@command{gcc})
5739 All subscripts expressions are checked for validity, whether they appear
5740 on the right side or left side (in default mode only left side subscripts
5741 are validity checked).
5742
5743 @item -gnatVt
5744 @emph{Validity checks for tests.}
5745 @cindex @option{-gnatVt} (@command{gcc})
5746 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5747 statements are checked, as well as guard expressions in entry calls.
5748
5749 @end table
5750
5751 @noindent
5752 The @option{-gnatV} switch may be followed by
5753 ^a string of letters^a list of options^
5754 to turn on a series of validity checking options.
5755 For example,
5756 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5757 specifies that in addition to the default validity checking, copies and
5758 function return expressions are to be validity checked.
5759 In order to make it easier
5760 to specify the desired combination of effects,
5761 @ifclear vms
5762 the upper case letters @code{CDFIMORST} may
5763 be used to turn off the corresponding lower case option.
5764 @end ifclear
5765 @ifset vms
5766 the prefix @code{NO} on an option turns off the corresponding validity
5767 checking:
5768 @itemize @bullet
5769 @item @code{NOCOPIES}
5770 @item @code{NODEFAULT}
5771 @item @code{NOFLOATS}
5772 @item @code{NOIN_PARAMS}
5773 @item @code{NOMOD_PARAMS}
5774 @item @code{NOOPERANDS}
5775 @item @code{NORETURNS}
5776 @item @code{NOSUBSCRIPTS}
5777 @item @code{NOTESTS}
5778 @end itemize
5779 @end ifset
5780 Thus
5781 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5782 turns on all validity checking options except for
5783 checking of @code{@b{in out}} procedure arguments.
5784
5785 The specification of additional validity checking generates extra code (and
5786 in the case of @option{-gnatVa} the code expansion can be substantial).
5787 However, these additional checks can be very useful in detecting
5788 uninitialized variables, incorrect use of unchecked conversion, and other
5789 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5790 is useful in conjunction with the extra validity checking, since this
5791 ensures that wherever possible uninitialized variables have invalid values.
5792
5793 See also the pragma @code{Validity_Checks} which allows modification of
5794 the validity checking mode at the program source level, and also allows for
5795 temporary disabling of validity checks.
5796
5797 @node Style Checking
5798 @subsection Style Checking
5799 @findex Style checking
5800
5801 @noindent
5802 The @option{-gnaty^x^(option,option,@dots{})^} switch
5803 @cindex @option{-gnaty} (@command{gcc})
5804 causes the compiler to
5805 enforce specified style rules. A limited set of style rules has been used
5806 in writing the GNAT sources themselves. This switch allows user programs
5807 to activate all or some of these checks. If the source program fails a
5808 specified style check, an appropriate warning message is given, preceded by
5809 the character sequence ``(style)''.
5810 @ifset vms
5811 @code{(option,option,@dots{})} is a sequence of keywords
5812 @end ifset
5813 @ifclear vms
5814 The string @var{x} is a sequence of letters or digits
5815 @end ifclear
5816 indicating the particular style
5817 checks to be performed. The following checks are defined:
5818
5819 @table @option
5820 @c !sort!
5821 @item 0-9
5822 @emph{Specify indentation level.}
5823 If a digit from 1-9 appears
5824 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5825 then proper indentation is checked, with the digit indicating the
5826 indentation level required. A value of zero turns off this style check.
5827 The general style of required indentation is as specified by
5828 the examples in the Ada Reference Manual. Full line comments must be
5829 aligned with the @code{--} starting on a column that is a multiple of
5830 the alignment level, or they may be aligned the same way as the following
5831 non-blank line (this is useful when full line comments appear in the middle
5832 of a statement.
5833
5834 @item ^a^ATTRIBUTE^
5835 @emph{Check attribute casing.}
5836 Attribute names, including the case of keywords such as @code{digits}
5837 used as attributes names, must be written in mixed case, that is, the
5838 initial letter and any letter following an underscore must be uppercase.
5839 All other letters must be lowercase.
5840
5841 @item ^A^ARRAY_INDEXES^
5842 @emph{Use of array index numbers in array attributes.}
5843 When using the array attributes First, Last, Range,
5844 or Length, the index number must be omitted for one-dimensional arrays
5845 and is required for multi-dimensional arrays.
5846
5847 @item ^b^BLANKS^
5848 @emph{Blanks not allowed at statement end.}
5849 Trailing blanks are not allowed at the end of statements. The purpose of this
5850 rule, together with h (no horizontal tabs), is to enforce a canonical format
5851 for the use of blanks to separate source tokens.
5852
5853 @item ^c^COMMENTS^
5854 @emph{Check comments.}
5855 Comments must meet the following set of rules:
5856
5857 @itemize @bullet
5858
5859 @item
5860 The ``@code{--}'' that starts the column must either start in column one,
5861 or else at least one blank must precede this sequence.
5862
5863 @item
5864 Comments that follow other tokens on a line must have at least one blank
5865 following the ``@code{--}'' at the start of the comment.
5866
5867 @item
5868 Full line comments must have two blanks following the ``@code{--}'' that
5869 starts the comment, with the following exceptions.
5870
5871 @item
5872 A line consisting only of the ``@code{--}'' characters, possibly preceded
5873 by blanks is permitted.
5874
5875 @item
5876 A comment starting with ``@code{--x}'' where @code{x} is a special character
5877 is permitted.
5878 This allows proper processing of the output generated by specialized tools
5879 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5880 annotation
5881 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5882 special character is defined as being in one of the ASCII ranges
5883 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
5884 Note that this usage is not permitted
5885 in GNAT implementation units (i.e., when @option{-gnatg} is used).
5886
5887 @item
5888 A line consisting entirely of minus signs, possibly preceded by blanks, is
5889 permitted. This allows the construction of box comments where lines of minus
5890 signs are used to form the top and bottom of the box.
5891
5892 @item
5893 A comment that starts and ends with ``@code{--}'' is permitted as long as at
5894 least one blank follows the initial ``@code{--}''. Together with the preceding
5895 rule, this allows the construction of box comments, as shown in the following
5896 example:
5897 @smallexample
5898 ---------------------------
5899 -- This is a box comment --
5900 -- with two text lines.  --
5901 ---------------------------
5902 @end smallexample
5903 @end itemize
5904
5905 @item ^d^DOS_LINE_ENDINGS^
5906 @emph{Check no DOS line terminators present.}
5907 All lines must be terminated by a single ASCII.LF
5908 character (in particular the DOS line terminator sequence CR/LF is not
5909 allowed).
5910
5911 @item ^e^END^
5912 @emph{Check end/exit labels.}
5913 Optional labels on @code{end} statements ending subprograms and on
5914 @code{exit} statements exiting named loops, are required to be present.
5915
5916 @item ^f^VTABS^
5917 @emph{No form feeds or vertical tabs.}
5918 Neither form feeds nor vertical tab characters are permitted
5919 in the source text.
5920
5921 @item ^g^GNAT^
5922 @emph{GNAT style mode}
5923 The set of style check switches is set to match that used by the GNAT sources.
5924 This may be useful when developing code that is eventually intended to be
5925 incorporated into GNAT. For further details, see GNAT sources.
5926
5927 @item ^h^HTABS^
5928 @emph{No horizontal tabs.}
5929 Horizontal tab characters are not permitted in the source text.
5930 Together with the b (no blanks at end of line) check, this
5931 enforces a canonical form for the use of blanks to separate
5932 source tokens.
5933
5934 @item ^i^IF_THEN^
5935 @emph{Check if-then layout.}
5936 The keyword @code{then} must appear either on the same
5937 line as corresponding @code{if}, or on a line on its own, lined
5938 up under the @code{if} with at least one non-blank line in between
5939 containing all or part of the condition to be tested.
5940
5941 @item ^I^IN_MODE^
5942 @emph{check mode IN keywords}
5943 Mode @code{in} (the default mode) is not
5944 allowed to be given explicitly. @code{in out} is fine,
5945 but not @code{in} on its own.
5946
5947 @item ^k^KEYWORD^
5948 @emph{Check keyword casing.}
5949 All keywords must be in lower case (with the exception of keywords
5950 such as @code{digits} used as attribute names to which this check
5951 does not apply).
5952
5953 @item ^l^LAYOUT^
5954 @emph{Check layout.}
5955 Layout of statement and declaration constructs must follow the
5956 recommendations in the Ada Reference Manual, as indicated by the
5957 form of the syntax rules. For example an @code{else} keyword must
5958 be lined up with the corresponding @code{if} keyword.
5959
5960 There are two respects in which the style rule enforced by this check
5961 option are more liberal than those in the Ada Reference Manual. First
5962 in the case of record declarations, it is permissible to put the
5963 @code{record} keyword on the same line as the @code{type} keyword, and
5964 then the @code{end} in @code{end record} must line up under @code{type}.
5965 This is also permitted when the type declaration is split on two lines.
5966 For example, any of the following three layouts is acceptable:
5967
5968 @smallexample @c ada
5969 @cartouche
5970 type q is record
5971    a : integer;
5972    b : integer;
5973 end record;
5974
5975 type q is
5976    record
5977       a : integer;
5978       b : integer;
5979    end record;
5980
5981 type q is
5982    record
5983       a : integer;
5984       b : integer;
5985 end record;
5986
5987 @end cartouche
5988 @end smallexample
5989
5990 @noindent
5991 Second, in the case of a block statement, a permitted alternative
5992 is to put the block label on the same line as the @code{declare} or
5993 @code{begin} keyword, and then line the @code{end} keyword up under
5994 the block label. For example both the following are permitted:
5995
5996 @smallexample @c ada
5997 @cartouche
5998 Block : declare
5999    A : Integer := 3;
6000 begin
6001    Proc (A, A);
6002 end Block;
6003
6004 Block :
6005    declare
6006       A : Integer := 3;
6007    begin
6008       Proc (A, A);
6009    end Block;
6010 @end cartouche
6011 @end smallexample
6012
6013 @noindent
6014 The same alternative format is allowed for loops. For example, both of
6015 the following are permitted:
6016
6017 @smallexample @c ada
6018 @cartouche
6019 Clear : while J < 10 loop
6020    A (J) := 0;
6021 end loop Clear;
6022
6023 Clear :
6024    while J < 10 loop
6025       A (J) := 0;
6026    end loop Clear;
6027 @end cartouche
6028 @end smallexample
6029
6030 @item ^Lnnn^MAX_NESTING=nnn^
6031 @emph{Set maximum nesting level}
6032 The maximum level of nesting of constructs (including subprograms, loops,
6033 blocks, packages, and conditionals) may not exceed the given value
6034 @option{nnn}. A value of zero disconnects this style check.
6035
6036 @item ^m^LINE_LENGTH^
6037 @emph{Check maximum line length.}
6038 The length of source lines must not exceed 79 characters, including
6039 any trailing blanks. The value of 79 allows convenient display on an
6040 80 character wide device or window, allowing for possible special
6041 treatment of 80 character lines. Note that this count is of
6042 characters in the source text. This means that a tab character counts
6043 as one character in this count but a wide character sequence counts as
6044 a single character (however many bytes are needed in the encoding).
6045
6046 @item ^Mnnn^MAX_LENGTH=nnn^
6047 @emph{Set maximum line length.}
6048 The length of lines must not exceed the
6049 given value @option{nnn}. The maximum value that can be specified is 32767.
6050
6051 @item ^n^STANDARD_CASING^
6052 @emph{Check casing of entities in Standard.}
6053 Any identifier from Standard must be cased
6054 to match the presentation in the Ada Reference Manual (for example,
6055 @code{Integer} and @code{ASCII.NUL}).
6056
6057 @item ^N^NONE^
6058 @emph{Turn off all style checks}
6059 All style check options are turned off.
6060
6061 @item ^o^ORDERED_SUBPROGRAMS^
6062 @emph{Check order of subprogram bodies.}
6063 All subprogram bodies in a given scope
6064 (e.g.@: a package body) must be in alphabetical order. The ordering
6065 rule uses normal Ada rules for comparing strings, ignoring casing
6066 of letters, except that if there is a trailing numeric suffix, then
6067 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6068 before Junk10).
6069
6070 @item ^O^OVERRIDING_INDICATORS^
6071 @emph{Check that overriding subprograms are explicitly marked as such.}
6072 The declaration of a primitive operation of a type extension that overrides
6073 an inherited operation must carry an overriding indicator.
6074
6075 @item ^p^PRAGMA^
6076 @emph{Check pragma casing.}
6077 Pragma names must be written in mixed case, that is, the
6078 initial letter and any letter following an underscore must be uppercase.
6079 All other letters must be lowercase.
6080
6081 @item ^r^REFERENCES^
6082 @emph{Check references.}
6083 All identifier references must be cased in the same way as the
6084 corresponding declaration. No specific casing style is imposed on
6085 identifiers. The only requirement is for consistency of references
6086 with declarations.
6087
6088 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6089 @emph{Check no statements after THEN/ELSE.}
6090 No statements are allowed
6091 on the same line as a THEN or ELSE keyword following the
6092 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6093 and a special exception allows a pragma to appear after ELSE.
6094
6095 @item ^s^SPECS^
6096 @emph{Check separate specs.}
6097 Separate declarations (``specs'') are required for subprograms (a
6098 body is not allowed to serve as its own declaration). The only
6099 exception is that parameterless library level procedures are
6100 not required to have a separate declaration. This exception covers
6101 the most frequent form of main program procedures.
6102
6103 @item ^t^TOKEN^
6104 @emph{Check token spacing.}
6105 The following token spacing rules are enforced:
6106
6107 @itemize @bullet
6108
6109 @item
6110 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6111
6112 @item
6113 The token @code{=>} must be surrounded by spaces.
6114
6115 @item
6116 The token @code{<>} must be preceded by a space or a left parenthesis.
6117
6118 @item
6119 Binary operators other than @code{**} must be surrounded by spaces.
6120 There is no restriction on the layout of the @code{**} binary operator.
6121
6122 @item
6123 Colon must be surrounded by spaces.
6124
6125 @item
6126 Colon-equal (assignment, initialization) must be surrounded by spaces.
6127
6128 @item
6129 Comma must be the first non-blank character on the line, or be
6130 immediately preceded by a non-blank character, and must be followed
6131 by a space.
6132
6133 @item
6134 If the token preceding a left parenthesis ends with a letter or digit, then
6135 a space must separate the two tokens.
6136
6137 @item
6138 A right parenthesis must either be the first non-blank character on
6139 a line, or it must be preceded by a non-blank character.
6140
6141 @item
6142 A semicolon must not be preceded by a space, and must not be followed by
6143 a non-blank character.
6144
6145 @item
6146 A unary plus or minus may not be followed by a space.
6147
6148 @item
6149 A vertical bar must be surrounded by spaces.
6150 @end itemize
6151
6152 @item ^u^UNNECESSARY_BLANK_LINES^
6153 @emph{Check unnecessary blank lines.}
6154 Unnecessary blank lines are not allowed. A blank line is considered
6155 unnecessary if it appears at the end of the file, or if more than
6156 one blank line occurs in sequence.
6157
6158 @item ^x^XTRA_PARENS^
6159 @emph{Check extra parentheses.}
6160 Unnecessary extra level of parentheses (C-style) are not allowed
6161 around conditions in @code{if} statements, @code{while} statements and
6162 @code{exit} statements.
6163
6164 @item ^y^ALL_BUILTIN^
6165 @emph{Set all standard style check options}
6166 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6167 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6168 @option{-gnatyS}, @option{-gnatyLnnn},
6169 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6170
6171 @ifclear vms
6172 @item -
6173 @emph{Remove style check options}
6174 This causes any subsequent options in the string to act as canceling the
6175 corresponding style check option. To cancel maximum nesting level control,
6176 use @option{L} parameter witout any integer value after that, because any
6177 digit following @option{-} in the parameter string of the @option{-gnaty}
6178 option will be threated as canceling indentation check. The same is true
6179 for @option{M} parameter. @option{y} and @option{N} parameters are not
6180 allowed after @option{-}.
6181
6182 @item +
6183 This causes any subsequent options in the string to enable the corresponding
6184 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6185 if any.
6186 @end ifclear
6187
6188 @ifset vms
6189 @item NOxxx
6190 @emph{Removing style check options}
6191 If the name of a style check is preceded by @option{NO} then the corresponding
6192 style check is turned off. For example @option{NOCOMMENTS} turns off style
6193 checking for comments.
6194 @end ifset
6195 @end table
6196
6197 @noindent
6198 In the above rules, appearing in column one is always permitted, that is,
6199 counts as meeting either a requirement for a required preceding space,
6200 or as meeting a requirement for no preceding space.
6201
6202 Appearing at the end of a line is also always permitted, that is, counts
6203 as meeting either a requirement for a following space, or as meeting
6204 a requirement for no following space.
6205
6206 @noindent
6207 If any of these style rules is violated, a message is generated giving
6208 details on the violation. The initial characters of such messages are
6209 always ``@code{(style)}''. Note that these messages are treated as warning
6210 messages, so they normally do not prevent the generation of an object
6211 file. The @option{-gnatwe} switch can be used to treat warning messages,
6212 including style messages, as fatal errors.
6213
6214 The switch
6215 @ifclear vms
6216 @option{-gnaty} on its own (that is not
6217 followed by any letters or digits), then the effect is equivalent
6218 to the use of @option{-gnatyy}, as described above, that is all
6219 built-in standard style check options are enabled.
6220
6221 @end ifclear
6222 @ifset vms
6223 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6224 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6225 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6226 @end ifset
6227
6228
6229
6230 The switch
6231 @ifclear vms
6232 @option{-gnatyN}
6233 @end ifclear
6234 @ifset vms
6235 /STYLE_CHECKS=NONE
6236 @end ifset
6237 clears any previously set style checks.
6238
6239 @node Run-Time Checks
6240 @subsection Run-Time Checks
6241 @cindex Division by zero
6242 @cindex Access before elaboration
6243 @cindex Checks, division by zero
6244 @cindex Checks, access before elaboration
6245 @cindex Checks, stack overflow checking
6246
6247 @noindent
6248 By default, the following checks are suppressed: integer overflow
6249 checks, stack overflow checks, and checks for access before
6250 elaboration on subprogram calls. All other checks, including range
6251 checks and array bounds checks, are turned on by default. The
6252 following @command{gcc} switches refine this default behavior.
6253
6254 @table @option
6255 @c !sort!
6256 @item -gnatp
6257 @cindex @option{-gnatp} (@command{gcc})
6258 @cindex Suppressing checks
6259 @cindex Checks, suppressing
6260 @findex Suppress
6261 Suppress all run-time checks as though @code{pragma Suppress (All_checks)}
6262 had been present in the source. Validity checks are also suppressed (in
6263 other words @option{-gnatp} also implies @option{-gnatVn}.
6264 Use this switch to improve the performance
6265 of the code at the expense of safety in the presence of invalid data or
6266 program bugs.
6267
6268 Note that when checks are suppressed, the compiler is allowed, but not
6269 required, to omit the checking code. If the run-time cost of the
6270 checking code is zero or near-zero, the compiler will generate it even
6271 if checks are suppressed. In particular, if the compiler can prove
6272 that a certain check will necessarily fail, it will generate code to
6273 do an unconditional ``raise'', even if checks are suppressed. The
6274 compiler warns in this case.
6275
6276 Of course, run-time checks are omitted whenever the compiler can prove
6277 that they will not fail, whether or not checks are suppressed.
6278
6279 Note that if you suppress a check that would have failed, program
6280 execution is erroneous, which means the behavior is totally
6281 unpredictable. The program might crash, or print wrong answers, or
6282 do anything else. It might even do exactly what you wanted it to do
6283 (and then it might start failing mysteriously next week or next
6284 year). The compiler will generate code based on the assumption that
6285 the condition being checked is true, which can result in disaster if
6286 that assumption is wrong.
6287
6288 @item -gnato
6289 @cindex @option{-gnato} (@command{gcc})
6290 @cindex Overflow checks
6291 @cindex Check, overflow
6292 Enables overflow checking for integer operations.
6293 This causes GNAT to generate slower and larger executable
6294 programs by adding code to check for overflow (resulting in raising
6295 @code{Constraint_Error} as required by standard Ada
6296 semantics). These overflow checks correspond to situations in which
6297 the true value of the result of an operation may be outside the base
6298 range of the result type. The following example shows the distinction:
6299
6300 @smallexample @c ada
6301 X1 : Integer := "Integer'Last";
6302 X2 : Integer range 1 .. 5 := "5";
6303 X3 : Integer := "Integer'Last";
6304 X4 : Integer range 1 .. 5 := "5";
6305 F  : Float := "2.0E+20";
6306 @dots{}
6307 X1 := X1 + 1;
6308 X2 := X2 + 1;
6309 X3 := Integer (F);
6310 X4 := Integer (F);
6311 @end smallexample
6312
6313 @noindent
6314 Note that if explicit values are assigned at compile time, the
6315 compiler may be able to detect overflow at compile time, in which case
6316 no actual run-time checking code is required, and Constraint_Error
6317 will be raised unconditionally, with or without
6318 @option{-gnato}. That's why the assigned values in the above fragment
6319 are in quotes, the meaning is "assign a value not known to the
6320 compiler that happens to be equal to ...". The remaining discussion
6321 assumes that the compiler cannot detect the values at compile time.
6322
6323 Here the first addition results in a value that is outside the base range
6324 of Integer, and hence requires an overflow check for detection of the
6325 constraint error. Thus the first assignment to @code{X1} raises a
6326 @code{Constraint_Error} exception only if @option{-gnato} is set.
6327
6328 The second increment operation results in a violation of the explicit
6329 range constraint; such range checks are performed by default, and are
6330 unaffected by @option{-gnato}.
6331
6332 The two conversions of @code{F} both result in values that are outside
6333 the base range of type @code{Integer} and thus will raise
6334 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6335 The fact that the result of the second conversion is assigned to
6336 variable @code{X4} with a restricted range is irrelevant, since the problem
6337 is in the conversion, not the assignment.
6338
6339 Basically the rule is that in the default mode (@option{-gnato} not
6340 used), the generated code assures that all integer variables stay
6341 within their declared ranges, or within the base range if there is
6342 no declared range. This prevents any serious problems like indexes
6343 out of range for array operations.
6344
6345 What is not checked in default mode is an overflow that results in
6346 an in-range, but incorrect value. In the above example, the assignments
6347 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6348 range of the target variable, but the result is wrong in the sense that
6349 it is too large to be represented correctly. Typically the assignment
6350 to @code{X1} will result in wrap around to the largest negative number.
6351 The conversions of @code{F} will result in some @code{Integer} value
6352 and if that integer value is out of the @code{X4} range then the
6353 subsequent assignment would generate an exception.
6354
6355 @findex Machine_Overflows
6356 Note that the @option{-gnato} switch does not affect the code generated
6357 for any floating-point operations; it applies only to integer
6358 semantics).
6359 For floating-point, GNAT has the @code{Machine_Overflows}
6360 attribute set to @code{False} and the normal mode of operation is to
6361 generate IEEE NaN and infinite values on overflow or invalid operations
6362 (such as dividing 0.0 by 0.0).
6363
6364 The reason that we distinguish overflow checking from other kinds of
6365 range constraint checking is that a failure of an overflow check, unlike
6366 for example the failure of a range check, can result in an incorrect
6367 value, but cannot cause random memory destruction (like an out of range
6368 subscript), or a wild jump (from an out of range case value). Overflow
6369 checking is also quite expensive in time and space, since in general it
6370 requires the use of double length arithmetic.
6371
6372 Note again that @option{-gnato} is off by default, so overflow checking is
6373 not performed in default mode. This means that out of the box, with the
6374 default settings, GNAT does not do all the checks expected from the
6375 language description in the Ada Reference Manual. If you want all constraint
6376 checks to be performed, as described in this Manual, then you must
6377 explicitly use the -gnato switch either on the @command{gnatmake} or
6378 @command{gcc} command.
6379
6380 @item -gnatE
6381 @cindex @option{-gnatE} (@command{gcc})
6382 @cindex Elaboration checks
6383 @cindex Check, elaboration
6384 Enables dynamic checks for access-before-elaboration
6385 on subprogram calls and generic instantiations.
6386 Note that @option{-gnatE} is not necessary for safety, because in the
6387 default mode, GNAT ensures statically that the checks would not fail.
6388 For full details of the effect and use of this switch,
6389 @xref{Compiling Using gcc}.
6390
6391 @item -fstack-check
6392 @cindex @option{-fstack-check} (@command{gcc})
6393 @cindex Stack Overflow Checking
6394 @cindex Checks, stack overflow checking
6395 Activates stack overflow checking. For full details of the effect and use of
6396 this switch see @ref{Stack Overflow Checking}.
6397 @end table
6398
6399 @findex Unsuppress
6400 @noindent
6401 The setting of these switches only controls the default setting of the
6402 checks. You may modify them using either @code{Suppress} (to remove
6403 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6404 the program source.
6405
6406 @node Using gcc for Syntax Checking
6407 @subsection Using @command{gcc} for Syntax Checking
6408 @table @option
6409 @item -gnats
6410 @cindex @option{-gnats} (@command{gcc})
6411 @ifclear vms
6412
6413 @noindent
6414 The @code{s} stands for ``syntax''.
6415 @end ifclear
6416
6417 Run GNAT in syntax checking only mode. For
6418 example, the command
6419
6420 @smallexample
6421 $ gcc -c -gnats x.adb
6422 @end smallexample
6423
6424 @noindent
6425 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6426 series of files in a single command
6427 @ifclear vms
6428 , and can use wild cards to specify such a group of files.
6429 Note that you must specify the @option{-c} (compile
6430 only) flag in addition to the @option{-gnats} flag.
6431 @end ifclear
6432 .
6433 You may use other switches in conjunction with @option{-gnats}. In
6434 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6435 format of any generated error messages.
6436
6437 When the source file is empty or contains only empty lines and/or comments,
6438 the output is a warning:
6439
6440 @smallexample
6441 $ gcc -c -gnats -x ada toto.txt
6442 toto.txt:1:01: warning: empty file, contains no compilation units
6443 $
6444 @end smallexample
6445
6446 Otherwise, the output is simply the error messages, if any. No object file or
6447 ALI file is generated by a syntax-only compilation. Also, no units other
6448 than the one specified are accessed. For example, if a unit @code{X}
6449 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6450 check only mode does not access the source file containing unit
6451 @code{Y}.
6452
6453 @cindex Multiple units, syntax checking
6454 Normally, GNAT allows only a single unit in a source file. However, this
6455 restriction does not apply in syntax-check-only mode, and it is possible
6456 to check a file containing multiple compilation units concatenated
6457 together. This is primarily used by the @code{gnatchop} utility
6458 (@pxref{Renaming Files Using gnatchop}).
6459 @end table
6460
6461 @node Using gcc for Semantic Checking
6462 @subsection Using @command{gcc} for Semantic Checking
6463 @table @option
6464 @item -gnatc
6465 @cindex @option{-gnatc} (@command{gcc})
6466
6467 @ifclear vms
6468 @noindent
6469 The @code{c} stands for ``check''.
6470 @end ifclear
6471 Causes the compiler to operate in semantic check mode,
6472 with full checking for all illegalities specified in the
6473 Ada Reference Manual, but without generation of any object code
6474 (no object file is generated).
6475
6476 Because dependent files must be accessed, you must follow the GNAT
6477 semantic restrictions on file structuring to operate in this mode:
6478
6479 @itemize @bullet
6480 @item
6481 The needed source files must be accessible
6482 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6483
6484 @item
6485 Each file must contain only one compilation unit.
6486
6487 @item
6488 The file name and unit name must match (@pxref{File Naming Rules}).
6489 @end itemize
6490
6491 The output consists of error messages as appropriate. No object file is
6492 generated. An @file{ALI} file is generated for use in the context of
6493 cross-reference tools, but this file is marked as not being suitable
6494 for binding (since no object file is generated).
6495 The checking corresponds exactly to the notion of
6496 legality in the Ada Reference Manual.
6497
6498 Any unit can be compiled in semantics-checking-only mode, including
6499 units that would not normally be compiled (subunits,
6500 and specifications where a separate body is present).
6501 @end table
6502
6503 @node Compiling Different Versions of Ada
6504 @subsection Compiling Different Versions of Ada
6505
6506 @noindent
6507 The switches described in this section allow you to explicitly specify
6508 the version of the Ada language that your programs are written in.
6509 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6510 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6511 indicate Ada 83 compatibility mode.
6512
6513 @table @option
6514 @cindex Compatibility with Ada 83
6515
6516 @item -gnat83 (Ada 83 Compatibility Mode)
6517 @cindex @option{-gnat83} (@command{gcc})
6518 @cindex ACVC, Ada 83 tests
6519 @cindex Ada 83 mode
6520
6521 @noindent
6522 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6523 specifies that the program is to be compiled in Ada 83 mode. With
6524 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6525 semantics where this can be done easily.
6526 It is not possible to guarantee this switch does a perfect
6527 job; some subtle tests, such as are
6528 found in earlier ACVC tests (and that have been removed from the ACATS suite
6529 for Ada 95), might not compile correctly.
6530 Nevertheless, this switch may be useful in some circumstances, for example
6531 where, due to contractual reasons, existing code needs to be maintained
6532 using only Ada 83 features.
6533
6534 With few exceptions (most notably the need to use @code{<>} on
6535 @cindex Generic formal parameters
6536 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6537 reserved words, and the use of packages
6538 with optional bodies), it is not necessary to specify the
6539 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6540 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6541 a correct Ada 83 program is usually also a correct program
6542 in these later versions of the language standard.
6543 For further information, please refer to @ref{Compatibility and Porting Guide}.
6544
6545 @item -gnat95 (Ada 95 mode)
6546 @cindex @option{-gnat95} (@command{gcc})
6547 @cindex Ada 95 mode
6548
6549 @noindent
6550 This switch directs the compiler to implement the Ada 95 version of the
6551 language.
6552 Since Ada 95 is almost completely upwards
6553 compatible with Ada 83, Ada 83 programs may generally be compiled using
6554 this switch (see the description of the @option{-gnat83} switch for further
6555 information about Ada 83 mode).
6556 If an Ada 2005 program is compiled in Ada 95 mode,
6557 uses of the new Ada 2005 features will cause error
6558 messages or warnings.
6559
6560 This switch also can be used to cancel the effect of a previous
6561 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6562
6563 @item -gnat05 (Ada 2005 mode)
6564 @cindex @option{-gnat05} (@command{gcc})
6565 @cindex Ada 2005 mode
6566
6567 @noindent
6568 This switch directs the compiler to implement the Ada 2005 version of the
6569 language.
6570 Since Ada 2005 is almost completely upwards
6571 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6572 may generally be compiled using this switch (see the description of the
6573 @option{-gnat83} and @option{-gnat95} switches for further
6574 information).
6575
6576 For information about the approved ``Ada Issues'' that have been incorporated
6577 into Ada 2005, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6578 Included with GNAT releases is a file @file{features-ada0y} that describes
6579 the set of implemented Ada 2005 features.
6580 @end table
6581
6582
6583 @node Character Set Control
6584 @subsection Character Set Control
6585 @table @option
6586 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6587 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6588
6589 @noindent
6590 Normally GNAT recognizes the Latin-1 character set in source program
6591 identifiers, as described in the Ada Reference Manual.
6592 This switch causes
6593 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6594 single character ^^or word^ indicating the character set, as follows:
6595
6596 @table @code
6597 @item 1
6598 ISO 8859-1 (Latin-1) identifiers
6599
6600 @item 2
6601 ISO 8859-2 (Latin-2) letters allowed in identifiers
6602
6603 @item 3
6604 ISO 8859-3 (Latin-3) letters allowed in identifiers
6605
6606 @item 4
6607 ISO 8859-4 (Latin-4) letters allowed in identifiers
6608
6609 @item 5
6610 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6611
6612 @item 9
6613 ISO 8859-15 (Latin-9) letters allowed in identifiers
6614
6615 @item ^p^PC^
6616 IBM PC letters (code page 437) allowed in identifiers
6617
6618 @item ^8^PC850^
6619 IBM PC letters (code page 850) allowed in identifiers
6620
6621 @item ^f^FULL_UPPER^
6622 Full upper-half codes allowed in identifiers
6623
6624 @item ^n^NO_UPPER^
6625 No upper-half codes allowed in identifiers
6626
6627 @item ^w^WIDE^
6628 Wide-character codes (that is, codes greater than 255)
6629 allowed in identifiers
6630 @end table
6631
6632 @xref{Foreign Language Representation}, for full details on the
6633 implementation of these character sets.
6634
6635 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6636 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6637 Specify the method of encoding for wide characters.
6638 @var{e} is one of the following:
6639
6640 @table @code
6641
6642 @item ^h^HEX^
6643 Hex encoding (brackets coding also recognized)
6644
6645 @item ^u^UPPER^
6646 Upper half encoding (brackets encoding also recognized)
6647
6648 @item ^s^SHIFT_JIS^
6649 Shift/JIS encoding (brackets encoding also recognized)
6650
6651 @item ^e^EUC^
6652 EUC encoding (brackets encoding also recognized)
6653
6654 @item ^8^UTF8^
6655 UTF-8 encoding (brackets encoding also recognized)
6656
6657 @item ^b^BRACKETS^
6658 Brackets encoding only (default value)
6659 @end table
6660 For full details on these encoding
6661 methods see @ref{Wide Character Encodings}.
6662 Note that brackets coding is always accepted, even if one of the other
6663 options is specified, so for example @option{-gnatW8} specifies that both
6664 brackets and UTF-8 encodings will be recognized. The units that are
6665 with'ed directly or indirectly will be scanned using the specified
6666 representation scheme, and so if one of the non-brackets scheme is
6667 used, it must be used consistently throughout the program. However,
6668 since brackets encoding is always recognized, it may be conveniently
6669 used in standard libraries, allowing these libraries to be used with
6670 any of the available coding schemes.
6671 scheme.
6672
6673 If no @option{-gnatW?} parameter is present, then the default
6674 representation is normally Brackets encoding only. However, if the
6675 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6676 byte order mark or BOM for UTF-8), then these three characters are
6677 skipped and the default representation for the file is set to UTF-8.
6678
6679 Note that the wide character representation that is specified (explicitly
6680 or by default) for the main program also acts as the default encoding used
6681 for Wide_Text_IO files if not specifically overridden by a WCEM form
6682 parameter.
6683
6684 @end table
6685 @node File Naming Control
6686 @subsection File Naming Control
6687
6688 @table @option
6689 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6690 @cindex @option{-gnatk} (@command{gcc})
6691 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6692 1-999, indicates the maximum allowable length of a file name (not
6693 including the @file{.ads} or @file{.adb} extension). The default is not
6694 to enable file name krunching.
6695
6696 For the source file naming rules, @xref{File Naming Rules}.
6697 @end table
6698
6699 @node Subprogram Inlining Control
6700 @subsection Subprogram Inlining Control
6701
6702 @table @option
6703 @c !sort!
6704 @item -gnatn
6705 @cindex @option{-gnatn} (@command{gcc})
6706 @ifclear vms
6707 The @code{n} here is intended to suggest the first syllable of the
6708 word ``inline''.
6709 @end ifclear
6710 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6711 inlining to actually occur, optimization must be enabled. To enable
6712 inlining of subprograms specified by pragma @code{Inline},
6713 you must also specify this switch.
6714 In the absence of this switch, GNAT does not attempt
6715 inlining and does not need to access the bodies of
6716 subprograms for which @code{pragma Inline} is specified if they are not
6717 in the current unit.
6718
6719 If you specify this switch the compiler will access these bodies,
6720 creating an extra source dependency for the resulting object file, and
6721 where possible, the call will be inlined.
6722 For further details on when inlining is possible
6723 see @ref{Inlining of Subprograms}.
6724
6725 @item -gnatN
6726 @cindex @option{-gnatN} (@command{gcc})
6727 This switch activates front-end inlining which also
6728 generates additional dependencies.
6729
6730 When using a gcc-based back end (in practice this means using any version
6731 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
6732 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
6733 Historically front end inlining was more extensive than the gcc back end
6734 inlining, but that is no longer the case.
6735 @end table
6736
6737 @node Auxiliary Output Control
6738 @subsection Auxiliary Output Control
6739
6740 @table @option
6741 @item -gnatt
6742 @cindex @option{-gnatt} (@command{gcc})
6743 @cindex Writing internal trees
6744 @cindex Internal trees, writing to file
6745 Causes GNAT to write the internal tree for a unit to a file (with the
6746 extension @file{.adt}.
6747 This not normally required, but is used by separate analysis tools.
6748 Typically
6749 these tools do the necessary compilations automatically, so you should
6750 not have to specify this switch in normal operation.
6751
6752 @item -gnatu
6753 @cindex @option{-gnatu} (@command{gcc})
6754 Print a list of units required by this compilation on @file{stdout}.
6755 The listing includes all units on which the unit being compiled depends
6756 either directly or indirectly.
6757
6758 @ifclear vms
6759 @item -pass-exit-codes
6760 @cindex @option{-pass-exit-codes} (@command{gcc})
6761 If this switch is not used, the exit code returned by @command{gcc} when
6762 compiling multiple files indicates whether all source files have
6763 been successfully used to generate object files or not.
6764
6765 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
6766 exit status and allows an integrated development environment to better
6767 react to a compilation failure. Those exit status are:
6768
6769 @table @asis
6770 @item 5
6771 There was an error in at least one source file.
6772 @item 3
6773 At least one source file did not generate an object file.
6774 @item 2
6775 The compiler died unexpectedly (internal error for example).
6776 @item 0
6777 An object file has been generated for every source file.
6778 @end table
6779 @end ifclear
6780 @end table
6781
6782 @node Debugging Control
6783 @subsection Debugging Control
6784
6785 @table @option
6786 @c !sort!
6787 @cindex Debugging options
6788 @ifclear vms
6789 @item -gnatd@var{x}
6790 @cindex @option{-gnatd} (@command{gcc})
6791 Activate internal debugging switches. @var{x} is a letter or digit, or
6792 string of letters or digits, which specifies the type of debugging
6793 outputs desired. Normally these are used only for internal development
6794 or system debugging purposes. You can find full documentation for these
6795 switches in the body of the @code{Debug} unit in the compiler source
6796 file @file{debug.adb}.
6797 @end ifclear
6798
6799 @item -gnatG[=nn]
6800 @cindex @option{-gnatG} (@command{gcc})
6801 This switch causes the compiler to generate auxiliary output containing
6802 a pseudo-source listing of the generated expanded code. Like most Ada
6803 compilers, GNAT works by first transforming the high level Ada code into
6804 lower level constructs. For example, tasking operations are transformed
6805 into calls to the tasking run-time routines. A unique capability of GNAT
6806 is to list this expanded code in a form very close to normal Ada source.
6807 This is very useful in understanding the implications of various Ada
6808 usage on the efficiency of the generated code. There are many cases in
6809 Ada (e.g.@: the use of controlled types), where simple Ada statements can
6810 generate a lot of run-time code. By using @option{-gnatG} you can identify
6811 these cases, and consider whether it may be desirable to modify the coding
6812 approach to improve efficiency.
6813
6814 The optional parameter @code{nn} if present after -gnatG specifies an
6815 alternative maximum line length that overrides the normal default of 72.
6816 This value is in the range 40-999999, values less than 40 being silently
6817 reset to 40. The equal sign is optional.
6818
6819 The format of the output is very similar to standard Ada source, and is
6820 easily understood by an Ada programmer. The following special syntactic
6821 additions correspond to low level features used in the generated code that
6822 do not have any exact analogies in pure Ada source form. The following
6823 is a partial list of these special constructions. See the spec
6824 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6825
6826 If the switch @option{-gnatL} is used in conjunction with
6827 @cindex @option{-gnatL} (@command{gcc})
6828 @option{-gnatG}, then the original source lines are interspersed
6829 in the expanded source (as comment lines with the original line number).
6830
6831 @table @code
6832 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
6833 Shows the storage pool being used for an allocator.
6834
6835 @item at end @var{procedure-name};
6836 Shows the finalization (cleanup) procedure for a scope.
6837
6838 @item (if @var{expr} then @var{expr} else @var{expr})
6839 Conditional expression equivalent to the @code{x?y:z} construction in C.
6840
6841 @item @var{target}^^^(@var{source})
6842 A conversion with floating-point truncation instead of rounding.
6843
6844 @item @var{target}?(@var{source})
6845 A conversion that bypasses normal Ada semantic checking. In particular
6846 enumeration types and fixed-point types are treated simply as integers.
6847
6848 @item @var{target}?^^^(@var{source})
6849 Combines the above two cases.
6850
6851 @item @var{x} #/ @var{y}
6852 @itemx @var{x} #mod @var{y}
6853 @itemx @var{x} #* @var{y}
6854 @itemx @var{x} #rem @var{y}
6855 A division or multiplication of fixed-point values which are treated as
6856 integers without any kind of scaling.
6857
6858 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
6859 Shows the storage pool associated with a @code{free} statement.
6860
6861 @item [subtype or type declaration]
6862 Used to list an equivalent declaration for an internally generated
6863 type that is referenced elsewhere in the listing.
6864
6865 @item freeze @var{type-name} @ovar{actions}
6866 Shows the point at which @var{type-name} is frozen, with possible
6867 associated actions to be performed at the freeze point.
6868
6869 @item reference @var{itype}
6870 Reference (and hence definition) to internal type @var{itype}.
6871
6872 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6873 Intrinsic function call.
6874
6875 @item @var{label-name} : label
6876 Declaration of label @var{labelname}.
6877
6878 @item #$ @var{subprogram-name}
6879 An implicit call to a run-time support routine
6880 (to meet the requirement of H.3.1(9) in a
6881 convenient manner).
6882
6883 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
6884 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6885 @var{expr}, but handled more efficiently).
6886
6887 @item [constraint_error]
6888 Raise the @code{Constraint_Error} exception.
6889
6890 @item @var{expression}'reference
6891 A pointer to the result of evaluating @var{expression}.
6892
6893 @item @var{target-type}!(@var{source-expression})
6894 An unchecked conversion of @var{source-expression} to @var{target-type}.
6895
6896 @item [@var{numerator}/@var{denominator}]
6897 Used to represent internal real literals (that) have no exact
6898 representation in base 2-16 (for example, the result of compile time
6899 evaluation of the expression 1.0/27.0).
6900 @end table
6901
6902 @item -gnatD[=nn]
6903 @cindex @option{-gnatD} (@command{gcc})
6904 When used in conjunction with @option{-gnatG}, this switch causes
6905 the expanded source, as described above for
6906 @option{-gnatG} to be written to files with names
6907 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6908 instead of to the standard output file. For
6909 example, if the source file name is @file{hello.adb}, then a file
6910 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
6911 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
6912 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6913 you to do source level debugging using the generated code which is
6914 sometimes useful for complex code, for example to find out exactly
6915 which part of a complex construction raised an exception. This switch
6916 also suppress generation of cross-reference information (see
6917 @option{-gnatx}) since otherwise the cross-reference information
6918 would refer to the @file{^.dg^.DG^} file, which would cause
6919 confusion since this is not the original source file.
6920
6921 Note that @option{-gnatD} actually implies @option{-gnatG}
6922 automatically, so it is not necessary to give both options.
6923 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6924
6925 If the switch @option{-gnatL} is used in conjunction with
6926 @cindex @option{-gnatL} (@command{gcc})
6927 @option{-gnatDG}, then the original source lines are interspersed
6928 in the expanded source (as comment lines with the original line number).
6929
6930 The optional parameter @code{nn} if present after -gnatD specifies an
6931 alternative maximum line length that overrides the normal default of 72.
6932 This value is in the range 40-999999, values less than 40 being silently
6933 reset to 40. The equal sign is optional.
6934
6935 @item -gnatr
6936 @cindex @option{-gnatr} (@command{gcc})
6937 @cindex pragma Restrictions
6938 This switch causes pragma Restrictions to be treated as Restriction_Warnings
6939 so that violation of restrictions causes warnings rather than illegalities.
6940 This is useful during the development process when new restrictions are added
6941 or investigated. The switch also causes pragma Profile to be treated as
6942 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
6943 restriction warnings rather than restrictions.
6944
6945 @ifclear vms
6946 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
6947 @cindex @option{-gnatR} (@command{gcc})
6948 This switch controls output from the compiler of a listing showing
6949 representation information for declared types and objects. For
6950 @option{-gnatR0}, no information is output (equivalent to omitting
6951 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6952 so @option{-gnatR} with no parameter has the same effect), size and alignment
6953 information is listed for declared array and record types. For
6954 @option{-gnatR2}, size and alignment information is listed for all
6955 declared types and objects. Finally @option{-gnatR3} includes symbolic
6956 expressions for values that are computed at run time for
6957 variant records. These symbolic expressions have a mostly obvious
6958 format with #n being used to represent the value of the n'th
6959 discriminant. See source files @file{repinfo.ads/adb} in the
6960 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6961 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
6962 the output is to a file with the name @file{^file.rep^file_REP^} where
6963 file is the name of the corresponding source file.
6964 @end ifclear
6965 @ifset vms
6966 @item /REPRESENTATION_INFO
6967 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
6968 This qualifier controls output from the compiler of a listing showing
6969 representation information for declared types and objects. For
6970 @option{/REPRESENTATION_INFO=NONE}, no information is output
6971 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6972 @option{/REPRESENTATION_INFO} without option is equivalent to
6973 @option{/REPRESENTATION_INFO=ARRAYS}.
6974 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6975 information is listed for declared array and record types. For
6976 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6977 is listed for all expression information for values that are computed
6978 at run time for variant records. These symbolic expressions have a mostly
6979 obvious format with #n being used to represent the value of the n'th
6980 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6981 @code{GNAT} sources for full details on the format of
6982 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6983 If _FILE is added at the end of an option
6984 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6985 then the output is to a file with the name @file{file_REP} where
6986 file is the name of the corresponding source file.
6987 @end ifset
6988 Note that it is possible for record components to have zero size. In
6989 this case, the component clause uses an obvious extension of permitted
6990 Ada syntax, for example @code{at 0 range 0 .. -1}.
6991
6992 Representation information requires that code be generated (since it is the
6993 code generator that lays out complex data structures). If an attempt is made
6994 to output representation information when no code is generated, for example
6995 when a subunit is compiled on its own, then no information can be generated
6996 and the compiler outputs a message to this effect.
6997
6998 @item -gnatS
6999 @cindex @option{-gnatS} (@command{gcc})
7000 The use of the switch @option{-gnatS} for an
7001 Ada compilation will cause the compiler to output a
7002 representation of package Standard in a form very
7003 close to standard Ada. It is not quite possible to
7004 do this entirely in standard Ada (since new
7005 numeric base types cannot be created in standard
7006 Ada), but the output is easily
7007 readable to any Ada programmer, and is useful to
7008 determine the characteristics of target dependent
7009 types in package Standard.
7010
7011 @item -gnatx
7012 @cindex @option{-gnatx} (@command{gcc})
7013 Normally the compiler generates full cross-referencing information in
7014 the @file{ALI} file. This information is used by a number of tools,
7015 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7016 suppresses this information. This saves some space and may slightly
7017 speed up compilation, but means that these tools cannot be used.
7018 @end table
7019
7020 @node Exception Handling Control
7021 @subsection Exception Handling Control
7022
7023 @noindent
7024 GNAT uses two methods for handling exceptions at run-time. The
7025 @code{setjmp/longjmp} method saves the context when entering
7026 a frame with an exception handler. Then when an exception is
7027 raised, the context can be restored immediately, without the
7028 need for tracing stack frames. This method provides very fast
7029 exception propagation, but introduces significant overhead for
7030 the use of exception handlers, even if no exception is raised.
7031
7032 The other approach is called ``zero cost'' exception handling.
7033 With this method, the compiler builds static tables to describe
7034 the exception ranges. No dynamic code is required when entering
7035 a frame containing an exception handler. When an exception is
7036 raised, the tables are used to control a back trace of the
7037 subprogram invocation stack to locate the required exception
7038 handler. This method has considerably poorer performance for
7039 the propagation of exceptions, but there is no overhead for
7040 exception handlers if no exception is raised. Note that in this
7041 mode and in the context of mixed Ada and C/C++ programming,
7042 to propagate an exception through a C/C++ code, the C/C++ code
7043 must be compiled with the @option{-funwind-tables} GCC's
7044 option.
7045
7046 The following switches may be used to control which of the
7047 two exception handling methods is used.
7048
7049 @table @option
7050 @c !sort!
7051
7052 @item --RTS=sjlj
7053 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7054 This switch causes the setjmp/longjmp run-time (when available) to be used
7055 for exception handling. If the default
7056 mechanism for the target is zero cost exceptions, then
7057 this switch can be used to modify this default, and must be
7058 used for all units in the partition.
7059 This option is rarely used. One case in which it may be
7060 advantageous is if you have an application where exception
7061 raising is common and the overall performance of the
7062 application is improved by favoring exception propagation.
7063
7064 @item --RTS=zcx
7065 @cindex @option{--RTS=zcx} (@command{gnatmake})
7066 @cindex Zero Cost Exceptions
7067 This switch causes the zero cost approach to be used
7068 for exception handling. If this is the default mechanism for the
7069 target (see below), then this switch is unneeded. If the default
7070 mechanism for the target is setjmp/longjmp exceptions, then
7071 this switch can be used to modify this default, and must be
7072 used for all units in the partition.
7073 This option can only be used if the zero cost approach
7074 is available for the target in use, otherwise it will generate an error.
7075 @end table
7076
7077 @noindent
7078 The same option @option{--RTS} must be used both for @command{gcc}
7079 and @command{gnatbind}. Passing this option to @command{gnatmake}
7080 (@pxref{Switches for gnatmake}) will ensure the required consistency
7081 through the compilation and binding steps.
7082
7083 @node Units to Sources Mapping Files
7084 @subsection Units to Sources Mapping Files
7085
7086 @table @option
7087
7088 @item -gnatem^^=^@var{path}
7089 @cindex @option{-gnatem} (@command{gcc})
7090 A mapping file is a way to communicate to the compiler two mappings:
7091 from unit names to file names (without any directory information) and from
7092 file names to path names (with full directory information). These mappings
7093 are used by the compiler to short-circuit the path search.
7094
7095 The use of mapping files is not required for correct operation of the
7096 compiler, but mapping files can improve efficiency, particularly when
7097 sources are read over a slow network connection. In normal operation,
7098 you need not be concerned with the format or use of mapping files,
7099 and the @option{-gnatem} switch is not a switch that you would use
7100 explicitly. it is intended only for use by automatic tools such as
7101 @command{gnatmake} running under the project file facility. The
7102 description here of the format of mapping files is provided
7103 for completeness and for possible use by other tools.
7104
7105 A mapping file is a sequence of sets of three lines. In each set,
7106 the first line is the unit name, in lower case, with ``@code{%s}''
7107 appended for
7108 specs and ``@code{%b}'' appended for bodies; the second line is the
7109 file name; and the third line is the path name.
7110
7111 Example:
7112 @smallexample
7113    main%b
7114    main.2.ada
7115    /gnat/project1/sources/main.2.ada
7116 @end smallexample
7117
7118 When the switch @option{-gnatem} is specified, the compiler will create
7119 in memory the two mappings from the specified file. If there is any problem
7120 (nonexistent file, truncated file or duplicate entries), no mapping will
7121 be created.
7122
7123 Several @option{-gnatem} switches may be specified; however, only the last
7124 one on the command line will be taken into account.
7125
7126 When using a project file, @command{gnatmake} create a temporary mapping file
7127 and communicates it to the compiler using this switch.
7128
7129 @end table
7130
7131 @node Integrated Preprocessing
7132 @subsection Integrated Preprocessing
7133
7134 @noindent
7135 GNAT sources may be preprocessed immediately before compilation.
7136 In this case, the actual
7137 text of the source is not the text of the source file, but is derived from it
7138 through a process called preprocessing. Integrated preprocessing is specified
7139 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7140 indicates, through a text file, the preprocessing data to be used.
7141 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7142
7143 @noindent
7144 Note that when integrated preprocessing is used, the output from the
7145 preprocessor is not written to any external file. Instead it is passed
7146 internally to the compiler. If you need to preserve the result of
7147 preprocessing in a file, then you should use @command{gnatprep}
7148 to perform the desired preprocessing in stand-alone mode.
7149
7150 @noindent
7151 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7152 used when Integrated Preprocessing is used. The reason is that preprocessing
7153 with another Preprocessing Data file without changing the sources will
7154 not trigger recompilation without this switch.
7155
7156 @noindent
7157 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7158 always trigger recompilation for sources that are preprocessed,
7159 because @command{gnatmake} cannot compute the checksum of the source after
7160 preprocessing.
7161
7162 @noindent
7163 The actual preprocessing function is described in details in section
7164 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7165 preprocessing is triggered and parameterized.
7166
7167 @table @code
7168
7169 @item -gnatep=@var{file}
7170 @cindex @option{-gnatep} (@command{gcc})
7171 This switch indicates to the compiler the file name (without directory
7172 information) of the preprocessor data file to use. The preprocessor data file
7173 should be found in the source directories.
7174
7175 @noindent
7176 A preprocessing data file is a text file with significant lines indicating
7177 how should be preprocessed either a specific source or all sources not
7178 mentioned in other lines. A significant line is a nonempty, non-comment line.
7179 Comments are similar to Ada comments.
7180
7181 @noindent
7182 Each significant line starts with either a literal string or the character '*'.
7183 A literal string is the file name (without directory information) of the source
7184 to preprocess. A character '*' indicates the preprocessing for all the sources
7185 that are not specified explicitly on other lines (order of the lines is not
7186 significant). It is an error to have two lines with the same file name or two
7187 lines starting with the character '*'.
7188
7189 @noindent
7190 After the file name or the character '*', another optional literal string
7191 indicating the file name of the definition file to be used for preprocessing
7192 (@pxref{Form of Definitions File}). The definition files are found by the
7193 compiler in one of the source directories. In some cases, when compiling
7194 a source in a directory other than the current directory, if the definition
7195 file is in the current directory, it may be necessary to add the current
7196 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7197 the compiler would not find the definition file.
7198
7199 @noindent
7200 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7201 be found. Those ^switches^switches^ are:
7202
7203 @table @code
7204
7205 @item -b
7206 Causes both preprocessor lines and the lines deleted by
7207 preprocessing to be replaced by blank lines, preserving the line number.
7208 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7209 it cancels the effect of @option{-c}.
7210
7211 @item -c
7212 Causes both preprocessor lines and the lines deleted
7213 by preprocessing to be retained as comments marked
7214 with the special string ``@code{--! }''.
7215
7216 @item -Dsymbol=value
7217 Define or redefine a symbol, associated with value. A symbol is an Ada
7218 identifier, or an Ada reserved word, with the exception of @code{if},
7219 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7220 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7221 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7222 same name defined in a definition file.
7223
7224 @item -s
7225 Causes a sorted list of symbol names and values to be
7226 listed on the standard output file.
7227
7228 @item -u
7229 Causes undefined symbols to be treated as having the value @code{FALSE}
7230 in the context
7231 of a preprocessor test. In the absence of this option, an undefined symbol in
7232 a @code{#if} or @code{#elsif} test will be treated as an error.
7233
7234 @end table
7235
7236 @noindent
7237 Examples of valid lines in a preprocessor data file:
7238
7239 @smallexample
7240   "toto.adb"  "prep.def" -u
7241   --  preprocess "toto.adb", using definition file "prep.def",
7242   --  undefined symbol are False.
7243
7244   * -c -DVERSION=V101
7245   --  preprocess all other sources without a definition file;
7246   --  suppressed lined are commented; symbol VERSION has the value V101.
7247
7248   "titi.adb" "prep2.def" -s
7249   --  preprocess "titi.adb", using definition file "prep2.def";
7250   --  list all symbols with their values.
7251 @end smallexample
7252
7253 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7254 @cindex @option{-gnateD} (@command{gcc})
7255 Define or redefine a preprocessing symbol, associated with value. If no value
7256 is given on the command line, then the value of the symbol is @code{True}.
7257 A symbol is an identifier, following normal Ada (case-insensitive)
7258 rules for its syntax, and value is any sequence (including an empty sequence)
7259 of characters from the set (letters, digits, period, underline).
7260 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7261 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7262
7263 @noindent
7264 A symbol declared with this ^switch^switch^ on the command line replaces a
7265 symbol with the same name either in a definition file or specified with a
7266 ^switch^switch^ -D in the preprocessor data file.
7267
7268 @noindent
7269 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7270
7271 @item -gnateG
7272 When integrated preprocessing is performed and the preprocessor modifies
7273 the source text, write the result of this preprocessing into a file
7274 <source>^.prep^_prep^.
7275
7276 @end table
7277
7278 @node Code Generation Control
7279 @subsection Code Generation Control
7280
7281 @noindent
7282
7283 The GCC technology provides a wide range of target dependent
7284 @option{-m} switches for controlling
7285 details of code generation with respect to different versions of
7286 architectures. This includes variations in instruction sets (e.g.@:
7287 different members of the power pc family), and different requirements
7288 for optimal arrangement of instructions (e.g.@: different members of
7289 the x86 family). The list of available @option{-m} switches may be
7290 found in the GCC documentation.
7291
7292 Use of these @option{-m} switches may in some cases result in improved
7293 code performance.
7294
7295 The GNAT Pro technology is tested and qualified without any
7296 @option{-m} switches,
7297 so generally the most reliable approach is to avoid the use of these
7298 switches. However, we generally expect most of these switches to work
7299 successfully with GNAT Pro, and many customers have reported successful
7300 use of these options.
7301
7302 Our general advice is to avoid the use of @option{-m} switches unless
7303 special needs lead to requirements in this area. In particular,
7304 there is no point in using @option{-m} switches to improve performance
7305 unless you actually see a performance improvement.
7306
7307 @ifset vms
7308 @node Return Codes
7309 @subsection Return Codes
7310 @cindex Return Codes
7311 @cindex @option{/RETURN_CODES=VMS}
7312
7313 @noindent
7314 On VMS, GNAT compiled programs return POSIX-style codes by default,
7315 e.g.@: @option{/RETURN_CODES=POSIX}.
7316
7317 To enable VMS style return codes, use GNAT BIND and LINK with the option
7318 @option{/RETURN_CODES=VMS}. For example:
7319
7320 @smallexample
7321 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7322 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7323 @end smallexample
7324
7325 @noindent
7326 Programs built with /RETURN_CODES=VMS are suitable to be called in
7327 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7328 are suitable for spawning with appropriate GNAT RTL routines.
7329
7330 @end ifset
7331
7332 @node Search Paths and the Run-Time Library (RTL)
7333 @section Search Paths and the Run-Time Library (RTL)
7334
7335 @noindent
7336 With the GNAT source-based library system, the compiler must be able to
7337 find source files for units that are needed by the unit being compiled.
7338 Search paths are used to guide this process.
7339
7340 The compiler compiles one source file whose name must be given
7341 explicitly on the command line. In other words, no searching is done
7342 for this file. To find all other source files that are needed (the most
7343 common being the specs of units), the compiler examines the following
7344 directories, in the following order:
7345
7346 @enumerate
7347 @item
7348 The directory containing the source file of the main unit being compiled
7349 (the file name on the command line).
7350
7351 @item
7352 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7353 @command{gcc} command line, in the order given.
7354
7355 @item
7356 @findex ADA_PRJ_INCLUDE_FILE
7357 Each of the directories listed in the text file whose name is given
7358 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7359
7360 @noindent
7361 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7362 driver when project files are used. It should not normally be set
7363 by other means.
7364
7365 @item
7366 @findex ADA_INCLUDE_PATH
7367 Each of the directories listed in the value of the
7368 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7369 @ifclear vms
7370 Construct this value
7371 exactly as the @env{PATH} environment variable: a list of directory
7372 names separated by colons (semicolons when working with the NT version).
7373 @end ifclear
7374 @ifset vms
7375 Normally, define this value as a logical name containing a comma separated
7376 list of directory names.
7377
7378 This variable can also be defined by means of an environment string
7379 (an argument to the HP C exec* set of functions).
7380
7381 Logical Name:
7382 @smallexample
7383 DEFINE ANOTHER_PATH FOO:[BAG]
7384 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7385 @end smallexample
7386
7387 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7388 first, followed by the standard Ada
7389 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7390 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7391 (Text_IO, Sequential_IO, etc)
7392 instead of the standard Ada packages. Thus, in order to get the standard Ada
7393 packages by default, ADA_INCLUDE_PATH must be redefined.
7394 @end ifset
7395
7396 @item
7397 The content of the @file{ada_source_path} file which is part of the GNAT
7398 installation tree and is used to store standard libraries such as the
7399 GNAT Run Time Library (RTL) source files.
7400 @ifclear vms
7401 @ref{Installing a library}
7402 @end ifclear
7403 @end enumerate
7404
7405 @noindent
7406 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7407 inhibits the use of the directory
7408 containing the source file named in the command line. You can still
7409 have this directory on your search path, but in this case it must be
7410 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7411
7412 Specifying the switch @option{-nostdinc}
7413 inhibits the search of the default location for the GNAT Run Time
7414 Library (RTL) source files.
7415
7416 The compiler outputs its object files and ALI files in the current
7417 working directory.
7418 @ifclear vms
7419 Caution: The object file can be redirected with the @option{-o} switch;
7420 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7421 so the @file{ALI} file will not go to the right place. Therefore, you should
7422 avoid using the @option{-o} switch.
7423 @end ifclear
7424
7425 @findex System.IO
7426 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7427 children make up the GNAT RTL, together with the simple @code{System.IO}
7428 package used in the @code{"Hello World"} example. The sources for these units
7429 are needed by the compiler and are kept together in one directory. Not
7430 all of the bodies are needed, but all of the sources are kept together
7431 anyway. In a normal installation, you need not specify these directory
7432 names when compiling or binding. Either the environment variables or
7433 the built-in defaults cause these files to be found.
7434
7435 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7436 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7437 consisting of child units of @code{GNAT}. This is a collection of generally
7438 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7439 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7440
7441 Besides simplifying access to the RTL, a major use of search paths is
7442 in compiling sources from multiple directories. This can make
7443 development environments much more flexible.
7444
7445 @node Order of Compilation Issues
7446 @section Order of Compilation Issues
7447
7448 @noindent
7449 If, in our earlier example, there was a spec for the @code{hello}
7450 procedure, it would be contained in the file @file{hello.ads}; yet this
7451 file would not have to be explicitly compiled. This is the result of the
7452 model we chose to implement library management. Some of the consequences
7453 of this model are as follows:
7454
7455 @itemize @bullet
7456 @item
7457 There is no point in compiling specs (except for package
7458 specs with no bodies) because these are compiled as needed by clients. If
7459 you attempt a useless compilation, you will receive an error message.
7460 It is also useless to compile subunits because they are compiled as needed
7461 by the parent.
7462
7463 @item
7464 There are no order of compilation requirements: performing a
7465 compilation never obsoletes anything. The only way you can obsolete
7466 something and require recompilations is to modify one of the
7467 source files on which it depends.
7468
7469 @item
7470 There is no library as such, apart from the ALI files
7471 (@pxref{The Ada Library Information Files}, for information on the format
7472 of these files). For now we find it convenient to create separate ALI files,
7473 but eventually the information therein may be incorporated into the object
7474 file directly.
7475
7476 @item
7477 When you compile a unit, the source files for the specs of all units
7478 that it @code{with}'s, all its subunits, and the bodies of any generics it
7479 instantiates must be available (reachable by the search-paths mechanism
7480 described above), or you will receive a fatal error message.
7481 @end itemize
7482
7483 @node Examples
7484 @section Examples
7485
7486 @noindent
7487 The following are some typical Ada compilation command line examples:
7488
7489 @table @code
7490 @item $ gcc -c xyz.adb
7491 Compile body in file @file{xyz.adb} with all default options.
7492
7493 @ifclear vms
7494 @item $ gcc -c -O2 -gnata xyz-def.adb
7495 @end ifclear
7496 @ifset vms
7497 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7498 @end ifset
7499
7500 Compile the child unit package in file @file{xyz-def.adb} with extensive
7501 optimizations, and pragma @code{Assert}/@code{Debug} statements
7502 enabled.
7503
7504 @item $ gcc -c -gnatc abc-def.adb
7505 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7506 mode.
7507 @end table
7508
7509 @node Binding Using gnatbind
7510 @chapter Binding Using @code{gnatbind}
7511 @findex gnatbind
7512
7513 @menu
7514 * Running gnatbind::
7515 * Switches for gnatbind::
7516 * Command-Line Access::
7517 * Search Paths for gnatbind::
7518 * Examples of gnatbind Usage::
7519 @end menu
7520
7521 @noindent
7522 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7523 to bind compiled GNAT objects.
7524
7525 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7526 driver (see @ref{The GNAT Driver and Project Files}).
7527
7528 The @code{gnatbind} program performs four separate functions:
7529
7530 @enumerate
7531 @item
7532 Checks that a program is consistent, in accordance with the rules in
7533 Chapter 10 of the Ada Reference Manual. In particular, error
7534 messages are generated if a program uses inconsistent versions of a
7535 given unit.
7536
7537 @item
7538 Checks that an acceptable order of elaboration exists for the program
7539 and issues an error message if it cannot find an order of elaboration
7540 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7541
7542 @item
7543 Generates a main program incorporating the given elaboration order.
7544 This program is a small Ada package (body and spec) that
7545 must be subsequently compiled
7546 using the GNAT compiler. The necessary compilation step is usually
7547 performed automatically by @command{gnatlink}. The two most important
7548 functions of this program
7549 are to call the elaboration routines of units in an appropriate order
7550 and to call the main program.
7551
7552 @item
7553 Determines the set of object files required by the given main program.
7554 This information is output in the forms of comments in the generated program,
7555 to be read by the @command{gnatlink} utility used to link the Ada application.
7556 @end enumerate
7557
7558 @node Running gnatbind
7559 @section Running @code{gnatbind}
7560
7561 @noindent
7562 The form of the @code{gnatbind} command is
7563
7564 @smallexample
7565 $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7566 @end smallexample
7567
7568 @noindent
7569 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7570 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
7571 package in two files whose names are
7572 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7573 For example, if given the
7574 parameter @file{hello.ali}, for a main program contained in file
7575 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7576 and @file{b~hello.adb}.
7577
7578 When doing consistency checking, the binder takes into consideration
7579 any source files it can locate. For example, if the binder determines
7580 that the given main program requires the package @code{Pack}, whose
7581 @file{.ALI}
7582 file is @file{pack.ali} and whose corresponding source spec file is
7583 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7584 (using the same search path conventions as previously described for the
7585 @command{gcc} command). If it can locate this source file, it checks that
7586 the time stamps
7587 or source checksums of the source and its references to in @file{ALI} files
7588 match. In other words, any @file{ALI} files that mentions this spec must have
7589 resulted from compiling this version of the source file (or in the case
7590 where the source checksums match, a version close enough that the
7591 difference does not matter).
7592
7593 @cindex Source files, use by binder
7594 The effect of this consistency checking, which includes source files, is
7595 that the binder ensures that the program is consistent with the latest
7596 version of the source files that can be located at bind time. Editing a
7597 source file without compiling files that depend on the source file cause
7598 error messages to be generated by the binder.
7599
7600 For example, suppose you have a main program @file{hello.adb} and a
7601 package @code{P}, from file @file{p.ads} and you perform the following
7602 steps:
7603
7604 @enumerate
7605 @item
7606 Enter @code{gcc -c hello.adb} to compile the main program.
7607
7608 @item
7609 Enter @code{gcc -c p.ads} to compile package @code{P}.
7610
7611 @item
7612 Edit file @file{p.ads}.
7613
7614 @item
7615 Enter @code{gnatbind hello}.
7616 @end enumerate
7617
7618 @noindent
7619 At this point, the file @file{p.ali} contains an out-of-date time stamp
7620 because the file @file{p.ads} has been edited. The attempt at binding
7621 fails, and the binder generates the following error messages:
7622
7623 @smallexample
7624 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7625 error: "p.ads" has been modified and must be recompiled
7626 @end smallexample
7627
7628 @noindent
7629 Now both files must be recompiled as indicated, and then the bind can
7630 succeed, generating a main program. You need not normally be concerned
7631 with the contents of this file, but for reference purposes a sample
7632 binder output file is given in @ref{Example of Binder Output File}.
7633
7634 In most normal usage, the default mode of @command{gnatbind} which is to
7635 generate the main package in Ada, as described in the previous section.
7636 In particular, this means that any Ada programmer can read and understand
7637 the generated main program. It can also be debugged just like any other
7638 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7639 @command{gnatbind} and @command{gnatlink}.
7640
7641 However for some purposes it may be convenient to generate the main
7642 program in C rather than Ada. This may for example be helpful when you
7643 are generating a mixed language program with the main program in C. The
7644 GNAT compiler itself is an example.
7645 The use of the @option{^-C^/BIND_FILE=C^} switch
7646 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7647 be generated in C (and compiled using the gnu C compiler).
7648
7649 @node Switches for gnatbind
7650 @section Switches for @command{gnatbind}
7651
7652 @noindent
7653 The following switches are available with @code{gnatbind}; details will
7654 be presented in subsequent sections.
7655
7656 @menu
7657 * Consistency-Checking Modes::
7658 * Binder Error Message Control::
7659 * Elaboration Control::
7660 * Output Control::
7661 * Binding with Non-Ada Main Programs::
7662 * Binding Programs with No Main Subprogram::
7663 @end menu
7664
7665 @table @option
7666 @c !sort!
7667
7668 @item --version
7669 @cindex @option{--version} @command{gnatbind}
7670 Display Copyright and version, then exit disregarding all other options.
7671
7672 @item --help
7673 @cindex @option{--help} @command{gnatbind}
7674 If @option{--version} was not used, display usage, then exit disregarding
7675 all other options.
7676
7677 @item -a
7678 @cindex @option{-a} @command{gnatbind}
7679 Indicates that, if supported by the platform, the adainit procedure should
7680 be treated as an initialisation routine by the linker (a constructor). This
7681 is intended to be used by the Project Manager to automatically initialize
7682 shared Stand-Alone Libraries.
7683
7684 @item ^-aO^/OBJECT_SEARCH^
7685 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7686 Specify directory to be searched for ALI files.
7687
7688 @item ^-aI^/SOURCE_SEARCH^
7689 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7690 Specify directory to be searched for source file.
7691
7692 @item ^-A^/BIND_FILE=ADA^
7693 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7694 Generate binder program in Ada (default)
7695
7696 @item ^-b^/REPORT_ERRORS=BRIEF^
7697 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
7698 Generate brief messages to @file{stderr} even if verbose mode set.
7699
7700 @item ^-c^/NOOUTPUT^
7701 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
7702 Check only, no generation of binder output file.
7703
7704 @item ^-C^/BIND_FILE=C^
7705 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
7706 Generate binder program in C
7707
7708 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
7709 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
7710 This switch can be used to change the default task stack size value
7711 to a specified size @var{nn}, which is expressed in bytes by default, or
7712 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7713 with @var{m}.
7714 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
7715 in effect, to completing all task specs with
7716 @smallexample @c ada
7717    pragma Storage_Size (nn);
7718 @end smallexample
7719 When they do not already have such a pragma.
7720
7721 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
7722 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
7723 This switch can be used to change the default secondary stack size value
7724 to a specified size @var{nn}, which is expressed in bytes by default, or
7725 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7726 with @var{m}.
7727
7728 The secondary stack is used to deal with functions that return a variable
7729 sized result, for example a function returning an unconstrained
7730 String. There are two ways in which this secondary stack is allocated.
7731
7732 For most targets, the secondary stack is growing on demand and is allocated
7733 as a chain of blocks in the heap. The -D option is not very
7734 relevant. It only give some control over the size of the allocated
7735 blocks (whose size is the minimum of the default secondary stack size value,
7736 and the actual size needed for the current allocation request).
7737
7738 For certain targets, notably VxWorks 653,
7739 the secondary stack is allocated by carving off a fixed ratio chunk of the
7740 primary task stack. The -D option is used to define the
7741 size of the environment task's secondary stack.
7742
7743 @item ^-e^/ELABORATION_DEPENDENCIES^
7744 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
7745 Output complete list of elaboration-order dependencies.
7746
7747 @item ^-E^/STORE_TRACEBACKS^
7748 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
7749 Store tracebacks in exception occurrences when the target supports it.
7750 This is the default with the zero cost exception mechanism.
7751 @ignore
7752 @c The following may get moved to an appendix
7753 This option is currently supported on the following targets:
7754 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
7755 @end ignore
7756 See also the packages @code{GNAT.Traceback} and
7757 @code{GNAT.Traceback.Symbolic} for more information.
7758 @ifclear vms
7759 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
7760 @command{gcc} option.
7761 @end ifclear
7762
7763 @item ^-F^/FORCE_ELABS_FLAGS^
7764 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
7765 Force the checks of elaboration flags. @command{gnatbind} does not normally
7766 generate checks of elaboration flags for the main executable, except when
7767 a Stand-Alone Library is used. However, there are cases when this cannot be
7768 detected by gnatbind. An example is importing an interface of a Stand-Alone
7769 Library through a pragma Import and only specifying through a linker switch
7770 this Stand-Alone Library. This switch is used to guarantee that elaboration
7771 flag checks are generated.
7772
7773 @item ^-h^/HELP^
7774 @cindex @option{^-h^/HELP^} (@command{gnatbind})
7775 Output usage (help) information
7776
7777 @item ^-I^/SEARCH^
7778 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7779 Specify directory to be searched for source and ALI files.
7780
7781 @item ^-I-^/NOCURRENT_DIRECTORY^
7782 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
7783 Do not look for sources in the current directory where @code{gnatbind} was
7784 invoked, and do not look for ALI files in the directory containing the
7785 ALI file named in the @code{gnatbind} command line.
7786
7787 @item ^-l^/ORDER_OF_ELABORATION^
7788 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
7789 Output chosen elaboration order.
7790
7791 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
7792 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7793 Bind the units for library building. In this case the adainit and
7794 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
7795 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
7796 ^@var{xxx}final^@var{XXX}FINAL^.
7797 Implies ^-n^/NOCOMPILE^.
7798 @ifclear vms
7799 (@xref{GNAT and Libraries}, for more details.)
7800 @end ifclear
7801 @ifset vms
7802 On OpenVMS, these init and final procedures are exported in uppercase
7803 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
7804 the init procedure will be "TOTOINIT" and the exported name of the final
7805 procedure will be "TOTOFINAL".
7806 @end ifset
7807
7808 @item ^-Mxyz^/RENAME_MAIN=xyz^
7809 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
7810 Rename generated main program from main to xyz. This option is
7811 supported on cross environments only.
7812
7813 @item ^-m^/ERROR_LIMIT=^@var{n}
7814 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
7815 Limit number of detected errors or warnings to @var{n}, where @var{n} is
7816 in the range 1..999999. The default value if no switch is
7817 given is 9999. If the number of warnings reaches this limit, then a
7818 message is output and further warnings are suppressed, the bind
7819 continues in this case. If the number of errors reaches this
7820 limit, then a message is output and the bind is abandoned.
7821 A value of zero means that no limit is enforced. The equal
7822 sign is optional.
7823
7824 @ifset unw
7825 Furthermore, under Windows, the sources pointed to by the libraries path
7826 set in the registry are not searched for.
7827 @end ifset
7828
7829 @item ^-n^/NOMAIN^
7830 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7831 No main program.
7832
7833 @item -nostdinc
7834 @cindex @option{-nostdinc} (@command{gnatbind})
7835 Do not look for sources in the system default directory.
7836
7837 @item -nostdlib
7838 @cindex @option{-nostdlib} (@command{gnatbind})
7839 Do not look for library files in the system default directory.
7840
7841 @item --RTS=@var{rts-path}
7842 @cindex @option{--RTS} (@code{gnatbind})
7843 Specifies the default location of the runtime library. Same meaning as the
7844 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
7845
7846 @item ^-o ^/OUTPUT=^@var{file}
7847 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7848 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7849 Note that if this option is used, then linking must be done manually,
7850 gnatlink cannot be used.
7851
7852 @item ^-O^/OBJECT_LIST^
7853 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7854 Output object list.
7855
7856 @item ^-p^/PESSIMISTIC_ELABORATION^
7857 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7858 Pessimistic (worst-case) elaboration order
7859
7860 @item ^-R^-R^
7861 @cindex @option{^-R^-R^} (@command{gnatbind})
7862 Output closure source list.
7863
7864 @item ^-s^/READ_SOURCES=ALL^
7865 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7866 Require all source files to be present.
7867
7868 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7869 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7870 Specifies the value to be used when detecting uninitialized scalar
7871 objects with pragma Initialize_Scalars.
7872 The @var{xxx} ^string specified with the switch^option^ may be either
7873 @itemize @bullet
7874 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7875 @item ``@option{^lo^LOW^}'' for the lowest possible value
7876 @item ``@option{^hi^HIGH^}'' for the highest possible value
7877 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
7878 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
7879 @end itemize
7880
7881 In addition, you can specify @option{-Sev} to indicate that the value is
7882 to be set at run time. In this case, the program will look for an environment
7883 @cindex GNAT_INIT_SCALARS
7884 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
7885 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
7886 If no environment variable is found, or if it does not have a valid value,
7887 then the default is @option{in} (invalid values).
7888
7889 @ifclear vms
7890 @item -static
7891 @cindex @option{-static} (@code{gnatbind})
7892 Link against a static GNAT run time.
7893
7894 @item -shared
7895 @cindex @option{-shared} (@code{gnatbind})
7896 Link against a shared GNAT run time when available.
7897 @end ifclear
7898
7899 @item ^-t^/NOTIME_STAMP_CHECK^
7900 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7901 Tolerate time stamp and other consistency errors
7902
7903 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7904 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7905 Set the time slice value to @var{n} milliseconds. If the system supports
7906 the specification of a specific time slice value, then the indicated value
7907 is used. If the system does not support specific time slice values, but
7908 does support some general notion of round-robin scheduling, then any
7909 nonzero value will activate round-robin scheduling.
7910
7911 A value of zero is treated specially. It turns off time
7912 slicing, and in addition, indicates to the tasking run time that the
7913 semantics should match as closely as possible the Annex D
7914 requirements of the Ada RM, and in particular sets the default
7915 scheduling policy to @code{FIFO_Within_Priorities}.
7916
7917 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
7918 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
7919 Enable dynamic stack usage, with @var{n} results stored and displayed
7920 at program termination. A result is generated when a task
7921 terminates. Results that can't be stored are displayed on the fly, at
7922 task termination. This option is currently not supported on Itanium
7923 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
7924
7925 @item ^-v^/REPORT_ERRORS=VERBOSE^
7926 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7927 Verbose mode. Write error messages, header, summary output to
7928 @file{stdout}.
7929
7930 @ifclear vms
7931 @item -w@var{x}
7932 @cindex @option{-w} (@code{gnatbind})
7933 Warning mode (@var{x}=s/e for suppress/treat as error)
7934 @end ifclear
7935
7936 @ifset vms
7937 @item /WARNINGS=NORMAL
7938 @cindex @option{/WARNINGS} (@code{gnatbind})
7939 Normal warnings mode. Warnings are issued but ignored
7940
7941 @item /WARNINGS=SUPPRESS
7942 @cindex @option{/WARNINGS} (@code{gnatbind})
7943 All warning messages are suppressed
7944
7945 @item /WARNINGS=ERROR
7946 @cindex @option{/WARNINGS} (@code{gnatbind})
7947 Warning messages are treated as fatal errors
7948 @end ifset
7949
7950 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
7951 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
7952 Override default wide character encoding for standard Text_IO files.
7953
7954 @item ^-x^/READ_SOURCES=NONE^
7955 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7956 Exclude source files (check object consistency only).
7957
7958 @ifset vms
7959 @item /READ_SOURCES=AVAILABLE
7960 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7961 Default mode, in which sources are checked for consistency only if
7962 they are available.
7963 @end ifset
7964
7965 @item ^-y^/ENABLE_LEAP_SECONDS^
7966 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
7967 Enable leap seconds support in @code{Ada.Calendar} and its children.
7968
7969 @item ^-z^/ZERO_MAIN^
7970 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7971 No main subprogram.
7972 @end table
7973
7974 @ifclear vms
7975 @noindent
7976 You may obtain this listing of switches by running @code{gnatbind} with
7977 no arguments.
7978 @end ifclear
7979
7980 @node Consistency-Checking Modes
7981 @subsection Consistency-Checking Modes
7982
7983 @noindent
7984 As described earlier, by default @code{gnatbind} checks
7985 that object files are consistent with one another and are consistent
7986 with any source files it can locate. The following switches control binder
7987 access to sources.
7988
7989 @table @option
7990 @c !sort!
7991 @item ^-s^/READ_SOURCES=ALL^
7992 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7993 Require source files to be present. In this mode, the binder must be
7994 able to locate all source files that are referenced, in order to check
7995 their consistency. In normal mode, if a source file cannot be located it
7996 is simply ignored. If you specify this switch, a missing source
7997 file is an error.
7998
7999 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8000 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8001 Override default wide character encoding for standard Text_IO files.
8002 Normally the default wide character encoding method used for standard
8003 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8004 the main source input (see description of switch
8005 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8006 use of this switch for the binder (which has the same set of
8007 possible arguments) overrides this default as specified.
8008
8009 @item ^-x^/READ_SOURCES=NONE^
8010 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8011 Exclude source files. In this mode, the binder only checks that ALI
8012 files are consistent with one another. Source files are not accessed.
8013 The binder runs faster in this mode, and there is still a guarantee that
8014 the resulting program is self-consistent.
8015 If a source file has been edited since it was last compiled, and you
8016 specify this switch, the binder will not detect that the object
8017 file is out of date with respect to the source file. Note that this is the
8018 mode that is automatically used by @command{gnatmake} because in this
8019 case the checking against sources has already been performed by
8020 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8021
8022 @ifset vms
8023 @item /READ_SOURCES=AVAILABLE
8024 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8025 This is the default mode in which source files are checked if they are
8026 available, and ignored if they are not available.
8027 @end ifset
8028 @end table
8029
8030 @node Binder Error Message Control
8031 @subsection Binder Error Message Control
8032
8033 @noindent
8034 The following switches provide control over the generation of error
8035 messages from the binder:
8036
8037 @table @option
8038 @c !sort!
8039 @item ^-v^/REPORT_ERRORS=VERBOSE^
8040 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8041 Verbose mode. In the normal mode, brief error messages are generated to
8042 @file{stderr}. If this switch is present, a header is written
8043 to @file{stdout} and any error messages are directed to @file{stdout}.
8044 All that is written to @file{stderr} is a brief summary message.
8045
8046 @item ^-b^/REPORT_ERRORS=BRIEF^
8047 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8048 Generate brief error messages to @file{stderr} even if verbose mode is
8049 specified. This is relevant only when used with the
8050 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8051
8052 @ifclear vms
8053 @item -m@var{n}
8054 @cindex @option{-m} (@code{gnatbind})
8055 Limits the number of error messages to @var{n}, a decimal integer in the
8056 range 1-999. The binder terminates immediately if this limit is reached.
8057
8058 @item -M@var{xxx}
8059 @cindex @option{-M} (@code{gnatbind})
8060 Renames the generated main program from @code{main} to @code{xxx}.
8061 This is useful in the case of some cross-building environments, where
8062 the actual main program is separate from the one generated
8063 by @code{gnatbind}.
8064 @end ifclear
8065
8066 @item ^-ws^/WARNINGS=SUPPRESS^
8067 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8068 @cindex Warnings
8069 Suppress all warning messages.
8070
8071 @item ^-we^/WARNINGS=ERROR^
8072 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8073 Treat any warning messages as fatal errors.
8074
8075 @ifset vms
8076 @item /WARNINGS=NORMAL
8077 Standard mode with warnings generated, but warnings do not get treated
8078 as errors.
8079 @end ifset
8080
8081 @item ^-t^/NOTIME_STAMP_CHECK^
8082 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8083 @cindex Time stamp checks, in binder
8084 @cindex Binder consistency checks
8085 @cindex Consistency checks, in binder
8086 The binder performs a number of consistency checks including:
8087
8088 @itemize @bullet
8089 @item
8090 Check that time stamps of a given source unit are consistent
8091 @item
8092 Check that checksums of a given source unit are consistent
8093 @item
8094 Check that consistent versions of @code{GNAT} were used for compilation
8095 @item
8096 Check consistency of configuration pragmas as required
8097 @end itemize
8098
8099 @noindent
8100 Normally failure of such checks, in accordance with the consistency
8101 requirements of the Ada Reference Manual, causes error messages to be
8102 generated which abort the binder and prevent the output of a binder
8103 file and subsequent link to obtain an executable.
8104
8105 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8106 into warnings, so that
8107 binding and linking can continue to completion even in the presence of such
8108 errors. The result may be a failed link (due to missing symbols), or a
8109 non-functional executable which has undefined semantics.
8110 @emph{This means that
8111 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8112 with extreme care.}
8113 @end table
8114
8115 @node Elaboration Control
8116 @subsection Elaboration Control
8117
8118 @noindent
8119 The following switches provide additional control over the elaboration
8120 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8121
8122 @table @option
8123 @item ^-p^/PESSIMISTIC_ELABORATION^
8124 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8125 Normally the binder attempts to choose an elaboration order that is
8126 likely to minimize the likelihood of an elaboration order error resulting
8127 in raising a @code{Program_Error} exception. This switch reverses the
8128 action of the binder, and requests that it deliberately choose an order
8129 that is likely to maximize the likelihood of an elaboration error.
8130 This is useful in ensuring portability and avoiding dependence on
8131 accidental fortuitous elaboration ordering.
8132
8133 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8134 switch if dynamic
8135 elaboration checking is used (@option{-gnatE} switch used for compilation).
8136 This is because in the default static elaboration mode, all necessary
8137 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8138 These implicit pragmas are still respected by the binder in
8139 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8140 safe elaboration order is assured.
8141 @end table
8142
8143 @node Output Control
8144 @subsection Output Control
8145
8146 @noindent
8147 The following switches allow additional control over the output
8148 generated by the binder.
8149
8150 @table @option
8151 @c !sort!
8152
8153 @item ^-A^/BIND_FILE=ADA^
8154 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
8155 Generate binder program in Ada (default). The binder program is named
8156 @file{b~@var{mainprog}.adb} by default. This can be changed with
8157 @option{^-o^/OUTPUT^} @code{gnatbind} option.
8158
8159 @item ^-c^/NOOUTPUT^
8160 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8161 Check only. Do not generate the binder output file. In this mode the
8162 binder performs all error checks but does not generate an output file.
8163
8164 @item ^-C^/BIND_FILE=C^
8165 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
8166 Generate binder program in C. The binder program is named
8167 @file{b_@var{mainprog}.c}.
8168 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
8169 option.
8170
8171 @item ^-e^/ELABORATION_DEPENDENCIES^
8172 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8173 Output complete list of elaboration-order dependencies, showing the
8174 reason for each dependency. This output can be rather extensive but may
8175 be useful in diagnosing problems with elaboration order. The output is
8176 written to @file{stdout}.
8177
8178 @item ^-h^/HELP^
8179 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8180 Output usage information. The output is written to @file{stdout}.
8181
8182 @item ^-K^/LINKER_OPTION_LIST^
8183 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8184 Output linker options to @file{stdout}. Includes library search paths,
8185 contents of pragmas Ident and Linker_Options, and libraries added
8186 by @code{gnatbind}.
8187
8188 @item ^-l^/ORDER_OF_ELABORATION^
8189 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8190 Output chosen elaboration order. The output is written to @file{stdout}.
8191
8192 @item ^-O^/OBJECT_LIST^
8193 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8194 Output full names of all the object files that must be linked to provide
8195 the Ada component of the program. The output is written to @file{stdout}.
8196 This list includes the files explicitly supplied and referenced by the user
8197 as well as implicitly referenced run-time unit files. The latter are
8198 omitted if the corresponding units reside in shared libraries. The
8199 directory names for the run-time units depend on the system configuration.
8200
8201 @item ^-o ^/OUTPUT=^@var{file}
8202 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8203 Set name of output file to @var{file} instead of the normal
8204 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8205 binder generated body filename. In C mode you would normally give
8206 @var{file} an extension of @file{.c} because it will be a C source program.
8207 Note that if this option is used, then linking must be done manually.
8208 It is not possible to use gnatlink in this case, since it cannot locate
8209 the binder file.
8210
8211 @item ^-r^/RESTRICTION_LIST^
8212 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8213 Generate list of @code{pragma Restrictions} that could be applied to
8214 the current unit. This is useful for code audit purposes, and also may
8215 be used to improve code generation in some cases.
8216
8217 @end table
8218
8219 @node Binding with Non-Ada Main Programs
8220 @subsection Binding with Non-Ada Main Programs
8221
8222 @noindent
8223 In our description so far we have assumed that the main
8224 program is in Ada, and that the task of the binder is to generate a
8225 corresponding function @code{main} that invokes this Ada main
8226 program. GNAT also supports the building of executable programs where
8227 the main program is not in Ada, but some of the called routines are
8228 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8229 The following switch is used in this situation:
8230
8231 @table @option
8232 @item ^-n^/NOMAIN^
8233 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8234 No main program. The main program is not in Ada.
8235 @end table
8236
8237 @noindent
8238 In this case, most of the functions of the binder are still required,
8239 but instead of generating a main program, the binder generates a file
8240 containing the following callable routines:
8241
8242 @table @code
8243 @item adainit
8244 @findex adainit
8245 You must call this routine to initialize the Ada part of the program by
8246 calling the necessary elaboration routines. A call to @code{adainit} is
8247 required before the first call to an Ada subprogram.
8248
8249 Note that it is assumed that the basic execution environment must be setup
8250 to be appropriate for Ada execution at the point where the first Ada
8251 subprogram is called. In particular, if the Ada code will do any
8252 floating-point operations, then the FPU must be setup in an appropriate
8253 manner. For the case of the x86, for example, full precision mode is
8254 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8255 that the FPU is in the right state.
8256
8257 @item adafinal
8258 @findex adafinal
8259 You must call this routine to perform any library-level finalization
8260 required by the Ada subprograms. A call to @code{adafinal} is required
8261 after the last call to an Ada subprogram, and before the program
8262 terminates.
8263 @end table
8264
8265 @noindent
8266 If the @option{^-n^/NOMAIN^} switch
8267 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8268 @cindex Binder, multiple input files
8269 is given, more than one ALI file may appear on
8270 the command line for @code{gnatbind}. The normal @dfn{closure}
8271 calculation is performed for each of the specified units. Calculating
8272 the closure means finding out the set of units involved by tracing
8273 @code{with} references. The reason it is necessary to be able to
8274 specify more than one ALI file is that a given program may invoke two or
8275 more quite separate groups of Ada units.
8276
8277 The binder takes the name of its output file from the last specified ALI
8278 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8279 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8280 The output is an Ada unit in source form that can
8281 be compiled with GNAT unless the -C switch is used in which case the
8282 output is a C source file, which must be compiled using the C compiler.
8283 This compilation occurs automatically as part of the @command{gnatlink}
8284 processing.
8285
8286 Currently the GNAT run time requires a FPU using 80 bits mode
8287 precision. Under targets where this is not the default it is required to
8288 call GNAT.Float_Control.Reset before using floating point numbers (this
8289 include float computation, float input and output) in the Ada code. A
8290 side effect is that this could be the wrong mode for the foreign code
8291 where floating point computation could be broken after this call.
8292
8293 @node Binding Programs with No Main Subprogram
8294 @subsection Binding Programs with No Main Subprogram
8295
8296 @noindent
8297 It is possible to have an Ada program which does not have a main
8298 subprogram. This program will call the elaboration routines of all the
8299 packages, then the finalization routines.
8300
8301 The following switch is used to bind programs organized in this manner:
8302
8303 @table @option
8304 @item ^-z^/ZERO_MAIN^
8305 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8306 Normally the binder checks that the unit name given on the command line
8307 corresponds to a suitable main subprogram. When this switch is used,
8308 a list of ALI files can be given, and the execution of the program
8309 consists of elaboration of these units in an appropriate order. Note
8310 that the default wide character encoding method for standard Text_IO
8311 files is always set to Brackets if this switch is set (you can use
8312 the binder switch
8313 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8314 @end table
8315
8316 @node Command-Line Access
8317 @section Command-Line Access
8318
8319 @noindent
8320 The package @code{Ada.Command_Line} provides access to the command-line
8321 arguments and program name. In order for this interface to operate
8322 correctly, the two variables
8323
8324 @smallexample
8325 @group
8326 int gnat_argc;
8327 char **gnat_argv;
8328 @end group
8329 @end smallexample
8330
8331 @noindent
8332 @findex gnat_argv
8333 @findex gnat_argc
8334 are declared in one of the GNAT library routines. These variables must
8335 be set from the actual @code{argc} and @code{argv} values passed to the
8336 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8337 generates the C main program to automatically set these variables.
8338 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8339 set these variables. If they are not set, the procedures in
8340 @code{Ada.Command_Line} will not be available, and any attempt to use
8341 them will raise @code{Constraint_Error}. If command line access is
8342 required, your main program must set @code{gnat_argc} and
8343 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8344 it.
8345
8346 @node Search Paths for gnatbind
8347 @section Search Paths for @code{gnatbind}
8348
8349 @noindent
8350 The binder takes the name of an ALI file as its argument and needs to
8351 locate source files as well as other ALI files to verify object consistency.
8352
8353 For source files, it follows exactly the same search rules as @command{gcc}
8354 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8355 directories searched are:
8356
8357 @enumerate
8358 @item
8359 The directory containing the ALI file named in the command line, unless
8360 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8361
8362 @item
8363 All directories specified by @option{^-I^/SEARCH^}
8364 switches on the @code{gnatbind}
8365 command line, in the order given.
8366
8367 @item
8368 @findex ADA_PRJ_OBJECTS_FILE
8369 Each of the directories listed in the text file whose name is given
8370 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8371
8372 @noindent
8373 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8374 driver when project files are used. It should not normally be set
8375 by other means.
8376
8377 @item
8378 @findex ADA_OBJECTS_PATH
8379 Each of the directories listed in the value of the
8380 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8381 @ifset unw
8382 Construct this value
8383 exactly as the @env{PATH} environment variable: a list of directory
8384 names separated by colons (semicolons when working with the NT version
8385 of GNAT).
8386 @end ifset
8387 @ifset vms
8388 Normally, define this value as a logical name containing a comma separated
8389 list of directory names.
8390
8391 This variable can also be defined by means of an environment string
8392 (an argument to the HP C exec* set of functions).
8393
8394 Logical Name:
8395 @smallexample
8396 DEFINE ANOTHER_PATH FOO:[BAG]
8397 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8398 @end smallexample
8399
8400 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8401 first, followed by the standard Ada
8402 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8403 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8404 (Text_IO, Sequential_IO, etc)
8405 instead of the standard Ada packages. Thus, in order to get the standard Ada
8406 packages by default, ADA_OBJECTS_PATH must be redefined.
8407 @end ifset
8408
8409 @item
8410 The content of the @file{ada_object_path} file which is part of the GNAT
8411 installation tree and is used to store standard libraries such as the
8412 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8413 specified.
8414 @ifclear vms
8415 @ref{Installing a library}
8416 @end ifclear
8417 @end enumerate
8418
8419 @noindent
8420 In the binder the switch @option{^-I^/SEARCH^}
8421 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8422 is used to specify both source and
8423 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8424 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8425 instead if you want to specify
8426 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8427 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8428 if you want to specify library paths
8429 only. This means that for the binder
8430 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8431 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8432 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8433 The binder generates the bind file (a C language source file) in the
8434 current working directory.
8435
8436 @findex Ada
8437 @findex System
8438 @findex Interfaces
8439 @findex GNAT
8440 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8441 children make up the GNAT Run-Time Library, together with the package
8442 GNAT and its children, which contain a set of useful additional
8443 library functions provided by GNAT. The sources for these units are
8444 needed by the compiler and are kept together in one directory. The ALI
8445 files and object files generated by compiling the RTL are needed by the
8446 binder and the linker and are kept together in one directory, typically
8447 different from the directory containing the sources. In a normal
8448 installation, you need not specify these directory names when compiling
8449 or binding. Either the environment variables or the built-in defaults
8450 cause these files to be found.
8451
8452 Besides simplifying access to the RTL, a major use of search paths is
8453 in compiling sources from multiple directories. This can make
8454 development environments much more flexible.
8455
8456 @node Examples of gnatbind Usage
8457 @section Examples of @code{gnatbind} Usage
8458
8459 @noindent
8460 This section contains a number of examples of using the GNAT binding
8461 utility @code{gnatbind}.
8462
8463 @table @code
8464 @item gnatbind hello
8465 The main program @code{Hello} (source program in @file{hello.adb}) is
8466 bound using the standard switch settings. The generated main program is
8467 @file{b~hello.adb}. This is the normal, default use of the binder.
8468
8469 @ifclear vms
8470 @item gnatbind hello -o mainprog.adb
8471 @end ifclear
8472 @ifset vms
8473 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8474 @end ifset
8475 The main program @code{Hello} (source program in @file{hello.adb}) is
8476 bound using the standard switch settings. The generated main program is
8477 @file{mainprog.adb} with the associated spec in
8478 @file{mainprog.ads}. Note that you must specify the body here not the
8479 spec, in the case where the output is in Ada. Note that if this option
8480 is used, then linking must be done manually, since gnatlink will not
8481 be able to find the generated file.
8482
8483 @ifclear vms
8484 @item gnatbind main -C -o mainprog.c -x
8485 @end ifclear
8486 @ifset vms
8487 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
8488 @end ifset
8489 The main program @code{Main} (source program in
8490 @file{main.adb}) is bound, excluding source files from the
8491 consistency checking, generating
8492 the file @file{mainprog.c}.
8493
8494 @ifclear vms
8495 @item gnatbind -x main_program -C -o mainprog.c
8496 This command is exactly the same as the previous example. Switches may
8497 appear anywhere in the command line, and single letter switches may be
8498 combined into a single switch.
8499 @end ifclear
8500
8501 @ifclear vms
8502 @item gnatbind -n math dbase -C -o ada-control.c
8503 @end ifclear
8504 @ifset vms
8505 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
8506 @end ifset
8507 The main program is in a language other than Ada, but calls to
8508 subprograms in packages @code{Math} and @code{Dbase} appear. This call
8509 to @code{gnatbind} generates the file @file{ada-control.c} containing
8510 the @code{adainit} and @code{adafinal} routines to be called before and
8511 after accessing the Ada units.
8512 @end table
8513
8514 @c ------------------------------------
8515 @node Linking Using gnatlink
8516 @chapter Linking Using @command{gnatlink}
8517 @c ------------------------------------
8518 @findex gnatlink
8519
8520 @noindent
8521 This chapter discusses @command{gnatlink}, a tool that links
8522 an Ada program and builds an executable file. This utility
8523 invokes the system linker ^(via the @command{gcc} command)^^
8524 with a correct list of object files and library references.
8525 @command{gnatlink} automatically determines the list of files and
8526 references for the Ada part of a program. It uses the binder file
8527 generated by the @command{gnatbind} to determine this list.
8528
8529 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8530 driver (see @ref{The GNAT Driver and Project Files}).
8531
8532 @menu
8533 * Running gnatlink::
8534 * Switches for gnatlink::
8535 @end menu
8536
8537 @node Running gnatlink
8538 @section Running @command{gnatlink}
8539
8540 @noindent
8541 The form of the @command{gnatlink} command is
8542
8543 @smallexample
8544 $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8545            @ovar{non-Ada objects} @ovar{linker options}
8546 @end smallexample
8547
8548 @noindent
8549 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8550 non-Ada objects
8551 or linker options) may be in any order, provided that no non-Ada object may
8552 be mistaken for a main @file{ALI} file.
8553 Any file name @file{F} without the @file{.ali}
8554 extension will be taken as the main @file{ALI} file if a file exists
8555 whose name is the concatenation of @file{F} and @file{.ali}.
8556
8557 @noindent
8558 @file{@var{mainprog}.ali} references the ALI file of the main program.
8559 The @file{.ali} extension of this file can be omitted. From this
8560 reference, @command{gnatlink} locates the corresponding binder file
8561 @file{b~@var{mainprog}.adb} and, using the information in this file along
8562 with the list of non-Ada objects and linker options, constructs a
8563 linker command file to create the executable.
8564
8565 The arguments other than the @command{gnatlink} switches and the main
8566 @file{ALI} file are passed to the linker uninterpreted.
8567 They typically include the names of
8568 object files for units written in other languages than Ada and any library
8569 references required to resolve references in any of these foreign language
8570 units, or in @code{Import} pragmas in any Ada units.
8571
8572 @var{linker options} is an optional list of linker specific
8573 switches.
8574 The default linker called by gnatlink is @command{gcc} which in
8575 turn calls the appropriate system linker.
8576 Standard options for the linker such as @option{-lmy_lib} or
8577 @option{-Ldir} can be added as is.
8578 For options that are not recognized by
8579 @command{gcc} as linker options, use the @command{gcc} switches
8580 @option{-Xlinker} or @option{-Wl,}.
8581 Refer to the GCC documentation for
8582 details. Here is an example showing how to generate a linker map:
8583
8584 @smallexample
8585 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8586 @end smallexample
8587
8588 Using @var{linker options} it is possible to set the program stack and
8589 heap size.
8590 @ifset unw
8591 See @ref{Setting Stack Size from gnatlink} and
8592 @ref{Setting Heap Size from gnatlink}.
8593 @end ifset
8594
8595 @command{gnatlink} determines the list of objects required by the Ada
8596 program and prepends them to the list of objects passed to the linker.
8597 @command{gnatlink} also gathers any arguments set by the use of
8598 @code{pragma Linker_Options} and adds them to the list of arguments
8599 presented to the linker.
8600
8601 @ifset vms
8602 @command{gnatlink} accepts the following types of extra files on the command
8603 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8604 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8605 handled according to their extension.
8606 @end ifset
8607
8608 @node Switches for gnatlink
8609 @section Switches for @command{gnatlink}
8610
8611 @noindent
8612 The following switches are available with the @command{gnatlink} utility:
8613
8614 @table @option
8615 @c !sort!
8616
8617 @item --version
8618 @cindex @option{--version} @command{gnatlink}
8619 Display Copyright and version, then exit disregarding all other options.
8620
8621 @item --help
8622 @cindex @option{--help} @command{gnatlink}
8623 If @option{--version} was not used, display usage, then exit disregarding
8624 all other options.
8625
8626 @item ^-A^/BIND_FILE=ADA^
8627 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
8628 The binder has generated code in Ada. This is the default.
8629
8630 @item ^-C^/BIND_FILE=C^
8631 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
8632 If instead of generating a file in Ada, the binder has generated one in
8633 C, then the linker needs to know about it. Use this switch to signal
8634 to @command{gnatlink} that the binder has generated C code rather than
8635 Ada code.
8636
8637 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8638 @cindex Command line length
8639 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8640 On some targets, the command line length is limited, and @command{gnatlink}
8641 will generate a separate file for the linker if the list of object files
8642 is too long.
8643 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8644 to be generated even if
8645 the limit is not exceeded. This is useful in some cases to deal with
8646 special situations where the command line length is exceeded.
8647
8648 @item ^-g^/DEBUG^
8649 @cindex Debugging information, including
8650 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8651 The option to include debugging information causes the Ada bind file (in
8652 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8653 @option{^-g^/DEBUG^}.
8654 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8655 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8656 Without @option{^-g^/DEBUG^}, the binder removes these files by
8657 default. The same procedure apply if a C bind file was generated using
8658 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8659 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8660
8661 @item ^-n^/NOCOMPILE^
8662 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8663 Do not compile the file generated by the binder. This may be used when
8664 a link is rerun with different options, but there is no need to recompile
8665 the binder file.
8666
8667 @item ^-v^/VERBOSE^
8668 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8669 Causes additional information to be output, including a full list of the
8670 included object files. This switch option is most useful when you want
8671 to see what set of object files are being used in the link step.
8672
8673 @item ^-v -v^/VERBOSE/VERBOSE^
8674 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8675 Very verbose mode. Requests that the compiler operate in verbose mode when
8676 it compiles the binder file, and that the system linker run in verbose mode.
8677
8678 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8679 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8680 @var{exec-name} specifies an alternate name for the generated
8681 executable program. If this switch is omitted, the executable has the same
8682 name as the main unit. For example, @code{gnatlink try.ali} creates
8683 an executable called @file{^try^TRY.EXE^}.
8684
8685 @ifclear vms
8686 @item -b @var{target}
8687 @cindex @option{-b} (@command{gnatlink})
8688 Compile your program to run on @var{target}, which is the name of a
8689 system configuration. You must have a GNAT cross-compiler built if
8690 @var{target} is not the same as your host system.
8691
8692 @item -B@var{dir}
8693 @cindex @option{-B} (@command{gnatlink})
8694 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8695 from @var{dir} instead of the default location. Only use this switch
8696 when multiple versions of the GNAT compiler are available.
8697 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
8698 for further details. You would normally use the @option{-b} or
8699 @option{-V} switch instead.
8700
8701 @item --GCC=@var{compiler_name}
8702 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8703 Program used for compiling the binder file. The default is
8704 @command{gcc}. You need to use quotes around @var{compiler_name} if
8705 @code{compiler_name} contains spaces or other separator characters.
8706 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8707 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8708 inserted after your command name. Thus in the above example the compiler
8709 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8710 A limitation of this syntax is that the name and path name of the executable
8711 itself must not include any embedded spaces. If the compiler executable is
8712 different from the default one (gcc or <prefix>-gcc), then the back-end
8713 switches in the ALI file are not used to compile the binder generated source.
8714 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
8715 switches will be used for @option{--GCC="gcc -gnatv"}. If several
8716 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8717 is taken into account. However, all the additional switches are also taken
8718 into account. Thus,
8719 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8720 @option{--GCC="bar -x -y -z -t"}.
8721
8722 @item --LINK=@var{name}
8723 @cindex @option{--LINK=} (@command{gnatlink})
8724 @var{name} is the name of the linker to be invoked. This is especially
8725 useful in mixed language programs since languages such as C++ require
8726 their own linker to be used. When this switch is omitted, the default
8727 name for the linker is @command{gcc}. When this switch is used, the
8728 specified linker is called instead of @command{gcc} with exactly the same
8729 parameters that would have been passed to @command{gcc} so if the desired
8730 linker requires different parameters it is necessary to use a wrapper
8731 script that massages the parameters before invoking the real linker. It
8732 may be useful to control the exact invocation by using the verbose
8733 switch.
8734
8735 @end ifclear
8736
8737 @ifset vms
8738 @item /DEBUG=TRACEBACK
8739 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
8740 This qualifier causes sufficient information to be included in the
8741 executable file to allow a traceback, but does not include the full
8742 symbol information needed by the debugger.
8743
8744 @item /IDENTIFICATION="<string>"
8745 @code{"<string>"} specifies the string to be stored in the image file
8746 identification field in the image header.
8747 It overrides any pragma @code{Ident} specified string.
8748
8749 @item /NOINHIBIT-EXEC
8750 Generate the executable file even if there are linker warnings.
8751
8752 @item /NOSTART_FILES
8753 Don't link in the object file containing the ``main'' transfer address.
8754 Used when linking with a foreign language main program compiled with an
8755 HP compiler.
8756
8757 @item /STATIC
8758 Prefer linking with object libraries over sharable images, even without
8759 /DEBUG.
8760 @end ifset
8761
8762 @end table
8763
8764 @node The GNAT Make Program gnatmake
8765 @chapter The GNAT Make Program @command{gnatmake}
8766 @findex gnatmake
8767
8768 @menu
8769 * Running gnatmake::
8770 * Switches for gnatmake::
8771 * Mode Switches for gnatmake::
8772 * Notes on the Command Line::
8773 * How gnatmake Works::
8774 * Examples of gnatmake Usage::
8775 @end menu
8776 @noindent
8777 A typical development cycle when working on an Ada program consists of
8778 the following steps:
8779
8780 @enumerate
8781 @item
8782 Edit some sources to fix bugs.
8783
8784 @item
8785 Add enhancements.
8786
8787 @item
8788 Compile all sources affected.
8789
8790 @item
8791 Rebind and relink.
8792
8793 @item
8794 Test.
8795 @end enumerate
8796
8797 @noindent
8798 The third step can be tricky, because not only do the modified files
8799 @cindex Dependency rules
8800 have to be compiled, but any files depending on these files must also be
8801 recompiled. The dependency rules in Ada can be quite complex, especially
8802 in the presence of overloading, @code{use} clauses, generics and inlined
8803 subprograms.
8804
8805 @command{gnatmake} automatically takes care of the third and fourth steps
8806 of this process. It determines which sources need to be compiled,
8807 compiles them, and binds and links the resulting object files.
8808
8809 Unlike some other Ada make programs, the dependencies are always
8810 accurately recomputed from the new sources. The source based approach of
8811 the GNAT compilation model makes this possible. This means that if
8812 changes to the source program cause corresponding changes in
8813 dependencies, they will always be tracked exactly correctly by
8814 @command{gnatmake}.
8815
8816 @node Running gnatmake
8817 @section Running @command{gnatmake}
8818
8819 @noindent
8820 The usual form of the @command{gnatmake} command is
8821
8822 @smallexample
8823 $ gnatmake @ovar{switches} @var{file_name}
8824       @ovar{file_names} @ovar{mode_switches}
8825 @end smallexample
8826
8827 @noindent
8828 The only required argument is one @var{file_name}, which specifies
8829 a compilation unit that is a main program. Several @var{file_names} can be
8830 specified: this will result in several executables being built.
8831 If @code{switches} are present, they can be placed before the first
8832 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8833 If @var{mode_switches} are present, they must always be placed after
8834 the last @var{file_name} and all @code{switches}.
8835
8836 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
8837 extension may be omitted from the @var{file_name} arguments. However, if
8838 you are using non-standard extensions, then it is required that the
8839 extension be given. A relative or absolute directory path can be
8840 specified in a @var{file_name}, in which case, the input source file will
8841 be searched for in the specified directory only. Otherwise, the input
8842 source file will first be searched in the directory where
8843 @command{gnatmake} was invoked and if it is not found, it will be search on
8844 the source path of the compiler as described in
8845 @ref{Search Paths and the Run-Time Library (RTL)}.
8846
8847 All @command{gnatmake} output (except when you specify
8848 @option{^-M^/DEPENDENCIES_LIST^}) is to
8849 @file{stderr}. The output produced by the
8850 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8851 @file{stdout}.
8852
8853 @node Switches for gnatmake
8854 @section Switches for @command{gnatmake}
8855
8856 @noindent
8857 You may specify any of the following switches to @command{gnatmake}:
8858
8859 @table @option
8860 @c !sort!
8861
8862 @item --version
8863 @cindex @option{--version} @command{gnatmake}
8864 Display Copyright and version, then exit disregarding all other options.
8865
8866 @item --help
8867 @cindex @option{--help} @command{gnatmake}
8868 If @option{--version} was not used, display usage, then exit disregarding
8869 all other options.
8870
8871 @ifclear vms
8872 @item --GCC=@var{compiler_name}
8873 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
8874 Program used for compiling. The default is `@command{gcc}'. You need to use
8875 quotes around @var{compiler_name} if @code{compiler_name} contains
8876 spaces or other separator characters. As an example @option{--GCC="foo -x
8877 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
8878 compiler. A limitation of this syntax is that the name and path name of
8879 the executable itself must not include any embedded spaces. Note that
8880 switch @option{-c} is always inserted after your command name. Thus in the
8881 above example the compiler command that will be used by @command{gnatmake}
8882 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
8883 used, only the last @var{compiler_name} is taken into account. However,
8884 all the additional switches are also taken into account. Thus,
8885 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8886 @option{--GCC="bar -x -y -z -t"}.
8887
8888 @item --GNATBIND=@var{binder_name}
8889 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
8890 Program used for binding. The default is `@code{gnatbind}'. You need to
8891 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8892 or other separator characters. As an example @option{--GNATBIND="bar -x
8893 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
8894 binder. Binder switches that are normally appended by @command{gnatmake}
8895 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8896 A limitation of this syntax is that the name and path name of the executable
8897 itself must not include any embedded spaces.
8898
8899 @item --GNATLINK=@var{linker_name}
8900 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
8901 Program used for linking. The default is `@command{gnatlink}'. You need to
8902 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8903 or other separator characters. As an example @option{--GNATLINK="lan -x
8904 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
8905 linker. Linker switches that are normally appended by @command{gnatmake} to
8906 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
8907 A limitation of this syntax is that the name and path name of the executable
8908 itself must not include any embedded spaces.
8909
8910 @end ifclear
8911
8912 @item ^-a^/ALL_FILES^
8913 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
8914 Consider all files in the make process, even the GNAT internal system
8915 files (for example, the predefined Ada library files), as well as any
8916 locked files. Locked files are files whose ALI file is write-protected.
8917 By default,
8918 @command{gnatmake} does not check these files,
8919 because the assumption is that the GNAT internal files are properly up
8920 to date, and also that any write protected ALI files have been properly
8921 installed. Note that if there is an installation problem, such that one
8922 of these files is not up to date, it will be properly caught by the
8923 binder.
8924 You may have to specify this switch if you are working on GNAT
8925 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8926 in conjunction with @option{^-f^/FORCE_COMPILE^}
8927 if you need to recompile an entire application,
8928 including run-time files, using special configuration pragmas,
8929 such as a @code{Normalize_Scalars} pragma.
8930
8931 By default
8932 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8933 internal files with
8934 @ifclear vms
8935 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8936 @end ifclear
8937 @ifset vms
8938 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8939 @end ifset
8940
8941 @item ^-b^/ACTIONS=BIND^
8942 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
8943 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8944 compilation and binding, but no link.
8945 Can be combined with @option{^-l^/ACTIONS=LINK^}
8946 to do binding and linking. When not combined with
8947 @option{^-c^/ACTIONS=COMPILE^}
8948 all the units in the closure of the main program must have been previously
8949 compiled and must be up to date. The root unit specified by @var{file_name}
8950 may be given without extension, with the source extension or, if no GNAT
8951 Project File is specified, with the ALI file extension.
8952
8953 @item ^-c^/ACTIONS=COMPILE^
8954 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
8955 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8956 is also specified. Do not perform linking, except if both
8957 @option{^-b^/ACTIONS=BIND^} and
8958 @option{^-l^/ACTIONS=LINK^} are also specified.
8959 If the root unit specified by @var{file_name} is not a main unit, this is the
8960 default. Otherwise @command{gnatmake} will attempt binding and linking
8961 unless all objects are up to date and the executable is more recent than
8962 the objects.
8963
8964 @item ^-C^/MAPPING^
8965 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
8966 Use a temporary mapping file. A mapping file is a way to communicate to the
8967 compiler two mappings: from unit names to file names (without any directory
8968 information) and from file names to path names (with full directory
8969 information). These mappings are used by the compiler to short-circuit the path
8970 search. When @command{gnatmake} is invoked with this switch, it will create
8971 a temporary mapping file, initially populated by the project manager,
8972 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8973 Each invocation of the compiler will add the newly accessed sources to the
8974 mapping file. This will improve the source search during the next invocation
8975 of the compiler.
8976
8977 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8978 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
8979 Use a specific mapping file. The file, specified as a path name (absolute or
8980 relative) by this switch, should already exist, otherwise the switch is
8981 ineffective. The specified mapping file will be communicated to the compiler.
8982 This switch is not compatible with a project file
8983 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8984 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8985
8986 @item ^-d^/DISPLAY_PROGRESS^
8987 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
8988 Display progress for each source, up to date or not, as a single line
8989
8990 @smallexample
8991 completed x out of y (zz%)
8992 @end smallexample
8993
8994 If the file needs to be compiled this is displayed after the invocation of
8995 the compiler. These lines are displayed even in quiet output mode.
8996
8997 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8998 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
8999 Put all object files and ALI file in directory @var{dir}.
9000 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9001 and ALI files go in the current working directory.
9002
9003 This switch cannot be used when using a project file.
9004
9005 @ifclear vms
9006 @item -eL
9007 @cindex @option{-eL} (@command{gnatmake})
9008 Follow all symbolic links when processing project files.
9009 @end ifclear
9010
9011 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9012 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9013 Output the commands for the compiler, the binder and the linker
9014 on ^standard output^SYS$OUTPUT^,
9015 instead of ^standard error^SYS$ERROR^.
9016
9017 @item ^-f^/FORCE_COMPILE^
9018 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9019 Force recompilations. Recompile all sources, even though some object
9020 files may be up to date, but don't recompile predefined or GNAT internal
9021 files or locked files (files with a write-protected ALI file),
9022 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9023
9024 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9025 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9026 When using project files, if some errors or warnings are detected during
9027 parsing and verbose mode is not in effect (no use of switch
9028 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9029 file, rather than its simple file name.
9030
9031 @item ^-g^/DEBUG^
9032 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9033 Enable debugging. This switch is simply passed to the compiler and to the
9034 linker.
9035
9036 @item ^-i^/IN_PLACE^
9037 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9038 In normal mode, @command{gnatmake} compiles all object files and ALI files
9039 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9040 then instead object files and ALI files that already exist are overwritten
9041 in place. This means that once a large project is organized into separate
9042 directories in the desired manner, then @command{gnatmake} will automatically
9043 maintain and update this organization. If no ALI files are found on the
9044 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9045 the new object and ALI files are created in the
9046 directory containing the source being compiled. If another organization
9047 is desired, where objects and sources are kept in different directories,
9048 a useful technique is to create dummy ALI files in the desired directories.
9049 When detecting such a dummy file, @command{gnatmake} will be forced to
9050 recompile the corresponding source file, and it will be put the resulting
9051 object and ALI files in the directory where it found the dummy file.
9052
9053 @item ^-j^/PROCESSES=^@var{n}
9054 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9055 @cindex Parallel make
9056 Use @var{n} processes to carry out the (re)compilations. On a
9057 multiprocessor machine compilations will occur in parallel. In the
9058 event of compilation errors, messages from various compilations might
9059 get interspersed (but @command{gnatmake} will give you the full ordered
9060 list of failing compiles at the end). If this is problematic, rerun
9061 the make process with n set to 1 to get a clean list of messages.
9062
9063 @item ^-k^/CONTINUE_ON_ERROR^
9064 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9065 Keep going. Continue as much as possible after a compilation error. To
9066 ease the programmer's task in case of compilation errors, the list of
9067 sources for which the compile fails is given when @command{gnatmake}
9068 terminates.
9069
9070 If @command{gnatmake} is invoked with several @file{file_names} and with this
9071 switch, if there are compilation errors when building an executable,
9072 @command{gnatmake} will not attempt to build the following executables.
9073
9074 @item ^-l^/ACTIONS=LINK^
9075 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9076 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9077 and linking. Linking will not be performed if combined with
9078 @option{^-c^/ACTIONS=COMPILE^}
9079 but not with @option{^-b^/ACTIONS=BIND^}.
9080 When not combined with @option{^-b^/ACTIONS=BIND^}
9081 all the units in the closure of the main program must have been previously
9082 compiled and must be up to date, and the main program needs to have been bound.
9083 The root unit specified by @var{file_name}
9084 may be given without extension, with the source extension or, if no GNAT
9085 Project File is specified, with the ALI file extension.
9086
9087 @item ^-m^/MINIMAL_RECOMPILATION^
9088 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9089 Specify that the minimum necessary amount of recompilations
9090 be performed. In this mode @command{gnatmake} ignores time
9091 stamp differences when the only
9092 modifications to a source file consist in adding/removing comments,
9093 empty lines, spaces or tabs. This means that if you have changed the
9094 comments in a source file or have simply reformatted it, using this
9095 switch will tell @command{gnatmake} not to recompile files that depend on it
9096 (provided other sources on which these files depend have undergone no
9097 semantic modifications). Note that the debugging information may be
9098 out of date with respect to the sources if the @option{-m} switch causes
9099 a compilation to be switched, so the use of this switch represents a
9100 trade-off between compilation time and accurate debugging information.
9101
9102 @item ^-M^/DEPENDENCIES_LIST^
9103 @cindex Dependencies, producing list
9104 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9105 Check if all objects are up to date. If they are, output the object
9106 dependences to @file{stdout} in a form that can be directly exploited in
9107 a @file{Makefile}. By default, each source file is prefixed with its
9108 (relative or absolute) directory name. This name is whatever you
9109 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9110 and @option{^-I^/SEARCH^} switches. If you use
9111 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9112 @option{^-q^/QUIET^}
9113 (see below), only the source file names,
9114 without relative paths, are output. If you just specify the
9115 @option{^-M^/DEPENDENCIES_LIST^}
9116 switch, dependencies of the GNAT internal system files are omitted. This
9117 is typically what you want. If you also specify
9118 the @option{^-a^/ALL_FILES^} switch,
9119 dependencies of the GNAT internal files are also listed. Note that
9120 dependencies of the objects in external Ada libraries (see switch
9121 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9122 are never reported.
9123
9124 @item ^-n^/DO_OBJECT_CHECK^
9125 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9126 Don't compile, bind, or link. Checks if all objects are up to date.
9127 If they are not, the full name of the first file that needs to be
9128 recompiled is printed.
9129 Repeated use of this option, followed by compiling the indicated source
9130 file, will eventually result in recompiling all required units.
9131
9132 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9133 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9134 Output executable name. The name of the final executable program will be
9135 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9136 name for the executable will be the name of the input file in appropriate form
9137 for an executable file on the host system.
9138
9139 This switch cannot be used when invoking @command{gnatmake} with several
9140 @file{file_names}.
9141
9142 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9143 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9144 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9145 automatically missing object directories, library directories and exec
9146 directories.
9147
9148 @item ^-P^/PROJECT_FILE=^@var{project}
9149 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9150 Use project file @var{project}. Only one such switch can be used.
9151 @xref{gnatmake and Project Files}.
9152
9153 @item ^-q^/QUIET^
9154 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9155 Quiet. When this flag is not set, the commands carried out by
9156 @command{gnatmake} are displayed.
9157
9158 @item ^-s^/SWITCH_CHECK/^
9159 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9160 Recompile if compiler switches have changed since last compilation.
9161 All compiler switches but -I and -o are taken into account in the
9162 following way:
9163 orders between different ``first letter'' switches are ignored, but
9164 orders between same switches are taken into account. For example,
9165 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9166 is equivalent to @option{-O -g}.
9167
9168 This switch is recommended when Integrated Preprocessing is used.
9169
9170 @item ^-u^/UNIQUE^
9171 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9172 Unique. Recompile at most the main files. It implies -c. Combined with
9173 -f, it is equivalent to calling the compiler directly. Note that using
9174 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9175 (@pxref{Project Files and Main Subprograms}).
9176
9177 @item ^-U^/ALL_PROJECTS^
9178 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9179 When used without a project file or with one or several mains on the command
9180 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9181 on the command line, all sources of all project files are checked and compiled
9182 if not up to date, and libraries are rebuilt, if necessary.
9183
9184 @item ^-v^/REASONS^
9185 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9186 Verbose. Display the reason for all recompilations @command{gnatmake}
9187 decides are necessary, with the highest verbosity level.
9188
9189 @item ^-vl^/LOW_VERBOSITY^
9190 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9191 Verbosity level Low. Display fewer lines than in verbosity Medium.
9192
9193 @item ^-vm^/MEDIUM_VERBOSITY^
9194 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9195 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9196
9197 @item ^-vh^/HIGH_VERBOSITY^
9198 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9199 Verbosity level High. Equivalent to ^-v^/REASONS^.
9200
9201 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9202 Indicate the verbosity of the parsing of GNAT project files.
9203 @xref{Switches Related to Project Files}.
9204
9205 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9206 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9207 Indicate that sources that are not part of any Project File may be compiled.
9208 Normally, when using Project Files, only sources that are part of a Project
9209 File may be compile. When this switch is used, a source outside of all Project
9210 Files may be compiled. The ALI file and the object file will be put in the
9211 object directory of the main Project. The compilation switches used will only
9212 be those specified on the command line. Even when
9213 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9214 command line need to be sources of a project file.
9215
9216 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9217 Indicate that external variable @var{name} has the value @var{value}.
9218 The Project Manager will use this value for occurrences of
9219 @code{external(name)} when parsing the project file.
9220 @xref{Switches Related to Project Files}.
9221
9222 @item ^-z^/NOMAIN^
9223 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9224 No main subprogram. Bind and link the program even if the unit name
9225 given on the command line is a package name. The resulting executable
9226 will execute the elaboration routines of the package and its closure,
9227 then the finalization routines.
9228
9229 @end table
9230
9231 @table @asis
9232 @item @command{gcc} @asis{switches}
9233 @ifclear vms
9234 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9235 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9236 @end ifclear
9237 @ifset vms
9238 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9239 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9240 automatically treated as a compiler switch, and passed on to all
9241 compilations that are carried out.
9242 @end ifset
9243 @end table
9244
9245 @noindent
9246 Source and library search path switches:
9247
9248 @table @option
9249 @c !sort!
9250 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9251 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9252 When looking for source files also look in directory @var{dir}.
9253 The order in which source files search is undertaken is
9254 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9255
9256 @item ^-aL^/SKIP_MISSING=^@var{dir}
9257 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9258 Consider @var{dir} as being an externally provided Ada library.
9259 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9260 files have been located in directory @var{dir}. This allows you to have
9261 missing bodies for the units in @var{dir} and to ignore out of date bodies
9262 for the same units. You still need to specify
9263 the location of the specs for these units by using the switches
9264 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9265 or @option{^-I^/SEARCH=^@var{dir}}.
9266 Note: this switch is provided for compatibility with previous versions
9267 of @command{gnatmake}. The easier method of causing standard libraries
9268 to be excluded from consideration is to write-protect the corresponding
9269 ALI files.
9270
9271 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9272 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9273 When searching for library and object files, look in directory
9274 @var{dir}. The order in which library files are searched is described in
9275 @ref{Search Paths for gnatbind}.
9276
9277 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9278 @cindex Search paths, for @command{gnatmake}
9279 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9280 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9281 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9282
9283 @item ^-I^/SEARCH=^@var{dir}
9284 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9285 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9286 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9287
9288 @item ^-I-^/NOCURRENT_DIRECTORY^
9289 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9290 @cindex Source files, suppressing search
9291 Do not look for source files in the directory containing the source
9292 file named in the command line.
9293 Do not look for ALI or object files in the directory
9294 where @command{gnatmake} was invoked.
9295
9296 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9297 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9298 @cindex Linker libraries
9299 Add directory @var{dir} to the list of directories in which the linker
9300 will search for libraries. This is equivalent to
9301 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9302 @ifclear vms
9303 Furthermore, under Windows, the sources pointed to by the libraries path
9304 set in the registry are not searched for.
9305 @end ifclear
9306
9307 @item -nostdinc
9308 @cindex @option{-nostdinc} (@command{gnatmake})
9309 Do not look for source files in the system default directory.
9310
9311 @item -nostdlib
9312 @cindex @option{-nostdlib} (@command{gnatmake})
9313 Do not look for library files in the system default directory.
9314
9315 @item --RTS=@var{rts-path}
9316 @cindex @option{--RTS} (@command{gnatmake})
9317 Specifies the default location of the runtime library. GNAT looks for the
9318 runtime
9319 in the following directories, and stops as soon as a valid runtime is found
9320 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9321 @file{ada_object_path} present):
9322
9323 @itemize @bullet
9324 @item <current directory>/$rts_path
9325
9326 @item <default-search-dir>/$rts_path
9327
9328 @item <default-search-dir>/rts-$rts_path
9329 @end itemize
9330
9331 @noindent
9332 The selected path is handled like a normal RTS path.
9333
9334 @end table
9335
9336 @node Mode Switches for gnatmake
9337 @section Mode Switches for @command{gnatmake}
9338
9339 @noindent
9340 The mode switches (referred to as @code{mode_switches}) allow the
9341 inclusion of switches that are to be passed to the compiler itself, the
9342 binder or the linker. The effect of a mode switch is to cause all
9343 subsequent switches up to the end of the switch list, or up to the next
9344 mode switch, to be interpreted as switches to be passed on to the
9345 designated component of GNAT.
9346
9347 @table @option
9348 @c !sort!
9349 @item -cargs @var{switches}
9350 @cindex @option{-cargs} (@command{gnatmake})
9351 Compiler switches. Here @var{switches} is a list of switches
9352 that are valid switches for @command{gcc}. They will be passed on to
9353 all compile steps performed by @command{gnatmake}.
9354
9355 @item -bargs @var{switches}
9356 @cindex @option{-bargs} (@command{gnatmake})
9357 Binder switches. Here @var{switches} is a list of switches
9358 that are valid switches for @code{gnatbind}. They will be passed on to
9359 all bind steps performed by @command{gnatmake}.
9360
9361 @item -largs @var{switches}
9362 @cindex @option{-largs} (@command{gnatmake})
9363 Linker switches. Here @var{switches} is a list of switches
9364 that are valid switches for @command{gnatlink}. They will be passed on to
9365 all link steps performed by @command{gnatmake}.
9366
9367 @item -margs @var{switches}
9368 @cindex @option{-margs} (@command{gnatmake})
9369 Make switches. The switches are directly interpreted by @command{gnatmake},
9370 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9371 or @option{-largs}.
9372 @end table
9373
9374 @node Notes on the Command Line
9375 @section Notes on the Command Line
9376
9377 @noindent
9378 This section contains some additional useful notes on the operation
9379 of the @command{gnatmake} command.
9380
9381 @itemize @bullet
9382 @item
9383 @cindex Recompilation, by @command{gnatmake}
9384 If @command{gnatmake} finds no ALI files, it recompiles the main program
9385 and all other units required by the main program.
9386 This means that @command{gnatmake}
9387 can be used for the initial compile, as well as during subsequent steps of
9388 the development cycle.
9389
9390 @item
9391 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9392 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9393 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9394 warning.
9395
9396 @item
9397 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9398 is used to specify both source and
9399 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9400 instead if you just want to specify
9401 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9402 if you want to specify library paths
9403 only.
9404
9405 @item
9406 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9407 This may conveniently be used to exclude standard libraries from
9408 consideration and in particular it means that the use of the
9409 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9410 unless @option{^-a^/ALL_FILES^} is also specified.
9411
9412 @item
9413 @command{gnatmake} has been designed to make the use of Ada libraries
9414 particularly convenient. Assume you have an Ada library organized
9415 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9416 of your Ada compilation units,
9417 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9418 specs of these units, but no bodies. Then to compile a unit
9419 stored in @code{main.adb}, which uses this Ada library you would just type
9420
9421 @smallexample
9422 @ifclear vms
9423 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9424 @end ifclear
9425 @ifset vms
9426 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9427            /SKIP_MISSING=@i{[OBJ_DIR]} main
9428 @end ifset
9429 @end smallexample
9430
9431 @item
9432 Using @command{gnatmake} along with the
9433 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9434 switch provides a mechanism for avoiding unnecessary recompilations. Using
9435 this switch,
9436 you can update the comments/format of your
9437 source files without having to recompile everything. Note, however, that
9438 adding or deleting lines in a source files may render its debugging
9439 info obsolete. If the file in question is a spec, the impact is rather
9440 limited, as that debugging info will only be useful during the
9441 elaboration phase of your program. For bodies the impact can be more
9442 significant. In all events, your debugger will warn you if a source file
9443 is more recent than the corresponding object, and alert you to the fact
9444 that the debugging information may be out of date.
9445 @end itemize
9446
9447 @node How gnatmake Works
9448 @section How @command{gnatmake} Works
9449
9450 @noindent
9451 Generally @command{gnatmake} automatically performs all necessary
9452 recompilations and you don't need to worry about how it works. However,
9453 it may be useful to have some basic understanding of the @command{gnatmake}
9454 approach and in particular to understand how it uses the results of
9455 previous compilations without incorrectly depending on them.
9456
9457 First a definition: an object file is considered @dfn{up to date} if the
9458 corresponding ALI file exists and if all the source files listed in the
9459 dependency section of this ALI file have time stamps matching those in
9460 the ALI file. This means that neither the source file itself nor any
9461 files that it depends on have been modified, and hence there is no need
9462 to recompile this file.
9463
9464 @command{gnatmake} works by first checking if the specified main unit is up
9465 to date. If so, no compilations are required for the main unit. If not,
9466 @command{gnatmake} compiles the main program to build a new ALI file that
9467 reflects the latest sources. Then the ALI file of the main unit is
9468 examined to find all the source files on which the main program depends,
9469 and @command{gnatmake} recursively applies the above procedure on all these
9470 files.
9471
9472 This process ensures that @command{gnatmake} only trusts the dependencies
9473 in an existing ALI file if they are known to be correct. Otherwise it
9474 always recompiles to determine a new, guaranteed accurate set of
9475 dependencies. As a result the program is compiled ``upside down'' from what may
9476 be more familiar as the required order of compilation in some other Ada
9477 systems. In particular, clients are compiled before the units on which
9478 they depend. The ability of GNAT to compile in any order is critical in
9479 allowing an order of compilation to be chosen that guarantees that
9480 @command{gnatmake} will recompute a correct set of new dependencies if
9481 necessary.
9482
9483 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9484 imported by several of the executables, it will be recompiled at most once.
9485
9486 Note: when using non-standard naming conventions
9487 (@pxref{Using Other File Names}), changing through a configuration pragmas
9488 file the version of a source and invoking @command{gnatmake} to recompile may
9489 have no effect, if the previous version of the source is still accessible
9490 by @command{gnatmake}. It may be necessary to use the switch
9491 ^-f^/FORCE_COMPILE^.
9492
9493 @node Examples of gnatmake Usage
9494 @section Examples of @command{gnatmake} Usage
9495
9496 @table @code
9497 @item gnatmake hello.adb
9498 Compile all files necessary to bind and link the main program
9499 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9500 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9501
9502 @item gnatmake main1 main2 main3
9503 Compile all files necessary to bind and link the main programs
9504 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9505 (containing unit @code{Main2}) and @file{main3.adb}
9506 (containing unit @code{Main3}) and bind and link the resulting object files
9507 to generate three executable files @file{^main1^MAIN1.EXE^},
9508 @file{^main2^MAIN2.EXE^}
9509 and @file{^main3^MAIN3.EXE^}.
9510
9511 @ifclear vms
9512 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9513 @end ifclear
9514
9515 @ifset vms
9516 @item gnatmake Main_Unit /QUIET
9517 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9518 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9519 @end ifset
9520 Compile all files necessary to bind and link the main program unit
9521 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9522 be done with optimization level 2 and the order of elaboration will be
9523 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9524 displaying commands it is executing.
9525 @end table
9526
9527 @c *************************
9528 @node Improving Performance
9529 @chapter Improving Performance
9530 @cindex Improving performance
9531
9532 @noindent
9533 This chapter presents several topics related to program performance.
9534 It first describes some of the tradeoffs that need to be considered
9535 and some of the techniques for making your program run faster.
9536 It then documents the @command{gnatelim} tool and unused subprogram/data
9537 elimination feature, which can reduce the size of program executables.
9538
9539 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9540 driver (see @ref{The GNAT Driver and Project Files}).
9541
9542 @ifnottex
9543 @menu
9544 * Performance Considerations::
9545 * Text_IO Suggestions::
9546 * Reducing Size of Ada Executables with gnatelim::
9547 * Reducing Size of Executables with unused subprogram/data elimination::
9548 @end menu
9549 @end ifnottex
9550
9551 @c *****************************
9552 @node Performance Considerations
9553 @section Performance Considerations
9554
9555 @noindent
9556 The GNAT system provides a number of options that allow a trade-off
9557 between
9558
9559 @itemize @bullet
9560 @item
9561 performance of the generated code
9562
9563 @item
9564 speed of compilation
9565
9566 @item
9567 minimization of dependences and recompilation
9568
9569 @item
9570 the degree of run-time checking.
9571 @end itemize
9572
9573 @noindent
9574 The defaults (if no options are selected) aim at improving the speed
9575 of compilation and minimizing dependences, at the expense of performance
9576 of the generated code:
9577
9578 @itemize @bullet
9579 @item
9580 no optimization
9581
9582 @item
9583 no inlining of subprogram calls
9584
9585 @item
9586 all run-time checks enabled except overflow and elaboration checks
9587 @end itemize
9588
9589 @noindent
9590 These options are suitable for most program development purposes. This
9591 chapter describes how you can modify these choices, and also provides
9592 some guidelines on debugging optimized code.
9593
9594 @menu
9595 * Controlling Run-Time Checks::
9596 * Use of Restrictions::
9597 * Optimization Levels::
9598 * Debugging Optimized Code::
9599 * Inlining of Subprograms::
9600 * Other Optimization Switches::
9601 * Optimization and Strict Aliasing::
9602
9603 @ifset vms
9604 * Coverage Analysis::
9605 @end ifset
9606 @end menu
9607
9608 @node Controlling Run-Time Checks
9609 @subsection Controlling Run-Time Checks
9610
9611 @noindent
9612 By default, GNAT generates all run-time checks, except integer overflow
9613 checks, stack overflow checks, and checks for access before elaboration on
9614 subprogram calls. The latter are not required in default mode, because all
9615 necessary checking is done at compile time.
9616 @cindex @option{-gnatp} (@command{gcc})
9617 @cindex @option{-gnato} (@command{gcc})
9618 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9619 be modified. @xref{Run-Time Checks}.
9620
9621 Our experience is that the default is suitable for most development
9622 purposes.
9623
9624 We treat integer overflow specially because these
9625 are quite expensive and in our experience are not as important as other
9626 run-time checks in the development process. Note that division by zero
9627 is not considered an overflow check, and divide by zero checks are
9628 generated where required by default.
9629
9630 Elaboration checks are off by default, and also not needed by default, since
9631 GNAT uses a static elaboration analysis approach that avoids the need for
9632 run-time checking. This manual contains a full chapter discussing the issue
9633 of elaboration checks, and if the default is not satisfactory for your use,
9634 you should read this chapter.
9635
9636 For validity checks, the minimal checks required by the Ada Reference
9637 Manual (for case statements and assignments to array elements) are on
9638 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9639 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9640 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9641 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9642 are also suppressed entirely if @option{-gnatp} is used.
9643
9644 @cindex Overflow checks
9645 @cindex Checks, overflow
9646 @findex Suppress
9647 @findex Unsuppress
9648 @cindex pragma Suppress
9649 @cindex pragma Unsuppress
9650 Note that the setting of the switches controls the default setting of
9651 the checks. They may be modified using either @code{pragma Suppress} (to
9652 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9653 checks) in the program source.
9654
9655 @node Use of Restrictions
9656 @subsection Use of Restrictions
9657
9658 @noindent
9659 The use of pragma Restrictions allows you to control which features are
9660 permitted in your program. Apart from the obvious point that if you avoid
9661 relatively expensive features like finalization (enforceable by the use
9662 of pragma Restrictions (No_Finalization), the use of this pragma does not
9663 affect the generated code in most cases.
9664
9665 One notable exception to this rule is that the possibility of task abort
9666 results in some distributed overhead, particularly if finalization or
9667 exception handlers are used. The reason is that certain sections of code
9668 have to be marked as non-abortable.
9669
9670 If you use neither the @code{abort} statement, nor asynchronous transfer
9671 of control (@code{select @dots{} then abort}), then this distributed overhead
9672 is removed, which may have a general positive effect in improving
9673 overall performance.  Especially code involving frequent use of tasking
9674 constructs and controlled types will show much improved performance.
9675 The relevant restrictions pragmas are
9676
9677 @smallexample @c ada
9678    pragma Restrictions (No_Abort_Statements);
9679    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9680 @end smallexample
9681
9682 @noindent
9683 It is recommended that these restriction pragmas be used if possible. Note
9684 that this also means that you can write code without worrying about the
9685 possibility of an immediate abort at any point.
9686
9687 @node Optimization Levels
9688 @subsection Optimization Levels
9689 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
9690
9691 @noindent
9692 Without any optimization ^option,^qualifier,^
9693 the compiler's goal is to reduce the cost of
9694 compilation and to make debugging produce the expected results.
9695 Statements are independent: if you stop the program with a breakpoint between
9696 statements, you can then assign a new value to any variable or change
9697 the program counter to any other statement in the subprogram and get exactly
9698 the results you would expect from the source code.
9699
9700 Turning on optimization makes the compiler attempt to improve the
9701 performance and/or code size at the expense of compilation time and
9702 possibly the ability to debug the program.
9703
9704 If you use multiple
9705 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
9706 the last such option is the one that is effective.
9707
9708 @noindent
9709 The default is optimization off. This results in the fastest compile
9710 times, but GNAT makes absolutely no attempt to optimize, and the
9711 generated programs are considerably larger and slower than when
9712 optimization is enabled. You can use the
9713 @ifclear vms
9714 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
9715 @option{-O2}, @option{-O3}, and @option{-Os})
9716 @end ifclear
9717 @ifset vms
9718 @code{OPTIMIZE} qualifier
9719 @end ifset
9720 to @command{gcc} to control the optimization level:
9721
9722 @table @option
9723 @item ^-O0^/OPTIMIZE=NONE^
9724 No optimization (the default);
9725 generates unoptimized code but has
9726 the fastest compilation time.
9727
9728 Note that many other compilers do fairly extensive optimization
9729 even if ``no optimization'' is specified. With gcc, it is
9730 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
9731 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
9732 really does mean no optimization at all. This difference between
9733 gcc and other compilers should be kept in mind when doing
9734 performance comparisons.
9735
9736 @item ^-O1^/OPTIMIZE=SOME^
9737 Moderate optimization;
9738 optimizes reasonably well but does not
9739 degrade compilation time significantly.
9740
9741 @item ^-O2^/OPTIMIZE=ALL^
9742 @ifset vms
9743 @itemx /OPTIMIZE=DEVELOPMENT
9744 @end ifset
9745 Full optimization;
9746 generates highly optimized code and has
9747 the slowest compilation time.
9748
9749 @item ^-O3^/OPTIMIZE=INLINING^
9750 Full optimization as in @option{-O2},
9751 and also attempts automatic inlining of small
9752 subprograms within a unit (@pxref{Inlining of Subprograms}).
9753
9754 @item ^-Os^/OPTIMIZE=SPACE^
9755 Optimize space usage of resulting program.
9756 @end table
9757
9758 @noindent
9759 Higher optimization levels perform more global transformations on the
9760 program and apply more expensive analysis algorithms in order to generate
9761 faster and more compact code. The price in compilation time, and the
9762 resulting improvement in execution time,
9763 both depend on the particular application and the hardware environment.
9764 You should experiment to find the best level for your application.
9765
9766 Since the precise set of optimizations done at each level will vary from
9767 release to release (and sometime from target to target), it is best to think
9768 of the optimization settings in general terms.
9769 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
9770 the GNU Compiler Collection (GCC)}, for details about
9771 ^the @option{-O} settings and a number of @option{-f} options that^how to^
9772 individually enable or disable specific optimizations.
9773
9774 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
9775 been tested extensively at all optimization levels. There are some bugs
9776 which appear only with optimization turned on, but there have also been
9777 bugs which show up only in @emph{unoptimized} code. Selecting a lower
9778 level of optimization does not improve the reliability of the code
9779 generator, which in practice is highly reliable at all optimization
9780 levels.
9781
9782 Note regarding the use of @option{-O3}: The use of this optimization level
9783 is generally discouraged with GNAT, since it often results in larger
9784 executables which run more slowly. See further discussion of this point
9785 in @ref{Inlining of Subprograms}.
9786
9787 @node Debugging Optimized Code
9788 @subsection Debugging Optimized Code
9789 @cindex Debugging optimized code
9790 @cindex Optimization and debugging
9791
9792 @noindent
9793 Although it is possible to do a reasonable amount of debugging at
9794 @ifclear vms
9795 nonzero optimization levels,
9796 the higher the level the more likely that
9797 @end ifclear
9798 @ifset vms
9799 @option{/OPTIMIZE} settings other than @code{NONE},
9800 such settings will make it more likely that
9801 @end ifset
9802 source-level constructs will have been eliminated by optimization.
9803 For example, if a loop is strength-reduced, the loop
9804 control variable may be completely eliminated and thus cannot be
9805 displayed in the debugger.
9806 This can only happen at @option{-O2} or @option{-O3}.
9807 Explicit temporary variables that you code might be eliminated at
9808 ^level^setting^ @option{-O1} or higher.
9809
9810 The use of the @option{^-g^/DEBUG^} switch,
9811 @cindex @option{^-g^/DEBUG^} (@command{gcc})
9812 which is needed for source-level debugging,
9813 affects the size of the program executable on disk,
9814 and indeed the debugging information can be quite large.
9815 However, it has no effect on the generated code (and thus does not
9816 degrade performance)
9817
9818 Since the compiler generates debugging tables for a compilation unit before
9819 it performs optimizations, the optimizing transformations may invalidate some
9820 of the debugging data.  You therefore need to anticipate certain
9821 anomalous situations that may arise while debugging optimized code.
9822 These are the most common cases:
9823
9824 @enumerate
9825 @item
9826 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
9827 commands show
9828 the PC bouncing back and forth in the code.  This may result from any of
9829 the following optimizations:
9830
9831 @itemize @bullet
9832 @item
9833 @i{Common subexpression elimination:} using a single instance of code for a
9834 quantity that the source computes several times.  As a result you
9835 may not be able to stop on what looks like a statement.
9836
9837 @item
9838 @i{Invariant code motion:} moving an expression that does not change within a
9839 loop, to the beginning of the loop.
9840
9841 @item
9842 @i{Instruction scheduling:} moving instructions so as to
9843 overlap loads and stores (typically) with other code, or in
9844 general to move computations of values closer to their uses. Often
9845 this causes you to pass an assignment statement without the assignment
9846 happening and then later bounce back to the statement when the
9847 value is actually needed.  Placing a breakpoint on a line of code
9848 and then stepping over it may, therefore, not always cause all the
9849 expected side-effects.
9850 @end itemize
9851
9852 @item
9853 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
9854 two identical pieces of code are merged and the program counter suddenly
9855 jumps to a statement that is not supposed to be executed, simply because
9856 it (and the code following) translates to the same thing as the code
9857 that @emph{was} supposed to be executed.  This effect is typically seen in
9858 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
9859 a @code{break} in a C @code{^switch^switch^} statement.
9860
9861 @item
9862 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
9863 There are various reasons for this effect:
9864
9865 @itemize @bullet
9866 @item
9867 In a subprogram prologue, a parameter may not yet have been moved to its
9868 ``home''.
9869
9870 @item
9871 A variable may be dead, and its register re-used.  This is
9872 probably the most common cause.
9873
9874 @item
9875 As mentioned above, the assignment of a value to a variable may
9876 have been moved.
9877
9878 @item
9879 A variable may be eliminated entirely by value propagation or
9880 other means.  In this case, GCC may incorrectly generate debugging
9881 information for the variable
9882 @end itemize
9883
9884 @noindent
9885 In general, when an unexpected value appears for a local variable or parameter
9886 you should first ascertain if that value was actually computed by
9887 your program, as opposed to being incorrectly reported by the debugger.
9888 Record fields or
9889 array elements in an object designated by an access value
9890 are generally less of a problem, once you have ascertained that the access
9891 value is sensible.
9892 Typically, this means checking variables in the preceding code and in the
9893 calling subprogram to verify that the value observed is explainable from other
9894 values (one must apply the procedure recursively to those
9895 other values); or re-running the code and stopping a little earlier
9896 (perhaps before the call) and stepping to better see how the variable obtained
9897 the value in question; or continuing to step @emph{from} the point of the
9898 strange value to see if code motion had simply moved the variable's
9899 assignments later.
9900 @end enumerate
9901
9902 @noindent
9903 In light of such anomalies, a recommended technique is to use @option{-O0}
9904 early in the software development cycle, when extensive debugging capabilities
9905 are most needed, and then move to @option{-O1} and later @option{-O2} as
9906 the debugger becomes less critical.
9907 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9908 a release management issue.
9909 @ifclear vms
9910 Note that if you use @option{-g} you can then use the @command{strip} program
9911 on the resulting executable,
9912 which removes both debugging information and global symbols.
9913 @end ifclear
9914
9915 @node Inlining of Subprograms
9916 @subsection Inlining of Subprograms
9917
9918 @noindent
9919 A call to a subprogram in the current unit is inlined if all the
9920 following conditions are met:
9921
9922 @itemize @bullet
9923 @item
9924 The optimization level is at least @option{-O1}.
9925
9926 @item
9927 The called subprogram is suitable for inlining: It must be small enough
9928 and not contain something that @command{gcc} cannot support in inlined
9929 subprograms.
9930
9931 @item
9932 @cindex pragma Inline
9933 @findex Inline
9934 Either @code{pragma Inline} applies to the subprogram, or it is local
9935 to the unit and called once from within it, or it is small and automatic
9936 inlining (optimization level @option{-O3}) is specified.
9937 @end itemize
9938
9939 @noindent
9940 Calls to subprograms in @code{with}'ed units are normally not inlined.
9941 To achieve actual inlining (that is, replacement of the call by the code
9942 in the body of the subprogram), the following conditions must all be true.
9943
9944 @itemize @bullet
9945 @item
9946 The optimization level is at least @option{-O1}.
9947
9948 @item
9949 The called subprogram is suitable for inlining: It must be small enough
9950 and not contain something that @command{gcc} cannot support in inlined
9951 subprograms.
9952
9953 @item
9954 The call appears in a body (not in a package spec).
9955
9956 @item
9957 There is a @code{pragma Inline} for the subprogram.
9958
9959 @item
9960 @cindex @option{-gnatn} (@command{gcc})
9961 The @option{^-gnatn^/INLINE^} switch
9962 is used in the @command{gcc} command line
9963 @end itemize
9964
9965 Even if all these conditions are met, it may not be possible for
9966 the compiler to inline the call, due to the length of the body,
9967 or features in the body that make it impossible for the compiler
9968 to do the inlining.
9969
9970 Note that specifying the @option{-gnatn} switch causes additional
9971 compilation dependencies. Consider the following:
9972
9973 @smallexample @c ada
9974 @cartouche
9975 package R is
9976    procedure Q;
9977    pragma Inline (Q);
9978 end R;
9979 package body R is
9980    @dots{}
9981 end R;
9982
9983 with R;
9984 procedure Main is
9985 begin
9986    @dots{}
9987    R.Q;
9988 end Main;
9989 @end cartouche
9990 @end smallexample
9991
9992 @noindent
9993 With the default behavior (no @option{-gnatn} switch specified), the
9994 compilation of the @code{Main} procedure depends only on its own source,
9995 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9996 means that editing the body of @code{R} does not require recompiling
9997 @code{Main}.
9998
9999 On the other hand, the call @code{R.Q} is not inlined under these
10000 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10001 is compiled, the call will be inlined if the body of @code{Q} is small
10002 enough, but now @code{Main} depends on the body of @code{R} in
10003 @file{r.adb} as well as on the spec. This means that if this body is edited,
10004 the main program must be recompiled. Note that this extra dependency
10005 occurs whether or not the call is in fact inlined by @command{gcc}.
10006
10007 The use of front end inlining with @option{-gnatN} generates similar
10008 additional dependencies.
10009
10010 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10011 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10012 can be used to prevent
10013 all inlining. This switch overrides all other conditions and ensures
10014 that no inlining occurs. The extra dependences resulting from
10015 @option{-gnatn} will still be active, even if
10016 this switch is used to suppress the resulting inlining actions.
10017
10018 @cindex @option{-fno-inline-functions} (@command{gcc})
10019 Note: The @option{-fno-inline-functions} switch can be used to prevent
10020 automatic inlining of small subprograms if @option{-O3} is used.
10021
10022 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10023 Note: The @option{-fno-inline-functions-called-once} switch
10024 can be used to prevent inlining of subprograms local to the unit
10025 and called once from within it if @option{-O1} is used.
10026
10027 Note regarding the use of @option{-O3}: There is no difference in inlining
10028 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10029 pragma @code{Inline} assuming the use of @option{-gnatn}
10030 or @option{-gnatN} (the switches that activate inlining). If you have used
10031 pragma @code{Inline} in appropriate cases, then it is usually much better
10032 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10033 in this case only has the effect of inlining subprograms you did not
10034 think should be inlined. We often find that the use of @option{-O3} slows
10035 down code by performing excessive inlining, leading to increased instruction
10036 cache pressure from the increased code size. So the bottom line here is
10037 that you should not automatically assume that @option{-O3} is better than
10038 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10039 it actually improves performance.
10040
10041 @node Other Optimization Switches
10042 @subsection Other Optimization Switches
10043 @cindex Optimization Switches
10044
10045 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10046 @command{gcc} optimization switches are potentially usable. These switches
10047 have not been extensively tested with GNAT but can generally be expected
10048 to work. Examples of switches in this category are
10049 @option{-funroll-loops} and
10050 the various target-specific @option{-m} options (in particular, it has been
10051 observed that @option{-march=pentium4} can significantly improve performance
10052 on appropriate machines). For full details of these switches, see
10053 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10054 the GNU Compiler Collection (GCC)}.
10055
10056 @node Optimization and Strict Aliasing
10057 @subsection Optimization and Strict Aliasing
10058 @cindex Aliasing
10059 @cindex Strict Aliasing
10060 @cindex No_Strict_Aliasing
10061
10062 @noindent
10063 The strong typing capabilities of Ada allow an optimizer to generate
10064 efficient code in situations where other languages would be forced to
10065 make worst case assumptions preventing such optimizations. Consider
10066 the following example:
10067
10068 @smallexample @c ada
10069 @cartouche
10070 procedure R is
10071    type Int1 is new Integer;
10072    type Int2 is new Integer;
10073    type Int1A is access Int1;
10074    type Int2A is access Int2;
10075    Int1V : Int1A;
10076    Int2V : Int2A;
10077    @dots{}
10078
10079 begin
10080    @dots{}
10081    for J in Data'Range loop
10082       if Data (J) = Int1V.all then
10083          Int2V.all := Int2V.all + 1;
10084       end if;
10085    end loop;
10086    @dots{}
10087 end R;
10088 @end cartouche
10089 @end smallexample
10090
10091 @noindent
10092 In this example, since the variable @code{Int1V} can only access objects
10093 of type @code{Int1}, and @code{Int2V} can only access objects of type
10094 @code{Int2}, there is no possibility that the assignment to
10095 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10096 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10097 for all iterations of the loop and avoid the extra memory reference
10098 required to dereference it each time through the loop.
10099
10100 This kind of optimization, called strict aliasing analysis, is
10101 triggered by specifying an optimization level of @option{-O2} or
10102 higher and allows @code{GNAT} to generate more efficient code
10103 when access values are involved.
10104
10105 However, although this optimization is always correct in terms of
10106 the formal semantics of the Ada Reference Manual, difficulties can
10107 arise if features like @code{Unchecked_Conversion} are used to break
10108 the typing system. Consider the following complete program example:
10109
10110 @smallexample @c ada
10111 @cartouche
10112 package p1 is
10113    type int1 is new integer;
10114    type int2 is new integer;
10115    type a1 is access int1;
10116    type a2 is access int2;
10117 end p1;
10118
10119 with p1; use p1;
10120 package p2 is
10121    function to_a2 (Input : a1) return a2;
10122 end p2;
10123
10124 with Unchecked_Conversion;
10125 package body p2 is
10126    function to_a2 (Input : a1) return a2 is
10127       function to_a2u is
10128         new Unchecked_Conversion (a1, a2);
10129    begin
10130       return to_a2u (Input);
10131    end to_a2;
10132 end p2;
10133
10134 with p2; use p2;
10135 with p1; use p1;
10136 with Text_IO; use Text_IO;
10137 procedure m is
10138    v1 : a1 := new int1;
10139    v2 : a2 := to_a2 (v1);
10140 begin
10141    v1.all := 1;
10142    v2.all := 0;
10143    put_line (int1'image (v1.all));
10144 end;
10145 @end cartouche
10146 @end smallexample
10147
10148 @noindent
10149 This program prints out 0 in @option{-O0} or @option{-O1}
10150 mode, but it prints out 1 in @option{-O2} mode. That's
10151 because in strict aliasing mode, the compiler can and
10152 does assume that the assignment to @code{v2.all} could not
10153 affect the value of @code{v1.all}, since different types
10154 are involved.
10155
10156 This behavior is not a case of non-conformance with the standard, since
10157 the Ada RM specifies that an unchecked conversion where the resulting
10158 bit pattern is not a correct value of the target type can result in an
10159 abnormal value and attempting to reference an abnormal value makes the
10160 execution of a program erroneous.  That's the case here since the result
10161 does not point to an object of type @code{int2}.  This means that the
10162 effect is entirely unpredictable.
10163
10164 However, although that explanation may satisfy a language
10165 lawyer, in practice an applications programmer expects an
10166 unchecked conversion involving pointers to create true
10167 aliases and the behavior of printing 1 seems plain wrong.
10168 In this case, the strict aliasing optimization is unwelcome.
10169
10170 Indeed the compiler recognizes this possibility, and the
10171 unchecked conversion generates a warning:
10172
10173 @smallexample
10174 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10175 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10176 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10177 @end smallexample
10178
10179 @noindent
10180 Unfortunately the problem is recognized when compiling the body of
10181 package @code{p2}, but the actual "bad" code is generated while
10182 compiling the body of @code{m} and this latter compilation does not see
10183 the suspicious @code{Unchecked_Conversion}.
10184
10185 As implied by the warning message, there are approaches you can use to
10186 avoid the unwanted strict aliasing optimization in a case like this.
10187
10188 One possibility is to simply avoid the use of @option{-O2}, but
10189 that is a bit drastic, since it throws away a number of useful
10190 optimizations that do not involve strict aliasing assumptions.
10191
10192 A less drastic approach is to compile the program using the
10193 option @option{-fno-strict-aliasing}. Actually it is only the
10194 unit containing the dereferencing of the suspicious pointer
10195 that needs to be compiled. So in this case, if we compile
10196 unit @code{m} with this switch, then we get the expected
10197 value of zero printed. Analyzing which units might need
10198 the switch can be painful, so a more reasonable approach
10199 is to compile the entire program with options @option{-O2}
10200 and @option{-fno-strict-aliasing}. If the performance is
10201 satisfactory with this combination of options, then the
10202 advantage is that the entire issue of possible "wrong"
10203 optimization due to strict aliasing is avoided.
10204
10205 To avoid the use of compiler switches, the configuration
10206 pragma @code{No_Strict_Aliasing} with no parameters may be
10207 used to specify that for all access types, the strict
10208 aliasing optimization should be suppressed.
10209
10210 However, these approaches are still overkill, in that they causes
10211 all manipulations of all access values to be deoptimized. A more
10212 refined approach is to concentrate attention on the specific
10213 access type identified as problematic.
10214
10215 First, if a careful analysis of uses of the pointer shows
10216 that there are no possible problematic references, then
10217 the warning can be suppressed by bracketing the
10218 instantiation of @code{Unchecked_Conversion} to turn
10219 the warning off:
10220
10221 @smallexample @c ada
10222    pragma Warnings (Off);
10223    function to_a2u is
10224      new Unchecked_Conversion (a1, a2);
10225    pragma Warnings (On);
10226 @end smallexample
10227
10228 @noindent
10229 Of course that approach is not appropriate for this particular
10230 example, since indeed there is a problematic reference. In this
10231 case we can take one of two other approaches.
10232
10233 The first possibility is to move the instantiation of unchecked
10234 conversion to the unit in which the type is declared. In
10235 this example, we would move the instantiation of
10236 @code{Unchecked_Conversion} from the body of package
10237 @code{p2} to the spec of package @code{p1}. Now the
10238 warning disappears. That's because any use of the
10239 access type knows there is a suspicious unchecked
10240 conversion, and the strict aliasing optimization
10241 is automatically suppressed for the type.
10242
10243 If it is not practical to move the unchecked conversion to the same unit
10244 in which the destination access type is declared (perhaps because the
10245 source type is not visible in that unit), you may use pragma
10246 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10247 same declarative sequence as the declaration of the access type:
10248
10249 @smallexample @c ada
10250    type a2 is access int2;
10251    pragma No_Strict_Aliasing (a2);
10252 @end smallexample
10253
10254 @noindent
10255 Here again, the compiler now knows that the strict aliasing optimization
10256 should be suppressed for any reference to type @code{a2} and the
10257 expected behavior is obtained.
10258
10259 Finally, note that although the compiler can generate warnings for
10260 simple cases of unchecked conversions, there are tricker and more
10261 indirect ways of creating type incorrect aliases which the compiler
10262 cannot detect. Examples are the use of address overlays and unchecked
10263 conversions involving composite types containing access types as
10264 components. In such cases, no warnings are generated, but there can
10265 still be aliasing problems. One safe coding practice is to forbid the
10266 use of address clauses for type overlaying, and to allow unchecked
10267 conversion only for primitive types. This is not really a significant
10268 restriction since any possible desired effect can be achieved by
10269 unchecked conversion of access values.
10270
10271 @ifset vms
10272 @node Coverage Analysis
10273 @subsection Coverage Analysis
10274
10275 @noindent
10276 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10277 the user to determine the distribution of execution time across a program,
10278 @pxref{Profiling} for details of usage.
10279 @end ifset
10280
10281
10282 @node Text_IO Suggestions
10283 @section @code{Text_IO} Suggestions
10284 @cindex @code{Text_IO} and performance
10285
10286 @noindent
10287 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10288 the requirement of maintaining page and line counts. If performance
10289 is critical, a recommendation is to use @code{Stream_IO} instead of
10290 @code{Text_IO} for volume output, since this package has less overhead.
10291
10292 If @code{Text_IO} must be used, note that by default output to the standard
10293 output and standard error files is unbuffered (this provides better
10294 behavior when output statements are used for debugging, or if the
10295 progress of a program is observed by tracking the output, e.g. by
10296 using the Unix @command{tail -f} command to watch redirected output.
10297
10298 If you are generating large volumes of output with @code{Text_IO} and
10299 performance is an important factor, use a designated file instead
10300 of the standard output file, or change the standard output file to
10301 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10302
10303
10304
10305 @node Reducing Size of Ada Executables with gnatelim
10306 @section Reducing Size of Ada Executables with @code{gnatelim}
10307 @findex gnatelim
10308
10309 @noindent
10310 This section describes @command{gnatelim}, a tool which detects unused
10311 subprograms and helps the compiler to create a smaller executable for your
10312 program.
10313
10314 @menu
10315 * About gnatelim::
10316 * Running gnatelim::
10317 * Correcting the List of Eliminate Pragmas::
10318 * Making Your Executables Smaller::
10319 * Summary of the gnatelim Usage Cycle::
10320 @end menu
10321
10322 @node About gnatelim
10323 @subsection About @code{gnatelim}
10324
10325 @noindent
10326 When a program shares a set of Ada
10327 packages with other programs, it may happen that this program uses
10328 only a fraction of the subprograms defined in these packages. The code
10329 created for these unused subprograms increases the size of the executable.
10330
10331 @code{gnatelim} tracks unused subprograms in an Ada program and
10332 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10333 subprograms that are declared but never called. By placing the list of
10334 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10335 recompiling your program, you may decrease the size of its executable,
10336 because the compiler will not generate the code for 'eliminated' subprograms.
10337 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10338 information about this pragma.
10339
10340 @code{gnatelim} needs as its input data the name of the main subprogram
10341 and a bind file for a main subprogram.
10342
10343 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
10344 the main subprogram. @code{gnatelim} can work with both Ada and C
10345 bind files; when both are present, it uses the Ada bind file.
10346 The following commands will build the program and create the bind file:
10347
10348 @smallexample
10349 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10350 $ gnatbind main_prog
10351 @end smallexample
10352
10353 Note that @code{gnatelim} needs neither object nor ALI files.
10354
10355 @node Running gnatelim
10356 @subsection Running @code{gnatelim}
10357
10358 @noindent
10359 @code{gnatelim} has the following command-line interface:
10360
10361 @smallexample
10362 $ gnatelim @ovar{options} name
10363 @end smallexample
10364
10365 @noindent
10366 @code{name} should be a name of a source file that contains the main subprogram
10367 of a program (partition).
10368
10369 @code{gnatelim} has the following switches:
10370
10371 @table @option
10372 @c !sort!
10373 @item ^-q^/QUIET^
10374 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10375 Quiet mode: by default @code{gnatelim} outputs to the standard error
10376 stream the number of program units left to be processed. This option turns
10377 this trace off.
10378
10379 @item ^-v^/VERBOSE^
10380 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10381 Verbose mode: @code{gnatelim} version information is printed as Ada
10382 comments to the standard output stream. Also, in addition to the number of
10383 program units left @code{gnatelim} will output the name of the current unit
10384 being processed.
10385
10386 @item ^-a^/ALL^
10387 @cindex @option{^-a^/ALL^} (@command{gnatelim})
10388 Also look for subprograms from the GNAT run time that can be eliminated. Note
10389 that when @file{gnat.adc} is produced using this switch, the entire program
10390 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
10391
10392 @item ^-I^/INCLUDE_DIRS=^@var{dir}
10393 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
10394 When looking for source files also look in directory @var{dir}. Specifying
10395 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
10396 sources in the current directory.
10397
10398 @item ^-b^/BIND_FILE=^@var{bind_file}
10399 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
10400 Specifies @var{bind_file} as the bind file to process. If not set, the name
10401 of the bind file is computed from the full expanded Ada name
10402 of a main subprogram.
10403
10404 @item ^-C^/CONFIG_FILE=^@var{config_file}
10405 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
10406 Specifies a file @var{config_file} that contains configuration pragmas. The
10407 file must be specified with full path.
10408
10409 @item ^--GCC^/COMPILER^=@var{compiler_name}
10410 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
10411 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
10412 available on the path.
10413
10414 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
10415 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
10416 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
10417 available on the path.
10418 @end table
10419
10420 @noindent
10421 @code{gnatelim} sends its output to the standard output stream, and all the
10422 tracing and debug information is sent to the standard error stream.
10423 In order to produce a proper GNAT configuration file
10424 @file{gnat.adc}, redirection must be used:
10425
10426 @smallexample
10427 @ifset vms
10428 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
10429 @end ifset
10430 @ifclear vms
10431 $ gnatelim main_prog.adb > gnat.adc
10432 @end ifclear
10433 @end smallexample
10434
10435 @ifclear vms
10436 @noindent
10437 or
10438
10439 @smallexample
10440 $ gnatelim main_prog.adb >> gnat.adc
10441 @end smallexample
10442
10443 @noindent
10444 in order to append the @code{gnatelim} output to the existing contents of
10445 @file{gnat.adc}.
10446 @end ifclear
10447
10448 @node Correcting the List of Eliminate Pragmas
10449 @subsection Correcting the List of Eliminate Pragmas
10450
10451 @noindent
10452 In some rare cases @code{gnatelim} may try to eliminate
10453 subprograms that are actually called in the program. In this case, the
10454 compiler will generate an error message of the form:
10455
10456 @smallexample
10457 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
10458 @end smallexample
10459
10460 @noindent
10461 You will need to manually remove the wrong @code{Eliminate} pragmas from
10462 the @file{gnat.adc} file. You should recompile your program
10463 from scratch after that, because you need a consistent @file{gnat.adc} file
10464 during the entire compilation.
10465
10466 @node Making Your Executables Smaller
10467 @subsection Making Your Executables Smaller
10468
10469 @noindent
10470 In order to get a smaller executable for your program you now have to
10471 recompile the program completely with the new @file{gnat.adc} file
10472 created by @code{gnatelim} in your current directory:
10473
10474 @smallexample
10475 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10476 @end smallexample
10477
10478 @noindent
10479 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10480 recompile everything
10481 with the set of pragmas @code{Eliminate} that you have obtained with
10482 @command{gnatelim}).
10483
10484 Be aware that the set of @code{Eliminate} pragmas is specific to each
10485 program. It is not recommended to merge sets of @code{Eliminate}
10486 pragmas created for different programs in one @file{gnat.adc} file.
10487
10488 @node Summary of the gnatelim Usage Cycle
10489 @subsection Summary of the gnatelim Usage Cycle
10490
10491 @noindent
10492 Here is a quick summary of the steps to be taken in order to reduce
10493 the size of your executables with @code{gnatelim}. You may use
10494 other GNAT options to control the optimization level,
10495 to produce the debugging information, to set search path, etc.
10496
10497 @enumerate
10498 @item
10499 Produce a bind file
10500
10501 @smallexample
10502 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10503 $ gnatbind main_prog
10504 @end smallexample
10505
10506 @item
10507 Generate a list of @code{Eliminate} pragmas
10508 @smallexample
10509 @ifset vms
10510 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10511 @end ifset
10512 @ifclear vms
10513 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
10514 @end ifclear
10515 @end smallexample
10516
10517 @item
10518 Recompile the application
10519
10520 @smallexample
10521 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10522 @end smallexample
10523
10524 @end enumerate
10525
10526 @node Reducing Size of Executables with unused subprogram/data elimination
10527 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10528 @findex unused subprogram/data elimination
10529
10530 @noindent
10531 This section describes how you can eliminate unused subprograms and data from
10532 your executable just by setting options at compilation time.
10533
10534 @menu
10535 * About unused subprogram/data elimination::
10536 * Compilation options::
10537 * Example of unused subprogram/data elimination::
10538 @end menu
10539
10540 @node About unused subprogram/data elimination
10541 @subsection About unused subprogram/data elimination
10542
10543 @noindent
10544 By default, an executable contains all code and data of its composing objects
10545 (directly linked or coming from statically linked libraries), even data or code
10546 never used by this executable.
10547
10548 This feature will allow you to eliminate such unused code from your
10549 executable, making it smaller (in disk and in memory).
10550
10551 This functionality is available on all Linux platforms except for the IA-64
10552 architecture and on all cross platforms using the ELF binary file format.
10553 In both cases GNU binutils version 2.16 or later are required to enable it.
10554
10555 @node Compilation options
10556 @subsection Compilation options
10557
10558 @noindent
10559 The operation of eliminating the unused code and data from the final executable
10560 is directly performed by the linker.
10561
10562 In order to do this, it has to work with objects compiled with the
10563 following options:
10564 @option{-ffunction-sections} @option{-fdata-sections}.
10565 @cindex @option{-ffunction-sections} (@command{gcc})
10566 @cindex @option{-fdata-sections} (@command{gcc})
10567 These options are usable with C and Ada files.
10568 They will place respectively each
10569 function or data in a separate section in the resulting object file.
10570
10571 Once the objects and static libraries are created with these options, the
10572 linker can perform the dead code elimination. You can do this by setting
10573 the @option{-Wl,--gc-sections} option to gcc command or in the
10574 @option{-largs} section of @command{gnatmake}. This will perform a
10575 garbage collection of code and data never referenced.
10576
10577 If the linker performs a partial link (@option{-r} ld linker option), then you
10578 will need to provide one or several entry point using the
10579 @option{-e} / @option{--entry} ld option.
10580
10581 Note that objects compiled without the @option{-ffunction-sections} and
10582 @option{-fdata-sections} options can still be linked with the executable.
10583 However, no dead code elimination will be performed on those objects (they will
10584 be linked as is).
10585
10586 The GNAT static library is now compiled with -ffunction-sections and
10587 -fdata-sections on some platforms. This allows you to eliminate the unused code
10588 and data of the GNAT library from your executable.
10589
10590 @node Example of unused subprogram/data elimination
10591 @subsection Example of unused subprogram/data elimination
10592
10593 @noindent
10594 Here is a simple example:
10595
10596 @smallexample @c ada
10597 with Aux;
10598
10599 procedure Test is
10600 begin
10601    Aux.Used (10);
10602 end Test;
10603
10604 package Aux is
10605    Used_Data   : Integer;
10606    Unused_Data : Integer;
10607
10608    procedure Used   (Data : Integer);
10609    procedure Unused (Data : Integer);
10610 end Aux;
10611
10612 package body Aux is
10613    procedure Used (Data : Integer) is
10614    begin
10615       Used_Data := Data;
10616    end Used;
10617
10618    procedure Unused (Data : Integer) is
10619    begin
10620       Unused_Data := Data;
10621    end Unused;
10622 end Aux;
10623 @end smallexample
10624
10625 @noindent
10626 @code{Unused} and @code{Unused_Data} are never referenced in this code
10627 excerpt, and hence they may be safely removed from the final executable.
10628
10629 @smallexample
10630 $ gnatmake test
10631
10632 $ nm test | grep used
10633 020015f0 T aux__unused
10634 02005d88 B aux__unused_data
10635 020015cc T aux__used
10636 02005d84 B aux__used_data
10637
10638 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10639      -largs -Wl,--gc-sections
10640
10641 $ nm test | grep used
10642 02005350 T aux__used
10643 0201ffe0 B aux__used_data
10644 @end smallexample
10645
10646 @noindent
10647 It can be observed that the procedure @code{Unused} and the object
10648 @code{Unused_Data} are removed by the linker when using the
10649 appropriate options.
10650
10651 @c ********************************
10652 @node Renaming Files Using gnatchop
10653 @chapter Renaming Files Using @code{gnatchop}
10654 @findex gnatchop
10655
10656 @noindent
10657 This chapter discusses how to handle files with multiple units by using
10658 the @code{gnatchop} utility. This utility is also useful in renaming
10659 files to meet the standard GNAT default file naming conventions.
10660
10661 @menu
10662 * Handling Files with Multiple Units::
10663 * Operating gnatchop in Compilation Mode::
10664 * Command Line for gnatchop::
10665 * Switches for gnatchop::
10666 * Examples of gnatchop Usage::
10667 @end menu
10668
10669 @node Handling Files with Multiple Units
10670 @section Handling Files with Multiple Units
10671
10672 @noindent
10673 The basic compilation model of GNAT requires that a file submitted to the
10674 compiler have only one unit and there be a strict correspondence
10675 between the file name and the unit name.
10676
10677 The @code{gnatchop} utility allows both of these rules to be relaxed,
10678 allowing GNAT to process files which contain multiple compilation units
10679 and files with arbitrary file names. @code{gnatchop}
10680 reads the specified file and generates one or more output files,
10681 containing one unit per file. The unit and the file name correspond,
10682 as required by GNAT.
10683
10684 If you want to permanently restructure a set of ``foreign'' files so that
10685 they match the GNAT rules, and do the remaining development using the
10686 GNAT structure, you can simply use @command{gnatchop} once, generate the
10687 new set of files and work with them from that point on.
10688
10689 Alternatively, if you want to keep your files in the ``foreign'' format,
10690 perhaps to maintain compatibility with some other Ada compilation
10691 system, you can set up a procedure where you use @command{gnatchop} each
10692 time you compile, regarding the source files that it writes as temporary
10693 files that you throw away.
10694
10695 @node Operating gnatchop in Compilation Mode
10696 @section Operating gnatchop in Compilation Mode
10697
10698 @noindent
10699 The basic function of @code{gnatchop} is to take a file with multiple units
10700 and split it into separate files. The boundary between files is reasonably
10701 clear, except for the issue of comments and pragmas. In default mode, the
10702 rule is that any pragmas between units belong to the previous unit, except
10703 that configuration pragmas always belong to the following unit. Any comments
10704 belong to the following unit. These rules
10705 almost always result in the right choice of
10706 the split point without needing to mark it explicitly and most users will
10707 find this default to be what they want. In this default mode it is incorrect to
10708 submit a file containing only configuration pragmas, or one that ends in
10709 configuration pragmas, to @code{gnatchop}.
10710
10711 However, using a special option to activate ``compilation mode'',
10712 @code{gnatchop}
10713 can perform another function, which is to provide exactly the semantics
10714 required by the RM for handling of configuration pragmas in a compilation.
10715 In the absence of configuration pragmas (at the main file level), this
10716 option has no effect, but it causes such configuration pragmas to be handled
10717 in a quite different manner.
10718
10719 First, in compilation mode, if @code{gnatchop} is given a file that consists of
10720 only configuration pragmas, then this file is appended to the
10721 @file{gnat.adc} file in the current directory. This behavior provides
10722 the required behavior described in the RM for the actions to be taken
10723 on submitting such a file to the compiler, namely that these pragmas
10724 should apply to all subsequent compilations in the same compilation
10725 environment. Using GNAT, the current directory, possibly containing a
10726 @file{gnat.adc} file is the representation
10727 of a compilation environment. For more information on the
10728 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
10729
10730 Second, in compilation mode, if @code{gnatchop}
10731 is given a file that starts with
10732 configuration pragmas, and contains one or more units, then these
10733 configuration pragmas are prepended to each of the chopped files. This
10734 behavior provides the required behavior described in the RM for the
10735 actions to be taken on compiling such a file, namely that the pragmas
10736 apply to all units in the compilation, but not to subsequently compiled
10737 units.
10738
10739 Finally, if configuration pragmas appear between units, they are appended
10740 to the previous unit. This results in the previous unit being illegal,
10741 since the compiler does not accept configuration pragmas that follow
10742 a unit. This provides the required RM behavior that forbids configuration
10743 pragmas other than those preceding the first compilation unit of a
10744 compilation.
10745
10746 For most purposes, @code{gnatchop} will be used in default mode. The
10747 compilation mode described above is used only if you need exactly
10748 accurate behavior with respect to compilations, and you have files
10749 that contain multiple units and configuration pragmas. In this
10750 circumstance the use of @code{gnatchop} with the compilation mode
10751 switch provides the required behavior, and is for example the mode
10752 in which GNAT processes the ACVC tests.
10753
10754 @node Command Line for gnatchop
10755 @section Command Line for @code{gnatchop}
10756
10757 @noindent
10758 The @code{gnatchop} command has the form:
10759
10760 @smallexample
10761 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
10762       @ovar{directory}
10763 @end smallexample
10764
10765 @noindent
10766 The only required argument is the file name of the file to be chopped.
10767 There are no restrictions on the form of this file name. The file itself
10768 contains one or more Ada units, in normal GNAT format, concatenated
10769 together. As shown, more than one file may be presented to be chopped.
10770
10771 When run in default mode, @code{gnatchop} generates one output file in
10772 the current directory for each unit in each of the files.
10773
10774 @var{directory}, if specified, gives the name of the directory to which
10775 the output files will be written. If it is not specified, all files are
10776 written to the current directory.
10777
10778 For example, given a
10779 file called @file{hellofiles} containing
10780
10781 @smallexample @c ada
10782 @group
10783 @cartouche
10784 procedure hello;
10785
10786 with Text_IO; use Text_IO;
10787 procedure hello is
10788 begin
10789    Put_Line ("Hello");
10790 end hello;
10791 @end cartouche
10792 @end group
10793 @end smallexample
10794
10795 @noindent
10796 the command
10797
10798 @smallexample
10799 $ gnatchop ^hellofiles^HELLOFILES.^
10800 @end smallexample
10801
10802 @noindent
10803 generates two files in the current directory, one called
10804 @file{hello.ads} containing the single line that is the procedure spec,
10805 and the other called @file{hello.adb} containing the remaining text. The
10806 original file is not affected. The generated files can be compiled in
10807 the normal manner.
10808
10809 @noindent
10810 When gnatchop is invoked on a file that is empty or that contains only empty
10811 lines and/or comments, gnatchop will not fail, but will not produce any
10812 new sources.
10813
10814 For example, given a
10815 file called @file{toto.txt} containing
10816
10817 @smallexample @c ada
10818 @group
10819 @cartouche
10820 --  Just a comment
10821 @end cartouche
10822 @end group
10823 @end smallexample
10824
10825 @noindent
10826 the command
10827
10828 @smallexample
10829 $ gnatchop ^toto.txt^TOT.TXT^
10830 @end smallexample
10831
10832 @noindent
10833 will not produce any new file and will result in the following warnings:
10834
10835 @smallexample
10836 toto.txt:1:01: warning: empty file, contains no compilation units
10837 no compilation units found
10838 no source files written
10839 @end smallexample
10840
10841 @node Switches for gnatchop
10842 @section Switches for @code{gnatchop}
10843
10844 @noindent
10845 @command{gnatchop} recognizes the following switches:
10846
10847 @table @option
10848 @c !sort!
10849
10850 @item --version
10851 @cindex @option{--version} @command{gnatchop}
10852 Display Copyright and version, then exit disregarding all other options.
10853
10854 @item --help
10855 @cindex @option{--help} @command{gnatchop}
10856 If @option{--version} was not used, display usage, then exit disregarding
10857 all other options.
10858
10859 @item ^-c^/COMPILATION^
10860 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
10861 Causes @code{gnatchop} to operate in compilation mode, in which
10862 configuration pragmas are handled according to strict RM rules. See
10863 previous section for a full description of this mode.
10864
10865 @ifclear vms
10866 @item -gnat@var{xxx}
10867 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
10868 used to parse the given file. Not all @var{xxx} options make sense,
10869 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
10870 process a source file that uses Latin-2 coding for identifiers.
10871 @end ifclear
10872
10873 @item ^-h^/HELP^
10874 Causes @code{gnatchop} to generate a brief help summary to the standard
10875 output file showing usage information.
10876
10877 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
10878 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
10879 Limit generated file names to the specified number @code{mm}
10880 of characters.
10881 This is useful if the
10882 resulting set of files is required to be interoperable with systems
10883 which limit the length of file names.
10884 @ifset vms
10885 If no value is given, or
10886 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
10887 a default of 39, suitable for OpenVMS Alpha
10888 Systems, is assumed
10889 @end ifset
10890 @ifclear vms
10891 No space is allowed between the @option{-k} and the numeric value. The numeric
10892 value may be omitted in which case a default of @option{-k8},
10893 suitable for use
10894 with DOS-like file systems, is used. If no @option{-k} switch
10895 is present then
10896 there is no limit on the length of file names.
10897 @end ifclear
10898
10899 @item ^-p^/PRESERVE^
10900 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
10901 Causes the file ^modification^creation^ time stamp of the input file to be
10902 preserved and used for the time stamp of the output file(s). This may be
10903 useful for preserving coherency of time stamps in an environment where
10904 @code{gnatchop} is used as part of a standard build process.
10905
10906 @item ^-q^/QUIET^
10907 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
10908 Causes output of informational messages indicating the set of generated
10909 files to be suppressed. Warnings and error messages are unaffected.
10910
10911 @item ^-r^/REFERENCE^
10912 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
10913 @findex Source_Reference
10914 Generate @code{Source_Reference} pragmas. Use this switch if the output
10915 files are regarded as temporary and development is to be done in terms
10916 of the original unchopped file. This switch causes
10917 @code{Source_Reference} pragmas to be inserted into each of the
10918 generated files to refers back to the original file name and line number.
10919 The result is that all error messages refer back to the original
10920 unchopped file.
10921 In addition, the debugging information placed into the object file (when
10922 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
10923 specified)
10924 also refers back to this original file so that tools like profilers and
10925 debuggers will give information in terms of the original unchopped file.
10926
10927 If the original file to be chopped itself contains
10928 a @code{Source_Reference}
10929 pragma referencing a third file, then gnatchop respects
10930 this pragma, and the generated @code{Source_Reference} pragmas
10931 in the chopped file refer to the original file, with appropriate
10932 line numbers. This is particularly useful when @code{gnatchop}
10933 is used in conjunction with @code{gnatprep} to compile files that
10934 contain preprocessing statements and multiple units.
10935
10936 @item ^-v^/VERBOSE^
10937 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
10938 Causes @code{gnatchop} to operate in verbose mode. The version
10939 number and copyright notice are output, as well as exact copies of
10940 the gnat1 commands spawned to obtain the chop control information.
10941
10942 @item ^-w^/OVERWRITE^
10943 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
10944 Overwrite existing file names. Normally @code{gnatchop} regards it as a
10945 fatal error if there is already a file with the same name as a
10946 file it would otherwise output, in other words if the files to be
10947 chopped contain duplicated units. This switch bypasses this
10948 check, and causes all but the last instance of such duplicated
10949 units to be skipped.
10950
10951 @ifclear vms
10952 @item --GCC=@var{xxxx}
10953 @cindex @option{--GCC=} (@code{gnatchop})
10954 Specify the path of the GNAT parser to be used. When this switch is used,
10955 no attempt is made to add the prefix to the GNAT parser executable.
10956 @end ifclear
10957 @end table
10958
10959 @node Examples of gnatchop Usage
10960 @section Examples of @code{gnatchop} Usage
10961
10962 @table @code
10963 @ifset vms
10964 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
10965 @end ifset
10966 @ifclear vms
10967 @item gnatchop -w hello_s.ada prerelease/files
10968 @end ifclear
10969
10970 Chops the source file @file{hello_s.ada}. The output files will be
10971 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
10972 overwriting any
10973 files with matching names in that directory (no files in the current
10974 directory are modified).
10975
10976 @item gnatchop ^archive^ARCHIVE.^
10977 Chops the source file @file{^archive^ARCHIVE.^}
10978 into the current directory. One
10979 useful application of @code{gnatchop} is in sending sets of sources
10980 around, for example in email messages. The required sources are simply
10981 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
10982 command), and then
10983 @command{gnatchop} is used at the other end to reconstitute the original
10984 file names.
10985
10986 @item gnatchop file1 file2 file3 direc
10987 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
10988 the resulting files in the directory @file{direc}. Note that if any units
10989 occur more than once anywhere within this set of files, an error message
10990 is generated, and no files are written. To override this check, use the
10991 @option{^-w^/OVERWRITE^} switch,
10992 in which case the last occurrence in the last file will
10993 be the one that is output, and earlier duplicate occurrences for a given
10994 unit will be skipped.
10995 @end table
10996
10997 @node Configuration Pragmas
10998 @chapter Configuration Pragmas
10999 @cindex Configuration pragmas
11000 @cindex Pragmas, configuration
11001
11002 @noindent
11003 Configuration pragmas include those pragmas described as
11004 such in the Ada Reference Manual, as well as
11005 implementation-dependent pragmas that are configuration pragmas.
11006 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11007 for details on these additional GNAT-specific configuration pragmas.
11008 Most notably, the pragma @code{Source_File_Name}, which allows
11009 specifying non-default names for source files, is a configuration
11010 pragma. The following is a complete list of configuration pragmas
11011 recognized by GNAT:
11012
11013 @smallexample
11014    Ada_83
11015    Ada_95
11016    Ada_05
11017    Ada_2005
11018    Assertion_Policy
11019    C_Pass_By_Copy
11020    Check_Name
11021    Check_Policy
11022    Compile_Time_Error
11023    Compile_Time_Warning
11024    Compiler_Unit
11025    Component_Alignment
11026    Debug_Policy
11027    Detect_Blocking
11028    Discard_Names
11029    Elaboration_Checks
11030    Eliminate
11031    Extend_System
11032    External_Name_Casing
11033    Fast_Math
11034    Favor_Top_Level
11035    Float_Representation
11036    Implicit_Packing
11037    Initialize_Scalars
11038    Interrupt_State
11039    License
11040    Locking_Policy
11041    Long_Float
11042    No_Run_Time
11043    No_Strict_Aliasing
11044    Normalize_Scalars
11045    Optimize_Alignment
11046    Persistent_BSS
11047    Polling
11048    Priority_Specific_Dispatching
11049    Profile
11050    Profile_Warnings
11051    Propagate_Exceptions
11052    Queuing_Policy
11053    Ravenscar
11054    Restricted_Run_Time
11055    Restrictions
11056    Restrictions_Warnings
11057    Reviewable
11058    Source_File_Name
11059    Source_File_Name_Project
11060    Style_Checks
11061    Suppress
11062    Suppress_Exception_Locations
11063    Task_Dispatching_Policy
11064    Universal_Data
11065    Unsuppress
11066    Use_VADS_Size
11067    Validity_Checks
11068    Warnings
11069    Wide_Character_Encoding
11070
11071 @end smallexample
11072
11073 @menu
11074 * Handling of Configuration Pragmas::
11075 * The Configuration Pragmas Files::
11076 @end menu
11077
11078 @node Handling of Configuration Pragmas
11079 @section Handling of Configuration Pragmas
11080
11081 Configuration pragmas may either appear at the start of a compilation
11082 unit, in which case they apply only to that unit, or they may apply to
11083 all compilations performed in a given compilation environment.
11084
11085 GNAT also provides the @code{gnatchop} utility to provide an automatic
11086 way to handle configuration pragmas following the semantics for
11087 compilations (that is, files with multiple units), described in the RM.
11088 See @ref{Operating gnatchop in Compilation Mode} for details.
11089 However, for most purposes, it will be more convenient to edit the
11090 @file{gnat.adc} file that contains configuration pragmas directly,
11091 as described in the following section.
11092
11093 @node The Configuration Pragmas Files
11094 @section The Configuration Pragmas Files
11095 @cindex @file{gnat.adc}
11096
11097 @noindent
11098 In GNAT a compilation environment is defined by the current
11099 directory at the time that a compile command is given. This current
11100 directory is searched for a file whose name is @file{gnat.adc}. If
11101 this file is present, it is expected to contain one or more
11102 configuration pragmas that will be applied to the current compilation.
11103 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11104 considered.
11105
11106 Configuration pragmas may be entered into the @file{gnat.adc} file
11107 either by running @code{gnatchop} on a source file that consists only of
11108 configuration pragmas, or more conveniently  by
11109 direct editing of the @file{gnat.adc} file, which is a standard format
11110 source file.
11111
11112 In addition to @file{gnat.adc}, additional files containing configuration
11113 pragmas may be applied to the current compilation using the switch
11114 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11115 contains only configuration pragmas. These configuration pragmas are
11116 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11117 is present and switch @option{-gnatA} is not used).
11118
11119 It is allowed to specify several switches @option{-gnatec}, all of which
11120 will be taken into account.
11121
11122 If you are using project file, a separate mechanism is provided using
11123 project attributes, see @ref{Specifying Configuration Pragmas} for more
11124 details.
11125
11126 @ifset vms
11127 Of special interest to GNAT OpenVMS Alpha is the following
11128 configuration pragma:
11129
11130 @smallexample @c ada
11131 @cartouche
11132 pragma Extend_System (Aux_DEC);
11133 @end cartouche
11134 @end smallexample
11135
11136 @noindent
11137 In the presence of this pragma, GNAT adds to the definition of the
11138 predefined package SYSTEM all the additional types and subprograms that are
11139 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11140 @end ifset
11141
11142 @node Handling Arbitrary File Naming Conventions Using gnatname
11143 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11144 @cindex Arbitrary File Naming Conventions
11145
11146 @menu
11147 * Arbitrary File Naming Conventions::
11148 * Running gnatname::
11149 * Switches for gnatname::
11150 * Examples of gnatname Usage::
11151 @end menu
11152
11153 @node Arbitrary File Naming Conventions
11154 @section Arbitrary File Naming Conventions
11155
11156 @noindent
11157 The GNAT compiler must be able to know the source file name of a compilation
11158 unit.  When using the standard GNAT default file naming conventions
11159 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11160 does not need additional information.
11161
11162 @noindent
11163 When the source file names do not follow the standard GNAT default file naming
11164 conventions, the GNAT compiler must be given additional information through
11165 a configuration pragmas file (@pxref{Configuration Pragmas})
11166 or a project file.
11167 When the non-standard file naming conventions are well-defined,
11168 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11169 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11170 if the file naming conventions are irregular or arbitrary, a number
11171 of pragma @code{Source_File_Name} for individual compilation units
11172 must be defined.
11173 To help maintain the correspondence between compilation unit names and
11174 source file names within the compiler,
11175 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11176 set of files.
11177
11178 @node Running gnatname
11179 @section Running @code{gnatname}
11180
11181 @noindent
11182 The usual form of the @code{gnatname} command is
11183
11184 @smallexample
11185 $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11186       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11187 @end smallexample
11188
11189 @noindent
11190 All of the arguments are optional. If invoked without any argument,
11191 @code{gnatname} will display its usage.
11192
11193 @noindent
11194 When used with at least one naming pattern, @code{gnatname} will attempt to
11195 find all the compilation units in files that follow at least one of the
11196 naming patterns. To find these compilation units,
11197 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11198 regular files.
11199
11200 @noindent
11201 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11202 Each Naming Pattern is enclosed between double quotes.
11203 A Naming Pattern is a regular expression similar to the wildcard patterns
11204 used in file names by the Unix shells or the DOS prompt.
11205
11206 @noindent
11207 @code{gnatname} may be called with several sections of directories/patterns.
11208 Sections are separated by switch @code{--and}. In each section, there must be
11209 at least one pattern. If no directory is specified in a section, the current
11210 directory (or the project directory is @code{-P} is used) is implied.
11211 The options other that the directory switches and the patterns apply globally
11212 even if they are in different sections.
11213
11214 @noindent
11215 Examples of Naming Patterns are
11216
11217 @smallexample
11218    "*.[12].ada"
11219    "*.ad[sb]*"
11220    "body_*"    "spec_*"
11221 @end smallexample
11222
11223 @noindent
11224 For a more complete description of the syntax of Naming Patterns,
11225 see the second kind of regular expressions described in @file{g-regexp.ads}
11226 (the ``Glob'' regular expressions).
11227
11228 @noindent
11229 When invoked with no switch @code{-P}, @code{gnatname} will create a
11230 configuration pragmas file @file{gnat.adc} in the current working directory,
11231 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11232 unit.
11233
11234 @node Switches for gnatname
11235 @section Switches for @code{gnatname}
11236
11237 @noindent
11238 Switches for @code{gnatname} must precede any specified Naming Pattern.
11239
11240 @noindent
11241 You may specify any of the following switches to @code{gnatname}:
11242
11243 @table @option
11244 @c !sort!
11245
11246 @item --version
11247 @cindex @option{--version} @command{gnatname}
11248 Display Copyright and version, then exit disregarding all other options.
11249
11250 @item --help
11251 @cindex @option{--help} @command{gnatname}
11252 If @option{--version} was not used, display usage, then exit disregarding
11253 all other options.
11254
11255 @item --and
11256 Start another section of directories/patterns.
11257
11258 @item ^-c^/CONFIG_FILE=^@file{file}
11259 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11260 Create a configuration pragmas file @file{file} (instead of the default
11261 @file{gnat.adc}).
11262 @ifclear vms
11263 There may be zero, one or more space between @option{-c} and
11264 @file{file}.
11265 @end ifclear
11266 @file{file} may include directory information. @file{file} must be
11267 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11268 When a switch @option{^-c^/CONFIG_FILE^} is
11269 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11270
11271 @item ^-d^/SOURCE_DIRS=^@file{dir}
11272 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11273 Look for source files in directory @file{dir}. There may be zero, one or more
11274 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11275 When a switch @option{^-d^/SOURCE_DIRS^}
11276 is specified, the current working directory will not be searched for source
11277 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11278 or @option{^-D^/DIR_FILES^} switch.
11279 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11280 If @file{dir} is a relative path, it is relative to the directory of
11281 the configuration pragmas file specified with switch
11282 @option{^-c^/CONFIG_FILE^},
11283 or to the directory of the project file specified with switch
11284 @option{^-P^/PROJECT_FILE^} or,
11285 if neither switch @option{^-c^/CONFIG_FILE^}
11286 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11287 current working directory. The directory
11288 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11289
11290 @item ^-D^/DIRS_FILE=^@file{file}
11291 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11292 Look for source files in all directories listed in text file @file{file}.
11293 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11294 and @file{file}.
11295 @file{file} must be an existing, readable text file.
11296 Each nonempty line in @file{file} must be a directory.
11297 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11298 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11299 @file{file}.
11300
11301 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11302 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11303 Foreign patterns. Using this switch, it is possible to add sources of languages
11304 other than Ada to the list of sources of a project file.
11305 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11306 For example,
11307 @smallexample
11308 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11309 @end smallexample
11310 @noindent
11311 will look for Ada units in all files with the @file{.ada} extension,
11312 and will add to the list of file for project @file{prj.gpr} the C files
11313 with extension @file{.^c^C^}.
11314
11315 @item ^-h^/HELP^
11316 @cindex @option{^-h^/HELP^} (@code{gnatname})
11317 Output usage (help) information. The output is written to @file{stdout}.
11318
11319 @item ^-P^/PROJECT_FILE=^@file{proj}
11320 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11321 Create or update project file @file{proj}. There may be zero, one or more space
11322 between @option{-P} and @file{proj}. @file{proj} may include directory
11323 information. @file{proj} must be writable.
11324 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11325 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11326 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11327
11328 @item ^-v^/VERBOSE^
11329 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11330 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11331 This includes name of the file written, the name of the directories to search
11332 and, for each file in those directories whose name matches at least one of
11333 the Naming Patterns, an indication of whether the file contains a unit,
11334 and if so the name of the unit.
11335
11336 @item ^-v -v^/VERBOSE /VERBOSE^
11337 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11338 Very Verbose mode. In addition to the output produced in verbose mode,
11339 for each file in the searched directories whose name matches none of
11340 the Naming Patterns, an indication is given that there is no match.
11341
11342 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11343 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11344 Excluded patterns. Using this switch, it is possible to exclude some files
11345 that would match the name patterns. For example,
11346 @smallexample
11347 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11348 @end smallexample
11349 @noindent
11350 will look for Ada units in all files with the @file{.ada} extension,
11351 except those whose names end with @file{_nt.ada}.
11352
11353 @end table
11354
11355 @node Examples of gnatname Usage
11356 @section Examples of @code{gnatname} Usage
11357
11358 @ifset vms
11359 @smallexample
11360 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11361 @end smallexample
11362 @end ifset
11363
11364 @ifclear vms
11365 @smallexample
11366 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11367 @end smallexample
11368 @end ifclear
11369
11370 @noindent
11371 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11372 and be writable. In addition, the directory
11373 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11374 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11375
11376 @ifclear vms
11377 Note the optional spaces after @option{-c} and @option{-d}.
11378 @end ifclear
11379
11380 @smallexample
11381 @ifclear vms
11382 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11383   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11384 @end ifclear
11385 @ifset vms
11386 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11387   /EXCLUDED_PATTERN=*_nt_body.ada
11388   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11389   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11390 @end ifset
11391 @end smallexample
11392
11393 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11394 even in conjunction with one or several switches
11395 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11396 are used in this example.
11397
11398 @c *****************************************
11399 @c * G N A T  P r o j e c t  M a n a g e r *
11400 @c *****************************************
11401 @node GNAT Project Manager
11402 @chapter GNAT Project Manager
11403
11404 @menu
11405 * Introduction::
11406 * Examples of Project Files::
11407 * Project File Syntax::
11408 * Objects and Sources in Project Files::
11409 * Importing Projects::
11410 * Project Extension::
11411 * Project Hierarchy Extension::
11412 * External References in Project Files::
11413 * Packages in Project Files::
11414 * Variables from Imported Projects::
11415 * Naming Schemes::
11416 * Library Projects::
11417 * Stand-alone Library Projects::
11418 * Switches Related to Project Files::
11419 * Tools Supporting Project Files::
11420 * An Extended Example::
11421 * Project File Complete Syntax::
11422 @end menu
11423
11424 @c ****************
11425 @c * Introduction *
11426 @c ****************
11427
11428 @node Introduction
11429 @section Introduction
11430
11431 @noindent
11432 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
11433 you to manage complex builds involving a number of source files, directories,
11434 and compilation options for different system configurations. In particular,
11435 project files allow you to specify:
11436 @itemize @bullet
11437 @item
11438 The directory or set of directories containing the source files, and/or the
11439 names of the specific source files themselves
11440 @item
11441 The directory in which the compiler's output
11442 (@file{ALI} files, object files, tree files) is to be placed
11443 @item
11444 The directory in which the executable programs is to be placed
11445 @item
11446 ^Switch^Switch^ settings for any of the project-enabled tools
11447 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
11448 @code{gnatfind}); you can apply these settings either globally or to individual
11449 compilation units.
11450 @item
11451 The source files containing the main subprogram(s) to be built
11452 @item
11453 The source programming language(s) (currently Ada and/or C)
11454 @item
11455 Source file naming conventions; you can specify these either globally or for
11456 individual compilation units
11457 @end itemize
11458
11459 @menu
11460 * Project Files::
11461 @end menu
11462
11463 @node Project Files
11464 @subsection Project Files
11465
11466 @noindent
11467 Project files are written in a syntax close to that of Ada, using  familiar
11468 notions such as packages, context clauses, declarations, default values,
11469 assignments, and inheritance. Finally, project files can be built
11470 hierarchically from other project files, simplifying complex system
11471 integration and project reuse.
11472
11473 A @dfn{project} is a specific set of values for various compilation properties.
11474 The settings for a given project are described by means of
11475 a @dfn{project file}, which is a text file written in an Ada-like syntax.
11476 Property values in project files are either strings or lists of strings.
11477 Properties that are not explicitly set receive default values.  A project
11478 file may interrogate the values of @dfn{external variables} (user-defined
11479 command-line switches or environment variables), and it may specify property
11480 settings conditionally, based on the value of such variables.
11481
11482 In simple cases, a project's source files depend only on other source files
11483 in the same project, or on the predefined libraries.  (@emph{Dependence} is
11484 used in
11485 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
11486 the Project Manager also allows more sophisticated arrangements,
11487 where the source files in one project depend on source files in other
11488 projects:
11489 @itemize @bullet
11490 @item
11491 One project can @emph{import} other projects containing needed source files.
11492 @item
11493 You can organize GNAT projects in a hierarchy: a @emph{child} project
11494 can extend a @emph{parent} project, inheriting the parent's source files and
11495 optionally overriding any of them with alternative versions
11496 @end itemize
11497
11498 @noindent
11499 More generally, the Project Manager lets you structure large development
11500 efforts into hierarchical subsystems, where build decisions are delegated
11501 to the subsystem level, and thus different compilation environments
11502 (^switch^switch^ settings) used for different subsystems.
11503
11504 The Project Manager is invoked through the
11505 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
11506 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
11507 @ifclear vms
11508 There may be zero, one or more spaces between @option{-P} and
11509 @option{@emph{projectfile}}.
11510 @end ifclear
11511 If you want to define (on the command line) an external variable that is
11512 queried by the project file, you must use the
11513 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11514 The Project Manager parses and interprets the project file, and drives the
11515 invoked tool based on the project settings.
11516
11517 The Project Manager supports a wide range of development strategies,
11518 for systems of all sizes.  Here are some typical practices that are
11519 easily handled:
11520 @itemize @bullet
11521 @item
11522 Using a common set of source files, but generating object files in different
11523 directories via different ^switch^switch^ settings
11524 @item
11525 Using a mostly-shared set of source files, but with different versions of
11526 some unit or units
11527 @end itemize
11528
11529 @noindent
11530 The destination of an executable can be controlled inside a project file
11531 using the @option{^-o^-o^}
11532 ^switch^switch^.
11533 In the absence of such a ^switch^switch^ either inside
11534 the project file or on the command line, any executable files generated by
11535 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
11536 in the project file. If no @code{Exec_Dir} is specified, they will be placed
11537 in the object directory of the project.
11538
11539 You can use project files to achieve some of the effects of a source
11540 versioning system (for example, defining separate projects for
11541 the different sets of sources that comprise different releases) but the
11542 Project Manager is independent of any source configuration management tools
11543 that might be used by the developers.
11544
11545 The next section introduces the main features of GNAT's project facility
11546 through a sequence of examples; subsequent sections will present the syntax
11547 and semantics in more detail. A more formal description of the project
11548 facility appears in @ref{Project File Reference,,, gnat_rm, GNAT
11549 Reference Manual}.
11550
11551 @c *****************************
11552 @c * Examples of Project Files *
11553 @c *****************************
11554
11555 @node Examples of Project Files
11556 @section Examples of Project Files
11557 @noindent
11558 This section illustrates some of the typical uses of project files and
11559 explains their basic structure and behavior.
11560
11561 @menu
11562 * Common Sources with Different ^Switches^Switches^ and Directories::
11563 * Using External Variables::
11564 * Importing Other Projects::
11565 * Extending a Project::
11566 @end menu
11567
11568 @node Common Sources with Different ^Switches^Switches^ and Directories
11569 @subsection Common Sources with Different ^Switches^Switches^ and Directories
11570
11571 @menu
11572 * Source Files::
11573 * Specifying the Object Directory::
11574 * Specifying the Exec Directory::
11575 * Project File Packages::
11576 * Specifying ^Switch^Switch^ Settings::
11577 * Main Subprograms::
11578 * Executable File Names::
11579 * Source File Naming Conventions::
11580 * Source Language(s)::
11581 @end menu
11582
11583 @noindent
11584 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
11585 @file{proc.adb} are in the @file{/common} directory.  The file
11586 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
11587 package @code{Pack}.  We want to compile these source files under two sets
11588 of ^switches^switches^:
11589 @itemize @bullet
11590 @item
11591 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
11592 and the @option{^-gnata^-gnata^},
11593 @option{^-gnato^-gnato^},
11594 and @option{^-gnatE^-gnatE^} switches to the
11595 compiler; the compiler's output is to appear in @file{/common/debug}
11596 @item
11597 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
11598 to the compiler; the compiler's output is to appear in @file{/common/release}
11599 @end itemize
11600
11601 @noindent
11602 The GNAT project files shown below, respectively @file{debug.gpr} and
11603 @file{release.gpr} in the @file{/common} directory, achieve these effects.
11604
11605 Schematically:
11606 @smallexample
11607 @group
11608 ^/common^[COMMON]^
11609   debug.gpr
11610   release.gpr
11611   pack.ads
11612   pack.adb
11613   proc.adb
11614 @end group
11615 @group
11616 ^/common/debug^[COMMON.DEBUG]^
11617   proc.ali, proc.o
11618   pack.ali, pack.o
11619 @end group
11620 @group
11621 ^/common/release^[COMMON.RELEASE]^
11622   proc.ali, proc.o
11623   pack.ali, pack.o
11624 @end group
11625 @end smallexample
11626 Here are the corresponding project files:
11627
11628 @smallexample @c projectfile
11629 @group
11630 project Debug is
11631   for Object_Dir use "debug";
11632   for Main use ("proc");
11633
11634   package Builder is
11635     for ^Default_Switches^Default_Switches^ ("Ada")
11636         use ("^-g^-g^");
11637     for Executable ("proc.adb") use "proc1";
11638   end Builder;
11639 @end group
11640
11641 @group
11642   package Compiler is
11643     for ^Default_Switches^Default_Switches^ ("Ada")
11644        use ("-fstack-check",
11645             "^-gnata^-gnata^",
11646             "^-gnato^-gnato^",
11647             "^-gnatE^-gnatE^");
11648   end Compiler;
11649 end Debug;
11650 @end group
11651 @end smallexample
11652
11653 @smallexample @c projectfile
11654 @group
11655 project Release is
11656   for Object_Dir use "release";
11657   for Exec_Dir use ".";
11658   for Main use ("proc");
11659
11660   package Compiler is
11661     for ^Default_Switches^Default_Switches^ ("Ada")
11662         use ("^-O2^-O2^");
11663   end Compiler;
11664 end Release;
11665 @end group
11666 @end smallexample
11667
11668 @noindent
11669 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
11670 insensitive), and analogously the project defined by @file{release.gpr} is
11671 @code{"Release"}.  For consistency the file should have the same name as the
11672 project, and the project file's extension should be @code{"gpr"}. These
11673 conventions are not required, but a warning is issued if they are not followed.
11674
11675 If the current directory is @file{^/temp^[TEMP]^}, then the command
11676 @smallexample
11677 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
11678 @end smallexample
11679
11680 @noindent
11681 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
11682 as well as the @code{^proc1^PROC1.EXE^} executable,
11683 using the ^switch^switch^ settings defined in the project file.
11684
11685 Likewise, the command
11686 @smallexample
11687 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
11688 @end smallexample
11689
11690 @noindent
11691 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
11692 and the @code{^proc^PROC.EXE^}
11693 executable in @file{^/common^[COMMON]^},
11694 using the ^switch^switch^ settings from the project file.
11695
11696 @node Source Files
11697 @unnumberedsubsubsec Source Files
11698
11699 @noindent
11700 If a project file does not explicitly specify a set of source directories or
11701 a set of source files, then by default the project's source files are the
11702 Ada source files in the project file directory.  Thus @file{pack.ads},
11703 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
11704
11705 @node Specifying the Object Directory
11706 @unnumberedsubsubsec Specifying the Object Directory
11707
11708 @noindent
11709 Several project properties are modeled by Ada-style @emph{attributes};
11710 a property is defined by supplying the equivalent of an Ada attribute
11711 definition clause in the project file.
11712 A project's object directory is another such a property; the corresponding
11713 attribute is @code{Object_Dir}, and its value is also a string expression,
11714 specified either as absolute or relative. In the later case,
11715 it is relative to the project file directory. Thus the compiler's
11716 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
11717 (for the @code{Debug} project)
11718 and to @file{^/common/release^[COMMON.RELEASE]^}
11719 (for the @code{Release} project).
11720 If @code{Object_Dir} is not specified, then the default is the project file
11721 directory itself.
11722
11723 @node Specifying the Exec Directory
11724 @unnumberedsubsubsec Specifying the Exec Directory
11725
11726 @noindent
11727 A project's exec directory is another property; the corresponding
11728 attribute is @code{Exec_Dir}, and its value is also a string expression,
11729 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
11730 then the default is the object directory (which may also be the project file
11731 directory if attribute @code{Object_Dir} is not specified). Thus the executable
11732 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
11733 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
11734 and in @file{^/common^[COMMON]^} for the @code{Release} project.
11735
11736 @node Project File Packages
11737 @unnumberedsubsubsec Project File Packages
11738
11739 @noindent
11740 A GNAT tool that is integrated with the Project Manager is modeled by a
11741 corresponding package in the project file. In the example above,
11742 The @code{Debug} project defines the packages @code{Builder}
11743 (for @command{gnatmake}) and @code{Compiler};
11744 the @code{Release} project defines only the @code{Compiler} package.
11745
11746 The Ada-like package syntax is not to be taken literally.  Although packages in
11747 project files bear a surface resemblance to packages in Ada source code, the
11748 notation is simply a way to convey a grouping of properties for a named
11749 entity.  Indeed, the package names permitted in project files are restricted
11750 to a predefined set, corresponding to the project-aware tools, and the contents
11751 of packages are limited to a small set of constructs.
11752 The packages in the example above contain attribute definitions.
11753
11754 @node Specifying ^Switch^Switch^ Settings
11755 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
11756
11757 @noindent
11758 ^Switch^Switch^ settings for a project-aware tool can be specified through
11759 attributes in the package that corresponds to the tool.
11760 The example above illustrates one of the relevant attributes,
11761 @code{^Default_Switches^Default_Switches^}, which is defined in packages
11762 in both project files.
11763 Unlike simple attributes like @code{Source_Dirs},
11764 @code{^Default_Switches^Default_Switches^} is
11765 known as an @emph{associative array}.  When you define this attribute, you must
11766 supply an ``index'' (a literal string), and the effect of the attribute
11767 definition is to set the value of the array at the specified index.
11768 For the @code{^Default_Switches^Default_Switches^} attribute,
11769 the index is a programming language (in our case, Ada),
11770 and the value specified (after @code{use}) must be a list
11771 of string expressions.
11772
11773 The attributes permitted in project files are restricted to a predefined set.
11774 Some may appear at project level, others in packages.
11775 For any attribute that is an associative array, the index must always be a
11776 literal string, but the restrictions on this string (e.g., a file name or a
11777 language name) depend on the individual attribute.
11778 Also depending on the attribute, its specified value will need to be either a
11779 string or a string list.
11780
11781 In the @code{Debug} project, we set the switches for two tools,
11782 @command{gnatmake} and the compiler, and thus we include the two corresponding
11783 packages; each package defines the @code{^Default_Switches^Default_Switches^}
11784 attribute with index @code{"Ada"}.
11785 Note that the package corresponding to
11786 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
11787 similar, but only includes the @code{Compiler} package.
11788
11789 In project @code{Debug} above, the ^switches^switches^ starting with
11790 @option{-gnat} that are specified in package @code{Compiler}
11791 could have been placed in package @code{Builder}, since @command{gnatmake}
11792 transmits all such ^switches^switches^ to the compiler.
11793
11794 @node Main Subprograms
11795 @unnumberedsubsubsec Main Subprograms
11796
11797 @noindent
11798 One of the specifiable properties of a project is a list of files that contain
11799 main subprograms.  This property is captured in the @code{Main} attribute,
11800 whose value is a list of strings.  If a project defines the @code{Main}
11801 attribute, it is not necessary to identify the main subprogram(s) when
11802 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
11803
11804 @node Executable File Names
11805 @unnumberedsubsubsec Executable File Names
11806
11807 @noindent
11808 By default, the executable file name corresponding to a main source is
11809 deduced from the main source file name. Through the attributes
11810 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
11811 it is possible to change this default.
11812 In project @code{Debug} above, the executable file name
11813 for main source @file{^proc.adb^PROC.ADB^} is
11814 @file{^proc1^PROC1.EXE^}.
11815 Attribute @code{Executable_Suffix}, when specified, may change the suffix
11816 of the executable files, when no attribute @code{Executable} applies:
11817 its value replace the platform-specific executable suffix.
11818 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
11819 specify a non-default executable file name when several mains are built at once
11820 in a single @command{gnatmake} command.
11821
11822 @node Source File Naming Conventions
11823 @unnumberedsubsubsec Source File Naming Conventions
11824
11825 @noindent
11826 Since the project files above do not specify any source file naming
11827 conventions, the GNAT defaults are used.  The mechanism for defining source
11828 file naming conventions -- a package named @code{Naming} --
11829 is described below (@pxref{Naming Schemes}).
11830
11831 @node Source Language(s)
11832 @unnumberedsubsubsec Source Language(s)
11833
11834 @noindent
11835 Since the project files do not specify a @code{Languages} attribute, by
11836 default the GNAT tools assume that the language of the project file is Ada.
11837 More generally, a project can comprise source files
11838 in Ada, C, and/or other languages.
11839
11840 @node Using External Variables
11841 @subsection Using External Variables
11842
11843 @noindent
11844 Instead of supplying different project files for debug and release, we can
11845 define a single project file that queries an external variable (set either
11846 on the command line or via an ^environment variable^logical name^) in order to
11847 conditionally define the appropriate settings.  Again, assume that the
11848 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
11849 located in directory @file{^/common^[COMMON]^}.  The following project file,
11850 @file{build.gpr}, queries the external variable named @code{STYLE} and
11851 defines an object directory and ^switch^switch^ settings based on whether
11852 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
11853 the default is @code{"deb"}.
11854
11855 @smallexample @c projectfile
11856 @group
11857 project Build is
11858   for Main use ("proc");
11859
11860   type Style_Type is ("deb", "rel");
11861   Style : Style_Type := external ("STYLE", "deb");
11862
11863   case Style is
11864     when "deb" =>
11865       for Object_Dir use "debug";
11866
11867     when "rel" =>
11868       for Object_Dir use "release";
11869       for Exec_Dir use ".";
11870   end case;
11871 @end group
11872
11873 @group
11874   package Builder is
11875
11876     case Style is
11877       when "deb" =>
11878         for ^Default_Switches^Default_Switches^ ("Ada")
11879             use ("^-g^-g^");
11880         for Executable ("proc") use "proc1";
11881       when others =>
11882         null;
11883     end case;
11884
11885   end Builder;
11886 @end group
11887
11888 @group
11889   package Compiler is
11890
11891     case Style is
11892       when "deb" =>
11893         for ^Default_Switches^Default_Switches^ ("Ada")
11894             use ("^-gnata^-gnata^",
11895                  "^-gnato^-gnato^",
11896                  "^-gnatE^-gnatE^");
11897
11898       when "rel" =>
11899         for ^Default_Switches^Default_Switches^ ("Ada")
11900             use ("^-O2^-O2^");
11901     end case;
11902
11903   end Compiler;
11904
11905 end Build;
11906 @end group
11907 @end smallexample
11908
11909 @noindent
11910 @code{Style_Type} is an example of a @emph{string type}, which is the project
11911 file analog of an Ada enumeration type but whose components are string literals
11912 rather than identifiers.  @code{Style} is declared as a variable of this type.
11913
11914 The form @code{external("STYLE", "deb")} is known as an
11915 @emph{external reference}; its first argument is the name of an
11916 @emph{external variable}, and the second argument is a default value to be
11917 used if the external variable doesn't exist.  You can define an external
11918 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
11919 or you can use ^an environment variable^a logical name^
11920 as an external variable.
11921
11922 Each @code{case} construct is expanded by the Project Manager based on the
11923 value of @code{Style}. Thus the command
11924 @ifclear vms
11925 @smallexample
11926 gnatmake -P/common/build.gpr -XSTYLE=deb
11927 @end smallexample
11928 @end ifclear
11929
11930 @ifset vms
11931 @smallexample
11932 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
11933 @end smallexample
11934 @end ifset
11935
11936 @noindent
11937 is equivalent to the @command{gnatmake} invocation using the project file
11938 @file{debug.gpr} in the earlier example.  So is the command
11939 @smallexample
11940 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
11941 @end smallexample
11942
11943 @noindent
11944 since @code{"deb"} is the default for @code{STYLE}.
11945
11946 Analogously,
11947
11948 @ifclear vms
11949 @smallexample
11950 gnatmake -P/common/build.gpr -XSTYLE=rel
11951 @end smallexample
11952 @end ifclear
11953
11954 @ifset vms
11955 @smallexample
11956 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
11957 @end smallexample
11958 @end ifset
11959
11960 @noindent
11961 is equivalent to the @command{gnatmake} invocation using the project file
11962 @file{release.gpr} in the earlier example.
11963
11964 @node Importing Other Projects
11965 @subsection Importing Other Projects
11966 @cindex @code{ADA_PROJECT_PATH}
11967
11968 @noindent
11969 A compilation unit in a source file in one project may depend on compilation
11970 units in source files in other projects.  To compile this unit under
11971 control of a project file, the
11972 dependent project must @emph{import} the projects containing the needed source
11973 files.
11974 This effect is obtained using syntax similar to an Ada @code{with} clause,
11975 but where @code{with}ed entities are strings that denote project files.
11976
11977 As an example, suppose that the two projects @code{GUI_Proj} and
11978 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
11979 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
11980 and @file{^/comm^[COMM]^}, respectively.
11981 Suppose that the source files for @code{GUI_Proj} are
11982 @file{gui.ads} and @file{gui.adb}, and that the source files for
11983 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
11984 files is located in its respective project file directory.  Schematically:
11985
11986 @smallexample
11987 @group
11988 ^/gui^[GUI]^
11989   gui_proj.gpr
11990   gui.ads
11991   gui.adb
11992 @end group
11993
11994 @group
11995 ^/comm^[COMM]^
11996   comm_proj.gpr
11997   comm.ads
11998   comm.adb
11999 @end group
12000 @end smallexample
12001
12002 @noindent
12003 We want to develop an application in directory @file{^/app^[APP]^} that
12004 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
12005 the corresponding project files (e.g.@: the ^switch^switch^ settings
12006 and object directory).
12007 Skeletal code for a main procedure might be something like the following:
12008
12009 @smallexample @c ada
12010 @group
12011 with GUI, Comm;
12012 procedure App_Main is
12013    @dots{}
12014 begin
12015    @dots{}
12016 end App_Main;
12017 @end group
12018 @end smallexample
12019
12020 @noindent
12021 Here is a project file, @file{app_proj.gpr}, that achieves the desired
12022 effect:
12023
12024 @smallexample @c projectfile
12025 @group
12026 with "/gui/gui_proj", "/comm/comm_proj";
12027 project App_Proj is
12028    for Main use ("app_main");
12029 end App_Proj;
12030 @end group
12031 @end smallexample
12032
12033 @noindent
12034 Building an executable is achieved through the command:
12035 @smallexample
12036 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
12037 @end smallexample
12038 @noindent
12039 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
12040 in the directory where @file{app_proj.gpr} resides.
12041
12042 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
12043 (as illustrated above) the @code{with} clause can omit the extension.
12044
12045 Our example specified an absolute path for each imported project file.
12046 Alternatively, the directory name of an imported object can be omitted
12047 if either
12048 @itemize @bullet
12049 @item
12050 The imported project file is in the same directory as the importing project
12051 file, or
12052 @item
12053 You have defined ^an environment variable^a logical name^
12054 that includes the directory containing
12055 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
12056 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
12057 directory names separated by colons (semicolons on Windows).
12058 @end itemize
12059
12060 @noindent
12061 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
12062 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
12063 as follows:
12064
12065 @smallexample @c projectfile
12066 @group
12067 with "gui_proj", "comm_proj";
12068 project App_Proj is
12069    for Main use ("app_main");
12070 end App_Proj;
12071 @end group
12072 @end smallexample
12073
12074 @noindent
12075 Importing other projects can create ambiguities.
12076 For example, the same unit might be present in different imported projects, or
12077 it might be present in both the importing project and in an imported project.
12078 Both of these conditions are errors.  Note that in the current version of
12079 the Project Manager, it is illegal to have an ambiguous unit even if the
12080 unit is never referenced by the importing project.  This restriction may be
12081 relaxed in a future release.
12082
12083 @node Extending a Project
12084 @subsection Extending a Project
12085
12086 @noindent
12087 In large software systems it is common to have multiple
12088 implementations of a common interface; in Ada terms, multiple versions of a
12089 package body for the same spec.  For example, one implementation
12090 might be safe for use in tasking programs, while another might only be used
12091 in sequential applications.  This can be modeled in GNAT using the concept
12092 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
12093 another project (the ``parent'') then by default all source files of the
12094 parent project are inherited by the child, but the child project can
12095 override any of the parent's source files with new versions, and can also
12096 add new files.  This facility is the project analog of a type extension in
12097 Object-Oriented Programming.  Project hierarchies are permitted (a child
12098 project may be the parent of yet another project), and a project that
12099 inherits one project can also import other projects.
12100
12101 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
12102 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
12103 @file{pack.adb}, and @file{proc.adb}:
12104
12105 @smallexample
12106 @group
12107 ^/seq^[SEQ]^
12108   pack.ads
12109   pack.adb
12110   proc.adb
12111   seq_proj.gpr
12112 @end group
12113 @end smallexample
12114
12115 @noindent
12116 Note that the project file can simply be empty (that is, no attribute or
12117 package is defined):
12118
12119 @smallexample @c projectfile
12120 @group
12121 project Seq_Proj is
12122 end Seq_Proj;
12123 @end group
12124 @end smallexample
12125
12126 @noindent
12127 implying that its source files are all the Ada source files in the project
12128 directory.
12129
12130 Suppose we want to supply an alternate version of @file{pack.adb}, in
12131 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
12132 @file{pack.ads} and @file{proc.adb}.  We can define a project
12133 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
12134
12135 @smallexample
12136 @group
12137 ^/tasking^[TASKING]^
12138   pack.adb
12139   tasking_proj.gpr
12140 @end group
12141
12142 @group
12143 project Tasking_Proj extends "/seq/seq_proj" is
12144 end Tasking_Proj;
12145 @end group
12146 @end smallexample
12147
12148 @noindent
12149 The version of @file{pack.adb} used in a build depends on which project file
12150 is specified.
12151
12152 Note that we could have obtained the desired behavior using project import
12153 rather than project inheritance; a @code{base} project would contain the
12154 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
12155 import @code{base} and add @file{pack.adb}, and likewise a tasking project
12156 would import @code{base} and add a different version of @file{pack.adb}.  The
12157 choice depends on whether other sources in the original project need to be
12158 overridden.  If they do, then project extension is necessary, otherwise,
12159 importing is sufficient.
12160
12161 @noindent
12162 In a project file that extends another project file, it is possible to
12163 indicate that an inherited source is not part of the sources of the extending
12164 project. This is necessary sometimes when a package spec has been overloaded
12165 and no longer requires a body: in this case, it is necessary to indicate that
12166 the inherited body is not part of the sources of the project, otherwise there
12167 will be a compilation error when compiling the spec.
12168
12169 For that purpose, the attribute @code{Excluded_Source_Files} is used.
12170 Its value is a string list: a list of file names. It is also possible to use
12171 attribute @code{Excluded_Source_List_File}. Its value is a single string:
12172 the file name of a text file containing a list of file names, one per line.
12173
12174 @smallexample @c @projectfile
12175 project B extends "a" is
12176    for Source_Files use ("pkg.ads");
12177    --  New spec of Pkg does not need a completion
12178    for Excluded_Source_Files use ("pkg.adb");
12179 end B;
12180 @end smallexample
12181
12182 Attribute @code{Excluded_Source_Files} may also be used to check if a source
12183 is still needed: if it is possible to build using @command{gnatmake} when such
12184 a source is put in attribute @code{Excluded_Source_Files} of a project P, then
12185 it is possible to remove the source completely from a system that includes
12186 project P.
12187
12188 @c ***********************
12189 @c * Project File Syntax *
12190 @c ***********************
12191
12192 @node Project File Syntax
12193 @section Project File Syntax
12194
12195 @menu
12196 * Basic Syntax::
12197 * Qualified Projects::
12198 * Packages::
12199 * Expressions::
12200 * String Types::
12201 * Variables::
12202 * Attributes::
12203 * Associative Array Attributes::
12204 * case Constructions::
12205 @end menu
12206
12207 @noindent
12208 This section describes the structure of project files.
12209
12210 A project may be an @emph{independent project}, entirely defined by a single
12211 project file. Any Ada source file in an independent project depends only
12212 on the predefined library and other Ada source files in the same project.
12213
12214 @noindent
12215 A project may also @dfn{depend on} other projects, in either or both of
12216 the following ways:
12217 @itemize @bullet
12218 @item It may import any number of projects
12219 @item It may extend at most one other project
12220 @end itemize
12221
12222 @noindent
12223 The dependence relation is a directed acyclic graph (the subgraph reflecting
12224 the ``extends'' relation is a tree).
12225
12226 A project's @dfn{immediate sources} are the source files directly defined by
12227 that project, either implicitly by residing in the project file's directory,
12228 or explicitly through any of the source-related attributes described below.
12229 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
12230 of @var{proj} together with the immediate sources (unless overridden) of any
12231 project on which @var{proj} depends (either directly or indirectly).
12232
12233 @node Basic Syntax
12234 @subsection Basic Syntax
12235
12236 @noindent
12237 As seen in the earlier examples, project files have an Ada-like syntax.
12238 The minimal project file is:
12239 @smallexample @c projectfile
12240 @group
12241 project Empty is
12242
12243 end Empty;
12244 @end group
12245 @end smallexample
12246
12247 @noindent
12248 The identifier @code{Empty} is the name of the project.
12249 This project name must be present after the reserved
12250 word @code{end} at the end of the project file, followed by a semi-colon.
12251
12252 Any name in a project file, such as the project name or a variable name,
12253 has the same syntax as an Ada identifier.
12254
12255 The reserved words of project files are the Ada 95 reserved words plus
12256 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
12257 reserved words currently used in project file syntax are:
12258
12259 @itemize @bullet
12260 @item
12261 @code{all}
12262 @item
12263 @code{at}
12264 @item
12265 @code{case}
12266 @item
12267 @code{end}
12268 @item
12269 @code{for}
12270 @item
12271 @code{is}
12272 @item
12273 @code{limited}
12274 @item
12275 @code{null}
12276 @item
12277 @code{others}
12278 @item
12279 @code{package}
12280 @item
12281 @code{renames}
12282 @item
12283 @code{type}
12284 @item
12285 @code{use}
12286 @item
12287 @code{when}
12288 @item
12289 @code{with}
12290 @end itemize
12291
12292 @noindent
12293 Comments in project files have the same syntax as in Ada, two consecutive
12294 hyphens through the end of the line.
12295
12296 @node Qualified Projects
12297 @subsection Qualified Projects
12298
12299 @noindent
12300 Before the reserved @code{project}, there may be one or two "qualifiers", that
12301 is identifiers or other reserved words, to qualify the project.
12302
12303 The current list of qualifiers is:
12304
12305 @itemize @bullet
12306 @item
12307 @code{abstract}: qualify a project with no sources. An abstract project must
12308 have a declaration specifying that there are no sources in the project, and,
12309 if it extends another project, the project it extends must also be a qualified
12310 abstract project.
12311
12312 @item
12313 @code{standard}: a standard project is a non library project with sources.
12314
12315 @item
12316 @code{aggregate}: for future extension
12317
12318 @item
12319 @code{aggregate library}: for future extension
12320
12321 @item
12322 @code{library}: a library project must declare both attributes
12323 @code{Library_Name} and @code{Library_Dir}.
12324
12325 @item
12326 @code{configuration}: a configuration project cannot be in a project tree.
12327 @end itemize
12328
12329 @node Packages
12330 @subsection Packages
12331
12332 @noindent
12333 A project file may contain @emph{packages}. The name of a package must be one
12334 of the identifiers from the following list. A package
12335 with a given name may only appear once in a project file. Package names are
12336 case insensitive. The following package names are legal:
12337
12338 @itemize @bullet
12339 @item
12340 @code{Naming}
12341 @item
12342 @code{Builder}
12343 @item
12344 @code{Compiler}
12345 @item
12346 @code{Binder}
12347 @item
12348 @code{Linker}
12349 @item
12350 @code{Finder}
12351 @item
12352 @code{Cross_Reference}
12353 @item
12354 @code{Eliminate}
12355 @item
12356 @code{Pretty_Printer}
12357 @item
12358 @code{Metrics}
12359 @item
12360 @code{gnatls}
12361 @item
12362 @code{gnatstub}
12363 @item
12364 @code{IDE}
12365 @item
12366 @code{Language_Processing}
12367 @end itemize
12368
12369 @noindent
12370 In its simplest form, a package may be empty:
12371
12372 @smallexample @c projectfile
12373 @group
12374 project Simple is
12375   package Builder is
12376   end Builder;
12377 end Simple;
12378 @end group
12379 @end smallexample
12380
12381 @noindent
12382 A package may contain @emph{attribute declarations},
12383 @emph{variable declarations} and @emph{case constructions}, as will be
12384 described below.
12385
12386 When there is ambiguity between a project name and a package name,
12387 the name always designates the project. To avoid possible confusion, it is
12388 always a good idea to avoid naming a project with one of the
12389 names allowed for packages or any name that starts with @code{gnat}.
12390
12391 @node Expressions
12392 @subsection Expressions
12393
12394 @noindent
12395 An @emph{expression} is either a @emph{string expression} or a
12396 @emph{string list expression}.
12397
12398 A @emph{string expression} is either a @emph{simple string expression} or a
12399 @emph{compound string expression}.
12400
12401 A @emph{simple string expression} is one of the following:
12402 @itemize @bullet
12403 @item A literal string; e.g.@: @code{"comm/my_proj.gpr"}
12404 @item A string-valued variable reference (@pxref{Variables})
12405 @item A string-valued attribute reference (@pxref{Attributes})
12406 @item An external reference (@pxref{External References in Project Files})
12407 @end itemize
12408
12409 @noindent
12410 A @emph{compound string expression} is a concatenation of string expressions,
12411 using the operator @code{"&"}
12412 @smallexample
12413        Path & "/" & File_Name & ".ads"
12414 @end smallexample
12415
12416 @noindent
12417 A @emph{string list expression} is either a
12418 @emph{simple string list expression} or a
12419 @emph{compound string list expression}.
12420
12421 A @emph{simple string list expression} is one of the following:
12422 @itemize @bullet
12423 @item A parenthesized list of zero or more string expressions,
12424 separated by commas
12425 @smallexample
12426    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
12427    Empty_List := ();
12428 @end smallexample
12429 @item A string list-valued variable reference
12430 @item A string list-valued attribute reference
12431 @end itemize
12432
12433 @noindent
12434 A @emph{compound string list expression} is the concatenation (using
12435 @code{"&"}) of a simple string list expression and an expression.  Note that
12436 each term in a compound string list expression, except the first, may be
12437 either a string expression or a string list expression.
12438
12439 @smallexample @c projectfile
12440 @group
12441    File_Name_List := () & File_Name; --  One string in this list
12442    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
12443    --  Two strings
12444    Big_List := File_Name_List & Extended_File_Name_List;
12445    --  Concatenation of two string lists: three strings
12446    Illegal_List := "gnat.adc" & Extended_File_Name_List;
12447    --  Illegal: must start with a string list
12448 @end group
12449 @end smallexample
12450
12451 @node String Types
12452 @subsection String Types
12453
12454 @noindent
12455 A @emph{string type declaration} introduces a discrete set of string literals.
12456 If a string variable is declared to have this type, its value
12457 is restricted to the given set of literals.
12458
12459 Here is an example of a string type declaration:
12460
12461 @smallexample @c projectfile
12462    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
12463 @end smallexample
12464
12465 @noindent
12466 Variables of a string type are called @emph{typed variables}; all other
12467 variables are called @emph{untyped variables}. Typed variables are
12468 particularly useful in @code{case} constructions, to support conditional
12469 attribute declarations.
12470 (@pxref{case Constructions}).
12471
12472 The string literals in the list are case sensitive and must all be different.
12473 They may include any graphic characters allowed in Ada, including spaces.
12474
12475 A string type may only be declared at the project level, not inside a package.
12476
12477 A string type may be referenced by its name if it has been declared in the same
12478 project file, or by an expanded name whose prefix is the name of the project
12479 in which it is declared.
12480
12481 @node Variables
12482 @subsection Variables
12483
12484 @noindent
12485 A variable may be declared at the project file level, or within a package.
12486 Here are some examples of variable declarations:
12487
12488 @smallexample @c projectfile
12489 @group
12490    This_OS : OS := external ("OS"); --  a typed variable declaration
12491    That_OS := "GNU/Linux";          --  an untyped variable declaration
12492 @end group
12493 @end smallexample
12494
12495 @noindent
12496 The syntax of a @emph{typed variable declaration} is identical to the Ada
12497 syntax for an object declaration. By contrast, the syntax of an untyped
12498 variable declaration is identical to an Ada assignment statement. In fact,
12499 variable declarations in project files have some of the characteristics of
12500 an assignment, in that successive declarations for the same variable are
12501 allowed. Untyped variable declarations do establish the expected kind of the
12502 variable (string or string list), and successive declarations for it must
12503 respect the initial kind.
12504
12505 @noindent
12506 A string variable declaration (typed or untyped) declares a variable
12507 whose value is a string. This variable may be used as a string expression.
12508 @smallexample @c projectfile
12509    File_Name       := "readme.txt";
12510    Saved_File_Name := File_Name & ".saved";
12511 @end smallexample
12512
12513 @noindent
12514 A string list variable declaration declares a variable whose value is a list
12515 of strings. The list may contain any number (zero or more) of strings.
12516
12517 @smallexample @c projectfile
12518    Empty_List := ();
12519    List_With_One_Element := ("^-gnaty^-gnaty^");
12520    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
12521    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
12522                  "pack2.ada", "util_.ada", "util.ada");
12523 @end smallexample
12524
12525 @noindent
12526 The same typed variable may not be declared more than once at project level,
12527 and it may not be declared more than once in any package; it is in effect
12528 a constant.
12529
12530 The same untyped variable may be declared several times. Declarations are
12531 elaborated in the order in which they appear, so  the new value replaces
12532 the old one, and any subsequent reference to the variable uses the new value.
12533 However, as noted above, if a variable has been declared as a string, all
12534 subsequent
12535 declarations must give it a string value. Similarly, if a variable has
12536 been declared as a string list, all subsequent declarations
12537 must give it a string list value.
12538
12539 A @emph{variable reference} may take several forms:
12540
12541 @itemize @bullet
12542 @item The simple variable name, for a variable in the current package (if any)
12543 or in the current project
12544 @item An expanded name, whose prefix is a context name.
12545 @end itemize
12546
12547 @noindent
12548 A @emph{context} may be one of the following:
12549
12550 @itemize @bullet
12551 @item The name of an existing package in the current project
12552 @item The name of an imported project of the current project
12553 @item The name of an ancestor project (i.e., a project extended by the current
12554 project, either directly or indirectly)
12555 @item An expanded name whose prefix is an imported/parent project name, and
12556 whose selector is a package name in that project.
12557 @end itemize
12558
12559 @noindent
12560 A variable reference may be used in an expression.
12561
12562 @node Attributes
12563 @subsection Attributes
12564
12565 @noindent
12566 A project (and its packages) may have @emph{attributes} that define
12567 the project's properties.  Some attributes have values that are strings;
12568 others have values that are string lists.
12569
12570 There are two categories of attributes: @emph{simple attributes}
12571 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
12572
12573 Legal project attribute names, and attribute names for each legal package are
12574 listed below. Attributes names are case-insensitive.
12575
12576 The following attributes are defined on projects (all are simple attributes):
12577
12578 @multitable @columnfractions .4 .3
12579 @item @emph{Attribute Name}
12580 @tab @emph{Value}
12581 @item @code{Source_Files}
12582 @tab string list
12583 @item @code{Source_Dirs}
12584 @tab string list
12585 @item @code{Source_List_File}
12586 @tab string
12587 @item @code{Object_Dir}
12588 @tab string
12589 @item @code{Exec_Dir}
12590 @tab string
12591 @item @code{Excluded_Source_Dirs}
12592 @tab string list
12593 @item @code{Excluded_Source_Files}
12594 @tab string list
12595 @item @code{Excluded_Source_List_File}
12596 @tab string
12597 @item @code{Languages}
12598 @tab string list
12599 @item @code{Main}
12600 @tab string list
12601 @item @code{Library_Dir}
12602 @tab string
12603 @item @code{Library_Name}
12604 @tab string
12605 @item @code{Library_Kind}
12606 @tab string
12607 @item @code{Library_Version}
12608 @tab string
12609 @item @code{Library_Interface}
12610 @tab string
12611 @item @code{Library_Auto_Init}
12612 @tab string
12613 @item @code{Library_Options}
12614 @tab string list
12615 @item @code{Library_Src_Dir}
12616 @tab string
12617 @item @code{Library_ALI_Dir}
12618 @tab string
12619 @item @code{Library_GCC}
12620 @tab string
12621 @item @code{Library_Symbol_File}
12622 @tab string
12623 @item @code{Library_Symbol_Policy}
12624 @tab string
12625 @item @code{Library_Reference_Symbol_File}
12626 @tab string
12627 @item @code{Externally_Built}
12628 @tab string
12629 @end multitable
12630
12631 @noindent
12632 The following attributes are defined for package  @code{Naming}
12633 (@pxref{Naming Schemes}):
12634
12635 @multitable @columnfractions .4 .2 .2 .2
12636 @item Attribute Name @tab Category @tab Index @tab Value
12637 @item @code{Spec_Suffix}
12638 @tab associative array
12639 @tab language name
12640 @tab string
12641 @item @code{Body_Suffix}
12642 @tab associative array
12643 @tab language name
12644 @tab string
12645 @item @code{Separate_Suffix}
12646 @tab simple attribute
12647 @tab n/a
12648 @tab string
12649 @item @code{Casing}
12650 @tab simple attribute
12651 @tab n/a
12652 @tab string
12653 @item @code{Dot_Replacement}
12654 @tab simple attribute
12655 @tab n/a
12656 @tab string
12657 @item @code{Spec}
12658 @tab associative array
12659 @tab Ada unit name
12660 @tab string
12661 @item @code{Body}
12662 @tab associative array
12663 @tab Ada unit name
12664 @tab string
12665 @item @code{Specification_Exceptions}
12666 @tab associative array
12667 @tab language name
12668 @tab string list
12669 @item @code{Implementation_Exceptions}
12670 @tab associative array
12671 @tab language name
12672 @tab string list
12673 @end multitable
12674
12675 @noindent
12676 The following attributes are defined for packages @code{Builder},
12677 @code{Compiler}, @code{Binder},
12678 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
12679 (@pxref{^Switches^Switches^ and Project Files}).
12680
12681 @multitable @columnfractions .4 .2 .2 .2
12682 @item Attribute Name @tab Category @tab Index @tab Value
12683 @item @code{^Default_Switches^Default_Switches^}
12684 @tab associative array
12685 @tab language name
12686 @tab string list
12687 @item @code{^Switches^Switches^}
12688 @tab associative array
12689 @tab file name
12690 @tab string list
12691 @end multitable
12692
12693 @noindent
12694 In addition, package @code{Compiler} has a single string attribute
12695 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
12696 string attribute @code{Global_Configuration_Pragmas}.
12697
12698 @noindent
12699 Each simple attribute has a default value: the empty string (for string-valued
12700 attributes) and the empty list (for string list-valued attributes).
12701
12702 An attribute declaration defines a new value for an attribute.
12703
12704 Examples of simple attribute declarations:
12705
12706 @smallexample @c projectfile
12707    for Object_Dir use "objects";
12708    for Source_Dirs use ("units", "test/drivers");
12709 @end smallexample
12710
12711 @noindent
12712 The syntax of a @dfn{simple attribute declaration} is similar to that of an
12713 attribute definition clause in Ada.
12714
12715 Attributes references may be appear in expressions.
12716 The general form for such a reference is @code{<entity>'<attribute>}:
12717 Associative array attributes are functions. Associative
12718 array attribute references must have an argument that is a string literal.
12719
12720 Examples are:
12721
12722 @smallexample @c projectfile
12723   project'Object_Dir
12724   Naming'Dot_Replacement
12725   Imported_Project'Source_Dirs
12726   Imported_Project.Naming'Casing
12727   Builder'^Default_Switches^Default_Switches^("Ada")
12728 @end smallexample
12729
12730 @noindent
12731 The prefix of an attribute may be:
12732 @itemize @bullet
12733 @item @code{project} for an attribute of the current project
12734 @item The name of an existing package of the current project
12735 @item The name of an imported project
12736 @item The name of a parent project that is extended by the current project
12737 @item An expanded name whose prefix is imported/parent project name,
12738 and whose selector is a package name
12739 @end itemize
12740
12741 @noindent
12742 Example:
12743 @smallexample @c projectfile
12744 @group
12745    project Prj is
12746      for Source_Dirs use project'Source_Dirs & "units";
12747      for Source_Dirs use project'Source_Dirs & "test/drivers"
12748    end Prj;
12749 @end group
12750 @end smallexample
12751
12752 @noindent
12753 In the first attribute declaration, initially the attribute @code{Source_Dirs}
12754 has the default value: an empty string list. After this declaration,
12755 @code{Source_Dirs} is a string list of one element: @code{"units"}.
12756 After the second attribute declaration @code{Source_Dirs} is a string list of
12757 two elements: @code{"units"} and @code{"test/drivers"}.
12758
12759 Note: this example is for illustration only. In practice,
12760 the project file would contain only one attribute declaration:
12761
12762 @smallexample @c projectfile
12763    for Source_Dirs use ("units", "test/drivers");
12764 @end smallexample
12765
12766 @node Associative Array Attributes
12767 @subsection Associative Array Attributes
12768
12769 @noindent
12770 Some attributes are defined as @emph{associative arrays}. An associative
12771 array may be regarded as a function that takes a string as a parameter
12772 and delivers a string or string list value as its result.
12773
12774 Here are some examples of single associative array attribute associations:
12775
12776 @smallexample @c projectfile
12777    for Body ("main") use "Main.ada";
12778    for ^Switches^Switches^ ("main.ada")
12779        use ("^-v^-v^",
12780             "^-gnatv^-gnatv^");
12781    for ^Switches^Switches^ ("main.ada")
12782             use Builder'^Switches^Switches^ ("main.ada")
12783               & "^-g^-g^";
12784 @end smallexample
12785
12786 @noindent
12787 Like untyped variables and simple attributes, associative array attributes
12788 may be declared several times. Each declaration supplies a new value for the
12789 attribute, and replaces the previous setting.
12790
12791 @noindent
12792 An associative array attribute may be declared as a full associative array
12793 declaration, with the value of the same attribute in an imported or extended
12794 project.
12795
12796 @smallexample @c projectfile
12797    package Builder is
12798       for Default_Switches use Default.Builder'Default_Switches;
12799    end Builder;
12800 @end smallexample
12801
12802 @noindent
12803 In this example, @code{Default} must be either a project imported by the
12804 current project, or the project that the current project extends. If the
12805 attribute is in a package (in this case, in package @code{Builder}), the same
12806 package needs to be specified.
12807
12808 @noindent
12809 A full associative array declaration replaces any other declaration for the
12810 attribute, including other full associative array declaration. Single
12811 associative array associations may be declare after a full associative
12812 declaration, modifying the value for a single association of the attribute.
12813
12814 @node case Constructions
12815 @subsection @code{case} Constructions
12816
12817 @noindent
12818 A @code{case} construction is used in a project file to effect conditional
12819 behavior.
12820 Here is a typical example:
12821
12822 @smallexample @c projectfile
12823 @group
12824 project MyProj is
12825    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
12826
12827    OS : OS_Type := external ("OS", "GNU/Linux");
12828 @end group
12829
12830 @group
12831    package Compiler is
12832      case OS is
12833        when "GNU/Linux" | "Unix" =>
12834          for ^Default_Switches^Default_Switches^ ("Ada")
12835              use ("^-gnath^-gnath^");
12836        when "NT" =>
12837          for ^Default_Switches^Default_Switches^ ("Ada")
12838              use ("^-gnatP^-gnatP^");
12839        when others =>
12840      end case;
12841    end Compiler;
12842 end MyProj;
12843 @end group
12844 @end smallexample
12845
12846 @noindent
12847 The syntax of a @code{case} construction is based on the Ada case statement
12848 (although there is no @code{null} construction for empty alternatives).
12849
12850 The case expression must be a typed string variable.
12851 Each alternative comprises the reserved word @code{when}, either a list of
12852 literal strings separated by the @code{"|"} character or the reserved word
12853 @code{others},  and the @code{"=>"} token.
12854 Each literal string must belong to the string type that is the type of the
12855 case variable.
12856 An @code{others} alternative, if present, must occur last.
12857
12858 After each @code{=>}, there are zero or more constructions.  The only
12859 constructions allowed in a case construction are other case constructions,
12860 attribute declarations and variable declarations. String type declarations and
12861 package declarations are not allowed. Variable declarations are restricted to
12862 variables that have already been declared before the case construction.
12863
12864 The value of the case variable is often given by an external reference
12865 (@pxref{External References in Project Files}).
12866
12867 @c ****************************************
12868 @c * Objects and Sources in Project Files *
12869 @c ****************************************
12870
12871 @node Objects and Sources in Project Files
12872 @section Objects and Sources in Project Files
12873
12874 @menu
12875 * Object Directory::
12876 * Exec Directory::
12877 * Source Directories::
12878 * Source File Names::
12879 @end menu
12880
12881 @noindent
12882 Each project has exactly one object directory and one or more source
12883 directories. The source directories must contain at least one source file,
12884 unless  the project file explicitly specifies that no source files are present
12885 (@pxref{Source File Names}).
12886
12887 @node Object Directory
12888 @subsection Object Directory
12889
12890 @noindent
12891 The object directory for a project is the directory containing the compiler's
12892 output (such as @file{ALI} files and object files) for the project's immediate
12893 sources.
12894
12895 The object directory is given by the value of the attribute @code{Object_Dir}
12896 in the project file.
12897
12898 @smallexample @c projectfile
12899    for Object_Dir use "objects";
12900 @end smallexample
12901
12902 @noindent
12903 The attribute @code{Object_Dir} has a string value, the path name of the object
12904 directory. The path name may be absolute or relative to the directory of the
12905 project file. This directory must already exist, and be readable and writable.
12906
12907 By default, when the attribute @code{Object_Dir} is not given an explicit value
12908 or when its value is the empty string, the object directory is the same as the
12909 directory containing the project file.
12910
12911 @node Exec Directory
12912 @subsection Exec Directory
12913
12914 @noindent
12915 The exec directory for a project is the directory containing the executables
12916 for the project's main subprograms.
12917
12918 The exec directory is given by the value of the attribute @code{Exec_Dir}
12919 in the project file.
12920
12921 @smallexample @c projectfile
12922    for Exec_Dir use "executables";
12923 @end smallexample
12924
12925 @noindent
12926 The attribute @code{Exec_Dir} has a string value, the path name of the exec
12927 directory. The path name may be absolute or relative to the directory of the
12928 project file. This directory must already exist, and be writable.
12929
12930 By default, when the attribute @code{Exec_Dir} is not given an explicit value
12931 or when its value is the empty string, the exec directory is the same as the
12932 object directory of the project file.
12933
12934 @node Source Directories
12935 @subsection Source Directories
12936
12937 @noindent
12938 The source directories of a project are specified by the project file
12939 attribute @code{Source_Dirs}.
12940
12941 This attribute's value is a string list. If the attribute is not given an
12942 explicit value, then there is only one source directory, the one where the
12943 project file resides.
12944
12945 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
12946 as in
12947
12948 @smallexample @c projectfile
12949     for Source_Dirs use ();
12950 @end smallexample
12951
12952 @noindent
12953 indicates that the project contains no source files.
12954
12955 Otherwise, each string in the string list designates one or more
12956 source directories.
12957
12958 @smallexample @c projectfile
12959    for Source_Dirs use ("sources", "test/drivers");
12960 @end smallexample
12961
12962 @noindent
12963 If a string in the list ends with @code{"/**"},  then the directory whose path
12964 name precedes the two asterisks, as well as all its subdirectories
12965 (recursively), are source directories.
12966
12967 @smallexample @c projectfile
12968    for Source_Dirs use ("/system/sources/**");
12969 @end smallexample
12970
12971 @noindent
12972 Here the directory @code{/system/sources} and all of its subdirectories
12973 (recursively) are source directories.
12974
12975 To specify that the source directories are the directory of the project file
12976 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
12977 @smallexample @c projectfile
12978    for Source_Dirs use ("./**");
12979 @end smallexample
12980
12981 @noindent
12982 Each of the source directories must exist and be readable.
12983
12984 @node Source File Names
12985 @subsection Source File Names
12986
12987 @noindent
12988 In a project that contains source files, their names may be specified by the
12989 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
12990 (a string). Source file names never include any directory information.
12991
12992 If the attribute @code{Source_Files} is given an explicit value, then each
12993 element of the list is a source file name.
12994
12995 @smallexample @c projectfile
12996    for Source_Files use ("main.adb");
12997    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
12998 @end smallexample
12999
13000 @noindent
13001 If the attribute @code{Source_Files} is not given an explicit value,
13002 but the attribute @code{Source_List_File} is given a string value,
13003 then the source file names are contained in the text file whose path name
13004 (absolute or relative to the directory of the project file) is the
13005 value of the attribute @code{Source_List_File}.
13006
13007 Each line in the file that is not empty or is not a comment
13008 contains a source file name.
13009
13010 @smallexample @c projectfile
13011    for Source_List_File use "source_list.txt";
13012 @end smallexample
13013
13014 @noindent
13015 By default, if neither the attribute @code{Source_Files} nor the attribute
13016 @code{Source_List_File} is given an explicit value, then each file in the
13017 source directories that conforms to the project's naming scheme
13018 (@pxref{Naming Schemes}) is an immediate source of the project.
13019
13020 A warning is issued if both attributes @code{Source_Files} and
13021 @code{Source_List_File} are given explicit values. In this case, the attribute
13022 @code{Source_Files} prevails.
13023
13024 Each source file name must be the name of one existing source file
13025 in one of the source directories.
13026
13027 A @code{Source_Files} attribute whose value is an empty list
13028 indicates that there are no source files in the project.
13029
13030 If the order of the source directories is known statically, that is if
13031 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
13032 be several files with the same source file name. In this case, only the file
13033 in the first directory is considered as an immediate source of the project
13034 file. If the order of the source directories is not known statically, it is
13035 an error to have several files with the same source file name.
13036
13037 Projects can be specified to have no Ada source
13038 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
13039 list, or the @code{"Ada"} may be absent from @code{Languages}:
13040
13041 @smallexample @c projectfile
13042    for Source_Dirs use ();
13043    for Source_Files use ();
13044    for Languages use ("C", "C++");
13045 @end smallexample
13046
13047 @noindent
13048 Otherwise, a project must contain at least one immediate source.
13049
13050 Projects with no source files are useful as template packages
13051 (@pxref{Packages in Project Files}) for other projects; in particular to
13052 define a package @code{Naming} (@pxref{Naming Schemes}).
13053
13054 @c ****************************
13055 @c * Importing Projects *
13056 @c ****************************
13057
13058 @node  Importing Projects
13059 @section Importing Projects
13060 @cindex @code{ADA_PROJECT_PATH}
13061
13062 @noindent
13063 An immediate source of a project P may depend on source files that
13064 are neither immediate sources of P nor in the predefined library.
13065 To get this effect, P must @emph{import} the projects that contain the needed
13066 source files.
13067
13068 @smallexample @c projectfile
13069 @group
13070   with "project1", "utilities.gpr";
13071   with "/namings/apex.gpr";
13072   project Main is
13073     @dots{}
13074 @end group
13075 @end smallexample
13076
13077 @noindent
13078 As can be seen in this example, the syntax for importing projects is similar
13079 to the syntax for importing compilation units in Ada. However, project files
13080 use literal strings instead of names, and the @code{with} clause identifies
13081 project files rather than packages.
13082
13083 Each literal string is the file name or path name (absolute or relative) of a
13084 project file. If a string corresponds to a file name, with no path or a
13085 relative path, then its location is determined by the @emph{project path}. The
13086 latter can be queried using @code{gnatls -v}. It contains:
13087
13088 @itemize @bullet
13089 @item
13090 In first position, the directory containing the current project file.
13091 @item
13092 In last position, the default project directory. This default project directory
13093 is part of the GNAT installation and is the standard place to install project
13094 files giving access to standard support libraries.
13095 @ifclear vms
13096 @ref{Installing a library}
13097 @end ifclear
13098
13099 @item
13100 In between, all the directories referenced in the
13101 ^environment variable^logical name^ @env{ADA_PROJECT_PATH} if it exists.
13102 @end itemize
13103
13104 @noindent
13105 If a relative pathname is used, as in
13106
13107 @smallexample @c projectfile
13108   with "tests/proj";
13109 @end smallexample
13110
13111 @noindent
13112 then the full path for the project is constructed by concatenating this
13113 relative path to those in the project path, in order, until a matching file is
13114 found. Any symbolic link will be fully resolved in the directory of the
13115 importing project file before the imported project file is examined.
13116
13117 If the @code{with}'ed project file name does not have an extension,
13118 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
13119 then the file name as specified in the @code{with} clause (no extension) will
13120 be used. In the above example, if a file @code{project1.gpr} is found, then it
13121 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
13122 then it will be used; if neither file exists, this is an error.
13123
13124 A warning is issued if the name of the project file does not match the
13125 name of the project; this check is case insensitive.
13126
13127 Any source file that is an immediate source of the imported project can be
13128 used by the immediate sources of the importing project, transitively. Thus
13129 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
13130 sources of @code{A} may depend on the immediate sources of @code{C}, even if
13131 @code{A} does not import @code{C} explicitly. However, this is not recommended,
13132 because if and when @code{B} ceases to import @code{C}, some sources in
13133 @code{A} will no longer compile.
13134
13135 A side effect of this capability is that normally cyclic dependencies are not
13136 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
13137 is not allowed to import @code{A}. However, there are cases when cyclic
13138 dependencies would be beneficial. For these cases, another form of import
13139 between projects exists, the @code{limited with}: a project @code{A} that
13140 imports a project @code{B} with a straight @code{with} may also be imported,
13141 directly or indirectly, by @code{B} on the condition that imports from @code{B}
13142 to @code{A} include at least one @code{limited with}.
13143
13144 @smallexample @c 0projectfile
13145 with "../b/b.gpr";
13146 with "../c/c.gpr";
13147 project A is
13148 end A;
13149
13150 limited with "../a/a.gpr";
13151 project B is
13152 end B;
13153
13154 with "../d/d.gpr";
13155 project C is
13156 end C;
13157
13158 limited with "../a/a.gpr";
13159 project D is
13160 end D;
13161 @end smallexample
13162
13163 @noindent
13164 In the above legal example, there are two project cycles:
13165 @itemize @bullet
13166 @item A-> B-> A
13167 @item A -> C -> D -> A
13168 @end itemize
13169
13170 @noindent
13171 In each of these cycle there is one @code{limited with}: import of @code{A}
13172 from @code{B} and import of @code{A} from @code{D}.
13173
13174 The difference between straight @code{with} and @code{limited with} is that
13175 the name of a project imported with a @code{limited with} cannot be used in the
13176 project that imports it. In particular, its packages cannot be renamed and
13177 its variables cannot be referred to.
13178
13179 An exception to the above rules for @code{limited with} is that for the main
13180 project specified to @command{gnatmake} or to the @command{GNAT} driver a
13181 @code{limited with} is equivalent to a straight @code{with}. For example,
13182 in the example above, projects @code{B} and @code{D} could not be main
13183 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
13184 each have a @code{limited with} that is the only one in a cycle of importing
13185 projects.
13186
13187 @c *********************
13188 @c * Project Extension *
13189 @c *********************
13190
13191 @node Project Extension
13192 @section Project Extension
13193
13194 @noindent
13195 During development of a large system, it is sometimes necessary to use
13196 modified versions of some of the source files, without changing the original
13197 sources. This can be achieved through the @emph{project extension} facility.
13198
13199 @smallexample @c projectfile
13200    project Modified_Utilities extends "/baseline/utilities.gpr" is @dots{}
13201 @end smallexample
13202
13203 @noindent
13204 A project extension declaration introduces an extending project
13205 (the @emph{child}) and a project being extended (the @emph{parent}).
13206
13207 By default, a child project inherits all the sources of its parent.
13208 However, inherited sources can be overridden: a unit in a parent is hidden
13209 by a unit of the same name in the child.
13210
13211 Inherited sources are considered to be sources (but not immediate sources)
13212 of the child project; see @ref{Project File Syntax}.
13213
13214 An inherited source file retains any switches specified in the parent project.
13215
13216 For example if the project @code{Utilities} contains the spec and the
13217 body of an Ada package @code{Util_IO}, then the project
13218 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
13219 The original body of @code{Util_IO} will not be considered in program builds.
13220 However, the package spec will still be found in the project
13221 @code{Utilities}.
13222
13223 A child project can have only one parent, except when it is qualified as
13224 abstract. But it may import any number of other projects.
13225
13226 A project is not allowed to import directly or indirectly at the same time a
13227 child project and any of its ancestors.
13228
13229 @c *******************************
13230 @c * Project Hierarchy Extension *
13231 @c *******************************
13232
13233 @node Project Hierarchy Extension
13234 @section Project Hierarchy Extension
13235
13236 @noindent
13237 When extending a large system spanning multiple projects, it is often
13238 inconvenient to extend every project in the hierarchy that is impacted by a
13239 small change introduced. In such cases, it is possible to create a virtual
13240 extension of entire hierarchy using @code{extends all} relationship.
13241
13242 When the project is extended using @code{extends all} inheritance, all projects
13243 that are imported by it, both directly and indirectly, are considered virtually
13244 extended. That is, the Project Manager creates "virtual projects"
13245 that extend every project in the hierarchy; all these virtual projects have
13246 no sources of their own and have as object directory the object directory of
13247 the root of "extending all" project.
13248
13249 It is possible to explicitly extend one or more projects in the hierarchy
13250 in order to modify the sources. These extending projects must be imported by
13251 the "extending all" project, which will replace the corresponding virtual
13252 projects with the explicit ones.
13253
13254 When building such a project hierarchy extension, the Project Manager will
13255 ensure that both modified sources and sources in virtual extending projects
13256 that depend on them, are recompiled.
13257
13258 By means of example, consider the following hierarchy of projects.
13259
13260 @enumerate
13261 @item
13262 project A, containing package P1
13263 @item
13264 project B importing A and containing package P2 which depends on P1
13265 @item
13266 project C importing B and containing package P3 which depends on P2
13267 @end enumerate
13268
13269 @noindent
13270 We want to modify packages P1 and P3.
13271
13272 This project hierarchy will need to be extended as follows:
13273
13274 @enumerate
13275 @item
13276 Create project A1 that extends A, placing modified P1 there:
13277
13278 @smallexample @c 0projectfile
13279 project A1 extends "(@dots{})/A" is
13280 end A1;
13281 @end smallexample
13282
13283 @item
13284 Create project C1 that "extends all" C and imports A1, placing modified
13285 P3 there:
13286
13287 @smallexample @c 0projectfile
13288 with "(@dots{})/A1";
13289 project C1 extends all "(@dots{})/C" is
13290 end C1;
13291 @end smallexample
13292 @end enumerate
13293
13294 When you build project C1, your entire modified project space will be
13295 recompiled, including the virtual project B1 that has been impacted by the
13296 "extending all" inheritance of project C.
13297
13298 Note that if a Library Project in the hierarchy is virtually extended,
13299 the virtual project that extends the Library Project is not a Library Project.
13300
13301 @c ****************************************
13302 @c * External References in Project Files *
13303 @c ****************************************
13304
13305 @node  External References in Project Files
13306 @section External References in Project Files
13307
13308 @noindent
13309 A project file may contain references to external variables; such references
13310 are called @emph{external references}.
13311
13312 An external variable is either defined as part of the environment (an
13313 environment variable in Unix, for example) or else specified on the command
13314 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
13315 If both, then the command line value is used.
13316
13317 The value of an external reference is obtained by means of the built-in
13318 function @code{external}, which returns a string value.
13319 This function has two forms:
13320 @itemize @bullet
13321 @item @code{external (external_variable_name)}
13322 @item @code{external (external_variable_name, default_value)}
13323 @end itemize
13324
13325 @noindent
13326 Each parameter must be a string literal.  For example:
13327
13328 @smallexample @c projectfile
13329    external ("USER")
13330    external ("OS", "GNU/Linux")
13331 @end smallexample
13332
13333 @noindent
13334 In the form with one parameter, the function returns the value of
13335 the external variable given as parameter. If this name is not present in the
13336 environment, the function returns an empty string.
13337
13338 In the form with two string parameters, the second argument is
13339 the value returned when the variable given as the first argument is not
13340 present in the environment. In the example above, if @code{"OS"} is not
13341 the name of ^an environment variable^a logical name^ and is not passed on
13342 the command line, then the returned value is @code{"GNU/Linux"}.
13343
13344 An external reference may be part of a string expression or of a string
13345 list expression, and can therefore appear in a variable declaration or
13346 an attribute declaration.
13347
13348 @smallexample @c projectfile
13349 @group
13350    type Mode_Type is ("Debug", "Release");
13351    Mode : Mode_Type := external ("MODE");
13352    case Mode is
13353      when "Debug" =>
13354         @dots{}
13355 @end group
13356 @end smallexample
13357
13358 @c *****************************
13359 @c * Packages in Project Files *
13360 @c *****************************
13361
13362 @node  Packages in Project Files
13363 @section Packages in Project Files
13364
13365 @noindent
13366 A @emph{package} defines the settings for project-aware tools within a
13367 project.
13368 For each such tool one can declare a package; the names for these
13369 packages are preset (@pxref{Packages}).
13370 A package may contain variable declarations, attribute declarations, and case
13371 constructions.
13372
13373 @smallexample @c projectfile
13374 @group
13375    project Proj is
13376       package Builder is  -- used by gnatmake
13377          for ^Default_Switches^Default_Switches^ ("Ada")
13378              use ("^-v^-v^",
13379                   "^-g^-g^");
13380       end Builder;
13381    end Proj;
13382 @end group
13383 @end smallexample
13384
13385 @noindent
13386 The syntax of package declarations mimics that of package in Ada.
13387
13388 Most of the packages have an attribute
13389 @code{^Default_Switches^Default_Switches^}.
13390 This attribute is an associative array, and its value is a string list.
13391 The index of the associative array is the name of a programming language (case
13392 insensitive). This attribute indicates the ^switch^switch^
13393 or ^switches^switches^ to be used
13394 with the corresponding tool.
13395
13396 Some packages also have another attribute, @code{^Switches^Switches^},
13397 an associative array whose value is a string list.
13398 The index is the name of a source file.
13399 This attribute indicates the ^switch^switch^
13400 or ^switches^switches^ to be used by the corresponding
13401 tool when dealing with this specific file.
13402
13403 Further information on these ^switch^switch^-related attributes is found in
13404 @ref{^Switches^Switches^ and Project Files}.
13405
13406 A package may be declared as a @emph{renaming} of another package; e.g., from
13407 the project file for an imported project.
13408
13409 @smallexample @c projectfile
13410 @group
13411   with "/global/apex.gpr";
13412   project Example is
13413     package Naming renames Apex.Naming;
13414     @dots{}
13415   end Example;
13416 @end group
13417 @end smallexample
13418
13419 @noindent
13420 Packages that are renamed in other project files often come from project files
13421 that have no sources: they are just used as templates. Any modification in the
13422 template will be reflected automatically in all the project files that rename
13423 a package from the template.
13424
13425 In addition to the tool-oriented packages, you can also declare a package
13426 named @code{Naming} to establish specialized source file naming conventions
13427 (@pxref{Naming Schemes}).
13428
13429 @c ************************************
13430 @c * Variables from Imported Projects *
13431 @c ************************************
13432
13433 @node Variables from Imported Projects
13434 @section Variables from Imported Projects
13435
13436 @noindent
13437 An attribute or variable defined in an imported or parent project can
13438 be used in expressions in the importing / extending project.
13439 Such an attribute or variable is denoted by an expanded name whose prefix
13440 is either the name of the project or the expanded name of a package within
13441 a project.
13442
13443 @smallexample @c projectfile
13444 @group
13445   with "imported";
13446   project Main extends "base" is
13447      Var1 := Imported.Var;
13448      Var2 := Base.Var & ".new";
13449 @end group
13450
13451 @group
13452      package Builder is
13453         for ^Default_Switches^Default_Switches^ ("Ada")
13454             use Imported.Builder'Ada_^Switches^Switches^ &
13455                 "^-gnatg^-gnatg^" &
13456                 "^-v^-v^";
13457      end Builder;
13458 @end group
13459
13460 @group
13461      package Compiler is
13462         for ^Default_Switches^Default_Switches^ ("Ada")
13463             use Base.Compiler'Ada_^Switches^Switches^;
13464      end Compiler;
13465   end Main;
13466 @end group
13467 @end smallexample
13468
13469 @noindent
13470 In this example:
13471
13472 @itemize @bullet
13473 @item
13474 The value of @code{Var1} is a copy of the variable @code{Var} defined
13475 in the project file @file{"imported.gpr"}
13476 @item
13477 the value of @code{Var2} is a copy of the value of variable @code{Var}
13478 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
13479 @item
13480 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13481 @code{Builder} is a string list that includes in its value a copy of the value
13482 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
13483 in project file @file{imported.gpr} plus two new elements:
13484 @option{"^-gnatg^-gnatg^"}
13485 and @option{"^-v^-v^"};
13486 @item
13487 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13488 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
13489 defined in the @code{Compiler} package in project file @file{base.gpr},
13490 the project being extended.
13491 @end itemize
13492
13493 @c ******************
13494 @c * Naming Schemes *
13495 @c ******************
13496
13497 @node  Naming Schemes
13498 @section Naming Schemes
13499
13500 @noindent
13501 Sometimes an Ada software system is ported from a foreign compilation
13502 environment to GNAT, and the file names do not use the default GNAT
13503 conventions. Instead of changing all the file names (which for a variety
13504 of reasons might not be possible), you can define the relevant file
13505 naming scheme in the @code{Naming} package in your project file.
13506
13507 @noindent
13508 Note that the use of pragmas described in
13509 @ref{Alternative File Naming Schemes} by mean of a configuration
13510 pragmas file is not supported when using project files. You must use
13511 the features described in this paragraph. You can however use specify
13512 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
13513
13514 @ifclear vms
13515 For example, the following
13516 package models the Apex file naming rules:
13517
13518 @smallexample @c projectfile
13519 @group
13520   package Naming is
13521     for Casing               use "lowercase";
13522     for Dot_Replacement      use ".";
13523     for Spec_Suffix ("Ada")  use ".1.ada";
13524     for Body_Suffix ("Ada")  use ".2.ada";
13525   end Naming;
13526 @end group
13527 @end smallexample
13528 @end ifclear
13529
13530 @ifset vms
13531 For example, the following package models the HP Ada file naming rules:
13532
13533 @smallexample @c projectfile
13534 @group
13535   package Naming is
13536     for Casing               use "lowercase";
13537     for Dot_Replacement      use "__";
13538     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
13539     for Body_Suffix ("Ada")  use ".^ada^ada^";
13540   end Naming;
13541 @end group
13542 @end smallexample
13543
13544 @noindent
13545 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
13546 names in lower case)
13547 @end ifset
13548
13549 @noindent
13550 You can define the following attributes in package @code{Naming}:
13551
13552 @table @code
13553
13554 @item @code{Casing}
13555 This must be a string with one of the three values @code{"lowercase"},
13556 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
13557
13558 @noindent
13559 If @code{Casing} is not specified, then the default is @code{"lowercase"}.
13560
13561 @item @code{Dot_Replacement}
13562 This must be a string whose value satisfies the following conditions:
13563
13564 @itemize @bullet
13565 @item It must not be empty
13566 @item It cannot start or end with an alphanumeric character
13567 @item It cannot be a single underscore
13568 @item It cannot start with an underscore followed by an alphanumeric
13569 @item It cannot contain a dot @code{'.'} except if the entire string
13570 is @code{"."}
13571 @end itemize
13572
13573 @noindent
13574 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
13575
13576 @item @code{Spec_Suffix}
13577 This is an associative array (indexed by the programming language name, case
13578 insensitive) whose value is a string that must satisfy the following
13579 conditions:
13580
13581 @itemize @bullet
13582 @item It must not be empty
13583 @item It must include at least one dot
13584 @end itemize
13585 @noindent
13586 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
13587 @code{"^.ads^.ADS^"}.
13588
13589 @item @code{Body_Suffix}
13590 This is an associative array (indexed by the programming language name, case
13591 insensitive) whose value is a string that must satisfy the following
13592 conditions:
13593
13594 @itemize @bullet
13595 @item It must not be empty
13596 @item It must include at least one dot
13597 @item It cannot be the same as @code{Spec_Suffix ("Ada")}
13598 @end itemize
13599 @noindent
13600 If @code{Body_Suffix ("Ada")} and @code{Spec_Suffix ("Ada")} end with the
13601 same string, then a file name that ends with the longest of these two suffixes
13602 will be a body if the longest suffix is @code{Body_Suffix ("Ada")} or a spec
13603 if the longest suffix is @code{Spec_Suffix ("Ada")}.
13604
13605 If @code{Body_Suffix ("Ada")} is not specified, then the default is
13606 @code{"^.adb^.ADB^"}.
13607
13608 @item @code{Separate_Suffix}
13609 This must be a string whose value satisfies the same conditions as
13610 @code{Body_Suffix}. The same "longest suffix" rules apply.
13611
13612 @noindent
13613 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
13614 value as @code{Body_Suffix ("Ada")}.
13615
13616 @item @code{Spec}
13617 @noindent
13618 You can use the associative array attribute @code{Spec}  to define
13619 the source file name for an individual Ada compilation unit's spec. The array
13620 index must be a string literal that identifies the Ada unit (case insensitive).
13621 The value of this attribute must be a string that identifies the file that
13622 contains this unit's spec (case sensitive or insensitive depending on the
13623 operating system).
13624
13625 @smallexample @c projectfile
13626    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
13627 @end smallexample
13628
13629 @item @code{Body}
13630
13631 You can use the associative array attribute @code{Body} to
13632 define the source file name for an individual Ada compilation unit's body
13633 (possibly a subunit).  The array index must be a string literal that identifies
13634 the Ada unit (case insensitive).  The value of this attribute must be a string
13635 that identifies the file that contains this unit's body or subunit (case
13636 sensitive or insensitive depending on the operating system).
13637
13638 @smallexample @c projectfile
13639    for Body ("MyPack.MyChild") use "mypack.mychild.body";
13640 @end smallexample
13641 @end table
13642
13643 @c ********************
13644 @c * Library Projects *
13645 @c ********************
13646
13647 @node Library Projects
13648 @section Library Projects
13649
13650 @noindent
13651 @emph{Library projects} are projects whose object code is placed in a library.
13652 (Note that this facility is not yet supported on all platforms)
13653
13654 To create a library project, you need to define in its project file
13655 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
13656 Additionally, you may define other library-related attributes such as
13657 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
13658 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
13659
13660 The @code{Library_Name} attribute has a string value. There is no restriction
13661 on the name of a library. It is the responsibility of the developer to
13662 choose a name that will be accepted by the platform. It is recommended to
13663 choose names that could be Ada identifiers; such names are almost guaranteed
13664 to be acceptable on all platforms.
13665
13666 The @code{Library_Dir} attribute has a string value that designates the path
13667 (absolute or relative) of the directory where the library will reside.
13668 It must designate an existing directory, and this directory must be writable,
13669 different from the project's object directory and from any source directory
13670 in the project tree.
13671
13672 If both @code{Library_Name} and @code{Library_Dir} are specified and
13673 are legal, then the project file defines a library project.  The optional
13674 library-related attributes are checked only for such project files.
13675
13676 The @code{Library_Kind} attribute has a string value that must be one of the
13677 following (case insensitive): @code{"static"}, @code{"dynamic"} or
13678 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
13679 attribute is not specified, the library is a static library, that is
13680 an archive of object files that can be potentially linked into a
13681 static executable. Otherwise, the library may be dynamic or
13682 relocatable, that is a library that is loaded only at the start of execution.
13683
13684 If you need to build both a static and a dynamic library, you should use two
13685 different object directories, since in some cases some extra code needs to
13686 be generated for the latter. For such cases, it is recommended to either use
13687 two different project files, or a single one which uses external variables
13688 to indicate what kind of library should be build.
13689
13690 The @code{Library_ALI_Dir} attribute may be specified to indicate the
13691 directory where the ALI files of the library will be copied. When it is
13692 not specified, the ALI files are copied to the directory specified in
13693 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
13694 must be writable and different from the project's object directory and from
13695 any source directory in the project tree.
13696
13697 The @code{Library_Version} attribute has a string value whose interpretation
13698 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
13699 used only for dynamic/relocatable libraries as the internal name of the
13700 library (the @code{"soname"}). If the library file name (built from the
13701 @code{Library_Name}) is different from the @code{Library_Version}, then the
13702 library file will be a symbolic link to the actual file whose name will be
13703 @code{Library_Version}.
13704
13705 Example (on Unix):
13706
13707 @smallexample @c projectfile
13708 @group
13709 project Plib is
13710
13711    Version := "1";
13712
13713    for Library_Dir use "lib_dir";
13714    for Library_Name use "dummy";
13715    for Library_Kind use "relocatable";
13716    for Library_Version use "libdummy.so." & Version;
13717
13718 end Plib;
13719 @end group
13720 @end smallexample
13721
13722 @noindent
13723 Directory @file{lib_dir} will contain the internal library file whose name
13724 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
13725 @file{libdummy.so.1}.
13726
13727 When @command{gnatmake} detects that a project file
13728 is a library project file, it will check all immediate sources of the project
13729 and rebuild the library if any of the sources have been recompiled.
13730
13731 Standard project files can import library project files. In such cases,
13732 the libraries will only be rebuilt if some of its sources are recompiled
13733 because they are in the closure of some other source in an importing project.
13734 Sources of the library project files that are not in such a closure will
13735 not be checked, unless the full library is checked, because one of its sources
13736 needs to be recompiled.
13737
13738 For instance, assume the project file @code{A} imports the library project file
13739 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
13740 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
13741 @file{l2.ads}, @file{l2.adb}.
13742
13743 If @file{l1.adb} has been modified, then the library associated with @code{L}
13744 will be rebuilt when compiling all the immediate sources of @code{A} only
13745 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
13746 @code{"with L1;"}.
13747
13748 To be sure that all the sources in the library associated with @code{L} are
13749 up to date, and that all the sources of project @code{A} are also up to date,
13750 the following two commands needs to be used:
13751
13752 @smallexample
13753 gnatmake -Pl.gpr
13754 gnatmake -Pa.gpr
13755 @end smallexample
13756
13757 When a library is built or rebuilt, an attempt is made first to delete all
13758 files in the library directory.
13759 All @file{ALI} files will also be copied from the object directory to the
13760 library directory. To build executables, @command{gnatmake} will use the
13761 library rather than the individual object files.
13762
13763 @ifclear vms
13764 It is also possible to create library project files for third-party libraries
13765 that are precompiled and cannot be compiled locally thanks to the
13766 @code{externally_built} attribute. (See @ref{Installing a library}).
13767 @end ifclear
13768
13769 @c *******************************
13770 @c * Stand-alone Library Projects *
13771 @c *******************************
13772
13773 @node Stand-alone Library Projects
13774 @section Stand-alone Library Projects
13775
13776 @noindent
13777 A Stand-alone Library is a library that contains the necessary code to
13778 elaborate the Ada units that are included in the library. A Stand-alone
13779 Library is suitable to be used in an executable when the main is not
13780 in Ada. However, Stand-alone Libraries may also be used with an Ada main
13781 subprogram.
13782
13783 A Stand-alone Library Project is a Library Project where the library is
13784 a Stand-alone Library.
13785
13786 To be a Stand-alone Library Project, in addition to the two attributes
13787 that make a project a Library Project (@code{Library_Name} and
13788 @code{Library_Dir}, see @ref{Library Projects}), the attribute
13789 @code{Library_Interface} must be defined.
13790
13791 @smallexample @c projectfile
13792 @group
13793    for Library_Dir use "lib_dir";
13794    for Library_Name use "dummy";
13795    for Library_Interface use ("int1", "int1.child");
13796 @end group
13797 @end smallexample
13798
13799 Attribute @code{Library_Interface} has a nonempty string list value,
13800 each string in the list designating a unit contained in an immediate source
13801 of the project file.
13802
13803 When a Stand-alone Library is built, first the binder is invoked to build
13804 a package whose name depends on the library name
13805 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
13806 This binder-generated package includes initialization and
13807 finalization procedures whose
13808 names depend on the library name (dummyinit and dummyfinal in the example
13809 above). The object corresponding to this package is included in the library.
13810
13811 A dynamic or relocatable Stand-alone Library is automatically initialized
13812 if automatic initialization of Stand-alone Libraries is supported on the
13813 platform and if attribute @code{Library_Auto_Init} is not specified or
13814 is specified with the value "true". A static Stand-alone Library is never
13815 automatically initialized.
13816
13817 Single string attribute @code{Library_Auto_Init} may be specified with only
13818 two possible values: "false" or "true" (case-insensitive). Specifying
13819 "false" for attribute @code{Library_Auto_Init} will prevent automatic
13820 initialization of dynamic or relocatable libraries.
13821
13822 When a non-automatically initialized Stand-alone Library is used
13823 in an executable, its initialization procedure must be called before
13824 any service of the library is used.
13825 When the main subprogram is in Ada, it may mean that the initialization
13826 procedure has to be called during elaboration of another package.
13827
13828 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
13829 (those that are listed in attribute @code{Library_Interface}) are copied to
13830 the Library Directory. As a consequence, only the Interface Units may be
13831 imported from Ada units outside of the library. If other units are imported,
13832 the binding phase will fail.
13833
13834 When a Stand-Alone Library is bound, the switches that are specified in
13835 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
13836 used in the call to @command{gnatbind}.
13837
13838 The string list attribute @code{Library_Options} may be used to specified
13839 additional switches to the call to @command{gcc} to link the library.
13840
13841 The attribute @code{Library_Src_Dir}, may be specified for a
13842 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
13843 single string value. Its value must be the path (absolute or relative to the
13844 project directory) of an existing directory. This directory cannot be the
13845 object directory or one of the source directories, but it can be the same as
13846 the library directory. The sources of the Interface
13847 Units of the library, necessary to an Ada client of the library, will be
13848 copied to the designated directory, called Interface Copy directory.
13849 These sources includes the specs of the Interface Units, but they may also
13850 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
13851 are used, or when there is a generic units in the spec. Before the sources
13852 are copied to the Interface Copy directory, an attempt is made to delete all
13853 files in the Interface Copy directory.
13854
13855 @c *************************************
13856 @c * Switches Related to Project Files *
13857 @c *************************************
13858 @node Switches Related to Project Files
13859 @section Switches Related to Project Files
13860
13861 @noindent
13862 The following switches are used by GNAT tools that support project files:
13863
13864 @table @option
13865
13866 @item ^-P^/PROJECT_FILE=^@var{project}
13867 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
13868 Indicates the name of a project file. This project file will be parsed with
13869 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
13870 if any, and using the external references indicated
13871 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
13872 @ifclear vms
13873 There may zero, one or more spaces between @option{-P} and @var{project}.
13874 @end ifclear
13875
13876 @noindent
13877 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
13878
13879 @noindent
13880 Since the Project Manager parses the project file only after all the switches
13881 on the command line are checked, the order of the switches
13882 @option{^-P^/PROJECT_FILE^},
13883 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
13884 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
13885
13886 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
13887 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
13888 Indicates that external variable @var{name} has the value @var{value}.
13889 The Project Manager will use this value for occurrences of
13890 @code{external(name)} when parsing the project file.
13891
13892 @ifclear vms
13893 @noindent
13894 If @var{name} or @var{value} includes a space, then @var{name=value} should be
13895 put between quotes.
13896 @smallexample
13897   -XOS=NT
13898   -X"user=John Doe"
13899 @end smallexample
13900 @end ifclear
13901
13902 @noindent
13903 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
13904 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
13905 @var{name}, only the last one is used.
13906
13907 @noindent
13908 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
13909 takes precedence over the value of the same name in the environment.
13910
13911 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
13912 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
13913 Indicates the verbosity of the parsing of GNAT project files.
13914
13915 @ifclear vms
13916 @option{-vP0} means Default;
13917 @option{-vP1} means Medium;
13918 @option{-vP2} means High.
13919 @end ifclear
13920
13921 @ifset vms
13922 There are three possible options for this qualifier: DEFAULT, MEDIUM and
13923 HIGH.
13924 @end ifset
13925
13926 @noindent
13927 The default is ^Default^DEFAULT^: no output for syntactically correct
13928 project files.
13929 @noindent
13930 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
13931 only the last one is used.
13932
13933 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
13934 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
13935 Add directory <dir> at the beginning of the project search path, in order,
13936 after the current working directory.
13937
13938 @ifclear vms
13939 @item -eL
13940 @cindex @option{-eL} (any project-aware tool)
13941 Follow all symbolic links when processing project files.
13942 @end ifclear
13943
13944 @item ^--subdirs^/SUBDIRS^=<subdir>
13945 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
13946 This switch is recognized by gnatmake and gnatclean. It indicate that the real
13947 directories (except the source directories) are the subdirectories <subdir>
13948 of the directories specified in the project files. This applies in particular
13949 to object directories, library directories and exec directories. If the
13950 subdirectories do not exist, they are created automatically.
13951
13952 @end table
13953
13954 @c **********************************
13955 @c * Tools Supporting Project Files *
13956 @c **********************************
13957
13958 @node  Tools Supporting Project Files
13959 @section Tools Supporting Project Files
13960
13961 @menu
13962 * gnatmake and Project Files::
13963 * The GNAT Driver and Project Files::
13964 @end menu
13965
13966 @node gnatmake and Project Files
13967 @subsection gnatmake and Project Files
13968
13969 @noindent
13970 This section covers several topics related to @command{gnatmake} and
13971 project files: defining ^switches^switches^ for @command{gnatmake}
13972 and for the tools that it invokes; specifying configuration pragmas;
13973 the use of the @code{Main} attribute; building and rebuilding library project
13974 files.
13975
13976 @menu
13977 * ^Switches^Switches^ and Project Files::
13978 * Specifying Configuration Pragmas::
13979 * Project Files and Main Subprograms::
13980 * Library Project Files::
13981 @end menu
13982
13983 @node ^Switches^Switches^ and Project Files
13984 @subsubsection ^Switches^Switches^ and Project Files
13985
13986 @ifset vms
13987 It is not currently possible to specify VMS style qualifiers in the project
13988 files; only Unix style ^switches^switches^ may be specified.
13989 @end ifset
13990
13991 @noindent
13992 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
13993 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
13994 attribute, a @code{^Switches^Switches^} attribute, or both;
13995 as their names imply, these ^switch^switch^-related
13996 attributes affect the ^switches^switches^ that are used for each of these GNAT
13997 components when
13998 @command{gnatmake} is invoked.  As will be explained below, these
13999 component-specific ^switches^switches^ precede
14000 the ^switches^switches^ provided on the @command{gnatmake} command line.
14001
14002 The @code{^Default_Switches^Default_Switches^} attribute is an associative
14003 array indexed by language name (case insensitive) whose value is a string list.
14004 For example:
14005
14006 @smallexample @c projectfile
14007 @group
14008 package Compiler is
14009   for ^Default_Switches^Default_Switches^ ("Ada")
14010       use ("^-gnaty^-gnaty^",
14011            "^-v^-v^");
14012 end Compiler;
14013 @end group
14014 @end smallexample
14015
14016 @noindent
14017 The @code{^Switches^Switches^} attribute is also an associative array,
14018 indexed by a file name (which may or may not be case sensitive, depending
14019 on the operating system) whose value is a string list.  For example:
14020
14021 @smallexample @c projectfile
14022 @group
14023 package Builder is
14024    for ^Switches^Switches^ ("main1.adb")
14025        use ("^-O2^-O2^");
14026    for ^Switches^Switches^ ("main2.adb")
14027        use ("^-g^-g^");
14028 end Builder;
14029 @end group
14030 @end smallexample
14031
14032 @noindent
14033 For the @code{Builder} package, the file names must designate source files
14034 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
14035 file names must designate @file{ALI} or source files for main subprograms.
14036 In each case just the file name without an explicit extension is acceptable.
14037
14038 For each tool used in a program build (@command{gnatmake}, the compiler, the
14039 binder, and the linker), the corresponding package @dfn{contributes} a set of
14040 ^switches^switches^ for each file on which the tool is invoked, based on the
14041 ^switch^switch^-related attributes defined in the package.
14042 In particular, the ^switches^switches^
14043 that each of these packages contributes for a given file @var{f} comprise:
14044
14045 @itemize @bullet
14046 @item
14047 the value of attribute @code{^Switches^Switches^ (@var{f})},
14048 if it is specified in the package for the given file,
14049 @item
14050 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
14051 if it is specified in the package.
14052 @end itemize
14053
14054 @noindent
14055 If neither of these attributes is defined in the package, then the package does
14056 not contribute any ^switches^switches^ for the given file.
14057
14058 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
14059 two sets, in the following order: those contributed for the file
14060 by the @code{Builder} package;
14061 and the switches passed on the command line.
14062
14063 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
14064 the ^switches^switches^ passed to the tool comprise three sets,
14065 in the following order:
14066
14067 @enumerate
14068 @item
14069 the applicable ^switches^switches^ contributed for the file
14070 by the @code{Builder} package in the project file supplied on the command line;
14071
14072 @item
14073 those contributed for the file by the package (in the relevant project file --
14074 see below) corresponding to the tool; and
14075
14076 @item
14077 the applicable switches passed on the command line.
14078 @end enumerate
14079
14080 @noindent
14081 The term @emph{applicable ^switches^switches^} reflects the fact that
14082 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
14083 tools, depending on the individual ^switch^switch^.
14084
14085 @command{gnatmake} may invoke the compiler on source files from different
14086 projects. The Project Manager will use the appropriate project file to
14087 determine the @code{Compiler} package for each source file being compiled.
14088 Likewise for the @code{Binder} and @code{Linker} packages.
14089
14090 As an example, consider the following package in a project file:
14091
14092 @smallexample @c projectfile
14093 @group
14094 project Proj1 is
14095    package Compiler is
14096       for ^Default_Switches^Default_Switches^ ("Ada")
14097           use ("^-g^-g^");
14098       for ^Switches^Switches^ ("a.adb")
14099           use ("^-O1^-O1^");
14100       for ^Switches^Switches^ ("b.adb")
14101           use ("^-O2^-O2^",
14102                "^-gnaty^-gnaty^");
14103    end Compiler;
14104 end Proj1;
14105 @end group
14106 @end smallexample
14107
14108 @noindent
14109 If @command{gnatmake} is invoked with this project file, and it needs to
14110 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
14111 @file{a.adb} will be compiled with the ^switch^switch^
14112 @option{^-O1^-O1^},
14113 @file{b.adb} with ^switches^switches^
14114 @option{^-O2^-O2^}
14115 and @option{^-gnaty^-gnaty^},
14116 and @file{c.adb} with @option{^-g^-g^}.
14117
14118 The following example illustrates the ordering of the ^switches^switches^
14119 contributed by different packages:
14120
14121 @smallexample @c projectfile
14122 @group
14123 project Proj2 is
14124    package Builder is
14125       for ^Switches^Switches^ ("main.adb")
14126           use ("^-g^-g^",
14127                "^-O1^-)1^",
14128                "^-f^-f^");
14129    end Builder;
14130 @end group
14131
14132 @group
14133    package Compiler is
14134       for ^Switches^Switches^ ("main.adb")
14135           use ("^-O2^-O2^");
14136    end Compiler;
14137 end Proj2;
14138 @end group
14139 @end smallexample
14140
14141 @noindent
14142 If you issue the command:
14143
14144 @smallexample
14145     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
14146 @end smallexample
14147
14148 @noindent
14149 then the compiler will be invoked on @file{main.adb} with the following
14150 sequence of ^switches^switches^
14151
14152 @smallexample
14153    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
14154 @end smallexample
14155
14156 with the last @option{^-O^-O^}
14157 ^switch^switch^ having precedence over the earlier ones;
14158 several other ^switches^switches^
14159 (such as @option{^-c^-c^}) are added implicitly.
14160
14161 The ^switches^switches^
14162 @option{^-g^-g^}
14163 and @option{^-O1^-O1^} are contributed by package
14164 @code{Builder},  @option{^-O2^-O2^} is contributed
14165 by the package @code{Compiler}
14166 and @option{^-O0^-O0^} comes from the command line.
14167
14168 The @option{^-g^-g^}
14169 ^switch^switch^ will also be passed in the invocation of
14170 @command{Gnatlink.}
14171
14172 A final example illustrates switch contributions from packages in different
14173 project files:
14174
14175 @smallexample @c projectfile
14176 @group
14177 project Proj3 is
14178    for Source_Files use ("pack.ads", "pack.adb");
14179    package Compiler is
14180       for ^Default_Switches^Default_Switches^ ("Ada")
14181           use ("^-gnata^-gnata^");
14182    end Compiler;
14183 end Proj3;
14184 @end group
14185
14186 @group
14187 with "Proj3";
14188 project Proj4 is
14189    for Source_Files use ("foo_main.adb", "bar_main.adb");
14190    package Builder is
14191       for ^Switches^Switches^ ("foo_main.adb")
14192           use ("^-s^-s^",
14193                "^-g^-g^");
14194    end Builder;
14195 end Proj4;
14196 @end group
14197
14198 @group
14199 -- Ada source file:
14200 with Pack;
14201 procedure Foo_Main is
14202    @dots{}
14203 end Foo_Main;
14204 @end group
14205 @end smallexample
14206
14207 If the command is
14208 @smallexample
14209 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
14210 @end smallexample
14211
14212 @noindent
14213 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
14214 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
14215 @option{^-gnato^-gnato^} (passed on the command line).
14216 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
14217 are @option{^-g^-g^} from @code{Proj4.Builder},
14218 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
14219 and @option{^-gnato^-gnato^} from the command line.
14220
14221 @noindent
14222 When using @command{gnatmake} with project files, some ^switches^switches^ or
14223 arguments may be expressed as relative paths. As the working directory where
14224 compilation occurs may change, these relative paths are converted to absolute
14225 paths. For the ^switches^switches^ found in a project file, the relative paths
14226 are relative to the project file directory, for the switches on the command
14227 line, they are relative to the directory where @command{gnatmake} is invoked.
14228 The ^switches^switches^ for which this occurs are:
14229 ^-I^-I^,
14230 ^-A^-A^,
14231 ^-L^-L^,
14232 ^-aO^-aO^,
14233 ^-aL^-aL^,
14234 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
14235 ^switch^switch^
14236 ^-o^-o^, object files specified in package @code{Linker} or after
14237 -largs on the command line). The exception to this rule is the ^switch^switch^
14238 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
14239
14240 @node Specifying Configuration Pragmas
14241 @subsubsection Specifying Configuration Pragmas
14242
14243 When using @command{gnatmake} with project files, if there exists a file
14244 @file{gnat.adc} that contains configuration pragmas, this file will be
14245 ignored.
14246
14247 Configuration pragmas can be defined by means of the following attributes in
14248 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
14249 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
14250
14251 Both these attributes are single string attributes. Their values is the path
14252 name of a file containing configuration pragmas. If a path name is relative,
14253 then it is relative to the project directory of the project file where the
14254 attribute is defined.
14255
14256 When compiling a source, the configuration pragmas used are, in order,
14257 those listed in the file designated by attribute
14258 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
14259 project file, if it is specified, and those listed in the file designated by
14260 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
14261 the project file of the source, if it exists.
14262
14263 @node Project Files and Main Subprograms
14264 @subsubsection Project Files and Main Subprograms
14265
14266 @noindent
14267 When using a project file, you can invoke @command{gnatmake}
14268 with one or several main subprograms, by specifying their source files on the
14269 command line.
14270
14271 @smallexample
14272     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
14273 @end smallexample
14274
14275 @noindent
14276 Each of these needs to be a source file of the same project, except
14277 when the switch ^-u^/UNIQUE^ is used.
14278
14279 @noindent
14280 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
14281 same project, one of the project in the tree rooted at the project specified
14282 on the command line. The package @code{Builder} of this common project, the
14283 "main project" is the one that is considered by @command{gnatmake}.
14284
14285 @noindent
14286 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
14287 imported directly or indirectly by the project specified on the command line.
14288 Note that if such a source file is not part of the project specified on the
14289 command line, the ^switches^switches^ found in package @code{Builder} of the
14290 project specified on the command line, if any, that are transmitted
14291 to the compiler will still be used, not those found in the project file of
14292 the source file.
14293
14294 @noindent
14295 When using a project file, you can also invoke @command{gnatmake} without
14296 explicitly specifying any main, and the effect depends on whether you have
14297 defined the @code{Main} attribute.  This attribute has a string list value,
14298 where each element in the list is the name of a source file (the file
14299 extension is optional) that contains a unit that can be a main subprogram.
14300
14301 If the @code{Main} attribute is defined in a project file as a non-empty
14302 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
14303 line, then invoking @command{gnatmake} with this project file but without any
14304 main on the command line is equivalent to invoking @command{gnatmake} with all
14305 the file names in the @code{Main} attribute on the command line.
14306
14307 Example:
14308 @smallexample @c projectfile
14309 @group
14310    project Prj is
14311       for Main use ("main1", "main2", "main3");
14312    end Prj;
14313 @end group
14314 @end smallexample
14315
14316 @noindent
14317 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
14318 is equivalent to
14319 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
14320
14321 When the project attribute @code{Main} is not specified, or is specified
14322 as an empty string list, or when the switch @option{-u} is used on the command
14323 line, then invoking @command{gnatmake} with no main on the command line will
14324 result in all immediate sources of the project file being checked, and
14325 potentially recompiled. Depending on the presence of the switch @option{-u},
14326 sources from other project files on which the immediate sources of the main
14327 project file depend are also checked and potentially recompiled. In other
14328 words, the @option{-u} switch is applied to all of the immediate sources of the
14329 main project file.
14330
14331 When no main is specified on the command line and attribute @code{Main} exists
14332 and includes several mains, or when several mains are specified on the
14333 command line, the default ^switches^switches^ in package @code{Builder} will
14334 be used for all mains, even if there are specific ^switches^switches^
14335 specified for one or several mains.
14336
14337 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
14338 the specific ^switches^switches^ for each main, if they are specified.
14339
14340 @node Library Project Files
14341 @subsubsection Library Project Files
14342
14343 @noindent
14344 When @command{gnatmake} is invoked with a main project file that is a library
14345 project file, it is not allowed to specify one or more mains on the command
14346 line.
14347
14348 @noindent
14349 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
14350 ^-l^/ACTION=LINK^ have special meanings.
14351
14352 @itemize @bullet
14353 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
14354 to @command{gnatmake} that @command{gnatbind} should be invoked for the
14355 library.
14356
14357 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
14358 to @command{gnatmake} that the binder generated file should be compiled
14359 (in the case of a stand-alone library) and that the library should be built.
14360
14361 @end itemize
14362
14363 @node The GNAT Driver and Project Files
14364 @subsection The GNAT Driver and Project Files
14365
14366 @noindent
14367 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
14368 can benefit from project files:
14369 @command{^gnatbind^gnatbind^},
14370 @command{^gnatcheck^gnatcheck^}),
14371 @command{^gnatclean^gnatclean^}),
14372 @command{^gnatelim^gnatelim^},
14373 @command{^gnatfind^gnatfind^},
14374 @command{^gnatlink^gnatlink^},
14375 @command{^gnatls^gnatls^},
14376 @command{^gnatmetric^gnatmetric^},
14377 @command{^gnatpp^gnatpp^},
14378 @command{^gnatstub^gnatstub^},
14379 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
14380 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
14381 They must be invoked through the @command{gnat} driver.
14382
14383 The @command{gnat} driver is a wrapper that accepts a number of commands and
14384 calls the corresponding tool. It was designed initially for VMS platforms (to
14385 convert VMS qualifiers to Unix-style switches), but it is now available on all
14386 GNAT platforms.
14387
14388 On non-VMS platforms, the @command{gnat} driver accepts the following commands
14389 (case insensitive):
14390
14391 @itemize @bullet
14392 @item
14393 BIND to invoke @command{^gnatbind^gnatbind^}
14394 @item
14395 CHOP to invoke @command{^gnatchop^gnatchop^}
14396 @item
14397 CLEAN to invoke @command{^gnatclean^gnatclean^}
14398 @item
14399 COMP or COMPILE to invoke the compiler
14400 @item
14401 ELIM to invoke @command{^gnatelim^gnatelim^}
14402 @item
14403 FIND to invoke @command{^gnatfind^gnatfind^}
14404 @item
14405 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
14406 @item
14407 LINK to invoke @command{^gnatlink^gnatlink^}
14408 @item
14409 LS or LIST to invoke @command{^gnatls^gnatls^}
14410 @item
14411 MAKE to invoke @command{^gnatmake^gnatmake^}
14412 @item
14413 NAME to invoke @command{^gnatname^gnatname^}
14414 @item
14415 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
14416 @item
14417 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
14418 @item
14419 METRIC to invoke @command{^gnatmetric^gnatmetric^}
14420 @item
14421 STUB to invoke @command{^gnatstub^gnatstub^}
14422 @item
14423 XREF to invoke @command{^gnatxref^gnatxref^}
14424 @end itemize
14425
14426 @noindent
14427 (note that the compiler is invoked using the command
14428 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
14429
14430 @noindent
14431 On non-VMS platforms, between @command{gnat} and the command, two
14432 special switches may be used:
14433
14434 @itemize @bullet
14435 @item
14436 @command{-v} to display the invocation of the tool.
14437 @item
14438 @command{-dn} to prevent the @command{gnat} driver from removing
14439 the temporary files it has created. These temporary files are
14440 configuration files and temporary file list files.
14441 @end itemize
14442
14443 @noindent
14444 The command may be followed by switches and arguments for the invoked
14445 tool.
14446
14447 @smallexample
14448   gnat bind -C main.ali
14449   gnat ls -a main
14450   gnat chop foo.txt
14451 @end smallexample
14452
14453 @noindent
14454 Switches may also be put in text files, one switch per line, and the text
14455 files may be specified with their path name preceded by '@@'.
14456
14457 @smallexample
14458    gnat bind @@args.txt main.ali
14459 @end smallexample
14460
14461 @noindent
14462 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
14463 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
14464 (@option{^-P^/PROJECT_FILE^},
14465 @option{^-X^/EXTERNAL_REFERENCE^} and
14466 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
14467 the switches of the invoking tool.
14468
14469 @noindent
14470 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
14471 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
14472 the immediate sources of the specified project file.
14473
14474 @noindent
14475 When GNAT METRIC is used with a project file, but with no source
14476 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
14477 with all the immediate sources of the specified project file and with
14478 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
14479 of the project.
14480
14481 @noindent
14482 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
14483 a project file, no source is specified on the command line and
14484 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
14485 the underlying tool (^gnatpp^gnatpp^ or
14486 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
14487 not only for the immediate sources of the main project.
14488 @ifclear vms
14489 (-U stands for Universal or Union of the project files of the project tree)
14490 @end ifclear
14491
14492 @noindent
14493 For each of the following commands, there is optionally a corresponding
14494 package in the main project.
14495
14496 @itemize @bullet
14497 @item
14498 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
14499
14500 @item
14501 package @code{Check} for command CHECK (invoking
14502 @code{^gnatcheck^gnatcheck^})
14503
14504 @item
14505 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
14506
14507 @item
14508 package @code{Cross_Reference} for command XREF (invoking
14509 @code{^gnatxref^gnatxref^})
14510
14511 @item
14512 package @code{Eliminate} for command ELIM (invoking
14513 @code{^gnatelim^gnatelim^})
14514
14515 @item
14516 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
14517
14518 @item
14519 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
14520
14521 @item
14522 package @code{Gnatstub} for command STUB
14523 (invoking @code{^gnatstub^gnatstub^})
14524
14525 @item
14526 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
14527
14528 @item
14529 package @code{Metrics} for command METRIC
14530 (invoking @code{^gnatmetric^gnatmetric^})
14531
14532 @item
14533 package @code{Pretty_Printer} for command PP or PRETTY
14534 (invoking @code{^gnatpp^gnatpp^})
14535
14536 @end itemize
14537
14538 @noindent
14539 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
14540 a simple variable with a string list value. It contains ^switches^switches^
14541 for the invocation of @code{^gnatls^gnatls^}.
14542
14543 @smallexample @c projectfile
14544 @group
14545 project Proj1 is
14546    package gnatls is
14547       for ^Switches^Switches^
14548           use ("^-a^-a^",
14549                "^-v^-v^");
14550    end gnatls;
14551 end Proj1;
14552 @end group
14553 @end smallexample
14554
14555 @noindent
14556 All other packages have two attribute @code{^Switches^Switches^} and
14557 @code{^Default_Switches^Default_Switches^}.
14558
14559 @noindent
14560 @code{^Switches^Switches^} is an associative array attribute, indexed by the
14561 source file name, that has a string list value: the ^switches^switches^ to be
14562 used when the tool corresponding to the package is invoked for the specific
14563 source file.
14564
14565 @noindent
14566 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
14567 indexed by  the programming language that has a string list value.
14568 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14569 ^switches^switches^ for the invocation of the tool corresponding
14570 to the package, except if a specific @code{^Switches^Switches^} attribute
14571 is specified for the source file.
14572
14573 @smallexample @c projectfile
14574 @group
14575 project Proj is
14576
14577    for Source_Dirs use ("./**");
14578
14579    package gnatls is
14580       for ^Switches^Switches^ use
14581           ("^-a^-a^",
14582            "^-v^-v^");
14583    end gnatls;
14584 @end group
14585 @group
14586
14587    package Compiler is
14588       for ^Default_Switches^Default_Switches^ ("Ada")
14589           use ("^-gnatv^-gnatv^",
14590                "^-gnatwa^-gnatwa^");
14591    end Binder;
14592 @end group
14593 @group
14594
14595    package Binder is
14596       for ^Default_Switches^Default_Switches^ ("Ada")
14597           use ("^-C^-C^",
14598                "^-e^-e^");
14599    end Binder;
14600 @end group
14601 @group
14602
14603    package Linker is
14604       for ^Default_Switches^Default_Switches^ ("Ada")
14605           use ("^-C^-C^");
14606       for ^Switches^Switches^ ("main.adb")
14607           use ("^-C^-C^",
14608                "^-v^-v^",
14609                "^-v^-v^");
14610    end Linker;
14611 @end group
14612 @group
14613
14614    package Finder is
14615       for ^Default_Switches^Default_Switches^ ("Ada")
14616            use ("^-a^-a^",
14617                 "^-f^-f^");
14618    end Finder;
14619 @end group
14620 @group
14621
14622    package Cross_Reference is
14623       for ^Default_Switches^Default_Switches^ ("Ada")
14624           use ("^-a^-a^",
14625                "^-f^-f^",
14626                "^-d^-d^",
14627                "^-u^-u^");
14628    end Cross_Reference;
14629 end Proj;
14630 @end group
14631 @end smallexample
14632
14633 @noindent
14634 With the above project file, commands such as
14635
14636 @smallexample
14637    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
14638    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
14639    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
14640    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
14641    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
14642 @end smallexample
14643
14644 @noindent
14645 will set up the environment properly and invoke the tool with the switches
14646 found in the package corresponding to the tool:
14647 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
14648 except @code{^Switches^Switches^ ("main.adb")}
14649 for @code{^gnatlink^gnatlink^}.
14650 It is also possible to invoke some of the tools,
14651 @code{^gnatcheck^gnatcheck^}),
14652 @code{^gnatmetric^gnatmetric^}),
14653 and @code{^gnatpp^gnatpp^})
14654 on a set of project units thanks to the combination of the switches
14655 @option{-P}, @option{-U} and possibly the main unit when one is interested
14656 in its closure. For instance,
14657 @smallexample
14658 gnat metric -Pproj
14659 @end smallexample
14660 will compute the metrics for all the immediate units of project
14661 @code{proj}.
14662 @smallexample
14663 gnat metric -Pproj -U
14664 @end smallexample
14665 will compute the metrics for all the units of the closure of projects
14666 rooted at @code{proj}.
14667 @smallexample
14668 gnat metric -Pproj -U main_unit
14669 @end smallexample
14670 will compute the metrics for the closure of units rooted at
14671 @code{main_unit}. This last possibility relies implicitly
14672 on @command{gnatbind}'s option @option{-R}.
14673
14674 @c **********************
14675 @node An Extended Example
14676 @section An Extended Example
14677
14678 @noindent
14679 Suppose that we have two programs, @var{prog1} and @var{prog2},
14680 whose sources are in corresponding directories. We would like
14681 to build them with a single @command{gnatmake} command, and we want to place
14682 their object files into @file{build} subdirectories of the source directories.
14683 Furthermore, we want to have to have two separate subdirectories
14684 in @file{build}  -- @file{release} and @file{debug} -- which will contain
14685 the object files compiled with different set of compilation flags.
14686
14687 In other words, we have the following structure:
14688
14689 @smallexample
14690 @group
14691    main
14692      |- prog1
14693      |    |- build
14694      |         | debug
14695      |         | release
14696      |- prog2
14697           |- build
14698                | debug
14699                | release
14700 @end group
14701 @end smallexample
14702
14703 @noindent
14704 Here are the project files that we must place in a directory @file{main}
14705 to maintain this structure:
14706
14707 @enumerate
14708
14709 @item We create a @code{Common} project with a package @code{Compiler} that
14710 specifies the compilation ^switches^switches^:
14711
14712 @smallexample
14713 File "common.gpr":
14714 @group
14715 @b{project} Common @b{is}
14716
14717    @b{for} Source_Dirs @b{use} (); -- No source files
14718 @end group
14719
14720 @group
14721    @b{type} Build_Type @b{is} ("release", "debug");
14722    Build : Build_Type := External ("BUILD", "debug");
14723 @end group
14724 @group
14725    @b{package} Compiler @b{is}
14726       @b{case} Build @b{is}
14727          @b{when} "release" =>
14728            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14729                    @b{use} ("^-O2^-O2^");
14730          @b{when} "debug"   =>
14731            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14732                    @b{use} ("^-g^-g^");
14733       @b{end case};
14734    @b{end} Compiler;
14735
14736 @b{end} Common;
14737 @end group
14738 @end smallexample
14739
14740 @item We create separate projects for the two programs:
14741
14742 @smallexample
14743 @group
14744 File "prog1.gpr":
14745
14746 @b{with} "common";
14747 @b{project} Prog1 @b{is}
14748
14749     @b{for} Source_Dirs @b{use} ("prog1");
14750     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
14751
14752     @b{package} Compiler @b{renames} Common.Compiler;
14753
14754 @b{end} Prog1;
14755 @end group
14756 @end smallexample
14757
14758 @smallexample
14759 @group
14760 File "prog2.gpr":
14761
14762 @b{with} "common";
14763 @b{project} Prog2 @b{is}
14764
14765     @b{for} Source_Dirs @b{use} ("prog2");
14766     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
14767
14768     @b{package} Compiler @b{renames} Common.Compiler;
14769
14770 @end group
14771 @b{end} Prog2;
14772 @end smallexample
14773
14774 @item We create a wrapping project @code{Main}:
14775
14776 @smallexample
14777 @group
14778 File "main.gpr":
14779
14780 @b{with} "common";
14781 @b{with} "prog1";
14782 @b{with} "prog2";
14783 @b{project} Main @b{is}
14784
14785    @b{package} Compiler @b{renames} Common.Compiler;
14786
14787 @b{end} Main;
14788 @end group
14789 @end smallexample
14790
14791 @item Finally we need to create a dummy procedure that @code{with}s (either
14792 explicitly or implicitly) all the sources of our two programs.
14793
14794 @end enumerate
14795
14796 @noindent
14797 Now we can build the programs using the command
14798
14799 @smallexample
14800    gnatmake ^-P^/PROJECT_FILE=^main dummy
14801 @end smallexample
14802
14803 @noindent
14804 for the Debug mode, or
14805
14806 @ifclear vms
14807 @smallexample
14808    gnatmake -Pmain -XBUILD=release
14809 @end smallexample
14810 @end ifclear
14811
14812 @ifset vms
14813 @smallexample
14814    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
14815 @end smallexample
14816 @end ifset
14817
14818 @noindent
14819 for the Release mode.
14820
14821 @c ********************************
14822 @c * Project File Complete Syntax *
14823 @c ********************************
14824
14825 @node Project File Complete Syntax
14826 @section Project File Complete Syntax
14827
14828 @smallexample
14829 project ::=
14830   context_clause project_declaration
14831
14832 context_clause ::=
14833   @{with_clause@}
14834
14835 with_clause ::=
14836   @b{with} path_name @{ , path_name @} ;
14837
14838 path_name ::=
14839    string_literal
14840
14841 project_declaration ::=
14842   simple_project_declaration | project_extension
14843
14844 simple_project_declaration ::=
14845   @b{project} <project_>simple_name @b{is}
14846     @{declarative_item@}
14847   @b{end} <project_>simple_name;
14848
14849 project_extension ::=
14850   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
14851     @{declarative_item@}
14852   @b{end} <project_>simple_name;
14853
14854 declarative_item ::=
14855   package_declaration |
14856   typed_string_declaration |
14857   other_declarative_item
14858
14859 package_declaration ::=
14860   package_spec | package_renaming
14861
14862 package_spec ::=
14863   @b{package} package_identifier @b{is}
14864     @{simple_declarative_item@}
14865   @b{end} package_identifier ;
14866
14867 package_identifier ::=
14868   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
14869   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
14870   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
14871
14872 package_renaming ::==
14873   @b{package} package_identifier @b{renames}
14874        <project_>simple_name.package_identifier ;
14875
14876 typed_string_declaration ::=
14877   @b{type} <typed_string_>_simple_name @b{is}
14878    ( string_literal @{, string_literal@} );
14879
14880 other_declarative_item ::=
14881   attribute_declaration |
14882   typed_variable_declaration |
14883   variable_declaration |
14884   case_construction
14885
14886 attribute_declaration ::=
14887   full_associative_array_declaration |
14888   @b{for} attribute_designator @b{use} expression ;
14889
14890 full_associative_array_declaration ::=
14891   @b{for} <associative_array_attribute_>simple_name @b{use}
14892   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
14893
14894 attribute_designator ::=
14895   <simple_attribute_>simple_name |
14896   <associative_array_attribute_>simple_name ( string_literal )
14897
14898 typed_variable_declaration ::=
14899   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
14900
14901 variable_declaration ::=
14902   <variable_>simple_name := expression;
14903
14904 expression ::=
14905   term @{& term@}
14906
14907 term ::=
14908   literal_string |
14909   string_list |
14910   <variable_>name |
14911   external_value |
14912   attribute_reference
14913
14914 string_literal ::=
14915   (same as Ada)
14916
14917 string_list ::=
14918   ( <string_>expression @{ , <string_>expression @} )
14919
14920 external_value ::=
14921   @b{external} ( string_literal [, string_literal] )
14922
14923 attribute_reference ::=
14924   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
14925
14926 attribute_prefix ::=
14927   @b{project} |
14928   <project_>simple_name | package_identifier |
14929   <project_>simple_name . package_identifier
14930
14931 case_construction ::=
14932   @b{case} <typed_variable_>name @b{is}
14933     @{case_item@}
14934   @b{end case} ;
14935
14936 case_item ::=
14937   @b{when} discrete_choice_list =>
14938       @{case_construction | attribute_declaration@}
14939
14940 discrete_choice_list ::=
14941   string_literal @{| string_literal@} |
14942   @b{others}
14943
14944 name ::=
14945   simple_name @{. simple_name@}
14946
14947 simple_name ::=
14948   identifier (same as Ada)
14949
14950 @end smallexample
14951
14952 @node The Cross-Referencing Tools gnatxref and gnatfind
14953 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
14954 @findex gnatxref
14955 @findex gnatfind
14956
14957 @noindent
14958 The compiler generates cross-referencing information (unless
14959 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
14960 This information indicates where in the source each entity is declared and
14961 referenced. Note that entities in package Standard are not included, but
14962 entities in all other predefined units are included in the output.
14963
14964 Before using any of these two tools, you need to compile successfully your
14965 application, so that GNAT gets a chance to generate the cross-referencing
14966 information.
14967
14968 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
14969 information to provide the user with the capability to easily locate the
14970 declaration and references to an entity. These tools are quite similar,
14971 the difference being that @code{gnatfind} is intended for locating
14972 definitions and/or references to a specified entity or entities, whereas
14973 @code{gnatxref} is oriented to generating a full report of all
14974 cross-references.
14975
14976 To use these tools, you must not compile your application using the
14977 @option{-gnatx} switch on the @command{gnatmake} command line
14978 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
14979 information will not be generated.
14980
14981 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
14982 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
14983
14984 @menu
14985 * gnatxref Switches::
14986 * gnatfind Switches::
14987 * Project Files for gnatxref and gnatfind::
14988 * Regular Expressions in gnatfind and gnatxref::
14989 * Examples of gnatxref Usage::
14990 * Examples of gnatfind Usage::
14991 @end menu
14992
14993 @node gnatxref Switches
14994 @section @code{gnatxref} Switches
14995
14996 @noindent
14997 The command invocation for @code{gnatxref} is:
14998 @smallexample
14999 $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
15000 @end smallexample
15001
15002 @noindent
15003 where
15004
15005 @table @var
15006 @item sourcefile1
15007 @itemx sourcefile2
15008 identifies the source files for which a report is to be generated. The
15009 ``with''ed units will be processed too. You must provide at least one file.
15010
15011 These file names are considered to be regular expressions, so for instance
15012 specifying @file{source*.adb} is the same as giving every file in the current
15013 directory whose name starts with @file{source} and whose extension is
15014 @file{adb}.
15015
15016 You shouldn't specify any directory name, just base names. @command{gnatxref}
15017 and @command{gnatfind} will be able to locate these files by themselves using
15018 the source path. If you specify directories, no result is produced.
15019
15020 @end table
15021
15022 @noindent
15023 The switches can be:
15024 @table @option
15025 @c !sort!
15026 @item --version
15027 @cindex @option{--version} @command{gnatxref}
15028 Display Copyright and version, then exit disregarding all other options.
15029
15030 @item --help
15031 @cindex @option{--help} @command{gnatxref}
15032 If @option{--version} was not used, display usage, then exit disregarding
15033 all other options.
15034
15035 @item ^-a^/ALL_FILES^
15036 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
15037 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15038 the read-only files found in the library search path. Otherwise, these files
15039 will be ignored. This option can be used to protect Gnat sources or your own
15040 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15041 much faster, and their output much smaller. Read-only here refers to access
15042 or permissions status in the file system for the current user.
15043
15044 @item -aIDIR
15045 @cindex @option{-aIDIR} (@command{gnatxref})
15046 When looking for source files also look in directory DIR. The order in which
15047 source file search is undertaken is the same as for @command{gnatmake}.
15048
15049 @item -aODIR
15050 @cindex @option{-aODIR} (@command{gnatxref})
15051 When searching for library and object files, look in directory
15052 DIR. The order in which library files are searched is the same as for
15053 @command{gnatmake}.
15054
15055 @item -nostdinc
15056 @cindex @option{-nostdinc} (@command{gnatxref})
15057 Do not look for sources in the system default directory.
15058
15059 @item -nostdlib
15060 @cindex @option{-nostdlib} (@command{gnatxref})
15061 Do not look for library files in the system default directory.
15062
15063 @item --RTS=@var{rts-path}
15064 @cindex @option{--RTS} (@command{gnatxref})
15065 Specifies the default location of the runtime library. Same meaning as the
15066 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15067
15068 @item ^-d^/DERIVED_TYPES^
15069 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
15070 If this switch is set @code{gnatxref} will output the parent type
15071 reference for each matching derived types.
15072
15073 @item ^-f^/FULL_PATHNAME^
15074 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
15075 If this switch is set, the output file names will be preceded by their
15076 directory (if the file was found in the search path). If this switch is
15077 not set, the directory will not be printed.
15078
15079 @item ^-g^/IGNORE_LOCALS^
15080 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
15081 If this switch is set, information is output only for library-level
15082 entities, ignoring local entities. The use of this switch may accelerate
15083 @code{gnatfind} and @code{gnatxref}.
15084
15085 @item -IDIR
15086 @cindex @option{-IDIR} (@command{gnatxref})
15087 Equivalent to @samp{-aODIR -aIDIR}.
15088
15089 @item -pFILE
15090 @cindex @option{-pFILE} (@command{gnatxref})
15091 Specify a project file to use @xref{Project Files}.
15092 If you need to use the @file{.gpr}
15093 project files, you should use gnatxref through the GNAT driver
15094 (@command{gnat xref -Pproject}).
15095
15096 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15097 project file in the current directory.
15098
15099 If a project file is either specified or found by the tools, then the content
15100 of the source directory and object directory lines are added as if they
15101 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
15102 and @samp{^-aO^OBJECT_SEARCH^}.
15103 @item ^-u^/UNUSED^
15104 Output only unused symbols. This may be really useful if you give your
15105 main compilation unit on the command line, as @code{gnatxref} will then
15106 display every unused entity and 'with'ed package.
15107
15108 @ifclear vms
15109 @item -v
15110 Instead of producing the default output, @code{gnatxref} will generate a
15111 @file{tags} file that can be used by vi. For examples how to use this
15112 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
15113 to the standard output, thus you will have to redirect it to a file.
15114 @end ifclear
15115
15116 @end table
15117
15118 @noindent
15119 All these switches may be in any order on the command line, and may even
15120 appear after the file names. They need not be separated by spaces, thus
15121 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15122 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15123
15124 @node gnatfind Switches
15125 @section @code{gnatfind} Switches
15126
15127 @noindent
15128 The command line for @code{gnatfind} is:
15129
15130 @smallexample
15131 $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
15132       @r{[}@var{file1} @var{file2} @dots{}]
15133 @end smallexample
15134
15135 @noindent
15136 where
15137
15138 @table @var
15139 @item pattern
15140 An entity will be output only if it matches the regular expression found
15141 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
15142
15143 Omitting the pattern is equivalent to specifying @samp{*}, which
15144 will match any entity. Note that if you do not provide a pattern, you
15145 have to provide both a sourcefile and a line.
15146
15147 Entity names are given in Latin-1, with uppercase/lowercase equivalence
15148 for matching purposes. At the current time there is no support for
15149 8-bit codes other than Latin-1, or for wide characters in identifiers.
15150
15151 @item sourcefile
15152 @code{gnatfind} will look for references, bodies or declarations
15153 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
15154 and column @var{column}. See @ref{Examples of gnatfind Usage}
15155 for syntax examples.
15156
15157 @item line
15158 is a decimal integer identifying the line number containing
15159 the reference to the entity (or entities) to be located.
15160
15161 @item column
15162 is a decimal integer identifying the exact location on the
15163 line of the first character of the identifier for the
15164 entity reference. Columns are numbered from 1.
15165
15166 @item file1 file2 @dots{}
15167 The search will be restricted to these source files. If none are given, then
15168 the search will be done for every library file in the search path.
15169 These file must appear only after the pattern or sourcefile.
15170
15171 These file names are considered to be regular expressions, so for instance
15172 specifying @file{source*.adb} is the same as giving every file in the current
15173 directory whose name starts with @file{source} and whose extension is
15174 @file{adb}.
15175
15176 The location of the spec of the entity will always be displayed, even if it
15177 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
15178 occurrences of the entity in the separate units of the ones given on the
15179 command line will also be displayed.
15180
15181 Note that if you specify at least one file in this part, @code{gnatfind} may
15182 sometimes not be able to find the body of the subprograms.
15183
15184 @end table
15185
15186 @noindent
15187 At least one of 'sourcefile' or 'pattern' has to be present on
15188 the command line.
15189
15190 The following switches are available:
15191 @table @option
15192 @c !sort!
15193
15194 @cindex @option{--version} @command{gnatfind}
15195 Display Copyright and version, then exit disregarding all other options.
15196
15197 @item --help
15198 @cindex @option{--help} @command{gnatfind}
15199 If @option{--version} was not used, display usage, then exit disregarding
15200 all other options.
15201
15202 @item ^-a^/ALL_FILES^
15203 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
15204 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15205 the read-only files found in the library search path. Otherwise, these files
15206 will be ignored. This option can be used to protect Gnat sources or your own
15207 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15208 much faster, and their output much smaller. Read-only here refers to access
15209 or permission status in the file system for the current user.
15210
15211 @item -aIDIR
15212 @cindex @option{-aIDIR} (@command{gnatfind})
15213 When looking for source files also look in directory DIR. The order in which
15214 source file search is undertaken is the same as for @command{gnatmake}.
15215
15216 @item -aODIR
15217 @cindex @option{-aODIR} (@command{gnatfind})
15218 When searching for library and object files, look in directory
15219 DIR. The order in which library files are searched is the same as for
15220 @command{gnatmake}.
15221
15222 @item -nostdinc
15223 @cindex @option{-nostdinc} (@command{gnatfind})
15224 Do not look for sources in the system default directory.
15225
15226 @item -nostdlib
15227 @cindex @option{-nostdlib} (@command{gnatfind})
15228 Do not look for library files in the system default directory.
15229
15230 @item --RTS=@var{rts-path}
15231 @cindex @option{--RTS} (@command{gnatfind})
15232 Specifies the default location of the runtime library. Same meaning as the
15233 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15234
15235 @item ^-d^/DERIVED_TYPE_INFORMATION^
15236 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
15237 If this switch is set, then @code{gnatfind} will output the parent type
15238 reference for each matching derived types.
15239
15240 @item ^-e^/EXPRESSIONS^
15241 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
15242 By default, @code{gnatfind} accept the simple regular expression set for
15243 @samp{pattern}. If this switch is set, then the pattern will be
15244 considered as full Unix-style regular expression.
15245
15246 @item ^-f^/FULL_PATHNAME^
15247 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
15248 If this switch is set, the output file names will be preceded by their
15249 directory (if the file was found in the search path). If this switch is
15250 not set, the directory will not be printed.
15251
15252 @item ^-g^/IGNORE_LOCALS^
15253 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
15254 If this switch is set, information is output only for library-level
15255 entities, ignoring local entities. The use of this switch may accelerate
15256 @code{gnatfind} and @code{gnatxref}.
15257
15258 @item -IDIR
15259 @cindex @option{-IDIR} (@command{gnatfind})
15260 Equivalent to @samp{-aODIR -aIDIR}.
15261
15262 @item -pFILE
15263 @cindex @option{-pFILE} (@command{gnatfind})
15264 Specify a project file (@pxref{Project Files}) to use.
15265 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15266 project file in the current directory.
15267
15268 If a project file is either specified or found by the tools, then the content
15269 of the source directory and object directory lines are added as if they
15270 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
15271 @samp{^-aO^/OBJECT_SEARCH^}.
15272
15273 @item ^-r^/REFERENCES^
15274 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
15275 By default, @code{gnatfind} will output only the information about the
15276 declaration, body or type completion of the entities. If this switch is
15277 set, the @code{gnatfind} will locate every reference to the entities in
15278 the files specified on the command line (or in every file in the search
15279 path if no file is given on the command line).
15280
15281 @item ^-s^/PRINT_LINES^
15282 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
15283 If this switch is set, then @code{gnatfind} will output the content
15284 of the Ada source file lines were the entity was found.
15285
15286 @item ^-t^/TYPE_HIERARCHY^
15287 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
15288 If this switch is set, then @code{gnatfind} will output the type hierarchy for
15289 the specified type. It act like -d option but recursively from parent
15290 type to parent type. When this switch is set it is not possible to
15291 specify more than one file.
15292
15293 @end table
15294
15295 @noindent
15296 All these switches may be in any order on the command line, and may even
15297 appear after the file names. They need not be separated by spaces, thus
15298 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15299 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15300
15301 As stated previously, gnatfind will search in every directory in the
15302 search path. You can force it to look only in the current directory if
15303 you specify @code{*} at the end of the command line.
15304
15305 @node Project Files for gnatxref and gnatfind
15306 @section Project Files for @command{gnatxref} and @command{gnatfind}
15307
15308 @noindent
15309 Project files allow a programmer to specify how to compile its
15310 application, where to find sources, etc.  These files are used
15311 @ifclear vms
15312 primarily by GPS, but they can also be used
15313 @end ifclear
15314 by the two tools
15315 @code{gnatxref} and @code{gnatfind}.
15316
15317 A project file name must end with @file{.gpr}. If a single one is
15318 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
15319 extract the information from it. If multiple project files are found, none of
15320 them is read, and you have to use the @samp{-p} switch to specify the one
15321 you want to use.
15322
15323 The following lines can be included, even though most of them have default
15324 values which can be used in most cases.
15325 The lines can be entered in any order in the file.
15326 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
15327 each line. If you have multiple instances, only the last one is taken into
15328 account.
15329
15330 @table @code
15331 @item src_dir=DIR
15332 [default: @code{"^./^[]^"}]
15333 specifies a directory where to look for source files. Multiple @code{src_dir}
15334 lines can be specified and they will be searched in the order they
15335 are specified.
15336
15337 @item obj_dir=DIR
15338 [default: @code{"^./^[]^"}]
15339 specifies a directory where to look for object and library files. Multiple
15340 @code{obj_dir} lines can be specified, and they will be searched in the order
15341 they are specified
15342
15343 @item comp_opt=SWITCHES
15344 [default: @code{""}]
15345 creates a variable which can be referred to subsequently by using
15346 the @code{$@{comp_opt@}} notation. This is intended to store the default
15347 switches given to @command{gnatmake} and @command{gcc}.
15348
15349 @item bind_opt=SWITCHES
15350 [default: @code{""}]
15351 creates a variable which can be referred to subsequently by using
15352 the @samp{$@{bind_opt@}} notation. This is intended to store the default
15353 switches given to @command{gnatbind}.
15354
15355 @item link_opt=SWITCHES
15356 [default: @code{""}]
15357 creates a variable which can be referred to subsequently by using
15358 the @samp{$@{link_opt@}} notation. This is intended to store the default
15359 switches given to @command{gnatlink}.
15360
15361 @item main=EXECUTABLE
15362 [default: @code{""}]
15363 specifies the name of the executable for the application. This variable can
15364 be referred to in the following lines by using the @samp{$@{main@}} notation.
15365
15366 @ifset vms
15367 @item comp_cmd=COMMAND
15368 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
15369 @end ifset
15370 @ifclear vms
15371 @item comp_cmd=COMMAND
15372 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
15373 @end ifclear
15374 specifies the command used to compile a single file in the application.
15375
15376 @ifset vms
15377 @item make_cmd=COMMAND
15378 [default: @code{"GNAT MAKE $@{main@}
15379 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
15380 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
15381 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
15382 @end ifset
15383 @ifclear vms
15384 @item make_cmd=COMMAND
15385 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
15386 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
15387 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
15388 @end ifclear
15389 specifies the command used to recompile the whole application.
15390
15391 @item run_cmd=COMMAND
15392 [default: @code{"$@{main@}"}]
15393 specifies the command used to run the application.
15394
15395 @item debug_cmd=COMMAND
15396 [default: @code{"gdb $@{main@}"}]
15397 specifies the command used to debug the application
15398
15399 @end table
15400
15401 @noindent
15402 @command{gnatxref} and @command{gnatfind} only take into account the
15403 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
15404
15405 @node Regular Expressions in gnatfind and gnatxref
15406 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
15407
15408 @noindent
15409 As specified in the section about @command{gnatfind}, the pattern can be a
15410 regular expression. Actually, there are to set of regular expressions
15411 which are recognized by the program:
15412
15413 @table @code
15414 @item globbing patterns
15415 These are the most usual regular expression. They are the same that you
15416 generally used in a Unix shell command line, or in a DOS session.
15417
15418 Here is a more formal grammar:
15419 @smallexample
15420 @group
15421 @iftex
15422 @leftskip=.5cm
15423 @end iftex
15424 regexp ::= term
15425 term   ::= elmt            -- matches elmt
15426 term   ::= elmt elmt       -- concatenation (elmt then elmt)
15427 term   ::= *               -- any string of 0 or more characters
15428 term   ::= ?               -- matches any character
15429 term   ::= [char @{char@}]   -- matches any character listed
15430 term   ::= [char - char]   -- matches any character in range
15431 @end group
15432 @end smallexample
15433
15434 @item full regular expression
15435 The second set of regular expressions is much more powerful. This is the
15436 type of regular expressions recognized by utilities such a @file{grep}.
15437
15438 The following is the form of a regular expression, expressed in Ada
15439 reference manual style BNF is as follows
15440
15441 @smallexample
15442 @iftex
15443 @leftskip=.5cm
15444 @end iftex
15445 @group
15446 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
15447
15448 term ::= item @{item@}       -- concatenation (item then item)
15449
15450 item ::= elmt              -- match elmt
15451 item ::= elmt *            -- zero or more elmt's
15452 item ::= elmt +            -- one or more elmt's
15453 item ::= elmt ?            -- matches elmt or nothing
15454 @end group
15455 @group
15456 elmt ::= nschar            -- matches given character
15457 elmt ::= [nschar @{nschar@}]   -- matches any character listed
15458 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
15459 elmt ::= [char - char]     -- matches chars in given range
15460 elmt ::= \ char            -- matches given character
15461 elmt ::= .                 -- matches any single character
15462 elmt ::= ( regexp )        -- parens used for grouping
15463
15464 char ::= any character, including special characters
15465 nschar ::= any character except ()[].*+?^^^
15466 @end group
15467 @end smallexample
15468
15469 Following are a few examples:
15470
15471 @table @samp
15472 @item abcde|fghi
15473 will match any of the two strings @samp{abcde} and @samp{fghi},
15474
15475 @item abc*d
15476 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
15477 @samp{abcccd}, and so on,
15478
15479 @item [a-z]+
15480 will match any string which has only lowercase characters in it (and at
15481 least one character.
15482
15483 @end table
15484 @end table
15485
15486 @node Examples of gnatxref Usage
15487 @section Examples of @code{gnatxref} Usage
15488
15489 @subsection General Usage
15490
15491 @noindent
15492 For the following examples, we will consider the following units:
15493
15494 @smallexample @c ada
15495 @group
15496 @cartouche
15497 main.ads:
15498 1: with Bar;
15499 2: package Main is
15500 3:     procedure Foo (B : in Integer);
15501 4:     C : Integer;
15502 5: private
15503 6:     D : Integer;
15504 7: end Main;
15505
15506 main.adb:
15507 1: package body Main is
15508 2:     procedure Foo (B : in Integer) is
15509 3:     begin
15510 4:        C := B;
15511 5:        D := B;
15512 6:        Bar.Print (B);
15513 7:        Bar.Print (C);
15514 8:     end Foo;
15515 9: end Main;
15516
15517 bar.ads:
15518 1: package Bar is
15519 2:     procedure Print (B : Integer);
15520 3: end bar;
15521 @end cartouche
15522 @end group
15523 @end smallexample
15524
15525 @table @code
15526
15527 @noindent
15528 The first thing to do is to recompile your application (for instance, in
15529 that case just by doing a @samp{gnatmake main}, so that GNAT generates
15530 the cross-referencing information.
15531 You can then issue any of the following commands:
15532
15533 @item gnatxref main.adb
15534 @code{gnatxref} generates cross-reference information for main.adb
15535 and every unit 'with'ed by main.adb.
15536
15537 The output would be:
15538 @smallexample
15539 @iftex
15540 @leftskip=0cm
15541 @end iftex
15542 B                                                      Type: Integer
15543   Decl: bar.ads           2:22
15544 B                                                      Type: Integer
15545   Decl: main.ads          3:20
15546   Body: main.adb          2:20
15547   Ref:  main.adb          4:13     5:13     6:19
15548 Bar                                                    Type: Unit
15549   Decl: bar.ads           1:9
15550   Ref:  main.adb          6:8      7:8
15551        main.ads           1:6
15552 C                                                      Type: Integer
15553   Decl: main.ads          4:5
15554   Modi: main.adb          4:8
15555   Ref:  main.adb          7:19
15556 D                                                      Type: Integer
15557   Decl: main.ads          6:5
15558   Modi: main.adb          5:8
15559 Foo                                                    Type: Unit
15560   Decl: main.ads          3:15
15561   Body: main.adb          2:15
15562 Main                                                    Type: Unit
15563   Decl: main.ads          2:9
15564   Body: main.adb          1:14
15565 Print                                                   Type: Unit
15566   Decl: bar.ads           2:15
15567   Ref:  main.adb          6:12     7:12
15568 @end smallexample
15569
15570 @noindent
15571 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
15572 its body is in main.adb, line 1, column 14 and is not referenced any where.
15573
15574 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
15575 it referenced in main.adb, line 6 column 12 and line 7 column 12.
15576
15577 @item gnatxref package1.adb package2.ads
15578 @code{gnatxref} will generates cross-reference information for
15579 package1.adb, package2.ads and any other package 'with'ed by any
15580 of these.
15581
15582 @end table
15583
15584 @ifclear vms
15585 @subsection Using gnatxref with vi
15586
15587 @code{gnatxref} can generate a tags file output, which can be used
15588 directly from @command{vi}. Note that the standard version of @command{vi}
15589 will not work properly with overloaded symbols. Consider using another
15590 free implementation of @command{vi}, such as @command{vim}.
15591
15592 @smallexample
15593 $ gnatxref -v gnatfind.adb > tags
15594 @end smallexample
15595
15596 @noindent
15597 will generate the tags file for @code{gnatfind} itself (if the sources
15598 are in the search path!).
15599
15600 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
15601 (replacing @var{entity} by whatever you are looking for), and vi will
15602 display a new file with the corresponding declaration of entity.
15603 @end ifclear
15604
15605 @node Examples of gnatfind Usage
15606 @section Examples of @code{gnatfind} Usage
15607
15608 @table @code
15609
15610 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
15611 Find declarations for all entities xyz referenced at least once in
15612 main.adb. The references are search in every library file in the search
15613 path.
15614
15615 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
15616 switch is set)
15617
15618 The output will look like:
15619 @smallexample
15620 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15621 ^directory/^[directory]^main.adb:24:10: xyz <= body
15622 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15623 @end smallexample
15624
15625 @noindent
15626 that is to say, one of the entities xyz found in main.adb is declared at
15627 line 12 of main.ads (and its body is in main.adb), and another one is
15628 declared at line 45 of foo.ads
15629
15630 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
15631 This is the same command as the previous one, instead @code{gnatfind} will
15632 display the content of the Ada source file lines.
15633
15634 The output will look like:
15635
15636 @smallexample
15637 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15638    procedure xyz;
15639 ^directory/^[directory]^main.adb:24:10: xyz <= body
15640    procedure xyz is
15641 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15642    xyz : Integer;
15643 @end smallexample
15644
15645 @noindent
15646 This can make it easier to find exactly the location your are looking
15647 for.
15648
15649 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
15650 Find references to all entities containing an x that are
15651 referenced on line 123 of main.ads.
15652 The references will be searched only in main.ads and foo.adb.
15653
15654 @item gnatfind main.ads:123
15655 Find declarations and bodies for all entities that are referenced on
15656 line 123 of main.ads.
15657
15658 This is the same as @code{gnatfind "*":main.adb:123}.
15659
15660 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
15661 Find the declaration for the entity referenced at column 45 in
15662 line 123 of file main.adb in directory mydir. Note that it
15663 is usual to omit the identifier name when the column is given,
15664 since the column position identifies a unique reference.
15665
15666 The column has to be the beginning of the identifier, and should not
15667 point to any character in the middle of the identifier.
15668
15669 @end table
15670
15671 @c *********************************
15672 @node The GNAT Pretty-Printer gnatpp
15673 @chapter The GNAT Pretty-Printer @command{gnatpp}
15674 @findex gnatpp
15675 @cindex Pretty-Printer
15676
15677 @noindent
15678 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
15679 for source reformatting / pretty-printing.
15680 It takes an Ada source file as input and generates a reformatted
15681 version as output.
15682 You can specify various style directives via switches; e.g.,
15683 identifier case conventions, rules of indentation, and comment layout.
15684
15685 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
15686 tree for the input source and thus requires the input to be syntactically and
15687 semantically legal.
15688 If this condition is not met, @command{gnatpp} will terminate with an
15689 error message; no output file will be generated.
15690
15691 If the source files presented to @command{gnatpp} contain
15692 preprocessing directives, then the output file will
15693 correspond to the generated source after all
15694 preprocessing is carried out. There is no way
15695 using @command{gnatpp} to obtain pretty printed files that
15696 include the preprocessing directives.
15697
15698 If the compilation unit
15699 contained in the input source depends semantically upon units located
15700 outside the current directory, you have to provide the source search path
15701 when invoking @command{gnatpp}, if these units are contained in files with
15702 names that do not follow the GNAT file naming rules, you have to provide
15703 the configuration file describing the corresponding naming scheme;
15704 see the description of the @command{gnatpp}
15705 switches below. Another possibility is to use a project file and to
15706 call @command{gnatpp} through the @command{gnat} driver
15707
15708 The @command{gnatpp} command has the form
15709
15710 @smallexample
15711 $ gnatpp @ovar{switches} @var{filename}
15712 @end smallexample
15713
15714 @noindent
15715 where
15716 @itemize @bullet
15717 @item
15718 @var{switches} is an optional sequence of switches defining such properties as
15719 the formatting rules, the source search path, and the destination for the
15720 output source file
15721
15722 @item
15723 @var{filename} is the name (including the extension) of the source file to
15724 reformat; ``wildcards'' or several file names on the same gnatpp command are
15725 allowed.  The file name may contain path information; it does not have to
15726 follow the GNAT file naming rules
15727 @end itemize
15728
15729 @menu
15730 * Switches for gnatpp::
15731 * Formatting Rules::
15732 @end menu
15733
15734 @node Switches for gnatpp
15735 @section Switches for @command{gnatpp}
15736
15737 @noindent
15738 The following subsections describe the various switches accepted by
15739 @command{gnatpp}, organized by category.
15740
15741 @ifclear vms
15742 You specify a switch by supplying a name and generally also a value.
15743 In many cases the values for a switch with a given name are incompatible with
15744 each other
15745 (for example the switch that controls the casing of a reserved word may have
15746 exactly one value: upper case, lower case, or
15747 mixed case) and thus exactly one such switch can be in effect for an
15748 invocation of @command{gnatpp}.
15749 If more than one is supplied, the last one is used.
15750 However, some values for the same switch are mutually compatible.
15751 You may supply several such switches to @command{gnatpp}, but then
15752 each must be specified in full, with both the name and the value.
15753 Abbreviated forms (the name appearing once, followed by each value) are
15754 not permitted.
15755 For example, to set
15756 the alignment of the assignment delimiter both in declarations and in
15757 assignment statements, you must write @option{-A2A3}
15758 (or @option{-A2 -A3}), but not @option{-A23}.
15759 @end ifclear
15760
15761 @ifset vms
15762 In many cases the set of options for a given qualifier are incompatible with
15763 each other (for example the qualifier that controls the casing of a reserved
15764 word may have exactly one option, which specifies either upper case, lower
15765 case, or mixed case), and thus exactly one such option can be in effect for
15766 an invocation of @command{gnatpp}.
15767 If more than one is supplied, the last one is used.
15768 However, some qualifiers have options that are mutually compatible,
15769 and then you may then supply several such options when invoking
15770 @command{gnatpp}.
15771 @end ifset
15772
15773 In most cases, it is obvious whether or not the
15774 ^values for a switch with a given name^options for a given qualifier^
15775 are compatible with each other.
15776 When the semantics might not be evident, the summaries below explicitly
15777 indicate the effect.
15778
15779 @menu
15780 * Alignment Control::
15781 * Casing Control::
15782 * Construct Layout Control::
15783 * General Text Layout Control::
15784 * Other Formatting Options::
15785 * Setting the Source Search Path::
15786 * Output File Control::
15787 * Other gnatpp Switches::
15788 @end menu
15789
15790 @node Alignment Control
15791 @subsection Alignment Control
15792 @cindex Alignment control in @command{gnatpp}
15793
15794 @noindent
15795 Programs can be easier to read if certain constructs are vertically aligned.
15796 By default all alignments are set ON.
15797 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
15798 OFF, and then use one or more of the other
15799 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
15800 to activate alignment for specific constructs.
15801
15802 @table @option
15803 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
15804
15805 @ifset vms
15806 @item /ALIGN=ON
15807 Set all alignments to ON
15808 @end ifset
15809
15810 @item ^-A0^/ALIGN=OFF^
15811 Set all alignments to OFF
15812
15813 @item ^-A1^/ALIGN=COLONS^
15814 Align @code{:} in declarations
15815
15816 @item ^-A2^/ALIGN=DECLARATIONS^
15817 Align @code{:=} in initializations in declarations
15818
15819 @item ^-A3^/ALIGN=STATEMENTS^
15820 Align @code{:=} in assignment statements
15821
15822 @item ^-A4^/ALIGN=ARROWS^
15823 Align @code{=>} in associations
15824
15825 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
15826 Align @code{at} keywords in the component clauses in record
15827 representation clauses
15828 @end table
15829
15830 @noindent
15831 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
15832 is allowed.
15833
15834 @node Casing Control
15835 @subsection Casing Control
15836 @cindex Casing control in @command{gnatpp}
15837
15838 @noindent
15839 @command{gnatpp} allows you to specify the casing for reserved words,
15840 pragma names, attribute designators and identifiers.
15841 For identifiers you may define a
15842 general rule for name casing but also override this rule
15843 via a set of dictionary files.
15844
15845 Three types of casing are supported: lower case, upper case, and mixed case.
15846 Lower and upper case are self-explanatory (but since some letters in
15847 Latin1 and other GNAT-supported character sets
15848 exist only in lower-case form, an upper case conversion will have no
15849 effect on them.)
15850 ``Mixed case'' means that the first letter, and also each letter immediately
15851 following an underscore, are converted to their uppercase forms;
15852 all the other letters are converted to their lowercase forms.
15853
15854 @table @option
15855 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
15856 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
15857 Attribute designators are lower case
15858
15859 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
15860 Attribute designators are upper case
15861
15862 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
15863 Attribute designators are mixed case (this is the default)
15864
15865 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
15866 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
15867 Keywords (technically, these are known in Ada as @emph{reserved words}) are
15868 lower case (this is the default)
15869
15870 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
15871 Keywords are upper case
15872
15873 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
15874 @item ^-nD^/NAME_CASING=AS_DECLARED^
15875 Name casing for defining occurrences are as they appear in the source file
15876 (this is the default)
15877
15878 @item ^-nU^/NAME_CASING=UPPER_CASE^
15879 Names are in upper case
15880
15881 @item ^-nL^/NAME_CASING=LOWER_CASE^
15882 Names are in lower case
15883
15884 @item ^-nM^/NAME_CASING=MIXED_CASE^
15885 Names are in mixed case
15886
15887 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
15888 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
15889 Pragma names are lower case
15890
15891 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
15892 Pragma names are upper case
15893
15894 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
15895 Pragma names are mixed case (this is the default)
15896
15897 @item ^-D@var{file}^/DICTIONARY=@var{file}^
15898 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
15899 Use @var{file} as a @emph{dictionary file} that defines
15900 the casing for a set of specified names,
15901 thereby overriding the effect on these names by
15902 any explicit or implicit
15903 ^-n^/NAME_CASING^ switch.
15904 To supply more than one dictionary file,
15905 use ^several @option{-D} switches^a list of files as options^.
15906
15907 @noindent
15908 @option{gnatpp} implicitly uses a @emph{default dictionary file}
15909 to define the casing for the Ada predefined names and
15910 the names declared in the GNAT libraries.
15911
15912 @item ^-D-^/SPECIFIC_CASING^
15913 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
15914 Do not use the default dictionary file;
15915 instead, use the casing
15916 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
15917 dictionary file(s)
15918 @end table
15919
15920 @noindent
15921 The structure of a dictionary file, and details on the conventions
15922 used in the default dictionary file, are defined in @ref{Name Casing}.
15923
15924 The @option{^-D-^/SPECIFIC_CASING^} and
15925 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
15926 compatible.
15927
15928 @node Construct Layout Control
15929 @subsection Construct Layout Control
15930 @cindex Layout control in @command{gnatpp}
15931
15932 @noindent
15933 This group of @command{gnatpp} switches controls the layout of comments and
15934 complex syntactic constructs.  See @ref{Formatting Comments} for details
15935 on their effect.
15936
15937 @table @option
15938 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
15939 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
15940 All the comments remain unchanged
15941
15942 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
15943 GNAT-style comment line indentation (this is the default).
15944
15945 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
15946 Reference-manual comment line indentation.
15947
15948 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
15949 GNAT-style comment beginning
15950
15951 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
15952 Reformat comment blocks
15953
15954 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
15955 Keep unchanged special form comments
15956
15957 Reformat comment blocks
15958
15959 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
15960 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
15961 GNAT-style layout (this is the default)
15962
15963 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
15964 Compact layout
15965
15966 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
15967 Uncompact layout
15968
15969 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
15970 @item ^-N^/NOTABS^
15971 All the VT characters are removed from the comment text. All the HT characters
15972 are expanded with the sequences of space characters to get to the next tab
15973 stops.
15974
15975 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
15976 @item ^--no-separate-is^/NO_SEPARATE_IS^
15977 Do not place the keyword @code{is} on a separate line in a subprogram body in
15978 case if the spec occupies more then one line.
15979
15980 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
15981 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
15982 Place the keyword @code{loop} in FOR and WHILE loop statements and the
15983 keyword @code{then} in IF statements on a separate line.
15984
15985 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
15986 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
15987 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
15988 keyword @code{then} in IF statements on a separate line. This option is
15989 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
15990
15991 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
15992 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
15993 Start each USE clause in a context clause from a separate line.
15994
15995 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
15996 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
15997 Use a separate line for a loop or block statement name, but do not use an extra
15998 indentation level for the statement itself.
15999
16000 @end table
16001
16002 @ifclear vms
16003 @noindent
16004 The @option{-c1} and @option{-c2} switches are incompatible.
16005 The @option{-c3} and @option{-c4} switches are compatible with each other and
16006 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
16007 the other comment formatting switches.
16008
16009 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
16010 @end ifclear
16011
16012 @ifset vms
16013 @noindent
16014 For the @option{/COMMENTS_LAYOUT} qualifier:
16015 @itemize @bullet
16016 @item
16017 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
16018 @item
16019 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
16020 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
16021 @end itemize
16022
16023 @noindent
16024 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
16025 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
16026 @end ifset
16027
16028 @node General Text Layout Control
16029 @subsection General Text Layout Control
16030
16031 @noindent
16032 These switches allow control over line length and indentation.
16033
16034 @table @option
16035 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
16036 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
16037 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
16038
16039 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
16040 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
16041 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
16042
16043 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
16044 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
16045 Indentation level for continuation lines (relative to the line being
16046 continued), @var{nnn} from 1@dots{}9.
16047 The default
16048 value is one less then the (normal) indentation level, unless the
16049 indentation is set to 1 (in which case the default value for continuation
16050 line indentation is also 1)
16051 @end table
16052
16053 @node Other Formatting Options
16054 @subsection Other Formatting Options
16055
16056 @noindent
16057 These switches control the inclusion of missing end/exit labels, and
16058 the indentation level in @b{case} statements.
16059
16060 @table @option
16061 @item ^-e^/NO_MISSED_LABELS^
16062 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
16063 Do not insert missing end/exit labels. An end label is the name of
16064 a construct that may optionally be repeated at the end of the
16065 construct's declaration;
16066 e.g., the names of packages, subprograms, and tasks.
16067 An exit label is the name of a loop that may appear as target
16068 of an exit statement within the loop.
16069 By default, @command{gnatpp} inserts these end/exit labels when
16070 they are absent from the original source. This option suppresses such
16071 insertion, so that the formatted source reflects the original.
16072
16073 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
16074 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
16075 Insert a Form Feed character after a pragma Page.
16076
16077 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
16078 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
16079 Do not use an additional indentation level for @b{case} alternatives
16080 and variants if there are @var{nnn} or more (the default
16081 value is 10).
16082 If @var{nnn} is 0, an additional indentation level is
16083 used for @b{case} alternatives and variants regardless of their number.
16084 @end table
16085
16086 @node Setting the Source Search Path
16087 @subsection Setting the Source Search Path
16088
16089 @noindent
16090 To define the search path for the input source file, @command{gnatpp}
16091 uses the same switches as the GNAT compiler, with the same effects.
16092
16093 @table @option
16094 @item ^-I^/SEARCH=^@var{dir}
16095 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
16096 The same as the corresponding gcc switch
16097
16098 @item ^-I-^/NOCURRENT_DIRECTORY^
16099 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
16100 The same as the corresponding gcc switch
16101
16102 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
16103 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
16104 The same as the corresponding gcc switch
16105
16106 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
16107 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
16108 The same as the corresponding gcc switch
16109
16110 @end table
16111
16112 @node Output File Control
16113 @subsection Output File Control
16114
16115 @noindent
16116 By default the output is sent to the file whose name is obtained by appending
16117 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
16118 (if the file with this name already exists, it is unconditionally overwritten).
16119 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
16120 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
16121 as output file.
16122 The output may be redirected by the following switches:
16123
16124 @table @option
16125 @item ^-pipe^/STANDARD_OUTPUT^
16126 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
16127 Send the output to @code{Standard_Output}
16128
16129 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
16130 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
16131 Write the output into @var{output_file}.
16132 If @var{output_file} already exists, @command{gnatpp} terminates without
16133 reading or processing the input file.
16134
16135 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
16136 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
16137 Write the output into @var{output_file}, overwriting the existing file
16138 (if one is present).
16139
16140 @item ^-r^/REPLACE^
16141 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
16142 Replace the input source file with the reformatted output, and copy the
16143 original input source into the file whose name is obtained by appending the
16144 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
16145 If a file with this name already exists, @command{gnatpp} terminates without
16146 reading or processing the input file.
16147
16148 @item ^-rf^/OVERRIDING_REPLACE^
16149 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
16150 Like @option{^-r^/REPLACE^} except that if the file with the specified name
16151 already exists, it is overwritten.
16152
16153 @item ^-rnb^/REPLACE_NO_BACKUP^
16154 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
16155 Replace the input source file with the reformatted output without
16156 creating any backup copy of the input source.
16157
16158 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
16159 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
16160 Specifies the format of the reformatted output file. The @var{xxx}
16161 ^string specified with the switch^option^ may be either
16162 @itemize @bullet
16163 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
16164 @item ``@option{^crlf^CRLF^}''
16165 the same as @option{^crlf^CRLF^}
16166 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
16167 @item ``@option{^lf^LF^}''
16168 the same as @option{^unix^UNIX^}
16169 @end itemize
16170
16171 @item ^-W^/RESULT_ENCODING=^@var{e}
16172 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
16173 Specify the wide character encoding method used to write the code in the
16174 result file
16175 @var{e} is one of the following:
16176
16177 @itemize @bullet
16178
16179 @item ^h^HEX^
16180 Hex encoding
16181
16182 @item ^u^UPPER^
16183 Upper half encoding
16184
16185 @item ^s^SHIFT_JIS^
16186 Shift/JIS encoding
16187
16188 @item ^e^EUC^
16189 EUC encoding
16190
16191 @item ^8^UTF8^
16192 UTF-8 encoding
16193
16194 @item ^b^BRACKETS^
16195 Brackets encoding (default value)
16196 @end itemize
16197
16198 @end table
16199
16200 @noindent
16201 Options @option{^-pipe^/STANDARD_OUTPUT^},
16202 @option{^-o^/OUTPUT^} and
16203 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
16204 contains only one file to reformat.
16205 Option
16206 @option{^--eol^/END_OF_LINE^}
16207 and
16208 @option{^-W^/RESULT_ENCODING^}
16209 cannot be used together
16210 with @option{^-pipe^/STANDARD_OUTPUT^} option.
16211
16212 @node Other gnatpp Switches
16213 @subsection Other @code{gnatpp} Switches
16214
16215 @noindent
16216 The additional @command{gnatpp} switches are defined in this subsection.
16217
16218 @table @option
16219 @item ^-files @var{filename}^/FILES=@var{output_file}^
16220 @cindex @option{^-files^/FILES^} (@code{gnatpp})
16221 Take the argument source files from the specified file. This file should be an
16222 ordinary textual file containing file names separated by spaces or
16223 line breaks. You can use this switch more then once in the same call to
16224 @command{gnatpp}. You also can combine this switch with explicit list of
16225 files.
16226
16227 @item ^-v^/VERBOSE^
16228 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
16229 Verbose mode;
16230 @command{gnatpp} generates version information and then
16231 a trace of the actions it takes to produce or obtain the ASIS tree.
16232
16233 @item ^-w^/WARNINGS^
16234 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
16235 Warning mode;
16236 @command{gnatpp} generates a warning whenever it cannot provide
16237 a required layout in the result source.
16238 @end table
16239
16240 @node Formatting Rules
16241 @section Formatting Rules
16242
16243 @noindent
16244 The following subsections show how @command{gnatpp} treats ``white space'',
16245 comments, program layout, and name casing.
16246 They provide the detailed descriptions of the switches shown above.
16247
16248 @menu
16249 * White Space and Empty Lines::
16250 * Formatting Comments::
16251 * Construct Layout::
16252 * Name Casing::
16253 @end menu
16254
16255 @node White Space and Empty Lines
16256 @subsection White Space and Empty Lines
16257
16258 @noindent
16259 @command{gnatpp} does not have an option to control space characters.
16260 It will add or remove spaces according to the style illustrated by the
16261 examples in the @cite{Ada Reference Manual}.
16262
16263 The only format effectors
16264 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
16265 that will appear in the output file are platform-specific line breaks,
16266 and also format effectors within (but not at the end of) comments.
16267 In particular, each horizontal tab character that is not inside
16268 a comment will be treated as a space and thus will appear in the
16269 output file as zero or more spaces depending on
16270 the reformatting of the line in which it appears.
16271 The only exception is a Form Feed character, which is inserted after a
16272 pragma @code{Page} when @option{-ff} is set.
16273
16274 The output file will contain no lines with trailing ``white space'' (spaces,
16275 format effectors).
16276
16277 Empty lines in the original source are preserved
16278 only if they separate declarations or statements.
16279 In such contexts, a
16280 sequence of two or more empty lines is replaced by exactly one empty line.
16281 Note that a blank line will be removed if it separates two ``comment blocks''
16282 (a comment block is a sequence of whole-line comments).
16283 In order to preserve a visual separation between comment blocks, use an
16284 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
16285 Likewise, if for some reason you wish to have a sequence of empty lines,
16286 use a sequence of empty comments instead.
16287
16288 @node Formatting Comments
16289 @subsection Formatting Comments
16290
16291 @noindent
16292 Comments in Ada code are of two kinds:
16293 @itemize @bullet
16294 @item
16295 a @emph{whole-line comment}, which appears by itself (possibly preceded by
16296 ``white space'') on a line
16297
16298 @item
16299 an @emph{end-of-line comment}, which follows some other Ada lexical element
16300 on the same line.
16301 @end itemize
16302
16303 @noindent
16304 The indentation of a whole-line comment is that of either
16305 the preceding or following line in
16306 the formatted source, depending on switch settings as will be described below.
16307
16308 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
16309 between the end of the preceding Ada lexical element and the beginning
16310 of the comment as appear in the original source,
16311 unless either the comment has to be split to
16312 satisfy the line length limitation, or else the next line contains a
16313 whole line comment that is considered a continuation of this end-of-line
16314 comment (because it starts at the same position).
16315 In the latter two
16316 cases, the start of the end-of-line comment is moved right to the nearest
16317 multiple of the indentation level.
16318 This may result in a ``line overflow'' (the right-shifted comment extending
16319 beyond the maximum line length), in which case the comment is split as
16320 described below.
16321
16322 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
16323 (GNAT-style comment line indentation)
16324 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
16325 (reference-manual comment line indentation).
16326 With reference-manual style, a whole-line comment is indented as if it
16327 were a declaration or statement at the same place
16328 (i.e., according to the indentation of the preceding line(s)).
16329 With GNAT style, a whole-line comment that is immediately followed by an
16330 @b{if} or @b{case} statement alternative, a record variant, or the reserved
16331 word @b{begin}, is indented based on the construct that follows it.
16332
16333 For example:
16334 @smallexample @c ada
16335 @cartouche
16336 if A then
16337     null;
16338        -- some comment
16339 else
16340    null;
16341 end if;
16342 @end cartouche
16343 @end smallexample
16344
16345 @noindent
16346 Reference-manual indentation produces:
16347
16348 @smallexample @c ada
16349 @cartouche
16350 if A then
16351    null;
16352    --  some comment
16353 else
16354    null;
16355 end if;
16356 @end cartouche
16357 @end smallexample
16358
16359 @noindent
16360 while GNAT-style indentation produces:
16361
16362 @smallexample @c ada
16363 @cartouche
16364 if A then
16365    null;
16366 --  some comment
16367 else
16368    null;
16369 end if;
16370 @end cartouche
16371 @end smallexample
16372
16373 @noindent
16374 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
16375 (GNAT style comment beginning) has the following
16376 effect:
16377
16378 @itemize @bullet
16379 @item
16380 For each whole-line comment that does not end with two hyphens,
16381 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
16382 to ensure that there are at least two spaces between these hyphens and the
16383 first non-blank character of the comment.
16384 @end itemize
16385
16386 @noindent
16387 For an end-of-line comment, if in the original source the next line is a
16388 whole-line comment that starts at the same position
16389 as the end-of-line comment,
16390 then the whole-line comment (and all whole-line comments
16391 that follow it and that start at the same position)
16392 will start at this position in the output file.
16393
16394 @noindent
16395 That is, if in the original source we have:
16396
16397 @smallexample @c ada
16398 @cartouche
16399 begin
16400 A := B + C;            --  B must be in the range Low1..High1
16401                        --  C must be in the range Low2..High2
16402              --B+C will be in the range Low1+Low2..High1+High2
16403 X := X + 1;
16404 @end cartouche
16405 @end smallexample
16406
16407 @noindent
16408 Then in the formatted source we get
16409
16410 @smallexample @c ada
16411 @cartouche
16412 begin
16413    A := B + C;            --  B must be in the range Low1..High1
16414                           --  C must be in the range Low2..High2
16415    --  B+C will be in the range Low1+Low2..High1+High2
16416    X := X + 1;
16417 @end cartouche
16418 @end smallexample
16419
16420 @noindent
16421 A comment that exceeds the line length limit will be split.
16422 Unless switch
16423 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
16424 the line belongs to a reformattable block, splitting the line generates a
16425 @command{gnatpp} warning.
16426 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
16427 comments may be reformatted in typical
16428 word processor style (that is, moving words between lines and putting as
16429 many words in a line as possible).
16430
16431 @noindent
16432 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
16433 that has a special format (that is, a character that is neither a letter nor digit
16434 not white space nor line break immediately following the leading @code{--} of
16435 the comment) should be without any change moved from the argument source
16436 into reformatted source. This switch allows to preserve comments that are used
16437 as a special marks in the code (e.g.@: SPARK annotation).
16438
16439 @node Construct Layout
16440 @subsection Construct Layout
16441
16442 @noindent
16443 In several cases the suggested layout in the Ada Reference Manual includes
16444 an extra level of indentation that many programmers prefer to avoid. The
16445 affected cases include:
16446
16447 @itemize @bullet
16448
16449 @item Record type declaration (RM 3.8)
16450
16451 @item Record representation clause (RM 13.5.1)
16452
16453 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
16454
16455 @item Block statement in case if a block has a statement identifier (RM 5.6)
16456 @end itemize
16457
16458 @noindent
16459 In compact mode (when GNAT style layout or compact layout is set),
16460 the pretty printer uses one level of indentation instead
16461 of two. This is achieved in the record definition and record representation
16462 clause cases by putting the @code{record} keyword on the same line as the
16463 start of the declaration or representation clause, and in the block and loop
16464 case by putting the block or loop header on the same line as the statement
16465 identifier.
16466
16467 @noindent
16468 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
16469 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
16470 layout on the one hand, and uncompact layout
16471 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
16472 can be illustrated by the following examples:
16473
16474 @iftex
16475 @cartouche
16476 @multitable @columnfractions .5 .5
16477 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
16478
16479 @item
16480 @smallexample @c ada
16481 type q is record
16482    a : integer;
16483    b : integer;
16484 end record;
16485 @end smallexample
16486 @tab
16487 @smallexample @c ada
16488 type q is
16489    record
16490       a : integer;
16491       b : integer;
16492    end record;
16493 @end smallexample
16494
16495 @item
16496 @smallexample @c ada
16497 for q use record
16498    a at 0 range  0 .. 31;
16499    b at 4 range  0 .. 31;
16500 end record;
16501 @end smallexample
16502 @tab
16503 @smallexample @c ada
16504 for q use
16505    record
16506       a at 0 range  0 .. 31;
16507       b at 4 range  0 .. 31;
16508    end record;
16509 @end smallexample
16510
16511 @item
16512 @smallexample @c ada
16513 Block : declare
16514    A : Integer := 3;
16515 begin
16516    Proc (A, A);
16517 end Block;
16518 @end smallexample
16519 @tab
16520 @smallexample @c ada
16521 Block :
16522    declare
16523       A : Integer := 3;
16524    begin
16525       Proc (A, A);
16526    end Block;
16527 @end smallexample
16528
16529 @item
16530 @smallexample @c ada
16531 Clear : for J in 1 .. 10 loop
16532    A (J) := 0;
16533 end loop Clear;
16534 @end smallexample
16535 @tab
16536 @smallexample @c ada
16537 Clear :
16538    for J in 1 .. 10 loop
16539       A (J) := 0;
16540    end loop Clear;
16541 @end smallexample
16542 @end multitable
16543 @end cartouche
16544 @end iftex
16545
16546 @ifnottex
16547 @smallexample
16548 @cartouche
16549 GNAT style, compact layout              Uncompact layout
16550
16551 type q is record                        type q is
16552    a : integer;                            record
16553    b : integer;                               a : integer;
16554 end record;                                   b : integer;
16555                                            end record;
16556
16557 for q use record                        for q use
16558    a at 0 range  0 .. 31;                  record
16559    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
16560 end record;                                   b at 4 range  0 .. 31;
16561                                            end record;
16562
16563 Block : declare                         Block :
16564    A : Integer := 3;                       declare
16565 begin                                         A : Integer := 3;
16566    Proc (A, A);                            begin
16567 end Block;                                    Proc (A, A);
16568                                            end Block;
16569
16570 Clear : for J in 1 .. 10 loop           Clear :
16571    A (J) := 0;                             for J in 1 .. 10 loop
16572 end loop Clear;                               A (J) := 0;
16573                                            end loop Clear;
16574 @end cartouche
16575 @end smallexample
16576 @end ifnottex
16577
16578 @noindent
16579 A further difference between GNAT style layout and compact layout is that
16580 GNAT style layout inserts empty lines as separation for
16581 compound statements, return statements and bodies.
16582
16583 Note that the layout specified by
16584 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
16585 for named block and loop statements overrides the layout defined by these
16586 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
16587 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
16588 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
16589
16590 @node Name Casing
16591 @subsection Name Casing
16592
16593 @noindent
16594 @command{gnatpp} always converts the usage occurrence of a (simple) name to
16595 the same casing as the corresponding defining identifier.
16596
16597 You control the casing for defining occurrences via the
16598 @option{^-n^/NAME_CASING^} switch.
16599 @ifclear vms
16600 With @option{-nD} (``as declared'', which is the default),
16601 @end ifclear
16602 @ifset vms
16603 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
16604 @end ifset
16605 defining occurrences appear exactly as in the source file
16606 where they are declared.
16607 The other ^values for this switch^options for this qualifier^ ---
16608 @option{^-nU^UPPER_CASE^},
16609 @option{^-nL^LOWER_CASE^},
16610 @option{^-nM^MIXED_CASE^} ---
16611 result in
16612 ^upper, lower, or mixed case, respectively^the corresponding casing^.
16613 If @command{gnatpp} changes the casing of a defining
16614 occurrence, it analogously changes the casing of all the
16615 usage occurrences of this name.
16616
16617 If the defining occurrence of a name is not in the source compilation unit
16618 currently being processed by @command{gnatpp}, the casing of each reference to
16619 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
16620 switch (subject to the dictionary file mechanism described below).
16621 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
16622 had affected the
16623 casing for the defining occurrence of the name.
16624
16625 Some names may need to be spelled with casing conventions that are not
16626 covered by the upper-, lower-, and mixed-case transformations.
16627 You can arrange correct casing by placing such names in a
16628 @emph{dictionary file},
16629 and then supplying a @option{^-D^/DICTIONARY^} switch.
16630 The casing of names from dictionary files overrides
16631 any @option{^-n^/NAME_CASING^} switch.
16632
16633 To handle the casing of Ada predefined names and the names from GNAT libraries,
16634 @command{gnatpp} assumes a default dictionary file.
16635 The name of each predefined entity is spelled with the same casing as is used
16636 for the entity in the @cite{Ada Reference Manual}.
16637 The name of each entity in the GNAT libraries is spelled with the same casing
16638 as is used in the declaration of that entity.
16639
16640 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
16641 default dictionary file.
16642 Instead, the casing for predefined and GNAT-defined names will be established
16643 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
16644 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
16645 will appear as just shown,
16646 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
16647 To ensure that even such names are rendered in uppercase,
16648 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
16649 (or else, less conveniently, place these names in upper case in a dictionary
16650 file).
16651
16652 A dictionary file is
16653 a plain text file; each line in this file can be either a blank line
16654 (containing only space characters and ASCII.HT characters), an Ada comment
16655 line, or the specification of exactly one @emph{casing schema}.
16656
16657 A casing schema is a string that has the following syntax:
16658
16659 @smallexample
16660 @cartouche
16661   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
16662
16663   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
16664 @end cartouche
16665 @end smallexample
16666
16667 @noindent
16668 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
16669 @var{identifier} lexical element and the @var{letter_or_digit} category.)
16670
16671 The casing schema string can be followed by white space and/or an Ada-style
16672 comment; any amount of white space is allowed before the string.
16673
16674 If a dictionary file is passed as
16675 @ifclear vms
16676 the value of a @option{-D@var{file}} switch
16677 @end ifclear
16678 @ifset vms
16679 an option to the @option{/DICTIONARY} qualifier
16680 @end ifset
16681 then for every
16682 simple name and every identifier, @command{gnatpp} checks if the dictionary
16683 defines the casing for the name or for some of its parts (the term ``subword''
16684 is used below to denote the part of a name which is delimited by ``_'' or by
16685 the beginning or end of the word and which does not contain any ``_'' inside):
16686
16687 @itemize @bullet
16688 @item
16689 if the whole name is in the dictionary, @command{gnatpp} uses for this name
16690 the casing defined by the dictionary; no subwords are checked for this word
16691
16692 @item
16693 for every subword @command{gnatpp} checks if the dictionary contains the
16694 corresponding string of the form @code{*@var{simple_identifier}*},
16695 and if it does, the casing of this @var{simple_identifier} is used
16696 for this subword
16697
16698 @item
16699 if the whole name does not contain any ``_'' inside, and if for this name
16700 the dictionary contains two entries - one of the form @var{identifier},
16701 and another - of the form *@var{simple_identifier}*, then the first one
16702 is applied to define the casing of this name
16703
16704 @item
16705 if more than one dictionary file is passed as @command{gnatpp} switches, each
16706 dictionary adds new casing exceptions and overrides all the existing casing
16707 exceptions set by the previous dictionaries
16708
16709 @item
16710 when @command{gnatpp} checks if the word or subword is in the dictionary,
16711 this check is not case sensitive
16712 @end itemize
16713
16714 @noindent
16715 For example, suppose we have the following source to reformat:
16716
16717 @smallexample @c ada
16718 @cartouche
16719 procedure test is
16720    name1 : integer := 1;
16721    name4_name3_name2 : integer := 2;
16722    name2_name3_name4 : Boolean;
16723    name1_var : Float;
16724 begin
16725    name2_name3_name4 := name4_name3_name2 > name1;
16726 end;
16727 @end cartouche
16728 @end smallexample
16729
16730 @noindent
16731 And suppose we have two dictionaries:
16732
16733 @smallexample
16734 @cartouche
16735 @i{dict1:}
16736    NAME1
16737    *NaMe3*
16738    *Name1*
16739 @end cartouche
16740
16741 @cartouche
16742 @i{dict2:}
16743   *NAME3*
16744 @end cartouche
16745 @end smallexample
16746
16747 @noindent
16748 If @command{gnatpp} is called with the following switches:
16749
16750 @smallexample
16751 @ifclear vms
16752 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
16753 @end ifclear
16754 @ifset vms
16755 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
16756 @end ifset
16757 @end smallexample
16758
16759 @noindent
16760 then we will get the following name casing in the @command{gnatpp} output:
16761
16762 @smallexample @c ada
16763 @cartouche
16764 procedure Test is
16765    NAME1             : Integer := 1;
16766    Name4_NAME3_Name2 : Integer := 2;
16767    Name2_NAME3_Name4 : Boolean;
16768    Name1_Var         : Float;
16769 begin
16770    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
16771 end Test;
16772 @end cartouche
16773 @end smallexample
16774
16775 @c *********************************
16776 @node The GNAT Metric Tool gnatmetric
16777 @chapter The GNAT Metric Tool @command{gnatmetric}
16778 @findex gnatmetric
16779 @cindex Metric tool
16780
16781 @noindent
16782 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
16783 for computing various program metrics.
16784 It takes an Ada source file as input and generates a file containing the
16785 metrics data as output. Various switches control which
16786 metrics are computed and output.
16787
16788 @command{gnatmetric} generates and uses the ASIS
16789 tree for the input source and thus requires the input to be syntactically and
16790 semantically legal.
16791 If this condition is not met, @command{gnatmetric} will generate
16792 an error message; no metric information for this file will be
16793 computed and reported.
16794
16795 If the compilation unit contained in the input source depends semantically
16796 upon units in files located outside the current directory, you have to provide
16797 the source search path when invoking @command{gnatmetric}.
16798 If it depends semantically upon units that are contained
16799 in files with names that do not follow the GNAT file naming rules, you have to
16800 provide the configuration file describing the corresponding naming scheme (see
16801 the description of the @command{gnatmetric} switches below.)
16802 Alternatively, you may use a project file and invoke @command{gnatmetric}
16803 through the @command{gnat} driver.
16804
16805 The @command{gnatmetric} command has the form
16806
16807 @smallexample
16808 $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
16809 @end smallexample
16810
16811 @noindent
16812 where
16813 @itemize @bullet
16814 @item
16815 @var{switches} specify the metrics to compute and define the destination for
16816 the output
16817
16818 @item
16819 Each @var{filename} is the name (including the extension) of a source
16820 file to process. ``Wildcards'' are allowed, and
16821 the file name may contain path information.
16822 If no @var{filename} is supplied, then the @var{switches} list must contain
16823 at least one
16824 @option{-files} switch (@pxref{Other gnatmetric Switches}).
16825 Including both a @option{-files} switch and one or more
16826 @var{filename} arguments is permitted.
16827
16828 @item
16829 @samp{-cargs @var{gcc_switches}} is a list of switches for
16830 @command{gcc}. They will be passed on to all compiler invocations made by
16831 @command{gnatmetric} to generate the ASIS trees. Here you can provide
16832 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
16833 and use the @option{-gnatec} switch to set the configuration file.
16834 @end itemize
16835
16836 @menu
16837 * Switches for gnatmetric::
16838 @end menu
16839
16840 @node Switches for gnatmetric
16841 @section Switches for @command{gnatmetric}
16842
16843 @noindent
16844 The following subsections describe the various switches accepted by
16845 @command{gnatmetric}, organized by category.
16846
16847 @menu
16848 * Output Files Control::
16849 * Disable Metrics For Local Units::
16850 * Specifying a set of metrics to compute::
16851 * Other gnatmetric Switches::
16852 * Generate project-wide metrics::
16853 @end menu
16854
16855 @node Output Files Control
16856 @subsection Output File Control
16857 @cindex Output file control in @command{gnatmetric}
16858
16859 @noindent
16860 @command{gnatmetric} has two output formats. It can generate a
16861 textual (human-readable) form, and also XML. By default only textual
16862 output is generated.
16863
16864 When generating the output in textual form, @command{gnatmetric} creates
16865 for each Ada source file a corresponding text file
16866 containing the computed metrics, except for the case when the set of metrics
16867 specified by gnatmetric parameters consists only of metrics that are computed
16868 for the whole set of analyzed sources, but not for each Ada source.
16869 By default, this file is placed in the same directory as where the source
16870 file is located, and its name is obtained
16871 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
16872 input file.
16873
16874 All the output information generated in XML format is placed in a single
16875 file. By default this file is placed in the current directory and has the
16876 name ^@file{metrix.xml}^@file{METRIX$XML}^.
16877
16878 Some of the computed metrics are summed over the units passed to
16879 @command{gnatmetric}; for example, the total number of lines of code.
16880 By default this information is sent to @file{stdout}, but a file
16881 can be specified with the @option{-og} switch.
16882
16883 The following switches control the @command{gnatmetric} output:
16884
16885 @table @option
16886 @cindex @option{^-x^/XML^} (@command{gnatmetric})
16887 @item ^-x^/XML^
16888 Generate the XML output
16889
16890 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
16891 @item ^-nt^/NO_TEXT^
16892 Do not generate the output in text form (implies @option{^-x^/XML^})
16893
16894 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
16895 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
16896 Put textual files with detailed metrics into @var{output_dir}
16897
16898 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
16899 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
16900 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
16901 in the name of the output file.
16902
16903 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
16904 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
16905 Put global metrics into @var{file_name}
16906
16907 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
16908 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
16909 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
16910
16911 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
16912 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
16913 Use ``short'' source file names in the output.  (The @command{gnatmetric}
16914 output includes the name(s) of the Ada source file(s) from which the metrics
16915 are computed.  By default each name includes the absolute path. The
16916 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
16917 to exclude all directory information from the file names that are output.)
16918
16919 @end table
16920
16921 @node Disable Metrics For Local Units
16922 @subsection Disable Metrics For Local Units
16923 @cindex Disable Metrics For Local Units in @command{gnatmetric}
16924
16925 @noindent
16926 @command{gnatmetric} relies on the GNAT compilation model @minus{}
16927 one compilation
16928 unit per one source file. It computes line metrics for the whole source
16929 file, and it also computes syntax
16930 and complexity metrics for the file's outermost unit.
16931
16932 By default, @command{gnatmetric} will also compute all metrics for certain
16933 kinds of locally declared program units:
16934
16935 @itemize @bullet
16936 @item
16937 subprogram (and generic subprogram) bodies;
16938
16939 @item
16940 package (and generic package) specs and bodies;
16941
16942 @item
16943 task object and type specifications and bodies;
16944
16945 @item
16946 protected object and type specifications and bodies.
16947 @end itemize
16948
16949 @noindent
16950 These kinds of entities will be referred to as
16951 @emph{eligible local program units}, or simply @emph{eligible local units},
16952 @cindex Eligible local unit (for @command{gnatmetric})
16953 in the discussion below.
16954
16955 Note that a subprogram declaration, generic instantiation,
16956 or renaming declaration only receives metrics
16957 computation when it appear as the outermost entity
16958 in a source file.
16959
16960 Suppression of metrics computation for eligible local units can be
16961 obtained via the following switch:
16962
16963 @table @option
16964 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
16965 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
16966 Do not compute detailed metrics for eligible local program units
16967
16968 @end table
16969
16970 @node Specifying a set of metrics to compute
16971 @subsection Specifying a set of metrics to compute
16972
16973 @noindent
16974 By default all the metrics are computed and reported. The switches
16975 described in this subsection allow you to control, on an individual
16976 basis, whether metrics are computed and
16977 reported. If at least one positive metric
16978 switch is specified (that is, a switch that defines that a given
16979 metric or set of metrics is to be computed), then only
16980 explicitly specified metrics are reported.
16981
16982 @menu
16983 * Line Metrics Control::
16984 * Syntax Metrics Control::
16985 * Complexity Metrics Control::
16986 * Object-Oriented Metrics Control::
16987 @end menu
16988
16989 @node Line Metrics Control
16990 @subsubsection Line Metrics Control
16991 @cindex Line metrics control in @command{gnatmetric}
16992
16993 @noindent
16994 For any (legal) source file, and for each of its
16995 eligible local program units, @command{gnatmetric} computes the following
16996 metrics:
16997
16998 @itemize @bullet
16999 @item
17000 the total number of lines;
17001
17002 @item
17003 the total number of code lines (i.e., non-blank lines that are not comments)
17004
17005 @item
17006 the number of comment lines
17007
17008 @item
17009 the number of code lines containing end-of-line comments;
17010
17011 @item
17012 the comment percentage: the ratio between the number of lines that contain
17013 comments and the number of all non-blank lines, expressed as a percentage;
17014
17015 @item
17016 the number of empty lines and lines containing only space characters and/or
17017 format effectors (blank lines)
17018
17019 @item
17020 the average number of code lines in subprogram bodies, task bodies, entry
17021 bodies and statement sequences in package bodies (this metric is only computed
17022 across the whole set of the analyzed units)
17023
17024 @end itemize
17025
17026 @noindent
17027 @command{gnatmetric} sums the values of the line metrics for all the
17028 files being processed and then generates the cumulative results. The tool
17029 also computes for all the files being processed the average number of code
17030 lines in bodies.
17031
17032 You can use the following switches to select the specific line metrics
17033 to be computed and reported.
17034
17035 @table @option
17036 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
17037
17038 @ifclear vms
17039 @cindex @option{--no-lines@var{x}}
17040 @end ifclear
17041
17042 @item ^--lines-all^/LINE_COUNT_METRICS=ALL_ON^
17043 Report all the line metrics
17044
17045 @item ^--no-lines-all^/LINE_COUNT_METRICS=ALL_OFF^
17046 Do not report any of line metrics
17047
17048 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES_ON^
17049 Report the number of all lines
17050
17051 @item ^--no-lines^/LINE_COUNT_METRICS=ALL_LINES_OFF^
17052 Do not report the number of all lines
17053
17054 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES_ON^
17055 Report the number of code lines
17056
17057 @item ^--no-lines-code^/LINE_COUNT_METRICS=CODE_LINES_OFF^
17058 Do not report the number of code lines
17059
17060 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES_ON^
17061 Report the number of comment lines
17062
17063 @item ^--no-lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES_OFF^
17064 Do not report the number of comment lines
17065
17066 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES_ON^
17067 Report the number of code lines containing
17068 end-of-line comments
17069
17070 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES_OFF^
17071 Do not report the number of code lines containing
17072 end-of-line comments
17073
17074 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE_ON^
17075 Report the comment percentage in the program text
17076
17077 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE_OFF^
17078 Do not report the comment percentage in the program text
17079
17080 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES_ON^
17081 Report the number of blank lines
17082
17083 @item ^--no-lines-blank^/LINE_COUNT_METRICS=BLANK_LINES_OFF^
17084 Do not report the number of blank lines
17085
17086 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES_ON^
17087 Report the average number of code lines in subprogram bodies, task bodies,
17088 entry bodies and statement sequences in package bodies. The metric is computed
17089 and reported for the whole set of processed Ada sources only.
17090
17091 @item ^--no-lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES_OFF^
17092 Do not report the average number of code lines in subprogram bodies,
17093 task bodies, entry bodies and statement sequences in package bodies.
17094
17095 @end table
17096
17097 @node Syntax Metrics Control
17098 @subsubsection Syntax Metrics Control
17099 @cindex Syntax metrics control in @command{gnatmetric}
17100
17101 @noindent
17102 @command{gnatmetric} computes various syntactic metrics for the
17103 outermost unit and for each eligible local unit:
17104
17105 @table @emph
17106 @item LSLOC (``Logical Source Lines Of Code'')
17107 The total number of declarations and the total number of statements
17108
17109 @item Maximal static nesting level of inner program units
17110 According to
17111 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
17112 package, a task unit, a protected unit, a
17113 protected entry, a generic unit, or an explicitly declared subprogram other
17114 than an enumeration literal.''
17115
17116 @item Maximal nesting level of composite syntactic constructs
17117 This corresponds to the notion of the
17118 maximum nesting level in the GNAT built-in style checks
17119 (@pxref{Style Checking})
17120 @end table
17121
17122 @noindent
17123 For the outermost unit in the file, @command{gnatmetric} additionally computes
17124 the following metrics:
17125
17126 @table @emph
17127 @item Public subprograms
17128 This metric is computed for package specs. It is the
17129 number of subprograms and generic subprograms declared in the visible
17130 part (including the visible part of nested packages, protected objects, and
17131 protected types).
17132
17133 @item All subprograms
17134 This metric is computed for bodies and subunits. The
17135 metric is equal to a total number of subprogram bodies in the compilation
17136 unit.
17137 Neither generic instantiations nor renamings-as-a-body nor body stubs
17138 are counted. Any subprogram body is counted, independently of its nesting
17139 level and enclosing constructs. Generic bodies and bodies of protected
17140 subprograms are counted in the same way as ``usual'' subprogram bodies.
17141
17142 @item Public types
17143 This metric is computed for package specs and
17144 generic package declarations. It is the total number of types
17145 that can be referenced from outside this compilation unit, plus the
17146 number of types from all the visible parts of all the visible generic
17147 packages. Generic formal types are not counted.  Only types, not subtypes,
17148 are included.
17149
17150 @noindent
17151 Along with the total number of public types, the following
17152 types are counted and reported separately:
17153
17154 @itemize @bullet
17155 @item
17156 Abstract types
17157
17158 @item
17159 Root tagged types (abstract, non-abstract, private, non-private). Type
17160 extensions are @emph{not} counted
17161
17162 @item
17163 Private types (including private extensions)
17164
17165 @item
17166 Task types
17167
17168 @item
17169 Protected types
17170
17171 @end itemize
17172
17173 @item All types
17174 This metric is computed for any compilation unit. It is equal to the total
17175 number of the declarations of different types given in the compilation unit.
17176 The private and the corresponding full type declaration are counted as one
17177 type declaration. Incomplete type declarations and generic formal types
17178 are not counted.
17179 No distinction is made among different kinds of types (abstract,
17180 private etc.); the total number of types is computed and reported.
17181
17182 @end table
17183
17184 @noindent
17185 By default, all the syntax metrics are computed and reported. You can use the
17186 following switches to select specific syntax metrics.
17187
17188 @table @option
17189
17190 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
17191
17192 @ifclear vms
17193 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
17194 @end ifclear
17195
17196 @item ^--syntax-all^/SYNTAX_METRICS=ALL_ON^
17197 Report all the syntax metrics
17198
17199 @item ^--no-syntax-all^/ALL_OFF^
17200 Do not report any of syntax metrics
17201
17202 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS_ON^
17203 Report the total number of declarations
17204
17205 @item ^--no-declarations^/SYNTAX_METRICS=DECLARATIONS_OFF^
17206 Do not report the total number of declarations
17207
17208 @item ^--statements^/SYNTAX_METRICS=STATEMENTS_ON^
17209 Report the total number of statements
17210
17211 @item ^--no-statements^/SYNTAX_METRICS=STATEMENTS_OFF^
17212 Do not report the total number of statements
17213
17214 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS_ON^
17215 Report the number of public subprograms in a compilation unit
17216
17217 @item ^--no-public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS_OFF^
17218 Do not report the number of public subprograms in a compilation unit
17219
17220 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS_ON^
17221 Report the number of all the subprograms in a compilation unit
17222
17223 @item ^--no-all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS_OFF^
17224 Do not report the number of all the subprograms in a compilation unit
17225
17226 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES_ON^
17227 Report the number of public types in a compilation unit
17228
17229 @item ^--no-public-types^/SYNTAX_METRICS=PUBLIC_TYPES_OFF^
17230 Do not report the number of public types in a compilation unit
17231
17232 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES_ON^
17233 Report the number of all the types in a compilation unit
17234
17235 @item ^--no-all-types^/SYNTAX_METRICS=ALL_TYPES_OFF^
17236 Do not report the number of all the types in a compilation unit
17237
17238 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_ON^
17239 Report the maximal program unit nesting level
17240
17241 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
17242 Do not report the maximal program unit nesting level
17243
17244 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING_ON^
17245 Report the maximal construct nesting level
17246
17247 @item ^--no-construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING_OFF^
17248 Do not report the maximal construct nesting level
17249
17250 @end table
17251
17252 @node Complexity Metrics Control
17253 @subsubsection Complexity Metrics Control
17254 @cindex Complexity metrics control in @command{gnatmetric}
17255
17256 @noindent
17257 For a program unit that is an executable body (a subprogram body (including
17258 generic bodies), task body, entry body or a package body containing
17259 its own statement sequence) @command{gnatmetric} computes the following
17260 complexity metrics:
17261
17262 @itemize @bullet
17263 @item
17264 McCabe cyclomatic complexity;
17265
17266 @item
17267 McCabe essential complexity;
17268
17269 @item
17270 maximal loop nesting level
17271
17272 @end itemize
17273
17274 @noindent
17275 The McCabe complexity metrics are defined
17276 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
17277
17278 According to McCabe, both control statements and short-circuit control forms
17279 should be taken into account when computing cyclomatic complexity. For each
17280 body, we compute three metric values:
17281
17282 @itemize @bullet
17283 @item
17284 the complexity introduced by control
17285 statements only, without taking into account short-circuit forms,
17286
17287 @item
17288 the complexity introduced by short-circuit control forms only, and
17289
17290 @item
17291 the total
17292 cyclomatic complexity, which is the sum of these two values.
17293 @end itemize
17294
17295 @noindent
17296 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
17297 the code in the exception handlers and in all the nested program units.
17298
17299 By default, all the complexity metrics are computed and reported.
17300 For more fine-grained control you can use
17301 the following switches:
17302
17303 @table @option
17304 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
17305
17306 @ifclear vms
17307 @cindex @option{--no-complexity@var{x}}
17308 @end ifclear
17309
17310 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL_ON^
17311 Report all the complexity metrics
17312
17313 @item ^--no-complexity-all^/COMPLEXITY_METRICS=ALL_OFF^
17314 Do not report any of complexity metrics
17315
17316 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC_ON^
17317 Report the McCabe Cyclomatic Complexity
17318
17319 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC_OFF^
17320 Do not report the McCabe Cyclomatic Complexity
17321
17322 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL_ON^
17323 Report the Essential Complexity
17324
17325 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL_OFF^
17326 Do not report the Essential Complexity
17327
17328 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
17329 Report maximal loop nesting level
17330
17331 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_OFF^
17332 Do not report maximal loop nesting level
17333
17334 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY_ON^
17335 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
17336 task bodies, entry bodies and statement sequences in package bodies.
17337 The metric is computed and reported for whole set of processed Ada sources
17338 only.
17339
17340 @item ^--no-complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY_OFF^
17341 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
17342 bodies, task bodies, entry bodies and statement sequences in package bodies
17343
17344 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
17345 @item ^-ne^/NO_EXITS_AS_GOTOS^
17346 Do not consider @code{exit} statements as @code{goto}s when
17347 computing Essential Complexity
17348
17349 @end table
17350
17351
17352 @node Object-Oriented Metrics Control
17353 @subsubsection Object-Oriented Metrics Control
17354 @cindex Object-Oriented metrics control in @command{gnatmetric}
17355
17356 @noindent
17357 @cindex Coupling metrics (in in @command{gnatmetric})
17358 Coupling metrics are object-oriented metrics that measure the
17359 dependencies between a given class (or a group of classes) and the
17360 ``external world'' (that is, the other classes in the program). In this
17361 subsection the term ``class'' is used in its
17362 traditional object-oriented programming sense
17363 (an instantiable module that contains data and/or method members).
17364 A @emph{category} (of classes)
17365 is a group of closely related classes that are reused and/or
17366 modified together.
17367
17368 A class @code{K}'s @emph{efferent coupling} is the number of classes
17369 that @code{K} depends upon.
17370 A category's efferent coupling is the number of classes outside the
17371 category that the classes inside the category depend upon.
17372
17373 A class @code{K}'s @emph{afferent coupling} is the number of classes
17374 that depend upon @code{K}.
17375 A category's afferent coupling is the number of classes outside the
17376 category that depend on classes belonging to the category.
17377
17378 Ada's implementation of the object-oriented paradigm does not use the
17379 traditional class notion, so the definition of the coupling
17380 metrics for Ada maps the class and class category notions
17381 onto Ada constructs.
17382
17383 For the coupling metrics, several kinds of modules -- a library package,
17384 a library generic package, and a library generic package instantiation --
17385 that define a tagged type or an interface type are
17386 considered to be a class. A category consists of a library package (or
17387 a library generic package) that defines a tagged or an interface type,
17388 together with all its descendant (generic) packages that define tagged
17389 or interface types. For any package counted as a class,
17390 its body (if any) is considered
17391 together with its spec when counting the dependencies. For dependencies
17392 between classes, the Ada semantic dependencies are considered.
17393 For coupling metrics, only dependencies on units that are considered as
17394 classes, are considered.
17395
17396 When computing coupling metrics, @command{gnatmetric} counts only
17397 dependencies between units that are arguments of the gnatmetric call.
17398 Coupling metrics are program-wide (or project-wide) metrics, so to
17399 get a valid result, you should call @command{gnatmetric} for
17400 the whole set of sources that make up your program. It can be done
17401 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
17402 option (see See @ref{The GNAT Driver and Project Files} for details.
17403
17404 By default, all the coupling metrics are disabled. You can use the following
17405 switches to specify the coupling metrics to be computed and reported:
17406
17407 @table @option
17408
17409 @ifclear vms
17410 @cindex @option{--package@var{x}} (@command{gnatmetric})
17411 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
17412 @cindex @option{--category@var{x}} (@command{gnatmetric})
17413 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
17414 @end ifclear
17415
17416 @ifset vms
17417 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
17418 @end ifset
17419
17420 @item ^--coupling-all^/COUPLING_METRICS=ALL_ON^
17421 Report all the coupling metrics
17422
17423 @item ^--no-coupling-all^/COUPLING_METRICS=ALL_OFF^
17424 Do not report any of  metrics
17425
17426 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT_ON^
17427 Report package efferent coupling
17428
17429 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT_OFF^
17430 Do not report package efferent coupling
17431
17432 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT_ON^
17433 Report package afferent coupling
17434
17435 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT_OFF^
17436 Do not report package afferent coupling
17437
17438 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT_ON^
17439 Report category efferent coupling
17440
17441 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT_OFF^
17442 Do not report category efferent coupling
17443
17444 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT_ON^
17445 Report category afferent coupling
17446
17447 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT_OFF^
17448 Do not report category afferent coupling
17449
17450 @end table
17451
17452 @node Other gnatmetric Switches
17453 @subsection Other @code{gnatmetric} Switches
17454
17455 @noindent
17456 Additional @command{gnatmetric} switches are as follows:
17457
17458 @table @option
17459 @item ^-files @var{filename}^/FILES=@var{filename}^
17460 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
17461 Take the argument source files from the specified file. This file should be an
17462 ordinary text file containing file names separated by spaces or
17463 line breaks. You can use this switch more then once in the same call to
17464 @command{gnatmetric}. You also can combine this switch with
17465 an explicit list of files.
17466
17467 @item ^-v^/VERBOSE^
17468 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
17469 Verbose mode;
17470 @command{gnatmetric} generates version information and then
17471 a trace of sources being processed.
17472
17473 @item ^-dv^/DEBUG_OUTPUT^
17474 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
17475 Debug mode;
17476 @command{gnatmetric} generates various messages useful to understand what
17477 happens during the metrics computation
17478
17479 @item ^-q^/QUIET^
17480 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
17481 Quiet mode.
17482 @end table
17483
17484 @node Generate project-wide metrics
17485 @subsection Generate project-wide metrics
17486
17487 In order to compute metrics on all units of a given project, you can use
17488 the @command{gnat} driver along with the @option{-P} option:
17489 @smallexample
17490    gnat metric -Pproj
17491 @end smallexample
17492
17493 @noindent
17494 If the project @code{proj} depends upon other projects, you can compute
17495 the metrics on the project closure using the @option{-U} option:
17496 @smallexample
17497    gnat metric -Pproj -U
17498 @end smallexample
17499
17500 @noindent
17501 Finally, if not all the units are relevant to a particular main
17502 program in the project closure, you can generate metrics for the set
17503 of units needed to create a given main program (unit closure) using
17504 the @option{-U} option followed by the name of the main unit:
17505 @smallexample
17506    gnat metric -Pproj -U main
17507 @end smallexample
17508
17509
17510 @c ***********************************
17511 @node File Name Krunching Using gnatkr
17512 @chapter File Name Krunching Using @code{gnatkr}
17513 @findex gnatkr
17514
17515 @noindent
17516 This chapter discusses the method used by the compiler to shorten
17517 the default file names chosen for Ada units so that they do not
17518 exceed the maximum length permitted. It also describes the
17519 @code{gnatkr} utility that can be used to determine the result of
17520 applying this shortening.
17521 @menu
17522 * About gnatkr::
17523 * Using gnatkr::
17524 * Krunching Method::
17525 * Examples of gnatkr Usage::
17526 @end menu
17527
17528 @node About gnatkr
17529 @section About @code{gnatkr}
17530
17531 @noindent
17532 The default file naming rule in GNAT
17533 is that the file name must be derived from
17534 the unit name. The exact default rule is as follows:
17535 @itemize @bullet
17536 @item
17537 Take the unit name and replace all dots by hyphens.
17538 @item
17539 If such a replacement occurs in the
17540 second character position of a name, and the first character is
17541 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
17542 then replace the dot by the character
17543 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
17544 instead of a minus.
17545 @end itemize
17546 The reason for this exception is to avoid clashes
17547 with the standard names for children of System, Ada, Interfaces,
17548 and GNAT, which use the prefixes
17549 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
17550 respectively.
17551
17552 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
17553 switch of the compiler activates a ``krunching''
17554 circuit that limits file names to nn characters (where nn is a decimal
17555 integer). For example, using OpenVMS,
17556 where the maximum file name length is
17557 39, the value of nn is usually set to 39, but if you want to generate
17558 a set of files that would be usable if ported to a system with some
17559 different maximum file length, then a different value can be specified.
17560 The default value of 39 for OpenVMS need not be specified.
17561
17562 The @code{gnatkr} utility can be used to determine the krunched name for
17563 a given file, when krunched to a specified maximum length.
17564
17565 @node Using gnatkr
17566 @section Using @code{gnatkr}
17567
17568 @noindent
17569 The @code{gnatkr} command has the form
17570
17571 @ifclear vms
17572 @smallexample
17573 $ gnatkr @var{name} @ovar{length}
17574 @end smallexample
17575 @end ifclear
17576
17577 @ifset vms
17578 @smallexample
17579 $ gnatkr @var{name} /COUNT=nn
17580 @end smallexample
17581 @end ifset
17582
17583 @noindent
17584 @var{name} is the uncrunched file name, derived from the name of the unit
17585 in the standard manner described in the previous section (i.e., in particular
17586 all dots are replaced by hyphens). The file name may or may not have an
17587 extension (defined as a suffix of the form period followed by arbitrary
17588 characters other than period). If an extension is present then it will
17589 be preserved in the output. For example, when krunching @file{hellofile.ads}
17590 to eight characters, the result will be hellofil.ads.
17591
17592 Note: for compatibility with previous versions of @code{gnatkr} dots may
17593 appear in the name instead of hyphens, but the last dot will always be
17594 taken as the start of an extension. So if @code{gnatkr} is given an argument
17595 such as @file{Hello.World.adb} it will be treated exactly as if the first
17596 period had been a hyphen, and for example krunching to eight characters
17597 gives the result @file{hellworl.adb}.
17598
17599 Note that the result is always all lower case (except on OpenVMS where it is
17600 all upper case). Characters of the other case are folded as required.
17601
17602 @var{length} represents the length of the krunched name. The default
17603 when no argument is given is ^8^39^ characters. A length of zero stands for
17604 unlimited, in other words do not chop except for system files where the
17605 implied crunching length is always eight characters.
17606
17607 @noindent
17608 The output is the krunched name. The output has an extension only if the
17609 original argument was a file name with an extension.
17610
17611 @node Krunching Method
17612 @section Krunching Method
17613
17614 @noindent
17615 The initial file name is determined by the name of the unit that the file
17616 contains. The name is formed by taking the full expanded name of the
17617 unit and replacing the separating dots with hyphens and
17618 using ^lowercase^uppercase^
17619 for all letters, except that a hyphen in the second character position is
17620 replaced by a ^tilde^dollar sign^ if the first character is
17621 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
17622 The extension is @code{.ads} for a
17623 spec and @code{.adb} for a body.
17624 Krunching does not affect the extension, but the file name is shortened to
17625 the specified length by following these rules:
17626
17627 @itemize @bullet
17628 @item
17629 The name is divided into segments separated by hyphens, tildes or
17630 underscores and all hyphens, tildes, and underscores are
17631 eliminated. If this leaves the name short enough, we are done.
17632
17633 @item
17634 If the name is too long, the longest segment is located (left-most
17635 if there are two of equal length), and shortened by dropping
17636 its last character. This is repeated until the name is short enough.
17637
17638 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
17639 to fit the name into 8 characters as required by some operating systems.
17640
17641 @smallexample
17642 our-strings-wide_fixed 22
17643 our strings wide fixed 19
17644 our string  wide fixed 18
17645 our strin   wide fixed 17
17646 our stri    wide fixed 16
17647 our stri    wide fixe  15
17648 our str     wide fixe  14
17649 our str     wid  fixe  13
17650 our str     wid  fix   12
17651 ou  str     wid  fix   11
17652 ou  st      wid  fix   10
17653 ou  st      wi   fix   9
17654 ou  st      wi   fi    8
17655 Final file name: oustwifi.adb
17656 @end smallexample
17657
17658 @item
17659 The file names for all predefined units are always krunched to eight
17660 characters. The krunching of these predefined units uses the following
17661 special prefix replacements:
17662
17663 @table @file
17664 @item ada-
17665 replaced by @file{^a^A^-}
17666
17667 @item gnat-
17668 replaced by @file{^g^G^-}
17669
17670 @item interfaces-
17671 replaced by @file{^i^I^-}
17672
17673 @item system-
17674 replaced by @file{^s^S^-}
17675 @end table
17676
17677 These system files have a hyphen in the second character position. That
17678 is why normal user files replace such a character with a
17679 ^tilde^dollar sign^, to
17680 avoid confusion with system file names.
17681
17682 As an example of this special rule, consider
17683 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
17684
17685 @smallexample
17686 ada-strings-wide_fixed 22
17687 a-  strings wide fixed 18
17688 a-  string  wide fixed 17
17689 a-  strin   wide fixed 16
17690 a-  stri    wide fixed 15
17691 a-  stri    wide fixe  14
17692 a-  str     wide fixe  13
17693 a-  str     wid  fixe  12
17694 a-  str     wid  fix   11
17695 a-  st      wid  fix   10
17696 a-  st      wi   fix   9
17697 a-  st      wi   fi    8
17698 Final file name: a-stwifi.adb
17699 @end smallexample
17700 @end itemize
17701
17702 Of course no file shortening algorithm can guarantee uniqueness over all
17703 possible unit names, and if file name krunching is used then it is your
17704 responsibility to ensure that no name clashes occur. The utility
17705 program @code{gnatkr} is supplied for conveniently determining the
17706 krunched name of a file.
17707
17708 @node Examples of gnatkr Usage
17709 @section Examples of @code{gnatkr} Usage
17710
17711 @smallexample
17712 @iftex
17713 @leftskip=0cm
17714 @end iftex
17715 @ifclear vms
17716 $ gnatkr very_long_unit_name.ads      --> velounna.ads
17717 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
17718 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
17719 $ gnatkr grandparent-parent-child     --> grparchi
17720 @end ifclear
17721 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
17722 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
17723 @end smallexample
17724
17725 @node Preprocessing Using gnatprep
17726 @chapter Preprocessing Using @code{gnatprep}
17727 @findex gnatprep
17728
17729 @noindent
17730 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
17731 preprocessing.
17732 Although designed for use with GNAT, @code{gnatprep} does not depend on any
17733 special GNAT features.
17734 For further discussion of conditional compilation in general, see
17735 @ref{Conditional Compilation}.
17736
17737 @menu
17738 * Preprocessing Symbols::
17739 * Using gnatprep::
17740 * Switches for gnatprep::
17741 * Form of Definitions File::
17742 * Form of Input Text for gnatprep::
17743 @end menu
17744
17745 @node Preprocessing Symbols
17746 @section Preprocessing Symbols
17747
17748 @noindent
17749 Preprocessing symbols are defined in definition files and referred to in
17750 sources to be preprocessed. A Preprocessing symbol is an identifier, following
17751 normal Ada (case-insensitive) rules for its syntax, with the restriction that
17752 all characters need to be in the ASCII set (no accented letters).
17753
17754 @node Using gnatprep
17755 @section Using @code{gnatprep}
17756
17757 @noindent
17758 To call @code{gnatprep} use
17759
17760 @smallexample
17761 $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
17762 @end smallexample
17763
17764 @noindent
17765 where
17766 @table @var
17767 @item switches
17768 is an optional sequence of switches as described in the next section.
17769
17770 @item infile
17771 is the full name of the input file, which is an Ada source
17772 file containing preprocessor directives.
17773
17774 @item outfile
17775 is the full name of the output file, which is an Ada source
17776 in standard Ada form. When used with GNAT, this file name will
17777 normally have an ads or adb suffix.
17778
17779 @item deffile
17780 is the full name of a text file containing definitions of
17781 preprocessing symbols to be referenced by the preprocessor. This argument is
17782 optional, and can be replaced by the use of the @option{-D} switch.
17783
17784 @end table
17785
17786 @node Switches for gnatprep
17787 @section Switches for @code{gnatprep}
17788
17789 @table @option
17790 @c !sort!
17791
17792 @item ^-b^/BLANK_LINES^
17793 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
17794 Causes both preprocessor lines and the lines deleted by
17795 preprocessing to be replaced by blank lines in the output source file,
17796 preserving line numbers in the output file.
17797
17798 @item ^-c^/COMMENTS^
17799 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
17800 Causes both preprocessor lines and the lines deleted
17801 by preprocessing to be retained in the output source as comments marked
17802 with the special string @code{"--! "}. This option will result in line numbers
17803 being preserved in the output file.
17804
17805 @item ^-C^/REPLACE_IN_COMMENTS^
17806 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
17807 Causes comments to be scanned. Normally comments are ignored by gnatprep.
17808 If this option is specified, then comments are scanned and any $symbol
17809 substitutions performed as in program text. This is particularly useful
17810 when structured comments are used (e.g., when writing programs in the
17811 SPARK dialect of Ada). Note that this switch is not available when
17812 doing integrated preprocessing (it would be useless in this context
17813 since comments are ignored by the compiler in any case).
17814
17815 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
17816 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
17817 Defines a new preprocessing symbol, associated with value. If no value is given
17818 on the command line, then symbol is considered to be @code{True}. This switch
17819 can be used in place of a definition file.
17820
17821 @ifset vms
17822 @item /REMOVE
17823 @cindex @option{/REMOVE} (@command{gnatprep})
17824 This is the default setting which causes lines deleted by preprocessing
17825 to be entirely removed from the output file.
17826 @end ifset
17827
17828 @item ^-r^/REFERENCE^
17829 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
17830 Causes a @code{Source_Reference} pragma to be generated that
17831 references the original input file, so that error messages will use
17832 the file name of this original file. The use of this switch implies
17833 that preprocessor lines are not to be removed from the file, so its
17834 use will force @option{^-b^/BLANK_LINES^} mode if
17835 @option{^-c^/COMMENTS^}
17836 has not been specified explicitly.
17837
17838 Note that if the file to be preprocessed contains multiple units, then
17839 it will be necessary to @code{gnatchop} the output file from
17840 @code{gnatprep}. If a @code{Source_Reference} pragma is present
17841 in the preprocessed file, it will be respected by
17842 @code{gnatchop ^-r^/REFERENCE^}
17843 so that the final chopped files will correctly refer to the original
17844 input source file for @code{gnatprep}.
17845
17846 @item ^-s^/SYMBOLS^
17847 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
17848 Causes a sorted list of symbol names and values to be
17849 listed on the standard output file.
17850
17851 @item ^-u^/UNDEFINED^
17852 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
17853 Causes undefined symbols to be treated as having the value FALSE in the context
17854 of a preprocessor test. In the absence of this option, an undefined symbol in
17855 a @code{#if} or @code{#elsif} test will be treated as an error.
17856
17857 @end table
17858
17859 @ifclear vms
17860 @noindent
17861 Note: if neither @option{-b} nor @option{-c} is present,
17862 then preprocessor lines and
17863 deleted lines are completely removed from the output, unless -r is
17864 specified, in which case -b is assumed.
17865 @end ifclear
17866
17867 @node Form of Definitions File
17868 @section Form of Definitions File
17869
17870 @noindent
17871 The definitions file contains lines of the form
17872
17873 @smallexample
17874 symbol := value
17875 @end smallexample
17876
17877 @noindent
17878 where symbol is a preprocessing symbol, and value is one of the following:
17879
17880 @itemize @bullet
17881 @item
17882 Empty, corresponding to a null substitution
17883 @item
17884 A string literal using normal Ada syntax
17885 @item
17886 Any sequence of characters from the set
17887 (letters, digits, period, underline).
17888 @end itemize
17889
17890 @noindent
17891 Comment lines may also appear in the definitions file, starting with
17892 the usual @code{--},
17893 and comments may be added to the definitions lines.
17894
17895 @node Form of Input Text for gnatprep
17896 @section Form of Input Text for @code{gnatprep}
17897
17898 @noindent
17899 The input text may contain preprocessor conditional inclusion lines,
17900 as well as general symbol substitution sequences.
17901
17902 The preprocessor conditional inclusion commands have the form
17903
17904 @smallexample
17905 @group
17906 @cartouche
17907 #if @i{expression} @r{[}then@r{]}
17908    lines
17909 #elsif @i{expression} @r{[}then@r{]}
17910    lines
17911 #elsif @i{expression} @r{[}then@r{]}
17912    lines
17913 @dots{}
17914 #else
17915    lines
17916 #end if;
17917 @end cartouche
17918 @end group
17919 @end smallexample
17920
17921 @noindent
17922 In this example, @i{expression} is defined by the following grammar:
17923 @smallexample
17924 @i{expression} ::=  <symbol>
17925 @i{expression} ::=  <symbol> = "<value>"
17926 @i{expression} ::=  <symbol> = <symbol>
17927 @i{expression} ::=  <symbol> 'Defined
17928 @i{expression} ::=  not @i{expression}
17929 @i{expression} ::=  @i{expression} and @i{expression}
17930 @i{expression} ::=  @i{expression} or @i{expression}
17931 @i{expression} ::=  @i{expression} and then @i{expression}
17932 @i{expression} ::=  @i{expression} or else @i{expression}
17933 @i{expression} ::=  ( @i{expression} )
17934 @end smallexample
17935
17936 The following restriction exists: it is not allowed to have "and" or "or"
17937 following "not" in the same expression without parentheses. For example, this
17938 is not allowed:
17939
17940 @smallexample
17941    not X or Y
17942 @end smallexample
17943
17944 This should be one of the following:
17945
17946 @smallexample
17947    (not X) or Y
17948    not (X or Y)
17949 @end smallexample
17950
17951 @noindent
17952 For the first test (@i{expression} ::= <symbol>) the symbol must have
17953 either the value true or false, that is to say the right-hand of the
17954 symbol definition must be one of the (case-insensitive) literals
17955 @code{True} or @code{False}. If the value is true, then the
17956 corresponding lines are included, and if the value is false, they are
17957 excluded.
17958
17959 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
17960 the symbol has been defined in the definition file or by a @option{-D}
17961 switch on the command line. Otherwise, the test is false.
17962
17963 The equality tests are case insensitive, as are all the preprocessor lines.
17964
17965 If the symbol referenced is not defined in the symbol definitions file,
17966 then the effect depends on whether or not switch @option{-u}
17967 is specified. If so, then the symbol is treated as if it had the value
17968 false and the test fails. If this switch is not specified, then
17969 it is an error to reference an undefined symbol. It is also an error to
17970 reference a symbol that is defined with a value other than @code{True}
17971 or @code{False}.
17972
17973 The use of the @code{not} operator inverts the sense of this logical test.
17974 The @code{not} operator cannot be combined with the @code{or} or @code{and}
17975 operators, without parentheses. For example, "if not X or Y then" is not
17976 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
17977
17978 The @code{then} keyword is optional as shown
17979
17980 The @code{#} must be the first non-blank character on a line, but
17981 otherwise the format is free form. Spaces or tabs may appear between
17982 the @code{#} and the keyword. The keywords and the symbols are case
17983 insensitive as in normal Ada code. Comments may be used on a
17984 preprocessor line, but other than that, no other tokens may appear on a
17985 preprocessor line. Any number of @code{elsif} clauses can be present,
17986 including none at all. The @code{else} is optional, as in Ada.
17987
17988 The @code{#} marking the start of a preprocessor line must be the first
17989 non-blank character on the line, i.e., it must be preceded only by
17990 spaces or horizontal tabs.
17991
17992 Symbol substitution outside of preprocessor lines is obtained by using
17993 the sequence
17994
17995 @smallexample
17996 $symbol
17997 @end smallexample
17998
17999 @noindent
18000 anywhere within a source line, except in a comment or within a
18001 string literal. The identifier
18002 following the @code{$} must match one of the symbols defined in the symbol
18003 definition file, and the result is to substitute the value of the
18004 symbol in place of @code{$symbol} in the output file.
18005
18006 Note that although the substitution of strings within a string literal
18007 is not possible, it is possible to have a symbol whose defined value is
18008 a string literal. So instead of setting XYZ to @code{hello} and writing:
18009
18010 @smallexample
18011 Header : String := "$XYZ";
18012 @end smallexample
18013
18014 @noindent
18015 you should set XYZ to @code{"hello"} and write:
18016
18017 @smallexample
18018 Header : String := $XYZ;
18019 @end smallexample
18020
18021 @noindent
18022 and then the substitution will occur as desired.
18023
18024 @ifset vms
18025 @node The GNAT Run-Time Library Builder gnatlbr
18026 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
18027 @findex gnatlbr
18028 @cindex Library builder
18029
18030 @noindent
18031 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
18032 supplied configuration pragmas.
18033
18034 @menu
18035 * Running gnatlbr::
18036 * Switches for gnatlbr::
18037 * Examples of gnatlbr Usage::
18038 @end menu
18039
18040 @node Running gnatlbr
18041 @section Running @code{gnatlbr}
18042
18043 @noindent
18044 The @code{gnatlbr} command has the form
18045
18046 @smallexample
18047 $ GNAT LIBRARY /@r{[}CREATE@r{|}SET@r{|}DELETE@r{]}=directory @r{[}/CONFIG=file@r{]}
18048 @end smallexample
18049
18050 @node Switches for gnatlbr
18051 @section Switches for @code{gnatlbr}
18052
18053 @noindent
18054 @code{gnatlbr} recognizes the following switches:
18055
18056 @table @option
18057 @c !sort!
18058 @item /CREATE=directory
18059 @cindex @code{/CREATE} (@code{gnatlbr})
18060 Create the new run-time library in the specified directory.
18061
18062 @item /SET=directory
18063 @cindex @code{/SET} (@code{gnatlbr})
18064 Make the library in the specified directory the current run-time library.
18065
18066 @item /DELETE=directory
18067 @cindex @code{/DELETE} (@code{gnatlbr})
18068 Delete the run-time library in the specified directory.
18069
18070 @item /CONFIG=file
18071 @cindex @code{/CONFIG} (@code{gnatlbr})
18072 With /CREATE: Use the configuration pragmas in the specified file when
18073 building the library.
18074
18075 With /SET: Use the configuration pragmas in the specified file when
18076 compiling.
18077
18078 @end table
18079
18080 @node Examples of gnatlbr Usage
18081 @section Example of @code{gnatlbr} Usage
18082
18083 @smallexample
18084 Contents of VAXFLOAT.ADC:
18085 pragma Float_Representation (VAX_Float);
18086
18087 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
18088
18089 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
18090
18091 @end smallexample
18092 @end ifset
18093
18094 @node The GNAT Library Browser gnatls
18095 @chapter The GNAT Library Browser @code{gnatls}
18096 @findex gnatls
18097 @cindex Library browser
18098
18099 @noindent
18100 @code{gnatls} is a tool that outputs information about compiled
18101 units. It gives the relationship between objects, unit names and source
18102 files. It can also be used to check the source dependencies of a unit
18103 as well as various characteristics.
18104
18105 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
18106 driver (see @ref{The GNAT Driver and Project Files}).
18107
18108 @menu
18109 * Running gnatls::
18110 * Switches for gnatls::
18111 * Examples of gnatls Usage::
18112 @end menu
18113
18114 @node Running gnatls
18115 @section Running @code{gnatls}
18116
18117 @noindent
18118 The @code{gnatls} command has the form
18119
18120 @smallexample
18121 $ gnatls switches @var{object_or_ali_file}
18122 @end smallexample
18123
18124 @noindent
18125 The main argument is the list of object or @file{ali} files
18126 (@pxref{The Ada Library Information Files})
18127 for which information is requested.
18128
18129 In normal mode, without additional option, @code{gnatls} produces a
18130 four-column listing. Each line represents information for a specific
18131 object. The first column gives the full path of the object, the second
18132 column gives the name of the principal unit in this object, the third
18133 column gives the status of the source and the fourth column gives the
18134 full path of the source representing this unit.
18135 Here is a simple example of use:
18136
18137 @smallexample
18138 $ gnatls *.o
18139 ^./^[]^demo1.o            demo1            DIF demo1.adb
18140 ^./^[]^demo2.o            demo2             OK demo2.adb
18141 ^./^[]^hello.o            h1                OK hello.adb
18142 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
18143 ^./^[]^instr.o            instr             OK instr.adb
18144 ^./^[]^tef.o              tef              DIF tef.adb
18145 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
18146 ^./^[]^tgef.o             tgef             DIF tgef.adb
18147 @end smallexample
18148
18149 @noindent
18150 The first line can be interpreted as follows: the main unit which is
18151 contained in
18152 object file @file{demo1.o} is demo1, whose main source is in
18153 @file{demo1.adb}. Furthermore, the version of the source used for the
18154 compilation of demo1 has been modified (DIF). Each source file has a status
18155 qualifier which can be:
18156
18157 @table @code
18158 @item OK (unchanged)
18159 The version of the source file used for the compilation of the
18160 specified unit corresponds exactly to the actual source file.
18161
18162 @item MOK (slightly modified)
18163 The version of the source file used for the compilation of the
18164 specified unit differs from the actual source file but not enough to
18165 require recompilation. If you use gnatmake with the qualifier
18166 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
18167 MOK will not be recompiled.
18168
18169 @item DIF (modified)
18170 No version of the source found on the path corresponds to the source
18171 used to build this object.
18172
18173 @item ??? (file not found)
18174 No source file was found for this unit.
18175
18176 @item HID (hidden,  unchanged version not first on PATH)
18177 The version of the source that corresponds exactly to the source used
18178 for compilation has been found on the path but it is hidden by another
18179 version of the same source that has been modified.
18180
18181 @end table
18182
18183 @node Switches for gnatls
18184 @section Switches for @code{gnatls}
18185
18186 @noindent
18187 @code{gnatls} recognizes the following switches:
18188
18189 @table @option
18190 @c !sort!
18191 @cindex @option{--version} @command{gnatls}
18192 Display Copyright and version, then exit disregarding all other options.
18193
18194 @item --help
18195 @cindex @option{--help} @command{gnatls}
18196 If @option{--version} was not used, display usage, then exit disregarding
18197 all other options.
18198
18199 @item ^-a^/ALL_UNITS^
18200 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
18201 Consider all units, including those of the predefined Ada library.
18202 Especially useful with @option{^-d^/DEPENDENCIES^}.
18203
18204 @item ^-d^/DEPENDENCIES^
18205 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
18206 List sources from which specified units depend on.
18207
18208 @item ^-h^/OUTPUT=OPTIONS^
18209 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
18210 Output the list of options.
18211
18212 @item ^-o^/OUTPUT=OBJECTS^
18213 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
18214 Only output information about object files.
18215
18216 @item ^-s^/OUTPUT=SOURCES^
18217 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
18218 Only output information about source files.
18219
18220 @item ^-u^/OUTPUT=UNITS^
18221 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
18222 Only output information about compilation units.
18223
18224 @item ^-files^/FILES^=@var{file}
18225 @cindex @option{^-files^/FILES^} (@code{gnatls})
18226 Take as arguments the files listed in text file @var{file}.
18227 Text file @var{file} may contain empty lines that are ignored.
18228 Each nonempty line should contain the name of an existing file.
18229 Several such switches may be specified simultaneously.
18230
18231 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18232 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
18233 @itemx ^-I^/SEARCH=^@var{dir}
18234 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
18235 @itemx -nostdinc
18236 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
18237 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
18238 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
18239 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
18240 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
18241 flags (@pxref{Switches for gnatmake}).
18242
18243 @item --RTS=@var{rts-path}
18244 @cindex @option{--RTS} (@code{gnatls})
18245 Specifies the default location of the runtime library. Same meaning as the
18246 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
18247
18248 @item ^-v^/OUTPUT=VERBOSE^
18249 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
18250 Verbose mode. Output the complete source, object and project paths. Do not use
18251 the default column layout but instead use long format giving as much as
18252 information possible on each requested units, including special
18253 characteristics such as:
18254
18255 @table @code
18256 @item  Preelaborable
18257 The unit is preelaborable in the Ada sense.
18258
18259 @item No_Elab_Code
18260 No elaboration code has been produced by the compiler for this unit.
18261
18262 @item Pure
18263 The unit is pure in the Ada sense.
18264
18265 @item Elaborate_Body
18266 The unit contains a pragma Elaborate_Body.
18267
18268 @item Remote_Types
18269 The unit contains a pragma Remote_Types.
18270
18271 @item Shared_Passive
18272 The unit contains a pragma Shared_Passive.
18273
18274 @item Predefined
18275 This unit is part of the predefined environment and cannot be modified
18276 by the user.
18277
18278 @item Remote_Call_Interface
18279 The unit contains a pragma Remote_Call_Interface.
18280
18281 @end table
18282
18283 @end table
18284
18285 @node Examples of gnatls Usage
18286 @section Example of @code{gnatls} Usage
18287 @ifclear vms
18288
18289 @noindent
18290 Example of using the verbose switch. Note how the source and
18291 object paths are affected by the -I switch.
18292
18293 @smallexample
18294 $ gnatls -v -I.. demo1.o
18295
18296 GNATLS 5.03w (20041123-34)
18297 Copyright 1997-2004 Free Software Foundation, Inc.
18298
18299 Source Search Path:
18300    <Current_Directory>
18301    ../
18302    /home/comar/local/adainclude/
18303
18304 Object Search Path:
18305    <Current_Directory>
18306    ../
18307    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18308
18309 Project Search Path:
18310    <Current_Directory>
18311    /home/comar/local/lib/gnat/
18312
18313 ./demo1.o
18314    Unit =>
18315      Name   => demo1
18316      Kind   => subprogram body
18317      Flags  => No_Elab_Code
18318      Source => demo1.adb    modified
18319 @end smallexample
18320
18321 @noindent
18322 The following is an example of use of the dependency list.
18323 Note the use of the -s switch
18324 which gives a straight list of source files. This can be useful for
18325 building specialized scripts.
18326
18327 @smallexample
18328 $ gnatls -d demo2.o
18329 ./demo2.o   demo2        OK demo2.adb
18330                          OK gen_list.ads
18331                          OK gen_list.adb
18332                          OK instr.ads
18333                          OK instr-child.ads
18334
18335 $ gnatls -d -s -a demo1.o
18336 demo1.adb
18337 /home/comar/local/adainclude/ada.ads
18338 /home/comar/local/adainclude/a-finali.ads
18339 /home/comar/local/adainclude/a-filico.ads
18340 /home/comar/local/adainclude/a-stream.ads
18341 /home/comar/local/adainclude/a-tags.ads
18342 gen_list.ads
18343 gen_list.adb
18344 /home/comar/local/adainclude/gnat.ads
18345 /home/comar/local/adainclude/g-io.ads
18346 instr.ads
18347 /home/comar/local/adainclude/system.ads
18348 /home/comar/local/adainclude/s-exctab.ads
18349 /home/comar/local/adainclude/s-finimp.ads
18350 /home/comar/local/adainclude/s-finroo.ads
18351 /home/comar/local/adainclude/s-secsta.ads
18352 /home/comar/local/adainclude/s-stalib.ads
18353 /home/comar/local/adainclude/s-stoele.ads
18354 /home/comar/local/adainclude/s-stratt.ads
18355 /home/comar/local/adainclude/s-tasoli.ads
18356 /home/comar/local/adainclude/s-unstyp.ads
18357 /home/comar/local/adainclude/unchconv.ads
18358 @end smallexample
18359 @end ifclear
18360
18361 @ifset vms
18362 @smallexample
18363 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
18364
18365 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
18366 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
18367 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
18368 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
18369 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
18370 demo1.adb
18371 gen_list.ads
18372 gen_list.adb
18373 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
18374 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
18375 instr.ads
18376 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
18377 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
18378 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
18379 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
18380 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
18381 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
18382 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
18383 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
18384 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
18385 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
18386 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
18387 @end smallexample
18388 @end ifset
18389
18390 @node Cleaning Up Using gnatclean
18391 @chapter Cleaning Up Using @code{gnatclean}
18392 @findex gnatclean
18393 @cindex Cleaning tool
18394
18395 @noindent
18396 @code{gnatclean} is a tool that allows the deletion of files produced by the
18397 compiler, binder and linker, including ALI files, object files, tree files,
18398 expanded source files, library files, interface copy source files, binder
18399 generated files and executable files.
18400
18401 @menu
18402 * Running gnatclean::
18403 * Switches for gnatclean::
18404 @c * Examples of gnatclean Usage::
18405 @end menu
18406
18407 @node Running gnatclean
18408 @section Running @code{gnatclean}
18409
18410 @noindent
18411 The @code{gnatclean} command has the form:
18412
18413 @smallexample
18414 $ gnatclean switches @var{names}
18415 @end smallexample
18416
18417 @noindent
18418 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
18419 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
18420 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
18421
18422 @noindent
18423 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
18424 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
18425 the linker. In informative-only mode, specified by switch
18426 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
18427 normal mode is listed, but no file is actually deleted.
18428
18429 @node Switches for gnatclean
18430 @section Switches for @code{gnatclean}
18431
18432 @noindent
18433 @code{gnatclean} recognizes the following switches:
18434
18435 @table @option
18436 @c !sort!
18437 @cindex @option{--version} @command{gnatclean}
18438 Display Copyright and version, then exit disregarding all other options.
18439
18440 @item --help
18441 @cindex @option{--help} @command{gnatclean}
18442 If @option{--version} was not used, display usage, then exit disregarding
18443 all other options.
18444
18445 @item ^-c^/COMPILER_FILES_ONLY^
18446 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
18447 Only attempt to delete the files produced by the compiler, not those produced
18448 by the binder or the linker. The files that are not to be deleted are library
18449 files, interface copy files, binder generated files and executable files.
18450
18451 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
18452 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
18453 Indicate that ALI and object files should normally be found in directory
18454 @var{dir}.
18455
18456 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
18457 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
18458 When using project files, if some errors or warnings are detected during
18459 parsing and verbose mode is not in effect (no use of switch
18460 ^-v^/VERBOSE^), then error lines start with the full path name of the project
18461 file, rather than its simple file name.
18462
18463 @item ^-h^/HELP^
18464 @cindex @option{^-h^/HELP^} (@code{gnatclean})
18465 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
18466
18467 @item ^-n^/NODELETE^
18468 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
18469 Informative-only mode. Do not delete any files. Output the list of the files
18470 that would have been deleted if this switch was not specified.
18471
18472 @item ^-P^/PROJECT_FILE=^@var{project}
18473 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
18474 Use project file @var{project}. Only one such switch can be used.
18475 When cleaning a project file, the files produced by the compilation of the
18476 immediate sources or inherited sources of the project files are to be
18477 deleted. This is not depending on the presence or not of executable names
18478 on the command line.
18479
18480 @item ^-q^/QUIET^
18481 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
18482 Quiet output. If there are no errors, do not output anything, except in
18483 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
18484 (switch ^-n^/NODELETE^).
18485
18486 @item ^-r^/RECURSIVE^
18487 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
18488 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
18489 clean all imported and extended project files, recursively. If this switch
18490 is not specified, only the files related to the main project file are to be
18491 deleted. This switch has no effect if no project file is specified.
18492
18493 @item ^-v^/VERBOSE^
18494 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
18495 Verbose mode.
18496
18497 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
18498 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
18499 Indicates the verbosity of the parsing of GNAT project files.
18500 @xref{Switches Related to Project Files}.
18501
18502 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
18503 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
18504 Indicates that external variable @var{name} has the value @var{value}.
18505 The Project Manager will use this value for occurrences of
18506 @code{external(name)} when parsing the project file.
18507 @xref{Switches Related to Project Files}.
18508
18509 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18510 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
18511 When searching for ALI and object files, look in directory
18512 @var{dir}.
18513
18514 @item ^-I^/SEARCH=^@var{dir}
18515 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
18516 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
18517
18518 @item ^-I-^/NOCURRENT_DIRECTORY^
18519 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
18520 @cindex Source files, suppressing search
18521 Do not look for ALI or object files in the directory
18522 where @code{gnatclean} was invoked.
18523
18524 @end table
18525
18526 @c @node Examples of gnatclean Usage
18527 @c @section Examples of @code{gnatclean} Usage
18528
18529 @ifclear vms
18530 @node GNAT and Libraries
18531 @chapter GNAT and Libraries
18532 @cindex Library, building, installing, using
18533
18534 @noindent
18535 This chapter describes how to build and use libraries with GNAT, and also shows
18536 how to recompile the GNAT run-time library. You should be familiar with the
18537 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
18538 chapter.
18539
18540 @menu
18541 * Introduction to Libraries in GNAT::
18542 * General Ada Libraries::
18543 * Stand-alone Ada Libraries::
18544 * Rebuilding the GNAT Run-Time Library::
18545 @end menu
18546
18547 @node Introduction to Libraries in GNAT
18548 @section Introduction to Libraries in GNAT
18549
18550 @noindent
18551 A library is, conceptually, a collection of objects which does not have its
18552 own main thread of execution, but rather provides certain services to the
18553 applications that use it. A library can be either statically linked with the
18554 application, in which case its code is directly included in the application,
18555 or, on platforms that support it, be dynamically linked, in which case
18556 its code is shared by all applications making use of this library.
18557
18558 GNAT supports both types of libraries.
18559 In the static case, the compiled code can be provided in different ways. The
18560 simplest approach is to provide directly the set of objects resulting from
18561 compilation of the library source files. Alternatively, you can group the
18562 objects into an archive using whatever commands are provided by the operating
18563 system. For the latter case, the objects are grouped into a shared library.
18564
18565 In the GNAT environment, a library has three types of components:
18566 @itemize @bullet
18567 @item
18568 Source files.
18569 @item
18570 @file{ALI} files.
18571 @xref{The Ada Library Information Files}.
18572 @item
18573 Object files, an archive or a shared library.
18574 @end itemize
18575
18576 @noindent
18577 A GNAT library may expose all its source files, which is useful for
18578 documentation purposes. Alternatively, it may expose only the units needed by
18579 an external user to make use of the library. That is to say, the specs
18580 reflecting the library services along with all the units needed to compile
18581 those specs, which can include generic bodies or any body implementing an
18582 inlined routine. In the case of @emph{stand-alone libraries} those exposed
18583 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
18584
18585 All compilation units comprising an application, including those in a library,
18586 need to be elaborated in an order partially defined by Ada's semantics. GNAT
18587 computes the elaboration order from the @file{ALI} files and this is why they
18588 constitute a mandatory part of GNAT libraries. Except in the case of
18589 @emph{stand-alone libraries}, where a specific library elaboration routine is
18590 produced independently of the application(s) using the library.
18591
18592 @node General Ada Libraries
18593 @section General Ada Libraries
18594
18595 @menu
18596 * Building a library::
18597 * Installing a library::
18598 * Using a library::
18599 @end menu
18600
18601 @node Building a library
18602 @subsection Building a library
18603
18604 @noindent
18605 The easiest way to build a library is to use the Project Manager,
18606 which supports a special type of project called a @emph{Library Project}
18607 (@pxref{Library Projects}).
18608
18609 A project is considered a library project, when two project-level attributes
18610 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
18611 control different aspects of library configuration, additional optional
18612 project-level attributes can be specified:
18613 @table @code
18614 @item Library_Kind
18615 This attribute controls whether the library is to be static or dynamic
18616
18617 @item Library_Version
18618 This attribute specifies the library version; this value is used
18619 during dynamic linking of shared libraries to determine if the currently
18620 installed versions of the binaries are compatible.
18621
18622 @item Library_Options
18623 @item Library_GCC
18624 These attributes specify additional low-level options to be used during
18625 library generation, and redefine the actual application used to generate
18626 library.
18627 @end table
18628
18629 @noindent
18630 The GNAT Project Manager takes full care of the library maintenance task,
18631 including recompilation of the source files for which objects do not exist
18632 or are not up to date, assembly of the library archive, and installation of
18633 the library (i.e., copying associated source, object and @file{ALI} files
18634 to the specified location).
18635
18636 Here is a simple library project file:
18637 @smallexample @c ada
18638 project My_Lib is
18639    for Source_Dirs use ("src1", "src2");
18640    for Object_Dir use "obj";
18641    for Library_Name use "mylib";
18642    for Library_Dir use "lib";
18643    for Library_Kind use "dynamic";
18644 end My_lib;
18645 @end smallexample
18646
18647 @noindent
18648 and the compilation command to build and install the library:
18649
18650 @smallexample @c ada
18651   $ gnatmake -Pmy_lib
18652 @end smallexample
18653
18654 @noindent
18655 It is not entirely trivial to perform manually all the steps required to
18656 produce a library. We recommend that you use the GNAT Project Manager
18657 for this task. In special cases where this is not desired, the necessary
18658 steps are discussed below.
18659
18660 There are various possibilities for compiling the units that make up the
18661 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
18662 with a conventional script. For simple libraries, it is also possible to create
18663 a dummy main program which depends upon all the packages that comprise the
18664 interface of the library. This dummy main program can then be given to
18665 @command{gnatmake}, which will ensure that all necessary objects are built.
18666
18667 After this task is accomplished, you should follow the standard procedure
18668 of the underlying operating system to produce the static or shared library.
18669
18670 Here is an example of such a dummy program:
18671 @smallexample @c ada
18672 @group
18673 with My_Lib.Service1;
18674 with My_Lib.Service2;
18675 with My_Lib.Service3;
18676 procedure My_Lib_Dummy is
18677 begin
18678    null;
18679 end;
18680 @end group
18681 @end smallexample
18682
18683 @noindent
18684 Here are the generic commands that will build an archive or a shared library.
18685
18686 @smallexample
18687 # compiling the library
18688 $ gnatmake -c my_lib_dummy.adb
18689
18690 # we don't need the dummy object itself
18691 $ rm my_lib_dummy.o my_lib_dummy.ali
18692
18693 # create an archive with the remaining objects
18694 $ ar rc libmy_lib.a *.o
18695 # some systems may require "ranlib" to be run as well
18696
18697 # or create a shared library
18698 $ gcc -shared -o libmy_lib.so *.o
18699 # some systems may require the code to have been compiled with -fPIC
18700
18701 # remove the object files that are now in the library
18702 $ rm *.o
18703
18704 # Make the ALI files read-only so that gnatmake will not try to
18705 # regenerate the objects that are in the library
18706 $ chmod -w *.ali
18707 @end smallexample
18708
18709 @noindent
18710 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
18711 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
18712 be accessed by the directive @option{-l@var{xxx}} at link time.
18713
18714 @node Installing a library
18715 @subsection Installing a library
18716 @cindex @code{ADA_PROJECT_PATH}
18717
18718 @noindent
18719 If you use project files, library installation is part of the library build
18720 process. Thus no further action is needed in order to make use of the
18721 libraries that are built as part of the general application build. A usable
18722 version of the library is installed in the directory specified by the
18723 @code{Library_Dir} attribute of the library project file.
18724
18725 You may want to install a library in a context different from where the library
18726 is built. This situation arises with third party suppliers, who may want
18727 to distribute a library in binary form where the user is not expected to be
18728 able to recompile the library. The simplest option in this case is to provide
18729 a project file slightly different from the one used to build the library, by
18730 using the @code{externally_built} attribute. For instance, the project
18731 file used to build the library in the previous section can be changed into the
18732 following one when the library is installed:
18733
18734 @smallexample @c projectfile
18735 project My_Lib is
18736    for Source_Dirs use ("src1", "src2");
18737    for Library_Name use "mylib";
18738    for Library_Dir use "lib";
18739    for Library_Kind use "dynamic";
18740    for Externally_Built use "true";
18741 end My_lib;
18742 @end smallexample
18743
18744 @noindent
18745 This project file assumes that the directories @file{src1},
18746 @file{src2}, and @file{lib} exist in
18747 the directory containing the project file. The @code{externally_built}
18748 attribute makes it clear to the GNAT builder that it should not attempt to
18749 recompile any of the units from this library. It allows the library provider to
18750 restrict the source set to the minimum necessary for clients to make use of the
18751 library as described in the first section of this chapter. It is the
18752 responsibility of the library provider to install the necessary sources, ALI
18753 files and libraries in the directories mentioned in the project file. For
18754 convenience, the user's library project file should be installed in a location
18755 that will be searched automatically by the GNAT
18756 builder. These are the directories referenced in the @env{ADA_PROJECT_PATH}
18757 environment variable (@pxref{Importing Projects}), and also the default GNAT
18758 library location that can be queried with @command{gnatls -v} and is usually of
18759 the form $gnat_install_root/lib/gnat.
18760
18761 When project files are not an option, it is also possible, but not recommended,
18762 to install the library so that the sources needed to use the library are on the
18763 Ada source path and the ALI files & libraries be on the Ada Object path (see
18764 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
18765 administrator can place general-purpose libraries in the default compiler
18766 paths, by specifying the libraries' location in the configuration files
18767 @file{ada_source_path} and @file{ada_object_path}. These configuration files
18768 must be located in the GNAT installation tree at the same place as the gcc spec
18769 file. The location of the gcc spec file can be determined as follows:
18770 @smallexample
18771 $ gcc -v
18772 @end smallexample
18773
18774 @noindent
18775 The configuration files mentioned above have a simple format: each line
18776 must contain one unique directory name.
18777 Those names are added to the corresponding path
18778 in their order of appearance in the file. The names can be either absolute
18779 or relative; in the latter case, they are relative to where theses files
18780 are located.
18781
18782 The files @file{ada_source_path} and @file{ada_object_path} might not be
18783 present in a
18784 GNAT installation, in which case, GNAT will look for its run-time library in
18785 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
18786 objects and @file{ALI} files). When the files exist, the compiler does not
18787 look in @file{adainclude} and @file{adalib}, and thus the
18788 @file{ada_source_path} file
18789 must contain the location for the GNAT run-time sources (which can simply
18790 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
18791 contain the location for the GNAT run-time objects (which can simply
18792 be @file{adalib}).
18793
18794 You can also specify a new default path to the run-time library at compilation
18795 time with the switch @option{--RTS=rts-path}. You can thus choose / change
18796 the run-time library you want your program to be compiled with. This switch is
18797 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
18798 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
18799
18800 It is possible to install a library before or after the standard GNAT
18801 library, by reordering the lines in the configuration files. In general, a
18802 library must be installed before the GNAT library if it redefines
18803 any part of it.
18804
18805 @node Using a library
18806 @subsection Using a library
18807
18808 @noindent Once again, the project facility greatly simplifies the use of
18809 libraries. In this context, using a library is just a matter of adding a
18810 @code{with} clause in the user project. For instance, to make use of the
18811 library @code{My_Lib} shown in examples in earlier sections, you can
18812 write:
18813
18814 @smallexample @c projectfile
18815 with "my_lib";
18816 project My_Proj is
18817   @dots{}
18818 end My_Proj;
18819 @end smallexample
18820
18821 Even if you have a third-party, non-Ada library, you can still use GNAT's
18822 Project Manager facility to provide a wrapper for it. For example, the
18823 following project, when @code{with}ed by your main project, will link with the
18824 third-party library @file{liba.a}:
18825
18826 @smallexample @c projectfile
18827 @group
18828 project Liba is
18829    for Externally_Built use "true";
18830    for Source_Files use ();
18831    for Library_Dir use "lib";
18832    for Library_Name use "a";
18833    for Library_Kind use "static";
18834 end Liba;
18835 @end group
18836 @end smallexample
18837 This is an alternative to the use of @code{pragma Linker_Options}. It is
18838 especially interesting in the context of systems with several interdependent
18839 static libraries where finding a proper linker order is not easy and best be
18840 left to the tools having visibility over project dependence information.
18841
18842 @noindent
18843 In order to use an Ada library manually, you need to make sure that this
18844 library is on both your source and object path
18845 (see @ref{Search Paths and the Run-Time Library (RTL)}
18846 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
18847 in an archive or a shared library, you need to specify the desired
18848 library at link time.
18849
18850 For example, you can use the library @file{mylib} installed in
18851 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
18852
18853 @smallexample
18854 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
18855   -largs -lmy_lib
18856 @end smallexample
18857
18858 @noindent
18859 This can be expressed more simply:
18860 @smallexample
18861 $ gnatmake my_appl
18862 @end smallexample
18863 @noindent
18864 when the following conditions are met:
18865 @itemize @bullet
18866 @item
18867 @file{/dir/my_lib_src} has been added by the user to the environment
18868 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
18869 @file{ada_source_path}
18870 @item
18871 @file{/dir/my_lib_obj} has been added by the user to the environment
18872 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
18873 @file{ada_object_path}
18874 @item
18875 a pragma @code{Linker_Options} has been added to one of the sources.
18876 For example:
18877
18878 @smallexample @c ada
18879 pragma Linker_Options ("-lmy_lib");
18880 @end smallexample
18881 @end itemize
18882
18883 @node Stand-alone Ada Libraries
18884 @section Stand-alone Ada Libraries
18885 @cindex Stand-alone library, building, using
18886
18887 @menu
18888 * Introduction to Stand-alone Libraries::
18889 * Building a Stand-alone Library::
18890 * Creating a Stand-alone Library to be used in a non-Ada context::
18891 * Restrictions in Stand-alone Libraries::
18892 @end menu
18893
18894 @node Introduction to Stand-alone Libraries
18895 @subsection Introduction to Stand-alone Libraries
18896
18897 @noindent
18898 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
18899 necessary code to
18900 elaborate the Ada units that are included in the library. In contrast with
18901 an ordinary library, which consists of all sources, objects and @file{ALI}
18902 files of the
18903 library, a SAL may specify a restricted subset of compilation units
18904 to serve as a library interface. In this case, the fully
18905 self-sufficient set of files will normally consist of an objects
18906 archive, the sources of interface units' specs, and the @file{ALI}
18907 files of interface units.
18908 If an interface spec contains a generic unit or an inlined subprogram,
18909 the body's
18910 source must also be provided; if the units that must be provided in the source
18911 form depend on other units, the source and @file{ALI} files of those must
18912 also be provided.
18913
18914 The main purpose of a SAL is to minimize the recompilation overhead of client
18915 applications when a new version of the library is installed. Specifically,
18916 if the interface sources have not changed, client applications do not need to
18917 be recompiled. If, furthermore, a SAL is provided in the shared form and its
18918 version, controlled by @code{Library_Version} attribute, is not changed,
18919 then the clients do not need to be relinked.
18920
18921 SALs also allow the library providers to minimize the amount of library source
18922 text exposed to the clients.  Such ``information hiding'' might be useful or
18923 necessary for various reasons.
18924
18925 Stand-alone libraries are also well suited to be used in an executable whose
18926 main routine is not written in Ada.
18927
18928 @node Building a Stand-alone Library
18929 @subsection Building a Stand-alone Library
18930
18931 @noindent
18932 GNAT's Project facility provides a simple way of building and installing
18933 stand-alone libraries; see @ref{Stand-alone Library Projects}.
18934 To be a Stand-alone Library Project, in addition to the two attributes
18935 that make a project a Library Project (@code{Library_Name} and
18936 @code{Library_Dir}; see @ref{Library Projects}), the attribute
18937 @code{Library_Interface} must be defined.  For example:
18938
18939 @smallexample @c projectfile
18940 @group
18941    for Library_Dir use "lib_dir";
18942    for Library_Name use "dummy";
18943    for Library_Interface use ("int1", "int1.child");
18944 @end group
18945 @end smallexample
18946
18947 @noindent
18948 Attribute @code{Library_Interface} has a non-empty string list value,
18949 each string in the list designating a unit contained in an immediate source
18950 of the project file.
18951
18952 When a Stand-alone Library is built, first the binder is invoked to build
18953 a package whose name depends on the library name
18954 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
18955 This binder-generated package includes initialization and
18956 finalization procedures whose
18957 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
18958 in the example
18959 above). The object corresponding to this package is included in the library.
18960
18961 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
18962 calling of these procedures if a static SAL is built, or if a shared SAL
18963 is built
18964 with the project-level attribute @code{Library_Auto_Init} set to
18965 @code{"false"}.
18966
18967 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
18968 (those that are listed in attribute @code{Library_Interface}) are copied to
18969 the Library Directory. As a consequence, only the Interface Units may be
18970 imported from Ada units outside of the library. If other units are imported,
18971 the binding phase will fail.
18972
18973 The attribute @code{Library_Src_Dir} may be specified for a
18974 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
18975 single string value. Its value must be the path (absolute or relative to the
18976 project directory) of an existing directory. This directory cannot be the
18977 object directory or one of the source directories, but it can be the same as
18978 the library directory. The sources of the Interface
18979 Units of the library that are needed by an Ada client of the library will be
18980 copied to the designated directory, called the Interface Copy directory.
18981 These sources include the specs of the Interface Units, but they may also
18982 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
18983 are used, or when there is a generic unit in the spec. Before the sources
18984 are copied to the Interface Copy directory, an attempt is made to delete all
18985 files in the Interface Copy directory.
18986
18987 Building stand-alone libraries by hand is somewhat tedious, but for those
18988 occasions when it is necessary here are the steps that you need to perform:
18989 @itemize @bullet
18990 @item
18991 Compile all library sources.
18992
18993 @item
18994 Invoke the binder with the switch @option{-n} (No Ada main program),
18995 with all the @file{ALI} files of the interfaces, and
18996 with the switch @option{-L} to give specific names to the @code{init}
18997 and @code{final} procedures.  For example:
18998 @smallexample
18999   gnatbind -n int1.ali int2.ali -Lsal1
19000 @end smallexample
19001
19002 @item
19003 Compile the binder generated file:
19004 @smallexample
19005   gcc -c b~int2.adb
19006 @end smallexample
19007
19008 @item
19009 Link the dynamic library with all the necessary object files,
19010 indicating to the linker the names of the @code{init} (and possibly
19011 @code{final}) procedures for automatic initialization (and finalization).
19012 The built library should be placed in a directory different from
19013 the object directory.
19014
19015 @item
19016 Copy the @code{ALI} files of the interface to the library directory,
19017 add in this copy an indication that it is an interface to a SAL
19018 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
19019 with letter ``P'') and make the modified copy of the @file{ALI} file
19020 read-only.
19021 @end itemize
19022
19023 @noindent
19024 Using SALs is not different from using other libraries
19025 (see @ref{Using a library}).
19026
19027 @node Creating a Stand-alone Library to be used in a non-Ada context
19028 @subsection Creating a Stand-alone Library to be used in a non-Ada context
19029
19030 @noindent
19031 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
19032 a non-Ada context.
19033
19034 The only extra step required is to ensure that library interface subprograms
19035 are compatible with the main program, by means of @code{pragma Export}
19036 or @code{pragma Convention}.
19037
19038 Here is an example of simple library interface for use with C main program:
19039
19040 @smallexample @c ada
19041 package Interface is
19042
19043    procedure Do_Something;
19044    pragma Export (C, Do_Something, "do_something");
19045
19046    procedure Do_Something_Else;
19047    pragma Export (C, Do_Something_Else, "do_something_else");
19048
19049 end Interface;
19050 @end smallexample
19051
19052 @noindent
19053 On the foreign language side, you must provide a ``foreign'' view of the
19054 library interface; remember that it should contain elaboration routines in
19055 addition to interface subprograms.
19056
19057 The example below shows the content of @code{mylib_interface.h} (note
19058 that there is no rule for the naming of this file, any name can be used)
19059 @smallexample
19060 /* the library elaboration procedure */
19061 extern void mylibinit (void);
19062
19063 /* the library finalization procedure */
19064 extern void mylibfinal (void);
19065
19066 /* the interface exported by the library */
19067 extern void do_something (void);
19068 extern void do_something_else (void);
19069 @end smallexample
19070
19071 @noindent
19072 Libraries built as explained above can be used from any program, provided
19073 that the elaboration procedures (named @code{mylibinit} in the previous
19074 example) are called before the library services are used. Any number of
19075 libraries can be used simultaneously, as long as the elaboration
19076 procedure of each library is called.
19077
19078 Below is an example of a C program that uses the @code{mylib} library.
19079
19080 @smallexample
19081 #include "mylib_interface.h"
19082
19083 int
19084 main (void)
19085 @{
19086    /* First, elaborate the library before using it */
19087    mylibinit ();
19088
19089    /* Main program, using the library exported entities */
19090    do_something ();
19091    do_something_else ();
19092
19093    /* Library finalization at the end of the program */
19094    mylibfinal ();
19095    return 0;
19096 @}
19097 @end smallexample
19098
19099 @noindent
19100 Note that invoking any library finalization procedure generated by
19101 @code{gnatbind} shuts down the Ada run-time environment.
19102 Consequently, the
19103 finalization of all Ada libraries must be performed at the end of the program.
19104 No call to these libraries or to the Ada run-time library should be made
19105 after the finalization phase.
19106
19107 @node Restrictions in Stand-alone Libraries
19108 @subsection Restrictions in Stand-alone Libraries
19109
19110 @noindent
19111 The pragmas listed below should be used with caution inside libraries,
19112 as they can create incompatibilities with other Ada libraries:
19113 @itemize @bullet
19114 @item pragma @code{Locking_Policy}
19115 @item pragma @code{Queuing_Policy}
19116 @item pragma @code{Task_Dispatching_Policy}
19117 @item pragma @code{Unreserve_All_Interrupts}
19118 @end itemize
19119
19120 @noindent
19121 When using a library that contains such pragmas, the user must make sure
19122 that all libraries use the same pragmas with the same values. Otherwise,
19123 @code{Program_Error} will
19124 be raised during the elaboration of the conflicting
19125 libraries. The usage of these pragmas and its consequences for the user
19126 should therefore be well documented.
19127
19128 Similarly, the traceback in the exception occurrence mechanism should be
19129 enabled or disabled in a consistent manner across all libraries.
19130 Otherwise, Program_Error will be raised during the elaboration of the
19131 conflicting libraries.
19132
19133 If the @code{Version} or @code{Body_Version}
19134 attributes are used inside a library, then you need to
19135 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
19136 libraries, so that version identifiers can be properly computed.
19137 In practice these attributes are rarely used, so this is unlikely
19138 to be a consideration.
19139
19140 @node  Rebuilding the GNAT Run-Time Library
19141 @section Rebuilding the GNAT Run-Time Library
19142 @cindex GNAT Run-Time Library, rebuilding
19143 @cindex Building the GNAT Run-Time Library
19144 @cindex Rebuilding the GNAT Run-Time Library
19145 @cindex Run-Time Library, rebuilding
19146
19147 @noindent
19148 It may be useful to recompile the GNAT library in various contexts, the
19149 most important one being the use of partition-wide configuration pragmas
19150 such as @code{Normalize_Scalars}. A special Makefile called
19151 @code{Makefile.adalib} is provided to that effect and can be found in
19152 the directory containing the GNAT library. The location of this
19153 directory depends on the way the GNAT environment has been installed and can
19154 be determined by means of the command:
19155
19156 @smallexample
19157 $ gnatls -v
19158 @end smallexample
19159
19160 @noindent
19161 The last entry in the object search path usually contains the
19162 gnat library. This Makefile contains its own documentation and in
19163 particular the set of instructions needed to rebuild a new library and
19164 to use it.
19165
19166 @node Using the GNU make Utility
19167 @chapter Using the GNU @code{make} Utility
19168 @findex make
19169
19170 @noindent
19171 This chapter offers some examples of makefiles that solve specific
19172 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
19173 make, make, GNU @code{make}}), nor does it try to replace the
19174 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
19175
19176 All the examples in this section are specific to the GNU version of
19177 make. Although @command{make} is a standard utility, and the basic language
19178 is the same, these examples use some advanced features found only in
19179 @code{GNU make}.
19180
19181 @menu
19182 * Using gnatmake in a Makefile::
19183 * Automatically Creating a List of Directories::
19184 * Generating the Command Line Switches::
19185 * Overcoming Command Line Length Limits::
19186 @end menu
19187
19188 @node Using gnatmake in a Makefile
19189 @section Using gnatmake in a Makefile
19190 @findex makefile
19191 @cindex GNU make
19192
19193 @noindent
19194 Complex project organizations can be handled in a very powerful way by
19195 using GNU make combined with gnatmake. For instance, here is a Makefile
19196 which allows you to build each subsystem of a big project into a separate
19197 shared library. Such a makefile allows you to significantly reduce the link
19198 time of very big applications while maintaining full coherence at
19199 each step of the build process.
19200
19201 The list of dependencies are handled automatically by
19202 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
19203 the appropriate directories.
19204
19205 Note that you should also read the example on how to automatically
19206 create the list of directories
19207 (@pxref{Automatically Creating a List of Directories})
19208 which might help you in case your project has a lot of subdirectories.
19209
19210 @smallexample
19211 @iftex
19212 @leftskip=0cm
19213 @font@heightrm=cmr8
19214 @heightrm
19215 @end iftex
19216 ## This Makefile is intended to be used with the following directory
19217 ## configuration:
19218 ##  - The sources are split into a series of csc (computer software components)
19219 ##    Each of these csc is put in its own directory.
19220 ##    Their name are referenced by the directory names.
19221 ##    They will be compiled into shared library (although this would also work
19222 ##    with static libraries
19223 ##  - The main program (and possibly other packages that do not belong to any
19224 ##    csc is put in the top level directory (where the Makefile is).
19225 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
19226 ##                    \_ second_csc (sources) __ lib (will contain the library)
19227 ##                    \_ @dots{}
19228 ## Although this Makefile is build for shared library, it is easy to modify
19229 ## to build partial link objects instead (modify the lines with -shared and
19230 ## gnatlink below)
19231 ##
19232 ## With this makefile, you can change any file in the system or add any new
19233 ## file, and everything will be recompiled correctly (only the relevant shared
19234 ## objects will be recompiled, and the main program will be re-linked).
19235
19236 # The list of computer software component for your project. This might be
19237 # generated automatically.
19238 CSC_LIST=aa bb cc
19239
19240 # Name of the main program (no extension)
19241 MAIN=main
19242
19243 # If we need to build objects with -fPIC, uncomment the following line
19244 #NEED_FPIC=-fPIC
19245
19246 # The following variable should give the directory containing libgnat.so
19247 # You can get this directory through 'gnatls -v'. This is usually the last
19248 # directory in the Object_Path.
19249 GLIB=@dots{}
19250
19251 # The directories for the libraries
19252 # (This macro expands the list of CSC to the list of shared libraries, you
19253 # could simply use the expanded form:
19254 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
19255 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
19256
19257 $@{MAIN@}: objects $@{LIB_DIR@}
19258     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
19259     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
19260
19261 objects::
19262     # recompile the sources
19263     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
19264
19265 # Note: In a future version of GNAT, the following commands will be simplified
19266 # by a new tool, gnatmlib
19267 $@{LIB_DIR@}:
19268     mkdir -p $@{dir $@@ @}
19269     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
19270     cd $@{dir $@@ @} && cp -f ../*.ali .
19271
19272 # The dependencies for the modules
19273 # Note that we have to force the expansion of *.o, since in some cases
19274 # make won't be able to do it itself.
19275 aa/lib/libaa.so: $@{wildcard aa/*.o@}
19276 bb/lib/libbb.so: $@{wildcard bb/*.o@}
19277 cc/lib/libcc.so: $@{wildcard cc/*.o@}
19278
19279 # Make sure all of the shared libraries are in the path before starting the
19280 # program
19281 run::
19282     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
19283
19284 clean::
19285     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
19286     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
19287     $@{RM@} $@{CSC_LIST:%=%/*.o@}
19288     $@{RM@} *.o *.ali $@{MAIN@}
19289 @end smallexample
19290
19291 @node Automatically Creating a List of Directories
19292 @section Automatically Creating a List of Directories
19293
19294 @noindent
19295 In most makefiles, you will have to specify a list of directories, and
19296 store it in a variable. For small projects, it is often easier to
19297 specify each of them by hand, since you then have full control over what
19298 is the proper order for these directories, which ones should be
19299 included.
19300
19301 However, in larger projects, which might involve hundreds of
19302 subdirectories, it might be more convenient to generate this list
19303 automatically.
19304
19305 The example below presents two methods. The first one, although less
19306 general, gives you more control over the list. It involves wildcard
19307 characters, that are automatically expanded by @command{make}. Its
19308 shortcoming is that you need to explicitly specify some of the
19309 organization of your project, such as for instance the directory tree
19310 depth, whether some directories are found in a separate tree, @enddots{}
19311
19312 The second method is the most general one. It requires an external
19313 program, called @command{find}, which is standard on all Unix systems. All
19314 the directories found under a given root directory will be added to the
19315 list.
19316
19317 @smallexample
19318 @iftex
19319 @leftskip=0cm
19320 @font@heightrm=cmr8
19321 @heightrm
19322 @end iftex
19323 # The examples below are based on the following directory hierarchy:
19324 # All the directories can contain any number of files
19325 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
19326 #                       ->  ab
19327 #                       ->  ac
19328 #                ->  b  ->  ba  ->  baa
19329 #                       ->  bb
19330 #                       ->  bc
19331 # This Makefile creates a variable called DIRS, that can be reused any time
19332 # you need this list (see the other examples in this section)
19333
19334 # The root of your project's directory hierarchy
19335 ROOT_DIRECTORY=.
19336
19337 ####
19338 # First method: specify explicitly the list of directories
19339 # This allows you to specify any subset of all the directories you need.
19340 ####
19341
19342 DIRS := a/aa/ a/ab/ b/ba/
19343
19344 ####
19345 # Second method: use wildcards
19346 # Note that the argument(s) to wildcard below should end with a '/'.
19347 # Since wildcards also return file names, we have to filter them out
19348 # to avoid duplicate directory names.
19349 # We thus use make's @code{dir} and @code{sort} functions.
19350 # It sets DIRs to the following value (note that the directories aaa and baa
19351 # are not given, unless you change the arguments to wildcard).
19352 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
19353 ####
19354
19355 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
19356                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
19357
19358 ####
19359 # Third method: use an external program
19360 # This command is much faster if run on local disks, avoiding NFS slowdowns.
19361 # This is the most complete command: it sets DIRs to the following value:
19362 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
19363 ####
19364
19365 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
19366
19367 @end smallexample
19368
19369 @node Generating the Command Line Switches
19370 @section Generating the Command Line Switches
19371
19372 @noindent
19373 Once you have created the list of directories as explained in the
19374 previous section (@pxref{Automatically Creating a List of Directories}),
19375 you can easily generate the command line arguments to pass to gnatmake.
19376
19377 For the sake of completeness, this example assumes that the source path
19378 is not the same as the object path, and that you have two separate lists
19379 of directories.
19380
19381 @smallexample
19382 # see "Automatically creating a list of directories" to create
19383 # these variables
19384 SOURCE_DIRS=
19385 OBJECT_DIRS=
19386
19387 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
19388 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
19389
19390 all:
19391         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
19392 @end smallexample
19393
19394 @node Overcoming Command Line Length Limits
19395 @section Overcoming Command Line Length Limits
19396
19397 @noindent
19398 One problem that might be encountered on big projects is that many
19399 operating systems limit the length of the command line. It is thus hard to give
19400 gnatmake the list of source and object directories.
19401
19402 This example shows how you can set up environment variables, which will
19403 make @command{gnatmake} behave exactly as if the directories had been
19404 specified on the command line, but have a much higher length limit (or
19405 even none on most systems).
19406
19407 It assumes that you have created a list of directories in your Makefile,
19408 using one of the methods presented in
19409 @ref{Automatically Creating a List of Directories}.
19410 For the sake of completeness, we assume that the object
19411 path (where the ALI files are found) is different from the sources patch.
19412
19413 Note a small trick in the Makefile below: for efficiency reasons, we
19414 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
19415 expanded immediately by @code{make}. This way we overcome the standard
19416 make behavior which is to expand the variables only when they are
19417 actually used.
19418
19419 On Windows, if you are using the standard Windows command shell, you must
19420 replace colons with semicolons in the assignments to these variables.
19421
19422 @smallexample
19423 @iftex
19424 @leftskip=0cm
19425 @font@heightrm=cmr8
19426 @heightrm
19427 @end iftex
19428 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
19429 # This is the same thing as putting the -I arguments on the command line.
19430 # (the equivalent of using -aI on the command line would be to define
19431 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
19432 # You can of course have different values for these variables.
19433 #
19434 # Note also that we need to keep the previous values of these variables, since
19435 # they might have been set before running 'make' to specify where the GNAT
19436 # library is installed.
19437
19438 # see "Automatically creating a list of directories" to create these
19439 # variables
19440 SOURCE_DIRS=
19441 OBJECT_DIRS=
19442
19443 empty:=
19444 space:=$@{empty@} $@{empty@}
19445 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
19446 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
19447 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
19448 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
19449 export ADA_INCLUDE_PATH
19450 export ADA_OBJECT_PATH
19451
19452 all:
19453         gnatmake main_unit
19454 @end smallexample
19455 @end ifclear
19456
19457 @node Memory Management Issues
19458 @chapter Memory Management Issues
19459
19460 @noindent
19461 This chapter describes some useful memory pools provided in the GNAT library
19462 and in particular the GNAT Debug Pool facility, which can be used to detect
19463 incorrect uses of access values (including ``dangling references'').
19464 @ifclear vms
19465 It also describes the @command{gnatmem} tool, which can be used to track down
19466 ``memory leaks''.
19467 @end ifclear
19468
19469 @menu
19470 * Some Useful Memory Pools::
19471 * The GNAT Debug Pool Facility::
19472 @ifclear vms
19473 * The gnatmem Tool::
19474 @end ifclear
19475 @end menu
19476
19477 @node Some Useful Memory Pools
19478 @section Some Useful Memory Pools
19479 @findex Memory Pool
19480 @cindex storage, pool
19481
19482 @noindent
19483 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
19484 storage pool. Allocations use the standard system call @code{malloc} while
19485 deallocations use the standard system call @code{free}. No reclamation is
19486 performed when the pool goes out of scope. For performance reasons, the
19487 standard default Ada allocators/deallocators do not use any explicit storage
19488 pools but if they did, they could use this storage pool without any change in
19489 behavior. That is why this storage pool is used  when the user
19490 manages to make the default implicit allocator explicit as in this example:
19491 @smallexample @c ada
19492    type T1 is access Something;
19493     -- no Storage pool is defined for T2
19494    type T2 is access Something_Else;
19495    for T2'Storage_Pool use T1'Storage_Pool;
19496    -- the above is equivalent to
19497    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
19498 @end smallexample
19499
19500 @noindent
19501 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
19502 pool. The allocation strategy is similar to @code{Pool_Local}'s
19503 except that the all
19504 storage allocated with this pool is reclaimed when the pool object goes out of
19505 scope. This pool provides a explicit mechanism similar to the implicit one
19506 provided by several Ada 83 compilers for allocations performed through a local
19507 access type and whose purpose was to reclaim memory when exiting the
19508 scope of a given local access. As an example, the following program does not
19509 leak memory even though it does not perform explicit deallocation:
19510
19511 @smallexample @c ada
19512 with System.Pool_Local;
19513 procedure Pooloc1 is
19514    procedure Internal is
19515       type A is access Integer;
19516       X : System.Pool_Local.Unbounded_Reclaim_Pool;
19517       for A'Storage_Pool use X;
19518       v : A;
19519    begin
19520       for I in  1 .. 50 loop
19521          v := new Integer;
19522       end loop;
19523    end Internal;
19524 begin
19525    for I in  1 .. 100 loop
19526       Internal;
19527    end loop;
19528 end Pooloc1;
19529 @end smallexample
19530
19531 @noindent
19532 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
19533 @code{Storage_Size} is specified for an access type.
19534 The whole storage for the pool is
19535 allocated at once, usually on the stack at the point where the access type is
19536 elaborated. It is automatically reclaimed when exiting the scope where the
19537 access type is defined. This package is not intended to be used directly by the
19538 user and it is implicitly used for each such declaration:
19539
19540 @smallexample @c ada
19541    type T1 is access Something;
19542    for T1'Storage_Size use 10_000;
19543 @end smallexample
19544
19545 @node The GNAT Debug Pool Facility
19546 @section The GNAT Debug Pool Facility
19547 @findex Debug Pool
19548 @cindex storage, pool, memory corruption
19549
19550 @noindent
19551 The use of unchecked deallocation and unchecked conversion can easily
19552 lead to incorrect memory references. The problems generated by such
19553 references are usually difficult to tackle because the symptoms can be
19554 very remote from the origin of the problem. In such cases, it is
19555 very helpful to detect the problem as early as possible. This is the
19556 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
19557
19558 In order to use the GNAT specific debugging pool, the user must
19559 associate a debug pool object with each of the access types that may be
19560 related to suspected memory problems. See Ada Reference Manual 13.11.
19561 @smallexample @c ada
19562 type Ptr is access Some_Type;
19563 Pool : GNAT.Debug_Pools.Debug_Pool;
19564 for Ptr'Storage_Pool use Pool;
19565 @end smallexample
19566
19567 @noindent
19568 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
19569 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
19570 allow the user to redefine allocation and deallocation strategies. They
19571 also provide a checkpoint for each dereference, through the use of
19572 the primitive operation @code{Dereference} which is implicitly called at
19573 each dereference of an access value.
19574
19575 Once an access type has been associated with a debug pool, operations on
19576 values of the type may raise four distinct exceptions,
19577 which correspond to four potential kinds of memory corruption:
19578 @itemize @bullet
19579 @item
19580 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
19581 @item
19582 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
19583 @item
19584 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
19585 @item
19586 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
19587 @end itemize
19588
19589 @noindent
19590 For types associated with a Debug_Pool, dynamic allocation is performed using
19591 the standard GNAT allocation routine. References to all allocated chunks of
19592 memory are kept in an internal dictionary. Several deallocation strategies are
19593 provided, whereupon the user can choose to release the memory to the system,
19594 keep it allocated for further invalid access checks, or fill it with an easily
19595 recognizable pattern for debug sessions. The memory pattern is the old IBM
19596 hexadecimal convention: @code{16#DEADBEEF#}.
19597
19598 See the documentation in the file g-debpoo.ads for more information on the
19599 various strategies.
19600
19601 Upon each dereference, a check is made that the access value denotes a
19602 properly allocated memory location. Here is a complete example of use of
19603 @code{Debug_Pools}, that includes typical instances of  memory corruption:
19604 @smallexample @c ada
19605 @iftex
19606 @leftskip=0cm
19607 @end iftex
19608 with Gnat.Io; use Gnat.Io;
19609 with Unchecked_Deallocation;
19610 with Unchecked_Conversion;
19611 with GNAT.Debug_Pools;
19612 with System.Storage_Elements;
19613 with Ada.Exceptions; use Ada.Exceptions;
19614 procedure Debug_Pool_Test is
19615
19616    type T is access Integer;
19617    type U is access all T;
19618
19619    P : GNAT.Debug_Pools.Debug_Pool;
19620    for T'Storage_Pool use P;
19621
19622    procedure Free is new Unchecked_Deallocation (Integer, T);
19623    function UC is new Unchecked_Conversion (U, T);
19624    A, B : aliased T;
19625
19626    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
19627
19628 begin
19629    Info (P);
19630    A := new Integer;
19631    B := new Integer;
19632    B := A;
19633    Info (P);
19634    Free (A);
19635    begin
19636       Put_Line (Integer'Image(B.all));
19637    exception
19638       when E : others => Put_Line ("raised: " & Exception_Name (E));
19639    end;
19640    begin
19641       Free (B);
19642    exception
19643       when E : others => Put_Line ("raised: " & Exception_Name (E));
19644    end;
19645    B := UC(A'Access);
19646    begin
19647       Put_Line (Integer'Image(B.all));
19648    exception
19649       when E : others => Put_Line ("raised: " & Exception_Name (E));
19650    end;
19651    begin
19652       Free (B);
19653    exception
19654       when E : others => Put_Line ("raised: " & Exception_Name (E));
19655    end;
19656    Info (P);
19657 end Debug_Pool_Test;
19658 @end smallexample
19659
19660 @noindent
19661 The debug pool mechanism provides the following precise diagnostics on the
19662 execution of this erroneous program:
19663 @smallexample
19664 Debug Pool info:
19665   Total allocated bytes :  0
19666   Total deallocated bytes :  0
19667   Current Water Mark:  0
19668   High Water Mark:  0
19669
19670 Debug Pool info:
19671   Total allocated bytes :  8
19672   Total deallocated bytes :  0
19673   Current Water Mark:  8
19674   High Water Mark:  8
19675
19676 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
19677 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
19678 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
19679 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
19680 Debug Pool info:
19681   Total allocated bytes :  8
19682   Total deallocated bytes :  4
19683   Current Water Mark:  4
19684   High Water Mark:  8
19685 @end smallexample
19686
19687 @ifclear vms
19688 @node The gnatmem Tool
19689 @section The @command{gnatmem} Tool
19690 @findex gnatmem
19691
19692 @noindent
19693 The @code{gnatmem} utility monitors dynamic allocation and
19694 deallocation activity in a program, and displays information about
19695 incorrect deallocations and possible sources of memory leaks.
19696 It provides three type of information:
19697 @itemize @bullet
19698 @item
19699 General information concerning memory management, such as the total
19700 number of allocations and deallocations, the amount of allocated
19701 memory and the high water mark, i.e.@: the largest amount of allocated
19702 memory in the course of program execution.
19703
19704 @item
19705 Backtraces for all incorrect deallocations, that is to say deallocations
19706 which do not correspond to a valid allocation.
19707
19708 @item
19709 Information on each allocation that is potentially the origin of a memory
19710 leak.
19711 @end itemize
19712
19713 @menu
19714 * Running gnatmem::
19715 * Switches for gnatmem::
19716 * Example of gnatmem Usage::
19717 @end menu
19718
19719 @node Running gnatmem
19720 @subsection Running @code{gnatmem}
19721
19722 @noindent
19723 @code{gnatmem} makes use of the output created by the special version of
19724 allocation and deallocation routines that record call information. This
19725 allows to obtain accurate dynamic memory usage history at a minimal cost to
19726 the execution speed. Note however, that @code{gnatmem} is not supported on
19727 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
19728 Solaris and Windows NT/2000/XP (x86).
19729
19730 @noindent
19731 The @code{gnatmem} command has the form
19732
19733 @smallexample
19734    $ gnatmem @ovar{switches} user_program
19735 @end smallexample
19736
19737 @noindent
19738 The program must have been linked with the instrumented version of the
19739 allocation and deallocation routines. This is done by linking with the
19740 @file{libgmem.a} library. For correct symbolic backtrace information,
19741 the user program should be compiled with debugging options
19742 (see @ref{Switches for gcc}). For example to build @file{my_program}:
19743
19744 @smallexample
19745 $ gnatmake -g my_program -largs -lgmem
19746 @end smallexample
19747
19748 @noindent
19749 As library @file{libgmem.a} contains an alternate body for package
19750 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
19751 when an executable is linked with library @file{libgmem.a}. It is then not
19752 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
19753
19754 @noindent
19755 When @file{my_program} is executed, the file @file{gmem.out} is produced.
19756 This file contains information about all allocations and deallocations
19757 performed by the program. It is produced by the instrumented allocations and
19758 deallocations routines and will be used by @code{gnatmem}.
19759
19760 In order to produce symbolic backtrace information for allocations and
19761 deallocations performed by the GNAT run-time library, you need to use a
19762 version of that library that has been compiled with the @option{-g} switch
19763 (see @ref{Rebuilding the GNAT Run-Time Library}).
19764
19765 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
19766 examine. If the location of @file{gmem.out} file was not explicitly supplied by
19767 @option{-i} switch, gnatmem will assume that this file can be found in the
19768 current directory. For example, after you have executed @file{my_program},
19769 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
19770
19771 @smallexample
19772 $ gnatmem my_program
19773 @end smallexample
19774
19775 @noindent
19776 This will produce the output with the following format:
19777
19778 *************** debut cc
19779 @smallexample
19780 $ gnatmem my_program
19781
19782 Global information
19783 ------------------
19784    Total number of allocations        :  45
19785    Total number of deallocations      :   6
19786    Final Water Mark (non freed mem)   :  11.29 Kilobytes
19787    High Water Mark                    :  11.40 Kilobytes
19788
19789 .
19790 .
19791 .
19792 Allocation Root # 2
19793 -------------------
19794  Number of non freed allocations    :  11
19795  Final Water Mark (non freed mem)   :   1.16 Kilobytes
19796  High Water Mark                    :   1.27 Kilobytes
19797  Backtrace                          :
19798    my_program.adb:23 my_program.alloc
19799 .
19800 .
19801 .
19802 @end smallexample
19803
19804 The first block of output gives general information. In this case, the
19805 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
19806 Unchecked_Deallocation routine occurred.
19807
19808 @noindent
19809 Subsequent paragraphs display  information on all allocation roots.
19810 An allocation root is a specific point in the execution of the program
19811 that generates some dynamic allocation, such as a ``@code{@b{new}}''
19812 construct. This root is represented by an execution backtrace (or subprogram
19813 call stack). By default the backtrace depth for allocations roots is 1, so
19814 that a root corresponds exactly to a source location. The backtrace can
19815 be made deeper, to make the root more specific.
19816
19817 @node Switches for gnatmem
19818 @subsection Switches for @code{gnatmem}
19819
19820 @noindent
19821 @code{gnatmem} recognizes the following switches:
19822
19823 @table @option
19824
19825 @item -q
19826 @cindex @option{-q} (@code{gnatmem})
19827 Quiet. Gives the minimum output needed to identify the origin of the
19828 memory leaks. Omits statistical information.
19829
19830 @item @var{N}
19831 @cindex @var{N} (@code{gnatmem})
19832 N is an integer literal (usually between 1 and 10) which controls the
19833 depth of the backtraces defining allocation root. The default value for
19834 N is 1. The deeper the backtrace, the more precise the localization of
19835 the root. Note that the total number of roots can depend on this
19836 parameter. This parameter must be specified @emph{before} the name of the
19837 executable to be analyzed, to avoid ambiguity.
19838
19839 @item -b n
19840 @cindex @option{-b} (@code{gnatmem})
19841 This switch has the same effect as just depth parameter.
19842
19843 @item -i @var{file}
19844 @cindex @option{-i} (@code{gnatmem})
19845 Do the @code{gnatmem} processing starting from @file{file}, rather than
19846 @file{gmem.out} in the current directory.
19847
19848 @item -m n
19849 @cindex @option{-m} (@code{gnatmem})
19850 This switch causes @code{gnatmem} to mask the allocation roots that have less
19851 than n leaks. The default value is 1. Specifying the value of 0 will allow to
19852 examine even the roots that didn't result in leaks.
19853
19854 @item -s order
19855 @cindex @option{-s} (@code{gnatmem})
19856 This switch causes @code{gnatmem} to sort the allocation roots according to the
19857 specified order of sort criteria, each identified by a single letter. The
19858 currently supported criteria are @code{n, h, w} standing respectively for
19859 number of unfreed allocations, high watermark, and final watermark
19860 corresponding to a specific root. The default order is @code{nwh}.
19861
19862 @end table
19863
19864 @node Example of gnatmem Usage
19865 @subsection Example of @code{gnatmem} Usage
19866
19867 @noindent
19868 The following example shows the use of @code{gnatmem}
19869 on a simple memory-leaking program.
19870 Suppose that we have the following Ada program:
19871
19872 @smallexample @c ada
19873 @group
19874 @cartouche
19875 with Unchecked_Deallocation;
19876 procedure Test_Gm is
19877
19878    type T is array (1..1000) of Integer;
19879    type Ptr is access T;
19880    procedure Free is new Unchecked_Deallocation (T, Ptr);
19881    A : Ptr;
19882
19883    procedure My_Alloc is
19884    begin
19885       A := new T;
19886    end My_Alloc;
19887
19888    procedure My_DeAlloc is
19889       B : Ptr := A;
19890    begin
19891       Free (B);
19892    end My_DeAlloc;
19893
19894 begin
19895    My_Alloc;
19896    for I in 1 .. 5 loop
19897       for J in I .. 5 loop
19898          My_Alloc;
19899       end loop;
19900       My_Dealloc;
19901    end loop;
19902 end;
19903 @end cartouche
19904 @end group
19905 @end smallexample
19906
19907 @noindent
19908 The program needs to be compiled with debugging option and linked with
19909 @code{gmem} library:
19910
19911 @smallexample
19912 $ gnatmake -g test_gm -largs -lgmem
19913 @end smallexample
19914
19915 @noindent
19916 Then we execute the program as usual:
19917
19918 @smallexample
19919 $ test_gm
19920 @end smallexample
19921
19922 @noindent
19923 Then @code{gnatmem} is invoked simply with
19924 @smallexample
19925 $ gnatmem test_gm
19926 @end smallexample
19927
19928 @noindent
19929 which produces the following output (result may vary on different platforms):
19930
19931 @smallexample
19932 Global information
19933 ------------------
19934    Total number of allocations        :  18
19935    Total number of deallocations      :   5
19936    Final Water Mark (non freed mem)   :  53.00 Kilobytes
19937    High Water Mark                    :  56.90 Kilobytes
19938
19939 Allocation Root # 1
19940 -------------------
19941  Number of non freed allocations    :  11
19942  Final Water Mark (non freed mem)   :  42.97 Kilobytes
19943  High Water Mark                    :  46.88 Kilobytes
19944  Backtrace                          :
19945    test_gm.adb:11 test_gm.my_alloc
19946
19947 Allocation Root # 2
19948 -------------------
19949  Number of non freed allocations    :   1
19950  Final Water Mark (non freed mem)   :  10.02 Kilobytes
19951  High Water Mark                    :  10.02 Kilobytes
19952  Backtrace                          :
19953    s-secsta.adb:81 system.secondary_stack.ss_init
19954
19955 Allocation Root # 3
19956 -------------------
19957  Number of non freed allocations    :   1
19958  Final Water Mark (non freed mem)   :  12 Bytes
19959  High Water Mark                    :  12 Bytes
19960  Backtrace                          :
19961    s-secsta.adb:181 system.secondary_stack.ss_init
19962 @end smallexample
19963
19964 @noindent
19965 Note that the GNAT run time contains itself a certain number of
19966 allocations that have no  corresponding deallocation,
19967 as shown here for root #2 and root
19968 #3. This is a normal behavior when the number of non-freed allocations
19969 is one, it allocates dynamic data structures that the run time needs for
19970 the complete lifetime of the program. Note also that there is only one
19971 allocation root in the user program with a single line back trace:
19972 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
19973 program shows that 'My_Alloc' is called at 2 different points in the
19974 source (line 21 and line 24). If those two allocation roots need to be
19975 distinguished, the backtrace depth parameter can be used:
19976
19977 @smallexample
19978 $ gnatmem 3 test_gm
19979 @end smallexample
19980
19981 @noindent
19982 which will give the following output:
19983
19984 @smallexample
19985 Global information
19986 ------------------
19987    Total number of allocations        :  18
19988    Total number of deallocations      :   5
19989    Final Water Mark (non freed mem)   :  53.00 Kilobytes
19990    High Water Mark                    :  56.90 Kilobytes
19991
19992 Allocation Root # 1
19993 -------------------
19994  Number of non freed allocations    :  10
19995  Final Water Mark (non freed mem)   :  39.06 Kilobytes
19996  High Water Mark                    :  42.97 Kilobytes
19997  Backtrace                          :
19998    test_gm.adb:11 test_gm.my_alloc
19999    test_gm.adb:24 test_gm
20000    b_test_gm.c:52 main
20001
20002 Allocation Root # 2
20003 -------------------
20004  Number of non freed allocations    :   1
20005  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20006  High Water Mark                    :  10.02 Kilobytes
20007  Backtrace                          :
20008    s-secsta.adb:81  system.secondary_stack.ss_init
20009    s-secsta.adb:283 <system__secondary_stack___elabb>
20010    b_test_gm.c:33   adainit
20011
20012 Allocation Root # 3
20013 -------------------
20014  Number of non freed allocations    :   1
20015  Final Water Mark (non freed mem)   :   3.91 Kilobytes
20016  High Water Mark                    :   3.91 Kilobytes
20017  Backtrace                          :
20018    test_gm.adb:11 test_gm.my_alloc
20019    test_gm.adb:21 test_gm
20020    b_test_gm.c:52 main
20021
20022 Allocation Root # 4
20023 -------------------
20024  Number of non freed allocations    :   1
20025  Final Water Mark (non freed mem)   :  12 Bytes
20026  High Water Mark                    :  12 Bytes
20027  Backtrace                          :
20028    s-secsta.adb:181 system.secondary_stack.ss_init
20029    s-secsta.adb:283 <system__secondary_stack___elabb>
20030    b_test_gm.c:33   adainit
20031 @end smallexample
20032
20033 @noindent
20034 The allocation root #1 of the first example has been split in 2 roots #1
20035 and #3 thanks to the more precise associated backtrace.
20036
20037 @end ifclear
20038
20039 @node Stack Related Facilities
20040 @chapter Stack Related Facilities
20041
20042 @noindent
20043 This chapter describes some useful tools associated with stack
20044 checking and analysis. In
20045 particular, it deals with dynamic and static stack usage measurements.
20046
20047 @menu
20048 * Stack Overflow Checking::
20049 * Static Stack Usage Analysis::
20050 * Dynamic Stack Usage Analysis::
20051 @end menu
20052
20053 @node Stack Overflow Checking
20054 @section Stack Overflow Checking
20055 @cindex Stack Overflow Checking
20056 @cindex -fstack-check
20057
20058 @noindent
20059 For most operating systems, @command{gcc} does not perform stack overflow
20060 checking by default. This means that if the main environment task or
20061 some other task exceeds the available stack space, then unpredictable
20062 behavior will occur. Most native systems offer some level of protection by
20063 adding a guard page at the end of each task stack. This mechanism is usually
20064 not enough for dealing properly with stack overflow situations because
20065 a large local variable could ``jump'' above the guard page.
20066 Furthermore, when the
20067 guard page is hit, there may not be any space left on the stack for executing
20068 the exception propagation code. Enabling stack checking avoids
20069 such situations.
20070
20071 To activate stack checking, compile all units with the gcc option
20072 @option{-fstack-check}. For example:
20073
20074 @smallexample
20075 gcc -c -fstack-check package1.adb
20076 @end smallexample
20077
20078 @noindent
20079 Units compiled with this option will generate extra instructions to check
20080 that any use of the stack (for procedure calls or for declaring local
20081 variables in declare blocks) does not exceed the available stack space.
20082 If the space is exceeded, then a @code{Storage_Error} exception is raised.
20083
20084 For declared tasks, the stack size is controlled by the size
20085 given in an applicable @code{Storage_Size} pragma or by the value specified
20086 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
20087 the default size as defined in the GNAT runtime otherwise.
20088
20089 For the environment task, the stack size depends on
20090 system defaults and is unknown to the compiler. Stack checking
20091 may still work correctly if a fixed
20092 size stack is allocated, but this cannot be guaranteed.
20093 @ifclear vms
20094 To ensure that a clean exception is signalled for stack
20095 overflow, set the environment variable
20096 @env{GNAT_STACK_LIMIT} to indicate the maximum
20097 stack area that can be used, as in:
20098 @cindex GNAT_STACK_LIMIT
20099
20100 @smallexample
20101 SET GNAT_STACK_LIMIT 1600
20102 @end smallexample
20103
20104 @noindent
20105 The limit is given in kilobytes, so the above declaration would
20106 set the stack limit of the environment task to 1.6 megabytes.
20107 Note that the only purpose of this usage is to limit the amount
20108 of stack used by the environment task. If it is necessary to
20109 increase the amount of stack for the environment task, then this
20110 is an operating systems issue, and must be addressed with the
20111 appropriate operating systems commands.
20112 @end ifclear
20113 @ifset vms
20114 To have a fixed size stack in the environment task, the stack must be put
20115 in the P0 address space and its size specified.  Use these switches to
20116 create a p0 image:
20117
20118 @smallexample
20119 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
20120 @end smallexample
20121
20122 @noindent
20123 The quotes are required to keep case.  The number after @samp{STACK=} is the
20124 size of the environmental task stack in pagelets (512 bytes).  In this example
20125 the stack size is about 2 megabytes.
20126
20127 @noindent
20128 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
20129 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
20130 more details about the @option{/p0image} qualifier and the @option{stack}
20131 option.
20132 @end ifset
20133
20134 @node Static Stack Usage Analysis
20135 @section Static Stack Usage Analysis
20136 @cindex Static Stack Usage Analysis
20137 @cindex -fstack-usage
20138
20139 @noindent
20140 A unit compiled with @option{-fstack-usage} will generate an extra file
20141 that specifies
20142 the maximum amount of stack used, on a per-function basis.
20143 The file has the same
20144 basename as the target object file with a @file{.su} extension.
20145 Each line of this file is made up of three fields:
20146
20147 @itemize
20148 @item
20149 The name of the function.
20150 @item
20151 A number of bytes.
20152 @item
20153 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
20154 @end itemize
20155
20156 The second field corresponds to the size of the known part of the function
20157 frame.
20158
20159 The qualifier @code{static} means that the function frame size
20160 is purely static.
20161 It usually means that all local variables have a static size.
20162 In this case, the second field is a reliable measure of the function stack
20163 utilization.
20164
20165 The qualifier @code{dynamic} means that the function frame size is not static.
20166 It happens mainly when some local variables have a dynamic size. When this
20167 qualifier appears alone, the second field is not a reliable measure
20168 of the function stack analysis. When it is qualified with  @code{bounded}, it
20169 means that the second field is a reliable maximum of the function stack
20170 utilization.
20171
20172 @node Dynamic Stack Usage Analysis
20173 @section Dynamic Stack Usage Analysis
20174
20175 @noindent
20176 It is possible to measure the maximum amount of stack used by a task, by
20177 adding a switch to @command{gnatbind}, as:
20178
20179 @smallexample
20180 $ gnatbind -u0 file
20181 @end smallexample
20182
20183 @noindent
20184 With this option, at each task termination, its stack usage is  output on
20185 @file{stderr}.
20186 It is not always convenient to output the stack usage when the program
20187 is still running. Hence, it is possible to delay this output until program
20188 termination. for a given number of tasks specified as the argument of the
20189 @option{-u} option. For instance:
20190
20191 @smallexample
20192 $ gnatbind -u100 file
20193 @end smallexample
20194
20195 @noindent
20196 will buffer the stack usage information of the first 100 tasks to terminate and
20197 output this info at program termination. Results are displayed in four
20198 columns:
20199
20200 @noindent
20201 Index | Task Name | Stack Size | Actual Use [min - max]
20202
20203 @noindent
20204 where:
20205
20206 @table @emph
20207 @item Index
20208 is a number associated with each task.
20209
20210 @item Task Name
20211 is the name of the task analyzed.
20212
20213 @item Stack Size
20214 is the maximum size for the stack.
20215
20216 @item Actual Use
20217 is the measure done by the stack analyzer. In order to prevent overflow,
20218 the stack is not entirely analyzed, and it's not possible to know exactly how
20219 much has actually been used. The real amount of stack used is between the min
20220 and max values.
20221
20222 @end table
20223
20224 @noindent
20225 The environment task stack, e.g., the stack that contains the main unit, is
20226 only processed when the environment variable GNAT_STACK_LIMIT is set.
20227
20228
20229 @c *********************************
20230 @c *            GNATCHECK          *
20231 @c *********************************
20232 @node Verifying Properties Using gnatcheck
20233 @chapter Verifying Properties Using @command{gnatcheck}
20234 @findex gnatcheck
20235 @cindex @command{gnatcheck}
20236
20237 @noindent
20238 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
20239 of Ada source files according to a given set of semantic rules.
20240 @cindex ASIS
20241
20242 In order to check compliance with a given rule, @command{gnatcheck} has to
20243 semantically analyze the Ada sources.
20244 Therefore, checks can only be performed on
20245 legal Ada units. Moreover, when a unit depends semantically upon units located
20246 outside the current directory, the source search path has to be provided when
20247 calling @command{gnatcheck}, either through a specified project file or
20248 through @command{gnatcheck} switches as described below.
20249
20250 A number of rules are predefined in @command{gnatcheck} and are described
20251 later in this chapter.
20252 You can also add new rules, by modifying the @command{gnatcheck} code and
20253 rebuilding the tool. In order to add a simple rule making some local checks,
20254 a small amount of straightforward ASIS-based programming is usually needed.
20255
20256 Project support for @command{gnatcheck} is provided by the GNAT
20257 driver (see @ref{The GNAT Driver and Project Files}).
20258
20259 Invoking @command{gnatcheck} on the command line has the form:
20260
20261 @smallexample
20262 $ gnatcheck @ovar{switches}  @{@var{filename}@}
20263       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
20264       @r{[}-cargs @var{gcc_switches}@r{]} @r{[}-rules @var{rule_options}@r{]}
20265 @end smallexample
20266
20267 @noindent
20268 where
20269 @itemize @bullet
20270 @item
20271 @var{switches} specify the general tool options
20272
20273 @item
20274 Each @var{filename} is the name (including the extension) of a source
20275 file to process. ``Wildcards'' are allowed, and
20276 the file name may contain path information.
20277
20278 @item
20279 Each @var{arg_list_filename} is the name (including the extension) of a text
20280 file containing the names of the source files to process, separated by spaces
20281 or line breaks.
20282
20283 @item
20284 @var{gcc_switches} is a list of switches for
20285 @command{gcc}. They will be passed on to all compiler invocations made by
20286 @command{gnatcheck} to generate the ASIS trees. Here you can provide
20287 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
20288 and use the @option{-gnatec} switch to set the configuration file.
20289
20290 @item
20291 @var{rule_options} is a list of options for controlling a set of
20292 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
20293 @end itemize
20294
20295 @noindent
20296 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be supplied.
20297
20298 @menu
20299 * Format of the Report File::
20300 * General gnatcheck Switches::
20301 * gnatcheck Rule Options::
20302 * Adding the Results of Compiler Checks to gnatcheck Output::
20303 * Project-Wide Checks::
20304 * Predefined Rules::
20305 @end menu
20306
20307 @node Format of the Report File
20308 @section Format of the Report File
20309 @cindex Report file (for @code{gnatcheck})
20310
20311 @noindent
20312 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
20313 rule violations.
20314 It also creates, in the current
20315 directory, a text file named @file{^gnatcheck.out^GNATCHECK.OUT^} that
20316 contains the complete report of the last gnatcheck run. This report contains:
20317 @itemize @bullet
20318 @item a list of the Ada source files being checked,
20319 @item a list of enabled and disabled rules,
20320 @item a list of the diagnostic messages, ordered in three different ways
20321 and collected in three separate
20322 sections. Section 1 contains the raw list of diagnostic messages. It
20323 corresponds to the output going to @file{stdout}. Section 2 contains
20324 messages ordered by rules.
20325 Section 3 contains messages ordered by source files.
20326 @end itemize
20327
20328 @node General gnatcheck Switches
20329 @section General @command{gnatcheck} Switches
20330
20331 @noindent
20332 The following switches control the general @command{gnatcheck} behavior
20333
20334 @table @option
20335 @c !sort!
20336 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
20337 @item ^-a^/ALL^
20338 Process all units including those with read-only ALI files such as
20339 those from GNAT Run-Time library.
20340
20341 @ifclear vms
20342 @ignore
20343 @cindex @option{-d} (@command{gnatcheck})
20344 @item -d
20345 Debug mode
20346 @end ignore
20347
20348 @cindex @option{-dd} (@command{gnatcheck})
20349 @item -dd
20350 Progress indicator mode (for use in GPS)
20351 @end ifclear
20352
20353 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
20354 @item ^-h^/HELP^
20355 List the predefined and user-defined rules. For more details see
20356 @ref{Predefined Rules}.
20357
20358 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
20359 @item ^-l^/LOCS^
20360 Use full source locations references in the report file. For a construct from
20361 a generic instantiation a full source location is a chain from the location
20362 of this construct in the generic unit to the place where this unit is
20363 instantiated.
20364
20365 @cindex @option{^-m^/DIAGNOSIS_LIMIT^} (@command{gnatcheck})
20366 @item ^-m@i{nnn}^/DIAGNOSIS_LIMIT=@i{nnn}^
20367 Maximum number of diagnoses to be sent to Stdout, @i{nnn} from o@dots{}1000,
20368 the default value is 500. Zero means that there is no limitation on
20369 the number of diagnostic messages to be printed into Stdout.
20370
20371 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
20372 @item ^-q^/QUIET^
20373 Quiet mode. All the diagnoses about rule violations are placed in the
20374 @command{gnatcheck} report file only, without duplicating in @file{stdout}.
20375
20376 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
20377 @item ^-s^/SHORT^
20378 Short format of the report file (no version information, no list of applied
20379 rules, no list of checked sources is included)
20380
20381 @cindex @option{^-s1^/COMPILER_STYLE^} (@command{gnatcheck})
20382 @item ^-s1^/COMPILER_STYLE^
20383 Include the compiler-style section in the report file
20384
20385 @cindex @option{^-s2^/BY_RULES^} (@command{gnatcheck})
20386 @item ^-s2^/BY_RULES^
20387 Include the section containing diagnoses ordered by rules in the report file
20388
20389 @cindex @option{^-s3^/BY_FILES_BY_RULES^} (@command{gnatcheck})
20390 @item ^-s3^/BY_FILES_BY_RULES^
20391 Include the section containing diagnoses ordered by files and then by rules
20392 in the report file
20393
20394 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
20395 @item ^-v^/VERBOSE^
20396 Verbose mode; @command{gnatcheck} generates version information and then
20397 a trace of sources being processed.
20398
20399 @end table
20400
20401 @noindent
20402 Note that if any of the options @option{^-s1^/COMPILER_STYLE^},
20403 @option{^-s2^/BY_RULES^} or
20404 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
20405 then the  @command{gnatcheck} report file will only contain sections
20406 explicitly denoted by these options.
20407
20408 @node gnatcheck Rule Options
20409 @section @command{gnatcheck} Rule Options
20410
20411 @noindent
20412 The following options control the processing performed by
20413 @command{gnatcheck}.
20414
20415 @table @option
20416 @cindex @option{+ALL} (@command{gnatcheck})
20417 @item +ALL
20418 Turn all the rule checks ON.
20419
20420 @cindex @option{-ALL} (@command{gnatcheck})
20421 @item -ALL
20422 Turn all the rule checks OFF.
20423
20424 @cindex @option{+R} (@command{gnatcheck})
20425 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
20426 Turn on the check for a specified rule with the specified parameter, if any.
20427 @var{rule_id} must be the identifier of one of the currently implemented rules
20428 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
20429 are not case-sensitive. The @var{param} item must
20430 be a string representing a valid parameter(s) for the specified rule.
20431 If it contains any space characters then this string must be enclosed in
20432 quotation marks.
20433
20434 @cindex @option{-R} (@command{gnatcheck})
20435 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
20436 Turn off the check for a specified rule with the specified parameter, if any.
20437
20438 @cindex @option{-from} (@command{gnatcheck})
20439 @item -from=@var{rule_option_filename}
20440 Read the rule options from the text file @var{rule_option_filename}, referred as
20441 ``rule file'' below.
20442
20443 @end table
20444
20445 @noindent
20446 The default behavior is that all the rule checks are disabled.
20447
20448 A rule file is a text file containing a set of rule options.
20449 @cindex Rule file (for @code{gnatcheck})
20450 The file may contain empty lines and Ada-style comments (comment
20451 lines and end-of-line comments). The rule file has free format; that is,
20452 you do not have to start a new rule option on a new line.
20453
20454 A rule file may contain other @option{-from=@var{rule_option_filename}}
20455 options, each such option being replaced with the content of the
20456 corresponding rule file during the rule files processing. In case a
20457 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
20458 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
20459 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
20460 the processing of rule files is interrupted and a part of their content
20461 is ignored.
20462
20463
20464 @node Adding the Results of Compiler Checks to gnatcheck Output
20465 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
20466
20467 @noindent
20468 The @command{gnatcheck} tool can include in the generated diagnostic messages
20469 and in
20470 the report file the results of the checks performed by the compiler. Though
20471 disabled by default, this effect may be obtained by using @option{+R} with
20472 the following rule identifiers and parameters:
20473
20474 @table @option
20475 @item Restrictions
20476 To record restrictions violations (that are performed by the compiler if the
20477 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
20478 use the rule named
20479 @code{Restrictions} with the same parameters as pragma
20480 @code{Restrictions} or @code{Restriction_Warnings}.
20481
20482 @item Style_Checks
20483 To record compiler style checks(@pxref{Style Checking}), use the rule named
20484 @code{Style_Checks}. A parameter of this rule can be either @code{All_Checks},
20485 which enables all the standard style checks that corresponds to @option{-gnatyy}
20486 GNAT style check option, or a string that has exactly the same
20487 structure and semantics as the @code{string_LITERAL} parameter of GNAT pragma
20488 @code{Style_Checks} (for further information about this pragma,
20489 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}).
20490
20491 @item Warnings
20492 To record compiler warnings (@pxref{Warning Message Control}), use the rule
20493 named @code{Warnings} with a parameter that is a valid
20494 @i{static_string_expression} argument of GNAT pragma @code{Warnings}
20495 (for further information about this pragma, @pxref{Pragma Warnings,,,
20496 gnat_rm, GNAT Reference Manual}). Note, that in case of gnatcheck
20497 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
20498 all the specific warnings, but not suppresses the warning mode,
20499 and 'e' parameter, corresponding to @option{-gnatwe} that means
20500 "treat warnings as errors", does not have any effect.
20501
20502 @end table
20503
20504 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
20505 option with the corresponding restriction name as a parameter. @code{-R} is
20506 not available for @code{Style_Checks} and @code{Warnings} options, to disable
20507 warnings and style checks, use the corresponding warning and style options.
20508
20509 @node Project-Wide Checks
20510 @section Project-Wide Checks
20511 @cindex Project-wide checks (for @command{gnatcheck})
20512
20513 @noindent
20514 In order to perform checks on all units of a given project, you can use
20515 the GNAT driver along with the @option{-P} option:
20516 @smallexample
20517    gnat check -Pproj -rules -from=my_rules
20518 @end smallexample
20519
20520 @noindent
20521 If the project @code{proj} depends upon other projects, you can perform
20522 checks on the project closure using the @option{-U} option:
20523 @smallexample
20524    gnat check -Pproj -U -rules -from=my_rules
20525 @end smallexample
20526
20527 @noindent
20528 Finally, if not all the units are relevant to a particular main
20529 program in the project closure, you can perform checks for the set
20530 of units needed to create a given main program (unit closure) using
20531 the @option{-U} option followed by the name of the main unit:
20532 @smallexample
20533    gnat check -Pproj -U main -rules -from=my_rules
20534 @end smallexample
20535
20536
20537 @node Predefined Rules
20538 @section Predefined Rules
20539 @cindex Predefined rules (for @command{gnatcheck})
20540
20541 @ignore
20542 @c (Jan 2007) Since the global rules are still under development and are not
20543 @c documented, there is no point in explaining the difference between
20544 @c global and local rules
20545 @noindent
20546 A rule in @command{gnatcheck} is either local or global.
20547 A @emph{local rule} is a rule that applies to a well-defined section
20548 of a program and that can be checked by analyzing only this section.
20549 A @emph{global rule} requires analysis of some global properties of the
20550 whole program (mostly related to the program call graph).
20551 As of @value{NOW}, the implementation of global rules should be
20552 considered to be at a preliminary stage. You can use the
20553 @option{+GLOBAL} option to enable all the global rules, and the
20554 @option{-GLOBAL} rule option to disable all the global rules.
20555
20556 All the global rules in the list below are
20557 so indicated by marking them ``GLOBAL''.
20558 This +GLOBAL and -GLOBAL options are not
20559 included in the list of gnatcheck options above, because at the moment they
20560 are considered as a temporary debug options.
20561
20562 @command{gnatcheck} performs rule checks for generic
20563 instances only for global rules.  This limitation may be relaxed in a later
20564 release.
20565 @end ignore
20566
20567 @noindent
20568 The following subsections document the rules implemented in
20569 @command{gnatcheck}.
20570 The subsection title is the same as the rule identifier, which may be
20571 used as a parameter of the @option{+R} or @option{-R} options.
20572
20573
20574 @menu
20575 * Abstract_Type_Declarations::
20576 * Anonymous_Arrays::
20577 * Anonymous_Subtypes::
20578 * Blocks::
20579 * Boolean_Relational_Operators::
20580 @ignore
20581 * Ceiling_Violations::
20582 @end ignore
20583 * Controlled_Type_Declarations::
20584 * Declarations_In_Blocks::
20585 * Default_Parameters::
20586 * Discriminated_Records::
20587 * Enumeration_Ranges_In_CASE_Statements::
20588 * Exceptions_As_Control_Flow::
20589 * EXIT_Statements_With_No_Loop_Name::
20590 * Expanded_Loop_Exit_Names::
20591 * Explicit_Full_Discrete_Ranges::
20592 * Float_Equality_Checks::
20593 * Forbidden_Pragmas::
20594 * Function_Style_Procedures::
20595 * Generics_In_Subprograms::
20596 * GOTO_Statements::
20597 * Implicit_IN_Mode_Parameters::
20598 * Implicit_SMALL_For_Fixed_Point_Types::
20599 * Improperly_Located_Instantiations::
20600 * Improper_Returns::
20601 * Library_Level_Subprograms::
20602 * Local_Packages::
20603 @ignore
20604 * Improperly_Called_Protected_Entries::
20605 @end ignore
20606 * Metrics::
20607 * Misnamed_Identifiers::
20608 * Multiple_Entries_In_Protected_Definitions::
20609 * Name_Clashes::
20610 * Non_Qualified_Aggregates::
20611 * Non_Short_Circuit_Operators::
20612 * Non_SPARK_Attributes::
20613 * Non_Tagged_Derived_Types::
20614 * Non_Visible_Exceptions::
20615 * Numeric_Literals::
20616 * OTHERS_In_Aggregates::
20617 * OTHERS_In_CASE_Statements::
20618 * OTHERS_In_Exception_Handlers::
20619 * Outer_Loop_Exits::
20620 * Overloaded_Operators::
20621 * Overly_Nested_Control_Structures::
20622 * Parameters_Out_Of_Order::
20623 * Positional_Actuals_For_Defaulted_Generic_Parameters::
20624 * Positional_Actuals_For_Defaulted_Parameters::
20625 * Positional_Components::
20626 * Positional_Generic_Parameters::
20627 * Positional_Parameters::
20628 * Predefined_Numeric_Types::
20629 * Raising_External_Exceptions::
20630 * Raising_Predefined_Exceptions::
20631 * Separate_Numeric_Error_Handlers::
20632 @ignore
20633 * Recursion::
20634 * Side_Effect_Functions::
20635 @end ignore
20636 * Slices::
20637 * Unassigned_OUT_Parameters::
20638 * Uncommented_BEGIN_In_Package_Bodies::
20639 * Unconstrained_Array_Returns::
20640 * Universal_Ranges::
20641 * Unnamed_Blocks_And_Loops::
20642 @ignore
20643 * Unused_Subprograms::
20644 @end ignore
20645 * USE_PACKAGE_Clauses::
20646 * Volatile_Objects_Without_Address_Clauses::
20647 @end menu
20648
20649
20650 @node Abstract_Type_Declarations
20651 @subsection @code{Abstract_Type_Declarations}
20652 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
20653
20654 @noindent
20655 Flag all declarations of abstract types. For an abstract private
20656 type, both the private and full type declarations are flagged.
20657
20658 This rule has no parameters.
20659
20660
20661 @node Anonymous_Arrays
20662 @subsection @code{Anonymous_Arrays}
20663 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
20664
20665 @noindent
20666 Flag all anonymous array type definitions (by Ada semantics these can only
20667 occur in object declarations).
20668
20669 This rule has no parameters.
20670
20671 @node Anonymous_Subtypes
20672 @subsection @code{Anonymous_Subtypes}
20673 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
20674
20675 @noindent
20676 Flag all uses of anonymous subtypes. A use of an anonymous subtype is
20677 any instance of a subtype indication with a constraint, other than one
20678 that occurs immediately within a subtype declaration. Any use of a range
20679 other than as a constraint used immediately within a subtype declaration
20680 is considered as an anonymous subtype.
20681
20682 An effect of this rule is that @code{for} loops such as the following are
20683 flagged (since @code{1..N} is formally a ``range''):
20684
20685 @smallexample @c ada
20686 for I in 1 .. N loop
20687    @dots{}
20688 end loop;
20689 @end smallexample
20690
20691 @noindent
20692 Declaring an explicit subtype solves the problem:
20693
20694 @smallexample @c ada
20695 subtype S is Integer range 1..N;
20696 @dots{}
20697 for I in S loop
20698    @dots{}
20699 end loop;
20700 @end smallexample
20701
20702 @noindent
20703 This rule has no parameters.
20704
20705 @node Blocks
20706 @subsection @code{Blocks}
20707 @cindex @code{Blocks} rule (for @command{gnatcheck})
20708
20709 @noindent
20710 Flag each block statement.
20711
20712 This rule has no parameters.
20713
20714 @node Boolean_Relational_Operators
20715 @subsection @code{Boolean_Relational_Operators}
20716 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
20717
20718 @noindent
20719 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
20720 ``>='', ``='' and ``/='') for the predefined Boolean type.
20721 (This rule is useful in enforcing the SPARK language restrictions.)
20722
20723 Calls to predefined relational operators of any type derived from
20724 @code{Standard.Boolean} are not detected.  Calls to user-defined functions
20725 with these designators, and uses of operators that are renamings
20726 of the predefined relational operators for @code{Standard.Boolean},
20727 are likewise not detected.
20728
20729 This rule has no parameters.
20730
20731 @ignore
20732 @node Ceiling_Violations
20733 @subsection @code{Ceiling_Violations} (under construction, GLOBAL)
20734 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
20735
20736 @noindent
20737 Flag invocations of a protected operation by a task whose priority exceeds
20738 the protected object's ceiling.
20739
20740 As of @value{NOW}, this rule has the following limitations:
20741
20742 @itemize @bullet
20743
20744 @item
20745  We consider only pragmas Priority and Interrupt_Priority as means to define
20746   a task/protected operation priority. We do not consider the effect of using
20747   Ada.Dynamic_Priorities.Set_Priority procedure;
20748
20749 @item
20750  We consider only base task priorities, and no priority inheritance. That is,
20751   we do not make a difference between calls issued during task activation and
20752   execution of the sequence of statements from task body;
20753
20754 @item
20755  Any situation when the priority of protected operation caller is set by a
20756   dynamic expression (that is, the corresponding Priority or
20757   Interrupt_Priority pragma has a non-static expression as an argument) we
20758   treat as a priority inconsistency (and, therefore, detect this situation).
20759 @end itemize
20760
20761 @noindent
20762 At the moment the notion of the main subprogram is not implemented in
20763 gnatcheck, so any pragma Priority in a library level subprogram body (in case
20764 if this subprogram can be a main subprogram of a partition) changes the
20765 priority of an environment task. So if we have more then one such pragma in
20766 the set of processed sources, the pragma that is processed last, defines the
20767 priority of an environment task.
20768
20769 This rule has no parameters.
20770 @end ignore
20771
20772 @node Controlled_Type_Declarations
20773 @subsection @code{Controlled_Type_Declarations}
20774 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
20775
20776 @noindent
20777 Flag all declarations of controlled types. A declaration of a private type
20778 is flagged if its full declaration declares a controlled type. A declaration
20779 of a derived type is flagged if its ancestor type is controlled. Subtype
20780 declarations are not checked. A declaration of a type that itself is not a
20781 descendant of a type declared in @code{Ada.Finalization} but has a controlled
20782 component is not checked.
20783
20784 This rule has no parameters.
20785
20786
20787
20788 @node Declarations_In_Blocks
20789 @subsection @code{Declarations_In_Blocks}
20790 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
20791
20792 @noindent
20793 Flag all block statements containing local declarations. A @code{declare}
20794 block with an empty @i{declarative_part} or with a @i{declarative part}
20795 containing only pragmas and/or @code{use} clauses is not flagged.
20796
20797 This rule has no parameters.
20798
20799
20800 @node Default_Parameters
20801 @subsection @code{Default_Parameters}
20802 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
20803
20804 @noindent
20805 Flag all default expressions for subprogram parameters. Parameter
20806 declarations of formal and generic subprograms are also checked.
20807
20808 This rule has no parameters.
20809
20810
20811 @node Discriminated_Records
20812 @subsection @code{Discriminated_Records}
20813 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
20814
20815 @noindent
20816 Flag all declarations of record types with discriminants. Only the
20817 declarations of record and record extension types are checked. Incomplete,
20818 formal, private, derived and private extension type declarations are not
20819 checked. Task and protected type declarations also are not checked.
20820
20821 This rule has no parameters.
20822
20823
20824 @node Enumeration_Ranges_In_CASE_Statements
20825 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
20826 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
20827
20828 @noindent
20829 Flag each use of a range of enumeration literals as a choice in a
20830 @code{case} statement.
20831 All forms for specifying a range (explicit ranges
20832 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
20833 An enumeration range is
20834 flagged even if contains exactly one enumeration value or no values at all. A
20835 type derived from an enumeration type is considered as an enumeration type.
20836
20837 This rule helps prevent maintenance problems arising from adding an
20838 enumeration value to a type and having it implicitly handled by an existing
20839 @code{case} statement with an enumeration range that includes the new literal.
20840
20841 This rule has no parameters.
20842
20843
20844 @node Exceptions_As_Control_Flow
20845 @subsection @code{Exceptions_As_Control_Flow}
20846 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
20847
20848 @noindent
20849 Flag each place where an exception is explicitly raised and handled in the
20850 same subprogram body. A @code{raise} statement in an exception handler,
20851 package body, task body or entry body is not flagged.
20852
20853 The rule has no parameters.
20854
20855 @node EXIT_Statements_With_No_Loop_Name
20856 @subsection @code{EXIT_Statements_With_No_Loop_Name}
20857 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
20858
20859 @noindent
20860 Flag each @code{exit} statement that does not specify the name of the loop
20861 being exited.
20862
20863 The rule has no parameters.
20864
20865
20866 @node Expanded_Loop_Exit_Names
20867 @subsection @code{Expanded_Loop_Exit_Names}
20868 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
20869
20870 @noindent
20871 Flag all expanded loop names in @code{exit} statements.
20872
20873 This rule has no parameters.
20874
20875 @node Explicit_Full_Discrete_Ranges
20876 @subsection @code{Explicit_Full_Discrete_Ranges}
20877 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
20878
20879 @noindent
20880 Flag each discrete range that has the form @code{A'First .. A'Last}.
20881
20882 This rule has no parameters.
20883
20884 @node Float_Equality_Checks
20885 @subsection @code{Float_Equality_Checks}
20886 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
20887
20888 @noindent
20889 Flag all calls to the predefined equality operations for floating-point types.
20890 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
20891 User-defined equality operations are not flagged, nor are ``@code{=}''
20892 and ``@code{/=}'' operations for fixed-point types.
20893
20894 This rule has no parameters.
20895
20896
20897 @node Forbidden_Pragmas
20898 @subsection @code{Forbidden_Pragmas}
20899 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
20900
20901 @noindent
20902 Flag each use of the specified pragmas.  The pragmas to be detected
20903 are named in the rule's  parameters.
20904
20905 This rule has the following parameters:
20906
20907 @itemize @bullet
20908 @item For the @option{+R} option
20909
20910 @table @asis
20911 @item @emph{Pragma_Name}
20912 Adds the specified pragma to the set of pragmas to be
20913 checked and sets the checks for all the specified pragmas
20914 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
20915 does not correspond to any pragma name defined in the Ada
20916 standard or to the name of a GNAT-specific pragma defined
20917 in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
20918 Manual}, it is treated as the name of unknown pragma.
20919
20920 @item @code{GNAT}
20921 All the GNAT-specific pragmas are detected; this sets
20922 the checks for all the specified pragmas ON.
20923
20924 @item @code{ALL}
20925 All pragmas are detected; this sets the rule ON.
20926 @end table
20927
20928 @item For the @option{-R} option
20929 @table @asis
20930 @item @emph{Pragma_Name}
20931 Removes the specified pragma from the set of pragmas to be
20932 checked without affecting checks for
20933 other pragmas. @emph{Pragma_Name} is treated as a name
20934 of a pragma. If it does not correspond to any pragma
20935 defined in the Ada standard or to any name defined in
20936 @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
20937 this option is treated as turning OFF detection of all unknown pragmas.
20938
20939 @item GNAT
20940 Turn OFF detection of all GNAT-specific pragmas
20941
20942 @item ALL
20943 Clear the list of the pragmas to be detected and
20944 turn the rule OFF.
20945 @end table
20946 @end itemize
20947
20948 @noindent
20949 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
20950 the syntax of an Ada identifier and therefore can not be considered
20951 as a pragma name, a diagnostic message is generated and the corresponding
20952 parameter is ignored.
20953
20954 When more then one parameter is given in the same rule option, the parameters
20955 must be separated by a comma.
20956
20957 If more then one option for this rule is specified for the @command{gnatcheck}
20958 call, a new option overrides the previous one(s).
20959
20960 The @option{+R} option with no parameters turns the rule ON with the set of
20961 pragmas to be detected defined by the previous rule options.
20962 (By default this set is empty, so if the only option specified for the rule is
20963 @option{+RForbidden_Pragmas} (with
20964 no parameter), then the rule is enabled, but it does not detect anything).
20965 The @option{-R} option with no parameter turns the rule OFF, but it does not
20966 affect the set of pragmas to be detected.
20967
20968
20969
20970
20971 @node Function_Style_Procedures
20972 @subsection @code{Function_Style_Procedures}
20973 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
20974
20975 @noindent
20976 Flag each procedure that can be rewritten as a function. A procedure can be
20977 converted into a function if it has exactly one parameter of mode @code{out}
20978 and no parameters of mode @code{in out}. Procedure declarations,
20979 formal procedure declarations, and generic procedure declarations are always
20980 checked. Procedure
20981 bodies and body stubs are flagged only if they do not have corresponding
20982 separate declarations. Procedure renamings and procedure instantiations are
20983 not flagged.
20984
20985 If a procedure can be rewritten as a function, but its @code{out} parameter is
20986 of a limited type, it is not flagged.
20987
20988 Protected procedures are not flagged. Null procedures also are not flagged.
20989
20990 This rule has no parameters.
20991
20992
20993 @node Generics_In_Subprograms
20994 @subsection @code{Generics_In_Subprograms}
20995 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
20996
20997 @noindent
20998 Flag each declaration of a generic unit in a subprogram. Generic
20999 declarations in the bodies of generic subprograms are also flagged.
21000 A generic unit nested in another generic unit is not flagged.
21001 If a generic unit is
21002 declared in a local package that is declared in a subprogram body, the
21003 generic unit is flagged.
21004
21005 This rule has no parameters.
21006
21007
21008 @node GOTO_Statements
21009 @subsection @code{GOTO_Statements}
21010 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
21011
21012 @noindent
21013 Flag each occurrence of a @code{goto} statement.
21014
21015 This rule has no parameters.
21016
21017
21018 @node Implicit_IN_Mode_Parameters
21019 @subsection @code{Implicit_IN_Mode_Parameters}
21020 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
21021
21022 @noindent
21023 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
21024 Note that @code{access} parameters, although they technically behave
21025 like @code{in} parameters, are not flagged.
21026
21027 This rule has no parameters.
21028
21029
21030 @node Implicit_SMALL_For_Fixed_Point_Types
21031 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
21032 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
21033
21034 @noindent
21035 Flag each fixed point type declaration that lacks an explicit
21036 representation  clause to define its @code{'Small} value.
21037 Since @code{'Small} can be  defined only for ordinary fixed point types,
21038 decimal fixed point type declarations are not checked.
21039
21040 This rule has no parameters.
21041
21042
21043 @node Improperly_Located_Instantiations
21044 @subsection @code{Improperly_Located_Instantiations}
21045 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
21046
21047 @noindent
21048 Flag all generic instantiations in library-level package specs
21049 (including library generic packages) and in all subprogram bodies.
21050
21051 Instantiations in task and entry bodies are not flagged. Instantiations in the
21052 bodies of protected subprograms are flagged.
21053
21054 This rule has no parameters.
21055
21056
21057
21058 @node Improper_Returns
21059 @subsection @code{Improper_Returns}
21060 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
21061
21062 @noindent
21063 Flag each explicit @code{return} statement in procedures, and
21064 multiple @code{return} statements in functions.
21065 Diagnostic messages are generated for all @code{return} statements
21066 in a procedure (thus each procedure must be written so that it
21067 returns implicitly at the end of its statement part),
21068 and for all @code{return} statements in a function after the first one.
21069 This rule supports the stylistic convention that each subprogram
21070 should have no more than one point of normal return.
21071
21072 This rule has no parameters.
21073
21074
21075 @node Library_Level_Subprograms
21076 @subsection @code{Library_Level_Subprograms}
21077 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
21078
21079 @noindent
21080 Flag all library-level subprograms (including generic subprogram instantiations).
21081
21082 This rule has no parameters.
21083
21084
21085 @node Local_Packages
21086 @subsection @code{Local_Packages}
21087 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
21088
21089 @noindent
21090 Flag all local packages declared in package and generic package
21091 specs.
21092 Local packages in bodies are not flagged.
21093
21094 This rule has no parameters.
21095
21096 @ignore
21097 @node Improperly_Called_Protected_Entries
21098 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
21099 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
21100
21101 @noindent
21102 Flag each protected entry that can be called from more than one task.
21103
21104 This rule has no parameters.
21105 @end ignore
21106
21107 @node Metrics
21108 @subsection @code{Metrics}
21109 @cindex @code{Metrics} rule (for @command{gnatcheck})
21110
21111 @noindent
21112 There is a set of checks based on computing a metric value and comparing the
21113 result with the specified upper (or lower, depending on a specific metric)
21114 value specified for a given metric. A construct is flagged if a given metric
21115 is applicable (can be computed) for it and the computed value is greater
21116 then (lover then) the specified upper (lower) bound.
21117
21118 The name of any metric-based rule consists of the prefix @code{Metrics_}
21119 followed by the name of the corresponding metric (see the table below).
21120 For @option{+R} option, each metric-based rule has a numeric parameter
21121 specifying the bound (integer or real, depending on a metric), @option{-R}
21122 option for metric rules does not have a parameter.
21123
21124 The following table shows the metric names for that the corresponding
21125 metrics-based checks are supported by gnatcheck, including the
21126 constraint that must be satisfied by the bound that is specified for the check
21127 and what bound - upper (U) or lower (L) - should be specified.
21128
21129 @multitable {@code{Cyclomatic_Complexity}}{Cyclomatic complexity}{Positive integer}
21130 @ifnothtml
21131 @headitem Check Name @tab Description @tab Bounds Value
21132 @end ifnothtml
21133 @ifhtml
21134 @item @b{Check Name} @tab @b{Description} @tab @b{Bounds Value}
21135 @end ifhtml
21136 @c Above conditional code is workaround to bug in texi2html (Feb 2008)
21137 @item @code{Essential_Complexity} @tab Essential complexity @tab Positive integer (U)
21138 @item @code{Cyclomatic_Complexity} @tab Cyclomatic complexity @tab Positive integer (U)
21139 @item @code{LSLOC} @tab Logical Source Lines of Code @tab Positive integer (U)
21140 @end multitable
21141
21142 @noindent
21143 The meaning and the computed values for all these metrics are exactly
21144 the same as for the corresponding metrics in @command{gnatmetric}.
21145
21146 @emph{Example:} the rule
21147 @smallexample
21148 +RMetrics_Cyclomatic_Complexity : 7
21149 @end smallexample
21150 @noindent
21151 means that all bodies with cyclomatic complexity exceeding 7 will be flagged.
21152
21153 To turn OFF the check for cyclomatic complexity metric, use the following option:
21154 @smallexample
21155 -RMetrics_Cyclomatic_Complexity
21156 @end smallexample
21157
21158 @node Misnamed_Identifiers
21159 @subsection @code{Misnamed_Identifiers}
21160 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
21161
21162 @noindent
21163 Flag the declaration of each identifier that does not have a suffix
21164 corresponding to the kind of entity being declared.
21165 The following declarations are checked:
21166
21167 @itemize @bullet
21168 @item
21169 type declarations
21170
21171 @item
21172 constant declarations (but not number declarations)
21173
21174 @item
21175 package renaming declarations (but not generic package renaming
21176 declarations)
21177 @end itemize
21178
21179 @noindent
21180 This rule may have parameters. When used without parameters, the rule enforces
21181 the following checks:
21182
21183 @itemize @bullet
21184 @item
21185 type-defining names end with @code{_T}, unless the type is an access type,
21186 in which case the suffix must be @code{_A}
21187 @item
21188 constant names end with @code{_C}
21189 @item
21190 names defining package renamings end with @code{_R}
21191 @end itemize
21192
21193 @noindent
21194 For a private or incomplete type declaration the following checks are
21195 made for the defining name suffix:
21196
21197 @itemize @bullet
21198 @item
21199 For an incomplete type declaration: if the corresponding full type
21200 declaration is available, the defining identifier from the full type
21201 declaration is checked, but the defining identifier from the incomplete type
21202 declaration is not; otherwise the defining identifier from the incomplete
21203 type declaration is checked against the suffix specified for type
21204 declarations.
21205
21206 @item
21207 For a private type declaration (including private extensions),  the defining
21208 identifier from the private type declaration is checked against the type
21209 suffix (even if the corresponding full declaration is an access type
21210 declaration), and the defining identifier from the corresponding full type
21211 declaration is not checked.
21212 @end itemize
21213
21214 @noindent
21215 For a deferred constant, the defining name in the corresponding full constant
21216 declaration is not checked.
21217
21218 Defining names of formal types are not checked.
21219
21220 The rule may have the following parameters:
21221
21222 @itemize @bullet
21223 @item
21224 For the @option{+R} option:
21225 @table @code
21226 @item Default
21227 Sets the default listed above for all the names to be checked.
21228
21229 @item Type_Suffix=@emph{string}
21230 Specifies the suffix for a type name.
21231
21232 @item Access_Suffix=@emph{string}
21233 Specifies the suffix for an access type name. If
21234 this parameter is set, it overrides for access
21235 types the suffix set by the @code{Type_Suffix} parameter.
21236
21237 @item Constant_Suffix=@emph{string}
21238 Specifies the suffix for a constant name.
21239
21240 @item Renaming_Suffix=@emph{string}
21241 Specifies the suffix for a package renaming name.
21242 @end table
21243
21244 @item
21245 For the @option{-R} option:
21246 @table @code
21247 @item All_Suffixes
21248 Remove all the suffixes specified for the
21249 identifier suffix checks, whether by default or
21250 as specified by other rule parameters. All the
21251 checks for this rule are disabled as a result.
21252
21253 @item Type_Suffix
21254 Removes the suffix specified for types. This
21255 disables checks for types but does not disable
21256 any other checks for this rule (including the
21257 check for access type names if @code{Access_Suffix} is
21258 set).
21259
21260 @item Access_Suffix
21261 Removes the suffix specified for access types.
21262 This disables checks for access type names but
21263 does not disable any other checks for this rule.
21264 If @code{Type_Suffix} is set, access type names are
21265 checked as ordinary type names.
21266
21267 @item Constant_Suffix
21268 Removes the suffix specified for constants. This
21269 disables checks for constant names but does not
21270 disable any other checks for this rule.
21271
21272 @item Renaming_Suffix
21273 Removes the suffix specified for package
21274 renamings. This disables checks for package
21275 renamings but does not disable any other checks
21276 for this rule.
21277 @end table
21278 @end itemize
21279
21280 @noindent
21281 If more than one parameter is used, parameters must be separated by commas.
21282
21283 If more than one  option is specified for the @command{gnatcheck} invocation,
21284 a new option overrides the previous one(s).
21285
21286 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
21287 checks for all the
21288 name suffixes specified by previous options used for this rule.
21289
21290 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
21291 all the checks but keeps
21292 all the suffixes specified by previous options used for this rule.
21293
21294 The @emph{string} value must be a valid suffix for an Ada identifier (after
21295 trimming all the leading and trailing space characters, if any).
21296 Parameters are not case sensitive, except the @emph{string} part.
21297
21298 If any error is detected in a rule parameter, the parameter is ignored.
21299 In such a case the options that are set for the rule are not
21300 specified.
21301
21302
21303
21304 @node Multiple_Entries_In_Protected_Definitions
21305 @subsection @code{Multiple_Entries_In_Protected_Definitions}
21306 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
21307
21308 @noindent
21309 Flag each protected definition (i.e., each protected object/type declaration)
21310 that defines more than one entry.
21311 Diagnostic messages are generated for all the entry declarations
21312 except the first one. An entry family is counted as one entry. Entries from
21313 the private part of the protected definition are also checked.
21314
21315 This rule has no parameters.
21316
21317 @node Name_Clashes
21318 @subsection @code{Name_Clashes}
21319 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
21320
21321 @noindent
21322 Check that certain names are not used as defining identifiers. To activate
21323 this rule, you need to supply a reference to the dictionary file(s) as a rule
21324 parameter(s) (more then one dictionary file can be specified). If no
21325 dictionary file is set, this rule will not cause anything to be flagged.
21326 Only defining occurrences, not references, are checked.
21327 The check is not case-sensitive.
21328
21329 This rule is enabled by default, but without setting any corresponding
21330 dictionary file(s); thus the default effect is to do no checks.
21331
21332 A dictionary file is a plain text file. The maximum line length for this file
21333 is 1024 characters.  If the line is longer then this limit, extra characters
21334 are ignored.
21335
21336 Each line can be either an empty line, a comment line, or a line containing
21337 a list of identifiers separated by space or HT characters.
21338 A comment is an Ada-style comment (from @code{--} to end-of-line).
21339 Identifiers must follow the Ada syntax for identifiers.
21340 A line containing one or more identifiers may end with a comment.
21341
21342 @node Non_Qualified_Aggregates
21343 @subsection @code{Non_Qualified_Aggregates}
21344 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
21345
21346 @noindent
21347 Flag each non-qualified aggregate.
21348 A non-qualified aggregate is an
21349 aggregate that is not the expression of a qualified expression. A
21350 string literal is not considered an aggregate, but an array
21351 aggregate of a string type is considered as a normal aggregate.
21352 Aggregates of anonymous array types are not flagged.
21353
21354 This rule has no parameters.
21355
21356
21357 @node Non_Short_Circuit_Operators
21358 @subsection @code{Non_Short_Circuit_Operators}
21359 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
21360
21361 @noindent
21362 Flag all calls to predefined @code{and} and @code{or} operators for
21363 any boolean type. Calls to
21364 user-defined @code{and} and @code{or} and to operators defined by renaming
21365 declarations are not flagged. Calls to predefined @code{and} and @code{or}
21366 operators for modular types or boolean array types are not flagged.
21367
21368 This rule has no parameters.
21369
21370
21371
21372 @node Non_SPARK_Attributes
21373 @subsection @code{Non_SPARK_Attributes}
21374 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
21375
21376 @noindent
21377 The SPARK language defines the following subset of Ada 95 attribute
21378 designators as those that can be used in SPARK programs. The use of
21379 any other attribute is flagged.
21380
21381 @itemize @bullet
21382 @item @code{'Adjacent}
21383 @item @code{'Aft}
21384 @item @code{'Base}
21385 @item @code{'Ceiling}
21386 @item @code{'Component_Size}
21387 @item @code{'Compose}
21388 @item @code{'Copy_Sign}
21389 @item @code{'Delta}
21390 @item @code{'Denorm}
21391 @item @code{'Digits}
21392 @item @code{'Exponent}
21393 @item @code{'First}
21394 @item @code{'Floor}
21395 @item @code{'Fore}
21396 @item @code{'Fraction}
21397 @item @code{'Last}
21398 @item @code{'Leading_Part}
21399 @item @code{'Length}
21400 @item @code{'Machine}
21401 @item @code{'Machine_Emax}
21402 @item @code{'Machine_Emin}
21403 @item @code{'Machine_Mantissa}
21404 @item @code{'Machine_Overflows}
21405 @item @code{'Machine_Radix}
21406 @item @code{'Machine_Rounds}
21407 @item @code{'Max}
21408 @item @code{'Min}
21409 @item @code{'Model}
21410 @item @code{'Model_Emin}
21411 @item @code{'Model_Epsilon}
21412 @item @code{'Model_Mantissa}
21413 @item @code{'Model_Small}
21414 @item @code{'Modulus}
21415 @item @code{'Pos}
21416 @item @code{'Pred}
21417 @item @code{'Range}
21418 @item @code{'Remainder}
21419 @item @code{'Rounding}
21420 @item @code{'Safe_First}
21421 @item @code{'Safe_Last}
21422 @item @code{'Scaling}
21423 @item @code{'Signed_Zeros}
21424 @item @code{'Size}
21425 @item @code{'Small}
21426 @item @code{'Succ}
21427 @item @code{'Truncation}
21428 @item @code{'Unbiased_Rounding}
21429 @item @code{'Val}
21430 @item @code{'Valid}
21431 @end itemize
21432
21433 @noindent
21434 This rule has no parameters.
21435
21436
21437 @node Non_Tagged_Derived_Types
21438 @subsection @code{Non_Tagged_Derived_Types}
21439 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
21440
21441 @noindent
21442 Flag all derived type declarations that do not have a record extension part.
21443
21444 This rule has no parameters.
21445
21446
21447
21448 @node Non_Visible_Exceptions
21449 @subsection @code{Non_Visible_Exceptions}
21450 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
21451
21452 @noindent
21453 Flag constructs leading to the possibility of propagating an exception
21454 out of the scope in which the exception is declared.
21455 Two cases are detected:
21456
21457 @itemize @bullet
21458 @item
21459 An exception declaration in a subprogram body, task body or block
21460 statement is flagged if the body or statement does not contain a handler for
21461 that exception or a handler with an @code{others} choice.
21462
21463 @item
21464 A @code{raise} statement in an exception handler of a subprogram body,
21465 task body or block statement is flagged if it (re)raises a locally
21466 declared exception.  This may occur under the following circumstances:
21467 @itemize @minus
21468 @item
21469 it explicitly raises a locally declared exception, or
21470 @item
21471 it does not specify an exception name (i.e., it is simply @code{raise;})
21472 and the enclosing handler contains a locally declared exception in its
21473 exception choices.
21474 @end itemize
21475 @end itemize
21476
21477 @noindent
21478 Renamings of local exceptions are not flagged.
21479
21480 This rule has no parameters.
21481
21482
21483 @node Numeric_Literals
21484 @subsection @code{Numeric_Literals}
21485 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
21486
21487 @noindent
21488 Flag each use of a numeric literal in an index expression, and in any
21489 circumstance except for the following:
21490
21491 @itemize @bullet
21492 @item
21493 a literal occurring in the initialization expression for a constant
21494 declaration or a named number declaration, or
21495
21496 @item
21497 an integer literal that is less than or equal to a value
21498 specified by the @option{N} rule parameter.
21499 @end itemize
21500
21501 @noindent
21502 This rule may have the following parameters for the @option{+R} option:
21503
21504 @table @asis
21505 @item @emph{N}
21506 @emph{N} is an integer literal used as the maximal value that is not flagged
21507 (i.e., integer literals not exceeding this value are allowed)
21508
21509 @item @code{ALL}
21510 All integer literals are flagged
21511 @end table
21512
21513 @noindent
21514 If no parameters are set, the maximum unflagged value is 1.
21515
21516 The last specified check limit (or the fact that there is no limit at
21517 all) is used when multiple @option{+R} options appear.
21518
21519 The @option{-R} option for this rule has no parameters.
21520 It disables the rule but retains the last specified maximum unflagged value.
21521 If the @option{+R} option subsequently appears, this value is used as the
21522 threshold for the check.
21523
21524
21525 @node OTHERS_In_Aggregates
21526 @subsection @code{OTHERS_In_Aggregates}
21527 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
21528
21529 @noindent
21530 Flag each use of an @code{others} choice in extension aggregates.
21531 In record and array aggregates, an @code{others} choice is flagged unless
21532 it is used to refer to all components, or to all but one component.
21533
21534 If, in case of a named array aggregate, there are two associations, one
21535 with an @code{others} choice and another with a discrete range, the
21536 @code{others} choice is flagged even if the discrete range specifies
21537 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
21538
21539 This rule has no parameters.
21540
21541 @node OTHERS_In_CASE_Statements
21542 @subsection @code{OTHERS_In_CASE_Statements}
21543 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
21544
21545 @noindent
21546 Flag any use of an @code{others} choice in a @code{case} statement.
21547
21548 This rule has no parameters.
21549
21550 @node OTHERS_In_Exception_Handlers
21551 @subsection @code{OTHERS_In_Exception_Handlers}
21552 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
21553
21554 @noindent
21555 Flag any use of an @code{others} choice in an exception handler.
21556
21557 This rule has no parameters.
21558
21559
21560 @node Outer_Loop_Exits
21561 @subsection @code{Outer_Loop_Exits}
21562 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
21563
21564 @noindent
21565 Flag each @code{exit} statement containing a loop name that is not the name
21566 of the immediately enclosing @code{loop} statement.
21567
21568 This rule has no parameters.
21569
21570
21571 @node Overloaded_Operators
21572 @subsection @code{Overloaded_Operators}
21573 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
21574
21575 @noindent
21576 Flag each function declaration that overloads an operator symbol.
21577 A function body is checked only if the body does not have a
21578 separate spec. Formal functions are also checked. For a
21579 renaming declaration, only renaming-as-declaration is checked
21580
21581 This rule has no parameters.
21582
21583
21584 @node Overly_Nested_Control_Structures
21585 @subsection @code{Overly_Nested_Control_Structures}
21586 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
21587
21588 @noindent
21589 Flag each control structure whose nesting level exceeds the value provided
21590 in the rule parameter.
21591
21592 The control structures checked are the following:
21593
21594 @itemize @bullet
21595 @item    @code{if} statement
21596 @item    @code{case} statement
21597 @item    @code{loop} statement
21598 @item    Selective accept statement
21599 @item    Timed entry call statement
21600 @item    Conditional entry call
21601 @item    Asynchronous select statement
21602 @end itemize
21603
21604 @noindent
21605 The rule has the following parameter for the @option{+R} option:
21606
21607 @table @emph
21608 @item N
21609 Positive integer specifying the maximal control structure nesting
21610 level that is not flagged
21611 @end table
21612
21613 @noindent
21614 If the parameter for the @option{+R} option is not specified or
21615 if it is not a positive integer, @option{+R} option is ignored.
21616
21617 If more then one  option is specified for the gnatcheck call, the later option and
21618 new parameter override the previous one(s).
21619
21620
21621 @node Parameters_Out_Of_Order
21622 @subsection @code{Parameters_Out_Of_Order}
21623 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
21624
21625 @noindent
21626 Flag each subprogram and entry declaration whose formal parameters are not
21627 ordered according to the following scheme:
21628
21629 @itemize @bullet
21630
21631 @item @code{in} and @code{access} parameters first,
21632 then @code{in out} parameters,
21633 and then @code{out} parameters;
21634
21635 @item for @code{in} mode, parameters with default initialization expressions
21636 occur last
21637 @end itemize
21638
21639 @noindent
21640 Only the first violation of the described order is flagged.
21641
21642 The following constructs are checked:
21643
21644 @itemize @bullet
21645 @item   subprogram declarations (including null procedures);
21646 @item   generic subprogram declarations;
21647 @item   formal subprogram declarations;
21648 @item   entry declarations;
21649 @item   subprogram bodies and subprogram body stubs that do not
21650 have separate specifications
21651 @end itemize
21652
21653 @noindent
21654 Subprogram renamings are not checked.
21655
21656 This rule has no parameters.
21657
21658
21659 @node Positional_Actuals_For_Defaulted_Generic_Parameters
21660 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
21661 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
21662
21663 @noindent
21664 Flag each generic actual parameter corresponding to a generic formal
21665 parameter with a default initialization, if positional notation is used.
21666
21667 This rule has no parameters.
21668
21669 @node Positional_Actuals_For_Defaulted_Parameters
21670 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
21671 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
21672
21673 @noindent
21674 Flag each actual parameter to a subprogram or entry call where the
21675 corresponding formal parameter has a default expression, if positional
21676 notation is used.
21677
21678 This rule has no parameters.
21679
21680 @node Positional_Components
21681 @subsection @code{Positional_Components}
21682 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
21683
21684 @noindent
21685 Flag each array, record and extension aggregate that includes positional
21686 notation.
21687
21688 This rule has no parameters.
21689
21690
21691 @node Positional_Generic_Parameters
21692 @subsection @code{Positional_Generic_Parameters}
21693 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
21694
21695 @noindent
21696 Flag each instantiation using positional parameter notation.
21697
21698 This rule has no parameters.
21699
21700
21701 @node Positional_Parameters
21702 @subsection @code{Positional_Parameters}
21703 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
21704
21705 @noindent
21706 Flag each subprogram or entry call using positional parameter notation,
21707 except for the following:
21708
21709 @itemize @bullet
21710 @item
21711 Invocations of prefix or infix operators are not flagged
21712 @item
21713 If the called subprogram or entry has only one formal parameter,
21714 the call is not flagged;
21715 @item
21716 If a subprogram call uses the @emph{Object.Operation} notation, then
21717 @itemize @minus
21718 @item
21719 the first parameter (that is, @emph{Object}) is not flagged;
21720 @item
21721 if the called subprogram has only two parameters, the second parameter
21722 of the call is not flagged;
21723 @end itemize
21724 @end itemize
21725
21726 @noindent
21727 This rule has no parameters.
21728
21729
21730
21731
21732 @node Predefined_Numeric_Types
21733 @subsection @code{Predefined_Numeric_Types}
21734 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
21735
21736 @noindent
21737 Flag each explicit use of the name of any numeric type or subtype defined
21738 in package @code{Standard}.
21739
21740 The rationale for this rule is to detect when the
21741 program may depend on platform-specific characteristics of the implementation
21742 of the predefined numeric types. Note that this rule is over-pessimistic;
21743 for example, a program that uses @code{String} indexing
21744 likely needs a variable of type @code{Integer}.
21745 Another example is the flagging of predefined numeric types with explicit
21746 constraints:
21747
21748 @smallexample @c ada
21749     subtype My_Integer is Integer range Left .. Right;
21750     Vy_Var : My_Integer;
21751 @end smallexample
21752
21753 @noindent
21754 This rule detects only numeric types and subtypes defined in
21755 @code{Standard}. The use of numeric types and subtypes defined in other
21756 predefined packages (such as @code{System.Any_Priority} or
21757 @code{Ada.Text_IO.Count}) is not flagged
21758
21759 This rule has no parameters.
21760
21761
21762
21763 @node Raising_External_Exceptions
21764 @subsection @code{Raising_External_Exceptions}
21765 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
21766
21767 @noindent
21768 Flag any @code{raise} statement, in a program unit declared in a library
21769 package or in a generic library package, for an exception that is
21770 neither a predefined exception nor an exception that is also declared (or
21771 renamed) in the visible part of the package.
21772
21773 This rule has no parameters.
21774
21775
21776
21777 @node Raising_Predefined_Exceptions
21778 @subsection @code{Raising_Predefined_Exceptions}
21779 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
21780
21781 @noindent
21782 Flag each @code{raise} statement that raises a predefined exception
21783 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
21784 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
21785
21786 This rule has no parameters.
21787
21788 @node Separate_Numeric_Error_Handlers
21789 @subsection @code{Separate_Numeric_Error_Handlers}
21790 @cindex @code{Separate_Numeric_Error_Handlers} rule (for @command{gnatcheck})
21791
21792 @noindent
21793 Flags each exception handler that contains a choice for
21794 the predefined @code{Constraint_Error} exception, but does not contain
21795 the choice for the predefined @code{Numeric_Error} exception, or
21796 that contains the choice for @code{Numeric_Error}, but does not contain the
21797 choice for @code{Constraint_Error}.
21798
21799 This rule has no parameters.
21800
21801 @ignore
21802 @node Recursion
21803 @subsection @code{Recursion} (under construction, GLOBAL)
21804 @cindex @code{Recursion} rule (for @command{gnatcheck})
21805
21806 @noindent
21807 Flag recursive subprograms (cycles in the call graph). Declarations, and not
21808 calls, of recursive subprograms are detected.
21809
21810 This rule has no parameters.
21811 @end ignore
21812
21813 @ignore
21814 @node Side_Effect_Functions
21815 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
21816 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
21817
21818 @noindent
21819 Flag functions with side effects.
21820
21821 We define a side effect as changing any data object that is not local for the
21822 body of this function.
21823
21824 At the moment, we do NOT consider a side effect any input-output operations
21825 (changing a state or a content of any file).
21826
21827 We do not consider protected functions for this rule (???)
21828
21829 There are the following sources of side effect:
21830
21831 @enumerate
21832 @item Explicit (or direct) side-effect:
21833
21834 @itemize @bullet
21835 @item
21836 direct assignment to a non-local variable;
21837
21838 @item
21839 direct call to an entity that is known to change some data object that is
21840      not local for the body of this function (Note, that if F1 calls F2 and F2
21841      does have a side effect, this does not automatically mean that F1 also
21842      have a side effect, because it may be the case that F2 is declared in
21843      F1's body and it changes some data object that is global for F2, but
21844      local for F1);
21845 @end itemize
21846
21847 @item Indirect side-effect:
21848 @itemize @bullet
21849 @item
21850 Subprogram calls implicitly issued by:
21851 @itemize @bullet
21852 @item
21853 computing initialization expressions from type declarations as a part
21854          of object elaboration or allocator evaluation;
21855 @item
21856 computing implicit parameters of subprogram or entry calls or generic
21857          instantiations;
21858 @end itemize
21859
21860 @item
21861 activation of a task that change some non-local data object (directly or
21862      indirectly);
21863
21864 @item
21865 elaboration code of a package that is a result of a package instantiation;
21866
21867 @item
21868 controlled objects;
21869 @end itemize
21870
21871 @item Situations when we can suspect a side-effect, but the full static check
21872 is either impossible or too hard:
21873 @itemize @bullet
21874 @item
21875 assignment to access variables or to the objects pointed by access
21876      variables;
21877
21878 @item
21879 call to a subprogram pointed by access-to-subprogram value
21880
21881 @item
21882 dispatching calls;
21883 @end itemize
21884 @end enumerate
21885
21886 @noindent
21887 This rule has no parameters.
21888 @end ignore
21889
21890 @node Slices
21891 @subsection @code{Slices}
21892 @cindex @code{Slices} rule (for @command{gnatcheck})
21893
21894 @noindent
21895 Flag all uses of array slicing
21896
21897 This rule has no parameters.
21898
21899
21900 @node Unassigned_OUT_Parameters
21901 @subsection @code{Unassigned_OUT_Parameters}
21902 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
21903
21904 @noindent
21905 Flags procedures' @code{out} parameters that are not assigned, and
21906 identifies the contexts in which the assignments are missing.
21907
21908 An @code{out} parameter is flagged in the statements in the procedure
21909 body's handled sequence of statements (before the procedure body's
21910 @code{exception} part, if any) if this sequence of statements contains
21911 no assignments to the parameter.
21912
21913 An @code{out} parameter is flagged in an exception handler in the exception
21914 part of the procedure body's handled sequence of statements if the handler
21915 contains no assignment to the parameter.
21916
21917 Bodies of generic procedures are also considered.
21918
21919 The following are treated as assignments to an @code{out} parameter:
21920
21921 @itemize @bullet
21922 @item
21923 an assignment statement, with the parameter or some component as the target;
21924
21925 @item
21926 passing the parameter (or one of its components) as an @code{out} or
21927 @code{in out} parameter.
21928 @end itemize
21929
21930 @noindent
21931 This rule does not have any parameters.
21932
21933
21934
21935 @node Uncommented_BEGIN_In_Package_Bodies
21936 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
21937 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
21938
21939 @noindent
21940 Flags each package body with declarations and a statement part that does not
21941 include a trailing comment on the line containing the @code{begin} keyword;
21942 this trailing comment needs to specify the package name and nothing else.
21943 The @code{begin} is not flagged if the package body does not
21944 contain any declarations.
21945
21946 If the @code{begin} keyword is placed on the
21947 same line as the last declaration or the first statement, it is flagged
21948 independently of whether the line contains a trailing comment. The
21949 diagnostic message is attached to the line containing the first statement.
21950
21951 This rule has no parameters.
21952
21953
21954 @node Unconstrained_Array_Returns
21955 @subsection @code{Unconstrained_Array_Returns}
21956 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
21957
21958 @noindent
21959 Flag each function returning an unconstrained array. Function declarations,
21960 function bodies (and body stubs) having no separate specifications,
21961 and generic function instantiations are checked.
21962 Generic function declarations, function calls and function renamings are
21963 not checked.
21964
21965 This rule has no parameters.
21966
21967 @node Universal_Ranges
21968 @subsection @code{Universal_Ranges}
21969 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
21970
21971 @noindent
21972 Flag discrete ranges that are a part of an index constraint, constrained
21973 array definition, or @code{for}-loop parameter specification, and whose bounds
21974 are both of type @i{universal_integer}. Ranges that have at least one
21975 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
21976 or an expression of non-universal type) are not flagged.
21977
21978 This rule has no parameters.
21979
21980
21981 @node Unnamed_Blocks_And_Loops
21982 @subsection @code{Unnamed_Blocks_And_Loops}
21983 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
21984
21985 @noindent
21986 Flag each unnamed block statement and loop statement.
21987
21988 The rule has no parameters.
21989
21990
21991
21992 @ignore
21993 @node Unused_Subprograms
21994 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
21995 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
21996
21997 @noindent
21998 Flag all unused subprograms.
21999
22000 This rule has no parameters.
22001 @end ignore
22002
22003
22004
22005
22006 @node USE_PACKAGE_Clauses
22007 @subsection @code{USE_PACKAGE_Clauses}
22008 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
22009
22010 @noindent
22011 Flag all @code{use} clauses for packages; @code{use type} clauses are
22012 not flagged.
22013
22014 This rule has no parameters.
22015
22016
22017
22018 @node Volatile_Objects_Without_Address_Clauses
22019 @subsection @code{Volatile_Objects_Without_Address_Clauses}
22020 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
22021
22022 @noindent
22023 Flag each volatile object that does not have an address clause.
22024
22025 The following check is made: if the pragma @code{Volatile} is applied to a
22026 data object or to its type, then an address clause must
22027 be supplied for this object.
22028
22029 This rule does not check the components of data objects,
22030 array components that are volatile as a result of the pragma
22031 @code{Volatile_Components}, or objects that are volatile because
22032 they are atomic as a result of pragmas @code{Atomic} or
22033 @code{Atomic_Components}.
22034
22035 Only variable declarations, and not constant declarations, are checked.
22036
22037 This rule has no parameters.
22038
22039
22040 @c *********************************
22041 @node Creating Sample Bodies Using gnatstub
22042 @chapter Creating Sample Bodies Using @command{gnatstub}
22043 @findex gnatstub
22044
22045 @noindent
22046 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
22047 for library unit declarations.
22048
22049 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
22050 driver (see @ref{The GNAT Driver and Project Files}).
22051
22052 To create a body stub, @command{gnatstub} has to compile the library
22053 unit declaration. Therefore, bodies can be created only for legal
22054 library units. Moreover, if a library unit depends semantically upon
22055 units located outside the current directory, you have to provide
22056 the source search path when calling @command{gnatstub}, see the description
22057 of @command{gnatstub} switches below.
22058
22059 @menu
22060 * Running gnatstub::
22061 * Switches for gnatstub::
22062 @end menu
22063
22064 @node Running gnatstub
22065 @section Running @command{gnatstub}
22066
22067 @noindent
22068 @command{gnatstub} has the command-line interface of the form
22069
22070 @smallexample
22071 $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
22072 @end smallexample
22073
22074 @noindent
22075 where
22076 @table @var
22077 @item filename
22078 is the name of the source file that contains a library unit declaration
22079 for which a body must be created. The file name may contain the path
22080 information.
22081 The file name does not have to follow the GNAT file name conventions. If the
22082 name
22083 does not follow GNAT file naming conventions, the name of the body file must
22084 be provided
22085 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
22086 If the file name follows the GNAT file naming
22087 conventions and the name of the body file is not provided,
22088 @command{gnatstub}
22089 creates the name
22090 of the body file from the argument file name by replacing the @file{.ads}
22091 suffix
22092 with the @file{.adb} suffix.
22093
22094 @item directory
22095 indicates the directory in which the body stub is to be placed (the default
22096 is the
22097 current directory)
22098
22099 @item switches
22100 is an optional sequence of switches as described in the next section
22101 @end table
22102
22103 @node Switches for gnatstub
22104 @section Switches for @command{gnatstub}
22105
22106 @table @option
22107 @c !sort!
22108
22109 @item ^-f^/FULL^
22110 @cindex @option{^-f^/FULL^} (@command{gnatstub})
22111 If the destination directory already contains a file with the name of the
22112 body file
22113 for the argument spec file, replace it with the generated body stub.
22114
22115 @item ^-hs^/HEADER=SPEC^
22116 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
22117 Put the comment header (i.e., all the comments preceding the
22118 compilation unit) from the source of the library unit declaration
22119 into the body stub.
22120
22121 @item ^-hg^/HEADER=GENERAL^
22122 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
22123 Put a sample comment header into the body stub.
22124
22125 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
22126 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
22127 Use the content of the file as the comment header for a generated body stub.
22128
22129 @ifclear vms
22130 @item -IDIR
22131 @cindex @option{-IDIR} (@command{gnatstub})
22132 @itemx -I-
22133 @cindex @option{-I-} (@command{gnatstub})
22134 @end ifclear
22135 @ifset vms
22136 @item /NOCURRENT_DIRECTORY
22137 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
22138 @end ifset
22139 ^These switches have ^This switch has^ the same meaning as in calls to
22140 @command{gcc}.
22141 ^They define ^It defines ^ the source search path in the call to
22142 @command{gcc} issued
22143 by @command{gnatstub} to compile an argument source file.
22144
22145 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
22146 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
22147 This switch has the same meaning as in calls to @command{gcc}.
22148 It defines the additional configuration file to be passed to the call to
22149 @command{gcc} issued
22150 by @command{gnatstub} to compile an argument source file.
22151
22152 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
22153 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
22154 (@var{n} is a non-negative integer). Set the maximum line length in the
22155 body stub to @var{n}; the default is 79. The maximum value that can be
22156 specified is 32767. Note that in the special case of configuration
22157 pragma files, the maximum is always 32767 regardless of whether or
22158 not this switch appears.
22159
22160 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
22161 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
22162 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
22163 the generated body sample to @var{n}.
22164 The default indentation is 3.
22165
22166 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
22167 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
22168 Order local bodies alphabetically. (By default local bodies are ordered
22169 in the same way as the corresponding local specs in the argument spec file.)
22170
22171 @item ^-i^/INDENTATION=^@var{n}
22172 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
22173 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
22174
22175 @item ^-k^/TREE_FILE=SAVE^
22176 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
22177 Do not remove the tree file (i.e., the snapshot of the compiler internal
22178 structures used by @command{gnatstub}) after creating the body stub.
22179
22180 @item ^-l^/LINE_LENGTH=^@var{n}
22181 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
22182 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
22183
22184 @item ^-o^/BODY=^@var{body-name}
22185 @cindex @option{^-o^/BODY^} (@command{gnatstub})
22186 Body file name.  This should be set if the argument file name does not
22187 follow
22188 the GNAT file naming
22189 conventions. If this switch is omitted the default name for the body will be
22190 obtained
22191 from the argument file name according to the GNAT file naming conventions.
22192
22193 @item ^-q^/QUIET^
22194 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
22195 Quiet mode: do not generate a confirmation when a body is
22196 successfully created, and do not generate a message when a body is not
22197 required for an
22198 argument unit.
22199
22200 @item ^-r^/TREE_FILE=REUSE^
22201 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
22202 Reuse the tree file (if it exists) instead of creating it.  Instead of
22203 creating the tree file for the library unit declaration, @command{gnatstub}
22204 tries to find it in the current directory and use it for creating
22205 a body. If the tree file is not found, no body is created. This option
22206 also implies @option{^-k^/SAVE^}, whether or not
22207 the latter is set explicitly.
22208
22209 @item ^-t^/TREE_FILE=OVERWRITE^
22210 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
22211 Overwrite the existing tree file.  If the current directory already
22212 contains the file which, according to the GNAT file naming rules should
22213 be considered as a tree file for the argument source file,
22214 @command{gnatstub}
22215 will refuse to create the tree file needed to create a sample body
22216 unless this option is set.
22217
22218 @item ^-v^/VERBOSE^
22219 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
22220 Verbose mode: generate version information.
22221
22222 @end table
22223
22224 @node Other Utility Programs
22225 @chapter Other Utility Programs
22226
22227 @noindent
22228 This chapter discusses some other utility programs available in the Ada
22229 environment.
22230
22231 @menu
22232 * Using Other Utility Programs with GNAT::
22233 * The External Symbol Naming Scheme of GNAT::
22234 * Converting Ada Files to html with gnathtml::
22235 * Installing gnathtml::
22236 @ifset vms
22237 * LSE::
22238 * Profiling::
22239 @end ifset
22240 @end menu
22241
22242 @node Using Other Utility Programs with GNAT
22243 @section Using Other Utility Programs with GNAT
22244
22245 @noindent
22246 The object files generated by GNAT are in standard system format and in
22247 particular the debugging information uses this format. This means
22248 programs generated by GNAT can be used with existing utilities that
22249 depend on these formats.
22250
22251 @ifclear vms
22252 In general, any utility program that works with C will also often work with
22253 Ada programs generated by GNAT. This includes software utilities such as
22254 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
22255 as Purify.
22256 @end ifclear
22257
22258 @node The External Symbol Naming Scheme of GNAT
22259 @section The External Symbol Naming Scheme of GNAT
22260
22261 @noindent
22262 In order to interpret the output from GNAT, when using tools that are
22263 originally intended for use with other languages, it is useful to
22264 understand the conventions used to generate link names from the Ada
22265 entity names.
22266
22267 All link names are in all lowercase letters. With the exception of library
22268 procedure names, the mechanism used is simply to use the full expanded
22269 Ada name with dots replaced by double underscores. For example, suppose
22270 we have the following package spec:
22271
22272 @smallexample @c ada
22273 @group
22274 @cartouche
22275 package QRS is
22276    MN : Integer;
22277 end QRS;
22278 @end cartouche
22279 @end group
22280 @end smallexample
22281
22282 @noindent
22283 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
22284 the corresponding link name is @code{qrs__mn}.
22285 @findex Export
22286 Of course if a @code{pragma Export} is used this may be overridden:
22287
22288 @smallexample @c ada
22289 @group
22290 @cartouche
22291 package Exports is
22292    Var1 : Integer;
22293    pragma Export (Var1, C, External_Name => "var1_name");
22294    Var2 : Integer;
22295    pragma Export (Var2, C, Link_Name => "var2_link_name");
22296 end Exports;
22297 @end cartouche
22298 @end group
22299 @end smallexample
22300
22301 @noindent
22302 In this case, the link name for @var{Var1} is whatever link name the
22303 C compiler would assign for the C function @var{var1_name}. This typically
22304 would be either @var{var1_name} or @var{_var1_name}, depending on operating
22305 system conventions, but other possibilities exist. The link name for
22306 @var{Var2} is @var{var2_link_name}, and this is not operating system
22307 dependent.
22308
22309 @findex _main
22310 One exception occurs for library level procedures. A potential ambiguity
22311 arises between the required name @code{_main} for the C main program,
22312 and the name we would otherwise assign to an Ada library level procedure
22313 called @code{Main} (which might well not be the main program).
22314
22315 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
22316 names. So if we have a library level procedure such as
22317
22318 @smallexample @c ada
22319 @group
22320 @cartouche
22321 procedure Hello (S : String);
22322 @end cartouche
22323 @end group
22324 @end smallexample
22325
22326 @noindent
22327 the external name of this procedure will be @var{_ada_hello}.
22328
22329
22330 @node Converting Ada Files to html with gnathtml
22331 @section Converting Ada Files to HTML with @code{gnathtml}
22332
22333 @noindent
22334 This @code{Perl} script allows Ada source files to be browsed using
22335 standard Web browsers. For installation procedure, see the section
22336 @xref{Installing gnathtml}.
22337
22338 Ada reserved keywords are highlighted in a bold font and Ada comments in
22339 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
22340 switch to suppress the generation of cross-referencing information, user
22341 defined variables and types will appear in a different color; you will
22342 be able to click on any identifier and go to its declaration.
22343
22344 The command line is as follow:
22345 @smallexample
22346 $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
22347 @end smallexample
22348
22349 @noindent
22350 You can pass it as many Ada files as you want. @code{gnathtml} will generate
22351 an html file for every ada file, and a global file called @file{index.htm}.
22352 This file is an index of every identifier defined in the files.
22353
22354 The available ^switches^options^ are the following ones:
22355
22356 @table @option
22357 @item -83
22358 @cindex @option{-83} (@code{gnathtml})
22359 Only the Ada 83 subset of keywords will be highlighted.
22360
22361 @item -cc @var{color}
22362 @cindex @option{-cc} (@code{gnathtml})
22363 This option allows you to change the color used for comments. The default
22364 value is green. The color argument can be any name accepted by html.
22365
22366 @item -d
22367 @cindex @option{-d} (@code{gnathtml})
22368 If the Ada files depend on some other files (for instance through
22369 @code{with} clauses, the latter files will also be converted to html.
22370 Only the files in the user project will be converted to html, not the files
22371 in the run-time library itself.
22372
22373 @item -D
22374 @cindex @option{-D} (@code{gnathtml})
22375 This command is the same as @option{-d} above, but @command{gnathtml} will
22376 also look for files in the run-time library, and generate html files for them.
22377
22378 @item -ext @var{extension}
22379 @cindex @option{-ext} (@code{gnathtml})
22380 This option allows you to change the extension of the generated HTML files.
22381 If you do not specify an extension, it will default to @file{htm}.
22382
22383 @item -f
22384 @cindex @option{-f} (@code{gnathtml})
22385 By default, gnathtml will generate html links only for global entities
22386 ('with'ed units, global variables and types,@dots{}).  If you specify
22387 @option{-f} on the command line, then links will be generated for local
22388 entities too.
22389
22390 @item -l @var{number}
22391 @cindex @option{-l} (@code{gnathtml})
22392 If this ^switch^option^ is provided and @var{number} is not 0, then
22393 @code{gnathtml} will number the html files every @var{number} line.
22394
22395 @item -I @var{dir}
22396 @cindex @option{-I} (@code{gnathtml})
22397 Specify a directory to search for library files (@file{.ALI} files) and
22398 source files. You can provide several -I switches on the command line,
22399 and the directories will be parsed in the order of the command line.
22400
22401 @item -o @var{dir}
22402 @cindex @option{-o} (@code{gnathtml})
22403 Specify the output directory for html files. By default, gnathtml will
22404 saved the generated html files in a subdirectory named @file{html/}.
22405
22406 @item -p @var{file}
22407 @cindex @option{-p} (@code{gnathtml})
22408 If you are using Emacs and the most recent Emacs Ada mode, which provides
22409 a full Integrated Development Environment for compiling, checking,
22410 running and debugging applications, you may use @file{.gpr} files
22411 to give the directories where Emacs can find sources and object files.
22412
22413 Using this ^switch^option^, you can tell gnathtml to use these files.
22414 This allows you to get an html version of your application, even if it
22415 is spread over multiple directories.
22416
22417 @item -sc @var{color}
22418 @cindex @option{-sc} (@code{gnathtml})
22419 This ^switch^option^ allows you to change the color used for symbol
22420 definitions.
22421 The default value is red. The color argument can be any name accepted by html.
22422
22423 @item -t @var{file}
22424 @cindex @option{-t} (@code{gnathtml})
22425 This ^switch^option^ provides the name of a file. This file contains a list of
22426 file names to be converted, and the effect is exactly as though they had
22427 appeared explicitly on the command line. This
22428 is the recommended way to work around the command line length limit on some
22429 systems.
22430
22431 @end table
22432
22433 @node Installing gnathtml
22434 @section Installing @code{gnathtml}
22435
22436 @noindent
22437 @code{Perl} needs to be installed on your machine to run this script.
22438 @code{Perl} is freely available for almost every architecture and
22439 Operating System via the Internet.
22440
22441 On Unix systems, you  may want to modify  the  first line of  the script
22442 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
22443 is. The syntax of this line is:
22444 @smallexample
22445 #!full_path_name_to_perl
22446 @end smallexample
22447
22448 @noindent
22449 Alternatively, you may run the script using the following command line:
22450
22451 @smallexample
22452 $ perl gnathtml.pl @ovar{switches} @var{files}
22453 @end smallexample
22454
22455 @ifset vms
22456 @node LSE
22457 @section LSE
22458 @findex LSE
22459
22460 @noindent
22461 The GNAT distribution provides an Ada 95 template for the HP Language
22462 Sensitive Editor (LSE), a component of DECset. In order to
22463 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
22464
22465 @node Profiling
22466 @section Profiling
22467 @findex PCA
22468
22469 @noindent
22470 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
22471 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
22472 the collection phase with the /DEBUG qualifier.
22473
22474 @smallexample
22475 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
22476 $ DEFINE LIB$DEBUG PCA$COLLECTOR
22477 $ RUN/DEBUG <PROGRAM_NAME>
22478 @end smallexample
22479 @noindent
22480 @end ifset
22481
22482 @ifclear vms
22483 @c ******************************
22484 @node Code Coverage and Profiling
22485 @chapter Code Coverage and Profiling
22486 @cindex Code Coverage
22487 @cindex Profiling
22488
22489 @noindent
22490 This chapter describes how to use @code{gcov} - coverage testing tool - and
22491 @code{gprof} - profiler tool - on your Ada programs.
22492
22493 @menu
22494 * Code Coverage of Ada Programs using gcov::
22495 * Profiling an Ada Program using gprof::
22496 @end menu
22497
22498 @node Code Coverage of Ada Programs using gcov
22499 @section Code Coverage of Ada Programs using gcov
22500 @cindex gcov
22501 @cindex -fprofile-arcs
22502 @cindex -ftest-coverage
22503 @cindex -coverage
22504 @cindex Code Coverage
22505
22506 @noindent
22507 @code{gcov} is a test coverage program: it analyzes the execution of a given
22508 program on selected tests, to help you determine the portions of the program
22509 that are still untested.
22510
22511 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
22512 User's Guide. You can refer to this documentation for a more complete
22513 description.
22514
22515 This chapter provides a quick startup guide, and
22516 details some Gnat-specific features.
22517
22518 @menu
22519 * Quick startup guide::
22520 * Gnat specifics::
22521 @end menu
22522
22523 @node Quick startup guide
22524 @subsection Quick startup guide
22525
22526 In order to perform coverage analysis of a program using @code{gcov}, 3
22527 steps are needed:
22528
22529 @itemize @bullet
22530 @item
22531 Code instrumentation during the compilation process
22532 @item
22533 Execution of the instrumented program
22534 @item
22535 Execution of the @code{gcov} tool to generate the result.
22536 @end itemize
22537
22538 The code instrumentation needed by gcov is created at the object level:
22539 The source code is not modified in any way, because the instrumentation code is
22540 inserted by gcc during the compilation process. To compile your code with code
22541 coverage activated, you need to recompile your whole project using the
22542 switches
22543 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
22544 @code{-fprofile-arcs}.
22545
22546 @smallexample
22547 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
22548    -largs -fprofile-arcs
22549 @end smallexample
22550
22551 This compilation process will create @file{.gcno} files together with
22552 the usual object files.
22553
22554 Once the program is compiled with coverage instrumentation, you can
22555 run it as many times as needed - on portions of a test suite for
22556 example. The first execution will produce @file{.gcda} files at the
22557 same location as the @file{.gcno} files.  The following executions
22558 will update those files, so that a cumulative result of the covered
22559 portions of the program is generated.
22560
22561 Finally, you need to call the @code{gcov} tool. The different options of
22562 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
22563
22564 This will create annotated source files with a @file{.gcov} extension:
22565 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
22566
22567 @node Gnat specifics
22568 @subsection Gnat specifics
22569
22570 Because Ada semantics, portions of the source code may be shared among
22571 several object files. This is the case for example when generics are
22572 involved, when inlining is active  or when declarations generate  initialisation
22573 calls. In order to take
22574 into account this shared code, you need to call @code{gcov} on all
22575 source files of the tested program at once.
22576
22577 The list of source files might exceed the system's maximum command line
22578 length. In order to bypass this limitation, a new mechanism has been
22579 implemented in @code{gcov}: you can now list all your project's files into a
22580 text file, and provide this file to gcov as a parameter,  preceded by a @@
22581 (e.g. @samp{gcov @@mysrclist.txt}).
22582
22583 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
22584 not supported as there can be unresolved symbols during the final link.
22585
22586 @node Profiling an Ada Program using gprof
22587 @section Profiling an Ada Program using gprof
22588 @cindex gprof
22589 @cindex -pg
22590 @cindex Profiling
22591
22592 @noindent
22593 This section is not meant to be an exhaustive documentation of @code{gprof}.
22594 Full documentation for it can be found in the GNU Profiler User's Guide
22595 documentation that is part of this GNAT distribution.
22596
22597 Profiling a program helps determine the parts of a program that are executed
22598 most often, and are therefore the most time-consuming.
22599
22600 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
22601 better handle Ada programs and multitasking.
22602 It is currently supported on the following platforms
22603 @itemize @bullet
22604 @item
22605 linux x86/x86_64
22606 @item
22607 solaris sparc/sparc64/x86
22608 @item
22609 windows x86
22610 @end itemize
22611
22612 @noindent
22613 In order to profile a program using @code{gprof}, 3 steps are needed:
22614
22615 @itemize @bullet
22616 @item
22617 Code instrumentation, requiring a full recompilation of the project with the
22618 proper switches.
22619 @item
22620 Execution of the program under the analysis conditions, i.e. with the desired
22621 input.
22622 @item
22623 Analysis of the results using the @code{gprof} tool.
22624 @end itemize
22625
22626 @noindent
22627 The following sections detail the different steps, and indicate how
22628 to interpret the results:
22629 @menu
22630 * Compilation for profiling::
22631 * Program execution::
22632 * Running gprof::
22633 * Interpretation of profiling results::
22634 @end menu
22635
22636 @node Compilation for profiling
22637 @subsection Compilation for profiling
22638 @cindex -pg
22639 @cindex Profiling
22640
22641 In order to profile a program the first step is to tell the compiler
22642 to generate the necessary profiling information. The compiler switch to be used
22643 is @code{-pg}, which must be added to other compilation switches. This
22644 switch needs to be specified both during compilation and link stages, and can
22645 be specified once when using gnatmake:
22646
22647 @smallexample
22648 gnatmake -f -pg -P my_project
22649 @end smallexample
22650
22651 @noindent
22652 Note that only the objects that were compiled with the @samp{-pg} switch will be
22653 profiled; if you need to profile your whole project, use the
22654 @samp{-f} gnatmake switch to force full recompilation.
22655
22656 @node Program execution
22657 @subsection Program execution
22658
22659 @noindent
22660 Once the program has been compiled for profiling, you can run it as usual.
22661
22662 The only constraint imposed by profiling is that the program must terminate
22663 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
22664 properly analyzed.
22665
22666 Once the program completes execution, a data file called @file{gmon.out} is
22667 generated in the directory where the program was launched from. If this file
22668 already exists, it will be overwritten.
22669
22670 @node Running gprof
22671 @subsection Running gprof
22672
22673 @noindent
22674 The @code{gprof} tool is called as follow:
22675
22676 @smallexample
22677 gprof my_prog gmon.out
22678 @end smallexample
22679
22680 @noindent
22681 or simpler:
22682
22683 @smallexample
22684 gprof my_prog
22685 @end smallexample
22686
22687 @noindent
22688 The complete form of the gprof command line is the following:
22689
22690 @smallexample
22691 gprof [^switches^options^] [executable [data-file]]
22692 @end smallexample
22693
22694 @noindent
22695 @code{gprof} supports numerous ^switch^options^. The order of these
22696 ^switch^options^ does not matter. The full list of options can be found in
22697 the GNU Profiler User's Guide documentation that comes with this documentation.
22698
22699 The following is the subset of those switches that is most relevant:
22700
22701 @table @option
22702
22703 @item --demangle[=@var{style}]
22704 @itemx --no-demangle
22705 @cindex @option{--demangle} (@code{gprof})
22706 These options control whether symbol names should be demangled when
22707 printing output.  The default is to demangle C++ symbols.  The
22708 @code{--no-demangle} option may be used to turn off demangling. Different
22709 compilers have different mangling styles.  The optional demangling style
22710 argument can be used to choose an appropriate demangling style for your
22711 compiler, in particular Ada symbols generated by GNAT can be demangled using
22712 @code{--demangle=gnat}.
22713
22714 @item -e @var{function_name}
22715 @cindex @option{-e} (@code{gprof})
22716 The @samp{-e @var{function}} option tells @code{gprof} not to print
22717 information about the function @var{function_name} (and its
22718 children@dots{}) in the call graph.  The function will still be listed
22719 as a child of any functions that call it, but its index number will be
22720 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
22721 given; only one @var{function_name} may be indicated with each @samp{-e}
22722 option.
22723
22724 @item -E @var{function_name}
22725 @cindex @option{-E} (@code{gprof})
22726 The @code{-E @var{function}} option works like the @code{-e} option, but
22727 execution time spent in the function (and children who were not called from
22728 anywhere else), will not be used to compute the percentages-of-time for
22729 the call graph.  More than one @samp{-E} option may be given; only one
22730 @var{function_name} may be indicated with each @samp{-E} option.
22731
22732 @item -f @var{function_name}
22733 @cindex @option{-f} (@code{gprof})
22734 The @samp{-f @var{function}} option causes @code{gprof} to limit the
22735 call graph to the function @var{function_name} and its children (and
22736 their children@dots{}).  More than one @samp{-f} option may be given;
22737 only one @var{function_name} may be indicated with each @samp{-f}
22738 option.
22739
22740 @item -F @var{function_name}
22741 @cindex @option{-F} (@code{gprof})
22742 The @samp{-F @var{function}} option works like the @code{-f} option, but
22743 only time spent in the function and its children (and their
22744 children@dots{}) will be used to determine total-time and
22745 percentages-of-time for the call graph.  More than one @samp{-F} option
22746 may be given; only one @var{function_name} may be indicated with each
22747 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
22748
22749 @end table
22750
22751 @node Interpretation of profiling results
22752 @subsection Interpretation of profiling results
22753
22754 @noindent
22755
22756 The results of the profiling analysis are represented by two arrays: the
22757 'flat profile' and the 'call graph'. Full documentation of those outputs
22758 can be found in the GNU Profiler User's Guide.
22759
22760 The flat profile shows the time spent in each function of the program, and how
22761 many time it has been called. This allows you to locate easily the most
22762 time-consuming functions.
22763
22764 The call graph shows, for each subprogram, the subprograms that call it,
22765 and the subprograms that it calls. It also provides an estimate of the time
22766 spent in each of those callers/called subprograms.
22767 @end ifclear
22768
22769 @c ******************************
22770 @node Running and Debugging Ada Programs
22771 @chapter Running and Debugging Ada Programs
22772 @cindex Debugging
22773
22774 @noindent
22775 This chapter discusses how to debug Ada programs.
22776 @ifset vms
22777 It applies to GNAT on the Alpha OpenVMS platform;
22778 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
22779 since HP has implemented Ada support in the OpenVMS debugger on I64.
22780 @end ifset
22781
22782 An incorrect Ada program may be handled in three ways by the GNAT compiler:
22783
22784 @enumerate
22785 @item
22786 The illegality may be a violation of the static semantics of Ada. In
22787 that case GNAT diagnoses the constructs in the program that are illegal.
22788 It is then a straightforward matter for the user to modify those parts of
22789 the program.
22790
22791 @item
22792 The illegality may be a violation of the dynamic semantics of Ada. In
22793 that case the program compiles and executes, but may generate incorrect
22794 results, or may terminate abnormally with some exception.
22795
22796 @item
22797 When presented with a program that contains convoluted errors, GNAT
22798 itself may terminate abnormally without providing full diagnostics on
22799 the incorrect user program.
22800 @end enumerate
22801
22802 @menu
22803 * The GNAT Debugger GDB::
22804 * Running GDB::
22805 * Introduction to GDB Commands::
22806 * Using Ada Expressions::
22807 * Calling User-Defined Subprograms::
22808 * Using the Next Command in a Function::
22809 * Ada Exceptions::
22810 * Ada Tasks::
22811 * Debugging Generic Units::
22812 * GNAT Abnormal Termination or Failure to Terminate::
22813 * Naming Conventions for GNAT Source Files::
22814 * Getting Internal Debugging Information::
22815 * Stack Traceback::
22816 @end menu
22817
22818 @cindex Debugger
22819 @findex gdb
22820
22821 @node The GNAT Debugger GDB
22822 @section The GNAT Debugger GDB
22823
22824 @noindent
22825 @code{GDB} is a general purpose, platform-independent debugger that
22826 can be used to debug mixed-language programs compiled with @command{gcc},
22827 and in particular is capable of debugging Ada programs compiled with
22828 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
22829 complex Ada data structures.
22830
22831 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
22832 @ifset vms
22833 located in the GNU:[DOCS] directory,
22834 @end ifset
22835 for full details on the usage of @code{GDB}, including a section on
22836 its usage on programs. This manual should be consulted for full
22837 details. The section that follows is a brief introduction to the
22838 philosophy and use of @code{GDB}.
22839
22840 When GNAT programs are compiled, the compiler optionally writes debugging
22841 information into the generated object file, including information on
22842 line numbers, and on declared types and variables. This information is
22843 separate from the generated code. It makes the object files considerably
22844 larger, but it does not add to the size of the actual executable that
22845 will be loaded into memory, and has no impact on run-time performance. The
22846 generation of debug information is triggered by the use of the
22847 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
22848 used to carry out the compilations. It is important to emphasize that
22849 the use of these options does not change the generated code.
22850
22851 The debugging information is written in standard system formats that
22852 are used by many tools, including debuggers and profilers. The format
22853 of the information is typically designed to describe C types and
22854 semantics, but GNAT implements a translation scheme which allows full
22855 details about Ada types and variables to be encoded into these
22856 standard C formats. Details of this encoding scheme may be found in
22857 the file exp_dbug.ads in the GNAT source distribution. However, the
22858 details of this encoding are, in general, of no interest to a user,
22859 since @code{GDB} automatically performs the necessary decoding.
22860
22861 When a program is bound and linked, the debugging information is
22862 collected from the object files, and stored in the executable image of
22863 the program. Again, this process significantly increases the size of
22864 the generated executable file, but it does not increase the size of
22865 the executable program itself. Furthermore, if this program is run in
22866 the normal manner, it runs exactly as if the debug information were
22867 not present, and takes no more actual memory.
22868
22869 However, if the program is run under control of @code{GDB}, the
22870 debugger is activated.  The image of the program is loaded, at which
22871 point it is ready to run.  If a run command is given, then the program
22872 will run exactly as it would have if @code{GDB} were not present. This
22873 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
22874 entirely non-intrusive until a breakpoint is encountered.  If no
22875 breakpoint is ever hit, the program will run exactly as it would if no
22876 debugger were present. When a breakpoint is hit, @code{GDB} accesses
22877 the debugging information and can respond to user commands to inspect
22878 variables, and more generally to report on the state of execution.
22879
22880 @c **************
22881 @node Running GDB
22882 @section Running GDB
22883
22884 @noindent
22885 This section describes how to initiate the debugger.
22886 @c The above sentence is really just filler, but it was otherwise
22887 @c clumsy to get the first paragraph nonindented given the conditional
22888 @c nature of the description
22889
22890 @ifclear vms
22891 The debugger can be launched from a @code{GPS} menu or
22892 directly from the command line. The description below covers the latter use.
22893 All the commands shown can be used in the @code{GPS} debug console window,
22894 but there are usually more GUI-based ways to achieve the same effect.
22895 @end ifclear
22896
22897 The command to run @code{GDB} is
22898
22899 @smallexample
22900 $ ^gdb program^GDB PROGRAM^
22901 @end smallexample
22902
22903 @noindent
22904 where @code{^program^PROGRAM^} is the name of the executable file. This
22905 activates the debugger and results in a prompt for debugger commands.
22906 The simplest command is simply @code{run}, which causes the program to run
22907 exactly as if the debugger were not present. The following section
22908 describes some of the additional commands that can be given to @code{GDB}.
22909
22910 @c *******************************
22911 @node Introduction to GDB Commands
22912 @section Introduction to GDB Commands
22913
22914 @noindent
22915 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
22916 Debugging with GDB, gdb, Debugging with GDB},
22917 @ifset vms
22918 located in the GNU:[DOCS] directory,
22919 @end ifset
22920 for extensive documentation on the use
22921 of these commands, together with examples of their use. Furthermore,
22922 the command @command{help} invoked from within GDB activates a simple help
22923 facility which summarizes the available commands and their options.
22924 In this section we summarize a few of the most commonly
22925 used commands to give an idea of what @code{GDB} is about. You should create
22926 a simple program with debugging information and experiment with the use of
22927 these @code{GDB} commands on the program as you read through the
22928 following section.
22929
22930 @table @code
22931 @item set args @var{arguments}
22932 The @var{arguments} list above is a list of arguments to be passed to
22933 the program on a subsequent run command, just as though the arguments
22934 had been entered on a normal invocation of the program. The @code{set args}
22935 command is not needed if the program does not require arguments.
22936
22937 @item run
22938 The @code{run} command causes execution of the program to start from
22939 the beginning. If the program is already running, that is to say if
22940 you are currently positioned at a breakpoint, then a prompt will ask
22941 for confirmation that you want to abandon the current execution and
22942 restart.
22943
22944 @item breakpoint @var{location}
22945 The breakpoint command sets a breakpoint, that is to say a point at which
22946 execution will halt and @code{GDB} will await further
22947 commands. @var{location} is
22948 either a line number within a file, given in the format @code{file:linenumber},
22949 or it is the name of a subprogram. If you request that a breakpoint be set on
22950 a subprogram that is overloaded, a prompt will ask you to specify on which of
22951 those subprograms you want to breakpoint. You can also
22952 specify that all of them should be breakpointed. If the program is run
22953 and execution encounters the breakpoint, then the program
22954 stops and @code{GDB} signals that the breakpoint was encountered by
22955 printing the line of code before which the program is halted.
22956
22957 @item breakpoint exception @var{name}
22958 A special form of the breakpoint command which breakpoints whenever
22959 exception @var{name} is raised.
22960 If @var{name} is omitted,
22961 then a breakpoint will occur when any exception is raised.
22962
22963 @item print @var{expression}
22964 This will print the value of the given expression. Most simple
22965 Ada expression formats are properly handled by @code{GDB}, so the expression
22966 can contain function calls, variables, operators, and attribute references.
22967
22968 @item continue
22969 Continues execution following a breakpoint, until the next breakpoint or the
22970 termination of the program.
22971
22972 @item step
22973 Executes a single line after a breakpoint. If the next statement
22974 is a subprogram call, execution continues into (the first statement of)
22975 the called subprogram.
22976
22977 @item next
22978 Executes a single line. If this line is a subprogram call, executes and
22979 returns from the call.
22980
22981 @item list
22982 Lists a few lines around the current source location. In practice, it
22983 is usually more convenient to have a separate edit window open with the
22984 relevant source file displayed. Successive applications of this command
22985 print subsequent lines. The command can be given an argument which is a
22986 line number, in which case it displays a few lines around the specified one.
22987
22988 @item backtrace
22989 Displays a backtrace of the call chain. This command is typically
22990 used after a breakpoint has occurred, to examine the sequence of calls that
22991 leads to the current breakpoint. The display includes one line for each
22992 activation record (frame) corresponding to an active subprogram.
22993
22994 @item up
22995 At a breakpoint, @code{GDB} can display the values of variables local
22996 to the current frame. The command @code{up} can be used to
22997 examine the contents of other active frames, by moving the focus up
22998 the stack, that is to say from callee to caller, one frame at a time.
22999
23000 @item down
23001 Moves the focus of @code{GDB} down from the frame currently being
23002 examined to the frame of its callee (the reverse of the previous command),
23003
23004 @item frame @var{n}
23005 Inspect the frame with the given number. The value 0 denotes the frame
23006 of the current breakpoint, that is to say the top of the call stack.
23007
23008 @end table
23009
23010 @noindent
23011 The above list is a very short introduction to the commands that
23012 @code{GDB} provides. Important additional capabilities, including conditional
23013 breakpoints, the ability to execute command sequences on a breakpoint,
23014 the ability to debug at the machine instruction level and many other
23015 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
23016 Debugging with GDB}.  Note that most commands can be abbreviated
23017 (for example, c for continue, bt for backtrace).
23018
23019 @node Using Ada Expressions
23020 @section Using Ada Expressions
23021 @cindex Ada expressions
23022
23023 @noindent
23024 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
23025 extensions. The philosophy behind the design of this subset is
23026
23027 @itemize @bullet
23028 @item
23029 That @code{GDB} should provide basic literals and access to operations for
23030 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
23031 leaving more sophisticated computations to subprograms written into the
23032 program (which therefore may be called from @code{GDB}).
23033
23034 @item
23035 That type safety and strict adherence to Ada language restrictions
23036 are not particularly important to the @code{GDB} user.
23037
23038 @item
23039 That brevity is important to the @code{GDB} user.
23040 @end itemize
23041
23042 @noindent
23043 Thus, for brevity, the debugger acts as if there were
23044 implicit @code{with} and @code{use} clauses in effect for all user-written
23045 packages, thus making it unnecessary to fully qualify most names with
23046 their packages, regardless of context. Where this causes ambiguity,
23047 @code{GDB} asks the user's intent.
23048
23049 For details on the supported Ada syntax, see @ref{Top,, Debugging with
23050 GDB, gdb, Debugging with GDB}.
23051
23052 @node Calling User-Defined Subprograms
23053 @section Calling User-Defined Subprograms
23054
23055 @noindent
23056 An important capability of @code{GDB} is the ability to call user-defined
23057 subprograms while debugging. This is achieved simply by entering
23058 a subprogram call statement in the form:
23059
23060 @smallexample
23061 call subprogram-name (parameters)
23062 @end smallexample
23063
23064 @noindent
23065 The keyword @code{call} can be omitted in the normal case where the
23066 @code{subprogram-name} does not coincide with any of the predefined
23067 @code{GDB} commands.
23068
23069 The effect is to invoke the given subprogram, passing it the
23070 list of parameters that is supplied. The parameters can be expressions and
23071 can include variables from the program being debugged. The
23072 subprogram must be defined
23073 at the library level within your program, and @code{GDB} will call the
23074 subprogram within the environment of your program execution (which
23075 means that the subprogram is free to access or even modify variables
23076 within your program).
23077
23078 The most important use of this facility is in allowing the inclusion of
23079 debugging routines that are tailored to particular data structures
23080 in your program. Such debugging routines can be written to provide a suitably
23081 high-level description of an abstract type, rather than a low-level dump
23082 of its physical layout. After all, the standard
23083 @code{GDB print} command only knows the physical layout of your
23084 types, not their abstract meaning. Debugging routines can provide information
23085 at the desired semantic level and are thus enormously useful.
23086
23087 For example, when debugging GNAT itself, it is crucial to have access to
23088 the contents of the tree nodes used to represent the program internally.
23089 But tree nodes are represented simply by an integer value (which in turn
23090 is an index into a table of nodes).
23091 Using the @code{print} command on a tree node would simply print this integer
23092 value, which is not very useful. But the PN routine (defined in file
23093 treepr.adb in the GNAT sources) takes a tree node as input, and displays
23094 a useful high level representation of the tree node, which includes the
23095 syntactic category of the node, its position in the source, the integers
23096 that denote descendant nodes and parent node, as well as varied
23097 semantic information. To study this example in more detail, you might want to
23098 look at the body of the PN procedure in the stated file.
23099
23100 @node Using the Next Command in a Function
23101 @section Using the Next Command in a Function
23102
23103 @noindent
23104 When you use the @code{next} command in a function, the current source
23105 location will advance to the next statement as usual. A special case
23106 arises in the case of a @code{return} statement.
23107
23108 Part of the code for a return statement is the ``epilog'' of the function.
23109 This is the code that returns to the caller. There is only one copy of
23110 this epilog code, and it is typically associated with the last return
23111 statement in the function if there is more than one return. In some
23112 implementations, this epilog is associated with the first statement
23113 of the function.
23114
23115 The result is that if you use the @code{next} command from a return
23116 statement that is not the last return statement of the function you
23117 may see a strange apparent jump to the last return statement or to
23118 the start of the function. You should simply ignore this odd jump.
23119 The value returned is always that from the first return statement
23120 that was stepped through.
23121
23122 @node Ada Exceptions
23123 @section Breaking on Ada Exceptions
23124 @cindex Exceptions
23125
23126 @noindent
23127 You can set breakpoints that trip when your program raises
23128 selected exceptions.
23129
23130 @table @code
23131 @item break exception
23132 Set a breakpoint that trips whenever (any task in the) program raises
23133 any exception.
23134
23135 @item break exception @var{name}
23136 Set a breakpoint that trips whenever (any task in the) program raises
23137 the exception @var{name}.
23138
23139 @item break exception unhandled
23140 Set a breakpoint that trips whenever (any task in the) program raises an
23141 exception for which there is no handler.
23142
23143 @item info exceptions
23144 @itemx info exceptions @var{regexp}
23145 The @code{info exceptions} command permits the user to examine all defined
23146 exceptions within Ada programs. With a regular expression, @var{regexp}, as
23147 argument, prints out only those exceptions whose name matches @var{regexp}.
23148 @end table
23149
23150 @node Ada Tasks
23151 @section Ada Tasks
23152 @cindex Tasks
23153
23154 @noindent
23155 @code{GDB} allows the following task-related commands:
23156
23157 @table @code
23158 @item info tasks
23159 This command shows a list of current Ada tasks, as in the following example:
23160
23161 @smallexample
23162 @iftex
23163 @leftskip=0cm
23164 @end iftex
23165 (gdb) info tasks
23166   ID       TID P-ID   Thread Pri State                 Name
23167    1   8088000   0   807e000  15 Child Activation Wait main_task
23168    2   80a4000   1   80ae000  15 Accept/Select Wait    b
23169    3   809a800   1   80a4800  15 Child Activation Wait a
23170 *  4   80ae800   3   80b8000  15 Running               c
23171 @end smallexample
23172
23173 @noindent
23174 In this listing, the asterisk before the first task indicates it to be the
23175 currently running task. The first column lists the task ID that is used
23176 to refer to tasks in the following commands.
23177
23178 @item break @var{linespec} task @var{taskid}
23179 @itemx break @var{linespec} task @var{taskid} if @dots{}
23180 @cindex Breakpoints and tasks
23181 These commands are like the @code{break @dots{} thread @dots{}}.
23182 @var{linespec} specifies source lines.
23183
23184 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
23185 to specify that you only want @code{GDB} to stop the program when a
23186 particular Ada task reaches this breakpoint. @var{taskid} is one of the
23187 numeric task identifiers assigned by @code{GDB}, shown in the first
23188 column of the @samp{info tasks} display.
23189
23190 If you do not specify @samp{task @var{taskid}} when you set a
23191 breakpoint, the breakpoint applies to @emph{all} tasks of your
23192 program.
23193
23194 You can use the @code{task} qualifier on conditional breakpoints as
23195 well; in this case, place @samp{task @var{taskid}} before the
23196 breakpoint condition (before the @code{if}).
23197
23198 @item task @var{taskno}
23199 @cindex Task switching
23200
23201 This command allows to switch to the task referred by @var{taskno}. In
23202 particular, This allows to browse the backtrace of the specified
23203 task. It is advised to switch back to the original task before
23204 continuing execution otherwise the scheduling of the program may be
23205 perturbed.
23206 @end table
23207
23208 @noindent
23209 For more detailed information on the tasking support,
23210 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
23211
23212 @node Debugging Generic Units
23213 @section Debugging Generic Units
23214 @cindex Debugging Generic Units
23215 @cindex Generics
23216
23217 @noindent
23218 GNAT always uses code expansion for generic instantiation. This means that
23219 each time an instantiation occurs, a complete copy of the original code is
23220 made, with appropriate substitutions of formals by actuals.
23221
23222 It is not possible to refer to the original generic entities in
23223 @code{GDB}, but it is always possible to debug a particular instance of
23224 a generic, by using the appropriate expanded names. For example, if we have
23225
23226 @smallexample @c ada
23227 @group
23228 @cartouche
23229 procedure g is
23230
23231    generic package k is
23232       procedure kp (v1 : in out integer);
23233    end k;
23234
23235    package body k is
23236       procedure kp (v1 : in out integer) is
23237       begin
23238          v1 := v1 + 1;
23239       end kp;
23240    end k;
23241
23242    package k1 is new k;
23243    package k2 is new k;
23244
23245    var : integer := 1;
23246
23247 begin
23248    k1.kp (var);
23249    k2.kp (var);
23250    k1.kp (var);
23251    k2.kp (var);
23252 end;
23253 @end cartouche
23254 @end group
23255 @end smallexample
23256
23257 @noindent
23258 Then to break on a call to procedure kp in the k2 instance, simply
23259 use the command:
23260
23261 @smallexample
23262 (gdb) break g.k2.kp
23263 @end smallexample
23264
23265 @noindent
23266 When the breakpoint occurs, you can step through the code of the
23267 instance in the normal manner and examine the values of local variables, as for
23268 other units.
23269
23270 @node GNAT Abnormal Termination or Failure to Terminate
23271 @section GNAT Abnormal Termination or Failure to Terminate
23272 @cindex GNAT Abnormal Termination or Failure to Terminate
23273
23274 @noindent
23275 When presented with programs that contain serious errors in syntax
23276 or semantics,
23277 GNAT may on rare occasions  experience problems in operation, such
23278 as aborting with a
23279 segmentation fault or illegal memory access, raising an internal
23280 exception, terminating abnormally, or failing to terminate at all.
23281 In such cases, you can activate
23282 various features of GNAT that can help you pinpoint the construct in your
23283 program that is the likely source of the problem.
23284
23285 The following strategies are presented in increasing order of
23286 difficulty, corresponding to your experience in using GNAT and your
23287 familiarity with compiler internals.
23288
23289 @enumerate
23290 @item
23291 Run @command{gcc} with the @option{-gnatf}. This first
23292 switch causes all errors on a given line to be reported. In its absence,
23293 only the first error on a line is displayed.
23294
23295 The @option{-gnatdO} switch causes errors to be displayed as soon as they
23296 are encountered, rather than after compilation is terminated. If GNAT
23297 terminates prematurely or goes into an infinite loop, the last error
23298 message displayed may help to pinpoint the culprit.
23299
23300 @item
23301 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
23302 mode, @command{gcc} produces ongoing information about the progress of the
23303 compilation and provides the name of each procedure as code is
23304 generated. This switch allows you to find which Ada procedure was being
23305 compiled when it encountered a code generation problem.
23306
23307 @item
23308 @cindex @option{-gnatdc} switch
23309 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
23310 switch that does for the front-end what @option{^-v^VERBOSE^} does
23311 for the back end. The system prints the name of each unit,
23312 either a compilation unit or nested unit, as it is being analyzed.
23313 @item
23314 Finally, you can start
23315 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
23316 front-end of GNAT, and can be run independently (normally it is just
23317 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
23318 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
23319 @code{where} command is the first line of attack; the variable
23320 @code{lineno} (seen by @code{print lineno}), used by the second phase of
23321 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
23322 which the execution stopped, and @code{input_file name} indicates the name of
23323 the source file.
23324 @end enumerate
23325
23326 @node Naming Conventions for GNAT Source Files
23327 @section Naming Conventions for GNAT Source Files
23328
23329 @noindent
23330 In order to examine the workings of the GNAT system, the following
23331 brief description of its organization may be helpful:
23332
23333 @itemize @bullet
23334 @item
23335 Files with prefix @file{^sc^SC^} contain the lexical scanner.
23336
23337 @item
23338 All files prefixed with @file{^par^PAR^} are components of the parser. The
23339 numbers correspond to chapters of the Ada Reference Manual. For example,
23340 parsing of select statements can be found in @file{par-ch9.adb}.
23341
23342 @item
23343 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
23344 numbers correspond to chapters of the Ada standard. For example, all
23345 issues involving context clauses can be found in @file{sem_ch10.adb}. In
23346 addition, some features of the language require sufficient special processing
23347 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
23348 dynamic dispatching, etc.
23349
23350 @item
23351 All files prefixed with @file{^exp^EXP^} perform normalization and
23352 expansion of the intermediate representation (abstract syntax tree, or AST).
23353 these files use the same numbering scheme as the parser and semantics files.
23354 For example, the construction of record initialization procedures is done in
23355 @file{exp_ch3.adb}.
23356
23357 @item
23358 The files prefixed with @file{^bind^BIND^} implement the binder, which
23359 verifies the consistency of the compilation, determines an order of
23360 elaboration, and generates the bind file.
23361
23362 @item
23363 The files @file{atree.ads} and @file{atree.adb} detail the low-level
23364 data structures used by the front-end.
23365
23366 @item
23367 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
23368 the abstract syntax tree as produced by the parser.
23369
23370 @item
23371 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
23372 all entities, computed during semantic analysis.
23373
23374 @item
23375 Library management issues are dealt with in files with prefix
23376 @file{^lib^LIB^}.
23377
23378 @item
23379 @findex Ada
23380 @cindex Annex A
23381 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
23382 defined in Annex A.
23383
23384 @item
23385 @findex Interfaces
23386 @cindex Annex B
23387 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
23388 defined in Annex B.
23389
23390 @item
23391 @findex System
23392 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
23393 both language-defined children and GNAT run-time routines.
23394
23395 @item
23396 @findex GNAT
23397 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
23398 general-purpose packages, fully documented in their specs. All
23399 the other @file{.c} files are modifications of common @command{gcc} files.
23400 @end itemize
23401
23402 @node Getting Internal Debugging Information
23403 @section Getting Internal Debugging Information
23404
23405 @noindent
23406 Most compilers have internal debugging switches and modes. GNAT
23407 does also, except GNAT internal debugging switches and modes are not
23408 secret. A summary and full description of all the compiler and binder
23409 debug flags are in the file @file{debug.adb}. You must obtain the
23410 sources of the compiler to see the full detailed effects of these flags.
23411
23412 The switches that print the source of the program (reconstructed from
23413 the internal tree) are of general interest for user programs, as are the
23414 options to print
23415 the full internal tree, and the entity table (the symbol table
23416 information). The reconstructed source provides a readable version of the
23417 program after the front-end has completed analysis and  expansion,
23418 and is useful when studying the performance of specific constructs.
23419 For example, constraint checks are indicated, complex aggregates
23420 are replaced with loops and assignments, and tasking primitives
23421 are replaced with run-time calls.
23422
23423 @node Stack Traceback
23424 @section Stack Traceback
23425 @cindex traceback
23426 @cindex stack traceback
23427 @cindex stack unwinding
23428
23429 @noindent
23430 Traceback is a mechanism to display the sequence of subprogram calls that
23431 leads to a specified execution point in a program. Often (but not always)
23432 the execution point is an instruction at which an exception has been raised.
23433 This mechanism is also known as @i{stack unwinding} because it obtains
23434 its information by scanning the run-time stack and recovering the activation
23435 records of all active subprograms. Stack unwinding is one of the most
23436 important tools for program debugging.
23437
23438 The first entry stored in traceback corresponds to the deepest calling level,
23439 that is to say the subprogram currently executing the instruction
23440 from which we want to obtain the traceback.
23441
23442 Note that there is no runtime performance penalty when stack traceback
23443 is enabled, and no exception is raised during program execution.
23444
23445 @menu
23446 * Non-Symbolic Traceback::
23447 * Symbolic Traceback::
23448 @end menu
23449
23450 @node Non-Symbolic Traceback
23451 @subsection Non-Symbolic Traceback
23452 @cindex traceback, non-symbolic
23453
23454 @noindent
23455 Note: this feature is not supported on all platforms. See
23456 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
23457 platforms.
23458
23459 @menu
23460 * Tracebacks From an Unhandled Exception::
23461 * Tracebacks From Exception Occurrences (non-symbolic)::
23462 * Tracebacks From Anywhere in a Program (non-symbolic)::
23463 @end menu
23464
23465 @node Tracebacks From an Unhandled Exception
23466 @subsubsection Tracebacks From an Unhandled Exception
23467
23468 @noindent
23469 A runtime non-symbolic traceback is a list of addresses of call instructions.
23470 To enable this feature you must use the @option{-E}
23471 @code{gnatbind}'s option. With this option a stack traceback is stored as part
23472 of exception information. You can retrieve this information using the
23473 @code{addr2line} tool.
23474
23475 Here is a simple example:
23476
23477 @smallexample @c ada
23478 @cartouche
23479 procedure STB is
23480
23481    procedure P1 is
23482    begin
23483       raise Constraint_Error;
23484    end P1;
23485
23486    procedure P2 is
23487    begin
23488       P1;
23489    end P2;
23490
23491 begin
23492    P2;
23493 end STB;
23494 @end cartouche
23495 @end smallexample
23496
23497 @smallexample
23498 $ gnatmake stb -bargs -E
23499 $ stb
23500
23501 Execution terminated by unhandled exception
23502 Exception name: CONSTRAINT_ERROR
23503 Message: stb.adb:5
23504 Call stack traceback locations:
23505 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
23506 @end smallexample
23507
23508 @noindent
23509 As we see the traceback lists a sequence of addresses for the unhandled
23510 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
23511 guess that this exception come from procedure P1. To translate these
23512 addresses into the source lines where the calls appear, the
23513 @code{addr2line} tool, described below, is invaluable. The use of this tool
23514 requires the program to be compiled with debug information.
23515
23516 @smallexample
23517 $ gnatmake -g stb -bargs -E
23518 $ stb
23519
23520 Execution terminated by unhandled exception
23521 Exception name: CONSTRAINT_ERROR
23522 Message: stb.adb:5
23523 Call stack traceback locations:
23524 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
23525
23526 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
23527    0x4011f1 0x77e892a4
23528
23529 00401373 at d:/stb/stb.adb:5
23530 0040138B at d:/stb/stb.adb:10
23531 0040139C at d:/stb/stb.adb:14
23532 00401335 at d:/stb/b~stb.adb:104
23533 004011C4 at /build/@dots{}/crt1.c:200
23534 004011F1 at /build/@dots{}/crt1.c:222
23535 77E892A4 in ?? at ??:0
23536 @end smallexample
23537
23538 @noindent
23539 The @code{addr2line} tool has several other useful options:
23540
23541 @table @code
23542 @item --functions
23543 to get the function name corresponding to any location
23544
23545 @item --demangle=gnat
23546 to use the gnat decoding mode for the function names. Note that
23547 for binutils version 2.9.x the option is simply @option{--demangle}.
23548 @end table
23549
23550 @smallexample
23551 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
23552    0x40139c 0x401335 0x4011c4 0x4011f1
23553
23554 00401373 in stb.p1 at d:/stb/stb.adb:5
23555 0040138B in stb.p2 at d:/stb/stb.adb:10
23556 0040139C in stb at d:/stb/stb.adb:14
23557 00401335 in main at d:/stb/b~stb.adb:104
23558 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
23559 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
23560 @end smallexample
23561
23562 @noindent
23563 From this traceback we can see that the exception was raised in
23564 @file{stb.adb} at line 5, which was reached from a procedure call in
23565 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
23566 which contains the call to the main program.
23567 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
23568 and the output will vary from platform to platform.
23569
23570 It is also possible to use @code{GDB} with these traceback addresses to debug
23571 the program. For example, we can break at a given code location, as reported
23572 in the stack traceback:
23573
23574 @smallexample
23575 $ gdb -nw stb
23576 @ifclear vms
23577 @noindent
23578 Furthermore, this feature is not implemented inside Windows DLL. Only
23579 the non-symbolic traceback is reported in this case.
23580 @end ifclear
23581
23582 (gdb) break *0x401373
23583 Breakpoint 1 at 0x401373: file stb.adb, line 5.
23584 @end smallexample
23585
23586 @noindent
23587 It is important to note that the stack traceback addresses
23588 do not change when debug information is included. This is particularly useful
23589 because it makes it possible to release software without debug information (to
23590 minimize object size), get a field report that includes a stack traceback
23591 whenever an internal bug occurs, and then be able to retrieve the sequence
23592 of calls with the same program compiled with debug information.
23593
23594 @node Tracebacks From Exception Occurrences (non-symbolic)
23595 @subsubsection Tracebacks From Exception Occurrences
23596
23597 @noindent
23598 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
23599 The stack traceback is attached to the exception information string, and can
23600 be retrieved in an exception handler within the Ada program, by means of the
23601 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
23602
23603 @smallexample @c ada
23604 with Ada.Text_IO;
23605 with Ada.Exceptions;
23606
23607 procedure STB is
23608
23609    use Ada;
23610    use Ada.Exceptions;
23611
23612    procedure P1 is
23613       K : Positive := 1;
23614    begin
23615       K := K - 1;
23616    exception
23617       when E : others =>
23618          Text_IO.Put_Line (Exception_Information (E));
23619    end P1;
23620
23621    procedure P2 is
23622    begin
23623       P1;
23624    end P2;
23625
23626 begin
23627    P2;
23628 end STB;
23629 @end smallexample
23630
23631 @noindent
23632 This program will output:
23633
23634 @smallexample
23635 $ stb
23636
23637 Exception name: CONSTRAINT_ERROR
23638 Message: stb.adb:12
23639 Call stack traceback locations:
23640 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
23641 @end smallexample
23642
23643 @node Tracebacks From Anywhere in a Program (non-symbolic)
23644 @subsubsection Tracebacks From Anywhere in a Program
23645
23646 @noindent
23647 It is also possible to retrieve a stack traceback from anywhere in a
23648 program. For this you need to
23649 use the @code{GNAT.Traceback} API. This package includes a procedure called
23650 @code{Call_Chain} that computes a complete stack traceback, as well as useful
23651 display procedures described below. It is not necessary to use the
23652 @option{-E gnatbind} option in this case, because the stack traceback mechanism
23653 is invoked explicitly.
23654
23655 @noindent
23656 In the following example we compute a traceback at a specific location in
23657 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
23658 convert addresses to strings:
23659
23660 @smallexample @c ada
23661 with Ada.Text_IO;
23662 with GNAT.Traceback;
23663 with GNAT.Debug_Utilities;
23664
23665 procedure STB is
23666
23667    use Ada;
23668    use GNAT;
23669    use GNAT.Traceback;
23670
23671    procedure P1 is
23672       TB  : Tracebacks_Array (1 .. 10);
23673       --  We are asking for a maximum of 10 stack frames.
23674       Len : Natural;
23675       --  Len will receive the actual number of stack frames returned.
23676    begin
23677       Call_Chain (TB, Len);
23678
23679       Text_IO.Put ("In STB.P1 : ");
23680
23681       for K in 1 .. Len loop
23682          Text_IO.Put (Debug_Utilities.Image (TB (K)));
23683          Text_IO.Put (' ');
23684       end loop;
23685
23686       Text_IO.New_Line;
23687    end P1;
23688
23689    procedure P2 is
23690    begin
23691       P1;
23692    end P2;
23693
23694 begin
23695    P2;
23696 end STB;
23697 @end smallexample
23698
23699 @smallexample
23700 $ gnatmake -g stb
23701 $ stb
23702
23703 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
23704 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
23705 @end smallexample
23706
23707 @noindent
23708 You can then get further information by invoking the @code{addr2line}
23709 tool as described earlier (note that the hexadecimal addresses
23710 need to be specified in C format, with a leading ``0x'').
23711
23712 @node Symbolic Traceback
23713 @subsection Symbolic Traceback
23714 @cindex traceback, symbolic
23715
23716 @noindent
23717 A symbolic traceback is a stack traceback in which procedure names are
23718 associated with each code location.
23719
23720 @noindent
23721 Note that this feature is not supported on all platforms. See
23722 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
23723 list of currently supported platforms.
23724
23725 @noindent
23726 Note that the symbolic traceback requires that the program be compiled
23727 with debug information. If it is not compiled with debug information
23728 only the non-symbolic information will be valid.
23729
23730 @menu
23731 * Tracebacks From Exception Occurrences (symbolic)::
23732 * Tracebacks From Anywhere in a Program (symbolic)::
23733 @end menu
23734
23735 @node Tracebacks From Exception Occurrences (symbolic)
23736 @subsubsection Tracebacks From Exception Occurrences
23737
23738 @smallexample @c ada
23739 with Ada.Text_IO;
23740 with GNAT.Traceback.Symbolic;
23741
23742 procedure STB is
23743
23744    procedure P1 is
23745    begin
23746       raise Constraint_Error;
23747    end P1;
23748
23749    procedure P2 is
23750    begin
23751       P1;
23752    end P2;
23753
23754    procedure P3 is
23755    begin
23756       P2;
23757    end P3;
23758
23759 begin
23760    P3;
23761 exception
23762    when E : others =>
23763       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
23764 end STB;
23765 @end smallexample
23766
23767 @smallexample
23768 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
23769 $ stb
23770
23771 0040149F in stb.p1 at stb.adb:8
23772 004014B7 in stb.p2 at stb.adb:13
23773 004014CF in stb.p3 at stb.adb:18
23774 004015DD in ada.stb at stb.adb:22
23775 00401461 in main at b~stb.adb:168
23776 004011C4 in __mingw_CRTStartup at crt1.c:200
23777 004011F1 in mainCRTStartup at crt1.c:222
23778 77E892A4 in ?? at ??:0
23779 @end smallexample
23780
23781 @noindent
23782 In the above example the ``.\'' syntax in the @command{gnatmake} command
23783 is currently required by @command{addr2line} for files that are in
23784 the current working directory.
23785 Moreover, the exact sequence of linker options may vary from platform
23786 to platform.
23787 The above @option{-largs} section is for Windows platforms. By contrast,
23788 under Unix there is no need for the @option{-largs} section.
23789 Differences across platforms are due to details of linker implementation.
23790
23791 @node Tracebacks From Anywhere in a Program (symbolic)
23792 @subsubsection Tracebacks From Anywhere in a Program
23793
23794 @noindent
23795 It is possible to get a symbolic stack traceback
23796 from anywhere in a program, just as for non-symbolic tracebacks.
23797 The first step is to obtain a non-symbolic
23798 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
23799 information. Here is an example:
23800
23801 @smallexample @c ada
23802 with Ada.Text_IO;
23803 with GNAT.Traceback;
23804 with GNAT.Traceback.Symbolic;
23805
23806 procedure STB is
23807
23808    use Ada;
23809    use GNAT.Traceback;
23810    use GNAT.Traceback.Symbolic;
23811
23812    procedure P1 is
23813       TB  : Tracebacks_Array (1 .. 10);
23814       --  We are asking for a maximum of 10 stack frames.
23815       Len : Natural;
23816       --  Len will receive the actual number of stack frames returned.
23817    begin
23818       Call_Chain (TB, Len);
23819       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
23820    end P1;
23821
23822    procedure P2 is
23823    begin
23824       P1;
23825    end P2;
23826
23827 begin
23828    P2;
23829 end STB;
23830 @end smallexample
23831
23832 @c ******************************
23833 @ifset vms
23834 @node Compatibility with HP Ada
23835 @chapter Compatibility with HP Ada
23836 @cindex Compatibility
23837
23838 @noindent
23839 @cindex DEC Ada
23840 @cindex HP Ada
23841 @cindex Compatibility between GNAT and HP Ada
23842 This chapter compares HP Ada (formerly known as ``DEC Ada'')
23843 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
23844 GNAT is highly compatible
23845 with HP Ada, and it should generally be straightforward to port code
23846 from the HP Ada environment to GNAT. However, there are a few language
23847 and implementation differences of which the user must be aware. These
23848 differences are discussed in this chapter. In
23849 addition, the operating environment and command structure for the
23850 compiler are different, and these differences are also discussed.
23851
23852 For further details on these and other compatibility issues,
23853 see Appendix E of the HP publication
23854 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
23855
23856 Except where otherwise indicated, the description of GNAT for OpenVMS
23857 applies to both the Alpha and I64 platforms.
23858
23859 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
23860 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
23861
23862 The discussion in this chapter addresses specifically the implementation
23863 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
23864 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
23865 GNAT always follows the Alpha implementation.
23866
23867 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
23868 attributes are recognized, although only a subset of them can sensibly
23869 be implemented.  The description of pragmas in
23870 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
23871 indicates whether or not they are applicable to non-VMS systems.
23872
23873 @menu
23874 * Ada Language Compatibility::
23875 * Differences in the Definition of Package System::
23876 * Language-Related Features::
23877 * The Package STANDARD::
23878 * The Package SYSTEM::
23879 * Tasking and Task-Related Features::
23880 * Pragmas and Pragma-Related Features::
23881 * Library of Predefined Units::
23882 * Bindings::
23883 * Main Program Definition::
23884 * Implementation-Defined Attributes::
23885 * Compiler and Run-Time Interfacing::
23886 * Program Compilation and Library Management::
23887 * Input-Output::
23888 * Implementation Limits::
23889 * Tools and Utilities::
23890 @end menu
23891
23892 @node Ada Language Compatibility
23893 @section Ada Language Compatibility
23894
23895 @noindent
23896 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
23897 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
23898 with Ada 83, and therefore Ada 83 programs will compile
23899 and run under GNAT with
23900 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
23901 provides details on specific incompatibilities.
23902
23903 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
23904 as well as the pragma @code{ADA_83}, to force the compiler to
23905 operate in Ada 83 mode. This mode does not guarantee complete
23906 conformance to Ada 83, but in practice is sufficient to
23907 eliminate most sources of incompatibilities.
23908 In particular, it eliminates the recognition of the
23909 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
23910 in Ada 83 programs is legal, and handles the cases of packages
23911 with optional bodies, and generics that instantiate unconstrained
23912 types without the use of @code{(<>)}.
23913
23914 @node Differences in the Definition of Package System
23915 @section Differences in the Definition of Package @code{System}
23916
23917 @noindent
23918 An Ada compiler is allowed to add
23919 implementation-dependent declarations to package @code{System}.
23920 In normal mode,
23921 GNAT does not take advantage of this permission, and the version of
23922 @code{System} provided by GNAT exactly matches that defined in the Ada
23923 Reference Manual.
23924
23925 However, HP Ada adds an extensive set of declarations to package
23926 @code{System},
23927 as fully documented in the HP Ada manuals. To minimize changes required
23928 for programs that make use of these extensions, GNAT provides the pragma
23929 @code{Extend_System} for extending the definition of package System. By using:
23930 @cindex pragma @code{Extend_System}
23931 @cindex @code{Extend_System} pragma
23932
23933 @smallexample @c ada
23934 @group
23935 @cartouche
23936 pragma Extend_System (Aux_DEC);
23937 @end cartouche
23938 @end group
23939 @end smallexample
23940
23941 @noindent
23942 the set of definitions in @code{System} is extended to include those in
23943 package @code{System.Aux_DEC}.
23944 @cindex @code{System.Aux_DEC} package
23945 @cindex @code{Aux_DEC} package (child of @code{System})
23946 These definitions are incorporated directly into package @code{System},
23947 as though they had been declared there. For a
23948 list of the declarations added, see the spec of this package,
23949 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
23950 @cindex @file{s-auxdec.ads} file
23951 The pragma @code{Extend_System} is a configuration pragma, which means that
23952 it can be placed in the file @file{gnat.adc}, so that it will automatically
23953 apply to all subsequent compilations. See @ref{Configuration Pragmas},
23954 for further details.
23955
23956 An alternative approach that avoids the use of the non-standard
23957 @code{Extend_System} pragma is to add a context clause to the unit that
23958 references these facilities:
23959
23960 @smallexample @c ada
23961 @cartouche
23962 with System.Aux_DEC;
23963 use  System.Aux_DEC;
23964 @end cartouche
23965 @end smallexample
23966
23967 @noindent
23968 The effect is not quite semantically identical to incorporating
23969 the declarations directly into package @code{System},
23970 but most programs will not notice a difference
23971 unless they use prefix notation (e.g.@: @code{System.Integer_8})
23972 to reference the entities directly in package @code{System}.
23973 For units containing such references,
23974 the prefixes must either be removed, or the pragma @code{Extend_System}
23975 must be used.
23976
23977 @node Language-Related Features
23978 @section Language-Related Features
23979
23980 @noindent
23981 The following sections highlight differences in types,
23982 representations of types, operations, alignment, and
23983 related topics.
23984
23985 @menu
23986 * Integer Types and Representations::
23987 * Floating-Point Types and Representations::
23988 * Pragmas Float_Representation and Long_Float::
23989 * Fixed-Point Types and Representations::
23990 * Record and Array Component Alignment::
23991 * Address Clauses::
23992 * Other Representation Clauses::
23993 @end menu
23994
23995 @node Integer Types and Representations
23996 @subsection Integer Types and Representations
23997
23998 @noindent
23999 The set of predefined integer types is identical in HP Ada and GNAT.
24000 Furthermore the representation of these integer types is also identical,
24001 including the capability of size clauses forcing biased representation.
24002
24003 In addition,
24004 HP Ada for OpenVMS Alpha systems has defined the
24005 following additional integer types in package @code{System}:
24006
24007 @itemize @bullet
24008
24009 @item
24010 @code{INTEGER_8}
24011
24012 @item
24013 @code{INTEGER_16}
24014
24015 @item
24016 @code{INTEGER_32}
24017
24018 @item
24019 @code{INTEGER_64}
24020
24021 @item
24022 @code{LARGEST_INTEGER}
24023 @end itemize
24024
24025 @noindent
24026 In GNAT, the first four of these types may be obtained from the
24027 standard Ada package @code{Interfaces}.
24028 Alternatively, by use of the pragma @code{Extend_System}, identical
24029 declarations can be referenced directly in package @code{System}.
24030 On both GNAT and HP Ada, the maximum integer size is 64 bits.
24031
24032 @node Floating-Point Types and Representations
24033 @subsection Floating-Point Types and Representations
24034 @cindex Floating-Point types
24035
24036 @noindent
24037 The set of predefined floating-point types is identical in HP Ada and GNAT.
24038 Furthermore the representation of these floating-point
24039 types is also identical. One important difference is that the default
24040 representation for HP Ada is @code{VAX_Float}, but the default representation
24041 for GNAT is IEEE.
24042
24043 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
24044 pragma @code{Float_Representation} as described in the HP Ada
24045 documentation.
24046 For example, the declarations:
24047
24048 @smallexample @c ada
24049 @cartouche
24050 type F_Float is digits 6;
24051 pragma Float_Representation (VAX_Float, F_Float);
24052 @end cartouche
24053 @end smallexample
24054
24055 @noindent
24056 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
24057 format.
24058 This set of declarations actually appears in @code{System.Aux_DEC},
24059 which contains
24060 the full set of additional floating-point declarations provided in
24061 the HP Ada version of package @code{System}.
24062 This and similar declarations may be accessed in a user program
24063 by using pragma @code{Extend_System}. The use of this
24064 pragma, and the related pragma @code{Long_Float} is described in further
24065 detail in the following section.
24066
24067 @node Pragmas Float_Representation and Long_Float
24068 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
24069
24070 @noindent
24071 HP Ada provides the pragma @code{Float_Representation}, which
24072 acts as a program library switch to allow control over
24073 the internal representation chosen for the predefined
24074 floating-point types declared in the package @code{Standard}.
24075 The format of this pragma is as follows:
24076
24077 @smallexample @c ada
24078 @cartouche
24079 pragma Float_Representation(VAX_Float | IEEE_Float);
24080 @end cartouche
24081 @end smallexample
24082
24083 @noindent
24084 This pragma controls the representation of floating-point
24085 types as follows:
24086
24087 @itemize @bullet
24088 @item
24089 @code{VAX_Float} specifies that floating-point
24090 types are represented by default with the VAX system hardware types
24091 @code{F-floating}, @code{D-floating}, @code{G-floating}.
24092 Note that the @code{H-floating}
24093 type was available only on VAX systems, and is not available
24094 in either HP Ada or GNAT.
24095
24096 @item
24097 @code{IEEE_Float} specifies that floating-point
24098 types are represented by default with the IEEE single and
24099 double floating-point types.
24100 @end itemize
24101
24102 @noindent
24103 GNAT provides an identical implementation of the pragma
24104 @code{Float_Representation}, except that it functions as a
24105 configuration pragma. Note that the
24106 notion of configuration pragma corresponds closely to the
24107 HP Ada notion of a program library switch.
24108
24109 When no pragma is used in GNAT, the default is @code{IEEE_Float},
24110 which is different
24111 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
24112 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
24113 advisable to change the format of numbers passed to standard library
24114 routines, and if necessary explicit type conversions may be needed.
24115
24116 The use of @code{IEEE_Float} is recommended in GNAT since it is more
24117 efficient, and (given that it conforms to an international standard)
24118 potentially more portable.
24119 The situation in which @code{VAX_Float} may be useful is in interfacing
24120 to existing code and data that expect the use of @code{VAX_Float}.
24121 In such a situation use the predefined @code{VAX_Float}
24122 types in package @code{System}, as extended by
24123 @code{Extend_System}. For example, use @code{System.F_Float}
24124 to specify the 32-bit @code{F-Float} format.
24125
24126 @noindent
24127 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
24128 to allow control over the internal representation chosen
24129 for the predefined type @code{Long_Float} and for floating-point
24130 type declarations with digits specified in the range 7 .. 15.
24131 The format of this pragma is as follows:
24132
24133 @smallexample @c ada
24134 @cartouche
24135 pragma Long_Float (D_FLOAT | G_FLOAT);
24136 @end cartouche
24137 @end smallexample
24138
24139 @node Fixed-Point Types and Representations
24140 @subsection Fixed-Point Types and Representations
24141
24142 @noindent
24143 On HP Ada for OpenVMS Alpha systems, rounding is
24144 away from zero for both positive and negative numbers.
24145 Therefore, @code{+0.5} rounds to @code{1},
24146 and @code{-0.5} rounds to @code{-1}.
24147
24148 On GNAT the results of operations
24149 on fixed-point types are in accordance with the Ada
24150 rules. In particular, results of operations on decimal
24151 fixed-point types are truncated.
24152
24153 @node Record and Array Component Alignment
24154 @subsection Record and Array Component Alignment
24155
24156 @noindent
24157 On HP Ada for OpenVMS Alpha, all non-composite components
24158 are aligned on natural boundaries. For example, 1-byte
24159 components are aligned on byte boundaries, 2-byte
24160 components on 2-byte boundaries, 4-byte components on 4-byte
24161 byte boundaries, and so on. The OpenVMS Alpha hardware
24162 runs more efficiently with naturally aligned data.
24163
24164 On GNAT, alignment rules are compatible
24165 with HP Ada for OpenVMS Alpha.
24166
24167 @node Address Clauses
24168 @subsection Address Clauses
24169
24170 @noindent
24171 In HP Ada and GNAT, address clauses are supported for
24172 objects and imported subprograms.
24173 The predefined type @code{System.Address} is a private type
24174 in both compilers on Alpha OpenVMS, with the same representation
24175 (it is simply a machine pointer). Addition, subtraction, and comparison
24176 operations are available in the standard Ada package
24177 @code{System.Storage_Elements}, or in package @code{System}
24178 if it is extended to include @code{System.Aux_DEC} using a
24179 pragma @code{Extend_System} as previously described.
24180
24181 Note that code that @code{with}'s both this extended package @code{System}
24182 and the package @code{System.Storage_Elements} should not @code{use}
24183 both packages, or ambiguities will result. In general it is better
24184 not to mix these two sets of facilities. The Ada package was
24185 designed specifically to provide the kind of features that HP Ada
24186 adds directly to package @code{System}.
24187
24188 The type @code{System.Address} is a 64-bit integer type in GNAT for
24189 I64 OpenVMS.  For more information,
24190 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
24191
24192 GNAT is compatible with HP Ada in its handling of address
24193 clauses, except for some limitations in
24194 the form of address clauses for composite objects with
24195 initialization. Such address clauses are easily replaced
24196 by the use of an explicitly-defined constant as described
24197 in the Ada Reference Manual (13.1(22)). For example, the sequence
24198 of declarations:
24199
24200 @smallexample @c ada
24201 @cartouche
24202 X, Y : Integer := Init_Func;
24203 Q : String (X .. Y) := "abc";
24204 @dots{}
24205 for Q'Address use Compute_Address;
24206 @end cartouche
24207 @end smallexample
24208
24209 @noindent
24210 will be rejected by GNAT, since the address cannot be computed at the time
24211 that @code{Q} is declared. To achieve the intended effect, write instead:
24212
24213 @smallexample @c ada
24214 @group
24215 @cartouche
24216 X, Y : Integer := Init_Func;
24217 Q_Address : constant Address := Compute_Address;
24218 Q : String (X .. Y) := "abc";
24219 @dots{}
24220 for Q'Address use Q_Address;
24221 @end cartouche
24222 @end group
24223 @end smallexample
24224
24225 @noindent
24226 which will be accepted by GNAT (and other Ada compilers), and is also
24227 compatible with Ada 83. A fuller description of the restrictions
24228 on address specifications is found in @ref{Top, GNAT Reference Manual,
24229 About This Guide, gnat_rm, GNAT Reference Manual}.
24230
24231 @node Other Representation Clauses
24232 @subsection Other Representation Clauses
24233
24234 @noindent
24235 GNAT implements in a compatible manner all the representation
24236 clauses supported by HP Ada. In addition, GNAT
24237 implements the representation clause forms that were introduced in Ada 95,
24238 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
24239
24240 @node The Package STANDARD
24241 @section The Package @code{STANDARD}
24242
24243 @noindent
24244 The package @code{STANDARD}, as implemented by HP Ada, is fully
24245 described in the @cite{Ada Reference Manual} and in the
24246 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
24247 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
24248
24249 In addition, HP Ada supports the Latin-1 character set in
24250 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
24251 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
24252 the type @code{WIDE_CHARACTER}.
24253
24254 The floating-point types supported by GNAT are those
24255 supported by HP Ada, but the defaults are different, and are controlled by
24256 pragmas. See @ref{Floating-Point Types and Representations}, for details.
24257
24258 @node The Package SYSTEM
24259 @section The Package @code{SYSTEM}
24260
24261 @noindent
24262 HP Ada provides a specific version of the package
24263 @code{SYSTEM} for each platform on which the language is implemented.
24264 For the complete spec of the package @code{SYSTEM}, see
24265 Appendix F of the @cite{HP Ada Language Reference Manual}.
24266
24267 On HP Ada, the package @code{SYSTEM} includes the following conversion
24268 functions:
24269 @itemize @bullet
24270 @item @code{TO_ADDRESS(INTEGER)}
24271
24272 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
24273
24274 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
24275
24276 @item @code{TO_INTEGER(ADDRESS)}
24277
24278 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
24279
24280 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
24281 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
24282 @end itemize
24283
24284 @noindent
24285 By default, GNAT supplies a version of @code{SYSTEM} that matches
24286 the definition given in the @cite{Ada Reference Manual}.
24287 This
24288 is a subset of the HP system definitions, which is as
24289 close as possible to the original definitions. The only difference
24290 is that the definition of @code{SYSTEM_NAME} is different:
24291
24292 @smallexample @c ada
24293 @cartouche
24294 type Name is (SYSTEM_NAME_GNAT);
24295 System_Name : constant Name := SYSTEM_NAME_GNAT;
24296 @end cartouche
24297 @end smallexample
24298
24299 @noindent
24300 Also, GNAT adds the Ada declarations for
24301 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
24302
24303 However, the use of the following pragma causes GNAT
24304 to extend the definition of package @code{SYSTEM} so that it
24305 encompasses the full set of HP-specific extensions,
24306 including the functions listed above:
24307
24308 @smallexample @c ada
24309 @cartouche
24310 pragma Extend_System (Aux_DEC);
24311 @end cartouche
24312 @end smallexample
24313
24314 @noindent
24315 The pragma @code{Extend_System} is a configuration pragma that
24316 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
24317 Extend_System,,, gnat_rm, GNAT Reference Manual} for further details.
24318
24319 HP Ada does not allow the recompilation of the package
24320 @code{SYSTEM}. Instead HP Ada provides several pragmas
24321 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
24322 to modify values in the package @code{SYSTEM}.
24323 On OpenVMS Alpha systems, the pragma
24324 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
24325 its single argument.
24326
24327 GNAT does permit the recompilation of package @code{SYSTEM} using
24328 the special switch @option{-gnatg}, and this switch can be used if
24329 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
24330 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
24331 or @code{MEMORY_SIZE} by any other means.
24332
24333 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
24334 enumeration literal @code{SYSTEM_NAME_GNAT}.
24335
24336 The definitions provided by the use of
24337
24338 @smallexample @c ada
24339 pragma Extend_System (AUX_Dec);
24340 @end smallexample
24341
24342 @noindent
24343 are virtually identical to those provided by the HP Ada 83 package
24344 @code{SYSTEM}. One important difference is that the name of the
24345 @code{TO_ADDRESS}
24346 function for type @code{UNSIGNED_LONGWORD} is changed to
24347 @code{TO_ADDRESS_LONG}.
24348 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual} for a
24349 discussion of why this change was necessary.
24350
24351 @noindent
24352 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
24353 is in fact
24354 an extension to Ada 83 not strictly compatible with the reference manual.
24355 GNAT, in order to be exactly compatible with the standard,
24356 does not provide this capability. In HP Ada 83, the
24357 point of this definition is to deal with a call like:
24358
24359 @smallexample @c ada
24360 TO_ADDRESS (16#12777#);
24361 @end smallexample
24362
24363 @noindent
24364 Normally, according to Ada 83 semantics, one would expect this to be
24365 ambiguous, since it matches both the @code{INTEGER} and
24366 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
24367 However, in HP Ada 83, there is no ambiguity, since the
24368 definition using @i{universal_integer} takes precedence.
24369
24370 In GNAT, since the version with @i{universal_integer} cannot be supplied,
24371 it is
24372 not possible to be 100% compatible. Since there are many programs using
24373 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
24374 GNAT was
24375 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
24376 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
24377
24378 @smallexample @c ada
24379 function To_Address (X : Integer) return Address;
24380 pragma Pure_Function (To_Address);
24381
24382 function To_Address_Long (X : Unsigned_Longword) return Address;
24383 pragma Pure_Function (To_Address_Long);
24384 @end smallexample
24385
24386 @noindent
24387 This means that programs using @code{TO_ADDRESS} for
24388 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
24389
24390 @node Tasking and Task-Related Features
24391 @section Tasking and Task-Related Features
24392
24393 @noindent
24394 This section compares the treatment of tasking in GNAT
24395 and in HP Ada for OpenVMS Alpha.
24396 The GNAT description applies to both Alpha and I64 OpenVMS.
24397 For detailed information on tasking in
24398 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
24399 relevant run-time reference manual.
24400
24401 @menu
24402 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
24403 * Assigning Task IDs::
24404 * Task IDs and Delays::
24405 * Task-Related Pragmas::
24406 * Scheduling and Task Priority::
24407 * The Task Stack::
24408 * External Interrupts::
24409 @end menu
24410
24411 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
24412 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
24413
24414 @noindent
24415 On OpenVMS Alpha systems, each Ada task (except a passive
24416 task) is implemented as a single stream of execution
24417 that is created and managed by the kernel. On these
24418 systems, HP Ada tasking support is based on DECthreads,
24419 an implementation of the POSIX standard for threads.
24420
24421 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
24422 code that calls DECthreads routines can be used together.
24423 The interaction between Ada tasks and DECthreads routines
24424 can have some benefits. For example when on OpenVMS Alpha,
24425 HP Ada can call C code that is already threaded.
24426
24427 GNAT uses the facilities of DECthreads,
24428 and Ada tasks are mapped to threads.
24429
24430 @node Assigning Task IDs
24431 @subsection Assigning Task IDs
24432
24433 @noindent
24434 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
24435 the environment task that executes the main program. On
24436 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
24437 that have been created but are not yet activated.
24438
24439 On OpenVMS Alpha systems, task IDs are assigned at
24440 activation. On GNAT systems, task IDs are also assigned at
24441 task creation but do not have the same form or values as
24442 task ID values in HP Ada. There is no null task, and the
24443 environment task does not have a specific task ID value.
24444
24445 @node Task IDs and Delays
24446 @subsection Task IDs and Delays
24447
24448 @noindent
24449 On OpenVMS Alpha systems, tasking delays are implemented
24450 using Timer System Services. The Task ID is used for the
24451 identification of the timer request (the @code{REQIDT} parameter).
24452 If Timers are used in the application take care not to use
24453 @code{0} for the identification, because cancelling such a timer
24454 will cancel all timers and may lead to unpredictable results.
24455
24456 @node Task-Related Pragmas
24457 @subsection Task-Related Pragmas
24458
24459 @noindent
24460 Ada supplies the pragma @code{TASK_STORAGE}, which allows
24461 specification of the size of the guard area for a task
24462 stack. (The guard area forms an area of memory that has no
24463 read or write access and thus helps in the detection of
24464 stack overflow.) On OpenVMS Alpha systems, if the pragma
24465 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
24466 area is created. In the absence of a pragma @code{TASK_STORAGE},
24467 a default guard area is created.
24468
24469 GNAT supplies the following task-related pragmas:
24470
24471 @itemize @bullet
24472 @item  @code{TASK_INFO}
24473
24474 This pragma appears within a task definition and
24475 applies to the task in which it appears. The argument
24476 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
24477
24478 @item  @code{TASK_STORAGE}
24479
24480 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
24481 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
24482 @code{SUPPRESS}, and @code{VOLATILE}.
24483 @end itemize
24484 @node Scheduling and Task Priority
24485 @subsection Scheduling and Task Priority
24486
24487 @noindent
24488 HP Ada implements the Ada language requirement that
24489 when two tasks are eligible for execution and they have
24490 different priorities, the lower priority task does not
24491 execute while the higher priority task is waiting. The HP
24492 Ada Run-Time Library keeps a task running until either the
24493 task is suspended or a higher priority task becomes ready.
24494
24495 On OpenVMS Alpha systems, the default strategy is round-
24496 robin with preemption. Tasks of equal priority take turns
24497 at the processor. A task is run for a certain period of
24498 time and then placed at the tail of the ready queue for
24499 its priority level.
24500
24501 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
24502 which can be used to enable or disable round-robin
24503 scheduling of tasks with the same priority.
24504 See the relevant HP Ada run-time reference manual for
24505 information on using the pragmas to control HP Ada task
24506 scheduling.
24507
24508 GNAT follows the scheduling rules of Annex D (Real-Time
24509 Annex) of the @cite{Ada Reference Manual}. In general, this
24510 scheduling strategy is fully compatible with HP Ada
24511 although it provides some additional constraints (as
24512 fully documented in Annex D).
24513 GNAT implements time slicing control in a manner compatible with
24514 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
24515 are identical to the HP Ada 83 pragma of the same name.
24516 Note that it is not possible to mix GNAT tasking and
24517 HP Ada 83 tasking in the same program, since the two run-time
24518 libraries are not compatible.
24519
24520 @node The Task Stack
24521 @subsection The Task Stack
24522
24523 @noindent
24524 In HP Ada, a task stack is allocated each time a
24525 non-passive task is activated. As soon as the task is
24526 terminated, the storage for the task stack is deallocated.
24527 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
24528 a default stack size is used. Also, regardless of the size
24529 specified, some additional space is allocated for task
24530 management purposes. On OpenVMS Alpha systems, at least
24531 one page is allocated.
24532
24533 GNAT handles task stacks in a similar manner. In accordance with
24534 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
24535 an alternative method for controlling the task stack size.
24536 The specification of the attribute @code{T'STORAGE_SIZE} is also
24537 supported in a manner compatible with HP Ada.
24538
24539 @node External Interrupts
24540 @subsection External Interrupts
24541
24542 @noindent
24543 On HP Ada, external interrupts can be associated with task entries.
24544 GNAT is compatible with HP Ada in its handling of external interrupts.
24545
24546 @node Pragmas and Pragma-Related Features
24547 @section Pragmas and Pragma-Related Features
24548
24549 @noindent
24550 Both HP Ada and GNAT supply all language-defined pragmas
24551 as specified by the Ada 83 standard. GNAT also supplies all
24552 language-defined pragmas introduced by Ada 95 and Ada 2005.
24553 In addition, GNAT implements the implementation-defined pragmas
24554 from HP Ada 83.
24555
24556 @itemize @bullet
24557 @item  @code{AST_ENTRY}
24558
24559 @item  @code{COMMON_OBJECT}
24560
24561 @item  @code{COMPONENT_ALIGNMENT}
24562
24563 @item  @code{EXPORT_EXCEPTION}
24564
24565 @item  @code{EXPORT_FUNCTION}
24566
24567 @item  @code{EXPORT_OBJECT}
24568
24569 @item  @code{EXPORT_PROCEDURE}
24570
24571 @item  @code{EXPORT_VALUED_PROCEDURE}
24572
24573 @item  @code{FLOAT_REPRESENTATION}
24574
24575 @item  @code{IDENT}
24576
24577 @item  @code{IMPORT_EXCEPTION}
24578
24579 @item  @code{IMPORT_FUNCTION}
24580
24581 @item  @code{IMPORT_OBJECT}
24582
24583 @item  @code{IMPORT_PROCEDURE}
24584
24585 @item  @code{IMPORT_VALUED_PROCEDURE}
24586
24587 @item  @code{INLINE_GENERIC}
24588
24589 @item  @code{INTERFACE_NAME}
24590
24591 @item  @code{LONG_FLOAT}
24592
24593 @item  @code{MAIN_STORAGE}
24594
24595 @item  @code{PASSIVE}
24596
24597 @item  @code{PSECT_OBJECT}
24598
24599 @item  @code{SHARE_GENERIC}
24600
24601 @item  @code{SUPPRESS_ALL}
24602
24603 @item  @code{TASK_STORAGE}
24604
24605 @item  @code{TIME_SLICE}
24606
24607 @item  @code{TITLE}
24608 @end itemize
24609
24610 @noindent
24611 These pragmas are all fully implemented, with the exception of @code{TITLE},
24612 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
24613 recognized, but which have no
24614 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
24615 use of Ada protected objects. In GNAT, all generics are inlined.
24616
24617 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
24618 a separate subprogram specification which must appear before the
24619 subprogram body.
24620
24621 GNAT also supplies a number of implementation-defined pragmas as follows:
24622 @itemize @bullet
24623 @item  @code{ABORT_DEFER}
24624
24625 @item  @code{ADA_83}
24626
24627 @item  @code{ADA_95}
24628
24629 @item  @code{ADA_05}
24630
24631 @item  @code{ANNOTATE}
24632
24633 @item  @code{ASSERT}
24634
24635 @item  @code{C_PASS_BY_COPY}
24636
24637 @item  @code{CPP_CLASS}
24638
24639 @item  @code{CPP_CONSTRUCTOR}
24640
24641 @item  @code{CPP_DESTRUCTOR}
24642
24643 @item  @code{DEBUG}
24644
24645 @item  @code{EXTEND_SYSTEM}
24646
24647 @item  @code{LINKER_ALIAS}
24648
24649 @item  @code{LINKER_SECTION}
24650
24651 @item  @code{MACHINE_ATTRIBUTE}
24652
24653 @item  @code{NO_RETURN}
24654
24655 @item  @code{PURE_FUNCTION}
24656
24657 @item  @code{SOURCE_FILE_NAME}
24658
24659 @item  @code{SOURCE_REFERENCE}
24660
24661 @item  @code{TASK_INFO}
24662
24663 @item  @code{UNCHECKED_UNION}
24664
24665 @item  @code{UNIMPLEMENTED_UNIT}
24666
24667 @item  @code{UNIVERSAL_DATA}
24668
24669 @item  @code{UNSUPPRESS}
24670
24671 @item  @code{WARNINGS}
24672
24673 @item  @code{WEAK_EXTERNAL}
24674 @end itemize
24675
24676 @noindent
24677 For full details on these GNAT implementation-defined pragmas,
24678 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
24679 Manual}.
24680
24681 @menu
24682 * Restrictions on the Pragma INLINE::
24683 * Restrictions on the Pragma INTERFACE::
24684 * Restrictions on the Pragma SYSTEM_NAME::
24685 @end menu
24686
24687 @node Restrictions on the Pragma INLINE
24688 @subsection Restrictions on Pragma @code{INLINE}
24689
24690 @noindent
24691 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
24692 @itemize @bullet
24693 @item  Parameters cannot have a task type.
24694
24695 @item  Function results cannot be task types, unconstrained
24696 array types, or unconstrained types with discriminants.
24697
24698 @item  Bodies cannot declare the following:
24699 @itemize @bullet
24700 @item  Subprogram body or stub (imported subprogram is allowed)
24701
24702 @item  Tasks
24703
24704 @item  Generic declarations
24705
24706 @item  Instantiations
24707
24708 @item  Exceptions
24709
24710 @item  Access types (types derived from access types allowed)
24711
24712 @item  Array or record types
24713
24714 @item  Dependent tasks
24715
24716 @item  Direct recursive calls of subprogram or containing
24717 subprogram, directly or via a renaming
24718
24719 @end itemize
24720 @end itemize
24721
24722 @noindent
24723 In GNAT, the only restriction on pragma @code{INLINE} is that the
24724 body must occur before the call if both are in the same
24725 unit, and the size must be appropriately small. There are
24726 no other specific restrictions which cause subprograms to
24727 be incapable of being inlined.
24728
24729 @node  Restrictions on the Pragma INTERFACE
24730 @subsection  Restrictions on Pragma @code{INTERFACE}
24731
24732 @noindent
24733 The following restrictions on pragma @code{INTERFACE}
24734 are enforced by both HP Ada and GNAT:
24735 @itemize @bullet
24736 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
24737 Default is the default on OpenVMS Alpha systems.
24738
24739 @item  Parameter passing: Language specifies default
24740 mechanisms but can be overridden with an @code{EXPORT} pragma.
24741
24742 @itemize @bullet
24743 @item  Ada: Use internal Ada rules.
24744
24745 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
24746 record or task type. Result cannot be a string, an
24747 array, or a record.
24748
24749 @item  Fortran: Parameters cannot have a task type. Result cannot
24750 be a string, an array, or a record.
24751 @end itemize
24752 @end itemize
24753
24754 @noindent
24755 GNAT is entirely upwards compatible with HP Ada, and in addition allows
24756 record parameters for all languages.
24757
24758 @node  Restrictions on the Pragma SYSTEM_NAME
24759 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
24760
24761 @noindent
24762 For HP Ada for OpenVMS Alpha, the enumeration literal
24763 for the type @code{NAME} is @code{OPENVMS_AXP}.
24764 In GNAT, the enumeration
24765 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
24766
24767 @node  Library of Predefined Units
24768 @section  Library of Predefined Units
24769
24770 @noindent
24771 A library of predefined units is provided as part of the
24772 HP Ada and GNAT implementations. HP Ada does not provide
24773 the package @code{MACHINE_CODE} but instead recommends importing
24774 assembler code.
24775
24776 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
24777 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
24778 version.
24779 The HP Ada Predefined Library units are modified to remove post-Ada 83
24780 incompatibilities and to make them interoperable with GNAT
24781 (@pxref{Changes to DECLIB}, for details).
24782 The units are located in the @file{DECLIB} directory.
24783
24784 The GNAT RTL is contained in
24785 the @file{ADALIB} directory, and
24786 the default search path is set up to find @code{DECLIB} units in preference
24787 to @code{ADALIB} units with the same name (@code{TEXT_IO},
24788 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
24789
24790 @menu
24791 * Changes to DECLIB::
24792 @end menu
24793
24794 @node Changes to DECLIB
24795 @subsection Changes to @code{DECLIB}
24796
24797 @noindent
24798 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
24799 compatibility are minor and include the following:
24800
24801 @itemize @bullet
24802 @item  Adjusting the location of pragmas and record representation
24803 clauses to obey Ada 95 (and thus Ada 2005) rules
24804
24805 @item  Adding the proper notation to generic formal parameters
24806 that take unconstrained types in instantiation
24807
24808 @item  Adding pragma @code{ELABORATE_BODY} to package specs
24809 that have package bodies not otherwise allowed
24810
24811 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
24812 ``@code{PROTECTD}''.
24813 Currently these are found only in the @code{STARLET} package spec.
24814
24815 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
24816 where the address size is constrained to 32 bits.
24817 @end itemize
24818
24819 @noindent
24820 None of the above changes is visible to users.
24821
24822 @node Bindings
24823 @section Bindings
24824
24825 @noindent
24826 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
24827 @itemize @bullet
24828
24829 @item  Command Language Interpreter (CLI interface)
24830
24831 @item  DECtalk Run-Time Library (DTK interface)
24832
24833 @item  Librarian utility routines (LBR interface)
24834
24835 @item  General Purpose Run-Time Library (LIB interface)
24836
24837 @item  Math Run-Time Library (MTH interface)
24838
24839 @item  National Character Set Run-Time Library (NCS interface)
24840
24841 @item  Compiled Code Support Run-Time Library (OTS interface)
24842
24843 @item  Parallel Processing Run-Time Library (PPL interface)
24844
24845 @item  Screen Management Run-Time Library (SMG interface)
24846
24847 @item  Sort Run-Time Library (SOR interface)
24848
24849 @item  String Run-Time Library (STR interface)
24850
24851 @item STARLET System Library
24852 @findex Starlet
24853
24854 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
24855
24856 @item  X Windows Toolkit (XT interface)
24857
24858 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
24859 @end itemize
24860
24861 @noindent
24862 GNAT provides implementations of these HP bindings in the @code{DECLIB}
24863 directory, on both the Alpha and I64 OpenVMS platforms.
24864
24865 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
24866 in the
24867 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
24868 A pragma @code{Linker_Options} has been added to packages @code{Xm},
24869 @code{Xt}, and @code{X_Lib}
24870 causing the default X/Motif sharable image libraries to be linked in. This
24871 is done via options files named @file{xm.opt}, @file{xt.opt}, and
24872 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
24873
24874 It may be necessary to edit these options files to update or correct the
24875 library names if, for example, the newer X/Motif bindings from
24876 @file{ADA$EXAMPLES}
24877 had been (previous to installing GNAT) copied and renamed to supersede the
24878 default @file{ADA$PREDEFINED} versions.
24879
24880 @menu
24881 * Shared Libraries and Options Files::
24882 * Interfaces to C::
24883 @end menu
24884
24885 @node Shared Libraries and Options Files
24886 @subsection Shared Libraries and Options Files
24887
24888 @noindent
24889 When using the HP Ada
24890 predefined X and Motif bindings, the linking with their sharable images is
24891 done automatically by @command{GNAT LINK}.
24892 When using other X and Motif bindings, you need
24893 to add the corresponding sharable images to the command line for
24894 @code{GNAT LINK}. When linking with shared libraries, or with
24895 @file{.OPT} files, you must
24896 also add them to the command line for @command{GNAT LINK}.
24897
24898 A shared library to be used with GNAT is built in the same way as other
24899 libraries under VMS. The VMS Link command can be used in standard fashion.
24900
24901 @node Interfaces to C
24902 @subsection Interfaces to C
24903
24904 @noindent
24905 HP Ada
24906 provides the following Ada types and operations:
24907
24908 @itemize @bullet
24909 @item C types package (@code{C_TYPES})
24910
24911 @item C strings (@code{C_TYPES.NULL_TERMINATED})
24912
24913 @item Other_types (@code{SHORT_INT})
24914 @end itemize
24915
24916 @noindent
24917 Interfacing to C with GNAT, you can use the above approach
24918 described for HP Ada or the facilities of Annex B of
24919 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
24920 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
24921 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
24922
24923 The @option{-gnatF} qualifier forces default and explicit
24924 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
24925 to be uppercased for compatibility with the default behavior
24926 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
24927
24928 @node Main Program Definition
24929 @section Main Program Definition
24930
24931 @noindent
24932 The following section discusses differences in the
24933 definition of main programs on HP Ada and GNAT.
24934 On HP Ada, main programs are defined to meet the
24935 following conditions:
24936 @itemize @bullet
24937 @item  Procedure with no formal parameters (returns @code{0} upon
24938 normal completion)
24939
24940 @item  Procedure with no formal parameters (returns @code{42} when
24941 an unhandled exception is raised)
24942
24943 @item  Function with no formal parameters whose returned value
24944 is of a discrete type
24945
24946 @item  Procedure with one @code{out} formal of a discrete type for
24947 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
24948
24949 @end itemize
24950
24951 @noindent
24952 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
24953 a main function or main procedure returns a discrete
24954 value whose size is less than 64 bits (32 on VAX systems),
24955 the value is zero- or sign-extended as appropriate.
24956 On GNAT, main programs are defined as follows:
24957 @itemize @bullet
24958 @item  Must be a non-generic, parameterless subprogram that
24959 is either a procedure or function returning an Ada
24960 @code{STANDARD.INTEGER} (the predefined type)
24961
24962 @item  Cannot be a generic subprogram or an instantiation of a
24963 generic subprogram
24964 @end itemize
24965
24966 @node Implementation-Defined Attributes
24967 @section Implementation-Defined Attributes
24968
24969 @noindent
24970 GNAT provides all HP Ada implementation-defined
24971 attributes.
24972
24973 @node Compiler and Run-Time Interfacing
24974 @section Compiler and Run-Time Interfacing
24975
24976 @noindent
24977 HP Ada provides the following qualifiers to pass options to the linker
24978 (ACS LINK):
24979 @itemize @bullet
24980 @item  @option{/WAIT} and @option{/SUBMIT}
24981
24982 @item  @option{/COMMAND}
24983
24984 @item  @option{/@r{[}NO@r{]}MAP}
24985
24986 @item  @option{/OUTPUT=@var{file-spec}}
24987
24988 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
24989 @end itemize
24990
24991 @noindent
24992 To pass options to the linker, GNAT provides the following
24993 switches:
24994
24995 @itemize @bullet
24996 @item   @option{/EXECUTABLE=@var{exec-name}}
24997
24998 @item   @option{/VERBOSE}
24999
25000 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
25001 @end itemize
25002
25003 @noindent
25004 For more information on these switches, see
25005 @ref{Switches for gnatlink}.
25006 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
25007 to control optimization. HP Ada also supplies the
25008 following pragmas:
25009 @itemize @bullet
25010 @item  @code{OPTIMIZE}
25011
25012 @item  @code{INLINE}
25013
25014 @item  @code{INLINE_GENERIC}
25015
25016 @item  @code{SUPPRESS_ALL}
25017
25018 @item  @code{PASSIVE}
25019 @end itemize
25020
25021 @noindent
25022 In GNAT, optimization is controlled strictly by command
25023 line parameters, as described in the corresponding section of this guide.
25024 The HP pragmas for control of optimization are
25025 recognized but ignored.
25026
25027 Note that in GNAT, the default is optimization off, whereas in HP Ada
25028 the default is that optimization is turned on.
25029
25030 @node Program Compilation and Library Management
25031 @section Program Compilation and Library Management
25032
25033 @noindent
25034 HP Ada and GNAT provide a comparable set of commands to
25035 build programs. HP Ada also provides a program library,
25036 which is a concept that does not exist on GNAT. Instead,
25037 GNAT provides directories of sources that are compiled as
25038 needed.
25039
25040 The following table summarizes
25041 the HP Ada commands and provides
25042 equivalent GNAT commands. In this table, some GNAT
25043 equivalents reflect the fact that GNAT does not use the
25044 concept of a program library. Instead, it uses a model
25045 in which collections of source and object files are used
25046 in a manner consistent with other languages like C and
25047 Fortran. Therefore, standard system file commands are used
25048 to manipulate these elements. Those GNAT commands are marked with
25049 an asterisk.
25050 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
25051
25052 @need 1500
25053 @multitable @columnfractions .35 .65
25054
25055 @item @emph{HP Ada Command}
25056 @tab @emph{GNAT Equivalent / Description}
25057
25058 @item @command{ADA}
25059 @tab @command{GNAT COMPILE}@*
25060 Invokes the compiler to compile one or more Ada source files.
25061
25062 @item @command{ACS ATTACH}@*
25063 @tab [No equivalent]@*
25064 Switches control of terminal from current process running the program
25065 library manager.
25066
25067 @item @command{ACS CHECK}
25068 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
25069 Forms the execution closure of one
25070 or more compiled units and checks completeness and currency.
25071
25072 @item @command{ACS COMPILE}
25073 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
25074 Forms the execution closure of one or
25075 more specified units, checks completeness and currency,
25076 identifies units that have revised source files, compiles same,
25077 and recompiles units that are or will become obsolete.
25078 Also completes incomplete generic instantiations.
25079
25080 @item @command{ACS COPY FOREIGN}
25081 @tab Copy (*)@*
25082 Copies a foreign object file into the program library as a
25083 library unit body.
25084
25085 @item @command{ACS COPY UNIT}
25086 @tab Copy (*)@*
25087 Copies a compiled unit from one program library to another.
25088
25089 @item @command{ACS CREATE LIBRARY}
25090 @tab Create /directory (*)@*
25091 Creates a program library.
25092
25093 @item @command{ACS CREATE SUBLIBRARY}
25094 @tab Create /directory (*)@*
25095 Creates a program sublibrary.
25096
25097 @item @command{ACS DELETE LIBRARY}
25098 @tab @*
25099 Deletes a program library and its contents.
25100
25101 @item @command{ACS DELETE SUBLIBRARY}
25102 @tab @*
25103 Deletes a program sublibrary and its contents.
25104
25105 @item @command{ACS DELETE UNIT}
25106 @tab Delete file (*)@*
25107 On OpenVMS systems, deletes one or more compiled units from
25108 the current program library.
25109
25110 @item @command{ACS DIRECTORY}
25111 @tab Directory (*)@*
25112 On OpenVMS systems, lists units contained in the current
25113 program library.
25114
25115 @item @command{ACS ENTER FOREIGN}
25116 @tab Copy (*)@*
25117 Allows the import of a foreign body as an Ada library
25118 spec and enters a reference to a pointer.
25119
25120 @item @command{ACS ENTER UNIT}
25121 @tab Copy (*)@*
25122 Enters a reference (pointer) from the current program library to
25123 a unit compiled into another program library.
25124
25125 @item @command{ACS EXIT}
25126 @tab [No equivalent]@*
25127 Exits from the program library manager.
25128
25129 @item @command{ACS EXPORT}
25130 @tab Copy (*)@*
25131 Creates an object file that contains system-specific object code
25132 for one or more units. With GNAT, object files can simply be copied
25133 into the desired directory.
25134
25135 @item @command{ACS EXTRACT SOURCE}
25136 @tab Copy (*)@*
25137 Allows access to the copied source file for each Ada compilation unit
25138
25139 @item @command{ACS HELP}
25140 @tab @command{HELP GNAT}@*
25141 Provides online help.
25142
25143 @item @command{ACS LINK}
25144 @tab @command{GNAT LINK}@*
25145 Links an object file containing Ada units into an executable file.
25146
25147 @item @command{ACS LOAD}
25148 @tab Copy (*)@*
25149 Loads (partially compiles) Ada units into the program library.
25150 Allows loading a program from a collection of files into a library
25151 without knowing the relationship among units.
25152
25153 @item @command{ACS MERGE}
25154 @tab Copy (*)@*
25155 Merges into the current program library, one or more units from
25156 another library where they were modified.
25157
25158 @item @command{ACS RECOMPILE}
25159 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
25160 Recompiles from   external or copied source files any obsolete
25161 unit in the closure. Also, completes any incomplete generic
25162 instantiations.
25163
25164 @item @command{ACS REENTER}
25165 @tab @command{GNAT MAKE}@*
25166 Reenters current references to units compiled after last entered
25167 with the @command{ACS ENTER UNIT} command.
25168
25169 @item @command{ACS SET LIBRARY}
25170 @tab Set default (*)@*
25171 Defines a program library to be the compilation context as well
25172 as the target library for compiler output and commands in general.
25173
25174 @item @command{ACS SET PRAGMA}
25175 @tab Edit @file{gnat.adc} (*)@*
25176 Redefines specified  values of the library characteristics
25177 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
25178 and @code{Float_Representation}.
25179
25180 @item @command{ACS SET SOURCE}
25181 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
25182 Defines the source file search list for the @command{ACS COMPILE} command.
25183
25184 @item @command{ACS SHOW LIBRARY}
25185 @tab Directory (*)@*
25186 Lists information about one or more program libraries.
25187
25188 @item @command{ACS SHOW PROGRAM}
25189 @tab [No equivalent]@*
25190 Lists information about the execution closure of one or
25191 more units in the program library.
25192
25193 @item @command{ACS SHOW SOURCE}
25194 @tab Show logical @code{ADA_INCLUDE_PATH}@*
25195 Shows the source file search used when compiling units.
25196
25197 @item @command{ACS SHOW VERSION}
25198 @tab Compile with @option{VERBOSE} option
25199 Displays the version number of the compiler and program library
25200 manager used.
25201
25202 @item @command{ACS SPAWN}
25203 @tab [No equivalent]@*
25204 Creates a subprocess of the current process (same as @command{DCL SPAWN}
25205 command).
25206
25207 @item @command{ACS VERIFY}
25208 @tab [No equivalent]@*
25209 Performs a series of consistency checks on a program library to
25210 determine whether the library structure and library files are in
25211 valid form.
25212 @end multitable
25213
25214 @noindent
25215
25216 @node Input-Output
25217 @section Input-Output
25218
25219 @noindent
25220 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
25221 Management Services (RMS) to perform operations on
25222 external files.
25223
25224 @noindent
25225 HP Ada and GNAT predefine an identical set of input-
25226 output packages. To make the use of the
25227 generic @code{TEXT_IO} operations more convenient, HP Ada
25228 provides predefined library packages that instantiate the
25229 integer and floating-point operations for the predefined
25230 integer and floating-point types as shown in the following table.
25231
25232 @multitable @columnfractions .45 .55
25233 @item @emph{Package Name} @tab Instantiation
25234
25235 @item @code{INTEGER_TEXT_IO}
25236 @tab @code{INTEGER_IO(INTEGER)}
25237
25238 @item @code{SHORT_INTEGER_TEXT_IO}
25239 @tab @code{INTEGER_IO(SHORT_INTEGER)}
25240
25241 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
25242 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
25243
25244 @item @code{FLOAT_TEXT_IO}
25245 @tab @code{FLOAT_IO(FLOAT)}
25246
25247 @item @code{LONG_FLOAT_TEXT_IO}
25248 @tab @code{FLOAT_IO(LONG_FLOAT)}
25249 @end multitable
25250
25251 @noindent
25252 The HP Ada predefined packages and their operations
25253 are implemented using OpenVMS Alpha files and input-output
25254 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
25255 Familiarity with the following is recommended:
25256 @itemize @bullet
25257 @item  RMS file organizations and access methods
25258
25259 @item  OpenVMS file specifications and directories
25260
25261 @item  OpenVMS File Definition Language (FDL)
25262 @end itemize
25263
25264 @noindent
25265 GNAT provides I/O facilities that are completely
25266 compatible with HP Ada. The distribution includes the
25267 standard HP Ada versions of all I/O packages, operating
25268 in a manner compatible with HP Ada. In particular, the
25269 following packages are by default the HP Ada (Ada 83)
25270 versions of these packages rather than the renamings
25271 suggested in Annex J of the Ada Reference Manual:
25272 @itemize @bullet
25273 @item  @code{TEXT_IO}
25274
25275 @item  @code{SEQUENTIAL_IO}
25276
25277 @item  @code{DIRECT_IO}
25278 @end itemize
25279
25280 @noindent
25281 The use of the standard child package syntax (for
25282 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
25283 packages.
25284 GNAT provides HP-compatible predefined instantiations
25285 of the @code{TEXT_IO} packages, and also
25286 provides the standard predefined instantiations required
25287 by the @cite{Ada Reference Manual}.
25288
25289 For further information on how GNAT interfaces to the file
25290 system or how I/O is implemented in programs written in
25291 mixed languages, see @ref{Implementation of the Standard I/O,,,
25292 gnat_rm, GNAT Reference Manual}.
25293 This chapter covers the following:
25294 @itemize @bullet
25295 @item  Standard I/O packages
25296
25297 @item  @code{FORM} strings
25298
25299 @item  @code{ADA.DIRECT_IO}
25300
25301 @item  @code{ADA.SEQUENTIAL_IO}
25302
25303 @item  @code{ADA.TEXT_IO}
25304
25305 @item  Stream pointer positioning
25306
25307 @item  Reading and writing non-regular files
25308
25309 @item  @code{GET_IMMEDIATE}
25310
25311 @item  Treating @code{TEXT_IO} files as streams
25312
25313 @item  Shared files
25314
25315 @item  Open modes
25316 @end itemize
25317
25318 @node Implementation Limits
25319 @section Implementation Limits
25320
25321 @noindent
25322 The following table lists implementation limits for HP Ada
25323 and GNAT systems.
25324 @multitable @columnfractions .60 .20 .20
25325 @sp 1
25326 @item  @emph{Compilation Parameter}
25327 @tab   @emph{HP Ada}
25328 @tab   @emph{GNAT}
25329 @sp 1
25330
25331 @item  In a subprogram or entry  declaration, maximum number of
25332 formal parameters that are of an unconstrained record type
25333 @tab   32
25334 @tab   No set limit
25335 @sp 1
25336
25337 @item  Maximum identifier length (number of characters)
25338 @tab   255
25339 @tab   32766
25340 @sp 1
25341
25342 @item  Maximum number of characters in a source line
25343 @tab   255
25344 @tab   32766
25345 @sp 1
25346
25347 @item  Maximum collection size   (number of bytes)
25348 @tab   2**31-1
25349 @tab   2**31-1
25350 @sp 1
25351
25352 @item  Maximum number of discriminants for a record type
25353 @tab   245
25354 @tab   No set limit
25355 @sp 1
25356
25357 @item  Maximum number of formal parameters in an entry or
25358 subprogram declaration
25359 @tab   246
25360 @tab    No set limit
25361 @sp 1
25362
25363 @item  Maximum number of dimensions in an array type
25364 @tab   255
25365 @tab   No set limit
25366 @sp 1
25367
25368 @item  Maximum number of library  units and subunits in a compilation.
25369 @tab   4095
25370 @tab   No set limit
25371 @sp 1
25372
25373 @item  Maximum number of library units and subunits in an execution.
25374 @tab   16383
25375 @tab   No set limit
25376 @sp 1
25377
25378 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
25379 or @code{PSECT_OBJECT}
25380 @tab   32757
25381 @tab   No set limit
25382 @sp 1
25383
25384 @item  Maximum number of enumeration literals in an enumeration type
25385 definition
25386 @tab   65535
25387 @tab   No set limit
25388 @sp 1
25389
25390 @item  Maximum number of lines in a source file
25391 @tab   65534
25392 @tab   No set limit
25393 @sp 1
25394
25395 @item  Maximum number of bits in any object
25396 @tab   2**31-1
25397 @tab   2**31-1
25398 @sp 1
25399
25400 @item  Maximum size of the static portion of a stack frame (approximate)
25401 @tab   2**31-1
25402 @tab   2**31-1
25403 @end multitable
25404
25405 @node Tools and Utilities
25406 @section Tools and Utilities
25407
25408 @noindent
25409 The following table lists some of the OpenVMS development tools
25410 available for HP Ada, and the corresponding tools for
25411 use with @value{EDITION} on Alpha and I64 platforms.
25412 Aside from the debugger, all the OpenVMS tools identified are part
25413 of the DECset package.
25414
25415 @iftex
25416 @c Specify table in TeX since Texinfo does a poor job
25417 @tex
25418 \smallskip
25419 \smallskip
25420 \settabs\+Language-Sensitive Editor\quad
25421    &Product with HP Ada\quad
25422    &\cr
25423 \+\it Tool
25424    &\it Product with HP Ada
25425    & \it Product with GNAT Pro\cr
25426 \smallskip
25427 \+Code Management System
25428    &HP CMS
25429    & HP CMS\cr
25430 \smallskip
25431 \+Language-Sensitive Editor
25432    &HP LSE
25433    & emacs or HP LSE (Alpha)\cr
25434 \+
25435    &
25436    & HP LSE (I64)\cr
25437 \smallskip
25438 \+Debugger
25439    &OpenVMS Debug
25440    & gdb (Alpha),\cr
25441 \+
25442    &
25443    & OpenVMS Debug (I64)\cr
25444 \smallskip
25445 \+Source Code Analyzer /
25446    &HP SCA
25447    & GNAT XREF\cr
25448 \+Cross Referencer
25449    &
25450    &\cr
25451 \smallskip
25452 \+Test Manager
25453    &HP Digital Test
25454    & HP DTM\cr
25455 \+
25456    &Manager (DTM)
25457    &\cr
25458 \smallskip
25459 \+Performance and
25460    & HP PCA
25461    & HP PCA\cr
25462 \+Coverage Analyzer
25463    &
25464    &\cr
25465 \smallskip
25466 \+Module Management
25467    & HP MMS
25468    & Not applicable\cr
25469 \+ System
25470    &
25471    &\cr
25472 \smallskip
25473 \smallskip
25474 @end tex
25475 @end iftex
25476
25477 @ifnottex
25478 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
25479 @c the TeX version above for the printed version
25480 @flushleft
25481 @c @multitable @columnfractions .3 .4 .4
25482 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
25483 @item @i{Tool}
25484 @tab @i{Tool with HP Ada}
25485 @tab @i{Tool with @value{EDITION}}
25486 @item Code Management@*System
25487 @tab HP CMS
25488 @tab HP CMS
25489 @item Language-Sensitive@*Editor
25490 @tab HP LSE
25491 @tab emacs or HP LSE (Alpha)
25492 @item
25493 @tab
25494 @tab HP LSE (I64)
25495 @item Debugger
25496 @tab OpenVMS Debug
25497 @tab gdb (Alpha),
25498 @item
25499 @tab
25500 @tab OpenVMS Debug (I64)
25501 @item Source Code Analyzer /@*Cross Referencer
25502 @tab HP SCA
25503 @tab GNAT XREF
25504 @item Test Manager
25505 @tab HP Digital Test@*Manager (DTM)
25506 @tab HP DTM
25507 @item Performance and@*Coverage Analyzer
25508 @tab HP PCA
25509 @tab HP PCA
25510 @item Module Management@*System
25511 @tab HP MMS
25512 @tab Not applicable
25513 @end multitable
25514 @end flushleft
25515 @end ifnottex
25516
25517 @end ifset
25518
25519 @c **************************************
25520 @node Platform-Specific Information for the Run-Time Libraries
25521 @appendix Platform-Specific Information for the Run-Time Libraries
25522 @cindex Tasking and threads libraries
25523 @cindex Threads libraries and tasking
25524 @cindex Run-time libraries (platform-specific information)
25525
25526 @noindent
25527 The GNAT run-time implementation may vary with respect to both the
25528 underlying threads library and the exception handling scheme.
25529 For threads support, one or more of the following are supplied:
25530 @itemize @bullet
25531 @item @b{native threads library}, a binding to the thread package from
25532 the underlying operating system
25533
25534 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
25535 POSIX thread package
25536 @end itemize
25537
25538 @noindent
25539 For exception handling, either or both of two models are supplied:
25540 @itemize @bullet
25541 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
25542 Most programs should experience a substantial speed improvement by
25543 being compiled with a ZCX run-time.
25544 This is especially true for
25545 tasking applications or applications with many exception handlers.}
25546 @cindex Zero-Cost Exceptions
25547 @cindex ZCX (Zero-Cost Exceptions)
25548 which uses binder-generated tables that
25549 are interrogated at run time to locate a handler
25550
25551 @item @b{setjmp / longjmp} (``SJLJ''),
25552 @cindex setjmp/longjmp Exception Model
25553 @cindex SJLJ (setjmp/longjmp Exception Model)
25554 which uses dynamically-set data to establish
25555 the set of handlers
25556 @end itemize
25557
25558 @noindent
25559 This appendix summarizes which combinations of threads and exception support
25560 are supplied on various GNAT platforms.
25561 It then shows how to select a particular library either
25562 permanently or temporarily,
25563 explains the properties of (and tradeoffs among) the various threads
25564 libraries, and provides some additional
25565 information about several specific platforms.
25566
25567 @menu
25568 * Summary of Run-Time Configurations::
25569 * Specifying a Run-Time Library::
25570 * Choosing the Scheduling Policy::
25571 * Solaris-Specific Considerations::
25572 * Linux-Specific Considerations::
25573 * AIX-Specific Considerations::
25574 * Irix-Specific Considerations::
25575 * RTX-Specific Considerations::
25576 @end menu
25577
25578 @node Summary of Run-Time Configurations
25579 @section Summary of Run-Time Configurations
25580
25581 @multitable @columnfractions .30 .70
25582 @item @b{alpha-openvms}
25583 @item @code{@ @ }@i{rts-native (default)}
25584 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
25585 @item @code{@ @ @ @ }Exceptions @tab ZCX
25586 @*
25587 @item @b{alpha-tru64}
25588 @item @code{@ @ }@i{rts-native (default)}
25589 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
25590 @item @code{@ @ @ @ }Exceptions @tab ZCX
25591 @*
25592 @item @code{@ @ }@i{rts-sjlj}
25593 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
25594 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25595 @*
25596 @item @b{ia64-hp_linux}
25597 @item @code{@ @ }@i{rts-native (default)}
25598 @item @code{@ @ @ @ }Tasking    @tab pthread library
25599 @item @code{@ @ @ @ }Exceptions @tab ZCX
25600 @*
25601 @item @b{ia64-hpux}
25602 @item @code{@ @ }@i{rts-native (default)}
25603 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
25604 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25605 @*
25606 @item @b{ia64-openvms}
25607 @item @code{@ @ }@i{rts-native (default)}
25608 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
25609 @item @code{@ @ @ @ }Exceptions @tab ZCX
25610 @*
25611 @item @b{ia64-sgi_linux}
25612 @item @code{@ @ }@i{rts-native (default)}
25613 @item @code{@ @ @ @ }Tasking    @tab pthread library
25614 @item @code{@ @ @ @ }Exceptions @tab ZCX
25615 @*
25616 @item @b{mips-irix}
25617 @item @code{@ @ }@i{rts-native (default)}
25618 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
25619 @item @code{@ @ @ @ }Exceptions @tab ZCX
25620 @*
25621 @item @b{pa-hpux}
25622 @item @code{@ @ }@i{rts-native (default)}
25623 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
25624 @item @code{@ @ @ @ }Exceptions @tab ZCX
25625 @*
25626 @item @code{@ @ }@i{rts-sjlj}
25627 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
25628 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25629 @*
25630 @item @b{ppc-aix}
25631 @item @code{@ @ }@i{rts-native (default)}
25632 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
25633 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25634 @*
25635 @item @b{ppc-darwin}
25636 @item @code{@ @ }@i{rts-native (default)}
25637 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
25638 @item @code{@ @ @ @ }Exceptions @tab ZCX
25639 @*
25640 @item @b{sparc-solaris}  @tab
25641 @item @code{@ @ }@i{rts-native (default)}
25642 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
25643 @item @code{@ @ @ @ }Exceptions @tab ZCX
25644 @*
25645 @item @code{@ @ }@i{rts-pthread}
25646 @item @code{@ @ @ @ }Tasking    @tab pthread library
25647 @item @code{@ @ @ @ }Exceptions @tab ZCX
25648 @*
25649 @item @code{@ @ }@i{rts-sjlj}
25650 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
25651 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25652 @*
25653 @item @b{sparc64-solaris}  @tab
25654 @item @code{@ @ }@i{rts-native (default)}
25655 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
25656 @item @code{@ @ @ @ }Exceptions @tab ZCX
25657 @*
25658 @item @b{x86-linux}
25659 @item @code{@ @ }@i{rts-native (default)}
25660 @item @code{@ @ @ @ }Tasking    @tab pthread library
25661 @item @code{@ @ @ @ }Exceptions @tab ZCX
25662 @*
25663 @item @code{@ @ }@i{rts-sjlj}
25664 @item @code{@ @ @ @ }Tasking    @tab pthread library
25665 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25666 @*
25667 @item @b{x86-lynx}
25668 @item @code{@ @ }@i{rts-native (default)}
25669 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
25670 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25671 @*
25672 @item @b{x86-solaris}
25673 @item @code{@ @ }@i{rts-native (default)}
25674 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
25675 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25676 @*
25677 @item @b{x86-windows}
25678 @item @code{@ @ }@i{rts-native (default)}
25679 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
25680 @item @code{@ @ @ @ }Exceptions @tab ZCX
25681 @*
25682 @item @code{@ @ }@i{rts-sjlj (default)}
25683 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
25684 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25685 @*
25686 @item @b{x86-windows-rtx}
25687 @item @code{@ @ }@i{rts-rtx-rtss (default)}
25688 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
25689 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25690 @*
25691 @item @code{@ @ }@i{rts-rtx-w32}
25692 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
25693 @item @code{@ @ @ @ }Exceptions @tab ZCX
25694 @*
25695 @item @b{x86_64-linux}
25696 @item @code{@ @ }@i{rts-native (default)}
25697 @item @code{@ @ @ @ }Tasking    @tab pthread library
25698 @item @code{@ @ @ @ }Exceptions @tab ZCX
25699 @*
25700 @item @code{@ @ }@i{rts-sjlj}
25701 @item @code{@ @ @ @ }Tasking    @tab pthread library
25702 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25703 @*
25704 @end multitable
25705
25706 @node Specifying a Run-Time Library
25707 @section Specifying a Run-Time Library
25708
25709 @noindent
25710 The @file{adainclude} subdirectory containing the sources of the GNAT
25711 run-time library, and the @file{adalib} subdirectory containing the
25712 @file{ALI} files and the static and/or shared GNAT library, are located
25713 in the gcc target-dependent area:
25714
25715 @smallexample
25716 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
25717 @end smallexample
25718
25719 @noindent
25720 As indicated above, on some platforms several run-time libraries are supplied.
25721 These libraries are installed in the target dependent area and
25722 contain a complete source and binary subdirectory. The detailed description
25723 below explains the differences between the different libraries in terms of
25724 their thread support.
25725
25726 The default run-time library (when GNAT is installed) is @emph{rts-native}.
25727 This default run time is selected by the means of soft links.
25728 For example on x86-linux:
25729
25730 @smallexample
25731 @group
25732  $(target-dir)
25733      |
25734      +--- adainclude----------+
25735      |                        |
25736      +--- adalib-----------+  |
25737      |                     |  |
25738      +--- rts-native       |  |
25739      |    |                |  |
25740      |    +--- adainclude <---+
25741      |    |                |
25742      |    +--- adalib <----+
25743      |
25744      +--- rts-sjlj
25745           |
25746           +--- adainclude
25747           |
25748           +--- adalib
25749 @end group
25750 @end smallexample
25751
25752 @noindent
25753 If the @i{rts-sjlj} library is to be selected on a permanent basis,
25754 these soft links can be modified with the following commands:
25755
25756 @smallexample
25757 $ cd $target
25758 $ rm -f adainclude adalib
25759 $ ln -s rts-sjlj/adainclude adainclude
25760 $ ln -s rts-sjlj/adalib adalib
25761 @end smallexample
25762
25763 @noindent
25764 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
25765 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
25766 @file{$target/ada_object_path}.
25767
25768 Selecting another run-time library temporarily can be
25769 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
25770 @cindex @option{--RTS} option
25771
25772 @node Choosing the Scheduling Policy
25773 @section Choosing the Scheduling Policy
25774
25775 @noindent
25776 When using a POSIX threads implementation, you have a choice of several
25777 scheduling policies: @code{SCHED_FIFO},
25778 @cindex @code{SCHED_FIFO} scheduling policy
25779 @code{SCHED_RR}
25780 @cindex @code{SCHED_RR} scheduling policy
25781 and @code{SCHED_OTHER}.
25782 @cindex @code{SCHED_OTHER} scheduling policy
25783 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
25784 or @code{SCHED_RR} requires special (e.g., root) privileges.
25785
25786 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
25787 @code{SCHED_FIFO},
25788 @cindex @code{SCHED_FIFO} scheduling policy
25789 you can use one of the following:
25790
25791 @itemize @bullet
25792 @item
25793 @code{pragma Time_Slice (0.0)}
25794 @cindex pragma Time_Slice
25795 @item
25796 the corresponding binder option @option{-T0}
25797 @cindex @option{-T0} option
25798 @item
25799 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
25800 @cindex pragma Task_Dispatching_Policy
25801 @end itemize
25802
25803 @noindent
25804 To specify @code{SCHED_RR},
25805 @cindex @code{SCHED_RR} scheduling policy
25806 you should use @code{pragma Time_Slice} with a
25807 value greater than @code{0.0}, or else use the corresponding @option{-T}
25808 binder option.
25809
25810 @node Solaris-Specific Considerations
25811 @section Solaris-Specific Considerations
25812 @cindex Solaris Sparc threads libraries
25813
25814 @noindent
25815 This section addresses some topics related to the various threads libraries
25816 on Sparc Solaris.
25817
25818 @menu
25819 * Solaris Threads Issues::
25820 @end menu
25821
25822 @node Solaris Threads Issues
25823 @subsection Solaris Threads Issues
25824
25825 @noindent
25826 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
25827 library based on POSIX threads --- @emph{rts-pthread}.
25828 @cindex rts-pthread threads library
25829 This run-time library has the advantage of being mostly shared across all
25830 POSIX-compliant thread implementations, and it also provides under
25831 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
25832 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
25833 and @code{PTHREAD_PRIO_PROTECT}
25834 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
25835 semantics that can be selected using the predefined pragma
25836 @code{Locking_Policy}
25837 @cindex pragma Locking_Policy (under rts-pthread)
25838 with respectively
25839 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
25840 @cindex @code{Inheritance_Locking} (under rts-pthread)
25841 @cindex @code{Ceiling_Locking} (under rts-pthread)
25842
25843 As explained above, the native run-time library is based on the Solaris thread
25844 library (@code{libthread}) and is the default library.
25845
25846 When the Solaris threads library is used (this is the default), programs
25847 compiled with GNAT can automatically take advantage of
25848 and can thus execute on multiple processors.
25849 The user can alternatively specify a processor on which the program should run
25850 to emulate a single-processor system. The multiprocessor / uniprocessor choice
25851 is made by
25852 setting the environment variable @env{GNAT_PROCESSOR}
25853 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
25854 to one of the following:
25855
25856 @table @code
25857 @item -2
25858 Use the default configuration (run the program on all
25859 available processors) - this is the same as having @code{GNAT_PROCESSOR}
25860 unset
25861
25862 @item -1
25863 Let the run-time implementation choose one processor and run the program on
25864 that processor
25865
25866 @item 0 .. Last_Proc
25867 Run the program on the specified processor.
25868 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
25869 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
25870 @end table
25871
25872 @node Linux-Specific Considerations
25873 @section Linux-Specific Considerations
25874 @cindex Linux threads libraries
25875
25876 @noindent
25877 On GNU/Linux without NPTL support (usually system with GNU C Library
25878 older than 2.3), the signal model is not POSIX compliant, which means
25879 that to send a signal to the process, you need to send the signal to all
25880 threads, e.g.@: by using @code{killpg()}.
25881
25882 @node AIX-Specific Considerations
25883 @section AIX-Specific Considerations
25884 @cindex AIX resolver library
25885
25886 @noindent
25887 On AIX, the resolver library initializes some internal structure on
25888 the first call to @code{get*by*} functions, which are used to implement
25889 @code{GNAT.Sockets.Get_Host_By_Name} and
25890 @code{GNAT.Sockets.Get_Host_By_Address}.
25891 If such initialization occurs within an Ada task, and the stack size for
25892 the task is the default size, a stack overflow may occur.
25893
25894 To avoid this overflow, the user should either ensure that the first call
25895 to @code{GNAT.Sockets.Get_Host_By_Name} or
25896 @code{GNAT.Sockets.Get_Host_By_Addrss}
25897 occurs in the environment task, or use @code{pragma Storage_Size} to
25898 specify a sufficiently large size for the stack of the task that contains
25899 this call.
25900
25901 @node Irix-Specific Considerations
25902 @section Irix-Specific Considerations
25903 @cindex Irix libraries
25904
25905 @noindent
25906 The GCC support libraries coming with the Irix compiler have moved to
25907 their canonical place with respect to the general Irix ABI related
25908 conventions. Running applications built with the default shared GNAT
25909 run-time now requires the LD_LIBRARY_PATH environment variable to
25910 include this location. A possible way to achieve this is to issue the
25911 following command line on a bash prompt:
25912
25913 @smallexample
25914 @group
25915 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
25916 @end group
25917 @end smallexample
25918
25919 @node RTX-Specific Considerations
25920 @section RTX-Specific Considerations
25921 @cindex RTX libraries
25922
25923 @noindent
25924 The Real-time Extension (RTX) to Windows is based on the Windows Win32
25925 API. Applications can be built to work in two different modes:
25926
25927 @itemize @bullet
25928 @item
25929 Windows executables that run in Ring 3 to utilize memory protection
25930 (@emph{rts-rtx-w32}).
25931
25932 @item
25933 Real-time subsystem (RTSS) executables that run in Ring 0, where
25934 performance can be optimized with RTSS applications taking precedent
25935 over all Windows applications (@emph{rts-rtx-rtss}).
25936
25937 @end itemize
25938
25939 @c *******************************
25940 @node Example of Binder Output File
25941 @appendix Example of Binder Output File
25942
25943 @noindent
25944 This Appendix displays the source code for @command{gnatbind}'s output
25945 file generated for a simple ``Hello World'' program.
25946 Comments have been added for clarification purposes.
25947
25948 @smallexample @c adanocomment
25949 @iftex
25950 @leftskip=0cm
25951 @end iftex
25952 --  The package is called Ada_Main unless this name is actually used
25953 --  as a unit name in the partition, in which case some other unique
25954 --  name is used.
25955
25956 with System;
25957 package ada_main is
25958
25959    Elab_Final_Code : Integer;
25960    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
25961
25962    --  The main program saves the parameters (argument count,
25963    --  argument values, environment pointer) in global variables
25964    --  for later access by other units including
25965    --  Ada.Command_Line.
25966
25967    gnat_argc : Integer;
25968    gnat_argv : System.Address;
25969    gnat_envp : System.Address;
25970
25971    --  The actual variables are stored in a library routine. This
25972    --  is useful for some shared library situations, where there
25973    --  are problems if variables are not in the library.
25974
25975    pragma Import (C, gnat_argc);
25976    pragma Import (C, gnat_argv);
25977    pragma Import (C, gnat_envp);
25978
25979    --  The exit status is similarly an external location
25980
25981    gnat_exit_status : Integer;
25982    pragma Import (C, gnat_exit_status);
25983
25984    GNAT_Version : constant String :=
25985                     "GNAT Version: 6.0.0w (20061115)";
25986    pragma Export (C, GNAT_Version, "__gnat_version");
25987
25988    --  This is the generated adafinal routine that performs
25989    --  finalization at the end of execution. In the case where
25990    --  Ada is the main program, this main program makes a call
25991    --  to adafinal at program termination.
25992
25993    procedure adafinal;
25994    pragma Export (C, adafinal, "adafinal");
25995
25996    --  This is the generated adainit routine that performs
25997    --  initialization at the start of execution. In the case
25998    --  where Ada is the main program, this main program makes
25999    --  a call to adainit at program startup.
26000
26001    procedure adainit;
26002    pragma Export (C, adainit, "adainit");
26003
26004    --  This routine is called at the start of execution. It is
26005    --  a dummy routine that is used by the debugger to breakpoint
26006    --  at the start of execution.
26007
26008    procedure Break_Start;
26009    pragma Import (C, Break_Start, "__gnat_break_start");
26010
26011    --  This is the actual generated main program (it would be
26012    --  suppressed if the no main program switch were used). As
26013    --  required by standard system conventions, this program has
26014    --  the external name main.
26015
26016    function main
26017      (argc : Integer;
26018       argv : System.Address;
26019       envp : System.Address)
26020       return Integer;
26021    pragma Export (C, main, "main");
26022
26023    --  The following set of constants give the version
26024    --  identification values for every unit in the bound
26025    --  partition. This identification is computed from all
26026    --  dependent semantic units, and corresponds to the
26027    --  string that would be returned by use of the
26028    --  Body_Version or Version attributes.
26029
26030    type Version_32 is mod 2 ** 32;
26031    u00001 : constant Version_32 := 16#7880BEB3#;
26032    u00002 : constant Version_32 := 16#0D24CBD0#;
26033    u00003 : constant Version_32 := 16#3283DBEB#;
26034    u00004 : constant Version_32 := 16#2359F9ED#;
26035    u00005 : constant Version_32 := 16#664FB847#;
26036    u00006 : constant Version_32 := 16#68E803DF#;
26037    u00007 : constant Version_32 := 16#5572E604#;
26038    u00008 : constant Version_32 := 16#46B173D8#;
26039    u00009 : constant Version_32 := 16#156A40CF#;
26040    u00010 : constant Version_32 := 16#033DABE0#;
26041    u00011 : constant Version_32 := 16#6AB38FEA#;
26042    u00012 : constant Version_32 := 16#22B6217D#;
26043    u00013 : constant Version_32 := 16#68A22947#;
26044    u00014 : constant Version_32 := 16#18CC4A56#;
26045    u00015 : constant Version_32 := 16#08258E1B#;
26046    u00016 : constant Version_32 := 16#367D5222#;
26047    u00017 : constant Version_32 := 16#20C9ECA4#;
26048    u00018 : constant Version_32 := 16#50D32CB6#;
26049    u00019 : constant Version_32 := 16#39A8BB77#;
26050    u00020 : constant Version_32 := 16#5CF8FA2B#;
26051    u00021 : constant Version_32 := 16#2F1EB794#;
26052    u00022 : constant Version_32 := 16#31AB6444#;
26053    u00023 : constant Version_32 := 16#1574B6E9#;
26054    u00024 : constant Version_32 := 16#5109C189#;
26055    u00025 : constant Version_32 := 16#56D770CD#;
26056    u00026 : constant Version_32 := 16#02F9DE3D#;
26057    u00027 : constant Version_32 := 16#08AB6B2C#;
26058    u00028 : constant Version_32 := 16#3FA37670#;
26059    u00029 : constant Version_32 := 16#476457A0#;
26060    u00030 : constant Version_32 := 16#731E1B6E#;
26061    u00031 : constant Version_32 := 16#23C2E789#;
26062    u00032 : constant Version_32 := 16#0F1BD6A1#;
26063    u00033 : constant Version_32 := 16#7C25DE96#;
26064    u00034 : constant Version_32 := 16#39ADFFA2#;
26065    u00035 : constant Version_32 := 16#571DE3E7#;
26066    u00036 : constant Version_32 := 16#5EB646AB#;
26067    u00037 : constant Version_32 := 16#4249379B#;
26068    u00038 : constant Version_32 := 16#0357E00A#;
26069    u00039 : constant Version_32 := 16#3784FB72#;
26070    u00040 : constant Version_32 := 16#2E723019#;
26071    u00041 : constant Version_32 := 16#623358EA#;
26072    u00042 : constant Version_32 := 16#107F9465#;
26073    u00043 : constant Version_32 := 16#6843F68A#;
26074    u00044 : constant Version_32 := 16#63305874#;
26075    u00045 : constant Version_32 := 16#31E56CE1#;
26076    u00046 : constant Version_32 := 16#02917970#;
26077    u00047 : constant Version_32 := 16#6CCBA70E#;
26078    u00048 : constant Version_32 := 16#41CD4204#;
26079    u00049 : constant Version_32 := 16#572E3F58#;
26080    u00050 : constant Version_32 := 16#20729FF5#;
26081    u00051 : constant Version_32 := 16#1D4F93E8#;
26082    u00052 : constant Version_32 := 16#30B2EC3D#;
26083    u00053 : constant Version_32 := 16#34054F96#;
26084    u00054 : constant Version_32 := 16#5A199860#;
26085    u00055 : constant Version_32 := 16#0E7F912B#;
26086    u00056 : constant Version_32 := 16#5760634A#;
26087    u00057 : constant Version_32 := 16#5D851835#;
26088
26089    --  The following Export pragmas export the version numbers
26090    --  with symbolic names ending in B (for body) or S
26091    --  (for spec) so that they can be located in a link. The
26092    --  information provided here is sufficient to track down
26093    --  the exact versions of units used in a given build.
26094
26095    pragma Export (C, u00001, "helloB");
26096    pragma Export (C, u00002, "system__standard_libraryB");
26097    pragma Export (C, u00003, "system__standard_libraryS");
26098    pragma Export (C, u00004, "adaS");
26099    pragma Export (C, u00005, "ada__text_ioB");
26100    pragma Export (C, u00006, "ada__text_ioS");
26101    pragma Export (C, u00007, "ada__exceptionsB");
26102    pragma Export (C, u00008, "ada__exceptionsS");
26103    pragma Export (C, u00009, "gnatS");
26104    pragma Export (C, u00010, "gnat__heap_sort_aB");
26105    pragma Export (C, u00011, "gnat__heap_sort_aS");
26106    pragma Export (C, u00012, "systemS");
26107    pragma Export (C, u00013, "system__exception_tableB");
26108    pragma Export (C, u00014, "system__exception_tableS");
26109    pragma Export (C, u00015, "gnat__htableB");
26110    pragma Export (C, u00016, "gnat__htableS");
26111    pragma Export (C, u00017, "system__exceptionsS");
26112    pragma Export (C, u00018, "system__machine_state_operationsB");
26113    pragma Export (C, u00019, "system__machine_state_operationsS");
26114    pragma Export (C, u00020, "system__machine_codeS");
26115    pragma Export (C, u00021, "system__storage_elementsB");
26116    pragma Export (C, u00022, "system__storage_elementsS");
26117    pragma Export (C, u00023, "system__secondary_stackB");
26118    pragma Export (C, u00024, "system__secondary_stackS");
26119    pragma Export (C, u00025, "system__parametersB");
26120    pragma Export (C, u00026, "system__parametersS");
26121    pragma Export (C, u00027, "system__soft_linksB");
26122    pragma Export (C, u00028, "system__soft_linksS");
26123    pragma Export (C, u00029, "system__stack_checkingB");
26124    pragma Export (C, u00030, "system__stack_checkingS");
26125    pragma Export (C, u00031, "system__tracebackB");
26126    pragma Export (C, u00032, "system__tracebackS");
26127    pragma Export (C, u00033, "ada__streamsS");
26128    pragma Export (C, u00034, "ada__tagsB");
26129    pragma Export (C, u00035, "ada__tagsS");
26130    pragma Export (C, u00036, "system__string_opsB");
26131    pragma Export (C, u00037, "system__string_opsS");
26132    pragma Export (C, u00038, "interfacesS");
26133    pragma Export (C, u00039, "interfaces__c_streamsB");
26134    pragma Export (C, u00040, "interfaces__c_streamsS");
26135    pragma Export (C, u00041, "system__file_ioB");
26136    pragma Export (C, u00042, "system__file_ioS");
26137    pragma Export (C, u00043, "ada__finalizationB");
26138    pragma Export (C, u00044, "ada__finalizationS");
26139    pragma Export (C, u00045, "system__finalization_rootB");
26140    pragma Export (C, u00046, "system__finalization_rootS");
26141    pragma Export (C, u00047, "system__finalization_implementationB");
26142    pragma Export (C, u00048, "system__finalization_implementationS");
26143    pragma Export (C, u00049, "system__string_ops_concat_3B");
26144    pragma Export (C, u00050, "system__string_ops_concat_3S");
26145    pragma Export (C, u00051, "system__stream_attributesB");
26146    pragma Export (C, u00052, "system__stream_attributesS");
26147    pragma Export (C, u00053, "ada__io_exceptionsS");
26148    pragma Export (C, u00054, "system__unsigned_typesS");
26149    pragma Export (C, u00055, "system__file_control_blockS");
26150    pragma Export (C, u00056, "ada__finalization__list_controllerB");
26151    pragma Export (C, u00057, "ada__finalization__list_controllerS");
26152
26153    -- BEGIN ELABORATION ORDER
26154    -- ada (spec)
26155    -- gnat (spec)
26156    -- gnat.heap_sort_a (spec)
26157    -- gnat.heap_sort_a (body)
26158    -- gnat.htable (spec)
26159    -- gnat.htable (body)
26160    -- interfaces (spec)
26161    -- system (spec)
26162    -- system.machine_code (spec)
26163    -- system.parameters (spec)
26164    -- system.parameters (body)
26165    -- interfaces.c_streams (spec)
26166    -- interfaces.c_streams (body)
26167    -- system.standard_library (spec)
26168    -- ada.exceptions (spec)
26169    -- system.exception_table (spec)
26170    -- system.exception_table (body)
26171    -- ada.io_exceptions (spec)
26172    -- system.exceptions (spec)
26173    -- system.storage_elements (spec)
26174    -- system.storage_elements (body)
26175    -- system.machine_state_operations (spec)
26176    -- system.machine_state_operations (body)
26177    -- system.secondary_stack (spec)
26178    -- system.stack_checking (spec)
26179    -- system.soft_links (spec)
26180    -- system.soft_links (body)
26181    -- system.stack_checking (body)
26182    -- system.secondary_stack (body)
26183    -- system.standard_library (body)
26184    -- system.string_ops (spec)
26185    -- system.string_ops (body)
26186    -- ada.tags (spec)
26187    -- ada.tags (body)
26188    -- ada.streams (spec)
26189    -- system.finalization_root (spec)
26190    -- system.finalization_root (body)
26191    -- system.string_ops_concat_3 (spec)
26192    -- system.string_ops_concat_3 (body)
26193    -- system.traceback (spec)
26194    -- system.traceback (body)
26195    -- ada.exceptions (body)
26196    -- system.unsigned_types (spec)
26197    -- system.stream_attributes (spec)
26198    -- system.stream_attributes (body)
26199    -- system.finalization_implementation (spec)
26200    -- system.finalization_implementation (body)
26201    -- ada.finalization (spec)
26202    -- ada.finalization (body)
26203    -- ada.finalization.list_controller (spec)
26204    -- ada.finalization.list_controller (body)
26205    -- system.file_control_block (spec)
26206    -- system.file_io (spec)
26207    -- system.file_io (body)
26208    -- ada.text_io (spec)
26209    -- ada.text_io (body)
26210    -- hello (body)
26211    -- END ELABORATION ORDER
26212
26213 end ada_main;
26214
26215 --  The following source file name pragmas allow the generated file
26216 --  names to be unique for different main programs. They are needed
26217 --  since the package name will always be Ada_Main.
26218
26219 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
26220 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
26221
26222 --  Generated package body for Ada_Main starts here
26223
26224 package body ada_main is
26225
26226    --  The actual finalization is performed by calling the
26227    --  library routine in System.Standard_Library.Adafinal
26228
26229    procedure Do_Finalize;
26230    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
26231
26232    -------------
26233    -- adainit --
26234    -------------
26235
26236 @findex adainit
26237    procedure adainit is
26238
26239       --  These booleans are set to True once the associated unit has
26240       --  been elaborated. It is also used to avoid elaborating the
26241       --  same unit twice.
26242
26243       E040 : Boolean;
26244       pragma Import (Ada, E040, "interfaces__c_streams_E");
26245
26246       E008 : Boolean;
26247       pragma Import (Ada, E008, "ada__exceptions_E");
26248
26249       E014 : Boolean;
26250       pragma Import (Ada, E014, "system__exception_table_E");
26251
26252       E053 : Boolean;
26253       pragma Import (Ada, E053, "ada__io_exceptions_E");
26254
26255       E017 : Boolean;
26256       pragma Import (Ada, E017, "system__exceptions_E");
26257
26258       E024 : Boolean;
26259       pragma Import (Ada, E024, "system__secondary_stack_E");
26260
26261       E030 : Boolean;
26262       pragma Import (Ada, E030, "system__stack_checking_E");
26263
26264       E028 : Boolean;
26265       pragma Import (Ada, E028, "system__soft_links_E");
26266
26267       E035 : Boolean;
26268       pragma Import (Ada, E035, "ada__tags_E");
26269
26270       E033 : Boolean;
26271       pragma Import (Ada, E033, "ada__streams_E");
26272
26273       E046 : Boolean;
26274       pragma Import (Ada, E046, "system__finalization_root_E");
26275
26276       E048 : Boolean;
26277       pragma Import (Ada, E048, "system__finalization_implementation_E");
26278
26279       E044 : Boolean;
26280       pragma Import (Ada, E044, "ada__finalization_E");
26281
26282       E057 : Boolean;
26283       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
26284
26285       E055 : Boolean;
26286       pragma Import (Ada, E055, "system__file_control_block_E");
26287
26288       E042 : Boolean;
26289       pragma Import (Ada, E042, "system__file_io_E");
26290
26291       E006 : Boolean;
26292       pragma Import (Ada, E006, "ada__text_io_E");
26293
26294       --  Set_Globals is a library routine that stores away the
26295       --  value of the indicated set of global values in global
26296       --  variables within the library.
26297
26298       procedure Set_Globals
26299         (Main_Priority            : Integer;
26300          Time_Slice_Value         : Integer;
26301          WC_Encoding              : Character;
26302          Locking_Policy           : Character;
26303          Queuing_Policy           : Character;
26304          Task_Dispatching_Policy  : Character;
26305          Adafinal                 : System.Address;
26306          Unreserve_All_Interrupts : Integer;
26307          Exception_Tracebacks     : Integer);
26308 @findex __gnat_set_globals
26309       pragma Import (C, Set_Globals, "__gnat_set_globals");
26310
26311       --  SDP_Table_Build is a library routine used to build the
26312       --  exception tables. See unit Ada.Exceptions in files
26313       --  a-except.ads/adb for full details of how zero cost
26314       --  exception handling works. This procedure, the call to
26315       --  it, and the two following tables are all omitted if the
26316       --  build is in longjmp/setjmp exception mode.
26317
26318 @findex SDP_Table_Build
26319 @findex Zero Cost Exceptions
26320       procedure SDP_Table_Build
26321         (SDP_Addresses   : System.Address;
26322          SDP_Count       : Natural;
26323          Elab_Addresses  : System.Address;
26324          Elab_Addr_Count : Natural);
26325       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
26326
26327       --  Table of Unit_Exception_Table addresses. Used for zero
26328       --  cost exception handling to build the top level table.
26329
26330       ST : aliased constant array (1 .. 23) of System.Address := (
26331         Hello'UET_Address,
26332         Ada.Text_Io'UET_Address,
26333         Ada.Exceptions'UET_Address,
26334         Gnat.Heap_Sort_A'UET_Address,
26335         System.Exception_Table'UET_Address,
26336         System.Machine_State_Operations'UET_Address,
26337         System.Secondary_Stack'UET_Address,
26338         System.Parameters'UET_Address,
26339         System.Soft_Links'UET_Address,
26340         System.Stack_Checking'UET_Address,
26341         System.Traceback'UET_Address,
26342         Ada.Streams'UET_Address,
26343         Ada.Tags'UET_Address,
26344         System.String_Ops'UET_Address,
26345         Interfaces.C_Streams'UET_Address,
26346         System.File_Io'UET_Address,
26347         Ada.Finalization'UET_Address,
26348         System.Finalization_Root'UET_Address,
26349         System.Finalization_Implementation'UET_Address,
26350         System.String_Ops_Concat_3'UET_Address,
26351         System.Stream_Attributes'UET_Address,
26352         System.File_Control_Block'UET_Address,
26353         Ada.Finalization.List_Controller'UET_Address);
26354
26355       --  Table of addresses of elaboration routines. Used for
26356       --  zero cost exception handling to make sure these
26357       --  addresses are included in the top level procedure
26358       --  address table.
26359
26360       EA : aliased constant array (1 .. 23) of System.Address := (
26361         adainit'Code_Address,
26362         Do_Finalize'Code_Address,
26363         Ada.Exceptions'Elab_Spec'Address,
26364         System.Exceptions'Elab_Spec'Address,
26365         Interfaces.C_Streams'Elab_Spec'Address,
26366         System.Exception_Table'Elab_Body'Address,
26367         Ada.Io_Exceptions'Elab_Spec'Address,
26368         System.Stack_Checking'Elab_Spec'Address,
26369         System.Soft_Links'Elab_Body'Address,
26370         System.Secondary_Stack'Elab_Body'Address,
26371         Ada.Tags'Elab_Spec'Address,
26372         Ada.Tags'Elab_Body'Address,
26373         Ada.Streams'Elab_Spec'Address,
26374         System.Finalization_Root'Elab_Spec'Address,
26375         Ada.Exceptions'Elab_Body'Address,
26376         System.Finalization_Implementation'Elab_Spec'Address,
26377         System.Finalization_Implementation'Elab_Body'Address,
26378         Ada.Finalization'Elab_Spec'Address,
26379         Ada.Finalization.List_Controller'Elab_Spec'Address,
26380         System.File_Control_Block'Elab_Spec'Address,
26381         System.File_Io'Elab_Body'Address,
26382         Ada.Text_Io'Elab_Spec'Address,
26383         Ada.Text_Io'Elab_Body'Address);
26384
26385    --  Start of processing for adainit
26386
26387    begin
26388
26389       --  Call SDP_Table_Build to build the top level procedure
26390       --  table for zero cost exception handling (omitted in
26391       --  longjmp/setjmp mode).
26392
26393       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
26394
26395       --  Call Set_Globals to record various information for
26396       --  this partition.  The values are derived by the binder
26397       --  from information stored in the ali files by the compiler.
26398
26399 @findex __gnat_set_globals
26400       Set_Globals
26401         (Main_Priority            => -1,
26402          --  Priority of main program, -1 if no pragma Priority used
26403
26404          Time_Slice_Value         => -1,
26405          --  Time slice from Time_Slice pragma, -1 if none used
26406
26407          WC_Encoding              => 'b',
26408          --  Wide_Character encoding used, default is brackets
26409
26410          Locking_Policy           => ' ',
26411          --  Locking_Policy used, default of space means not
26412          --  specified, otherwise it is the first character of
26413          --  the policy name.
26414
26415          Queuing_Policy           => ' ',
26416          --  Queuing_Policy used, default of space means not
26417          --  specified, otherwise it is the first character of
26418          --  the policy name.
26419
26420          Task_Dispatching_Policy  => ' ',
26421          --  Task_Dispatching_Policy used, default of space means
26422          --  not specified, otherwise first character of the
26423          --  policy name.
26424
26425          Adafinal                 => System.Null_Address,
26426          --  Address of Adafinal routine, not used anymore
26427
26428          Unreserve_All_Interrupts => 0,
26429          --  Set true if pragma Unreserve_All_Interrupts was used
26430
26431          Exception_Tracebacks     => 0);
26432          --  Indicates if exception tracebacks are enabled
26433
26434       Elab_Final_Code := 1;
26435
26436       --  Now we have the elaboration calls for all units in the partition.
26437       --  The Elab_Spec and Elab_Body attributes generate references to the
26438       --  implicit elaboration procedures generated by the compiler for
26439       --  each unit that requires elaboration.
26440
26441       if not E040 then
26442          Interfaces.C_Streams'Elab_Spec;
26443       end if;
26444       E040 := True;
26445       if not E008 then
26446          Ada.Exceptions'Elab_Spec;
26447       end if;
26448       if not E014 then
26449          System.Exception_Table'Elab_Body;
26450          E014 := True;
26451       end if;
26452       if not E053 then
26453          Ada.Io_Exceptions'Elab_Spec;
26454          E053 := True;
26455       end if;
26456       if not E017 then
26457          System.Exceptions'Elab_Spec;
26458          E017 := True;
26459       end if;
26460       if not E030 then
26461          System.Stack_Checking'Elab_Spec;
26462       end if;
26463       if not E028 then
26464          System.Soft_Links'Elab_Body;
26465          E028 := True;
26466       end if;
26467       E030 := True;
26468       if not E024 then
26469          System.Secondary_Stack'Elab_Body;
26470          E024 := True;
26471       end if;
26472       if not E035 then
26473          Ada.Tags'Elab_Spec;
26474       end if;
26475       if not E035 then
26476          Ada.Tags'Elab_Body;
26477          E035 := True;
26478       end if;
26479       if not E033 then
26480          Ada.Streams'Elab_Spec;
26481          E033 := True;
26482       end if;
26483       if not E046 then
26484          System.Finalization_Root'Elab_Spec;
26485       end if;
26486       E046 := True;
26487       if not E008 then
26488          Ada.Exceptions'Elab_Body;
26489          E008 := True;
26490       end if;
26491       if not E048 then
26492          System.Finalization_Implementation'Elab_Spec;
26493       end if;
26494       if not E048 then
26495          System.Finalization_Implementation'Elab_Body;
26496          E048 := True;
26497       end if;
26498       if not E044 then
26499          Ada.Finalization'Elab_Spec;
26500       end if;
26501       E044 := True;
26502       if not E057 then
26503          Ada.Finalization.List_Controller'Elab_Spec;
26504       end if;
26505       E057 := True;
26506       if not E055 then
26507          System.File_Control_Block'Elab_Spec;
26508          E055 := True;
26509       end if;
26510       if not E042 then
26511          System.File_Io'Elab_Body;
26512          E042 := True;
26513       end if;
26514       if not E006 then
26515          Ada.Text_Io'Elab_Spec;
26516       end if;
26517       if not E006 then
26518          Ada.Text_Io'Elab_Body;
26519          E006 := True;
26520       end if;
26521
26522       Elab_Final_Code := 0;
26523    end adainit;
26524
26525    --------------
26526    -- adafinal --
26527    --------------
26528
26529 @findex adafinal
26530    procedure adafinal is
26531    begin
26532       Do_Finalize;
26533    end adafinal;
26534
26535    ----------
26536    -- main --
26537    ----------
26538
26539    --  main is actually a function, as in the ANSI C standard,
26540    --  defined to return the exit status. The three parameters
26541    --  are the argument count, argument values and environment
26542    --  pointer.
26543
26544 @findex Main Program
26545    function main
26546      (argc : Integer;
26547       argv : System.Address;
26548       envp : System.Address)
26549       return Integer
26550    is
26551       --  The initialize routine performs low level system
26552       --  initialization using a standard library routine which
26553       --  sets up signal handling and performs any other
26554       --  required setup. The routine can be found in file
26555       --  a-init.c.
26556
26557 @findex __gnat_initialize
26558       procedure initialize;
26559       pragma Import (C, initialize, "__gnat_initialize");
26560
26561       --  The finalize routine performs low level system
26562       --  finalization using a standard library routine. The
26563       --  routine is found in file a-final.c and in the standard
26564       --  distribution is a dummy routine that does nothing, so
26565       --  really this is a hook for special user finalization.
26566
26567 @findex __gnat_finalize
26568       procedure finalize;
26569       pragma Import (C, finalize, "__gnat_finalize");
26570
26571       --  We get to the main program of the partition by using
26572       --  pragma Import because if we try to with the unit and
26573       --  call it Ada style, then not only do we waste time
26574       --  recompiling it, but also, we don't really know the right
26575       --  switches (e.g.@: identifier character set) to be used
26576       --  to compile it.
26577
26578       procedure Ada_Main_Program;
26579       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
26580
26581    --  Start of processing for main
26582
26583    begin
26584       --  Save global variables
26585
26586       gnat_argc := argc;
26587       gnat_argv := argv;
26588       gnat_envp := envp;
26589
26590       --  Call low level system initialization
26591
26592       Initialize;
26593
26594       --  Call our generated Ada initialization routine
26595
26596       adainit;
26597
26598       --  This is the point at which we want the debugger to get
26599       --  control
26600
26601       Break_Start;
26602
26603       --  Now we call the main program of the partition
26604
26605       Ada_Main_Program;
26606
26607       --  Perform Ada finalization
26608
26609       adafinal;
26610
26611       --  Perform low level system finalization
26612
26613       Finalize;
26614
26615       --  Return the proper exit status
26616       return (gnat_exit_status);
26617    end;
26618
26619 --  This section is entirely comments, so it has no effect on the
26620 --  compilation of the Ada_Main package. It provides the list of
26621 --  object files and linker options, as well as some standard
26622 --  libraries needed for the link. The gnatlink utility parses
26623 --  this b~hello.adb file to read these comment lines to generate
26624 --  the appropriate command line arguments for the call to the
26625 --  system linker. The BEGIN/END lines are used for sentinels for
26626 --  this parsing operation.
26627
26628 --  The exact file names will of course depend on the environment,
26629 --  host/target and location of files on the host system.
26630
26631 @findex Object file list
26632 -- BEGIN Object file/option list
26633    --   ./hello.o
26634    --   -L./
26635    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
26636    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
26637 -- END Object file/option list
26638
26639 end ada_main;
26640 @end smallexample
26641
26642 @noindent
26643 The Ada code in the above example is exactly what is generated by the
26644 binder. We have added comments to more clearly indicate the function
26645 of each part of the generated @code{Ada_Main} package.
26646
26647 The code is standard Ada in all respects, and can be processed by any
26648 tools that handle Ada. In particular, it is possible to use the debugger
26649 in Ada mode to debug the generated @code{Ada_Main} package. For example,
26650 suppose that for reasons that you do not understand, your program is crashing
26651 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
26652 you can place a breakpoint on the call:
26653
26654 @smallexample @c ada
26655 Ada.Text_Io'Elab_Body;
26656 @end smallexample
26657
26658 @noindent
26659 and trace the elaboration routine for this package to find out where
26660 the problem might be (more usually of course you would be debugging
26661 elaboration code in your own application).
26662
26663 @node Elaboration Order Handling in GNAT
26664 @appendix Elaboration Order Handling in GNAT
26665 @cindex Order of elaboration
26666 @cindex Elaboration control
26667
26668 @menu
26669 * Elaboration Code::
26670 * Checking the Elaboration Order::
26671 * Controlling the Elaboration Order::
26672 * Controlling Elaboration in GNAT - Internal Calls::
26673 * Controlling Elaboration in GNAT - External Calls::
26674 * Default Behavior in GNAT - Ensuring Safety::
26675 * Treatment of Pragma Elaborate::
26676 * Elaboration Issues for Library Tasks::
26677 * Mixing Elaboration Models::
26678 * What to Do If the Default Elaboration Behavior Fails::
26679 * Elaboration for Access-to-Subprogram Values::
26680 * Summary of Procedures for Elaboration Control::
26681 * Other Elaboration Order Considerations::
26682 @end menu
26683
26684 @noindent
26685 This chapter describes the handling of elaboration code in Ada and
26686 in GNAT, and discusses how the order of elaboration of program units can
26687 be controlled in GNAT, either automatically or with explicit programming
26688 features.
26689
26690 @node Elaboration Code
26691 @section Elaboration Code
26692
26693 @noindent
26694 Ada provides rather general mechanisms for executing code at elaboration
26695 time, that is to say before the main program starts executing. Such code arises
26696 in three contexts:
26697
26698 @table @asis
26699 @item Initializers for variables.
26700 Variables declared at the library level, in package specs or bodies, can
26701 require initialization that is performed at elaboration time, as in:
26702 @smallexample @c ada
26703 @cartouche
26704 Sqrt_Half : Float := Sqrt (0.5);
26705 @end cartouche
26706 @end smallexample
26707
26708 @item Package initialization code
26709 Code in a @code{BEGIN-END} section at the outer level of a package body is
26710 executed as part of the package body elaboration code.
26711
26712 @item Library level task allocators
26713 Tasks that are declared using task allocators at the library level
26714 start executing immediately and hence can execute at elaboration time.
26715 @end table
26716
26717 @noindent
26718 Subprogram calls are possible in any of these contexts, which means that
26719 any arbitrary part of the program may be executed as part of the elaboration
26720 code. It is even possible to write a program which does all its work at
26721 elaboration time, with a null main program, although stylistically this
26722 would usually be considered an inappropriate way to structure
26723 a program.
26724
26725 An important concern arises in the context of elaboration code:
26726 we have to be sure that it is executed in an appropriate order. What we
26727 have is a series of elaboration code sections, potentially one section
26728 for each unit in the program. It is important that these execute
26729 in the correct order. Correctness here means that, taking the above
26730 example of the declaration of @code{Sqrt_Half},
26731 if some other piece of
26732 elaboration code references @code{Sqrt_Half},
26733 then it must run after the
26734 section of elaboration code that contains the declaration of
26735 @code{Sqrt_Half}.
26736
26737 There would never be any order of elaboration problem if we made a rule
26738 that whenever you @code{with} a unit, you must elaborate both the spec and body
26739 of that unit before elaborating the unit doing the @code{with}'ing:
26740
26741 @smallexample @c ada
26742 @group
26743 @cartouche
26744 with Unit_1;
26745 package Unit_2 is @dots{}
26746 @end cartouche
26747 @end group
26748 @end smallexample
26749
26750 @noindent
26751 would require that both the body and spec of @code{Unit_1} be elaborated
26752 before the spec of @code{Unit_2}. However, a rule like that would be far too
26753 restrictive. In particular, it would make it impossible to have routines
26754 in separate packages that were mutually recursive.
26755
26756 You might think that a clever enough compiler could look at the actual
26757 elaboration code and determine an appropriate correct order of elaboration,
26758 but in the general case, this is not possible. Consider the following
26759 example.
26760
26761 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
26762 that references
26763 the variable @code{Sqrt_1}, which is declared in the elaboration code
26764 of the body of @code{Unit_1}:
26765
26766 @smallexample @c ada
26767 @cartouche
26768 Sqrt_1 : Float := Sqrt (0.1);
26769 @end cartouche
26770 @end smallexample
26771
26772 @noindent
26773 The elaboration code of the body of @code{Unit_1} also contains:
26774
26775 @smallexample @c ada
26776 @group
26777 @cartouche
26778 if expression_1 = 1 then
26779    Q := Unit_2.Func_2;
26780 end if;
26781 @end cartouche
26782 @end group
26783 @end smallexample
26784
26785 @noindent
26786 @code{Unit_2} is exactly parallel,
26787 it has a procedure @code{Func_2} that references
26788 the variable @code{Sqrt_2}, which is declared in the elaboration code of
26789 the body @code{Unit_2}:
26790
26791 @smallexample @c ada
26792 @cartouche
26793 Sqrt_2 : Float := Sqrt (0.1);
26794 @end cartouche
26795 @end smallexample
26796
26797 @noindent
26798 The elaboration code of the body of @code{Unit_2} also contains:
26799
26800 @smallexample @c ada
26801 @group
26802 @cartouche
26803 if expression_2 = 2 then
26804    Q := Unit_1.Func_1;
26805 end if;
26806 @end cartouche
26807 @end group
26808 @end smallexample
26809
26810 @noindent
26811 Now the question is, which of the following orders of elaboration is
26812 acceptable:
26813
26814 @smallexample
26815 @group
26816 Spec of Unit_1
26817 Spec of Unit_2
26818 Body of Unit_1
26819 Body of Unit_2
26820 @end group
26821 @end smallexample
26822
26823 @noindent
26824 or
26825
26826 @smallexample
26827 @group
26828 Spec of Unit_2
26829 Spec of Unit_1
26830 Body of Unit_2
26831 Body of Unit_1
26832 @end group
26833 @end smallexample
26834
26835 @noindent
26836 If you carefully analyze the flow here, you will see that you cannot tell
26837 at compile time the answer to this question.
26838 If @code{expression_1} is not equal to 1,
26839 and @code{expression_2} is not equal to 2,
26840 then either order is acceptable, because neither of the function calls is
26841 executed. If both tests evaluate to true, then neither order is acceptable
26842 and in fact there is no correct order.
26843
26844 If one of the two expressions is true, and the other is false, then one
26845 of the above orders is correct, and the other is incorrect. For example,
26846 if @code{expression_1} /= 1 and @code{expression_2} = 2,
26847 then the call to @code{Func_1}
26848 will occur, but not the call to @code{Func_2.}
26849 This means that it is essential
26850 to elaborate the body of @code{Unit_1} before
26851 the body of @code{Unit_2}, so the first
26852 order of elaboration is correct and the second is wrong.
26853
26854 By making @code{expression_1} and @code{expression_2}
26855 depend on input data, or perhaps
26856 the time of day, we can make it impossible for the compiler or binder
26857 to figure out which of these expressions will be true, and hence it
26858 is impossible to guarantee a safe order of elaboration at run time.
26859
26860 @node Checking the Elaboration Order
26861 @section Checking the Elaboration Order
26862
26863 @noindent
26864 In some languages that involve the same kind of elaboration problems,
26865 e.g.@: Java and C++, the programmer is expected to worry about these
26866 ordering problems himself, and it is common to
26867 write a program in which an incorrect elaboration order  gives
26868 surprising results, because it references variables before they
26869 are initialized.
26870 Ada is designed to be a safe language, and a programmer-beware approach is
26871 clearly not sufficient. Consequently, the language provides three lines
26872 of defense:
26873
26874 @table @asis
26875 @item Standard rules
26876 Some standard rules restrict the possible choice of elaboration
26877 order. In particular, if you @code{with} a unit, then its spec is always
26878 elaborated before the unit doing the @code{with}. Similarly, a parent
26879 spec is always elaborated before the child spec, and finally
26880 a spec is always elaborated before its corresponding body.
26881
26882 @item Dynamic elaboration checks
26883 @cindex Elaboration checks
26884 @cindex Checks, elaboration
26885 Dynamic checks are made at run time, so that if some entity is accessed
26886 before it is elaborated (typically  by means of a subprogram call)
26887 then the exception (@code{Program_Error}) is raised.
26888
26889 @item Elaboration control
26890 Facilities are provided for the programmer to specify the desired order
26891 of elaboration.
26892 @end table
26893
26894 Let's look at these facilities in more detail. First, the rules for
26895 dynamic checking. One possible rule would be simply to say that the
26896 exception is raised if you access a variable which has not yet been
26897 elaborated. The trouble with this approach is that it could require
26898 expensive checks on every variable reference. Instead Ada has two
26899 rules which are a little more restrictive, but easier to check, and
26900 easier to state:
26901
26902 @table @asis
26903 @item Restrictions on calls
26904 A subprogram can only be called at elaboration time if its body
26905 has been elaborated. The rules for elaboration given above guarantee
26906 that the spec of the subprogram has been elaborated before the
26907 call, but not the body. If this rule is violated, then the
26908 exception @code{Program_Error} is raised.
26909
26910 @item Restrictions on instantiations
26911 A generic unit can only be instantiated if the body of the generic
26912 unit has been elaborated. Again, the rules for elaboration given above
26913 guarantee that the spec of the generic unit has been elaborated
26914 before the instantiation, but not the body. If this rule is
26915 violated, then the exception @code{Program_Error} is raised.
26916 @end table
26917
26918 @noindent
26919 The idea is that if the body has been elaborated, then any variables
26920 it references must have been elaborated; by checking for the body being
26921 elaborated we guarantee that none of its references causes any
26922 trouble. As we noted above, this is a little too restrictive, because a
26923 subprogram that has no non-local references in its body may in fact be safe
26924 to call. However, it really would be unsafe to rely on this, because
26925 it would mean that the caller was aware of details of the implementation
26926 in the body. This goes against the basic tenets of Ada.
26927
26928 A plausible implementation can be described as follows.
26929 A Boolean variable is associated with each subprogram
26930 and each generic unit. This variable is initialized to False, and is set to
26931 True at the point body is elaborated. Every call or instantiation checks the
26932 variable, and raises @code{Program_Error} if the variable is False.
26933
26934 Note that one might think that it would be good enough to have one Boolean
26935 variable for each package, but that would not deal with cases of trying
26936 to call a body in the same package as the call
26937 that has not been elaborated yet.
26938 Of course a compiler may be able to do enough analysis to optimize away
26939 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
26940 does such optimizations, but still the easiest conceptual model is to
26941 think of there being one variable per subprogram.
26942
26943 @node Controlling the Elaboration Order
26944 @section Controlling the Elaboration Order
26945
26946 @noindent
26947 In the previous section we discussed the rules in Ada which ensure
26948 that @code{Program_Error} is raised if an incorrect elaboration order is
26949 chosen. This prevents erroneous executions, but we need mechanisms to
26950 specify a correct execution and avoid the exception altogether.
26951 To achieve this, Ada provides a number of features for controlling
26952 the order of elaboration. We discuss these features in this section.
26953
26954 First, there are several ways of indicating to the compiler that a given
26955 unit has no elaboration problems:
26956
26957 @table @asis
26958 @item packages that do not require a body
26959 A library package that does not require a body does not permit
26960 a body (this rule was introduced in Ada 95).
26961 Thus if we have a such a package, as in:
26962
26963 @smallexample @c ada
26964 @group
26965 @cartouche
26966 package Definitions is
26967    generic
26968       type m is new integer;
26969    package Subp is
26970       type a is array (1 .. 10) of m;
26971       type b is array (1 .. 20) of m;
26972    end Subp;
26973 end Definitions;
26974 @end cartouche
26975 @end group
26976 @end smallexample
26977
26978 @noindent
26979 A package that @code{with}'s @code{Definitions} may safely instantiate
26980 @code{Definitions.Subp} because the compiler can determine that there
26981 definitely is no package body to worry about in this case
26982
26983 @item pragma Pure
26984 @cindex pragma Pure
26985 @findex Pure
26986 Places sufficient restrictions on a unit to guarantee that
26987 no call to any subprogram in the unit can result in an
26988 elaboration problem. This means that the compiler does not need
26989 to worry about the point of elaboration of such units, and in
26990 particular, does not need to check any calls to any subprograms
26991 in this unit.
26992
26993 @item pragma Preelaborate
26994 @findex Preelaborate
26995 @cindex pragma Preelaborate
26996 This pragma places slightly less stringent restrictions on a unit than
26997 does pragma Pure,
26998 but these restrictions are still sufficient to ensure that there
26999 are no elaboration problems with any calls to the unit.
27000
27001 @item pragma Elaborate_Body
27002 @findex Elaborate_Body
27003 @cindex pragma Elaborate_Body
27004 This pragma requires that the body of a unit be elaborated immediately
27005 after its spec. Suppose a unit @code{A} has such a pragma,
27006 and unit @code{B} does
27007 a @code{with} of unit @code{A}. Recall that the standard rules require
27008 the spec of unit @code{A}
27009 to be elaborated before the @code{with}'ing unit; given the pragma in
27010 @code{A}, we also know that the body of @code{A}
27011 will be elaborated before @code{B}, so
27012 that calls to @code{A} are safe and do not need a check.
27013 @end table
27014
27015 @noindent
27016 Note that,
27017 unlike pragma @code{Pure} and pragma @code{Preelaborate},
27018 the use of
27019 @code{Elaborate_Body} does not guarantee that the program is
27020 free of elaboration problems, because it may not be possible
27021 to satisfy the requested elaboration order.
27022 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
27023 If a programmer
27024 marks @code{Unit_1} as @code{Elaborate_Body},
27025 and not @code{Unit_2,} then the order of
27026 elaboration will be:
27027
27028 @smallexample
27029 @group
27030 Spec of Unit_2
27031 Spec of Unit_1
27032 Body of Unit_1
27033 Body of Unit_2
27034 @end group
27035 @end smallexample
27036
27037 @noindent
27038 Now that means that the call to @code{Func_1} in @code{Unit_2}
27039 need not be checked,
27040 it must be safe. But the call to @code{Func_2} in
27041 @code{Unit_1} may still fail if
27042 @code{Expression_1} is equal to 1,
27043 and the programmer must still take
27044 responsibility for this not being the case.
27045
27046 If all units carry a pragma @code{Elaborate_Body}, then all problems are
27047 eliminated, except for calls entirely within a body, which are
27048 in any case fully under programmer control. However, using the pragma
27049 everywhere is not always possible.
27050 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
27051 we marked both of them as having pragma @code{Elaborate_Body}, then
27052 clearly there would be no possible elaboration order.
27053
27054 The above pragmas allow a server to guarantee safe use by clients, and
27055 clearly this is the preferable approach. Consequently a good rule
27056 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
27057 and if this is not possible,
27058 mark them as @code{Elaborate_Body} if possible.
27059 As we have seen, there are situations where neither of these
27060 three pragmas can be used.
27061 So we also provide methods for clients to control the
27062 order of elaboration of the servers on which they depend:
27063
27064 @table @asis
27065 @item pragma Elaborate (unit)
27066 @findex Elaborate
27067 @cindex pragma Elaborate
27068 This pragma is placed in the context clause, after a @code{with} clause,
27069 and it requires that the body of the named unit be elaborated before
27070 the unit in which the pragma occurs. The idea is to use this pragma
27071 if the current unit calls at elaboration time, directly or indirectly,
27072 some subprogram in the named unit.
27073
27074 @item pragma Elaborate_All (unit)
27075 @findex Elaborate_All
27076 @cindex pragma Elaborate_All
27077 This is a stronger version of the Elaborate pragma. Consider the
27078 following example:
27079
27080 @smallexample
27081 Unit A @code{with}'s unit B and calls B.Func in elab code
27082 Unit B @code{with}'s unit C, and B.Func calls C.Func
27083 @end smallexample
27084
27085 @noindent
27086 Now if we put a pragma @code{Elaborate (B)}
27087 in unit @code{A}, this ensures that the
27088 body of @code{B} is elaborated before the call, but not the
27089 body of @code{C}, so
27090 the call to @code{C.Func} could still cause @code{Program_Error} to
27091 be raised.
27092
27093 The effect of a pragma @code{Elaborate_All} is stronger, it requires
27094 not only that the body of the named unit be elaborated before the
27095 unit doing the @code{with}, but also the bodies of all units that the
27096 named unit uses, following @code{with} links transitively. For example,
27097 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
27098 then it requires
27099 not only that the body of @code{B} be elaborated before @code{A},
27100 but also the
27101 body of @code{C}, because @code{B} @code{with}'s @code{C}.
27102 @end table
27103
27104 @noindent
27105 We are now in a position to give a usage rule in Ada for avoiding
27106 elaboration problems, at least if dynamic dispatching and access to
27107 subprogram values are not used. We will handle these cases separately
27108 later.
27109
27110 The rule is simple. If a unit has elaboration code that can directly or
27111 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
27112 a generic package in a @code{with}'ed unit,
27113 then if the @code{with}'ed unit does not have
27114 pragma @code{Pure} or @code{Preelaborate}, then the client should have
27115 a pragma @code{Elaborate_All}
27116 for the @code{with}'ed unit. By following this rule a client is
27117 assured that calls can be made without risk of an exception.
27118
27119 For generic subprogram instantiations, the rule can be relaxed to
27120 require only a pragma @code{Elaborate} since elaborating the body
27121 of a subprogram cannot cause any transitive elaboration (we are
27122 not calling the subprogram in this case, just elaborating its
27123 declaration).
27124
27125 If this rule is not followed, then a program may be in one of four
27126 states:
27127
27128 @table @asis
27129 @item No order exists
27130 No order of elaboration exists which follows the rules, taking into
27131 account any @code{Elaborate}, @code{Elaborate_All},
27132 or @code{Elaborate_Body} pragmas. In
27133 this case, an Ada compiler must diagnose the situation at bind
27134 time, and refuse to build an executable program.
27135
27136 @item One or more orders exist, all incorrect
27137 One or more acceptable elaboration orders exist, and all of them
27138 generate an elaboration order problem. In this case, the binder
27139 can build an executable program, but @code{Program_Error} will be raised
27140 when the program is run.
27141
27142 @item Several orders exist, some right, some incorrect
27143 One or more acceptable elaboration orders exists, and some of them
27144 work, and some do not. The programmer has not controlled
27145 the order of elaboration, so the binder may or may not pick one of
27146 the correct orders, and the program may or may not raise an
27147 exception when it is run. This is the worst case, because it means
27148 that the program may fail when moved to another compiler, or even
27149 another version of the same compiler.
27150
27151 @item One or more orders exists, all correct
27152 One ore more acceptable elaboration orders exist, and all of them
27153 work. In this case the program runs successfully. This state of
27154 affairs can be guaranteed by following the rule we gave above, but
27155 may be true even if the rule is not followed.
27156 @end table
27157
27158 @noindent
27159 Note that one additional advantage of following our rules on the use
27160 of @code{Elaborate} and @code{Elaborate_All}
27161 is that the program continues to stay in the ideal (all orders OK) state
27162 even if maintenance
27163 changes some bodies of some units. Conversely, if a program that does
27164 not follow this rule happens to be safe at some point, this state of affairs
27165 may deteriorate silently as a result of maintenance changes.
27166
27167 You may have noticed that the above discussion did not mention
27168 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
27169 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
27170 code in the body makes calls to some other unit, so it is still necessary
27171 to use @code{Elaborate_All} on such units.
27172
27173 @node Controlling Elaboration in GNAT - Internal Calls
27174 @section Controlling Elaboration in GNAT - Internal Calls
27175
27176 @noindent
27177 In the case of internal calls, i.e., calls within a single package, the
27178 programmer has full control over the order of elaboration, and it is up
27179 to the programmer to elaborate declarations in an appropriate order. For
27180 example writing:
27181
27182 @smallexample @c ada
27183 @group
27184 @cartouche
27185 function One return Float;
27186
27187 Q : Float := One;
27188
27189 function One return Float is
27190 begin
27191      return 1.0;
27192 end One;
27193 @end cartouche
27194 @end group
27195 @end smallexample
27196
27197 @noindent
27198 will obviously raise @code{Program_Error} at run time, because function
27199 One will be called before its body is elaborated. In this case GNAT will
27200 generate a warning that the call will raise @code{Program_Error}:
27201
27202 @smallexample
27203 @group
27204 @cartouche
27205  1. procedure y is
27206  2.    function One return Float;
27207  3.
27208  4.    Q : Float := One;
27209                     |
27210     >>> warning: cannot call "One" before body is elaborated
27211     >>> warning: Program_Error will be raised at run time
27212
27213  5.
27214  6.    function One return Float is
27215  7.    begin
27216  8.         return 1.0;
27217  9.    end One;
27218 10.
27219 11. begin
27220 12.    null;
27221 13. end;
27222 @end cartouche
27223 @end group
27224 @end smallexample
27225
27226 @noindent
27227 Note that in this particular case, it is likely that the call is safe, because
27228 the function @code{One} does not access any global variables.
27229 Nevertheless in Ada, we do not want the validity of the check to depend on
27230 the contents of the body (think about the separate compilation case), so this
27231 is still wrong, as we discussed in the previous sections.
27232
27233 The error is easily corrected by rearranging the declarations so that the
27234 body of @code{One} appears before the declaration containing the call
27235 (note that in Ada 95 and Ada 2005,
27236 declarations can appear in any order, so there is no restriction that
27237 would prevent this reordering, and if we write:
27238
27239 @smallexample @c ada
27240 @group
27241 @cartouche
27242 function One return Float;
27243
27244 function One return Float is
27245 begin
27246      return 1.0;
27247 end One;
27248
27249 Q : Float := One;
27250 @end cartouche
27251 @end group
27252 @end smallexample
27253
27254 @noindent
27255 then all is well, no warning is generated, and no
27256 @code{Program_Error} exception
27257 will be raised.
27258 Things are more complicated when a chain of subprograms is executed:
27259
27260 @smallexample @c ada
27261 @group
27262 @cartouche
27263 function A return Integer;
27264 function B return Integer;
27265 function C return Integer;
27266
27267 function B return Integer is begin return A; end;
27268 function C return Integer is begin return B; end;
27269
27270 X : Integer := C;
27271
27272 function A return Integer is begin return 1; end;
27273 @end cartouche
27274 @end group
27275 @end smallexample
27276
27277 @noindent
27278 Now the call to @code{C}
27279 at elaboration time in the declaration of @code{X} is correct, because
27280 the body of @code{C} is already elaborated,
27281 and the call to @code{B} within the body of
27282 @code{C} is correct, but the call
27283 to @code{A} within the body of @code{B} is incorrect, because the body
27284 of @code{A} has not been elaborated, so @code{Program_Error}
27285 will be raised on the call to @code{A}.
27286 In this case GNAT will generate a
27287 warning that @code{Program_Error} may be
27288 raised at the point of the call. Let's look at the warning:
27289
27290 @smallexample
27291 @group
27292 @cartouche
27293  1. procedure x is
27294  2.    function A return Integer;
27295  3.    function B return Integer;
27296  4.    function C return Integer;
27297  5.
27298  6.    function B return Integer is begin return A; end;
27299                                                     |
27300     >>> warning: call to "A" before body is elaborated may
27301                  raise Program_Error
27302     >>> warning: "B" called at line 7
27303     >>> warning: "C" called at line 9
27304
27305  7.    function C return Integer is begin return B; end;
27306  8.
27307  9.    X : Integer := C;
27308 10.
27309 11.    function A return Integer is begin return 1; end;
27310 12.
27311 13. begin
27312 14.    null;
27313 15. end;
27314 @end cartouche
27315 @end group
27316 @end smallexample
27317
27318 @noindent
27319 Note that the message here says ``may raise'', instead of the direct case,
27320 where the message says ``will be raised''. That's because whether
27321 @code{A} is
27322 actually called depends in general on run-time flow of control.
27323 For example, if the body of @code{B} said
27324
27325 @smallexample @c ada
27326 @group
27327 @cartouche
27328 function B return Integer is
27329 begin
27330    if some-condition-depending-on-input-data then
27331       return A;
27332    else
27333       return 1;
27334    end if;
27335 end B;
27336 @end cartouche
27337 @end group
27338 @end smallexample
27339
27340 @noindent
27341 then we could not know until run time whether the incorrect call to A would
27342 actually occur, so @code{Program_Error} might
27343 or might not be raised. It is possible for a compiler to
27344 do a better job of analyzing bodies, to
27345 determine whether or not @code{Program_Error}
27346 might be raised, but it certainly
27347 couldn't do a perfect job (that would require solving the halting problem
27348 and is provably impossible), and because this is a warning anyway, it does
27349 not seem worth the effort to do the analysis. Cases in which it
27350 would be relevant are rare.
27351
27352 In practice, warnings of either of the forms given
27353 above will usually correspond to
27354 real errors, and should be examined carefully and eliminated.
27355 In the rare case where a warning is bogus, it can be suppressed by any of
27356 the following methods:
27357
27358 @itemize @bullet
27359 @item
27360 Compile with the @option{-gnatws} switch set
27361
27362 @item
27363 Suppress @code{Elaboration_Check} for the called subprogram
27364
27365 @item
27366 Use pragma @code{Warnings_Off} to turn warnings off for the call
27367 @end itemize
27368
27369 @noindent
27370 For the internal elaboration check case,
27371 GNAT by default generates the
27372 necessary run-time checks to ensure
27373 that @code{Program_Error} is raised if any
27374 call fails an elaboration check. Of course this can only happen if a
27375 warning has been issued as described above. The use of pragma
27376 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
27377 some of these checks, meaning that it may be possible (but is not
27378 guaranteed) for a program to be able to call a subprogram whose body
27379 is not yet elaborated, without raising a @code{Program_Error} exception.
27380
27381 @node Controlling Elaboration in GNAT - External Calls
27382 @section Controlling Elaboration in GNAT - External Calls
27383
27384 @noindent
27385 The previous section discussed the case in which the execution of a
27386 particular thread of elaboration code occurred entirely within a
27387 single unit. This is the easy case to handle, because a programmer
27388 has direct and total control over the order of elaboration, and
27389 furthermore, checks need only be generated in cases which are rare
27390 and which the compiler can easily detect.
27391 The situation is more complex when separate compilation is taken into account.
27392 Consider the following:
27393
27394 @smallexample @c ada
27395 @cartouche
27396 @group
27397 package Math is
27398    function Sqrt (Arg : Float) return Float;
27399 end Math;
27400
27401 package body Math is
27402    function Sqrt (Arg : Float) return Float is
27403    begin
27404          @dots{}
27405    end Sqrt;
27406 end Math;
27407 @end group
27408 @group
27409 with Math;
27410 package Stuff is
27411    X : Float := Math.Sqrt (0.5);
27412 end Stuff;
27413
27414 with Stuff;
27415 procedure Main is
27416 begin
27417    @dots{}
27418 end Main;
27419 @end group
27420 @end cartouche
27421 @end smallexample
27422
27423 @noindent
27424 where @code{Main} is the main program. When this program is executed, the
27425 elaboration code must first be executed, and one of the jobs of the
27426 binder is to determine the order in which the units of a program are
27427 to be elaborated. In this case we have four units: the spec and body
27428 of @code{Math},
27429 the spec of @code{Stuff} and the body of @code{Main}).
27430 In what order should the four separate sections of elaboration code
27431 be executed?
27432
27433 There are some restrictions in the order of elaboration that the binder
27434 can choose. In particular, if unit U has a @code{with}
27435 for a package @code{X}, then you
27436 are assured that the spec of @code{X}
27437 is elaborated before U , but you are
27438 not assured that the body of @code{X}
27439 is elaborated before U.
27440 This means that in the above case, the binder is allowed to choose the
27441 order:
27442
27443 @smallexample
27444 spec of Math
27445 spec of Stuff
27446 body of Math
27447 body of Main
27448 @end smallexample
27449
27450 @noindent
27451 but that's not good, because now the call to @code{Math.Sqrt}
27452 that happens during
27453 the elaboration of the @code{Stuff}
27454 spec happens before the body of @code{Math.Sqrt} is
27455 elaborated, and hence causes @code{Program_Error} exception to be raised.
27456 At first glance, one might say that the binder is misbehaving, because
27457 obviously you want to elaborate the body of something you @code{with}
27458 first, but
27459 that is not a general rule that can be followed in all cases. Consider
27460
27461 @smallexample @c ada
27462 @group
27463 @cartouche
27464 package X is @dots{}
27465
27466 package Y is @dots{}
27467
27468 with X;
27469 package body Y is @dots{}
27470
27471 with Y;
27472 package body X is @dots{}
27473 @end cartouche
27474 @end group
27475 @end smallexample
27476
27477 @noindent
27478 This is a common arrangement, and, apart from the order of elaboration
27479 problems that might arise in connection with elaboration code, this works fine.
27480 A rule that says that you must first elaborate the body of anything you
27481 @code{with} cannot work in this case:
27482 the body of @code{X} @code{with}'s @code{Y},
27483 which means you would have to
27484 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
27485 which means
27486 you have to elaborate the body of @code{X} first, but @dots{} and we have a
27487 loop that cannot be broken.
27488
27489 It is true that the binder can in many cases guess an order of elaboration
27490 that is unlikely to cause a @code{Program_Error}
27491 exception to be raised, and it tries to do so (in the
27492 above example of @code{Math/Stuff/Spec}, the GNAT binder will
27493 by default
27494 elaborate the body of @code{Math} right after its spec, so all will be well).
27495
27496 However, a program that blindly relies on the binder to be helpful can
27497 get into trouble, as we discussed in the previous sections, so
27498 GNAT
27499 provides a number of facilities for assisting the programmer in
27500 developing programs that are robust with respect to elaboration order.
27501
27502 @node Default Behavior in GNAT - Ensuring Safety
27503 @section Default Behavior in GNAT - Ensuring Safety
27504
27505 @noindent
27506 The default behavior in GNAT ensures elaboration safety. In its
27507 default mode GNAT implements the
27508 rule we previously described as the right approach. Let's restate it:
27509
27510 @itemize
27511 @item
27512 @emph{If a unit has elaboration code that can directly or indirectly make a
27513 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
27514 package in a @code{with}'ed unit, then if the @code{with}'ed unit
27515 does not have pragma @code{Pure} or
27516 @code{Preelaborate}, then the client should have an
27517 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
27518
27519 @emph{In the case of instantiating a generic subprogram, it is always
27520 sufficient to have only an @code{Elaborate} pragma for the
27521 @code{with}'ed unit.}
27522 @end itemize
27523
27524 @noindent
27525 By following this rule a client is assured that calls and instantiations
27526 can be made without risk of an exception.
27527
27528 In this mode GNAT traces all calls that are potentially made from
27529 elaboration code, and puts in any missing implicit @code{Elaborate}
27530 and @code{Elaborate_All} pragmas.
27531 The advantage of this approach is that no elaboration problems
27532 are possible if the binder can find an elaboration order that is
27533 consistent with these implicit @code{Elaborate} and
27534 @code{Elaborate_All} pragmas. The
27535 disadvantage of this approach is that no such order may exist.
27536
27537 If the binder does not generate any diagnostics, then it means that it has
27538 found an elaboration order that is guaranteed to be safe. However, the binder
27539 may still be relying on implicitly generated @code{Elaborate} and
27540 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
27541 guaranteed.
27542
27543 If it is important to guarantee portability, then the compilations should
27544 use the
27545 @option{-gnatwl}
27546 (warn on elaboration problems) switch. This will cause warning messages
27547 to be generated indicating the missing @code{Elaborate} and
27548 @code{Elaborate_All} pragmas.
27549 Consider the following source program:
27550
27551 @smallexample @c ada
27552 @group
27553 @cartouche
27554 with k;
27555 package j is
27556   m : integer := k.r;
27557 end;
27558 @end cartouche
27559 @end group
27560 @end smallexample
27561
27562 @noindent
27563 where it is clear that there
27564 should be a pragma @code{Elaborate_All}
27565 for unit @code{k}. An implicit pragma will be generated, and it is
27566 likely that the binder will be able to honor it. However, if you want
27567 to port this program to some other Ada compiler than GNAT.
27568 it is safer to include the pragma explicitly in the source. If this
27569 unit is compiled with the
27570 @option{-gnatwl}
27571 switch, then the compiler outputs a warning:
27572
27573 @smallexample
27574 @group
27575 @cartouche
27576 1. with k;
27577 2. package j is
27578 3.   m : integer := k.r;
27579                      |
27580    >>> warning: call to "r" may raise Program_Error
27581    >>> warning: missing pragma Elaborate_All for "k"
27582
27583 4. end;
27584 @end cartouche
27585 @end group
27586 @end smallexample
27587
27588 @noindent
27589 and these warnings can be used as a guide for supplying manually
27590 the missing pragmas. It is usually a bad idea to use this warning
27591 option during development. That's because it will warn you when
27592 you need to put in a pragma, but cannot warn you when it is time
27593 to take it out. So the use of pragma @code{Elaborate_All} may lead to
27594 unnecessary dependencies and even false circularities.
27595
27596 This default mode is more restrictive than the Ada Reference
27597 Manual, and it is possible to construct programs which will compile
27598 using the dynamic model described there, but will run into a
27599 circularity using the safer static model we have described.
27600
27601 Of course any Ada compiler must be able to operate in a mode
27602 consistent with the requirements of the Ada Reference Manual,
27603 and in particular must have the capability of implementing the
27604 standard dynamic model of elaboration with run-time checks.
27605
27606 In GNAT, this standard mode can be achieved either by the use of
27607 the @option{-gnatE} switch on the compiler (@command{gcc} or
27608 @command{gnatmake}) command, or by the use of the configuration pragma:
27609
27610 @smallexample @c ada
27611 pragma Elaboration_Checks (RM);
27612 @end smallexample
27613
27614 @noindent
27615 Either approach will cause the unit affected to be compiled using the
27616 standard dynamic run-time elaboration checks described in the Ada
27617 Reference Manual. The static model is generally preferable, since it
27618 is clearly safer to rely on compile and link time checks rather than
27619 run-time checks. However, in the case of legacy code, it may be
27620 difficult to meet the requirements of the static model. This
27621 issue is further discussed in
27622 @ref{What to Do If the Default Elaboration Behavior Fails}.
27623
27624 Note that the static model provides a strict subset of the allowed
27625 behavior and programs of the Ada Reference Manual, so if you do
27626 adhere to the static model and no circularities exist,
27627 then you are assured that your program will
27628 work using the dynamic model, providing that you remove any
27629 pragma Elaborate statements from the source.
27630
27631 @node Treatment of Pragma Elaborate
27632 @section Treatment of Pragma Elaborate
27633 @cindex Pragma Elaborate
27634
27635 @noindent
27636 The use of @code{pragma Elaborate}
27637 should generally be avoided in Ada 95 and Ada 2005 programs,
27638 since there is no guarantee that transitive calls
27639 will be properly handled. Indeed at one point, this pragma was placed
27640 in Annex J (Obsolescent Features), on the grounds that it is never useful.
27641
27642 Now that's a bit restrictive. In practice, the case in which
27643 @code{pragma Elaborate} is useful is when the caller knows that there
27644 are no transitive calls, or that the called unit contains all necessary
27645 transitive @code{pragma Elaborate} statements, and legacy code often
27646 contains such uses.
27647
27648 Strictly speaking the static mode in GNAT should ignore such pragmas,
27649 since there is no assurance at compile time that the necessary safety
27650 conditions are met. In practice, this would cause GNAT to be incompatible
27651 with correctly written Ada 83 code that had all necessary
27652 @code{pragma Elaborate} statements in place. Consequently, we made the
27653 decision that GNAT in its default mode will believe that if it encounters
27654 a @code{pragma Elaborate} then the programmer knows what they are doing,
27655 and it will trust that no elaboration errors can occur.
27656
27657 The result of this decision is two-fold. First to be safe using the
27658 static mode, you should remove all @code{pragma Elaborate} statements.
27659 Second, when fixing circularities in existing code, you can selectively
27660 use @code{pragma Elaborate} statements to convince the static mode of
27661 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
27662 statement.
27663
27664 When using the static mode with @option{-gnatwl}, any use of
27665 @code{pragma Elaborate} will generate a warning about possible
27666 problems.
27667
27668 @node Elaboration Issues for Library Tasks
27669 @section Elaboration Issues for Library Tasks
27670 @cindex Library tasks, elaboration issues
27671 @cindex Elaboration of library tasks
27672
27673 @noindent
27674 In this section we examine special elaboration issues that arise for
27675 programs that declare library level tasks.
27676
27677 Generally the model of execution of an Ada program is that all units are
27678 elaborated, and then execution of the program starts. However, the
27679 declaration of library tasks definitely does not fit this model. The
27680 reason for this is that library tasks start as soon as they are declared
27681 (more precisely, as soon as the statement part of the enclosing package
27682 body is reached), that is to say before elaboration
27683 of the program is complete. This means that if such a task calls a
27684 subprogram, or an entry in another task, the callee may or may not be
27685 elaborated yet, and in the standard
27686 Reference Manual model of dynamic elaboration checks, you can even
27687 get timing dependent Program_Error exceptions, since there can be
27688 a race between the elaboration code and the task code.
27689
27690 The static model of elaboration in GNAT seeks to avoid all such
27691 dynamic behavior, by being conservative, and the conservative
27692 approach in this particular case is to assume that all the code
27693 in a task body is potentially executed at elaboration time if
27694 a task is declared at the library level.
27695
27696 This can definitely result in unexpected circularities. Consider
27697 the following example
27698
27699 @smallexample @c ada
27700 package Decls is
27701   task Lib_Task is
27702      entry Start;
27703   end Lib_Task;
27704
27705   type My_Int is new Integer;
27706
27707   function Ident (M : My_Int) return My_Int;
27708 end Decls;
27709
27710 with Utils;
27711 package body Decls is
27712   task body Lib_Task is
27713   begin
27714      accept Start;
27715      Utils.Put_Val (2);
27716   end Lib_Task;
27717
27718   function Ident (M : My_Int) return My_Int is
27719   begin
27720      return M;
27721   end Ident;
27722 end Decls;
27723
27724 with Decls;
27725 package Utils is
27726   procedure Put_Val (Arg : Decls.My_Int);
27727 end Utils;
27728
27729 with Text_IO;
27730 package body Utils is
27731   procedure Put_Val (Arg : Decls.My_Int) is
27732   begin
27733      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
27734   end Put_Val;
27735 end Utils;
27736
27737 with Decls;
27738 procedure Main is
27739 begin
27740    Decls.Lib_Task.Start;
27741 end;
27742 @end smallexample
27743
27744 @noindent
27745 If the above example is compiled in the default static elaboration
27746 mode, then a circularity occurs. The circularity comes from the call
27747 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
27748 this call occurs in elaboration code, we need an implicit pragma
27749 @code{Elaborate_All} for @code{Utils}. This means that not only must
27750 the spec and body of @code{Utils} be elaborated before the body
27751 of @code{Decls}, but also the spec and body of any unit that is
27752 @code{with'ed} by the body of @code{Utils} must also be elaborated before
27753 the body of @code{Decls}. This is the transitive implication of
27754 pragma @code{Elaborate_All} and it makes sense, because in general
27755 the body of @code{Put_Val} might have a call to something in a
27756 @code{with'ed} unit.
27757
27758 In this case, the body of Utils (actually its spec) @code{with's}
27759 @code{Decls}. Unfortunately this means that the body of @code{Decls}
27760 must be elaborated before itself, in case there is a call from the
27761 body of @code{Utils}.
27762
27763 Here is the exact chain of events we are worrying about:
27764
27765 @enumerate
27766 @item
27767 In the body of @code{Decls} a call is made from within the body of a library
27768 task to a subprogram in the package @code{Utils}. Since this call may
27769 occur at elaboration time (given that the task is activated at elaboration
27770 time), we have to assume the worst, i.e., that the
27771 call does happen at elaboration time.
27772
27773 @item
27774 This means that the body and spec of @code{Util} must be elaborated before
27775 the body of @code{Decls} so that this call does not cause an access before
27776 elaboration.
27777
27778 @item
27779 Within the body of @code{Util}, specifically within the body of
27780 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
27781 by this package.
27782
27783 @item
27784 One such @code{with}'ed package is package @code{Decls}, so there
27785 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
27786 In fact there is such a call in this example, but we would have to
27787 assume that there was such a call even if it were not there, since
27788 we are not supposed to write the body of @code{Decls} knowing what
27789 is in the body of @code{Utils}; certainly in the case of the
27790 static elaboration model, the compiler does not know what is in
27791 other bodies and must assume the worst.
27792
27793 @item
27794 This means that the spec and body of @code{Decls} must also be
27795 elaborated before we elaborate the unit containing the call, but
27796 that unit is @code{Decls}! This means that the body of @code{Decls}
27797 must be elaborated before itself, and that's a circularity.
27798 @end enumerate
27799
27800 @noindent
27801 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
27802 the body of @code{Decls} you will get a true Ada Reference Manual
27803 circularity that makes the program illegal.
27804
27805 In practice, we have found that problems with the static model of
27806 elaboration in existing code often arise from library tasks, so
27807 we must address this particular situation.
27808
27809 Note that if we compile and run the program above, using the dynamic model of
27810 elaboration (that is to say use the @option{-gnatE} switch),
27811 then it compiles, binds,
27812 links, and runs, printing the expected result of 2. Therefore in some sense
27813 the circularity here is only apparent, and we need to capture
27814 the properties of this program that  distinguish it from other library-level
27815 tasks that have real elaboration problems.
27816
27817 We have four possible answers to this question:
27818
27819 @itemize @bullet
27820
27821 @item
27822 Use the dynamic model of elaboration.
27823
27824 If we use the @option{-gnatE} switch, then as noted above, the program works.
27825 Why is this? If we examine the task body, it is apparent that the task cannot
27826 proceed past the
27827 @code{accept} statement until after elaboration has been completed, because
27828 the corresponding entry call comes from the main program, not earlier.
27829 This is why the dynamic model works here. But that's really giving
27830 up on a precise analysis, and we prefer to take this approach only if we cannot
27831 solve the
27832 problem in any other manner. So let us examine two ways to reorganize
27833 the program to avoid the potential elaboration problem.
27834
27835 @item
27836 Split library tasks into separate packages.
27837
27838 Write separate packages, so that library tasks are isolated from
27839 other declarations as much as possible. Let us look at a variation on
27840 the above program.
27841
27842 @smallexample @c ada
27843 package Decls1 is
27844   task Lib_Task is
27845      entry Start;
27846   end Lib_Task;
27847 end Decls1;
27848
27849 with Utils;
27850 package body Decls1 is
27851   task body Lib_Task is
27852   begin
27853      accept Start;
27854      Utils.Put_Val (2);
27855   end Lib_Task;
27856 end Decls1;
27857
27858 package Decls2 is
27859   type My_Int is new Integer;
27860   function Ident (M : My_Int) return My_Int;
27861 end Decls2;
27862
27863 with Utils;
27864 package body Decls2 is
27865   function Ident (M : My_Int) return My_Int is
27866   begin
27867      return M;
27868   end Ident;
27869 end Decls2;
27870
27871 with Decls2;
27872 package Utils is
27873   procedure Put_Val (Arg : Decls2.My_Int);
27874 end Utils;
27875
27876 with Text_IO;
27877 package body Utils is
27878   procedure Put_Val (Arg : Decls2.My_Int) is
27879   begin
27880      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
27881   end Put_Val;
27882 end Utils;
27883
27884 with Decls1;
27885 procedure Main is
27886 begin
27887    Decls1.Lib_Task.Start;
27888 end;
27889 @end smallexample
27890
27891 @noindent
27892 All we have done is to split @code{Decls} into two packages, one
27893 containing the library task, and one containing everything else. Now
27894 there is no cycle, and the program compiles, binds, links and executes
27895 using the default static model of elaboration.
27896
27897 @item
27898 Declare separate task types.
27899
27900 A significant part of the problem arises because of the use of the
27901 single task declaration form. This means that the elaboration of
27902 the task type, and the elaboration of the task itself (i.e.@: the
27903 creation of the task) happen at the same time. A good rule
27904 of style in Ada is to always create explicit task types. By
27905 following the additional step of placing task objects in separate
27906 packages from the task type declaration, many elaboration problems
27907 are avoided. Here is another modified example of the example program:
27908
27909 @smallexample @c ada
27910 package Decls is
27911   task type Lib_Task_Type is
27912      entry Start;
27913   end Lib_Task_Type;
27914
27915   type My_Int is new Integer;
27916
27917   function Ident (M : My_Int) return My_Int;
27918 end Decls;
27919
27920 with Utils;
27921 package body Decls is
27922   task body Lib_Task_Type is
27923   begin
27924      accept Start;
27925      Utils.Put_Val (2);
27926   end Lib_Task_Type;
27927
27928   function Ident (M : My_Int) return My_Int is
27929   begin
27930      return M;
27931   end Ident;
27932 end Decls;
27933
27934 with Decls;
27935 package Utils is
27936   procedure Put_Val (Arg : Decls.My_Int);
27937 end Utils;
27938
27939 with Text_IO;
27940 package body Utils is
27941   procedure Put_Val (Arg : Decls.My_Int) is
27942   begin
27943      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
27944   end Put_Val;
27945 end Utils;
27946
27947 with Decls;
27948 package Declst is
27949    Lib_Task : Decls.Lib_Task_Type;
27950 end Declst;
27951
27952 with Declst;
27953 procedure Main is
27954 begin
27955    Declst.Lib_Task.Start;
27956 end;
27957 @end smallexample
27958
27959 @noindent
27960 What we have done here is to replace the @code{task} declaration in
27961 package @code{Decls} with a @code{task type} declaration. Then we
27962 introduce a separate package @code{Declst} to contain the actual
27963 task object. This separates the elaboration issues for
27964 the @code{task type}
27965 declaration, which causes no trouble, from the elaboration issues
27966 of the task object, which is also unproblematic, since it is now independent
27967 of the elaboration of  @code{Utils}.
27968 This separation of concerns also corresponds to
27969 a generally sound engineering principle of separating declarations
27970 from instances. This version of the program also compiles, binds, links,
27971 and executes, generating the expected output.
27972
27973 @item
27974 Use No_Entry_Calls_In_Elaboration_Code restriction.
27975 @cindex No_Entry_Calls_In_Elaboration_Code
27976
27977 The previous two approaches described how a program can be restructured
27978 to avoid the special problems caused by library task bodies. in practice,
27979 however, such restructuring may be difficult to apply to existing legacy code,
27980 so we must consider solutions that do not require massive rewriting.
27981
27982 Let us consider more carefully why our original sample program works
27983 under the dynamic model of elaboration. The reason is that the code
27984 in the task body blocks immediately on the @code{accept}
27985 statement. Now of course there is nothing to prohibit elaboration
27986 code from making entry calls (for example from another library level task),
27987 so we cannot tell in isolation that
27988 the task will not execute the accept statement  during elaboration.
27989
27990 However, in practice it is very unusual to see elaboration code
27991 make any entry calls, and the pattern of tasks starting
27992 at elaboration time and then immediately blocking on @code{accept} or
27993 @code{select} statements is very common. What this means is that
27994 the compiler is being too pessimistic when it analyzes the
27995 whole package body as though it might be executed at elaboration
27996 time.
27997
27998 If we know that the elaboration code contains no entry calls, (a very safe
27999 assumption most of the time, that could almost be made the default
28000 behavior), then we can compile all units of the program under control
28001 of the following configuration pragma:
28002
28003 @smallexample
28004 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
28005 @end smallexample
28006
28007 @noindent
28008 This pragma can be placed in the @file{gnat.adc} file in the usual
28009 manner. If we take our original unmodified program and compile it
28010 in the presence of a @file{gnat.adc} containing the above pragma,
28011 then once again, we can compile, bind, link, and execute, obtaining
28012 the expected result. In the presence of this pragma, the compiler does
28013 not trace calls in a task body, that appear after the first @code{accept}
28014 or @code{select} statement, and therefore does not report a potential
28015 circularity in the original program.
28016
28017 The compiler will check to the extent it can that the above
28018 restriction is not violated, but it is not always possible to do a
28019 complete check at compile time, so it is important to use this
28020 pragma only if the stated restriction is in fact met, that is to say
28021 no task receives an entry call before elaboration of all units is completed.
28022
28023 @end itemize
28024
28025 @node Mixing Elaboration Models
28026 @section Mixing Elaboration Models
28027 @noindent
28028 So far, we have assumed that the entire program is either compiled
28029 using the dynamic model or static model, ensuring consistency. It
28030 is possible to mix the two models, but rules have to be followed
28031 if this mixing is done to ensure that elaboration checks are not
28032 omitted.
28033
28034 The basic rule is that @emph{a unit compiled with the static model cannot
28035 be @code{with'ed} by a unit compiled with the dynamic model}. The
28036 reason for this is that in the static model, a unit assumes that
28037 its clients guarantee to use (the equivalent of) pragma
28038 @code{Elaborate_All} so that no elaboration checks are required
28039 in inner subprograms, and this assumption is violated if the
28040 client is compiled with dynamic checks.
28041
28042 The precise rule is as follows. A unit that is compiled with dynamic
28043 checks can only @code{with} a unit that meets at least one of the
28044 following criteria:
28045
28046 @itemize @bullet
28047
28048 @item
28049 The @code{with'ed} unit is itself compiled with dynamic elaboration
28050 checks (that is with the @option{-gnatE} switch.
28051
28052 @item
28053 The @code{with'ed} unit is an internal GNAT implementation unit from
28054 the System, Interfaces, Ada, or GNAT hierarchies.
28055
28056 @item
28057 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
28058
28059 @item
28060 The @code{with'ing} unit (that is the client) has an explicit pragma
28061 @code{Elaborate_All} for the @code{with'ed} unit.
28062
28063 @end itemize
28064
28065 @noindent
28066 If this rule is violated, that is if a unit with dynamic elaboration
28067 checks @code{with's} a unit that does not meet one of the above four
28068 criteria, then the binder (@code{gnatbind}) will issue a warning
28069 similar to that in the following example:
28070
28071 @smallexample
28072 warning: "x.ads" has dynamic elaboration checks and with's
28073 warning:   "y.ads" which has static elaboration checks
28074 @end smallexample
28075
28076 @noindent
28077 These warnings indicate that the rule has been violated, and that as a result
28078 elaboration checks may be missed in the resulting executable file.
28079 This warning may be suppressed using the @option{-ws} binder switch
28080 in the usual manner.
28081
28082 One useful application of this mixing rule is in the case of a subsystem
28083 which does not itself @code{with} units from the remainder of the
28084 application. In this case, the entire subsystem can be compiled with
28085 dynamic checks to resolve a circularity in the subsystem, while
28086 allowing the main application that uses this subsystem to be compiled
28087 using the more reliable default static model.
28088
28089 @node What to Do If the Default Elaboration Behavior Fails
28090 @section What to Do If the Default Elaboration Behavior Fails
28091
28092 @noindent
28093 If the binder cannot find an acceptable order, it outputs detailed
28094 diagnostics. For example:
28095 @smallexample
28096 @group
28097 @iftex
28098 @leftskip=0cm
28099 @end iftex
28100 error: elaboration circularity detected
28101 info:   "proc (body)" must be elaborated before "pack (body)"
28102 info:     reason: Elaborate_All probably needed in unit "pack (body)"
28103 info:     recompile "pack (body)" with -gnatwl
28104 info:                             for full details
28105 info:       "proc (body)"
28106 info:         is needed by its spec:
28107 info:       "proc (spec)"
28108 info:         which is withed by:
28109 info:       "pack (body)"
28110 info:  "pack (body)" must be elaborated before "proc (body)"
28111 info:     reason: pragma Elaborate in unit "proc (body)"
28112 @end group
28113
28114 @end smallexample
28115
28116 @noindent
28117 In this case we have a cycle that the binder cannot break. On the one
28118 hand, there is an explicit pragma Elaborate in @code{proc} for
28119 @code{pack}. This means that the body of @code{pack} must be elaborated
28120 before the body of @code{proc}. On the other hand, there is elaboration
28121 code in @code{pack} that calls a subprogram in @code{proc}. This means
28122 that for maximum safety, there should really be a pragma
28123 Elaborate_All in @code{pack} for @code{proc} which would require that
28124 the body of @code{proc} be elaborated before the body of
28125 @code{pack}. Clearly both requirements cannot be satisfied.
28126 Faced with a circularity of this kind, you have three different options.
28127
28128 @table @asis
28129 @item Fix the program
28130 The most desirable option from the point of view of long-term maintenance
28131 is to rearrange the program so that the elaboration problems are avoided.
28132 One useful technique is to place the elaboration code into separate
28133 child packages. Another is to move some of the initialization code to
28134 explicitly called subprograms, where the program controls the order
28135 of initialization explicitly. Although this is the most desirable option,
28136 it may be impractical and involve too much modification, especially in
28137 the case of complex legacy code.
28138
28139 @item Perform dynamic checks
28140 If the compilations are done using the
28141 @option{-gnatE}
28142 (dynamic elaboration check) switch, then GNAT behaves in a quite different
28143 manner. Dynamic checks are generated for all calls that could possibly result
28144 in raising an exception. With this switch, the compiler does not generate
28145 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
28146 exactly as specified in the @cite{Ada Reference Manual}.
28147 The binder will generate
28148 an executable program that may or may not raise @code{Program_Error}, and then
28149 it is the programmer's job to ensure that it does not raise an exception. Note
28150 that it is important to compile all units with the switch, it cannot be used
28151 selectively.
28152
28153 @item Suppress checks
28154 The drawback of dynamic checks is that they generate a
28155 significant overhead at run time, both in space and time. If you
28156 are absolutely sure that your program cannot raise any elaboration
28157 exceptions, and you still want to use the dynamic elaboration model,
28158 then you can use the configuration pragma
28159 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
28160 example this pragma could be placed in the @file{gnat.adc} file.
28161
28162 @item Suppress checks selectively
28163 When you know that certain calls or instantiations in elaboration code cannot
28164 possibly lead to an elaboration error, and the binder nevertheless complains
28165 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
28166 elaboration circularities, it is possible to remove those warnings locally and
28167 obtain a program that will bind. Clearly this can be unsafe, and it is the
28168 responsibility of the programmer to make sure that the resulting program has no
28169 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
28170 used with different granularity to suppress warnings and break elaboration
28171 circularities:
28172
28173 @itemize @bullet
28174 @item
28175 Place the pragma that names the called subprogram in the declarative part
28176 that contains the call.
28177
28178 @item
28179 Place the pragma in the declarative part, without naming an entity. This
28180 disables warnings on all calls in the corresponding  declarative region.
28181
28182 @item
28183 Place the pragma in the package spec that declares the called subprogram,
28184 and name the subprogram. This disables warnings on all elaboration calls to
28185 that subprogram.
28186
28187 @item
28188 Place the pragma in the package spec that declares the called subprogram,
28189 without naming any entity. This disables warnings on all elaboration calls to
28190 all subprograms declared in this spec.
28191
28192 @item Use Pragma Elaborate
28193 As previously described in section @xref{Treatment of Pragma Elaborate},
28194 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
28195 that no elaboration checks are required on calls to the designated unit.
28196 There may be cases in which the caller knows that no transitive calls
28197 can occur, so that a @code{pragma Elaborate} will be sufficient in a
28198 case where @code{pragma Elaborate_All} would cause a circularity.
28199 @end itemize
28200
28201 @noindent
28202 These five cases are listed in order of decreasing safety, and therefore
28203 require increasing programmer care in their application. Consider the
28204 following program:
28205
28206 @smallexample @c adanocomment
28207 package Pack1 is
28208   function F1 return Integer;
28209   X1 : Integer;
28210 end Pack1;
28211
28212 package Pack2 is
28213   function F2 return Integer;
28214   function Pure (x : integer) return integer;
28215   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
28216   --  pragma Suppress (Elaboration_Check);              -- (4)
28217 end Pack2;
28218
28219 with Pack2;
28220 package body Pack1 is
28221   function F1 return Integer is
28222   begin
28223     return 100;
28224   end F1;
28225   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
28226 begin
28227   declare
28228     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
28229     --  pragma Suppress(Elaboration_Check);             -- (2)
28230   begin
28231     X1 := Pack2.F2 + 1;                --  Elab. call (2)
28232   end;
28233 end Pack1;
28234
28235 with Pack1;
28236 package body Pack2 is
28237   function F2 return Integer is
28238   begin
28239      return Pack1.F1;
28240   end F2;
28241   function Pure (x : integer) return integer is
28242   begin
28243      return x ** 3 - 3 * x;
28244   end;
28245 end Pack2;
28246
28247 with Pack1, Ada.Text_IO;
28248 procedure Proc3 is
28249 begin
28250   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
28251 end Proc3;
28252 @end smallexample
28253 In the absence of any pragmas, an attempt to bind this program produces
28254 the following diagnostics:
28255 @smallexample
28256 @group
28257 @iftex
28258 @leftskip=.5cm
28259 @end iftex
28260 error: elaboration circularity detected
28261 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
28262 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
28263 info:       recompile "pack1 (body)" with -gnatwl for full details
28264 info:          "pack1 (body)"
28265 info:             must be elaborated along with its spec:
28266 info:          "pack1 (spec)"
28267 info:             which is withed by:
28268 info:          "pack2 (body)"
28269 info:             which must be elaborated along with its spec:
28270 info:          "pack2 (spec)"
28271 info:             which is withed by:
28272 info:          "pack1 (body)"
28273 @end group
28274 @end smallexample
28275 The sources of the circularity are the two calls to @code{Pack2.Pure} and
28276 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
28277 F2 is safe, even though F2 calls F1, because the call appears after the
28278 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
28279 remove the warning on the call. It is also possible to use pragma (2)
28280 because there are no other potentially unsafe calls in the block.
28281
28282 @noindent
28283 The call to @code{Pure} is safe because this function does not depend on the
28284 state of @code{Pack2}. Therefore any call to this function is safe, and it
28285 is correct to place pragma (3) in the corresponding package spec.
28286
28287 @noindent
28288 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
28289 warnings on all calls to functions declared therein. Note that this is not
28290 necessarily safe, and requires more detailed examination of the subprogram
28291 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
28292 be already elaborated.
28293 @end table
28294
28295 @noindent
28296 It is hard to generalize on which of these four approaches should be
28297 taken. Obviously if it is possible to fix the program so that the default
28298 treatment works, this is preferable, but this may not always be practical.
28299 It is certainly simple enough to use
28300 @option{-gnatE}
28301 but the danger in this case is that, even if the GNAT binder
28302 finds a correct elaboration order, it may not always do so,
28303 and certainly a binder from another Ada compiler might not. A
28304 combination of testing and analysis (for which the warnings generated
28305 with the
28306 @option{-gnatwl}
28307 switch can be useful) must be used to ensure that the program is free
28308 of errors. One switch that is useful in this testing is the
28309 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
28310 switch for
28311 @code{gnatbind}.
28312 Normally the binder tries to find an order that has the best chance
28313 of avoiding elaboration problems. However, if this switch is used, the binder
28314 plays a devil's advocate role, and tries to choose the order that
28315 has the best chance of failing. If your program works even with this
28316 switch, then it has a better chance of being error free, but this is still
28317 not a guarantee.
28318
28319 For an example of this approach in action, consider the C-tests (executable
28320 tests) from the ACVC suite. If these are compiled and run with the default
28321 treatment, then all but one of them succeed without generating any error
28322 diagnostics from the binder. However, there is one test that fails, and
28323 this is not surprising, because the whole point of this test is to ensure
28324 that the compiler can handle cases where it is impossible to determine
28325 a correct order statically, and it checks that an exception is indeed
28326 raised at run time.
28327
28328 This one test must be compiled and run using the
28329 @option{-gnatE}
28330 switch, and then it passes. Alternatively, the entire suite can
28331 be run using this switch. It is never wrong to run with the dynamic
28332 elaboration switch if your code is correct, and we assume that the
28333 C-tests are indeed correct (it is less efficient, but efficiency is
28334 not a factor in running the ACVC tests.)
28335
28336 @node Elaboration for Access-to-Subprogram Values
28337 @section Elaboration for Access-to-Subprogram Values
28338 @cindex Access-to-subprogram
28339
28340 @noindent
28341 Access-to-subprogram types (introduced in Ada 95) complicate
28342 the handling of elaboration. The trouble is that it becomes
28343 impossible to tell at compile time which procedure
28344 is being called. This means that it is not possible for the binder
28345 to analyze the elaboration requirements in this case.
28346
28347 If at the point at which the access value is created
28348 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
28349 the body of the subprogram is
28350 known to have been elaborated, then the access value is safe, and its use
28351 does not require a check. This may be achieved by appropriate arrangement
28352 of the order of declarations if the subprogram is in the current unit,
28353 or, if the subprogram is in another unit, by using pragma
28354 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
28355 on the referenced unit.
28356
28357 If the referenced body is not known to have been elaborated at the point
28358 the access value is created, then any use of the access value must do a
28359 dynamic check, and this dynamic check will fail and raise a
28360 @code{Program_Error} exception if the body has not been elaborated yet.
28361 GNAT will generate the necessary checks, and in addition, if the
28362 @option{-gnatwl}
28363 switch is set, will generate warnings that such checks are required.
28364
28365 The use of dynamic dispatching for tagged types similarly generates
28366 a requirement for dynamic checks, and premature calls to any primitive
28367 operation of a tagged type before the body of the operation has been
28368 elaborated, will result in the raising of @code{Program_Error}.
28369
28370 @node Summary of Procedures for Elaboration Control
28371 @section Summary of Procedures for Elaboration Control
28372 @cindex Elaboration control
28373
28374 @noindent
28375 First, compile your program with the default options, using none of
28376 the special elaboration control switches. If the binder successfully
28377 binds your program, then you can be confident that, apart from issues
28378 raised by the use of access-to-subprogram types and dynamic dispatching,
28379 the program is free of elaboration errors. If it is important that the
28380 program be portable, then use the
28381 @option{-gnatwl}
28382 switch to generate warnings about missing @code{Elaborate} or
28383 @code{Elaborate_All} pragmas, and supply the missing pragmas.
28384
28385 If the program fails to bind using the default static elaboration
28386 handling, then you can fix the program to eliminate the binder
28387 message, or recompile the entire program with the
28388 @option{-gnatE} switch to generate dynamic elaboration checks,
28389 and, if you are sure there really are no elaboration problems,
28390 use a global pragma @code{Suppress (Elaboration_Check)}.
28391
28392 @node Other Elaboration Order Considerations
28393 @section Other Elaboration Order Considerations
28394 @noindent
28395 This section has been entirely concerned with the issue of finding a valid
28396 elaboration order, as defined by the Ada Reference Manual. In a case
28397 where several elaboration orders are valid, the task is to find one
28398 of the possible valid elaboration orders (and the static model in GNAT
28399 will ensure that this is achieved).
28400
28401 The purpose of the elaboration rules in the Ada Reference Manual is to
28402 make sure that no entity is accessed before it has been elaborated. For
28403 a subprogram, this means that the spec and body must have been elaborated
28404 before the subprogram is called. For an object, this means that the object
28405 must have been elaborated before its value is read or written. A violation
28406 of either of these two requirements is an access before elaboration order,
28407 and this section has been all about avoiding such errors.
28408
28409 In the case where more than one order of elaboration is possible, in the
28410 sense that access before elaboration errors are avoided, then any one of
28411 the orders is ``correct'' in the sense that it meets the requirements of
28412 the Ada Reference Manual, and no such error occurs.
28413
28414 However, it may be the case for a given program, that there are
28415 constraints on the order of elaboration that come not from consideration
28416 of avoiding elaboration errors, but rather from extra-lingual logic
28417 requirements. Consider this example:
28418
28419 @smallexample @c ada
28420 with Init_Constants;
28421 package Constants is
28422    X : Integer := 0;
28423    Y : Integer := 0;
28424 end Constants;
28425
28426 package Init_Constants is
28427    procedure P; -- require a body
28428 end Init_Constants;
28429
28430 with Constants;
28431 package body Init_Constants is
28432    procedure P is begin null; end;
28433 begin
28434    Constants.X := 3;
28435    Constants.Y := 4;
28436 end Init_Constants;
28437
28438 with Constants;
28439 package Calc is
28440    Z : Integer := Constants.X + Constants.Y;
28441 end Calc;
28442
28443 with Calc;
28444 with Text_IO; use Text_IO;
28445 procedure Main is
28446 begin
28447    Put_Line (Calc.Z'Img);
28448 end Main;
28449 @end smallexample
28450
28451 @noindent
28452 In this example, there is more than one valid order of elaboration. For
28453 example both the following are correct orders:
28454
28455 @smallexample
28456 Init_Constants spec
28457 Constants spec
28458 Calc spec
28459 Init_Constants body
28460 Main body
28461
28462   and
28463
28464 Init_Constants spec
28465 Init_Constants body
28466 Constants spec
28467 Calc spec
28468 Main body
28469 @end smallexample
28470
28471 @noindent
28472 There is no language rule to prefer one or the other, both are correct
28473 from an order of elaboration point of view. But the programmatic effects
28474 of the two orders are very different. In the first, the elaboration routine
28475 of @code{Calc} initializes @code{Z} to zero, and then the main program
28476 runs with this value of zero. But in the second order, the elaboration
28477 routine of @code{Calc} runs after the body of Init_Constants has set
28478 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
28479 runs.
28480
28481 One could perhaps by applying pretty clever non-artificial intelligence
28482 to the situation guess that it is more likely that the second order of
28483 elaboration is the one desired, but there is no formal linguistic reason
28484 to prefer one over the other. In fact in this particular case, GNAT will
28485 prefer the second order, because of the rule that bodies are elaborated
28486 as soon as possible, but it's just luck that this is what was wanted
28487 (if indeed the second order was preferred).
28488
28489 If the program cares about the order of elaboration routines in a case like
28490 this, it is important to specify the order required. In this particular
28491 case, that could have been achieved by adding to the spec of Calc:
28492
28493 @smallexample @c ada
28494 pragma Elaborate_All (Constants);
28495 @end smallexample
28496
28497 @noindent
28498 which requires that the body (if any) and spec of @code{Constants},
28499 as well as the body and spec of any unit @code{with}'ed by
28500 @code{Constants} be elaborated before @code{Calc} is elaborated.
28501
28502 Clearly no automatic method can always guess which alternative you require,
28503 and if you are working with legacy code that had constraints of this kind
28504 which were not properly specified by adding @code{Elaborate} or
28505 @code{Elaborate_All} pragmas, then indeed it is possible that two different
28506 compilers can choose different orders.
28507
28508 However, GNAT does attempt to diagnose the common situation where there
28509 are uninitialized variables in the visible part of a package spec, and the
28510 corresponding package body has an elaboration block that directly or
28511 indirectly initialized one or more of these variables. This is the situation
28512 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
28513 a warning that suggests this addition if it detects this situation.
28514
28515 The @code{gnatbind}
28516 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
28517 out problems. This switch causes bodies to be elaborated as late as possible
28518 instead of as early as possible. In the example above, it would have forced
28519 the choice of the first elaboration order. If you get different results
28520 when using this switch, and particularly if one set of results is right,
28521 and one is wrong as far as you are concerned, it shows that you have some
28522 missing @code{Elaborate} pragmas. For the example above, we have the
28523 following output:
28524
28525 @smallexample
28526 gnatmake -f -q main
28527 main
28528  7
28529 gnatmake -f -q main -bargs -p
28530 main
28531  0
28532 @end smallexample
28533
28534 @noindent
28535 It is of course quite unlikely that both these results are correct, so
28536 it is up to you in a case like this to investigate the source of the
28537 difference, by looking at the two elaboration orders that are chosen,
28538 and figuring out which is correct, and then adding the necessary
28539 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
28540
28541
28542
28543 @c *******************************
28544 @node Conditional Compilation
28545 @appendix Conditional Compilation
28546 @c *******************************
28547 @cindex Conditional compilation
28548
28549 @noindent
28550 It is often necessary to arrange for a single source program
28551 to serve multiple purposes, where it is compiled in different
28552 ways to achieve these different goals. Some examples of the
28553 need for this feature are
28554
28555 @itemize @bullet
28556 @item  Adapting a program to a different hardware environment
28557 @item  Adapting a program to a different target architecture
28558 @item  Turning debugging features on and off
28559 @item  Arranging for a program to compile with different compilers
28560 @end itemize
28561
28562 @noindent
28563 In C, or C++, the typical approach would be to use the preprocessor
28564 that is defined as part of the language. The Ada language does not
28565 contain such a feature. This is not an oversight, but rather a very
28566 deliberate design decision, based on the experience that overuse of
28567 the preprocessing features in C and C++ can result in programs that
28568 are extremely difficult to maintain. For example, if we have ten
28569 switches that can be on or off, this means that there are a thousand
28570 separate programs, any one of which might not even be syntactically
28571 correct, and even if syntactically correct, the resulting program
28572 might not work correctly. Testing all combinations can quickly become
28573 impossible.
28574
28575 Nevertheless, the need to tailor programs certainly exists, and in
28576 this Appendix we will discuss how this can
28577 be achieved using Ada in general, and GNAT in particular.
28578
28579 @menu
28580 * Use of Boolean Constants::
28581 * Debugging - A Special Case::
28582 * Conditionalizing Declarations::
28583 * Use of Alternative Implementations::
28584 * Preprocessing::
28585 @end menu
28586
28587 @node Use of Boolean Constants
28588 @section Use of Boolean Constants
28589
28590 @noindent
28591 In the case where the difference is simply which code
28592 sequence is executed, the cleanest solution is to use Boolean
28593 constants to control which code is executed.
28594
28595 @smallexample @c ada
28596 @group
28597 FP_Initialize_Required : constant Boolean := True;
28598 @dots{}
28599 if FP_Initialize_Required then
28600 @dots{}
28601 end if;
28602 @end group
28603 @end smallexample
28604
28605 @noindent
28606 Not only will the code inside the @code{if} statement not be executed if
28607 the constant Boolean is @code{False}, but it will also be completely
28608 deleted from the program.
28609 However, the code is only deleted after the @code{if} statement
28610 has been checked for syntactic and semantic correctness.
28611 (In contrast, with preprocessors the code is deleted before the
28612 compiler ever gets to see it, so it is not checked until the switch
28613 is turned on.)
28614 @cindex Preprocessors (contrasted with conditional compilation)
28615
28616 Typically the Boolean constants will be in a separate package,
28617 something like:
28618
28619 @smallexample @c ada
28620 @group
28621 package Config is
28622    FP_Initialize_Required : constant Boolean := True;
28623    Reset_Available        : constant Boolean := False;
28624    @dots{}
28625 end Config;
28626 @end group
28627 @end smallexample
28628
28629 @noindent
28630 The @code{Config} package exists in multiple forms for the various targets,
28631 with an appropriate script selecting the version of @code{Config} needed.
28632 Then any other unit requiring conditional compilation can do a @code{with}
28633 of @code{Config} to make the constants visible.
28634
28635
28636 @node Debugging - A Special Case
28637 @section Debugging - A Special Case
28638
28639 @noindent
28640 A common use of conditional code is to execute statements (for example
28641 dynamic checks, or output of intermediate results) under control of a
28642 debug switch, so that the debugging behavior can be turned on and off.
28643 This can be done using a Boolean constant to control whether the code
28644 is active:
28645
28646 @smallexample @c ada
28647 @group
28648 if Debugging then
28649    Put_Line ("got to the first stage!");
28650 end if;
28651 @end group
28652 @end smallexample
28653
28654 @noindent
28655 or
28656
28657 @smallexample @c ada
28658 @group
28659 if Debugging and then Temperature > 999.0 then
28660    raise Temperature_Crazy;
28661 end if;
28662 @end group
28663 @end smallexample
28664
28665 @noindent
28666 Since this is a common case, there are special features to deal with
28667 this in a convenient manner. For the case of tests, Ada 2005 has added
28668 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
28669 @cindex pragma @code{Assert}
28670 on the @code{Assert} pragma that has always been available in GNAT, so this
28671 feature may be used with GNAT even if you are not using Ada 2005 features.
28672 The use of pragma @code{Assert} is described in
28673 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
28674 example, the last test could be written:
28675
28676 @smallexample @c ada
28677 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
28678 @end smallexample
28679
28680 @noindent
28681 or simply
28682
28683 @smallexample @c ada
28684 pragma Assert (Temperature <= 999.0);
28685 @end smallexample
28686
28687 @noindent
28688 In both cases, if assertions are active and the temperature is excessive,
28689 the exception @code{Assert_Failure} will be raised, with the given string in
28690 the first case or a string indicating the location of the pragma in the second
28691 case used as the exception message.
28692
28693 You can turn assertions on and off by using the @code{Assertion_Policy}
28694 pragma.
28695 @cindex pragma @code{Assertion_Policy}
28696 This is an Ada 2005 pragma which is implemented in all modes by
28697 GNAT, but only in the latest versions of GNAT which include Ada 2005
28698 capability. Alternatively, you can use the @option{-gnata} switch
28699 @cindex @option{-gnata} switch
28700 to enable assertions from the command line (this is recognized by all versions
28701 of GNAT).
28702
28703 For the example above with the @code{Put_Line}, the GNAT-specific pragma
28704 @code{Debug} can be used:
28705 @cindex pragma @code{Debug}
28706
28707 @smallexample @c ada
28708 pragma Debug (Put_Line ("got to the first stage!"));
28709 @end smallexample
28710
28711 @noindent
28712 If debug pragmas are enabled, the argument, which must be of the form of
28713 a procedure call, is executed (in this case, @code{Put_Line} will be called).
28714 Only one call can be present, but of course a special debugging procedure
28715 containing any code you like can be included in the program and then
28716 called in a pragma @code{Debug} argument as needed.
28717
28718 One advantage of pragma @code{Debug} over the @code{if Debugging then}
28719 construct is that pragma @code{Debug} can appear in declarative contexts,
28720 such as at the very beginning of a procedure, before local declarations have
28721 been elaborated.
28722
28723 Debug pragmas are enabled using either the @option{-gnata} switch that also
28724 controls assertions, or with a separate Debug_Policy pragma.
28725 @cindex pragma @code{Debug_Policy}
28726 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
28727 in Ada 95 and Ada 83 programs as well), and is analogous to
28728 pragma @code{Assertion_Policy} to control assertions.
28729
28730 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
28731 and thus they can appear in @file{gnat.adc} if you are not using a
28732 project file, or in the file designated to contain configuration pragmas
28733 in a project file.
28734 They then apply to all subsequent compilations. In practice the use of
28735 the @option{-gnata} switch is often the most convenient method of controlling
28736 the status of these pragmas.
28737
28738 Note that a pragma is not a statement, so in contexts where a statement
28739 sequence is required, you can't just write a pragma on its own. You have
28740 to add a @code{null} statement.
28741
28742 @smallexample @c ada
28743 @group
28744 if @dots{} then
28745    @dots{} -- some statements
28746 else
28747    pragma Assert (Num_Cases < 10);
28748    null;
28749 end if;
28750 @end group
28751 @end smallexample
28752
28753
28754 @node Conditionalizing Declarations
28755 @section Conditionalizing Declarations
28756
28757 @noindent
28758 In some cases, it may be necessary to conditionalize declarations to meet
28759 different requirements. For example we might want a bit string whose length
28760 is set to meet some hardware message requirement.
28761
28762 In some cases, it may be possible to do this using declare blocks controlled
28763 by conditional constants:
28764
28765 @smallexample @c ada
28766 @group
28767 if Small_Machine then
28768    declare
28769       X : Bit_String (1 .. 10);
28770    begin
28771       @dots{}
28772    end;
28773 else
28774    declare
28775       X : Large_Bit_String (1 .. 1000);
28776    begin
28777       @dots{}
28778    end;
28779 end if;
28780 @end group
28781 @end smallexample
28782
28783 @noindent
28784 Note that in this approach, both declarations are analyzed by the
28785 compiler so this can only be used where both declarations are legal,
28786 even though one of them will not be used.
28787
28788 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
28789 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
28790 that are parameterized by these constants. For example
28791
28792 @smallexample @c ada
28793 @group
28794 for Rec use
28795   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
28796 end record;
28797 @end group
28798 @end smallexample
28799
28800 @noindent
28801 If @code{Bits_Per_Word} is set to 32, this generates either
28802
28803 @smallexample @c ada
28804 @group
28805 for Rec use
28806   Field1 at 0 range 0 .. 32;
28807 end record;
28808 @end group
28809 @end smallexample
28810
28811 @noindent
28812 for the big endian case, or
28813
28814 @smallexample @c ada
28815 @group
28816 for Rec use record
28817   Field1 at 0 range 10 .. 32;
28818 end record;
28819 @end group
28820 @end smallexample
28821
28822 @noindent
28823 for the little endian case. Since a powerful subset of Ada expression
28824 notation is usable for creating static constants, clever use of this
28825 feature can often solve quite difficult problems in conditionalizing
28826 compilation (note incidentally that in Ada 95, the little endian
28827 constant was introduced as @code{System.Default_Bit_Order}, so you do not
28828 need to define this one yourself).
28829
28830
28831 @node Use of Alternative Implementations
28832 @section Use of Alternative Implementations
28833
28834 @noindent
28835 In some cases, none of the approaches described above are adequate. This
28836 can occur for example if the set of declarations required is radically
28837 different for two different configurations.
28838
28839 In this situation, the official Ada way of dealing with conditionalizing
28840 such code is to write separate units for the different cases. As long as
28841 this does not result in excessive duplication of code, this can be done
28842 without creating maintenance problems. The approach is to share common
28843 code as far as possible, and then isolate the code and declarations
28844 that are different. Subunits are often a convenient method for breaking
28845 out a piece of a unit that is to be conditionalized, with separate files
28846 for different versions of the subunit for different targets, where the
28847 build script selects the right one to give to the compiler.
28848 @cindex Subunits (and conditional compilation)
28849
28850 As an example, consider a situation where a new feature in Ada 2005
28851 allows something to be done in a really nice way. But your code must be able
28852 to compile with an Ada 95 compiler. Conceptually you want to say:
28853
28854 @smallexample @c ada
28855 @group
28856 if Ada_2005 then
28857    @dots{} neat Ada 2005 code
28858 else
28859    @dots{} not quite as neat Ada 95 code
28860 end if;
28861 @end group
28862 @end smallexample
28863
28864 @noindent
28865 where @code{Ada_2005} is a Boolean constant.
28866
28867 But this won't work when @code{Ada_2005} is set to @code{False},
28868 since the @code{then} clause will be illegal for an Ada 95 compiler.
28869 (Recall that although such unreachable code would eventually be deleted
28870 by the compiler, it still needs to be legal.  If it uses features
28871 introduced in Ada 2005, it will be illegal in Ada 95.)
28872
28873 So instead we write
28874
28875 @smallexample @c ada
28876 procedure Insert is separate;
28877 @end smallexample
28878
28879 @noindent
28880 Then we have two files for the subunit @code{Insert}, with the two sets of
28881 code.
28882 If the package containing this is called @code{File_Queries}, then we might
28883 have two files
28884
28885 @itemize @bullet
28886 @item    @file{file_queries-insert-2005.adb}
28887 @item    @file{file_queries-insert-95.adb}
28888 @end itemize
28889
28890 @noindent
28891 and the build script renames the appropriate file to
28892
28893 @smallexample
28894 file_queries-insert.adb
28895 @end smallexample
28896
28897 @noindent
28898 and then carries out the compilation.
28899
28900 This can also be done with project files' naming schemes. For example:
28901
28902 @smallexample @c project
28903 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
28904 @end smallexample
28905
28906 @noindent
28907 Note also that with project files it is desirable to use a different extension
28908 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
28909 conflict may arise through another commonly used feature: to declare as part
28910 of the project a set of directories containing all the sources obeying the
28911 default naming scheme.
28912
28913 The use of alternative units is certainly feasible in all situations,
28914 and for example the Ada part of the GNAT run-time is conditionalized
28915 based on the target architecture using this approach. As a specific example,
28916 consider the implementation of the AST feature in VMS. There is one
28917 spec:
28918
28919 @smallexample
28920 s-asthan.ads
28921 @end smallexample
28922
28923 @noindent
28924 which is the same for all architectures, and three bodies:
28925
28926 @table @file
28927 @item    s-asthan.adb
28928 used for all non-VMS operating systems
28929 @item    s-asthan-vms-alpha.adb
28930 used for VMS on the Alpha
28931 @item    s-asthan-vms-ia64.adb
28932 used for VMS on the ia64
28933 @end table
28934
28935 @noindent
28936 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
28937 this operating system feature is not available, and the two remaining
28938 versions interface with the corresponding versions of VMS to provide
28939 VMS-compatible AST handling. The GNAT build script knows the architecture
28940 and operating system, and automatically selects the right version,
28941 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
28942
28943 Another style for arranging alternative implementations is through Ada's
28944 access-to-subprogram facility.
28945 In case some functionality is to be conditionally included,
28946 you can declare an access-to-procedure variable @code{Ref} that is initialized
28947 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
28948 when appropriate.
28949 In some library package, set @code{Ref} to @code{Proc'Access} for some
28950 procedure @code{Proc} that performs the relevant processing.
28951 The initialization only occurs if the library package is included in the
28952 program.
28953 The same idea can also be implemented using tagged types and dispatching
28954 calls.
28955
28956
28957 @node Preprocessing
28958 @section Preprocessing
28959 @cindex Preprocessing
28960
28961 @noindent
28962 Although it is quite possible to conditionalize code without the use of
28963 C-style preprocessing, as described earlier in this section, it is
28964 nevertheless convenient in some cases to use the C approach. Moreover,
28965 older Ada compilers have often provided some preprocessing capability,
28966 so legacy code may depend on this approach, even though it is not
28967 standard.
28968
28969 To accommodate such use, GNAT provides a preprocessor (modeled to a large
28970 extent on the various preprocessors that have been used
28971 with legacy code on other compilers, to enable easier transition).
28972
28973 The preprocessor may be used in two separate modes. It can be used quite
28974 separately from the compiler, to generate a separate output source file
28975 that is then fed to the compiler as a separate step. This is the
28976 @code{gnatprep} utility, whose use is fully described in
28977 @ref{Preprocessing Using gnatprep}.
28978 @cindex @code{gnatprep}
28979
28980 The preprocessing language allows such constructs as
28981
28982 @smallexample
28983 @group
28984 #if DEBUG or PRIORITY > 4 then
28985    bunch of declarations
28986 #else
28987    completely different bunch of declarations
28988 #end if;
28989 @end group
28990 @end smallexample
28991
28992 @noindent
28993 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
28994 defined either on the command line or in a separate file.
28995
28996 The other way of running the preprocessor is even closer to the C style and
28997 often more convenient. In this approach the preprocessing is integrated into
28998 the compilation process. The compiler is fed the preprocessor input which
28999 includes @code{#if} lines etc, and then the compiler carries out the
29000 preprocessing internally and processes the resulting output.
29001 For more details on this approach, see @ref{Integrated Preprocessing}.
29002
29003
29004 @c *******************************
29005 @node Inline Assembler
29006 @appendix Inline Assembler
29007 @c *******************************
29008
29009 @noindent
29010 If you need to write low-level software that interacts directly
29011 with the hardware, Ada provides two ways to incorporate assembly
29012 language code into your program.  First, you can import and invoke
29013 external routines written in assembly language, an Ada feature fully
29014 supported by GNAT@.  However, for small sections of code it may be simpler
29015 or more efficient to include assembly language statements directly
29016 in your Ada source program, using the facilities of the implementation-defined
29017 package @code{System.Machine_Code}, which incorporates the gcc
29018 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
29019 including the following:
29020
29021 @itemize @bullet
29022 @item No need to use non-Ada tools
29023 @item Consistent interface over different targets
29024 @item Automatic usage of the proper calling conventions
29025 @item Access to Ada constants and variables
29026 @item Definition of intrinsic routines
29027 @item Possibility of inlining a subprogram comprising assembler code
29028 @item Code optimizer can take Inline Assembler code into account
29029 @end itemize
29030
29031 This chapter presents a series of examples to show you how to use
29032 the Inline Assembler.  Although it focuses on the Intel x86,
29033 the general approach applies also to other processors.
29034 It is assumed that you are familiar with Ada
29035 and with assembly language programming.
29036
29037 @menu
29038 * Basic Assembler Syntax::
29039 * A Simple Example of Inline Assembler::
29040 * Output Variables in Inline Assembler::
29041 * Input Variables in Inline Assembler::
29042 * Inlining Inline Assembler Code::
29043 * Other Asm Functionality::
29044 @end menu
29045
29046 @c ---------------------------------------------------------------------------
29047 @node Basic Assembler Syntax
29048 @section Basic Assembler Syntax
29049
29050 @noindent
29051 The assembler used by GNAT and gcc is based not on the Intel assembly
29052 language, but rather on a language that descends from the AT&T Unix
29053 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
29054 The following table summarizes the main features of @emph{as} syntax
29055 and points out the differences from the Intel conventions.
29056 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
29057 pre-processor) documentation for further information.
29058
29059 @table @asis
29060 @item Register names
29061 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
29062 @*
29063 Intel: No extra punctuation; for example @code{eax}
29064
29065 @item Immediate operand
29066 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
29067 @*
29068 Intel: No extra punctuation; for example @code{4}
29069
29070 @item Address
29071 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
29072 @*
29073 Intel: No extra punctuation; for example @code{loc}
29074
29075 @item Memory contents
29076 gcc / @emph{as}: No extra punctuation; for example @code{loc}
29077 @*
29078 Intel: Square brackets; for example @code{[loc]}
29079
29080 @item Register contents
29081 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
29082 @*
29083 Intel: Square brackets; for example @code{[eax]}
29084
29085 @item Hexadecimal numbers
29086 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
29087 @*
29088 Intel: Trailing ``h''; for example @code{A0h}
29089
29090 @item Operand size
29091 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
29092 a 16-bit word
29093 @*
29094 Intel: Implicit, deduced by assembler; for example @code{mov}
29095
29096 @item Instruction repetition
29097 gcc / @emph{as}: Split into two lines; for example
29098 @*
29099 @code{rep}
29100 @*
29101 @code{stosl}
29102 @*
29103 Intel: Keep on one line; for example @code{rep stosl}
29104
29105 @item Order of operands
29106 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
29107 @*
29108 Intel: Destination first; for example @code{mov eax, 4}
29109 @end table
29110
29111 @c ---------------------------------------------------------------------------
29112 @node A Simple Example of Inline Assembler
29113 @section A Simple Example of Inline Assembler
29114
29115 @noindent
29116 The following example will generate a single assembly language statement,
29117 @code{nop}, which does nothing.  Despite its lack of run-time effect,
29118 the example will be useful in illustrating the basics of
29119 the Inline Assembler facility.
29120
29121 @smallexample @c ada
29122 @group
29123 with System.Machine_Code; use System.Machine_Code;
29124 procedure Nothing is
29125 begin
29126    Asm ("nop");
29127 end Nothing;
29128 @end group
29129 @end smallexample
29130
29131 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
29132 here it takes one parameter, a @emph{template string} that must be a static
29133 expression and that will form the generated instruction.
29134 @code{Asm} may be regarded as a compile-time procedure that parses
29135 the template string and additional parameters (none here),
29136 from which it generates a sequence of assembly language instructions.
29137
29138 The examples in this chapter will illustrate several of the forms
29139 for invoking @code{Asm}; a complete specification of the syntax
29140 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
29141 Manual}.
29142
29143 Under the standard GNAT conventions, the @code{Nothing} procedure
29144 should be in a file named @file{nothing.adb}.
29145 You can build the executable in the usual way:
29146 @smallexample
29147 gnatmake nothing
29148 @end smallexample
29149 However, the interesting aspect of this example is not its run-time behavior
29150 but rather the generated assembly code.
29151 To see this output, invoke the compiler as follows:
29152 @smallexample
29153    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
29154 @end smallexample
29155 where the options are:
29156
29157 @table @code
29158 @item -c
29159 compile only (no bind or link)
29160 @item -S
29161 generate assembler listing
29162 @item -fomit-frame-pointer
29163 do not set up separate stack frames
29164 @item -gnatp
29165 do not add runtime checks
29166 @end table
29167
29168 This gives a human-readable assembler version of the code. The resulting
29169 file will have the same name as the Ada source file, but with a @code{.s}
29170 extension. In our example, the file @file{nothing.s} has the following
29171 contents:
29172
29173 @smallexample
29174 @group
29175 .file "nothing.adb"
29176 gcc2_compiled.:
29177 ___gnu_compiled_ada:
29178 .text
29179    .align 4
29180 .globl __ada_nothing
29181 __ada_nothing:
29182 #APP
29183    nop
29184 #NO_APP
29185    jmp L1
29186    .align 2,0x90
29187 L1:
29188    ret
29189 @end group
29190 @end smallexample
29191
29192 The assembly code you included is clearly indicated by
29193 the compiler, between the @code{#APP} and @code{#NO_APP}
29194 delimiters. The character before the 'APP' and 'NOAPP'
29195 can differ on different targets. For example, GNU/Linux uses '#APP' while
29196 on NT you will see '/APP'.
29197
29198 If you make a mistake in your assembler code (such as using the
29199 wrong size modifier, or using a wrong operand for the instruction) GNAT
29200 will report this error in a temporary file, which will be deleted when
29201 the compilation is finished.  Generating an assembler file will help
29202 in such cases, since you can assemble this file separately using the
29203 @emph{as} assembler that comes with gcc.
29204
29205 Assembling the file using the command
29206
29207 @smallexample
29208 as @file{nothing.s}
29209 @end smallexample
29210 @noindent
29211 will give you error messages whose lines correspond to the assembler
29212 input file, so you can easily find and correct any mistakes you made.
29213 If there are no errors, @emph{as} will generate an object file
29214 @file{nothing.out}.
29215
29216 @c ---------------------------------------------------------------------------
29217 @node Output Variables in Inline Assembler
29218 @section Output Variables in Inline Assembler
29219
29220 @noindent
29221 The examples in this section, showing how to access the processor flags,
29222 illustrate how to specify the destination operands for assembly language
29223 statements.
29224
29225 @smallexample @c ada
29226 @group
29227 with Interfaces; use Interfaces;
29228 with Ada.Text_IO; use Ada.Text_IO;
29229 with System.Machine_Code; use System.Machine_Code;
29230 procedure Get_Flags is
29231    Flags : Unsigned_32;
29232    use ASCII;
29233 begin
29234    Asm ("pushfl"          & LF & HT & -- push flags on stack
29235         "popl %%eax"      & LF & HT & -- load eax with flags
29236         "movl %%eax, %0",             -- store flags in variable
29237         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29238    Put_Line ("Flags register:" & Flags'Img);
29239 end Get_Flags;
29240 @end group
29241 @end smallexample
29242
29243 In order to have a nicely aligned assembly listing, we have separated
29244 multiple assembler statements in the Asm template string with linefeed
29245 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
29246 The resulting section of the assembly output file is:
29247
29248 @smallexample
29249 @group
29250 #APP
29251    pushfl
29252    popl %eax
29253    movl %eax, -40(%ebp)
29254 #NO_APP
29255 @end group
29256 @end smallexample
29257
29258 It would have been legal to write the Asm invocation as:
29259
29260 @smallexample
29261 Asm ("pushfl popl %%eax movl %%eax, %0")
29262 @end smallexample
29263
29264 but in the generated assembler file, this would come out as:
29265
29266 @smallexample
29267 #APP
29268    pushfl popl %eax movl %eax, -40(%ebp)
29269 #NO_APP
29270 @end smallexample
29271
29272 which is not so convenient for the human reader.
29273
29274 We use Ada comments
29275 at the end of each line to explain what the assembler instructions
29276 actually do.  This is a useful convention.
29277
29278 When writing Inline Assembler instructions, you need to precede each register
29279 and variable name with a percent sign.  Since the assembler already requires
29280 a percent sign at the beginning of a register name, you need two consecutive
29281 percent signs for such names in the Asm template string, thus @code{%%eax}.
29282 In the generated assembly code, one of the percent signs will be stripped off.
29283
29284 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
29285 variables: operands you later define using @code{Input} or @code{Output}
29286 parameters to @code{Asm}.
29287 An output variable is illustrated in
29288 the third statement in the Asm template string:
29289 @smallexample
29290 movl %%eax, %0
29291 @end smallexample
29292 The intent is to store the contents of the eax register in a variable that can
29293 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
29294 necessarily work, since the compiler might optimize by using a register
29295 to hold Flags, and the expansion of the @code{movl} instruction would not be
29296 aware of this optimization.  The solution is not to store the result directly
29297 but rather to advise the compiler to choose the correct operand form;
29298 that is the purpose of the @code{%0} output variable.
29299
29300 Information about the output variable is supplied in the @code{Outputs}
29301 parameter to @code{Asm}:
29302 @smallexample
29303 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29304 @end smallexample
29305
29306 The output is defined by the @code{Asm_Output} attribute of the target type;
29307 the general format is
29308 @smallexample
29309 Type'Asm_Output (constraint_string, variable_name)
29310 @end smallexample
29311
29312 The constraint string directs the compiler how
29313 to store/access the associated variable.  In the example
29314 @smallexample
29315 Unsigned_32'Asm_Output ("=m", Flags);
29316 @end smallexample
29317 the @code{"m"} (memory) constraint tells the compiler that the variable
29318 @code{Flags} should be stored in a memory variable, thus preventing
29319 the optimizer from keeping it in a register.  In contrast,
29320 @smallexample
29321 Unsigned_32'Asm_Output ("=r", Flags);
29322 @end smallexample
29323 uses the @code{"r"} (register) constraint, telling the compiler to
29324 store the variable in a register.
29325
29326 If the constraint is preceded by the equal character (@strong{=}), it tells
29327 the compiler that the variable will be used to store data into it.
29328
29329 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
29330 allowing the optimizer to choose whatever it deems best.
29331
29332 There are a fairly large number of constraints, but the ones that are
29333 most useful (for the Intel x86 processor) are the following:
29334
29335 @table @code
29336 @item =
29337 output constraint
29338 @item g
29339 global (i.e.@: can be stored anywhere)
29340 @item m
29341 in memory
29342 @item I
29343 a constant
29344 @item a
29345 use eax
29346 @item b
29347 use ebx
29348 @item c
29349 use ecx
29350 @item d
29351 use edx
29352 @item S
29353 use esi
29354 @item D
29355 use edi
29356 @item r
29357 use one of eax, ebx, ecx or edx
29358 @item q
29359 use one of eax, ebx, ecx, edx, esi or edi
29360 @end table
29361
29362 The full set of constraints is described in the gcc and @emph{as}
29363 documentation; note that it is possible to combine certain constraints
29364 in one constraint string.
29365
29366 You specify the association of an output variable with an assembler operand
29367 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
29368 integer.  Thus in
29369 @smallexample @c ada
29370 @group
29371 Asm ("pushfl"          & LF & HT & -- push flags on stack
29372      "popl %%eax"      & LF & HT & -- load eax with flags
29373      "movl %%eax, %0",             -- store flags in variable
29374      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29375 @end group
29376 @end smallexample
29377 @noindent
29378 @code{%0} will be replaced in the expanded code by the appropriate operand,
29379 whatever
29380 the compiler decided for the @code{Flags} variable.
29381
29382 In general, you may have any number of output variables:
29383 @itemize @bullet
29384 @item
29385 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
29386 @item
29387 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
29388 of @code{Asm_Output} attributes
29389 @end itemize
29390
29391 For example:
29392 @smallexample @c ada
29393 @group
29394 Asm ("movl %%eax, %0" & LF & HT &
29395      "movl %%ebx, %1" & LF & HT &
29396      "movl %%ecx, %2",
29397      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
29398                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
29399                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
29400 @end group
29401 @end smallexample
29402 @noindent
29403 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
29404 in the Ada program.
29405
29406 As a variation on the @code{Get_Flags} example, we can use the constraints
29407 string to direct the compiler to store the eax register into the @code{Flags}
29408 variable, instead of including the store instruction explicitly in the
29409 @code{Asm} template string:
29410
29411 @smallexample @c ada
29412 @group
29413 with Interfaces; use Interfaces;
29414 with Ada.Text_IO; use Ada.Text_IO;
29415 with System.Machine_Code; use System.Machine_Code;
29416 procedure Get_Flags_2 is
29417    Flags : Unsigned_32;
29418    use ASCII;
29419 begin
29420    Asm ("pushfl"      & LF & HT & -- push flags on stack
29421         "popl %%eax",             -- save flags in eax
29422         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
29423    Put_Line ("Flags register:" & Flags'Img);
29424 end Get_Flags_2;
29425 @end group
29426 @end smallexample
29427
29428 @noindent
29429 The @code{"a"} constraint tells the compiler that the @code{Flags}
29430 variable will come from the eax register. Here is the resulting code:
29431
29432 @smallexample
29433 @group
29434 #APP
29435    pushfl
29436    popl %eax
29437 #NO_APP
29438    movl %eax,-40(%ebp)
29439 @end group
29440 @end smallexample
29441
29442 @noindent
29443 The compiler generated the store of eax into Flags after
29444 expanding the assembler code.
29445
29446 Actually, there was no need to pop the flags into the eax register;
29447 more simply, we could just pop the flags directly into the program variable:
29448
29449 @smallexample @c ada
29450 @group
29451 with Interfaces; use Interfaces;
29452 with Ada.Text_IO; use Ada.Text_IO;
29453 with System.Machine_Code; use System.Machine_Code;
29454 procedure Get_Flags_3 is
29455    Flags : Unsigned_32;
29456    use ASCII;
29457 begin
29458    Asm ("pushfl"  & LF & HT & -- push flags on stack
29459         "pop %0",             -- save flags in Flags
29460         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29461    Put_Line ("Flags register:" & Flags'Img);
29462 end Get_Flags_3;
29463 @end group
29464 @end smallexample
29465
29466 @c ---------------------------------------------------------------------------
29467 @node Input Variables in Inline Assembler
29468 @section Input Variables in Inline Assembler
29469
29470 @noindent
29471 The example in this section illustrates how to specify the source operands
29472 for assembly language statements.
29473 The program simply increments its input value by 1:
29474
29475 @smallexample @c ada
29476 @group
29477 with Interfaces; use Interfaces;
29478 with Ada.Text_IO; use Ada.Text_IO;
29479 with System.Machine_Code; use System.Machine_Code;
29480 procedure Increment is
29481
29482    function Incr (Value : Unsigned_32) return Unsigned_32 is
29483       Result : Unsigned_32;
29484    begin
29485       Asm ("incl %0",
29486            Inputs  => Unsigned_32'Asm_Input ("a", Value),
29487            Outputs => Unsigned_32'Asm_Output ("=a", Result));
29488       return Result;
29489    end Incr;
29490
29491    Value : Unsigned_32;
29492
29493 begin
29494    Value := 5;
29495    Put_Line ("Value before is" & Value'Img);
29496    Value := Incr (Value);
29497    Put_Line ("Value after is" & Value'Img);
29498 end Increment;
29499 @end group
29500 @end smallexample
29501
29502 The @code{Outputs} parameter to @code{Asm} specifies
29503 that the result will be in the eax register and that it is to be stored
29504 in the @code{Result} variable.
29505
29506 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
29507 but with an @code{Asm_Input} attribute.
29508 The @code{"="} constraint, indicating an output value, is not present.
29509
29510 You can have multiple input variables, in the same way that you can have more
29511 than one output variable.
29512
29513 The parameter count (%0, %1) etc, now starts at the first input
29514 statement, and continues with the output statements.
29515 When both parameters use the same variable, the
29516 compiler will treat them as the same %n operand, which is the case here.
29517
29518 Just as the @code{Outputs} parameter causes the register to be stored into the
29519 target variable after execution of the assembler statements, so does the
29520 @code{Inputs} parameter cause its variable to be loaded into the register
29521 before execution of the assembler statements.
29522
29523 Thus the effect of the @code{Asm} invocation is:
29524 @enumerate
29525 @item load the 32-bit value of @code{Value} into eax
29526 @item execute the @code{incl %eax} instruction
29527 @item store the contents of eax into the @code{Result} variable
29528 @end enumerate
29529
29530 The resulting assembler file (with @option{-O2} optimization) contains:
29531 @smallexample
29532 @group
29533 _increment__incr.1:
29534    subl $4,%esp
29535    movl 8(%esp),%eax
29536 #APP
29537    incl %eax
29538 #NO_APP
29539    movl %eax,%edx
29540    movl %ecx,(%esp)
29541    addl $4,%esp
29542    ret
29543 @end group
29544 @end smallexample
29545
29546 @c ---------------------------------------------------------------------------
29547 @node Inlining Inline Assembler Code
29548 @section Inlining Inline Assembler Code
29549
29550 @noindent
29551 For a short subprogram such as the @code{Incr} function in the previous
29552 section, the overhead of the call and return (creating / deleting the stack
29553 frame) can be significant, compared to the amount of code in the subprogram
29554 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
29555 which directs the compiler to expand invocations of the subprogram at the
29556 point(s) of call, instead of setting up a stack frame for out-of-line calls.
29557 Here is the resulting program:
29558
29559 @smallexample @c ada
29560 @group
29561 with Interfaces; use Interfaces;
29562 with Ada.Text_IO; use Ada.Text_IO;
29563 with System.Machine_Code; use System.Machine_Code;
29564 procedure Increment_2 is
29565
29566    function Incr (Value : Unsigned_32) return Unsigned_32 is
29567       Result : Unsigned_32;
29568    begin
29569       Asm ("incl %0",
29570            Inputs  => Unsigned_32'Asm_Input ("a", Value),
29571            Outputs => Unsigned_32'Asm_Output ("=a", Result));
29572       return Result;
29573    end Incr;
29574    pragma Inline (Increment);
29575
29576    Value : Unsigned_32;
29577
29578 begin
29579    Value := 5;
29580    Put_Line ("Value before is" & Value'Img);
29581    Value := Increment (Value);
29582    Put_Line ("Value after is" & Value'Img);
29583 end Increment_2;
29584 @end group
29585 @end smallexample
29586
29587 Compile the program with both optimization (@option{-O2}) and inlining
29588 (@option{-gnatn}) enabled.
29589
29590 The @code{Incr} function is still compiled as usual, but at the
29591 point in @code{Increment} where our function used to be called:
29592
29593 @smallexample
29594 @group
29595 pushl %edi
29596 call _increment__incr.1
29597 @end group
29598 @end smallexample
29599
29600 @noindent
29601 the code for the function body directly appears:
29602
29603 @smallexample
29604 @group
29605 movl %esi,%eax
29606 #APP
29607    incl %eax
29608 #NO_APP
29609    movl %eax,%edx
29610 @end group
29611 @end smallexample
29612
29613 @noindent
29614 thus saving the overhead of stack frame setup and an out-of-line call.
29615
29616 @c ---------------------------------------------------------------------------
29617 @node Other Asm Functionality
29618 @section Other @code{Asm} Functionality
29619
29620 @noindent
29621 This section describes two important parameters to the @code{Asm}
29622 procedure: @code{Clobber}, which identifies register usage;
29623 and @code{Volatile}, which inhibits unwanted optimizations.
29624
29625 @menu
29626 * The Clobber Parameter::
29627 * The Volatile Parameter::
29628 @end menu
29629
29630 @c ---------------------------------------------------------------------------
29631 @node The Clobber Parameter
29632 @subsection The @code{Clobber} Parameter
29633
29634 @noindent
29635 One of the dangers of intermixing assembly language and a compiled language
29636 such as Ada is that the compiler needs to be aware of which registers are
29637 being used by the assembly code.  In some cases, such as the earlier examples,
29638 the constraint string is sufficient to indicate register usage (e.g.,
29639 @code{"a"} for
29640 the eax register).  But more generally, the compiler needs an explicit
29641 identification of the registers that are used by the Inline Assembly
29642 statements.
29643
29644 Using a register that the compiler doesn't know about
29645 could be a side effect of an instruction (like @code{mull}
29646 storing its result in both eax and edx).
29647 It can also arise from explicit register usage in your
29648 assembly code; for example:
29649 @smallexample
29650 @group
29651 Asm ("movl %0, %%ebx" & LF & HT &
29652      "movl %%ebx, %1",
29653      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
29654      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
29655 @end group
29656 @end smallexample
29657 @noindent
29658 where the compiler (since it does not analyze the @code{Asm} template string)
29659 does not know you are using the ebx register.
29660
29661 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
29662 to identify the registers that will be used by your assembly code:
29663
29664 @smallexample
29665 @group
29666 Asm ("movl %0, %%ebx" & LF & HT &
29667      "movl %%ebx, %1",
29668      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
29669      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
29670      Clobber => "ebx");
29671 @end group
29672 @end smallexample
29673
29674 The Clobber parameter is a static string expression specifying the
29675 register(s) you are using.  Note that register names are @emph{not} prefixed
29676 by a percent sign. Also, if more than one register is used then their names
29677 are separated by commas; e.g., @code{"eax, ebx"}
29678
29679 The @code{Clobber} parameter has several additional uses:
29680 @enumerate
29681 @item Use ``register'' name @code{cc} to indicate that flags might have changed
29682 @item Use ``register'' name @code{memory} if you changed a memory location
29683 @end enumerate
29684
29685 @c ---------------------------------------------------------------------------
29686 @node The Volatile Parameter
29687 @subsection The @code{Volatile} Parameter
29688 @cindex Volatile parameter
29689
29690 @noindent
29691 Compiler optimizations in the presence of Inline Assembler may sometimes have
29692 unwanted effects.  For example, when an @code{Asm} invocation with an input
29693 variable is inside a loop, the compiler might move the loading of the input
29694 variable outside the loop, regarding it as a one-time initialization.
29695
29696 If this effect is not desired, you can disable such optimizations by setting
29697 the @code{Volatile} parameter to @code{True}; for example:
29698
29699 @smallexample @c ada
29700 @group
29701 Asm ("movl %0, %%ebx" & LF & HT &
29702      "movl %%ebx, %1",
29703      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
29704      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
29705      Clobber  => "ebx",
29706      Volatile => True);
29707 @end group
29708 @end smallexample
29709
29710 By default, @code{Volatile} is set to @code{False} unless there is no
29711 @code{Outputs} parameter.
29712
29713 Although setting @code{Volatile} to @code{True} prevents unwanted
29714 optimizations, it will also disable other optimizations that might be
29715 important for efficiency. In general, you should set @code{Volatile}
29716 to @code{True} only if the compiler's optimizations have created
29717 problems.
29718 @c END OF INLINE ASSEMBLER CHAPTER
29719 @c ===============================
29720
29721 @c ***********************************
29722 @c * Compatibility and Porting Guide *
29723 @c ***********************************
29724 @node Compatibility and Porting Guide
29725 @appendix Compatibility and Porting Guide
29726
29727 @noindent
29728 This chapter describes the compatibility issues that may arise between
29729 GNAT and other Ada compilation systems (including those for Ada 83),
29730 and shows how GNAT can expedite porting
29731 applications developed in other Ada environments.
29732
29733 @menu
29734 * Compatibility with Ada 83::
29735 * Compatibility between Ada 95 and Ada 2005::
29736 * Implementation-dependent characteristics::
29737 * Compatibility with Other Ada Systems::
29738 * Representation Clauses::
29739 @ifclear vms
29740 @c Brief section is only in non-VMS version
29741 @c Full chapter is in VMS version
29742 * Compatibility with HP Ada 83::
29743 @end ifclear
29744 @ifset vms
29745 * Transitioning to 64-Bit GNAT for OpenVMS::
29746 @end ifset
29747 @end menu
29748
29749 @node Compatibility with Ada 83
29750 @section Compatibility with Ada 83
29751 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
29752
29753 @noindent
29754 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
29755 particular, the design intention was that the difficulties associated
29756 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
29757 that occur when moving from one Ada 83 system to another.
29758
29759 However, there are a number of points at which there are minor
29760 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
29761 full details of these issues,
29762 and should be consulted for a complete treatment.
29763 In practice the
29764 following subsections treat the most likely issues to be encountered.
29765
29766 @menu
29767 * Legal Ada 83 programs that are illegal in Ada 95::
29768 * More deterministic semantics::
29769 * Changed semantics::
29770 * Other language compatibility issues::
29771 @end menu
29772
29773 @node Legal Ada 83 programs that are illegal in Ada 95
29774 @subsection Legal Ada 83 programs that are illegal in Ada 95
29775
29776 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
29777 Ada 95 and thus also in Ada 2005:
29778
29779 @table @emph
29780 @item Character literals
29781 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
29782 @code{Wide_Character} as a new predefined character type, some uses of
29783 character literals that were legal in Ada 83 are illegal in Ada 95.
29784 For example:
29785 @smallexample @c ada
29786    for Char in 'A' .. 'Z' loop @dots{} end loop;
29787 @end smallexample
29788
29789 @noindent
29790 The problem is that @code{'A'} and @code{'Z'} could be from either
29791 @code{Character} or @code{Wide_Character}.  The simplest correction
29792 is to make the type explicit; e.g.:
29793 @smallexample @c ada
29794    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
29795 @end smallexample
29796
29797 @item New reserved words
29798 The identifiers @code{abstract}, @code{aliased}, @code{protected},
29799 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
29800 Existing Ada 83 code using any of these identifiers must be edited to
29801 use some alternative name.
29802
29803 @item Freezing rules
29804 The rules in Ada 95 are slightly different with regard to the point at
29805 which entities are frozen, and representation pragmas and clauses are
29806 not permitted past the freeze point.  This shows up most typically in
29807 the form of an error message complaining that a representation item
29808 appears too late, and the appropriate corrective action is to move
29809 the item nearer to the declaration of the entity to which it refers.
29810
29811 A particular case is that representation pragmas
29812 @ifset vms
29813 (including the
29814 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
29815 @end ifset
29816 cannot be applied to a subprogram body.  If necessary, a separate subprogram
29817 declaration must be introduced to which the pragma can be applied.
29818
29819 @item Optional bodies for library packages
29820 In Ada 83, a package that did not require a package body was nevertheless
29821 allowed to have one.  This lead to certain surprises in compiling large
29822 systems (situations in which the body could be unexpectedly ignored by the
29823 binder).  In Ada 95, if a package does not require a body then it is not
29824 permitted to have a body.  To fix this problem, simply remove a redundant
29825 body if it is empty, or, if it is non-empty, introduce a dummy declaration
29826 into the spec that makes the body required.  One approach is to add a private
29827 part to the package declaration (if necessary), and define a parameterless
29828 procedure called @code{Requires_Body}, which must then be given a dummy
29829 procedure body in the package body, which then becomes required.
29830 Another approach (assuming that this does not introduce elaboration
29831 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
29832 since one effect of this pragma is to require the presence of a package body.
29833
29834 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
29835 In Ada 95, the exception @code{Numeric_Error} is a renaming of
29836 @code{Constraint_Error}.
29837 This means that it is illegal to have separate exception handlers for
29838 the two exceptions.  The fix is simply to remove the handler for the
29839 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
29840 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
29841
29842 @item Indefinite subtypes in generics
29843 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
29844 as the actual for a generic formal private type, but then the instantiation
29845 would be illegal if there were any instances of declarations of variables
29846 of this type in the generic body.  In Ada 95, to avoid this clear violation
29847 of the methodological principle known as the ``contract model'',
29848 the generic declaration explicitly indicates whether
29849 or not such instantiations are permitted.  If a generic formal parameter
29850 has explicit unknown discriminants, indicated by using @code{(<>)} after the
29851 type name, then it can be instantiated with indefinite types, but no
29852 stand-alone variables can be declared of this type.  Any attempt to declare
29853 such a variable will result in an illegality at the time the generic is
29854 declared.  If the @code{(<>)} notation is not used, then it is illegal
29855 to instantiate the generic with an indefinite type.
29856 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
29857 It will show up as a compile time error, and
29858 the fix is usually simply to add the @code{(<>)} to the generic declaration.
29859 @end table
29860
29861 @node More deterministic semantics
29862 @subsection More deterministic semantics
29863
29864 @table @emph
29865 @item Conversions
29866 Conversions from real types to integer types round away from 0.  In Ada 83
29867 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
29868 implementation freedom was intended to support unbiased rounding in
29869 statistical applications, but in practice it interfered with portability.
29870 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
29871 is required.  Numeric code may be affected by this change in semantics.
29872 Note, though, that this issue is no worse than already existed in Ada 83
29873 when porting code from one vendor to another.
29874
29875 @item Tasking
29876 The Real-Time Annex introduces a set of policies that define the behavior of
29877 features that were implementation dependent in Ada 83, such as the order in
29878 which open select branches are executed.
29879 @end table
29880
29881 @node Changed semantics
29882 @subsection Changed semantics
29883
29884 @noindent
29885 The worst kind of incompatibility is one where a program that is legal in
29886 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
29887 possible in Ada 83.  Fortunately this is extremely rare, but the one
29888 situation that you should be alert to is the change in the predefined type
29889 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
29890
29891 @table @emph
29892 @item Range of type @code{Character}
29893 The range of @code{Standard.Character} is now the full 256 characters
29894 of Latin-1, whereas in most Ada 83 implementations it was restricted
29895 to 128 characters. Although some of the effects of
29896 this change will be manifest in compile-time rejection of legal
29897 Ada 83 programs it is possible for a working Ada 83 program to have
29898 a different effect in Ada 95, one that was not permitted in Ada 83.
29899 As an example, the expression
29900 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
29901 delivers @code{255} as its value.
29902 In general, you should look at the logic of any
29903 character-processing Ada 83 program and see whether it needs to be adapted
29904 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
29905 character handling package that may be relevant if code needs to be adapted
29906 to account for the additional Latin-1 elements.
29907 The desirable fix is to
29908 modify the program to accommodate the full character set, but in some cases
29909 it may be convenient to define a subtype or derived type of Character that
29910 covers only the restricted range.
29911 @cindex Latin-1
29912 @end table
29913
29914 @node Other language compatibility issues
29915 @subsection Other language compatibility issues
29916
29917 @table @emph
29918 @item @option{-gnat83} switch
29919 All implementations of GNAT provide a switch that causes GNAT to operate
29920 in Ada 83 mode.  In this mode, some but not all compatibility problems
29921 of the type described above are handled automatically.  For example, the
29922 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
29923 as identifiers as in Ada 83.
29924 However,
29925 in practice, it is usually advisable to make the necessary modifications
29926 to the program to remove the need for using this switch.
29927 See @ref{Compiling Different Versions of Ada}.
29928
29929 @item Support for removed Ada 83 pragmas and attributes
29930 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
29931 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
29932 compilers are allowed, but not required, to implement these missing
29933 elements.  In contrast with some other compilers, GNAT implements all
29934 such pragmas and attributes, eliminating this compatibility concern.  These
29935 include @code{pragma Interface} and the floating point type attributes
29936 (@code{Emax}, @code{Mantissa}, etc.), among other items.
29937 @end table
29938
29939
29940 @node Compatibility between Ada 95 and Ada 2005
29941 @section Compatibility between Ada 95 and Ada 2005
29942 @cindex Compatibility between Ada 95 and Ada 2005
29943
29944 @noindent
29945 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
29946 a number of incompatibilities. Several are enumerated below;
29947 for a complete description please see the
29948 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
29949 @cite{Rationale for Ada 2005}.
29950
29951 @table @emph
29952 @item New reserved words.
29953 The words @code{interface}, @code{overriding} and @code{synchronized} are
29954 reserved in Ada 2005.
29955 A pre-Ada 2005 program that uses any of these as an identifier will be
29956 illegal.
29957
29958 @item New declarations in predefined packages.
29959 A number of packages in the predefined environment contain new declarations:
29960 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
29961 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
29962 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
29963 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
29964 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
29965 If an Ada 95 program does a @code{with} and @code{use} of any of these
29966 packages, the new declarations may cause name clashes.
29967
29968 @item Access parameters.
29969 A nondispatching subprogram with an access parameter cannot be renamed
29970 as a dispatching operation.  This was permitted in Ada 95.
29971
29972 @item Access types, discriminants, and constraints.
29973 Rule changes in this area have led to some incompatibilities; for example,
29974 constrained subtypes of some access types are not permitted in Ada 2005.
29975
29976 @item Aggregates for limited types.
29977 The allowance of aggregates for limited types in Ada 2005 raises the
29978 possibility of ambiguities in legal Ada 95 programs, since additional types
29979 now need to be considered in expression resolution.
29980
29981 @item Fixed-point multiplication and division.
29982 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
29983 were legal in Ada 95 and invoked the predefined versions of these operations,
29984 are now ambiguous.
29985 The ambiguity may be resolved either by applying a type conversion to the
29986 expression, or by explicitly invoking the operation from package
29987 @code{Standard}.
29988
29989 @item Return-by-reference types.
29990 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
29991 can declare a function returning a value from an anonymous access type.
29992 @end table
29993
29994
29995 @node Implementation-dependent characteristics
29996 @section Implementation-dependent characteristics
29997 @noindent
29998 Although the Ada language defines the semantics of each construct as
29999 precisely as practical, in some situations (for example for reasons of
30000 efficiency, or where the effect is heavily dependent on the host or target
30001 platform) the implementation is allowed some freedom.  In porting Ada 83
30002 code to GNAT, you need to be aware of whether / how the existing code
30003 exercised such implementation dependencies.  Such characteristics fall into
30004 several categories, and GNAT offers specific support in assisting the
30005 transition from certain Ada 83 compilers.
30006
30007 @menu
30008 * Implementation-defined pragmas::
30009 * Implementation-defined attributes::
30010 * Libraries::
30011 * Elaboration order::
30012 * Target-specific aspects::
30013 @end menu
30014
30015 @node Implementation-defined pragmas
30016 @subsection Implementation-defined pragmas
30017
30018 @noindent
30019 Ada compilers are allowed to supplement the language-defined pragmas, and
30020 these are a potential source of non-portability.  All GNAT-defined pragmas
30021 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
30022 Reference Manual}, and these include several that are specifically
30023 intended to correspond to other vendors' Ada 83 pragmas.
30024 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
30025 For compatibility with HP Ada 83, GNAT supplies the pragmas
30026 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
30027 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
30028 and @code{Volatile}.
30029 Other relevant pragmas include @code{External} and @code{Link_With}.
30030 Some vendor-specific
30031 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
30032 recognized, thus
30033 avoiding compiler rejection of units that contain such pragmas; they are not
30034 relevant in a GNAT context and hence are not otherwise implemented.
30035
30036 @node Implementation-defined attributes
30037 @subsection Implementation-defined attributes
30038
30039 Analogous to pragmas, the set of attributes may be extended by an
30040 implementation.  All GNAT-defined attributes are described in
30041 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
30042 Manual}, and these include several that are specifically intended
30043 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
30044 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
30045 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
30046 @code{Type_Class}.
30047
30048 @node Libraries
30049 @subsection Libraries
30050 @noindent
30051 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
30052 code uses vendor-specific libraries then there are several ways to manage
30053 this in Ada 95 or Ada 2005:
30054 @enumerate
30055 @item
30056 If the source code for the libraries (specs and bodies) are
30057 available, then the libraries can be migrated in the same way as the
30058 application.
30059 @item
30060 If the source code for the specs but not the bodies are
30061 available, then you can reimplement the bodies.
30062 @item
30063 Some features introduced by Ada 95 obviate the need for library support.  For
30064 example most Ada 83 vendors supplied a package for unsigned integers.  The
30065 Ada 95 modular type feature is the preferred way to handle this need, so
30066 instead of migrating or reimplementing the unsigned integer package it may
30067 be preferable to retrofit the application using modular types.
30068 @end enumerate
30069
30070 @node Elaboration order
30071 @subsection Elaboration order
30072 @noindent
30073 The implementation can choose any elaboration order consistent with the unit
30074 dependency relationship.  This freedom means that some orders can result in
30075 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
30076 to invoke a subprogram its body has been elaborated, or to instantiate a
30077 generic before the generic body has been elaborated.  By default GNAT
30078 attempts to choose a safe order (one that will not encounter access before
30079 elaboration problems) by implicitly inserting @code{Elaborate} or
30080 @code{Elaborate_All} pragmas where
30081 needed.  However, this can lead to the creation of elaboration circularities
30082 and a resulting rejection of the program by gnatbind.  This issue is
30083 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
30084 In brief, there are several
30085 ways to deal with this situation:
30086
30087 @itemize @bullet
30088 @item
30089 Modify the program to eliminate the circularities, e.g.@: by moving
30090 elaboration-time code into explicitly-invoked procedures
30091 @item
30092 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
30093 @code{Elaborate} pragmas, and then inhibit the generation of implicit
30094 @code{Elaborate_All}
30095 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
30096 (by selectively suppressing elaboration checks via pragma
30097 @code{Suppress(Elaboration_Check)} when it is safe to do so).
30098 @end itemize
30099
30100 @node Target-specific aspects
30101 @subsection Target-specific aspects
30102 @noindent
30103 Low-level applications need to deal with machine addresses, data
30104 representations, interfacing with assembler code, and similar issues.  If
30105 such an Ada 83 application is being ported to different target hardware (for
30106 example where the byte endianness has changed) then you will need to
30107 carefully examine the program logic; the porting effort will heavily depend
30108 on the robustness of the original design.  Moreover, Ada 95 (and thus
30109 Ada 2005) are sometimes
30110 incompatible with typical Ada 83 compiler practices regarding implicit
30111 packing, the meaning of the Size attribute, and the size of access values.
30112 GNAT's approach to these issues is described in @ref{Representation Clauses}.
30113
30114 @node Compatibility with Other Ada Systems
30115 @section Compatibility with Other Ada Systems
30116
30117 @noindent
30118 If programs avoid the use of implementation dependent and
30119 implementation defined features, as documented in the @cite{Ada
30120 Reference Manual}, there should be a high degree of portability between
30121 GNAT and other Ada systems.  The following are specific items which
30122 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
30123 compilers, but do not affect porting code to GNAT@.
30124 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
30125 the following issues may or may not arise for Ada 2005 programs
30126 when other compilers appear.)
30127
30128 @table @emph
30129 @item Ada 83 Pragmas and Attributes
30130 Ada 95 compilers are allowed, but not required, to implement the missing
30131 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
30132 GNAT implements all such pragmas and attributes, eliminating this as
30133 a compatibility concern, but some other Ada 95 compilers reject these
30134 pragmas and attributes.
30135
30136 @item Specialized Needs Annexes
30137 GNAT implements the full set of special needs annexes.  At the
30138 current time, it is the only Ada 95 compiler to do so.  This means that
30139 programs making use of these features may not be portable to other Ada
30140 95 compilation systems.
30141
30142 @item Representation Clauses
30143 Some other Ada 95 compilers implement only the minimal set of
30144 representation clauses required by the Ada 95 reference manual.  GNAT goes
30145 far beyond this minimal set, as described in the next section.
30146 @end table
30147
30148 @node Representation Clauses
30149 @section Representation Clauses
30150
30151 @noindent
30152 The Ada 83 reference manual was quite vague in describing both the minimal
30153 required implementation of representation clauses, and also their precise
30154 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
30155 minimal set of capabilities required is still quite limited.
30156
30157 GNAT implements the full required set of capabilities in
30158 Ada 95 and Ada 2005, but also goes much further, and in particular
30159 an effort has been made to be compatible with existing Ada 83 usage to the
30160 greatest extent possible.
30161
30162 A few cases exist in which Ada 83 compiler behavior is incompatible with
30163 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
30164 intentional or accidental dependence on specific implementation dependent
30165 characteristics of these Ada 83 compilers.  The following is a list of
30166 the cases most likely to arise in existing Ada 83 code.
30167
30168 @table @emph
30169 @item Implicit Packing
30170 Some Ada 83 compilers allowed a Size specification to cause implicit
30171 packing of an array or record.  This could cause expensive implicit
30172 conversions for change of representation in the presence of derived
30173 types, and the Ada design intends to avoid this possibility.
30174 Subsequent AI's were issued to make it clear that such implicit
30175 change of representation in response to a Size clause is inadvisable,
30176 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
30177 Reference Manuals as implementation advice that is followed by GNAT@.
30178 The problem will show up as an error
30179 message rejecting the size clause.  The fix is simply to provide
30180 the explicit pragma @code{Pack}, or for more fine tuned control, provide
30181 a Component_Size clause.
30182
30183 @item Meaning of Size Attribute
30184 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
30185 the minimal number of bits required to hold values of the type.  For example,
30186 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
30187 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
30188 some 32 in this situation.  This problem will usually show up as a compile
30189 time error, but not always.  It is a good idea to check all uses of the
30190 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
30191 Object_Size can provide a useful way of duplicating the behavior of
30192 some Ada 83 compiler systems.
30193
30194 @item Size of Access Types
30195 A common assumption in Ada 83 code is that an access type is in fact a pointer,
30196 and that therefore it will be the same size as a System.Address value.  This
30197 assumption is true for GNAT in most cases with one exception.  For the case of
30198 a pointer to an unconstrained array type (where the bounds may vary from one
30199 value of the access type to another), the default is to use a ``fat pointer'',
30200 which is represented as two separate pointers, one to the bounds, and one to
30201 the array.  This representation has a number of advantages, including improved
30202 efficiency.  However, it may cause some difficulties in porting existing Ada 83
30203 code which makes the assumption that, for example, pointers fit in 32 bits on
30204 a machine with 32-bit addressing.
30205
30206 To get around this problem, GNAT also permits the use of ``thin pointers'' for
30207 access types in this case (where the designated type is an unconstrained array
30208 type).  These thin pointers are indeed the same size as a System.Address value.
30209 To specify a thin pointer, use a size clause for the type, for example:
30210
30211 @smallexample @c ada
30212 type X is access all String;
30213 for X'Size use Standard'Address_Size;
30214 @end smallexample
30215
30216 @noindent
30217 which will cause the type X to be represented using a single pointer.
30218 When using this representation, the bounds are right behind the array.
30219 This representation is slightly less efficient, and does not allow quite
30220 such flexibility in the use of foreign pointers or in using the
30221 Unrestricted_Access attribute to create pointers to non-aliased objects.
30222 But for any standard portable use of the access type it will work in
30223 a functionally correct manner and allow porting of existing code.
30224 Note that another way of forcing a thin pointer representation
30225 is to use a component size clause for the element size in an array,
30226 or a record representation clause for an access field in a record.
30227 @end table
30228
30229 @ifclear vms
30230 @c This brief section is only in the non-VMS version
30231 @c The complete chapter on HP Ada is in the VMS version
30232 @node Compatibility with HP Ada 83
30233 @section Compatibility with HP Ada 83
30234
30235 @noindent
30236 The VMS version of GNAT fully implements all the pragmas and attributes
30237 provided by HP Ada 83, as well as providing the standard HP Ada 83
30238 libraries, including Starlet.  In addition, data layouts and parameter
30239 passing conventions are highly compatible.  This means that porting
30240 existing HP Ada 83 code to GNAT in VMS systems should be easier than
30241 most other porting efforts.  The following are some of the most
30242 significant differences between GNAT and HP Ada 83.
30243
30244 @table @emph
30245 @item Default floating-point representation
30246 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
30247 it is VMS format.  GNAT does implement the necessary pragmas
30248 (Long_Float, Float_Representation) for changing this default.
30249
30250 @item System
30251 The package System in GNAT exactly corresponds to the definition in the
30252 Ada 95 reference manual, which means that it excludes many of the
30253 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
30254 that contains the additional definitions, and a special pragma,
30255 Extend_System allows this package to be treated transparently as an
30256 extension of package System.
30257
30258 @item To_Address
30259 The definitions provided by Aux_DEC are exactly compatible with those
30260 in the HP Ada 83 version of System, with one exception.
30261 HP Ada provides the following declarations:
30262
30263 @smallexample @c ada
30264 TO_ADDRESS (INTEGER)
30265 TO_ADDRESS (UNSIGNED_LONGWORD)
30266 TO_ADDRESS (@i{universal_integer})
30267 @end smallexample
30268
30269 @noindent
30270 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
30271 an extension to Ada 83 not strictly compatible with the reference manual.
30272 In GNAT, we are constrained to be exactly compatible with the standard,
30273 and this means we cannot provide this capability.  In HP Ada 83, the
30274 point of this definition is to deal with a call like:
30275
30276 @smallexample @c ada
30277 TO_ADDRESS (16#12777#);
30278 @end smallexample
30279
30280 @noindent
30281 Normally, according to the Ada 83 standard, one would expect this to be
30282 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
30283 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
30284 definition using @i{universal_integer} takes precedence.
30285
30286 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
30287 is not possible to be 100% compatible.  Since there are many programs using
30288 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
30289 to change the name of the function in the UNSIGNED_LONGWORD case, so the
30290 declarations provided in the GNAT version of AUX_Dec are:
30291
30292 @smallexample @c ada
30293 function To_Address (X : Integer) return Address;
30294 pragma Pure_Function (To_Address);
30295
30296 function To_Address_Long (X : Unsigned_Longword)
30297  return Address;
30298 pragma Pure_Function (To_Address_Long);
30299 @end smallexample
30300
30301 @noindent
30302 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
30303 change the name to TO_ADDRESS_LONG@.
30304
30305 @item Task_Id values
30306 The Task_Id values assigned will be different in the two systems, and GNAT
30307 does not provide a specified value for the Task_Id of the environment task,
30308 which in GNAT is treated like any other declared task.
30309 @end table
30310
30311 @noindent
30312 For full details on these and other less significant compatibility issues,
30313 see appendix E of the HP publication entitled @cite{HP Ada, Technical
30314 Overview and Comparison on HP Platforms}.
30315
30316 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
30317 attributes are recognized, although only a subset of them can sensibly
30318 be implemented.  The description of pragmas in @ref{Implementation
30319 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
30320 indicates whether or not they are applicable to non-VMS systems.
30321 @end ifclear
30322
30323 @ifset vms
30324 @node Transitioning to 64-Bit GNAT for OpenVMS
30325 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
30326
30327 @noindent
30328 This section is meant to assist users of pre-2006 @value{EDITION}
30329 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
30330 the version of the GNAT technology supplied in 2006 and later for
30331 OpenVMS on both Alpha and I64.
30332
30333 @menu
30334 * Introduction to transitioning::
30335 * Migration of 32 bit code::
30336 * Taking advantage of 64 bit addressing::
30337 * Technical details::
30338 @end menu
30339
30340 @node Introduction to transitioning
30341 @subsection Introduction
30342
30343 @noindent
30344 64-bit @value{EDITION} for Open VMS has been designed to meet
30345 three main goals:
30346
30347 @enumerate
30348 @item
30349 Providing a full conforming implementation of Ada 95 and Ada 2005
30350
30351 @item
30352 Allowing maximum backward compatibility, thus easing migration of existing
30353 Ada source code
30354
30355 @item
30356 Supplying a path for exploiting the full 64-bit address range
30357 @end enumerate
30358
30359 @noindent
30360 Ada's strong typing semantics has made it
30361 impractical to have different 32-bit and 64-bit modes. As soon as
30362 one object could possibly be outside the 32-bit address space, this
30363 would make it necessary for the @code{System.Address} type to be 64 bits.
30364 In particular, this would cause inconsistencies if 32-bit code is
30365 called from 64-bit code that raises an exception.
30366
30367 This issue has been resolved by always using 64-bit addressing
30368 at the system level, but allowing for automatic conversions between
30369 32-bit and 64-bit addresses where required. Thus users who
30370 do not currently require 64-bit addressing capabilities, can
30371 recompile their code with only minimal changes (and indeed
30372 if the code is written in portable Ada, with no assumptions about
30373 the size of the @code{Address} type, then no changes at all are necessary).
30374 At the same time,
30375 this approach provides a simple, gradual upgrade path to future
30376 use of larger memories than available for 32-bit systems.
30377 Also, newly written applications or libraries will by default
30378 be fully compatible with future systems exploiting 64-bit
30379 addressing capabilities.
30380
30381 @ref{Migration of 32 bit code}, will focus on porting applications
30382 that do not require more than 2 GB of
30383 addressable memory. This code will be referred to as
30384 @emph{32-bit code}.
30385 For applications intending to exploit the full 64-bit address space,
30386 @ref{Taking advantage of 64 bit addressing},
30387 will consider further changes that may be required.
30388 Such code will be referred to below as @emph{64-bit code}.
30389
30390 @node Migration of 32 bit code
30391 @subsection Migration of 32-bit code
30392
30393 @menu
30394 * Address types::
30395 * Access types::
30396 * Unchecked conversions::
30397 * Predefined constants::
30398 * Interfacing with C::
30399 * Experience with source compatibility::
30400 @end menu
30401
30402 @node Address types
30403 @subsubsection Address types
30404
30405 @noindent
30406 To solve the problem of mixing 64-bit and 32-bit addressing,
30407 while maintaining maximum backward compatibility, the following
30408 approach has been taken:
30409
30410 @itemize @bullet
30411 @item
30412 @code{System.Address} always has a size of 64 bits
30413
30414 @item
30415 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
30416 @end itemize
30417
30418 @noindent
30419 Since @code{System.Short_Address} is a subtype of @code{System.Address},
30420 a @code{Short_Address}
30421 may be used where an @code{Address} is required, and vice versa, without
30422 needing explicit type conversions.
30423 By virtue of the Open VMS parameter passing conventions,
30424 even imported
30425 and exported subprograms that have 32-bit address parameters are
30426 compatible with those that have 64-bit address parameters.
30427 (See @ref{Making code 64 bit clean} for details.)
30428
30429 The areas that may need attention are those where record types have
30430 been defined that contain components of the type @code{System.Address}, and
30431 where objects of this type are passed to code expecting a record layout with
30432 32-bit addresses.
30433
30434 Different compilers on different platforms cannot be
30435 expected to represent the same type in the same way,
30436 since alignment constraints
30437 and other system-dependent properties affect the compiler's decision.
30438 For that reason, Ada code
30439 generally uses representation clauses to specify the expected
30440 layout where required.
30441
30442 If such a representation clause uses 32 bits for a component having
30443 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
30444 will detect that error and produce a specific diagnostic message.
30445 The developer should then determine whether the representation
30446 should be 64 bits or not and make either of two changes:
30447 change the size to 64 bits and leave the type as @code{System.Address}, or
30448 leave the size as 32 bits and change the type to @code{System.Short_Address}.
30449 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
30450 required in any code setting or accessing the field; the compiler will
30451 automatically perform any needed conversions between address
30452 formats.
30453
30454 @node Access types
30455 @subsubsection Access types
30456
30457 @noindent
30458 By default, objects designated by access values are always
30459 allocated in the 32-bit
30460 address space. Thus legacy code will never contain
30461 any objects that are not addressable with 32-bit addresses, and
30462 the compiler will never raise exceptions as result of mixing
30463 32-bit and 64-bit addresses.
30464
30465 However, the access values themselves are represented in 64 bits, for optimum
30466 performance and future compatibility with 64-bit code. As was
30467 the case with @code{System.Address}, the compiler will give an error message
30468 if an object or record component has a representation clause that
30469 requires the access value to fit in 32 bits. In such a situation,
30470 an explicit size clause for the access type, specifying 32 bits,
30471 will have the desired effect.
30472
30473 General access types (declared with @code{access all}) can never be
30474 32 bits, as values of such types must be able to refer to any object
30475 of the  designated type,
30476 including objects residing outside the 32-bit address range.
30477 Existing Ada 83 code will not contain such type definitions,
30478 however, since general access types were introduced in Ada 95.
30479
30480 @node Unchecked conversions
30481 @subsubsection Unchecked conversions
30482
30483 @noindent
30484 In the case of an @code{Unchecked_Conversion} where the source type is a
30485 64-bit access type or the type @code{System.Address}, and the target
30486 type is a 32-bit type, the compiler will generate a warning.
30487 Even though the generated code will still perform the required
30488 conversions, it is highly recommended in these cases to use
30489 respectively a 32-bit access type or @code{System.Short_Address}
30490 as the source type.
30491
30492 @node Predefined constants
30493 @subsubsection Predefined constants
30494
30495 @noindent
30496 The following table shows the correspondence between pre-2006 versions of
30497 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
30498 (``New''):
30499
30500 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
30501 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
30502 @item   @code{System.Word_Size}          @tab 32      @tab 64
30503 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
30504 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
30505 @item   @code{System.Address_Size}       @tab 32      @tab 64
30506 @end multitable
30507
30508 @noindent
30509 If you need to refer to the specific
30510 memory size of a 32-bit implementation, instead of the
30511 actual memory size, use @code{System.Short_Memory_Size}
30512 rather than @code{System.Memory_Size}.
30513 Similarly, references to @code{System.Address_Size} may need
30514 to be replaced by @code{System.Short_Address'Size}.
30515 The program @command{gnatfind} may be useful for locating
30516 references to the above constants, so that you can verify that they
30517 are still correct.
30518
30519 @node Interfacing with C
30520 @subsubsection Interfacing with C
30521
30522 @noindent
30523 In order to minimize the impact of the transition to 64-bit addresses on
30524 legacy programs, some fundamental types in the @code{Interfaces.C}
30525 package hierarchy continue to be represented in 32 bits.
30526 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
30527 This eases integration with the default HP C layout choices, for example
30528 as found in the system routines in @code{DECC$SHR.EXE}.
30529 Because of this implementation choice, the type fully compatible with
30530 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
30531 Depending on the context the compiler will issue a
30532 warning or an error when type @code{Address} is used, alerting the user to a
30533 potential problem. Otherwise 32-bit programs that use
30534 @code{Interfaces.C} should normally not require code modifications
30535
30536 The other issue arising with C interfacing concerns pragma @code{Convention}.
30537 For VMS 64-bit systems, there is an issue of the appropriate default size
30538 of C convention pointers in the absence of an explicit size clause. The HP
30539 C compiler can choose either 32 or 64 bits depending on compiler options.
30540 GNAT chooses 32-bits rather than 64-bits in the default case where no size
30541 clause is given. This proves a better choice for porting 32-bit legacy
30542 applications. In order to have a 64-bit representation, it is necessary to
30543 specify a size representation clause. For example:
30544
30545 @smallexample @c ada
30546 type int_star is access Interfaces.C.int;
30547 pragma Convention(C, int_star);
30548 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
30549 @end smallexample
30550
30551 @node Experience with source compatibility
30552 @subsubsection Experience with source compatibility
30553
30554 @noindent
30555 The Security Server and STARLET on I64 provide an interesting ``test case''
30556 for source compatibility issues, since it is in such system code
30557 where assumptions about @code{Address} size might be expected to occur.
30558 Indeed, there were a small number of occasions in the Security Server
30559 file @file{jibdef.ads}
30560 where a representation clause for a record type specified
30561 32 bits for a component of type @code{Address}.
30562 All of these errors were detected by the compiler.
30563 The repair was obvious and immediate; to simply replace @code{Address} by
30564 @code{Short_Address}.
30565
30566 In the case of STARLET, there were several record types that should
30567 have had representation clauses but did not.  In these record types
30568 there was an implicit assumption that an @code{Address} value occupied
30569 32 bits.
30570 These compiled without error, but their usage resulted in run-time error
30571 returns from STARLET system calls.
30572 Future GNAT technology enhancements may include a tool that detects and flags
30573 these sorts of potential source code porting problems.
30574
30575 @c ****************************************
30576 @node Taking advantage of 64 bit addressing
30577 @subsection Taking advantage of 64-bit addressing
30578
30579 @menu
30580 * Making code 64 bit clean::
30581 * Allocating memory from the 64 bit storage pool::
30582 * Restrictions on use of 64 bit objects::
30583 * Using 64 bit storage pools by default::
30584 * General access types::
30585 * STARLET and other predefined libraries::
30586 @end menu
30587
30588 @node Making code 64 bit clean
30589 @subsubsection Making code 64-bit clean
30590
30591 @noindent
30592 In order to prevent problems that may occur when (parts of) a
30593 system start using memory outside the 32-bit address range,
30594 we recommend some additional guidelines:
30595
30596 @itemize @bullet
30597 @item
30598 For imported subprograms that take parameters of the
30599 type @code{System.Address}, ensure that these subprograms can
30600 indeed handle 64-bit addresses. If not, or when in doubt,
30601 change the subprogram declaration to specify
30602 @code{System.Short_Address} instead.
30603
30604 @item
30605 Resolve all warnings related to size mismatches in
30606 unchecked conversions. Failing to do so causes
30607 erroneous execution if the source object is outside
30608 the 32-bit address space.
30609
30610 @item
30611 (optional) Explicitly use the 32-bit storage pool
30612 for access types used in a 32-bit context, or use
30613 generic access types where possible
30614 (@pxref{Restrictions on use of 64 bit objects}).
30615 @end itemize
30616
30617 @noindent
30618 If these rules are followed, the compiler will automatically insert
30619 any necessary checks to ensure that no addresses or access values
30620 passed to 32-bit code ever refer to objects outside the 32-bit
30621 address range.
30622 Any attempt to do this will raise @code{Constraint_Error}.
30623
30624 @node Allocating memory from the 64 bit storage pool
30625 @subsubsection Allocating memory from the 64-bit storage pool
30626
30627 @noindent
30628 For any access type @code{T} that potentially requires memory allocations
30629 beyond the 32-bit address space,
30630 use the following representation clause:
30631
30632 @smallexample @c ada
30633    for T'Storage_Pool use System.Pool_64;
30634 @end smallexample
30635
30636 @node Restrictions on use of 64 bit objects
30637 @subsubsection Restrictions on use of 64-bit objects
30638
30639 @noindent
30640 Taking the address of an object allocated from a 64-bit storage pool,
30641 and then passing this address to a subprogram expecting
30642 @code{System.Short_Address},
30643 or assigning it to a variable of type @code{Short_Address}, will cause
30644 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
30645 (@pxref{Making code 64 bit clean}), or checks are suppressed,
30646 no exception is raised and execution
30647 will become erroneous.
30648
30649 @node Using 64 bit storage pools by default
30650 @subsubsection Using 64-bit storage pools by default
30651
30652 @noindent
30653 In some cases it may be desirable to have the compiler allocate
30654 from 64-bit storage pools by default. This may be the case for
30655 libraries that are 64-bit clean, but may be used in both 32-bit
30656 and 64-bit contexts. For these cases the following configuration
30657 pragma may be specified:
30658
30659 @smallexample @c ada
30660   pragma Pool_64_Default;
30661 @end smallexample
30662
30663 @noindent
30664 Any code compiled in the context of this pragma will by default
30665 use the @code{System.Pool_64} storage pool. This default may be overridden
30666 for a specific access type @code{T} by the representation clause:
30667
30668 @smallexample @c ada
30669    for T'Storage_Pool use System.Pool_32;
30670 @end smallexample
30671
30672 @noindent
30673 Any object whose address may be passed to a subprogram with a
30674 @code{Short_Address} argument, or assigned to a variable of type
30675 @code{Short_Address}, needs to be allocated from this pool.
30676
30677 @node General access types
30678 @subsubsection General access types
30679
30680 @noindent
30681 Objects designated by access values from a
30682 general access type (declared with @code{access all}) are never allocated
30683 from a 64-bit storage pool. Code that uses general access types will
30684 accept objects allocated in either 32-bit or 64-bit address spaces,
30685 but never allocate objects outside the 32-bit address space.
30686 Using general access types ensures maximum compatibility with both
30687 32-bit and 64-bit code.
30688
30689 @node STARLET and other predefined libraries
30690 @subsubsection STARLET and other predefined libraries
30691
30692 @noindent
30693 All code that comes as part of GNAT is 64-bit clean, but the
30694 restrictions given in @ref{Restrictions on use of 64 bit objects},
30695 still apply. Look at the package
30696 specs to see in which contexts objects allocated
30697 in 64-bit address space are acceptable.
30698
30699 @node Technical details
30700 @subsection Technical details
30701
30702 @noindent
30703 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
30704 Ada standard with respect to the type of @code{System.Address}. Previous
30705 versions of GNAT Pro have defined this type as private and implemented it as a
30706 modular type.
30707
30708 In order to allow defining @code{System.Short_Address} as a proper subtype,
30709 and to match the implicit sign extension in parameter passing,
30710 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
30711 visible (i.e., non-private) integer type.
30712 Standard operations on the type, such as the binary operators ``+'', ``-'',
30713 etc., that take @code{Address} operands and return an @code{Address} result,
30714 have been hidden by declaring these
30715 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
30716 ambiguities that would otherwise result from overloading.
30717 (Note that, although @code{Address} is a visible integer type,
30718 good programming practice dictates against exploiting the type's
30719 integer properties such as literals, since this will compromise
30720 code portability.)
30721
30722 Defining @code{Address} as a visible integer type helps achieve
30723 maximum compatibility for existing Ada code,
30724 without sacrificing the capabilities of the 64-bit architecture.
30725 @end ifset
30726
30727 @c ************************************************
30728 @ifset unw
30729 @node Microsoft Windows Topics
30730 @appendix Microsoft Windows Topics
30731 @cindex Windows NT
30732 @cindex Windows 95
30733 @cindex Windows 98
30734
30735 @noindent
30736 This chapter describes topics that are specific to the Microsoft Windows
30737 platforms (NT, 2000, and XP Professional).
30738
30739 @menu
30740 * Using GNAT on Windows::
30741 * Using a network installation of GNAT::
30742 * CONSOLE and WINDOWS subsystems::
30743 * Temporary Files::
30744 * Mixed-Language Programming on Windows::
30745 * Windows Calling Conventions::
30746 * Introduction to Dynamic Link Libraries (DLLs)::
30747 * Using DLLs with GNAT::
30748 * Building DLLs with GNAT::
30749 * Building DLLs with GNAT Project files::
30750 * Building DLLs with gnatdll::
30751 * GNAT and Windows Resources::
30752 * Debugging a DLL::
30753 * Setting Stack Size from gnatlink::
30754 * Setting Heap Size from gnatlink::
30755 @end menu
30756
30757 @node Using GNAT on Windows
30758 @section Using GNAT on Windows
30759
30760 @noindent
30761 One of the strengths of the GNAT technology is that its tool set
30762 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
30763 @code{gdb} debugger, etc.) is used in the same way regardless of the
30764 platform.
30765
30766 On Windows this tool set is complemented by a number of Microsoft-specific
30767 tools that have been provided to facilitate interoperability with Windows
30768 when this is required. With these tools:
30769
30770 @itemize @bullet
30771
30772 @item
30773 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
30774 subsystems.
30775
30776 @item
30777 You can use any Dynamically Linked Library (DLL) in your Ada code (both
30778 relocatable and non-relocatable DLLs are supported).
30779
30780 @item
30781 You can build Ada DLLs for use in other applications. These applications
30782 can be written in a language other than Ada (e.g., C, C++, etc). Again both
30783 relocatable and non-relocatable Ada DLLs are supported.
30784
30785 @item
30786 You can include Windows resources in your Ada application.
30787
30788 @item
30789 You can use or create COM/DCOM objects.
30790 @end itemize
30791
30792 @noindent
30793 Immediately below are listed all known general GNAT-for-Windows restrictions.
30794 Other restrictions about specific features like Windows Resources and DLLs
30795 are listed in separate sections below.
30796
30797 @itemize @bullet
30798
30799 @item
30800 It is not possible to use @code{GetLastError} and @code{SetLastError}
30801 when tasking, protected records, or exceptions are used. In these
30802 cases, in order to implement Ada semantics, the GNAT run-time system
30803 calls certain Win32 routines that set the last error variable to 0 upon
30804 success. It should be possible to use @code{GetLastError} and
30805 @code{SetLastError} when tasking, protected record, and exception
30806 features are not used, but it is not guaranteed to work.
30807
30808 @item
30809 It is not possible to link against Microsoft libraries except for
30810 import libraries. The library must be built to be compatible with
30811 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
30812 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
30813 not be compatible with the GNAT runtime. Even if the library is
30814 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
30815
30816 @item
30817 When the compilation environment is located on FAT32 drives, users may
30818 experience recompilations of the source files that have not changed if
30819 Daylight Saving Time (DST) state has changed since the last time files
30820 were compiled. NTFS drives do not have this problem.
30821
30822 @item
30823 No components of the GNAT toolset use any entries in the Windows
30824 registry. The only entries that can be created are file associations and
30825 PATH settings, provided the user has chosen to create them at installation
30826 time, as well as some minimal book-keeping information needed to correctly
30827 uninstall or integrate different GNAT products.
30828 @end itemize
30829
30830 @node Using a network installation of GNAT
30831 @section Using a network installation of GNAT
30832
30833 @noindent
30834 Make sure the system on which GNAT is installed is accessible from the
30835 current machine, i.e., the install location is shared over the network.
30836 Shared resources are accessed on Windows by means of UNC paths, which
30837 have the format @code{\\server\sharename\path}
30838
30839 In order to use such a network installation, simply add the UNC path of the
30840 @file{bin} directory of your GNAT installation in front of your PATH. For
30841 example, if GNAT is installed in @file{\GNAT} directory of a share location
30842 called @file{c-drive} on a machine @file{LOKI}, the following command will
30843 make it available:
30844
30845 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
30846
30847 Be aware that every compilation using the network installation results in the
30848 transfer of large amounts of data across the network and will likely cause
30849 serious performance penalty.
30850
30851 @node CONSOLE and WINDOWS subsystems
30852 @section CONSOLE and WINDOWS subsystems
30853 @cindex CONSOLE Subsystem
30854 @cindex WINDOWS Subsystem
30855 @cindex -mwindows
30856
30857 @noindent
30858 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
30859 (which is the default subsystem) will always create a console when
30860 launching the application. This is not something desirable when the
30861 application has a Windows GUI. To get rid of this console the
30862 application must be using the @code{WINDOWS} subsystem. To do so
30863 the @option{-mwindows} linker option must be specified.
30864
30865 @smallexample
30866 $ gnatmake winprog -largs -mwindows
30867 @end smallexample
30868
30869 @node Temporary Files
30870 @section Temporary Files
30871 @cindex Temporary files
30872
30873 @noindent
30874 It is possible to control where temporary files gets created by setting
30875 the @env{TMP} environment variable. The file will be created:
30876
30877 @itemize
30878 @item Under the directory pointed to by the @env{TMP} environment variable if
30879 this directory exists.
30880
30881 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
30882 set (or not pointing to a directory) and if this directory exists.
30883
30884 @item Under the current working directory otherwise.
30885 @end itemize
30886
30887 @noindent
30888 This allows you to determine exactly where the temporary
30889 file will be created. This is particularly useful in networked
30890 environments where you may not have write access to some
30891 directories.
30892
30893 @node Mixed-Language Programming on Windows
30894 @section Mixed-Language Programming on Windows
30895
30896 @noindent
30897 Developing pure Ada applications on Windows is no different than on
30898 other GNAT-supported platforms. However, when developing or porting an
30899 application that contains a mix of Ada and C/C++, the choice of your
30900 Windows C/C++ development environment conditions your overall
30901 interoperability strategy.
30902
30903 If you use @command{gcc} to compile the non-Ada part of your application,
30904 there are no Windows-specific restrictions that affect the overall
30905 interoperability with your Ada code. If you plan to use
30906 Microsoft tools (e.g.@: Microsoft Visual C/C++), you should be aware of
30907 the following limitations:
30908
30909 @itemize @bullet
30910 @item
30911 You cannot link your Ada code with an object or library generated with
30912 Microsoft tools if these use the @code{.tls} section (Thread Local
30913 Storage section) since the GNAT linker does not yet support this section.
30914
30915 @item
30916 You cannot link your Ada code with an object or library generated with
30917 Microsoft tools if these use I/O routines other than those provided in
30918 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
30919 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
30920 libraries can cause a conflict with @code{msvcrt.dll} services. For
30921 instance Visual C++ I/O stream routines conflict with those in
30922 @code{msvcrt.dll}.
30923 @end itemize
30924
30925 @noindent
30926 If you do want to use the Microsoft tools for your non-Ada code and hit one
30927 of the above limitations, you have two choices:
30928
30929 @enumerate
30930 @item
30931 Encapsulate your non-Ada code in a DLL to be linked with your Ada
30932 application. In this case, use the Microsoft or whatever environment to
30933 build the DLL and use GNAT to build your executable
30934 (@pxref{Using DLLs with GNAT}).
30935
30936 @item
30937 Or you can encapsulate your Ada code in a DLL to be linked with the
30938 other part of your application. In this case, use GNAT to build the DLL
30939 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
30940 environment to build your executable.
30941 @end enumerate
30942
30943 @node Windows Calling Conventions
30944 @section Windows Calling Conventions
30945 @findex Stdcall
30946 @findex APIENTRY
30947
30948 @menu
30949 * C Calling Convention::
30950 * Stdcall Calling Convention::
30951 * Win32 Calling Convention::
30952 * DLL Calling Convention::
30953 @end menu
30954
30955 @noindent
30956 When a subprogram @code{F} (caller) calls a subprogram @code{G}
30957 (callee), there are several ways to push @code{G}'s parameters on the
30958 stack and there are several possible scenarios to clean up the stack
30959 upon @code{G}'s return. A calling convention is an agreed upon software
30960 protocol whereby the responsibilities between the caller (@code{F}) and
30961 the callee (@code{G}) are clearly defined. Several calling conventions
30962 are available for Windows:
30963
30964 @itemize @bullet
30965 @item
30966 @code{C} (Microsoft defined)
30967
30968 @item
30969 @code{Stdcall} (Microsoft defined)
30970
30971 @item
30972 @code{Win32} (GNAT specific)
30973
30974 @item
30975 @code{DLL} (GNAT specific)
30976 @end itemize
30977
30978 @node C Calling Convention
30979 @subsection @code{C} Calling Convention
30980
30981 @noindent
30982 This is the default calling convention used when interfacing to C/C++
30983 routines compiled with either @command{gcc} or Microsoft Visual C++.
30984
30985 In the @code{C} calling convention subprogram parameters are pushed on the
30986 stack by the caller from right to left. The caller itself is in charge of
30987 cleaning up the stack after the call. In addition, the name of a routine
30988 with @code{C} calling convention is mangled by adding a leading underscore.
30989
30990 The name to use on the Ada side when importing (or exporting) a routine
30991 with @code{C} calling convention is the name of the routine. For
30992 instance the C function:
30993
30994 @smallexample
30995 int get_val (long);
30996 @end smallexample
30997
30998 @noindent
30999 should be imported from Ada as follows:
31000
31001 @smallexample @c ada
31002 @group
31003 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31004 pragma Import (C, Get_Val, External_Name => "get_val");
31005 @end group
31006 @end smallexample
31007
31008 @noindent
31009 Note that in this particular case the @code{External_Name} parameter could
31010 have been omitted since, when missing, this parameter is taken to be the
31011 name of the Ada entity in lower case. When the @code{Link_Name} parameter
31012 is missing, as in the above example, this parameter is set to be the
31013 @code{External_Name} with a leading underscore.
31014
31015 When importing a variable defined in C, you should always use the @code{C}
31016 calling convention unless the object containing the variable is part of a
31017 DLL (in which case you should use the @code{Stdcall} calling
31018 convention, @pxref{Stdcall Calling Convention}).
31019
31020 @node Stdcall Calling Convention
31021 @subsection @code{Stdcall} Calling Convention
31022
31023 @noindent
31024 This convention, which was the calling convention used for Pascal
31025 programs, is used by Microsoft for all the routines in the Win32 API for
31026 efficiency reasons. It must be used to import any routine for which this
31027 convention was specified.
31028
31029 In the @code{Stdcall} calling convention subprogram parameters are pushed
31030 on the stack by the caller from right to left. The callee (and not the
31031 caller) is in charge of cleaning the stack on routine exit. In addition,
31032 the name of a routine with @code{Stdcall} calling convention is mangled by
31033 adding a leading underscore (as for the @code{C} calling convention) and a
31034 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
31035 bytes) of the parameters passed to the routine.
31036
31037 The name to use on the Ada side when importing a C routine with a
31038 @code{Stdcall} calling convention is the name of the C routine. The leading
31039 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
31040 the compiler. For instance the Win32 function:
31041
31042 @smallexample
31043 @b{APIENTRY} int get_val (long);
31044 @end smallexample
31045
31046 @noindent
31047 should be imported from Ada as follows:
31048
31049 @smallexample @c ada
31050 @group
31051 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31052 pragma Import (Stdcall, Get_Val);
31053 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
31054 @end group
31055 @end smallexample
31056
31057 @noindent
31058 As for the @code{C} calling convention, when the @code{External_Name}
31059 parameter is missing, it is taken to be the name of the Ada entity in lower
31060 case. If instead of writing the above import pragma you write:
31061
31062 @smallexample @c ada
31063 @group
31064 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31065 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
31066 @end group
31067 @end smallexample
31068
31069 @noindent
31070 then the imported routine is @code{_retrieve_val@@4}. However, if instead
31071 of specifying the @code{External_Name} parameter you specify the
31072 @code{Link_Name} as in the following example:
31073
31074 @smallexample @c ada
31075 @group
31076 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31077 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
31078 @end group
31079 @end smallexample
31080
31081 @noindent
31082 then the imported routine is @code{retrieve_val}, that is, there is no
31083 decoration at all. No leading underscore and no Stdcall suffix
31084 @code{@@}@code{@var{nn}}.
31085
31086 @noindent
31087 This is especially important as in some special cases a DLL's entry
31088 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
31089 name generated for a call has it.
31090
31091 @noindent
31092 It is also possible to import variables defined in a DLL by using an
31093 import pragma for a variable. As an example, if a DLL contains a
31094 variable defined as:
31095
31096 @smallexample
31097 int my_var;
31098 @end smallexample
31099
31100 @noindent
31101 then, to access this variable from Ada you should write:
31102
31103 @smallexample @c ada
31104 @group
31105 My_Var : Interfaces.C.int;
31106 pragma Import (Stdcall, My_Var);
31107 @end group
31108 @end smallexample
31109
31110 @noindent
31111 Note that to ease building cross-platform bindings this convention
31112 will be handled as a @code{C} calling convention on non-Windows platforms.
31113
31114 @node Win32 Calling Convention
31115 @subsection @code{Win32} Calling Convention
31116
31117 @noindent
31118 This convention, which is GNAT-specific is fully equivalent to the
31119 @code{Stdcall} calling convention described above.
31120
31121 @node DLL Calling Convention
31122 @subsection @code{DLL} Calling Convention
31123
31124 @noindent
31125 This convention, which is GNAT-specific is fully equivalent to the
31126 @code{Stdcall} calling convention described above.
31127
31128 @node Introduction to Dynamic Link Libraries (DLLs)
31129 @section Introduction to Dynamic Link Libraries (DLLs)
31130 @findex DLL
31131
31132 @noindent
31133 A Dynamically Linked Library (DLL) is a library that can be shared by
31134 several applications running under Windows. A DLL can contain any number of
31135 routines and variables.
31136
31137 One advantage of DLLs is that you can change and enhance them without
31138 forcing all the applications that depend on them to be relinked or
31139 recompiled. However, you should be aware than all calls to DLL routines are
31140 slower since, as you will understand below, such calls are indirect.
31141
31142 To illustrate the remainder of this section, suppose that an application
31143 wants to use the services of a DLL @file{API.dll}. To use the services
31144 provided by @file{API.dll} you must statically link against the DLL or
31145 an import library which contains a jump table with an entry for each
31146 routine and variable exported by the DLL. In the Microsoft world this
31147 import library is called @file{API.lib}. When using GNAT this import
31148 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
31149 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
31150
31151 After you have linked your application with the DLL or the import library
31152 and you run your application, here is what happens:
31153
31154 @enumerate
31155 @item
31156 Your application is loaded into memory.
31157
31158 @item
31159 The DLL @file{API.dll} is mapped into the address space of your
31160 application. This means that:
31161
31162 @itemize @bullet
31163 @item
31164 The DLL will use the stack of the calling thread.
31165
31166 @item
31167 The DLL will use the virtual address space of the calling process.
31168
31169 @item
31170 The DLL will allocate memory from the virtual address space of the calling
31171 process.
31172
31173 @item
31174 Handles (pointers) can be safely exchanged between routines in the DLL
31175 routines and routines in the application using the DLL.
31176 @end itemize
31177
31178 @item
31179 The entries in the jump table (from the import library @file{libAPI.dll.a}
31180 or @file{API.lib} or automatically created when linking against a DLL)
31181 which is part of your application are initialized with the addresses
31182 of the routines and variables in @file{API.dll}.
31183
31184 @item
31185 If present in @file{API.dll}, routines @code{DllMain} or
31186 @code{DllMainCRTStartup} are invoked. These routines typically contain
31187 the initialization code needed for the well-being of the routines and
31188 variables exported by the DLL.
31189 @end enumerate
31190
31191 @noindent
31192 There is an additional point which is worth mentioning. In the Windows
31193 world there are two kind of DLLs: relocatable and non-relocatable
31194 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
31195 in the target application address space. If the addresses of two
31196 non-relocatable DLLs overlap and these happen to be used by the same
31197 application, a conflict will occur and the application will run
31198 incorrectly. Hence, when possible, it is always preferable to use and
31199 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
31200 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
31201 User's Guide) removes the debugging symbols from the DLL but the DLL can
31202 still be relocated.
31203
31204 As a side note, an interesting difference between Microsoft DLLs and
31205 Unix shared libraries, is the fact that on most Unix systems all public
31206 routines are exported by default in a Unix shared library, while under
31207 Windows it is possible (but not required) to list exported routines in
31208 a definition file (@pxref{The Definition File}).
31209
31210 @node Using DLLs with GNAT
31211 @section Using DLLs with GNAT
31212
31213 @menu
31214 * Creating an Ada Spec for the DLL Services::
31215 * Creating an Import Library::
31216 @end menu
31217
31218 @noindent
31219 To use the services of a DLL, say @file{API.dll}, in your Ada application
31220 you must have:
31221
31222 @enumerate
31223 @item
31224 The Ada spec for the routines and/or variables you want to access in
31225 @file{API.dll}. If not available this Ada spec must be built from the C/C++
31226 header files provided with the DLL.
31227
31228 @item
31229 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
31230 mentioned an import library is a statically linked library containing the
31231 import table which will be filled at load time to point to the actual
31232 @file{API.dll} routines. Sometimes you don't have an import library for the
31233 DLL you want to use. The following sections will explain how to build
31234 one. Note that this is optional.
31235
31236 @item
31237 The actual DLL, @file{API.dll}.
31238 @end enumerate
31239
31240 @noindent
31241 Once you have all the above, to compile an Ada application that uses the
31242 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
31243 you simply issue the command
31244
31245 @smallexample
31246 $ gnatmake my_ada_app -largs -lAPI
31247 @end smallexample
31248
31249 @noindent
31250 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
31251 tells the GNAT linker to look first for a library named @file{API.lib}
31252 (Microsoft-style name) and if not found for a libraries named
31253 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
31254 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
31255 contains the following pragma
31256
31257 @smallexample @c ada
31258 pragma Linker_Options ("-lAPI");
31259 @end smallexample
31260
31261 @noindent
31262 you do not have to add @option{-largs -lAPI} at the end of the
31263 @command{gnatmake} command.
31264
31265 If any one of the items above is missing you will have to create it
31266 yourself. The following sections explain how to do so using as an
31267 example a fictitious DLL called @file{API.dll}.
31268
31269 @node Creating an Ada Spec for the DLL Services
31270 @subsection Creating an Ada Spec for the DLL Services
31271
31272 @noindent
31273 A DLL typically comes with a C/C++ header file which provides the
31274 definitions of the routines and variables exported by the DLL. The Ada
31275 equivalent of this header file is a package spec that contains definitions
31276 for the imported entities. If the DLL you intend to use does not come with
31277 an Ada spec you have to generate one such spec yourself. For example if
31278 the header file of @file{API.dll} is a file @file{api.h} containing the
31279 following two definitions:
31280
31281 @smallexample
31282 @group
31283 @cartouche
31284 int some_var;
31285 int get (char *);
31286 @end cartouche
31287 @end group
31288 @end smallexample
31289
31290 @noindent
31291 then the equivalent Ada spec could be:
31292
31293 @smallexample @c ada
31294 @group
31295 @cartouche
31296 with Interfaces.C.Strings;
31297 package API is
31298    use Interfaces;
31299
31300    Some_Var : C.int;
31301    function Get (Str : C.Strings.Chars_Ptr) return C.int;
31302
31303 private
31304    pragma Import (C, Get);
31305    pragma Import (DLL, Some_Var);
31306 end API;
31307 @end cartouche
31308 @end group
31309 @end smallexample
31310
31311 @noindent
31312 Note that a variable is
31313 @strong{always imported with a Stdcall convention}. A function
31314 can have @code{C} or @code{Stdcall} convention.
31315 (@pxref{Windows Calling Conventions}).
31316
31317 @node Creating an Import Library
31318 @subsection Creating an Import Library
31319 @cindex Import library
31320
31321 @menu
31322 * The Definition File::
31323 * GNAT-Style Import Library::
31324 * Microsoft-Style Import Library::
31325 @end menu
31326
31327 @noindent
31328 If a Microsoft-style import library @file{API.lib} or a GNAT-style
31329 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
31330 with @file{API.dll} you can skip this section. You can also skip this
31331 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
31332 as in this case it is possible to link directly against the
31333 DLL. Otherwise read on.
31334
31335 @node The Definition File
31336 @subsubsection The Definition File
31337 @cindex Definition file
31338 @findex .def
31339
31340 @noindent
31341 As previously mentioned, and unlike Unix systems, the list of symbols
31342 that are exported from a DLL must be provided explicitly in Windows.
31343 The main goal of a definition file is precisely that: list the symbols
31344 exported by a DLL. A definition file (usually a file with a @code{.def}
31345 suffix) has the following structure:
31346
31347 @smallexample
31348 @group
31349 @cartouche
31350 @r{[}LIBRARY @var{name}@r{]}
31351 @r{[}DESCRIPTION @var{string}@r{]}
31352 EXPORTS
31353    @var{symbol1}
31354    @var{symbol2}
31355    @dots{}
31356 @end cartouche
31357 @end group
31358 @end smallexample
31359
31360 @table @code
31361 @item LIBRARY @var{name}
31362 This section, which is optional, gives the name of the DLL.
31363
31364 @item DESCRIPTION @var{string}
31365 This section, which is optional, gives a description string that will be
31366 embedded in the import library.
31367
31368 @item EXPORTS
31369 This section gives the list of exported symbols (procedures, functions or
31370 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
31371 section of @file{API.def} looks like:
31372
31373 @smallexample
31374 @group
31375 @cartouche
31376 EXPORTS
31377    some_var
31378    get
31379 @end cartouche
31380 @end group
31381 @end smallexample
31382 @end table
31383
31384 @noindent
31385 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
31386 (@pxref{Windows Calling Conventions}) for a Stdcall
31387 calling convention function in the exported symbols list.
31388
31389 @noindent
31390 There can actually be other sections in a definition file, but these
31391 sections are not relevant to the discussion at hand.
31392
31393 @node GNAT-Style Import Library
31394 @subsubsection GNAT-Style Import Library
31395
31396 @noindent
31397 To create a static import library from @file{API.dll} with the GNAT tools
31398 you should proceed as follows:
31399
31400 @enumerate
31401 @item
31402 Create the definition file @file{API.def} (@pxref{The Definition File}).
31403 For that use the @code{dll2def} tool as follows:
31404
31405 @smallexample
31406 $ dll2def API.dll > API.def
31407 @end smallexample
31408
31409 @noindent
31410 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
31411 to standard output the list of entry points in the DLL. Note that if
31412 some routines in the DLL have the @code{Stdcall} convention
31413 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
31414 suffix then you'll have to edit @file{api.def} to add it, and specify
31415 @option{-k} to @command{gnatdll} when creating the import library.
31416
31417 @noindent
31418 Here are some hints to find the right @code{@@}@var{nn} suffix.
31419
31420 @enumerate
31421 @item
31422 If you have the Microsoft import library (.lib), it is possible to get
31423 the right symbols by using Microsoft @code{dumpbin} tool (see the
31424 corresponding Microsoft documentation for further details).
31425
31426 @smallexample
31427 $ dumpbin /exports api.lib
31428 @end smallexample
31429
31430 @item
31431 If you have a message about a missing symbol at link time the compiler
31432 tells you what symbol is expected. You just have to go back to the
31433 definition file and add the right suffix.
31434 @end enumerate
31435
31436 @item
31437 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
31438 (@pxref{Using gnatdll}) as follows:
31439
31440 @smallexample
31441 $ gnatdll -e API.def -d API.dll
31442 @end smallexample
31443
31444 @noindent
31445 @code{gnatdll} takes as input a definition file @file{API.def} and the
31446 name of the DLL containing the services listed in the definition file
31447 @file{API.dll}. The name of the static import library generated is
31448 computed from the name of the definition file as follows: if the
31449 definition file name is @var{xyz}@code{.def}, the import library name will
31450 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
31451 @option{-e} could have been removed because the name of the definition
31452 file (before the ``@code{.def}'' suffix) is the same as the name of the
31453 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
31454 @end enumerate
31455
31456 @node Microsoft-Style Import Library
31457 @subsubsection Microsoft-Style Import Library
31458
31459 @noindent
31460 With GNAT you can either use a GNAT-style or Microsoft-style import
31461 library. A Microsoft import library is needed only if you plan to make an
31462 Ada DLL available to applications developed with Microsoft
31463 tools (@pxref{Mixed-Language Programming on Windows}).
31464
31465 To create a Microsoft-style import library for @file{API.dll} you
31466 should proceed as follows:
31467
31468 @enumerate
31469 @item
31470 Create the definition file @file{API.def} from the DLL. For this use either
31471 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
31472 tool (see the corresponding Microsoft documentation for further details).
31473
31474 @item
31475 Build the actual import library using Microsoft's @code{lib} utility:
31476
31477 @smallexample
31478 $ lib -machine:IX86 -def:API.def -out:API.lib
31479 @end smallexample
31480
31481 @noindent
31482 If you use the above command the definition file @file{API.def} must
31483 contain a line giving the name of the DLL:
31484
31485 @smallexample
31486 LIBRARY      "API"
31487 @end smallexample
31488
31489 @noindent
31490 See the Microsoft documentation for further details about the usage of
31491 @code{lib}.
31492 @end enumerate
31493
31494 @node Building DLLs with GNAT
31495 @section Building DLLs with GNAT
31496 @cindex DLLs, building
31497
31498 @noindent
31499 This section explain how to build DLLs using the GNAT built-in DLL
31500 support. With the following procedure it is straight forward to build
31501 and use DLLs with GNAT.
31502
31503 @enumerate
31504
31505 @item building object files
31506
31507 The first step is to build all objects files that are to be included
31508 into the DLL. This is done by using the standard @command{gnatmake} tool.
31509
31510 @item building the DLL
31511
31512 To build the DLL you must use @command{gcc}'s @option{-shared}
31513 option. It is quite simple to use this method:
31514
31515 @smallexample
31516 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
31517 @end smallexample
31518
31519 It is important to note that in this case all symbols found in the
31520 object files are automatically exported. It is possible to restrict
31521 the set of symbols to export by passing to @command{gcc} a definition
31522 file, @pxref{The Definition File}. For example:
31523
31524 @smallexample
31525 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
31526 @end smallexample
31527
31528 If you use a definition file you must export the elaboration procedures
31529 for every package that required one. Elaboration procedures are named
31530 using the package name followed by "_E".
31531
31532 @item preparing DLL to be used
31533
31534 For the DLL to be used by client programs the bodies must be hidden
31535 from it and the .ali set with read-only attribute. This is very important
31536 otherwise GNAT will recompile all packages and will not actually use
31537 the code in the DLL. For example:
31538
31539 @smallexample
31540 $ mkdir apilib
31541 $ copy *.ads *.ali api.dll apilib
31542 $ attrib +R apilib\*.ali
31543 @end smallexample
31544
31545 @end enumerate
31546
31547 At this point it is possible to use the DLL by directly linking
31548 against it. Note that you must use the GNAT shared runtime when using
31549 GNAT shared libraries. This is achieved by using @option{-shared} binder's
31550 option.
31551
31552 @smallexample
31553 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
31554 @end smallexample
31555
31556 @node Building DLLs with GNAT Project files
31557 @section Building DLLs with GNAT Project files
31558 @cindex DLLs, building
31559
31560 @noindent
31561 There is nothing specific to Windows in the build process.
31562 @pxref{Library Projects}.
31563
31564 @noindent
31565 Due to a system limitation, it is not possible under Windows to create threads
31566 when inside the @code{DllMain} routine which is used for auto-initialization
31567 of shared libraries, so it is not possible to have library level tasks in SALs.
31568
31569 @node Building DLLs with gnatdll
31570 @section Building DLLs with gnatdll
31571 @cindex DLLs, building
31572
31573 @menu
31574 * Limitations When Using Ada DLLs from Ada::
31575 * Exporting Ada Entities::
31576 * Ada DLLs and Elaboration::
31577 * Ada DLLs and Finalization::
31578 * Creating a Spec for Ada DLLs::
31579 * Creating the Definition File::
31580 * Using gnatdll::
31581 @end menu
31582
31583 @noindent
31584 Note that it is preferred to use the built-in GNAT DLL support
31585 (@pxref{Building DLLs with GNAT}) or GNAT Project files
31586 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
31587
31588 This section explains how to build DLLs containing Ada code using
31589 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
31590 remainder of this section.
31591
31592 The steps required to build an Ada DLL that is to be used by Ada as well as
31593 non-Ada applications are as follows:
31594
31595 @enumerate
31596 @item
31597 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
31598 @code{Stdcall} calling convention to avoid any Ada name mangling for the
31599 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
31600 skip this step if you plan to use the Ada DLL only from Ada applications.
31601
31602 @item
31603 Your Ada code must export an initialization routine which calls the routine
31604 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
31605 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
31606 routine exported by the Ada DLL must be invoked by the clients of the DLL
31607 to initialize the DLL.
31608
31609 @item
31610 When useful, the DLL should also export a finalization routine which calls
31611 routine @code{adafinal} generated by @command{gnatbind} to perform the
31612 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
31613 The finalization routine exported by the Ada DLL must be invoked by the
31614 clients of the DLL when the DLL services are no further needed.
31615
31616 @item
31617 You must provide a spec for the services exported by the Ada DLL in each
31618 of the programming languages to which you plan to make the DLL available.
31619
31620 @item
31621 You must provide a definition file listing the exported entities
31622 (@pxref{The Definition File}).
31623
31624 @item
31625 Finally you must use @code{gnatdll} to produce the DLL and the import
31626 library (@pxref{Using gnatdll}).
31627 @end enumerate
31628
31629 @noindent
31630 Note that a relocatable DLL stripped using the @code{strip}
31631 binutils tool will not be relocatable anymore. To build a DLL without
31632 debug information pass @code{-largs -s} to @code{gnatdll}. This
31633 restriction does not apply to a DLL built using a Library Project.
31634 @pxref{Library Projects}.
31635
31636 @node Limitations When Using Ada DLLs from Ada
31637 @subsection Limitations When Using Ada DLLs from Ada
31638
31639 @noindent
31640 When using Ada DLLs from Ada applications there is a limitation users
31641 should be aware of. Because on Windows the GNAT run time is not in a DLL of
31642 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
31643 each Ada DLL includes the services of the GNAT run time that are necessary
31644 to the Ada code inside the DLL. As a result, when an Ada program uses an
31645 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
31646 one in the main program.
31647
31648 It is therefore not possible to exchange GNAT run-time objects between the
31649 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
31650 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
31651 types, etc.
31652
31653 It is completely safe to exchange plain elementary, array or record types,
31654 Windows object handles, etc.
31655
31656 @node Exporting Ada Entities
31657 @subsection Exporting Ada Entities
31658 @cindex Export table
31659
31660 @noindent
31661 Building a DLL is a way to encapsulate a set of services usable from any
31662 application. As a result, the Ada entities exported by a DLL should be
31663 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
31664 any Ada name mangling. As an example here is an Ada package
31665 @code{API}, spec and body, exporting two procedures, a function, and a
31666 variable:
31667
31668 @smallexample @c ada
31669 @group
31670 @cartouche
31671 with Interfaces.C; use Interfaces;
31672 package API is
31673    Count : C.int := 0;
31674    function Factorial (Val : C.int) return C.int;
31675
31676    procedure Initialize_API;
31677    procedure Finalize_API;
31678    --  Initialization & Finalization routines. More in the next section.
31679 private
31680    pragma Export (C, Initialize_API);
31681    pragma Export (C, Finalize_API);
31682    pragma Export (C, Count);
31683    pragma Export (C, Factorial);
31684 end API;
31685 @end cartouche
31686 @end group
31687 @end smallexample
31688
31689 @smallexample @c ada
31690 @group
31691 @cartouche
31692 package body API is
31693    function Factorial (Val : C.int) return C.int is
31694       Fact : C.int := 1;
31695    begin
31696       Count := Count + 1;
31697       for K in 1 .. Val loop
31698          Fact := Fact * K;
31699       end loop;
31700       return Fact;
31701    end Factorial;
31702
31703    procedure Initialize_API is
31704       procedure Adainit;
31705       pragma Import (C, Adainit);
31706    begin
31707       Adainit;
31708    end Initialize_API;
31709
31710    procedure Finalize_API is
31711       procedure Adafinal;
31712       pragma Import (C, Adafinal);
31713    begin
31714       Adafinal;
31715    end Finalize_API;
31716 end API;
31717 @end cartouche
31718 @end group
31719 @end smallexample
31720
31721 @noindent
31722 If the Ada DLL you are building will only be used by Ada applications
31723 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
31724 convention. As an example, the previous package could be written as
31725 follows:
31726
31727 @smallexample @c ada
31728 @group
31729 @cartouche
31730 package API is
31731    Count : Integer := 0;
31732    function Factorial (Val : Integer) return Integer;
31733
31734    procedure Initialize_API;
31735    procedure Finalize_API;
31736    --  Initialization and Finalization routines.
31737 end API;
31738 @end cartouche
31739 @end group
31740 @end smallexample
31741
31742 @smallexample @c ada
31743 @group
31744 @cartouche
31745 package body API is
31746    function Factorial (Val : Integer) return Integer is
31747       Fact : Integer := 1;
31748    begin
31749       Count := Count + 1;
31750       for K in 1 .. Val loop
31751          Fact := Fact * K;
31752       end loop;
31753       return Fact;
31754    end Factorial;
31755
31756    @dots{}
31757    --  The remainder of this package body is unchanged.
31758 end API;
31759 @end cartouche
31760 @end group
31761 @end smallexample
31762
31763 @noindent
31764 Note that if you do not export the Ada entities with a @code{C} or
31765 @code{Stdcall} convention you will have to provide the mangled Ada names
31766 in the definition file of the Ada DLL
31767 (@pxref{Creating the Definition File}).
31768
31769 @node Ada DLLs and Elaboration
31770 @subsection Ada DLLs and Elaboration
31771 @cindex DLLs and elaboration
31772
31773 @noindent
31774 The DLL that you are building contains your Ada code as well as all the
31775 routines in the Ada library that are needed by it. The first thing a
31776 user of your DLL must do is elaborate the Ada code
31777 (@pxref{Elaboration Order Handling in GNAT}).
31778
31779 To achieve this you must export an initialization routine
31780 (@code{Initialize_API} in the previous example), which must be invoked
31781 before using any of the DLL services. This elaboration routine must call
31782 the Ada elaboration routine @code{adainit} generated by the GNAT binder
31783 (@pxref{Binding with Non-Ada Main Programs}). See the body of
31784 @code{Initialize_Api} for an example. Note that the GNAT binder is
31785 automatically invoked during the DLL build process by the @code{gnatdll}
31786 tool (@pxref{Using gnatdll}).
31787
31788 When a DLL is loaded, Windows systematically invokes a routine called
31789 @code{DllMain}. It would therefore be possible to call @code{adainit}
31790 directly from @code{DllMain} without having to provide an explicit
31791 initialization routine. Unfortunately, it is not possible to call
31792 @code{adainit} from the @code{DllMain} if your program has library level
31793 tasks because access to the @code{DllMain} entry point is serialized by
31794 the system (that is, only a single thread can execute ``through'' it at a
31795 time), which means that the GNAT run time will deadlock waiting for the
31796 newly created task to complete its initialization.
31797
31798 @node Ada DLLs and Finalization
31799 @subsection Ada DLLs and Finalization
31800 @cindex DLLs and finalization
31801
31802 @noindent
31803 When the services of an Ada DLL are no longer needed, the client code should
31804 invoke the DLL finalization routine, if available. The DLL finalization
31805 routine is in charge of releasing all resources acquired by the DLL. In the
31806 case of the Ada code contained in the DLL, this is achieved by calling
31807 routine @code{adafinal} generated by the GNAT binder
31808 (@pxref{Binding with Non-Ada Main Programs}).
31809 See the body of @code{Finalize_Api} for an
31810 example. As already pointed out the GNAT binder is automatically invoked
31811 during the DLL build process by the @code{gnatdll} tool
31812 (@pxref{Using gnatdll}).
31813
31814 @node Creating a Spec for Ada DLLs
31815 @subsection Creating a Spec for Ada DLLs
31816
31817 @noindent
31818 To use the services exported by the Ada DLL from another programming
31819 language (e.g.@: C), you have to translate the specs of the exported Ada
31820 entities in that language. For instance in the case of @code{API.dll},
31821 the corresponding C header file could look like:
31822
31823 @smallexample
31824 @group
31825 @cartouche
31826 extern int *_imp__count;
31827 #define count (*_imp__count)
31828 int factorial (int);
31829 @end cartouche
31830 @end group
31831 @end smallexample
31832
31833 @noindent
31834 It is important to understand that when building an Ada DLL to be used by
31835 other Ada applications, you need two different specs for the packages
31836 contained in the DLL: one for building the DLL and the other for using
31837 the DLL. This is because the @code{DLL} calling convention is needed to
31838 use a variable defined in a DLL, but when building the DLL, the variable
31839 must have either the @code{Ada} or @code{C} calling convention. As an
31840 example consider a DLL comprising the following package @code{API}:
31841
31842 @smallexample @c ada
31843 @group
31844 @cartouche
31845 package API is
31846    Count : Integer := 0;
31847    @dots{}
31848    --  Remainder of the package omitted.
31849 end API;
31850 @end cartouche
31851 @end group
31852 @end smallexample
31853
31854 @noindent
31855 After producing a DLL containing package @code{API}, the spec that
31856 must be used to import @code{API.Count} from Ada code outside of the
31857 DLL is:
31858
31859 @smallexample @c ada
31860 @group
31861 @cartouche
31862 package API is
31863    Count : Integer;
31864    pragma Import (DLL, Count);
31865 end API;
31866 @end cartouche
31867 @end group
31868 @end smallexample
31869
31870 @node Creating the Definition File
31871 @subsection Creating the Definition File
31872
31873 @noindent
31874 The definition file is the last file needed to build the DLL. It lists
31875 the exported symbols. As an example, the definition file for a DLL
31876 containing only package @code{API} (where all the entities are exported
31877 with a @code{C} calling convention) is:
31878
31879 @smallexample
31880 @group
31881 @cartouche
31882 EXPORTS
31883     count
31884     factorial
31885     finalize_api
31886     initialize_api
31887 @end cartouche
31888 @end group
31889 @end smallexample
31890
31891 @noindent
31892 If the @code{C} calling convention is missing from package @code{API},
31893 then the definition file contains the mangled Ada names of the above
31894 entities, which in this case are:
31895
31896 @smallexample
31897 @group
31898 @cartouche
31899 EXPORTS
31900     api__count
31901     api__factorial
31902     api__finalize_api
31903     api__initialize_api
31904 @end cartouche
31905 @end group
31906 @end smallexample
31907
31908 @node Using gnatdll
31909 @subsection Using @code{gnatdll}
31910 @findex gnatdll
31911
31912 @menu
31913 * gnatdll Example::
31914 * gnatdll behind the Scenes::
31915 * Using dlltool::
31916 @end menu
31917
31918 @noindent
31919 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
31920 and non-Ada sources that make up your DLL have been compiled.
31921 @code{gnatdll} is actually in charge of two distinct tasks: build the
31922 static import library for the DLL and the actual DLL. The form of the
31923 @code{gnatdll} command is
31924
31925 @smallexample
31926 @cartouche
31927 $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
31928 @end cartouche
31929 @end smallexample
31930
31931 @noindent
31932 where @var{list-of-files} is a list of ALI and object files. The object
31933 file list must be the exact list of objects corresponding to the non-Ada
31934 sources whose services are to be included in the DLL. The ALI file list
31935 must be the exact list of ALI files for the corresponding Ada sources
31936 whose services are to be included in the DLL. If @var{list-of-files} is
31937 missing, only the static import library is generated.
31938
31939 @noindent
31940 You may specify any of the following switches to @code{gnatdll}:
31941
31942 @table @code
31943 @item -a@ovar{address}
31944 @cindex @option{-a} (@code{gnatdll})
31945 Build a non-relocatable DLL at @var{address}. If @var{address} is not
31946 specified the default address @var{0x11000000} will be used. By default,
31947 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
31948 advise the reader to build relocatable DLL.
31949
31950 @item -b @var{address}
31951 @cindex @option{-b} (@code{gnatdll})
31952 Set the relocatable DLL base address. By default the address is
31953 @code{0x11000000}.
31954
31955 @item -bargs @var{opts}
31956 @cindex @option{-bargs} (@code{gnatdll})
31957 Binder options. Pass @var{opts} to the binder.
31958
31959 @item -d @var{dllfile}
31960 @cindex @option{-d} (@code{gnatdll})
31961 @var{dllfile} is the name of the DLL. This switch must be present for
31962 @code{gnatdll} to do anything. The name of the generated import library is
31963 obtained algorithmically from @var{dllfile} as shown in the following
31964 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
31965 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
31966 by option @option{-e}) is obtained algorithmically from @var{dllfile}
31967 as shown in the following example:
31968 if @var{dllfile} is @code{xyz.dll}, the definition
31969 file used is @code{xyz.def}.
31970
31971 @item -e @var{deffile}
31972 @cindex @option{-e} (@code{gnatdll})
31973 @var{deffile} is the name of the definition file.
31974
31975 @item -g
31976 @cindex @option{-g} (@code{gnatdll})
31977 Generate debugging information. This information is stored in the object
31978 file and copied from there to the final DLL file by the linker,
31979 where it can be read by the debugger. You must use the
31980 @option{-g} switch if you plan on using the debugger or the symbolic
31981 stack traceback.
31982
31983 @item -h
31984 @cindex @option{-h} (@code{gnatdll})
31985 Help mode. Displays @code{gnatdll} switch usage information.
31986
31987 @item -Idir
31988 @cindex @option{-I} (@code{gnatdll})
31989 Direct @code{gnatdll} to search the @var{dir} directory for source and
31990 object files needed to build the DLL.
31991 (@pxref{Search Paths and the Run-Time Library (RTL)}).
31992
31993 @item -k
31994 @cindex @option{-k} (@code{gnatdll})
31995 Removes the @code{@@}@var{nn} suffix from the import library's exported
31996 names, but keeps them for the link names. You must specify this
31997 option if you want to use a @code{Stdcall} function in a DLL for which
31998 the @code{@@}@var{nn} suffix has been removed. This is the case for most
31999 of the Windows NT DLL for example. This option has no effect when
32000 @option{-n} option is specified.
32001
32002 @item -l @var{file}
32003 @cindex @option{-l} (@code{gnatdll})
32004 The list of ALI and object files used to build the DLL are listed in
32005 @var{file}, instead of being given in the command line. Each line in
32006 @var{file} contains the name of an ALI or object file.
32007
32008 @item -n
32009 @cindex @option{-n} (@code{gnatdll})
32010 No Import. Do not create the import library.
32011
32012 @item -q
32013 @cindex @option{-q} (@code{gnatdll})
32014 Quiet mode. Do not display unnecessary messages.
32015
32016 @item -v
32017 @cindex @option{-v} (@code{gnatdll})
32018 Verbose mode. Display extra information.
32019
32020 @item -largs @var{opts}
32021 @cindex @option{-largs} (@code{gnatdll})
32022 Linker options. Pass @var{opts} to the linker.
32023 @end table
32024
32025 @node gnatdll Example
32026 @subsubsection @code{gnatdll} Example
32027
32028 @noindent
32029 As an example the command to build a relocatable DLL from @file{api.adb}
32030 once @file{api.adb} has been compiled and @file{api.def} created is
32031
32032 @smallexample
32033 $ gnatdll -d api.dll api.ali
32034 @end smallexample
32035
32036 @noindent
32037 The above command creates two files: @file{libapi.dll.a} (the import
32038 library) and @file{api.dll} (the actual DLL). If you want to create
32039 only the DLL, just type:
32040
32041 @smallexample
32042 $ gnatdll -d api.dll -n api.ali
32043 @end smallexample
32044
32045 @noindent
32046 Alternatively if you want to create just the import library, type:
32047
32048 @smallexample
32049 $ gnatdll -d api.dll
32050 @end smallexample
32051
32052 @node gnatdll behind the Scenes
32053 @subsubsection @code{gnatdll} behind the Scenes
32054
32055 @noindent
32056 This section details the steps involved in creating a DLL. @code{gnatdll}
32057 does these steps for you. Unless you are interested in understanding what
32058 goes on behind the scenes, you should skip this section.
32059
32060 We use the previous example of a DLL containing the Ada package @code{API},
32061 to illustrate the steps necessary to build a DLL. The starting point is a
32062 set of objects that will make up the DLL and the corresponding ALI
32063 files. In the case of this example this means that @file{api.o} and
32064 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
32065 the following:
32066
32067 @enumerate
32068 @item
32069 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
32070 the information necessary to generate relocation information for the
32071 DLL.
32072
32073 @smallexample
32074 @group
32075 $ gnatbind -n api
32076 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
32077 @end group
32078 @end smallexample
32079
32080 @noindent
32081 In addition to the base file, the @command{gnatlink} command generates an
32082 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
32083 asks @command{gnatlink} to generate the routines @code{DllMain} and
32084 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
32085 is loaded into memory.
32086
32087 @item
32088 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
32089 export table (@file{api.exp}). The export table contains the relocation
32090 information in a form which can be used during the final link to ensure
32091 that the Windows loader is able to place the DLL anywhere in memory.
32092
32093 @smallexample
32094 @group
32095 $ dlltool --dllname api.dll --def api.def --base-file api.base \
32096           --output-exp api.exp
32097 @end group
32098 @end smallexample
32099
32100 @item
32101 @code{gnatdll} builds the base file using the new export table. Note that
32102 @command{gnatbind} must be called once again since the binder generated file
32103 has been deleted during the previous call to @command{gnatlink}.
32104
32105 @smallexample
32106 @group
32107 $ gnatbind -n api
32108 $ gnatlink api -o api.jnk api.exp -mdll
32109       -Wl,--base-file,api.base
32110 @end group
32111 @end smallexample
32112
32113 @item
32114 @code{gnatdll} builds the new export table using the new base file and
32115 generates the DLL import library @file{libAPI.dll.a}.
32116
32117 @smallexample
32118 @group
32119 $ dlltool --dllname api.dll --def api.def --base-file api.base \
32120           --output-exp api.exp --output-lib libAPI.a
32121 @end group
32122 @end smallexample
32123
32124 @item
32125 Finally @code{gnatdll} builds the relocatable DLL using the final export
32126 table.
32127
32128 @smallexample
32129 @group
32130 $ gnatbind -n api
32131 $ gnatlink api api.exp -o api.dll -mdll
32132 @end group
32133 @end smallexample
32134 @end enumerate
32135
32136 @node Using dlltool
32137 @subsubsection Using @code{dlltool}
32138
32139 @noindent
32140 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
32141 DLLs and static import libraries. This section summarizes the most
32142 common @code{dlltool} switches. The form of the @code{dlltool} command
32143 is
32144
32145 @smallexample
32146 $ dlltool @ovar{switches}
32147 @end smallexample
32148
32149 @noindent
32150 @code{dlltool} switches include:
32151
32152 @table @option
32153 @item --base-file @var{basefile}
32154 @cindex @option{--base-file} (@command{dlltool})
32155 Read the base file @var{basefile} generated by the linker. This switch
32156 is used to create a relocatable DLL.
32157
32158 @item --def @var{deffile}
32159 @cindex @option{--def} (@command{dlltool})
32160 Read the definition file.
32161
32162 @item --dllname @var{name}
32163 @cindex @option{--dllname} (@command{dlltool})
32164 Gives the name of the DLL. This switch is used to embed the name of the
32165 DLL in the static import library generated by @code{dlltool} with switch
32166 @option{--output-lib}.
32167
32168 @item -k
32169 @cindex @option{-k} (@command{dlltool})
32170 Kill @code{@@}@var{nn} from exported names
32171 (@pxref{Windows Calling Conventions}
32172 for a discussion about @code{Stdcall}-style symbols.
32173
32174 @item --help
32175 @cindex @option{--help} (@command{dlltool})
32176 Prints the @code{dlltool} switches with a concise description.
32177
32178 @item --output-exp @var{exportfile}
32179 @cindex @option{--output-exp} (@command{dlltool})
32180 Generate an export file @var{exportfile}. The export file contains the
32181 export table (list of symbols in the DLL) and is used to create the DLL.
32182
32183 @item --output-lib @var{libfile}
32184 @cindex @option{--output-lib} (@command{dlltool})
32185 Generate a static import library @var{libfile}.
32186
32187 @item -v
32188 @cindex @option{-v} (@command{dlltool})
32189 Verbose mode.
32190
32191 @item --as @var{assembler-name}
32192 @cindex @option{--as} (@command{dlltool})
32193 Use @var{assembler-name} as the assembler. The default is @code{as}.
32194 @end table
32195
32196 @node GNAT and Windows Resources
32197 @section GNAT and Windows Resources
32198 @cindex Resources, windows
32199
32200 @menu
32201 * Building Resources::
32202 * Compiling Resources::
32203 * Using Resources::
32204 @end menu
32205
32206 @noindent
32207 Resources are an easy way to add Windows specific objects to your
32208 application. The objects that can be added as resources include:
32209
32210 @itemize @bullet
32211 @item
32212 menus
32213
32214 @item
32215 accelerators
32216
32217 @item
32218 dialog boxes
32219
32220 @item
32221 string tables
32222
32223 @item
32224 bitmaps
32225
32226 @item
32227 cursors
32228
32229 @item
32230 icons
32231
32232 @item
32233 fonts
32234 @end itemize
32235
32236 @noindent
32237 This section explains how to build, compile and use resources.
32238
32239 @node Building Resources
32240 @subsection Building Resources
32241 @cindex Resources, building
32242
32243 @noindent
32244 A resource file is an ASCII file. By convention resource files have an
32245 @file{.rc} extension.
32246 The easiest way to build a resource file is to use Microsoft tools
32247 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
32248 @code{dlgedit.exe} to build dialogs.
32249 It is always possible to build an @file{.rc} file yourself by writing a
32250 resource script.
32251
32252 It is not our objective to explain how to write a resource file. A
32253 complete description of the resource script language can be found in the
32254 Microsoft documentation.
32255
32256 @node Compiling Resources
32257 @subsection Compiling Resources
32258 @findex rc
32259 @findex windres
32260 @cindex Resources, compiling
32261
32262 @noindent
32263 This section describes how to build a GNAT-compatible (COFF) object file
32264 containing the resources. This is done using the Resource Compiler
32265 @code{windres} as follows:
32266
32267 @smallexample
32268 $ windres -i myres.rc -o myres.o
32269 @end smallexample
32270
32271 @noindent
32272 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
32273 file. You can specify an alternate preprocessor (usually named
32274 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
32275 parameter. A list of all possible options may be obtained by entering
32276 the command @code{windres} @option{--help}.
32277
32278 It is also possible to use the Microsoft resource compiler @code{rc.exe}
32279 to produce a @file{.res} file (binary resource file). See the
32280 corresponding Microsoft documentation for further details. In this case
32281 you need to use @code{windres} to translate the @file{.res} file to a
32282 GNAT-compatible object file as follows:
32283
32284 @smallexample
32285 $ windres -i myres.res -o myres.o
32286 @end smallexample
32287
32288 @node Using Resources
32289 @subsection Using Resources
32290 @cindex Resources, using
32291
32292 @noindent
32293 To include the resource file in your program just add the
32294 GNAT-compatible object file for the resource(s) to the linker
32295 arguments. With @command{gnatmake} this is done by using the @option{-largs}
32296 option:
32297
32298 @smallexample
32299 $ gnatmake myprog -largs myres.o
32300 @end smallexample
32301
32302 @node Debugging a DLL
32303 @section Debugging a DLL
32304 @cindex DLL debugging
32305
32306 @menu
32307 * Program and DLL Both Built with GCC/GNAT::
32308 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
32309 @end menu
32310
32311 @noindent
32312 Debugging a DLL is similar to debugging a standard program. But
32313 we have to deal with two different executable parts: the DLL and the
32314 program that uses it. We have the following four possibilities:
32315
32316 @enumerate 1
32317 @item
32318 The program and the DLL are built with @code{GCC/GNAT}.
32319 @item
32320 The program is built with foreign tools and the DLL is built with
32321 @code{GCC/GNAT}.
32322 @item
32323 The program is built with @code{GCC/GNAT} and the DLL is built with
32324 foreign tools.
32325 @item
32326 @end enumerate
32327
32328 @noindent
32329 In this section we address only cases one and two above.
32330 There is no point in trying to debug
32331 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
32332 information in it. To do so you must use a debugger compatible with the
32333 tools suite used to build the DLL.
32334
32335 @node Program and DLL Both Built with GCC/GNAT
32336 @subsection Program and DLL Both Built with GCC/GNAT
32337
32338 @noindent
32339 This is the simplest case. Both the DLL and the program have @code{GDB}
32340 compatible debugging information. It is then possible to break anywhere in
32341 the process. Let's suppose here that the main procedure is named
32342 @code{ada_main} and that in the DLL there is an entry point named
32343 @code{ada_dll}.
32344
32345 @noindent
32346 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
32347 program must have been built with the debugging information (see GNAT -g
32348 switch). Here are the step-by-step instructions for debugging it:
32349
32350 @enumerate 1
32351 @item Launch @code{GDB} on the main program.
32352
32353 @smallexample
32354 $ gdb -nw ada_main
32355 @end smallexample
32356
32357 @item Start the program and stop at the beginning of the main procedure
32358
32359 @smallexample
32360 (gdb) start
32361 @end smallexample
32362
32363 @noindent
32364 This step is required to be able to set a breakpoint inside the DLL. As long
32365 as the program is not run, the DLL is not loaded. This has the
32366 consequence that the DLL debugging information is also not loaded, so it is not
32367 possible to set a breakpoint in the DLL.
32368
32369 @item Set a breakpoint inside the DLL
32370
32371 @smallexample
32372 (gdb) break ada_dll
32373 (gdb) cont
32374 @end smallexample
32375
32376 @end enumerate
32377
32378 @noindent
32379 At this stage a breakpoint is set inside the DLL. From there on
32380 you can use the standard approach to debug the whole program
32381 (@pxref{Running and Debugging Ada Programs}).
32382
32383 @ignore
32384 @c This used to work, probably because the DLLs were non-relocatable
32385 @c keep this section around until the problem is sorted out.
32386
32387 To break on the @code{DllMain} routine it is not possible to follow
32388 the procedure above. At the time the program stop on @code{ada_main}
32389 the @code{DllMain} routine as already been called. Either you can use
32390 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
32391
32392 @enumerate 1
32393 @item Launch @code{GDB} on the main program.
32394
32395 @smallexample
32396 $ gdb ada_main
32397 @end smallexample
32398
32399 @item Load DLL symbols
32400
32401 @smallexample
32402 (gdb) add-sym api.dll
32403 @end smallexample
32404
32405 @item Set a breakpoint inside the DLL
32406
32407 @smallexample
32408 (gdb) break ada_dll.adb:45
32409 @end smallexample
32410
32411 Note that at this point it is not possible to break using the routine symbol
32412 directly as the program is not yet running. The solution is to break
32413 on the proper line (break in @file{ada_dll.adb} line 45).
32414
32415 @item Start the program
32416
32417 @smallexample
32418 (gdb) run
32419 @end smallexample
32420
32421 @end enumerate
32422 @end ignore
32423
32424 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
32425 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
32426
32427 @menu
32428 * Debugging the DLL Directly::
32429 * Attaching to a Running Process::
32430 @end menu
32431
32432 @noindent
32433 In this case things are slightly more complex because it is not possible to
32434 start the main program and then break at the beginning to load the DLL and the
32435 associated DLL debugging information. It is not possible to break at the
32436 beginning of the program because there is no @code{GDB} debugging information,
32437 and therefore there is no direct way of getting initial control. This
32438 section addresses this issue by describing some methods that can be used
32439 to break somewhere in the DLL to debug it.
32440
32441 @noindent
32442 First suppose that the main procedure is named @code{main} (this is for
32443 example some C code built with Microsoft Visual C) and that there is a
32444 DLL named @code{test.dll} containing an Ada entry point named
32445 @code{ada_dll}.
32446
32447 @noindent
32448 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
32449 been built with debugging information (see GNAT -g option).
32450
32451 @node Debugging the DLL Directly
32452 @subsubsection Debugging the DLL Directly
32453
32454 @enumerate 1
32455 @item
32456 Find out the executable starting address
32457
32458 @smallexample
32459 $ objdump --file-header main.exe
32460 @end smallexample
32461
32462 The starting address is reported on the last line. For example:
32463
32464 @smallexample
32465 main.exe:     file format pei-i386
32466 architecture: i386, flags 0x0000010a:
32467 EXEC_P, HAS_DEBUG, D_PAGED
32468 start address 0x00401010
32469 @end smallexample
32470
32471 @item
32472 Launch the debugger on the executable.
32473
32474 @smallexample
32475 $ gdb main.exe
32476 @end smallexample
32477
32478 @item
32479 Set a breakpoint at the starting address, and launch the program.
32480
32481 @smallexample
32482 $ (gdb) break *0x00401010
32483 $ (gdb) run
32484 @end smallexample
32485
32486 The program will stop at the given address.
32487
32488 @item
32489 Set a breakpoint on a DLL subroutine.
32490
32491 @smallexample
32492 (gdb) break ada_dll.adb:45
32493 @end smallexample
32494
32495 Or if you want to break using a symbol on the DLL, you need first to
32496 select the Ada language (language used by the DLL).
32497
32498 @smallexample
32499 (gdb) set language ada
32500 (gdb) break ada_dll
32501 @end smallexample
32502
32503 @item
32504 Continue the program.
32505
32506 @smallexample
32507 (gdb) cont
32508 @end smallexample
32509
32510 @noindent
32511 This will run the program until it reaches the breakpoint that has been
32512 set. From that point you can use the standard way to debug a program
32513 as described in (@pxref{Running and Debugging Ada Programs}).
32514
32515 @end enumerate
32516
32517 @noindent
32518 It is also possible to debug the DLL by attaching to a running process.
32519
32520 @node Attaching to a Running Process
32521 @subsubsection Attaching to a Running Process
32522 @cindex DLL debugging, attach to process
32523
32524 @noindent
32525 With @code{GDB} it is always possible to debug a running process by
32526 attaching to it. It is possible to debug a DLL this way. The limitation
32527 of this approach is that the DLL must run long enough to perform the
32528 attach operation. It may be useful for instance to insert a time wasting
32529 loop in the code of the DLL to meet this criterion.
32530
32531 @enumerate 1
32532
32533 @item Launch the main program @file{main.exe}.
32534
32535 @smallexample
32536 $ main
32537 @end smallexample
32538
32539 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
32540 that the process PID for @file{main.exe} is 208.
32541
32542 @item Launch gdb.
32543
32544 @smallexample
32545 $ gdb
32546 @end smallexample
32547
32548 @item Attach to the running process to be debugged.
32549
32550 @smallexample
32551 (gdb) attach 208
32552 @end smallexample
32553
32554 @item Load the process debugging information.
32555
32556 @smallexample
32557 (gdb) symbol-file main.exe
32558 @end smallexample
32559
32560 @item Break somewhere in the DLL.
32561
32562 @smallexample
32563 (gdb) break ada_dll
32564 @end smallexample
32565
32566 @item Continue process execution.
32567
32568 @smallexample
32569 (gdb) cont
32570 @end smallexample
32571
32572 @end enumerate
32573
32574 @noindent
32575 This last step will resume the process execution, and stop at
32576 the breakpoint we have set. From there you can use the standard
32577 approach to debug a program as described in
32578 (@pxref{Running and Debugging Ada Programs}).
32579
32580 @node Setting Stack Size from gnatlink
32581 @section Setting Stack Size from @command{gnatlink}
32582
32583 @noindent
32584 It is possible to specify the program stack size at link time. On modern
32585 versions of Windows, starting with XP, this is mostly useful to set the size of
32586 the main stack (environment task). The other task stacks are set with pragma
32587 Storage_Size or with the @command{gnatbind -d} command.
32588
32589 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
32590 reserve size of individual tasks, the link-time stack size applies to all
32591 tasks, and pragma Storage_Size has no effect.
32592 In particular, Stack Overflow checks are made against this
32593 link-time specified size.
32594
32595 This setting can be done with
32596 @command{gnatlink} using either:
32597
32598 @itemize @bullet
32599
32600 @item using @option{-Xlinker} linker option
32601
32602 @smallexample
32603 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
32604 @end smallexample
32605
32606 This sets the stack reserve size to 0x10000 bytes and the stack commit
32607 size to 0x1000 bytes.
32608
32609 @item using @option{-Wl} linker option
32610
32611 @smallexample
32612 $ gnatlink hello -Wl,--stack=0x1000000
32613 @end smallexample
32614
32615 This sets the stack reserve size to 0x1000000 bytes. Note that with
32616 @option{-Wl} option it is not possible to set the stack commit size
32617 because the coma is a separator for this option.
32618
32619 @end itemize
32620
32621 @node Setting Heap Size from gnatlink
32622 @section Setting Heap Size from @command{gnatlink}
32623
32624 @noindent
32625 Under Windows systems, it is possible to specify the program heap size from
32626 @command{gnatlink} using either:
32627
32628 @itemize @bullet
32629
32630 @item using @option{-Xlinker} linker option
32631
32632 @smallexample
32633 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
32634 @end smallexample
32635
32636 This sets the heap reserve size to 0x10000 bytes and the heap commit
32637 size to 0x1000 bytes.
32638
32639 @item using @option{-Wl} linker option
32640
32641 @smallexample
32642 $ gnatlink hello -Wl,--heap=0x1000000
32643 @end smallexample
32644
32645 This sets the heap reserve size to 0x1000000 bytes. Note that with
32646 @option{-Wl} option it is not possible to set the heap commit size
32647 because the coma is a separator for this option.
32648
32649 @end itemize
32650
32651 @end ifset
32652
32653 @c **********************************
32654 @c * GNU Free Documentation License *
32655 @c **********************************
32656 @include fdl.texi
32657 @c GNU Free Documentation License
32658
32659 @node Index,,GNU Free Documentation License, Top
32660 @unnumbered Index
32661
32662 @printindex cp
32663
32664 @contents
32665 @c Put table of contents at end, otherwise it precedes the "title page" in
32666 @c the .txt version
32667 @c Edit the pdf file to move the contents to the beginning, after the title
32668 @c page
32669
32670 @bye