OSDN Git Service

2009-04-10 Sergey Rybin <rybin@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 @ifclear vms
3886 @item -gnatD
3887 @cindex @option{-gnatD[nn]} (@command{gcc})
3888 @end ifclear
3889 @ifset vms
3890 @item /XDEBUG /LXDEBUG=nnn
3891 @end ifset
3892 Create expanded source files for source level debugging. This switch
3893 also suppress generation of cross-reference information
3894 (see @option{-gnatx}).
3895
3896 @item -gnatec=@var{path}
3897 @cindex @option{-gnatec} (@command{gcc})
3898 Specify a configuration pragma file
3899 @ifclear vms
3900 (the equal sign is optional)
3901 @end ifclear
3902 (@pxref{The Configuration Pragmas Files}).
3903
3904 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
3905 @cindex @option{-gnateD} (@command{gcc})
3906 Defines a symbol, associated with @var{value}, for preprocessing.
3907 (@pxref{Integrated Preprocessing}).
3908
3909 @item -gnatef
3910 @cindex @option{-gnatef} (@command{gcc})
3911 Display full source path name in brief error messages.
3912
3913 @item -gnateG
3914 @cindex @option{-gnateG} (@command{gcc})
3915 Save result of preprocessing in a text file.
3916
3917 @item -gnatem=@var{path}
3918 @cindex @option{-gnatem} (@command{gcc})
3919 Specify a mapping file
3920 @ifclear vms
3921 (the equal sign is optional)
3922 @end ifclear
3923 (@pxref{Units to Sources Mapping Files}).
3924
3925 @item -gnatep=@var{file}
3926 @cindex @option{-gnatep} (@command{gcc})
3927 Specify a preprocessing data file
3928 @ifclear vms
3929 (the equal sign is optional)
3930 @end ifclear
3931 (@pxref{Integrated Preprocessing}).
3932
3933 @item -gnatE
3934 @cindex @option{-gnatE} (@command{gcc})
3935 Full dynamic elaboration checks.
3936
3937 @item -gnatf
3938 @cindex @option{-gnatf} (@command{gcc})
3939 Full errors. Multiple errors per line, all undefined references, do not
3940 attempt to suppress cascaded errors.
3941
3942 @item -gnatF
3943 @cindex @option{-gnatF} (@command{gcc})
3944 Externals names are folded to all uppercase.
3945
3946 @item ^-gnatg^/GNAT_INTERNAL^
3947 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
3948 Internal GNAT implementation mode. This should not be used for
3949 applications programs, it is intended only for use by the compiler
3950 and its run-time library. For documentation, see the GNAT sources.
3951 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
3952 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
3953 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
3954 so that all standard warnings and all standard style options are turned on.
3955 All warnings and style error messages are treated as errors.
3956
3957 @ifclear vms
3958 @item -gnatG=nn
3959 @cindex @option{-gnatG[nn]} (@command{gcc})
3960 @end ifclear
3961 @ifset vms
3962 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
3963 @end ifset
3964 List generated expanded code in source form.
3965
3966 @item ^-gnath^/HELP^
3967 @cindex @option{^-gnath^/HELP^} (@command{gcc})
3968 Output usage information. The output is written to @file{stdout}.
3969
3970 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3971 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
3972 Identifier character set
3973 @ifclear vms
3974 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3975 @end ifclear
3976 For details of the possible selections for @var{c},
3977 see @ref{Character Set Control}.
3978
3979 @item ^-gnatI^/IGNORE_REP_CLAUSES^
3980 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
3981 Ignore representation clauses. When this switch is used, all
3982 representation clauses are treated as comments. This is useful
3983 when initially porting code where you want to ignore rep clause
3984 problems, and also for compiling foreign code (particularly
3985 for use with ASIS).
3986
3987 @item -gnatjnn
3988 @cindex @option{-gnatjnn} (@command{gcc})
3989 Reformat error messages to fit on nn character lines
3990
3991 @item -gnatk=@var{n}
3992 @cindex @option{-gnatk} (@command{gcc})
3993 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3994
3995 @item -gnatl
3996 @cindex @option{-gnatl} (@command{gcc})
3997 Output full source listing with embedded error messages.
3998
3999 @item -gnatL
4000 @cindex @option{-gnatL} (@command{gcc})
4001 Used in conjunction with -gnatG or -gnatD to intersperse original
4002 source lines (as comment lines with line numbers) in the expanded
4003 source output.
4004
4005 @item -gnatm=@var{n}
4006 @cindex @option{-gnatm} (@command{gcc})
4007 Limit number of detected error or warning messages to @var{n}
4008 where @var{n} is in the range 1..999999. The default setting if
4009 no switch is given is 9999. If the number of warnings reaches this
4010 limit, then a message is output and further warnings are suppressed,
4011 but the compilation is continued. If the number of error messages
4012 reaches this limit, then a message is output and the compilation
4013 is abandoned. The equal sign here is optional. A value of zero
4014 means that no limit applies.
4015
4016 @item -gnatn
4017 @cindex @option{-gnatn} (@command{gcc})
4018 Activate inlining for subprograms for which
4019 pragma @code{inline} is specified. This inlining is performed
4020 by the GCC back-end.
4021
4022 @item -gnatN
4023 @cindex @option{-gnatN} (@command{gcc})
4024 Activate front end inlining for subprograms for which
4025 pragma @code{Inline} is specified. This inlining is performed
4026 by the front end and will be visible in the
4027 @option{-gnatG} output.
4028
4029 When using a gcc-based back end (in practice this means using any version
4030 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4031 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4032 Historically front end inlining was more extensive than the gcc back end
4033 inlining, but that is no longer the case.
4034
4035 @item -gnato
4036 @cindex @option{-gnato} (@command{gcc})
4037 Enable numeric overflow checking (which is not normally enabled by
4038 default). Note that division by zero is a separate check that is not
4039 controlled by this switch (division by zero checking is on by default).
4040
4041 @item -gnatp
4042 @cindex @option{-gnatp} (@command{gcc})
4043 Suppress all checks. See @ref{Run-Time Checks} for details.
4044
4045 @item -gnatP
4046 @cindex @option{-gnatP} (@command{gcc})
4047 Enable polling. This is required on some systems (notably Windows NT) to
4048 obtain asynchronous abort and asynchronous transfer of control capability.
4049 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4050 details.
4051
4052 @item -gnatq
4053 @cindex @option{-gnatq} (@command{gcc})
4054 Don't quit. Try semantics, even if parse errors.
4055
4056 @item -gnatQ
4057 @cindex @option{-gnatQ} (@command{gcc})
4058 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4059
4060 @item -gnatr
4061 @cindex @option{-gnatr} (@command{gcc})
4062 Treat pragma Restrictions as Restriction_Warnings.
4063
4064 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4065 @cindex @option{-gnatR} (@command{gcc})
4066 Output representation information for declared types and objects.
4067
4068 @item -gnats
4069 @cindex @option{-gnats} (@command{gcc})
4070 Syntax check only.
4071
4072 @item -gnatS
4073 @cindex @option{-gnatS} (@command{gcc})
4074 Print package Standard.
4075
4076 @item -gnatt
4077 @cindex @option{-gnatt} (@command{gcc})
4078 Generate tree output file.
4079
4080 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4081 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4082 All compiler tables start at @var{nnn} times usual starting size.
4083
4084 @item -gnatu
4085 @cindex @option{-gnatu} (@command{gcc})
4086 List units for this compilation.
4087
4088 @item -gnatU
4089 @cindex @option{-gnatU} (@command{gcc})
4090 Tag all error messages with the unique string ``error:''
4091
4092 @item -gnatv
4093 @cindex @option{-gnatv} (@command{gcc})
4094 Verbose mode. Full error output with source lines to @file{stdout}.
4095
4096 @item -gnatV
4097 @cindex @option{-gnatV} (@command{gcc})
4098 Control level of validity checking. See separate section describing
4099 this feature.
4100
4101 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4102 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4103 Warning mode where
4104 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4105 the exact warnings that
4106 are enabled or disabled (@pxref{Warning Message Control}).
4107
4108 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4109 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4110 Wide character encoding method
4111 @ifclear vms
4112 (@var{e}=n/h/u/s/e/8).
4113 @end ifclear
4114 @ifset vms
4115 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4116 @end ifset
4117
4118 @item -gnatx
4119 @cindex @option{-gnatx} (@command{gcc})
4120 Suppress generation of cross-reference information.
4121
4122 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4123 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4124 Enable built-in style checks (@pxref{Style Checking}).
4125
4126 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4127 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4128 Distribution stub generation and compilation
4129 @ifclear vms
4130 (@var{m}=r/c for receiver/caller stubs).
4131 @end ifclear
4132 @ifset vms
4133 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4134 to be generated and compiled).
4135 @end ifset
4136
4137 @item ^-I^/SEARCH=^@var{dir}
4138 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4139 @cindex RTL
4140 Direct GNAT to search the @var{dir} directory for source files needed by
4141 the current compilation
4142 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4143
4144 @item ^-I-^/NOCURRENT_DIRECTORY^
4145 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4146 @cindex RTL
4147 Except for the source file named in the command line, do not look for source
4148 files in the directory containing the source file named in the command line
4149 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4150
4151 @ifclear vms
4152 @item -mbig-switch
4153 @cindex @option{-mbig-switch} (@command{gcc})
4154 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4155 This standard gcc switch causes the compiler to use larger offsets in its
4156 jump table representation for @code{case} statements.
4157 This may result in less efficient code, but is sometimes necessary
4158 (for example on HP-UX targets)
4159 @cindex HP-UX and @option{-mbig-switch} option
4160 in order to compile large and/or nested @code{case} statements.
4161
4162 @item -o @var{file}
4163 @cindex @option{-o} (@command{gcc})
4164 This switch is used in @command{gcc} to redirect the generated object file
4165 and its associated ALI file. Beware of this switch with GNAT, because it may
4166 cause the object file and ALI file to have different names which in turn
4167 may confuse the binder and the linker.
4168 @end ifclear
4169
4170 @item -nostdinc
4171 @cindex @option{-nostdinc} (@command{gcc})
4172 Inhibit the search of the default location for the GNAT Run Time
4173 Library (RTL) source files.
4174
4175 @item -nostdlib
4176 @cindex @option{-nostdlib} (@command{gcc})
4177 Inhibit the search of the default location for the GNAT Run Time
4178 Library (RTL) ALI files.
4179
4180 @ifclear vms
4181 @item -O@ovar{n}
4182 @cindex @option{-O} (@command{gcc})
4183 @var{n} controls the optimization level.
4184
4185 @table @asis
4186 @item n = 0
4187 No optimization, the default setting if no @option{-O} appears
4188
4189 @item n = 1
4190 Normal optimization, the default if you specify @option{-O} without
4191 an operand. A good compromise between code quality and compilation
4192 time.
4193
4194 @item n = 2
4195 Extensive optimization, may improve execution time, possibly at the cost of
4196 substantially increased compilation time.
4197
4198 @item n = 3
4199 Same as @option{-O2}, and also includes inline expansion for small subprograms
4200 in the same unit.
4201
4202 @item n = s
4203 Optimize space usage
4204 @end table
4205
4206 @noindent
4207 See also @ref{Optimization Levels}.
4208 @end ifclear
4209
4210 @ifset vms
4211 @item  /NOOPTIMIZE
4212 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4213 Equivalent to @option{/OPTIMIZE=NONE}.
4214 This is the default behavior in the absence of an @option{/OPTIMIZE}
4215 qualifier.
4216
4217 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4218 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4219 Selects the level of optimization for your program. The supported
4220 keywords are as follows:
4221 @table @code
4222 @item   ALL
4223 Perform most optimizations, including those that
4224 are expensive.
4225 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4226 without keyword options.
4227
4228 @item   NONE
4229 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4230
4231 @item SOME
4232 Perform some optimizations, but omit ones that are costly.
4233
4234 @item   DEVELOPMENT
4235 Same as @code{SOME}.
4236
4237 @item INLINING
4238 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4239 automatic inlining of small subprograms within a unit
4240
4241 @item   UNROLL_LOOPS
4242 Try to unroll loops. This keyword may be specified together with
4243 any keyword above other than @code{NONE}. Loop unrolling
4244 usually, but not always, improves the performance of programs.
4245
4246 @item SPACE
4247 Optimize space usage
4248 @end table
4249
4250 @noindent
4251 See also @ref{Optimization Levels}.
4252 @end ifset
4253
4254 @ifclear vms
4255 @item -pass-exit-codes
4256 @cindex @option{-pass-exit-codes} (@command{gcc})
4257 Catch exit codes from the compiler and use the most meaningful as
4258 exit status.
4259 @end ifclear
4260
4261 @item --RTS=@var{rts-path}
4262 @cindex @option{--RTS} (@command{gcc})
4263 Specifies the default location of the runtime library. Same meaning as the
4264 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4265
4266 @item ^-S^/ASM^
4267 @cindex @option{^-S^/ASM^} (@command{gcc})
4268 ^Used in place of @option{-c} to^Used to^
4269 cause the assembler source file to be
4270 generated, using @file{^.s^.S^} as the extension,
4271 instead of the object file.
4272 This may be useful if you need to examine the generated assembly code.
4273
4274 @item ^-fverbose-asm^/VERBOSE_ASM^
4275 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4276 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4277 to cause the generated assembly code file to be annotated with variable
4278 names, making it significantly easier to follow.
4279
4280 @item ^-v^/VERBOSE^
4281 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4282 Show commands generated by the @command{gcc} driver. Normally used only for
4283 debugging purposes or if you need to be sure what version of the
4284 compiler you are executing.
4285
4286 @ifclear vms
4287 @item -V @var{ver}
4288 @cindex @option{-V} (@command{gcc})
4289 Execute @var{ver} version of the compiler. This is the @command{gcc}
4290 version, not the GNAT version.
4291 @end ifclear
4292
4293 @item ^-w^/NO_BACK_END_WARNINGS^
4294 @cindex @option{-w} (@command{gcc})
4295 Turn off warnings generated by the back end of the compiler. Use of
4296 this switch also causes the default for front end warnings to be set
4297 to suppress (as though @option{-gnatws} had appeared at the start of
4298 the options).
4299
4300 @end table
4301
4302 @ifclear vms
4303 @c Combining qualifiers does not work on VMS
4304 You may combine a sequence of GNAT switches into a single switch. For
4305 example, the combined switch
4306
4307 @cindex Combining GNAT switches
4308 @smallexample
4309 -gnatofi3
4310 @end smallexample
4311
4312 @noindent
4313 is equivalent to specifying the following sequence of switches:
4314
4315 @smallexample
4316 -gnato -gnatf -gnati3
4317 @end smallexample
4318 @end ifclear
4319
4320 @noindent
4321 The following restrictions apply to the combination of switches
4322 in this manner:
4323
4324 @itemize @bullet
4325 @item
4326 The switch @option{-gnatc} if combined with other switches must come
4327 first in the string.
4328
4329 @item
4330 The switch @option{-gnats} if combined with other switches must come
4331 first in the string.
4332
4333 @item
4334 The switches
4335 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4336 may not be combined with any other switches.
4337
4338 @ifclear vms
4339 @item
4340 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4341 switch), then all further characters in the switch are interpreted
4342 as style modifiers (see description of @option{-gnaty}).
4343
4344 @item
4345 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4346 switch), then all further characters in the switch are interpreted
4347 as debug flags (see description of @option{-gnatd}).
4348
4349 @item
4350 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4351 switch), then all further characters in the switch are interpreted
4352 as warning mode modifiers (see description of @option{-gnatw}).
4353
4354 @item
4355 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4356 switch), then all further characters in the switch are interpreted
4357 as validity checking options (see description of @option{-gnatV}).
4358 @end ifclear
4359 @end itemize
4360
4361 @node Output and Error Message Control
4362 @subsection Output and Error Message Control
4363 @findex stderr
4364
4365 @noindent
4366 The standard default format for error messages is called ``brief format''.
4367 Brief format messages are written to @file{stderr} (the standard error
4368 file) and have the following form:
4369
4370 @smallexample
4371 e.adb:3:04: Incorrect spelling of keyword "function"
4372 e.adb:4:20: ";" should be "is"
4373 @end smallexample
4374
4375 @noindent
4376 The first integer after the file name is the line number in the file,
4377 and the second integer is the column number within the line.
4378 @ifclear vms
4379 @code{GPS} can parse the error messages
4380 and point to the referenced character.
4381 @end ifclear
4382 The following switches provide control over the error message
4383 format:
4384
4385 @table @option
4386 @c !sort!
4387 @item -gnatv
4388 @cindex @option{-gnatv} (@command{gcc})
4389 @findex stdout
4390 @ifclear vms
4391 The v stands for verbose.
4392 @end ifclear
4393 The effect of this setting is to write long-format error
4394 messages to @file{stdout} (the standard output file.
4395 The same program compiled with the
4396 @option{-gnatv} switch would generate:
4397
4398 @smallexample
4399 @cartouche
4400 3. funcion X (Q : Integer)
4401    |
4402 >>> Incorrect spelling of keyword "function"
4403 4. return Integer;
4404                  |
4405 >>> ";" should be "is"
4406 @end cartouche
4407 @end smallexample
4408
4409 @noindent
4410 The vertical bar indicates the location of the error, and the @samp{>>>}
4411 prefix can be used to search for error messages. When this switch is
4412 used the only source lines output are those with errors.
4413
4414 @item -gnatl
4415 @cindex @option{-gnatl} (@command{gcc})
4416 @ifclear vms
4417 The @code{l} stands for list.
4418 @end ifclear
4419 This switch causes a full listing of
4420 the file to be generated. In the case where a body is
4421 compiled, the corresponding spec is also listed, along
4422 with any subunits. Typical output from compiling a package
4423 body @file{p.adb} might look like:
4424
4425 @smallexample @c ada
4426 @cartouche
4427  Compiling: p.adb
4428
4429      1. package body p is
4430      2.    procedure a;
4431      3.    procedure a is separate;
4432      4. begin
4433      5.    null
4434                |
4435         >>> missing ";"
4436
4437      6. end;
4438
4439 Compiling: p.ads
4440
4441      1. package p is
4442      2.    pragma Elaborate_Body
4443                                 |
4444         >>> missing ";"
4445
4446      3. end p;
4447
4448 Compiling: p-a.adb
4449
4450      1. separate p
4451                 |
4452         >>> missing "("
4453
4454      2. procedure a is
4455      3. begin
4456      4.    null
4457                |
4458         >>> missing ";"
4459
4460      5. end;
4461 @end cartouche
4462 @end smallexample
4463
4464 @noindent
4465 @findex stderr
4466 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4467 standard output is redirected, a brief summary is written to
4468 @file{stderr} (standard error) giving the number of error messages and
4469 warning messages generated.
4470
4471 @item -^gnatl^OUTPUT_FILE^=file
4472 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4473 This has the same effect as @option{-gnatl} except that the output is
4474 written to a file instead of to standard output. If the given name
4475 @file{fname} does not start with a period, then it is the full name
4476 of the file to be written. If @file{fname} is an extension, it is
4477 appended to the name of the file being compiled. For example, if
4478 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4479 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4480
4481 @item -gnatU
4482 @cindex @option{-gnatU} (@command{gcc})
4483 This switch forces all error messages to be preceded by the unique
4484 string ``error:''. This means that error messages take a few more
4485 characters in space, but allows easy searching for and identification
4486 of error messages.
4487
4488 @item -gnatb
4489 @cindex @option{-gnatb} (@command{gcc})
4490 @ifclear vms
4491 The @code{b} stands for brief.
4492 @end ifclear
4493 This switch causes GNAT to generate the
4494 brief format error messages to @file{stderr} (the standard error
4495 file) as well as the verbose
4496 format message or full listing (which as usual is written to
4497 @file{stdout} (the standard output file).
4498
4499 @item -gnatm=@var{n}
4500 @cindex @option{-gnatm} (@command{gcc})
4501 @ifclear vms
4502 The @code{m} stands for maximum.
4503 @end ifclear
4504 @var{n} is a decimal integer in the
4505 range of 1 to 999999 and limits the number of error or warning
4506 messages to be generated. For example, using
4507 @option{-gnatm2} might yield
4508
4509 @smallexample
4510 e.adb:3:04: Incorrect spelling of keyword "function"
4511 e.adb:5:35: missing ".."
4512 fatal error: maximum number of errors detected
4513 compilation abandoned
4514 @end smallexample
4515
4516 @noindent
4517 The default setting if
4518 no switch is given is 9999. If the number of warnings reaches this
4519 limit, then a message is output and further warnings are suppressed,
4520 but the compilation is continued. If the number of error messages
4521 reaches this limit, then a message is output and the compilation
4522 is abandoned. A value of zero means that no limit applies.
4523
4524 @noindent
4525 Note that the equal sign is optional, so the switches
4526 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4527
4528 @item -gnatf
4529 @cindex @option{-gnatf} (@command{gcc})
4530 @cindex Error messages, suppressing
4531 @ifclear vms
4532 The @code{f} stands for full.
4533 @end ifclear
4534 Normally, the compiler suppresses error messages that are likely to be
4535 redundant. This switch causes all error
4536 messages to be generated. In particular, in the case of
4537 references to undefined variables. If a given variable is referenced
4538 several times, the normal format of messages is
4539 @smallexample
4540 e.adb:7:07: "V" is undefined (more references follow)
4541 @end smallexample
4542
4543 @noindent
4544 where the parenthetical comment warns that there are additional
4545 references to the variable @code{V}. Compiling the same program with the
4546 @option{-gnatf} switch yields
4547
4548 @smallexample
4549 e.adb:7:07: "V" is undefined
4550 e.adb:8:07: "V" is undefined
4551 e.adb:8:12: "V" is undefined
4552 e.adb:8:16: "V" is undefined
4553 e.adb:9:07: "V" is undefined
4554 e.adb:9:12: "V" is undefined
4555 @end smallexample
4556
4557 @noindent
4558 The @option{-gnatf} switch also generates additional information for
4559 some error messages.  Some examples are:
4560
4561 @itemize @bullet
4562 @item
4563 Full details on entities not available in high integrity mode
4564 @item
4565 Details on possibly non-portable unchecked conversion
4566 @item
4567 List possible interpretations for ambiguous calls
4568 @item
4569 Additional details on incorrect parameters
4570 @end itemize
4571
4572 @item -gnatjnn
4573 @cindex @option{-gnatjnn} (@command{gcc})
4574 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4575 with continuation lines are treated as though the continuation lines were
4576 separate messages (and so a warning with two continuation lines counts as
4577 three warnings, and is listed as three separate messages).
4578
4579 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4580 messages are output in a different manner. A message and all its continuation
4581 lines are treated as a unit, and count as only one warning or message in the
4582 statistics totals. Furthermore, the message is reformatted so that no line
4583 is longer than nn characters.
4584
4585 @item -gnatq
4586 @cindex @option{-gnatq} (@command{gcc})
4587 @ifclear vms
4588 The @code{q} stands for quit (really ``don't quit'').
4589 @end ifclear
4590 In normal operation mode, the compiler first parses the program and
4591 determines if there are any syntax errors. If there are, appropriate
4592 error messages are generated and compilation is immediately terminated.
4593 This switch tells
4594 GNAT to continue with semantic analysis even if syntax errors have been
4595 found. This may enable the detection of more errors in a single run. On
4596 the other hand, the semantic analyzer is more likely to encounter some
4597 internal fatal error when given a syntactically invalid tree.
4598
4599 @item -gnatQ
4600 @cindex @option{-gnatQ} (@command{gcc})
4601 In normal operation mode, the @file{ALI} file is not generated if any
4602 illegalities are detected in the program. The use of @option{-gnatQ} forces
4603 generation of the @file{ALI} file. This file is marked as being in
4604 error, so it cannot be used for binding purposes, but it does contain
4605 reasonably complete cross-reference information, and thus may be useful
4606 for use by tools (e.g., semantic browsing tools or integrated development
4607 environments) that are driven from the @file{ALI} file. This switch
4608 implies @option{-gnatq}, since the semantic phase must be run to get a
4609 meaningful ALI file.
4610
4611 In addition, if @option{-gnatt} is also specified, then the tree file is
4612 generated even if there are illegalities. It may be useful in this case
4613 to also specify @option{-gnatq} to ensure that full semantic processing
4614 occurs. The resulting tree file can be processed by ASIS, for the purpose
4615 of providing partial information about illegal units, but if the error
4616 causes the tree to be badly malformed, then ASIS may crash during the
4617 analysis.
4618
4619 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4620 being in error, @command{gnatmake} will attempt to recompile the source when it
4621 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4622
4623 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4624 since ALI files are never generated if @option{-gnats} is set.
4625
4626 @end table
4627
4628 @node Warning Message Control
4629 @subsection Warning Message Control
4630 @cindex Warning messages
4631 @noindent
4632 In addition to error messages, which correspond to illegalities as defined
4633 in the Ada Reference Manual, the compiler detects two kinds of warning
4634 situations.
4635
4636 First, the compiler considers some constructs suspicious and generates a
4637 warning message to alert you to a possible error. Second, if the
4638 compiler detects a situation that is sure to raise an exception at
4639 run time, it generates a warning message. The following shows an example
4640 of warning messages:
4641 @smallexample
4642 e.adb:4:24: warning: creation of object may raise Storage_Error
4643 e.adb:10:17: warning: static value out of range
4644 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4645 @end smallexample
4646
4647 @noindent
4648 GNAT considers a large number of situations as appropriate
4649 for the generation of warning messages. As always, warnings are not
4650 definite indications of errors. For example, if you do an out-of-range
4651 assignment with the deliberate intention of raising a
4652 @code{Constraint_Error} exception, then the warning that may be
4653 issued does not indicate an error. Some of the situations for which GNAT
4654 issues warnings (at least some of the time) are given in the following
4655 list. This list is not complete, and new warnings are often added to
4656 subsequent versions of GNAT. The list is intended to give a general idea
4657 of the kinds of warnings that are generated.
4658
4659 @itemize @bullet
4660 @item
4661 Possible infinitely recursive calls
4662
4663 @item
4664 Out-of-range values being assigned
4665
4666 @item
4667 Possible order of elaboration problems
4668
4669 @item
4670 Assertions (pragma Assert) that are sure to fail
4671
4672 @item
4673 Unreachable code
4674
4675 @item
4676 Address clauses with possibly unaligned values, or where an attempt is
4677 made to overlay a smaller variable with a larger one.
4678
4679 @item
4680 Fixed-point type declarations with a null range
4681
4682 @item
4683 Direct_IO or Sequential_IO instantiated with a type that has access values
4684
4685 @item
4686 Variables that are never assigned a value
4687
4688 @item
4689 Variables that are referenced before being initialized
4690
4691 @item
4692 Task entries with no corresponding @code{accept} statement
4693
4694 @item
4695 Duplicate accepts for the same task entry in a @code{select}
4696
4697 @item
4698 Objects that take too much storage
4699
4700 @item
4701 Unchecked conversion between types of differing sizes
4702
4703 @item
4704 Missing @code{return} statement along some execution path in a function
4705
4706 @item
4707 Incorrect (unrecognized) pragmas
4708
4709 @item
4710 Incorrect external names
4711
4712 @item
4713 Allocation from empty storage pool
4714
4715 @item
4716 Potentially blocking operation in protected type
4717
4718 @item
4719 Suspicious parenthesization of expressions
4720
4721 @item
4722 Mismatching bounds in an aggregate
4723
4724 @item
4725 Attempt to return local value by reference
4726
4727 @item
4728 Premature instantiation of a generic body
4729
4730 @item
4731 Attempt to pack aliased components
4732
4733 @item
4734 Out of bounds array subscripts
4735
4736 @item
4737 Wrong length on string assignment
4738
4739 @item
4740 Violations of style rules if style checking is enabled
4741
4742 @item
4743 Unused @code{with} clauses
4744
4745 @item
4746 @code{Bit_Order} usage that does not have any effect
4747
4748 @item
4749 @code{Standard.Duration} used to resolve universal fixed expression
4750
4751 @item
4752 Dereference of possibly null value
4753
4754 @item
4755 Declaration that is likely to cause storage error
4756
4757 @item
4758 Internal GNAT unit @code{with}'ed by application unit
4759
4760 @item
4761 Values known to be out of range at compile time
4762
4763 @item
4764 Unreferenced labels and variables
4765
4766 @item
4767 Address overlays that could clobber memory
4768
4769 @item
4770 Unexpected initialization when address clause present
4771
4772 @item
4773 Bad alignment for address clause
4774
4775 @item
4776 Useless type conversions
4777
4778 @item
4779 Redundant assignment statements and other redundant constructs
4780
4781 @item
4782 Useless exception handlers
4783
4784 @item
4785 Accidental hiding of name by child unit
4786
4787 @item
4788 Access before elaboration detected at compile time
4789
4790 @item
4791 A range in a @code{for} loop that is known to be null or might be null
4792
4793 @end itemize
4794
4795 @noindent
4796 The following section lists compiler switches that are available
4797 to control the handling of warning messages. It is also possible
4798 to exercise much finer control over what warnings are issued and
4799 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
4800 gnat_rm, GNAT Reference manual}.
4801
4802 @table @option
4803 @c !sort!
4804 @item -gnatwa
4805 @emph{Activate all optional errors.}
4806 @cindex @option{-gnatwa} (@command{gcc})
4807 This switch activates most optional warning messages, see remaining list
4808 in this section for details on optional warning messages that can be
4809 individually controlled.  The warnings that are not turned on by this
4810 switch are
4811 @option{-gnatwd} (implicit dereferencing),
4812 @option{-gnatwh} (hiding),
4813 @option{-gnatwl} (elaboration warnings),
4814 @option{-gnatw.o} (warn on values set by out parameters ignored)
4815 and @option{-gnatwt} (tracking of deleted conditional code).
4816 All other optional warnings are turned on.
4817
4818 @item -gnatwA
4819 @emph{Suppress all optional errors.}
4820 @cindex @option{-gnatwA} (@command{gcc})
4821 This switch suppresses all optional warning messages, see remaining list
4822 in this section for details on optional warning messages that can be
4823 individually controlled.
4824
4825 @item -gnatw.a
4826 @emph{Activate warnings on failing assertions.}
4827 @cindex @option{-gnatw.a} (@command{gcc})
4828 @cindex Assert failures
4829 This switch activates warnings for assertions where the compiler can tell at
4830 compile time that the assertion will fail. Note that this warning is given
4831 even if assertions are disabled. The default is that such warnings are
4832 generated.
4833
4834 @item -gnatw.A
4835 @emph{Suppress warnings on failing assertions.}
4836 @cindex @option{-gnatw.A} (@command{gcc})
4837 @cindex Assert failures
4838 This switch suppresses warnings for assertions where the compiler can tell at
4839 compile time that the assertion will fail.
4840
4841 @item -gnatwb
4842 @emph{Activate warnings on bad fixed values.}
4843 @cindex @option{-gnatwb} (@command{gcc})
4844 @cindex Bad fixed values
4845 @cindex Fixed-point Small value
4846 @cindex Small value
4847 This switch activates warnings for static fixed-point expressions whose
4848 value is not an exact multiple of Small. Such values are implementation
4849 dependent, since an implementation is free to choose either of the multiples
4850 that surround the value. GNAT always chooses the closer one, but this is not
4851 required behavior, and it is better to specify a value that is an exact
4852 multiple, ensuring predictable execution. The default is that such warnings
4853 are not generated.
4854
4855 @item -gnatwB
4856 @emph{Suppress warnings on bad fixed values.}
4857 @cindex @option{-gnatwB} (@command{gcc})
4858 This switch suppresses warnings for static fixed-point expressions whose
4859 value is not an exact multiple of Small.
4860
4861 @item -gnatw.b
4862 @emph{Activate warnings on biased representation.}
4863 @cindex @option{-gnatw.b} (@command{gcc})
4864 @cindex Biased representation
4865 This switch activates warnings when a size clause, value size clause, component
4866 clause, or component size clause forces the use of biased representation for an
4867 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
4868 to represent 10/11). The default is that such warnings are generated.
4869
4870 @item -gnatw.B
4871 @emph{Suppress warnings on biased representation.}
4872 @cindex @option{-gnatwB} (@command{gcc})
4873 This switch suppresses warnings for representation clauses that force the use
4874 of biased representation.
4875
4876 @item -gnatwc
4877 @emph{Activate warnings on conditionals.}
4878 @cindex @option{-gnatwc} (@command{gcc})
4879 @cindex Conditionals, constant
4880 This switch activates warnings for conditional expressions used in
4881 tests that are known to be True or False at compile time. The default
4882 is that such warnings are not generated.
4883 Note that this warning does
4884 not get issued for the use of boolean variables or constants whose
4885 values are known at compile time, since this is a standard technique
4886 for conditional compilation in Ada, and this would generate too many
4887 false positive warnings.
4888
4889 This warning option also activates a special test for comparisons using
4890 the operators ``>='' and`` <=''.
4891 If the compiler can tell that only the equality condition is possible,
4892 then it will warn that the ``>'' or ``<'' part of the test
4893 is useless and that the operator could be replaced by ``=''.
4894 An example would be comparing a @code{Natural} variable <= 0.
4895
4896 This warning option also generates warnings if
4897 one or both tests is optimized away in a membership test for integer
4898 values if the result can be determined at compile time. Range tests on
4899 enumeration types are not included, since it is common for such tests
4900 to include an end point.
4901
4902 This warning can also be turned on using @option{-gnatwa}.
4903
4904 @item -gnatwC
4905 @emph{Suppress warnings on conditionals.}
4906 @cindex @option{-gnatwC} (@command{gcc})
4907 This switch suppresses warnings for conditional expressions used in
4908 tests that are known to be True or False at compile time.
4909
4910 @item -gnatw.c
4911 @emph{Activate warnings on missing component clauses.}
4912 @cindex @option{-gnatw.c} (@command{gcc})
4913 @cindex Component clause, missing
4914 This switch activates warnings for record components where a record
4915 representation clause is present and has component clauses for the
4916 majority, but not all, of the components. A warning is given for each
4917 component for which no component clause is present.
4918
4919 This warning can also be turned on using @option{-gnatwa}.
4920
4921 @item -gnatw.C
4922 @emph{Suppress warnings on missing component clauses.}
4923 @cindex @option{-gnatwC} (@command{gcc})
4924 This switch suppresses warnings for record components that are
4925 missing a component clause in the situation described above.
4926
4927 @item -gnatwd
4928 @emph{Activate warnings on implicit dereferencing.}
4929 @cindex @option{-gnatwd} (@command{gcc})
4930 If this switch is set, then the use of a prefix of an access type
4931 in an indexed component, slice, or selected component without an
4932 explicit @code{.all} will generate a warning. With this warning
4933 enabled, access checks occur only at points where an explicit
4934 @code{.all} appears in the source code (assuming no warnings are
4935 generated as a result of this switch). The default is that such
4936 warnings are not generated.
4937 Note that @option{-gnatwa} does not affect the setting of
4938 this warning option.
4939
4940 @item -gnatwD
4941 @emph{Suppress warnings on implicit dereferencing.}
4942 @cindex @option{-gnatwD} (@command{gcc})
4943 @cindex Implicit dereferencing
4944 @cindex Dereferencing, implicit
4945 This switch suppresses warnings for implicit dereferences in
4946 indexed components, slices, and selected components.
4947
4948 @item -gnatwe
4949 @emph{Treat warnings as errors.}
4950 @cindex @option{-gnatwe} (@command{gcc})
4951 @cindex Warnings, treat as error
4952 This switch causes warning messages to be treated as errors.
4953 The warning string still appears, but the warning messages are counted
4954 as errors, and prevent the generation of an object file.
4955
4956 @item -gnatw.e
4957 @emph{Activate every optional warning}
4958 @cindex @option{-gnatw.e} (@command{gcc})
4959 @cindex Warnings, activate every optional warning
4960 This switch activates all optional warnings, including those which
4961 are not activated by @code{-gnatwa}.
4962
4963 @item -gnatwf
4964 @emph{Activate warnings on unreferenced formals.}
4965 @cindex @option{-gnatwf} (@command{gcc})
4966 @cindex Formals, unreferenced
4967 This switch causes a warning to be generated if a formal parameter
4968 is not referenced in the body of the subprogram. This warning can
4969 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
4970 default is that these warnings are not generated.
4971
4972 @item -gnatwF
4973 @emph{Suppress warnings on unreferenced formals.}
4974 @cindex @option{-gnatwF} (@command{gcc})
4975 This switch suppresses warnings for unreferenced formal
4976 parameters. Note that the
4977 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4978 effect of warning on unreferenced entities other than subprogram
4979 formals.
4980
4981 @item -gnatwg
4982 @emph{Activate warnings on unrecognized pragmas.}
4983 @cindex @option{-gnatwg} (@command{gcc})
4984 @cindex Pragmas, unrecognized
4985 This switch causes a warning to be generated if an unrecognized
4986 pragma is encountered. Apart from issuing this warning, the
4987 pragma is ignored and has no effect. This warning can
4988 also be turned on using @option{-gnatwa}. The default
4989 is that such warnings are issued (satisfying the Ada Reference
4990 Manual requirement that such warnings appear).
4991
4992 @item -gnatwG
4993 @emph{Suppress warnings on unrecognized pragmas.}
4994 @cindex @option{-gnatwG} (@command{gcc})
4995 This switch suppresses warnings for unrecognized pragmas.
4996
4997 @item -gnatwh
4998 @emph{Activate warnings on hiding.}
4999 @cindex @option{-gnatwh} (@command{gcc})
5000 @cindex Hiding of Declarations
5001 This switch activates warnings on hiding declarations.
5002 A declaration is considered hiding
5003 if it is for a non-overloadable entity, and it declares an entity with the
5004 same name as some other entity that is directly or use-visible. The default
5005 is that such warnings are not generated.
5006 Note that @option{-gnatwa} does not affect the setting of this warning option.
5007
5008 @item -gnatwH
5009 @emph{Suppress warnings on hiding.}
5010 @cindex @option{-gnatwH} (@command{gcc})
5011 This switch suppresses warnings on hiding declarations.
5012
5013 @item -gnatwi
5014 @emph{Activate warnings on implementation units.}
5015 @cindex @option{-gnatwi} (@command{gcc})
5016 This switch activates warnings for a @code{with} of an internal GNAT
5017 implementation unit, defined as any unit from the @code{Ada},
5018 @code{Interfaces}, @code{GNAT},
5019 ^^@code{DEC},^ or @code{System}
5020 hierarchies that is not
5021 documented in either the Ada Reference Manual or the GNAT
5022 Programmer's Reference Manual. Such units are intended only
5023 for internal implementation purposes and should not be @code{with}'ed
5024 by user programs. The default is that such warnings are generated
5025 This warning can also be turned on using @option{-gnatwa}.
5026
5027 @item -gnatwI
5028 @emph{Disable warnings on implementation units.}
5029 @cindex @option{-gnatwI} (@command{gcc})
5030 This switch disables warnings for a @code{with} of an internal GNAT
5031 implementation unit.
5032
5033 @item -gnatwj
5034 @emph{Activate warnings on obsolescent features (Annex J).}
5035 @cindex @option{-gnatwj} (@command{gcc})
5036 @cindex Features, obsolescent
5037 @cindex Obsolescent features
5038 If this warning option is activated, then warnings are generated for
5039 calls to subprograms marked with @code{pragma Obsolescent} and
5040 for use of features in Annex J of the Ada Reference Manual. In the
5041 case of Annex J, not all features are flagged. In particular use
5042 of the renamed packages (like @code{Text_IO}) and use of package
5043 @code{ASCII} are not flagged, since these are very common and
5044 would generate many annoying positive warnings. The default is that
5045 such warnings are not generated. This warning is also turned on by
5046 the use of @option{-gnatwa}.
5047
5048 In addition to the above cases, warnings are also generated for
5049 GNAT features that have been provided in past versions but which
5050 have been superseded (typically by features in the new Ada standard).
5051 For example, @code{pragma Ravenscar} will be flagged since its
5052 function is replaced by @code{pragma Profile(Ravenscar)}.
5053
5054 Note that this warning option functions differently from the
5055 restriction @code{No_Obsolescent_Features} in two respects.
5056 First, the restriction applies only to annex J features.
5057 Second, the restriction does flag uses of package @code{ASCII}.
5058
5059 @item -gnatwJ
5060 @emph{Suppress warnings on obsolescent features (Annex J).}
5061 @cindex @option{-gnatwJ} (@command{gcc})
5062 This switch disables warnings on use of obsolescent features.
5063
5064 @item -gnatwk
5065 @emph{Activate warnings on variables that could be constants.}
5066 @cindex @option{-gnatwk} (@command{gcc})
5067 This switch activates warnings for variables that are initialized but
5068 never modified, and then could be declared constants. The default is that
5069 such warnings are not given.
5070 This warning can also be turned on using @option{-gnatwa}.
5071
5072 @item -gnatwK
5073 @emph{Suppress warnings on variables that could be constants.}
5074 @cindex @option{-gnatwK} (@command{gcc})
5075 This switch disables warnings on variables that could be declared constants.
5076
5077 @item -gnatwl
5078 @emph{Activate warnings for elaboration pragmas.}
5079 @cindex @option{-gnatwl} (@command{gcc})
5080 @cindex Elaboration, warnings
5081 This switch activates warnings on missing
5082 @code{Elaborate_All} and @code{Elaborate} pragmas.
5083 See the section in this guide on elaboration checking for details on
5084 when such pragmas should be used. In dynamic elaboration mode, this switch
5085 generations warnings about the need to add elaboration pragmas. Note however,
5086 that if you blindly follow these warnings, and add @code{Elaborate_All}
5087 warnings wherever they are recommended, you basically end up with the
5088 equivalent of the static elaboration model, which may not be what you want for
5089 legacy code for which the static model does not work.
5090
5091 For the static model, the messages generated are labeled "info:" (for
5092 information messages). They are not warnings to add elaboration pragmas,
5093 merely informational messages showing what implicit elaboration pragmas
5094 have been added, for use in analyzing elaboration circularity problems.
5095
5096 Warnings are also generated if you
5097 are using the static mode of elaboration, and a @code{pragma Elaborate}
5098 is encountered. The default is that such warnings
5099 are not generated.
5100 This warning is not automatically turned on by the use of @option{-gnatwa}.
5101
5102 @item -gnatwL
5103 @emph{Suppress warnings for elaboration pragmas.}
5104 @cindex @option{-gnatwL} (@command{gcc})
5105 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5106 See the section in this guide on elaboration checking for details on
5107 when such pragmas should be used.
5108
5109 @item -gnatwm
5110 @emph{Activate warnings on modified but unreferenced variables.}
5111 @cindex @option{-gnatwm} (@command{gcc})
5112 This switch activates warnings for variables that are assigned (using
5113 an initialization value or with one or more assignment statements) but
5114 whose value is never read. The warning is suppressed for volatile
5115 variables and also for variables that are renamings of other variables
5116 or for which an address clause is given.
5117 This warning can also be turned on using @option{-gnatwa}.
5118 The default is that these warnings are not given.
5119
5120 @item -gnatwM
5121 @emph{Disable warnings on modified but unreferenced variables.}
5122 @cindex @option{-gnatwM} (@command{gcc})
5123 This switch disables warnings for variables that are assigned or
5124 initialized, but never read.
5125
5126 @item -gnatwn
5127 @emph{Set normal warnings mode.}
5128 @cindex @option{-gnatwn} (@command{gcc})
5129 This switch sets normal warning mode, in which enabled warnings are
5130 issued and treated as warnings rather than errors. This is the default
5131 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5132 an explicit @option{-gnatws} or
5133 @option{-gnatwe}. It also cancels the effect of the
5134 implicit @option{-gnatwe} that is activated by the
5135 use of @option{-gnatg}.
5136
5137 @item -gnatwo
5138 @emph{Activate warnings on address clause overlays.}
5139 @cindex @option{-gnatwo} (@command{gcc})
5140 @cindex Address Clauses, warnings
5141 This switch activates warnings for possibly unintended initialization
5142 effects of defining address clauses that cause one variable to overlap
5143 another. The default is that such warnings are generated.
5144 This warning can also be turned on using @option{-gnatwa}.
5145
5146 @item -gnatwO
5147 @emph{Suppress warnings on address clause overlays.}
5148 @cindex @option{-gnatwO} (@command{gcc})
5149 This switch suppresses warnings on possibly unintended initialization
5150 effects of defining address clauses that cause one variable to overlap
5151 another.
5152
5153 @item -gnatw.o
5154 @emph{Activate warnings on modified but unreferenced out parameters.}
5155 @cindex @option{-gnatw.o} (@command{gcc})
5156 This switch activates warnings for variables that are modified by using
5157 them as actuals for a call to a procedure with an out mode formal, where
5158 the resulting assigned value is never read. It is applicable in the case
5159 where there is more than one out mode formal. If there is only one out
5160 mode formal, the warning is issued by default (controlled by -gnatwu).
5161 The warning is suppressed for volatile
5162 variables and also for variables that are renamings of other variables
5163 or for which an address clause is given.
5164 The default is that these warnings are not given. Note that this warning
5165 is not included in -gnatwa, it must be activated explicitly.
5166
5167 @item -gnatw.O
5168 @emph{Disable warnings on modified but unreferenced out parameters.}
5169 @cindex @option{-gnatw.O} (@command{gcc})
5170 This switch suppresses warnings for variables that are modified by using
5171 them as actuals for a call to a procedure with an out mode formal, where
5172 the resulting assigned value is never read.
5173
5174 @item -gnatwp
5175 @emph{Activate warnings on ineffective pragma Inlines.}
5176 @cindex @option{-gnatwp} (@command{gcc})
5177 @cindex Inlining, warnings
5178 This switch activates warnings for failure of front end inlining
5179 (activated by @option{-gnatN}) to inline a particular call. There are
5180 many reasons for not being able to inline a call, including most
5181 commonly that the call is too complex to inline. The default is
5182 that such warnings are not given.
5183 This warning can also be turned on using @option{-gnatwa}.
5184 Warnings on ineffective inlining by the gcc back-end can be activated
5185 separately, using the gcc switch -Winline.
5186
5187 @item -gnatwP
5188 @emph{Suppress warnings on ineffective pragma Inlines.}
5189 @cindex @option{-gnatwP} (@command{gcc})
5190 This switch suppresses warnings on ineffective pragma Inlines. If the
5191 inlining mechanism cannot inline a call, it will simply ignore the
5192 request silently.
5193
5194 @item -gnatw.p
5195 @emph{Activate warnings on parameter ordering.}
5196 @cindex @option{-gnatw.p} (@command{gcc})
5197 @cindex Parameter order, warnings
5198 This switch activates warnings for cases of suspicious parameter
5199 ordering when the list of arguments are all simple identifiers that
5200 match the names of the formals, but are in a different order. The
5201 warning is suppressed if any use of named parameter notation is used,
5202 so this is the appropriate way to suppress a false positive (and
5203 serves to emphasize that the "misordering" is deliberate). The
5204 default is
5205 that such warnings are not given.
5206 This warning can also be turned on using @option{-gnatwa}.
5207
5208 @item -gnatw.P
5209 @emph{Suppress warnings on parameter ordering.}
5210 @cindex @option{-gnatw.P} (@command{gcc})
5211 This switch suppresses warnings on cases of suspicious parameter
5212 ordering.
5213
5214 @item -gnatwq
5215 @emph{Activate warnings on questionable missing parentheses.}
5216 @cindex @option{-gnatwq} (@command{gcc})
5217 @cindex Parentheses, warnings
5218 This switch activates warnings for cases where parentheses are not used and
5219 the result is potential ambiguity from a readers point of view. For example
5220 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5221 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5222 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5223 follow the rule of always parenthesizing to make the association clear, and
5224 this warning switch warns if such parentheses are not present. The default
5225 is that these warnings are given.
5226 This warning can also be turned on using @option{-gnatwa}.
5227
5228 @item -gnatwQ
5229 @emph{Suppress warnings on questionable missing parentheses.}
5230 @cindex @option{-gnatwQ} (@command{gcc})
5231 This switch suppresses warnings for cases where the association is not
5232 clear and the use of parentheses is preferred.
5233
5234 @item -gnatwr
5235 @emph{Activate warnings on redundant constructs.}
5236 @cindex @option{-gnatwr} (@command{gcc})
5237 This switch activates warnings for redundant constructs. The following
5238 is the current list of constructs regarded as redundant:
5239
5240 @itemize @bullet
5241 @item
5242 Assignment of an item to itself.
5243 @item
5244 Type conversion that converts an expression to its own type.
5245 @item
5246 Use of the attribute @code{Base} where @code{typ'Base} is the same
5247 as @code{typ}.
5248 @item
5249 Use of pragma @code{Pack} when all components are placed by a record
5250 representation clause.
5251 @item
5252 Exception handler containing only a reraise statement (raise with no
5253 operand) which has no effect.
5254 @item
5255 Use of the operator abs on an operand that is known at compile time
5256 to be non-negative
5257 @item
5258 Comparison of boolean expressions to an explicit True value.
5259 @end itemize
5260
5261 This warning can also be turned on using @option{-gnatwa}.
5262 The default is that warnings for redundant constructs are not given.
5263
5264 @item -gnatwR
5265 @emph{Suppress warnings on redundant constructs.}
5266 @cindex @option{-gnatwR} (@command{gcc})
5267 This switch suppresses warnings for redundant constructs.
5268
5269 @item -gnatws
5270 @emph{Suppress all warnings.}
5271 @cindex @option{-gnatws} (@command{gcc})
5272 This switch completely suppresses the
5273 output of all warning messages from the GNAT front end.
5274 Note that it does not suppress warnings from the @command{gcc} back end.
5275 To suppress these back end warnings as well, use the switch @option{-w}
5276 in addition to @option{-gnatws}.
5277
5278 @item -gnatwt
5279 @emph{Activate warnings for tracking of deleted conditional code.}
5280 @cindex @option{-gnatwt} (@command{gcc})
5281 @cindex Deactivated code, warnings
5282 @cindex Deleted code, warnings
5283 This switch activates warnings for tracking of code in conditionals (IF and
5284 CASE statements) that is detected to be dead code which cannot be executed, and
5285 which is removed by the front end. This warning is off by default, and is not
5286 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5287 useful for detecting deactivated code in certified applications.
5288
5289 @item -gnatwT
5290 @emph{Suppress warnings for tracking of deleted conditional code.}
5291 @cindex @option{-gnatwT} (@command{gcc})
5292 This switch suppresses warnings for tracking of deleted conditional code.
5293
5294 @item -gnatwu
5295 @emph{Activate warnings on unused entities.}
5296 @cindex @option{-gnatwu} (@command{gcc})
5297 This switch activates warnings to be generated for entities that
5298 are declared but not referenced, and for units that are @code{with}'ed
5299 and not
5300 referenced. In the case of packages, a warning is also generated if
5301 no entities in the package are referenced. This means that if the package
5302 is referenced but the only references are in @code{use}
5303 clauses or @code{renames}
5304 declarations, a warning is still generated. A warning is also generated
5305 for a generic package that is @code{with}'ed but never instantiated.
5306 In the case where a package or subprogram body is compiled, and there
5307 is a @code{with} on the corresponding spec
5308 that is only referenced in the body,
5309 a warning is also generated, noting that the
5310 @code{with} can be moved to the body. The default is that
5311 such warnings are not generated.
5312 This switch also activates warnings on unreferenced formals
5313 (it includes the effect of @option{-gnatwf}).
5314 This warning can also be turned on using @option{-gnatwa}.
5315
5316 @item -gnatwU
5317 @emph{Suppress warnings on unused entities.}
5318 @cindex @option{-gnatwU} (@command{gcc})
5319 This switch suppresses warnings for unused entities and packages.
5320 It also turns off warnings on unreferenced formals (and thus includes
5321 the effect of @option{-gnatwF}).
5322
5323 @item -gnatwv
5324 @emph{Activate warnings on unassigned variables.}
5325 @cindex @option{-gnatwv} (@command{gcc})
5326 @cindex Unassigned variable warnings
5327 This switch activates warnings for access to variables which
5328 may not be properly initialized. The default is that
5329 such warnings are generated.
5330 This warning can also be turned on using @option{-gnatwa}.
5331
5332 @item -gnatwV
5333 @emph{Suppress warnings on unassigned variables.}
5334 @cindex @option{-gnatwV} (@command{gcc})
5335 This switch suppresses warnings for access to variables which
5336 may not be properly initialized.
5337 For variables of a composite type, the warning can also be suppressed in
5338 Ada 2005 by using a default initialization with a box. For example, if
5339 Table is an array of records whose components are only partially uninitialized,
5340 then the following code:
5341
5342 @smallexample @c ada
5343    Tab : Table := (others => <>);
5344 @end smallexample
5345
5346 will suppress warnings on subsequent statements that access components
5347 of variable Tab.
5348
5349 @item -gnatww
5350 @emph{Activate warnings on wrong low bound assumption.}
5351 @cindex @option{-gnatww} (@command{gcc})
5352 @cindex String indexing warnings
5353 This switch activates warnings for indexing an unconstrained string parameter
5354 with a literal or S'Length. This is a case where the code is assuming that the
5355 low bound is one, which is in general not true (for example when a slice is
5356 passed). The default is that such warnings are generated.
5357 This warning can also be turned on using @option{-gnatwa}.
5358
5359 @item -gnatwW
5360 @emph{Suppress warnings on wrong low bound assumption.}
5361 @cindex @option{-gnatwW} (@command{gcc})
5362 This switch suppresses warnings for indexing an unconstrained string parameter
5363 with a literal or S'Length. Note that this warning can also be suppressed
5364 in a particular case by adding an
5365 assertion that the lower bound is 1,
5366 as shown in the following example.
5367
5368 @smallexample @c ada
5369    procedure K (S : String) is
5370       pragma Assert (S'First = 1);
5371       @dots{}
5372 @end smallexample
5373
5374 @item -gnatw.w
5375 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5376 @cindex @option{-gnatw.w} (@command{gcc})
5377 @cindex Warnings Off control
5378 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5379 where either the pragma is entirely useless (because it suppresses no
5380 warnings), or it could be replaced by @code{pragma Unreferenced} or
5381 @code{pragma Unmodified}.The default is that these warnings are not given.
5382 Note that this warning is not included in -gnatwa, it must be
5383 activated explicitly.
5384
5385 @item -gnatw.W
5386 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5387 @cindex @option{-gnatw.W} (@command{gcc})
5388 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5389
5390 @item -gnatwx
5391 @emph{Activate warnings on Export/Import pragmas.}
5392 @cindex @option{-gnatwx} (@command{gcc})
5393 @cindex Export/Import pragma warnings
5394 This switch activates warnings on Export/Import pragmas when
5395 the compiler detects a possible conflict between the Ada and
5396 foreign language calling sequences. For example, the use of
5397 default parameters in a convention C procedure is dubious
5398 because the C compiler cannot supply the proper default, so
5399 a warning is issued. The default is that such warnings are
5400 generated.
5401 This warning can also be turned on using @option{-gnatwa}.
5402
5403 @item -gnatwX
5404 @emph{Suppress warnings on Export/Import pragmas.}
5405 @cindex @option{-gnatwX} (@command{gcc})
5406 This switch suppresses warnings on Export/Import pragmas.
5407 The sense of this is that you are telling the compiler that
5408 you know what you are doing in writing the pragma, and it
5409 should not complain at you.
5410
5411 @item -gnatw.x
5412 @emph{Activate warnings for No_Exception_Propagation mode.}
5413 @cindex @option{-gnatwm} (@command{gcc})
5414 This switch activates warnings for exception usage when pragma Restrictions
5415 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5416 explicit exception raises which are not covered by a local handler, and for
5417 exception handlers which do not cover a local raise. The default is that these
5418 warnings are not given.
5419
5420 @item -gnatw.X
5421 @emph{Disable warnings for No_Exception_Propagation mode.}
5422 This switch disables warnings for exception usage when pragma Restrictions
5423 (No_Exception_Propagation) is in effect.
5424
5425 @item -gnatwy
5426 @emph{Activate warnings for Ada 2005 compatibility issues.}
5427 @cindex @option{-gnatwy} (@command{gcc})
5428 @cindex Ada 2005 compatibility issues warnings
5429 For the most part Ada 2005 is upwards compatible with Ada 95,
5430 but there are some exceptions (for example the fact that
5431 @code{interface} is now a reserved word in Ada 2005). This
5432 switch activates several warnings to help in identifying
5433 and correcting such incompatibilities. The default is that
5434 these warnings are generated. Note that at one point Ada 2005
5435 was called Ada 0Y, hence the choice of character.
5436 This warning can also be turned on using @option{-gnatwa}.
5437
5438 @item -gnatwY
5439 @emph{Disable warnings for Ada 2005 compatibility issues.}
5440 @cindex @option{-gnatwY} (@command{gcc})
5441 @cindex Ada 2005 compatibility issues warnings
5442 This switch suppresses several warnings intended to help in identifying
5443 incompatibilities between Ada 95 and Ada 2005.
5444
5445 @item -gnatwz
5446 @emph{Activate warnings on unchecked conversions.}
5447 @cindex @option{-gnatwz} (@command{gcc})
5448 @cindex Unchecked_Conversion warnings
5449 This switch activates warnings for unchecked conversions
5450 where the types are known at compile time to have different
5451 sizes. The default
5452 is that such warnings are generated. Warnings are also
5453 generated for subprogram pointers with different conventions,
5454 and, on VMS only, for data pointers with different conventions.
5455 This warning can also be turned on using @option{-gnatwa}.
5456
5457 @item -gnatwZ
5458 @emph{Suppress warnings on unchecked conversions.}
5459 @cindex @option{-gnatwZ} (@command{gcc})
5460 This switch suppresses warnings for unchecked conversions
5461 where the types are known at compile time to have different
5462 sizes or conventions.
5463
5464 @item ^-Wunused^WARNINGS=UNUSED^
5465 @cindex @option{-Wunused}
5466 The warnings controlled by the @option{-gnatw} switch are generated by
5467 the front end of the compiler. The @option{GCC} back end can provide
5468 additional warnings and they are controlled by the @option{-W} switch.
5469 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5470 warnings for entities that are declared but not referenced.
5471
5472 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5473 @cindex @option{-Wuninitialized}
5474 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5475 the back end warning for uninitialized variables. This switch must be
5476 used in conjunction with an optimization level greater than zero.
5477
5478 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5479 @cindex @option{-Wall}
5480 This switch enables all the above warnings from the @option{GCC} back end.
5481 The code generator detects a number of warning situations that are missed
5482 by the @option{GNAT} front end, and this switch can be used to activate them.
5483 The use of this switch also sets the default front end warning mode to
5484 @option{-gnatwa}, that is, most front end warnings activated as well.
5485
5486 @item ^-w^/NO_BACK_END_WARNINGS^
5487 @cindex @option{-w}
5488 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5489 The use of this switch also sets the default front end warning mode to
5490 @option{-gnatws}, that is, front end warnings suppressed as well.
5491
5492 @end table
5493
5494 @noindent
5495 @ifclear vms
5496 A string of warning parameters can be used in the same parameter. For example:
5497
5498 @smallexample
5499 -gnatwaLe
5500 @end smallexample
5501
5502 @noindent
5503 will turn on all optional warnings except for elaboration pragma warnings,
5504 and also specify that warnings should be treated as errors.
5505 @end ifclear
5506 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5507
5508 @table @option
5509 @c !sort!
5510 @item -gnatwC
5511 @item -gnatwD
5512 @item -gnatwF
5513 @item -gnatwg
5514 @item -gnatwH
5515 @item -gnatwi
5516 @item -gnatwJ
5517 @item -gnatwK
5518 @item -gnatwL
5519 @item -gnatwM
5520 @item -gnatwn
5521 @item -gnatwo
5522 @item -gnatwP
5523 @item -gnatwR
5524 @item -gnatwU
5525 @item -gnatwv
5526 @item -gnatwz
5527 @item -gnatwx
5528
5529 @end table
5530
5531 @node Debugging and Assertion Control
5532 @subsection Debugging and Assertion Control
5533
5534 @table @option
5535 @item -gnata
5536 @cindex @option{-gnata} (@command{gcc})
5537 @findex Assert
5538 @findex Debug
5539 @cindex Assertions
5540
5541 @noindent
5542 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5543 are ignored. This switch, where @samp{a} stands for assert, causes
5544 @code{Assert} and @code{Debug} pragmas to be activated.
5545
5546 The pragmas have the form:
5547
5548 @smallexample
5549 @cartouche
5550    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5551                       @var{static-string-expression}@r{]})
5552    @b{pragma} Debug (@var{procedure call})
5553 @end cartouche
5554 @end smallexample
5555
5556 @noindent
5557 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5558 If the result is @code{True}, the pragma has no effect (other than
5559 possible side effects from evaluating the expression). If the result is
5560 @code{False}, the exception @code{Assert_Failure} declared in the package
5561 @code{System.Assertions} is
5562 raised (passing @var{static-string-expression}, if present, as the
5563 message associated with the exception). If no string expression is
5564 given the default is a string giving the file name and line number
5565 of the pragma.
5566
5567 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5568 @code{pragma Debug} may appear within a declaration sequence, allowing
5569 debugging procedures to be called between declarations.
5570
5571 @ifset vms
5572 @item /DEBUG@r{[}=debug-level@r{]}
5573 @itemx  /NODEBUG
5574 Specifies how much debugging information is to be included in
5575 the resulting object file where 'debug-level' is one of the following:
5576 @table @code
5577 @item   TRACEBACK
5578 Include both debugger symbol records and traceback
5579 the object file.
5580 This is the default setting.
5581 @item   ALL
5582 Include both debugger symbol records and traceback in
5583 object file.
5584 @item   NONE
5585 Excludes both debugger symbol records and traceback
5586 the object file. Same as /NODEBUG.
5587 @item   SYMBOLS
5588 Includes only debugger symbol records in the object
5589 file. Note that this doesn't include traceback information.
5590 @end table
5591 @end ifset
5592 @end table
5593
5594 @node Validity Checking
5595 @subsection Validity Checking
5596 @findex Validity Checking
5597
5598 @noindent
5599 The Ada Reference Manual has specific requirements for checking
5600 for invalid values. In particular, RM 13.9.1 requires that the
5601 evaluation of invalid values (for example from unchecked conversions),
5602 not result in erroneous execution. In GNAT, the result of such an
5603 evaluation in normal default mode is to either use the value
5604 unmodified, or to raise Constraint_Error in those cases where use
5605 of the unmodified value would cause erroneous execution. The cases
5606 where unmodified values might lead to erroneous execution are case
5607 statements (where a wild jump might result from an invalid value),
5608 and subscripts on the left hand side (where memory corruption could
5609 occur as a result of an invalid value).
5610
5611 The @option{-gnatB} switch tells the compiler to assume that all
5612 values are valid (that is, within their declared subtype range)
5613 except in the context of a use of the Valid attribute. This means
5614 the compiler can generate more efficient code, since the range
5615 of values is better known at compile time.
5616
5617 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5618 checking mode.
5619 @ifclear vms
5620 The @code{x} argument is a string of letters that
5621 indicate validity checks that are performed or not performed in addition
5622 to the default checks described above.
5623 @end ifclear
5624 @ifset vms
5625 The options allowed for this qualifier
5626 indicate validity checks that are performed or not performed in addition
5627 to the default checks described above.
5628 @end ifset
5629
5630 @table @option
5631 @c !sort!
5632 @item -gnatVa
5633 @emph{All validity checks.}
5634 @cindex @option{-gnatVa} (@command{gcc})
5635 All validity checks are turned on.
5636 @ifclear vms
5637 That is, @option{-gnatVa} is
5638 equivalent to @option{gnatVcdfimorst}.
5639 @end ifclear
5640
5641 @item -gnatVc
5642 @emph{Validity checks for copies.}
5643 @cindex @option{-gnatVc} (@command{gcc})
5644 The right hand side of assignments, and the initializing values of
5645 object declarations are validity checked.
5646
5647 @item -gnatVd
5648 @emph{Default (RM) validity checks.}
5649 @cindex @option{-gnatVd} (@command{gcc})
5650 Some validity checks are done by default following normal Ada semantics
5651 (RM 13.9.1 (9-11)).
5652 A check is done in case statements that the expression is within the range
5653 of the subtype. If it is not, Constraint_Error is raised.
5654 For assignments to array components, a check is done that the expression used
5655 as index is within the range. If it is not, Constraint_Error is raised.
5656 Both these validity checks may be turned off using switch @option{-gnatVD}.
5657 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5658 switch @option{-gnatVd} will leave the checks turned on.
5659 Switch @option{-gnatVD} should be used only if you are sure that all such
5660 expressions have valid values. If you use this switch and invalid values
5661 are present, then the program is erroneous, and wild jumps or memory
5662 overwriting may occur.
5663
5664 @item -gnatVe
5665 @emph{Validity checks for elementary components.}
5666 @cindex @option{-gnatVe} (@command{gcc})
5667 In the absence of this switch, assignments to record or array components are
5668 not validity checked, even if validity checks for assignments generally
5669 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5670 require valid data, but assignment of individual components does. So for
5671 example, there is a difference between copying the elements of an array with a
5672 slice assignment, compared to assigning element by element in a loop. This
5673 switch allows you to turn off validity checking for components, even when they
5674 are assigned component by component.
5675
5676 @item -gnatVf
5677 @emph{Validity checks for floating-point values.}
5678 @cindex @option{-gnatVf} (@command{gcc})
5679 In the absence of this switch, validity checking occurs only for discrete
5680 values. If @option{-gnatVf} is specified, then validity checking also applies
5681 for floating-point values, and NaNs and infinities are considered invalid,
5682 as well as out of range values for constrained types. Note that this means
5683 that standard IEEE infinity mode is not allowed. The exact contexts
5684 in which floating-point values are checked depends on the setting of other
5685 options. For example,
5686 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5687 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5688 (the order does not matter) specifies that floating-point parameters of mode
5689 @code{in} should be validity checked.
5690
5691 @item -gnatVi
5692 @emph{Validity checks for @code{in} mode parameters}
5693 @cindex @option{-gnatVi} (@command{gcc})
5694 Arguments for parameters of mode @code{in} are validity checked in function
5695 and procedure calls at the point of call.
5696
5697 @item -gnatVm
5698 @emph{Validity checks for @code{in out} mode parameters.}
5699 @cindex @option{-gnatVm} (@command{gcc})
5700 Arguments for parameters of mode @code{in out} are validity checked in
5701 procedure calls at the point of call. The @code{'m'} here stands for
5702 modify, since this concerns parameters that can be modified by the call.
5703 Note that there is no specific option to test @code{out} parameters,
5704 but any reference within the subprogram will be tested in the usual
5705 manner, and if an invalid value is copied back, any reference to it
5706 will be subject to validity checking.
5707
5708 @item -gnatVn
5709 @emph{No validity checks.}
5710 @cindex @option{-gnatVn} (@command{gcc})
5711 This switch turns off all validity checking, including the default checking
5712 for case statements and left hand side subscripts. Note that the use of
5713 the switch @option{-gnatp} suppresses all run-time checks, including
5714 validity checks, and thus implies @option{-gnatVn}. When this switch
5715 is used, it cancels any other @option{-gnatV} previously issued.
5716
5717 @item -gnatVo
5718 @emph{Validity checks for operator and attribute operands.}
5719 @cindex @option{-gnatVo} (@command{gcc})
5720 Arguments for predefined operators and attributes are validity checked.
5721 This includes all operators in package @code{Standard},
5722 the shift operators defined as intrinsic in package @code{Interfaces}
5723 and operands for attributes such as @code{Pos}. Checks are also made
5724 on individual component values for composite comparisons, and on the
5725 expressions in type conversions and qualified expressions. Checks are
5726 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
5727
5728 @item -gnatVp
5729 @emph{Validity checks for parameters.}
5730 @cindex @option{-gnatVp} (@command{gcc})
5731 This controls the treatment of parameters within a subprogram (as opposed
5732 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5733 of parameters on a call. If either of these call options is used, then
5734 normally an assumption is made within a subprogram that the input arguments
5735 have been validity checking at the point of call, and do not need checking
5736 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5737 is not made, and parameters are not assumed to be valid, so their validity
5738 will be checked (or rechecked) within the subprogram.
5739
5740 @item -gnatVr
5741 @emph{Validity checks for function returns.}
5742 @cindex @option{-gnatVr} (@command{gcc})
5743 The expression in @code{return} statements in functions is validity
5744 checked.
5745
5746 @item -gnatVs
5747 @emph{Validity checks for subscripts.}
5748 @cindex @option{-gnatVs} (@command{gcc})
5749 All subscripts expressions are checked for validity, whether they appear
5750 on the right side or left side (in default mode only left side subscripts
5751 are validity checked).
5752
5753 @item -gnatVt
5754 @emph{Validity checks for tests.}
5755 @cindex @option{-gnatVt} (@command{gcc})
5756 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5757 statements are checked, as well as guard expressions in entry calls.
5758
5759 @end table
5760
5761 @noindent
5762 The @option{-gnatV} switch may be followed by
5763 ^a string of letters^a list of options^
5764 to turn on a series of validity checking options.
5765 For example,
5766 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5767 specifies that in addition to the default validity checking, copies and
5768 function return expressions are to be validity checked.
5769 In order to make it easier
5770 to specify the desired combination of effects,
5771 @ifclear vms
5772 the upper case letters @code{CDFIMORST} may
5773 be used to turn off the corresponding lower case option.
5774 @end ifclear
5775 @ifset vms
5776 the prefix @code{NO} on an option turns off the corresponding validity
5777 checking:
5778 @itemize @bullet
5779 @item @code{NOCOPIES}
5780 @item @code{NODEFAULT}
5781 @item @code{NOFLOATS}
5782 @item @code{NOIN_PARAMS}
5783 @item @code{NOMOD_PARAMS}
5784 @item @code{NOOPERANDS}
5785 @item @code{NORETURNS}
5786 @item @code{NOSUBSCRIPTS}
5787 @item @code{NOTESTS}
5788 @end itemize
5789 @end ifset
5790 Thus
5791 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5792 turns on all validity checking options except for
5793 checking of @code{@b{in out}} procedure arguments.
5794
5795 The specification of additional validity checking generates extra code (and
5796 in the case of @option{-gnatVa} the code expansion can be substantial).
5797 However, these additional checks can be very useful in detecting
5798 uninitialized variables, incorrect use of unchecked conversion, and other
5799 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5800 is useful in conjunction with the extra validity checking, since this
5801 ensures that wherever possible uninitialized variables have invalid values.
5802
5803 See also the pragma @code{Validity_Checks} which allows modification of
5804 the validity checking mode at the program source level, and also allows for
5805 temporary disabling of validity checks.
5806
5807 @node Style Checking
5808 @subsection Style Checking
5809 @findex Style checking
5810
5811 @noindent
5812 The @option{-gnaty^x^(option,option,@dots{})^} switch
5813 @cindex @option{-gnaty} (@command{gcc})
5814 causes the compiler to
5815 enforce specified style rules. A limited set of style rules has been used
5816 in writing the GNAT sources themselves. This switch allows user programs
5817 to activate all or some of these checks. If the source program fails a
5818 specified style check, an appropriate warning message is given, preceded by
5819 the character sequence ``(style)''.
5820 @ifset vms
5821 @code{(option,option,@dots{})} is a sequence of keywords
5822 @end ifset
5823 @ifclear vms
5824 The string @var{x} is a sequence of letters or digits
5825 @end ifclear
5826 indicating the particular style
5827 checks to be performed. The following checks are defined:
5828
5829 @table @option
5830 @c !sort!
5831 @item 0-9
5832 @emph{Specify indentation level.}
5833 If a digit from 1-9 appears
5834 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5835 then proper indentation is checked, with the digit indicating the
5836 indentation level required. A value of zero turns off this style check.
5837 The general style of required indentation is as specified by
5838 the examples in the Ada Reference Manual. Full line comments must be
5839 aligned with the @code{--} starting on a column that is a multiple of
5840 the alignment level, or they may be aligned the same way as the following
5841 non-blank line (this is useful when full line comments appear in the middle
5842 of a statement.
5843
5844 @item ^a^ATTRIBUTE^
5845 @emph{Check attribute casing.}
5846 Attribute names, including the case of keywords such as @code{digits}
5847 used as attributes names, must be written in mixed case, that is, the
5848 initial letter and any letter following an underscore must be uppercase.
5849 All other letters must be lowercase.
5850
5851 @item ^A^ARRAY_INDEXES^
5852 @emph{Use of array index numbers in array attributes.}
5853 When using the array attributes First, Last, Range,
5854 or Length, the index number must be omitted for one-dimensional arrays
5855 and is required for multi-dimensional arrays.
5856
5857 @item ^b^BLANKS^
5858 @emph{Blanks not allowed at statement end.}
5859 Trailing blanks are not allowed at the end of statements. The purpose of this
5860 rule, together with h (no horizontal tabs), is to enforce a canonical format
5861 for the use of blanks to separate source tokens.
5862
5863 @item ^c^COMMENTS^
5864 @emph{Check comments.}
5865 Comments must meet the following set of rules:
5866
5867 @itemize @bullet
5868
5869 @item
5870 The ``@code{--}'' that starts the column must either start in column one,
5871 or else at least one blank must precede this sequence.
5872
5873 @item
5874 Comments that follow other tokens on a line must have at least one blank
5875 following the ``@code{--}'' at the start of the comment.
5876
5877 @item
5878 Full line comments must have two blanks following the ``@code{--}'' that
5879 starts the comment, with the following exceptions.
5880
5881 @item
5882 A line consisting only of the ``@code{--}'' characters, possibly preceded
5883 by blanks is permitted.
5884
5885 @item
5886 A comment starting with ``@code{--x}'' where @code{x} is a special character
5887 is permitted.
5888 This allows proper processing of the output generated by specialized tools
5889 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5890 annotation
5891 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5892 special character is defined as being in one of the ASCII ranges
5893 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
5894 Note that this usage is not permitted
5895 in GNAT implementation units (i.e., when @option{-gnatg} is used).
5896
5897 @item
5898 A line consisting entirely of minus signs, possibly preceded by blanks, is
5899 permitted. This allows the construction of box comments where lines of minus
5900 signs are used to form the top and bottom of the box.
5901
5902 @item
5903 A comment that starts and ends with ``@code{--}'' is permitted as long as at
5904 least one blank follows the initial ``@code{--}''. Together with the preceding
5905 rule, this allows the construction of box comments, as shown in the following
5906 example:
5907 @smallexample
5908 ---------------------------
5909 -- This is a box comment --
5910 -- with two text lines.  --
5911 ---------------------------
5912 @end smallexample
5913 @end itemize
5914
5915 @item ^d^DOS_LINE_ENDINGS^
5916 @emph{Check no DOS line terminators present.}
5917 All lines must be terminated by a single ASCII.LF
5918 character (in particular the DOS line terminator sequence CR/LF is not
5919 allowed).
5920
5921 @item ^e^END^
5922 @emph{Check end/exit labels.}
5923 Optional labels on @code{end} statements ending subprograms and on
5924 @code{exit} statements exiting named loops, are required to be present.
5925
5926 @item ^f^VTABS^
5927 @emph{No form feeds or vertical tabs.}
5928 Neither form feeds nor vertical tab characters are permitted
5929 in the source text.
5930
5931 @item ^g^GNAT^
5932 @emph{GNAT style mode}
5933 The set of style check switches is set to match that used by the GNAT sources.
5934 This may be useful when developing code that is eventually intended to be
5935 incorporated into GNAT. For further details, see GNAT sources.
5936
5937 @item ^h^HTABS^
5938 @emph{No horizontal tabs.}
5939 Horizontal tab characters are not permitted in the source text.
5940 Together with the b (no blanks at end of line) check, this
5941 enforces a canonical form for the use of blanks to separate
5942 source tokens.
5943
5944 @item ^i^IF_THEN^
5945 @emph{Check if-then layout.}
5946 The keyword @code{then} must appear either on the same
5947 line as corresponding @code{if}, or on a line on its own, lined
5948 up under the @code{if} with at least one non-blank line in between
5949 containing all or part of the condition to be tested.
5950
5951 @item ^I^IN_MODE^
5952 @emph{check mode IN keywords}
5953 Mode @code{in} (the default mode) is not
5954 allowed to be given explicitly. @code{in out} is fine,
5955 but not @code{in} on its own.
5956
5957 @item ^k^KEYWORD^
5958 @emph{Check keyword casing.}
5959 All keywords must be in lower case (with the exception of keywords
5960 such as @code{digits} used as attribute names to which this check
5961 does not apply).
5962
5963 @item ^l^LAYOUT^
5964 @emph{Check layout.}
5965 Layout of statement and declaration constructs must follow the
5966 recommendations in the Ada Reference Manual, as indicated by the
5967 form of the syntax rules. For example an @code{else} keyword must
5968 be lined up with the corresponding @code{if} keyword.
5969
5970 There are two respects in which the style rule enforced by this check
5971 option are more liberal than those in the Ada Reference Manual. First
5972 in the case of record declarations, it is permissible to put the
5973 @code{record} keyword on the same line as the @code{type} keyword, and
5974 then the @code{end} in @code{end record} must line up under @code{type}.
5975 This is also permitted when the type declaration is split on two lines.
5976 For example, any of the following three layouts is acceptable:
5977
5978 @smallexample @c ada
5979 @cartouche
5980 type q is record
5981    a : integer;
5982    b : integer;
5983 end record;
5984
5985 type q is
5986    record
5987       a : integer;
5988       b : integer;
5989    end record;
5990
5991 type q is
5992    record
5993       a : integer;
5994       b : integer;
5995 end record;
5996
5997 @end cartouche
5998 @end smallexample
5999
6000 @noindent
6001 Second, in the case of a block statement, a permitted alternative
6002 is to put the block label on the same line as the @code{declare} or
6003 @code{begin} keyword, and then line the @code{end} keyword up under
6004 the block label. For example both the following are permitted:
6005
6006 @smallexample @c ada
6007 @cartouche
6008 Block : declare
6009    A : Integer := 3;
6010 begin
6011    Proc (A, A);
6012 end Block;
6013
6014 Block :
6015    declare
6016       A : Integer := 3;
6017    begin
6018       Proc (A, A);
6019    end Block;
6020 @end cartouche
6021 @end smallexample
6022
6023 @noindent
6024 The same alternative format is allowed for loops. For example, both of
6025 the following are permitted:
6026
6027 @smallexample @c ada
6028 @cartouche
6029 Clear : while J < 10 loop
6030    A (J) := 0;
6031 end loop Clear;
6032
6033 Clear :
6034    while J < 10 loop
6035       A (J) := 0;
6036    end loop Clear;
6037 @end cartouche
6038 @end smallexample
6039
6040 @item ^Lnnn^MAX_NESTING=nnn^
6041 @emph{Set maximum nesting level}
6042 The maximum level of nesting of constructs (including subprograms, loops,
6043 blocks, packages, and conditionals) may not exceed the given value
6044 @option{nnn}. A value of zero disconnects this style check.
6045
6046 @item ^m^LINE_LENGTH^
6047 @emph{Check maximum line length.}
6048 The length of source lines must not exceed 79 characters, including
6049 any trailing blanks. The value of 79 allows convenient display on an
6050 80 character wide device or window, allowing for possible special
6051 treatment of 80 character lines. Note that this count is of
6052 characters in the source text. This means that a tab character counts
6053 as one character in this count but a wide character sequence counts as
6054 a single character (however many bytes are needed in the encoding).
6055
6056 @item ^Mnnn^MAX_LENGTH=nnn^
6057 @emph{Set maximum line length.}
6058 The length of lines must not exceed the
6059 given value @option{nnn}. The maximum value that can be specified is 32767.
6060
6061 @item ^n^STANDARD_CASING^
6062 @emph{Check casing of entities in Standard.}
6063 Any identifier from Standard must be cased
6064 to match the presentation in the Ada Reference Manual (for example,
6065 @code{Integer} and @code{ASCII.NUL}).
6066
6067 @item ^N^NONE^
6068 @emph{Turn off all style checks}
6069 All style check options are turned off.
6070
6071 @item ^o^ORDERED_SUBPROGRAMS^
6072 @emph{Check order of subprogram bodies.}
6073 All subprogram bodies in a given scope
6074 (e.g.@: a package body) must be in alphabetical order. The ordering
6075 rule uses normal Ada rules for comparing strings, ignoring casing
6076 of letters, except that if there is a trailing numeric suffix, then
6077 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6078 before Junk10).
6079
6080 @item ^O^OVERRIDING_INDICATORS^
6081 @emph{Check that overriding subprograms are explicitly marked as such.}
6082 The declaration of a primitive operation of a type extension that overrides
6083 an inherited operation must carry an overriding indicator.
6084
6085 @item ^p^PRAGMA^
6086 @emph{Check pragma casing.}
6087 Pragma names must be written in mixed case, that is, the
6088 initial letter and any letter following an underscore must be uppercase.
6089 All other letters must be lowercase.
6090
6091 @item ^r^REFERENCES^
6092 @emph{Check references.}
6093 All identifier references must be cased in the same way as the
6094 corresponding declaration. No specific casing style is imposed on
6095 identifiers. The only requirement is for consistency of references
6096 with declarations.
6097
6098 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6099 @emph{Check no statements after THEN/ELSE.}
6100 No statements are allowed
6101 on the same line as a THEN or ELSE keyword following the
6102 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6103 and a special exception allows a pragma to appear after ELSE.
6104
6105 @item ^s^SPECS^
6106 @emph{Check separate specs.}
6107 Separate declarations (``specs'') are required for subprograms (a
6108 body is not allowed to serve as its own declaration). The only
6109 exception is that parameterless library level procedures are
6110 not required to have a separate declaration. This exception covers
6111 the most frequent form of main program procedures.
6112
6113 @item ^t^TOKEN^
6114 @emph{Check token spacing.}
6115 The following token spacing rules are enforced:
6116
6117 @itemize @bullet
6118
6119 @item
6120 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6121
6122 @item
6123 The token @code{=>} must be surrounded by spaces.
6124
6125 @item
6126 The token @code{<>} must be preceded by a space or a left parenthesis.
6127
6128 @item
6129 Binary operators other than @code{**} must be surrounded by spaces.
6130 There is no restriction on the layout of the @code{**} binary operator.
6131
6132 @item
6133 Colon must be surrounded by spaces.
6134
6135 @item
6136 Colon-equal (assignment, initialization) must be surrounded by spaces.
6137
6138 @item
6139 Comma must be the first non-blank character on the line, or be
6140 immediately preceded by a non-blank character, and must be followed
6141 by a space.
6142
6143 @item
6144 If the token preceding a left parenthesis ends with a letter or digit, then
6145 a space must separate the two tokens.
6146
6147 @item
6148 A right parenthesis must either be the first non-blank character on
6149 a line, or it must be preceded by a non-blank character.
6150
6151 @item
6152 A semicolon must not be preceded by a space, and must not be followed by
6153 a non-blank character.
6154
6155 @item
6156 A unary plus or minus may not be followed by a space.
6157
6158 @item
6159 A vertical bar must be surrounded by spaces.
6160 @end itemize
6161
6162 @item ^u^UNNECESSARY_BLANK_LINES^
6163 @emph{Check unnecessary blank lines.}
6164 Unnecessary blank lines are not allowed. A blank line is considered
6165 unnecessary if it appears at the end of the file, or if more than
6166 one blank line occurs in sequence.
6167
6168 @item ^x^XTRA_PARENS^
6169 @emph{Check extra parentheses.}
6170 Unnecessary extra level of parentheses (C-style) are not allowed
6171 around conditions in @code{if} statements, @code{while} statements and
6172 @code{exit} statements.
6173
6174 @item ^y^ALL_BUILTIN^
6175 @emph{Set all standard style check options}
6176 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6177 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6178 @option{-gnatyS}, @option{-gnatyLnnn},
6179 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6180
6181 @ifclear vms
6182 @item -
6183 @emph{Remove style check options}
6184 This causes any subsequent options in the string to act as canceling the
6185 corresponding style check option. To cancel maximum nesting level control,
6186 use @option{L} parameter witout any integer value after that, because any
6187 digit following @option{-} in the parameter string of the @option{-gnaty}
6188 option will be threated as canceling indentation check. The same is true
6189 for @option{M} parameter. @option{y} and @option{N} parameters are not
6190 allowed after @option{-}.
6191
6192 @item +
6193 This causes any subsequent options in the string to enable the corresponding
6194 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6195 if any.
6196 @end ifclear
6197
6198 @ifset vms
6199 @item NOxxx
6200 @emph{Removing style check options}
6201 If the name of a style check is preceded by @option{NO} then the corresponding
6202 style check is turned off. For example @option{NOCOMMENTS} turns off style
6203 checking for comments.
6204 @end ifset
6205 @end table
6206
6207 @noindent
6208 In the above rules, appearing in column one is always permitted, that is,
6209 counts as meeting either a requirement for a required preceding space,
6210 or as meeting a requirement for no preceding space.
6211
6212 Appearing at the end of a line is also always permitted, that is, counts
6213 as meeting either a requirement for a following space, or as meeting
6214 a requirement for no following space.
6215
6216 @noindent
6217 If any of these style rules is violated, a message is generated giving
6218 details on the violation. The initial characters of such messages are
6219 always ``@code{(style)}''. Note that these messages are treated as warning
6220 messages, so they normally do not prevent the generation of an object
6221 file. The @option{-gnatwe} switch can be used to treat warning messages,
6222 including style messages, as fatal errors.
6223
6224 The switch
6225 @ifclear vms
6226 @option{-gnaty} on its own (that is not
6227 followed by any letters or digits), then the effect is equivalent
6228 to the use of @option{-gnatyy}, as described above, that is all
6229 built-in standard style check options are enabled.
6230
6231 @end ifclear
6232 @ifset vms
6233 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6234 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6235 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6236 @end ifset
6237
6238
6239
6240 The switch
6241 @ifclear vms
6242 @option{-gnatyN}
6243 @end ifclear
6244 @ifset vms
6245 /STYLE_CHECKS=NONE
6246 @end ifset
6247 clears any previously set style checks.
6248
6249 @node Run-Time Checks
6250 @subsection Run-Time Checks
6251 @cindex Division by zero
6252 @cindex Access before elaboration
6253 @cindex Checks, division by zero
6254 @cindex Checks, access before elaboration
6255 @cindex Checks, stack overflow checking
6256
6257 @noindent
6258 By default, the following checks are suppressed: integer overflow
6259 checks, stack overflow checks, and checks for access before
6260 elaboration on subprogram calls. All other checks, including range
6261 checks and array bounds checks, are turned on by default. The
6262 following @command{gcc} switches refine this default behavior.
6263
6264 @table @option
6265 @c !sort!
6266 @item -gnatp
6267 @cindex @option{-gnatp} (@command{gcc})
6268 @cindex Suppressing checks
6269 @cindex Checks, suppressing
6270 @findex Suppress
6271 Suppress all run-time checks as though @code{pragma Suppress (All_checks)}
6272 had been present in the source. Validity checks are also suppressed (in
6273 other words @option{-gnatp} also implies @option{-gnatVn}.
6274 Use this switch to improve the performance
6275 of the code at the expense of safety in the presence of invalid data or
6276 program bugs.
6277
6278 Note that when checks are suppressed, the compiler is allowed, but not
6279 required, to omit the checking code. If the run-time cost of the
6280 checking code is zero or near-zero, the compiler will generate it even
6281 if checks are suppressed. In particular, if the compiler can prove
6282 that a certain check will necessarily fail, it will generate code to
6283 do an unconditional ``raise'', even if checks are suppressed. The
6284 compiler warns in this case.
6285
6286 Of course, run-time checks are omitted whenever the compiler can prove
6287 that they will not fail, whether or not checks are suppressed.
6288
6289 Note that if you suppress a check that would have failed, program
6290 execution is erroneous, which means the behavior is totally
6291 unpredictable. The program might crash, or print wrong answers, or
6292 do anything else. It might even do exactly what you wanted it to do
6293 (and then it might start failing mysteriously next week or next
6294 year). The compiler will generate code based on the assumption that
6295 the condition being checked is true, which can result in disaster if
6296 that assumption is wrong.
6297
6298 @item -gnato
6299 @cindex @option{-gnato} (@command{gcc})
6300 @cindex Overflow checks
6301 @cindex Check, overflow
6302 Enables overflow checking for integer operations.
6303 This causes GNAT to generate slower and larger executable
6304 programs by adding code to check for overflow (resulting in raising
6305 @code{Constraint_Error} as required by standard Ada
6306 semantics). These overflow checks correspond to situations in which
6307 the true value of the result of an operation may be outside the base
6308 range of the result type. The following example shows the distinction:
6309
6310 @smallexample @c ada
6311 X1 : Integer := "Integer'Last";
6312 X2 : Integer range 1 .. 5 := "5";
6313 X3 : Integer := "Integer'Last";
6314 X4 : Integer range 1 .. 5 := "5";
6315 F  : Float := "2.0E+20";
6316 @dots{}
6317 X1 := X1 + 1;
6318 X2 := X2 + 1;
6319 X3 := Integer (F);
6320 X4 := Integer (F);
6321 @end smallexample
6322
6323 @noindent
6324 Note that if explicit values are assigned at compile time, the
6325 compiler may be able to detect overflow at compile time, in which case
6326 no actual run-time checking code is required, and Constraint_Error
6327 will be raised unconditionally, with or without
6328 @option{-gnato}. That's why the assigned values in the above fragment
6329 are in quotes, the meaning is "assign a value not known to the
6330 compiler that happens to be equal to ...". The remaining discussion
6331 assumes that the compiler cannot detect the values at compile time.
6332
6333 Here the first addition results in a value that is outside the base range
6334 of Integer, and hence requires an overflow check for detection of the
6335 constraint error. Thus the first assignment to @code{X1} raises a
6336 @code{Constraint_Error} exception only if @option{-gnato} is set.
6337
6338 The second increment operation results in a violation of the explicit
6339 range constraint; such range checks are performed by default, and are
6340 unaffected by @option{-gnato}.
6341
6342 The two conversions of @code{F} both result in values that are outside
6343 the base range of type @code{Integer} and thus will raise
6344 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6345 The fact that the result of the second conversion is assigned to
6346 variable @code{X4} with a restricted range is irrelevant, since the problem
6347 is in the conversion, not the assignment.
6348
6349 Basically the rule is that in the default mode (@option{-gnato} not
6350 used), the generated code assures that all integer variables stay
6351 within their declared ranges, or within the base range if there is
6352 no declared range. This prevents any serious problems like indexes
6353 out of range for array operations.
6354
6355 What is not checked in default mode is an overflow that results in
6356 an in-range, but incorrect value. In the above example, the assignments
6357 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6358 range of the target variable, but the result is wrong in the sense that
6359 it is too large to be represented correctly. Typically the assignment
6360 to @code{X1} will result in wrap around to the largest negative number.
6361 The conversions of @code{F} will result in some @code{Integer} value
6362 and if that integer value is out of the @code{X4} range then the
6363 subsequent assignment would generate an exception.
6364
6365 @findex Machine_Overflows
6366 Note that the @option{-gnato} switch does not affect the code generated
6367 for any floating-point operations; it applies only to integer
6368 semantics).
6369 For floating-point, GNAT has the @code{Machine_Overflows}
6370 attribute set to @code{False} and the normal mode of operation is to
6371 generate IEEE NaN and infinite values on overflow or invalid operations
6372 (such as dividing 0.0 by 0.0).
6373
6374 The reason that we distinguish overflow checking from other kinds of
6375 range constraint checking is that a failure of an overflow check, unlike
6376 for example the failure of a range check, can result in an incorrect
6377 value, but cannot cause random memory destruction (like an out of range
6378 subscript), or a wild jump (from an out of range case value). Overflow
6379 checking is also quite expensive in time and space, since in general it
6380 requires the use of double length arithmetic.
6381
6382 Note again that @option{-gnato} is off by default, so overflow checking is
6383 not performed in default mode. This means that out of the box, with the
6384 default settings, GNAT does not do all the checks expected from the
6385 language description in the Ada Reference Manual. If you want all constraint
6386 checks to be performed, as described in this Manual, then you must
6387 explicitly use the -gnato switch either on the @command{gnatmake} or
6388 @command{gcc} command.
6389
6390 @item -gnatE
6391 @cindex @option{-gnatE} (@command{gcc})
6392 @cindex Elaboration checks
6393 @cindex Check, elaboration
6394 Enables dynamic checks for access-before-elaboration
6395 on subprogram calls and generic instantiations.
6396 Note that @option{-gnatE} is not necessary for safety, because in the
6397 default mode, GNAT ensures statically that the checks would not fail.
6398 For full details of the effect and use of this switch,
6399 @xref{Compiling Using gcc}.
6400
6401 @item -fstack-check
6402 @cindex @option{-fstack-check} (@command{gcc})
6403 @cindex Stack Overflow Checking
6404 @cindex Checks, stack overflow checking
6405 Activates stack overflow checking. For full details of the effect and use of
6406 this switch see @ref{Stack Overflow Checking}.
6407 @end table
6408
6409 @findex Unsuppress
6410 @noindent
6411 The setting of these switches only controls the default setting of the
6412 checks. You may modify them using either @code{Suppress} (to remove
6413 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6414 the program source.
6415
6416 @node Using gcc for Syntax Checking
6417 @subsection Using @command{gcc} for Syntax Checking
6418 @table @option
6419 @item -gnats
6420 @cindex @option{-gnats} (@command{gcc})
6421 @ifclear vms
6422
6423 @noindent
6424 The @code{s} stands for ``syntax''.
6425 @end ifclear
6426
6427 Run GNAT in syntax checking only mode. For
6428 example, the command
6429
6430 @smallexample
6431 $ gcc -c -gnats x.adb
6432 @end smallexample
6433
6434 @noindent
6435 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6436 series of files in a single command
6437 @ifclear vms
6438 , and can use wild cards to specify such a group of files.
6439 Note that you must specify the @option{-c} (compile
6440 only) flag in addition to the @option{-gnats} flag.
6441 @end ifclear
6442 .
6443 You may use other switches in conjunction with @option{-gnats}. In
6444 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6445 format of any generated error messages.
6446
6447 When the source file is empty or contains only empty lines and/or comments,
6448 the output is a warning:
6449
6450 @smallexample
6451 $ gcc -c -gnats -x ada toto.txt
6452 toto.txt:1:01: warning: empty file, contains no compilation units
6453 $
6454 @end smallexample
6455
6456 Otherwise, the output is simply the error messages, if any. No object file or
6457 ALI file is generated by a syntax-only compilation. Also, no units other
6458 than the one specified are accessed. For example, if a unit @code{X}
6459 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6460 check only mode does not access the source file containing unit
6461 @code{Y}.
6462
6463 @cindex Multiple units, syntax checking
6464 Normally, GNAT allows only a single unit in a source file. However, this
6465 restriction does not apply in syntax-check-only mode, and it is possible
6466 to check a file containing multiple compilation units concatenated
6467 together. This is primarily used by the @code{gnatchop} utility
6468 (@pxref{Renaming Files Using gnatchop}).
6469 @end table
6470
6471 @node Using gcc for Semantic Checking
6472 @subsection Using @command{gcc} for Semantic Checking
6473 @table @option
6474 @item -gnatc
6475 @cindex @option{-gnatc} (@command{gcc})
6476
6477 @ifclear vms
6478 @noindent
6479 The @code{c} stands for ``check''.
6480 @end ifclear
6481 Causes the compiler to operate in semantic check mode,
6482 with full checking for all illegalities specified in the
6483 Ada Reference Manual, but without generation of any object code
6484 (no object file is generated).
6485
6486 Because dependent files must be accessed, you must follow the GNAT
6487 semantic restrictions on file structuring to operate in this mode:
6488
6489 @itemize @bullet
6490 @item
6491 The needed source files must be accessible
6492 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6493
6494 @item
6495 Each file must contain only one compilation unit.
6496
6497 @item
6498 The file name and unit name must match (@pxref{File Naming Rules}).
6499 @end itemize
6500
6501 The output consists of error messages as appropriate. No object file is
6502 generated. An @file{ALI} file is generated for use in the context of
6503 cross-reference tools, but this file is marked as not being suitable
6504 for binding (since no object file is generated).
6505 The checking corresponds exactly to the notion of
6506 legality in the Ada Reference Manual.
6507
6508 Any unit can be compiled in semantics-checking-only mode, including
6509 units that would not normally be compiled (subunits,
6510 and specifications where a separate body is present).
6511 @end table
6512
6513 @node Compiling Different Versions of Ada
6514 @subsection Compiling Different Versions of Ada
6515
6516 @noindent
6517 The switches described in this section allow you to explicitly specify
6518 the version of the Ada language that your programs are written in.
6519 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6520 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6521 indicate Ada 83 compatibility mode.
6522
6523 @table @option
6524 @cindex Compatibility with Ada 83
6525
6526 @item -gnat83 (Ada 83 Compatibility Mode)
6527 @cindex @option{-gnat83} (@command{gcc})
6528 @cindex ACVC, Ada 83 tests
6529 @cindex Ada 83 mode
6530
6531 @noindent
6532 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6533 specifies that the program is to be compiled in Ada 83 mode. With
6534 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6535 semantics where this can be done easily.
6536 It is not possible to guarantee this switch does a perfect
6537 job; some subtle tests, such as are
6538 found in earlier ACVC tests (and that have been removed from the ACATS suite
6539 for Ada 95), might not compile correctly.
6540 Nevertheless, this switch may be useful in some circumstances, for example
6541 where, due to contractual reasons, existing code needs to be maintained
6542 using only Ada 83 features.
6543
6544 With few exceptions (most notably the need to use @code{<>} on
6545 @cindex Generic formal parameters
6546 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6547 reserved words, and the use of packages
6548 with optional bodies), it is not necessary to specify the
6549 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6550 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6551 a correct Ada 83 program is usually also a correct program
6552 in these later versions of the language standard.
6553 For further information, please refer to @ref{Compatibility and Porting Guide}.
6554
6555 @item -gnat95 (Ada 95 mode)
6556 @cindex @option{-gnat95} (@command{gcc})
6557 @cindex Ada 95 mode
6558
6559 @noindent
6560 This switch directs the compiler to implement the Ada 95 version of the
6561 language.
6562 Since Ada 95 is almost completely upwards
6563 compatible with Ada 83, Ada 83 programs may generally be compiled using
6564 this switch (see the description of the @option{-gnat83} switch for further
6565 information about Ada 83 mode).
6566 If an Ada 2005 program is compiled in Ada 95 mode,
6567 uses of the new Ada 2005 features will cause error
6568 messages or warnings.
6569
6570 This switch also can be used to cancel the effect of a previous
6571 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6572
6573 @item -gnat05 (Ada 2005 mode)
6574 @cindex @option{-gnat05} (@command{gcc})
6575 @cindex Ada 2005 mode
6576
6577 @noindent
6578 This switch directs the compiler to implement the Ada 2005 version of the
6579 language.
6580 Since Ada 2005 is almost completely upwards
6581 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6582 may generally be compiled using this switch (see the description of the
6583 @option{-gnat83} and @option{-gnat95} switches for further
6584 information).
6585
6586 For information about the approved ``Ada Issues'' that have been incorporated
6587 into Ada 2005, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6588 Included with GNAT releases is a file @file{features-ada0y} that describes
6589 the set of implemented Ada 2005 features.
6590 @end table
6591
6592
6593 @node Character Set Control
6594 @subsection Character Set Control
6595 @table @option
6596 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6597 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6598
6599 @noindent
6600 Normally GNAT recognizes the Latin-1 character set in source program
6601 identifiers, as described in the Ada Reference Manual.
6602 This switch causes
6603 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6604 single character ^^or word^ indicating the character set, as follows:
6605
6606 @table @code
6607 @item 1
6608 ISO 8859-1 (Latin-1) identifiers
6609
6610 @item 2
6611 ISO 8859-2 (Latin-2) letters allowed in identifiers
6612
6613 @item 3
6614 ISO 8859-3 (Latin-3) letters allowed in identifiers
6615
6616 @item 4
6617 ISO 8859-4 (Latin-4) letters allowed in identifiers
6618
6619 @item 5
6620 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6621
6622 @item 9
6623 ISO 8859-15 (Latin-9) letters allowed in identifiers
6624
6625 @item ^p^PC^
6626 IBM PC letters (code page 437) allowed in identifiers
6627
6628 @item ^8^PC850^
6629 IBM PC letters (code page 850) allowed in identifiers
6630
6631 @item ^f^FULL_UPPER^
6632 Full upper-half codes allowed in identifiers
6633
6634 @item ^n^NO_UPPER^
6635 No upper-half codes allowed in identifiers
6636
6637 @item ^w^WIDE^
6638 Wide-character codes (that is, codes greater than 255)
6639 allowed in identifiers
6640 @end table
6641
6642 @xref{Foreign Language Representation}, for full details on the
6643 implementation of these character sets.
6644
6645 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6646 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6647 Specify the method of encoding for wide characters.
6648 @var{e} is one of the following:
6649
6650 @table @code
6651
6652 @item ^h^HEX^
6653 Hex encoding (brackets coding also recognized)
6654
6655 @item ^u^UPPER^
6656 Upper half encoding (brackets encoding also recognized)
6657
6658 @item ^s^SHIFT_JIS^
6659 Shift/JIS encoding (brackets encoding also recognized)
6660
6661 @item ^e^EUC^
6662 EUC encoding (brackets encoding also recognized)
6663
6664 @item ^8^UTF8^
6665 UTF-8 encoding (brackets encoding also recognized)
6666
6667 @item ^b^BRACKETS^
6668 Brackets encoding only (default value)
6669 @end table
6670 For full details on these encoding
6671 methods see @ref{Wide Character Encodings}.
6672 Note that brackets coding is always accepted, even if one of the other
6673 options is specified, so for example @option{-gnatW8} specifies that both
6674 brackets and UTF-8 encodings will be recognized. The units that are
6675 with'ed directly or indirectly will be scanned using the specified
6676 representation scheme, and so if one of the non-brackets scheme is
6677 used, it must be used consistently throughout the program. However,
6678 since brackets encoding is always recognized, it may be conveniently
6679 used in standard libraries, allowing these libraries to be used with
6680 any of the available coding schemes.
6681 scheme.
6682
6683 If no @option{-gnatW?} parameter is present, then the default
6684 representation is normally Brackets encoding only. However, if the
6685 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6686 byte order mark or BOM for UTF-8), then these three characters are
6687 skipped and the default representation for the file is set to UTF-8.
6688
6689 Note that the wide character representation that is specified (explicitly
6690 or by default) for the main program also acts as the default encoding used
6691 for Wide_Text_IO files if not specifically overridden by a WCEM form
6692 parameter.
6693
6694 @end table
6695 @node File Naming Control
6696 @subsection File Naming Control
6697
6698 @table @option
6699 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6700 @cindex @option{-gnatk} (@command{gcc})
6701 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6702 1-999, indicates the maximum allowable length of a file name (not
6703 including the @file{.ads} or @file{.adb} extension). The default is not
6704 to enable file name krunching.
6705
6706 For the source file naming rules, @xref{File Naming Rules}.
6707 @end table
6708
6709 @node Subprogram Inlining Control
6710 @subsection Subprogram Inlining Control
6711
6712 @table @option
6713 @c !sort!
6714 @item -gnatn
6715 @cindex @option{-gnatn} (@command{gcc})
6716 @ifclear vms
6717 The @code{n} here is intended to suggest the first syllable of the
6718 word ``inline''.
6719 @end ifclear
6720 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6721 inlining to actually occur, optimization must be enabled. To enable
6722 inlining of subprograms specified by pragma @code{Inline},
6723 you must also specify this switch.
6724 In the absence of this switch, GNAT does not attempt
6725 inlining and does not need to access the bodies of
6726 subprograms for which @code{pragma Inline} is specified if they are not
6727 in the current unit.
6728
6729 If you specify this switch the compiler will access these bodies,
6730 creating an extra source dependency for the resulting object file, and
6731 where possible, the call will be inlined.
6732 For further details on when inlining is possible
6733 see @ref{Inlining of Subprograms}.
6734
6735 @item -gnatN
6736 @cindex @option{-gnatN} (@command{gcc})
6737 This switch activates front-end inlining which also
6738 generates additional dependencies.
6739
6740 When using a gcc-based back end (in practice this means using any version
6741 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
6742 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
6743 Historically front end inlining was more extensive than the gcc back end
6744 inlining, but that is no longer the case.
6745 @end table
6746
6747 @node Auxiliary Output Control
6748 @subsection Auxiliary Output Control
6749
6750 @table @option
6751 @item -gnatt
6752 @cindex @option{-gnatt} (@command{gcc})
6753 @cindex Writing internal trees
6754 @cindex Internal trees, writing to file
6755 Causes GNAT to write the internal tree for a unit to a file (with the
6756 extension @file{.adt}.
6757 This not normally required, but is used by separate analysis tools.
6758 Typically
6759 these tools do the necessary compilations automatically, so you should
6760 not have to specify this switch in normal operation.
6761
6762 @item -gnatu
6763 @cindex @option{-gnatu} (@command{gcc})
6764 Print a list of units required by this compilation on @file{stdout}.
6765 The listing includes all units on which the unit being compiled depends
6766 either directly or indirectly.
6767
6768 @ifclear vms
6769 @item -pass-exit-codes
6770 @cindex @option{-pass-exit-codes} (@command{gcc})
6771 If this switch is not used, the exit code returned by @command{gcc} when
6772 compiling multiple files indicates whether all source files have
6773 been successfully used to generate object files or not.
6774
6775 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
6776 exit status and allows an integrated development environment to better
6777 react to a compilation failure. Those exit status are:
6778
6779 @table @asis
6780 @item 5
6781 There was an error in at least one source file.
6782 @item 3
6783 At least one source file did not generate an object file.
6784 @item 2
6785 The compiler died unexpectedly (internal error for example).
6786 @item 0
6787 An object file has been generated for every source file.
6788 @end table
6789 @end ifclear
6790 @end table
6791
6792 @node Debugging Control
6793 @subsection Debugging Control
6794
6795 @table @option
6796 @c !sort!
6797 @cindex Debugging options
6798 @ifclear vms
6799 @item -gnatd@var{x}
6800 @cindex @option{-gnatd} (@command{gcc})
6801 Activate internal debugging switches. @var{x} is a letter or digit, or
6802 string of letters or digits, which specifies the type of debugging
6803 outputs desired. Normally these are used only for internal development
6804 or system debugging purposes. You can find full documentation for these
6805 switches in the body of the @code{Debug} unit in the compiler source
6806 file @file{debug.adb}.
6807 @end ifclear
6808
6809 @item -gnatG[=nn]
6810 @cindex @option{-gnatG} (@command{gcc})
6811 This switch causes the compiler to generate auxiliary output containing
6812 a pseudo-source listing of the generated expanded code. Like most Ada
6813 compilers, GNAT works by first transforming the high level Ada code into
6814 lower level constructs. For example, tasking operations are transformed
6815 into calls to the tasking run-time routines. A unique capability of GNAT
6816 is to list this expanded code in a form very close to normal Ada source.
6817 This is very useful in understanding the implications of various Ada
6818 usage on the efficiency of the generated code. There are many cases in
6819 Ada (e.g.@: the use of controlled types), where simple Ada statements can
6820 generate a lot of run-time code. By using @option{-gnatG} you can identify
6821 these cases, and consider whether it may be desirable to modify the coding
6822 approach to improve efficiency.
6823
6824 The optional parameter @code{nn} if present after -gnatG specifies an
6825 alternative maximum line length that overrides the normal default of 72.
6826 This value is in the range 40-999999, values less than 40 being silently
6827 reset to 40. The equal sign is optional.
6828
6829 The format of the output is very similar to standard Ada source, and is
6830 easily understood by an Ada programmer. The following special syntactic
6831 additions correspond to low level features used in the generated code that
6832 do not have any exact analogies in pure Ada source form. The following
6833 is a partial list of these special constructions. See the spec
6834 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6835
6836 If the switch @option{-gnatL} is used in conjunction with
6837 @cindex @option{-gnatL} (@command{gcc})
6838 @option{-gnatG}, then the original source lines are interspersed
6839 in the expanded source (as comment lines with the original line number).
6840
6841 @table @code
6842 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
6843 Shows the storage pool being used for an allocator.
6844
6845 @item at end @var{procedure-name};
6846 Shows the finalization (cleanup) procedure for a scope.
6847
6848 @item (if @var{expr} then @var{expr} else @var{expr})
6849 Conditional expression equivalent to the @code{x?y:z} construction in C.
6850
6851 @item @var{target}^^^(@var{source})
6852 A conversion with floating-point truncation instead of rounding.
6853
6854 @item @var{target}?(@var{source})
6855 A conversion that bypasses normal Ada semantic checking. In particular
6856 enumeration types and fixed-point types are treated simply as integers.
6857
6858 @item @var{target}?^^^(@var{source})
6859 Combines the above two cases.
6860
6861 @item @var{x} #/ @var{y}
6862 @itemx @var{x} #mod @var{y}
6863 @itemx @var{x} #* @var{y}
6864 @itemx @var{x} #rem @var{y}
6865 A division or multiplication of fixed-point values which are treated as
6866 integers without any kind of scaling.
6867
6868 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
6869 Shows the storage pool associated with a @code{free} statement.
6870
6871 @item [subtype or type declaration]
6872 Used to list an equivalent declaration for an internally generated
6873 type that is referenced elsewhere in the listing.
6874
6875 @item freeze @var{type-name} @ovar{actions}
6876 Shows the point at which @var{type-name} is frozen, with possible
6877 associated actions to be performed at the freeze point.
6878
6879 @item reference @var{itype}
6880 Reference (and hence definition) to internal type @var{itype}.
6881
6882 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6883 Intrinsic function call.
6884
6885 @item @var{label-name} : label
6886 Declaration of label @var{labelname}.
6887
6888 @item #$ @var{subprogram-name}
6889 An implicit call to a run-time support routine
6890 (to meet the requirement of H.3.1(9) in a
6891 convenient manner).
6892
6893 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
6894 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6895 @var{expr}, but handled more efficiently).
6896
6897 @item [constraint_error]
6898 Raise the @code{Constraint_Error} exception.
6899
6900 @item @var{expression}'reference
6901 A pointer to the result of evaluating @var{expression}.
6902
6903 @item @var{target-type}!(@var{source-expression})
6904 An unchecked conversion of @var{source-expression} to @var{target-type}.
6905
6906 @item [@var{numerator}/@var{denominator}]
6907 Used to represent internal real literals (that) have no exact
6908 representation in base 2-16 (for example, the result of compile time
6909 evaluation of the expression 1.0/27.0).
6910 @end table
6911
6912 @item -gnatD[=nn]
6913 @cindex @option{-gnatD} (@command{gcc})
6914 When used in conjunction with @option{-gnatG}, this switch causes
6915 the expanded source, as described above for
6916 @option{-gnatG} to be written to files with names
6917 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6918 instead of to the standard output file. For
6919 example, if the source file name is @file{hello.adb}, then a file
6920 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
6921 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
6922 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6923 you to do source level debugging using the generated code which is
6924 sometimes useful for complex code, for example to find out exactly
6925 which part of a complex construction raised an exception. This switch
6926 also suppress generation of cross-reference information (see
6927 @option{-gnatx}) since otherwise the cross-reference information
6928 would refer to the @file{^.dg^.DG^} file, which would cause
6929 confusion since this is not the original source file.
6930
6931 Note that @option{-gnatD} actually implies @option{-gnatG}
6932 automatically, so it is not necessary to give both options.
6933 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6934
6935 If the switch @option{-gnatL} is used in conjunction with
6936 @cindex @option{-gnatL} (@command{gcc})
6937 @option{-gnatDG}, then the original source lines are interspersed
6938 in the expanded source (as comment lines with the original line number).
6939
6940 The optional parameter @code{nn} if present after -gnatD specifies an
6941 alternative maximum line length that overrides the normal default of 72.
6942 This value is in the range 40-999999, values less than 40 being silently
6943 reset to 40. The equal sign is optional.
6944
6945 @item -gnatr
6946 @cindex @option{-gnatr} (@command{gcc})
6947 @cindex pragma Restrictions
6948 This switch causes pragma Restrictions to be treated as Restriction_Warnings
6949 so that violation of restrictions causes warnings rather than illegalities.
6950 This is useful during the development process when new restrictions are added
6951 or investigated. The switch also causes pragma Profile to be treated as
6952 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
6953 restriction warnings rather than restrictions.
6954
6955 @ifclear vms
6956 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
6957 @cindex @option{-gnatR} (@command{gcc})
6958 This switch controls output from the compiler of a listing showing
6959 representation information for declared types and objects. For
6960 @option{-gnatR0}, no information is output (equivalent to omitting
6961 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6962 so @option{-gnatR} with no parameter has the same effect), size and alignment
6963 information is listed for declared array and record types. For
6964 @option{-gnatR2}, size and alignment information is listed for all
6965 declared types and objects. Finally @option{-gnatR3} includes symbolic
6966 expressions for values that are computed at run time for
6967 variant records. These symbolic expressions have a mostly obvious
6968 format with #n being used to represent the value of the n'th
6969 discriminant. See source files @file{repinfo.ads/adb} in the
6970 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6971 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
6972 the output is to a file with the name @file{^file.rep^file_REP^} where
6973 file is the name of the corresponding source file.
6974 @end ifclear
6975 @ifset vms
6976 @item /REPRESENTATION_INFO
6977 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
6978 This qualifier controls output from the compiler of a listing showing
6979 representation information for declared types and objects. For
6980 @option{/REPRESENTATION_INFO=NONE}, no information is output
6981 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6982 @option{/REPRESENTATION_INFO} without option is equivalent to
6983 @option{/REPRESENTATION_INFO=ARRAYS}.
6984 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6985 information is listed for declared array and record types. For
6986 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6987 is listed for all expression information for values that are computed
6988 at run time for variant records. These symbolic expressions have a mostly
6989 obvious format with #n being used to represent the value of the n'th
6990 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6991 @code{GNAT} sources for full details on the format of
6992 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6993 If _FILE is added at the end of an option
6994 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6995 then the output is to a file with the name @file{file_REP} where
6996 file is the name of the corresponding source file.
6997 @end ifset
6998 Note that it is possible for record components to have zero size. In
6999 this case, the component clause uses an obvious extension of permitted
7000 Ada syntax, for example @code{at 0 range 0 .. -1}.
7001
7002 Representation information requires that code be generated (since it is the
7003 code generator that lays out complex data structures). If an attempt is made
7004 to output representation information when no code is generated, for example
7005 when a subunit is compiled on its own, then no information can be generated
7006 and the compiler outputs a message to this effect.
7007
7008 @item -gnatS
7009 @cindex @option{-gnatS} (@command{gcc})
7010 The use of the switch @option{-gnatS} for an
7011 Ada compilation will cause the compiler to output a
7012 representation of package Standard in a form very
7013 close to standard Ada. It is not quite possible to
7014 do this entirely in standard Ada (since new
7015 numeric base types cannot be created in standard
7016 Ada), but the output is easily
7017 readable to any Ada programmer, and is useful to
7018 determine the characteristics of target dependent
7019 types in package Standard.
7020
7021 @item -gnatx
7022 @cindex @option{-gnatx} (@command{gcc})
7023 Normally the compiler generates full cross-referencing information in
7024 the @file{ALI} file. This information is used by a number of tools,
7025 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7026 suppresses this information. This saves some space and may slightly
7027 speed up compilation, but means that these tools cannot be used.
7028 @end table
7029
7030 @node Exception Handling Control
7031 @subsection Exception Handling Control
7032
7033 @noindent
7034 GNAT uses two methods for handling exceptions at run-time. The
7035 @code{setjmp/longjmp} method saves the context when entering
7036 a frame with an exception handler. Then when an exception is
7037 raised, the context can be restored immediately, without the
7038 need for tracing stack frames. This method provides very fast
7039 exception propagation, but introduces significant overhead for
7040 the use of exception handlers, even if no exception is raised.
7041
7042 The other approach is called ``zero cost'' exception handling.
7043 With this method, the compiler builds static tables to describe
7044 the exception ranges. No dynamic code is required when entering
7045 a frame containing an exception handler. When an exception is
7046 raised, the tables are used to control a back trace of the
7047 subprogram invocation stack to locate the required exception
7048 handler. This method has considerably poorer performance for
7049 the propagation of exceptions, but there is no overhead for
7050 exception handlers if no exception is raised. Note that in this
7051 mode and in the context of mixed Ada and C/C++ programming,
7052 to propagate an exception through a C/C++ code, the C/C++ code
7053 must be compiled with the @option{-funwind-tables} GCC's
7054 option.
7055
7056 The following switches may be used to control which of the
7057 two exception handling methods is used.
7058
7059 @table @option
7060 @c !sort!
7061
7062 @item --RTS=sjlj
7063 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7064 This switch causes the setjmp/longjmp run-time (when available) to be used
7065 for exception handling. If the default
7066 mechanism for the target is zero cost exceptions, then
7067 this switch can be used to modify this default, and must be
7068 used for all units in the partition.
7069 This option is rarely used. One case in which it may be
7070 advantageous is if you have an application where exception
7071 raising is common and the overall performance of the
7072 application is improved by favoring exception propagation.
7073
7074 @item --RTS=zcx
7075 @cindex @option{--RTS=zcx} (@command{gnatmake})
7076 @cindex Zero Cost Exceptions
7077 This switch causes the zero cost approach to be used
7078 for exception handling. If this is the default mechanism for the
7079 target (see below), then this switch is unneeded. If the default
7080 mechanism for the target is setjmp/longjmp exceptions, then
7081 this switch can be used to modify this default, and must be
7082 used for all units in the partition.
7083 This option can only be used if the zero cost approach
7084 is available for the target in use, otherwise it will generate an error.
7085 @end table
7086
7087 @noindent
7088 The same option @option{--RTS} must be used both for @command{gcc}
7089 and @command{gnatbind}. Passing this option to @command{gnatmake}
7090 (@pxref{Switches for gnatmake}) will ensure the required consistency
7091 through the compilation and binding steps.
7092
7093 @node Units to Sources Mapping Files
7094 @subsection Units to Sources Mapping Files
7095
7096 @table @option
7097
7098 @item -gnatem^^=^@var{path}
7099 @cindex @option{-gnatem} (@command{gcc})
7100 A mapping file is a way to communicate to the compiler two mappings:
7101 from unit names to file names (without any directory information) and from
7102 file names to path names (with full directory information). These mappings
7103 are used by the compiler to short-circuit the path search.
7104
7105 The use of mapping files is not required for correct operation of the
7106 compiler, but mapping files can improve efficiency, particularly when
7107 sources are read over a slow network connection. In normal operation,
7108 you need not be concerned with the format or use of mapping files,
7109 and the @option{-gnatem} switch is not a switch that you would use
7110 explicitly. it is intended only for use by automatic tools such as
7111 @command{gnatmake} running under the project file facility. The
7112 description here of the format of mapping files is provided
7113 for completeness and for possible use by other tools.
7114
7115 A mapping file is a sequence of sets of three lines. In each set,
7116 the first line is the unit name, in lower case, with ``@code{%s}''
7117 appended for
7118 specs and ``@code{%b}'' appended for bodies; the second line is the
7119 file name; and the third line is the path name.
7120
7121 Example:
7122 @smallexample
7123    main%b
7124    main.2.ada
7125    /gnat/project1/sources/main.2.ada
7126 @end smallexample
7127
7128 When the switch @option{-gnatem} is specified, the compiler will create
7129 in memory the two mappings from the specified file. If there is any problem
7130 (nonexistent file, truncated file or duplicate entries), no mapping will
7131 be created.
7132
7133 Several @option{-gnatem} switches may be specified; however, only the last
7134 one on the command line will be taken into account.
7135
7136 When using a project file, @command{gnatmake} create a temporary mapping file
7137 and communicates it to the compiler using this switch.
7138
7139 @end table
7140
7141 @node Integrated Preprocessing
7142 @subsection Integrated Preprocessing
7143
7144 @noindent
7145 GNAT sources may be preprocessed immediately before compilation.
7146 In this case, the actual
7147 text of the source is not the text of the source file, but is derived from it
7148 through a process called preprocessing. Integrated preprocessing is specified
7149 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7150 indicates, through a text file, the preprocessing data to be used.
7151 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7152
7153 @noindent
7154 Note that when integrated preprocessing is used, the output from the
7155 preprocessor is not written to any external file. Instead it is passed
7156 internally to the compiler. If you need to preserve the result of
7157 preprocessing in a file, then you should use @command{gnatprep}
7158 to perform the desired preprocessing in stand-alone mode.
7159
7160 @noindent
7161 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7162 used when Integrated Preprocessing is used. The reason is that preprocessing
7163 with another Preprocessing Data file without changing the sources will
7164 not trigger recompilation without this switch.
7165
7166 @noindent
7167 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7168 always trigger recompilation for sources that are preprocessed,
7169 because @command{gnatmake} cannot compute the checksum of the source after
7170 preprocessing.
7171
7172 @noindent
7173 The actual preprocessing function is described in details in section
7174 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7175 preprocessing is triggered and parameterized.
7176
7177 @table @code
7178
7179 @item -gnatep=@var{file}
7180 @cindex @option{-gnatep} (@command{gcc})
7181 This switch indicates to the compiler the file name (without directory
7182 information) of the preprocessor data file to use. The preprocessor data file
7183 should be found in the source directories.
7184
7185 @noindent
7186 A preprocessing data file is a text file with significant lines indicating
7187 how should be preprocessed either a specific source or all sources not
7188 mentioned in other lines. A significant line is a nonempty, non-comment line.
7189 Comments are similar to Ada comments.
7190
7191 @noindent
7192 Each significant line starts with either a literal string or the character '*'.
7193 A literal string is the file name (without directory information) of the source
7194 to preprocess. A character '*' indicates the preprocessing for all the sources
7195 that are not specified explicitly on other lines (order of the lines is not
7196 significant). It is an error to have two lines with the same file name or two
7197 lines starting with the character '*'.
7198
7199 @noindent
7200 After the file name or the character '*', another optional literal string
7201 indicating the file name of the definition file to be used for preprocessing
7202 (@pxref{Form of Definitions File}). The definition files are found by the
7203 compiler in one of the source directories. In some cases, when compiling
7204 a source in a directory other than the current directory, if the definition
7205 file is in the current directory, it may be necessary to add the current
7206 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7207 the compiler would not find the definition file.
7208
7209 @noindent
7210 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7211 be found. Those ^switches^switches^ are:
7212
7213 @table @code
7214
7215 @item -b
7216 Causes both preprocessor lines and the lines deleted by
7217 preprocessing to be replaced by blank lines, preserving the line number.
7218 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7219 it cancels the effect of @option{-c}.
7220
7221 @item -c
7222 Causes both preprocessor lines and the lines deleted
7223 by preprocessing to be retained as comments marked
7224 with the special string ``@code{--! }''.
7225
7226 @item -Dsymbol=value
7227 Define or redefine a symbol, associated with value. A symbol is an Ada
7228 identifier, or an Ada reserved word, with the exception of @code{if},
7229 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7230 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7231 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7232 same name defined in a definition file.
7233
7234 @item -s
7235 Causes a sorted list of symbol names and values to be
7236 listed on the standard output file.
7237
7238 @item -u
7239 Causes undefined symbols to be treated as having the value @code{FALSE}
7240 in the context
7241 of a preprocessor test. In the absence of this option, an undefined symbol in
7242 a @code{#if} or @code{#elsif} test will be treated as an error.
7243
7244 @end table
7245
7246 @noindent
7247 Examples of valid lines in a preprocessor data file:
7248
7249 @smallexample
7250   "toto.adb"  "prep.def" -u
7251   --  preprocess "toto.adb", using definition file "prep.def",
7252   --  undefined symbol are False.
7253
7254   * -c -DVERSION=V101
7255   --  preprocess all other sources without a definition file;
7256   --  suppressed lined are commented; symbol VERSION has the value V101.
7257
7258   "titi.adb" "prep2.def" -s
7259   --  preprocess "titi.adb", using definition file "prep2.def";
7260   --  list all symbols with their values.
7261 @end smallexample
7262
7263 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7264 @cindex @option{-gnateD} (@command{gcc})
7265 Define or redefine a preprocessing symbol, associated with value. If no value
7266 is given on the command line, then the value of the symbol is @code{True}.
7267 A symbol is an identifier, following normal Ada (case-insensitive)
7268 rules for its syntax, and value is any sequence (including an empty sequence)
7269 of characters from the set (letters, digits, period, underline).
7270 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7271 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7272
7273 @noindent
7274 A symbol declared with this ^switch^switch^ on the command line replaces a
7275 symbol with the same name either in a definition file or specified with a
7276 ^switch^switch^ -D in the preprocessor data file.
7277
7278 @noindent
7279 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7280
7281 @item -gnateG
7282 When integrated preprocessing is performed and the preprocessor modifies
7283 the source text, write the result of this preprocessing into a file
7284 <source>^.prep^_prep^.
7285
7286 @end table
7287
7288 @node Code Generation Control
7289 @subsection Code Generation Control
7290
7291 @noindent
7292
7293 The GCC technology provides a wide range of target dependent
7294 @option{-m} switches for controlling
7295 details of code generation with respect to different versions of
7296 architectures. This includes variations in instruction sets (e.g.@:
7297 different members of the power pc family), and different requirements
7298 for optimal arrangement of instructions (e.g.@: different members of
7299 the x86 family). The list of available @option{-m} switches may be
7300 found in the GCC documentation.
7301
7302 Use of these @option{-m} switches may in some cases result in improved
7303 code performance.
7304
7305 The GNAT Pro technology is tested and qualified without any
7306 @option{-m} switches,
7307 so generally the most reliable approach is to avoid the use of these
7308 switches. However, we generally expect most of these switches to work
7309 successfully with GNAT Pro, and many customers have reported successful
7310 use of these options.
7311
7312 Our general advice is to avoid the use of @option{-m} switches unless
7313 special needs lead to requirements in this area. In particular,
7314 there is no point in using @option{-m} switches to improve performance
7315 unless you actually see a performance improvement.
7316
7317 @ifset vms
7318 @node Return Codes
7319 @subsection Return Codes
7320 @cindex Return Codes
7321 @cindex @option{/RETURN_CODES=VMS}
7322
7323 @noindent
7324 On VMS, GNAT compiled programs return POSIX-style codes by default,
7325 e.g.@: @option{/RETURN_CODES=POSIX}.
7326
7327 To enable VMS style return codes, use GNAT BIND and LINK with the option
7328 @option{/RETURN_CODES=VMS}. For example:
7329
7330 @smallexample
7331 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7332 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7333 @end smallexample
7334
7335 @noindent
7336 Programs built with /RETURN_CODES=VMS are suitable to be called in
7337 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7338 are suitable for spawning with appropriate GNAT RTL routines.
7339
7340 @end ifset
7341
7342 @node Search Paths and the Run-Time Library (RTL)
7343 @section Search Paths and the Run-Time Library (RTL)
7344
7345 @noindent
7346 With the GNAT source-based library system, the compiler must be able to
7347 find source files for units that are needed by the unit being compiled.
7348 Search paths are used to guide this process.
7349
7350 The compiler compiles one source file whose name must be given
7351 explicitly on the command line. In other words, no searching is done
7352 for this file. To find all other source files that are needed (the most
7353 common being the specs of units), the compiler examines the following
7354 directories, in the following order:
7355
7356 @enumerate
7357 @item
7358 The directory containing the source file of the main unit being compiled
7359 (the file name on the command line).
7360
7361 @item
7362 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7363 @command{gcc} command line, in the order given.
7364
7365 @item
7366 @findex ADA_PRJ_INCLUDE_FILE
7367 Each of the directories listed in the text file whose name is given
7368 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7369
7370 @noindent
7371 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7372 driver when project files are used. It should not normally be set
7373 by other means.
7374
7375 @item
7376 @findex ADA_INCLUDE_PATH
7377 Each of the directories listed in the value of the
7378 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7379 @ifclear vms
7380 Construct this value
7381 exactly as the @env{PATH} environment variable: a list of directory
7382 names separated by colons (semicolons when working with the NT version).
7383 @end ifclear
7384 @ifset vms
7385 Normally, define this value as a logical name containing a comma separated
7386 list of directory names.
7387
7388 This variable can also be defined by means of an environment string
7389 (an argument to the HP C exec* set of functions).
7390
7391 Logical Name:
7392 @smallexample
7393 DEFINE ANOTHER_PATH FOO:[BAG]
7394 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7395 @end smallexample
7396
7397 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7398 first, followed by the standard Ada
7399 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7400 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7401 (Text_IO, Sequential_IO, etc)
7402 instead of the standard Ada packages. Thus, in order to get the standard Ada
7403 packages by default, ADA_INCLUDE_PATH must be redefined.
7404 @end ifset
7405
7406 @item
7407 The content of the @file{ada_source_path} file which is part of the GNAT
7408 installation tree and is used to store standard libraries such as the
7409 GNAT Run Time Library (RTL) source files.
7410 @ifclear vms
7411 @ref{Installing a library}
7412 @end ifclear
7413 @end enumerate
7414
7415 @noindent
7416 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7417 inhibits the use of the directory
7418 containing the source file named in the command line. You can still
7419 have this directory on your search path, but in this case it must be
7420 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7421
7422 Specifying the switch @option{-nostdinc}
7423 inhibits the search of the default location for the GNAT Run Time
7424 Library (RTL) source files.
7425
7426 The compiler outputs its object files and ALI files in the current
7427 working directory.
7428 @ifclear vms
7429 Caution: The object file can be redirected with the @option{-o} switch;
7430 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7431 so the @file{ALI} file will not go to the right place. Therefore, you should
7432 avoid using the @option{-o} switch.
7433 @end ifclear
7434
7435 @findex System.IO
7436 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7437 children make up the GNAT RTL, together with the simple @code{System.IO}
7438 package used in the @code{"Hello World"} example. The sources for these units
7439 are needed by the compiler and are kept together in one directory. Not
7440 all of the bodies are needed, but all of the sources are kept together
7441 anyway. In a normal installation, you need not specify these directory
7442 names when compiling or binding. Either the environment variables or
7443 the built-in defaults cause these files to be found.
7444
7445 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7446 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7447 consisting of child units of @code{GNAT}. This is a collection of generally
7448 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7449 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7450
7451 Besides simplifying access to the RTL, a major use of search paths is
7452 in compiling sources from multiple directories. This can make
7453 development environments much more flexible.
7454
7455 @node Order of Compilation Issues
7456 @section Order of Compilation Issues
7457
7458 @noindent
7459 If, in our earlier example, there was a spec for the @code{hello}
7460 procedure, it would be contained in the file @file{hello.ads}; yet this
7461 file would not have to be explicitly compiled. This is the result of the
7462 model we chose to implement library management. Some of the consequences
7463 of this model are as follows:
7464
7465 @itemize @bullet
7466 @item
7467 There is no point in compiling specs (except for package
7468 specs with no bodies) because these are compiled as needed by clients. If
7469 you attempt a useless compilation, you will receive an error message.
7470 It is also useless to compile subunits because they are compiled as needed
7471 by the parent.
7472
7473 @item
7474 There are no order of compilation requirements: performing a
7475 compilation never obsoletes anything. The only way you can obsolete
7476 something and require recompilations is to modify one of the
7477 source files on which it depends.
7478
7479 @item
7480 There is no library as such, apart from the ALI files
7481 (@pxref{The Ada Library Information Files}, for information on the format
7482 of these files). For now we find it convenient to create separate ALI files,
7483 but eventually the information therein may be incorporated into the object
7484 file directly.
7485
7486 @item
7487 When you compile a unit, the source files for the specs of all units
7488 that it @code{with}'s, all its subunits, and the bodies of any generics it
7489 instantiates must be available (reachable by the search-paths mechanism
7490 described above), or you will receive a fatal error message.
7491 @end itemize
7492
7493 @node Examples
7494 @section Examples
7495
7496 @noindent
7497 The following are some typical Ada compilation command line examples:
7498
7499 @table @code
7500 @item $ gcc -c xyz.adb
7501 Compile body in file @file{xyz.adb} with all default options.
7502
7503 @ifclear vms
7504 @item $ gcc -c -O2 -gnata xyz-def.adb
7505 @end ifclear
7506 @ifset vms
7507 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7508 @end ifset
7509
7510 Compile the child unit package in file @file{xyz-def.adb} with extensive
7511 optimizations, and pragma @code{Assert}/@code{Debug} statements
7512 enabled.
7513
7514 @item $ gcc -c -gnatc abc-def.adb
7515 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7516 mode.
7517 @end table
7518
7519 @node Binding Using gnatbind
7520 @chapter Binding Using @code{gnatbind}
7521 @findex gnatbind
7522
7523 @menu
7524 * Running gnatbind::
7525 * Switches for gnatbind::
7526 * Command-Line Access::
7527 * Search Paths for gnatbind::
7528 * Examples of gnatbind Usage::
7529 @end menu
7530
7531 @noindent
7532 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7533 to bind compiled GNAT objects.
7534
7535 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7536 driver (see @ref{The GNAT Driver and Project Files}).
7537
7538 The @code{gnatbind} program performs four separate functions:
7539
7540 @enumerate
7541 @item
7542 Checks that a program is consistent, in accordance with the rules in
7543 Chapter 10 of the Ada Reference Manual. In particular, error
7544 messages are generated if a program uses inconsistent versions of a
7545 given unit.
7546
7547 @item
7548 Checks that an acceptable order of elaboration exists for the program
7549 and issues an error message if it cannot find an order of elaboration
7550 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7551
7552 @item
7553 Generates a main program incorporating the given elaboration order.
7554 This program is a small Ada package (body and spec) that
7555 must be subsequently compiled
7556 using the GNAT compiler. The necessary compilation step is usually
7557 performed automatically by @command{gnatlink}. The two most important
7558 functions of this program
7559 are to call the elaboration routines of units in an appropriate order
7560 and to call the main program.
7561
7562 @item
7563 Determines the set of object files required by the given main program.
7564 This information is output in the forms of comments in the generated program,
7565 to be read by the @command{gnatlink} utility used to link the Ada application.
7566 @end enumerate
7567
7568 @node Running gnatbind
7569 @section Running @code{gnatbind}
7570
7571 @noindent
7572 The form of the @code{gnatbind} command is
7573
7574 @smallexample
7575 $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7576 @end smallexample
7577
7578 @noindent
7579 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7580 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
7581 package in two files whose names are
7582 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7583 For example, if given the
7584 parameter @file{hello.ali}, for a main program contained in file
7585 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7586 and @file{b~hello.adb}.
7587
7588 When doing consistency checking, the binder takes into consideration
7589 any source files it can locate. For example, if the binder determines
7590 that the given main program requires the package @code{Pack}, whose
7591 @file{.ALI}
7592 file is @file{pack.ali} and whose corresponding source spec file is
7593 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7594 (using the same search path conventions as previously described for the
7595 @command{gcc} command). If it can locate this source file, it checks that
7596 the time stamps
7597 or source checksums of the source and its references to in @file{ALI} files
7598 match. In other words, any @file{ALI} files that mentions this spec must have
7599 resulted from compiling this version of the source file (or in the case
7600 where the source checksums match, a version close enough that the
7601 difference does not matter).
7602
7603 @cindex Source files, use by binder
7604 The effect of this consistency checking, which includes source files, is
7605 that the binder ensures that the program is consistent with the latest
7606 version of the source files that can be located at bind time. Editing a
7607 source file without compiling files that depend on the source file cause
7608 error messages to be generated by the binder.
7609
7610 For example, suppose you have a main program @file{hello.adb} and a
7611 package @code{P}, from file @file{p.ads} and you perform the following
7612 steps:
7613
7614 @enumerate
7615 @item
7616 Enter @code{gcc -c hello.adb} to compile the main program.
7617
7618 @item
7619 Enter @code{gcc -c p.ads} to compile package @code{P}.
7620
7621 @item
7622 Edit file @file{p.ads}.
7623
7624 @item
7625 Enter @code{gnatbind hello}.
7626 @end enumerate
7627
7628 @noindent
7629 At this point, the file @file{p.ali} contains an out-of-date time stamp
7630 because the file @file{p.ads} has been edited. The attempt at binding
7631 fails, and the binder generates the following error messages:
7632
7633 @smallexample
7634 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7635 error: "p.ads" has been modified and must be recompiled
7636 @end smallexample
7637
7638 @noindent
7639 Now both files must be recompiled as indicated, and then the bind can
7640 succeed, generating a main program. You need not normally be concerned
7641 with the contents of this file, but for reference purposes a sample
7642 binder output file is given in @ref{Example of Binder Output File}.
7643
7644 In most normal usage, the default mode of @command{gnatbind} which is to
7645 generate the main package in Ada, as described in the previous section.
7646 In particular, this means that any Ada programmer can read and understand
7647 the generated main program. It can also be debugged just like any other
7648 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7649 @command{gnatbind} and @command{gnatlink}.
7650
7651 However for some purposes it may be convenient to generate the main
7652 program in C rather than Ada. This may for example be helpful when you
7653 are generating a mixed language program with the main program in C. The
7654 GNAT compiler itself is an example.
7655 The use of the @option{^-C^/BIND_FILE=C^} switch
7656 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7657 be generated in C (and compiled using the gnu C compiler).
7658
7659 @node Switches for gnatbind
7660 @section Switches for @command{gnatbind}
7661
7662 @noindent
7663 The following switches are available with @code{gnatbind}; details will
7664 be presented in subsequent sections.
7665
7666 @menu
7667 * Consistency-Checking Modes::
7668 * Binder Error Message Control::
7669 * Elaboration Control::
7670 * Output Control::
7671 * Binding with Non-Ada Main Programs::
7672 * Binding Programs with No Main Subprogram::
7673 @end menu
7674
7675 @table @option
7676 @c !sort!
7677
7678 @item --version
7679 @cindex @option{--version} @command{gnatbind}
7680 Display Copyright and version, then exit disregarding all other options.
7681
7682 @item --help
7683 @cindex @option{--help} @command{gnatbind}
7684 If @option{--version} was not used, display usage, then exit disregarding
7685 all other options.
7686
7687 @item -a
7688 @cindex @option{-a} @command{gnatbind}
7689 Indicates that, if supported by the platform, the adainit procedure should
7690 be treated as an initialisation routine by the linker (a constructor). This
7691 is intended to be used by the Project Manager to automatically initialize
7692 shared Stand-Alone Libraries.
7693
7694 @item ^-aO^/OBJECT_SEARCH^
7695 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7696 Specify directory to be searched for ALI files.
7697
7698 @item ^-aI^/SOURCE_SEARCH^
7699 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7700 Specify directory to be searched for source file.
7701
7702 @item ^-A^/BIND_FILE=ADA^
7703 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7704 Generate binder program in Ada (default)
7705
7706 @item ^-b^/REPORT_ERRORS=BRIEF^
7707 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
7708 Generate brief messages to @file{stderr} even if verbose mode set.
7709
7710 @item ^-c^/NOOUTPUT^
7711 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
7712 Check only, no generation of binder output file.
7713
7714 @item ^-C^/BIND_FILE=C^
7715 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
7716 Generate binder program in C
7717
7718 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
7719 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
7720 This switch can be used to change the default task stack size value
7721 to a specified size @var{nn}, which is expressed in bytes by default, or
7722 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7723 with @var{m}.
7724 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
7725 in effect, to completing all task specs with
7726 @smallexample @c ada
7727    pragma Storage_Size (nn);
7728 @end smallexample
7729 When they do not already have such a pragma.
7730
7731 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
7732 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
7733 This switch can be used to change the default secondary stack size value
7734 to a specified size @var{nn}, which is expressed in bytes by default, or
7735 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7736 with @var{m}.
7737
7738 The secondary stack is used to deal with functions that return a variable
7739 sized result, for example a function returning an unconstrained
7740 String. There are two ways in which this secondary stack is allocated.
7741
7742 For most targets, the secondary stack is growing on demand and is allocated
7743 as a chain of blocks in the heap. The -D option is not very
7744 relevant. It only give some control over the size of the allocated
7745 blocks (whose size is the minimum of the default secondary stack size value,
7746 and the actual size needed for the current allocation request).
7747
7748 For certain targets, notably VxWorks 653,
7749 the secondary stack is allocated by carving off a fixed ratio chunk of the
7750 primary task stack. The -D option is used to define the
7751 size of the environment task's secondary stack.
7752
7753 @item ^-e^/ELABORATION_DEPENDENCIES^
7754 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
7755 Output complete list of elaboration-order dependencies.
7756
7757 @item ^-E^/STORE_TRACEBACKS^
7758 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
7759 Store tracebacks in exception occurrences when the target supports it.
7760 This is the default with the zero cost exception mechanism.
7761 @ignore
7762 @c The following may get moved to an appendix
7763 This option is currently supported on the following targets:
7764 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
7765 @end ignore
7766 See also the packages @code{GNAT.Traceback} and
7767 @code{GNAT.Traceback.Symbolic} for more information.
7768 @ifclear vms
7769 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
7770 @command{gcc} option.
7771 @end ifclear
7772
7773 @item ^-F^/FORCE_ELABS_FLAGS^
7774 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
7775 Force the checks of elaboration flags. @command{gnatbind} does not normally
7776 generate checks of elaboration flags for the main executable, except when
7777 a Stand-Alone Library is used. However, there are cases when this cannot be
7778 detected by gnatbind. An example is importing an interface of a Stand-Alone
7779 Library through a pragma Import and only specifying through a linker switch
7780 this Stand-Alone Library. This switch is used to guarantee that elaboration
7781 flag checks are generated.
7782
7783 @item ^-h^/HELP^
7784 @cindex @option{^-h^/HELP^} (@command{gnatbind})
7785 Output usage (help) information
7786
7787 @item ^-I^/SEARCH^
7788 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7789 Specify directory to be searched for source and ALI files.
7790
7791 @item ^-I-^/NOCURRENT_DIRECTORY^
7792 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
7793 Do not look for sources in the current directory where @code{gnatbind} was
7794 invoked, and do not look for ALI files in the directory containing the
7795 ALI file named in the @code{gnatbind} command line.
7796
7797 @item ^-l^/ORDER_OF_ELABORATION^
7798 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
7799 Output chosen elaboration order.
7800
7801 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
7802 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7803 Bind the units for library building. In this case the adainit and
7804 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
7805 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
7806 ^@var{xxx}final^@var{XXX}FINAL^.
7807 Implies ^-n^/NOCOMPILE^.
7808 @ifclear vms
7809 (@xref{GNAT and Libraries}, for more details.)
7810 @end ifclear
7811 @ifset vms
7812 On OpenVMS, these init and final procedures are exported in uppercase
7813 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
7814 the init procedure will be "TOTOINIT" and the exported name of the final
7815 procedure will be "TOTOFINAL".
7816 @end ifset
7817
7818 @item ^-Mxyz^/RENAME_MAIN=xyz^
7819 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
7820 Rename generated main program from main to xyz. This option is
7821 supported on cross environments only.
7822
7823 @item ^-m^/ERROR_LIMIT=^@var{n}
7824 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
7825 Limit number of detected errors or warnings to @var{n}, where @var{n} is
7826 in the range 1..999999. The default value if no switch is
7827 given is 9999. If the number of warnings reaches this limit, then a
7828 message is output and further warnings are suppressed, the bind
7829 continues in this case. If the number of errors reaches this
7830 limit, then a message is output and the bind is abandoned.
7831 A value of zero means that no limit is enforced. The equal
7832 sign is optional.
7833
7834 @ifset unw
7835 Furthermore, under Windows, the sources pointed to by the libraries path
7836 set in the registry are not searched for.
7837 @end ifset
7838
7839 @item ^-n^/NOMAIN^
7840 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7841 No main program.
7842
7843 @item -nostdinc
7844 @cindex @option{-nostdinc} (@command{gnatbind})
7845 Do not look for sources in the system default directory.
7846
7847 @item -nostdlib
7848 @cindex @option{-nostdlib} (@command{gnatbind})
7849 Do not look for library files in the system default directory.
7850
7851 @item --RTS=@var{rts-path}
7852 @cindex @option{--RTS} (@code{gnatbind})
7853 Specifies the default location of the runtime library. Same meaning as the
7854 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
7855
7856 @item ^-o ^/OUTPUT=^@var{file}
7857 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7858 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7859 Note that if this option is used, then linking must be done manually,
7860 gnatlink cannot be used.
7861
7862 @item ^-O^/OBJECT_LIST^
7863 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7864 Output object list.
7865
7866 @item ^-p^/PESSIMISTIC_ELABORATION^
7867 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7868 Pessimistic (worst-case) elaboration order
7869
7870 @item ^-R^-R^
7871 @cindex @option{^-R^-R^} (@command{gnatbind})
7872 Output closure source list.
7873
7874 @item ^-s^/READ_SOURCES=ALL^
7875 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7876 Require all source files to be present.
7877
7878 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7879 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7880 Specifies the value to be used when detecting uninitialized scalar
7881 objects with pragma Initialize_Scalars.
7882 The @var{xxx} ^string specified with the switch^option^ may be either
7883 @itemize @bullet
7884 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7885 @item ``@option{^lo^LOW^}'' for the lowest possible value
7886 @item ``@option{^hi^HIGH^}'' for the highest possible value
7887 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
7888 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
7889 @end itemize
7890
7891 In addition, you can specify @option{-Sev} to indicate that the value is
7892 to be set at run time. In this case, the program will look for an environment
7893 @cindex GNAT_INIT_SCALARS
7894 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
7895 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
7896 If no environment variable is found, or if it does not have a valid value,
7897 then the default is @option{in} (invalid values).
7898
7899 @ifclear vms
7900 @item -static
7901 @cindex @option{-static} (@code{gnatbind})
7902 Link against a static GNAT run time.
7903
7904 @item -shared
7905 @cindex @option{-shared} (@code{gnatbind})
7906 Link against a shared GNAT run time when available.
7907 @end ifclear
7908
7909 @item ^-t^/NOTIME_STAMP_CHECK^
7910 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7911 Tolerate time stamp and other consistency errors
7912
7913 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7914 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7915 Set the time slice value to @var{n} milliseconds. If the system supports
7916 the specification of a specific time slice value, then the indicated value
7917 is used. If the system does not support specific time slice values, but
7918 does support some general notion of round-robin scheduling, then any
7919 nonzero value will activate round-robin scheduling.
7920
7921 A value of zero is treated specially. It turns off time
7922 slicing, and in addition, indicates to the tasking run time that the
7923 semantics should match as closely as possible the Annex D
7924 requirements of the Ada RM, and in particular sets the default
7925 scheduling policy to @code{FIFO_Within_Priorities}.
7926
7927 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
7928 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
7929 Enable dynamic stack usage, with @var{n} results stored and displayed
7930 at program termination. A result is generated when a task
7931 terminates. Results that can't be stored are displayed on the fly, at
7932 task termination. This option is currently not supported on Itanium
7933 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
7934
7935 @item ^-v^/REPORT_ERRORS=VERBOSE^
7936 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7937 Verbose mode. Write error messages, header, summary output to
7938 @file{stdout}.
7939
7940 @ifclear vms
7941 @item -w@var{x}
7942 @cindex @option{-w} (@code{gnatbind})
7943 Warning mode (@var{x}=s/e for suppress/treat as error)
7944 @end ifclear
7945
7946 @ifset vms
7947 @item /WARNINGS=NORMAL
7948 @cindex @option{/WARNINGS} (@code{gnatbind})
7949 Normal warnings mode. Warnings are issued but ignored
7950
7951 @item /WARNINGS=SUPPRESS
7952 @cindex @option{/WARNINGS} (@code{gnatbind})
7953 All warning messages are suppressed
7954
7955 @item /WARNINGS=ERROR
7956 @cindex @option{/WARNINGS} (@code{gnatbind})
7957 Warning messages are treated as fatal errors
7958 @end ifset
7959
7960 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
7961 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
7962 Override default wide character encoding for standard Text_IO files.
7963
7964 @item ^-x^/READ_SOURCES=NONE^
7965 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7966 Exclude source files (check object consistency only).
7967
7968 @ifset vms
7969 @item /READ_SOURCES=AVAILABLE
7970 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7971 Default mode, in which sources are checked for consistency only if
7972 they are available.
7973 @end ifset
7974
7975 @item ^-y^/ENABLE_LEAP_SECONDS^
7976 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
7977 Enable leap seconds support in @code{Ada.Calendar} and its children.
7978
7979 @item ^-z^/ZERO_MAIN^
7980 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7981 No main subprogram.
7982 @end table
7983
7984 @ifclear vms
7985 @noindent
7986 You may obtain this listing of switches by running @code{gnatbind} with
7987 no arguments.
7988 @end ifclear
7989
7990 @node Consistency-Checking Modes
7991 @subsection Consistency-Checking Modes
7992
7993 @noindent
7994 As described earlier, by default @code{gnatbind} checks
7995 that object files are consistent with one another and are consistent
7996 with any source files it can locate. The following switches control binder
7997 access to sources.
7998
7999 @table @option
8000 @c !sort!
8001 @item ^-s^/READ_SOURCES=ALL^
8002 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8003 Require source files to be present. In this mode, the binder must be
8004 able to locate all source files that are referenced, in order to check
8005 their consistency. In normal mode, if a source file cannot be located it
8006 is simply ignored. If you specify this switch, a missing source
8007 file is an error.
8008
8009 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8010 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8011 Override default wide character encoding for standard Text_IO files.
8012 Normally the default wide character encoding method used for standard
8013 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8014 the main source input (see description of switch
8015 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8016 use of this switch for the binder (which has the same set of
8017 possible arguments) overrides this default as specified.
8018
8019 @item ^-x^/READ_SOURCES=NONE^
8020 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8021 Exclude source files. In this mode, the binder only checks that ALI
8022 files are consistent with one another. Source files are not accessed.
8023 The binder runs faster in this mode, and there is still a guarantee that
8024 the resulting program is self-consistent.
8025 If a source file has been edited since it was last compiled, and you
8026 specify this switch, the binder will not detect that the object
8027 file is out of date with respect to the source file. Note that this is the
8028 mode that is automatically used by @command{gnatmake} because in this
8029 case the checking against sources has already been performed by
8030 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8031
8032 @ifset vms
8033 @item /READ_SOURCES=AVAILABLE
8034 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8035 This is the default mode in which source files are checked if they are
8036 available, and ignored if they are not available.
8037 @end ifset
8038 @end table
8039
8040 @node Binder Error Message Control
8041 @subsection Binder Error Message Control
8042
8043 @noindent
8044 The following switches provide control over the generation of error
8045 messages from the binder:
8046
8047 @table @option
8048 @c !sort!
8049 @item ^-v^/REPORT_ERRORS=VERBOSE^
8050 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8051 Verbose mode. In the normal mode, brief error messages are generated to
8052 @file{stderr}. If this switch is present, a header is written
8053 to @file{stdout} and any error messages are directed to @file{stdout}.
8054 All that is written to @file{stderr} is a brief summary message.
8055
8056 @item ^-b^/REPORT_ERRORS=BRIEF^
8057 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8058 Generate brief error messages to @file{stderr} even if verbose mode is
8059 specified. This is relevant only when used with the
8060 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8061
8062 @ifclear vms
8063 @item -m@var{n}
8064 @cindex @option{-m} (@code{gnatbind})
8065 Limits the number of error messages to @var{n}, a decimal integer in the
8066 range 1-999. The binder terminates immediately if this limit is reached.
8067
8068 @item -M@var{xxx}
8069 @cindex @option{-M} (@code{gnatbind})
8070 Renames the generated main program from @code{main} to @code{xxx}.
8071 This is useful in the case of some cross-building environments, where
8072 the actual main program is separate from the one generated
8073 by @code{gnatbind}.
8074 @end ifclear
8075
8076 @item ^-ws^/WARNINGS=SUPPRESS^
8077 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8078 @cindex Warnings
8079 Suppress all warning messages.
8080
8081 @item ^-we^/WARNINGS=ERROR^
8082 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8083 Treat any warning messages as fatal errors.
8084
8085 @ifset vms
8086 @item /WARNINGS=NORMAL
8087 Standard mode with warnings generated, but warnings do not get treated
8088 as errors.
8089 @end ifset
8090
8091 @item ^-t^/NOTIME_STAMP_CHECK^
8092 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8093 @cindex Time stamp checks, in binder
8094 @cindex Binder consistency checks
8095 @cindex Consistency checks, in binder
8096 The binder performs a number of consistency checks including:
8097
8098 @itemize @bullet
8099 @item
8100 Check that time stamps of a given source unit are consistent
8101 @item
8102 Check that checksums of a given source unit are consistent
8103 @item
8104 Check that consistent versions of @code{GNAT} were used for compilation
8105 @item
8106 Check consistency of configuration pragmas as required
8107 @end itemize
8108
8109 @noindent
8110 Normally failure of such checks, in accordance with the consistency
8111 requirements of the Ada Reference Manual, causes error messages to be
8112 generated which abort the binder and prevent the output of a binder
8113 file and subsequent link to obtain an executable.
8114
8115 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8116 into warnings, so that
8117 binding and linking can continue to completion even in the presence of such
8118 errors. The result may be a failed link (due to missing symbols), or a
8119 non-functional executable which has undefined semantics.
8120 @emph{This means that
8121 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8122 with extreme care.}
8123 @end table
8124
8125 @node Elaboration Control
8126 @subsection Elaboration Control
8127
8128 @noindent
8129 The following switches provide additional control over the elaboration
8130 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8131
8132 @table @option
8133 @item ^-p^/PESSIMISTIC_ELABORATION^
8134 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8135 Normally the binder attempts to choose an elaboration order that is
8136 likely to minimize the likelihood of an elaboration order error resulting
8137 in raising a @code{Program_Error} exception. This switch reverses the
8138 action of the binder, and requests that it deliberately choose an order
8139 that is likely to maximize the likelihood of an elaboration error.
8140 This is useful in ensuring portability and avoiding dependence on
8141 accidental fortuitous elaboration ordering.
8142
8143 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8144 switch if dynamic
8145 elaboration checking is used (@option{-gnatE} switch used for compilation).
8146 This is because in the default static elaboration mode, all necessary
8147 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8148 These implicit pragmas are still respected by the binder in
8149 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8150 safe elaboration order is assured.
8151 @end table
8152
8153 @node Output Control
8154 @subsection Output Control
8155
8156 @noindent
8157 The following switches allow additional control over the output
8158 generated by the binder.
8159
8160 @table @option
8161 @c !sort!
8162
8163 @item ^-A^/BIND_FILE=ADA^
8164 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
8165 Generate binder program in Ada (default). The binder program is named
8166 @file{b~@var{mainprog}.adb} by default. This can be changed with
8167 @option{^-o^/OUTPUT^} @code{gnatbind} option.
8168
8169 @item ^-c^/NOOUTPUT^
8170 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8171 Check only. Do not generate the binder output file. In this mode the
8172 binder performs all error checks but does not generate an output file.
8173
8174 @item ^-C^/BIND_FILE=C^
8175 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
8176 Generate binder program in C. The binder program is named
8177 @file{b_@var{mainprog}.c}.
8178 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
8179 option.
8180
8181 @item ^-e^/ELABORATION_DEPENDENCIES^
8182 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8183 Output complete list of elaboration-order dependencies, showing the
8184 reason for each dependency. This output can be rather extensive but may
8185 be useful in diagnosing problems with elaboration order. The output is
8186 written to @file{stdout}.
8187
8188 @item ^-h^/HELP^
8189 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8190 Output usage information. The output is written to @file{stdout}.
8191
8192 @item ^-K^/LINKER_OPTION_LIST^
8193 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8194 Output linker options to @file{stdout}. Includes library search paths,
8195 contents of pragmas Ident and Linker_Options, and libraries added
8196 by @code{gnatbind}.
8197
8198 @item ^-l^/ORDER_OF_ELABORATION^
8199 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8200 Output chosen elaboration order. The output is written to @file{stdout}.
8201
8202 @item ^-O^/OBJECT_LIST^
8203 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8204 Output full names of all the object files that must be linked to provide
8205 the Ada component of the program. The output is written to @file{stdout}.
8206 This list includes the files explicitly supplied and referenced by the user
8207 as well as implicitly referenced run-time unit files. The latter are
8208 omitted if the corresponding units reside in shared libraries. The
8209 directory names for the run-time units depend on the system configuration.
8210
8211 @item ^-o ^/OUTPUT=^@var{file}
8212 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8213 Set name of output file to @var{file} instead of the normal
8214 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8215 binder generated body filename. In C mode you would normally give
8216 @var{file} an extension of @file{.c} because it will be a C source program.
8217 Note that if this option is used, then linking must be done manually.
8218 It is not possible to use gnatlink in this case, since it cannot locate
8219 the binder file.
8220
8221 @item ^-r^/RESTRICTION_LIST^
8222 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8223 Generate list of @code{pragma Restrictions} that could be applied to
8224 the current unit. This is useful for code audit purposes, and also may
8225 be used to improve code generation in some cases.
8226
8227 @end table
8228
8229 @node Binding with Non-Ada Main Programs
8230 @subsection Binding with Non-Ada Main Programs
8231
8232 @noindent
8233 In our description so far we have assumed that the main
8234 program is in Ada, and that the task of the binder is to generate a
8235 corresponding function @code{main} that invokes this Ada main
8236 program. GNAT also supports the building of executable programs where
8237 the main program is not in Ada, but some of the called routines are
8238 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8239 The following switch is used in this situation:
8240
8241 @table @option
8242 @item ^-n^/NOMAIN^
8243 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8244 No main program. The main program is not in Ada.
8245 @end table
8246
8247 @noindent
8248 In this case, most of the functions of the binder are still required,
8249 but instead of generating a main program, the binder generates a file
8250 containing the following callable routines:
8251
8252 @table @code
8253 @item adainit
8254 @findex adainit
8255 You must call this routine to initialize the Ada part of the program by
8256 calling the necessary elaboration routines. A call to @code{adainit} is
8257 required before the first call to an Ada subprogram.
8258
8259 Note that it is assumed that the basic execution environment must be setup
8260 to be appropriate for Ada execution at the point where the first Ada
8261 subprogram is called. In particular, if the Ada code will do any
8262 floating-point operations, then the FPU must be setup in an appropriate
8263 manner. For the case of the x86, for example, full precision mode is
8264 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8265 that the FPU is in the right state.
8266
8267 @item adafinal
8268 @findex adafinal
8269 You must call this routine to perform any library-level finalization
8270 required by the Ada subprograms. A call to @code{adafinal} is required
8271 after the last call to an Ada subprogram, and before the program
8272 terminates.
8273 @end table
8274
8275 @noindent
8276 If the @option{^-n^/NOMAIN^} switch
8277 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8278 @cindex Binder, multiple input files
8279 is given, more than one ALI file may appear on
8280 the command line for @code{gnatbind}. The normal @dfn{closure}
8281 calculation is performed for each of the specified units. Calculating
8282 the closure means finding out the set of units involved by tracing
8283 @code{with} references. The reason it is necessary to be able to
8284 specify more than one ALI file is that a given program may invoke two or
8285 more quite separate groups of Ada units.
8286
8287 The binder takes the name of its output file from the last specified ALI
8288 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8289 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8290 The output is an Ada unit in source form that can
8291 be compiled with GNAT unless the -C switch is used in which case the
8292 output is a C source file, which must be compiled using the C compiler.
8293 This compilation occurs automatically as part of the @command{gnatlink}
8294 processing.
8295
8296 Currently the GNAT run time requires a FPU using 80 bits mode
8297 precision. Under targets where this is not the default it is required to
8298 call GNAT.Float_Control.Reset before using floating point numbers (this
8299 include float computation, float input and output) in the Ada code. A
8300 side effect is that this could be the wrong mode for the foreign code
8301 where floating point computation could be broken after this call.
8302
8303 @node Binding Programs with No Main Subprogram
8304 @subsection Binding Programs with No Main Subprogram
8305
8306 @noindent
8307 It is possible to have an Ada program which does not have a main
8308 subprogram. This program will call the elaboration routines of all the
8309 packages, then the finalization routines.
8310
8311 The following switch is used to bind programs organized in this manner:
8312
8313 @table @option
8314 @item ^-z^/ZERO_MAIN^
8315 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8316 Normally the binder checks that the unit name given on the command line
8317 corresponds to a suitable main subprogram. When this switch is used,
8318 a list of ALI files can be given, and the execution of the program
8319 consists of elaboration of these units in an appropriate order. Note
8320 that the default wide character encoding method for standard Text_IO
8321 files is always set to Brackets if this switch is set (you can use
8322 the binder switch
8323 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8324 @end table
8325
8326 @node Command-Line Access
8327 @section Command-Line Access
8328
8329 @noindent
8330 The package @code{Ada.Command_Line} provides access to the command-line
8331 arguments and program name. In order for this interface to operate
8332 correctly, the two variables
8333
8334 @smallexample
8335 @group
8336 int gnat_argc;
8337 char **gnat_argv;
8338 @end group
8339 @end smallexample
8340
8341 @noindent
8342 @findex gnat_argv
8343 @findex gnat_argc
8344 are declared in one of the GNAT library routines. These variables must
8345 be set from the actual @code{argc} and @code{argv} values passed to the
8346 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8347 generates the C main program to automatically set these variables.
8348 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8349 set these variables. If they are not set, the procedures in
8350 @code{Ada.Command_Line} will not be available, and any attempt to use
8351 them will raise @code{Constraint_Error}. If command line access is
8352 required, your main program must set @code{gnat_argc} and
8353 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8354 it.
8355
8356 @node Search Paths for gnatbind
8357 @section Search Paths for @code{gnatbind}
8358
8359 @noindent
8360 The binder takes the name of an ALI file as its argument and needs to
8361 locate source files as well as other ALI files to verify object consistency.
8362
8363 For source files, it follows exactly the same search rules as @command{gcc}
8364 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8365 directories searched are:
8366
8367 @enumerate
8368 @item
8369 The directory containing the ALI file named in the command line, unless
8370 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8371
8372 @item
8373 All directories specified by @option{^-I^/SEARCH^}
8374 switches on the @code{gnatbind}
8375 command line, in the order given.
8376
8377 @item
8378 @findex ADA_PRJ_OBJECTS_FILE
8379 Each of the directories listed in the text file whose name is given
8380 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8381
8382 @noindent
8383 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8384 driver when project files are used. It should not normally be set
8385 by other means.
8386
8387 @item
8388 @findex ADA_OBJECTS_PATH
8389 Each of the directories listed in the value of the
8390 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8391 @ifset unw
8392 Construct this value
8393 exactly as the @env{PATH} environment variable: a list of directory
8394 names separated by colons (semicolons when working with the NT version
8395 of GNAT).
8396 @end ifset
8397 @ifset vms
8398 Normally, define this value as a logical name containing a comma separated
8399 list of directory names.
8400
8401 This variable can also be defined by means of an environment string
8402 (an argument to the HP C exec* set of functions).
8403
8404 Logical Name:
8405 @smallexample
8406 DEFINE ANOTHER_PATH FOO:[BAG]
8407 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8408 @end smallexample
8409
8410 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8411 first, followed by the standard Ada
8412 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8413 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8414 (Text_IO, Sequential_IO, etc)
8415 instead of the standard Ada packages. Thus, in order to get the standard Ada
8416 packages by default, ADA_OBJECTS_PATH must be redefined.
8417 @end ifset
8418
8419 @item
8420 The content of the @file{ada_object_path} file which is part of the GNAT
8421 installation tree and is used to store standard libraries such as the
8422 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8423 specified.
8424 @ifclear vms
8425 @ref{Installing a library}
8426 @end ifclear
8427 @end enumerate
8428
8429 @noindent
8430 In the binder the switch @option{^-I^/SEARCH^}
8431 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8432 is used to specify both source and
8433 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8434 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8435 instead if you want to specify
8436 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8437 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8438 if you want to specify library paths
8439 only. This means that for the binder
8440 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8441 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8442 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8443 The binder generates the bind file (a C language source file) in the
8444 current working directory.
8445
8446 @findex Ada
8447 @findex System
8448 @findex Interfaces
8449 @findex GNAT
8450 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8451 children make up the GNAT Run-Time Library, together with the package
8452 GNAT and its children, which contain a set of useful additional
8453 library functions provided by GNAT. The sources for these units are
8454 needed by the compiler and are kept together in one directory. The ALI
8455 files and object files generated by compiling the RTL are needed by the
8456 binder and the linker and are kept together in one directory, typically
8457 different from the directory containing the sources. In a normal
8458 installation, you need not specify these directory names when compiling
8459 or binding. Either the environment variables or the built-in defaults
8460 cause these files to be found.
8461
8462 Besides simplifying access to the RTL, a major use of search paths is
8463 in compiling sources from multiple directories. This can make
8464 development environments much more flexible.
8465
8466 @node Examples of gnatbind Usage
8467 @section Examples of @code{gnatbind} Usage
8468
8469 @noindent
8470 This section contains a number of examples of using the GNAT binding
8471 utility @code{gnatbind}.
8472
8473 @table @code
8474 @item gnatbind hello
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{b~hello.adb}. This is the normal, default use of the binder.
8478
8479 @ifclear vms
8480 @item gnatbind hello -o mainprog.adb
8481 @end ifclear
8482 @ifset vms
8483 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8484 @end ifset
8485 The main program @code{Hello} (source program in @file{hello.adb}) is
8486 bound using the standard switch settings. The generated main program is
8487 @file{mainprog.adb} with the associated spec in
8488 @file{mainprog.ads}. Note that you must specify the body here not the
8489 spec, in the case where the output is in Ada. Note that if this option
8490 is used, then linking must be done manually, since gnatlink will not
8491 be able to find the generated file.
8492
8493 @ifclear vms
8494 @item gnatbind main -C -o mainprog.c -x
8495 @end ifclear
8496 @ifset vms
8497 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
8498 @end ifset
8499 The main program @code{Main} (source program in
8500 @file{main.adb}) is bound, excluding source files from the
8501 consistency checking, generating
8502 the file @file{mainprog.c}.
8503
8504 @ifclear vms
8505 @item gnatbind -x main_program -C -o mainprog.c
8506 This command is exactly the same as the previous example. Switches may
8507 appear anywhere in the command line, and single letter switches may be
8508 combined into a single switch.
8509 @end ifclear
8510
8511 @ifclear vms
8512 @item gnatbind -n math dbase -C -o ada-control.c
8513 @end ifclear
8514 @ifset vms
8515 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
8516 @end ifset
8517 The main program is in a language other than Ada, but calls to
8518 subprograms in packages @code{Math} and @code{Dbase} appear. This call
8519 to @code{gnatbind} generates the file @file{ada-control.c} containing
8520 the @code{adainit} and @code{adafinal} routines to be called before and
8521 after accessing the Ada units.
8522 @end table
8523
8524 @c ------------------------------------
8525 @node Linking Using gnatlink
8526 @chapter Linking Using @command{gnatlink}
8527 @c ------------------------------------
8528 @findex gnatlink
8529
8530 @noindent
8531 This chapter discusses @command{gnatlink}, a tool that links
8532 an Ada program and builds an executable file. This utility
8533 invokes the system linker ^(via the @command{gcc} command)^^
8534 with a correct list of object files and library references.
8535 @command{gnatlink} automatically determines the list of files and
8536 references for the Ada part of a program. It uses the binder file
8537 generated by the @command{gnatbind} to determine this list.
8538
8539 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8540 driver (see @ref{The GNAT Driver and Project Files}).
8541
8542 @menu
8543 * Running gnatlink::
8544 * Switches for gnatlink::
8545 @end menu
8546
8547 @node Running gnatlink
8548 @section Running @command{gnatlink}
8549
8550 @noindent
8551 The form of the @command{gnatlink} command is
8552
8553 @smallexample
8554 $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8555            @ovar{non-Ada objects} @ovar{linker options}
8556 @end smallexample
8557
8558 @noindent
8559 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8560 non-Ada objects
8561 or linker options) may be in any order, provided that no non-Ada object may
8562 be mistaken for a main @file{ALI} file.
8563 Any file name @file{F} without the @file{.ali}
8564 extension will be taken as the main @file{ALI} file if a file exists
8565 whose name is the concatenation of @file{F} and @file{.ali}.
8566
8567 @noindent
8568 @file{@var{mainprog}.ali} references the ALI file of the main program.
8569 The @file{.ali} extension of this file can be omitted. From this
8570 reference, @command{gnatlink} locates the corresponding binder file
8571 @file{b~@var{mainprog}.adb} and, using the information in this file along
8572 with the list of non-Ada objects and linker options, constructs a
8573 linker command file to create the executable.
8574
8575 The arguments other than the @command{gnatlink} switches and the main
8576 @file{ALI} file are passed to the linker uninterpreted.
8577 They typically include the names of
8578 object files for units written in other languages than Ada and any library
8579 references required to resolve references in any of these foreign language
8580 units, or in @code{Import} pragmas in any Ada units.
8581
8582 @var{linker options} is an optional list of linker specific
8583 switches.
8584 The default linker called by gnatlink is @command{gcc} which in
8585 turn calls the appropriate system linker.
8586 Standard options for the linker such as @option{-lmy_lib} or
8587 @option{-Ldir} can be added as is.
8588 For options that are not recognized by
8589 @command{gcc} as linker options, use the @command{gcc} switches
8590 @option{-Xlinker} or @option{-Wl,}.
8591 Refer to the GCC documentation for
8592 details. Here is an example showing how to generate a linker map:
8593
8594 @smallexample
8595 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8596 @end smallexample
8597
8598 Using @var{linker options} it is possible to set the program stack and
8599 heap size.
8600 @ifset unw
8601 See @ref{Setting Stack Size from gnatlink} and
8602 @ref{Setting Heap Size from gnatlink}.
8603 @end ifset
8604
8605 @command{gnatlink} determines the list of objects required by the Ada
8606 program and prepends them to the list of objects passed to the linker.
8607 @command{gnatlink} also gathers any arguments set by the use of
8608 @code{pragma Linker_Options} and adds them to the list of arguments
8609 presented to the linker.
8610
8611 @ifset vms
8612 @command{gnatlink} accepts the following types of extra files on the command
8613 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8614 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8615 handled according to their extension.
8616 @end ifset
8617
8618 @node Switches for gnatlink
8619 @section Switches for @command{gnatlink}
8620
8621 @noindent
8622 The following switches are available with the @command{gnatlink} utility:
8623
8624 @table @option
8625 @c !sort!
8626
8627 @item --version
8628 @cindex @option{--version} @command{gnatlink}
8629 Display Copyright and version, then exit disregarding all other options.
8630
8631 @item --help
8632 @cindex @option{--help} @command{gnatlink}
8633 If @option{--version} was not used, display usage, then exit disregarding
8634 all other options.
8635
8636 @item ^-A^/BIND_FILE=ADA^
8637 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
8638 The binder has generated code in Ada. This is the default.
8639
8640 @item ^-C^/BIND_FILE=C^
8641 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
8642 If instead of generating a file in Ada, the binder has generated one in
8643 C, then the linker needs to know about it. Use this switch to signal
8644 to @command{gnatlink} that the binder has generated C code rather than
8645 Ada code.
8646
8647 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8648 @cindex Command line length
8649 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8650 On some targets, the command line length is limited, and @command{gnatlink}
8651 will generate a separate file for the linker if the list of object files
8652 is too long.
8653 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8654 to be generated even if
8655 the limit is not exceeded. This is useful in some cases to deal with
8656 special situations where the command line length is exceeded.
8657
8658 @item ^-g^/DEBUG^
8659 @cindex Debugging information, including
8660 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8661 The option to include debugging information causes the Ada bind file (in
8662 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8663 @option{^-g^/DEBUG^}.
8664 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8665 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8666 Without @option{^-g^/DEBUG^}, the binder removes these files by
8667 default. The same procedure apply if a C bind file was generated using
8668 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8669 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8670
8671 @item ^-n^/NOCOMPILE^
8672 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8673 Do not compile the file generated by the binder. This may be used when
8674 a link is rerun with different options, but there is no need to recompile
8675 the binder file.
8676
8677 @item ^-v^/VERBOSE^
8678 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8679 Causes additional information to be output, including a full list of the
8680 included object files. This switch option is most useful when you want
8681 to see what set of object files are being used in the link step.
8682
8683 @item ^-v -v^/VERBOSE/VERBOSE^
8684 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8685 Very verbose mode. Requests that the compiler operate in verbose mode when
8686 it compiles the binder file, and that the system linker run in verbose mode.
8687
8688 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8689 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8690 @var{exec-name} specifies an alternate name for the generated
8691 executable program. If this switch is omitted, the executable has the same
8692 name as the main unit. For example, @code{gnatlink try.ali} creates
8693 an executable called @file{^try^TRY.EXE^}.
8694
8695 @ifclear vms
8696 @item -b @var{target}
8697 @cindex @option{-b} (@command{gnatlink})
8698 Compile your program to run on @var{target}, which is the name of a
8699 system configuration. You must have a GNAT cross-compiler built if
8700 @var{target} is not the same as your host system.
8701
8702 @item -B@var{dir}
8703 @cindex @option{-B} (@command{gnatlink})
8704 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8705 from @var{dir} instead of the default location. Only use this switch
8706 when multiple versions of the GNAT compiler are available.
8707 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
8708 for further details. You would normally use the @option{-b} or
8709 @option{-V} switch instead.
8710
8711 @item --GCC=@var{compiler_name}
8712 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8713 Program used for compiling the binder file. The default is
8714 @command{gcc}. You need to use quotes around @var{compiler_name} if
8715 @code{compiler_name} contains spaces or other separator characters.
8716 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8717 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8718 inserted after your command name. Thus in the above example the compiler
8719 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8720 A limitation of this syntax is that the name and path name of the executable
8721 itself must not include any embedded spaces. If the compiler executable is
8722 different from the default one (gcc or <prefix>-gcc), then the back-end
8723 switches in the ALI file are not used to compile the binder generated source.
8724 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
8725 switches will be used for @option{--GCC="gcc -gnatv"}. If several
8726 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8727 is taken into account. However, all the additional switches are also taken
8728 into account. Thus,
8729 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8730 @option{--GCC="bar -x -y -z -t"}.
8731
8732 @item --LINK=@var{name}
8733 @cindex @option{--LINK=} (@command{gnatlink})
8734 @var{name} is the name of the linker to be invoked. This is especially
8735 useful in mixed language programs since languages such as C++ require
8736 their own linker to be used. When this switch is omitted, the default
8737 name for the linker is @command{gcc}. When this switch is used, the
8738 specified linker is called instead of @command{gcc} with exactly the same
8739 parameters that would have been passed to @command{gcc} so if the desired
8740 linker requires different parameters it is necessary to use a wrapper
8741 script that massages the parameters before invoking the real linker. It
8742 may be useful to control the exact invocation by using the verbose
8743 switch.
8744
8745 @end ifclear
8746
8747 @ifset vms
8748 @item /DEBUG=TRACEBACK
8749 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
8750 This qualifier causes sufficient information to be included in the
8751 executable file to allow a traceback, but does not include the full
8752 symbol information needed by the debugger.
8753
8754 @item /IDENTIFICATION="<string>"
8755 @code{"<string>"} specifies the string to be stored in the image file
8756 identification field in the image header.
8757 It overrides any pragma @code{Ident} specified string.
8758
8759 @item /NOINHIBIT-EXEC
8760 Generate the executable file even if there are linker warnings.
8761
8762 @item /NOSTART_FILES
8763 Don't link in the object file containing the ``main'' transfer address.
8764 Used when linking with a foreign language main program compiled with an
8765 HP compiler.
8766
8767 @item /STATIC
8768 Prefer linking with object libraries over sharable images, even without
8769 /DEBUG.
8770 @end ifset
8771
8772 @end table
8773
8774 @node The GNAT Make Program gnatmake
8775 @chapter The GNAT Make Program @command{gnatmake}
8776 @findex gnatmake
8777
8778 @menu
8779 * Running gnatmake::
8780 * Switches for gnatmake::
8781 * Mode Switches for gnatmake::
8782 * Notes on the Command Line::
8783 * How gnatmake Works::
8784 * Examples of gnatmake Usage::
8785 @end menu
8786 @noindent
8787 A typical development cycle when working on an Ada program consists of
8788 the following steps:
8789
8790 @enumerate
8791 @item
8792 Edit some sources to fix bugs.
8793
8794 @item
8795 Add enhancements.
8796
8797 @item
8798 Compile all sources affected.
8799
8800 @item
8801 Rebind and relink.
8802
8803 @item
8804 Test.
8805 @end enumerate
8806
8807 @noindent
8808 The third step can be tricky, because not only do the modified files
8809 @cindex Dependency rules
8810 have to be compiled, but any files depending on these files must also be
8811 recompiled. The dependency rules in Ada can be quite complex, especially
8812 in the presence of overloading, @code{use} clauses, generics and inlined
8813 subprograms.
8814
8815 @command{gnatmake} automatically takes care of the third and fourth steps
8816 of this process. It determines which sources need to be compiled,
8817 compiles them, and binds and links the resulting object files.
8818
8819 Unlike some other Ada make programs, the dependencies are always
8820 accurately recomputed from the new sources. The source based approach of
8821 the GNAT compilation model makes this possible. This means that if
8822 changes to the source program cause corresponding changes in
8823 dependencies, they will always be tracked exactly correctly by
8824 @command{gnatmake}.
8825
8826 @node Running gnatmake
8827 @section Running @command{gnatmake}
8828
8829 @noindent
8830 The usual form of the @command{gnatmake} command is
8831
8832 @smallexample
8833 $ gnatmake @ovar{switches} @var{file_name}
8834       @ovar{file_names} @ovar{mode_switches}
8835 @end smallexample
8836
8837 @noindent
8838 The only required argument is one @var{file_name}, which specifies
8839 a compilation unit that is a main program. Several @var{file_names} can be
8840 specified: this will result in several executables being built.
8841 If @code{switches} are present, they can be placed before the first
8842 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8843 If @var{mode_switches} are present, they must always be placed after
8844 the last @var{file_name} and all @code{switches}.
8845
8846 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
8847 extension may be omitted from the @var{file_name} arguments. However, if
8848 you are using non-standard extensions, then it is required that the
8849 extension be given. A relative or absolute directory path can be
8850 specified in a @var{file_name}, in which case, the input source file will
8851 be searched for in the specified directory only. Otherwise, the input
8852 source file will first be searched in the directory where
8853 @command{gnatmake} was invoked and if it is not found, it will be search on
8854 the source path of the compiler as described in
8855 @ref{Search Paths and the Run-Time Library (RTL)}.
8856
8857 All @command{gnatmake} output (except when you specify
8858 @option{^-M^/DEPENDENCIES_LIST^}) is to
8859 @file{stderr}. The output produced by the
8860 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8861 @file{stdout}.
8862
8863 @node Switches for gnatmake
8864 @section Switches for @command{gnatmake}
8865
8866 @noindent
8867 You may specify any of the following switches to @command{gnatmake}:
8868
8869 @table @option
8870 @c !sort!
8871
8872 @item --version
8873 @cindex @option{--version} @command{gnatmake}
8874 Display Copyright and version, then exit disregarding all other options.
8875
8876 @item --help
8877 @cindex @option{--help} @command{gnatmake}
8878 If @option{--version} was not used, display usage, then exit disregarding
8879 all other options.
8880
8881 @ifclear vms
8882 @item --GCC=@var{compiler_name}
8883 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
8884 Program used for compiling. The default is `@command{gcc}'. You need to use
8885 quotes around @var{compiler_name} if @code{compiler_name} contains
8886 spaces or other separator characters. As an example @option{--GCC="foo -x
8887 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
8888 compiler. A limitation of this syntax is that the name and path name of
8889 the executable itself must not include any embedded spaces. Note that
8890 switch @option{-c} is always inserted after your command name. Thus in the
8891 above example the compiler command that will be used by @command{gnatmake}
8892 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
8893 used, only the last @var{compiler_name} is taken into account. However,
8894 all the additional switches are also taken into account. Thus,
8895 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8896 @option{--GCC="bar -x -y -z -t"}.
8897
8898 @item --GNATBIND=@var{binder_name}
8899 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
8900 Program used for binding. The default is `@code{gnatbind}'. You need to
8901 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8902 or other separator characters. As an example @option{--GNATBIND="bar -x
8903 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
8904 binder. Binder switches that are normally appended by @command{gnatmake}
8905 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8906 A limitation of this syntax is that the name and path name of the executable
8907 itself must not include any embedded spaces.
8908
8909 @item --GNATLINK=@var{linker_name}
8910 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
8911 Program used for linking. The default is `@command{gnatlink}'. You need to
8912 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8913 or other separator characters. As an example @option{--GNATLINK="lan -x
8914 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
8915 linker. Linker switches that are normally appended by @command{gnatmake} to
8916 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
8917 A limitation of this syntax is that the name and path name of the executable
8918 itself must not include any embedded spaces.
8919
8920 @end ifclear
8921
8922 @item ^-a^/ALL_FILES^
8923 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
8924 Consider all files in the make process, even the GNAT internal system
8925 files (for example, the predefined Ada library files), as well as any
8926 locked files. Locked files are files whose ALI file is write-protected.
8927 By default,
8928 @command{gnatmake} does not check these files,
8929 because the assumption is that the GNAT internal files are properly up
8930 to date, and also that any write protected ALI files have been properly
8931 installed. Note that if there is an installation problem, such that one
8932 of these files is not up to date, it will be properly caught by the
8933 binder.
8934 You may have to specify this switch if you are working on GNAT
8935 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8936 in conjunction with @option{^-f^/FORCE_COMPILE^}
8937 if you need to recompile an entire application,
8938 including run-time files, using special configuration pragmas,
8939 such as a @code{Normalize_Scalars} pragma.
8940
8941 By default
8942 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8943 internal files with
8944 @ifclear vms
8945 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8946 @end ifclear
8947 @ifset vms
8948 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8949 @end ifset
8950
8951 @item ^-b^/ACTIONS=BIND^
8952 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
8953 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8954 compilation and binding, but no link.
8955 Can be combined with @option{^-l^/ACTIONS=LINK^}
8956 to do binding and linking. When not combined with
8957 @option{^-c^/ACTIONS=COMPILE^}
8958 all the units in the closure of the main program must have been previously
8959 compiled and must be up to date. The root unit specified by @var{file_name}
8960 may be given without extension, with the source extension or, if no GNAT
8961 Project File is specified, with the ALI file extension.
8962
8963 @item ^-c^/ACTIONS=COMPILE^
8964 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
8965 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8966 is also specified. Do not perform linking, except if both
8967 @option{^-b^/ACTIONS=BIND^} and
8968 @option{^-l^/ACTIONS=LINK^} are also specified.
8969 If the root unit specified by @var{file_name} is not a main unit, this is the
8970 default. Otherwise @command{gnatmake} will attempt binding and linking
8971 unless all objects are up to date and the executable is more recent than
8972 the objects.
8973
8974 @item ^-C^/MAPPING^
8975 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
8976 Use a temporary mapping file. A mapping file is a way to communicate to the
8977 compiler two mappings: from unit names to file names (without any directory
8978 information) and from file names to path names (with full directory
8979 information). These mappings are used by the compiler to short-circuit the path
8980 search. When @command{gnatmake} is invoked with this switch, it will create
8981 a temporary mapping file, initially populated by the project manager,
8982 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8983 Each invocation of the compiler will add the newly accessed sources to the
8984 mapping file. This will improve the source search during the next invocation
8985 of the compiler.
8986
8987 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8988 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
8989 Use a specific mapping file. The file, specified as a path name (absolute or
8990 relative) by this switch, should already exist, otherwise the switch is
8991 ineffective. The specified mapping file will be communicated to the compiler.
8992 This switch is not compatible with a project file
8993 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8994 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8995
8996 @item ^-d^/DISPLAY_PROGRESS^
8997 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
8998 Display progress for each source, up to date or not, as a single line
8999
9000 @smallexample
9001 completed x out of y (zz%)
9002 @end smallexample
9003
9004 If the file needs to be compiled this is displayed after the invocation of
9005 the compiler. These lines are displayed even in quiet output mode.
9006
9007 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9008 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9009 Put all object files and ALI file in directory @var{dir}.
9010 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9011 and ALI files go in the current working directory.
9012
9013 This switch cannot be used when using a project file.
9014
9015 @ifclear vms
9016 @item -eL
9017 @cindex @option{-eL} (@command{gnatmake})
9018 Follow all symbolic links when processing project files.
9019 @end ifclear
9020
9021 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9022 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9023 Output the commands for the compiler, the binder and the linker
9024 on ^standard output^SYS$OUTPUT^,
9025 instead of ^standard error^SYS$ERROR^.
9026
9027 @item ^-f^/FORCE_COMPILE^
9028 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9029 Force recompilations. Recompile all sources, even though some object
9030 files may be up to date, but don't recompile predefined or GNAT internal
9031 files or locked files (files with a write-protected ALI file),
9032 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9033
9034 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9035 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9036 When using project files, if some errors or warnings are detected during
9037 parsing and verbose mode is not in effect (no use of switch
9038 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9039 file, rather than its simple file name.
9040
9041 @item ^-g^/DEBUG^
9042 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9043 Enable debugging. This switch is simply passed to the compiler and to the
9044 linker.
9045
9046 @item ^-i^/IN_PLACE^
9047 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9048 In normal mode, @command{gnatmake} compiles all object files and ALI files
9049 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9050 then instead object files and ALI files that already exist are overwritten
9051 in place. This means that once a large project is organized into separate
9052 directories in the desired manner, then @command{gnatmake} will automatically
9053 maintain and update this organization. If no ALI files are found on the
9054 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9055 the new object and ALI files are created in the
9056 directory containing the source being compiled. If another organization
9057 is desired, where objects and sources are kept in different directories,
9058 a useful technique is to create dummy ALI files in the desired directories.
9059 When detecting such a dummy file, @command{gnatmake} will be forced to
9060 recompile the corresponding source file, and it will be put the resulting
9061 object and ALI files in the directory where it found the dummy file.
9062
9063 @item ^-j^/PROCESSES=^@var{n}
9064 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9065 @cindex Parallel make
9066 Use @var{n} processes to carry out the (re)compilations. On a
9067 multiprocessor machine compilations will occur in parallel. In the
9068 event of compilation errors, messages from various compilations might
9069 get interspersed (but @command{gnatmake} will give you the full ordered
9070 list of failing compiles at the end). If this is problematic, rerun
9071 the make process with n set to 1 to get a clean list of messages.
9072
9073 @item ^-k^/CONTINUE_ON_ERROR^
9074 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9075 Keep going. Continue as much as possible after a compilation error. To
9076 ease the programmer's task in case of compilation errors, the list of
9077 sources for which the compile fails is given when @command{gnatmake}
9078 terminates.
9079
9080 If @command{gnatmake} is invoked with several @file{file_names} and with this
9081 switch, if there are compilation errors when building an executable,
9082 @command{gnatmake} will not attempt to build the following executables.
9083
9084 @item ^-l^/ACTIONS=LINK^
9085 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9086 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9087 and linking. Linking will not be performed if combined with
9088 @option{^-c^/ACTIONS=COMPILE^}
9089 but not with @option{^-b^/ACTIONS=BIND^}.
9090 When not combined with @option{^-b^/ACTIONS=BIND^}
9091 all the units in the closure of the main program must have been previously
9092 compiled and must be up to date, and the main program needs to have been bound.
9093 The root unit specified by @var{file_name}
9094 may be given without extension, with the source extension or, if no GNAT
9095 Project File is specified, with the ALI file extension.
9096
9097 @item ^-m^/MINIMAL_RECOMPILATION^
9098 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9099 Specify that the minimum necessary amount of recompilations
9100 be performed. In this mode @command{gnatmake} ignores time
9101 stamp differences when the only
9102 modifications to a source file consist in adding/removing comments,
9103 empty lines, spaces or tabs. This means that if you have changed the
9104 comments in a source file or have simply reformatted it, using this
9105 switch will tell @command{gnatmake} not to recompile files that depend on it
9106 (provided other sources on which these files depend have undergone no
9107 semantic modifications). Note that the debugging information may be
9108 out of date with respect to the sources if the @option{-m} switch causes
9109 a compilation to be switched, so the use of this switch represents a
9110 trade-off between compilation time and accurate debugging information.
9111
9112 @item ^-M^/DEPENDENCIES_LIST^
9113 @cindex Dependencies, producing list
9114 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9115 Check if all objects are up to date. If they are, output the object
9116 dependences to @file{stdout} in a form that can be directly exploited in
9117 a @file{Makefile}. By default, each source file is prefixed with its
9118 (relative or absolute) directory name. This name is whatever you
9119 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9120 and @option{^-I^/SEARCH^} switches. If you use
9121 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9122 @option{^-q^/QUIET^}
9123 (see below), only the source file names,
9124 without relative paths, are output. If you just specify the
9125 @option{^-M^/DEPENDENCIES_LIST^}
9126 switch, dependencies of the GNAT internal system files are omitted. This
9127 is typically what you want. If you also specify
9128 the @option{^-a^/ALL_FILES^} switch,
9129 dependencies of the GNAT internal files are also listed. Note that
9130 dependencies of the objects in external Ada libraries (see switch
9131 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9132 are never reported.
9133
9134 @item ^-n^/DO_OBJECT_CHECK^
9135 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9136 Don't compile, bind, or link. Checks if all objects are up to date.
9137 If they are not, the full name of the first file that needs to be
9138 recompiled is printed.
9139 Repeated use of this option, followed by compiling the indicated source
9140 file, will eventually result in recompiling all required units.
9141
9142 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9143 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9144 Output executable name. The name of the final executable program will be
9145 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9146 name for the executable will be the name of the input file in appropriate form
9147 for an executable file on the host system.
9148
9149 This switch cannot be used when invoking @command{gnatmake} with several
9150 @file{file_names}.
9151
9152 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9153 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9154 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9155 automatically missing object directories, library directories and exec
9156 directories.
9157
9158 @item ^-P^/PROJECT_FILE=^@var{project}
9159 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9160 Use project file @var{project}. Only one such switch can be used.
9161 @xref{gnatmake and Project Files}.
9162
9163 @item ^-q^/QUIET^
9164 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9165 Quiet. When this flag is not set, the commands carried out by
9166 @command{gnatmake} are displayed.
9167
9168 @item ^-s^/SWITCH_CHECK/^
9169 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9170 Recompile if compiler switches have changed since last compilation.
9171 All compiler switches but -I and -o are taken into account in the
9172 following way:
9173 orders between different ``first letter'' switches are ignored, but
9174 orders between same switches are taken into account. For example,
9175 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9176 is equivalent to @option{-O -g}.
9177
9178 This switch is recommended when Integrated Preprocessing is used.
9179
9180 @item ^-u^/UNIQUE^
9181 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9182 Unique. Recompile at most the main files. It implies -c. Combined with
9183 -f, it is equivalent to calling the compiler directly. Note that using
9184 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9185 (@pxref{Project Files and Main Subprograms}).
9186
9187 @item ^-U^/ALL_PROJECTS^
9188 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9189 When used without a project file or with one or several mains on the command
9190 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9191 on the command line, all sources of all project files are checked and compiled
9192 if not up to date, and libraries are rebuilt, if necessary.
9193
9194 @item ^-v^/REASONS^
9195 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9196 Verbose. Display the reason for all recompilations @command{gnatmake}
9197 decides are necessary, with the highest verbosity level.
9198
9199 @item ^-vl^/LOW_VERBOSITY^
9200 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9201 Verbosity level Low. Display fewer lines than in verbosity Medium.
9202
9203 @item ^-vm^/MEDIUM_VERBOSITY^
9204 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9205 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9206
9207 @item ^-vh^/HIGH_VERBOSITY^
9208 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9209 Verbosity level High. Equivalent to ^-v^/REASONS^.
9210
9211 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9212 Indicate the verbosity of the parsing of GNAT project files.
9213 @xref{Switches Related to Project Files}.
9214
9215 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9216 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9217 Indicate that sources that are not part of any Project File may be compiled.
9218 Normally, when using Project Files, only sources that are part of a Project
9219 File may be compile. When this switch is used, a source outside of all Project
9220 Files may be compiled. The ALI file and the object file will be put in the
9221 object directory of the main Project. The compilation switches used will only
9222 be those specified on the command line. Even when
9223 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9224 command line need to be sources of a project file.
9225
9226 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9227 Indicate that external variable @var{name} has the value @var{value}.
9228 The Project Manager will use this value for occurrences of
9229 @code{external(name)} when parsing the project file.
9230 @xref{Switches Related to Project Files}.
9231
9232 @item ^-z^/NOMAIN^
9233 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9234 No main subprogram. Bind and link the program even if the unit name
9235 given on the command line is a package name. The resulting executable
9236 will execute the elaboration routines of the package and its closure,
9237 then the finalization routines.
9238
9239 @end table
9240
9241 @table @asis
9242 @item @command{gcc} @asis{switches}
9243 @ifclear vms
9244 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9245 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9246 @end ifclear
9247 @ifset vms
9248 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9249 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9250 automatically treated as a compiler switch, and passed on to all
9251 compilations that are carried out.
9252 @end ifset
9253 @end table
9254
9255 @noindent
9256 Source and library search path switches:
9257
9258 @table @option
9259 @c !sort!
9260 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9261 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9262 When looking for source files also look in directory @var{dir}.
9263 The order in which source files search is undertaken is
9264 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9265
9266 @item ^-aL^/SKIP_MISSING=^@var{dir}
9267 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9268 Consider @var{dir} as being an externally provided Ada library.
9269 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9270 files have been located in directory @var{dir}. This allows you to have
9271 missing bodies for the units in @var{dir} and to ignore out of date bodies
9272 for the same units. You still need to specify
9273 the location of the specs for these units by using the switches
9274 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9275 or @option{^-I^/SEARCH=^@var{dir}}.
9276 Note: this switch is provided for compatibility with previous versions
9277 of @command{gnatmake}. The easier method of causing standard libraries
9278 to be excluded from consideration is to write-protect the corresponding
9279 ALI files.
9280
9281 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9282 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9283 When searching for library and object files, look in directory
9284 @var{dir}. The order in which library files are searched is described in
9285 @ref{Search Paths for gnatbind}.
9286
9287 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9288 @cindex Search paths, for @command{gnatmake}
9289 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9290 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9291 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9292
9293 @item ^-I^/SEARCH=^@var{dir}
9294 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9295 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9296 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9297
9298 @item ^-I-^/NOCURRENT_DIRECTORY^
9299 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9300 @cindex Source files, suppressing search
9301 Do not look for source files in the directory containing the source
9302 file named in the command line.
9303 Do not look for ALI or object files in the directory
9304 where @command{gnatmake} was invoked.
9305
9306 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9307 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9308 @cindex Linker libraries
9309 Add directory @var{dir} to the list of directories in which the linker
9310 will search for libraries. This is equivalent to
9311 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9312 @ifclear vms
9313 Furthermore, under Windows, the sources pointed to by the libraries path
9314 set in the registry are not searched for.
9315 @end ifclear
9316
9317 @item -nostdinc
9318 @cindex @option{-nostdinc} (@command{gnatmake})
9319 Do not look for source files in the system default directory.
9320
9321 @item -nostdlib
9322 @cindex @option{-nostdlib} (@command{gnatmake})
9323 Do not look for library files in the system default directory.
9324
9325 @item --RTS=@var{rts-path}
9326 @cindex @option{--RTS} (@command{gnatmake})
9327 Specifies the default location of the runtime library. GNAT looks for the
9328 runtime
9329 in the following directories, and stops as soon as a valid runtime is found
9330 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9331 @file{ada_object_path} present):
9332
9333 @itemize @bullet
9334 @item <current directory>/$rts_path
9335
9336 @item <default-search-dir>/$rts_path
9337
9338 @item <default-search-dir>/rts-$rts_path
9339 @end itemize
9340
9341 @noindent
9342 The selected path is handled like a normal RTS path.
9343
9344 @end table
9345
9346 @node Mode Switches for gnatmake
9347 @section Mode Switches for @command{gnatmake}
9348
9349 @noindent
9350 The mode switches (referred to as @code{mode_switches}) allow the
9351 inclusion of switches that are to be passed to the compiler itself, the
9352 binder or the linker. The effect of a mode switch is to cause all
9353 subsequent switches up to the end of the switch list, or up to the next
9354 mode switch, to be interpreted as switches to be passed on to the
9355 designated component of GNAT.
9356
9357 @table @option
9358 @c !sort!
9359 @item -cargs @var{switches}
9360 @cindex @option{-cargs} (@command{gnatmake})
9361 Compiler switches. Here @var{switches} is a list of switches
9362 that are valid switches for @command{gcc}. They will be passed on to
9363 all compile steps performed by @command{gnatmake}.
9364
9365 @item -bargs @var{switches}
9366 @cindex @option{-bargs} (@command{gnatmake})
9367 Binder switches. Here @var{switches} is a list of switches
9368 that are valid switches for @code{gnatbind}. They will be passed on to
9369 all bind steps performed by @command{gnatmake}.
9370
9371 @item -largs @var{switches}
9372 @cindex @option{-largs} (@command{gnatmake})
9373 Linker switches. Here @var{switches} is a list of switches
9374 that are valid switches for @command{gnatlink}. They will be passed on to
9375 all link steps performed by @command{gnatmake}.
9376
9377 @item -margs @var{switches}
9378 @cindex @option{-margs} (@command{gnatmake})
9379 Make switches. The switches are directly interpreted by @command{gnatmake},
9380 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9381 or @option{-largs}.
9382 @end table
9383
9384 @node Notes on the Command Line
9385 @section Notes on the Command Line
9386
9387 @noindent
9388 This section contains some additional useful notes on the operation
9389 of the @command{gnatmake} command.
9390
9391 @itemize @bullet
9392 @item
9393 @cindex Recompilation, by @command{gnatmake}
9394 If @command{gnatmake} finds no ALI files, it recompiles the main program
9395 and all other units required by the main program.
9396 This means that @command{gnatmake}
9397 can be used for the initial compile, as well as during subsequent steps of
9398 the development cycle.
9399
9400 @item
9401 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9402 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9403 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9404 warning.
9405
9406 @item
9407 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9408 is used to specify both source and
9409 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9410 instead if you just want to specify
9411 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9412 if you want to specify library paths
9413 only.
9414
9415 @item
9416 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9417 This may conveniently be used to exclude standard libraries from
9418 consideration and in particular it means that the use of the
9419 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9420 unless @option{^-a^/ALL_FILES^} is also specified.
9421
9422 @item
9423 @command{gnatmake} has been designed to make the use of Ada libraries
9424 particularly convenient. Assume you have an Ada library organized
9425 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9426 of your Ada compilation units,
9427 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9428 specs of these units, but no bodies. Then to compile a unit
9429 stored in @code{main.adb}, which uses this Ada library you would just type
9430
9431 @smallexample
9432 @ifclear vms
9433 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9434 @end ifclear
9435 @ifset vms
9436 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9437            /SKIP_MISSING=@i{[OBJ_DIR]} main
9438 @end ifset
9439 @end smallexample
9440
9441 @item
9442 Using @command{gnatmake} along with the
9443 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9444 switch provides a mechanism for avoiding unnecessary recompilations. Using
9445 this switch,
9446 you can update the comments/format of your
9447 source files without having to recompile everything. Note, however, that
9448 adding or deleting lines in a source files may render its debugging
9449 info obsolete. If the file in question is a spec, the impact is rather
9450 limited, as that debugging info will only be useful during the
9451 elaboration phase of your program. For bodies the impact can be more
9452 significant. In all events, your debugger will warn you if a source file
9453 is more recent than the corresponding object, and alert you to the fact
9454 that the debugging information may be out of date.
9455 @end itemize
9456
9457 @node How gnatmake Works
9458 @section How @command{gnatmake} Works
9459
9460 @noindent
9461 Generally @command{gnatmake} automatically performs all necessary
9462 recompilations and you don't need to worry about how it works. However,
9463 it may be useful to have some basic understanding of the @command{gnatmake}
9464 approach and in particular to understand how it uses the results of
9465 previous compilations without incorrectly depending on them.
9466
9467 First a definition: an object file is considered @dfn{up to date} if the
9468 corresponding ALI file exists and if all the source files listed in the
9469 dependency section of this ALI file have time stamps matching those in
9470 the ALI file. This means that neither the source file itself nor any
9471 files that it depends on have been modified, and hence there is no need
9472 to recompile this file.
9473
9474 @command{gnatmake} works by first checking if the specified main unit is up
9475 to date. If so, no compilations are required for the main unit. If not,
9476 @command{gnatmake} compiles the main program to build a new ALI file that
9477 reflects the latest sources. Then the ALI file of the main unit is
9478 examined to find all the source files on which the main program depends,
9479 and @command{gnatmake} recursively applies the above procedure on all these
9480 files.
9481
9482 This process ensures that @command{gnatmake} only trusts the dependencies
9483 in an existing ALI file if they are known to be correct. Otherwise it
9484 always recompiles to determine a new, guaranteed accurate set of
9485 dependencies. As a result the program is compiled ``upside down'' from what may
9486 be more familiar as the required order of compilation in some other Ada
9487 systems. In particular, clients are compiled before the units on which
9488 they depend. The ability of GNAT to compile in any order is critical in
9489 allowing an order of compilation to be chosen that guarantees that
9490 @command{gnatmake} will recompute a correct set of new dependencies if
9491 necessary.
9492
9493 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9494 imported by several of the executables, it will be recompiled at most once.
9495
9496 Note: when using non-standard naming conventions
9497 (@pxref{Using Other File Names}), changing through a configuration pragmas
9498 file the version of a source and invoking @command{gnatmake} to recompile may
9499 have no effect, if the previous version of the source is still accessible
9500 by @command{gnatmake}. It may be necessary to use the switch
9501 ^-f^/FORCE_COMPILE^.
9502
9503 @node Examples of gnatmake Usage
9504 @section Examples of @command{gnatmake} Usage
9505
9506 @table @code
9507 @item gnatmake hello.adb
9508 Compile all files necessary to bind and link the main program
9509 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9510 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9511
9512 @item gnatmake main1 main2 main3
9513 Compile all files necessary to bind and link the main programs
9514 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9515 (containing unit @code{Main2}) and @file{main3.adb}
9516 (containing unit @code{Main3}) and bind and link the resulting object files
9517 to generate three executable files @file{^main1^MAIN1.EXE^},
9518 @file{^main2^MAIN2.EXE^}
9519 and @file{^main3^MAIN3.EXE^}.
9520
9521 @ifclear vms
9522 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9523 @end ifclear
9524
9525 @ifset vms
9526 @item gnatmake Main_Unit /QUIET
9527 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9528 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9529 @end ifset
9530 Compile all files necessary to bind and link the main program unit
9531 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9532 be done with optimization level 2 and the order of elaboration will be
9533 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9534 displaying commands it is executing.
9535 @end table
9536
9537 @c *************************
9538 @node Improving Performance
9539 @chapter Improving Performance
9540 @cindex Improving performance
9541
9542 @noindent
9543 This chapter presents several topics related to program performance.
9544 It first describes some of the tradeoffs that need to be considered
9545 and some of the techniques for making your program run faster.
9546 It then documents the @command{gnatelim} tool and unused subprogram/data
9547 elimination feature, which can reduce the size of program executables.
9548
9549 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9550 driver (see @ref{The GNAT Driver and Project Files}).
9551
9552 @ifnottex
9553 @menu
9554 * Performance Considerations::
9555 * Text_IO Suggestions::
9556 * Reducing Size of Ada Executables with gnatelim::
9557 * Reducing Size of Executables with unused subprogram/data elimination::
9558 @end menu
9559 @end ifnottex
9560
9561 @c *****************************
9562 @node Performance Considerations
9563 @section Performance Considerations
9564
9565 @noindent
9566 The GNAT system provides a number of options that allow a trade-off
9567 between
9568
9569 @itemize @bullet
9570 @item
9571 performance of the generated code
9572
9573 @item
9574 speed of compilation
9575
9576 @item
9577 minimization of dependences and recompilation
9578
9579 @item
9580 the degree of run-time checking.
9581 @end itemize
9582
9583 @noindent
9584 The defaults (if no options are selected) aim at improving the speed
9585 of compilation and minimizing dependences, at the expense of performance
9586 of the generated code:
9587
9588 @itemize @bullet
9589 @item
9590 no optimization
9591
9592 @item
9593 no inlining of subprogram calls
9594
9595 @item
9596 all run-time checks enabled except overflow and elaboration checks
9597 @end itemize
9598
9599 @noindent
9600 These options are suitable for most program development purposes. This
9601 chapter describes how you can modify these choices, and also provides
9602 some guidelines on debugging optimized code.
9603
9604 @menu
9605 * Controlling Run-Time Checks::
9606 * Use of Restrictions::
9607 * Optimization Levels::
9608 * Debugging Optimized Code::
9609 * Inlining of Subprograms::
9610 * Other Optimization Switches::
9611 * Optimization and Strict Aliasing::
9612
9613 @ifset vms
9614 * Coverage Analysis::
9615 @end ifset
9616 @end menu
9617
9618 @node Controlling Run-Time Checks
9619 @subsection Controlling Run-Time Checks
9620
9621 @noindent
9622 By default, GNAT generates all run-time checks, except integer overflow
9623 checks, stack overflow checks, and checks for access before elaboration on
9624 subprogram calls. The latter are not required in default mode, because all
9625 necessary checking is done at compile time.
9626 @cindex @option{-gnatp} (@command{gcc})
9627 @cindex @option{-gnato} (@command{gcc})
9628 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9629 be modified. @xref{Run-Time Checks}.
9630
9631 Our experience is that the default is suitable for most development
9632 purposes.
9633
9634 We treat integer overflow specially because these
9635 are quite expensive and in our experience are not as important as other
9636 run-time checks in the development process. Note that division by zero
9637 is not considered an overflow check, and divide by zero checks are
9638 generated where required by default.
9639
9640 Elaboration checks are off by default, and also not needed by default, since
9641 GNAT uses a static elaboration analysis approach that avoids the need for
9642 run-time checking. This manual contains a full chapter discussing the issue
9643 of elaboration checks, and if the default is not satisfactory for your use,
9644 you should read this chapter.
9645
9646 For validity checks, the minimal checks required by the Ada Reference
9647 Manual (for case statements and assignments to array elements) are on
9648 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9649 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9650 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9651 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9652 are also suppressed entirely if @option{-gnatp} is used.
9653
9654 @cindex Overflow checks
9655 @cindex Checks, overflow
9656 @findex Suppress
9657 @findex Unsuppress
9658 @cindex pragma Suppress
9659 @cindex pragma Unsuppress
9660 Note that the setting of the switches controls the default setting of
9661 the checks. They may be modified using either @code{pragma Suppress} (to
9662 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9663 checks) in the program source.
9664
9665 @node Use of Restrictions
9666 @subsection Use of Restrictions
9667
9668 @noindent
9669 The use of pragma Restrictions allows you to control which features are
9670 permitted in your program. Apart from the obvious point that if you avoid
9671 relatively expensive features like finalization (enforceable by the use
9672 of pragma Restrictions (No_Finalization), the use of this pragma does not
9673 affect the generated code in most cases.
9674
9675 One notable exception to this rule is that the possibility of task abort
9676 results in some distributed overhead, particularly if finalization or
9677 exception handlers are used. The reason is that certain sections of code
9678 have to be marked as non-abortable.
9679
9680 If you use neither the @code{abort} statement, nor asynchronous transfer
9681 of control (@code{select @dots{} then abort}), then this distributed overhead
9682 is removed, which may have a general positive effect in improving
9683 overall performance.  Especially code involving frequent use of tasking
9684 constructs and controlled types will show much improved performance.
9685 The relevant restrictions pragmas are
9686
9687 @smallexample @c ada
9688    pragma Restrictions (No_Abort_Statements);
9689    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9690 @end smallexample
9691
9692 @noindent
9693 It is recommended that these restriction pragmas be used if possible. Note
9694 that this also means that you can write code without worrying about the
9695 possibility of an immediate abort at any point.
9696
9697 @node Optimization Levels
9698 @subsection Optimization Levels
9699 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
9700
9701 @noindent
9702 Without any optimization ^option,^qualifier,^
9703 the compiler's goal is to reduce the cost of
9704 compilation and to make debugging produce the expected results.
9705 Statements are independent: if you stop the program with a breakpoint between
9706 statements, you can then assign a new value to any variable or change
9707 the program counter to any other statement in the subprogram and get exactly
9708 the results you would expect from the source code.
9709
9710 Turning on optimization makes the compiler attempt to improve the
9711 performance and/or code size at the expense of compilation time and
9712 possibly the ability to debug the program.
9713
9714 If you use multiple
9715 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
9716 the last such option is the one that is effective.
9717
9718 @noindent
9719 The default is optimization off. This results in the fastest compile
9720 times, but GNAT makes absolutely no attempt to optimize, and the
9721 generated programs are considerably larger and slower than when
9722 optimization is enabled. You can use the
9723 @ifclear vms
9724 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
9725 @option{-O2}, @option{-O3}, and @option{-Os})
9726 @end ifclear
9727 @ifset vms
9728 @code{OPTIMIZE} qualifier
9729 @end ifset
9730 to @command{gcc} to control the optimization level:
9731
9732 @table @option
9733 @item ^-O0^/OPTIMIZE=NONE^
9734 No optimization (the default);
9735 generates unoptimized code but has
9736 the fastest compilation time.
9737
9738 Note that many other compilers do fairly extensive optimization
9739 even if ``no optimization'' is specified. With gcc, it is
9740 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
9741 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
9742 really does mean no optimization at all. This difference between
9743 gcc and other compilers should be kept in mind when doing
9744 performance comparisons.
9745
9746 @item ^-O1^/OPTIMIZE=SOME^
9747 Moderate optimization;
9748 optimizes reasonably well but does not
9749 degrade compilation time significantly.
9750
9751 @item ^-O2^/OPTIMIZE=ALL^
9752 @ifset vms
9753 @itemx /OPTIMIZE=DEVELOPMENT
9754 @end ifset
9755 Full optimization;
9756 generates highly optimized code and has
9757 the slowest compilation time.
9758
9759 @item ^-O3^/OPTIMIZE=INLINING^
9760 Full optimization as in @option{-O2},
9761 and also attempts automatic inlining of small
9762 subprograms within a unit (@pxref{Inlining of Subprograms}).
9763
9764 @item ^-Os^/OPTIMIZE=SPACE^
9765 Optimize space usage of resulting program.
9766 @end table
9767
9768 @noindent
9769 Higher optimization levels perform more global transformations on the
9770 program and apply more expensive analysis algorithms in order to generate
9771 faster and more compact code. The price in compilation time, and the
9772 resulting improvement in execution time,
9773 both depend on the particular application and the hardware environment.
9774 You should experiment to find the best level for your application.
9775
9776 Since the precise set of optimizations done at each level will vary from
9777 release to release (and sometime from target to target), it is best to think
9778 of the optimization settings in general terms.
9779 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
9780 the GNU Compiler Collection (GCC)}, for details about
9781 ^the @option{-O} settings and a number of @option{-f} options that^how to^
9782 individually enable or disable specific optimizations.
9783
9784 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
9785 been tested extensively at all optimization levels. There are some bugs
9786 which appear only with optimization turned on, but there have also been
9787 bugs which show up only in @emph{unoptimized} code. Selecting a lower
9788 level of optimization does not improve the reliability of the code
9789 generator, which in practice is highly reliable at all optimization
9790 levels.
9791
9792 Note regarding the use of @option{-O3}: The use of this optimization level
9793 is generally discouraged with GNAT, since it often results in larger
9794 executables which run more slowly. See further discussion of this point
9795 in @ref{Inlining of Subprograms}.
9796
9797 @node Debugging Optimized Code
9798 @subsection Debugging Optimized Code
9799 @cindex Debugging optimized code
9800 @cindex Optimization and debugging
9801
9802 @noindent
9803 Although it is possible to do a reasonable amount of debugging at
9804 @ifclear vms
9805 nonzero optimization levels,
9806 the higher the level the more likely that
9807 @end ifclear
9808 @ifset vms
9809 @option{/OPTIMIZE} settings other than @code{NONE},
9810 such settings will make it more likely that
9811 @end ifset
9812 source-level constructs will have been eliminated by optimization.
9813 For example, if a loop is strength-reduced, the loop
9814 control variable may be completely eliminated and thus cannot be
9815 displayed in the debugger.
9816 This can only happen at @option{-O2} or @option{-O3}.
9817 Explicit temporary variables that you code might be eliminated at
9818 ^level^setting^ @option{-O1} or higher.
9819
9820 The use of the @option{^-g^/DEBUG^} switch,
9821 @cindex @option{^-g^/DEBUG^} (@command{gcc})
9822 which is needed for source-level debugging,
9823 affects the size of the program executable on disk,
9824 and indeed the debugging information can be quite large.
9825 However, it has no effect on the generated code (and thus does not
9826 degrade performance)
9827
9828 Since the compiler generates debugging tables for a compilation unit before
9829 it performs optimizations, the optimizing transformations may invalidate some
9830 of the debugging data.  You therefore need to anticipate certain
9831 anomalous situations that may arise while debugging optimized code.
9832 These are the most common cases:
9833
9834 @enumerate
9835 @item
9836 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
9837 commands show
9838 the PC bouncing back and forth in the code.  This may result from any of
9839 the following optimizations:
9840
9841 @itemize @bullet
9842 @item
9843 @i{Common subexpression elimination:} using a single instance of code for a
9844 quantity that the source computes several times.  As a result you
9845 may not be able to stop on what looks like a statement.
9846
9847 @item
9848 @i{Invariant code motion:} moving an expression that does not change within a
9849 loop, to the beginning of the loop.
9850
9851 @item
9852 @i{Instruction scheduling:} moving instructions so as to
9853 overlap loads and stores (typically) with other code, or in
9854 general to move computations of values closer to their uses. Often
9855 this causes you to pass an assignment statement without the assignment
9856 happening and then later bounce back to the statement when the
9857 value is actually needed.  Placing a breakpoint on a line of code
9858 and then stepping over it may, therefore, not always cause all the
9859 expected side-effects.
9860 @end itemize
9861
9862 @item
9863 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
9864 two identical pieces of code are merged and the program counter suddenly
9865 jumps to a statement that is not supposed to be executed, simply because
9866 it (and the code following) translates to the same thing as the code
9867 that @emph{was} supposed to be executed.  This effect is typically seen in
9868 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
9869 a @code{break} in a C @code{^switch^switch^} statement.
9870
9871 @item
9872 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
9873 There are various reasons for this effect:
9874
9875 @itemize @bullet
9876 @item
9877 In a subprogram prologue, a parameter may not yet have been moved to its
9878 ``home''.
9879
9880 @item
9881 A variable may be dead, and its register re-used.  This is
9882 probably the most common cause.
9883
9884 @item
9885 As mentioned above, the assignment of a value to a variable may
9886 have been moved.
9887
9888 @item
9889 A variable may be eliminated entirely by value propagation or
9890 other means.  In this case, GCC may incorrectly generate debugging
9891 information for the variable
9892 @end itemize
9893
9894 @noindent
9895 In general, when an unexpected value appears for a local variable or parameter
9896 you should first ascertain if that value was actually computed by
9897 your program, as opposed to being incorrectly reported by the debugger.
9898 Record fields or
9899 array elements in an object designated by an access value
9900 are generally less of a problem, once you have ascertained that the access
9901 value is sensible.
9902 Typically, this means checking variables in the preceding code and in the
9903 calling subprogram to verify that the value observed is explainable from other
9904 values (one must apply the procedure recursively to those
9905 other values); or re-running the code and stopping a little earlier
9906 (perhaps before the call) and stepping to better see how the variable obtained
9907 the value in question; or continuing to step @emph{from} the point of the
9908 strange value to see if code motion had simply moved the variable's
9909 assignments later.
9910 @end enumerate
9911
9912 @noindent
9913 In light of such anomalies, a recommended technique is to use @option{-O0}
9914 early in the software development cycle, when extensive debugging capabilities
9915 are most needed, and then move to @option{-O1} and later @option{-O2} as
9916 the debugger becomes less critical.
9917 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9918 a release management issue.
9919 @ifclear vms
9920 Note that if you use @option{-g} you can then use the @command{strip} program
9921 on the resulting executable,
9922 which removes both debugging information and global symbols.
9923 @end ifclear
9924
9925 @node Inlining of Subprograms
9926 @subsection Inlining of Subprograms
9927
9928 @noindent
9929 A call to a subprogram in the current unit is inlined if all the
9930 following conditions are met:
9931
9932 @itemize @bullet
9933 @item
9934 The optimization level is at least @option{-O1}.
9935
9936 @item
9937 The called subprogram is suitable for inlining: It must be small enough
9938 and not contain something that @command{gcc} cannot support in inlined
9939 subprograms.
9940
9941 @item
9942 @cindex pragma Inline
9943 @findex Inline
9944 Either @code{pragma Inline} applies to the subprogram, or it is local
9945 to the unit and called once from within it, or it is small and automatic
9946 inlining (optimization level @option{-O3}) is specified.
9947 @end itemize
9948
9949 @noindent
9950 Calls to subprograms in @code{with}'ed units are normally not inlined.
9951 To achieve actual inlining (that is, replacement of the call by the code
9952 in the body of the subprogram), the following conditions must all be true.
9953
9954 @itemize @bullet
9955 @item
9956 The optimization level is at least @option{-O1}.
9957
9958 @item
9959 The called subprogram is suitable for inlining: It must be small enough
9960 and not contain something that @command{gcc} cannot support in inlined
9961 subprograms.
9962
9963 @item
9964 The call appears in a body (not in a package spec).
9965
9966 @item
9967 There is a @code{pragma Inline} for the subprogram.
9968
9969 @item
9970 @cindex @option{-gnatn} (@command{gcc})
9971 The @option{^-gnatn^/INLINE^} switch
9972 is used in the @command{gcc} command line
9973 @end itemize
9974
9975 Even if all these conditions are met, it may not be possible for
9976 the compiler to inline the call, due to the length of the body,
9977 or features in the body that make it impossible for the compiler
9978 to do the inlining.
9979
9980 Note that specifying the @option{-gnatn} switch causes additional
9981 compilation dependencies. Consider the following:
9982
9983 @smallexample @c ada
9984 @cartouche
9985 package R is
9986    procedure Q;
9987    pragma Inline (Q);
9988 end R;
9989 package body R is
9990    @dots{}
9991 end R;
9992
9993 with R;
9994 procedure Main is
9995 begin
9996    @dots{}
9997    R.Q;
9998 end Main;
9999 @end cartouche
10000 @end smallexample
10001
10002 @noindent
10003 With the default behavior (no @option{-gnatn} switch specified), the
10004 compilation of the @code{Main} procedure depends only on its own source,
10005 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10006 means that editing the body of @code{R} does not require recompiling
10007 @code{Main}.
10008
10009 On the other hand, the call @code{R.Q} is not inlined under these
10010 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10011 is compiled, the call will be inlined if the body of @code{Q} is small
10012 enough, but now @code{Main} depends on the body of @code{R} in
10013 @file{r.adb} as well as on the spec. This means that if this body is edited,
10014 the main program must be recompiled. Note that this extra dependency
10015 occurs whether or not the call is in fact inlined by @command{gcc}.
10016
10017 The use of front end inlining with @option{-gnatN} generates similar
10018 additional dependencies.
10019
10020 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10021 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10022 can be used to prevent
10023 all inlining. This switch overrides all other conditions and ensures
10024 that no inlining occurs. The extra dependences resulting from
10025 @option{-gnatn} will still be active, even if
10026 this switch is used to suppress the resulting inlining actions.
10027
10028 @cindex @option{-fno-inline-functions} (@command{gcc})
10029 Note: The @option{-fno-inline-functions} switch can be used to prevent
10030 automatic inlining of small subprograms if @option{-O3} is used.
10031
10032 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10033 Note: The @option{-fno-inline-functions-called-once} switch
10034 can be used to prevent inlining of subprograms local to the unit
10035 and called once from within it if @option{-O1} is used.
10036
10037 Note regarding the use of @option{-O3}: There is no difference in inlining
10038 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10039 pragma @code{Inline} assuming the use of @option{-gnatn}
10040 or @option{-gnatN} (the switches that activate inlining). If you have used
10041 pragma @code{Inline} in appropriate cases, then it is usually much better
10042 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10043 in this case only has the effect of inlining subprograms you did not
10044 think should be inlined. We often find that the use of @option{-O3} slows
10045 down code by performing excessive inlining, leading to increased instruction
10046 cache pressure from the increased code size. So the bottom line here is
10047 that you should not automatically assume that @option{-O3} is better than
10048 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10049 it actually improves performance.
10050
10051 @node Other Optimization Switches
10052 @subsection Other Optimization Switches
10053 @cindex Optimization Switches
10054
10055 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10056 @command{gcc} optimization switches are potentially usable. These switches
10057 have not been extensively tested with GNAT but can generally be expected
10058 to work. Examples of switches in this category are
10059 @option{-funroll-loops} and
10060 the various target-specific @option{-m} options (in particular, it has been
10061 observed that @option{-march=pentium4} can significantly improve performance
10062 on appropriate machines). For full details of these switches, see
10063 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10064 the GNU Compiler Collection (GCC)}.
10065
10066 @node Optimization and Strict Aliasing
10067 @subsection Optimization and Strict Aliasing
10068 @cindex Aliasing
10069 @cindex Strict Aliasing
10070 @cindex No_Strict_Aliasing
10071
10072 @noindent
10073 The strong typing capabilities of Ada allow an optimizer to generate
10074 efficient code in situations where other languages would be forced to
10075 make worst case assumptions preventing such optimizations. Consider
10076 the following example:
10077
10078 @smallexample @c ada
10079 @cartouche
10080 procedure R is
10081    type Int1 is new Integer;
10082    type Int2 is new Integer;
10083    type Int1A is access Int1;
10084    type Int2A is access Int2;
10085    Int1V : Int1A;
10086    Int2V : Int2A;
10087    @dots{}
10088
10089 begin
10090    @dots{}
10091    for J in Data'Range loop
10092       if Data (J) = Int1V.all then
10093          Int2V.all := Int2V.all + 1;
10094       end if;
10095    end loop;
10096    @dots{}
10097 end R;
10098 @end cartouche
10099 @end smallexample
10100
10101 @noindent
10102 In this example, since the variable @code{Int1V} can only access objects
10103 of type @code{Int1}, and @code{Int2V} can only access objects of type
10104 @code{Int2}, there is no possibility that the assignment to
10105 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10106 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10107 for all iterations of the loop and avoid the extra memory reference
10108 required to dereference it each time through the loop.
10109
10110 This kind of optimization, called strict aliasing analysis, is
10111 triggered by specifying an optimization level of @option{-O2} or
10112 higher and allows @code{GNAT} to generate more efficient code
10113 when access values are involved.
10114
10115 However, although this optimization is always correct in terms of
10116 the formal semantics of the Ada Reference Manual, difficulties can
10117 arise if features like @code{Unchecked_Conversion} are used to break
10118 the typing system. Consider the following complete program example:
10119
10120 @smallexample @c ada
10121 @cartouche
10122 package p1 is
10123    type int1 is new integer;
10124    type int2 is new integer;
10125    type a1 is access int1;
10126    type a2 is access int2;
10127 end p1;
10128
10129 with p1; use p1;
10130 package p2 is
10131    function to_a2 (Input : a1) return a2;
10132 end p2;
10133
10134 with Unchecked_Conversion;
10135 package body p2 is
10136    function to_a2 (Input : a1) return a2 is
10137       function to_a2u is
10138         new Unchecked_Conversion (a1, a2);
10139    begin
10140       return to_a2u (Input);
10141    end to_a2;
10142 end p2;
10143
10144 with p2; use p2;
10145 with p1; use p1;
10146 with Text_IO; use Text_IO;
10147 procedure m is
10148    v1 : a1 := new int1;
10149    v2 : a2 := to_a2 (v1);
10150 begin
10151    v1.all := 1;
10152    v2.all := 0;
10153    put_line (int1'image (v1.all));
10154 end;
10155 @end cartouche
10156 @end smallexample
10157
10158 @noindent
10159 This program prints out 0 in @option{-O0} or @option{-O1}
10160 mode, but it prints out 1 in @option{-O2} mode. That's
10161 because in strict aliasing mode, the compiler can and
10162 does assume that the assignment to @code{v2.all} could not
10163 affect the value of @code{v1.all}, since different types
10164 are involved.
10165
10166 This behavior is not a case of non-conformance with the standard, since
10167 the Ada RM specifies that an unchecked conversion where the resulting
10168 bit pattern is not a correct value of the target type can result in an
10169 abnormal value and attempting to reference an abnormal value makes the
10170 execution of a program erroneous.  That's the case here since the result
10171 does not point to an object of type @code{int2}.  This means that the
10172 effect is entirely unpredictable.
10173
10174 However, although that explanation may satisfy a language
10175 lawyer, in practice an applications programmer expects an
10176 unchecked conversion involving pointers to create true
10177 aliases and the behavior of printing 1 seems plain wrong.
10178 In this case, the strict aliasing optimization is unwelcome.
10179
10180 Indeed the compiler recognizes this possibility, and the
10181 unchecked conversion generates a warning:
10182
10183 @smallexample
10184 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10185 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10186 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10187 @end smallexample
10188
10189 @noindent
10190 Unfortunately the problem is recognized when compiling the body of
10191 package @code{p2}, but the actual "bad" code is generated while
10192 compiling the body of @code{m} and this latter compilation does not see
10193 the suspicious @code{Unchecked_Conversion}.
10194
10195 As implied by the warning message, there are approaches you can use to
10196 avoid the unwanted strict aliasing optimization in a case like this.
10197
10198 One possibility is to simply avoid the use of @option{-O2}, but
10199 that is a bit drastic, since it throws away a number of useful
10200 optimizations that do not involve strict aliasing assumptions.
10201
10202 A less drastic approach is to compile the program using the
10203 option @option{-fno-strict-aliasing}. Actually it is only the
10204 unit containing the dereferencing of the suspicious pointer
10205 that needs to be compiled. So in this case, if we compile
10206 unit @code{m} with this switch, then we get the expected
10207 value of zero printed. Analyzing which units might need
10208 the switch can be painful, so a more reasonable approach
10209 is to compile the entire program with options @option{-O2}
10210 and @option{-fno-strict-aliasing}. If the performance is
10211 satisfactory with this combination of options, then the
10212 advantage is that the entire issue of possible "wrong"
10213 optimization due to strict aliasing is avoided.
10214
10215 To avoid the use of compiler switches, the configuration
10216 pragma @code{No_Strict_Aliasing} with no parameters may be
10217 used to specify that for all access types, the strict
10218 aliasing optimization should be suppressed.
10219
10220 However, these approaches are still overkill, in that they causes
10221 all manipulations of all access values to be deoptimized. A more
10222 refined approach is to concentrate attention on the specific
10223 access type identified as problematic.
10224
10225 First, if a careful analysis of uses of the pointer shows
10226 that there are no possible problematic references, then
10227 the warning can be suppressed by bracketing the
10228 instantiation of @code{Unchecked_Conversion} to turn
10229 the warning off:
10230
10231 @smallexample @c ada
10232    pragma Warnings (Off);
10233    function to_a2u is
10234      new Unchecked_Conversion (a1, a2);
10235    pragma Warnings (On);
10236 @end smallexample
10237
10238 @noindent
10239 Of course that approach is not appropriate for this particular
10240 example, since indeed there is a problematic reference. In this
10241 case we can take one of two other approaches.
10242
10243 The first possibility is to move the instantiation of unchecked
10244 conversion to the unit in which the type is declared. In
10245 this example, we would move the instantiation of
10246 @code{Unchecked_Conversion} from the body of package
10247 @code{p2} to the spec of package @code{p1}. Now the
10248 warning disappears. That's because any use of the
10249 access type knows there is a suspicious unchecked
10250 conversion, and the strict aliasing optimization
10251 is automatically suppressed for the type.
10252
10253 If it is not practical to move the unchecked conversion to the same unit
10254 in which the destination access type is declared (perhaps because the
10255 source type is not visible in that unit), you may use pragma
10256 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10257 same declarative sequence as the declaration of the access type:
10258
10259 @smallexample @c ada
10260    type a2 is access int2;
10261    pragma No_Strict_Aliasing (a2);
10262 @end smallexample
10263
10264 @noindent
10265 Here again, the compiler now knows that the strict aliasing optimization
10266 should be suppressed for any reference to type @code{a2} and the
10267 expected behavior is obtained.
10268
10269 Finally, note that although the compiler can generate warnings for
10270 simple cases of unchecked conversions, there are tricker and more
10271 indirect ways of creating type incorrect aliases which the compiler
10272 cannot detect. Examples are the use of address overlays and unchecked
10273 conversions involving composite types containing access types as
10274 components. In such cases, no warnings are generated, but there can
10275 still be aliasing problems. One safe coding practice is to forbid the
10276 use of address clauses for type overlaying, and to allow unchecked
10277 conversion only for primitive types. This is not really a significant
10278 restriction since any possible desired effect can be achieved by
10279 unchecked conversion of access values.
10280
10281 @ifset vms
10282 @node Coverage Analysis
10283 @subsection Coverage Analysis
10284
10285 @noindent
10286 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10287 the user to determine the distribution of execution time across a program,
10288 @pxref{Profiling} for details of usage.
10289 @end ifset
10290
10291
10292 @node Text_IO Suggestions
10293 @section @code{Text_IO} Suggestions
10294 @cindex @code{Text_IO} and performance
10295
10296 @noindent
10297 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10298 the requirement of maintaining page and line counts. If performance
10299 is critical, a recommendation is to use @code{Stream_IO} instead of
10300 @code{Text_IO} for volume output, since this package has less overhead.
10301
10302 If @code{Text_IO} must be used, note that by default output to the standard
10303 output and standard error files is unbuffered (this provides better
10304 behavior when output statements are used for debugging, or if the
10305 progress of a program is observed by tracking the output, e.g. by
10306 using the Unix @command{tail -f} command to watch redirected output.
10307
10308 If you are generating large volumes of output with @code{Text_IO} and
10309 performance is an important factor, use a designated file instead
10310 of the standard output file, or change the standard output file to
10311 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10312
10313
10314
10315 @node Reducing Size of Ada Executables with gnatelim
10316 @section Reducing Size of Ada Executables with @code{gnatelim}
10317 @findex gnatelim
10318
10319 @noindent
10320 This section describes @command{gnatelim}, a tool which detects unused
10321 subprograms and helps the compiler to create a smaller executable for your
10322 program.
10323
10324 @menu
10325 * About gnatelim::
10326 * Running gnatelim::
10327 * Correcting the List of Eliminate Pragmas::
10328 * Making Your Executables Smaller::
10329 * Summary of the gnatelim Usage Cycle::
10330 @end menu
10331
10332 @node About gnatelim
10333 @subsection About @code{gnatelim}
10334
10335 @noindent
10336 When a program shares a set of Ada
10337 packages with other programs, it may happen that this program uses
10338 only a fraction of the subprograms defined in these packages. The code
10339 created for these unused subprograms increases the size of the executable.
10340
10341 @code{gnatelim} tracks unused subprograms in an Ada program and
10342 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10343 subprograms that are declared but never called. By placing the list of
10344 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10345 recompiling your program, you may decrease the size of its executable,
10346 because the compiler will not generate the code for 'eliminated' subprograms.
10347 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10348 information about this pragma.
10349
10350 @code{gnatelim} needs as its input data the name of the main subprogram
10351 and a bind file for a main subprogram.
10352
10353 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
10354 the main subprogram. @code{gnatelim} can work with both Ada and C
10355 bind files; when both are present, it uses the Ada bind file.
10356 The following commands will build the program and create the bind file:
10357
10358 @smallexample
10359 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10360 $ gnatbind main_prog
10361 @end smallexample
10362
10363 Note that @code{gnatelim} needs neither object nor ALI files.
10364
10365 @node Running gnatelim
10366 @subsection Running @code{gnatelim}
10367
10368 @noindent
10369 @code{gnatelim} has the following command-line interface:
10370
10371 @smallexample
10372 $ gnatelim @ovar{options} name
10373 @end smallexample
10374
10375 @noindent
10376 @code{name} should be a name of a source file that contains the main subprogram
10377 of a program (partition).
10378
10379 @code{gnatelim} has the following switches:
10380
10381 @table @option
10382 @c !sort!
10383 @item ^-q^/QUIET^
10384 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10385 Quiet mode: by default @code{gnatelim} outputs to the standard error
10386 stream the number of program units left to be processed. This option turns
10387 this trace off.
10388
10389 @item ^-v^/VERBOSE^
10390 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10391 Verbose mode: @code{gnatelim} version information is printed as Ada
10392 comments to the standard output stream. Also, in addition to the number of
10393 program units left @code{gnatelim} will output the name of the current unit
10394 being processed.
10395
10396 @item ^-a^/ALL^
10397 @cindex @option{^-a^/ALL^} (@command{gnatelim})
10398 Also look for subprograms from the GNAT run time that can be eliminated. Note
10399 that when @file{gnat.adc} is produced using this switch, the entire program
10400 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
10401
10402 @item ^-I^/INCLUDE_DIRS=^@var{dir}
10403 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
10404 When looking for source files also look in directory @var{dir}. Specifying
10405 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
10406 sources in the current directory.
10407
10408 @item ^-b^/BIND_FILE=^@var{bind_file}
10409 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
10410 Specifies @var{bind_file} as the bind file to process. If not set, the name
10411 of the bind file is computed from the full expanded Ada name
10412 of a main subprogram.
10413
10414 @item ^-C^/CONFIG_FILE=^@var{config_file}
10415 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
10416 Specifies a file @var{config_file} that contains configuration pragmas. The
10417 file must be specified with full path.
10418
10419 @item ^--GCC^/COMPILER^=@var{compiler_name}
10420 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
10421 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
10422 available on the path.
10423
10424 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
10425 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
10426 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
10427 available on the path.
10428 @end table
10429
10430 @noindent
10431 @code{gnatelim} sends its output to the standard output stream, and all the
10432 tracing and debug information is sent to the standard error stream.
10433 In order to produce a proper GNAT configuration file
10434 @file{gnat.adc}, redirection must be used:
10435
10436 @smallexample
10437 @ifset vms
10438 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
10439 @end ifset
10440 @ifclear vms
10441 $ gnatelim main_prog.adb > gnat.adc
10442 @end ifclear
10443 @end smallexample
10444
10445 @ifclear vms
10446 @noindent
10447 or
10448
10449 @smallexample
10450 $ gnatelim main_prog.adb >> gnat.adc
10451 @end smallexample
10452
10453 @noindent
10454 in order to append the @code{gnatelim} output to the existing contents of
10455 @file{gnat.adc}.
10456 @end ifclear
10457
10458 @node Correcting the List of Eliminate Pragmas
10459 @subsection Correcting the List of Eliminate Pragmas
10460
10461 @noindent
10462 In some rare cases @code{gnatelim} may try to eliminate
10463 subprograms that are actually called in the program. In this case, the
10464 compiler will generate an error message of the form:
10465
10466 @smallexample
10467 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
10468 @end smallexample
10469
10470 @noindent
10471 You will need to manually remove the wrong @code{Eliminate} pragmas from
10472 the @file{gnat.adc} file. You should recompile your program
10473 from scratch after that, because you need a consistent @file{gnat.adc} file
10474 during the entire compilation.
10475
10476 @node Making Your Executables Smaller
10477 @subsection Making Your Executables Smaller
10478
10479 @noindent
10480 In order to get a smaller executable for your program you now have to
10481 recompile the program completely with the new @file{gnat.adc} file
10482 created by @code{gnatelim} in your current directory:
10483
10484 @smallexample
10485 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10486 @end smallexample
10487
10488 @noindent
10489 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10490 recompile everything
10491 with the set of pragmas @code{Eliminate} that you have obtained with
10492 @command{gnatelim}).
10493
10494 Be aware that the set of @code{Eliminate} pragmas is specific to each
10495 program. It is not recommended to merge sets of @code{Eliminate}
10496 pragmas created for different programs in one @file{gnat.adc} file.
10497
10498 @node Summary of the gnatelim Usage Cycle
10499 @subsection Summary of the gnatelim Usage Cycle
10500
10501 @noindent
10502 Here is a quick summary of the steps to be taken in order to reduce
10503 the size of your executables with @code{gnatelim}. You may use
10504 other GNAT options to control the optimization level,
10505 to produce the debugging information, to set search path, etc.
10506
10507 @enumerate
10508 @item
10509 Produce a bind file
10510
10511 @smallexample
10512 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10513 $ gnatbind main_prog
10514 @end smallexample
10515
10516 @item
10517 Generate a list of @code{Eliminate} pragmas
10518 @smallexample
10519 @ifset vms
10520 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10521 @end ifset
10522 @ifclear vms
10523 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
10524 @end ifclear
10525 @end smallexample
10526
10527 @item
10528 Recompile the application
10529
10530 @smallexample
10531 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10532 @end smallexample
10533
10534 @end enumerate
10535
10536 @node Reducing Size of Executables with unused subprogram/data elimination
10537 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10538 @findex unused subprogram/data elimination
10539
10540 @noindent
10541 This section describes how you can eliminate unused subprograms and data from
10542 your executable just by setting options at compilation time.
10543
10544 @menu
10545 * About unused subprogram/data elimination::
10546 * Compilation options::
10547 * Example of unused subprogram/data elimination::
10548 @end menu
10549
10550 @node About unused subprogram/data elimination
10551 @subsection About unused subprogram/data elimination
10552
10553 @noindent
10554 By default, an executable contains all code and data of its composing objects
10555 (directly linked or coming from statically linked libraries), even data or code
10556 never used by this executable.
10557
10558 This feature will allow you to eliminate such unused code from your
10559 executable, making it smaller (in disk and in memory).
10560
10561 This functionality is available on all Linux platforms except for the IA-64
10562 architecture and on all cross platforms using the ELF binary file format.
10563 In both cases GNU binutils version 2.16 or later are required to enable it.
10564
10565 @node Compilation options
10566 @subsection Compilation options
10567
10568 @noindent
10569 The operation of eliminating the unused code and data from the final executable
10570 is directly performed by the linker.
10571
10572 In order to do this, it has to work with objects compiled with the
10573 following options:
10574 @option{-ffunction-sections} @option{-fdata-sections}.
10575 @cindex @option{-ffunction-sections} (@command{gcc})
10576 @cindex @option{-fdata-sections} (@command{gcc})
10577 These options are usable with C and Ada files.
10578 They will place respectively each
10579 function or data in a separate section in the resulting object file.
10580
10581 Once the objects and static libraries are created with these options, the
10582 linker can perform the dead code elimination. You can do this by setting
10583 the @option{-Wl,--gc-sections} option to gcc command or in the
10584 @option{-largs} section of @command{gnatmake}. This will perform a
10585 garbage collection of code and data never referenced.
10586
10587 If the linker performs a partial link (@option{-r} ld linker option), then you
10588 will need to provide one or several entry point using the
10589 @option{-e} / @option{--entry} ld option.
10590
10591 Note that objects compiled without the @option{-ffunction-sections} and
10592 @option{-fdata-sections} options can still be linked with the executable.
10593 However, no dead code elimination will be performed on those objects (they will
10594 be linked as is).
10595
10596 The GNAT static library is now compiled with -ffunction-sections and
10597 -fdata-sections on some platforms. This allows you to eliminate the unused code
10598 and data of the GNAT library from your executable.
10599
10600 @node Example of unused subprogram/data elimination
10601 @subsection Example of unused subprogram/data elimination
10602
10603 @noindent
10604 Here is a simple example:
10605
10606 @smallexample @c ada
10607 with Aux;
10608
10609 procedure Test is
10610 begin
10611    Aux.Used (10);
10612 end Test;
10613
10614 package Aux is
10615    Used_Data   : Integer;
10616    Unused_Data : Integer;
10617
10618    procedure Used   (Data : Integer);
10619    procedure Unused (Data : Integer);
10620 end Aux;
10621
10622 package body Aux is
10623    procedure Used (Data : Integer) is
10624    begin
10625       Used_Data := Data;
10626    end Used;
10627
10628    procedure Unused (Data : Integer) is
10629    begin
10630       Unused_Data := Data;
10631    end Unused;
10632 end Aux;
10633 @end smallexample
10634
10635 @noindent
10636 @code{Unused} and @code{Unused_Data} are never referenced in this code
10637 excerpt, and hence they may be safely removed from the final executable.
10638
10639 @smallexample
10640 $ gnatmake test
10641
10642 $ nm test | grep used
10643 020015f0 T aux__unused
10644 02005d88 B aux__unused_data
10645 020015cc T aux__used
10646 02005d84 B aux__used_data
10647
10648 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10649      -largs -Wl,--gc-sections
10650
10651 $ nm test | grep used
10652 02005350 T aux__used
10653 0201ffe0 B aux__used_data
10654 @end smallexample
10655
10656 @noindent
10657 It can be observed that the procedure @code{Unused} and the object
10658 @code{Unused_Data} are removed by the linker when using the
10659 appropriate options.
10660
10661 @c ********************************
10662 @node Renaming Files Using gnatchop
10663 @chapter Renaming Files Using @code{gnatchop}
10664 @findex gnatchop
10665
10666 @noindent
10667 This chapter discusses how to handle files with multiple units by using
10668 the @code{gnatchop} utility. This utility is also useful in renaming
10669 files to meet the standard GNAT default file naming conventions.
10670
10671 @menu
10672 * Handling Files with Multiple Units::
10673 * Operating gnatchop in Compilation Mode::
10674 * Command Line for gnatchop::
10675 * Switches for gnatchop::
10676 * Examples of gnatchop Usage::
10677 @end menu
10678
10679 @node Handling Files with Multiple Units
10680 @section Handling Files with Multiple Units
10681
10682 @noindent
10683 The basic compilation model of GNAT requires that a file submitted to the
10684 compiler have only one unit and there be a strict correspondence
10685 between the file name and the unit name.
10686
10687 The @code{gnatchop} utility allows both of these rules to be relaxed,
10688 allowing GNAT to process files which contain multiple compilation units
10689 and files with arbitrary file names. @code{gnatchop}
10690 reads the specified file and generates one or more output files,
10691 containing one unit per file. The unit and the file name correspond,
10692 as required by GNAT.
10693
10694 If you want to permanently restructure a set of ``foreign'' files so that
10695 they match the GNAT rules, and do the remaining development using the
10696 GNAT structure, you can simply use @command{gnatchop} once, generate the
10697 new set of files and work with them from that point on.
10698
10699 Alternatively, if you want to keep your files in the ``foreign'' format,
10700 perhaps to maintain compatibility with some other Ada compilation
10701 system, you can set up a procedure where you use @command{gnatchop} each
10702 time you compile, regarding the source files that it writes as temporary
10703 files that you throw away.
10704
10705 @node Operating gnatchop in Compilation Mode
10706 @section Operating gnatchop in Compilation Mode
10707
10708 @noindent
10709 The basic function of @code{gnatchop} is to take a file with multiple units
10710 and split it into separate files. The boundary between files is reasonably
10711 clear, except for the issue of comments and pragmas. In default mode, the
10712 rule is that any pragmas between units belong to the previous unit, except
10713 that configuration pragmas always belong to the following unit. Any comments
10714 belong to the following unit. These rules
10715 almost always result in the right choice of
10716 the split point without needing to mark it explicitly and most users will
10717 find this default to be what they want. In this default mode it is incorrect to
10718 submit a file containing only configuration pragmas, or one that ends in
10719 configuration pragmas, to @code{gnatchop}.
10720
10721 However, using a special option to activate ``compilation mode'',
10722 @code{gnatchop}
10723 can perform another function, which is to provide exactly the semantics
10724 required by the RM for handling of configuration pragmas in a compilation.
10725 In the absence of configuration pragmas (at the main file level), this
10726 option has no effect, but it causes such configuration pragmas to be handled
10727 in a quite different manner.
10728
10729 First, in compilation mode, if @code{gnatchop} is given a file that consists of
10730 only configuration pragmas, then this file is appended to the
10731 @file{gnat.adc} file in the current directory. This behavior provides
10732 the required behavior described in the RM for the actions to be taken
10733 on submitting such a file to the compiler, namely that these pragmas
10734 should apply to all subsequent compilations in the same compilation
10735 environment. Using GNAT, the current directory, possibly containing a
10736 @file{gnat.adc} file is the representation
10737 of a compilation environment. For more information on the
10738 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
10739
10740 Second, in compilation mode, if @code{gnatchop}
10741 is given a file that starts with
10742 configuration pragmas, and contains one or more units, then these
10743 configuration pragmas are prepended to each of the chopped files. This
10744 behavior provides the required behavior described in the RM for the
10745 actions to be taken on compiling such a file, namely that the pragmas
10746 apply to all units in the compilation, but not to subsequently compiled
10747 units.
10748
10749 Finally, if configuration pragmas appear between units, they are appended
10750 to the previous unit. This results in the previous unit being illegal,
10751 since the compiler does not accept configuration pragmas that follow
10752 a unit. This provides the required RM behavior that forbids configuration
10753 pragmas other than those preceding the first compilation unit of a
10754 compilation.
10755
10756 For most purposes, @code{gnatchop} will be used in default mode. The
10757 compilation mode described above is used only if you need exactly
10758 accurate behavior with respect to compilations, and you have files
10759 that contain multiple units and configuration pragmas. In this
10760 circumstance the use of @code{gnatchop} with the compilation mode
10761 switch provides the required behavior, and is for example the mode
10762 in which GNAT processes the ACVC tests.
10763
10764 @node Command Line for gnatchop
10765 @section Command Line for @code{gnatchop}
10766
10767 @noindent
10768 The @code{gnatchop} command has the form:
10769
10770 @smallexample
10771 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
10772       @ovar{directory}
10773 @end smallexample
10774
10775 @noindent
10776 The only required argument is the file name of the file to be chopped.
10777 There are no restrictions on the form of this file name. The file itself
10778 contains one or more Ada units, in normal GNAT format, concatenated
10779 together. As shown, more than one file may be presented to be chopped.
10780
10781 When run in default mode, @code{gnatchop} generates one output file in
10782 the current directory for each unit in each of the files.
10783
10784 @var{directory}, if specified, gives the name of the directory to which
10785 the output files will be written. If it is not specified, all files are
10786 written to the current directory.
10787
10788 For example, given a
10789 file called @file{hellofiles} containing
10790
10791 @smallexample @c ada
10792 @group
10793 @cartouche
10794 procedure hello;
10795
10796 with Text_IO; use Text_IO;
10797 procedure hello is
10798 begin
10799    Put_Line ("Hello");
10800 end hello;
10801 @end cartouche
10802 @end group
10803 @end smallexample
10804
10805 @noindent
10806 the command
10807
10808 @smallexample
10809 $ gnatchop ^hellofiles^HELLOFILES.^
10810 @end smallexample
10811
10812 @noindent
10813 generates two files in the current directory, one called
10814 @file{hello.ads} containing the single line that is the procedure spec,
10815 and the other called @file{hello.adb} containing the remaining text. The
10816 original file is not affected. The generated files can be compiled in
10817 the normal manner.
10818
10819 @noindent
10820 When gnatchop is invoked on a file that is empty or that contains only empty
10821 lines and/or comments, gnatchop will not fail, but will not produce any
10822 new sources.
10823
10824 For example, given a
10825 file called @file{toto.txt} containing
10826
10827 @smallexample @c ada
10828 @group
10829 @cartouche
10830 --  Just a comment
10831 @end cartouche
10832 @end group
10833 @end smallexample
10834
10835 @noindent
10836 the command
10837
10838 @smallexample
10839 $ gnatchop ^toto.txt^TOT.TXT^
10840 @end smallexample
10841
10842 @noindent
10843 will not produce any new file and will result in the following warnings:
10844
10845 @smallexample
10846 toto.txt:1:01: warning: empty file, contains no compilation units
10847 no compilation units found
10848 no source files written
10849 @end smallexample
10850
10851 @node Switches for gnatchop
10852 @section Switches for @code{gnatchop}
10853
10854 @noindent
10855 @command{gnatchop} recognizes the following switches:
10856
10857 @table @option
10858 @c !sort!
10859
10860 @item --version
10861 @cindex @option{--version} @command{gnatchop}
10862 Display Copyright and version, then exit disregarding all other options.
10863
10864 @item --help
10865 @cindex @option{--help} @command{gnatchop}
10866 If @option{--version} was not used, display usage, then exit disregarding
10867 all other options.
10868
10869 @item ^-c^/COMPILATION^
10870 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
10871 Causes @code{gnatchop} to operate in compilation mode, in which
10872 configuration pragmas are handled according to strict RM rules. See
10873 previous section for a full description of this mode.
10874
10875 @ifclear vms
10876 @item -gnat@var{xxx}
10877 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
10878 used to parse the given file. Not all @var{xxx} options make sense,
10879 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
10880 process a source file that uses Latin-2 coding for identifiers.
10881 @end ifclear
10882
10883 @item ^-h^/HELP^
10884 Causes @code{gnatchop} to generate a brief help summary to the standard
10885 output file showing usage information.
10886
10887 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
10888 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
10889 Limit generated file names to the specified number @code{mm}
10890 of characters.
10891 This is useful if the
10892 resulting set of files is required to be interoperable with systems
10893 which limit the length of file names.
10894 @ifset vms
10895 If no value is given, or
10896 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
10897 a default of 39, suitable for OpenVMS Alpha
10898 Systems, is assumed
10899 @end ifset
10900 @ifclear vms
10901 No space is allowed between the @option{-k} and the numeric value. The numeric
10902 value may be omitted in which case a default of @option{-k8},
10903 suitable for use
10904 with DOS-like file systems, is used. If no @option{-k} switch
10905 is present then
10906 there is no limit on the length of file names.
10907 @end ifclear
10908
10909 @item ^-p^/PRESERVE^
10910 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
10911 Causes the file ^modification^creation^ time stamp of the input file to be
10912 preserved and used for the time stamp of the output file(s). This may be
10913 useful for preserving coherency of time stamps in an environment where
10914 @code{gnatchop} is used as part of a standard build process.
10915
10916 @item ^-q^/QUIET^
10917 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
10918 Causes output of informational messages indicating the set of generated
10919 files to be suppressed. Warnings and error messages are unaffected.
10920
10921 @item ^-r^/REFERENCE^
10922 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
10923 @findex Source_Reference
10924 Generate @code{Source_Reference} pragmas. Use this switch if the output
10925 files are regarded as temporary and development is to be done in terms
10926 of the original unchopped file. This switch causes
10927 @code{Source_Reference} pragmas to be inserted into each of the
10928 generated files to refers back to the original file name and line number.
10929 The result is that all error messages refer back to the original
10930 unchopped file.
10931 In addition, the debugging information placed into the object file (when
10932 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
10933 specified)
10934 also refers back to this original file so that tools like profilers and
10935 debuggers will give information in terms of the original unchopped file.
10936
10937 If the original file to be chopped itself contains
10938 a @code{Source_Reference}
10939 pragma referencing a third file, then gnatchop respects
10940 this pragma, and the generated @code{Source_Reference} pragmas
10941 in the chopped file refer to the original file, with appropriate
10942 line numbers. This is particularly useful when @code{gnatchop}
10943 is used in conjunction with @code{gnatprep} to compile files that
10944 contain preprocessing statements and multiple units.
10945
10946 @item ^-v^/VERBOSE^
10947 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
10948 Causes @code{gnatchop} to operate in verbose mode. The version
10949 number and copyright notice are output, as well as exact copies of
10950 the gnat1 commands spawned to obtain the chop control information.
10951
10952 @item ^-w^/OVERWRITE^
10953 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
10954 Overwrite existing file names. Normally @code{gnatchop} regards it as a
10955 fatal error if there is already a file with the same name as a
10956 file it would otherwise output, in other words if the files to be
10957 chopped contain duplicated units. This switch bypasses this
10958 check, and causes all but the last instance of such duplicated
10959 units to be skipped.
10960
10961 @ifclear vms
10962 @item --GCC=@var{xxxx}
10963 @cindex @option{--GCC=} (@code{gnatchop})
10964 Specify the path of the GNAT parser to be used. When this switch is used,
10965 no attempt is made to add the prefix to the GNAT parser executable.
10966 @end ifclear
10967 @end table
10968
10969 @node Examples of gnatchop Usage
10970 @section Examples of @code{gnatchop} Usage
10971
10972 @table @code
10973 @ifset vms
10974 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
10975 @end ifset
10976 @ifclear vms
10977 @item gnatchop -w hello_s.ada prerelease/files
10978 @end ifclear
10979
10980 Chops the source file @file{hello_s.ada}. The output files will be
10981 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
10982 overwriting any
10983 files with matching names in that directory (no files in the current
10984 directory are modified).
10985
10986 @item gnatchop ^archive^ARCHIVE.^
10987 Chops the source file @file{^archive^ARCHIVE.^}
10988 into the current directory. One
10989 useful application of @code{gnatchop} is in sending sets of sources
10990 around, for example in email messages. The required sources are simply
10991 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
10992 command), and then
10993 @command{gnatchop} is used at the other end to reconstitute the original
10994 file names.
10995
10996 @item gnatchop file1 file2 file3 direc
10997 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
10998 the resulting files in the directory @file{direc}. Note that if any units
10999 occur more than once anywhere within this set of files, an error message
11000 is generated, and no files are written. To override this check, use the
11001 @option{^-w^/OVERWRITE^} switch,
11002 in which case the last occurrence in the last file will
11003 be the one that is output, and earlier duplicate occurrences for a given
11004 unit will be skipped.
11005 @end table
11006
11007 @node Configuration Pragmas
11008 @chapter Configuration Pragmas
11009 @cindex Configuration pragmas
11010 @cindex Pragmas, configuration
11011
11012 @noindent
11013 Configuration pragmas include those pragmas described as
11014 such in the Ada Reference Manual, as well as
11015 implementation-dependent pragmas that are configuration pragmas.
11016 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11017 for details on these additional GNAT-specific configuration pragmas.
11018 Most notably, the pragma @code{Source_File_Name}, which allows
11019 specifying non-default names for source files, is a configuration
11020 pragma. The following is a complete list of configuration pragmas
11021 recognized by GNAT:
11022
11023 @smallexample
11024    Ada_83
11025    Ada_95
11026    Ada_05
11027    Ada_2005
11028    Assertion_Policy
11029    C_Pass_By_Copy
11030    Check_Name
11031    Check_Policy
11032    Compile_Time_Error
11033    Compile_Time_Warning
11034    Compiler_Unit
11035    Component_Alignment
11036    Debug_Policy
11037    Detect_Blocking
11038    Discard_Names
11039    Elaboration_Checks
11040    Eliminate
11041    Extend_System
11042    External_Name_Casing
11043    Fast_Math
11044    Favor_Top_Level
11045    Float_Representation
11046    Implicit_Packing
11047    Initialize_Scalars
11048    Interrupt_State
11049    License
11050    Locking_Policy
11051    Long_Float
11052    No_Run_Time
11053    No_Strict_Aliasing
11054    Normalize_Scalars
11055    Optimize_Alignment
11056    Persistent_BSS
11057    Polling
11058    Priority_Specific_Dispatching
11059    Profile
11060    Profile_Warnings
11061    Propagate_Exceptions
11062    Queuing_Policy
11063    Ravenscar
11064    Restricted_Run_Time
11065    Restrictions
11066    Restrictions_Warnings
11067    Reviewable
11068    Source_File_Name
11069    Source_File_Name_Project
11070    Style_Checks
11071    Suppress
11072    Suppress_Exception_Locations
11073    Task_Dispatching_Policy
11074    Universal_Data
11075    Unsuppress
11076    Use_VADS_Size
11077    Validity_Checks
11078    Warnings
11079    Wide_Character_Encoding
11080
11081 @end smallexample
11082
11083 @menu
11084 * Handling of Configuration Pragmas::
11085 * The Configuration Pragmas Files::
11086 @end menu
11087
11088 @node Handling of Configuration Pragmas
11089 @section Handling of Configuration Pragmas
11090
11091 Configuration pragmas may either appear at the start of a compilation
11092 unit, in which case they apply only to that unit, or they may apply to
11093 all compilations performed in a given compilation environment.
11094
11095 GNAT also provides the @code{gnatchop} utility to provide an automatic
11096 way to handle configuration pragmas following the semantics for
11097 compilations (that is, files with multiple units), described in the RM.
11098 See @ref{Operating gnatchop in Compilation Mode} for details.
11099 However, for most purposes, it will be more convenient to edit the
11100 @file{gnat.adc} file that contains configuration pragmas directly,
11101 as described in the following section.
11102
11103 @node The Configuration Pragmas Files
11104 @section The Configuration Pragmas Files
11105 @cindex @file{gnat.adc}
11106
11107 @noindent
11108 In GNAT a compilation environment is defined by the current
11109 directory at the time that a compile command is given. This current
11110 directory is searched for a file whose name is @file{gnat.adc}. If
11111 this file is present, it is expected to contain one or more
11112 configuration pragmas that will be applied to the current compilation.
11113 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11114 considered.
11115
11116 Configuration pragmas may be entered into the @file{gnat.adc} file
11117 either by running @code{gnatchop} on a source file that consists only of
11118 configuration pragmas, or more conveniently  by
11119 direct editing of the @file{gnat.adc} file, which is a standard format
11120 source file.
11121
11122 In addition to @file{gnat.adc}, additional files containing configuration
11123 pragmas may be applied to the current compilation using the switch
11124 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11125 contains only configuration pragmas. These configuration pragmas are
11126 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11127 is present and switch @option{-gnatA} is not used).
11128
11129 It is allowed to specify several switches @option{-gnatec}, all of which
11130 will be taken into account.
11131
11132 If you are using project file, a separate mechanism is provided using
11133 project attributes, see @ref{Specifying Configuration Pragmas} for more
11134 details.
11135
11136 @ifset vms
11137 Of special interest to GNAT OpenVMS Alpha is the following
11138 configuration pragma:
11139
11140 @smallexample @c ada
11141 @cartouche
11142 pragma Extend_System (Aux_DEC);
11143 @end cartouche
11144 @end smallexample
11145
11146 @noindent
11147 In the presence of this pragma, GNAT adds to the definition of the
11148 predefined package SYSTEM all the additional types and subprograms that are
11149 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11150 @end ifset
11151
11152 @node Handling Arbitrary File Naming Conventions Using gnatname
11153 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11154 @cindex Arbitrary File Naming Conventions
11155
11156 @menu
11157 * Arbitrary File Naming Conventions::
11158 * Running gnatname::
11159 * Switches for gnatname::
11160 * Examples of gnatname Usage::
11161 @end menu
11162
11163 @node Arbitrary File Naming Conventions
11164 @section Arbitrary File Naming Conventions
11165
11166 @noindent
11167 The GNAT compiler must be able to know the source file name of a compilation
11168 unit.  When using the standard GNAT default file naming conventions
11169 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11170 does not need additional information.
11171
11172 @noindent
11173 When the source file names do not follow the standard GNAT default file naming
11174 conventions, the GNAT compiler must be given additional information through
11175 a configuration pragmas file (@pxref{Configuration Pragmas})
11176 or a project file.
11177 When the non-standard file naming conventions are well-defined,
11178 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11179 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11180 if the file naming conventions are irregular or arbitrary, a number
11181 of pragma @code{Source_File_Name} for individual compilation units
11182 must be defined.
11183 To help maintain the correspondence between compilation unit names and
11184 source file names within the compiler,
11185 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11186 set of files.
11187
11188 @node Running gnatname
11189 @section Running @code{gnatname}
11190
11191 @noindent
11192 The usual form of the @code{gnatname} command is
11193
11194 @smallexample
11195 $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11196       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11197 @end smallexample
11198
11199 @noindent
11200 All of the arguments are optional. If invoked without any argument,
11201 @code{gnatname} will display its usage.
11202
11203 @noindent
11204 When used with at least one naming pattern, @code{gnatname} will attempt to
11205 find all the compilation units in files that follow at least one of the
11206 naming patterns. To find these compilation units,
11207 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11208 regular files.
11209
11210 @noindent
11211 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11212 Each Naming Pattern is enclosed between double quotes.
11213 A Naming Pattern is a regular expression similar to the wildcard patterns
11214 used in file names by the Unix shells or the DOS prompt.
11215
11216 @noindent
11217 @code{gnatname} may be called with several sections of directories/patterns.
11218 Sections are separated by switch @code{--and}. In each section, there must be
11219 at least one pattern. If no directory is specified in a section, the current
11220 directory (or the project directory is @code{-P} is used) is implied.
11221 The options other that the directory switches and the patterns apply globally
11222 even if they are in different sections.
11223
11224 @noindent
11225 Examples of Naming Patterns are
11226
11227 @smallexample
11228    "*.[12].ada"
11229    "*.ad[sb]*"
11230    "body_*"    "spec_*"
11231 @end smallexample
11232
11233 @noindent
11234 For a more complete description of the syntax of Naming Patterns,
11235 see the second kind of regular expressions described in @file{g-regexp.ads}
11236 (the ``Glob'' regular expressions).
11237
11238 @noindent
11239 When invoked with no switch @code{-P}, @code{gnatname} will create a
11240 configuration pragmas file @file{gnat.adc} in the current working directory,
11241 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11242 unit.
11243
11244 @node Switches for gnatname
11245 @section Switches for @code{gnatname}
11246
11247 @noindent
11248 Switches for @code{gnatname} must precede any specified Naming Pattern.
11249
11250 @noindent
11251 You may specify any of the following switches to @code{gnatname}:
11252
11253 @table @option
11254 @c !sort!
11255
11256 @item --version
11257 @cindex @option{--version} @command{gnatname}
11258 Display Copyright and version, then exit disregarding all other options.
11259
11260 @item --help
11261 @cindex @option{--help} @command{gnatname}
11262 If @option{--version} was not used, display usage, then exit disregarding
11263 all other options.
11264
11265 @item --and
11266 Start another section of directories/patterns.
11267
11268 @item ^-c^/CONFIG_FILE=^@file{file}
11269 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11270 Create a configuration pragmas file @file{file} (instead of the default
11271 @file{gnat.adc}).
11272 @ifclear vms
11273 There may be zero, one or more space between @option{-c} and
11274 @file{file}.
11275 @end ifclear
11276 @file{file} may include directory information. @file{file} must be
11277 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11278 When a switch @option{^-c^/CONFIG_FILE^} is
11279 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11280
11281 @item ^-d^/SOURCE_DIRS=^@file{dir}
11282 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11283 Look for source files in directory @file{dir}. There may be zero, one or more
11284 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11285 When a switch @option{^-d^/SOURCE_DIRS^}
11286 is specified, the current working directory will not be searched for source
11287 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11288 or @option{^-D^/DIR_FILES^} switch.
11289 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11290 If @file{dir} is a relative path, it is relative to the directory of
11291 the configuration pragmas file specified with switch
11292 @option{^-c^/CONFIG_FILE^},
11293 or to the directory of the project file specified with switch
11294 @option{^-P^/PROJECT_FILE^} or,
11295 if neither switch @option{^-c^/CONFIG_FILE^}
11296 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11297 current working directory. The directory
11298 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11299
11300 @item ^-D^/DIRS_FILE=^@file{file}
11301 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11302 Look for source files in all directories listed in text file @file{file}.
11303 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11304 and @file{file}.
11305 @file{file} must be an existing, readable text file.
11306 Each nonempty line in @file{file} must be a directory.
11307 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11308 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11309 @file{file}.
11310
11311 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11312 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11313 Foreign patterns. Using this switch, it is possible to add sources of languages
11314 other than Ada to the list of sources of a project file.
11315 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11316 For example,
11317 @smallexample
11318 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11319 @end smallexample
11320 @noindent
11321 will look for Ada units in all files with the @file{.ada} extension,
11322 and will add to the list of file for project @file{prj.gpr} the C files
11323 with extension @file{.^c^C^}.
11324
11325 @item ^-h^/HELP^
11326 @cindex @option{^-h^/HELP^} (@code{gnatname})
11327 Output usage (help) information. The output is written to @file{stdout}.
11328
11329 @item ^-P^/PROJECT_FILE=^@file{proj}
11330 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11331 Create or update project file @file{proj}. There may be zero, one or more space
11332 between @option{-P} and @file{proj}. @file{proj} may include directory
11333 information. @file{proj} must be writable.
11334 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11335 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11336 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11337
11338 @item ^-v^/VERBOSE^
11339 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11340 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11341 This includes name of the file written, the name of the directories to search
11342 and, for each file in those directories whose name matches at least one of
11343 the Naming Patterns, an indication of whether the file contains a unit,
11344 and if so the name of the unit.
11345
11346 @item ^-v -v^/VERBOSE /VERBOSE^
11347 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11348 Very Verbose mode. In addition to the output produced in verbose mode,
11349 for each file in the searched directories whose name matches none of
11350 the Naming Patterns, an indication is given that there is no match.
11351
11352 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11353 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11354 Excluded patterns. Using this switch, it is possible to exclude some files
11355 that would match the name patterns. For example,
11356 @smallexample
11357 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11358 @end smallexample
11359 @noindent
11360 will look for Ada units in all files with the @file{.ada} extension,
11361 except those whose names end with @file{_nt.ada}.
11362
11363 @end table
11364
11365 @node Examples of gnatname Usage
11366 @section Examples of @code{gnatname} Usage
11367
11368 @ifset vms
11369 @smallexample
11370 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11371 @end smallexample
11372 @end ifset
11373
11374 @ifclear vms
11375 @smallexample
11376 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11377 @end smallexample
11378 @end ifclear
11379
11380 @noindent
11381 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11382 and be writable. In addition, the directory
11383 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11384 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11385
11386 @ifclear vms
11387 Note the optional spaces after @option{-c} and @option{-d}.
11388 @end ifclear
11389
11390 @smallexample
11391 @ifclear vms
11392 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11393   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11394 @end ifclear
11395 @ifset vms
11396 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11397   /EXCLUDED_PATTERN=*_nt_body.ada
11398   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11399   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11400 @end ifset
11401 @end smallexample
11402
11403 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11404 even in conjunction with one or several switches
11405 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11406 are used in this example.
11407
11408 @c *****************************************
11409 @c * G N A T  P r o j e c t  M a n a g e r *
11410 @c *****************************************
11411 @node GNAT Project Manager
11412 @chapter GNAT Project Manager
11413
11414 @menu
11415 * Introduction::
11416 * Examples of Project Files::
11417 * Project File Syntax::
11418 * Objects and Sources in Project Files::
11419 * Importing Projects::
11420 * Project Extension::
11421 * Project Hierarchy Extension::
11422 * External References in Project Files::
11423 * Packages in Project Files::
11424 * Variables from Imported Projects::
11425 * Naming Schemes::
11426 * Library Projects::
11427 * Stand-alone Library Projects::
11428 * Switches Related to Project Files::
11429 * Tools Supporting Project Files::
11430 * An Extended Example::
11431 * Project File Complete Syntax::
11432 @end menu
11433
11434 @c ****************
11435 @c * Introduction *
11436 @c ****************
11437
11438 @node Introduction
11439 @section Introduction
11440
11441 @noindent
11442 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
11443 you to manage complex builds involving a number of source files, directories,
11444 and compilation options for different system configurations. In particular,
11445 project files allow you to specify:
11446 @itemize @bullet
11447 @item
11448 The directory or set of directories containing the source files, and/or the
11449 names of the specific source files themselves
11450 @item
11451 The directory in which the compiler's output
11452 (@file{ALI} files, object files, tree files) is to be placed
11453 @item
11454 The directory in which the executable programs is to be placed
11455 @item
11456 ^Switch^Switch^ settings for any of the project-enabled tools
11457 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
11458 @code{gnatfind}); you can apply these settings either globally or to individual
11459 compilation units.
11460 @item
11461 The source files containing the main subprogram(s) to be built
11462 @item
11463 The source programming language(s) (currently Ada and/or C)
11464 @item
11465 Source file naming conventions; you can specify these either globally or for
11466 individual compilation units
11467 @end itemize
11468
11469 @menu
11470 * Project Files::
11471 @end menu
11472
11473 @node Project Files
11474 @subsection Project Files
11475
11476 @noindent
11477 Project files are written in a syntax close to that of Ada, using  familiar
11478 notions such as packages, context clauses, declarations, default values,
11479 assignments, and inheritance. Finally, project files can be built
11480 hierarchically from other project files, simplifying complex system
11481 integration and project reuse.
11482
11483 A @dfn{project} is a specific set of values for various compilation properties.
11484 The settings for a given project are described by means of
11485 a @dfn{project file}, which is a text file written in an Ada-like syntax.
11486 Property values in project files are either strings or lists of strings.
11487 Properties that are not explicitly set receive default values.  A project
11488 file may interrogate the values of @dfn{external variables} (user-defined
11489 command-line switches or environment variables), and it may specify property
11490 settings conditionally, based on the value of such variables.
11491
11492 In simple cases, a project's source files depend only on other source files
11493 in the same project, or on the predefined libraries.  (@emph{Dependence} is
11494 used in
11495 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
11496 the Project Manager also allows more sophisticated arrangements,
11497 where the source files in one project depend on source files in other
11498 projects:
11499 @itemize @bullet
11500 @item
11501 One project can @emph{import} other projects containing needed source files.
11502 @item
11503 You can organize GNAT projects in a hierarchy: a @emph{child} project
11504 can extend a @emph{parent} project, inheriting the parent's source files and
11505 optionally overriding any of them with alternative versions
11506 @end itemize
11507
11508 @noindent
11509 More generally, the Project Manager lets you structure large development
11510 efforts into hierarchical subsystems, where build decisions are delegated
11511 to the subsystem level, and thus different compilation environments
11512 (^switch^switch^ settings) used for different subsystems.
11513
11514 The Project Manager is invoked through the
11515 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
11516 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
11517 @ifclear vms
11518 There may be zero, one or more spaces between @option{-P} and
11519 @option{@emph{projectfile}}.
11520 @end ifclear
11521 If you want to define (on the command line) an external variable that is
11522 queried by the project file, you must use the
11523 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11524 The Project Manager parses and interprets the project file, and drives the
11525 invoked tool based on the project settings.
11526
11527 The Project Manager supports a wide range of development strategies,
11528 for systems of all sizes.  Here are some typical practices that are
11529 easily handled:
11530 @itemize @bullet
11531 @item
11532 Using a common set of source files, but generating object files in different
11533 directories via different ^switch^switch^ settings
11534 @item
11535 Using a mostly-shared set of source files, but with different versions of
11536 some unit or units
11537 @end itemize
11538
11539 @noindent
11540 The destination of an executable can be controlled inside a project file
11541 using the @option{^-o^-o^}
11542 ^switch^switch^.
11543 In the absence of such a ^switch^switch^ either inside
11544 the project file or on the command line, any executable files generated by
11545 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
11546 in the project file. If no @code{Exec_Dir} is specified, they will be placed
11547 in the object directory of the project.
11548
11549 You can use project files to achieve some of the effects of a source
11550 versioning system (for example, defining separate projects for
11551 the different sets of sources that comprise different releases) but the
11552 Project Manager is independent of any source configuration management tools
11553 that might be used by the developers.
11554
11555 The next section introduces the main features of GNAT's project facility
11556 through a sequence of examples; subsequent sections will present the syntax
11557 and semantics in more detail. A more formal description of the project
11558 facility appears in @ref{Project File Reference,,, gnat_rm, GNAT
11559 Reference Manual}.
11560
11561 @c *****************************
11562 @c * Examples of Project Files *
11563 @c *****************************
11564
11565 @node Examples of Project Files
11566 @section Examples of Project Files
11567 @noindent
11568 This section illustrates some of the typical uses of project files and
11569 explains their basic structure and behavior.
11570
11571 @menu
11572 * Common Sources with Different ^Switches^Switches^ and Directories::
11573 * Using External Variables::
11574 * Importing Other Projects::
11575 * Extending a Project::
11576 @end menu
11577
11578 @node Common Sources with Different ^Switches^Switches^ and Directories
11579 @subsection Common Sources with Different ^Switches^Switches^ and Directories
11580
11581 @menu
11582 * Source Files::
11583 * Specifying the Object Directory::
11584 * Specifying the Exec Directory::
11585 * Project File Packages::
11586 * Specifying ^Switch^Switch^ Settings::
11587 * Main Subprograms::
11588 * Executable File Names::
11589 * Source File Naming Conventions::
11590 * Source Language(s)::
11591 @end menu
11592
11593 @noindent
11594 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
11595 @file{proc.adb} are in the @file{/common} directory.  The file
11596 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
11597 package @code{Pack}.  We want to compile these source files under two sets
11598 of ^switches^switches^:
11599 @itemize @bullet
11600 @item
11601 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
11602 and the @option{^-gnata^-gnata^},
11603 @option{^-gnato^-gnato^},
11604 and @option{^-gnatE^-gnatE^} switches to the
11605 compiler; the compiler's output is to appear in @file{/common/debug}
11606 @item
11607 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
11608 to the compiler; the compiler's output is to appear in @file{/common/release}
11609 @end itemize
11610
11611 @noindent
11612 The GNAT project files shown below, respectively @file{debug.gpr} and
11613 @file{release.gpr} in the @file{/common} directory, achieve these effects.
11614
11615 Schematically:
11616 @smallexample
11617 @group
11618 ^/common^[COMMON]^
11619   debug.gpr
11620   release.gpr
11621   pack.ads
11622   pack.adb
11623   proc.adb
11624 @end group
11625 @group
11626 ^/common/debug^[COMMON.DEBUG]^
11627   proc.ali, proc.o
11628   pack.ali, pack.o
11629 @end group
11630 @group
11631 ^/common/release^[COMMON.RELEASE]^
11632   proc.ali, proc.o
11633   pack.ali, pack.o
11634 @end group
11635 @end smallexample
11636 Here are the corresponding project files:
11637
11638 @smallexample @c projectfile
11639 @group
11640 project Debug is
11641   for Object_Dir use "debug";
11642   for Main use ("proc");
11643
11644   package Builder is
11645     for ^Default_Switches^Default_Switches^ ("Ada")
11646         use ("^-g^-g^");
11647     for Executable ("proc.adb") use "proc1";
11648   end Builder;
11649 @end group
11650
11651 @group
11652   package Compiler is
11653     for ^Default_Switches^Default_Switches^ ("Ada")
11654        use ("-fstack-check",
11655             "^-gnata^-gnata^",
11656             "^-gnato^-gnato^",
11657             "^-gnatE^-gnatE^");
11658   end Compiler;
11659 end Debug;
11660 @end group
11661 @end smallexample
11662
11663 @smallexample @c projectfile
11664 @group
11665 project Release is
11666   for Object_Dir use "release";
11667   for Exec_Dir use ".";
11668   for Main use ("proc");
11669
11670   package Compiler is
11671     for ^Default_Switches^Default_Switches^ ("Ada")
11672         use ("^-O2^-O2^");
11673   end Compiler;
11674 end Release;
11675 @end group
11676 @end smallexample
11677
11678 @noindent
11679 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
11680 insensitive), and analogously the project defined by @file{release.gpr} is
11681 @code{"Release"}.  For consistency the file should have the same name as the
11682 project, and the project file's extension should be @code{"gpr"}. These
11683 conventions are not required, but a warning is issued if they are not followed.
11684
11685 If the current directory is @file{^/temp^[TEMP]^}, then the command
11686 @smallexample
11687 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
11688 @end smallexample
11689
11690 @noindent
11691 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
11692 as well as the @code{^proc1^PROC1.EXE^} executable,
11693 using the ^switch^switch^ settings defined in the project file.
11694
11695 Likewise, the command
11696 @smallexample
11697 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
11698 @end smallexample
11699
11700 @noindent
11701 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
11702 and the @code{^proc^PROC.EXE^}
11703 executable in @file{^/common^[COMMON]^},
11704 using the ^switch^switch^ settings from the project file.
11705
11706 @node Source Files
11707 @unnumberedsubsubsec Source Files
11708
11709 @noindent
11710 If a project file does not explicitly specify a set of source directories or
11711 a set of source files, then by default the project's source files are the
11712 Ada source files in the project file directory.  Thus @file{pack.ads},
11713 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
11714
11715 @node Specifying the Object Directory
11716 @unnumberedsubsubsec Specifying the Object Directory
11717
11718 @noindent
11719 Several project properties are modeled by Ada-style @emph{attributes};
11720 a property is defined by supplying the equivalent of an Ada attribute
11721 definition clause in the project file.
11722 A project's object directory is another such a property; the corresponding
11723 attribute is @code{Object_Dir}, and its value is also a string expression,
11724 specified either as absolute or relative. In the later case,
11725 it is relative to the project file directory. Thus the compiler's
11726 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
11727 (for the @code{Debug} project)
11728 and to @file{^/common/release^[COMMON.RELEASE]^}
11729 (for the @code{Release} project).
11730 If @code{Object_Dir} is not specified, then the default is the project file
11731 directory itself.
11732
11733 @node Specifying the Exec Directory
11734 @unnumberedsubsubsec Specifying the Exec Directory
11735
11736 @noindent
11737 A project's exec directory is another property; the corresponding
11738 attribute is @code{Exec_Dir}, and its value is also a string expression,
11739 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
11740 then the default is the object directory (which may also be the project file
11741 directory if attribute @code{Object_Dir} is not specified). Thus the executable
11742 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
11743 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
11744 and in @file{^/common^[COMMON]^} for the @code{Release} project.
11745
11746 @node Project File Packages
11747 @unnumberedsubsubsec Project File Packages
11748
11749 @noindent
11750 A GNAT tool that is integrated with the Project Manager is modeled by a
11751 corresponding package in the project file. In the example above,
11752 The @code{Debug} project defines the packages @code{Builder}
11753 (for @command{gnatmake}) and @code{Compiler};
11754 the @code{Release} project defines only the @code{Compiler} package.
11755
11756 The Ada-like package syntax is not to be taken literally.  Although packages in
11757 project files bear a surface resemblance to packages in Ada source code, the
11758 notation is simply a way to convey a grouping of properties for a named
11759 entity.  Indeed, the package names permitted in project files are restricted
11760 to a predefined set, corresponding to the project-aware tools, and the contents
11761 of packages are limited to a small set of constructs.
11762 The packages in the example above contain attribute definitions.
11763
11764 @node Specifying ^Switch^Switch^ Settings
11765 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
11766
11767 @noindent
11768 ^Switch^Switch^ settings for a project-aware tool can be specified through
11769 attributes in the package that corresponds to the tool.
11770 The example above illustrates one of the relevant attributes,
11771 @code{^Default_Switches^Default_Switches^}, which is defined in packages
11772 in both project files.
11773 Unlike simple attributes like @code{Source_Dirs},
11774 @code{^Default_Switches^Default_Switches^} is
11775 known as an @emph{associative array}.  When you define this attribute, you must
11776 supply an ``index'' (a literal string), and the effect of the attribute
11777 definition is to set the value of the array at the specified index.
11778 For the @code{^Default_Switches^Default_Switches^} attribute,
11779 the index is a programming language (in our case, Ada),
11780 and the value specified (after @code{use}) must be a list
11781 of string expressions.
11782
11783 The attributes permitted in project files are restricted to a predefined set.
11784 Some may appear at project level, others in packages.
11785 For any attribute that is an associative array, the index must always be a
11786 literal string, but the restrictions on this string (e.g., a file name or a
11787 language name) depend on the individual attribute.
11788 Also depending on the attribute, its specified value will need to be either a
11789 string or a string list.
11790
11791 In the @code{Debug} project, we set the switches for two tools,
11792 @command{gnatmake} and the compiler, and thus we include the two corresponding
11793 packages; each package defines the @code{^Default_Switches^Default_Switches^}
11794 attribute with index @code{"Ada"}.
11795 Note that the package corresponding to
11796 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
11797 similar, but only includes the @code{Compiler} package.
11798
11799 In project @code{Debug} above, the ^switches^switches^ starting with
11800 @option{-gnat} that are specified in package @code{Compiler}
11801 could have been placed in package @code{Builder}, since @command{gnatmake}
11802 transmits all such ^switches^switches^ to the compiler.
11803
11804 @node Main Subprograms
11805 @unnumberedsubsubsec Main Subprograms
11806
11807 @noindent
11808 One of the specifiable properties of a project is a list of files that contain
11809 main subprograms.  This property is captured in the @code{Main} attribute,
11810 whose value is a list of strings.  If a project defines the @code{Main}
11811 attribute, it is not necessary to identify the main subprogram(s) when
11812 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
11813
11814 @node Executable File Names
11815 @unnumberedsubsubsec Executable File Names
11816
11817 @noindent
11818 By default, the executable file name corresponding to a main source is
11819 deduced from the main source file name. Through the attributes
11820 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
11821 it is possible to change this default.
11822 In project @code{Debug} above, the executable file name
11823 for main source @file{^proc.adb^PROC.ADB^} is
11824 @file{^proc1^PROC1.EXE^}.
11825 Attribute @code{Executable_Suffix}, when specified, may change the suffix
11826 of the executable files, when no attribute @code{Executable} applies:
11827 its value replace the platform-specific executable suffix.
11828 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
11829 specify a non-default executable file name when several mains are built at once
11830 in a single @command{gnatmake} command.
11831
11832 @node Source File Naming Conventions
11833 @unnumberedsubsubsec Source File Naming Conventions
11834
11835 @noindent
11836 Since the project files above do not specify any source file naming
11837 conventions, the GNAT defaults are used.  The mechanism for defining source
11838 file naming conventions -- a package named @code{Naming} --
11839 is described below (@pxref{Naming Schemes}).
11840
11841 @node Source Language(s)
11842 @unnumberedsubsubsec Source Language(s)
11843
11844 @noindent
11845 Since the project files do not specify a @code{Languages} attribute, by
11846 default the GNAT tools assume that the language of the project file is Ada.
11847 More generally, a project can comprise source files
11848 in Ada, C, and/or other languages.
11849
11850 @node Using External Variables
11851 @subsection Using External Variables
11852
11853 @noindent
11854 Instead of supplying different project files for debug and release, we can
11855 define a single project file that queries an external variable (set either
11856 on the command line or via an ^environment variable^logical name^) in order to
11857 conditionally define the appropriate settings.  Again, assume that the
11858 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
11859 located in directory @file{^/common^[COMMON]^}.  The following project file,
11860 @file{build.gpr}, queries the external variable named @code{STYLE} and
11861 defines an object directory and ^switch^switch^ settings based on whether
11862 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
11863 the default is @code{"deb"}.
11864
11865 @smallexample @c projectfile
11866 @group
11867 project Build is
11868   for Main use ("proc");
11869
11870   type Style_Type is ("deb", "rel");
11871   Style : Style_Type := external ("STYLE", "deb");
11872
11873   case Style is
11874     when "deb" =>
11875       for Object_Dir use "debug";
11876
11877     when "rel" =>
11878       for Object_Dir use "release";
11879       for Exec_Dir use ".";
11880   end case;
11881 @end group
11882
11883 @group
11884   package Builder is
11885
11886     case Style is
11887       when "deb" =>
11888         for ^Default_Switches^Default_Switches^ ("Ada")
11889             use ("^-g^-g^");
11890         for Executable ("proc") use "proc1";
11891       when others =>
11892         null;
11893     end case;
11894
11895   end Builder;
11896 @end group
11897
11898 @group
11899   package Compiler is
11900
11901     case Style is
11902       when "deb" =>
11903         for ^Default_Switches^Default_Switches^ ("Ada")
11904             use ("^-gnata^-gnata^",
11905                  "^-gnato^-gnato^",
11906                  "^-gnatE^-gnatE^");
11907
11908       when "rel" =>
11909         for ^Default_Switches^Default_Switches^ ("Ada")
11910             use ("^-O2^-O2^");
11911     end case;
11912
11913   end Compiler;
11914
11915 end Build;
11916 @end group
11917 @end smallexample
11918
11919 @noindent
11920 @code{Style_Type} is an example of a @emph{string type}, which is the project
11921 file analog of an Ada enumeration type but whose components are string literals
11922 rather than identifiers.  @code{Style} is declared as a variable of this type.
11923
11924 The form @code{external("STYLE", "deb")} is known as an
11925 @emph{external reference}; its first argument is the name of an
11926 @emph{external variable}, and the second argument is a default value to be
11927 used if the external variable doesn't exist.  You can define an external
11928 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
11929 or you can use ^an environment variable^a logical name^
11930 as an external variable.
11931
11932 Each @code{case} construct is expanded by the Project Manager based on the
11933 value of @code{Style}. Thus the command
11934 @ifclear vms
11935 @smallexample
11936 gnatmake -P/common/build.gpr -XSTYLE=deb
11937 @end smallexample
11938 @end ifclear
11939
11940 @ifset vms
11941 @smallexample
11942 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
11943 @end smallexample
11944 @end ifset
11945
11946 @noindent
11947 is equivalent to the @command{gnatmake} invocation using the project file
11948 @file{debug.gpr} in the earlier example.  So is the command
11949 @smallexample
11950 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
11951 @end smallexample
11952
11953 @noindent
11954 since @code{"deb"} is the default for @code{STYLE}.
11955
11956 Analogously,
11957
11958 @ifclear vms
11959 @smallexample
11960 gnatmake -P/common/build.gpr -XSTYLE=rel
11961 @end smallexample
11962 @end ifclear
11963
11964 @ifset vms
11965 @smallexample
11966 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
11967 @end smallexample
11968 @end ifset
11969
11970 @noindent
11971 is equivalent to the @command{gnatmake} invocation using the project file
11972 @file{release.gpr} in the earlier example.
11973
11974 @node Importing Other Projects
11975 @subsection Importing Other Projects
11976 @cindex @code{ADA_PROJECT_PATH}
11977
11978 @noindent
11979 A compilation unit in a source file in one project may depend on compilation
11980 units in source files in other projects.  To compile this unit under
11981 control of a project file, the
11982 dependent project must @emph{import} the projects containing the needed source
11983 files.
11984 This effect is obtained using syntax similar to an Ada @code{with} clause,
11985 but where @code{with}ed entities are strings that denote project files.
11986
11987 As an example, suppose that the two projects @code{GUI_Proj} and
11988 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
11989 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
11990 and @file{^/comm^[COMM]^}, respectively.
11991 Suppose that the source files for @code{GUI_Proj} are
11992 @file{gui.ads} and @file{gui.adb}, and that the source files for
11993 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
11994 files is located in its respective project file directory.  Schematically:
11995
11996 @smallexample
11997 @group
11998 ^/gui^[GUI]^
11999   gui_proj.gpr
12000   gui.ads
12001   gui.adb
12002 @end group
12003
12004 @group
12005 ^/comm^[COMM]^
12006   comm_proj.gpr
12007   comm.ads
12008   comm.adb
12009 @end group
12010 @end smallexample
12011
12012 @noindent
12013 We want to develop an application in directory @file{^/app^[APP]^} that
12014 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
12015 the corresponding project files (e.g.@: the ^switch^switch^ settings
12016 and object directory).
12017 Skeletal code for a main procedure might be something like the following:
12018
12019 @smallexample @c ada
12020 @group
12021 with GUI, Comm;
12022 procedure App_Main is
12023    @dots{}
12024 begin
12025    @dots{}
12026 end App_Main;
12027 @end group
12028 @end smallexample
12029
12030 @noindent
12031 Here is a project file, @file{app_proj.gpr}, that achieves the desired
12032 effect:
12033
12034 @smallexample @c projectfile
12035 @group
12036 with "/gui/gui_proj", "/comm/comm_proj";
12037 project App_Proj is
12038    for Main use ("app_main");
12039 end App_Proj;
12040 @end group
12041 @end smallexample
12042
12043 @noindent
12044 Building an executable is achieved through the command:
12045 @smallexample
12046 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
12047 @end smallexample
12048 @noindent
12049 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
12050 in the directory where @file{app_proj.gpr} resides.
12051
12052 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
12053 (as illustrated above) the @code{with} clause can omit the extension.
12054
12055 Our example specified an absolute path for each imported project file.
12056 Alternatively, the directory name of an imported object can be omitted
12057 if either
12058 @itemize @bullet
12059 @item
12060 The imported project file is in the same directory as the importing project
12061 file, or
12062 @item
12063 You have defined ^an environment variable^a logical name^
12064 that includes the directory containing
12065 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
12066 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
12067 directory names separated by colons (semicolons on Windows).
12068 @end itemize
12069
12070 @noindent
12071 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
12072 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
12073 as follows:
12074
12075 @smallexample @c projectfile
12076 @group
12077 with "gui_proj", "comm_proj";
12078 project App_Proj is
12079    for Main use ("app_main");
12080 end App_Proj;
12081 @end group
12082 @end smallexample
12083
12084 @noindent
12085 Importing other projects can create ambiguities.
12086 For example, the same unit might be present in different imported projects, or
12087 it might be present in both the importing project and in an imported project.
12088 Both of these conditions are errors.  Note that in the current version of
12089 the Project Manager, it is illegal to have an ambiguous unit even if the
12090 unit is never referenced by the importing project.  This restriction may be
12091 relaxed in a future release.
12092
12093 @node Extending a Project
12094 @subsection Extending a Project
12095
12096 @noindent
12097 In large software systems it is common to have multiple
12098 implementations of a common interface; in Ada terms, multiple versions of a
12099 package body for the same spec.  For example, one implementation
12100 might be safe for use in tasking programs, while another might only be used
12101 in sequential applications.  This can be modeled in GNAT using the concept
12102 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
12103 another project (the ``parent'') then by default all source files of the
12104 parent project are inherited by the child, but the child project can
12105 override any of the parent's source files with new versions, and can also
12106 add new files.  This facility is the project analog of a type extension in
12107 Object-Oriented Programming.  Project hierarchies are permitted (a child
12108 project may be the parent of yet another project), and a project that
12109 inherits one project can also import other projects.
12110
12111 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
12112 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
12113 @file{pack.adb}, and @file{proc.adb}:
12114
12115 @smallexample
12116 @group
12117 ^/seq^[SEQ]^
12118   pack.ads
12119   pack.adb
12120   proc.adb
12121   seq_proj.gpr
12122 @end group
12123 @end smallexample
12124
12125 @noindent
12126 Note that the project file can simply be empty (that is, no attribute or
12127 package is defined):
12128
12129 @smallexample @c projectfile
12130 @group
12131 project Seq_Proj is
12132 end Seq_Proj;
12133 @end group
12134 @end smallexample
12135
12136 @noindent
12137 implying that its source files are all the Ada source files in the project
12138 directory.
12139
12140 Suppose we want to supply an alternate version of @file{pack.adb}, in
12141 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
12142 @file{pack.ads} and @file{proc.adb}.  We can define a project
12143 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
12144
12145 @smallexample
12146 @group
12147 ^/tasking^[TASKING]^
12148   pack.adb
12149   tasking_proj.gpr
12150 @end group
12151
12152 @group
12153 project Tasking_Proj extends "/seq/seq_proj" is
12154 end Tasking_Proj;
12155 @end group
12156 @end smallexample
12157
12158 @noindent
12159 The version of @file{pack.adb} used in a build depends on which project file
12160 is specified.
12161
12162 Note that we could have obtained the desired behavior using project import
12163 rather than project inheritance; a @code{base} project would contain the
12164 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
12165 import @code{base} and add @file{pack.adb}, and likewise a tasking project
12166 would import @code{base} and add a different version of @file{pack.adb}.  The
12167 choice depends on whether other sources in the original project need to be
12168 overridden.  If they do, then project extension is necessary, otherwise,
12169 importing is sufficient.
12170
12171 @noindent
12172 In a project file that extends another project file, it is possible to
12173 indicate that an inherited source is not part of the sources of the extending
12174 project. This is necessary sometimes when a package spec has been overloaded
12175 and no longer requires a body: in this case, it is necessary to indicate that
12176 the inherited body is not part of the sources of the project, otherwise there
12177 will be a compilation error when compiling the spec.
12178
12179 For that purpose, the attribute @code{Excluded_Source_Files} is used.
12180 Its value is a string list: a list of file names. It is also possible to use
12181 attribute @code{Excluded_Source_List_File}. Its value is a single string:
12182 the file name of a text file containing a list of file names, one per line.
12183
12184 @smallexample @c @projectfile
12185 project B extends "a" is
12186    for Source_Files use ("pkg.ads");
12187    --  New spec of Pkg does not need a completion
12188    for Excluded_Source_Files use ("pkg.adb");
12189 end B;
12190 @end smallexample
12191
12192 Attribute @code{Excluded_Source_Files} may also be used to check if a source
12193 is still needed: if it is possible to build using @command{gnatmake} when such
12194 a source is put in attribute @code{Excluded_Source_Files} of a project P, then
12195 it is possible to remove the source completely from a system that includes
12196 project P.
12197
12198 @c ***********************
12199 @c * Project File Syntax *
12200 @c ***********************
12201
12202 @node Project File Syntax
12203 @section Project File Syntax
12204
12205 @menu
12206 * Basic Syntax::
12207 * Qualified Projects::
12208 * Packages::
12209 * Expressions::
12210 * String Types::
12211 * Variables::
12212 * Attributes::
12213 * Associative Array Attributes::
12214 * case Constructions::
12215 @end menu
12216
12217 @noindent
12218 This section describes the structure of project files.
12219
12220 A project may be an @emph{independent project}, entirely defined by a single
12221 project file. Any Ada source file in an independent project depends only
12222 on the predefined library and other Ada source files in the same project.
12223
12224 @noindent
12225 A project may also @dfn{depend on} other projects, in either or both of
12226 the following ways:
12227 @itemize @bullet
12228 @item It may import any number of projects
12229 @item It may extend at most one other project
12230 @end itemize
12231
12232 @noindent
12233 The dependence relation is a directed acyclic graph (the subgraph reflecting
12234 the ``extends'' relation is a tree).
12235
12236 A project's @dfn{immediate sources} are the source files directly defined by
12237 that project, either implicitly by residing in the project file's directory,
12238 or explicitly through any of the source-related attributes described below.
12239 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
12240 of @var{proj} together with the immediate sources (unless overridden) of any
12241 project on which @var{proj} depends (either directly or indirectly).
12242
12243 @node Basic Syntax
12244 @subsection Basic Syntax
12245
12246 @noindent
12247 As seen in the earlier examples, project files have an Ada-like syntax.
12248 The minimal project file is:
12249 @smallexample @c projectfile
12250 @group
12251 project Empty is
12252
12253 end Empty;
12254 @end group
12255 @end smallexample
12256
12257 @noindent
12258 The identifier @code{Empty} is the name of the project.
12259 This project name must be present after the reserved
12260 word @code{end} at the end of the project file, followed by a semi-colon.
12261
12262 Any name in a project file, such as the project name or a variable name,
12263 has the same syntax as an Ada identifier.
12264
12265 The reserved words of project files are the Ada 95 reserved words plus
12266 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
12267 reserved words currently used in project file syntax are:
12268
12269 @itemize @bullet
12270 @item
12271 @code{all}
12272 @item
12273 @code{at}
12274 @item
12275 @code{case}
12276 @item
12277 @code{end}
12278 @item
12279 @code{for}
12280 @item
12281 @code{is}
12282 @item
12283 @code{limited}
12284 @item
12285 @code{null}
12286 @item
12287 @code{others}
12288 @item
12289 @code{package}
12290 @item
12291 @code{renames}
12292 @item
12293 @code{type}
12294 @item
12295 @code{use}
12296 @item
12297 @code{when}
12298 @item
12299 @code{with}
12300 @end itemize
12301
12302 @noindent
12303 Comments in project files have the same syntax as in Ada, two consecutive
12304 hyphens through the end of the line.
12305
12306 @node Qualified Projects
12307 @subsection Qualified Projects
12308
12309 @noindent
12310 Before the reserved @code{project}, there may be one or two "qualifiers", that
12311 is identifiers or other reserved words, to qualify the project.
12312
12313 The current list of qualifiers is:
12314
12315 @itemize @bullet
12316 @item
12317 @code{abstract}: qualify a project with no sources. An abstract project must
12318 have a declaration specifying that there are no sources in the project, and,
12319 if it extends another project, the project it extends must also be a qualified
12320 abstract project.
12321
12322 @item
12323 @code{standard}: a standard project is a non library project with sources.
12324
12325 @item
12326 @code{aggregate}: for future extension
12327
12328 @item
12329 @code{aggregate library}: for future extension
12330
12331 @item
12332 @code{library}: a library project must declare both attributes
12333 @code{Library_Name} and @code{Library_Dir}.
12334
12335 @item
12336 @code{configuration}: a configuration project cannot be in a project tree.
12337 @end itemize
12338
12339 @node Packages
12340 @subsection Packages
12341
12342 @noindent
12343 A project file may contain @emph{packages}. The name of a package must be one
12344 of the identifiers from the following list. A package
12345 with a given name may only appear once in a project file. Package names are
12346 case insensitive. The following package names are legal:
12347
12348 @itemize @bullet
12349 @item
12350 @code{Naming}
12351 @item
12352 @code{Builder}
12353 @item
12354 @code{Compiler}
12355 @item
12356 @code{Binder}
12357 @item
12358 @code{Linker}
12359 @item
12360 @code{Finder}
12361 @item
12362 @code{Cross_Reference}
12363 @item
12364 @code{Eliminate}
12365 @item
12366 @code{Pretty_Printer}
12367 @item
12368 @code{Metrics}
12369 @item
12370 @code{gnatls}
12371 @item
12372 @code{gnatstub}
12373 @item
12374 @code{IDE}
12375 @item
12376 @code{Language_Processing}
12377 @end itemize
12378
12379 @noindent
12380 In its simplest form, a package may be empty:
12381
12382 @smallexample @c projectfile
12383 @group
12384 project Simple is
12385   package Builder is
12386   end Builder;
12387 end Simple;
12388 @end group
12389 @end smallexample
12390
12391 @noindent
12392 A package may contain @emph{attribute declarations},
12393 @emph{variable declarations} and @emph{case constructions}, as will be
12394 described below.
12395
12396 When there is ambiguity between a project name and a package name,
12397 the name always designates the project. To avoid possible confusion, it is
12398 always a good idea to avoid naming a project with one of the
12399 names allowed for packages or any name that starts with @code{gnat}.
12400
12401 @node Expressions
12402 @subsection Expressions
12403
12404 @noindent
12405 An @emph{expression} is either a @emph{string expression} or a
12406 @emph{string list expression}.
12407
12408 A @emph{string expression} is either a @emph{simple string expression} or a
12409 @emph{compound string expression}.
12410
12411 A @emph{simple string expression} is one of the following:
12412 @itemize @bullet
12413 @item A literal string; e.g.@: @code{"comm/my_proj.gpr"}
12414 @item A string-valued variable reference (@pxref{Variables})
12415 @item A string-valued attribute reference (@pxref{Attributes})
12416 @item An external reference (@pxref{External References in Project Files})
12417 @end itemize
12418
12419 @noindent
12420 A @emph{compound string expression} is a concatenation of string expressions,
12421 using the operator @code{"&"}
12422 @smallexample
12423        Path & "/" & File_Name & ".ads"
12424 @end smallexample
12425
12426 @noindent
12427 A @emph{string list expression} is either a
12428 @emph{simple string list expression} or a
12429 @emph{compound string list expression}.
12430
12431 A @emph{simple string list expression} is one of the following:
12432 @itemize @bullet
12433 @item A parenthesized list of zero or more string expressions,
12434 separated by commas
12435 @smallexample
12436    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
12437    Empty_List := ();
12438 @end smallexample
12439 @item A string list-valued variable reference
12440 @item A string list-valued attribute reference
12441 @end itemize
12442
12443 @noindent
12444 A @emph{compound string list expression} is the concatenation (using
12445 @code{"&"}) of a simple string list expression and an expression.  Note that
12446 each term in a compound string list expression, except the first, may be
12447 either a string expression or a string list expression.
12448
12449 @smallexample @c projectfile
12450 @group
12451    File_Name_List := () & File_Name; --  One string in this list
12452    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
12453    --  Two strings
12454    Big_List := File_Name_List & Extended_File_Name_List;
12455    --  Concatenation of two string lists: three strings
12456    Illegal_List := "gnat.adc" & Extended_File_Name_List;
12457    --  Illegal: must start with a string list
12458 @end group
12459 @end smallexample
12460
12461 @node String Types
12462 @subsection String Types
12463
12464 @noindent
12465 A @emph{string type declaration} introduces a discrete set of string literals.
12466 If a string variable is declared to have this type, its value
12467 is restricted to the given set of literals.
12468
12469 Here is an example of a string type declaration:
12470
12471 @smallexample @c projectfile
12472    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
12473 @end smallexample
12474
12475 @noindent
12476 Variables of a string type are called @emph{typed variables}; all other
12477 variables are called @emph{untyped variables}. Typed variables are
12478 particularly useful in @code{case} constructions, to support conditional
12479 attribute declarations.
12480 (@pxref{case Constructions}).
12481
12482 The string literals in the list are case sensitive and must all be different.
12483 They may include any graphic characters allowed in Ada, including spaces.
12484
12485 A string type may only be declared at the project level, not inside a package.
12486
12487 A string type may be referenced by its name if it has been declared in the same
12488 project file, or by an expanded name whose prefix is the name of the project
12489 in which it is declared.
12490
12491 @node Variables
12492 @subsection Variables
12493
12494 @noindent
12495 A variable may be declared at the project file level, or within a package.
12496 Here are some examples of variable declarations:
12497
12498 @smallexample @c projectfile
12499 @group
12500    This_OS : OS := external ("OS"); --  a typed variable declaration
12501    That_OS := "GNU/Linux";          --  an untyped variable declaration
12502 @end group
12503 @end smallexample
12504
12505 @noindent
12506 The syntax of a @emph{typed variable declaration} is identical to the Ada
12507 syntax for an object declaration. By contrast, the syntax of an untyped
12508 variable declaration is identical to an Ada assignment statement. In fact,
12509 variable declarations in project files have some of the characteristics of
12510 an assignment, in that successive declarations for the same variable are
12511 allowed. Untyped variable declarations do establish the expected kind of the
12512 variable (string or string list), and successive declarations for it must
12513 respect the initial kind.
12514
12515 @noindent
12516 A string variable declaration (typed or untyped) declares a variable
12517 whose value is a string. This variable may be used as a string expression.
12518 @smallexample @c projectfile
12519    File_Name       := "readme.txt";
12520    Saved_File_Name := File_Name & ".saved";
12521 @end smallexample
12522
12523 @noindent
12524 A string list variable declaration declares a variable whose value is a list
12525 of strings. The list may contain any number (zero or more) of strings.
12526
12527 @smallexample @c projectfile
12528    Empty_List := ();
12529    List_With_One_Element := ("^-gnaty^-gnaty^");
12530    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
12531    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
12532                  "pack2.ada", "util_.ada", "util.ada");
12533 @end smallexample
12534
12535 @noindent
12536 The same typed variable may not be declared more than once at project level,
12537 and it may not be declared more than once in any package; it is in effect
12538 a constant.
12539
12540 The same untyped variable may be declared several times. Declarations are
12541 elaborated in the order in which they appear, so  the new value replaces
12542 the old one, and any subsequent reference to the variable uses the new value.
12543 However, as noted above, if a variable has been declared as a string, all
12544 subsequent
12545 declarations must give it a string value. Similarly, if a variable has
12546 been declared as a string list, all subsequent declarations
12547 must give it a string list value.
12548
12549 A @emph{variable reference} may take several forms:
12550
12551 @itemize @bullet
12552 @item The simple variable name, for a variable in the current package (if any)
12553 or in the current project
12554 @item An expanded name, whose prefix is a context name.
12555 @end itemize
12556
12557 @noindent
12558 A @emph{context} may be one of the following:
12559
12560 @itemize @bullet
12561 @item The name of an existing package in the current project
12562 @item The name of an imported project of the current project
12563 @item The name of an ancestor project (i.e., a project extended by the current
12564 project, either directly or indirectly)
12565 @item An expanded name whose prefix is an imported/parent project name, and
12566 whose selector is a package name in that project.
12567 @end itemize
12568
12569 @noindent
12570 A variable reference may be used in an expression.
12571
12572 @node Attributes
12573 @subsection Attributes
12574
12575 @noindent
12576 A project (and its packages) may have @emph{attributes} that define
12577 the project's properties.  Some attributes have values that are strings;
12578 others have values that are string lists.
12579
12580 There are two categories of attributes: @emph{simple attributes}
12581 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
12582
12583 Legal project attribute names, and attribute names for each legal package are
12584 listed below. Attributes names are case-insensitive.
12585
12586 The following attributes are defined on projects (all are simple attributes):
12587
12588 @multitable @columnfractions .4 .3
12589 @item @emph{Attribute Name}
12590 @tab @emph{Value}
12591 @item @code{Source_Files}
12592 @tab string list
12593 @item @code{Source_Dirs}
12594 @tab string list
12595 @item @code{Source_List_File}
12596 @tab string
12597 @item @code{Object_Dir}
12598 @tab string
12599 @item @code{Exec_Dir}
12600 @tab string
12601 @item @code{Excluded_Source_Dirs}
12602 @tab string list
12603 @item @code{Excluded_Source_Files}
12604 @tab string list
12605 @item @code{Excluded_Source_List_File}
12606 @tab string
12607 @item @code{Languages}
12608 @tab string list
12609 @item @code{Main}
12610 @tab string list
12611 @item @code{Library_Dir}
12612 @tab string
12613 @item @code{Library_Name}
12614 @tab string
12615 @item @code{Library_Kind}
12616 @tab string
12617 @item @code{Library_Version}
12618 @tab string
12619 @item @code{Library_Interface}
12620 @tab string
12621 @item @code{Library_Auto_Init}
12622 @tab string
12623 @item @code{Library_Options}
12624 @tab string list
12625 @item @code{Library_Src_Dir}
12626 @tab string
12627 @item @code{Library_ALI_Dir}
12628 @tab string
12629 @item @code{Library_GCC}
12630 @tab string
12631 @item @code{Library_Symbol_File}
12632 @tab string
12633 @item @code{Library_Symbol_Policy}
12634 @tab string
12635 @item @code{Library_Reference_Symbol_File}
12636 @tab string
12637 @item @code{Externally_Built}
12638 @tab string
12639 @end multitable
12640
12641 @noindent
12642 The following attributes are defined for package  @code{Naming}
12643 (@pxref{Naming Schemes}):
12644
12645 @multitable @columnfractions .4 .2 .2 .2
12646 @item Attribute Name @tab Category @tab Index @tab Value
12647 @item @code{Spec_Suffix}
12648 @tab associative array
12649 @tab language name
12650 @tab string
12651 @item @code{Body_Suffix}
12652 @tab associative array
12653 @tab language name
12654 @tab string
12655 @item @code{Separate_Suffix}
12656 @tab simple attribute
12657 @tab n/a
12658 @tab string
12659 @item @code{Casing}
12660 @tab simple attribute
12661 @tab n/a
12662 @tab string
12663 @item @code{Dot_Replacement}
12664 @tab simple attribute
12665 @tab n/a
12666 @tab string
12667 @item @code{Spec}
12668 @tab associative array
12669 @tab Ada unit name
12670 @tab string
12671 @item @code{Body}
12672 @tab associative array
12673 @tab Ada unit name
12674 @tab string
12675 @item @code{Specification_Exceptions}
12676 @tab associative array
12677 @tab language name
12678 @tab string list
12679 @item @code{Implementation_Exceptions}
12680 @tab associative array
12681 @tab language name
12682 @tab string list
12683 @end multitable
12684
12685 @noindent
12686 The following attributes are defined for packages @code{Builder},
12687 @code{Compiler}, @code{Binder},
12688 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
12689 (@pxref{^Switches^Switches^ and Project Files}).
12690
12691 @multitable @columnfractions .4 .2 .2 .2
12692 @item Attribute Name @tab Category @tab Index @tab Value
12693 @item @code{^Default_Switches^Default_Switches^}
12694 @tab associative array
12695 @tab language name
12696 @tab string list
12697 @item @code{^Switches^Switches^}
12698 @tab associative array
12699 @tab file name
12700 @tab string list
12701 @end multitable
12702
12703 @noindent
12704 In addition, package @code{Compiler} has a single string attribute
12705 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
12706 string attribute @code{Global_Configuration_Pragmas}.
12707
12708 @noindent
12709 Each simple attribute has a default value: the empty string (for string-valued
12710 attributes) and the empty list (for string list-valued attributes).
12711
12712 An attribute declaration defines a new value for an attribute.
12713
12714 Examples of simple attribute declarations:
12715
12716 @smallexample @c projectfile
12717    for Object_Dir use "objects";
12718    for Source_Dirs use ("units", "test/drivers");
12719 @end smallexample
12720
12721 @noindent
12722 The syntax of a @dfn{simple attribute declaration} is similar to that of an
12723 attribute definition clause in Ada.
12724
12725 Attributes references may be appear in expressions.
12726 The general form for such a reference is @code{<entity>'<attribute>}:
12727 Associative array attributes are functions. Associative
12728 array attribute references must have an argument that is a string literal.
12729
12730 Examples are:
12731
12732 @smallexample @c projectfile
12733   project'Object_Dir
12734   Naming'Dot_Replacement
12735   Imported_Project'Source_Dirs
12736   Imported_Project.Naming'Casing
12737   Builder'^Default_Switches^Default_Switches^("Ada")
12738 @end smallexample
12739
12740 @noindent
12741 The prefix of an attribute may be:
12742 @itemize @bullet
12743 @item @code{project} for an attribute of the current project
12744 @item The name of an existing package of the current project
12745 @item The name of an imported project
12746 @item The name of a parent project that is extended by the current project
12747 @item An expanded name whose prefix is imported/parent project name,
12748 and whose selector is a package name
12749 @end itemize
12750
12751 @noindent
12752 Example:
12753 @smallexample @c projectfile
12754 @group
12755    project Prj is
12756      for Source_Dirs use project'Source_Dirs & "units";
12757      for Source_Dirs use project'Source_Dirs & "test/drivers"
12758    end Prj;
12759 @end group
12760 @end smallexample
12761
12762 @noindent
12763 In the first attribute declaration, initially the attribute @code{Source_Dirs}
12764 has the default value: an empty string list. After this declaration,
12765 @code{Source_Dirs} is a string list of one element: @code{"units"}.
12766 After the second attribute declaration @code{Source_Dirs} is a string list of
12767 two elements: @code{"units"} and @code{"test/drivers"}.
12768
12769 Note: this example is for illustration only. In practice,
12770 the project file would contain only one attribute declaration:
12771
12772 @smallexample @c projectfile
12773    for Source_Dirs use ("units", "test/drivers");
12774 @end smallexample
12775
12776 @node Associative Array Attributes
12777 @subsection Associative Array Attributes
12778
12779 @noindent
12780 Some attributes are defined as @emph{associative arrays}. An associative
12781 array may be regarded as a function that takes a string as a parameter
12782 and delivers a string or string list value as its result.
12783
12784 Here are some examples of single associative array attribute associations:
12785
12786 @smallexample @c projectfile
12787    for Body ("main") use "Main.ada";
12788    for ^Switches^Switches^ ("main.ada")
12789        use ("^-v^-v^",
12790             "^-gnatv^-gnatv^");
12791    for ^Switches^Switches^ ("main.ada")
12792             use Builder'^Switches^Switches^ ("main.ada")
12793               & "^-g^-g^";
12794 @end smallexample
12795
12796 @noindent
12797 Like untyped variables and simple attributes, associative array attributes
12798 may be declared several times. Each declaration supplies a new value for the
12799 attribute, and replaces the previous setting.
12800
12801 @noindent
12802 An associative array attribute may be declared as a full associative array
12803 declaration, with the value of the same attribute in an imported or extended
12804 project.
12805
12806 @smallexample @c projectfile
12807    package Builder is
12808       for Default_Switches use Default.Builder'Default_Switches;
12809    end Builder;
12810 @end smallexample
12811
12812 @noindent
12813 In this example, @code{Default} must be either a project imported by the
12814 current project, or the project that the current project extends. If the
12815 attribute is in a package (in this case, in package @code{Builder}), the same
12816 package needs to be specified.
12817
12818 @noindent
12819 A full associative array declaration replaces any other declaration for the
12820 attribute, including other full associative array declaration. Single
12821 associative array associations may be declare after a full associative
12822 declaration, modifying the value for a single association of the attribute.
12823
12824 @node case Constructions
12825 @subsection @code{case} Constructions
12826
12827 @noindent
12828 A @code{case} construction is used in a project file to effect conditional
12829 behavior.
12830 Here is a typical example:
12831
12832 @smallexample @c projectfile
12833 @group
12834 project MyProj is
12835    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
12836
12837    OS : OS_Type := external ("OS", "GNU/Linux");
12838 @end group
12839
12840 @group
12841    package Compiler is
12842      case OS is
12843        when "GNU/Linux" | "Unix" =>
12844          for ^Default_Switches^Default_Switches^ ("Ada")
12845              use ("^-gnath^-gnath^");
12846        when "NT" =>
12847          for ^Default_Switches^Default_Switches^ ("Ada")
12848              use ("^-gnatP^-gnatP^");
12849        when others =>
12850      end case;
12851    end Compiler;
12852 end MyProj;
12853 @end group
12854 @end smallexample
12855
12856 @noindent
12857 The syntax of a @code{case} construction is based on the Ada case statement
12858 (although there is no @code{null} construction for empty alternatives).
12859
12860 The case expression must be a typed string variable.
12861 Each alternative comprises the reserved word @code{when}, either a list of
12862 literal strings separated by the @code{"|"} character or the reserved word
12863 @code{others},  and the @code{"=>"} token.
12864 Each literal string must belong to the string type that is the type of the
12865 case variable.
12866 An @code{others} alternative, if present, must occur last.
12867
12868 After each @code{=>}, there are zero or more constructions.  The only
12869 constructions allowed in a case construction are other case constructions,
12870 attribute declarations and variable declarations. String type declarations and
12871 package declarations are not allowed. Variable declarations are restricted to
12872 variables that have already been declared before the case construction.
12873
12874 The value of the case variable is often given by an external reference
12875 (@pxref{External References in Project Files}).
12876
12877 @c ****************************************
12878 @c * Objects and Sources in Project Files *
12879 @c ****************************************
12880
12881 @node Objects and Sources in Project Files
12882 @section Objects and Sources in Project Files
12883
12884 @menu
12885 * Object Directory::
12886 * Exec Directory::
12887 * Source Directories::
12888 * Source File Names::
12889 @end menu
12890
12891 @noindent
12892 Each project has exactly one object directory and one or more source
12893 directories. The source directories must contain at least one source file,
12894 unless  the project file explicitly specifies that no source files are present
12895 (@pxref{Source File Names}).
12896
12897 @node Object Directory
12898 @subsection Object Directory
12899
12900 @noindent
12901 The object directory for a project is the directory containing the compiler's
12902 output (such as @file{ALI} files and object files) for the project's immediate
12903 sources.
12904
12905 The object directory is given by the value of the attribute @code{Object_Dir}
12906 in the project file.
12907
12908 @smallexample @c projectfile
12909    for Object_Dir use "objects";
12910 @end smallexample
12911
12912 @noindent
12913 The attribute @code{Object_Dir} has a string value, the path name of the object
12914 directory. The path name may be absolute or relative to the directory of the
12915 project file. This directory must already exist, and be readable and writable.
12916
12917 By default, when the attribute @code{Object_Dir} is not given an explicit value
12918 or when its value is the empty string, the object directory is the same as the
12919 directory containing the project file.
12920
12921 @node Exec Directory
12922 @subsection Exec Directory
12923
12924 @noindent
12925 The exec directory for a project is the directory containing the executables
12926 for the project's main subprograms.
12927
12928 The exec directory is given by the value of the attribute @code{Exec_Dir}
12929 in the project file.
12930
12931 @smallexample @c projectfile
12932    for Exec_Dir use "executables";
12933 @end smallexample
12934
12935 @noindent
12936 The attribute @code{Exec_Dir} has a string value, the path name of the exec
12937 directory. The path name may be absolute or relative to the directory of the
12938 project file. This directory must already exist, and be writable.
12939
12940 By default, when the attribute @code{Exec_Dir} is not given an explicit value
12941 or when its value is the empty string, the exec directory is the same as the
12942 object directory of the project file.
12943
12944 @node Source Directories
12945 @subsection Source Directories
12946
12947 @noindent
12948 The source directories of a project are specified by the project file
12949 attribute @code{Source_Dirs}.
12950
12951 This attribute's value is a string list. If the attribute is not given an
12952 explicit value, then there is only one source directory, the one where the
12953 project file resides.
12954
12955 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
12956 as in
12957
12958 @smallexample @c projectfile
12959     for Source_Dirs use ();
12960 @end smallexample
12961
12962 @noindent
12963 indicates that the project contains no source files.
12964
12965 Otherwise, each string in the string list designates one or more
12966 source directories.
12967
12968 @smallexample @c projectfile
12969    for Source_Dirs use ("sources", "test/drivers");
12970 @end smallexample
12971
12972 @noindent
12973 If a string in the list ends with @code{"/**"},  then the directory whose path
12974 name precedes the two asterisks, as well as all its subdirectories
12975 (recursively), are source directories.
12976
12977 @smallexample @c projectfile
12978    for Source_Dirs use ("/system/sources/**");
12979 @end smallexample
12980
12981 @noindent
12982 Here the directory @code{/system/sources} and all of its subdirectories
12983 (recursively) are source directories.
12984
12985 To specify that the source directories are the directory of the project file
12986 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
12987 @smallexample @c projectfile
12988    for Source_Dirs use ("./**");
12989 @end smallexample
12990
12991 @noindent
12992 Each of the source directories must exist and be readable.
12993
12994 @node Source File Names
12995 @subsection Source File Names
12996
12997 @noindent
12998 In a project that contains source files, their names may be specified by the
12999 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
13000 (a string). Source file names never include any directory information.
13001
13002 If the attribute @code{Source_Files} is given an explicit value, then each
13003 element of the list is a source file name.
13004
13005 @smallexample @c projectfile
13006    for Source_Files use ("main.adb");
13007    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
13008 @end smallexample
13009
13010 @noindent
13011 If the attribute @code{Source_Files} is not given an explicit value,
13012 but the attribute @code{Source_List_File} is given a string value,
13013 then the source file names are contained in the text file whose path name
13014 (absolute or relative to the directory of the project file) is the
13015 value of the attribute @code{Source_List_File}.
13016
13017 Each line in the file that is not empty or is not a comment
13018 contains a source file name.
13019
13020 @smallexample @c projectfile
13021    for Source_List_File use "source_list.txt";
13022 @end smallexample
13023
13024 @noindent
13025 By default, if neither the attribute @code{Source_Files} nor the attribute
13026 @code{Source_List_File} is given an explicit value, then each file in the
13027 source directories that conforms to the project's naming scheme
13028 (@pxref{Naming Schemes}) is an immediate source of the project.
13029
13030 A warning is issued if both attributes @code{Source_Files} and
13031 @code{Source_List_File} are given explicit values. In this case, the attribute
13032 @code{Source_Files} prevails.
13033
13034 Each source file name must be the name of one existing source file
13035 in one of the source directories.
13036
13037 A @code{Source_Files} attribute whose value is an empty list
13038 indicates that there are no source files in the project.
13039
13040 If the order of the source directories is known statically, that is if
13041 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
13042 be several files with the same source file name. In this case, only the file
13043 in the first directory is considered as an immediate source of the project
13044 file. If the order of the source directories is not known statically, it is
13045 an error to have several files with the same source file name.
13046
13047 Projects can be specified to have no Ada source
13048 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
13049 list, or the @code{"Ada"} may be absent from @code{Languages}:
13050
13051 @smallexample @c projectfile
13052    for Source_Dirs use ();
13053    for Source_Files use ();
13054    for Languages use ("C", "C++");
13055 @end smallexample
13056
13057 @noindent
13058 Otherwise, a project must contain at least one immediate source.
13059
13060 Projects with no source files are useful as template packages
13061 (@pxref{Packages in Project Files}) for other projects; in particular to
13062 define a package @code{Naming} (@pxref{Naming Schemes}).
13063
13064 @c ****************************
13065 @c * Importing Projects *
13066 @c ****************************
13067
13068 @node  Importing Projects
13069 @section Importing Projects
13070 @cindex @code{ADA_PROJECT_PATH}
13071
13072 @noindent
13073 An immediate source of a project P may depend on source files that
13074 are neither immediate sources of P nor in the predefined library.
13075 To get this effect, P must @emph{import} the projects that contain the needed
13076 source files.
13077
13078 @smallexample @c projectfile
13079 @group
13080   with "project1", "utilities.gpr";
13081   with "/namings/apex.gpr";
13082   project Main is
13083     @dots{}
13084 @end group
13085 @end smallexample
13086
13087 @noindent
13088 As can be seen in this example, the syntax for importing projects is similar
13089 to the syntax for importing compilation units in Ada. However, project files
13090 use literal strings instead of names, and the @code{with} clause identifies
13091 project files rather than packages.
13092
13093 Each literal string is the file name or path name (absolute or relative) of a
13094 project file. If a string corresponds to a file name, with no path or a
13095 relative path, then its location is determined by the @emph{project path}. The
13096 latter can be queried using @code{gnatls -v}. It contains:
13097
13098 @itemize @bullet
13099 @item
13100 In first position, the directory containing the current project file.
13101 @item
13102 In last position, the default project directory. This default project directory
13103 is part of the GNAT installation and is the standard place to install project
13104 files giving access to standard support libraries.
13105 @ifclear vms
13106 @ref{Installing a library}
13107 @end ifclear
13108
13109 @item
13110 In between, all the directories referenced in the
13111 ^environment variable^logical name^ @env{ADA_PROJECT_PATH} if it exists.
13112 @end itemize
13113
13114 @noindent
13115 If a relative pathname is used, as in
13116
13117 @smallexample @c projectfile
13118   with "tests/proj";
13119 @end smallexample
13120
13121 @noindent
13122 then the full path for the project is constructed by concatenating this
13123 relative path to those in the project path, in order, until a matching file is
13124 found. Any symbolic link will be fully resolved in the directory of the
13125 importing project file before the imported project file is examined.
13126
13127 If the @code{with}'ed project file name does not have an extension,
13128 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
13129 then the file name as specified in the @code{with} clause (no extension) will
13130 be used. In the above example, if a file @code{project1.gpr} is found, then it
13131 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
13132 then it will be used; if neither file exists, this is an error.
13133
13134 A warning is issued if the name of the project file does not match the
13135 name of the project; this check is case insensitive.
13136
13137 Any source file that is an immediate source of the imported project can be
13138 used by the immediate sources of the importing project, transitively. Thus
13139 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
13140 sources of @code{A} may depend on the immediate sources of @code{C}, even if
13141 @code{A} does not import @code{C} explicitly. However, this is not recommended,
13142 because if and when @code{B} ceases to import @code{C}, some sources in
13143 @code{A} will no longer compile.
13144
13145 A side effect of this capability is that normally cyclic dependencies are not
13146 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
13147 is not allowed to import @code{A}. However, there are cases when cyclic
13148 dependencies would be beneficial. For these cases, another form of import
13149 between projects exists, the @code{limited with}: a project @code{A} that
13150 imports a project @code{B} with a straight @code{with} may also be imported,
13151 directly or indirectly, by @code{B} on the condition that imports from @code{B}
13152 to @code{A} include at least one @code{limited with}.
13153
13154 @smallexample @c 0projectfile
13155 with "../b/b.gpr";
13156 with "../c/c.gpr";
13157 project A is
13158 end A;
13159
13160 limited with "../a/a.gpr";
13161 project B is
13162 end B;
13163
13164 with "../d/d.gpr";
13165 project C is
13166 end C;
13167
13168 limited with "../a/a.gpr";
13169 project D is
13170 end D;
13171 @end smallexample
13172
13173 @noindent
13174 In the above legal example, there are two project cycles:
13175 @itemize @bullet
13176 @item A-> B-> A
13177 @item A -> C -> D -> A
13178 @end itemize
13179
13180 @noindent
13181 In each of these cycle there is one @code{limited with}: import of @code{A}
13182 from @code{B} and import of @code{A} from @code{D}.
13183
13184 The difference between straight @code{with} and @code{limited with} is that
13185 the name of a project imported with a @code{limited with} cannot be used in the
13186 project that imports it. In particular, its packages cannot be renamed and
13187 its variables cannot be referred to.
13188
13189 An exception to the above rules for @code{limited with} is that for the main
13190 project specified to @command{gnatmake} or to the @command{GNAT} driver a
13191 @code{limited with} is equivalent to a straight @code{with}. For example,
13192 in the example above, projects @code{B} and @code{D} could not be main
13193 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
13194 each have a @code{limited with} that is the only one in a cycle of importing
13195 projects.
13196
13197 @c *********************
13198 @c * Project Extension *
13199 @c *********************
13200
13201 @node Project Extension
13202 @section Project Extension
13203
13204 @noindent
13205 During development of a large system, it is sometimes necessary to use
13206 modified versions of some of the source files, without changing the original
13207 sources. This can be achieved through the @emph{project extension} facility.
13208
13209 @smallexample @c projectfile
13210    project Modified_Utilities extends "/baseline/utilities.gpr" is @dots{}
13211 @end smallexample
13212
13213 @noindent
13214 A project extension declaration introduces an extending project
13215 (the @emph{child}) and a project being extended (the @emph{parent}).
13216
13217 By default, a child project inherits all the sources of its parent.
13218 However, inherited sources can be overridden: a unit in a parent is hidden
13219 by a unit of the same name in the child.
13220
13221 Inherited sources are considered to be sources (but not immediate sources)
13222 of the child project; see @ref{Project File Syntax}.
13223
13224 An inherited source file retains any switches specified in the parent project.
13225
13226 For example if the project @code{Utilities} contains the spec and the
13227 body of an Ada package @code{Util_IO}, then the project
13228 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
13229 The original body of @code{Util_IO} will not be considered in program builds.
13230 However, the package spec will still be found in the project
13231 @code{Utilities}.
13232
13233 A child project can have only one parent, except when it is qualified as
13234 abstract. But it may import any number of other projects.
13235
13236 A project is not allowed to import directly or indirectly at the same time a
13237 child project and any of its ancestors.
13238
13239 @c *******************************
13240 @c * Project Hierarchy Extension *
13241 @c *******************************
13242
13243 @node Project Hierarchy Extension
13244 @section Project Hierarchy Extension
13245
13246 @noindent
13247 When extending a large system spanning multiple projects, it is often
13248 inconvenient to extend every project in the hierarchy that is impacted by a
13249 small change introduced. In such cases, it is possible to create a virtual
13250 extension of entire hierarchy using @code{extends all} relationship.
13251
13252 When the project is extended using @code{extends all} inheritance, all projects
13253 that are imported by it, both directly and indirectly, are considered virtually
13254 extended. That is, the Project Manager creates "virtual projects"
13255 that extend every project in the hierarchy; all these virtual projects have
13256 no sources of their own and have as object directory the object directory of
13257 the root of "extending all" project.
13258
13259 It is possible to explicitly extend one or more projects in the hierarchy
13260 in order to modify the sources. These extending projects must be imported by
13261 the "extending all" project, which will replace the corresponding virtual
13262 projects with the explicit ones.
13263
13264 When building such a project hierarchy extension, the Project Manager will
13265 ensure that both modified sources and sources in virtual extending projects
13266 that depend on them, are recompiled.
13267
13268 By means of example, consider the following hierarchy of projects.
13269
13270 @enumerate
13271 @item
13272 project A, containing package P1
13273 @item
13274 project B importing A and containing package P2 which depends on P1
13275 @item
13276 project C importing B and containing package P3 which depends on P2
13277 @end enumerate
13278
13279 @noindent
13280 We want to modify packages P1 and P3.
13281
13282 This project hierarchy will need to be extended as follows:
13283
13284 @enumerate
13285 @item
13286 Create project A1 that extends A, placing modified P1 there:
13287
13288 @smallexample @c 0projectfile
13289 project A1 extends "(@dots{})/A" is
13290 end A1;
13291 @end smallexample
13292
13293 @item
13294 Create project C1 that "extends all" C and imports A1, placing modified
13295 P3 there:
13296
13297 @smallexample @c 0projectfile
13298 with "(@dots{})/A1";
13299 project C1 extends all "(@dots{})/C" is
13300 end C1;
13301 @end smallexample
13302 @end enumerate
13303
13304 When you build project C1, your entire modified project space will be
13305 recompiled, including the virtual project B1 that has been impacted by the
13306 "extending all" inheritance of project C.
13307
13308 Note that if a Library Project in the hierarchy is virtually extended,
13309 the virtual project that extends the Library Project is not a Library Project.
13310
13311 @c ****************************************
13312 @c * External References in Project Files *
13313 @c ****************************************
13314
13315 @node  External References in Project Files
13316 @section External References in Project Files
13317
13318 @noindent
13319 A project file may contain references to external variables; such references
13320 are called @emph{external references}.
13321
13322 An external variable is either defined as part of the environment (an
13323 environment variable in Unix, for example) or else specified on the command
13324 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
13325 If both, then the command line value is used.
13326
13327 The value of an external reference is obtained by means of the built-in
13328 function @code{external}, which returns a string value.
13329 This function has two forms:
13330 @itemize @bullet
13331 @item @code{external (external_variable_name)}
13332 @item @code{external (external_variable_name, default_value)}
13333 @end itemize
13334
13335 @noindent
13336 Each parameter must be a string literal.  For example:
13337
13338 @smallexample @c projectfile
13339    external ("USER")
13340    external ("OS", "GNU/Linux")
13341 @end smallexample
13342
13343 @noindent
13344 In the form with one parameter, the function returns the value of
13345 the external variable given as parameter. If this name is not present in the
13346 environment, the function returns an empty string.
13347
13348 In the form with two string parameters, the second argument is
13349 the value returned when the variable given as the first argument is not
13350 present in the environment. In the example above, if @code{"OS"} is not
13351 the name of ^an environment variable^a logical name^ and is not passed on
13352 the command line, then the returned value is @code{"GNU/Linux"}.
13353
13354 An external reference may be part of a string expression or of a string
13355 list expression, and can therefore appear in a variable declaration or
13356 an attribute declaration.
13357
13358 @smallexample @c projectfile
13359 @group
13360    type Mode_Type is ("Debug", "Release");
13361    Mode : Mode_Type := external ("MODE");
13362    case Mode is
13363      when "Debug" =>
13364         @dots{}
13365 @end group
13366 @end smallexample
13367
13368 @c *****************************
13369 @c * Packages in Project Files *
13370 @c *****************************
13371
13372 @node  Packages in Project Files
13373 @section Packages in Project Files
13374
13375 @noindent
13376 A @emph{package} defines the settings for project-aware tools within a
13377 project.
13378 For each such tool one can declare a package; the names for these
13379 packages are preset (@pxref{Packages}).
13380 A package may contain variable declarations, attribute declarations, and case
13381 constructions.
13382
13383 @smallexample @c projectfile
13384 @group
13385    project Proj is
13386       package Builder is  -- used by gnatmake
13387          for ^Default_Switches^Default_Switches^ ("Ada")
13388              use ("^-v^-v^",
13389                   "^-g^-g^");
13390       end Builder;
13391    end Proj;
13392 @end group
13393 @end smallexample
13394
13395 @noindent
13396 The syntax of package declarations mimics that of package in Ada.
13397
13398 Most of the packages have an attribute
13399 @code{^Default_Switches^Default_Switches^}.
13400 This attribute is an associative array, and its value is a string list.
13401 The index of the associative array is the name of a programming language (case
13402 insensitive). This attribute indicates the ^switch^switch^
13403 or ^switches^switches^ to be used
13404 with the corresponding tool.
13405
13406 Some packages also have another attribute, @code{^Switches^Switches^},
13407 an associative array whose value is a string list.
13408 The index is the name of a source file.
13409 This attribute indicates the ^switch^switch^
13410 or ^switches^switches^ to be used by the corresponding
13411 tool when dealing with this specific file.
13412
13413 Further information on these ^switch^switch^-related attributes is found in
13414 @ref{^Switches^Switches^ and Project Files}.
13415
13416 A package may be declared as a @emph{renaming} of another package; e.g., from
13417 the project file for an imported project.
13418
13419 @smallexample @c projectfile
13420 @group
13421   with "/global/apex.gpr";
13422   project Example is
13423     package Naming renames Apex.Naming;
13424     @dots{}
13425   end Example;
13426 @end group
13427 @end smallexample
13428
13429 @noindent
13430 Packages that are renamed in other project files often come from project files
13431 that have no sources: they are just used as templates. Any modification in the
13432 template will be reflected automatically in all the project files that rename
13433 a package from the template.
13434
13435 In addition to the tool-oriented packages, you can also declare a package
13436 named @code{Naming} to establish specialized source file naming conventions
13437 (@pxref{Naming Schemes}).
13438
13439 @c ************************************
13440 @c * Variables from Imported Projects *
13441 @c ************************************
13442
13443 @node Variables from Imported Projects
13444 @section Variables from Imported Projects
13445
13446 @noindent
13447 An attribute or variable defined in an imported or parent project can
13448 be used in expressions in the importing / extending project.
13449 Such an attribute or variable is denoted by an expanded name whose prefix
13450 is either the name of the project or the expanded name of a package within
13451 a project.
13452
13453 @smallexample @c projectfile
13454 @group
13455   with "imported";
13456   project Main extends "base" is
13457      Var1 := Imported.Var;
13458      Var2 := Base.Var & ".new";
13459 @end group
13460
13461 @group
13462      package Builder is
13463         for ^Default_Switches^Default_Switches^ ("Ada")
13464             use Imported.Builder'Ada_^Switches^Switches^ &
13465                 "^-gnatg^-gnatg^" &
13466                 "^-v^-v^";
13467      end Builder;
13468 @end group
13469
13470 @group
13471      package Compiler is
13472         for ^Default_Switches^Default_Switches^ ("Ada")
13473             use Base.Compiler'Ada_^Switches^Switches^;
13474      end Compiler;
13475   end Main;
13476 @end group
13477 @end smallexample
13478
13479 @noindent
13480 In this example:
13481
13482 @itemize @bullet
13483 @item
13484 The value of @code{Var1} is a copy of the variable @code{Var} defined
13485 in the project file @file{"imported.gpr"}
13486 @item
13487 the value of @code{Var2} is a copy of the value of variable @code{Var}
13488 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
13489 @item
13490 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13491 @code{Builder} is a string list that includes in its value a copy of the value
13492 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
13493 in project file @file{imported.gpr} plus two new elements:
13494 @option{"^-gnatg^-gnatg^"}
13495 and @option{"^-v^-v^"};
13496 @item
13497 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13498 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
13499 defined in the @code{Compiler} package in project file @file{base.gpr},
13500 the project being extended.
13501 @end itemize
13502
13503 @c ******************
13504 @c * Naming Schemes *
13505 @c ******************
13506
13507 @node  Naming Schemes
13508 @section Naming Schemes
13509
13510 @noindent
13511 Sometimes an Ada software system is ported from a foreign compilation
13512 environment to GNAT, and the file names do not use the default GNAT
13513 conventions. Instead of changing all the file names (which for a variety
13514 of reasons might not be possible), you can define the relevant file
13515 naming scheme in the @code{Naming} package in your project file.
13516
13517 @noindent
13518 Note that the use of pragmas described in
13519 @ref{Alternative File Naming Schemes} by mean of a configuration
13520 pragmas file is not supported when using project files. You must use
13521 the features described in this paragraph. You can however use specify
13522 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
13523
13524 @ifclear vms
13525 For example, the following
13526 package models the Apex file naming rules:
13527
13528 @smallexample @c projectfile
13529 @group
13530   package Naming is
13531     for Casing               use "lowercase";
13532     for Dot_Replacement      use ".";
13533     for Spec_Suffix ("Ada")  use ".1.ada";
13534     for Body_Suffix ("Ada")  use ".2.ada";
13535   end Naming;
13536 @end group
13537 @end smallexample
13538 @end ifclear
13539
13540 @ifset vms
13541 For example, the following package models the HP Ada file naming rules:
13542
13543 @smallexample @c projectfile
13544 @group
13545   package Naming is
13546     for Casing               use "lowercase";
13547     for Dot_Replacement      use "__";
13548     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
13549     for Body_Suffix ("Ada")  use ".^ada^ada^";
13550   end Naming;
13551 @end group
13552 @end smallexample
13553
13554 @noindent
13555 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
13556 names in lower case)
13557 @end ifset
13558
13559 @noindent
13560 You can define the following attributes in package @code{Naming}:
13561
13562 @table @code
13563
13564 @item @code{Casing}
13565 This must be a string with one of the three values @code{"lowercase"},
13566 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
13567
13568 @noindent
13569 If @code{Casing} is not specified, then the default is @code{"lowercase"}.
13570
13571 @item @code{Dot_Replacement}
13572 This must be a string whose value satisfies the following conditions:
13573
13574 @itemize @bullet
13575 @item It must not be empty
13576 @item It cannot start or end with an alphanumeric character
13577 @item It cannot be a single underscore
13578 @item It cannot start with an underscore followed by an alphanumeric
13579 @item It cannot contain a dot @code{'.'} except if the entire string
13580 is @code{"."}
13581 @end itemize
13582
13583 @noindent
13584 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
13585
13586 @item @code{Spec_Suffix}
13587 This is an associative array (indexed by the programming language name, case
13588 insensitive) whose value is a string that must satisfy the following
13589 conditions:
13590
13591 @itemize @bullet
13592 @item It must not be empty
13593 @item It must include at least one dot
13594 @end itemize
13595 @noindent
13596 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
13597 @code{"^.ads^.ADS^"}.
13598
13599 @item @code{Body_Suffix}
13600 This is an associative array (indexed by the programming language name, case
13601 insensitive) whose value is a string that must satisfy the following
13602 conditions:
13603
13604 @itemize @bullet
13605 @item It must not be empty
13606 @item It must include at least one dot
13607 @item It cannot be the same as @code{Spec_Suffix ("Ada")}
13608 @end itemize
13609 @noindent
13610 If @code{Body_Suffix ("Ada")} and @code{Spec_Suffix ("Ada")} end with the
13611 same string, then a file name that ends with the longest of these two suffixes
13612 will be a body if the longest suffix is @code{Body_Suffix ("Ada")} or a spec
13613 if the longest suffix is @code{Spec_Suffix ("Ada")}.
13614
13615 If @code{Body_Suffix ("Ada")} is not specified, then the default is
13616 @code{"^.adb^.ADB^"}.
13617
13618 @item @code{Separate_Suffix}
13619 This must be a string whose value satisfies the same conditions as
13620 @code{Body_Suffix}. The same "longest suffix" rules apply.
13621
13622 @noindent
13623 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
13624 value as @code{Body_Suffix ("Ada")}.
13625
13626 @item @code{Spec}
13627 @noindent
13628 You can use the associative array attribute @code{Spec}  to define
13629 the source file name for an individual Ada compilation unit's spec. The array
13630 index must be a string literal that identifies the Ada unit (case insensitive).
13631 The value of this attribute must be a string that identifies the file that
13632 contains this unit's spec (case sensitive or insensitive depending on the
13633 operating system).
13634
13635 @smallexample @c projectfile
13636    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
13637 @end smallexample
13638
13639 @item @code{Body}
13640
13641 You can use the associative array attribute @code{Body} to
13642 define the source file name for an individual Ada compilation unit's body
13643 (possibly a subunit).  The array index must be a string literal that identifies
13644 the Ada unit (case insensitive).  The value of this attribute must be a string
13645 that identifies the file that contains this unit's body or subunit (case
13646 sensitive or insensitive depending on the operating system).
13647
13648 @smallexample @c projectfile
13649    for Body ("MyPack.MyChild") use "mypack.mychild.body";
13650 @end smallexample
13651 @end table
13652
13653 @c ********************
13654 @c * Library Projects *
13655 @c ********************
13656
13657 @node Library Projects
13658 @section Library Projects
13659
13660 @noindent
13661 @emph{Library projects} are projects whose object code is placed in a library.
13662 (Note that this facility is not yet supported on all platforms)
13663
13664 To create a library project, you need to define in its project file
13665 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
13666 Additionally, you may define other library-related attributes such as
13667 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
13668 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
13669
13670 The @code{Library_Name} attribute has a string value. There is no restriction
13671 on the name of a library. It is the responsibility of the developer to
13672 choose a name that will be accepted by the platform. It is recommended to
13673 choose names that could be Ada identifiers; such names are almost guaranteed
13674 to be acceptable on all platforms.
13675
13676 The @code{Library_Dir} attribute has a string value that designates the path
13677 (absolute or relative) of the directory where the library will reside.
13678 It must designate an existing directory, and this directory must be writable,
13679 different from the project's object directory and from any source directory
13680 in the project tree.
13681
13682 If both @code{Library_Name} and @code{Library_Dir} are specified and
13683 are legal, then the project file defines a library project.  The optional
13684 library-related attributes are checked only for such project files.
13685
13686 The @code{Library_Kind} attribute has a string value that must be one of the
13687 following (case insensitive): @code{"static"}, @code{"dynamic"} or
13688 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
13689 attribute is not specified, the library is a static library, that is
13690 an archive of object files that can be potentially linked into a
13691 static executable. Otherwise, the library may be dynamic or
13692 relocatable, that is a library that is loaded only at the start of execution.
13693
13694 If you need to build both a static and a dynamic library, you should use two
13695 different object directories, since in some cases some extra code needs to
13696 be generated for the latter. For such cases, it is recommended to either use
13697 two different project files, or a single one which uses external variables
13698 to indicate what kind of library should be build.
13699
13700 The @code{Library_ALI_Dir} attribute may be specified to indicate the
13701 directory where the ALI files of the library will be copied. When it is
13702 not specified, the ALI files are copied to the directory specified in
13703 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
13704 must be writable and different from the project's object directory and from
13705 any source directory in the project tree.
13706
13707 The @code{Library_Version} attribute has a string value whose interpretation
13708 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
13709 used only for dynamic/relocatable libraries as the internal name of the
13710 library (the @code{"soname"}). If the library file name (built from the
13711 @code{Library_Name}) is different from the @code{Library_Version}, then the
13712 library file will be a symbolic link to the actual file whose name will be
13713 @code{Library_Version}.
13714
13715 Example (on Unix):
13716
13717 @smallexample @c projectfile
13718 @group
13719 project Plib is
13720
13721    Version := "1";
13722
13723    for Library_Dir use "lib_dir";
13724    for Library_Name use "dummy";
13725    for Library_Kind use "relocatable";
13726    for Library_Version use "libdummy.so." & Version;
13727
13728 end Plib;
13729 @end group
13730 @end smallexample
13731
13732 @noindent
13733 Directory @file{lib_dir} will contain the internal library file whose name
13734 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
13735 @file{libdummy.so.1}.
13736
13737 When @command{gnatmake} detects that a project file
13738 is a library project file, it will check all immediate sources of the project
13739 and rebuild the library if any of the sources have been recompiled.
13740
13741 Standard project files can import library project files. In such cases,
13742 the libraries will only be rebuilt if some of its sources are recompiled
13743 because they are in the closure of some other source in an importing project.
13744 Sources of the library project files that are not in such a closure will
13745 not be checked, unless the full library is checked, because one of its sources
13746 needs to be recompiled.
13747
13748 For instance, assume the project file @code{A} imports the library project file
13749 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
13750 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
13751 @file{l2.ads}, @file{l2.adb}.
13752
13753 If @file{l1.adb} has been modified, then the library associated with @code{L}
13754 will be rebuilt when compiling all the immediate sources of @code{A} only
13755 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
13756 @code{"with L1;"}.
13757
13758 To be sure that all the sources in the library associated with @code{L} are
13759 up to date, and that all the sources of project @code{A} are also up to date,
13760 the following two commands needs to be used:
13761
13762 @smallexample
13763 gnatmake -Pl.gpr
13764 gnatmake -Pa.gpr
13765 @end smallexample
13766
13767 When a library is built or rebuilt, an attempt is made first to delete all
13768 files in the library directory.
13769 All @file{ALI} files will also be copied from the object directory to the
13770 library directory. To build executables, @command{gnatmake} will use the
13771 library rather than the individual object files.
13772
13773 @ifclear vms
13774 It is also possible to create library project files for third-party libraries
13775 that are precompiled and cannot be compiled locally thanks to the
13776 @code{externally_built} attribute. (See @ref{Installing a library}).
13777 @end ifclear
13778
13779 @c *******************************
13780 @c * Stand-alone Library Projects *
13781 @c *******************************
13782
13783 @node Stand-alone Library Projects
13784 @section Stand-alone Library Projects
13785
13786 @noindent
13787 A Stand-alone Library is a library that contains the necessary code to
13788 elaborate the Ada units that are included in the library. A Stand-alone
13789 Library is suitable to be used in an executable when the main is not
13790 in Ada. However, Stand-alone Libraries may also be used with an Ada main
13791 subprogram.
13792
13793 A Stand-alone Library Project is a Library Project where the library is
13794 a Stand-alone Library.
13795
13796 To be a Stand-alone Library Project, in addition to the two attributes
13797 that make a project a Library Project (@code{Library_Name} and
13798 @code{Library_Dir}, see @ref{Library Projects}), the attribute
13799 @code{Library_Interface} must be defined.
13800
13801 @smallexample @c projectfile
13802 @group
13803    for Library_Dir use "lib_dir";
13804    for Library_Name use "dummy";
13805    for Library_Interface use ("int1", "int1.child");
13806 @end group
13807 @end smallexample
13808
13809 Attribute @code{Library_Interface} has a nonempty string list value,
13810 each string in the list designating a unit contained in an immediate source
13811 of the project file.
13812
13813 When a Stand-alone Library is built, first the binder is invoked to build
13814 a package whose name depends on the library name
13815 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
13816 This binder-generated package includes initialization and
13817 finalization procedures whose
13818 names depend on the library name (dummyinit and dummyfinal in the example
13819 above). The object corresponding to this package is included in the library.
13820
13821 A dynamic or relocatable Stand-alone Library is automatically initialized
13822 if automatic initialization of Stand-alone Libraries is supported on the
13823 platform and if attribute @code{Library_Auto_Init} is not specified or
13824 is specified with the value "true". A static Stand-alone Library is never
13825 automatically initialized.
13826
13827 Single string attribute @code{Library_Auto_Init} may be specified with only
13828 two possible values: "false" or "true" (case-insensitive). Specifying
13829 "false" for attribute @code{Library_Auto_Init} will prevent automatic
13830 initialization of dynamic or relocatable libraries.
13831
13832 When a non-automatically initialized Stand-alone Library is used
13833 in an executable, its initialization procedure must be called before
13834 any service of the library is used.
13835 When the main subprogram is in Ada, it may mean that the initialization
13836 procedure has to be called during elaboration of another package.
13837
13838 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
13839 (those that are listed in attribute @code{Library_Interface}) are copied to
13840 the Library Directory. As a consequence, only the Interface Units may be
13841 imported from Ada units outside of the library. If other units are imported,
13842 the binding phase will fail.
13843
13844 When a Stand-Alone Library is bound, the switches that are specified in
13845 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
13846 used in the call to @command{gnatbind}.
13847
13848 The string list attribute @code{Library_Options} may be used to specified
13849 additional switches to the call to @command{gcc} to link the library.
13850
13851 The attribute @code{Library_Src_Dir}, may be specified for a
13852 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
13853 single string value. Its value must be the path (absolute or relative to the
13854 project directory) of an existing directory. This directory cannot be the
13855 object directory or one of the source directories, but it can be the same as
13856 the library directory. The sources of the Interface
13857 Units of the library, necessary to an Ada client of the library, will be
13858 copied to the designated directory, called Interface Copy directory.
13859 These sources includes the specs of the Interface Units, but they may also
13860 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
13861 are used, or when there is a generic units in the spec. Before the sources
13862 are copied to the Interface Copy directory, an attempt is made to delete all
13863 files in the Interface Copy directory.
13864
13865 @c *************************************
13866 @c * Switches Related to Project Files *
13867 @c *************************************
13868 @node Switches Related to Project Files
13869 @section Switches Related to Project Files
13870
13871 @noindent
13872 The following switches are used by GNAT tools that support project files:
13873
13874 @table @option
13875
13876 @item ^-P^/PROJECT_FILE=^@var{project}
13877 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
13878 Indicates the name of a project file. This project file will be parsed with
13879 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
13880 if any, and using the external references indicated
13881 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
13882 @ifclear vms
13883 There may zero, one or more spaces between @option{-P} and @var{project}.
13884 @end ifclear
13885
13886 @noindent
13887 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
13888
13889 @noindent
13890 Since the Project Manager parses the project file only after all the switches
13891 on the command line are checked, the order of the switches
13892 @option{^-P^/PROJECT_FILE^},
13893 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
13894 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
13895
13896 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
13897 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
13898 Indicates that external variable @var{name} has the value @var{value}.
13899 The Project Manager will use this value for occurrences of
13900 @code{external(name)} when parsing the project file.
13901
13902 @ifclear vms
13903 @noindent
13904 If @var{name} or @var{value} includes a space, then @var{name=value} should be
13905 put between quotes.
13906 @smallexample
13907   -XOS=NT
13908   -X"user=John Doe"
13909 @end smallexample
13910 @end ifclear
13911
13912 @noindent
13913 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
13914 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
13915 @var{name}, only the last one is used.
13916
13917 @noindent
13918 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
13919 takes precedence over the value of the same name in the environment.
13920
13921 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
13922 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
13923 Indicates the verbosity of the parsing of GNAT project files.
13924
13925 @ifclear vms
13926 @option{-vP0} means Default;
13927 @option{-vP1} means Medium;
13928 @option{-vP2} means High.
13929 @end ifclear
13930
13931 @ifset vms
13932 There are three possible options for this qualifier: DEFAULT, MEDIUM and
13933 HIGH.
13934 @end ifset
13935
13936 @noindent
13937 The default is ^Default^DEFAULT^: no output for syntactically correct
13938 project files.
13939 @noindent
13940 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
13941 only the last one is used.
13942
13943 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
13944 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
13945 Add directory <dir> at the beginning of the project search path, in order,
13946 after the current working directory.
13947
13948 @ifclear vms
13949 @item -eL
13950 @cindex @option{-eL} (any project-aware tool)
13951 Follow all symbolic links when processing project files.
13952 @end ifclear
13953
13954 @item ^--subdirs^/SUBDIRS^=<subdir>
13955 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
13956 This switch is recognized by gnatmake and gnatclean. It indicate that the real
13957 directories (except the source directories) are the subdirectories <subdir>
13958 of the directories specified in the project files. This applies in particular
13959 to object directories, library directories and exec directories. If the
13960 subdirectories do not exist, they are created automatically.
13961
13962 @end table
13963
13964 @c **********************************
13965 @c * Tools Supporting Project Files *
13966 @c **********************************
13967
13968 @node  Tools Supporting Project Files
13969 @section Tools Supporting Project Files
13970
13971 @menu
13972 * gnatmake and Project Files::
13973 * The GNAT Driver and Project Files::
13974 @end menu
13975
13976 @node gnatmake and Project Files
13977 @subsection gnatmake and Project Files
13978
13979 @noindent
13980 This section covers several topics related to @command{gnatmake} and
13981 project files: defining ^switches^switches^ for @command{gnatmake}
13982 and for the tools that it invokes; specifying configuration pragmas;
13983 the use of the @code{Main} attribute; building and rebuilding library project
13984 files.
13985
13986 @menu
13987 * ^Switches^Switches^ and Project Files::
13988 * Specifying Configuration Pragmas::
13989 * Project Files and Main Subprograms::
13990 * Library Project Files::
13991 @end menu
13992
13993 @node ^Switches^Switches^ and Project Files
13994 @subsubsection ^Switches^Switches^ and Project Files
13995
13996 @ifset vms
13997 It is not currently possible to specify VMS style qualifiers in the project
13998 files; only Unix style ^switches^switches^ may be specified.
13999 @end ifset
14000
14001 @noindent
14002 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
14003 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
14004 attribute, a @code{^Switches^Switches^} attribute, or both;
14005 as their names imply, these ^switch^switch^-related
14006 attributes affect the ^switches^switches^ that are used for each of these GNAT
14007 components when
14008 @command{gnatmake} is invoked.  As will be explained below, these
14009 component-specific ^switches^switches^ precede
14010 the ^switches^switches^ provided on the @command{gnatmake} command line.
14011
14012 The @code{^Default_Switches^Default_Switches^} attribute is an associative
14013 array indexed by language name (case insensitive) whose value is a string list.
14014 For example:
14015
14016 @smallexample @c projectfile
14017 @group
14018 package Compiler is
14019   for ^Default_Switches^Default_Switches^ ("Ada")
14020       use ("^-gnaty^-gnaty^",
14021            "^-v^-v^");
14022 end Compiler;
14023 @end group
14024 @end smallexample
14025
14026 @noindent
14027 The @code{^Switches^Switches^} attribute is also an associative array,
14028 indexed by a file name (which may or may not be case sensitive, depending
14029 on the operating system) whose value is a string list.  For example:
14030
14031 @smallexample @c projectfile
14032 @group
14033 package Builder is
14034    for ^Switches^Switches^ ("main1.adb")
14035        use ("^-O2^-O2^");
14036    for ^Switches^Switches^ ("main2.adb")
14037        use ("^-g^-g^");
14038 end Builder;
14039 @end group
14040 @end smallexample
14041
14042 @noindent
14043 For the @code{Builder} package, the file names must designate source files
14044 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
14045 file names must designate @file{ALI} or source files for main subprograms.
14046 In each case just the file name without an explicit extension is acceptable.
14047
14048 For each tool used in a program build (@command{gnatmake}, the compiler, the
14049 binder, and the linker), the corresponding package @dfn{contributes} a set of
14050 ^switches^switches^ for each file on which the tool is invoked, based on the
14051 ^switch^switch^-related attributes defined in the package.
14052 In particular, the ^switches^switches^
14053 that each of these packages contributes for a given file @var{f} comprise:
14054
14055 @itemize @bullet
14056 @item
14057 the value of attribute @code{^Switches^Switches^ (@var{f})},
14058 if it is specified in the package for the given file,
14059 @item
14060 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
14061 if it is specified in the package.
14062 @end itemize
14063
14064 @noindent
14065 If neither of these attributes is defined in the package, then the package does
14066 not contribute any ^switches^switches^ for the given file.
14067
14068 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
14069 two sets, in the following order: those contributed for the file
14070 by the @code{Builder} package;
14071 and the switches passed on the command line.
14072
14073 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
14074 the ^switches^switches^ passed to the tool comprise three sets,
14075 in the following order:
14076
14077 @enumerate
14078 @item
14079 the applicable ^switches^switches^ contributed for the file
14080 by the @code{Builder} package in the project file supplied on the command line;
14081
14082 @item
14083 those contributed for the file by the package (in the relevant project file --
14084 see below) corresponding to the tool; and
14085
14086 @item
14087 the applicable switches passed on the command line.
14088 @end enumerate
14089
14090 @noindent
14091 The term @emph{applicable ^switches^switches^} reflects the fact that
14092 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
14093 tools, depending on the individual ^switch^switch^.
14094
14095 @command{gnatmake} may invoke the compiler on source files from different
14096 projects. The Project Manager will use the appropriate project file to
14097 determine the @code{Compiler} package for each source file being compiled.
14098 Likewise for the @code{Binder} and @code{Linker} packages.
14099
14100 As an example, consider the following package in a project file:
14101
14102 @smallexample @c projectfile
14103 @group
14104 project Proj1 is
14105    package Compiler is
14106       for ^Default_Switches^Default_Switches^ ("Ada")
14107           use ("^-g^-g^");
14108       for ^Switches^Switches^ ("a.adb")
14109           use ("^-O1^-O1^");
14110       for ^Switches^Switches^ ("b.adb")
14111           use ("^-O2^-O2^",
14112                "^-gnaty^-gnaty^");
14113    end Compiler;
14114 end Proj1;
14115 @end group
14116 @end smallexample
14117
14118 @noindent
14119 If @command{gnatmake} is invoked with this project file, and it needs to
14120 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
14121 @file{a.adb} will be compiled with the ^switch^switch^
14122 @option{^-O1^-O1^},
14123 @file{b.adb} with ^switches^switches^
14124 @option{^-O2^-O2^}
14125 and @option{^-gnaty^-gnaty^},
14126 and @file{c.adb} with @option{^-g^-g^}.
14127
14128 The following example illustrates the ordering of the ^switches^switches^
14129 contributed by different packages:
14130
14131 @smallexample @c projectfile
14132 @group
14133 project Proj2 is
14134    package Builder is
14135       for ^Switches^Switches^ ("main.adb")
14136           use ("^-g^-g^",
14137                "^-O1^-)1^",
14138                "^-f^-f^");
14139    end Builder;
14140 @end group
14141
14142 @group
14143    package Compiler is
14144       for ^Switches^Switches^ ("main.adb")
14145           use ("^-O2^-O2^");
14146    end Compiler;
14147 end Proj2;
14148 @end group
14149 @end smallexample
14150
14151 @noindent
14152 If you issue the command:
14153
14154 @smallexample
14155     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
14156 @end smallexample
14157
14158 @noindent
14159 then the compiler will be invoked on @file{main.adb} with the following
14160 sequence of ^switches^switches^
14161
14162 @smallexample
14163    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
14164 @end smallexample
14165
14166 with the last @option{^-O^-O^}
14167 ^switch^switch^ having precedence over the earlier ones;
14168 several other ^switches^switches^
14169 (such as @option{^-c^-c^}) are added implicitly.
14170
14171 The ^switches^switches^
14172 @option{^-g^-g^}
14173 and @option{^-O1^-O1^} are contributed by package
14174 @code{Builder},  @option{^-O2^-O2^} is contributed
14175 by the package @code{Compiler}
14176 and @option{^-O0^-O0^} comes from the command line.
14177
14178 The @option{^-g^-g^}
14179 ^switch^switch^ will also be passed in the invocation of
14180 @command{Gnatlink.}
14181
14182 A final example illustrates switch contributions from packages in different
14183 project files:
14184
14185 @smallexample @c projectfile
14186 @group
14187 project Proj3 is
14188    for Source_Files use ("pack.ads", "pack.adb");
14189    package Compiler is
14190       for ^Default_Switches^Default_Switches^ ("Ada")
14191           use ("^-gnata^-gnata^");
14192    end Compiler;
14193 end Proj3;
14194 @end group
14195
14196 @group
14197 with "Proj3";
14198 project Proj4 is
14199    for Source_Files use ("foo_main.adb", "bar_main.adb");
14200    package Builder is
14201       for ^Switches^Switches^ ("foo_main.adb")
14202           use ("^-s^-s^",
14203                "^-g^-g^");
14204    end Builder;
14205 end Proj4;
14206 @end group
14207
14208 @group
14209 -- Ada source file:
14210 with Pack;
14211 procedure Foo_Main is
14212    @dots{}
14213 end Foo_Main;
14214 @end group
14215 @end smallexample
14216
14217 If the command is
14218 @smallexample
14219 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
14220 @end smallexample
14221
14222 @noindent
14223 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
14224 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
14225 @option{^-gnato^-gnato^} (passed on the command line).
14226 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
14227 are @option{^-g^-g^} from @code{Proj4.Builder},
14228 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
14229 and @option{^-gnato^-gnato^} from the command line.
14230
14231 @noindent
14232 When using @command{gnatmake} with project files, some ^switches^switches^ or
14233 arguments may be expressed as relative paths. As the working directory where
14234 compilation occurs may change, these relative paths are converted to absolute
14235 paths. For the ^switches^switches^ found in a project file, the relative paths
14236 are relative to the project file directory, for the switches on the command
14237 line, they are relative to the directory where @command{gnatmake} is invoked.
14238 The ^switches^switches^ for which this occurs are:
14239 ^-I^-I^,
14240 ^-A^-A^,
14241 ^-L^-L^,
14242 ^-aO^-aO^,
14243 ^-aL^-aL^,
14244 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
14245 ^switch^switch^
14246 ^-o^-o^, object files specified in package @code{Linker} or after
14247 -largs on the command line). The exception to this rule is the ^switch^switch^
14248 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
14249
14250 @node Specifying Configuration Pragmas
14251 @subsubsection Specifying Configuration Pragmas
14252
14253 When using @command{gnatmake} with project files, if there exists a file
14254 @file{gnat.adc} that contains configuration pragmas, this file will be
14255 ignored.
14256
14257 Configuration pragmas can be defined by means of the following attributes in
14258 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
14259 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
14260
14261 Both these attributes are single string attributes. Their values is the path
14262 name of a file containing configuration pragmas. If a path name is relative,
14263 then it is relative to the project directory of the project file where the
14264 attribute is defined.
14265
14266 When compiling a source, the configuration pragmas used are, in order,
14267 those listed in the file designated by attribute
14268 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
14269 project file, if it is specified, and those listed in the file designated by
14270 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
14271 the project file of the source, if it exists.
14272
14273 @node Project Files and Main Subprograms
14274 @subsubsection Project Files and Main Subprograms
14275
14276 @noindent
14277 When using a project file, you can invoke @command{gnatmake}
14278 with one or several main subprograms, by specifying their source files on the
14279 command line.
14280
14281 @smallexample
14282     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
14283 @end smallexample
14284
14285 @noindent
14286 Each of these needs to be a source file of the same project, except
14287 when the switch ^-u^/UNIQUE^ is used.
14288
14289 @noindent
14290 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
14291 same project, one of the project in the tree rooted at the project specified
14292 on the command line. The package @code{Builder} of this common project, the
14293 "main project" is the one that is considered by @command{gnatmake}.
14294
14295 @noindent
14296 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
14297 imported directly or indirectly by the project specified on the command line.
14298 Note that if such a source file is not part of the project specified on the
14299 command line, the ^switches^switches^ found in package @code{Builder} of the
14300 project specified on the command line, if any, that are transmitted
14301 to the compiler will still be used, not those found in the project file of
14302 the source file.
14303
14304 @noindent
14305 When using a project file, you can also invoke @command{gnatmake} without
14306 explicitly specifying any main, and the effect depends on whether you have
14307 defined the @code{Main} attribute.  This attribute has a string list value,
14308 where each element in the list is the name of a source file (the file
14309 extension is optional) that contains a unit that can be a main subprogram.
14310
14311 If the @code{Main} attribute is defined in a project file as a non-empty
14312 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
14313 line, then invoking @command{gnatmake} with this project file but without any
14314 main on the command line is equivalent to invoking @command{gnatmake} with all
14315 the file names in the @code{Main} attribute on the command line.
14316
14317 Example:
14318 @smallexample @c projectfile
14319 @group
14320    project Prj is
14321       for Main use ("main1", "main2", "main3");
14322    end Prj;
14323 @end group
14324 @end smallexample
14325
14326 @noindent
14327 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
14328 is equivalent to
14329 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
14330
14331 When the project attribute @code{Main} is not specified, or is specified
14332 as an empty string list, or when the switch @option{-u} is used on the command
14333 line, then invoking @command{gnatmake} with no main on the command line will
14334 result in all immediate sources of the project file being checked, and
14335 potentially recompiled. Depending on the presence of the switch @option{-u},
14336 sources from other project files on which the immediate sources of the main
14337 project file depend are also checked and potentially recompiled. In other
14338 words, the @option{-u} switch is applied to all of the immediate sources of the
14339 main project file.
14340
14341 When no main is specified on the command line and attribute @code{Main} exists
14342 and includes several mains, or when several mains are specified on the
14343 command line, the default ^switches^switches^ in package @code{Builder} will
14344 be used for all mains, even if there are specific ^switches^switches^
14345 specified for one or several mains.
14346
14347 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
14348 the specific ^switches^switches^ for each main, if they are specified.
14349
14350 @node Library Project Files
14351 @subsubsection Library Project Files
14352
14353 @noindent
14354 When @command{gnatmake} is invoked with a main project file that is a library
14355 project file, it is not allowed to specify one or more mains on the command
14356 line.
14357
14358 @noindent
14359 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
14360 ^-l^/ACTION=LINK^ have special meanings.
14361
14362 @itemize @bullet
14363 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
14364 to @command{gnatmake} that @command{gnatbind} should be invoked for the
14365 library.
14366
14367 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
14368 to @command{gnatmake} that the binder generated file should be compiled
14369 (in the case of a stand-alone library) and that the library should be built.
14370
14371 @end itemize
14372
14373 @node The GNAT Driver and Project Files
14374 @subsection The GNAT Driver and Project Files
14375
14376 @noindent
14377 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
14378 can benefit from project files:
14379 @command{^gnatbind^gnatbind^},
14380 @command{^gnatcheck^gnatcheck^}),
14381 @command{^gnatclean^gnatclean^}),
14382 @command{^gnatelim^gnatelim^},
14383 @command{^gnatfind^gnatfind^},
14384 @command{^gnatlink^gnatlink^},
14385 @command{^gnatls^gnatls^},
14386 @command{^gnatmetric^gnatmetric^},
14387 @command{^gnatpp^gnatpp^},
14388 @command{^gnatstub^gnatstub^},
14389 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
14390 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
14391 They must be invoked through the @command{gnat} driver.
14392
14393 The @command{gnat} driver is a wrapper that accepts a number of commands and
14394 calls the corresponding tool. It was designed initially for VMS platforms (to
14395 convert VMS qualifiers to Unix-style switches), but it is now available on all
14396 GNAT platforms.
14397
14398 On non-VMS platforms, the @command{gnat} driver accepts the following commands
14399 (case insensitive):
14400
14401 @itemize @bullet
14402 @item
14403 BIND to invoke @command{^gnatbind^gnatbind^}
14404 @item
14405 CHOP to invoke @command{^gnatchop^gnatchop^}
14406 @item
14407 CLEAN to invoke @command{^gnatclean^gnatclean^}
14408 @item
14409 COMP or COMPILE to invoke the compiler
14410 @item
14411 ELIM to invoke @command{^gnatelim^gnatelim^}
14412 @item
14413 FIND to invoke @command{^gnatfind^gnatfind^}
14414 @item
14415 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
14416 @item
14417 LINK to invoke @command{^gnatlink^gnatlink^}
14418 @item
14419 LS or LIST to invoke @command{^gnatls^gnatls^}
14420 @item
14421 MAKE to invoke @command{^gnatmake^gnatmake^}
14422 @item
14423 NAME to invoke @command{^gnatname^gnatname^}
14424 @item
14425 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
14426 @item
14427 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
14428 @item
14429 METRIC to invoke @command{^gnatmetric^gnatmetric^}
14430 @item
14431 STUB to invoke @command{^gnatstub^gnatstub^}
14432 @item
14433 XREF to invoke @command{^gnatxref^gnatxref^}
14434 @end itemize
14435
14436 @noindent
14437 (note that the compiler is invoked using the command
14438 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
14439
14440 @noindent
14441 On non-VMS platforms, between @command{gnat} and the command, two
14442 special switches may be used:
14443
14444 @itemize @bullet
14445 @item
14446 @command{-v} to display the invocation of the tool.
14447 @item
14448 @command{-dn} to prevent the @command{gnat} driver from removing
14449 the temporary files it has created. These temporary files are
14450 configuration files and temporary file list files.
14451 @end itemize
14452
14453 @noindent
14454 The command may be followed by switches and arguments for the invoked
14455 tool.
14456
14457 @smallexample
14458   gnat bind -C main.ali
14459   gnat ls -a main
14460   gnat chop foo.txt
14461 @end smallexample
14462
14463 @noindent
14464 Switches may also be put in text files, one switch per line, and the text
14465 files may be specified with their path name preceded by '@@'.
14466
14467 @smallexample
14468    gnat bind @@args.txt main.ali
14469 @end smallexample
14470
14471 @noindent
14472 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
14473 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
14474 (@option{^-P^/PROJECT_FILE^},
14475 @option{^-X^/EXTERNAL_REFERENCE^} and
14476 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
14477 the switches of the invoking tool.
14478
14479 @noindent
14480 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
14481 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
14482 the immediate sources of the specified project file.
14483
14484 @noindent
14485 When GNAT METRIC is used with a project file, but with no source
14486 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
14487 with all the immediate sources of the specified project file and with
14488 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
14489 of the project.
14490
14491 @noindent
14492 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
14493 a project file, no source is specified on the command line and
14494 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
14495 the underlying tool (^gnatpp^gnatpp^ or
14496 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
14497 not only for the immediate sources of the main project.
14498 @ifclear vms
14499 (-U stands for Universal or Union of the project files of the project tree)
14500 @end ifclear
14501
14502 @noindent
14503 For each of the following commands, there is optionally a corresponding
14504 package in the main project.
14505
14506 @itemize @bullet
14507 @item
14508 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
14509
14510 @item
14511 package @code{Check} for command CHECK (invoking
14512 @code{^gnatcheck^gnatcheck^})
14513
14514 @item
14515 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
14516
14517 @item
14518 package @code{Cross_Reference} for command XREF (invoking
14519 @code{^gnatxref^gnatxref^})
14520
14521 @item
14522 package @code{Eliminate} for command ELIM (invoking
14523 @code{^gnatelim^gnatelim^})
14524
14525 @item
14526 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
14527
14528 @item
14529 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
14530
14531 @item
14532 package @code{Gnatstub} for command STUB
14533 (invoking @code{^gnatstub^gnatstub^})
14534
14535 @item
14536 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
14537
14538 @item
14539 package @code{Metrics} for command METRIC
14540 (invoking @code{^gnatmetric^gnatmetric^})
14541
14542 @item
14543 package @code{Pretty_Printer} for command PP or PRETTY
14544 (invoking @code{^gnatpp^gnatpp^})
14545
14546 @end itemize
14547
14548 @noindent
14549 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
14550 a simple variable with a string list value. It contains ^switches^switches^
14551 for the invocation of @code{^gnatls^gnatls^}.
14552
14553 @smallexample @c projectfile
14554 @group
14555 project Proj1 is
14556    package gnatls is
14557       for ^Switches^Switches^
14558           use ("^-a^-a^",
14559                "^-v^-v^");
14560    end gnatls;
14561 end Proj1;
14562 @end group
14563 @end smallexample
14564
14565 @noindent
14566 All other packages have two attribute @code{^Switches^Switches^} and
14567 @code{^Default_Switches^Default_Switches^}.
14568
14569 @noindent
14570 @code{^Switches^Switches^} is an associative array attribute, indexed by the
14571 source file name, that has a string list value: the ^switches^switches^ to be
14572 used when the tool corresponding to the package is invoked for the specific
14573 source file.
14574
14575 @noindent
14576 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
14577 indexed by  the programming language that has a string list value.
14578 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14579 ^switches^switches^ for the invocation of the tool corresponding
14580 to the package, except if a specific @code{^Switches^Switches^} attribute
14581 is specified for the source file.
14582
14583 @smallexample @c projectfile
14584 @group
14585 project Proj is
14586
14587    for Source_Dirs use ("./**");
14588
14589    package gnatls is
14590       for ^Switches^Switches^ use
14591           ("^-a^-a^",
14592            "^-v^-v^");
14593    end gnatls;
14594 @end group
14595 @group
14596
14597    package Compiler is
14598       for ^Default_Switches^Default_Switches^ ("Ada")
14599           use ("^-gnatv^-gnatv^",
14600                "^-gnatwa^-gnatwa^");
14601    end Binder;
14602 @end group
14603 @group
14604
14605    package Binder is
14606       for ^Default_Switches^Default_Switches^ ("Ada")
14607           use ("^-C^-C^",
14608                "^-e^-e^");
14609    end Binder;
14610 @end group
14611 @group
14612
14613    package Linker is
14614       for ^Default_Switches^Default_Switches^ ("Ada")
14615           use ("^-C^-C^");
14616       for ^Switches^Switches^ ("main.adb")
14617           use ("^-C^-C^",
14618                "^-v^-v^",
14619                "^-v^-v^");
14620    end Linker;
14621 @end group
14622 @group
14623
14624    package Finder is
14625       for ^Default_Switches^Default_Switches^ ("Ada")
14626            use ("^-a^-a^",
14627                 "^-f^-f^");
14628    end Finder;
14629 @end group
14630 @group
14631
14632    package Cross_Reference is
14633       for ^Default_Switches^Default_Switches^ ("Ada")
14634           use ("^-a^-a^",
14635                "^-f^-f^",
14636                "^-d^-d^",
14637                "^-u^-u^");
14638    end Cross_Reference;
14639 end Proj;
14640 @end group
14641 @end smallexample
14642
14643 @noindent
14644 With the above project file, commands such as
14645
14646 @smallexample
14647    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
14648    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
14649    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
14650    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
14651    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
14652 @end smallexample
14653
14654 @noindent
14655 will set up the environment properly and invoke the tool with the switches
14656 found in the package corresponding to the tool:
14657 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
14658 except @code{^Switches^Switches^ ("main.adb")}
14659 for @code{^gnatlink^gnatlink^}.
14660 It is also possible to invoke some of the tools,
14661 @code{^gnatcheck^gnatcheck^}),
14662 @code{^gnatmetric^gnatmetric^}),
14663 and @code{^gnatpp^gnatpp^})
14664 on a set of project units thanks to the combination of the switches
14665 @option{-P}, @option{-U} and possibly the main unit when one is interested
14666 in its closure. For instance,
14667 @smallexample
14668 gnat metric -Pproj
14669 @end smallexample
14670 will compute the metrics for all the immediate units of project
14671 @code{proj}.
14672 @smallexample
14673 gnat metric -Pproj -U
14674 @end smallexample
14675 will compute the metrics for all the units of the closure of projects
14676 rooted at @code{proj}.
14677 @smallexample
14678 gnat metric -Pproj -U main_unit
14679 @end smallexample
14680 will compute the metrics for the closure of units rooted at
14681 @code{main_unit}. This last possibility relies implicitly
14682 on @command{gnatbind}'s option @option{-R}.
14683
14684 @c **********************
14685 @node An Extended Example
14686 @section An Extended Example
14687
14688 @noindent
14689 Suppose that we have two programs, @var{prog1} and @var{prog2},
14690 whose sources are in corresponding directories. We would like
14691 to build them with a single @command{gnatmake} command, and we want to place
14692 their object files into @file{build} subdirectories of the source directories.
14693 Furthermore, we want to have to have two separate subdirectories
14694 in @file{build}  -- @file{release} and @file{debug} -- which will contain
14695 the object files compiled with different set of compilation flags.
14696
14697 In other words, we have the following structure:
14698
14699 @smallexample
14700 @group
14701    main
14702      |- prog1
14703      |    |- build
14704      |         | debug
14705      |         | release
14706      |- prog2
14707           |- build
14708                | debug
14709                | release
14710 @end group
14711 @end smallexample
14712
14713 @noindent
14714 Here are the project files that we must place in a directory @file{main}
14715 to maintain this structure:
14716
14717 @enumerate
14718
14719 @item We create a @code{Common} project with a package @code{Compiler} that
14720 specifies the compilation ^switches^switches^:
14721
14722 @smallexample
14723 File "common.gpr":
14724 @group
14725 @b{project} Common @b{is}
14726
14727    @b{for} Source_Dirs @b{use} (); -- No source files
14728 @end group
14729
14730 @group
14731    @b{type} Build_Type @b{is} ("release", "debug");
14732    Build : Build_Type := External ("BUILD", "debug");
14733 @end group
14734 @group
14735    @b{package} Compiler @b{is}
14736       @b{case} Build @b{is}
14737          @b{when} "release" =>
14738            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14739                    @b{use} ("^-O2^-O2^");
14740          @b{when} "debug"   =>
14741            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
14742                    @b{use} ("^-g^-g^");
14743       @b{end case};
14744    @b{end} Compiler;
14745
14746 @b{end} Common;
14747 @end group
14748 @end smallexample
14749
14750 @item We create separate projects for the two programs:
14751
14752 @smallexample
14753 @group
14754 File "prog1.gpr":
14755
14756 @b{with} "common";
14757 @b{project} Prog1 @b{is}
14758
14759     @b{for} Source_Dirs @b{use} ("prog1");
14760     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
14761
14762     @b{package} Compiler @b{renames} Common.Compiler;
14763
14764 @b{end} Prog1;
14765 @end group
14766 @end smallexample
14767
14768 @smallexample
14769 @group
14770 File "prog2.gpr":
14771
14772 @b{with} "common";
14773 @b{project} Prog2 @b{is}
14774
14775     @b{for} Source_Dirs @b{use} ("prog2");
14776     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
14777
14778     @b{package} Compiler @b{renames} Common.Compiler;
14779
14780 @end group
14781 @b{end} Prog2;
14782 @end smallexample
14783
14784 @item We create a wrapping project @code{Main}:
14785
14786 @smallexample
14787 @group
14788 File "main.gpr":
14789
14790 @b{with} "common";
14791 @b{with} "prog1";
14792 @b{with} "prog2";
14793 @b{project} Main @b{is}
14794
14795    @b{package} Compiler @b{renames} Common.Compiler;
14796
14797 @b{end} Main;
14798 @end group
14799 @end smallexample
14800
14801 @item Finally we need to create a dummy procedure that @code{with}s (either
14802 explicitly or implicitly) all the sources of our two programs.
14803
14804 @end enumerate
14805
14806 @noindent
14807 Now we can build the programs using the command
14808
14809 @smallexample
14810    gnatmake ^-P^/PROJECT_FILE=^main dummy
14811 @end smallexample
14812
14813 @noindent
14814 for the Debug mode, or
14815
14816 @ifclear vms
14817 @smallexample
14818    gnatmake -Pmain -XBUILD=release
14819 @end smallexample
14820 @end ifclear
14821
14822 @ifset vms
14823 @smallexample
14824    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
14825 @end smallexample
14826 @end ifset
14827
14828 @noindent
14829 for the Release mode.
14830
14831 @c ********************************
14832 @c * Project File Complete Syntax *
14833 @c ********************************
14834
14835 @node Project File Complete Syntax
14836 @section Project File Complete Syntax
14837
14838 @smallexample
14839 project ::=
14840   context_clause project_declaration
14841
14842 context_clause ::=
14843   @{with_clause@}
14844
14845 with_clause ::=
14846   @b{with} path_name @{ , path_name @} ;
14847
14848 path_name ::=
14849    string_literal
14850
14851 project_declaration ::=
14852   simple_project_declaration | project_extension
14853
14854 simple_project_declaration ::=
14855   @b{project} <project_>simple_name @b{is}
14856     @{declarative_item@}
14857   @b{end} <project_>simple_name;
14858
14859 project_extension ::=
14860   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
14861     @{declarative_item@}
14862   @b{end} <project_>simple_name;
14863
14864 declarative_item ::=
14865   package_declaration |
14866   typed_string_declaration |
14867   other_declarative_item
14868
14869 package_declaration ::=
14870   package_spec | package_renaming
14871
14872 package_spec ::=
14873   @b{package} package_identifier @b{is}
14874     @{simple_declarative_item@}
14875   @b{end} package_identifier ;
14876
14877 package_identifier ::=
14878   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
14879   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
14880   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
14881
14882 package_renaming ::==
14883   @b{package} package_identifier @b{renames}
14884        <project_>simple_name.package_identifier ;
14885
14886 typed_string_declaration ::=
14887   @b{type} <typed_string_>_simple_name @b{is}
14888    ( string_literal @{, string_literal@} );
14889
14890 other_declarative_item ::=
14891   attribute_declaration |
14892   typed_variable_declaration |
14893   variable_declaration |
14894   case_construction
14895
14896 attribute_declaration ::=
14897   full_associative_array_declaration |
14898   @b{for} attribute_designator @b{use} expression ;
14899
14900 full_associative_array_declaration ::=
14901   @b{for} <associative_array_attribute_>simple_name @b{use}
14902   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
14903
14904 attribute_designator ::=
14905   <simple_attribute_>simple_name |
14906   <associative_array_attribute_>simple_name ( string_literal )
14907
14908 typed_variable_declaration ::=
14909   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
14910
14911 variable_declaration ::=
14912   <variable_>simple_name := expression;
14913
14914 expression ::=
14915   term @{& term@}
14916
14917 term ::=
14918   literal_string |
14919   string_list |
14920   <variable_>name |
14921   external_value |
14922   attribute_reference
14923
14924 string_literal ::=
14925   (same as Ada)
14926
14927 string_list ::=
14928   ( <string_>expression @{ , <string_>expression @} )
14929
14930 external_value ::=
14931   @b{external} ( string_literal [, string_literal] )
14932
14933 attribute_reference ::=
14934   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
14935
14936 attribute_prefix ::=
14937   @b{project} |
14938   <project_>simple_name | package_identifier |
14939   <project_>simple_name . package_identifier
14940
14941 case_construction ::=
14942   @b{case} <typed_variable_>name @b{is}
14943     @{case_item@}
14944   @b{end case} ;
14945
14946 case_item ::=
14947   @b{when} discrete_choice_list =>
14948       @{case_construction | attribute_declaration@}
14949
14950 discrete_choice_list ::=
14951   string_literal @{| string_literal@} |
14952   @b{others}
14953
14954 name ::=
14955   simple_name @{. simple_name@}
14956
14957 simple_name ::=
14958   identifier (same as Ada)
14959
14960 @end smallexample
14961
14962 @node The Cross-Referencing Tools gnatxref and gnatfind
14963 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
14964 @findex gnatxref
14965 @findex gnatfind
14966
14967 @noindent
14968 The compiler generates cross-referencing information (unless
14969 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
14970 This information indicates where in the source each entity is declared and
14971 referenced. Note that entities in package Standard are not included, but
14972 entities in all other predefined units are included in the output.
14973
14974 Before using any of these two tools, you need to compile successfully your
14975 application, so that GNAT gets a chance to generate the cross-referencing
14976 information.
14977
14978 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
14979 information to provide the user with the capability to easily locate the
14980 declaration and references to an entity. These tools are quite similar,
14981 the difference being that @code{gnatfind} is intended for locating
14982 definitions and/or references to a specified entity or entities, whereas
14983 @code{gnatxref} is oriented to generating a full report of all
14984 cross-references.
14985
14986 To use these tools, you must not compile your application using the
14987 @option{-gnatx} switch on the @command{gnatmake} command line
14988 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
14989 information will not be generated.
14990
14991 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
14992 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
14993
14994 @menu
14995 * gnatxref Switches::
14996 * gnatfind Switches::
14997 * Project Files for gnatxref and gnatfind::
14998 * Regular Expressions in gnatfind and gnatxref::
14999 * Examples of gnatxref Usage::
15000 * Examples of gnatfind Usage::
15001 @end menu
15002
15003 @node gnatxref Switches
15004 @section @code{gnatxref} Switches
15005
15006 @noindent
15007 The command invocation for @code{gnatxref} is:
15008 @smallexample
15009 $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
15010 @end smallexample
15011
15012 @noindent
15013 where
15014
15015 @table @var
15016 @item sourcefile1
15017 @itemx sourcefile2
15018 identifies the source files for which a report is to be generated. The
15019 ``with''ed units will be processed too. You must provide at least one file.
15020
15021 These file names are considered to be regular expressions, so for instance
15022 specifying @file{source*.adb} is the same as giving every file in the current
15023 directory whose name starts with @file{source} and whose extension is
15024 @file{adb}.
15025
15026 You shouldn't specify any directory name, just base names. @command{gnatxref}
15027 and @command{gnatfind} will be able to locate these files by themselves using
15028 the source path. If you specify directories, no result is produced.
15029
15030 @end table
15031
15032 @noindent
15033 The switches can be:
15034 @table @option
15035 @c !sort!
15036 @item --version
15037 @cindex @option{--version} @command{gnatxref}
15038 Display Copyright and version, then exit disregarding all other options.
15039
15040 @item --help
15041 @cindex @option{--help} @command{gnatxref}
15042 If @option{--version} was not used, display usage, then exit disregarding
15043 all other options.
15044
15045 @item ^-a^/ALL_FILES^
15046 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
15047 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15048 the read-only files found in the library search path. Otherwise, these files
15049 will be ignored. This option can be used to protect Gnat sources or your own
15050 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15051 much faster, and their output much smaller. Read-only here refers to access
15052 or permissions status in the file system for the current user.
15053
15054 @item -aIDIR
15055 @cindex @option{-aIDIR} (@command{gnatxref})
15056 When looking for source files also look in directory DIR. The order in which
15057 source file search is undertaken is the same as for @command{gnatmake}.
15058
15059 @item -aODIR
15060 @cindex @option{-aODIR} (@command{gnatxref})
15061 When searching for library and object files, look in directory
15062 DIR. The order in which library files are searched is the same as for
15063 @command{gnatmake}.
15064
15065 @item -nostdinc
15066 @cindex @option{-nostdinc} (@command{gnatxref})
15067 Do not look for sources in the system default directory.
15068
15069 @item -nostdlib
15070 @cindex @option{-nostdlib} (@command{gnatxref})
15071 Do not look for library files in the system default directory.
15072
15073 @item --RTS=@var{rts-path}
15074 @cindex @option{--RTS} (@command{gnatxref})
15075 Specifies the default location of the runtime library. Same meaning as the
15076 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15077
15078 @item ^-d^/DERIVED_TYPES^
15079 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
15080 If this switch is set @code{gnatxref} will output the parent type
15081 reference for each matching derived types.
15082
15083 @item ^-f^/FULL_PATHNAME^
15084 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
15085 If this switch is set, the output file names will be preceded by their
15086 directory (if the file was found in the search path). If this switch is
15087 not set, the directory will not be printed.
15088
15089 @item ^-g^/IGNORE_LOCALS^
15090 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
15091 If this switch is set, information is output only for library-level
15092 entities, ignoring local entities. The use of this switch may accelerate
15093 @code{gnatfind} and @code{gnatxref}.
15094
15095 @item -IDIR
15096 @cindex @option{-IDIR} (@command{gnatxref})
15097 Equivalent to @samp{-aODIR -aIDIR}.
15098
15099 @item -pFILE
15100 @cindex @option{-pFILE} (@command{gnatxref})
15101 Specify a project file to use @xref{Project Files}.
15102 If you need to use the @file{.gpr}
15103 project files, you should use gnatxref through the GNAT driver
15104 (@command{gnat xref -Pproject}).
15105
15106 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15107 project file in the current directory.
15108
15109 If a project file is either specified or found by the tools, then the content
15110 of the source directory and object directory lines are added as if they
15111 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
15112 and @samp{^-aO^OBJECT_SEARCH^}.
15113 @item ^-u^/UNUSED^
15114 Output only unused symbols. This may be really useful if you give your
15115 main compilation unit on the command line, as @code{gnatxref} will then
15116 display every unused entity and 'with'ed package.
15117
15118 @ifclear vms
15119 @item -v
15120 Instead of producing the default output, @code{gnatxref} will generate a
15121 @file{tags} file that can be used by vi. For examples how to use this
15122 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
15123 to the standard output, thus you will have to redirect it to a file.
15124 @end ifclear
15125
15126 @end table
15127
15128 @noindent
15129 All these switches may be in any order on the command line, and may even
15130 appear after the file names. They need not be separated by spaces, thus
15131 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15132 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15133
15134 @node gnatfind Switches
15135 @section @code{gnatfind} Switches
15136
15137 @noindent
15138 The command line for @code{gnatfind} is:
15139
15140 @smallexample
15141 $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
15142       @r{[}@var{file1} @var{file2} @dots{}]
15143 @end smallexample
15144
15145 @noindent
15146 where
15147
15148 @table @var
15149 @item pattern
15150 An entity will be output only if it matches the regular expression found
15151 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
15152
15153 Omitting the pattern is equivalent to specifying @samp{*}, which
15154 will match any entity. Note that if you do not provide a pattern, you
15155 have to provide both a sourcefile and a line.
15156
15157 Entity names are given in Latin-1, with uppercase/lowercase equivalence
15158 for matching purposes. At the current time there is no support for
15159 8-bit codes other than Latin-1, or for wide characters in identifiers.
15160
15161 @item sourcefile
15162 @code{gnatfind} will look for references, bodies or declarations
15163 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
15164 and column @var{column}. See @ref{Examples of gnatfind Usage}
15165 for syntax examples.
15166
15167 @item line
15168 is a decimal integer identifying the line number containing
15169 the reference to the entity (or entities) to be located.
15170
15171 @item column
15172 is a decimal integer identifying the exact location on the
15173 line of the first character of the identifier for the
15174 entity reference. Columns are numbered from 1.
15175
15176 @item file1 file2 @dots{}
15177 The search will be restricted to these source files. If none are given, then
15178 the search will be done for every library file in the search path.
15179 These file must appear only after the pattern or sourcefile.
15180
15181 These file names are considered to be regular expressions, so for instance
15182 specifying @file{source*.adb} is the same as giving every file in the current
15183 directory whose name starts with @file{source} and whose extension is
15184 @file{adb}.
15185
15186 The location of the spec of the entity will always be displayed, even if it
15187 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
15188 occurrences of the entity in the separate units of the ones given on the
15189 command line will also be displayed.
15190
15191 Note that if you specify at least one file in this part, @code{gnatfind} may
15192 sometimes not be able to find the body of the subprograms.
15193
15194 @end table
15195
15196 @noindent
15197 At least one of 'sourcefile' or 'pattern' has to be present on
15198 the command line.
15199
15200 The following switches are available:
15201 @table @option
15202 @c !sort!
15203
15204 @cindex @option{--version} @command{gnatfind}
15205 Display Copyright and version, then exit disregarding all other options.
15206
15207 @item --help
15208 @cindex @option{--help} @command{gnatfind}
15209 If @option{--version} was not used, display usage, then exit disregarding
15210 all other options.
15211
15212 @item ^-a^/ALL_FILES^
15213 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
15214 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15215 the read-only files found in the library search path. Otherwise, these files
15216 will be ignored. This option can be used to protect Gnat sources or your own
15217 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15218 much faster, and their output much smaller. Read-only here refers to access
15219 or permission status in the file system for the current user.
15220
15221 @item -aIDIR
15222 @cindex @option{-aIDIR} (@command{gnatfind})
15223 When looking for source files also look in directory DIR. The order in which
15224 source file search is undertaken is the same as for @command{gnatmake}.
15225
15226 @item -aODIR
15227 @cindex @option{-aODIR} (@command{gnatfind})
15228 When searching for library and object files, look in directory
15229 DIR. The order in which library files are searched is the same as for
15230 @command{gnatmake}.
15231
15232 @item -nostdinc
15233 @cindex @option{-nostdinc} (@command{gnatfind})
15234 Do not look for sources in the system default directory.
15235
15236 @item -nostdlib
15237 @cindex @option{-nostdlib} (@command{gnatfind})
15238 Do not look for library files in the system default directory.
15239
15240 @item --RTS=@var{rts-path}
15241 @cindex @option{--RTS} (@command{gnatfind})
15242 Specifies the default location of the runtime library. Same meaning as the
15243 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15244
15245 @item ^-d^/DERIVED_TYPE_INFORMATION^
15246 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
15247 If this switch is set, then @code{gnatfind} will output the parent type
15248 reference for each matching derived types.
15249
15250 @item ^-e^/EXPRESSIONS^
15251 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
15252 By default, @code{gnatfind} accept the simple regular expression set for
15253 @samp{pattern}. If this switch is set, then the pattern will be
15254 considered as full Unix-style regular expression.
15255
15256 @item ^-f^/FULL_PATHNAME^
15257 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
15258 If this switch is set, the output file names will be preceded by their
15259 directory (if the file was found in the search path). If this switch is
15260 not set, the directory will not be printed.
15261
15262 @item ^-g^/IGNORE_LOCALS^
15263 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
15264 If this switch is set, information is output only for library-level
15265 entities, ignoring local entities. The use of this switch may accelerate
15266 @code{gnatfind} and @code{gnatxref}.
15267
15268 @item -IDIR
15269 @cindex @option{-IDIR} (@command{gnatfind})
15270 Equivalent to @samp{-aODIR -aIDIR}.
15271
15272 @item -pFILE
15273 @cindex @option{-pFILE} (@command{gnatfind})
15274 Specify a project file (@pxref{Project Files}) to use.
15275 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15276 project file in the current directory.
15277
15278 If a project file is either specified or found by the tools, then the content
15279 of the source directory and object directory lines are added as if they
15280 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
15281 @samp{^-aO^/OBJECT_SEARCH^}.
15282
15283 @item ^-r^/REFERENCES^
15284 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
15285 By default, @code{gnatfind} will output only the information about the
15286 declaration, body or type completion of the entities. If this switch is
15287 set, the @code{gnatfind} will locate every reference to the entities in
15288 the files specified on the command line (or in every file in the search
15289 path if no file is given on the command line).
15290
15291 @item ^-s^/PRINT_LINES^
15292 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
15293 If this switch is set, then @code{gnatfind} will output the content
15294 of the Ada source file lines were the entity was found.
15295
15296 @item ^-t^/TYPE_HIERARCHY^
15297 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
15298 If this switch is set, then @code{gnatfind} will output the type hierarchy for
15299 the specified type. It act like -d option but recursively from parent
15300 type to parent type. When this switch is set it is not possible to
15301 specify more than one file.
15302
15303 @end table
15304
15305 @noindent
15306 All these switches may be in any order on the command line, and may even
15307 appear after the file names. They need not be separated by spaces, thus
15308 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15309 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15310
15311 As stated previously, gnatfind will search in every directory in the
15312 search path. You can force it to look only in the current directory if
15313 you specify @code{*} at the end of the command line.
15314
15315 @node Project Files for gnatxref and gnatfind
15316 @section Project Files for @command{gnatxref} and @command{gnatfind}
15317
15318 @noindent
15319 Project files allow a programmer to specify how to compile its
15320 application, where to find sources, etc.  These files are used
15321 @ifclear vms
15322 primarily by GPS, but they can also be used
15323 @end ifclear
15324 by the two tools
15325 @code{gnatxref} and @code{gnatfind}.
15326
15327 A project file name must end with @file{.gpr}. If a single one is
15328 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
15329 extract the information from it. If multiple project files are found, none of
15330 them is read, and you have to use the @samp{-p} switch to specify the one
15331 you want to use.
15332
15333 The following lines can be included, even though most of them have default
15334 values which can be used in most cases.
15335 The lines can be entered in any order in the file.
15336 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
15337 each line. If you have multiple instances, only the last one is taken into
15338 account.
15339
15340 @table @code
15341 @item src_dir=DIR
15342 [default: @code{"^./^[]^"}]
15343 specifies a directory where to look for source files. Multiple @code{src_dir}
15344 lines can be specified and they will be searched in the order they
15345 are specified.
15346
15347 @item obj_dir=DIR
15348 [default: @code{"^./^[]^"}]
15349 specifies a directory where to look for object and library files. Multiple
15350 @code{obj_dir} lines can be specified, and they will be searched in the order
15351 they are specified
15352
15353 @item comp_opt=SWITCHES
15354 [default: @code{""}]
15355 creates a variable which can be referred to subsequently by using
15356 the @code{$@{comp_opt@}} notation. This is intended to store the default
15357 switches given to @command{gnatmake} and @command{gcc}.
15358
15359 @item bind_opt=SWITCHES
15360 [default: @code{""}]
15361 creates a variable which can be referred to subsequently by using
15362 the @samp{$@{bind_opt@}} notation. This is intended to store the default
15363 switches given to @command{gnatbind}.
15364
15365 @item link_opt=SWITCHES
15366 [default: @code{""}]
15367 creates a variable which can be referred to subsequently by using
15368 the @samp{$@{link_opt@}} notation. This is intended to store the default
15369 switches given to @command{gnatlink}.
15370
15371 @item main=EXECUTABLE
15372 [default: @code{""}]
15373 specifies the name of the executable for the application. This variable can
15374 be referred to in the following lines by using the @samp{$@{main@}} notation.
15375
15376 @ifset vms
15377 @item comp_cmd=COMMAND
15378 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
15379 @end ifset
15380 @ifclear vms
15381 @item comp_cmd=COMMAND
15382 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
15383 @end ifclear
15384 specifies the command used to compile a single file in the application.
15385
15386 @ifset vms
15387 @item make_cmd=COMMAND
15388 [default: @code{"GNAT MAKE $@{main@}
15389 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
15390 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
15391 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
15392 @end ifset
15393 @ifclear vms
15394 @item make_cmd=COMMAND
15395 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
15396 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
15397 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
15398 @end ifclear
15399 specifies the command used to recompile the whole application.
15400
15401 @item run_cmd=COMMAND
15402 [default: @code{"$@{main@}"}]
15403 specifies the command used to run the application.
15404
15405 @item debug_cmd=COMMAND
15406 [default: @code{"gdb $@{main@}"}]
15407 specifies the command used to debug the application
15408
15409 @end table
15410
15411 @noindent
15412 @command{gnatxref} and @command{gnatfind} only take into account the
15413 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
15414
15415 @node Regular Expressions in gnatfind and gnatxref
15416 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
15417
15418 @noindent
15419 As specified in the section about @command{gnatfind}, the pattern can be a
15420 regular expression. Actually, there are to set of regular expressions
15421 which are recognized by the program:
15422
15423 @table @code
15424 @item globbing patterns
15425 These are the most usual regular expression. They are the same that you
15426 generally used in a Unix shell command line, or in a DOS session.
15427
15428 Here is a more formal grammar:
15429 @smallexample
15430 @group
15431 @iftex
15432 @leftskip=.5cm
15433 @end iftex
15434 regexp ::= term
15435 term   ::= elmt            -- matches elmt
15436 term   ::= elmt elmt       -- concatenation (elmt then elmt)
15437 term   ::= *               -- any string of 0 or more characters
15438 term   ::= ?               -- matches any character
15439 term   ::= [char @{char@}]   -- matches any character listed
15440 term   ::= [char - char]   -- matches any character in range
15441 @end group
15442 @end smallexample
15443
15444 @item full regular expression
15445 The second set of regular expressions is much more powerful. This is the
15446 type of regular expressions recognized by utilities such a @file{grep}.
15447
15448 The following is the form of a regular expression, expressed in Ada
15449 reference manual style BNF is as follows
15450
15451 @smallexample
15452 @iftex
15453 @leftskip=.5cm
15454 @end iftex
15455 @group
15456 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
15457
15458 term ::= item @{item@}       -- concatenation (item then item)
15459
15460 item ::= elmt              -- match elmt
15461 item ::= elmt *            -- zero or more elmt's
15462 item ::= elmt +            -- one or more elmt's
15463 item ::= elmt ?            -- matches elmt or nothing
15464 @end group
15465 @group
15466 elmt ::= nschar            -- matches given character
15467 elmt ::= [nschar @{nschar@}]   -- matches any character listed
15468 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
15469 elmt ::= [char - char]     -- matches chars in given range
15470 elmt ::= \ char            -- matches given character
15471 elmt ::= .                 -- matches any single character
15472 elmt ::= ( regexp )        -- parens used for grouping
15473
15474 char ::= any character, including special characters
15475 nschar ::= any character except ()[].*+?^^^
15476 @end group
15477 @end smallexample
15478
15479 Following are a few examples:
15480
15481 @table @samp
15482 @item abcde|fghi
15483 will match any of the two strings @samp{abcde} and @samp{fghi},
15484
15485 @item abc*d
15486 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
15487 @samp{abcccd}, and so on,
15488
15489 @item [a-z]+
15490 will match any string which has only lowercase characters in it (and at
15491 least one character.
15492
15493 @end table
15494 @end table
15495
15496 @node Examples of gnatxref Usage
15497 @section Examples of @code{gnatxref} Usage
15498
15499 @subsection General Usage
15500
15501 @noindent
15502 For the following examples, we will consider the following units:
15503
15504 @smallexample @c ada
15505 @group
15506 @cartouche
15507 main.ads:
15508 1: with Bar;
15509 2: package Main is
15510 3:     procedure Foo (B : in Integer);
15511 4:     C : Integer;
15512 5: private
15513 6:     D : Integer;
15514 7: end Main;
15515
15516 main.adb:
15517 1: package body Main is
15518 2:     procedure Foo (B : in Integer) is
15519 3:     begin
15520 4:        C := B;
15521 5:        D := B;
15522 6:        Bar.Print (B);
15523 7:        Bar.Print (C);
15524 8:     end Foo;
15525 9: end Main;
15526
15527 bar.ads:
15528 1: package Bar is
15529 2:     procedure Print (B : Integer);
15530 3: end bar;
15531 @end cartouche
15532 @end group
15533 @end smallexample
15534
15535 @table @code
15536
15537 @noindent
15538 The first thing to do is to recompile your application (for instance, in
15539 that case just by doing a @samp{gnatmake main}, so that GNAT generates
15540 the cross-referencing information.
15541 You can then issue any of the following commands:
15542
15543 @item gnatxref main.adb
15544 @code{gnatxref} generates cross-reference information for main.adb
15545 and every unit 'with'ed by main.adb.
15546
15547 The output would be:
15548 @smallexample
15549 @iftex
15550 @leftskip=0cm
15551 @end iftex
15552 B                                                      Type: Integer
15553   Decl: bar.ads           2:22
15554 B                                                      Type: Integer
15555   Decl: main.ads          3:20
15556   Body: main.adb          2:20
15557   Ref:  main.adb          4:13     5:13     6:19
15558 Bar                                                    Type: Unit
15559   Decl: bar.ads           1:9
15560   Ref:  main.adb          6:8      7:8
15561        main.ads           1:6
15562 C                                                      Type: Integer
15563   Decl: main.ads          4:5
15564   Modi: main.adb          4:8
15565   Ref:  main.adb          7:19
15566 D                                                      Type: Integer
15567   Decl: main.ads          6:5
15568   Modi: main.adb          5:8
15569 Foo                                                    Type: Unit
15570   Decl: main.ads          3:15
15571   Body: main.adb          2:15
15572 Main                                                    Type: Unit
15573   Decl: main.ads          2:9
15574   Body: main.adb          1:14
15575 Print                                                   Type: Unit
15576   Decl: bar.ads           2:15
15577   Ref:  main.adb          6:12     7:12
15578 @end smallexample
15579
15580 @noindent
15581 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
15582 its body is in main.adb, line 1, column 14 and is not referenced any where.
15583
15584 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
15585 it referenced in main.adb, line 6 column 12 and line 7 column 12.
15586
15587 @item gnatxref package1.adb package2.ads
15588 @code{gnatxref} will generates cross-reference information for
15589 package1.adb, package2.ads and any other package 'with'ed by any
15590 of these.
15591
15592 @end table
15593
15594 @ifclear vms
15595 @subsection Using gnatxref with vi
15596
15597 @code{gnatxref} can generate a tags file output, which can be used
15598 directly from @command{vi}. Note that the standard version of @command{vi}
15599 will not work properly with overloaded symbols. Consider using another
15600 free implementation of @command{vi}, such as @command{vim}.
15601
15602 @smallexample
15603 $ gnatxref -v gnatfind.adb > tags
15604 @end smallexample
15605
15606 @noindent
15607 will generate the tags file for @code{gnatfind} itself (if the sources
15608 are in the search path!).
15609
15610 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
15611 (replacing @var{entity} by whatever you are looking for), and vi will
15612 display a new file with the corresponding declaration of entity.
15613 @end ifclear
15614
15615 @node Examples of gnatfind Usage
15616 @section Examples of @code{gnatfind} Usage
15617
15618 @table @code
15619
15620 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
15621 Find declarations for all entities xyz referenced at least once in
15622 main.adb. The references are search in every library file in the search
15623 path.
15624
15625 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
15626 switch is set)
15627
15628 The output will look like:
15629 @smallexample
15630 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15631 ^directory/^[directory]^main.adb:24:10: xyz <= body
15632 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15633 @end smallexample
15634
15635 @noindent
15636 that is to say, one of the entities xyz found in main.adb is declared at
15637 line 12 of main.ads (and its body is in main.adb), and another one is
15638 declared at line 45 of foo.ads
15639
15640 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
15641 This is the same command as the previous one, instead @code{gnatfind} will
15642 display the content of the Ada source file lines.
15643
15644 The output will look like:
15645
15646 @smallexample
15647 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
15648    procedure xyz;
15649 ^directory/^[directory]^main.adb:24:10: xyz <= body
15650    procedure xyz is
15651 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
15652    xyz : Integer;
15653 @end smallexample
15654
15655 @noindent
15656 This can make it easier to find exactly the location your are looking
15657 for.
15658
15659 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
15660 Find references to all entities containing an x that are
15661 referenced on line 123 of main.ads.
15662 The references will be searched only in main.ads and foo.adb.
15663
15664 @item gnatfind main.ads:123
15665 Find declarations and bodies for all entities that are referenced on
15666 line 123 of main.ads.
15667
15668 This is the same as @code{gnatfind "*":main.adb:123}.
15669
15670 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
15671 Find the declaration for the entity referenced at column 45 in
15672 line 123 of file main.adb in directory mydir. Note that it
15673 is usual to omit the identifier name when the column is given,
15674 since the column position identifies a unique reference.
15675
15676 The column has to be the beginning of the identifier, and should not
15677 point to any character in the middle of the identifier.
15678
15679 @end table
15680
15681 @c *********************************
15682 @node The GNAT Pretty-Printer gnatpp
15683 @chapter The GNAT Pretty-Printer @command{gnatpp}
15684 @findex gnatpp
15685 @cindex Pretty-Printer
15686
15687 @noindent
15688 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
15689 for source reformatting / pretty-printing.
15690 It takes an Ada source file as input and generates a reformatted
15691 version as output.
15692 You can specify various style directives via switches; e.g.,
15693 identifier case conventions, rules of indentation, and comment layout.
15694
15695 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
15696 tree for the input source and thus requires the input to be syntactically and
15697 semantically legal.
15698 If this condition is not met, @command{gnatpp} will terminate with an
15699 error message; no output file will be generated.
15700
15701 If the source files presented to @command{gnatpp} contain
15702 preprocessing directives, then the output file will
15703 correspond to the generated source after all
15704 preprocessing is carried out. There is no way
15705 using @command{gnatpp} to obtain pretty printed files that
15706 include the preprocessing directives.
15707
15708 If the compilation unit
15709 contained in the input source depends semantically upon units located
15710 outside the current directory, you have to provide the source search path
15711 when invoking @command{gnatpp}, if these units are contained in files with
15712 names that do not follow the GNAT file naming rules, you have to provide
15713 the configuration file describing the corresponding naming scheme;
15714 see the description of the @command{gnatpp}
15715 switches below. Another possibility is to use a project file and to
15716 call @command{gnatpp} through the @command{gnat} driver
15717
15718 The @command{gnatpp} command has the form
15719
15720 @smallexample
15721 $ gnatpp @ovar{switches} @var{filename}
15722 @end smallexample
15723
15724 @noindent
15725 where
15726 @itemize @bullet
15727 @item
15728 @var{switches} is an optional sequence of switches defining such properties as
15729 the formatting rules, the source search path, and the destination for the
15730 output source file
15731
15732 @item
15733 @var{filename} is the name (including the extension) of the source file to
15734 reformat; ``wildcards'' or several file names on the same gnatpp command are
15735 allowed.  The file name may contain path information; it does not have to
15736 follow the GNAT file naming rules
15737 @end itemize
15738
15739 @menu
15740 * Switches for gnatpp::
15741 * Formatting Rules::
15742 @end menu
15743
15744 @node Switches for gnatpp
15745 @section Switches for @command{gnatpp}
15746
15747 @noindent
15748 The following subsections describe the various switches accepted by
15749 @command{gnatpp}, organized by category.
15750
15751 @ifclear vms
15752 You specify a switch by supplying a name and generally also a value.
15753 In many cases the values for a switch with a given name are incompatible with
15754 each other
15755 (for example the switch that controls the casing of a reserved word may have
15756 exactly one value: upper case, lower case, or
15757 mixed case) and thus exactly one such switch can be in effect for an
15758 invocation of @command{gnatpp}.
15759 If more than one is supplied, the last one is used.
15760 However, some values for the same switch are mutually compatible.
15761 You may supply several such switches to @command{gnatpp}, but then
15762 each must be specified in full, with both the name and the value.
15763 Abbreviated forms (the name appearing once, followed by each value) are
15764 not permitted.
15765 For example, to set
15766 the alignment of the assignment delimiter both in declarations and in
15767 assignment statements, you must write @option{-A2A3}
15768 (or @option{-A2 -A3}), but not @option{-A23}.
15769 @end ifclear
15770
15771 @ifset vms
15772 In many cases the set of options for a given qualifier are incompatible with
15773 each other (for example the qualifier that controls the casing of a reserved
15774 word may have exactly one option, which specifies either upper case, lower
15775 case, or mixed case), and thus exactly one such option can be in effect for
15776 an invocation of @command{gnatpp}.
15777 If more than one is supplied, the last one is used.
15778 However, some qualifiers have options that are mutually compatible,
15779 and then you may then supply several such options when invoking
15780 @command{gnatpp}.
15781 @end ifset
15782
15783 In most cases, it is obvious whether or not the
15784 ^values for a switch with a given name^options for a given qualifier^
15785 are compatible with each other.
15786 When the semantics might not be evident, the summaries below explicitly
15787 indicate the effect.
15788
15789 @menu
15790 * Alignment Control::
15791 * Casing Control::
15792 * Construct Layout Control::
15793 * General Text Layout Control::
15794 * Other Formatting Options::
15795 * Setting the Source Search Path::
15796 * Output File Control::
15797 * Other gnatpp Switches::
15798 @end menu
15799
15800 @node Alignment Control
15801 @subsection Alignment Control
15802 @cindex Alignment control in @command{gnatpp}
15803
15804 @noindent
15805 Programs can be easier to read if certain constructs are vertically aligned.
15806 By default all alignments are set ON.
15807 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
15808 OFF, and then use one or more of the other
15809 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
15810 to activate alignment for specific constructs.
15811
15812 @table @option
15813 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
15814
15815 @ifset vms
15816 @item /ALIGN=ON
15817 Set all alignments to ON
15818 @end ifset
15819
15820 @item ^-A0^/ALIGN=OFF^
15821 Set all alignments to OFF
15822
15823 @item ^-A1^/ALIGN=COLONS^
15824 Align @code{:} in declarations
15825
15826 @item ^-A2^/ALIGN=DECLARATIONS^
15827 Align @code{:=} in initializations in declarations
15828
15829 @item ^-A3^/ALIGN=STATEMENTS^
15830 Align @code{:=} in assignment statements
15831
15832 @item ^-A4^/ALIGN=ARROWS^
15833 Align @code{=>} in associations
15834
15835 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
15836 Align @code{at} keywords in the component clauses in record
15837 representation clauses
15838 @end table
15839
15840 @noindent
15841 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
15842 is allowed.
15843
15844 @node Casing Control
15845 @subsection Casing Control
15846 @cindex Casing control in @command{gnatpp}
15847
15848 @noindent
15849 @command{gnatpp} allows you to specify the casing for reserved words,
15850 pragma names, attribute designators and identifiers.
15851 For identifiers you may define a
15852 general rule for name casing but also override this rule
15853 via a set of dictionary files.
15854
15855 Three types of casing are supported: lower case, upper case, and mixed case.
15856 Lower and upper case are self-explanatory (but since some letters in
15857 Latin1 and other GNAT-supported character sets
15858 exist only in lower-case form, an upper case conversion will have no
15859 effect on them.)
15860 ``Mixed case'' means that the first letter, and also each letter immediately
15861 following an underscore, are converted to their uppercase forms;
15862 all the other letters are converted to their lowercase forms.
15863
15864 @table @option
15865 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
15866 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
15867 Attribute designators are lower case
15868
15869 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
15870 Attribute designators are upper case
15871
15872 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
15873 Attribute designators are mixed case (this is the default)
15874
15875 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
15876 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
15877 Keywords (technically, these are known in Ada as @emph{reserved words}) are
15878 lower case (this is the default)
15879
15880 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
15881 Keywords are upper case
15882
15883 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
15884 @item ^-nD^/NAME_CASING=AS_DECLARED^
15885 Name casing for defining occurrences are as they appear in the source file
15886 (this is the default)
15887
15888 @item ^-nU^/NAME_CASING=UPPER_CASE^
15889 Names are in upper case
15890
15891 @item ^-nL^/NAME_CASING=LOWER_CASE^
15892 Names are in lower case
15893
15894 @item ^-nM^/NAME_CASING=MIXED_CASE^
15895 Names are in mixed case
15896
15897 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
15898 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
15899 Pragma names are lower case
15900
15901 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
15902 Pragma names are upper case
15903
15904 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
15905 Pragma names are mixed case (this is the default)
15906
15907 @item ^-D@var{file}^/DICTIONARY=@var{file}^
15908 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
15909 Use @var{file} as a @emph{dictionary file} that defines
15910 the casing for a set of specified names,
15911 thereby overriding the effect on these names by
15912 any explicit or implicit
15913 ^-n^/NAME_CASING^ switch.
15914 To supply more than one dictionary file,
15915 use ^several @option{-D} switches^a list of files as options^.
15916
15917 @noindent
15918 @option{gnatpp} implicitly uses a @emph{default dictionary file}
15919 to define the casing for the Ada predefined names and
15920 the names declared in the GNAT libraries.
15921
15922 @item ^-D-^/SPECIFIC_CASING^
15923 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
15924 Do not use the default dictionary file;
15925 instead, use the casing
15926 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
15927 dictionary file(s)
15928 @end table
15929
15930 @noindent
15931 The structure of a dictionary file, and details on the conventions
15932 used in the default dictionary file, are defined in @ref{Name Casing}.
15933
15934 The @option{^-D-^/SPECIFIC_CASING^} and
15935 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
15936 compatible.
15937
15938 @node Construct Layout Control
15939 @subsection Construct Layout Control
15940 @cindex Layout control in @command{gnatpp}
15941
15942 @noindent
15943 This group of @command{gnatpp} switches controls the layout of comments and
15944 complex syntactic constructs.  See @ref{Formatting Comments} for details
15945 on their effect.
15946
15947 @table @option
15948 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
15949 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
15950 All the comments remain unchanged
15951
15952 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
15953 GNAT-style comment line indentation (this is the default).
15954
15955 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
15956 Reference-manual comment line indentation.
15957
15958 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
15959 GNAT-style comment beginning
15960
15961 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
15962 Reformat comment blocks
15963
15964 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
15965 Keep unchanged special form comments
15966
15967 Reformat comment blocks
15968
15969 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
15970 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
15971 GNAT-style layout (this is the default)
15972
15973 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
15974 Compact layout
15975
15976 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
15977 Uncompact layout
15978
15979 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
15980 @item ^-N^/NOTABS^
15981 All the VT characters are removed from the comment text. All the HT characters
15982 are expanded with the sequences of space characters to get to the next tab
15983 stops.
15984
15985 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
15986 @item ^--no-separate-is^/NO_SEPARATE_IS^
15987 Do not place the keyword @code{is} on a separate line in a subprogram body in
15988 case if the spec occupies more then one line.
15989
15990 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
15991 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
15992 Place the keyword @code{loop} in FOR and WHILE loop statements and the
15993 keyword @code{then} in IF statements on a separate line.
15994
15995 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
15996 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
15997 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
15998 keyword @code{then} in IF statements on a separate line. This option is
15999 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
16000
16001 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
16002 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
16003 Start each USE clause in a context clause from a separate line.
16004
16005 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
16006 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
16007 Use a separate line for a loop or block statement name, but do not use an extra
16008 indentation level for the statement itself.
16009
16010 @end table
16011
16012 @ifclear vms
16013 @noindent
16014 The @option{-c1} and @option{-c2} switches are incompatible.
16015 The @option{-c3} and @option{-c4} switches are compatible with each other and
16016 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
16017 the other comment formatting switches.
16018
16019 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
16020 @end ifclear
16021
16022 @ifset vms
16023 @noindent
16024 For the @option{/COMMENTS_LAYOUT} qualifier:
16025 @itemize @bullet
16026 @item
16027 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
16028 @item
16029 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
16030 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
16031 @end itemize
16032
16033 @noindent
16034 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
16035 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
16036 @end ifset
16037
16038 @node General Text Layout Control
16039 @subsection General Text Layout Control
16040
16041 @noindent
16042 These switches allow control over line length and indentation.
16043
16044 @table @option
16045 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
16046 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
16047 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
16048
16049 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
16050 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
16051 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
16052
16053 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
16054 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
16055 Indentation level for continuation lines (relative to the line being
16056 continued), @var{nnn} from 1@dots{}9.
16057 The default
16058 value is one less then the (normal) indentation level, unless the
16059 indentation is set to 1 (in which case the default value for continuation
16060 line indentation is also 1)
16061 @end table
16062
16063 @node Other Formatting Options
16064 @subsection Other Formatting Options
16065
16066 @noindent
16067 These switches control the inclusion of missing end/exit labels, and
16068 the indentation level in @b{case} statements.
16069
16070 @table @option
16071 @item ^-e^/NO_MISSED_LABELS^
16072 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
16073 Do not insert missing end/exit labels. An end label is the name of
16074 a construct that may optionally be repeated at the end of the
16075 construct's declaration;
16076 e.g., the names of packages, subprograms, and tasks.
16077 An exit label is the name of a loop that may appear as target
16078 of an exit statement within the loop.
16079 By default, @command{gnatpp} inserts these end/exit labels when
16080 they are absent from the original source. This option suppresses such
16081 insertion, so that the formatted source reflects the original.
16082
16083 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
16084 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
16085 Insert a Form Feed character after a pragma Page.
16086
16087 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
16088 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
16089 Do not use an additional indentation level for @b{case} alternatives
16090 and variants if there are @var{nnn} or more (the default
16091 value is 10).
16092 If @var{nnn} is 0, an additional indentation level is
16093 used for @b{case} alternatives and variants regardless of their number.
16094 @end table
16095
16096 @node Setting the Source Search Path
16097 @subsection Setting the Source Search Path
16098
16099 @noindent
16100 To define the search path for the input source file, @command{gnatpp}
16101 uses the same switches as the GNAT compiler, with the same effects.
16102
16103 @table @option
16104 @item ^-I^/SEARCH=^@var{dir}
16105 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
16106 The same as the corresponding gcc switch
16107
16108 @item ^-I-^/NOCURRENT_DIRECTORY^
16109 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
16110 The same as the corresponding gcc switch
16111
16112 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
16113 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
16114 The same as the corresponding gcc switch
16115
16116 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
16117 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
16118 The same as the corresponding gcc switch
16119
16120 @end table
16121
16122 @node Output File Control
16123 @subsection Output File Control
16124
16125 @noindent
16126 By default the output is sent to the file whose name is obtained by appending
16127 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
16128 (if the file with this name already exists, it is unconditionally overwritten).
16129 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
16130 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
16131 as output file.
16132 The output may be redirected by the following switches:
16133
16134 @table @option
16135 @item ^-pipe^/STANDARD_OUTPUT^
16136 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
16137 Send the output to @code{Standard_Output}
16138
16139 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
16140 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
16141 Write the output into @var{output_file}.
16142 If @var{output_file} already exists, @command{gnatpp} terminates without
16143 reading or processing the input file.
16144
16145 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
16146 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
16147 Write the output into @var{output_file}, overwriting the existing file
16148 (if one is present).
16149
16150 @item ^-r^/REPLACE^
16151 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
16152 Replace the input source file with the reformatted output, and copy the
16153 original input source into the file whose name is obtained by appending the
16154 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
16155 If a file with this name already exists, @command{gnatpp} terminates without
16156 reading or processing the input file.
16157
16158 @item ^-rf^/OVERRIDING_REPLACE^
16159 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
16160 Like @option{^-r^/REPLACE^} except that if the file with the specified name
16161 already exists, it is overwritten.
16162
16163 @item ^-rnb^/REPLACE_NO_BACKUP^
16164 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
16165 Replace the input source file with the reformatted output without
16166 creating any backup copy of the input source.
16167
16168 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
16169 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
16170 Specifies the format of the reformatted output file. The @var{xxx}
16171 ^string specified with the switch^option^ may be either
16172 @itemize @bullet
16173 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
16174 @item ``@option{^crlf^CRLF^}''
16175 the same as @option{^crlf^CRLF^}
16176 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
16177 @item ``@option{^lf^LF^}''
16178 the same as @option{^unix^UNIX^}
16179 @end itemize
16180
16181 @item ^-W^/RESULT_ENCODING=^@var{e}
16182 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
16183 Specify the wide character encoding method used to write the code in the
16184 result file
16185 @var{e} is one of the following:
16186
16187 @itemize @bullet
16188
16189 @item ^h^HEX^
16190 Hex encoding
16191
16192 @item ^u^UPPER^
16193 Upper half encoding
16194
16195 @item ^s^SHIFT_JIS^
16196 Shift/JIS encoding
16197
16198 @item ^e^EUC^
16199 EUC encoding
16200
16201 @item ^8^UTF8^
16202 UTF-8 encoding
16203
16204 @item ^b^BRACKETS^
16205 Brackets encoding (default value)
16206 @end itemize
16207
16208 @end table
16209
16210 @noindent
16211 Options @option{^-pipe^/STANDARD_OUTPUT^},
16212 @option{^-o^/OUTPUT^} and
16213 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
16214 contains only one file to reformat.
16215 Option
16216 @option{^--eol^/END_OF_LINE^}
16217 and
16218 @option{^-W^/RESULT_ENCODING^}
16219 cannot be used together
16220 with @option{^-pipe^/STANDARD_OUTPUT^} option.
16221
16222 @node Other gnatpp Switches
16223 @subsection Other @code{gnatpp} Switches
16224
16225 @noindent
16226 The additional @command{gnatpp} switches are defined in this subsection.
16227
16228 @table @option
16229 @item ^-files @var{filename}^/FILES=@var{output_file}^
16230 @cindex @option{^-files^/FILES^} (@code{gnatpp})
16231 Take the argument source files from the specified file. This file should be an
16232 ordinary textual file containing file names separated by spaces or
16233 line breaks. You can use this switch more then once in the same call to
16234 @command{gnatpp}. You also can combine this switch with explicit list of
16235 files.
16236
16237 @item ^-v^/VERBOSE^
16238 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
16239 Verbose mode;
16240 @command{gnatpp} generates version information and then
16241 a trace of the actions it takes to produce or obtain the ASIS tree.
16242
16243 @item ^-w^/WARNINGS^
16244 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
16245 Warning mode;
16246 @command{gnatpp} generates a warning whenever it cannot provide
16247 a required layout in the result source.
16248 @end table
16249
16250 @node Formatting Rules
16251 @section Formatting Rules
16252
16253 @noindent
16254 The following subsections show how @command{gnatpp} treats ``white space'',
16255 comments, program layout, and name casing.
16256 They provide the detailed descriptions of the switches shown above.
16257
16258 @menu
16259 * White Space and Empty Lines::
16260 * Formatting Comments::
16261 * Construct Layout::
16262 * Name Casing::
16263 @end menu
16264
16265 @node White Space and Empty Lines
16266 @subsection White Space and Empty Lines
16267
16268 @noindent
16269 @command{gnatpp} does not have an option to control space characters.
16270 It will add or remove spaces according to the style illustrated by the
16271 examples in the @cite{Ada Reference Manual}.
16272
16273 The only format effectors
16274 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
16275 that will appear in the output file are platform-specific line breaks,
16276 and also format effectors within (but not at the end of) comments.
16277 In particular, each horizontal tab character that is not inside
16278 a comment will be treated as a space and thus will appear in the
16279 output file as zero or more spaces depending on
16280 the reformatting of the line in which it appears.
16281 The only exception is a Form Feed character, which is inserted after a
16282 pragma @code{Page} when @option{-ff} is set.
16283
16284 The output file will contain no lines with trailing ``white space'' (spaces,
16285 format effectors).
16286
16287 Empty lines in the original source are preserved
16288 only if they separate declarations or statements.
16289 In such contexts, a
16290 sequence of two or more empty lines is replaced by exactly one empty line.
16291 Note that a blank line will be removed if it separates two ``comment blocks''
16292 (a comment block is a sequence of whole-line comments).
16293 In order to preserve a visual separation between comment blocks, use an
16294 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
16295 Likewise, if for some reason you wish to have a sequence of empty lines,
16296 use a sequence of empty comments instead.
16297
16298 @node Formatting Comments
16299 @subsection Formatting Comments
16300
16301 @noindent
16302 Comments in Ada code are of two kinds:
16303 @itemize @bullet
16304 @item
16305 a @emph{whole-line comment}, which appears by itself (possibly preceded by
16306 ``white space'') on a line
16307
16308 @item
16309 an @emph{end-of-line comment}, which follows some other Ada lexical element
16310 on the same line.
16311 @end itemize
16312
16313 @noindent
16314 The indentation of a whole-line comment is that of either
16315 the preceding or following line in
16316 the formatted source, depending on switch settings as will be described below.
16317
16318 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
16319 between the end of the preceding Ada lexical element and the beginning
16320 of the comment as appear in the original source,
16321 unless either the comment has to be split to
16322 satisfy the line length limitation, or else the next line contains a
16323 whole line comment that is considered a continuation of this end-of-line
16324 comment (because it starts at the same position).
16325 In the latter two
16326 cases, the start of the end-of-line comment is moved right to the nearest
16327 multiple of the indentation level.
16328 This may result in a ``line overflow'' (the right-shifted comment extending
16329 beyond the maximum line length), in which case the comment is split as
16330 described below.
16331
16332 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
16333 (GNAT-style comment line indentation)
16334 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
16335 (reference-manual comment line indentation).
16336 With reference-manual style, a whole-line comment is indented as if it
16337 were a declaration or statement at the same place
16338 (i.e., according to the indentation of the preceding line(s)).
16339 With GNAT style, a whole-line comment that is immediately followed by an
16340 @b{if} or @b{case} statement alternative, a record variant, or the reserved
16341 word @b{begin}, is indented based on the construct that follows it.
16342
16343 For example:
16344 @smallexample @c ada
16345 @cartouche
16346 if A then
16347     null;
16348        -- some comment
16349 else
16350    null;
16351 end if;
16352 @end cartouche
16353 @end smallexample
16354
16355 @noindent
16356 Reference-manual indentation produces:
16357
16358 @smallexample @c ada
16359 @cartouche
16360 if A then
16361    null;
16362    --  some comment
16363 else
16364    null;
16365 end if;
16366 @end cartouche
16367 @end smallexample
16368
16369 @noindent
16370 while GNAT-style indentation produces:
16371
16372 @smallexample @c ada
16373 @cartouche
16374 if A then
16375    null;
16376 --  some comment
16377 else
16378    null;
16379 end if;
16380 @end cartouche
16381 @end smallexample
16382
16383 @noindent
16384 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
16385 (GNAT style comment beginning) has the following
16386 effect:
16387
16388 @itemize @bullet
16389 @item
16390 For each whole-line comment that does not end with two hyphens,
16391 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
16392 to ensure that there are at least two spaces between these hyphens and the
16393 first non-blank character of the comment.
16394 @end itemize
16395
16396 @noindent
16397 For an end-of-line comment, if in the original source the next line is a
16398 whole-line comment that starts at the same position
16399 as the end-of-line comment,
16400 then the whole-line comment (and all whole-line comments
16401 that follow it and that start at the same position)
16402 will start at this position in the output file.
16403
16404 @noindent
16405 That is, if in the original source we have:
16406
16407 @smallexample @c ada
16408 @cartouche
16409 begin
16410 A := B + C;            --  B must be in the range Low1..High1
16411                        --  C must be in the range Low2..High2
16412              --B+C will be in the range Low1+Low2..High1+High2
16413 X := X + 1;
16414 @end cartouche
16415 @end smallexample
16416
16417 @noindent
16418 Then in the formatted source we get
16419
16420 @smallexample @c ada
16421 @cartouche
16422 begin
16423    A := B + C;            --  B must be in the range Low1..High1
16424                           --  C must be in the range Low2..High2
16425    --  B+C will be in the range Low1+Low2..High1+High2
16426    X := X + 1;
16427 @end cartouche
16428 @end smallexample
16429
16430 @noindent
16431 A comment that exceeds the line length limit will be split.
16432 Unless switch
16433 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
16434 the line belongs to a reformattable block, splitting the line generates a
16435 @command{gnatpp} warning.
16436 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
16437 comments may be reformatted in typical
16438 word processor style (that is, moving words between lines and putting as
16439 many words in a line as possible).
16440
16441 @noindent
16442 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
16443 that has a special format (that is, a character that is neither a letter nor digit
16444 not white space nor line break immediately following the leading @code{--} of
16445 the comment) should be without any change moved from the argument source
16446 into reformatted source. This switch allows to preserve comments that are used
16447 as a special marks in the code (e.g.@: SPARK annotation).
16448
16449 @node Construct Layout
16450 @subsection Construct Layout
16451
16452 @noindent
16453 In several cases the suggested layout in the Ada Reference Manual includes
16454 an extra level of indentation that many programmers prefer to avoid. The
16455 affected cases include:
16456
16457 @itemize @bullet
16458
16459 @item Record type declaration (RM 3.8)
16460
16461 @item Record representation clause (RM 13.5.1)
16462
16463 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
16464
16465 @item Block statement in case if a block has a statement identifier (RM 5.6)
16466 @end itemize
16467
16468 @noindent
16469 In compact mode (when GNAT style layout or compact layout is set),
16470 the pretty printer uses one level of indentation instead
16471 of two. This is achieved in the record definition and record representation
16472 clause cases by putting the @code{record} keyword on the same line as the
16473 start of the declaration or representation clause, and in the block and loop
16474 case by putting the block or loop header on the same line as the statement
16475 identifier.
16476
16477 @noindent
16478 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
16479 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
16480 layout on the one hand, and uncompact layout
16481 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
16482 can be illustrated by the following examples:
16483
16484 @iftex
16485 @cartouche
16486 @multitable @columnfractions .5 .5
16487 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
16488
16489 @item
16490 @smallexample @c ada
16491 type q is record
16492    a : integer;
16493    b : integer;
16494 end record;
16495 @end smallexample
16496 @tab
16497 @smallexample @c ada
16498 type q is
16499    record
16500       a : integer;
16501       b : integer;
16502    end record;
16503 @end smallexample
16504
16505 @item
16506 @smallexample @c ada
16507 for q use record
16508    a at 0 range  0 .. 31;
16509    b at 4 range  0 .. 31;
16510 end record;
16511 @end smallexample
16512 @tab
16513 @smallexample @c ada
16514 for q use
16515    record
16516       a at 0 range  0 .. 31;
16517       b at 4 range  0 .. 31;
16518    end record;
16519 @end smallexample
16520
16521 @item
16522 @smallexample @c ada
16523 Block : declare
16524    A : Integer := 3;
16525 begin
16526    Proc (A, A);
16527 end Block;
16528 @end smallexample
16529 @tab
16530 @smallexample @c ada
16531 Block :
16532    declare
16533       A : Integer := 3;
16534    begin
16535       Proc (A, A);
16536    end Block;
16537 @end smallexample
16538
16539 @item
16540 @smallexample @c ada
16541 Clear : for J in 1 .. 10 loop
16542    A (J) := 0;
16543 end loop Clear;
16544 @end smallexample
16545 @tab
16546 @smallexample @c ada
16547 Clear :
16548    for J in 1 .. 10 loop
16549       A (J) := 0;
16550    end loop Clear;
16551 @end smallexample
16552 @end multitable
16553 @end cartouche
16554 @end iftex
16555
16556 @ifnottex
16557 @smallexample
16558 @cartouche
16559 GNAT style, compact layout              Uncompact layout
16560
16561 type q is record                        type q is
16562    a : integer;                            record
16563    b : integer;                               a : integer;
16564 end record;                                   b : integer;
16565                                            end record;
16566
16567 for q use record                        for q use
16568    a at 0 range  0 .. 31;                  record
16569    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
16570 end record;                                   b at 4 range  0 .. 31;
16571                                            end record;
16572
16573 Block : declare                         Block :
16574    A : Integer := 3;                       declare
16575 begin                                         A : Integer := 3;
16576    Proc (A, A);                            begin
16577 end Block;                                    Proc (A, A);
16578                                            end Block;
16579
16580 Clear : for J in 1 .. 10 loop           Clear :
16581    A (J) := 0;                             for J in 1 .. 10 loop
16582 end loop Clear;                               A (J) := 0;
16583                                            end loop Clear;
16584 @end cartouche
16585 @end smallexample
16586 @end ifnottex
16587
16588 @noindent
16589 A further difference between GNAT style layout and compact layout is that
16590 GNAT style layout inserts empty lines as separation for
16591 compound statements, return statements and bodies.
16592
16593 Note that the layout specified by
16594 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
16595 for named block and loop statements overrides the layout defined by these
16596 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
16597 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
16598 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
16599
16600 @node Name Casing
16601 @subsection Name Casing
16602
16603 @noindent
16604 @command{gnatpp} always converts the usage occurrence of a (simple) name to
16605 the same casing as the corresponding defining identifier.
16606
16607 You control the casing for defining occurrences via the
16608 @option{^-n^/NAME_CASING^} switch.
16609 @ifclear vms
16610 With @option{-nD} (``as declared'', which is the default),
16611 @end ifclear
16612 @ifset vms
16613 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
16614 @end ifset
16615 defining occurrences appear exactly as in the source file
16616 where they are declared.
16617 The other ^values for this switch^options for this qualifier^ ---
16618 @option{^-nU^UPPER_CASE^},
16619 @option{^-nL^LOWER_CASE^},
16620 @option{^-nM^MIXED_CASE^} ---
16621 result in
16622 ^upper, lower, or mixed case, respectively^the corresponding casing^.
16623 If @command{gnatpp} changes the casing of a defining
16624 occurrence, it analogously changes the casing of all the
16625 usage occurrences of this name.
16626
16627 If the defining occurrence of a name is not in the source compilation unit
16628 currently being processed by @command{gnatpp}, the casing of each reference to
16629 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
16630 switch (subject to the dictionary file mechanism described below).
16631 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
16632 had affected the
16633 casing for the defining occurrence of the name.
16634
16635 Some names may need to be spelled with casing conventions that are not
16636 covered by the upper-, lower-, and mixed-case transformations.
16637 You can arrange correct casing by placing such names in a
16638 @emph{dictionary file},
16639 and then supplying a @option{^-D^/DICTIONARY^} switch.
16640 The casing of names from dictionary files overrides
16641 any @option{^-n^/NAME_CASING^} switch.
16642
16643 To handle the casing of Ada predefined names and the names from GNAT libraries,
16644 @command{gnatpp} assumes a default dictionary file.
16645 The name of each predefined entity is spelled with the same casing as is used
16646 for the entity in the @cite{Ada Reference Manual}.
16647 The name of each entity in the GNAT libraries is spelled with the same casing
16648 as is used in the declaration of that entity.
16649
16650 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
16651 default dictionary file.
16652 Instead, the casing for predefined and GNAT-defined names will be established
16653 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
16654 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
16655 will appear as just shown,
16656 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
16657 To ensure that even such names are rendered in uppercase,
16658 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
16659 (or else, less conveniently, place these names in upper case in a dictionary
16660 file).
16661
16662 A dictionary file is
16663 a plain text file; each line in this file can be either a blank line
16664 (containing only space characters and ASCII.HT characters), an Ada comment
16665 line, or the specification of exactly one @emph{casing schema}.
16666
16667 A casing schema is a string that has the following syntax:
16668
16669 @smallexample
16670 @cartouche
16671   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
16672
16673   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
16674 @end cartouche
16675 @end smallexample
16676
16677 @noindent
16678 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
16679 @var{identifier} lexical element and the @var{letter_or_digit} category.)
16680
16681 The casing schema string can be followed by white space and/or an Ada-style
16682 comment; any amount of white space is allowed before the string.
16683
16684 If a dictionary file is passed as
16685 @ifclear vms
16686 the value of a @option{-D@var{file}} switch
16687 @end ifclear
16688 @ifset vms
16689 an option to the @option{/DICTIONARY} qualifier
16690 @end ifset
16691 then for every
16692 simple name and every identifier, @command{gnatpp} checks if the dictionary
16693 defines the casing for the name or for some of its parts (the term ``subword''
16694 is used below to denote the part of a name which is delimited by ``_'' or by
16695 the beginning or end of the word and which does not contain any ``_'' inside):
16696
16697 @itemize @bullet
16698 @item
16699 if the whole name is in the dictionary, @command{gnatpp} uses for this name
16700 the casing defined by the dictionary; no subwords are checked for this word
16701
16702 @item
16703 for every subword @command{gnatpp} checks if the dictionary contains the
16704 corresponding string of the form @code{*@var{simple_identifier}*},
16705 and if it does, the casing of this @var{simple_identifier} is used
16706 for this subword
16707
16708 @item
16709 if the whole name does not contain any ``_'' inside, and if for this name
16710 the dictionary contains two entries - one of the form @var{identifier},
16711 and another - of the form *@var{simple_identifier}*, then the first one
16712 is applied to define the casing of this name
16713
16714 @item
16715 if more than one dictionary file is passed as @command{gnatpp} switches, each
16716 dictionary adds new casing exceptions and overrides all the existing casing
16717 exceptions set by the previous dictionaries
16718
16719 @item
16720 when @command{gnatpp} checks if the word or subword is in the dictionary,
16721 this check is not case sensitive
16722 @end itemize
16723
16724 @noindent
16725 For example, suppose we have the following source to reformat:
16726
16727 @smallexample @c ada
16728 @cartouche
16729 procedure test is
16730    name1 : integer := 1;
16731    name4_name3_name2 : integer := 2;
16732    name2_name3_name4 : Boolean;
16733    name1_var : Float;
16734 begin
16735    name2_name3_name4 := name4_name3_name2 > name1;
16736 end;
16737 @end cartouche
16738 @end smallexample
16739
16740 @noindent
16741 And suppose we have two dictionaries:
16742
16743 @smallexample
16744 @cartouche
16745 @i{dict1:}
16746    NAME1
16747    *NaMe3*
16748    *Name1*
16749 @end cartouche
16750
16751 @cartouche
16752 @i{dict2:}
16753   *NAME3*
16754 @end cartouche
16755 @end smallexample
16756
16757 @noindent
16758 If @command{gnatpp} is called with the following switches:
16759
16760 @smallexample
16761 @ifclear vms
16762 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
16763 @end ifclear
16764 @ifset vms
16765 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
16766 @end ifset
16767 @end smallexample
16768
16769 @noindent
16770 then we will get the following name casing in the @command{gnatpp} output:
16771
16772 @smallexample @c ada
16773 @cartouche
16774 procedure Test is
16775    NAME1             : Integer := 1;
16776    Name4_NAME3_Name2 : Integer := 2;
16777    Name2_NAME3_Name4 : Boolean;
16778    Name1_Var         : Float;
16779 begin
16780    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
16781 end Test;
16782 @end cartouche
16783 @end smallexample
16784
16785 @c *********************************
16786 @node The GNAT Metric Tool gnatmetric
16787 @chapter The GNAT Metric Tool @command{gnatmetric}
16788 @findex gnatmetric
16789 @cindex Metric tool
16790
16791 @noindent
16792 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
16793 for computing various program metrics.
16794 It takes an Ada source file as input and generates a file containing the
16795 metrics data as output. Various switches control which
16796 metrics are computed and output.
16797
16798 @command{gnatmetric} generates and uses the ASIS
16799 tree for the input source and thus requires the input to be syntactically and
16800 semantically legal.
16801 If this condition is not met, @command{gnatmetric} will generate
16802 an error message; no metric information for this file will be
16803 computed and reported.
16804
16805 If the compilation unit contained in the input source depends semantically
16806 upon units in files located outside the current directory, you have to provide
16807 the source search path when invoking @command{gnatmetric}.
16808 If it depends semantically upon units that are contained
16809 in files with names that do not follow the GNAT file naming rules, you have to
16810 provide the configuration file describing the corresponding naming scheme (see
16811 the description of the @command{gnatmetric} switches below.)
16812 Alternatively, you may use a project file and invoke @command{gnatmetric}
16813 through the @command{gnat} driver.
16814
16815 The @command{gnatmetric} command has the form
16816
16817 @smallexample
16818 $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
16819 @end smallexample
16820
16821 @noindent
16822 where
16823 @itemize @bullet
16824 @item
16825 @var{switches} specify the metrics to compute and define the destination for
16826 the output
16827
16828 @item
16829 Each @var{filename} is the name (including the extension) of a source
16830 file to process. ``Wildcards'' are allowed, and
16831 the file name may contain path information.
16832 If no @var{filename} is supplied, then the @var{switches} list must contain
16833 at least one
16834 @option{-files} switch (@pxref{Other gnatmetric Switches}).
16835 Including both a @option{-files} switch and one or more
16836 @var{filename} arguments is permitted.
16837
16838 @item
16839 @samp{-cargs @var{gcc_switches}} is a list of switches for
16840 @command{gcc}. They will be passed on to all compiler invocations made by
16841 @command{gnatmetric} to generate the ASIS trees. Here you can provide
16842 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
16843 and use the @option{-gnatec} switch to set the configuration file.
16844 @end itemize
16845
16846 @menu
16847 * Switches for gnatmetric::
16848 @end menu
16849
16850 @node Switches for gnatmetric
16851 @section Switches for @command{gnatmetric}
16852
16853 @noindent
16854 The following subsections describe the various switches accepted by
16855 @command{gnatmetric}, organized by category.
16856
16857 @menu
16858 * Output Files Control::
16859 * Disable Metrics For Local Units::
16860 * Specifying a set of metrics to compute::
16861 * Other gnatmetric Switches::
16862 * Generate project-wide metrics::
16863 @end menu
16864
16865 @node Output Files Control
16866 @subsection Output File Control
16867 @cindex Output file control in @command{gnatmetric}
16868
16869 @noindent
16870 @command{gnatmetric} has two output formats. It can generate a
16871 textual (human-readable) form, and also XML. By default only textual
16872 output is generated.
16873
16874 When generating the output in textual form, @command{gnatmetric} creates
16875 for each Ada source file a corresponding text file
16876 containing the computed metrics, except for the case when the set of metrics
16877 specified by gnatmetric parameters consists only of metrics that are computed
16878 for the whole set of analyzed sources, but not for each Ada source.
16879 By default, this file is placed in the same directory as where the source
16880 file is located, and its name is obtained
16881 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
16882 input file.
16883
16884 All the output information generated in XML format is placed in a single
16885 file. By default this file is placed in the current directory and has the
16886 name ^@file{metrix.xml}^@file{METRIX$XML}^.
16887
16888 Some of the computed metrics are summed over the units passed to
16889 @command{gnatmetric}; for example, the total number of lines of code.
16890 By default this information is sent to @file{stdout}, but a file
16891 can be specified with the @option{-og} switch.
16892
16893 The following switches control the @command{gnatmetric} output:
16894
16895 @table @option
16896 @cindex @option{^-x^/XML^} (@command{gnatmetric})
16897 @item ^-x^/XML^
16898 Generate the XML output
16899
16900 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
16901 @item ^-nt^/NO_TEXT^
16902 Do not generate the output in text form (implies @option{^-x^/XML^})
16903
16904 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
16905 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
16906 Put textual files with detailed metrics into @var{output_dir}
16907
16908 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
16909 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
16910 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
16911 in the name of the output file.
16912
16913 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
16914 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
16915 Put global metrics into @var{file_name}
16916
16917 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
16918 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
16919 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
16920
16921 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
16922 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
16923 Use ``short'' source file names in the output.  (The @command{gnatmetric}
16924 output includes the name(s) of the Ada source file(s) from which the metrics
16925 are computed.  By default each name includes the absolute path. The
16926 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
16927 to exclude all directory information from the file names that are output.)
16928
16929 @end table
16930
16931 @node Disable Metrics For Local Units
16932 @subsection Disable Metrics For Local Units
16933 @cindex Disable Metrics For Local Units in @command{gnatmetric}
16934
16935 @noindent
16936 @command{gnatmetric} relies on the GNAT compilation model @minus{}
16937 one compilation
16938 unit per one source file. It computes line metrics for the whole source
16939 file, and it also computes syntax
16940 and complexity metrics for the file's outermost unit.
16941
16942 By default, @command{gnatmetric} will also compute all metrics for certain
16943 kinds of locally declared program units:
16944
16945 @itemize @bullet
16946 @item
16947 subprogram (and generic subprogram) bodies;
16948
16949 @item
16950 package (and generic package) specs and bodies;
16951
16952 @item
16953 task object and type specifications and bodies;
16954
16955 @item
16956 protected object and type specifications and bodies.
16957 @end itemize
16958
16959 @noindent
16960 These kinds of entities will be referred to as
16961 @emph{eligible local program units}, or simply @emph{eligible local units},
16962 @cindex Eligible local unit (for @command{gnatmetric})
16963 in the discussion below.
16964
16965 Note that a subprogram declaration, generic instantiation,
16966 or renaming declaration only receives metrics
16967 computation when it appear as the outermost entity
16968 in a source file.
16969
16970 Suppression of metrics computation for eligible local units can be
16971 obtained via the following switch:
16972
16973 @table @option
16974 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
16975 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
16976 Do not compute detailed metrics for eligible local program units
16977
16978 @end table
16979
16980 @node Specifying a set of metrics to compute
16981 @subsection Specifying a set of metrics to compute
16982
16983 @noindent
16984 By default all the metrics are computed and reported. The switches
16985 described in this subsection allow you to control, on an individual
16986 basis, whether metrics are computed and
16987 reported. If at least one positive metric
16988 switch is specified (that is, a switch that defines that a given
16989 metric or set of metrics is to be computed), then only
16990 explicitly specified metrics are reported.
16991
16992 @menu
16993 * Line Metrics Control::
16994 * Syntax Metrics Control::
16995 * Complexity Metrics Control::
16996 * Object-Oriented Metrics Control::
16997 @end menu
16998
16999 @node Line Metrics Control
17000 @subsubsection Line Metrics Control
17001 @cindex Line metrics control in @command{gnatmetric}
17002
17003 @noindent
17004 For any (legal) source file, and for each of its
17005 eligible local program units, @command{gnatmetric} computes the following
17006 metrics:
17007
17008 @itemize @bullet
17009 @item
17010 the total number of lines;
17011
17012 @item
17013 the total number of code lines (i.e., non-blank lines that are not comments)
17014
17015 @item
17016 the number of comment lines
17017
17018 @item
17019 the number of code lines containing end-of-line comments;
17020
17021 @item
17022 the comment percentage: the ratio between the number of lines that contain
17023 comments and the number of all non-blank lines, expressed as a percentage;
17024
17025 @item
17026 the number of empty lines and lines containing only space characters and/or
17027 format effectors (blank lines)
17028
17029 @item
17030 the average number of code lines in subprogram bodies, task bodies, entry
17031 bodies and statement sequences in package bodies (this metric is only computed
17032 across the whole set of the analyzed units)
17033
17034 @end itemize
17035
17036 @noindent
17037 @command{gnatmetric} sums the values of the line metrics for all the
17038 files being processed and then generates the cumulative results. The tool
17039 also computes for all the files being processed the average number of code
17040 lines in bodies.
17041
17042 You can use the following switches to select the specific line metrics
17043 to be computed and reported.
17044
17045 @table @option
17046 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
17047
17048 @ifclear vms
17049 @cindex @option{--no-lines@var{x}}
17050 @end ifclear
17051
17052 @item ^--lines-all^/LINE_COUNT_METRICS=ALL_ON^
17053 Report all the line metrics
17054
17055 @item ^--no-lines-all^/LINE_COUNT_METRICS=ALL_OFF^
17056 Do not report any of line metrics
17057
17058 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES_ON^
17059 Report the number of all lines
17060
17061 @item ^--no-lines^/LINE_COUNT_METRICS=ALL_LINES_OFF^
17062 Do not report the number of all lines
17063
17064 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES_ON^
17065 Report the number of code lines
17066
17067 @item ^--no-lines-code^/LINE_COUNT_METRICS=CODE_LINES_OFF^
17068 Do not report the number of code lines
17069
17070 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES_ON^
17071 Report the number of comment lines
17072
17073 @item ^--no-lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES_OFF^
17074 Do not report the number of comment lines
17075
17076 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES_ON^
17077 Report the number of code lines containing
17078 end-of-line comments
17079
17080 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES_OFF^
17081 Do not report the number of code lines containing
17082 end-of-line comments
17083
17084 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE_ON^
17085 Report the comment percentage in the program text
17086
17087 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE_OFF^
17088 Do not report the comment percentage in the program text
17089
17090 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES_ON^
17091 Report the number of blank lines
17092
17093 @item ^--no-lines-blank^/LINE_COUNT_METRICS=BLANK_LINES_OFF^
17094 Do not report the number of blank lines
17095
17096 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES_ON^
17097 Report the average number of code lines in subprogram bodies, task bodies,
17098 entry bodies and statement sequences in package bodies. The metric is computed
17099 and reported for the whole set of processed Ada sources only.
17100
17101 @item ^--no-lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES_OFF^
17102 Do not report the average number of code lines in subprogram bodies,
17103 task bodies, entry bodies and statement sequences in package bodies.
17104
17105 @end table
17106
17107 @node Syntax Metrics Control
17108 @subsubsection Syntax Metrics Control
17109 @cindex Syntax metrics control in @command{gnatmetric}
17110
17111 @noindent
17112 @command{gnatmetric} computes various syntactic metrics for the
17113 outermost unit and for each eligible local unit:
17114
17115 @table @emph
17116 @item LSLOC (``Logical Source Lines Of Code'')
17117 The total number of declarations and the total number of statements
17118
17119 @item Maximal static nesting level of inner program units
17120 According to
17121 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
17122 package, a task unit, a protected unit, a
17123 protected entry, a generic unit, or an explicitly declared subprogram other
17124 than an enumeration literal.''
17125
17126 @item Maximal nesting level of composite syntactic constructs
17127 This corresponds to the notion of the
17128 maximum nesting level in the GNAT built-in style checks
17129 (@pxref{Style Checking})
17130 @end table
17131
17132 @noindent
17133 For the outermost unit in the file, @command{gnatmetric} additionally computes
17134 the following metrics:
17135
17136 @table @emph
17137 @item Public subprograms
17138 This metric is computed for package specs. It is the
17139 number of subprograms and generic subprograms declared in the visible
17140 part (including the visible part of nested packages, protected objects, and
17141 protected types).
17142
17143 @item All subprograms
17144 This metric is computed for bodies and subunits. The
17145 metric is equal to a total number of subprogram bodies in the compilation
17146 unit.
17147 Neither generic instantiations nor renamings-as-a-body nor body stubs
17148 are counted. Any subprogram body is counted, independently of its nesting
17149 level and enclosing constructs. Generic bodies and bodies of protected
17150 subprograms are counted in the same way as ``usual'' subprogram bodies.
17151
17152 @item Public types
17153 This metric is computed for package specs and
17154 generic package declarations. It is the total number of types
17155 that can be referenced from outside this compilation unit, plus the
17156 number of types from all the visible parts of all the visible generic
17157 packages. Generic formal types are not counted.  Only types, not subtypes,
17158 are included.
17159
17160 @noindent
17161 Along with the total number of public types, the following
17162 types are counted and reported separately:
17163
17164 @itemize @bullet
17165 @item
17166 Abstract types
17167
17168 @item
17169 Root tagged types (abstract, non-abstract, private, non-private). Type
17170 extensions are @emph{not} counted
17171
17172 @item
17173 Private types (including private extensions)
17174
17175 @item
17176 Task types
17177
17178 @item
17179 Protected types
17180
17181 @end itemize
17182
17183 @item All types
17184 This metric is computed for any compilation unit. It is equal to the total
17185 number of the declarations of different types given in the compilation unit.
17186 The private and the corresponding full type declaration are counted as one
17187 type declaration. Incomplete type declarations and generic formal types
17188 are not counted.
17189 No distinction is made among different kinds of types (abstract,
17190 private etc.); the total number of types is computed and reported.
17191
17192 @end table
17193
17194 @noindent
17195 By default, all the syntax metrics are computed and reported. You can use the
17196 following switches to select specific syntax metrics.
17197
17198 @table @option
17199
17200 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
17201
17202 @ifclear vms
17203 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
17204 @end ifclear
17205
17206 @item ^--syntax-all^/SYNTAX_METRICS=ALL_ON^
17207 Report all the syntax metrics
17208
17209 @item ^--no-syntax-all^/ALL_OFF^
17210 Do not report any of syntax metrics
17211
17212 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS_ON^
17213 Report the total number of declarations
17214
17215 @item ^--no-declarations^/SYNTAX_METRICS=DECLARATIONS_OFF^
17216 Do not report the total number of declarations
17217
17218 @item ^--statements^/SYNTAX_METRICS=STATEMENTS_ON^
17219 Report the total number of statements
17220
17221 @item ^--no-statements^/SYNTAX_METRICS=STATEMENTS_OFF^
17222 Do not report the total number of statements
17223
17224 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS_ON^
17225 Report the number of public subprograms in a compilation unit
17226
17227 @item ^--no-public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS_OFF^
17228 Do not report the number of public subprograms in a compilation unit
17229
17230 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS_ON^
17231 Report the number of all the subprograms in a compilation unit
17232
17233 @item ^--no-all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS_OFF^
17234 Do not report the number of all the subprograms in a compilation unit
17235
17236 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES_ON^
17237 Report the number of public types in a compilation unit
17238
17239 @item ^--no-public-types^/SYNTAX_METRICS=PUBLIC_TYPES_OFF^
17240 Do not report the number of public types in a compilation unit
17241
17242 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES_ON^
17243 Report the number of all the types in a compilation unit
17244
17245 @item ^--no-all-types^/SYNTAX_METRICS=ALL_TYPES_OFF^
17246 Do not report the number of all the types in a compilation unit
17247
17248 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_ON^
17249 Report the maximal program unit nesting level
17250
17251 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
17252 Do not report the maximal program unit nesting level
17253
17254 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING_ON^
17255 Report the maximal construct nesting level
17256
17257 @item ^--no-construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING_OFF^
17258 Do not report the maximal construct nesting level
17259
17260 @end table
17261
17262 @node Complexity Metrics Control
17263 @subsubsection Complexity Metrics Control
17264 @cindex Complexity metrics control in @command{gnatmetric}
17265
17266 @noindent
17267 For a program unit that is an executable body (a subprogram body (including
17268 generic bodies), task body, entry body or a package body containing
17269 its own statement sequence) @command{gnatmetric} computes the following
17270 complexity metrics:
17271
17272 @itemize @bullet
17273 @item
17274 McCabe cyclomatic complexity;
17275
17276 @item
17277 McCabe essential complexity;
17278
17279 @item
17280 maximal loop nesting level
17281
17282 @end itemize
17283
17284 @noindent
17285 The McCabe complexity metrics are defined
17286 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
17287
17288 According to McCabe, both control statements and short-circuit control forms
17289 should be taken into account when computing cyclomatic complexity. For each
17290 body, we compute three metric values:
17291
17292 @itemize @bullet
17293 @item
17294 the complexity introduced by control
17295 statements only, without taking into account short-circuit forms,
17296
17297 @item
17298 the complexity introduced by short-circuit control forms only, and
17299
17300 @item
17301 the total
17302 cyclomatic complexity, which is the sum of these two values.
17303 @end itemize
17304
17305 @noindent
17306 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
17307 the code in the exception handlers and in all the nested program units.
17308
17309 By default, all the complexity metrics are computed and reported.
17310 For more fine-grained control you can use
17311 the following switches:
17312
17313 @table @option
17314 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
17315
17316 @ifclear vms
17317 @cindex @option{--no-complexity@var{x}}
17318 @end ifclear
17319
17320 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL_ON^
17321 Report all the complexity metrics
17322
17323 @item ^--no-complexity-all^/COMPLEXITY_METRICS=ALL_OFF^
17324 Do not report any of complexity metrics
17325
17326 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC_ON^
17327 Report the McCabe Cyclomatic Complexity
17328
17329 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC_OFF^
17330 Do not report the McCabe Cyclomatic Complexity
17331
17332 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL_ON^
17333 Report the Essential Complexity
17334
17335 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL_OFF^
17336 Do not report the Essential Complexity
17337
17338 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
17339 Report maximal loop nesting level
17340
17341 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_OFF^
17342 Do not report maximal loop nesting level
17343
17344 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY_ON^
17345 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
17346 task bodies, entry bodies and statement sequences in package bodies.
17347 The metric is computed and reported for whole set of processed Ada sources
17348 only.
17349
17350 @item ^--no-complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY_OFF^
17351 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
17352 bodies, task bodies, entry bodies and statement sequences in package bodies
17353
17354 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
17355 @item ^-ne^/NO_EXITS_AS_GOTOS^
17356 Do not consider @code{exit} statements as @code{goto}s when
17357 computing Essential Complexity
17358
17359 @end table
17360
17361
17362 @node Object-Oriented Metrics Control
17363 @subsubsection Object-Oriented Metrics Control
17364 @cindex Object-Oriented metrics control in @command{gnatmetric}
17365
17366 @noindent
17367 @cindex Coupling metrics (in in @command{gnatmetric})
17368 Coupling metrics are object-oriented metrics that measure the
17369 dependencies between a given class (or a group of classes) and the
17370 ``external world'' (that is, the other classes in the program). In this
17371 subsection the term ``class'' is used in its
17372 traditional object-oriented programming sense
17373 (an instantiable module that contains data and/or method members).
17374 A @emph{category} (of classes)
17375 is a group of closely related classes that are reused and/or
17376 modified together.
17377
17378 A class @code{K}'s @emph{efferent coupling} is the number of classes
17379 that @code{K} depends upon.
17380 A category's efferent coupling is the number of classes outside the
17381 category that the classes inside the category depend upon.
17382
17383 A class @code{K}'s @emph{afferent coupling} is the number of classes
17384 that depend upon @code{K}.
17385 A category's afferent coupling is the number of classes outside the
17386 category that depend on classes belonging to the category.
17387
17388 Ada's implementation of the object-oriented paradigm does not use the
17389 traditional class notion, so the definition of the coupling
17390 metrics for Ada maps the class and class category notions
17391 onto Ada constructs.
17392
17393 For the coupling metrics, several kinds of modules -- a library package,
17394 a library generic package, and a library generic package instantiation --
17395 that define a tagged type or an interface type are
17396 considered to be a class. A category consists of a library package (or
17397 a library generic package) that defines a tagged or an interface type,
17398 together with all its descendant (generic) packages that define tagged
17399 or interface types. For any package counted as a class,
17400 its body (if any) is considered
17401 together with its spec when counting the dependencies. For dependencies
17402 between classes, the Ada semantic dependencies are considered.
17403 For coupling metrics, only dependencies on units that are considered as
17404 classes, are considered.
17405
17406 When computing coupling metrics, @command{gnatmetric} counts only
17407 dependencies between units that are arguments of the gnatmetric call.
17408 Coupling metrics are program-wide (or project-wide) metrics, so to
17409 get a valid result, you should call @command{gnatmetric} for
17410 the whole set of sources that make up your program. It can be done
17411 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
17412 option (see See @ref{The GNAT Driver and Project Files} for details.
17413
17414 By default, all the coupling metrics are disabled. You can use the following
17415 switches to specify the coupling metrics to be computed and reported:
17416
17417 @table @option
17418
17419 @ifclear vms
17420 @cindex @option{--package@var{x}} (@command{gnatmetric})
17421 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
17422 @cindex @option{--category@var{x}} (@command{gnatmetric})
17423 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
17424 @end ifclear
17425
17426 @ifset vms
17427 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
17428 @end ifset
17429
17430 @item ^--coupling-all^/COUPLING_METRICS=ALL_ON^
17431 Report all the coupling metrics
17432
17433 @item ^--no-coupling-all^/COUPLING_METRICS=ALL_OFF^
17434 Do not report any of  metrics
17435
17436 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT_ON^
17437 Report package efferent coupling
17438
17439 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT_OFF^
17440 Do not report package efferent coupling
17441
17442 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT_ON^
17443 Report package afferent coupling
17444
17445 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT_OFF^
17446 Do not report package afferent coupling
17447
17448 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT_ON^
17449 Report category efferent coupling
17450
17451 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT_OFF^
17452 Do not report category efferent coupling
17453
17454 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT_ON^
17455 Report category afferent coupling
17456
17457 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT_OFF^
17458 Do not report category afferent coupling
17459
17460 @end table
17461
17462 @node Other gnatmetric Switches
17463 @subsection Other @code{gnatmetric} Switches
17464
17465 @noindent
17466 Additional @command{gnatmetric} switches are as follows:
17467
17468 @table @option
17469 @item ^-files @var{filename}^/FILES=@var{filename}^
17470 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
17471 Take the argument source files from the specified file. This file should be an
17472 ordinary text file containing file names separated by spaces or
17473 line breaks. You can use this switch more then once in the same call to
17474 @command{gnatmetric}. You also can combine this switch with
17475 an explicit list of files.
17476
17477 @item ^-v^/VERBOSE^
17478 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
17479 Verbose mode;
17480 @command{gnatmetric} generates version information and then
17481 a trace of sources being processed.
17482
17483 @item ^-dv^/DEBUG_OUTPUT^
17484 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
17485 Debug mode;
17486 @command{gnatmetric} generates various messages useful to understand what
17487 happens during the metrics computation
17488
17489 @item ^-q^/QUIET^
17490 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
17491 Quiet mode.
17492 @end table
17493
17494 @node Generate project-wide metrics
17495 @subsection Generate project-wide metrics
17496
17497 In order to compute metrics on all units of a given project, you can use
17498 the @command{gnat} driver along with the @option{-P} option:
17499 @smallexample
17500    gnat metric -Pproj
17501 @end smallexample
17502
17503 @noindent
17504 If the project @code{proj} depends upon other projects, you can compute
17505 the metrics on the project closure using the @option{-U} option:
17506 @smallexample
17507    gnat metric -Pproj -U
17508 @end smallexample
17509
17510 @noindent
17511 Finally, if not all the units are relevant to a particular main
17512 program in the project closure, you can generate metrics for the set
17513 of units needed to create a given main program (unit closure) using
17514 the @option{-U} option followed by the name of the main unit:
17515 @smallexample
17516    gnat metric -Pproj -U main
17517 @end smallexample
17518
17519
17520 @c ***********************************
17521 @node File Name Krunching Using gnatkr
17522 @chapter File Name Krunching Using @code{gnatkr}
17523 @findex gnatkr
17524
17525 @noindent
17526 This chapter discusses the method used by the compiler to shorten
17527 the default file names chosen for Ada units so that they do not
17528 exceed the maximum length permitted. It also describes the
17529 @code{gnatkr} utility that can be used to determine the result of
17530 applying this shortening.
17531 @menu
17532 * About gnatkr::
17533 * Using gnatkr::
17534 * Krunching Method::
17535 * Examples of gnatkr Usage::
17536 @end menu
17537
17538 @node About gnatkr
17539 @section About @code{gnatkr}
17540
17541 @noindent
17542 The default file naming rule in GNAT
17543 is that the file name must be derived from
17544 the unit name. The exact default rule is as follows:
17545 @itemize @bullet
17546 @item
17547 Take the unit name and replace all dots by hyphens.
17548 @item
17549 If such a replacement occurs in the
17550 second character position of a name, and the first character is
17551 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
17552 then replace the dot by the character
17553 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
17554 instead of a minus.
17555 @end itemize
17556 The reason for this exception is to avoid clashes
17557 with the standard names for children of System, Ada, Interfaces,
17558 and GNAT, which use the prefixes
17559 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
17560 respectively.
17561
17562 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
17563 switch of the compiler activates a ``krunching''
17564 circuit that limits file names to nn characters (where nn is a decimal
17565 integer). For example, using OpenVMS,
17566 where the maximum file name length is
17567 39, the value of nn is usually set to 39, but if you want to generate
17568 a set of files that would be usable if ported to a system with some
17569 different maximum file length, then a different value can be specified.
17570 The default value of 39 for OpenVMS need not be specified.
17571
17572 The @code{gnatkr} utility can be used to determine the krunched name for
17573 a given file, when krunched to a specified maximum length.
17574
17575 @node Using gnatkr
17576 @section Using @code{gnatkr}
17577
17578 @noindent
17579 The @code{gnatkr} command has the form
17580
17581 @ifclear vms
17582 @smallexample
17583 $ gnatkr @var{name} @ovar{length}
17584 @end smallexample
17585 @end ifclear
17586
17587 @ifset vms
17588 @smallexample
17589 $ gnatkr @var{name} /COUNT=nn
17590 @end smallexample
17591 @end ifset
17592
17593 @noindent
17594 @var{name} is the uncrunched file name, derived from the name of the unit
17595 in the standard manner described in the previous section (i.e., in particular
17596 all dots are replaced by hyphens). The file name may or may not have an
17597 extension (defined as a suffix of the form period followed by arbitrary
17598 characters other than period). If an extension is present then it will
17599 be preserved in the output. For example, when krunching @file{hellofile.ads}
17600 to eight characters, the result will be hellofil.ads.
17601
17602 Note: for compatibility with previous versions of @code{gnatkr} dots may
17603 appear in the name instead of hyphens, but the last dot will always be
17604 taken as the start of an extension. So if @code{gnatkr} is given an argument
17605 such as @file{Hello.World.adb} it will be treated exactly as if the first
17606 period had been a hyphen, and for example krunching to eight characters
17607 gives the result @file{hellworl.adb}.
17608
17609 Note that the result is always all lower case (except on OpenVMS where it is
17610 all upper case). Characters of the other case are folded as required.
17611
17612 @var{length} represents the length of the krunched name. The default
17613 when no argument is given is ^8^39^ characters. A length of zero stands for
17614 unlimited, in other words do not chop except for system files where the
17615 implied crunching length is always eight characters.
17616
17617 @noindent
17618 The output is the krunched name. The output has an extension only if the
17619 original argument was a file name with an extension.
17620
17621 @node Krunching Method
17622 @section Krunching Method
17623
17624 @noindent
17625 The initial file name is determined by the name of the unit that the file
17626 contains. The name is formed by taking the full expanded name of the
17627 unit and replacing the separating dots with hyphens and
17628 using ^lowercase^uppercase^
17629 for all letters, except that a hyphen in the second character position is
17630 replaced by a ^tilde^dollar sign^ if the first character is
17631 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
17632 The extension is @code{.ads} for a
17633 spec and @code{.adb} for a body.
17634 Krunching does not affect the extension, but the file name is shortened to
17635 the specified length by following these rules:
17636
17637 @itemize @bullet
17638 @item
17639 The name is divided into segments separated by hyphens, tildes or
17640 underscores and all hyphens, tildes, and underscores are
17641 eliminated. If this leaves the name short enough, we are done.
17642
17643 @item
17644 If the name is too long, the longest segment is located (left-most
17645 if there are two of equal length), and shortened by dropping
17646 its last character. This is repeated until the name is short enough.
17647
17648 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
17649 to fit the name into 8 characters as required by some operating systems.
17650
17651 @smallexample
17652 our-strings-wide_fixed 22
17653 our strings wide fixed 19
17654 our string  wide fixed 18
17655 our strin   wide fixed 17
17656 our stri    wide fixed 16
17657 our stri    wide fixe  15
17658 our str     wide fixe  14
17659 our str     wid  fixe  13
17660 our str     wid  fix   12
17661 ou  str     wid  fix   11
17662 ou  st      wid  fix   10
17663 ou  st      wi   fix   9
17664 ou  st      wi   fi    8
17665 Final file name: oustwifi.adb
17666 @end smallexample
17667
17668 @item
17669 The file names for all predefined units are always krunched to eight
17670 characters. The krunching of these predefined units uses the following
17671 special prefix replacements:
17672
17673 @table @file
17674 @item ada-
17675 replaced by @file{^a^A^-}
17676
17677 @item gnat-
17678 replaced by @file{^g^G^-}
17679
17680 @item interfaces-
17681 replaced by @file{^i^I^-}
17682
17683 @item system-
17684 replaced by @file{^s^S^-}
17685 @end table
17686
17687 These system files have a hyphen in the second character position. That
17688 is why normal user files replace such a character with a
17689 ^tilde^dollar sign^, to
17690 avoid confusion with system file names.
17691
17692 As an example of this special rule, consider
17693 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
17694
17695 @smallexample
17696 ada-strings-wide_fixed 22
17697 a-  strings wide fixed 18
17698 a-  string  wide fixed 17
17699 a-  strin   wide fixed 16
17700 a-  stri    wide fixed 15
17701 a-  stri    wide fixe  14
17702 a-  str     wide fixe  13
17703 a-  str     wid  fixe  12
17704 a-  str     wid  fix   11
17705 a-  st      wid  fix   10
17706 a-  st      wi   fix   9
17707 a-  st      wi   fi    8
17708 Final file name: a-stwifi.adb
17709 @end smallexample
17710 @end itemize
17711
17712 Of course no file shortening algorithm can guarantee uniqueness over all
17713 possible unit names, and if file name krunching is used then it is your
17714 responsibility to ensure that no name clashes occur. The utility
17715 program @code{gnatkr} is supplied for conveniently determining the
17716 krunched name of a file.
17717
17718 @node Examples of gnatkr Usage
17719 @section Examples of @code{gnatkr} Usage
17720
17721 @smallexample
17722 @iftex
17723 @leftskip=0cm
17724 @end iftex
17725 @ifclear vms
17726 $ gnatkr very_long_unit_name.ads      --> velounna.ads
17727 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
17728 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
17729 $ gnatkr grandparent-parent-child     --> grparchi
17730 @end ifclear
17731 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
17732 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
17733 @end smallexample
17734
17735 @node Preprocessing Using gnatprep
17736 @chapter Preprocessing Using @code{gnatprep}
17737 @findex gnatprep
17738
17739 @noindent
17740 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
17741 preprocessing.
17742 Although designed for use with GNAT, @code{gnatprep} does not depend on any
17743 special GNAT features.
17744 For further discussion of conditional compilation in general, see
17745 @ref{Conditional Compilation}.
17746
17747 @menu
17748 * Preprocessing Symbols::
17749 * Using gnatprep::
17750 * Switches for gnatprep::
17751 * Form of Definitions File::
17752 * Form of Input Text for gnatprep::
17753 @end menu
17754
17755 @node Preprocessing Symbols
17756 @section Preprocessing Symbols
17757
17758 @noindent
17759 Preprocessing symbols are defined in definition files and referred to in
17760 sources to be preprocessed. A Preprocessing symbol is an identifier, following
17761 normal Ada (case-insensitive) rules for its syntax, with the restriction that
17762 all characters need to be in the ASCII set (no accented letters).
17763
17764 @node Using gnatprep
17765 @section Using @code{gnatprep}
17766
17767 @noindent
17768 To call @code{gnatprep} use
17769
17770 @smallexample
17771 $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
17772 @end smallexample
17773
17774 @noindent
17775 where
17776 @table @var
17777 @item switches
17778 is an optional sequence of switches as described in the next section.
17779
17780 @item infile
17781 is the full name of the input file, which is an Ada source
17782 file containing preprocessor directives.
17783
17784 @item outfile
17785 is the full name of the output file, which is an Ada source
17786 in standard Ada form. When used with GNAT, this file name will
17787 normally have an ads or adb suffix.
17788
17789 @item deffile
17790 is the full name of a text file containing definitions of
17791 preprocessing symbols to be referenced by the preprocessor. This argument is
17792 optional, and can be replaced by the use of the @option{-D} switch.
17793
17794 @end table
17795
17796 @node Switches for gnatprep
17797 @section Switches for @code{gnatprep}
17798
17799 @table @option
17800 @c !sort!
17801
17802 @item ^-b^/BLANK_LINES^
17803 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
17804 Causes both preprocessor lines and the lines deleted by
17805 preprocessing to be replaced by blank lines in the output source file,
17806 preserving line numbers in the output file.
17807
17808 @item ^-c^/COMMENTS^
17809 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
17810 Causes both preprocessor lines and the lines deleted
17811 by preprocessing to be retained in the output source as comments marked
17812 with the special string @code{"--! "}. This option will result in line numbers
17813 being preserved in the output file.
17814
17815 @item ^-C^/REPLACE_IN_COMMENTS^
17816 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
17817 Causes comments to be scanned. Normally comments are ignored by gnatprep.
17818 If this option is specified, then comments are scanned and any $symbol
17819 substitutions performed as in program text. This is particularly useful
17820 when structured comments are used (e.g., when writing programs in the
17821 SPARK dialect of Ada). Note that this switch is not available when
17822 doing integrated preprocessing (it would be useless in this context
17823 since comments are ignored by the compiler in any case).
17824
17825 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
17826 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
17827 Defines a new preprocessing symbol, associated with value. If no value is given
17828 on the command line, then symbol is considered to be @code{True}. This switch
17829 can be used in place of a definition file.
17830
17831 @ifset vms
17832 @item /REMOVE
17833 @cindex @option{/REMOVE} (@command{gnatprep})
17834 This is the default setting which causes lines deleted by preprocessing
17835 to be entirely removed from the output file.
17836 @end ifset
17837
17838 @item ^-r^/REFERENCE^
17839 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
17840 Causes a @code{Source_Reference} pragma to be generated that
17841 references the original input file, so that error messages will use
17842 the file name of this original file. The use of this switch implies
17843 that preprocessor lines are not to be removed from the file, so its
17844 use will force @option{^-b^/BLANK_LINES^} mode if
17845 @option{^-c^/COMMENTS^}
17846 has not been specified explicitly.
17847
17848 Note that if the file to be preprocessed contains multiple units, then
17849 it will be necessary to @code{gnatchop} the output file from
17850 @code{gnatprep}. If a @code{Source_Reference} pragma is present
17851 in the preprocessed file, it will be respected by
17852 @code{gnatchop ^-r^/REFERENCE^}
17853 so that the final chopped files will correctly refer to the original
17854 input source file for @code{gnatprep}.
17855
17856 @item ^-s^/SYMBOLS^
17857 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
17858 Causes a sorted list of symbol names and values to be
17859 listed on the standard output file.
17860
17861 @item ^-u^/UNDEFINED^
17862 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
17863 Causes undefined symbols to be treated as having the value FALSE in the context
17864 of a preprocessor test. In the absence of this option, an undefined symbol in
17865 a @code{#if} or @code{#elsif} test will be treated as an error.
17866
17867 @end table
17868
17869 @ifclear vms
17870 @noindent
17871 Note: if neither @option{-b} nor @option{-c} is present,
17872 then preprocessor lines and
17873 deleted lines are completely removed from the output, unless -r is
17874 specified, in which case -b is assumed.
17875 @end ifclear
17876
17877 @node Form of Definitions File
17878 @section Form of Definitions File
17879
17880 @noindent
17881 The definitions file contains lines of the form
17882
17883 @smallexample
17884 symbol := value
17885 @end smallexample
17886
17887 @noindent
17888 where symbol is a preprocessing symbol, and value is one of the following:
17889
17890 @itemize @bullet
17891 @item
17892 Empty, corresponding to a null substitution
17893 @item
17894 A string literal using normal Ada syntax
17895 @item
17896 Any sequence of characters from the set
17897 (letters, digits, period, underline).
17898 @end itemize
17899
17900 @noindent
17901 Comment lines may also appear in the definitions file, starting with
17902 the usual @code{--},
17903 and comments may be added to the definitions lines.
17904
17905 @node Form of Input Text for gnatprep
17906 @section Form of Input Text for @code{gnatprep}
17907
17908 @noindent
17909 The input text may contain preprocessor conditional inclusion lines,
17910 as well as general symbol substitution sequences.
17911
17912 The preprocessor conditional inclusion commands have the form
17913
17914 @smallexample
17915 @group
17916 @cartouche
17917 #if @i{expression} @r{[}then@r{]}
17918    lines
17919 #elsif @i{expression} @r{[}then@r{]}
17920    lines
17921 #elsif @i{expression} @r{[}then@r{]}
17922    lines
17923 @dots{}
17924 #else
17925    lines
17926 #end if;
17927 @end cartouche
17928 @end group
17929 @end smallexample
17930
17931 @noindent
17932 In this example, @i{expression} is defined by the following grammar:
17933 @smallexample
17934 @i{expression} ::=  <symbol>
17935 @i{expression} ::=  <symbol> = "<value>"
17936 @i{expression} ::=  <symbol> = <symbol>
17937 @i{expression} ::=  <symbol> 'Defined
17938 @i{expression} ::=  not @i{expression}
17939 @i{expression} ::=  @i{expression} and @i{expression}
17940 @i{expression} ::=  @i{expression} or @i{expression}
17941 @i{expression} ::=  @i{expression} and then @i{expression}
17942 @i{expression} ::=  @i{expression} or else @i{expression}
17943 @i{expression} ::=  ( @i{expression} )
17944 @end smallexample
17945
17946 The following restriction exists: it is not allowed to have "and" or "or"
17947 following "not" in the same expression without parentheses. For example, this
17948 is not allowed:
17949
17950 @smallexample
17951    not X or Y
17952 @end smallexample
17953
17954 This should be one of the following:
17955
17956 @smallexample
17957    (not X) or Y
17958    not (X or Y)
17959 @end smallexample
17960
17961 @noindent
17962 For the first test (@i{expression} ::= <symbol>) the symbol must have
17963 either the value true or false, that is to say the right-hand of the
17964 symbol definition must be one of the (case-insensitive) literals
17965 @code{True} or @code{False}. If the value is true, then the
17966 corresponding lines are included, and if the value is false, they are
17967 excluded.
17968
17969 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
17970 the symbol has been defined in the definition file or by a @option{-D}
17971 switch on the command line. Otherwise, the test is false.
17972
17973 The equality tests are case insensitive, as are all the preprocessor lines.
17974
17975 If the symbol referenced is not defined in the symbol definitions file,
17976 then the effect depends on whether or not switch @option{-u}
17977 is specified. If so, then the symbol is treated as if it had the value
17978 false and the test fails. If this switch is not specified, then
17979 it is an error to reference an undefined symbol. It is also an error to
17980 reference a symbol that is defined with a value other than @code{True}
17981 or @code{False}.
17982
17983 The use of the @code{not} operator inverts the sense of this logical test.
17984 The @code{not} operator cannot be combined with the @code{or} or @code{and}
17985 operators, without parentheses. For example, "if not X or Y then" is not
17986 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
17987
17988 The @code{then} keyword is optional as shown
17989
17990 The @code{#} must be the first non-blank character on a line, but
17991 otherwise the format is free form. Spaces or tabs may appear between
17992 the @code{#} and the keyword. The keywords and the symbols are case
17993 insensitive as in normal Ada code. Comments may be used on a
17994 preprocessor line, but other than that, no other tokens may appear on a
17995 preprocessor line. Any number of @code{elsif} clauses can be present,
17996 including none at all. The @code{else} is optional, as in Ada.
17997
17998 The @code{#} marking the start of a preprocessor line must be the first
17999 non-blank character on the line, i.e., it must be preceded only by
18000 spaces or horizontal tabs.
18001
18002 Symbol substitution outside of preprocessor lines is obtained by using
18003 the sequence
18004
18005 @smallexample
18006 $symbol
18007 @end smallexample
18008
18009 @noindent
18010 anywhere within a source line, except in a comment or within a
18011 string literal. The identifier
18012 following the @code{$} must match one of the symbols defined in the symbol
18013 definition file, and the result is to substitute the value of the
18014 symbol in place of @code{$symbol} in the output file.
18015
18016 Note that although the substitution of strings within a string literal
18017 is not possible, it is possible to have a symbol whose defined value is
18018 a string literal. So instead of setting XYZ to @code{hello} and writing:
18019
18020 @smallexample
18021 Header : String := "$XYZ";
18022 @end smallexample
18023
18024 @noindent
18025 you should set XYZ to @code{"hello"} and write:
18026
18027 @smallexample
18028 Header : String := $XYZ;
18029 @end smallexample
18030
18031 @noindent
18032 and then the substitution will occur as desired.
18033
18034 @ifset vms
18035 @node The GNAT Run-Time Library Builder gnatlbr
18036 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
18037 @findex gnatlbr
18038 @cindex Library builder
18039
18040 @noindent
18041 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
18042 supplied configuration pragmas.
18043
18044 @menu
18045 * Running gnatlbr::
18046 * Switches for gnatlbr::
18047 * Examples of gnatlbr Usage::
18048 @end menu
18049
18050 @node Running gnatlbr
18051 @section Running @code{gnatlbr}
18052
18053 @noindent
18054 The @code{gnatlbr} command has the form
18055
18056 @smallexample
18057 $ GNAT LIBRARY /@r{[}CREATE@r{|}SET@r{|}DELETE@r{]}=directory @r{[}/CONFIG=file@r{]}
18058 @end smallexample
18059
18060 @node Switches for gnatlbr
18061 @section Switches for @code{gnatlbr}
18062
18063 @noindent
18064 @code{gnatlbr} recognizes the following switches:
18065
18066 @table @option
18067 @c !sort!
18068 @item /CREATE=directory
18069 @cindex @code{/CREATE} (@code{gnatlbr})
18070 Create the new run-time library in the specified directory.
18071
18072 @item /SET=directory
18073 @cindex @code{/SET} (@code{gnatlbr})
18074 Make the library in the specified directory the current run-time library.
18075
18076 @item /DELETE=directory
18077 @cindex @code{/DELETE} (@code{gnatlbr})
18078 Delete the run-time library in the specified directory.
18079
18080 @item /CONFIG=file
18081 @cindex @code{/CONFIG} (@code{gnatlbr})
18082 With /CREATE: Use the configuration pragmas in the specified file when
18083 building the library.
18084
18085 With /SET: Use the configuration pragmas in the specified file when
18086 compiling.
18087
18088 @end table
18089
18090 @node Examples of gnatlbr Usage
18091 @section Example of @code{gnatlbr} Usage
18092
18093 @smallexample
18094 Contents of VAXFLOAT.ADC:
18095 pragma Float_Representation (VAX_Float);
18096
18097 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
18098
18099 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
18100
18101 @end smallexample
18102 @end ifset
18103
18104 @node The GNAT Library Browser gnatls
18105 @chapter The GNAT Library Browser @code{gnatls}
18106 @findex gnatls
18107 @cindex Library browser
18108
18109 @noindent
18110 @code{gnatls} is a tool that outputs information about compiled
18111 units. It gives the relationship between objects, unit names and source
18112 files. It can also be used to check the source dependencies of a unit
18113 as well as various characteristics.
18114
18115 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
18116 driver (see @ref{The GNAT Driver and Project Files}).
18117
18118 @menu
18119 * Running gnatls::
18120 * Switches for gnatls::
18121 * Examples of gnatls Usage::
18122 @end menu
18123
18124 @node Running gnatls
18125 @section Running @code{gnatls}
18126
18127 @noindent
18128 The @code{gnatls} command has the form
18129
18130 @smallexample
18131 $ gnatls switches @var{object_or_ali_file}
18132 @end smallexample
18133
18134 @noindent
18135 The main argument is the list of object or @file{ali} files
18136 (@pxref{The Ada Library Information Files})
18137 for which information is requested.
18138
18139 In normal mode, without additional option, @code{gnatls} produces a
18140 four-column listing. Each line represents information for a specific
18141 object. The first column gives the full path of the object, the second
18142 column gives the name of the principal unit in this object, the third
18143 column gives the status of the source and the fourth column gives the
18144 full path of the source representing this unit.
18145 Here is a simple example of use:
18146
18147 @smallexample
18148 $ gnatls *.o
18149 ^./^[]^demo1.o            demo1            DIF demo1.adb
18150 ^./^[]^demo2.o            demo2             OK demo2.adb
18151 ^./^[]^hello.o            h1                OK hello.adb
18152 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
18153 ^./^[]^instr.o            instr             OK instr.adb
18154 ^./^[]^tef.o              tef              DIF tef.adb
18155 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
18156 ^./^[]^tgef.o             tgef             DIF tgef.adb
18157 @end smallexample
18158
18159 @noindent
18160 The first line can be interpreted as follows: the main unit which is
18161 contained in
18162 object file @file{demo1.o} is demo1, whose main source is in
18163 @file{demo1.adb}. Furthermore, the version of the source used for the
18164 compilation of demo1 has been modified (DIF). Each source file has a status
18165 qualifier which can be:
18166
18167 @table @code
18168 @item OK (unchanged)
18169 The version of the source file used for the compilation of the
18170 specified unit corresponds exactly to the actual source file.
18171
18172 @item MOK (slightly modified)
18173 The version of the source file used for the compilation of the
18174 specified unit differs from the actual source file but not enough to
18175 require recompilation. If you use gnatmake with the qualifier
18176 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
18177 MOK will not be recompiled.
18178
18179 @item DIF (modified)
18180 No version of the source found on the path corresponds to the source
18181 used to build this object.
18182
18183 @item ??? (file not found)
18184 No source file was found for this unit.
18185
18186 @item HID (hidden,  unchanged version not first on PATH)
18187 The version of the source that corresponds exactly to the source used
18188 for compilation has been found on the path but it is hidden by another
18189 version of the same source that has been modified.
18190
18191 @end table
18192
18193 @node Switches for gnatls
18194 @section Switches for @code{gnatls}
18195
18196 @noindent
18197 @code{gnatls} recognizes the following switches:
18198
18199 @table @option
18200 @c !sort!
18201 @cindex @option{--version} @command{gnatls}
18202 Display Copyright and version, then exit disregarding all other options.
18203
18204 @item --help
18205 @cindex @option{--help} @command{gnatls}
18206 If @option{--version} was not used, display usage, then exit disregarding
18207 all other options.
18208
18209 @item ^-a^/ALL_UNITS^
18210 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
18211 Consider all units, including those of the predefined Ada library.
18212 Especially useful with @option{^-d^/DEPENDENCIES^}.
18213
18214 @item ^-d^/DEPENDENCIES^
18215 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
18216 List sources from which specified units depend on.
18217
18218 @item ^-h^/OUTPUT=OPTIONS^
18219 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
18220 Output the list of options.
18221
18222 @item ^-o^/OUTPUT=OBJECTS^
18223 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
18224 Only output information about object files.
18225
18226 @item ^-s^/OUTPUT=SOURCES^
18227 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
18228 Only output information about source files.
18229
18230 @item ^-u^/OUTPUT=UNITS^
18231 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
18232 Only output information about compilation units.
18233
18234 @item ^-files^/FILES^=@var{file}
18235 @cindex @option{^-files^/FILES^} (@code{gnatls})
18236 Take as arguments the files listed in text file @var{file}.
18237 Text file @var{file} may contain empty lines that are ignored.
18238 Each nonempty line should contain the name of an existing file.
18239 Several such switches may be specified simultaneously.
18240
18241 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18242 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
18243 @itemx ^-I^/SEARCH=^@var{dir}
18244 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
18245 @itemx -nostdinc
18246 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
18247 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
18248 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
18249 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
18250 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
18251 flags (@pxref{Switches for gnatmake}).
18252
18253 @item --RTS=@var{rts-path}
18254 @cindex @option{--RTS} (@code{gnatls})
18255 Specifies the default location of the runtime library. Same meaning as the
18256 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
18257
18258 @item ^-v^/OUTPUT=VERBOSE^
18259 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
18260 Verbose mode. Output the complete source, object and project paths. Do not use
18261 the default column layout but instead use long format giving as much as
18262 information possible on each requested units, including special
18263 characteristics such as:
18264
18265 @table @code
18266 @item  Preelaborable
18267 The unit is preelaborable in the Ada sense.
18268
18269 @item No_Elab_Code
18270 No elaboration code has been produced by the compiler for this unit.
18271
18272 @item Pure
18273 The unit is pure in the Ada sense.
18274
18275 @item Elaborate_Body
18276 The unit contains a pragma Elaborate_Body.
18277
18278 @item Remote_Types
18279 The unit contains a pragma Remote_Types.
18280
18281 @item Shared_Passive
18282 The unit contains a pragma Shared_Passive.
18283
18284 @item Predefined
18285 This unit is part of the predefined environment and cannot be modified
18286 by the user.
18287
18288 @item Remote_Call_Interface
18289 The unit contains a pragma Remote_Call_Interface.
18290
18291 @end table
18292
18293 @end table
18294
18295 @node Examples of gnatls Usage
18296 @section Example of @code{gnatls} Usage
18297 @ifclear vms
18298
18299 @noindent
18300 Example of using the verbose switch. Note how the source and
18301 object paths are affected by the -I switch.
18302
18303 @smallexample
18304 $ gnatls -v -I.. demo1.o
18305
18306 GNATLS 5.03w (20041123-34)
18307 Copyright 1997-2004 Free Software Foundation, Inc.
18308
18309 Source Search Path:
18310    <Current_Directory>
18311    ../
18312    /home/comar/local/adainclude/
18313
18314 Object Search Path:
18315    <Current_Directory>
18316    ../
18317    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18318
18319 Project Search Path:
18320    <Current_Directory>
18321    /home/comar/local/lib/gnat/
18322
18323 ./demo1.o
18324    Unit =>
18325      Name   => demo1
18326      Kind   => subprogram body
18327      Flags  => No_Elab_Code
18328      Source => demo1.adb    modified
18329 @end smallexample
18330
18331 @noindent
18332 The following is an example of use of the dependency list.
18333 Note the use of the -s switch
18334 which gives a straight list of source files. This can be useful for
18335 building specialized scripts.
18336
18337 @smallexample
18338 $ gnatls -d demo2.o
18339 ./demo2.o   demo2        OK demo2.adb
18340                          OK gen_list.ads
18341                          OK gen_list.adb
18342                          OK instr.ads
18343                          OK instr-child.ads
18344
18345 $ gnatls -d -s -a demo1.o
18346 demo1.adb
18347 /home/comar/local/adainclude/ada.ads
18348 /home/comar/local/adainclude/a-finali.ads
18349 /home/comar/local/adainclude/a-filico.ads
18350 /home/comar/local/adainclude/a-stream.ads
18351 /home/comar/local/adainclude/a-tags.ads
18352 gen_list.ads
18353 gen_list.adb
18354 /home/comar/local/adainclude/gnat.ads
18355 /home/comar/local/adainclude/g-io.ads
18356 instr.ads
18357 /home/comar/local/adainclude/system.ads
18358 /home/comar/local/adainclude/s-exctab.ads
18359 /home/comar/local/adainclude/s-finimp.ads
18360 /home/comar/local/adainclude/s-finroo.ads
18361 /home/comar/local/adainclude/s-secsta.ads
18362 /home/comar/local/adainclude/s-stalib.ads
18363 /home/comar/local/adainclude/s-stoele.ads
18364 /home/comar/local/adainclude/s-stratt.ads
18365 /home/comar/local/adainclude/s-tasoli.ads
18366 /home/comar/local/adainclude/s-unstyp.ads
18367 /home/comar/local/adainclude/unchconv.ads
18368 @end smallexample
18369 @end ifclear
18370
18371 @ifset vms
18372 @smallexample
18373 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
18374
18375 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
18376 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
18377 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
18378 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
18379 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
18380 demo1.adb
18381 gen_list.ads
18382 gen_list.adb
18383 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
18384 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
18385 instr.ads
18386 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
18387 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
18388 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
18389 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
18390 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
18391 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
18392 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
18393 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
18394 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
18395 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
18396 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
18397 @end smallexample
18398 @end ifset
18399
18400 @node Cleaning Up Using gnatclean
18401 @chapter Cleaning Up Using @code{gnatclean}
18402 @findex gnatclean
18403 @cindex Cleaning tool
18404
18405 @noindent
18406 @code{gnatclean} is a tool that allows the deletion of files produced by the
18407 compiler, binder and linker, including ALI files, object files, tree files,
18408 expanded source files, library files, interface copy source files, binder
18409 generated files and executable files.
18410
18411 @menu
18412 * Running gnatclean::
18413 * Switches for gnatclean::
18414 @c * Examples of gnatclean Usage::
18415 @end menu
18416
18417 @node Running gnatclean
18418 @section Running @code{gnatclean}
18419
18420 @noindent
18421 The @code{gnatclean} command has the form:
18422
18423 @smallexample
18424 $ gnatclean switches @var{names}
18425 @end smallexample
18426
18427 @noindent
18428 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
18429 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
18430 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
18431
18432 @noindent
18433 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
18434 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
18435 the linker. In informative-only mode, specified by switch
18436 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
18437 normal mode is listed, but no file is actually deleted.
18438
18439 @node Switches for gnatclean
18440 @section Switches for @code{gnatclean}
18441
18442 @noindent
18443 @code{gnatclean} recognizes the following switches:
18444
18445 @table @option
18446 @c !sort!
18447 @cindex @option{--version} @command{gnatclean}
18448 Display Copyright and version, then exit disregarding all other options.
18449
18450 @item --help
18451 @cindex @option{--help} @command{gnatclean}
18452 If @option{--version} was not used, display usage, then exit disregarding
18453 all other options.
18454
18455 @item ^-c^/COMPILER_FILES_ONLY^
18456 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
18457 Only attempt to delete the files produced by the compiler, not those produced
18458 by the binder or the linker. The files that are not to be deleted are library
18459 files, interface copy files, binder generated files and executable files.
18460
18461 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
18462 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
18463 Indicate that ALI and object files should normally be found in directory
18464 @var{dir}.
18465
18466 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
18467 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
18468 When using project files, if some errors or warnings are detected during
18469 parsing and verbose mode is not in effect (no use of switch
18470 ^-v^/VERBOSE^), then error lines start with the full path name of the project
18471 file, rather than its simple file name.
18472
18473 @item ^-h^/HELP^
18474 @cindex @option{^-h^/HELP^} (@code{gnatclean})
18475 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
18476
18477 @item ^-n^/NODELETE^
18478 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
18479 Informative-only mode. Do not delete any files. Output the list of the files
18480 that would have been deleted if this switch was not specified.
18481
18482 @item ^-P^/PROJECT_FILE=^@var{project}
18483 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
18484 Use project file @var{project}. Only one such switch can be used.
18485 When cleaning a project file, the files produced by the compilation of the
18486 immediate sources or inherited sources of the project files are to be
18487 deleted. This is not depending on the presence or not of executable names
18488 on the command line.
18489
18490 @item ^-q^/QUIET^
18491 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
18492 Quiet output. If there are no errors, do not output anything, except in
18493 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
18494 (switch ^-n^/NODELETE^).
18495
18496 @item ^-r^/RECURSIVE^
18497 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
18498 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
18499 clean all imported and extended project files, recursively. If this switch
18500 is not specified, only the files related to the main project file are to be
18501 deleted. This switch has no effect if no project file is specified.
18502
18503 @item ^-v^/VERBOSE^
18504 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
18505 Verbose mode.
18506
18507 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
18508 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
18509 Indicates the verbosity of the parsing of GNAT project files.
18510 @xref{Switches Related to Project Files}.
18511
18512 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
18513 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
18514 Indicates that external variable @var{name} has the value @var{value}.
18515 The Project Manager will use this value for occurrences of
18516 @code{external(name)} when parsing the project file.
18517 @xref{Switches Related to Project Files}.
18518
18519 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18520 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
18521 When searching for ALI and object files, look in directory
18522 @var{dir}.
18523
18524 @item ^-I^/SEARCH=^@var{dir}
18525 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
18526 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
18527
18528 @item ^-I-^/NOCURRENT_DIRECTORY^
18529 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
18530 @cindex Source files, suppressing search
18531 Do not look for ALI or object files in the directory
18532 where @code{gnatclean} was invoked.
18533
18534 @end table
18535
18536 @c @node Examples of gnatclean Usage
18537 @c @section Examples of @code{gnatclean} Usage
18538
18539 @ifclear vms
18540 @node GNAT and Libraries
18541 @chapter GNAT and Libraries
18542 @cindex Library, building, installing, using
18543
18544 @noindent
18545 This chapter describes how to build and use libraries with GNAT, and also shows
18546 how to recompile the GNAT run-time library. You should be familiar with the
18547 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
18548 chapter.
18549
18550 @menu
18551 * Introduction to Libraries in GNAT::
18552 * General Ada Libraries::
18553 * Stand-alone Ada Libraries::
18554 * Rebuilding the GNAT Run-Time Library::
18555 @end menu
18556
18557 @node Introduction to Libraries in GNAT
18558 @section Introduction to Libraries in GNAT
18559
18560 @noindent
18561 A library is, conceptually, a collection of objects which does not have its
18562 own main thread of execution, but rather provides certain services to the
18563 applications that use it. A library can be either statically linked with the
18564 application, in which case its code is directly included in the application,
18565 or, on platforms that support it, be dynamically linked, in which case
18566 its code is shared by all applications making use of this library.
18567
18568 GNAT supports both types of libraries.
18569 In the static case, the compiled code can be provided in different ways. The
18570 simplest approach is to provide directly the set of objects resulting from
18571 compilation of the library source files. Alternatively, you can group the
18572 objects into an archive using whatever commands are provided by the operating
18573 system. For the latter case, the objects are grouped into a shared library.
18574
18575 In the GNAT environment, a library has three types of components:
18576 @itemize @bullet
18577 @item
18578 Source files.
18579 @item
18580 @file{ALI} files.
18581 @xref{The Ada Library Information Files}.
18582 @item
18583 Object files, an archive or a shared library.
18584 @end itemize
18585
18586 @noindent
18587 A GNAT library may expose all its source files, which is useful for
18588 documentation purposes. Alternatively, it may expose only the units needed by
18589 an external user to make use of the library. That is to say, the specs
18590 reflecting the library services along with all the units needed to compile
18591 those specs, which can include generic bodies or any body implementing an
18592 inlined routine. In the case of @emph{stand-alone libraries} those exposed
18593 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
18594
18595 All compilation units comprising an application, including those in a library,
18596 need to be elaborated in an order partially defined by Ada's semantics. GNAT
18597 computes the elaboration order from the @file{ALI} files and this is why they
18598 constitute a mandatory part of GNAT libraries. Except in the case of
18599 @emph{stand-alone libraries}, where a specific library elaboration routine is
18600 produced independently of the application(s) using the library.
18601
18602 @node General Ada Libraries
18603 @section General Ada Libraries
18604
18605 @menu
18606 * Building a library::
18607 * Installing a library::
18608 * Using a library::
18609 @end menu
18610
18611 @node Building a library
18612 @subsection Building a library
18613
18614 @noindent
18615 The easiest way to build a library is to use the Project Manager,
18616 which supports a special type of project called a @emph{Library Project}
18617 (@pxref{Library Projects}).
18618
18619 A project is considered a library project, when two project-level attributes
18620 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
18621 control different aspects of library configuration, additional optional
18622 project-level attributes can be specified:
18623 @table @code
18624 @item Library_Kind
18625 This attribute controls whether the library is to be static or dynamic
18626
18627 @item Library_Version
18628 This attribute specifies the library version; this value is used
18629 during dynamic linking of shared libraries to determine if the currently
18630 installed versions of the binaries are compatible.
18631
18632 @item Library_Options
18633 @item Library_GCC
18634 These attributes specify additional low-level options to be used during
18635 library generation, and redefine the actual application used to generate
18636 library.
18637 @end table
18638
18639 @noindent
18640 The GNAT Project Manager takes full care of the library maintenance task,
18641 including recompilation of the source files for which objects do not exist
18642 or are not up to date, assembly of the library archive, and installation of
18643 the library (i.e., copying associated source, object and @file{ALI} files
18644 to the specified location).
18645
18646 Here is a simple library project file:
18647 @smallexample @c ada
18648 project My_Lib is
18649    for Source_Dirs use ("src1", "src2");
18650    for Object_Dir use "obj";
18651    for Library_Name use "mylib";
18652    for Library_Dir use "lib";
18653    for Library_Kind use "dynamic";
18654 end My_lib;
18655 @end smallexample
18656
18657 @noindent
18658 and the compilation command to build and install the library:
18659
18660 @smallexample @c ada
18661   $ gnatmake -Pmy_lib
18662 @end smallexample
18663
18664 @noindent
18665 It is not entirely trivial to perform manually all the steps required to
18666 produce a library. We recommend that you use the GNAT Project Manager
18667 for this task. In special cases where this is not desired, the necessary
18668 steps are discussed below.
18669
18670 There are various possibilities for compiling the units that make up the
18671 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
18672 with a conventional script. For simple libraries, it is also possible to create
18673 a dummy main program which depends upon all the packages that comprise the
18674 interface of the library. This dummy main program can then be given to
18675 @command{gnatmake}, which will ensure that all necessary objects are built.
18676
18677 After this task is accomplished, you should follow the standard procedure
18678 of the underlying operating system to produce the static or shared library.
18679
18680 Here is an example of such a dummy program:
18681 @smallexample @c ada
18682 @group
18683 with My_Lib.Service1;
18684 with My_Lib.Service2;
18685 with My_Lib.Service3;
18686 procedure My_Lib_Dummy is
18687 begin
18688    null;
18689 end;
18690 @end group
18691 @end smallexample
18692
18693 @noindent
18694 Here are the generic commands that will build an archive or a shared library.
18695
18696 @smallexample
18697 # compiling the library
18698 $ gnatmake -c my_lib_dummy.adb
18699
18700 # we don't need the dummy object itself
18701 $ rm my_lib_dummy.o my_lib_dummy.ali
18702
18703 # create an archive with the remaining objects
18704 $ ar rc libmy_lib.a *.o
18705 # some systems may require "ranlib" to be run as well
18706
18707 # or create a shared library
18708 $ gcc -shared -o libmy_lib.so *.o
18709 # some systems may require the code to have been compiled with -fPIC
18710
18711 # remove the object files that are now in the library
18712 $ rm *.o
18713
18714 # Make the ALI files read-only so that gnatmake will not try to
18715 # regenerate the objects that are in the library
18716 $ chmod -w *.ali
18717 @end smallexample
18718
18719 @noindent
18720 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
18721 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
18722 be accessed by the directive @option{-l@var{xxx}} at link time.
18723
18724 @node Installing a library
18725 @subsection Installing a library
18726 @cindex @code{ADA_PROJECT_PATH}
18727
18728 @noindent
18729 If you use project files, library installation is part of the library build
18730 process. Thus no further action is needed in order to make use of the
18731 libraries that are built as part of the general application build. A usable
18732 version of the library is installed in the directory specified by the
18733 @code{Library_Dir} attribute of the library project file.
18734
18735 You may want to install a library in a context different from where the library
18736 is built. This situation arises with third party suppliers, who may want
18737 to distribute a library in binary form where the user is not expected to be
18738 able to recompile the library. The simplest option in this case is to provide
18739 a project file slightly different from the one used to build the library, by
18740 using the @code{externally_built} attribute. For instance, the project
18741 file used to build the library in the previous section can be changed into the
18742 following one when the library is installed:
18743
18744 @smallexample @c projectfile
18745 project My_Lib is
18746    for Source_Dirs use ("src1", "src2");
18747    for Library_Name use "mylib";
18748    for Library_Dir use "lib";
18749    for Library_Kind use "dynamic";
18750    for Externally_Built use "true";
18751 end My_lib;
18752 @end smallexample
18753
18754 @noindent
18755 This project file assumes that the directories @file{src1},
18756 @file{src2}, and @file{lib} exist in
18757 the directory containing the project file. The @code{externally_built}
18758 attribute makes it clear to the GNAT builder that it should not attempt to
18759 recompile any of the units from this library. It allows the library provider to
18760 restrict the source set to the minimum necessary for clients to make use of the
18761 library as described in the first section of this chapter. It is the
18762 responsibility of the library provider to install the necessary sources, ALI
18763 files and libraries in the directories mentioned in the project file. For
18764 convenience, the user's library project file should be installed in a location
18765 that will be searched automatically by the GNAT
18766 builder. These are the directories referenced in the @env{ADA_PROJECT_PATH}
18767 environment variable (@pxref{Importing Projects}), and also the default GNAT
18768 library location that can be queried with @command{gnatls -v} and is usually of
18769 the form $gnat_install_root/lib/gnat.
18770
18771 When project files are not an option, it is also possible, but not recommended,
18772 to install the library so that the sources needed to use the library are on the
18773 Ada source path and the ALI files & libraries be on the Ada Object path (see
18774 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
18775 administrator can place general-purpose libraries in the default compiler
18776 paths, by specifying the libraries' location in the configuration files
18777 @file{ada_source_path} and @file{ada_object_path}. These configuration files
18778 must be located in the GNAT installation tree at the same place as the gcc spec
18779 file. The location of the gcc spec file can be determined as follows:
18780 @smallexample
18781 $ gcc -v
18782 @end smallexample
18783
18784 @noindent
18785 The configuration files mentioned above have a simple format: each line
18786 must contain one unique directory name.
18787 Those names are added to the corresponding path
18788 in their order of appearance in the file. The names can be either absolute
18789 or relative; in the latter case, they are relative to where theses files
18790 are located.
18791
18792 The files @file{ada_source_path} and @file{ada_object_path} might not be
18793 present in a
18794 GNAT installation, in which case, GNAT will look for its run-time library in
18795 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
18796 objects and @file{ALI} files). When the files exist, the compiler does not
18797 look in @file{adainclude} and @file{adalib}, and thus the
18798 @file{ada_source_path} file
18799 must contain the location for the GNAT run-time sources (which can simply
18800 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
18801 contain the location for the GNAT run-time objects (which can simply
18802 be @file{adalib}).
18803
18804 You can also specify a new default path to the run-time library at compilation
18805 time with the switch @option{--RTS=rts-path}. You can thus choose / change
18806 the run-time library you want your program to be compiled with. This switch is
18807 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
18808 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
18809
18810 It is possible to install a library before or after the standard GNAT
18811 library, by reordering the lines in the configuration files. In general, a
18812 library must be installed before the GNAT library if it redefines
18813 any part of it.
18814
18815 @node Using a library
18816 @subsection Using a library
18817
18818 @noindent Once again, the project facility greatly simplifies the use of
18819 libraries. In this context, using a library is just a matter of adding a
18820 @code{with} clause in the user project. For instance, to make use of the
18821 library @code{My_Lib} shown in examples in earlier sections, you can
18822 write:
18823
18824 @smallexample @c projectfile
18825 with "my_lib";
18826 project My_Proj is
18827   @dots{}
18828 end My_Proj;
18829 @end smallexample
18830
18831 Even if you have a third-party, non-Ada library, you can still use GNAT's
18832 Project Manager facility to provide a wrapper for it. For example, the
18833 following project, when @code{with}ed by your main project, will link with the
18834 third-party library @file{liba.a}:
18835
18836 @smallexample @c projectfile
18837 @group
18838 project Liba is
18839    for Externally_Built use "true";
18840    for Source_Files use ();
18841    for Library_Dir use "lib";
18842    for Library_Name use "a";
18843    for Library_Kind use "static";
18844 end Liba;
18845 @end group
18846 @end smallexample
18847 This is an alternative to the use of @code{pragma Linker_Options}. It is
18848 especially interesting in the context of systems with several interdependent
18849 static libraries where finding a proper linker order is not easy and best be
18850 left to the tools having visibility over project dependence information.
18851
18852 @noindent
18853 In order to use an Ada library manually, you need to make sure that this
18854 library is on both your source and object path
18855 (see @ref{Search Paths and the Run-Time Library (RTL)}
18856 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
18857 in an archive or a shared library, you need to specify the desired
18858 library at link time.
18859
18860 For example, you can use the library @file{mylib} installed in
18861 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
18862
18863 @smallexample
18864 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
18865   -largs -lmy_lib
18866 @end smallexample
18867
18868 @noindent
18869 This can be expressed more simply:
18870 @smallexample
18871 $ gnatmake my_appl
18872 @end smallexample
18873 @noindent
18874 when the following conditions are met:
18875 @itemize @bullet
18876 @item
18877 @file{/dir/my_lib_src} has been added by the user to the environment
18878 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
18879 @file{ada_source_path}
18880 @item
18881 @file{/dir/my_lib_obj} has been added by the user to the environment
18882 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
18883 @file{ada_object_path}
18884 @item
18885 a pragma @code{Linker_Options} has been added to one of the sources.
18886 For example:
18887
18888 @smallexample @c ada
18889 pragma Linker_Options ("-lmy_lib");
18890 @end smallexample
18891 @end itemize
18892
18893 @node Stand-alone Ada Libraries
18894 @section Stand-alone Ada Libraries
18895 @cindex Stand-alone library, building, using
18896
18897 @menu
18898 * Introduction to Stand-alone Libraries::
18899 * Building a Stand-alone Library::
18900 * Creating a Stand-alone Library to be used in a non-Ada context::
18901 * Restrictions in Stand-alone Libraries::
18902 @end menu
18903
18904 @node Introduction to Stand-alone Libraries
18905 @subsection Introduction to Stand-alone Libraries
18906
18907 @noindent
18908 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
18909 necessary code to
18910 elaborate the Ada units that are included in the library. In contrast with
18911 an ordinary library, which consists of all sources, objects and @file{ALI}
18912 files of the
18913 library, a SAL may specify a restricted subset of compilation units
18914 to serve as a library interface. In this case, the fully
18915 self-sufficient set of files will normally consist of an objects
18916 archive, the sources of interface units' specs, and the @file{ALI}
18917 files of interface units.
18918 If an interface spec contains a generic unit or an inlined subprogram,
18919 the body's
18920 source must also be provided; if the units that must be provided in the source
18921 form depend on other units, the source and @file{ALI} files of those must
18922 also be provided.
18923
18924 The main purpose of a SAL is to minimize the recompilation overhead of client
18925 applications when a new version of the library is installed. Specifically,
18926 if the interface sources have not changed, client applications do not need to
18927 be recompiled. If, furthermore, a SAL is provided in the shared form and its
18928 version, controlled by @code{Library_Version} attribute, is not changed,
18929 then the clients do not need to be relinked.
18930
18931 SALs also allow the library providers to minimize the amount of library source
18932 text exposed to the clients.  Such ``information hiding'' might be useful or
18933 necessary for various reasons.
18934
18935 Stand-alone libraries are also well suited to be used in an executable whose
18936 main routine is not written in Ada.
18937
18938 @node Building a Stand-alone Library
18939 @subsection Building a Stand-alone Library
18940
18941 @noindent
18942 GNAT's Project facility provides a simple way of building and installing
18943 stand-alone libraries; see @ref{Stand-alone Library Projects}.
18944 To be a Stand-alone Library Project, in addition to the two attributes
18945 that make a project a Library Project (@code{Library_Name} and
18946 @code{Library_Dir}; see @ref{Library Projects}), the attribute
18947 @code{Library_Interface} must be defined.  For example:
18948
18949 @smallexample @c projectfile
18950 @group
18951    for Library_Dir use "lib_dir";
18952    for Library_Name use "dummy";
18953    for Library_Interface use ("int1", "int1.child");
18954 @end group
18955 @end smallexample
18956
18957 @noindent
18958 Attribute @code{Library_Interface} has a non-empty string list value,
18959 each string in the list designating a unit contained in an immediate source
18960 of the project file.
18961
18962 When a Stand-alone Library is built, first the binder is invoked to build
18963 a package whose name depends on the library name
18964 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
18965 This binder-generated package includes initialization and
18966 finalization procedures whose
18967 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
18968 in the example
18969 above). The object corresponding to this package is included in the library.
18970
18971 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
18972 calling of these procedures if a static SAL is built, or if a shared SAL
18973 is built
18974 with the project-level attribute @code{Library_Auto_Init} set to
18975 @code{"false"}.
18976
18977 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
18978 (those that are listed in attribute @code{Library_Interface}) are copied to
18979 the Library Directory. As a consequence, only the Interface Units may be
18980 imported from Ada units outside of the library. If other units are imported,
18981 the binding phase will fail.
18982
18983 The attribute @code{Library_Src_Dir} may be specified for a
18984 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
18985 single string value. Its value must be the path (absolute or relative to the
18986 project directory) of an existing directory. This directory cannot be the
18987 object directory or one of the source directories, but it can be the same as
18988 the library directory. The sources of the Interface
18989 Units of the library that are needed by an Ada client of the library will be
18990 copied to the designated directory, called the Interface Copy directory.
18991 These sources include the specs of the Interface Units, but they may also
18992 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
18993 are used, or when there is a generic unit in the spec. Before the sources
18994 are copied to the Interface Copy directory, an attempt is made to delete all
18995 files in the Interface Copy directory.
18996
18997 Building stand-alone libraries by hand is somewhat tedious, but for those
18998 occasions when it is necessary here are the steps that you need to perform:
18999 @itemize @bullet
19000 @item
19001 Compile all library sources.
19002
19003 @item
19004 Invoke the binder with the switch @option{-n} (No Ada main program),
19005 with all the @file{ALI} files of the interfaces, and
19006 with the switch @option{-L} to give specific names to the @code{init}
19007 and @code{final} procedures.  For example:
19008 @smallexample
19009   gnatbind -n int1.ali int2.ali -Lsal1
19010 @end smallexample
19011
19012 @item
19013 Compile the binder generated file:
19014 @smallexample
19015   gcc -c b~int2.adb
19016 @end smallexample
19017
19018 @item
19019 Link the dynamic library with all the necessary object files,
19020 indicating to the linker the names of the @code{init} (and possibly
19021 @code{final}) procedures for automatic initialization (and finalization).
19022 The built library should be placed in a directory different from
19023 the object directory.
19024
19025 @item
19026 Copy the @code{ALI} files of the interface to the library directory,
19027 add in this copy an indication that it is an interface to a SAL
19028 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
19029 with letter ``P'') and make the modified copy of the @file{ALI} file
19030 read-only.
19031 @end itemize
19032
19033 @noindent
19034 Using SALs is not different from using other libraries
19035 (see @ref{Using a library}).
19036
19037 @node Creating a Stand-alone Library to be used in a non-Ada context
19038 @subsection Creating a Stand-alone Library to be used in a non-Ada context
19039
19040 @noindent
19041 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
19042 a non-Ada context.
19043
19044 The only extra step required is to ensure that library interface subprograms
19045 are compatible with the main program, by means of @code{pragma Export}
19046 or @code{pragma Convention}.
19047
19048 Here is an example of simple library interface for use with C main program:
19049
19050 @smallexample @c ada
19051 package Interface is
19052
19053    procedure Do_Something;
19054    pragma Export (C, Do_Something, "do_something");
19055
19056    procedure Do_Something_Else;
19057    pragma Export (C, Do_Something_Else, "do_something_else");
19058
19059 end Interface;
19060 @end smallexample
19061
19062 @noindent
19063 On the foreign language side, you must provide a ``foreign'' view of the
19064 library interface; remember that it should contain elaboration routines in
19065 addition to interface subprograms.
19066
19067 The example below shows the content of @code{mylib_interface.h} (note
19068 that there is no rule for the naming of this file, any name can be used)
19069 @smallexample
19070 /* the library elaboration procedure */
19071 extern void mylibinit (void);
19072
19073 /* the library finalization procedure */
19074 extern void mylibfinal (void);
19075
19076 /* the interface exported by the library */
19077 extern void do_something (void);
19078 extern void do_something_else (void);
19079 @end smallexample
19080
19081 @noindent
19082 Libraries built as explained above can be used from any program, provided
19083 that the elaboration procedures (named @code{mylibinit} in the previous
19084 example) are called before the library services are used. Any number of
19085 libraries can be used simultaneously, as long as the elaboration
19086 procedure of each library is called.
19087
19088 Below is an example of a C program that uses the @code{mylib} library.
19089
19090 @smallexample
19091 #include "mylib_interface.h"
19092
19093 int
19094 main (void)
19095 @{
19096    /* First, elaborate the library before using it */
19097    mylibinit ();
19098
19099    /* Main program, using the library exported entities */
19100    do_something ();
19101    do_something_else ();
19102
19103    /* Library finalization at the end of the program */
19104    mylibfinal ();
19105    return 0;
19106 @}
19107 @end smallexample
19108
19109 @noindent
19110 Note that invoking any library finalization procedure generated by
19111 @code{gnatbind} shuts down the Ada run-time environment.
19112 Consequently, the
19113 finalization of all Ada libraries must be performed at the end of the program.
19114 No call to these libraries or to the Ada run-time library should be made
19115 after the finalization phase.
19116
19117 @node Restrictions in Stand-alone Libraries
19118 @subsection Restrictions in Stand-alone Libraries
19119
19120 @noindent
19121 The pragmas listed below should be used with caution inside libraries,
19122 as they can create incompatibilities with other Ada libraries:
19123 @itemize @bullet
19124 @item pragma @code{Locking_Policy}
19125 @item pragma @code{Queuing_Policy}
19126 @item pragma @code{Task_Dispatching_Policy}
19127 @item pragma @code{Unreserve_All_Interrupts}
19128 @end itemize
19129
19130 @noindent
19131 When using a library that contains such pragmas, the user must make sure
19132 that all libraries use the same pragmas with the same values. Otherwise,
19133 @code{Program_Error} will
19134 be raised during the elaboration of the conflicting
19135 libraries. The usage of these pragmas and its consequences for the user
19136 should therefore be well documented.
19137
19138 Similarly, the traceback in the exception occurrence mechanism should be
19139 enabled or disabled in a consistent manner across all libraries.
19140 Otherwise, Program_Error will be raised during the elaboration of the
19141 conflicting libraries.
19142
19143 If the @code{Version} or @code{Body_Version}
19144 attributes are used inside a library, then you need to
19145 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
19146 libraries, so that version identifiers can be properly computed.
19147 In practice these attributes are rarely used, so this is unlikely
19148 to be a consideration.
19149
19150 @node  Rebuilding the GNAT Run-Time Library
19151 @section Rebuilding the GNAT Run-Time Library
19152 @cindex GNAT Run-Time Library, rebuilding
19153 @cindex Building the GNAT Run-Time Library
19154 @cindex Rebuilding the GNAT Run-Time Library
19155 @cindex Run-Time Library, rebuilding
19156
19157 @noindent
19158 It may be useful to recompile the GNAT library in various contexts, the
19159 most important one being the use of partition-wide configuration pragmas
19160 such as @code{Normalize_Scalars}. A special Makefile called
19161 @code{Makefile.adalib} is provided to that effect and can be found in
19162 the directory containing the GNAT library. The location of this
19163 directory depends on the way the GNAT environment has been installed and can
19164 be determined by means of the command:
19165
19166 @smallexample
19167 $ gnatls -v
19168 @end smallexample
19169
19170 @noindent
19171 The last entry in the object search path usually contains the
19172 gnat library. This Makefile contains its own documentation and in
19173 particular the set of instructions needed to rebuild a new library and
19174 to use it.
19175
19176 @node Using the GNU make Utility
19177 @chapter Using the GNU @code{make} Utility
19178 @findex make
19179
19180 @noindent
19181 This chapter offers some examples of makefiles that solve specific
19182 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
19183 make, make, GNU @code{make}}), nor does it try to replace the
19184 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
19185
19186 All the examples in this section are specific to the GNU version of
19187 make. Although @command{make} is a standard utility, and the basic language
19188 is the same, these examples use some advanced features found only in
19189 @code{GNU make}.
19190
19191 @menu
19192 * Using gnatmake in a Makefile::
19193 * Automatically Creating a List of Directories::
19194 * Generating the Command Line Switches::
19195 * Overcoming Command Line Length Limits::
19196 @end menu
19197
19198 @node Using gnatmake in a Makefile
19199 @section Using gnatmake in a Makefile
19200 @findex makefile
19201 @cindex GNU make
19202
19203 @noindent
19204 Complex project organizations can be handled in a very powerful way by
19205 using GNU make combined with gnatmake. For instance, here is a Makefile
19206 which allows you to build each subsystem of a big project into a separate
19207 shared library. Such a makefile allows you to significantly reduce the link
19208 time of very big applications while maintaining full coherence at
19209 each step of the build process.
19210
19211 The list of dependencies are handled automatically by
19212 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
19213 the appropriate directories.
19214
19215 Note that you should also read the example on how to automatically
19216 create the list of directories
19217 (@pxref{Automatically Creating a List of Directories})
19218 which might help you in case your project has a lot of subdirectories.
19219
19220 @smallexample
19221 @iftex
19222 @leftskip=0cm
19223 @font@heightrm=cmr8
19224 @heightrm
19225 @end iftex
19226 ## This Makefile is intended to be used with the following directory
19227 ## configuration:
19228 ##  - The sources are split into a series of csc (computer software components)
19229 ##    Each of these csc is put in its own directory.
19230 ##    Their name are referenced by the directory names.
19231 ##    They will be compiled into shared library (although this would also work
19232 ##    with static libraries
19233 ##  - The main program (and possibly other packages that do not belong to any
19234 ##    csc is put in the top level directory (where the Makefile is).
19235 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
19236 ##                    \_ second_csc (sources) __ lib (will contain the library)
19237 ##                    \_ @dots{}
19238 ## Although this Makefile is build for shared library, it is easy to modify
19239 ## to build partial link objects instead (modify the lines with -shared and
19240 ## gnatlink below)
19241 ##
19242 ## With this makefile, you can change any file in the system or add any new
19243 ## file, and everything will be recompiled correctly (only the relevant shared
19244 ## objects will be recompiled, and the main program will be re-linked).
19245
19246 # The list of computer software component for your project. This might be
19247 # generated automatically.
19248 CSC_LIST=aa bb cc
19249
19250 # Name of the main program (no extension)
19251 MAIN=main
19252
19253 # If we need to build objects with -fPIC, uncomment the following line
19254 #NEED_FPIC=-fPIC
19255
19256 # The following variable should give the directory containing libgnat.so
19257 # You can get this directory through 'gnatls -v'. This is usually the last
19258 # directory in the Object_Path.
19259 GLIB=@dots{}
19260
19261 # The directories for the libraries
19262 # (This macro expands the list of CSC to the list of shared libraries, you
19263 # could simply use the expanded form:
19264 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
19265 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
19266
19267 $@{MAIN@}: objects $@{LIB_DIR@}
19268     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
19269     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
19270
19271 objects::
19272     # recompile the sources
19273     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
19274
19275 # Note: In a future version of GNAT, the following commands will be simplified
19276 # by a new tool, gnatmlib
19277 $@{LIB_DIR@}:
19278     mkdir -p $@{dir $@@ @}
19279     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
19280     cd $@{dir $@@ @} && cp -f ../*.ali .
19281
19282 # The dependencies for the modules
19283 # Note that we have to force the expansion of *.o, since in some cases
19284 # make won't be able to do it itself.
19285 aa/lib/libaa.so: $@{wildcard aa/*.o@}
19286 bb/lib/libbb.so: $@{wildcard bb/*.o@}
19287 cc/lib/libcc.so: $@{wildcard cc/*.o@}
19288
19289 # Make sure all of the shared libraries are in the path before starting the
19290 # program
19291 run::
19292     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
19293
19294 clean::
19295     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
19296     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
19297     $@{RM@} $@{CSC_LIST:%=%/*.o@}
19298     $@{RM@} *.o *.ali $@{MAIN@}
19299 @end smallexample
19300
19301 @node Automatically Creating a List of Directories
19302 @section Automatically Creating a List of Directories
19303
19304 @noindent
19305 In most makefiles, you will have to specify a list of directories, and
19306 store it in a variable. For small projects, it is often easier to
19307 specify each of them by hand, since you then have full control over what
19308 is the proper order for these directories, which ones should be
19309 included.
19310
19311 However, in larger projects, which might involve hundreds of
19312 subdirectories, it might be more convenient to generate this list
19313 automatically.
19314
19315 The example below presents two methods. The first one, although less
19316 general, gives you more control over the list. It involves wildcard
19317 characters, that are automatically expanded by @command{make}. Its
19318 shortcoming is that you need to explicitly specify some of the
19319 organization of your project, such as for instance the directory tree
19320 depth, whether some directories are found in a separate tree, @enddots{}
19321
19322 The second method is the most general one. It requires an external
19323 program, called @command{find}, which is standard on all Unix systems. All
19324 the directories found under a given root directory will be added to the
19325 list.
19326
19327 @smallexample
19328 @iftex
19329 @leftskip=0cm
19330 @font@heightrm=cmr8
19331 @heightrm
19332 @end iftex
19333 # The examples below are based on the following directory hierarchy:
19334 # All the directories can contain any number of files
19335 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
19336 #                       ->  ab
19337 #                       ->  ac
19338 #                ->  b  ->  ba  ->  baa
19339 #                       ->  bb
19340 #                       ->  bc
19341 # This Makefile creates a variable called DIRS, that can be reused any time
19342 # you need this list (see the other examples in this section)
19343
19344 # The root of your project's directory hierarchy
19345 ROOT_DIRECTORY=.
19346
19347 ####
19348 # First method: specify explicitly the list of directories
19349 # This allows you to specify any subset of all the directories you need.
19350 ####
19351
19352 DIRS := a/aa/ a/ab/ b/ba/
19353
19354 ####
19355 # Second method: use wildcards
19356 # Note that the argument(s) to wildcard below should end with a '/'.
19357 # Since wildcards also return file names, we have to filter them out
19358 # to avoid duplicate directory names.
19359 # We thus use make's @code{dir} and @code{sort} functions.
19360 # It sets DIRs to the following value (note that the directories aaa and baa
19361 # are not given, unless you change the arguments to wildcard).
19362 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
19363 ####
19364
19365 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
19366                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
19367
19368 ####
19369 # Third method: use an external program
19370 # This command is much faster if run on local disks, avoiding NFS slowdowns.
19371 # This is the most complete command: it sets DIRs to the following value:
19372 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
19373 ####
19374
19375 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
19376
19377 @end smallexample
19378
19379 @node Generating the Command Line Switches
19380 @section Generating the Command Line Switches
19381
19382 @noindent
19383 Once you have created the list of directories as explained in the
19384 previous section (@pxref{Automatically Creating a List of Directories}),
19385 you can easily generate the command line arguments to pass to gnatmake.
19386
19387 For the sake of completeness, this example assumes that the source path
19388 is not the same as the object path, and that you have two separate lists
19389 of directories.
19390
19391 @smallexample
19392 # see "Automatically creating a list of directories" to create
19393 # these variables
19394 SOURCE_DIRS=
19395 OBJECT_DIRS=
19396
19397 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
19398 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
19399
19400 all:
19401         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
19402 @end smallexample
19403
19404 @node Overcoming Command Line Length Limits
19405 @section Overcoming Command Line Length Limits
19406
19407 @noindent
19408 One problem that might be encountered on big projects is that many
19409 operating systems limit the length of the command line. It is thus hard to give
19410 gnatmake the list of source and object directories.
19411
19412 This example shows how you can set up environment variables, which will
19413 make @command{gnatmake} behave exactly as if the directories had been
19414 specified on the command line, but have a much higher length limit (or
19415 even none on most systems).
19416
19417 It assumes that you have created a list of directories in your Makefile,
19418 using one of the methods presented in
19419 @ref{Automatically Creating a List of Directories}.
19420 For the sake of completeness, we assume that the object
19421 path (where the ALI files are found) is different from the sources patch.
19422
19423 Note a small trick in the Makefile below: for efficiency reasons, we
19424 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
19425 expanded immediately by @code{make}. This way we overcome the standard
19426 make behavior which is to expand the variables only when they are
19427 actually used.
19428
19429 On Windows, if you are using the standard Windows command shell, you must
19430 replace colons with semicolons in the assignments to these variables.
19431
19432 @smallexample
19433 @iftex
19434 @leftskip=0cm
19435 @font@heightrm=cmr8
19436 @heightrm
19437 @end iftex
19438 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
19439 # This is the same thing as putting the -I arguments on the command line.
19440 # (the equivalent of using -aI on the command line would be to define
19441 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
19442 # You can of course have different values for these variables.
19443 #
19444 # Note also that we need to keep the previous values of these variables, since
19445 # they might have been set before running 'make' to specify where the GNAT
19446 # library is installed.
19447
19448 # see "Automatically creating a list of directories" to create these
19449 # variables
19450 SOURCE_DIRS=
19451 OBJECT_DIRS=
19452
19453 empty:=
19454 space:=$@{empty@} $@{empty@}
19455 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
19456 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
19457 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
19458 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
19459 export ADA_INCLUDE_PATH
19460 export ADA_OBJECT_PATH
19461
19462 all:
19463         gnatmake main_unit
19464 @end smallexample
19465 @end ifclear
19466
19467 @node Memory Management Issues
19468 @chapter Memory Management Issues
19469
19470 @noindent
19471 This chapter describes some useful memory pools provided in the GNAT library
19472 and in particular the GNAT Debug Pool facility, which can be used to detect
19473 incorrect uses of access values (including ``dangling references'').
19474 @ifclear vms
19475 It also describes the @command{gnatmem} tool, which can be used to track down
19476 ``memory leaks''.
19477 @end ifclear
19478
19479 @menu
19480 * Some Useful Memory Pools::
19481 * The GNAT Debug Pool Facility::
19482 @ifclear vms
19483 * The gnatmem Tool::
19484 @end ifclear
19485 @end menu
19486
19487 @node Some Useful Memory Pools
19488 @section Some Useful Memory Pools
19489 @findex Memory Pool
19490 @cindex storage, pool
19491
19492 @noindent
19493 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
19494 storage pool. Allocations use the standard system call @code{malloc} while
19495 deallocations use the standard system call @code{free}. No reclamation is
19496 performed when the pool goes out of scope. For performance reasons, the
19497 standard default Ada allocators/deallocators do not use any explicit storage
19498 pools but if they did, they could use this storage pool without any change in
19499 behavior. That is why this storage pool is used  when the user
19500 manages to make the default implicit allocator explicit as in this example:
19501 @smallexample @c ada
19502    type T1 is access Something;
19503     -- no Storage pool is defined for T2
19504    type T2 is access Something_Else;
19505    for T2'Storage_Pool use T1'Storage_Pool;
19506    -- the above is equivalent to
19507    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
19508 @end smallexample
19509
19510 @noindent
19511 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
19512 pool. The allocation strategy is similar to @code{Pool_Local}'s
19513 except that the all
19514 storage allocated with this pool is reclaimed when the pool object goes out of
19515 scope. This pool provides a explicit mechanism similar to the implicit one
19516 provided by several Ada 83 compilers for allocations performed through a local
19517 access type and whose purpose was to reclaim memory when exiting the
19518 scope of a given local access. As an example, the following program does not
19519 leak memory even though it does not perform explicit deallocation:
19520
19521 @smallexample @c ada
19522 with System.Pool_Local;
19523 procedure Pooloc1 is
19524    procedure Internal is
19525       type A is access Integer;
19526       X : System.Pool_Local.Unbounded_Reclaim_Pool;
19527       for A'Storage_Pool use X;
19528       v : A;
19529    begin
19530       for I in  1 .. 50 loop
19531          v := new Integer;
19532       end loop;
19533    end Internal;
19534 begin
19535    for I in  1 .. 100 loop
19536       Internal;
19537    end loop;
19538 end Pooloc1;
19539 @end smallexample
19540
19541 @noindent
19542 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
19543 @code{Storage_Size} is specified for an access type.
19544 The whole storage for the pool is
19545 allocated at once, usually on the stack at the point where the access type is
19546 elaborated. It is automatically reclaimed when exiting the scope where the
19547 access type is defined. This package is not intended to be used directly by the
19548 user and it is implicitly used for each such declaration:
19549
19550 @smallexample @c ada
19551    type T1 is access Something;
19552    for T1'Storage_Size use 10_000;
19553 @end smallexample
19554
19555 @node The GNAT Debug Pool Facility
19556 @section The GNAT Debug Pool Facility
19557 @findex Debug Pool
19558 @cindex storage, pool, memory corruption
19559
19560 @noindent
19561 The use of unchecked deallocation and unchecked conversion can easily
19562 lead to incorrect memory references. The problems generated by such
19563 references are usually difficult to tackle because the symptoms can be
19564 very remote from the origin of the problem. In such cases, it is
19565 very helpful to detect the problem as early as possible. This is the
19566 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
19567
19568 In order to use the GNAT specific debugging pool, the user must
19569 associate a debug pool object with each of the access types that may be
19570 related to suspected memory problems. See Ada Reference Manual 13.11.
19571 @smallexample @c ada
19572 type Ptr is access Some_Type;
19573 Pool : GNAT.Debug_Pools.Debug_Pool;
19574 for Ptr'Storage_Pool use Pool;
19575 @end smallexample
19576
19577 @noindent
19578 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
19579 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
19580 allow the user to redefine allocation and deallocation strategies. They
19581 also provide a checkpoint for each dereference, through the use of
19582 the primitive operation @code{Dereference} which is implicitly called at
19583 each dereference of an access value.
19584
19585 Once an access type has been associated with a debug pool, operations on
19586 values of the type may raise four distinct exceptions,
19587 which correspond to four potential kinds of memory corruption:
19588 @itemize @bullet
19589 @item
19590 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
19591 @item
19592 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
19593 @item
19594 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
19595 @item
19596 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
19597 @end itemize
19598
19599 @noindent
19600 For types associated with a Debug_Pool, dynamic allocation is performed using
19601 the standard GNAT allocation routine. References to all allocated chunks of
19602 memory are kept in an internal dictionary. Several deallocation strategies are
19603 provided, whereupon the user can choose to release the memory to the system,
19604 keep it allocated for further invalid access checks, or fill it with an easily
19605 recognizable pattern for debug sessions. The memory pattern is the old IBM
19606 hexadecimal convention: @code{16#DEADBEEF#}.
19607
19608 See the documentation in the file g-debpoo.ads for more information on the
19609 various strategies.
19610
19611 Upon each dereference, a check is made that the access value denotes a
19612 properly allocated memory location. Here is a complete example of use of
19613 @code{Debug_Pools}, that includes typical instances of  memory corruption:
19614 @smallexample @c ada
19615 @iftex
19616 @leftskip=0cm
19617 @end iftex
19618 with Gnat.Io; use Gnat.Io;
19619 with Unchecked_Deallocation;
19620 with Unchecked_Conversion;
19621 with GNAT.Debug_Pools;
19622 with System.Storage_Elements;
19623 with Ada.Exceptions; use Ada.Exceptions;
19624 procedure Debug_Pool_Test is
19625
19626    type T is access Integer;
19627    type U is access all T;
19628
19629    P : GNAT.Debug_Pools.Debug_Pool;
19630    for T'Storage_Pool use P;
19631
19632    procedure Free is new Unchecked_Deallocation (Integer, T);
19633    function UC is new Unchecked_Conversion (U, T);
19634    A, B : aliased T;
19635
19636    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
19637
19638 begin
19639    Info (P);
19640    A := new Integer;
19641    B := new Integer;
19642    B := A;
19643    Info (P);
19644    Free (A);
19645    begin
19646       Put_Line (Integer'Image(B.all));
19647    exception
19648       when E : others => Put_Line ("raised: " & Exception_Name (E));
19649    end;
19650    begin
19651       Free (B);
19652    exception
19653       when E : others => Put_Line ("raised: " & Exception_Name (E));
19654    end;
19655    B := UC(A'Access);
19656    begin
19657       Put_Line (Integer'Image(B.all));
19658    exception
19659       when E : others => Put_Line ("raised: " & Exception_Name (E));
19660    end;
19661    begin
19662       Free (B);
19663    exception
19664       when E : others => Put_Line ("raised: " & Exception_Name (E));
19665    end;
19666    Info (P);
19667 end Debug_Pool_Test;
19668 @end smallexample
19669
19670 @noindent
19671 The debug pool mechanism provides the following precise diagnostics on the
19672 execution of this erroneous program:
19673 @smallexample
19674 Debug Pool info:
19675   Total allocated bytes :  0
19676   Total deallocated bytes :  0
19677   Current Water Mark:  0
19678   High Water Mark:  0
19679
19680 Debug Pool info:
19681   Total allocated bytes :  8
19682   Total deallocated bytes :  0
19683   Current Water Mark:  8
19684   High Water Mark:  8
19685
19686 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
19687 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
19688 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
19689 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
19690 Debug Pool info:
19691   Total allocated bytes :  8
19692   Total deallocated bytes :  4
19693   Current Water Mark:  4
19694   High Water Mark:  8
19695 @end smallexample
19696
19697 @ifclear vms
19698 @node The gnatmem Tool
19699 @section The @command{gnatmem} Tool
19700 @findex gnatmem
19701
19702 @noindent
19703 The @code{gnatmem} utility monitors dynamic allocation and
19704 deallocation activity in a program, and displays information about
19705 incorrect deallocations and possible sources of memory leaks.
19706 It provides three type of information:
19707 @itemize @bullet
19708 @item
19709 General information concerning memory management, such as the total
19710 number of allocations and deallocations, the amount of allocated
19711 memory and the high water mark, i.e.@: the largest amount of allocated
19712 memory in the course of program execution.
19713
19714 @item
19715 Backtraces for all incorrect deallocations, that is to say deallocations
19716 which do not correspond to a valid allocation.
19717
19718 @item
19719 Information on each allocation that is potentially the origin of a memory
19720 leak.
19721 @end itemize
19722
19723 @menu
19724 * Running gnatmem::
19725 * Switches for gnatmem::
19726 * Example of gnatmem Usage::
19727 @end menu
19728
19729 @node Running gnatmem
19730 @subsection Running @code{gnatmem}
19731
19732 @noindent
19733 @code{gnatmem} makes use of the output created by the special version of
19734 allocation and deallocation routines that record call information. This
19735 allows to obtain accurate dynamic memory usage history at a minimal cost to
19736 the execution speed. Note however, that @code{gnatmem} is not supported on
19737 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
19738 Solaris and Windows NT/2000/XP (x86).
19739
19740 @noindent
19741 The @code{gnatmem} command has the form
19742
19743 @smallexample
19744    $ gnatmem @ovar{switches} user_program
19745 @end smallexample
19746
19747 @noindent
19748 The program must have been linked with the instrumented version of the
19749 allocation and deallocation routines. This is done by linking with the
19750 @file{libgmem.a} library. For correct symbolic backtrace information,
19751 the user program should be compiled with debugging options
19752 (see @ref{Switches for gcc}). For example to build @file{my_program}:
19753
19754 @smallexample
19755 $ gnatmake -g my_program -largs -lgmem
19756 @end smallexample
19757
19758 @noindent
19759 As library @file{libgmem.a} contains an alternate body for package
19760 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
19761 when an executable is linked with library @file{libgmem.a}. It is then not
19762 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
19763
19764 @noindent
19765 When @file{my_program} is executed, the file @file{gmem.out} is produced.
19766 This file contains information about all allocations and deallocations
19767 performed by the program. It is produced by the instrumented allocations and
19768 deallocations routines and will be used by @code{gnatmem}.
19769
19770 In order to produce symbolic backtrace information for allocations and
19771 deallocations performed by the GNAT run-time library, you need to use a
19772 version of that library that has been compiled with the @option{-g} switch
19773 (see @ref{Rebuilding the GNAT Run-Time Library}).
19774
19775 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
19776 examine. If the location of @file{gmem.out} file was not explicitly supplied by
19777 @option{-i} switch, gnatmem will assume that this file can be found in the
19778 current directory. For example, after you have executed @file{my_program},
19779 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
19780
19781 @smallexample
19782 $ gnatmem my_program
19783 @end smallexample
19784
19785 @noindent
19786 This will produce the output with the following format:
19787
19788 *************** debut cc
19789 @smallexample
19790 $ gnatmem my_program
19791
19792 Global information
19793 ------------------
19794    Total number of allocations        :  45
19795    Total number of deallocations      :   6
19796    Final Water Mark (non freed mem)   :  11.29 Kilobytes
19797    High Water Mark                    :  11.40 Kilobytes
19798
19799 .
19800 .
19801 .
19802 Allocation Root # 2
19803 -------------------
19804  Number of non freed allocations    :  11
19805  Final Water Mark (non freed mem)   :   1.16 Kilobytes
19806  High Water Mark                    :   1.27 Kilobytes
19807  Backtrace                          :
19808    my_program.adb:23 my_program.alloc
19809 .
19810 .
19811 .
19812 @end smallexample
19813
19814 The first block of output gives general information. In this case, the
19815 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
19816 Unchecked_Deallocation routine occurred.
19817
19818 @noindent
19819 Subsequent paragraphs display  information on all allocation roots.
19820 An allocation root is a specific point in the execution of the program
19821 that generates some dynamic allocation, such as a ``@code{@b{new}}''
19822 construct. This root is represented by an execution backtrace (or subprogram
19823 call stack). By default the backtrace depth for allocations roots is 1, so
19824 that a root corresponds exactly to a source location. The backtrace can
19825 be made deeper, to make the root more specific.
19826
19827 @node Switches for gnatmem
19828 @subsection Switches for @code{gnatmem}
19829
19830 @noindent
19831 @code{gnatmem} recognizes the following switches:
19832
19833 @table @option
19834
19835 @item -q
19836 @cindex @option{-q} (@code{gnatmem})
19837 Quiet. Gives the minimum output needed to identify the origin of the
19838 memory leaks. Omits statistical information.
19839
19840 @item @var{N}
19841 @cindex @var{N} (@code{gnatmem})
19842 N is an integer literal (usually between 1 and 10) which controls the
19843 depth of the backtraces defining allocation root. The default value for
19844 N is 1. The deeper the backtrace, the more precise the localization of
19845 the root. Note that the total number of roots can depend on this
19846 parameter. This parameter must be specified @emph{before} the name of the
19847 executable to be analyzed, to avoid ambiguity.
19848
19849 @item -b n
19850 @cindex @option{-b} (@code{gnatmem})
19851 This switch has the same effect as just depth parameter.
19852
19853 @item -i @var{file}
19854 @cindex @option{-i} (@code{gnatmem})
19855 Do the @code{gnatmem} processing starting from @file{file}, rather than
19856 @file{gmem.out} in the current directory.
19857
19858 @item -m n
19859 @cindex @option{-m} (@code{gnatmem})
19860 This switch causes @code{gnatmem} to mask the allocation roots that have less
19861 than n leaks. The default value is 1. Specifying the value of 0 will allow to
19862 examine even the roots that didn't result in leaks.
19863
19864 @item -s order
19865 @cindex @option{-s} (@code{gnatmem})
19866 This switch causes @code{gnatmem} to sort the allocation roots according to the
19867 specified order of sort criteria, each identified by a single letter. The
19868 currently supported criteria are @code{n, h, w} standing respectively for
19869 number of unfreed allocations, high watermark, and final watermark
19870 corresponding to a specific root. The default order is @code{nwh}.
19871
19872 @end table
19873
19874 @node Example of gnatmem Usage
19875 @subsection Example of @code{gnatmem} Usage
19876
19877 @noindent
19878 The following example shows the use of @code{gnatmem}
19879 on a simple memory-leaking program.
19880 Suppose that we have the following Ada program:
19881
19882 @smallexample @c ada
19883 @group
19884 @cartouche
19885 with Unchecked_Deallocation;
19886 procedure Test_Gm is
19887
19888    type T is array (1..1000) of Integer;
19889    type Ptr is access T;
19890    procedure Free is new Unchecked_Deallocation (T, Ptr);
19891    A : Ptr;
19892
19893    procedure My_Alloc is
19894    begin
19895       A := new T;
19896    end My_Alloc;
19897
19898    procedure My_DeAlloc is
19899       B : Ptr := A;
19900    begin
19901       Free (B);
19902    end My_DeAlloc;
19903
19904 begin
19905    My_Alloc;
19906    for I in 1 .. 5 loop
19907       for J in I .. 5 loop
19908          My_Alloc;
19909       end loop;
19910       My_Dealloc;
19911    end loop;
19912 end;
19913 @end cartouche
19914 @end group
19915 @end smallexample
19916
19917 @noindent
19918 The program needs to be compiled with debugging option and linked with
19919 @code{gmem} library:
19920
19921 @smallexample
19922 $ gnatmake -g test_gm -largs -lgmem
19923 @end smallexample
19924
19925 @noindent
19926 Then we execute the program as usual:
19927
19928 @smallexample
19929 $ test_gm
19930 @end smallexample
19931
19932 @noindent
19933 Then @code{gnatmem} is invoked simply with
19934 @smallexample
19935 $ gnatmem test_gm
19936 @end smallexample
19937
19938 @noindent
19939 which produces the following output (result may vary on different platforms):
19940
19941 @smallexample
19942 Global information
19943 ------------------
19944    Total number of allocations        :  18
19945    Total number of deallocations      :   5
19946    Final Water Mark (non freed mem)   :  53.00 Kilobytes
19947    High Water Mark                    :  56.90 Kilobytes
19948
19949 Allocation Root # 1
19950 -------------------
19951  Number of non freed allocations    :  11
19952  Final Water Mark (non freed mem)   :  42.97 Kilobytes
19953  High Water Mark                    :  46.88 Kilobytes
19954  Backtrace                          :
19955    test_gm.adb:11 test_gm.my_alloc
19956
19957 Allocation Root # 2
19958 -------------------
19959  Number of non freed allocations    :   1
19960  Final Water Mark (non freed mem)   :  10.02 Kilobytes
19961  High Water Mark                    :  10.02 Kilobytes
19962  Backtrace                          :
19963    s-secsta.adb:81 system.secondary_stack.ss_init
19964
19965 Allocation Root # 3
19966 -------------------
19967  Number of non freed allocations    :   1
19968  Final Water Mark (non freed mem)   :  12 Bytes
19969  High Water Mark                    :  12 Bytes
19970  Backtrace                          :
19971    s-secsta.adb:181 system.secondary_stack.ss_init
19972 @end smallexample
19973
19974 @noindent
19975 Note that the GNAT run time contains itself a certain number of
19976 allocations that have no  corresponding deallocation,
19977 as shown here for root #2 and root
19978 #3. This is a normal behavior when the number of non-freed allocations
19979 is one, it allocates dynamic data structures that the run time needs for
19980 the complete lifetime of the program. Note also that there is only one
19981 allocation root in the user program with a single line back trace:
19982 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
19983 program shows that 'My_Alloc' is called at 2 different points in the
19984 source (line 21 and line 24). If those two allocation roots need to be
19985 distinguished, the backtrace depth parameter can be used:
19986
19987 @smallexample
19988 $ gnatmem 3 test_gm
19989 @end smallexample
19990
19991 @noindent
19992 which will give the following output:
19993
19994 @smallexample
19995 Global information
19996 ------------------
19997    Total number of allocations        :  18
19998    Total number of deallocations      :   5
19999    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20000    High Water Mark                    :  56.90 Kilobytes
20001
20002 Allocation Root # 1
20003 -------------------
20004  Number of non freed allocations    :  10
20005  Final Water Mark (non freed mem)   :  39.06 Kilobytes
20006  High Water Mark                    :  42.97 Kilobytes
20007  Backtrace                          :
20008    test_gm.adb:11 test_gm.my_alloc
20009    test_gm.adb:24 test_gm
20010    b_test_gm.c:52 main
20011
20012 Allocation Root # 2
20013 -------------------
20014  Number of non freed allocations    :   1
20015  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20016  High Water Mark                    :  10.02 Kilobytes
20017  Backtrace                          :
20018    s-secsta.adb:81  system.secondary_stack.ss_init
20019    s-secsta.adb:283 <system__secondary_stack___elabb>
20020    b_test_gm.c:33   adainit
20021
20022 Allocation Root # 3
20023 -------------------
20024  Number of non freed allocations    :   1
20025  Final Water Mark (non freed mem)   :   3.91 Kilobytes
20026  High Water Mark                    :   3.91 Kilobytes
20027  Backtrace                          :
20028    test_gm.adb:11 test_gm.my_alloc
20029    test_gm.adb:21 test_gm
20030    b_test_gm.c:52 main
20031
20032 Allocation Root # 4
20033 -------------------
20034  Number of non freed allocations    :   1
20035  Final Water Mark (non freed mem)   :  12 Bytes
20036  High Water Mark                    :  12 Bytes
20037  Backtrace                          :
20038    s-secsta.adb:181 system.secondary_stack.ss_init
20039    s-secsta.adb:283 <system__secondary_stack___elabb>
20040    b_test_gm.c:33   adainit
20041 @end smallexample
20042
20043 @noindent
20044 The allocation root #1 of the first example has been split in 2 roots #1
20045 and #3 thanks to the more precise associated backtrace.
20046
20047 @end ifclear
20048
20049 @node Stack Related Facilities
20050 @chapter Stack Related Facilities
20051
20052 @noindent
20053 This chapter describes some useful tools associated with stack
20054 checking and analysis. In
20055 particular, it deals with dynamic and static stack usage measurements.
20056
20057 @menu
20058 * Stack Overflow Checking::
20059 * Static Stack Usage Analysis::
20060 * Dynamic Stack Usage Analysis::
20061 @end menu
20062
20063 @node Stack Overflow Checking
20064 @section Stack Overflow Checking
20065 @cindex Stack Overflow Checking
20066 @cindex -fstack-check
20067
20068 @noindent
20069 For most operating systems, @command{gcc} does not perform stack overflow
20070 checking by default. This means that if the main environment task or
20071 some other task exceeds the available stack space, then unpredictable
20072 behavior will occur. Most native systems offer some level of protection by
20073 adding a guard page at the end of each task stack. This mechanism is usually
20074 not enough for dealing properly with stack overflow situations because
20075 a large local variable could ``jump'' above the guard page.
20076 Furthermore, when the
20077 guard page is hit, there may not be any space left on the stack for executing
20078 the exception propagation code. Enabling stack checking avoids
20079 such situations.
20080
20081 To activate stack checking, compile all units with the gcc option
20082 @option{-fstack-check}. For example:
20083
20084 @smallexample
20085 gcc -c -fstack-check package1.adb
20086 @end smallexample
20087
20088 @noindent
20089 Units compiled with this option will generate extra instructions to check
20090 that any use of the stack (for procedure calls or for declaring local
20091 variables in declare blocks) does not exceed the available stack space.
20092 If the space is exceeded, then a @code{Storage_Error} exception is raised.
20093
20094 For declared tasks, the stack size is controlled by the size
20095 given in an applicable @code{Storage_Size} pragma or by the value specified
20096 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
20097 the default size as defined in the GNAT runtime otherwise.
20098
20099 For the environment task, the stack size depends on
20100 system defaults and is unknown to the compiler. Stack checking
20101 may still work correctly if a fixed
20102 size stack is allocated, but this cannot be guaranteed.
20103 @ifclear vms
20104 To ensure that a clean exception is signalled for stack
20105 overflow, set the environment variable
20106 @env{GNAT_STACK_LIMIT} to indicate the maximum
20107 stack area that can be used, as in:
20108 @cindex GNAT_STACK_LIMIT
20109
20110 @smallexample
20111 SET GNAT_STACK_LIMIT 1600
20112 @end smallexample
20113
20114 @noindent
20115 The limit is given in kilobytes, so the above declaration would
20116 set the stack limit of the environment task to 1.6 megabytes.
20117 Note that the only purpose of this usage is to limit the amount
20118 of stack used by the environment task. If it is necessary to
20119 increase the amount of stack for the environment task, then this
20120 is an operating systems issue, and must be addressed with the
20121 appropriate operating systems commands.
20122 @end ifclear
20123 @ifset vms
20124 To have a fixed size stack in the environment task, the stack must be put
20125 in the P0 address space and its size specified.  Use these switches to
20126 create a p0 image:
20127
20128 @smallexample
20129 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
20130 @end smallexample
20131
20132 @noindent
20133 The quotes are required to keep case.  The number after @samp{STACK=} is the
20134 size of the environmental task stack in pagelets (512 bytes).  In this example
20135 the stack size is about 2 megabytes.
20136
20137 @noindent
20138 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
20139 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
20140 more details about the @option{/p0image} qualifier and the @option{stack}
20141 option.
20142 @end ifset
20143
20144 @node Static Stack Usage Analysis
20145 @section Static Stack Usage Analysis
20146 @cindex Static Stack Usage Analysis
20147 @cindex -fstack-usage
20148
20149 @noindent
20150 A unit compiled with @option{-fstack-usage} will generate an extra file
20151 that specifies
20152 the maximum amount of stack used, on a per-function basis.
20153 The file has the same
20154 basename as the target object file with a @file{.su} extension.
20155 Each line of this file is made up of three fields:
20156
20157 @itemize
20158 @item
20159 The name of the function.
20160 @item
20161 A number of bytes.
20162 @item
20163 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
20164 @end itemize
20165
20166 The second field corresponds to the size of the known part of the function
20167 frame.
20168
20169 The qualifier @code{static} means that the function frame size
20170 is purely static.
20171 It usually means that all local variables have a static size.
20172 In this case, the second field is a reliable measure of the function stack
20173 utilization.
20174
20175 The qualifier @code{dynamic} means that the function frame size is not static.
20176 It happens mainly when some local variables have a dynamic size. When this
20177 qualifier appears alone, the second field is not a reliable measure
20178 of the function stack analysis. When it is qualified with  @code{bounded}, it
20179 means that the second field is a reliable maximum of the function stack
20180 utilization.
20181
20182 @node Dynamic Stack Usage Analysis
20183 @section Dynamic Stack Usage Analysis
20184
20185 @noindent
20186 It is possible to measure the maximum amount of stack used by a task, by
20187 adding a switch to @command{gnatbind}, as:
20188
20189 @smallexample
20190 $ gnatbind -u0 file
20191 @end smallexample
20192
20193 @noindent
20194 With this option, at each task termination, its stack usage is  output on
20195 @file{stderr}.
20196 It is not always convenient to output the stack usage when the program
20197 is still running. Hence, it is possible to delay this output until program
20198 termination. for a given number of tasks specified as the argument of the
20199 @option{-u} option. For instance:
20200
20201 @smallexample
20202 $ gnatbind -u100 file
20203 @end smallexample
20204
20205 @noindent
20206 will buffer the stack usage information of the first 100 tasks to terminate and
20207 output this info at program termination. Results are displayed in four
20208 columns:
20209
20210 @noindent
20211 Index | Task Name | Stack Size | Actual Use [min - max]
20212
20213 @noindent
20214 where:
20215
20216 @table @emph
20217 @item Index
20218 is a number associated with each task.
20219
20220 @item Task Name
20221 is the name of the task analyzed.
20222
20223 @item Stack Size
20224 is the maximum size for the stack.
20225
20226 @item Actual Use
20227 is the measure done by the stack analyzer. In order to prevent overflow,
20228 the stack is not entirely analyzed, and it's not possible to know exactly how
20229 much has actually been used. The real amount of stack used is between the min
20230 and max values.
20231
20232 @end table
20233
20234 @noindent
20235 The environment task stack, e.g., the stack that contains the main unit, is
20236 only processed when the environment variable GNAT_STACK_LIMIT is set.
20237
20238
20239 @c *********************************
20240 @c *            GNATCHECK          *
20241 @c *********************************
20242 @node Verifying Properties Using gnatcheck
20243 @chapter Verifying Properties Using @command{gnatcheck}
20244 @findex gnatcheck
20245 @cindex @command{gnatcheck}
20246
20247 @noindent
20248 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
20249 of Ada source files according to a given set of semantic rules.
20250 @cindex ASIS
20251
20252 In order to check compliance with a given rule, @command{gnatcheck} has to
20253 semantically analyze the Ada sources.
20254 Therefore, checks can only be performed on
20255 legal Ada units. Moreover, when a unit depends semantically upon units located
20256 outside the current directory, the source search path has to be provided when
20257 calling @command{gnatcheck}, either through a specified project file or
20258 through @command{gnatcheck} switches as described below.
20259
20260 A number of rules are predefined in @command{gnatcheck} and are described
20261 later in this chapter.
20262 You can also add new rules, by modifying the @command{gnatcheck} code and
20263 rebuilding the tool. In order to add a simple rule making some local checks,
20264 a small amount of straightforward ASIS-based programming is usually needed.
20265
20266 Project support for @command{gnatcheck} is provided by the GNAT
20267 driver (see @ref{The GNAT Driver and Project Files}).
20268
20269 Invoking @command{gnatcheck} on the command line has the form:
20270
20271 @smallexample
20272 $ gnatcheck @ovar{switches}  @{@var{filename}@}
20273       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
20274       @r{[}-cargs @var{gcc_switches}@r{]} @r{[}-rules @var{rule_options}@r{]}
20275 @end smallexample
20276
20277 @noindent
20278 where
20279 @itemize @bullet
20280 @item
20281 @var{switches} specify the general tool options
20282
20283 @item
20284 Each @var{filename} is the name (including the extension) of a source
20285 file to process. ``Wildcards'' are allowed, and
20286 the file name may contain path information.
20287
20288 @item
20289 Each @var{arg_list_filename} is the name (including the extension) of a text
20290 file containing the names of the source files to process, separated by spaces
20291 or line breaks.
20292
20293 @item
20294 @var{gcc_switches} is a list of switches for
20295 @command{gcc}. They will be passed on to all compiler invocations made by
20296 @command{gnatcheck} to generate the ASIS trees. Here you can provide
20297 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
20298 and use the @option{-gnatec} switch to set the configuration file.
20299
20300 @item
20301 @var{rule_options} is a list of options for controlling a set of
20302 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
20303 @end itemize
20304
20305 @noindent
20306 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be supplied.
20307
20308 @menu
20309 * Format of the Report File::
20310 * General gnatcheck Switches::
20311 * gnatcheck Rule Options::
20312 * Adding the Results of Compiler Checks to gnatcheck Output::
20313 * Project-Wide Checks::
20314 * Predefined Rules::
20315 @end menu
20316
20317 @node Format of the Report File
20318 @section Format of the Report File
20319 @cindex Report file (for @code{gnatcheck})
20320
20321 @noindent
20322 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
20323 rule violations.
20324 It also creates, in the current
20325 directory, a text file named @file{^gnatcheck.out^GNATCHECK.OUT^} that
20326 contains the complete report of the last gnatcheck run. This report contains:
20327 @itemize @bullet
20328 @item a list of the Ada source files being checked,
20329 @item a list of enabled and disabled rules,
20330 @item a list of the diagnostic messages, ordered in three different ways
20331 and collected in three separate
20332 sections. Section 1 contains the raw list of diagnostic messages. It
20333 corresponds to the output going to @file{stdout}. Section 2 contains
20334 messages ordered by rules.
20335 Section 3 contains messages ordered by source files.
20336 @end itemize
20337
20338 @node General gnatcheck Switches
20339 @section General @command{gnatcheck} Switches
20340
20341 @noindent
20342 The following switches control the general @command{gnatcheck} behavior
20343
20344 @table @option
20345 @c !sort!
20346 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
20347 @item ^-a^/ALL^
20348 Process all units including those with read-only ALI files such as
20349 those from GNAT Run-Time library.
20350
20351 @ifclear vms
20352 @ignore
20353 @cindex @option{-d} (@command{gnatcheck})
20354 @item -d
20355 Debug mode
20356 @end ignore
20357
20358 @cindex @option{-dd} (@command{gnatcheck})
20359 @item -dd
20360 Progress indicator mode (for use in GPS)
20361 @end ifclear
20362
20363 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
20364 @item ^-h^/HELP^
20365 List the predefined and user-defined rules. For more details see
20366 @ref{Predefined Rules}.
20367
20368 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
20369 @item ^-l^/LOCS^
20370 Use full source locations references in the report file. For a construct from
20371 a generic instantiation a full source location is a chain from the location
20372 of this construct in the generic unit to the place where this unit is
20373 instantiated.
20374
20375 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
20376 @item ^-m@i{nnn}^/DIAGNOSTIC_LIMIT=@i{nnn}^
20377 Maximum number of diagnoses to be sent to Stdout, @i{nnn} from o@dots{}1000,
20378 the default value is 500. Zero means that there is no limitation on
20379 the number of diagnostic messages to be printed into Stdout.
20380
20381 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
20382 @item ^-q^/QUIET^
20383 Quiet mode. All the diagnoses about rule violations are placed in the
20384 @command{gnatcheck} report file only, without duplicating in @file{stdout}.
20385
20386 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
20387 @item ^-s^/SHORT^
20388 Short format of the report file (no version information, no list of applied
20389 rules, no list of checked sources is included)
20390
20391 @cindex @option{^-s1^/COMPILER_STYLE^} (@command{gnatcheck})
20392 @item ^-s1^/COMPILER_STYLE^
20393 Include the compiler-style section in the report file
20394
20395 @cindex @option{^-s2^/BY_RULES^} (@command{gnatcheck})
20396 @item ^-s2^/BY_RULES^
20397 Include the section containing diagnoses ordered by rules in the report file
20398
20399 @cindex @option{^-s3^/BY_FILES_BY_RULES^} (@command{gnatcheck})
20400 @item ^-s3^/BY_FILES_BY_RULES^
20401 Include the section containing diagnoses ordered by files and then by rules
20402 in the report file
20403
20404 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
20405 @item ^-v^/VERBOSE^
20406 Verbose mode; @command{gnatcheck} generates version information and then
20407 a trace of sources being processed.
20408
20409 @end table
20410
20411 @noindent
20412 Note that if any of the options @option{^-s1^/COMPILER_STYLE^},
20413 @option{^-s2^/BY_RULES^} or
20414 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
20415 then the  @command{gnatcheck} report file will only contain sections
20416 explicitly denoted by these options.
20417
20418 @node gnatcheck Rule Options
20419 @section @command{gnatcheck} Rule Options
20420
20421 @noindent
20422 The following options control the processing performed by
20423 @command{gnatcheck}.
20424
20425 @table @option
20426 @cindex @option{+ALL} (@command{gnatcheck})
20427 @item +ALL
20428 Turn all the rule checks ON.
20429
20430 @cindex @option{-ALL} (@command{gnatcheck})
20431 @item -ALL
20432 Turn all the rule checks OFF.
20433
20434 @cindex @option{+R} (@command{gnatcheck})
20435 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
20436 Turn on the check for a specified rule with the specified parameter, if any.
20437 @var{rule_id} must be the identifier of one of the currently implemented rules
20438 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
20439 are not case-sensitive. The @var{param} item must
20440 be a string representing a valid parameter(s) for the specified rule.
20441 If it contains any space characters then this string must be enclosed in
20442 quotation marks.
20443
20444 @cindex @option{-R} (@command{gnatcheck})
20445 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
20446 Turn off the check for a specified rule with the specified parameter, if any.
20447
20448 @cindex @option{-from} (@command{gnatcheck})
20449 @item -from=@var{rule_option_filename}
20450 Read the rule options from the text file @var{rule_option_filename}, referred as
20451 ``rule file'' below.
20452
20453 @end table
20454
20455 @noindent
20456 The default behavior is that all the rule checks are disabled.
20457
20458 A rule file is a text file containing a set of rule options.
20459 @cindex Rule file (for @code{gnatcheck})
20460 The file may contain empty lines and Ada-style comments (comment
20461 lines and end-of-line comments). The rule file has free format; that is,
20462 you do not have to start a new rule option on a new line.
20463
20464 A rule file may contain other @option{-from=@var{rule_option_filename}}
20465 options, each such option being replaced with the content of the
20466 corresponding rule file during the rule files processing. In case a
20467 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
20468 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
20469 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
20470 the processing of rule files is interrupted and a part of their content
20471 is ignored.
20472
20473
20474 @node Adding the Results of Compiler Checks to gnatcheck Output
20475 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
20476
20477 @noindent
20478 The @command{gnatcheck} tool can include in the generated diagnostic messages
20479 and in
20480 the report file the results of the checks performed by the compiler. Though
20481 disabled by default, this effect may be obtained by using @option{+R} with
20482 the following rule identifiers and parameters:
20483
20484 @table @option
20485 @item Restrictions
20486 To record restrictions violations (that are performed by the compiler if the
20487 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
20488 use the rule named
20489 @code{Restrictions} with the same parameters as pragma
20490 @code{Restrictions} or @code{Restriction_Warnings}.
20491
20492 @item Style_Checks
20493 To record compiler style checks(@pxref{Style Checking}), use the rule named
20494 @code{Style_Checks}. A parameter of this rule can be either @code{All_Checks},
20495 which enables all the standard style checks that corresponds to @option{-gnatyy}
20496 GNAT style check option, or a string that has exactly the same
20497 structure and semantics as the @code{string_LITERAL} parameter of GNAT pragma
20498 @code{Style_Checks} (for further information about this pragma,
20499 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}).
20500
20501 @item Warnings
20502 To record compiler warnings (@pxref{Warning Message Control}), use the rule
20503 named @code{Warnings} with a parameter that is a valid
20504 @i{static_string_expression} argument of GNAT pragma @code{Warnings}
20505 (for further information about this pragma, @pxref{Pragma Warnings,,,
20506 gnat_rm, GNAT Reference Manual}). Note, that in case of gnatcheck
20507 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
20508 all the specific warnings, but not suppresses the warning mode,
20509 and 'e' parameter, corresponding to @option{-gnatwe} that means
20510 "treat warnings as errors", does not have any effect.
20511
20512 @end table
20513
20514 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
20515 option with the corresponding restriction name as a parameter. @code{-R} is
20516 not available for @code{Style_Checks} and @code{Warnings} options, to disable
20517 warnings and style checks, use the corresponding warning and style options.
20518
20519 @node Project-Wide Checks
20520 @section Project-Wide Checks
20521 @cindex Project-wide checks (for @command{gnatcheck})
20522
20523 @noindent
20524 In order to perform checks on all units of a given project, you can use
20525 the GNAT driver along with the @option{-P} option:
20526 @smallexample
20527    gnat check -Pproj -rules -from=my_rules
20528 @end smallexample
20529
20530 @noindent
20531 If the project @code{proj} depends upon other projects, you can perform
20532 checks on the project closure using the @option{-U} option:
20533 @smallexample
20534    gnat check -Pproj -U -rules -from=my_rules
20535 @end smallexample
20536
20537 @noindent
20538 Finally, if not all the units are relevant to a particular main
20539 program in the project closure, you can perform checks for the set
20540 of units needed to create a given main program (unit closure) using
20541 the @option{-U} option followed by the name of the main unit:
20542 @smallexample
20543    gnat check -Pproj -U main -rules -from=my_rules
20544 @end smallexample
20545
20546
20547 @node Predefined Rules
20548 @section Predefined Rules
20549 @cindex Predefined rules (for @command{gnatcheck})
20550
20551 @ignore
20552 @c (Jan 2007) Since the global rules are still under development and are not
20553 @c documented, there is no point in explaining the difference between
20554 @c global and local rules
20555 @noindent
20556 A rule in @command{gnatcheck} is either local or global.
20557 A @emph{local rule} is a rule that applies to a well-defined section
20558 of a program and that can be checked by analyzing only this section.
20559 A @emph{global rule} requires analysis of some global properties of the
20560 whole program (mostly related to the program call graph).
20561 As of @value{NOW}, the implementation of global rules should be
20562 considered to be at a preliminary stage. You can use the
20563 @option{+GLOBAL} option to enable all the global rules, and the
20564 @option{-GLOBAL} rule option to disable all the global rules.
20565
20566 All the global rules in the list below are
20567 so indicated by marking them ``GLOBAL''.
20568 This +GLOBAL and -GLOBAL options are not
20569 included in the list of gnatcheck options above, because at the moment they
20570 are considered as a temporary debug options.
20571
20572 @command{gnatcheck} performs rule checks for generic
20573 instances only for global rules.  This limitation may be relaxed in a later
20574 release.
20575 @end ignore
20576
20577 @noindent
20578 The following subsections document the rules implemented in
20579 @command{gnatcheck}.
20580 The subsection title is the same as the rule identifier, which may be
20581 used as a parameter of the @option{+R} or @option{-R} options.
20582
20583
20584 @menu
20585 * Abstract_Type_Declarations::
20586 * Anonymous_Arrays::
20587 * Anonymous_Subtypes::
20588 * Blocks::
20589 * Boolean_Relational_Operators::
20590 @ignore
20591 * Ceiling_Violations::
20592 @end ignore
20593 * Controlled_Type_Declarations::
20594 * Declarations_In_Blocks::
20595 * Default_Parameters::
20596 * Discriminated_Records::
20597 * Enumeration_Ranges_In_CASE_Statements::
20598 * Exceptions_As_Control_Flow::
20599 * EXIT_Statements_With_No_Loop_Name::
20600 * Expanded_Loop_Exit_Names::
20601 * Explicit_Full_Discrete_Ranges::
20602 * Float_Equality_Checks::
20603 * Forbidden_Pragmas::
20604 * Function_Style_Procedures::
20605 * Generics_In_Subprograms::
20606 * GOTO_Statements::
20607 * Implicit_IN_Mode_Parameters::
20608 * Implicit_SMALL_For_Fixed_Point_Types::
20609 * Improperly_Located_Instantiations::
20610 * Improper_Returns::
20611 * Library_Level_Subprograms::
20612 * Local_Packages::
20613 @ignore
20614 * Improperly_Called_Protected_Entries::
20615 @end ignore
20616 * Metrics::
20617 * Misnamed_Identifiers::
20618 * Multiple_Entries_In_Protected_Definitions::
20619 * Name_Clashes::
20620 * Non_Qualified_Aggregates::
20621 * Non_Short_Circuit_Operators::
20622 * Non_SPARK_Attributes::
20623 * Non_Tagged_Derived_Types::
20624 * Non_Visible_Exceptions::
20625 * Numeric_Literals::
20626 * OTHERS_In_Aggregates::
20627 * OTHERS_In_CASE_Statements::
20628 * OTHERS_In_Exception_Handlers::
20629 * Outer_Loop_Exits::
20630 * Overloaded_Operators::
20631 * Overly_Nested_Control_Structures::
20632 * Parameters_Out_Of_Order::
20633 * Positional_Actuals_For_Defaulted_Generic_Parameters::
20634 * Positional_Actuals_For_Defaulted_Parameters::
20635 * Positional_Components::
20636 * Positional_Generic_Parameters::
20637 * Positional_Parameters::
20638 * Predefined_Numeric_Types::
20639 * Raising_External_Exceptions::
20640 * Raising_Predefined_Exceptions::
20641 * Separate_Numeric_Error_Handlers::
20642 @ignore
20643 * Recursion::
20644 * Side_Effect_Functions::
20645 @end ignore
20646 * Slices::
20647 * Unassigned_OUT_Parameters::
20648 * Uncommented_BEGIN_In_Package_Bodies::
20649 * Unconstrained_Array_Returns::
20650 * Universal_Ranges::
20651 * Unnamed_Blocks_And_Loops::
20652 @ignore
20653 * Unused_Subprograms::
20654 @end ignore
20655 * USE_PACKAGE_Clauses::
20656 * Volatile_Objects_Without_Address_Clauses::
20657 @end menu
20658
20659
20660 @node Abstract_Type_Declarations
20661 @subsection @code{Abstract_Type_Declarations}
20662 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
20663
20664 @noindent
20665 Flag all declarations of abstract types. For an abstract private
20666 type, both the private and full type declarations are flagged.
20667
20668 This rule has no parameters.
20669
20670
20671 @node Anonymous_Arrays
20672 @subsection @code{Anonymous_Arrays}
20673 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
20674
20675 @noindent
20676 Flag all anonymous array type definitions (by Ada semantics these can only
20677 occur in object declarations).
20678
20679 This rule has no parameters.
20680
20681 @node Anonymous_Subtypes
20682 @subsection @code{Anonymous_Subtypes}
20683 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
20684
20685 @noindent
20686 Flag all uses of anonymous subtypes. A use of an anonymous subtype is
20687 any instance of a subtype indication with a constraint, other than one
20688 that occurs immediately within a subtype declaration. Any use of a range
20689 other than as a constraint used immediately within a subtype declaration
20690 is considered as an anonymous subtype.
20691
20692 An effect of this rule is that @code{for} loops such as the following are
20693 flagged (since @code{1..N} is formally a ``range''):
20694
20695 @smallexample @c ada
20696 for I in 1 .. N loop
20697    @dots{}
20698 end loop;
20699 @end smallexample
20700
20701 @noindent
20702 Declaring an explicit subtype solves the problem:
20703
20704 @smallexample @c ada
20705 subtype S is Integer range 1..N;
20706 @dots{}
20707 for I in S loop
20708    @dots{}
20709 end loop;
20710 @end smallexample
20711
20712 @noindent
20713 This rule has no parameters.
20714
20715 @node Blocks
20716 @subsection @code{Blocks}
20717 @cindex @code{Blocks} rule (for @command{gnatcheck})
20718
20719 @noindent
20720 Flag each block statement.
20721
20722 This rule has no parameters.
20723
20724 @node Boolean_Relational_Operators
20725 @subsection @code{Boolean_Relational_Operators}
20726 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
20727
20728 @noindent
20729 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
20730 ``>='', ``='' and ``/='') for the predefined Boolean type.
20731 (This rule is useful in enforcing the SPARK language restrictions.)
20732
20733 Calls to predefined relational operators of any type derived from
20734 @code{Standard.Boolean} are not detected.  Calls to user-defined functions
20735 with these designators, and uses of operators that are renamings
20736 of the predefined relational operators for @code{Standard.Boolean},
20737 are likewise not detected.
20738
20739 This rule has no parameters.
20740
20741 @ignore
20742 @node Ceiling_Violations
20743 @subsection @code{Ceiling_Violations} (under construction, GLOBAL)
20744 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
20745
20746 @noindent
20747 Flag invocations of a protected operation by a task whose priority exceeds
20748 the protected object's ceiling.
20749
20750 As of @value{NOW}, this rule has the following limitations:
20751
20752 @itemize @bullet
20753
20754 @item
20755  We consider only pragmas Priority and Interrupt_Priority as means to define
20756   a task/protected operation priority. We do not consider the effect of using
20757   Ada.Dynamic_Priorities.Set_Priority procedure;
20758
20759 @item
20760  We consider only base task priorities, and no priority inheritance. That is,
20761   we do not make a difference between calls issued during task activation and
20762   execution of the sequence of statements from task body;
20763
20764 @item
20765  Any situation when the priority of protected operation caller is set by a
20766   dynamic expression (that is, the corresponding Priority or
20767   Interrupt_Priority pragma has a non-static expression as an argument) we
20768   treat as a priority inconsistency (and, therefore, detect this situation).
20769 @end itemize
20770
20771 @noindent
20772 At the moment the notion of the main subprogram is not implemented in
20773 gnatcheck, so any pragma Priority in a library level subprogram body (in case
20774 if this subprogram can be a main subprogram of a partition) changes the
20775 priority of an environment task. So if we have more then one such pragma in
20776 the set of processed sources, the pragma that is processed last, defines the
20777 priority of an environment task.
20778
20779 This rule has no parameters.
20780 @end ignore
20781
20782 @node Controlled_Type_Declarations
20783 @subsection @code{Controlled_Type_Declarations}
20784 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
20785
20786 @noindent
20787 Flag all declarations of controlled types. A declaration of a private type
20788 is flagged if its full declaration declares a controlled type. A declaration
20789 of a derived type is flagged if its ancestor type is controlled. Subtype
20790 declarations are not checked. A declaration of a type that itself is not a
20791 descendant of a type declared in @code{Ada.Finalization} but has a controlled
20792 component is not checked.
20793
20794 This rule has no parameters.
20795
20796
20797
20798 @node Declarations_In_Blocks
20799 @subsection @code{Declarations_In_Blocks}
20800 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
20801
20802 @noindent
20803 Flag all block statements containing local declarations. A @code{declare}
20804 block with an empty @i{declarative_part} or with a @i{declarative part}
20805 containing only pragmas and/or @code{use} clauses is not flagged.
20806
20807 This rule has no parameters.
20808
20809
20810 @node Default_Parameters
20811 @subsection @code{Default_Parameters}
20812 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
20813
20814 @noindent
20815 Flag all default expressions for subprogram parameters. Parameter
20816 declarations of formal and generic subprograms are also checked.
20817
20818 This rule has no parameters.
20819
20820
20821 @node Discriminated_Records
20822 @subsection @code{Discriminated_Records}
20823 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
20824
20825 @noindent
20826 Flag all declarations of record types with discriminants. Only the
20827 declarations of record and record extension types are checked. Incomplete,
20828 formal, private, derived and private extension type declarations are not
20829 checked. Task and protected type declarations also are not checked.
20830
20831 This rule has no parameters.
20832
20833
20834 @node Enumeration_Ranges_In_CASE_Statements
20835 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
20836 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
20837
20838 @noindent
20839 Flag each use of a range of enumeration literals as a choice in a
20840 @code{case} statement.
20841 All forms for specifying a range (explicit ranges
20842 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
20843 An enumeration range is
20844 flagged even if contains exactly one enumeration value or no values at all. A
20845 type derived from an enumeration type is considered as an enumeration type.
20846
20847 This rule helps prevent maintenance problems arising from adding an
20848 enumeration value to a type and having it implicitly handled by an existing
20849 @code{case} statement with an enumeration range that includes the new literal.
20850
20851 This rule has no parameters.
20852
20853
20854 @node Exceptions_As_Control_Flow
20855 @subsection @code{Exceptions_As_Control_Flow}
20856 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
20857
20858 @noindent
20859 Flag each place where an exception is explicitly raised and handled in the
20860 same subprogram body. A @code{raise} statement in an exception handler,
20861 package body, task body or entry body is not flagged.
20862
20863 The rule has no parameters.
20864
20865 @node EXIT_Statements_With_No_Loop_Name
20866 @subsection @code{EXIT_Statements_With_No_Loop_Name}
20867 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
20868
20869 @noindent
20870 Flag each @code{exit} statement that does not specify the name of the loop
20871 being exited.
20872
20873 The rule has no parameters.
20874
20875
20876 @node Expanded_Loop_Exit_Names
20877 @subsection @code{Expanded_Loop_Exit_Names}
20878 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
20879
20880 @noindent
20881 Flag all expanded loop names in @code{exit} statements.
20882
20883 This rule has no parameters.
20884
20885 @node Explicit_Full_Discrete_Ranges
20886 @subsection @code{Explicit_Full_Discrete_Ranges}
20887 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
20888
20889 @noindent
20890 Flag each discrete range that has the form @code{A'First .. A'Last}.
20891
20892 This rule has no parameters.
20893
20894 @node Float_Equality_Checks
20895 @subsection @code{Float_Equality_Checks}
20896 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
20897
20898 @noindent
20899 Flag all calls to the predefined equality operations for floating-point types.
20900 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
20901 User-defined equality operations are not flagged, nor are ``@code{=}''
20902 and ``@code{/=}'' operations for fixed-point types.
20903
20904 This rule has no parameters.
20905
20906
20907 @node Forbidden_Pragmas
20908 @subsection @code{Forbidden_Pragmas}
20909 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
20910
20911 @noindent
20912 Flag each use of the specified pragmas.  The pragmas to be detected
20913 are named in the rule's  parameters.
20914
20915 This rule has the following parameters:
20916
20917 @itemize @bullet
20918 @item For the @option{+R} option
20919
20920 @table @asis
20921 @item @emph{Pragma_Name}
20922 Adds the specified pragma to the set of pragmas to be
20923 checked and sets the checks for all the specified pragmas
20924 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
20925 does not correspond to any pragma name defined in the Ada
20926 standard or to the name of a GNAT-specific pragma defined
20927 in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
20928 Manual}, it is treated as the name of unknown pragma.
20929
20930 @item @code{GNAT}
20931 All the GNAT-specific pragmas are detected; this sets
20932 the checks for all the specified pragmas ON.
20933
20934 @item @code{ALL}
20935 All pragmas are detected; this sets the rule ON.
20936 @end table
20937
20938 @item For the @option{-R} option
20939 @table @asis
20940 @item @emph{Pragma_Name}
20941 Removes the specified pragma from the set of pragmas to be
20942 checked without affecting checks for
20943 other pragmas. @emph{Pragma_Name} is treated as a name
20944 of a pragma. If it does not correspond to any pragma
20945 defined in the Ada standard or to any name defined in
20946 @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
20947 this option is treated as turning OFF detection of all unknown pragmas.
20948
20949 @item GNAT
20950 Turn OFF detection of all GNAT-specific pragmas
20951
20952 @item ALL
20953 Clear the list of the pragmas to be detected and
20954 turn the rule OFF.
20955 @end table
20956 @end itemize
20957
20958 @noindent
20959 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
20960 the syntax of an Ada identifier and therefore can not be considered
20961 as a pragma name, a diagnostic message is generated and the corresponding
20962 parameter is ignored.
20963
20964 When more then one parameter is given in the same rule option, the parameters
20965 must be separated by a comma.
20966
20967 If more then one option for this rule is specified for the @command{gnatcheck}
20968 call, a new option overrides the previous one(s).
20969
20970 The @option{+R} option with no parameters turns the rule ON with the set of
20971 pragmas to be detected defined by the previous rule options.
20972 (By default this set is empty, so if the only option specified for the rule is
20973 @option{+RForbidden_Pragmas} (with
20974 no parameter), then the rule is enabled, but it does not detect anything).
20975 The @option{-R} option with no parameter turns the rule OFF, but it does not
20976 affect the set of pragmas to be detected.
20977
20978
20979
20980
20981 @node Function_Style_Procedures
20982 @subsection @code{Function_Style_Procedures}
20983 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
20984
20985 @noindent
20986 Flag each procedure that can be rewritten as a function. A procedure can be
20987 converted into a function if it has exactly one parameter of mode @code{out}
20988 and no parameters of mode @code{in out}. Procedure declarations,
20989 formal procedure declarations, and generic procedure declarations are always
20990 checked. Procedure
20991 bodies and body stubs are flagged only if they do not have corresponding
20992 separate declarations. Procedure renamings and procedure instantiations are
20993 not flagged.
20994
20995 If a procedure can be rewritten as a function, but its @code{out} parameter is
20996 of a limited type, it is not flagged.
20997
20998 Protected procedures are not flagged. Null procedures also are not flagged.
20999
21000 This rule has no parameters.
21001
21002
21003 @node Generics_In_Subprograms
21004 @subsection @code{Generics_In_Subprograms}
21005 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
21006
21007 @noindent
21008 Flag each declaration of a generic unit in a subprogram. Generic
21009 declarations in the bodies of generic subprograms are also flagged.
21010 A generic unit nested in another generic unit is not flagged.
21011 If a generic unit is
21012 declared in a local package that is declared in a subprogram body, the
21013 generic unit is flagged.
21014
21015 This rule has no parameters.
21016
21017
21018 @node GOTO_Statements
21019 @subsection @code{GOTO_Statements}
21020 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
21021
21022 @noindent
21023 Flag each occurrence of a @code{goto} statement.
21024
21025 This rule has no parameters.
21026
21027
21028 @node Implicit_IN_Mode_Parameters
21029 @subsection @code{Implicit_IN_Mode_Parameters}
21030 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
21031
21032 @noindent
21033 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
21034 Note that @code{access} parameters, although they technically behave
21035 like @code{in} parameters, are not flagged.
21036
21037 This rule has no parameters.
21038
21039
21040 @node Implicit_SMALL_For_Fixed_Point_Types
21041 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
21042 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
21043
21044 @noindent
21045 Flag each fixed point type declaration that lacks an explicit
21046 representation  clause to define its @code{'Small} value.
21047 Since @code{'Small} can be  defined only for ordinary fixed point types,
21048 decimal fixed point type declarations are not checked.
21049
21050 This rule has no parameters.
21051
21052
21053 @node Improperly_Located_Instantiations
21054 @subsection @code{Improperly_Located_Instantiations}
21055 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
21056
21057 @noindent
21058 Flag all generic instantiations in library-level package specs
21059 (including library generic packages) and in all subprogram bodies.
21060
21061 Instantiations in task and entry bodies are not flagged. Instantiations in the
21062 bodies of protected subprograms are flagged.
21063
21064 This rule has no parameters.
21065
21066
21067
21068 @node Improper_Returns
21069 @subsection @code{Improper_Returns}
21070 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
21071
21072 @noindent
21073 Flag each explicit @code{return} statement in procedures, and
21074 multiple @code{return} statements in functions.
21075 Diagnostic messages are generated for all @code{return} statements
21076 in a procedure (thus each procedure must be written so that it
21077 returns implicitly at the end of its statement part),
21078 and for all @code{return} statements in a function after the first one.
21079 This rule supports the stylistic convention that each subprogram
21080 should have no more than one point of normal return.
21081
21082 This rule has no parameters.
21083
21084
21085 @node Library_Level_Subprograms
21086 @subsection @code{Library_Level_Subprograms}
21087 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
21088
21089 @noindent
21090 Flag all library-level subprograms (including generic subprogram instantiations).
21091
21092 This rule has no parameters.
21093
21094
21095 @node Local_Packages
21096 @subsection @code{Local_Packages}
21097 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
21098
21099 @noindent
21100 Flag all local packages declared in package and generic package
21101 specs.
21102 Local packages in bodies are not flagged.
21103
21104 This rule has no parameters.
21105
21106 @ignore
21107 @node Improperly_Called_Protected_Entries
21108 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
21109 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
21110
21111 @noindent
21112 Flag each protected entry that can be called from more than one task.
21113
21114 This rule has no parameters.
21115 @end ignore
21116
21117 @node Metrics
21118 @subsection @code{Metrics}
21119 @cindex @code{Metrics} rule (for @command{gnatcheck})
21120
21121 @noindent
21122 There is a set of checks based on computing a metric value and comparing the
21123 result with the specified upper (or lower, depending on a specific metric)
21124 value specified for a given metric. A construct is flagged if a given metric
21125 is applicable (can be computed) for it and the computed value is greater
21126 then (lover then) the specified upper (lower) bound.
21127
21128 The name of any metric-based rule consists of the prefix @code{Metrics_}
21129 followed by the name of the corresponding metric (see the table below).
21130 For @option{+R} option, each metric-based rule has a numeric parameter
21131 specifying the bound (integer or real, depending on a metric), @option{-R}
21132 option for metric rules does not have a parameter.
21133
21134 The following table shows the metric names for that the corresponding
21135 metrics-based checks are supported by gnatcheck, including the
21136 constraint that must be satisfied by the bound that is specified for the check
21137 and what bound - upper (U) or lower (L) - should be specified.
21138
21139 @multitable {@code{Cyclomatic_Complexity}}{Cyclomatic complexity}{Positive integer}
21140 @ifnothtml
21141 @headitem Check Name @tab Description @tab Bounds Value
21142 @end ifnothtml
21143 @ifhtml
21144 @item @b{Check Name} @tab @b{Description} @tab @b{Bounds Value}
21145 @end ifhtml
21146 @c Above conditional code is workaround to bug in texi2html (Feb 2008)
21147 @item @code{Essential_Complexity} @tab Essential complexity @tab Positive integer (U)
21148 @item @code{Cyclomatic_Complexity} @tab Cyclomatic complexity @tab Positive integer (U)
21149 @item @code{LSLOC} @tab Logical Source Lines of Code @tab Positive integer (U)
21150 @end multitable
21151
21152 @noindent
21153 The meaning and the computed values for all these metrics are exactly
21154 the same as for the corresponding metrics in @command{gnatmetric}.
21155
21156 @emph{Example:} the rule
21157 @smallexample
21158 +RMetrics_Cyclomatic_Complexity : 7
21159 @end smallexample
21160 @noindent
21161 means that all bodies with cyclomatic complexity exceeding 7 will be flagged.
21162
21163 To turn OFF the check for cyclomatic complexity metric, use the following option:
21164 @smallexample
21165 -RMetrics_Cyclomatic_Complexity
21166 @end smallexample
21167
21168 @node Misnamed_Identifiers
21169 @subsection @code{Misnamed_Identifiers}
21170 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
21171
21172 @noindent
21173 Flag the declaration of each identifier that does not have a suffix
21174 corresponding to the kind of entity being declared.
21175 The following declarations are checked:
21176
21177 @itemize @bullet
21178 @item
21179 type declarations
21180
21181 @item
21182 constant declarations (but not number declarations)
21183
21184 @item
21185 package renaming declarations (but not generic package renaming
21186 declarations)
21187 @end itemize
21188
21189 @noindent
21190 This rule may have parameters. When used without parameters, the rule enforces
21191 the following checks:
21192
21193 @itemize @bullet
21194 @item
21195 type-defining names end with @code{_T}, unless the type is an access type,
21196 in which case the suffix must be @code{_A}
21197 @item
21198 constant names end with @code{_C}
21199 @item
21200 names defining package renamings end with @code{_R}
21201 @end itemize
21202
21203 @noindent
21204 For a private or incomplete type declaration the following checks are
21205 made for the defining name suffix:
21206
21207 @itemize @bullet
21208 @item
21209 For an incomplete type declaration: if the corresponding full type
21210 declaration is available, the defining identifier from the full type
21211 declaration is checked, but the defining identifier from the incomplete type
21212 declaration is not; otherwise the defining identifier from the incomplete
21213 type declaration is checked against the suffix specified for type
21214 declarations.
21215
21216 @item
21217 For a private type declaration (including private extensions),  the defining
21218 identifier from the private type declaration is checked against the type
21219 suffix (even if the corresponding full declaration is an access type
21220 declaration), and the defining identifier from the corresponding full type
21221 declaration is not checked.
21222 @end itemize
21223
21224 @noindent
21225 For a deferred constant, the defining name in the corresponding full constant
21226 declaration is not checked.
21227
21228 Defining names of formal types are not checked.
21229
21230 The rule may have the following parameters:
21231
21232 @itemize @bullet
21233 @item
21234 For the @option{+R} option:
21235 @table @code
21236 @item Default
21237 Sets the default listed above for all the names to be checked.
21238
21239 @item Type_Suffix=@emph{string}
21240 Specifies the suffix for a type name.
21241
21242 @item Access_Suffix=@emph{string}
21243 Specifies the suffix for an access type name. If
21244 this parameter is set, it overrides for access
21245 types the suffix set by the @code{Type_Suffix} parameter.
21246
21247 @item Constant_Suffix=@emph{string}
21248 Specifies the suffix for a constant name.
21249
21250 @item Renaming_Suffix=@emph{string}
21251 Specifies the suffix for a package renaming name.
21252 @end table
21253
21254 @item
21255 For the @option{-R} option:
21256 @table @code
21257 @item All_Suffixes
21258 Remove all the suffixes specified for the
21259 identifier suffix checks, whether by default or
21260 as specified by other rule parameters. All the
21261 checks for this rule are disabled as a result.
21262
21263 @item Type_Suffix
21264 Removes the suffix specified for types. This
21265 disables checks for types but does not disable
21266 any other checks for this rule (including the
21267 check for access type names if @code{Access_Suffix} is
21268 set).
21269
21270 @item Access_Suffix
21271 Removes the suffix specified for access types.
21272 This disables checks for access type names but
21273 does not disable any other checks for this rule.
21274 If @code{Type_Suffix} is set, access type names are
21275 checked as ordinary type names.
21276
21277 @item Constant_Suffix
21278 Removes the suffix specified for constants. This
21279 disables checks for constant names but does not
21280 disable any other checks for this rule.
21281
21282 @item Renaming_Suffix
21283 Removes the suffix specified for package
21284 renamings. This disables checks for package
21285 renamings but does not disable any other checks
21286 for this rule.
21287 @end table
21288 @end itemize
21289
21290 @noindent
21291 If more than one parameter is used, parameters must be separated by commas.
21292
21293 If more than one  option is specified for the @command{gnatcheck} invocation,
21294 a new option overrides the previous one(s).
21295
21296 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
21297 checks for all the
21298 name suffixes specified by previous options used for this rule.
21299
21300 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
21301 all the checks but keeps
21302 all the suffixes specified by previous options used for this rule.
21303
21304 The @emph{string} value must be a valid suffix for an Ada identifier (after
21305 trimming all the leading and trailing space characters, if any).
21306 Parameters are not case sensitive, except the @emph{string} part.
21307
21308 If any error is detected in a rule parameter, the parameter is ignored.
21309 In such a case the options that are set for the rule are not
21310 specified.
21311
21312
21313
21314 @node Multiple_Entries_In_Protected_Definitions
21315 @subsection @code{Multiple_Entries_In_Protected_Definitions}
21316 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
21317
21318 @noindent
21319 Flag each protected definition (i.e., each protected object/type declaration)
21320 that defines more than one entry.
21321 Diagnostic messages are generated for all the entry declarations
21322 except the first one. An entry family is counted as one entry. Entries from
21323 the private part of the protected definition are also checked.
21324
21325 This rule has no parameters.
21326
21327 @node Name_Clashes
21328 @subsection @code{Name_Clashes}
21329 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
21330
21331 @noindent
21332 Check that certain names are not used as defining identifiers. To activate
21333 this rule, you need to supply a reference to the dictionary file(s) as a rule
21334 parameter(s) (more then one dictionary file can be specified). If no
21335 dictionary file is set, this rule will not cause anything to be flagged.
21336 Only defining occurrences, not references, are checked.
21337 The check is not case-sensitive.
21338
21339 This rule is enabled by default, but without setting any corresponding
21340 dictionary file(s); thus the default effect is to do no checks.
21341
21342 A dictionary file is a plain text file. The maximum line length for this file
21343 is 1024 characters.  If the line is longer then this limit, extra characters
21344 are ignored.
21345
21346 Each line can be either an empty line, a comment line, or a line containing
21347 a list of identifiers separated by space or HT characters.
21348 A comment is an Ada-style comment (from @code{--} to end-of-line).
21349 Identifiers must follow the Ada syntax for identifiers.
21350 A line containing one or more identifiers may end with a comment.
21351
21352 @node Non_Qualified_Aggregates
21353 @subsection @code{Non_Qualified_Aggregates}
21354 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
21355
21356 @noindent
21357 Flag each non-qualified aggregate.
21358 A non-qualified aggregate is an
21359 aggregate that is not the expression of a qualified expression. A
21360 string literal is not considered an aggregate, but an array
21361 aggregate of a string type is considered as a normal aggregate.
21362 Aggregates of anonymous array types are not flagged.
21363
21364 This rule has no parameters.
21365
21366
21367 @node Non_Short_Circuit_Operators
21368 @subsection @code{Non_Short_Circuit_Operators}
21369 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
21370
21371 @noindent
21372 Flag all calls to predefined @code{and} and @code{or} operators for
21373 any boolean type. Calls to
21374 user-defined @code{and} and @code{or} and to operators defined by renaming
21375 declarations are not flagged. Calls to predefined @code{and} and @code{or}
21376 operators for modular types or boolean array types are not flagged.
21377
21378 This rule has no parameters.
21379
21380
21381
21382 @node Non_SPARK_Attributes
21383 @subsection @code{Non_SPARK_Attributes}
21384 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
21385
21386 @noindent
21387 The SPARK language defines the following subset of Ada 95 attribute
21388 designators as those that can be used in SPARK programs. The use of
21389 any other attribute is flagged.
21390
21391 @itemize @bullet
21392 @item @code{'Adjacent}
21393 @item @code{'Aft}
21394 @item @code{'Base}
21395 @item @code{'Ceiling}
21396 @item @code{'Component_Size}
21397 @item @code{'Compose}
21398 @item @code{'Copy_Sign}
21399 @item @code{'Delta}
21400 @item @code{'Denorm}
21401 @item @code{'Digits}
21402 @item @code{'Exponent}
21403 @item @code{'First}
21404 @item @code{'Floor}
21405 @item @code{'Fore}
21406 @item @code{'Fraction}
21407 @item @code{'Last}
21408 @item @code{'Leading_Part}
21409 @item @code{'Length}
21410 @item @code{'Machine}
21411 @item @code{'Machine_Emax}
21412 @item @code{'Machine_Emin}
21413 @item @code{'Machine_Mantissa}
21414 @item @code{'Machine_Overflows}
21415 @item @code{'Machine_Radix}
21416 @item @code{'Machine_Rounds}
21417 @item @code{'Max}
21418 @item @code{'Min}
21419 @item @code{'Model}
21420 @item @code{'Model_Emin}
21421 @item @code{'Model_Epsilon}
21422 @item @code{'Model_Mantissa}
21423 @item @code{'Model_Small}
21424 @item @code{'Modulus}
21425 @item @code{'Pos}
21426 @item @code{'Pred}
21427 @item @code{'Range}
21428 @item @code{'Remainder}
21429 @item @code{'Rounding}
21430 @item @code{'Safe_First}
21431 @item @code{'Safe_Last}
21432 @item @code{'Scaling}
21433 @item @code{'Signed_Zeros}
21434 @item @code{'Size}
21435 @item @code{'Small}
21436 @item @code{'Succ}
21437 @item @code{'Truncation}
21438 @item @code{'Unbiased_Rounding}
21439 @item @code{'Val}
21440 @item @code{'Valid}
21441 @end itemize
21442
21443 @noindent
21444 This rule has no parameters.
21445
21446
21447 @node Non_Tagged_Derived_Types
21448 @subsection @code{Non_Tagged_Derived_Types}
21449 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
21450
21451 @noindent
21452 Flag all derived type declarations that do not have a record extension part.
21453
21454 This rule has no parameters.
21455
21456
21457
21458 @node Non_Visible_Exceptions
21459 @subsection @code{Non_Visible_Exceptions}
21460 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
21461
21462 @noindent
21463 Flag constructs leading to the possibility of propagating an exception
21464 out of the scope in which the exception is declared.
21465 Two cases are detected:
21466
21467 @itemize @bullet
21468 @item
21469 An exception declaration in a subprogram body, task body or block
21470 statement is flagged if the body or statement does not contain a handler for
21471 that exception or a handler with an @code{others} choice.
21472
21473 @item
21474 A @code{raise} statement in an exception handler of a subprogram body,
21475 task body or block statement is flagged if it (re)raises a locally
21476 declared exception.  This may occur under the following circumstances:
21477 @itemize @minus
21478 @item
21479 it explicitly raises a locally declared exception, or
21480 @item
21481 it does not specify an exception name (i.e., it is simply @code{raise;})
21482 and the enclosing handler contains a locally declared exception in its
21483 exception choices.
21484 @end itemize
21485 @end itemize
21486
21487 @noindent
21488 Renamings of local exceptions are not flagged.
21489
21490 This rule has no parameters.
21491
21492
21493 @node Numeric_Literals
21494 @subsection @code{Numeric_Literals}
21495 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
21496
21497 @noindent
21498 Flag each use of a numeric literal in an index expression, and in any
21499 circumstance except for the following:
21500
21501 @itemize @bullet
21502 @item
21503 a literal occurring in the initialization expression for a constant
21504 declaration or a named number declaration, or
21505
21506 @item
21507 an integer literal that is less than or equal to a value
21508 specified by the @option{N} rule parameter.
21509 @end itemize
21510
21511 @noindent
21512 This rule may have the following parameters for the @option{+R} option:
21513
21514 @table @asis
21515 @item @emph{N}
21516 @emph{N} is an integer literal used as the maximal value that is not flagged
21517 (i.e., integer literals not exceeding this value are allowed)
21518
21519 @item @code{ALL}
21520 All integer literals are flagged
21521 @end table
21522
21523 @noindent
21524 If no parameters are set, the maximum unflagged value is 1.
21525
21526 The last specified check limit (or the fact that there is no limit at
21527 all) is used when multiple @option{+R} options appear.
21528
21529 The @option{-R} option for this rule has no parameters.
21530 It disables the rule but retains the last specified maximum unflagged value.
21531 If the @option{+R} option subsequently appears, this value is used as the
21532 threshold for the check.
21533
21534
21535 @node OTHERS_In_Aggregates
21536 @subsection @code{OTHERS_In_Aggregates}
21537 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
21538
21539 @noindent
21540 Flag each use of an @code{others} choice in extension aggregates.
21541 In record and array aggregates, an @code{others} choice is flagged unless
21542 it is used to refer to all components, or to all but one component.
21543
21544 If, in case of a named array aggregate, there are two associations, one
21545 with an @code{others} choice and another with a discrete range, the
21546 @code{others} choice is flagged even if the discrete range specifies
21547 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
21548
21549 This rule has no parameters.
21550
21551 @node OTHERS_In_CASE_Statements
21552 @subsection @code{OTHERS_In_CASE_Statements}
21553 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
21554
21555 @noindent
21556 Flag any use of an @code{others} choice in a @code{case} statement.
21557
21558 This rule has no parameters.
21559
21560 @node OTHERS_In_Exception_Handlers
21561 @subsection @code{OTHERS_In_Exception_Handlers}
21562 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
21563
21564 @noindent
21565 Flag any use of an @code{others} choice in an exception handler.
21566
21567 This rule has no parameters.
21568
21569
21570 @node Outer_Loop_Exits
21571 @subsection @code{Outer_Loop_Exits}
21572 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
21573
21574 @noindent
21575 Flag each @code{exit} statement containing a loop name that is not the name
21576 of the immediately enclosing @code{loop} statement.
21577
21578 This rule has no parameters.
21579
21580
21581 @node Overloaded_Operators
21582 @subsection @code{Overloaded_Operators}
21583 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
21584
21585 @noindent
21586 Flag each function declaration that overloads an operator symbol.
21587 A function body is checked only if the body does not have a
21588 separate spec. Formal functions are also checked. For a
21589 renaming declaration, only renaming-as-declaration is checked
21590
21591 This rule has no parameters.
21592
21593
21594 @node Overly_Nested_Control_Structures
21595 @subsection @code{Overly_Nested_Control_Structures}
21596 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
21597
21598 @noindent
21599 Flag each control structure whose nesting level exceeds the value provided
21600 in the rule parameter.
21601
21602 The control structures checked are the following:
21603
21604 @itemize @bullet
21605 @item    @code{if} statement
21606 @item    @code{case} statement
21607 @item    @code{loop} statement
21608 @item    Selective accept statement
21609 @item    Timed entry call statement
21610 @item    Conditional entry call
21611 @item    Asynchronous select statement
21612 @end itemize
21613
21614 @noindent
21615 The rule has the following parameter for the @option{+R} option:
21616
21617 @table @emph
21618 @item N
21619 Positive integer specifying the maximal control structure nesting
21620 level that is not flagged
21621 @end table
21622
21623 @noindent
21624 If the parameter for the @option{+R} option is not specified or
21625 if it is not a positive integer, @option{+R} option is ignored.
21626
21627 If more then one  option is specified for the gnatcheck call, the later option and
21628 new parameter override the previous one(s).
21629
21630
21631 @node Parameters_Out_Of_Order
21632 @subsection @code{Parameters_Out_Of_Order}
21633 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
21634
21635 @noindent
21636 Flag each subprogram and entry declaration whose formal parameters are not
21637 ordered according to the following scheme:
21638
21639 @itemize @bullet
21640
21641 @item @code{in} and @code{access} parameters first,
21642 then @code{in out} parameters,
21643 and then @code{out} parameters;
21644
21645 @item for @code{in} mode, parameters with default initialization expressions
21646 occur last
21647 @end itemize
21648
21649 @noindent
21650 Only the first violation of the described order is flagged.
21651
21652 The following constructs are checked:
21653
21654 @itemize @bullet
21655 @item   subprogram declarations (including null procedures);
21656 @item   generic subprogram declarations;
21657 @item   formal subprogram declarations;
21658 @item   entry declarations;
21659 @item   subprogram bodies and subprogram body stubs that do not
21660 have separate specifications
21661 @end itemize
21662
21663 @noindent
21664 Subprogram renamings are not checked.
21665
21666 This rule has no parameters.
21667
21668
21669 @node Positional_Actuals_For_Defaulted_Generic_Parameters
21670 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
21671 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
21672
21673 @noindent
21674 Flag each generic actual parameter corresponding to a generic formal
21675 parameter with a default initialization, if positional notation is used.
21676
21677 This rule has no parameters.
21678
21679 @node Positional_Actuals_For_Defaulted_Parameters
21680 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
21681 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
21682
21683 @noindent
21684 Flag each actual parameter to a subprogram or entry call where the
21685 corresponding formal parameter has a default expression, if positional
21686 notation is used.
21687
21688 This rule has no parameters.
21689
21690 @node Positional_Components
21691 @subsection @code{Positional_Components}
21692 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
21693
21694 @noindent
21695 Flag each array, record and extension aggregate that includes positional
21696 notation.
21697
21698 This rule has no parameters.
21699
21700
21701 @node Positional_Generic_Parameters
21702 @subsection @code{Positional_Generic_Parameters}
21703 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
21704
21705 @noindent
21706 Flag each instantiation using positional parameter notation.
21707
21708 This rule has no parameters.
21709
21710
21711 @node Positional_Parameters
21712 @subsection @code{Positional_Parameters}
21713 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
21714
21715 @noindent
21716 Flag each subprogram or entry call using positional parameter notation,
21717 except for the following:
21718
21719 @itemize @bullet
21720 @item
21721 Invocations of prefix or infix operators are not flagged
21722 @item
21723 If the called subprogram or entry has only one formal parameter,
21724 the call is not flagged;
21725 @item
21726 If a subprogram call uses the @emph{Object.Operation} notation, then
21727 @itemize @minus
21728 @item
21729 the first parameter (that is, @emph{Object}) is not flagged;
21730 @item
21731 if the called subprogram has only two parameters, the second parameter
21732 of the call is not flagged;
21733 @end itemize
21734 @end itemize
21735
21736 @noindent
21737 This rule has no parameters.
21738
21739
21740
21741
21742 @node Predefined_Numeric_Types
21743 @subsection @code{Predefined_Numeric_Types}
21744 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
21745
21746 @noindent
21747 Flag each explicit use of the name of any numeric type or subtype defined
21748 in package @code{Standard}.
21749
21750 The rationale for this rule is to detect when the
21751 program may depend on platform-specific characteristics of the implementation
21752 of the predefined numeric types. Note that this rule is over-pessimistic;
21753 for example, a program that uses @code{String} indexing
21754 likely needs a variable of type @code{Integer}.
21755 Another example is the flagging of predefined numeric types with explicit
21756 constraints:
21757
21758 @smallexample @c ada
21759     subtype My_Integer is Integer range Left .. Right;
21760     Vy_Var : My_Integer;
21761 @end smallexample
21762
21763 @noindent
21764 This rule detects only numeric types and subtypes defined in
21765 @code{Standard}. The use of numeric types and subtypes defined in other
21766 predefined packages (such as @code{System.Any_Priority} or
21767 @code{Ada.Text_IO.Count}) is not flagged
21768
21769 This rule has no parameters.
21770
21771
21772
21773 @node Raising_External_Exceptions
21774 @subsection @code{Raising_External_Exceptions}
21775 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
21776
21777 @noindent
21778 Flag any @code{raise} statement, in a program unit declared in a library
21779 package or in a generic library package, for an exception that is
21780 neither a predefined exception nor an exception that is also declared (or
21781 renamed) in the visible part of the package.
21782
21783 This rule has no parameters.
21784
21785
21786
21787 @node Raising_Predefined_Exceptions
21788 @subsection @code{Raising_Predefined_Exceptions}
21789 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
21790
21791 @noindent
21792 Flag each @code{raise} statement that raises a predefined exception
21793 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
21794 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
21795
21796 This rule has no parameters.
21797
21798 @node Separate_Numeric_Error_Handlers
21799 @subsection @code{Separate_Numeric_Error_Handlers}
21800 @cindex @code{Separate_Numeric_Error_Handlers} rule (for @command{gnatcheck})
21801
21802 @noindent
21803 Flags each exception handler that contains a choice for
21804 the predefined @code{Constraint_Error} exception, but does not contain
21805 the choice for the predefined @code{Numeric_Error} exception, or
21806 that contains the choice for @code{Numeric_Error}, but does not contain the
21807 choice for @code{Constraint_Error}.
21808
21809 This rule has no parameters.
21810
21811 @ignore
21812 @node Recursion
21813 @subsection @code{Recursion} (under construction, GLOBAL)
21814 @cindex @code{Recursion} rule (for @command{gnatcheck})
21815
21816 @noindent
21817 Flag recursive subprograms (cycles in the call graph). Declarations, and not
21818 calls, of recursive subprograms are detected.
21819
21820 This rule has no parameters.
21821 @end ignore
21822
21823 @ignore
21824 @node Side_Effect_Functions
21825 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
21826 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
21827
21828 @noindent
21829 Flag functions with side effects.
21830
21831 We define a side effect as changing any data object that is not local for the
21832 body of this function.
21833
21834 At the moment, we do NOT consider a side effect any input-output operations
21835 (changing a state or a content of any file).
21836
21837 We do not consider protected functions for this rule (???)
21838
21839 There are the following sources of side effect:
21840
21841 @enumerate
21842 @item Explicit (or direct) side-effect:
21843
21844 @itemize @bullet
21845 @item
21846 direct assignment to a non-local variable;
21847
21848 @item
21849 direct call to an entity that is known to change some data object that is
21850      not local for the body of this function (Note, that if F1 calls F2 and F2
21851      does have a side effect, this does not automatically mean that F1 also
21852      have a side effect, because it may be the case that F2 is declared in
21853      F1's body and it changes some data object that is global for F2, but
21854      local for F1);
21855 @end itemize
21856
21857 @item Indirect side-effect:
21858 @itemize @bullet
21859 @item
21860 Subprogram calls implicitly issued by:
21861 @itemize @bullet
21862 @item
21863 computing initialization expressions from type declarations as a part
21864          of object elaboration or allocator evaluation;
21865 @item
21866 computing implicit parameters of subprogram or entry calls or generic
21867          instantiations;
21868 @end itemize
21869
21870 @item
21871 activation of a task that change some non-local data object (directly or
21872      indirectly);
21873
21874 @item
21875 elaboration code of a package that is a result of a package instantiation;
21876
21877 @item
21878 controlled objects;
21879 @end itemize
21880
21881 @item Situations when we can suspect a side-effect, but the full static check
21882 is either impossible or too hard:
21883 @itemize @bullet
21884 @item
21885 assignment to access variables or to the objects pointed by access
21886      variables;
21887
21888 @item
21889 call to a subprogram pointed by access-to-subprogram value
21890
21891 @item
21892 dispatching calls;
21893 @end itemize
21894 @end enumerate
21895
21896 @noindent
21897 This rule has no parameters.
21898 @end ignore
21899
21900 @node Slices
21901 @subsection @code{Slices}
21902 @cindex @code{Slices} rule (for @command{gnatcheck})
21903
21904 @noindent
21905 Flag all uses of array slicing
21906
21907 This rule has no parameters.
21908
21909
21910 @node Unassigned_OUT_Parameters
21911 @subsection @code{Unassigned_OUT_Parameters}
21912 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
21913
21914 @noindent
21915 Flags procedures' @code{out} parameters that are not assigned, and
21916 identifies the contexts in which the assignments are missing.
21917
21918 An @code{out} parameter is flagged in the statements in the procedure
21919 body's handled sequence of statements (before the procedure body's
21920 @code{exception} part, if any) if this sequence of statements contains
21921 no assignments to the parameter.
21922
21923 An @code{out} parameter is flagged in an exception handler in the exception
21924 part of the procedure body's handled sequence of statements if the handler
21925 contains no assignment to the parameter.
21926
21927 Bodies of generic procedures are also considered.
21928
21929 The following are treated as assignments to an @code{out} parameter:
21930
21931 @itemize @bullet
21932 @item
21933 an assignment statement, with the parameter or some component as the target;
21934
21935 @item
21936 passing the parameter (or one of its components) as an @code{out} or
21937 @code{in out} parameter.
21938 @end itemize
21939
21940 @noindent
21941 This rule does not have any parameters.
21942
21943
21944
21945 @node Uncommented_BEGIN_In_Package_Bodies
21946 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
21947 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
21948
21949 @noindent
21950 Flags each package body with declarations and a statement part that does not
21951 include a trailing comment on the line containing the @code{begin} keyword;
21952 this trailing comment needs to specify the package name and nothing else.
21953 The @code{begin} is not flagged if the package body does not
21954 contain any declarations.
21955
21956 If the @code{begin} keyword is placed on the
21957 same line as the last declaration or the first statement, it is flagged
21958 independently of whether the line contains a trailing comment. The
21959 diagnostic message is attached to the line containing the first statement.
21960
21961 This rule has no parameters.
21962
21963
21964 @node Unconstrained_Array_Returns
21965 @subsection @code{Unconstrained_Array_Returns}
21966 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
21967
21968 @noindent
21969 Flag each function returning an unconstrained array. Function declarations,
21970 function bodies (and body stubs) having no separate specifications,
21971 and generic function instantiations are checked.
21972 Generic function declarations, function calls and function renamings are
21973 not checked.
21974
21975 This rule has no parameters.
21976
21977 @node Universal_Ranges
21978 @subsection @code{Universal_Ranges}
21979 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
21980
21981 @noindent
21982 Flag discrete ranges that are a part of an index constraint, constrained
21983 array definition, or @code{for}-loop parameter specification, and whose bounds
21984 are both of type @i{universal_integer}. Ranges that have at least one
21985 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
21986 or an expression of non-universal type) are not flagged.
21987
21988 This rule has no parameters.
21989
21990
21991 @node Unnamed_Blocks_And_Loops
21992 @subsection @code{Unnamed_Blocks_And_Loops}
21993 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
21994
21995 @noindent
21996 Flag each unnamed block statement and loop statement.
21997
21998 The rule has no parameters.
21999
22000
22001
22002 @ignore
22003 @node Unused_Subprograms
22004 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
22005 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
22006
22007 @noindent
22008 Flag all unused subprograms.
22009
22010 This rule has no parameters.
22011 @end ignore
22012
22013
22014
22015
22016 @node USE_PACKAGE_Clauses
22017 @subsection @code{USE_PACKAGE_Clauses}
22018 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
22019
22020 @noindent
22021 Flag all @code{use} clauses for packages; @code{use type} clauses are
22022 not flagged.
22023
22024 This rule has no parameters.
22025
22026
22027
22028 @node Volatile_Objects_Without_Address_Clauses
22029 @subsection @code{Volatile_Objects_Without_Address_Clauses}
22030 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
22031
22032 @noindent
22033 Flag each volatile object that does not have an address clause.
22034
22035 The following check is made: if the pragma @code{Volatile} is applied to a
22036 data object or to its type, then an address clause must
22037 be supplied for this object.
22038
22039 This rule does not check the components of data objects,
22040 array components that are volatile as a result of the pragma
22041 @code{Volatile_Components}, or objects that are volatile because
22042 they are atomic as a result of pragmas @code{Atomic} or
22043 @code{Atomic_Components}.
22044
22045 Only variable declarations, and not constant declarations, are checked.
22046
22047 This rule has no parameters.
22048
22049
22050 @c *********************************
22051 @node Creating Sample Bodies Using gnatstub
22052 @chapter Creating Sample Bodies Using @command{gnatstub}
22053 @findex gnatstub
22054
22055 @noindent
22056 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
22057 for library unit declarations.
22058
22059 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
22060 driver (see @ref{The GNAT Driver and Project Files}).
22061
22062 To create a body stub, @command{gnatstub} has to compile the library
22063 unit declaration. Therefore, bodies can be created only for legal
22064 library units. Moreover, if a library unit depends semantically upon
22065 units located outside the current directory, you have to provide
22066 the source search path when calling @command{gnatstub}, see the description
22067 of @command{gnatstub} switches below.
22068
22069 By default, all the program unit body stubs generated by @code{gnatstub}
22070 raise the predefined @code{Program_Error} exception, which will catch
22071 accidental calls of generated stubs. This behavior can be changed with
22072 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
22073
22074 @menu
22075 * Running gnatstub::
22076 * Switches for gnatstub::
22077 @end menu
22078
22079 @node Running gnatstub
22080 @section Running @command{gnatstub}
22081
22082 @noindent
22083 @command{gnatstub} has the command-line interface of the form
22084
22085 @smallexample
22086 $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
22087 @end smallexample
22088
22089 @noindent
22090 where
22091 @table @var
22092 @item filename
22093 is the name of the source file that contains a library unit declaration
22094 for which a body must be created. The file name may contain the path
22095 information.
22096 The file name does not have to follow the GNAT file name conventions. If the
22097 name
22098 does not follow GNAT file naming conventions, the name of the body file must
22099 be provided
22100 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
22101 If the file name follows the GNAT file naming
22102 conventions and the name of the body file is not provided,
22103 @command{gnatstub}
22104 creates the name
22105 of the body file from the argument file name by replacing the @file{.ads}
22106 suffix
22107 with the @file{.adb} suffix.
22108
22109 @item directory
22110 indicates the directory in which the body stub is to be placed (the default
22111 is the
22112 current directory)
22113
22114 @item switches
22115 is an optional sequence of switches as described in the next section
22116 @end table
22117
22118 @node Switches for gnatstub
22119 @section Switches for @command{gnatstub}
22120
22121 @table @option
22122 @c !sort!
22123
22124 @item ^-f^/FULL^
22125 @cindex @option{^-f^/FULL^} (@command{gnatstub})
22126 If the destination directory already contains a file with the name of the
22127 body file
22128 for the argument spec file, replace it with the generated body stub.
22129
22130 @item ^-hs^/HEADER=SPEC^
22131 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
22132 Put the comment header (i.e., all the comments preceding the
22133 compilation unit) from the source of the library unit declaration
22134 into the body stub.
22135
22136 @item ^-hg^/HEADER=GENERAL^
22137 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
22138 Put a sample comment header into the body stub.
22139
22140 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
22141 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
22142 Use the content of the file as the comment header for a generated body stub.
22143
22144 @ifclear vms
22145 @item -IDIR
22146 @cindex @option{-IDIR} (@command{gnatstub})
22147 @itemx -I-
22148 @cindex @option{-I-} (@command{gnatstub})
22149 @end ifclear
22150 @ifset vms
22151 @item /NOCURRENT_DIRECTORY
22152 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
22153 @end ifset
22154 ^These switches have ^This switch has^ the same meaning as in calls to
22155 @command{gcc}.
22156 ^They define ^It defines ^ the source search path in the call to
22157 @command{gcc} issued
22158 by @command{gnatstub} to compile an argument source file.
22159
22160 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
22161 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
22162 This switch has the same meaning as in calls to @command{gcc}.
22163 It defines the additional configuration file to be passed to the call to
22164 @command{gcc} issued
22165 by @command{gnatstub} to compile an argument source file.
22166
22167 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
22168 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
22169 (@var{n} is a non-negative integer). Set the maximum line length in the
22170 body stub to @var{n}; the default is 79. The maximum value that can be
22171 specified is 32767. Note that in the special case of configuration
22172 pragma files, the maximum is always 32767 regardless of whether or
22173 not this switch appears.
22174
22175 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
22176 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
22177 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
22178 the generated body sample to @var{n}.
22179 The default indentation is 3.
22180
22181 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
22182 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
22183 Order local bodies alphabetically. (By default local bodies are ordered
22184 in the same way as the corresponding local specs in the argument spec file.)
22185
22186 @item ^-i^/INDENTATION=^@var{n}
22187 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
22188 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
22189
22190 @item ^-k^/TREE_FILE=SAVE^
22191 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
22192 Do not remove the tree file (i.e., the snapshot of the compiler internal
22193 structures used by @command{gnatstub}) after creating the body stub.
22194
22195 @item ^-l^/LINE_LENGTH=^@var{n}
22196 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
22197 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
22198
22199 @item ^--no-exception^/NO_EXCEPTION^
22200 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
22201 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
22202 This is not always possible for function stubs.
22203
22204 @item ^-o ^/BODY=^@var{body-name}
22205 @cindex @option{^-o^/BODY^} (@command{gnatstub})
22206 Body file name.  This should be set if the argument file name does not
22207 follow
22208 the GNAT file naming
22209 conventions. If this switch is omitted the default name for the body will be
22210 obtained
22211 from the argument file name according to the GNAT file naming conventions.
22212
22213 @item ^-q^/QUIET^
22214 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
22215 Quiet mode: do not generate a confirmation when a body is
22216 successfully created, and do not generate a message when a body is not
22217 required for an
22218 argument unit.
22219
22220 @item ^-r^/TREE_FILE=REUSE^
22221 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
22222 Reuse the tree file (if it exists) instead of creating it.  Instead of
22223 creating the tree file for the library unit declaration, @command{gnatstub}
22224 tries to find it in the current directory and use it for creating
22225 a body. If the tree file is not found, no body is created. This option
22226 also implies @option{^-k^/SAVE^}, whether or not
22227 the latter is set explicitly.
22228
22229 @item ^-t^/TREE_FILE=OVERWRITE^
22230 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
22231 Overwrite the existing tree file.  If the current directory already
22232 contains the file which, according to the GNAT file naming rules should
22233 be considered as a tree file for the argument source file,
22234 @command{gnatstub}
22235 will refuse to create the tree file needed to create a sample body
22236 unless this option is set.
22237
22238 @item ^-v^/VERBOSE^
22239 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
22240 Verbose mode: generate version information.
22241
22242 @end table
22243
22244 @node Other Utility Programs
22245 @chapter Other Utility Programs
22246
22247 @noindent
22248 This chapter discusses some other utility programs available in the Ada
22249 environment.
22250
22251 @menu
22252 * Using Other Utility Programs with GNAT::
22253 * The External Symbol Naming Scheme of GNAT::
22254 * Converting Ada Files to html with gnathtml::
22255 * Installing gnathtml::
22256 @ifset vms
22257 * LSE::
22258 * Profiling::
22259 @end ifset
22260 @end menu
22261
22262 @node Using Other Utility Programs with GNAT
22263 @section Using Other Utility Programs with GNAT
22264
22265 @noindent
22266 The object files generated by GNAT are in standard system format and in
22267 particular the debugging information uses this format. This means
22268 programs generated by GNAT can be used with existing utilities that
22269 depend on these formats.
22270
22271 @ifclear vms
22272 In general, any utility program that works with C will also often work with
22273 Ada programs generated by GNAT. This includes software utilities such as
22274 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
22275 as Purify.
22276 @end ifclear
22277
22278 @node The External Symbol Naming Scheme of GNAT
22279 @section The External Symbol Naming Scheme of GNAT
22280
22281 @noindent
22282 In order to interpret the output from GNAT, when using tools that are
22283 originally intended for use with other languages, it is useful to
22284 understand the conventions used to generate link names from the Ada
22285 entity names.
22286
22287 All link names are in all lowercase letters. With the exception of library
22288 procedure names, the mechanism used is simply to use the full expanded
22289 Ada name with dots replaced by double underscores. For example, suppose
22290 we have the following package spec:
22291
22292 @smallexample @c ada
22293 @group
22294 @cartouche
22295 package QRS is
22296    MN : Integer;
22297 end QRS;
22298 @end cartouche
22299 @end group
22300 @end smallexample
22301
22302 @noindent
22303 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
22304 the corresponding link name is @code{qrs__mn}.
22305 @findex Export
22306 Of course if a @code{pragma Export} is used this may be overridden:
22307
22308 @smallexample @c ada
22309 @group
22310 @cartouche
22311 package Exports is
22312    Var1 : Integer;
22313    pragma Export (Var1, C, External_Name => "var1_name");
22314    Var2 : Integer;
22315    pragma Export (Var2, C, Link_Name => "var2_link_name");
22316 end Exports;
22317 @end cartouche
22318 @end group
22319 @end smallexample
22320
22321 @noindent
22322 In this case, the link name for @var{Var1} is whatever link name the
22323 C compiler would assign for the C function @var{var1_name}. This typically
22324 would be either @var{var1_name} or @var{_var1_name}, depending on operating
22325 system conventions, but other possibilities exist. The link name for
22326 @var{Var2} is @var{var2_link_name}, and this is not operating system
22327 dependent.
22328
22329 @findex _main
22330 One exception occurs for library level procedures. A potential ambiguity
22331 arises between the required name @code{_main} for the C main program,
22332 and the name we would otherwise assign to an Ada library level procedure
22333 called @code{Main} (which might well not be the main program).
22334
22335 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
22336 names. So if we have a library level procedure such as
22337
22338 @smallexample @c ada
22339 @group
22340 @cartouche
22341 procedure Hello (S : String);
22342 @end cartouche
22343 @end group
22344 @end smallexample
22345
22346 @noindent
22347 the external name of this procedure will be @var{_ada_hello}.
22348
22349
22350 @node Converting Ada Files to html with gnathtml
22351 @section Converting Ada Files to HTML with @code{gnathtml}
22352
22353 @noindent
22354 This @code{Perl} script allows Ada source files to be browsed using
22355 standard Web browsers. For installation procedure, see the section
22356 @xref{Installing gnathtml}.
22357
22358 Ada reserved keywords are highlighted in a bold font and Ada comments in
22359 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
22360 switch to suppress the generation of cross-referencing information, user
22361 defined variables and types will appear in a different color; you will
22362 be able to click on any identifier and go to its declaration.
22363
22364 The command line is as follow:
22365 @smallexample
22366 $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
22367 @end smallexample
22368
22369 @noindent
22370 You can pass it as many Ada files as you want. @code{gnathtml} will generate
22371 an html file for every ada file, and a global file called @file{index.htm}.
22372 This file is an index of every identifier defined in the files.
22373
22374 The available ^switches^options^ are the following ones:
22375
22376 @table @option
22377 @item -83
22378 @cindex @option{-83} (@code{gnathtml})
22379 Only the Ada 83 subset of keywords will be highlighted.
22380
22381 @item -cc @var{color}
22382 @cindex @option{-cc} (@code{gnathtml})
22383 This option allows you to change the color used for comments. The default
22384 value is green. The color argument can be any name accepted by html.
22385
22386 @item -d
22387 @cindex @option{-d} (@code{gnathtml})
22388 If the Ada files depend on some other files (for instance through
22389 @code{with} clauses, the latter files will also be converted to html.
22390 Only the files in the user project will be converted to html, not the files
22391 in the run-time library itself.
22392
22393 @item -D
22394 @cindex @option{-D} (@code{gnathtml})
22395 This command is the same as @option{-d} above, but @command{gnathtml} will
22396 also look for files in the run-time library, and generate html files for them.
22397
22398 @item -ext @var{extension}
22399 @cindex @option{-ext} (@code{gnathtml})
22400 This option allows you to change the extension of the generated HTML files.
22401 If you do not specify an extension, it will default to @file{htm}.
22402
22403 @item -f
22404 @cindex @option{-f} (@code{gnathtml})
22405 By default, gnathtml will generate html links only for global entities
22406 ('with'ed units, global variables and types,@dots{}).  If you specify
22407 @option{-f} on the command line, then links will be generated for local
22408 entities too.
22409
22410 @item -l @var{number}
22411 @cindex @option{-l} (@code{gnathtml})
22412 If this ^switch^option^ is provided and @var{number} is not 0, then
22413 @code{gnathtml} will number the html files every @var{number} line.
22414
22415 @item -I @var{dir}
22416 @cindex @option{-I} (@code{gnathtml})
22417 Specify a directory to search for library files (@file{.ALI} files) and
22418 source files. You can provide several -I switches on the command line,
22419 and the directories will be parsed in the order of the command line.
22420
22421 @item -o @var{dir}
22422 @cindex @option{-o} (@code{gnathtml})
22423 Specify the output directory for html files. By default, gnathtml will
22424 saved the generated html files in a subdirectory named @file{html/}.
22425
22426 @item -p @var{file}
22427 @cindex @option{-p} (@code{gnathtml})
22428 If you are using Emacs and the most recent Emacs Ada mode, which provides
22429 a full Integrated Development Environment for compiling, checking,
22430 running and debugging applications, you may use @file{.gpr} files
22431 to give the directories where Emacs can find sources and object files.
22432
22433 Using this ^switch^option^, you can tell gnathtml to use these files.
22434 This allows you to get an html version of your application, even if it
22435 is spread over multiple directories.
22436
22437 @item -sc @var{color}
22438 @cindex @option{-sc} (@code{gnathtml})
22439 This ^switch^option^ allows you to change the color used for symbol
22440 definitions.
22441 The default value is red. The color argument can be any name accepted by html.
22442
22443 @item -t @var{file}
22444 @cindex @option{-t} (@code{gnathtml})
22445 This ^switch^option^ provides the name of a file. This file contains a list of
22446 file names to be converted, and the effect is exactly as though they had
22447 appeared explicitly on the command line. This
22448 is the recommended way to work around the command line length limit on some
22449 systems.
22450
22451 @end table
22452
22453 @node Installing gnathtml
22454 @section Installing @code{gnathtml}
22455
22456 @noindent
22457 @code{Perl} needs to be installed on your machine to run this script.
22458 @code{Perl} is freely available for almost every architecture and
22459 Operating System via the Internet.
22460
22461 On Unix systems, you  may want to modify  the  first line of  the script
22462 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
22463 is. The syntax of this line is:
22464 @smallexample
22465 #!full_path_name_to_perl
22466 @end smallexample
22467
22468 @noindent
22469 Alternatively, you may run the script using the following command line:
22470
22471 @smallexample
22472 $ perl gnathtml.pl @ovar{switches} @var{files}
22473 @end smallexample
22474
22475 @ifset vms
22476 @node LSE
22477 @section LSE
22478 @findex LSE
22479
22480 @noindent
22481 The GNAT distribution provides an Ada 95 template for the HP Language
22482 Sensitive Editor (LSE), a component of DECset. In order to
22483 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
22484
22485 @node Profiling
22486 @section Profiling
22487 @findex PCA
22488
22489 @noindent
22490 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
22491 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
22492 the collection phase with the /DEBUG qualifier.
22493
22494 @smallexample
22495 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
22496 $ DEFINE LIB$DEBUG PCA$COLLECTOR
22497 $ RUN/DEBUG <PROGRAM_NAME>
22498 @end smallexample
22499 @noindent
22500 @end ifset
22501
22502 @ifclear vms
22503 @c ******************************
22504 @node Code Coverage and Profiling
22505 @chapter Code Coverage and Profiling
22506 @cindex Code Coverage
22507 @cindex Profiling
22508
22509 @noindent
22510 This chapter describes how to use @code{gcov} - coverage testing tool - and
22511 @code{gprof} - profiler tool - on your Ada programs.
22512
22513 @menu
22514 * Code Coverage of Ada Programs using gcov::
22515 * Profiling an Ada Program using gprof::
22516 @end menu
22517
22518 @node Code Coverage of Ada Programs using gcov
22519 @section Code Coverage of Ada Programs using gcov
22520 @cindex gcov
22521 @cindex -fprofile-arcs
22522 @cindex -ftest-coverage
22523 @cindex -coverage
22524 @cindex Code Coverage
22525
22526 @noindent
22527 @code{gcov} is a test coverage program: it analyzes the execution of a given
22528 program on selected tests, to help you determine the portions of the program
22529 that are still untested.
22530
22531 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
22532 User's Guide. You can refer to this documentation for a more complete
22533 description.
22534
22535 This chapter provides a quick startup guide, and
22536 details some Gnat-specific features.
22537
22538 @menu
22539 * Quick startup guide::
22540 * Gnat specifics::
22541 @end menu
22542
22543 @node Quick startup guide
22544 @subsection Quick startup guide
22545
22546 In order to perform coverage analysis of a program using @code{gcov}, 3
22547 steps are needed:
22548
22549 @itemize @bullet
22550 @item
22551 Code instrumentation during the compilation process
22552 @item
22553 Execution of the instrumented program
22554 @item
22555 Execution of the @code{gcov} tool to generate the result.
22556 @end itemize
22557
22558 The code instrumentation needed by gcov is created at the object level:
22559 The source code is not modified in any way, because the instrumentation code is
22560 inserted by gcc during the compilation process. To compile your code with code
22561 coverage activated, you need to recompile your whole project using the
22562 switches
22563 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
22564 @code{-fprofile-arcs}.
22565
22566 @smallexample
22567 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
22568    -largs -fprofile-arcs
22569 @end smallexample
22570
22571 This compilation process will create @file{.gcno} files together with
22572 the usual object files.
22573
22574 Once the program is compiled with coverage instrumentation, you can
22575 run it as many times as needed - on portions of a test suite for
22576 example. The first execution will produce @file{.gcda} files at the
22577 same location as the @file{.gcno} files.  The following executions
22578 will update those files, so that a cumulative result of the covered
22579 portions of the program is generated.
22580
22581 Finally, you need to call the @code{gcov} tool. The different options of
22582 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
22583
22584 This will create annotated source files with a @file{.gcov} extension:
22585 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
22586
22587 @node Gnat specifics
22588 @subsection Gnat specifics
22589
22590 Because Ada semantics, portions of the source code may be shared among
22591 several object files. This is the case for example when generics are
22592 involved, when inlining is active  or when declarations generate  initialisation
22593 calls. In order to take
22594 into account this shared code, you need to call @code{gcov} on all
22595 source files of the tested program at once.
22596
22597 The list of source files might exceed the system's maximum command line
22598 length. In order to bypass this limitation, a new mechanism has been
22599 implemented in @code{gcov}: you can now list all your project's files into a
22600 text file, and provide this file to gcov as a parameter,  preceded by a @@
22601 (e.g. @samp{gcov @@mysrclist.txt}).
22602
22603 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
22604 not supported as there can be unresolved symbols during the final link.
22605
22606 @node Profiling an Ada Program using gprof
22607 @section Profiling an Ada Program using gprof
22608 @cindex gprof
22609 @cindex -pg
22610 @cindex Profiling
22611
22612 @noindent
22613 This section is not meant to be an exhaustive documentation of @code{gprof}.
22614 Full documentation for it can be found in the GNU Profiler User's Guide
22615 documentation that is part of this GNAT distribution.
22616
22617 Profiling a program helps determine the parts of a program that are executed
22618 most often, and are therefore the most time-consuming.
22619
22620 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
22621 better handle Ada programs and multitasking.
22622 It is currently supported on the following platforms
22623 @itemize @bullet
22624 @item
22625 linux x86/x86_64
22626 @item
22627 solaris sparc/sparc64/x86
22628 @item
22629 windows x86
22630 @end itemize
22631
22632 @noindent
22633 In order to profile a program using @code{gprof}, 3 steps are needed:
22634
22635 @itemize @bullet
22636 @item
22637 Code instrumentation, requiring a full recompilation of the project with the
22638 proper switches.
22639 @item
22640 Execution of the program under the analysis conditions, i.e. with the desired
22641 input.
22642 @item
22643 Analysis of the results using the @code{gprof} tool.
22644 @end itemize
22645
22646 @noindent
22647 The following sections detail the different steps, and indicate how
22648 to interpret the results:
22649 @menu
22650 * Compilation for profiling::
22651 * Program execution::
22652 * Running gprof::
22653 * Interpretation of profiling results::
22654 @end menu
22655
22656 @node Compilation for profiling
22657 @subsection Compilation for profiling
22658 @cindex -pg
22659 @cindex Profiling
22660
22661 In order to profile a program the first step is to tell the compiler
22662 to generate the necessary profiling information. The compiler switch to be used
22663 is @code{-pg}, which must be added to other compilation switches. This
22664 switch needs to be specified both during compilation and link stages, and can
22665 be specified once when using gnatmake:
22666
22667 @smallexample
22668 gnatmake -f -pg -P my_project
22669 @end smallexample
22670
22671 @noindent
22672 Note that only the objects that were compiled with the @samp{-pg} switch will be
22673 profiled; if you need to profile your whole project, use the
22674 @samp{-f} gnatmake switch to force full recompilation.
22675
22676 @node Program execution
22677 @subsection Program execution
22678
22679 @noindent
22680 Once the program has been compiled for profiling, you can run it as usual.
22681
22682 The only constraint imposed by profiling is that the program must terminate
22683 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
22684 properly analyzed.
22685
22686 Once the program completes execution, a data file called @file{gmon.out} is
22687 generated in the directory where the program was launched from. If this file
22688 already exists, it will be overwritten.
22689
22690 @node Running gprof
22691 @subsection Running gprof
22692
22693 @noindent
22694 The @code{gprof} tool is called as follow:
22695
22696 @smallexample
22697 gprof my_prog gmon.out
22698 @end smallexample
22699
22700 @noindent
22701 or simpler:
22702
22703 @smallexample
22704 gprof my_prog
22705 @end smallexample
22706
22707 @noindent
22708 The complete form of the gprof command line is the following:
22709
22710 @smallexample
22711 gprof [^switches^options^] [executable [data-file]]
22712 @end smallexample
22713
22714 @noindent
22715 @code{gprof} supports numerous ^switch^options^. The order of these
22716 ^switch^options^ does not matter. The full list of options can be found in
22717 the GNU Profiler User's Guide documentation that comes with this documentation.
22718
22719 The following is the subset of those switches that is most relevant:
22720
22721 @table @option
22722
22723 @item --demangle[=@var{style}]
22724 @itemx --no-demangle
22725 @cindex @option{--demangle} (@code{gprof})
22726 These options control whether symbol names should be demangled when
22727 printing output.  The default is to demangle C++ symbols.  The
22728 @code{--no-demangle} option may be used to turn off demangling. Different
22729 compilers have different mangling styles.  The optional demangling style
22730 argument can be used to choose an appropriate demangling style for your
22731 compiler, in particular Ada symbols generated by GNAT can be demangled using
22732 @code{--demangle=gnat}.
22733
22734 @item -e @var{function_name}
22735 @cindex @option{-e} (@code{gprof})
22736 The @samp{-e @var{function}} option tells @code{gprof} not to print
22737 information about the function @var{function_name} (and its
22738 children@dots{}) in the call graph.  The function will still be listed
22739 as a child of any functions that call it, but its index number will be
22740 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
22741 given; only one @var{function_name} may be indicated with each @samp{-e}
22742 option.
22743
22744 @item -E @var{function_name}
22745 @cindex @option{-E} (@code{gprof})
22746 The @code{-E @var{function}} option works like the @code{-e} option, but
22747 execution time spent in the function (and children who were not called from
22748 anywhere else), will not be used to compute the percentages-of-time for
22749 the call graph.  More than one @samp{-E} option may be given; only one
22750 @var{function_name} may be indicated with each @samp{-E} option.
22751
22752 @item -f @var{function_name}
22753 @cindex @option{-f} (@code{gprof})
22754 The @samp{-f @var{function}} option causes @code{gprof} to limit the
22755 call graph to the function @var{function_name} and its children (and
22756 their children@dots{}).  More than one @samp{-f} option may be given;
22757 only one @var{function_name} may be indicated with each @samp{-f}
22758 option.
22759
22760 @item -F @var{function_name}
22761 @cindex @option{-F} (@code{gprof})
22762 The @samp{-F @var{function}} option works like the @code{-f} option, but
22763 only time spent in the function and its children (and their
22764 children@dots{}) will be used to determine total-time and
22765 percentages-of-time for the call graph.  More than one @samp{-F} option
22766 may be given; only one @var{function_name} may be indicated with each
22767 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
22768
22769 @end table
22770
22771 @node Interpretation of profiling results
22772 @subsection Interpretation of profiling results
22773
22774 @noindent
22775
22776 The results of the profiling analysis are represented by two arrays: the
22777 'flat profile' and the 'call graph'. Full documentation of those outputs
22778 can be found in the GNU Profiler User's Guide.
22779
22780 The flat profile shows the time spent in each function of the program, and how
22781 many time it has been called. This allows you to locate easily the most
22782 time-consuming functions.
22783
22784 The call graph shows, for each subprogram, the subprograms that call it,
22785 and the subprograms that it calls. It also provides an estimate of the time
22786 spent in each of those callers/called subprograms.
22787 @end ifclear
22788
22789 @c ******************************
22790 @node Running and Debugging Ada Programs
22791 @chapter Running and Debugging Ada Programs
22792 @cindex Debugging
22793
22794 @noindent
22795 This chapter discusses how to debug Ada programs.
22796 @ifset vms
22797 It applies to GNAT on the Alpha OpenVMS platform;
22798 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
22799 since HP has implemented Ada support in the OpenVMS debugger on I64.
22800 @end ifset
22801
22802 An incorrect Ada program may be handled in three ways by the GNAT compiler:
22803
22804 @enumerate
22805 @item
22806 The illegality may be a violation of the static semantics of Ada. In
22807 that case GNAT diagnoses the constructs in the program that are illegal.
22808 It is then a straightforward matter for the user to modify those parts of
22809 the program.
22810
22811 @item
22812 The illegality may be a violation of the dynamic semantics of Ada. In
22813 that case the program compiles and executes, but may generate incorrect
22814 results, or may terminate abnormally with some exception.
22815
22816 @item
22817 When presented with a program that contains convoluted errors, GNAT
22818 itself may terminate abnormally without providing full diagnostics on
22819 the incorrect user program.
22820 @end enumerate
22821
22822 @menu
22823 * The GNAT Debugger GDB::
22824 * Running GDB::
22825 * Introduction to GDB Commands::
22826 * Using Ada Expressions::
22827 * Calling User-Defined Subprograms::
22828 * Using the Next Command in a Function::
22829 * Ada Exceptions::
22830 * Ada Tasks::
22831 * Debugging Generic Units::
22832 * GNAT Abnormal Termination or Failure to Terminate::
22833 * Naming Conventions for GNAT Source Files::
22834 * Getting Internal Debugging Information::
22835 * Stack Traceback::
22836 @end menu
22837
22838 @cindex Debugger
22839 @findex gdb
22840
22841 @node The GNAT Debugger GDB
22842 @section The GNAT Debugger GDB
22843
22844 @noindent
22845 @code{GDB} is a general purpose, platform-independent debugger that
22846 can be used to debug mixed-language programs compiled with @command{gcc},
22847 and in particular is capable of debugging Ada programs compiled with
22848 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
22849 complex Ada data structures.
22850
22851 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
22852 @ifset vms
22853 located in the GNU:[DOCS] directory,
22854 @end ifset
22855 for full details on the usage of @code{GDB}, including a section on
22856 its usage on programs. This manual should be consulted for full
22857 details. The section that follows is a brief introduction to the
22858 philosophy and use of @code{GDB}.
22859
22860 When GNAT programs are compiled, the compiler optionally writes debugging
22861 information into the generated object file, including information on
22862 line numbers, and on declared types and variables. This information is
22863 separate from the generated code. It makes the object files considerably
22864 larger, but it does not add to the size of the actual executable that
22865 will be loaded into memory, and has no impact on run-time performance. The
22866 generation of debug information is triggered by the use of the
22867 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
22868 used to carry out the compilations. It is important to emphasize that
22869 the use of these options does not change the generated code.
22870
22871 The debugging information is written in standard system formats that
22872 are used by many tools, including debuggers and profilers. The format
22873 of the information is typically designed to describe C types and
22874 semantics, but GNAT implements a translation scheme which allows full
22875 details about Ada types and variables to be encoded into these
22876 standard C formats. Details of this encoding scheme may be found in
22877 the file exp_dbug.ads in the GNAT source distribution. However, the
22878 details of this encoding are, in general, of no interest to a user,
22879 since @code{GDB} automatically performs the necessary decoding.
22880
22881 When a program is bound and linked, the debugging information is
22882 collected from the object files, and stored in the executable image of
22883 the program. Again, this process significantly increases the size of
22884 the generated executable file, but it does not increase the size of
22885 the executable program itself. Furthermore, if this program is run in
22886 the normal manner, it runs exactly as if the debug information were
22887 not present, and takes no more actual memory.
22888
22889 However, if the program is run under control of @code{GDB}, the
22890 debugger is activated.  The image of the program is loaded, at which
22891 point it is ready to run.  If a run command is given, then the program
22892 will run exactly as it would have if @code{GDB} were not present. This
22893 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
22894 entirely non-intrusive until a breakpoint is encountered.  If no
22895 breakpoint is ever hit, the program will run exactly as it would if no
22896 debugger were present. When a breakpoint is hit, @code{GDB} accesses
22897 the debugging information and can respond to user commands to inspect
22898 variables, and more generally to report on the state of execution.
22899
22900 @c **************
22901 @node Running GDB
22902 @section Running GDB
22903
22904 @noindent
22905 This section describes how to initiate the debugger.
22906 @c The above sentence is really just filler, but it was otherwise
22907 @c clumsy to get the first paragraph nonindented given the conditional
22908 @c nature of the description
22909
22910 @ifclear vms
22911 The debugger can be launched from a @code{GPS} menu or
22912 directly from the command line. The description below covers the latter use.
22913 All the commands shown can be used in the @code{GPS} debug console window,
22914 but there are usually more GUI-based ways to achieve the same effect.
22915 @end ifclear
22916
22917 The command to run @code{GDB} is
22918
22919 @smallexample
22920 $ ^gdb program^GDB PROGRAM^
22921 @end smallexample
22922
22923 @noindent
22924 where @code{^program^PROGRAM^} is the name of the executable file. This
22925 activates the debugger and results in a prompt for debugger commands.
22926 The simplest command is simply @code{run}, which causes the program to run
22927 exactly as if the debugger were not present. The following section
22928 describes some of the additional commands that can be given to @code{GDB}.
22929
22930 @c *******************************
22931 @node Introduction to GDB Commands
22932 @section Introduction to GDB Commands
22933
22934 @noindent
22935 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
22936 Debugging with GDB, gdb, Debugging with GDB},
22937 @ifset vms
22938 located in the GNU:[DOCS] directory,
22939 @end ifset
22940 for extensive documentation on the use
22941 of these commands, together with examples of their use. Furthermore,
22942 the command @command{help} invoked from within GDB activates a simple help
22943 facility which summarizes the available commands and their options.
22944 In this section we summarize a few of the most commonly
22945 used commands to give an idea of what @code{GDB} is about. You should create
22946 a simple program with debugging information and experiment with the use of
22947 these @code{GDB} commands on the program as you read through the
22948 following section.
22949
22950 @table @code
22951 @item set args @var{arguments}
22952 The @var{arguments} list above is a list of arguments to be passed to
22953 the program on a subsequent run command, just as though the arguments
22954 had been entered on a normal invocation of the program. The @code{set args}
22955 command is not needed if the program does not require arguments.
22956
22957 @item run
22958 The @code{run} command causes execution of the program to start from
22959 the beginning. If the program is already running, that is to say if
22960 you are currently positioned at a breakpoint, then a prompt will ask
22961 for confirmation that you want to abandon the current execution and
22962 restart.
22963
22964 @item breakpoint @var{location}
22965 The breakpoint command sets a breakpoint, that is to say a point at which
22966 execution will halt and @code{GDB} will await further
22967 commands. @var{location} is
22968 either a line number within a file, given in the format @code{file:linenumber},
22969 or it is the name of a subprogram. If you request that a breakpoint be set on
22970 a subprogram that is overloaded, a prompt will ask you to specify on which of
22971 those subprograms you want to breakpoint. You can also
22972 specify that all of them should be breakpointed. If the program is run
22973 and execution encounters the breakpoint, then the program
22974 stops and @code{GDB} signals that the breakpoint was encountered by
22975 printing the line of code before which the program is halted.
22976
22977 @item breakpoint exception @var{name}
22978 A special form of the breakpoint command which breakpoints whenever
22979 exception @var{name} is raised.
22980 If @var{name} is omitted,
22981 then a breakpoint will occur when any exception is raised.
22982
22983 @item print @var{expression}
22984 This will print the value of the given expression. Most simple
22985 Ada expression formats are properly handled by @code{GDB}, so the expression
22986 can contain function calls, variables, operators, and attribute references.
22987
22988 @item continue
22989 Continues execution following a breakpoint, until the next breakpoint or the
22990 termination of the program.
22991
22992 @item step
22993 Executes a single line after a breakpoint. If the next statement
22994 is a subprogram call, execution continues into (the first statement of)
22995 the called subprogram.
22996
22997 @item next
22998 Executes a single line. If this line is a subprogram call, executes and
22999 returns from the call.
23000
23001 @item list
23002 Lists a few lines around the current source location. In practice, it
23003 is usually more convenient to have a separate edit window open with the
23004 relevant source file displayed. Successive applications of this command
23005 print subsequent lines. The command can be given an argument which is a
23006 line number, in which case it displays a few lines around the specified one.
23007
23008 @item backtrace
23009 Displays a backtrace of the call chain. This command is typically
23010 used after a breakpoint has occurred, to examine the sequence of calls that
23011 leads to the current breakpoint. The display includes one line for each
23012 activation record (frame) corresponding to an active subprogram.
23013
23014 @item up
23015 At a breakpoint, @code{GDB} can display the values of variables local
23016 to the current frame. The command @code{up} can be used to
23017 examine the contents of other active frames, by moving the focus up
23018 the stack, that is to say from callee to caller, one frame at a time.
23019
23020 @item down
23021 Moves the focus of @code{GDB} down from the frame currently being
23022 examined to the frame of its callee (the reverse of the previous command),
23023
23024 @item frame @var{n}
23025 Inspect the frame with the given number. The value 0 denotes the frame
23026 of the current breakpoint, that is to say the top of the call stack.
23027
23028 @end table
23029
23030 @noindent
23031 The above list is a very short introduction to the commands that
23032 @code{GDB} provides. Important additional capabilities, including conditional
23033 breakpoints, the ability to execute command sequences on a breakpoint,
23034 the ability to debug at the machine instruction level and many other
23035 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
23036 Debugging with GDB}.  Note that most commands can be abbreviated
23037 (for example, c for continue, bt for backtrace).
23038
23039 @node Using Ada Expressions
23040 @section Using Ada Expressions
23041 @cindex Ada expressions
23042
23043 @noindent
23044 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
23045 extensions. The philosophy behind the design of this subset is
23046
23047 @itemize @bullet
23048 @item
23049 That @code{GDB} should provide basic literals and access to operations for
23050 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
23051 leaving more sophisticated computations to subprograms written into the
23052 program (which therefore may be called from @code{GDB}).
23053
23054 @item
23055 That type safety and strict adherence to Ada language restrictions
23056 are not particularly important to the @code{GDB} user.
23057
23058 @item
23059 That brevity is important to the @code{GDB} user.
23060 @end itemize
23061
23062 @noindent
23063 Thus, for brevity, the debugger acts as if there were
23064 implicit @code{with} and @code{use} clauses in effect for all user-written
23065 packages, thus making it unnecessary to fully qualify most names with
23066 their packages, regardless of context. Where this causes ambiguity,
23067 @code{GDB} asks the user's intent.
23068
23069 For details on the supported Ada syntax, see @ref{Top,, Debugging with
23070 GDB, gdb, Debugging with GDB}.
23071
23072 @node Calling User-Defined Subprograms
23073 @section Calling User-Defined Subprograms
23074
23075 @noindent
23076 An important capability of @code{GDB} is the ability to call user-defined
23077 subprograms while debugging. This is achieved simply by entering
23078 a subprogram call statement in the form:
23079
23080 @smallexample
23081 call subprogram-name (parameters)
23082 @end smallexample
23083
23084 @noindent
23085 The keyword @code{call} can be omitted in the normal case where the
23086 @code{subprogram-name} does not coincide with any of the predefined
23087 @code{GDB} commands.
23088
23089 The effect is to invoke the given subprogram, passing it the
23090 list of parameters that is supplied. The parameters can be expressions and
23091 can include variables from the program being debugged. The
23092 subprogram must be defined
23093 at the library level within your program, and @code{GDB} will call the
23094 subprogram within the environment of your program execution (which
23095 means that the subprogram is free to access or even modify variables
23096 within your program).
23097
23098 The most important use of this facility is in allowing the inclusion of
23099 debugging routines that are tailored to particular data structures
23100 in your program. Such debugging routines can be written to provide a suitably
23101 high-level description of an abstract type, rather than a low-level dump
23102 of its physical layout. After all, the standard
23103 @code{GDB print} command only knows the physical layout of your
23104 types, not their abstract meaning. Debugging routines can provide information
23105 at the desired semantic level and are thus enormously useful.
23106
23107 For example, when debugging GNAT itself, it is crucial to have access to
23108 the contents of the tree nodes used to represent the program internally.
23109 But tree nodes are represented simply by an integer value (which in turn
23110 is an index into a table of nodes).
23111 Using the @code{print} command on a tree node would simply print this integer
23112 value, which is not very useful. But the PN routine (defined in file
23113 treepr.adb in the GNAT sources) takes a tree node as input, and displays
23114 a useful high level representation of the tree node, which includes the
23115 syntactic category of the node, its position in the source, the integers
23116 that denote descendant nodes and parent node, as well as varied
23117 semantic information. To study this example in more detail, you might want to
23118 look at the body of the PN procedure in the stated file.
23119
23120 @node Using the Next Command in a Function
23121 @section Using the Next Command in a Function
23122
23123 @noindent
23124 When you use the @code{next} command in a function, the current source
23125 location will advance to the next statement as usual. A special case
23126 arises in the case of a @code{return} statement.
23127
23128 Part of the code for a return statement is the ``epilog'' of the function.
23129 This is the code that returns to the caller. There is only one copy of
23130 this epilog code, and it is typically associated with the last return
23131 statement in the function if there is more than one return. In some
23132 implementations, this epilog is associated with the first statement
23133 of the function.
23134
23135 The result is that if you use the @code{next} command from a return
23136 statement that is not the last return statement of the function you
23137 may see a strange apparent jump to the last return statement or to
23138 the start of the function. You should simply ignore this odd jump.
23139 The value returned is always that from the first return statement
23140 that was stepped through.
23141
23142 @node Ada Exceptions
23143 @section Breaking on Ada Exceptions
23144 @cindex Exceptions
23145
23146 @noindent
23147 You can set breakpoints that trip when your program raises
23148 selected exceptions.
23149
23150 @table @code
23151 @item break exception
23152 Set a breakpoint that trips whenever (any task in the) program raises
23153 any exception.
23154
23155 @item break exception @var{name}
23156 Set a breakpoint that trips whenever (any task in the) program raises
23157 the exception @var{name}.
23158
23159 @item break exception unhandled
23160 Set a breakpoint that trips whenever (any task in the) program raises an
23161 exception for which there is no handler.
23162
23163 @item info exceptions
23164 @itemx info exceptions @var{regexp}
23165 The @code{info exceptions} command permits the user to examine all defined
23166 exceptions within Ada programs. With a regular expression, @var{regexp}, as
23167 argument, prints out only those exceptions whose name matches @var{regexp}.
23168 @end table
23169
23170 @node Ada Tasks
23171 @section Ada Tasks
23172 @cindex Tasks
23173
23174 @noindent
23175 @code{GDB} allows the following task-related commands:
23176
23177 @table @code
23178 @item info tasks
23179 This command shows a list of current Ada tasks, as in the following example:
23180
23181 @smallexample
23182 @iftex
23183 @leftskip=0cm
23184 @end iftex
23185 (gdb) info tasks
23186   ID       TID P-ID   Thread Pri State                 Name
23187    1   8088000   0   807e000  15 Child Activation Wait main_task
23188    2   80a4000   1   80ae000  15 Accept/Select Wait    b
23189    3   809a800   1   80a4800  15 Child Activation Wait a
23190 *  4   80ae800   3   80b8000  15 Running               c
23191 @end smallexample
23192
23193 @noindent
23194 In this listing, the asterisk before the first task indicates it to be the
23195 currently running task. The first column lists the task ID that is used
23196 to refer to tasks in the following commands.
23197
23198 @item break @var{linespec} task @var{taskid}
23199 @itemx break @var{linespec} task @var{taskid} if @dots{}
23200 @cindex Breakpoints and tasks
23201 These commands are like the @code{break @dots{} thread @dots{}}.
23202 @var{linespec} specifies source lines.
23203
23204 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
23205 to specify that you only want @code{GDB} to stop the program when a
23206 particular Ada task reaches this breakpoint. @var{taskid} is one of the
23207 numeric task identifiers assigned by @code{GDB}, shown in the first
23208 column of the @samp{info tasks} display.
23209
23210 If you do not specify @samp{task @var{taskid}} when you set a
23211 breakpoint, the breakpoint applies to @emph{all} tasks of your
23212 program.
23213
23214 You can use the @code{task} qualifier on conditional breakpoints as
23215 well; in this case, place @samp{task @var{taskid}} before the
23216 breakpoint condition (before the @code{if}).
23217
23218 @item task @var{taskno}
23219 @cindex Task switching
23220
23221 This command allows to switch to the task referred by @var{taskno}. In
23222 particular, This allows to browse the backtrace of the specified
23223 task. It is advised to switch back to the original task before
23224 continuing execution otherwise the scheduling of the program may be
23225 perturbed.
23226 @end table
23227
23228 @noindent
23229 For more detailed information on the tasking support,
23230 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
23231
23232 @node Debugging Generic Units
23233 @section Debugging Generic Units
23234 @cindex Debugging Generic Units
23235 @cindex Generics
23236
23237 @noindent
23238 GNAT always uses code expansion for generic instantiation. This means that
23239 each time an instantiation occurs, a complete copy of the original code is
23240 made, with appropriate substitutions of formals by actuals.
23241
23242 It is not possible to refer to the original generic entities in
23243 @code{GDB}, but it is always possible to debug a particular instance of
23244 a generic, by using the appropriate expanded names. For example, if we have
23245
23246 @smallexample @c ada
23247 @group
23248 @cartouche
23249 procedure g is
23250
23251    generic package k is
23252       procedure kp (v1 : in out integer);
23253    end k;
23254
23255    package body k is
23256       procedure kp (v1 : in out integer) is
23257       begin
23258          v1 := v1 + 1;
23259       end kp;
23260    end k;
23261
23262    package k1 is new k;
23263    package k2 is new k;
23264
23265    var : integer := 1;
23266
23267 begin
23268    k1.kp (var);
23269    k2.kp (var);
23270    k1.kp (var);
23271    k2.kp (var);
23272 end;
23273 @end cartouche
23274 @end group
23275 @end smallexample
23276
23277 @noindent
23278 Then to break on a call to procedure kp in the k2 instance, simply
23279 use the command:
23280
23281 @smallexample
23282 (gdb) break g.k2.kp
23283 @end smallexample
23284
23285 @noindent
23286 When the breakpoint occurs, you can step through the code of the
23287 instance in the normal manner and examine the values of local variables, as for
23288 other units.
23289
23290 @node GNAT Abnormal Termination or Failure to Terminate
23291 @section GNAT Abnormal Termination or Failure to Terminate
23292 @cindex GNAT Abnormal Termination or Failure to Terminate
23293
23294 @noindent
23295 When presented with programs that contain serious errors in syntax
23296 or semantics,
23297 GNAT may on rare occasions  experience problems in operation, such
23298 as aborting with a
23299 segmentation fault or illegal memory access, raising an internal
23300 exception, terminating abnormally, or failing to terminate at all.
23301 In such cases, you can activate
23302 various features of GNAT that can help you pinpoint the construct in your
23303 program that is the likely source of the problem.
23304
23305 The following strategies are presented in increasing order of
23306 difficulty, corresponding to your experience in using GNAT and your
23307 familiarity with compiler internals.
23308
23309 @enumerate
23310 @item
23311 Run @command{gcc} with the @option{-gnatf}. This first
23312 switch causes all errors on a given line to be reported. In its absence,
23313 only the first error on a line is displayed.
23314
23315 The @option{-gnatdO} switch causes errors to be displayed as soon as they
23316 are encountered, rather than after compilation is terminated. If GNAT
23317 terminates prematurely or goes into an infinite loop, the last error
23318 message displayed may help to pinpoint the culprit.
23319
23320 @item
23321 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
23322 mode, @command{gcc} produces ongoing information about the progress of the
23323 compilation and provides the name of each procedure as code is
23324 generated. This switch allows you to find which Ada procedure was being
23325 compiled when it encountered a code generation problem.
23326
23327 @item
23328 @cindex @option{-gnatdc} switch
23329 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
23330 switch that does for the front-end what @option{^-v^VERBOSE^} does
23331 for the back end. The system prints the name of each unit,
23332 either a compilation unit or nested unit, as it is being analyzed.
23333 @item
23334 Finally, you can start
23335 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
23336 front-end of GNAT, and can be run independently (normally it is just
23337 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
23338 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
23339 @code{where} command is the first line of attack; the variable
23340 @code{lineno} (seen by @code{print lineno}), used by the second phase of
23341 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
23342 which the execution stopped, and @code{input_file name} indicates the name of
23343 the source file.
23344 @end enumerate
23345
23346 @node Naming Conventions for GNAT Source Files
23347 @section Naming Conventions for GNAT Source Files
23348
23349 @noindent
23350 In order to examine the workings of the GNAT system, the following
23351 brief description of its organization may be helpful:
23352
23353 @itemize @bullet
23354 @item
23355 Files with prefix @file{^sc^SC^} contain the lexical scanner.
23356
23357 @item
23358 All files prefixed with @file{^par^PAR^} are components of the parser. The
23359 numbers correspond to chapters of the Ada Reference Manual. For example,
23360 parsing of select statements can be found in @file{par-ch9.adb}.
23361
23362 @item
23363 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
23364 numbers correspond to chapters of the Ada standard. For example, all
23365 issues involving context clauses can be found in @file{sem_ch10.adb}. In
23366 addition, some features of the language require sufficient special processing
23367 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
23368 dynamic dispatching, etc.
23369
23370 @item
23371 All files prefixed with @file{^exp^EXP^} perform normalization and
23372 expansion of the intermediate representation (abstract syntax tree, or AST).
23373 these files use the same numbering scheme as the parser and semantics files.
23374 For example, the construction of record initialization procedures is done in
23375 @file{exp_ch3.adb}.
23376
23377 @item
23378 The files prefixed with @file{^bind^BIND^} implement the binder, which
23379 verifies the consistency of the compilation, determines an order of
23380 elaboration, and generates the bind file.
23381
23382 @item
23383 The files @file{atree.ads} and @file{atree.adb} detail the low-level
23384 data structures used by the front-end.
23385
23386 @item
23387 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
23388 the abstract syntax tree as produced by the parser.
23389
23390 @item
23391 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
23392 all entities, computed during semantic analysis.
23393
23394 @item
23395 Library management issues are dealt with in files with prefix
23396 @file{^lib^LIB^}.
23397
23398 @item
23399 @findex Ada
23400 @cindex Annex A
23401 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
23402 defined in Annex A.
23403
23404 @item
23405 @findex Interfaces
23406 @cindex Annex B
23407 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
23408 defined in Annex B.
23409
23410 @item
23411 @findex System
23412 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
23413 both language-defined children and GNAT run-time routines.
23414
23415 @item
23416 @findex GNAT
23417 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
23418 general-purpose packages, fully documented in their specs. All
23419 the other @file{.c} files are modifications of common @command{gcc} files.
23420 @end itemize
23421
23422 @node Getting Internal Debugging Information
23423 @section Getting Internal Debugging Information
23424
23425 @noindent
23426 Most compilers have internal debugging switches and modes. GNAT
23427 does also, except GNAT internal debugging switches and modes are not
23428 secret. A summary and full description of all the compiler and binder
23429 debug flags are in the file @file{debug.adb}. You must obtain the
23430 sources of the compiler to see the full detailed effects of these flags.
23431
23432 The switches that print the source of the program (reconstructed from
23433 the internal tree) are of general interest for user programs, as are the
23434 options to print
23435 the full internal tree, and the entity table (the symbol table
23436 information). The reconstructed source provides a readable version of the
23437 program after the front-end has completed analysis and  expansion,
23438 and is useful when studying the performance of specific constructs.
23439 For example, constraint checks are indicated, complex aggregates
23440 are replaced with loops and assignments, and tasking primitives
23441 are replaced with run-time calls.
23442
23443 @node Stack Traceback
23444 @section Stack Traceback
23445 @cindex traceback
23446 @cindex stack traceback
23447 @cindex stack unwinding
23448
23449 @noindent
23450 Traceback is a mechanism to display the sequence of subprogram calls that
23451 leads to a specified execution point in a program. Often (but not always)
23452 the execution point is an instruction at which an exception has been raised.
23453 This mechanism is also known as @i{stack unwinding} because it obtains
23454 its information by scanning the run-time stack and recovering the activation
23455 records of all active subprograms. Stack unwinding is one of the most
23456 important tools for program debugging.
23457
23458 The first entry stored in traceback corresponds to the deepest calling level,
23459 that is to say the subprogram currently executing the instruction
23460 from which we want to obtain the traceback.
23461
23462 Note that there is no runtime performance penalty when stack traceback
23463 is enabled, and no exception is raised during program execution.
23464
23465 @menu
23466 * Non-Symbolic Traceback::
23467 * Symbolic Traceback::
23468 @end menu
23469
23470 @node Non-Symbolic Traceback
23471 @subsection Non-Symbolic Traceback
23472 @cindex traceback, non-symbolic
23473
23474 @noindent
23475 Note: this feature is not supported on all platforms. See
23476 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
23477 platforms.
23478
23479 @menu
23480 * Tracebacks From an Unhandled Exception::
23481 * Tracebacks From Exception Occurrences (non-symbolic)::
23482 * Tracebacks From Anywhere in a Program (non-symbolic)::
23483 @end menu
23484
23485 @node Tracebacks From an Unhandled Exception
23486 @subsubsection Tracebacks From an Unhandled Exception
23487
23488 @noindent
23489 A runtime non-symbolic traceback is a list of addresses of call instructions.
23490 To enable this feature you must use the @option{-E}
23491 @code{gnatbind}'s option. With this option a stack traceback is stored as part
23492 of exception information. You can retrieve this information using the
23493 @code{addr2line} tool.
23494
23495 Here is a simple example:
23496
23497 @smallexample @c ada
23498 @cartouche
23499 procedure STB is
23500
23501    procedure P1 is
23502    begin
23503       raise Constraint_Error;
23504    end P1;
23505
23506    procedure P2 is
23507    begin
23508       P1;
23509    end P2;
23510
23511 begin
23512    P2;
23513 end STB;
23514 @end cartouche
23515 @end smallexample
23516
23517 @smallexample
23518 $ gnatmake stb -bargs -E
23519 $ stb
23520
23521 Execution terminated by unhandled exception
23522 Exception name: CONSTRAINT_ERROR
23523 Message: stb.adb:5
23524 Call stack traceback locations:
23525 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
23526 @end smallexample
23527
23528 @noindent
23529 As we see the traceback lists a sequence of addresses for the unhandled
23530 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
23531 guess that this exception come from procedure P1. To translate these
23532 addresses into the source lines where the calls appear, the
23533 @code{addr2line} tool, described below, is invaluable. The use of this tool
23534 requires the program to be compiled with debug information.
23535
23536 @smallexample
23537 $ gnatmake -g stb -bargs -E
23538 $ stb
23539
23540 Execution terminated by unhandled exception
23541 Exception name: CONSTRAINT_ERROR
23542 Message: stb.adb:5
23543 Call stack traceback locations:
23544 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
23545
23546 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
23547    0x4011f1 0x77e892a4
23548
23549 00401373 at d:/stb/stb.adb:5
23550 0040138B at d:/stb/stb.adb:10
23551 0040139C at d:/stb/stb.adb:14
23552 00401335 at d:/stb/b~stb.adb:104
23553 004011C4 at /build/@dots{}/crt1.c:200
23554 004011F1 at /build/@dots{}/crt1.c:222
23555 77E892A4 in ?? at ??:0
23556 @end smallexample
23557
23558 @noindent
23559 The @code{addr2line} tool has several other useful options:
23560
23561 @table @code
23562 @item --functions
23563 to get the function name corresponding to any location
23564
23565 @item --demangle=gnat
23566 to use the gnat decoding mode for the function names. Note that
23567 for binutils version 2.9.x the option is simply @option{--demangle}.
23568 @end table
23569
23570 @smallexample
23571 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
23572    0x40139c 0x401335 0x4011c4 0x4011f1
23573
23574 00401373 in stb.p1 at d:/stb/stb.adb:5
23575 0040138B in stb.p2 at d:/stb/stb.adb:10
23576 0040139C in stb at d:/stb/stb.adb:14
23577 00401335 in main at d:/stb/b~stb.adb:104
23578 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
23579 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
23580 @end smallexample
23581
23582 @noindent
23583 From this traceback we can see that the exception was raised in
23584 @file{stb.adb} at line 5, which was reached from a procedure call in
23585 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
23586 which contains the call to the main program.
23587 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
23588 and the output will vary from platform to platform.
23589
23590 It is also possible to use @code{GDB} with these traceback addresses to debug
23591 the program. For example, we can break at a given code location, as reported
23592 in the stack traceback:
23593
23594 @smallexample
23595 $ gdb -nw stb
23596 @ifclear vms
23597 @noindent
23598 Furthermore, this feature is not implemented inside Windows DLL. Only
23599 the non-symbolic traceback is reported in this case.
23600 @end ifclear
23601
23602 (gdb) break *0x401373
23603 Breakpoint 1 at 0x401373: file stb.adb, line 5.
23604 @end smallexample
23605
23606 @noindent
23607 It is important to note that the stack traceback addresses
23608 do not change when debug information is included. This is particularly useful
23609 because it makes it possible to release software without debug information (to
23610 minimize object size), get a field report that includes a stack traceback
23611 whenever an internal bug occurs, and then be able to retrieve the sequence
23612 of calls with the same program compiled with debug information.
23613
23614 @node Tracebacks From Exception Occurrences (non-symbolic)
23615 @subsubsection Tracebacks From Exception Occurrences
23616
23617 @noindent
23618 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
23619 The stack traceback is attached to the exception information string, and can
23620 be retrieved in an exception handler within the Ada program, by means of the
23621 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
23622
23623 @smallexample @c ada
23624 with Ada.Text_IO;
23625 with Ada.Exceptions;
23626
23627 procedure STB is
23628
23629    use Ada;
23630    use Ada.Exceptions;
23631
23632    procedure P1 is
23633       K : Positive := 1;
23634    begin
23635       K := K - 1;
23636    exception
23637       when E : others =>
23638          Text_IO.Put_Line (Exception_Information (E));
23639    end P1;
23640
23641    procedure P2 is
23642    begin
23643       P1;
23644    end P2;
23645
23646 begin
23647    P2;
23648 end STB;
23649 @end smallexample
23650
23651 @noindent
23652 This program will output:
23653
23654 @smallexample
23655 $ stb
23656
23657 Exception name: CONSTRAINT_ERROR
23658 Message: stb.adb:12
23659 Call stack traceback locations:
23660 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
23661 @end smallexample
23662
23663 @node Tracebacks From Anywhere in a Program (non-symbolic)
23664 @subsubsection Tracebacks From Anywhere in a Program
23665
23666 @noindent
23667 It is also possible to retrieve a stack traceback from anywhere in a
23668 program. For this you need to
23669 use the @code{GNAT.Traceback} API. This package includes a procedure called
23670 @code{Call_Chain} that computes a complete stack traceback, as well as useful
23671 display procedures described below. It is not necessary to use the
23672 @option{-E gnatbind} option in this case, because the stack traceback mechanism
23673 is invoked explicitly.
23674
23675 @noindent
23676 In the following example we compute a traceback at a specific location in
23677 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
23678 convert addresses to strings:
23679
23680 @smallexample @c ada
23681 with Ada.Text_IO;
23682 with GNAT.Traceback;
23683 with GNAT.Debug_Utilities;
23684
23685 procedure STB is
23686
23687    use Ada;
23688    use GNAT;
23689    use GNAT.Traceback;
23690
23691    procedure P1 is
23692       TB  : Tracebacks_Array (1 .. 10);
23693       --  We are asking for a maximum of 10 stack frames.
23694       Len : Natural;
23695       --  Len will receive the actual number of stack frames returned.
23696    begin
23697       Call_Chain (TB, Len);
23698
23699       Text_IO.Put ("In STB.P1 : ");
23700
23701       for K in 1 .. Len loop
23702          Text_IO.Put (Debug_Utilities.Image (TB (K)));
23703          Text_IO.Put (' ');
23704       end loop;
23705
23706       Text_IO.New_Line;
23707    end P1;
23708
23709    procedure P2 is
23710    begin
23711       P1;
23712    end P2;
23713
23714 begin
23715    P2;
23716 end STB;
23717 @end smallexample
23718
23719 @smallexample
23720 $ gnatmake -g stb
23721 $ stb
23722
23723 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
23724 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
23725 @end smallexample
23726
23727 @noindent
23728 You can then get further information by invoking the @code{addr2line}
23729 tool as described earlier (note that the hexadecimal addresses
23730 need to be specified in C format, with a leading ``0x'').
23731
23732 @node Symbolic Traceback
23733 @subsection Symbolic Traceback
23734 @cindex traceback, symbolic
23735
23736 @noindent
23737 A symbolic traceback is a stack traceback in which procedure names are
23738 associated with each code location.
23739
23740 @noindent
23741 Note that this feature is not supported on all platforms. See
23742 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
23743 list of currently supported platforms.
23744
23745 @noindent
23746 Note that the symbolic traceback requires that the program be compiled
23747 with debug information. If it is not compiled with debug information
23748 only the non-symbolic information will be valid.
23749
23750 @menu
23751 * Tracebacks From Exception Occurrences (symbolic)::
23752 * Tracebacks From Anywhere in a Program (symbolic)::
23753 @end menu
23754
23755 @node Tracebacks From Exception Occurrences (symbolic)
23756 @subsubsection Tracebacks From Exception Occurrences
23757
23758 @smallexample @c ada
23759 with Ada.Text_IO;
23760 with GNAT.Traceback.Symbolic;
23761
23762 procedure STB is
23763
23764    procedure P1 is
23765    begin
23766       raise Constraint_Error;
23767    end P1;
23768
23769    procedure P2 is
23770    begin
23771       P1;
23772    end P2;
23773
23774    procedure P3 is
23775    begin
23776       P2;
23777    end P3;
23778
23779 begin
23780    P3;
23781 exception
23782    when E : others =>
23783       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
23784 end STB;
23785 @end smallexample
23786
23787 @smallexample
23788 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
23789 $ stb
23790
23791 0040149F in stb.p1 at stb.adb:8
23792 004014B7 in stb.p2 at stb.adb:13
23793 004014CF in stb.p3 at stb.adb:18
23794 004015DD in ada.stb at stb.adb:22
23795 00401461 in main at b~stb.adb:168
23796 004011C4 in __mingw_CRTStartup at crt1.c:200
23797 004011F1 in mainCRTStartup at crt1.c:222
23798 77E892A4 in ?? at ??:0
23799 @end smallexample
23800
23801 @noindent
23802 In the above example the ``.\'' syntax in the @command{gnatmake} command
23803 is currently required by @command{addr2line} for files that are in
23804 the current working directory.
23805 Moreover, the exact sequence of linker options may vary from platform
23806 to platform.
23807 The above @option{-largs} section is for Windows platforms. By contrast,
23808 under Unix there is no need for the @option{-largs} section.
23809 Differences across platforms are due to details of linker implementation.
23810
23811 @node Tracebacks From Anywhere in a Program (symbolic)
23812 @subsubsection Tracebacks From Anywhere in a Program
23813
23814 @noindent
23815 It is possible to get a symbolic stack traceback
23816 from anywhere in a program, just as for non-symbolic tracebacks.
23817 The first step is to obtain a non-symbolic
23818 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
23819 information. Here is an example:
23820
23821 @smallexample @c ada
23822 with Ada.Text_IO;
23823 with GNAT.Traceback;
23824 with GNAT.Traceback.Symbolic;
23825
23826 procedure STB is
23827
23828    use Ada;
23829    use GNAT.Traceback;
23830    use GNAT.Traceback.Symbolic;
23831
23832    procedure P1 is
23833       TB  : Tracebacks_Array (1 .. 10);
23834       --  We are asking for a maximum of 10 stack frames.
23835       Len : Natural;
23836       --  Len will receive the actual number of stack frames returned.
23837    begin
23838       Call_Chain (TB, Len);
23839       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
23840    end P1;
23841
23842    procedure P2 is
23843    begin
23844       P1;
23845    end P2;
23846
23847 begin
23848    P2;
23849 end STB;
23850 @end smallexample
23851
23852 @c ******************************
23853 @ifset vms
23854 @node Compatibility with HP Ada
23855 @chapter Compatibility with HP Ada
23856 @cindex Compatibility
23857
23858 @noindent
23859 @cindex DEC Ada
23860 @cindex HP Ada
23861 @cindex Compatibility between GNAT and HP Ada
23862 This chapter compares HP Ada (formerly known as ``DEC Ada'')
23863 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
23864 GNAT is highly compatible
23865 with HP Ada, and it should generally be straightforward to port code
23866 from the HP Ada environment to GNAT. However, there are a few language
23867 and implementation differences of which the user must be aware. These
23868 differences are discussed in this chapter. In
23869 addition, the operating environment and command structure for the
23870 compiler are different, and these differences are also discussed.
23871
23872 For further details on these and other compatibility issues,
23873 see Appendix E of the HP publication
23874 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
23875
23876 Except where otherwise indicated, the description of GNAT for OpenVMS
23877 applies to both the Alpha and I64 platforms.
23878
23879 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
23880 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
23881
23882 The discussion in this chapter addresses specifically the implementation
23883 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
23884 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
23885 GNAT always follows the Alpha implementation.
23886
23887 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
23888 attributes are recognized, although only a subset of them can sensibly
23889 be implemented.  The description of pragmas in
23890 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
23891 indicates whether or not they are applicable to non-VMS systems.
23892
23893 @menu
23894 * Ada Language Compatibility::
23895 * Differences in the Definition of Package System::
23896 * Language-Related Features::
23897 * The Package STANDARD::
23898 * The Package SYSTEM::
23899 * Tasking and Task-Related Features::
23900 * Pragmas and Pragma-Related Features::
23901 * Library of Predefined Units::
23902 * Bindings::
23903 * Main Program Definition::
23904 * Implementation-Defined Attributes::
23905 * Compiler and Run-Time Interfacing::
23906 * Program Compilation and Library Management::
23907 * Input-Output::
23908 * Implementation Limits::
23909 * Tools and Utilities::
23910 @end menu
23911
23912 @node Ada Language Compatibility
23913 @section Ada Language Compatibility
23914
23915 @noindent
23916 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
23917 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
23918 with Ada 83, and therefore Ada 83 programs will compile
23919 and run under GNAT with
23920 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
23921 provides details on specific incompatibilities.
23922
23923 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
23924 as well as the pragma @code{ADA_83}, to force the compiler to
23925 operate in Ada 83 mode. This mode does not guarantee complete
23926 conformance to Ada 83, but in practice is sufficient to
23927 eliminate most sources of incompatibilities.
23928 In particular, it eliminates the recognition of the
23929 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
23930 in Ada 83 programs is legal, and handles the cases of packages
23931 with optional bodies, and generics that instantiate unconstrained
23932 types without the use of @code{(<>)}.
23933
23934 @node Differences in the Definition of Package System
23935 @section Differences in the Definition of Package @code{System}
23936
23937 @noindent
23938 An Ada compiler is allowed to add
23939 implementation-dependent declarations to package @code{System}.
23940 In normal mode,
23941 GNAT does not take advantage of this permission, and the version of
23942 @code{System} provided by GNAT exactly matches that defined in the Ada
23943 Reference Manual.
23944
23945 However, HP Ada adds an extensive set of declarations to package
23946 @code{System},
23947 as fully documented in the HP Ada manuals. To minimize changes required
23948 for programs that make use of these extensions, GNAT provides the pragma
23949 @code{Extend_System} for extending the definition of package System. By using:
23950 @cindex pragma @code{Extend_System}
23951 @cindex @code{Extend_System} pragma
23952
23953 @smallexample @c ada
23954 @group
23955 @cartouche
23956 pragma Extend_System (Aux_DEC);
23957 @end cartouche
23958 @end group
23959 @end smallexample
23960
23961 @noindent
23962 the set of definitions in @code{System} is extended to include those in
23963 package @code{System.Aux_DEC}.
23964 @cindex @code{System.Aux_DEC} package
23965 @cindex @code{Aux_DEC} package (child of @code{System})
23966 These definitions are incorporated directly into package @code{System},
23967 as though they had been declared there. For a
23968 list of the declarations added, see the spec of this package,
23969 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
23970 @cindex @file{s-auxdec.ads} file
23971 The pragma @code{Extend_System} is a configuration pragma, which means that
23972 it can be placed in the file @file{gnat.adc}, so that it will automatically
23973 apply to all subsequent compilations. See @ref{Configuration Pragmas},
23974 for further details.
23975
23976 An alternative approach that avoids the use of the non-standard
23977 @code{Extend_System} pragma is to add a context clause to the unit that
23978 references these facilities:
23979
23980 @smallexample @c ada
23981 @cartouche
23982 with System.Aux_DEC;
23983 use  System.Aux_DEC;
23984 @end cartouche
23985 @end smallexample
23986
23987 @noindent
23988 The effect is not quite semantically identical to incorporating
23989 the declarations directly into package @code{System},
23990 but most programs will not notice a difference
23991 unless they use prefix notation (e.g.@: @code{System.Integer_8})
23992 to reference the entities directly in package @code{System}.
23993 For units containing such references,
23994 the prefixes must either be removed, or the pragma @code{Extend_System}
23995 must be used.
23996
23997 @node Language-Related Features
23998 @section Language-Related Features
23999
24000 @noindent
24001 The following sections highlight differences in types,
24002 representations of types, operations, alignment, and
24003 related topics.
24004
24005 @menu
24006 * Integer Types and Representations::
24007 * Floating-Point Types and Representations::
24008 * Pragmas Float_Representation and Long_Float::
24009 * Fixed-Point Types and Representations::
24010 * Record and Array Component Alignment::
24011 * Address Clauses::
24012 * Other Representation Clauses::
24013 @end menu
24014
24015 @node Integer Types and Representations
24016 @subsection Integer Types and Representations
24017
24018 @noindent
24019 The set of predefined integer types is identical in HP Ada and GNAT.
24020 Furthermore the representation of these integer types is also identical,
24021 including the capability of size clauses forcing biased representation.
24022
24023 In addition,
24024 HP Ada for OpenVMS Alpha systems has defined the
24025 following additional integer types in package @code{System}:
24026
24027 @itemize @bullet
24028
24029 @item
24030 @code{INTEGER_8}
24031
24032 @item
24033 @code{INTEGER_16}
24034
24035 @item
24036 @code{INTEGER_32}
24037
24038 @item
24039 @code{INTEGER_64}
24040
24041 @item
24042 @code{LARGEST_INTEGER}
24043 @end itemize
24044
24045 @noindent
24046 In GNAT, the first four of these types may be obtained from the
24047 standard Ada package @code{Interfaces}.
24048 Alternatively, by use of the pragma @code{Extend_System}, identical
24049 declarations can be referenced directly in package @code{System}.
24050 On both GNAT and HP Ada, the maximum integer size is 64 bits.
24051
24052 @node Floating-Point Types and Representations
24053 @subsection Floating-Point Types and Representations
24054 @cindex Floating-Point types
24055
24056 @noindent
24057 The set of predefined floating-point types is identical in HP Ada and GNAT.
24058 Furthermore the representation of these floating-point
24059 types is also identical. One important difference is that the default
24060 representation for HP Ada is @code{VAX_Float}, but the default representation
24061 for GNAT is IEEE.
24062
24063 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
24064 pragma @code{Float_Representation} as described in the HP Ada
24065 documentation.
24066 For example, the declarations:
24067
24068 @smallexample @c ada
24069 @cartouche
24070 type F_Float is digits 6;
24071 pragma Float_Representation (VAX_Float, F_Float);
24072 @end cartouche
24073 @end smallexample
24074
24075 @noindent
24076 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
24077 format.
24078 This set of declarations actually appears in @code{System.Aux_DEC},
24079 which contains
24080 the full set of additional floating-point declarations provided in
24081 the HP Ada version of package @code{System}.
24082 This and similar declarations may be accessed in a user program
24083 by using pragma @code{Extend_System}. The use of this
24084 pragma, and the related pragma @code{Long_Float} is described in further
24085 detail in the following section.
24086
24087 @node Pragmas Float_Representation and Long_Float
24088 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
24089
24090 @noindent
24091 HP Ada provides the pragma @code{Float_Representation}, which
24092 acts as a program library switch to allow control over
24093 the internal representation chosen for the predefined
24094 floating-point types declared in the package @code{Standard}.
24095 The format of this pragma is as follows:
24096
24097 @smallexample @c ada
24098 @cartouche
24099 pragma Float_Representation(VAX_Float | IEEE_Float);
24100 @end cartouche
24101 @end smallexample
24102
24103 @noindent
24104 This pragma controls the representation of floating-point
24105 types as follows:
24106
24107 @itemize @bullet
24108 @item
24109 @code{VAX_Float} specifies that floating-point
24110 types are represented by default with the VAX system hardware types
24111 @code{F-floating}, @code{D-floating}, @code{G-floating}.
24112 Note that the @code{H-floating}
24113 type was available only on VAX systems, and is not available
24114 in either HP Ada or GNAT.
24115
24116 @item
24117 @code{IEEE_Float} specifies that floating-point
24118 types are represented by default with the IEEE single and
24119 double floating-point types.
24120 @end itemize
24121
24122 @noindent
24123 GNAT provides an identical implementation of the pragma
24124 @code{Float_Representation}, except that it functions as a
24125 configuration pragma. Note that the
24126 notion of configuration pragma corresponds closely to the
24127 HP Ada notion of a program library switch.
24128
24129 When no pragma is used in GNAT, the default is @code{IEEE_Float},
24130 which is different
24131 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
24132 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
24133 advisable to change the format of numbers passed to standard library
24134 routines, and if necessary explicit type conversions may be needed.
24135
24136 The use of @code{IEEE_Float} is recommended in GNAT since it is more
24137 efficient, and (given that it conforms to an international standard)
24138 potentially more portable.
24139 The situation in which @code{VAX_Float} may be useful is in interfacing
24140 to existing code and data that expect the use of @code{VAX_Float}.
24141 In such a situation use the predefined @code{VAX_Float}
24142 types in package @code{System}, as extended by
24143 @code{Extend_System}. For example, use @code{System.F_Float}
24144 to specify the 32-bit @code{F-Float} format.
24145
24146 @noindent
24147 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
24148 to allow control over the internal representation chosen
24149 for the predefined type @code{Long_Float} and for floating-point
24150 type declarations with digits specified in the range 7 .. 15.
24151 The format of this pragma is as follows:
24152
24153 @smallexample @c ada
24154 @cartouche
24155 pragma Long_Float (D_FLOAT | G_FLOAT);
24156 @end cartouche
24157 @end smallexample
24158
24159 @node Fixed-Point Types and Representations
24160 @subsection Fixed-Point Types and Representations
24161
24162 @noindent
24163 On HP Ada for OpenVMS Alpha systems, rounding is
24164 away from zero for both positive and negative numbers.
24165 Therefore, @code{+0.5} rounds to @code{1},
24166 and @code{-0.5} rounds to @code{-1}.
24167
24168 On GNAT the results of operations
24169 on fixed-point types are in accordance with the Ada
24170 rules. In particular, results of operations on decimal
24171 fixed-point types are truncated.
24172
24173 @node Record and Array Component Alignment
24174 @subsection Record and Array Component Alignment
24175
24176 @noindent
24177 On HP Ada for OpenVMS Alpha, all non-composite components
24178 are aligned on natural boundaries. For example, 1-byte
24179 components are aligned on byte boundaries, 2-byte
24180 components on 2-byte boundaries, 4-byte components on 4-byte
24181 byte boundaries, and so on. The OpenVMS Alpha hardware
24182 runs more efficiently with naturally aligned data.
24183
24184 On GNAT, alignment rules are compatible
24185 with HP Ada for OpenVMS Alpha.
24186
24187 @node Address Clauses
24188 @subsection Address Clauses
24189
24190 @noindent
24191 In HP Ada and GNAT, address clauses are supported for
24192 objects and imported subprograms.
24193 The predefined type @code{System.Address} is a private type
24194 in both compilers on Alpha OpenVMS, with the same representation
24195 (it is simply a machine pointer). Addition, subtraction, and comparison
24196 operations are available in the standard Ada package
24197 @code{System.Storage_Elements}, or in package @code{System}
24198 if it is extended to include @code{System.Aux_DEC} using a
24199 pragma @code{Extend_System} as previously described.
24200
24201 Note that code that @code{with}'s both this extended package @code{System}
24202 and the package @code{System.Storage_Elements} should not @code{use}
24203 both packages, or ambiguities will result. In general it is better
24204 not to mix these two sets of facilities. The Ada package was
24205 designed specifically to provide the kind of features that HP Ada
24206 adds directly to package @code{System}.
24207
24208 The type @code{System.Address} is a 64-bit integer type in GNAT for
24209 I64 OpenVMS.  For more information,
24210 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
24211
24212 GNAT is compatible with HP Ada in its handling of address
24213 clauses, except for some limitations in
24214 the form of address clauses for composite objects with
24215 initialization. Such address clauses are easily replaced
24216 by the use of an explicitly-defined constant as described
24217 in the Ada Reference Manual (13.1(22)). For example, the sequence
24218 of declarations:
24219
24220 @smallexample @c ada
24221 @cartouche
24222 X, Y : Integer := Init_Func;
24223 Q : String (X .. Y) := "abc";
24224 @dots{}
24225 for Q'Address use Compute_Address;
24226 @end cartouche
24227 @end smallexample
24228
24229 @noindent
24230 will be rejected by GNAT, since the address cannot be computed at the time
24231 that @code{Q} is declared. To achieve the intended effect, write instead:
24232
24233 @smallexample @c ada
24234 @group
24235 @cartouche
24236 X, Y : Integer := Init_Func;
24237 Q_Address : constant Address := Compute_Address;
24238 Q : String (X .. Y) := "abc";
24239 @dots{}
24240 for Q'Address use Q_Address;
24241 @end cartouche
24242 @end group
24243 @end smallexample
24244
24245 @noindent
24246 which will be accepted by GNAT (and other Ada compilers), and is also
24247 compatible with Ada 83. A fuller description of the restrictions
24248 on address specifications is found in @ref{Top, GNAT Reference Manual,
24249 About This Guide, gnat_rm, GNAT Reference Manual}.
24250
24251 @node Other Representation Clauses
24252 @subsection Other Representation Clauses
24253
24254 @noindent
24255 GNAT implements in a compatible manner all the representation
24256 clauses supported by HP Ada. In addition, GNAT
24257 implements the representation clause forms that were introduced in Ada 95,
24258 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
24259
24260 @node The Package STANDARD
24261 @section The Package @code{STANDARD}
24262
24263 @noindent
24264 The package @code{STANDARD}, as implemented by HP Ada, is fully
24265 described in the @cite{Ada Reference Manual} and in the
24266 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
24267 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
24268
24269 In addition, HP Ada supports the Latin-1 character set in
24270 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
24271 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
24272 the type @code{WIDE_CHARACTER}.
24273
24274 The floating-point types supported by GNAT are those
24275 supported by HP Ada, but the defaults are different, and are controlled by
24276 pragmas. See @ref{Floating-Point Types and Representations}, for details.
24277
24278 @node The Package SYSTEM
24279 @section The Package @code{SYSTEM}
24280
24281 @noindent
24282 HP Ada provides a specific version of the package
24283 @code{SYSTEM} for each platform on which the language is implemented.
24284 For the complete spec of the package @code{SYSTEM}, see
24285 Appendix F of the @cite{HP Ada Language Reference Manual}.
24286
24287 On HP Ada, the package @code{SYSTEM} includes the following conversion
24288 functions:
24289 @itemize @bullet
24290 @item @code{TO_ADDRESS(INTEGER)}
24291
24292 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
24293
24294 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
24295
24296 @item @code{TO_INTEGER(ADDRESS)}
24297
24298 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
24299
24300 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
24301 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
24302 @end itemize
24303
24304 @noindent
24305 By default, GNAT supplies a version of @code{SYSTEM} that matches
24306 the definition given in the @cite{Ada Reference Manual}.
24307 This
24308 is a subset of the HP system definitions, which is as
24309 close as possible to the original definitions. The only difference
24310 is that the definition of @code{SYSTEM_NAME} is different:
24311
24312 @smallexample @c ada
24313 @cartouche
24314 type Name is (SYSTEM_NAME_GNAT);
24315 System_Name : constant Name := SYSTEM_NAME_GNAT;
24316 @end cartouche
24317 @end smallexample
24318
24319 @noindent
24320 Also, GNAT adds the Ada declarations for
24321 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
24322
24323 However, the use of the following pragma causes GNAT
24324 to extend the definition of package @code{SYSTEM} so that it
24325 encompasses the full set of HP-specific extensions,
24326 including the functions listed above:
24327
24328 @smallexample @c ada
24329 @cartouche
24330 pragma Extend_System (Aux_DEC);
24331 @end cartouche
24332 @end smallexample
24333
24334 @noindent
24335 The pragma @code{Extend_System} is a configuration pragma that
24336 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
24337 Extend_System,,, gnat_rm, GNAT Reference Manual} for further details.
24338
24339 HP Ada does not allow the recompilation of the package
24340 @code{SYSTEM}. Instead HP Ada provides several pragmas
24341 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
24342 to modify values in the package @code{SYSTEM}.
24343 On OpenVMS Alpha systems, the pragma
24344 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
24345 its single argument.
24346
24347 GNAT does permit the recompilation of package @code{SYSTEM} using
24348 the special switch @option{-gnatg}, and this switch can be used if
24349 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
24350 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
24351 or @code{MEMORY_SIZE} by any other means.
24352
24353 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
24354 enumeration literal @code{SYSTEM_NAME_GNAT}.
24355
24356 The definitions provided by the use of
24357
24358 @smallexample @c ada
24359 pragma Extend_System (AUX_Dec);
24360 @end smallexample
24361
24362 @noindent
24363 are virtually identical to those provided by the HP Ada 83 package
24364 @code{SYSTEM}. One important difference is that the name of the
24365 @code{TO_ADDRESS}
24366 function for type @code{UNSIGNED_LONGWORD} is changed to
24367 @code{TO_ADDRESS_LONG}.
24368 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual} for a
24369 discussion of why this change was necessary.
24370
24371 @noindent
24372 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
24373 is in fact
24374 an extension to Ada 83 not strictly compatible with the reference manual.
24375 GNAT, in order to be exactly compatible with the standard,
24376 does not provide this capability. In HP Ada 83, the
24377 point of this definition is to deal with a call like:
24378
24379 @smallexample @c ada
24380 TO_ADDRESS (16#12777#);
24381 @end smallexample
24382
24383 @noindent
24384 Normally, according to Ada 83 semantics, one would expect this to be
24385 ambiguous, since it matches both the @code{INTEGER} and
24386 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
24387 However, in HP Ada 83, there is no ambiguity, since the
24388 definition using @i{universal_integer} takes precedence.
24389
24390 In GNAT, since the version with @i{universal_integer} cannot be supplied,
24391 it is
24392 not possible to be 100% compatible. Since there are many programs using
24393 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
24394 GNAT was
24395 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
24396 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
24397
24398 @smallexample @c ada
24399 function To_Address (X : Integer) return Address;
24400 pragma Pure_Function (To_Address);
24401
24402 function To_Address_Long (X : Unsigned_Longword) return Address;
24403 pragma Pure_Function (To_Address_Long);
24404 @end smallexample
24405
24406 @noindent
24407 This means that programs using @code{TO_ADDRESS} for
24408 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
24409
24410 @node Tasking and Task-Related Features
24411 @section Tasking and Task-Related Features
24412
24413 @noindent
24414 This section compares the treatment of tasking in GNAT
24415 and in HP Ada for OpenVMS Alpha.
24416 The GNAT description applies to both Alpha and I64 OpenVMS.
24417 For detailed information on tasking in
24418 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
24419 relevant run-time reference manual.
24420
24421 @menu
24422 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
24423 * Assigning Task IDs::
24424 * Task IDs and Delays::
24425 * Task-Related Pragmas::
24426 * Scheduling and Task Priority::
24427 * The Task Stack::
24428 * External Interrupts::
24429 @end menu
24430
24431 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
24432 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
24433
24434 @noindent
24435 On OpenVMS Alpha systems, each Ada task (except a passive
24436 task) is implemented as a single stream of execution
24437 that is created and managed by the kernel. On these
24438 systems, HP Ada tasking support is based on DECthreads,
24439 an implementation of the POSIX standard for threads.
24440
24441 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
24442 code that calls DECthreads routines can be used together.
24443 The interaction between Ada tasks and DECthreads routines
24444 can have some benefits. For example when on OpenVMS Alpha,
24445 HP Ada can call C code that is already threaded.
24446
24447 GNAT uses the facilities of DECthreads,
24448 and Ada tasks are mapped to threads.
24449
24450 @node Assigning Task IDs
24451 @subsection Assigning Task IDs
24452
24453 @noindent
24454 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
24455 the environment task that executes the main program. On
24456 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
24457 that have been created but are not yet activated.
24458
24459 On OpenVMS Alpha systems, task IDs are assigned at
24460 activation. On GNAT systems, task IDs are also assigned at
24461 task creation but do not have the same form or values as
24462 task ID values in HP Ada. There is no null task, and the
24463 environment task does not have a specific task ID value.
24464
24465 @node Task IDs and Delays
24466 @subsection Task IDs and Delays
24467
24468 @noindent
24469 On OpenVMS Alpha systems, tasking delays are implemented
24470 using Timer System Services. The Task ID is used for the
24471 identification of the timer request (the @code{REQIDT} parameter).
24472 If Timers are used in the application take care not to use
24473 @code{0} for the identification, because cancelling such a timer
24474 will cancel all timers and may lead to unpredictable results.
24475
24476 @node Task-Related Pragmas
24477 @subsection Task-Related Pragmas
24478
24479 @noindent
24480 Ada supplies the pragma @code{TASK_STORAGE}, which allows
24481 specification of the size of the guard area for a task
24482 stack. (The guard area forms an area of memory that has no
24483 read or write access and thus helps in the detection of
24484 stack overflow.) On OpenVMS Alpha systems, if the pragma
24485 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
24486 area is created. In the absence of a pragma @code{TASK_STORAGE},
24487 a default guard area is created.
24488
24489 GNAT supplies the following task-related pragmas:
24490
24491 @itemize @bullet
24492 @item  @code{TASK_INFO}
24493
24494 This pragma appears within a task definition and
24495 applies to the task in which it appears. The argument
24496 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
24497
24498 @item  @code{TASK_STORAGE}
24499
24500 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
24501 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
24502 @code{SUPPRESS}, and @code{VOLATILE}.
24503 @end itemize
24504 @node Scheduling and Task Priority
24505 @subsection Scheduling and Task Priority
24506
24507 @noindent
24508 HP Ada implements the Ada language requirement that
24509 when two tasks are eligible for execution and they have
24510 different priorities, the lower priority task does not
24511 execute while the higher priority task is waiting. The HP
24512 Ada Run-Time Library keeps a task running until either the
24513 task is suspended or a higher priority task becomes ready.
24514
24515 On OpenVMS Alpha systems, the default strategy is round-
24516 robin with preemption. Tasks of equal priority take turns
24517 at the processor. A task is run for a certain period of
24518 time and then placed at the tail of the ready queue for
24519 its priority level.
24520
24521 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
24522 which can be used to enable or disable round-robin
24523 scheduling of tasks with the same priority.
24524 See the relevant HP Ada run-time reference manual for
24525 information on using the pragmas to control HP Ada task
24526 scheduling.
24527
24528 GNAT follows the scheduling rules of Annex D (Real-Time
24529 Annex) of the @cite{Ada Reference Manual}. In general, this
24530 scheduling strategy is fully compatible with HP Ada
24531 although it provides some additional constraints (as
24532 fully documented in Annex D).
24533 GNAT implements time slicing control in a manner compatible with
24534 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
24535 are identical to the HP Ada 83 pragma of the same name.
24536 Note that it is not possible to mix GNAT tasking and
24537 HP Ada 83 tasking in the same program, since the two run-time
24538 libraries are not compatible.
24539
24540 @node The Task Stack
24541 @subsection The Task Stack
24542
24543 @noindent
24544 In HP Ada, a task stack is allocated each time a
24545 non-passive task is activated. As soon as the task is
24546 terminated, the storage for the task stack is deallocated.
24547 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
24548 a default stack size is used. Also, regardless of the size
24549 specified, some additional space is allocated for task
24550 management purposes. On OpenVMS Alpha systems, at least
24551 one page is allocated.
24552
24553 GNAT handles task stacks in a similar manner. In accordance with
24554 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
24555 an alternative method for controlling the task stack size.
24556 The specification of the attribute @code{T'STORAGE_SIZE} is also
24557 supported in a manner compatible with HP Ada.
24558
24559 @node External Interrupts
24560 @subsection External Interrupts
24561
24562 @noindent
24563 On HP Ada, external interrupts can be associated with task entries.
24564 GNAT is compatible with HP Ada in its handling of external interrupts.
24565
24566 @node Pragmas and Pragma-Related Features
24567 @section Pragmas and Pragma-Related Features
24568
24569 @noindent
24570 Both HP Ada and GNAT supply all language-defined pragmas
24571 as specified by the Ada 83 standard. GNAT also supplies all
24572 language-defined pragmas introduced by Ada 95 and Ada 2005.
24573 In addition, GNAT implements the implementation-defined pragmas
24574 from HP Ada 83.
24575
24576 @itemize @bullet
24577 @item  @code{AST_ENTRY}
24578
24579 @item  @code{COMMON_OBJECT}
24580
24581 @item  @code{COMPONENT_ALIGNMENT}
24582
24583 @item  @code{EXPORT_EXCEPTION}
24584
24585 @item  @code{EXPORT_FUNCTION}
24586
24587 @item  @code{EXPORT_OBJECT}
24588
24589 @item  @code{EXPORT_PROCEDURE}
24590
24591 @item  @code{EXPORT_VALUED_PROCEDURE}
24592
24593 @item  @code{FLOAT_REPRESENTATION}
24594
24595 @item  @code{IDENT}
24596
24597 @item  @code{IMPORT_EXCEPTION}
24598
24599 @item  @code{IMPORT_FUNCTION}
24600
24601 @item  @code{IMPORT_OBJECT}
24602
24603 @item  @code{IMPORT_PROCEDURE}
24604
24605 @item  @code{IMPORT_VALUED_PROCEDURE}
24606
24607 @item  @code{INLINE_GENERIC}
24608
24609 @item  @code{INTERFACE_NAME}
24610
24611 @item  @code{LONG_FLOAT}
24612
24613 @item  @code{MAIN_STORAGE}
24614
24615 @item  @code{PASSIVE}
24616
24617 @item  @code{PSECT_OBJECT}
24618
24619 @item  @code{SHARE_GENERIC}
24620
24621 @item  @code{SUPPRESS_ALL}
24622
24623 @item  @code{TASK_STORAGE}
24624
24625 @item  @code{TIME_SLICE}
24626
24627 @item  @code{TITLE}
24628 @end itemize
24629
24630 @noindent
24631 These pragmas are all fully implemented, with the exception of @code{TITLE},
24632 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
24633 recognized, but which have no
24634 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
24635 use of Ada protected objects. In GNAT, all generics are inlined.
24636
24637 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
24638 a separate subprogram specification which must appear before the
24639 subprogram body.
24640
24641 GNAT also supplies a number of implementation-defined pragmas as follows:
24642 @itemize @bullet
24643 @item  @code{ABORT_DEFER}
24644
24645 @item  @code{ADA_83}
24646
24647 @item  @code{ADA_95}
24648
24649 @item  @code{ADA_05}
24650
24651 @item  @code{ANNOTATE}
24652
24653 @item  @code{ASSERT}
24654
24655 @item  @code{C_PASS_BY_COPY}
24656
24657 @item  @code{CPP_CLASS}
24658
24659 @item  @code{CPP_CONSTRUCTOR}
24660
24661 @item  @code{CPP_DESTRUCTOR}
24662
24663 @item  @code{DEBUG}
24664
24665 @item  @code{EXTEND_SYSTEM}
24666
24667 @item  @code{LINKER_ALIAS}
24668
24669 @item  @code{LINKER_SECTION}
24670
24671 @item  @code{MACHINE_ATTRIBUTE}
24672
24673 @item  @code{NO_RETURN}
24674
24675 @item  @code{PURE_FUNCTION}
24676
24677 @item  @code{SOURCE_FILE_NAME}
24678
24679 @item  @code{SOURCE_REFERENCE}
24680
24681 @item  @code{TASK_INFO}
24682
24683 @item  @code{UNCHECKED_UNION}
24684
24685 @item  @code{UNIMPLEMENTED_UNIT}
24686
24687 @item  @code{UNIVERSAL_DATA}
24688
24689 @item  @code{UNSUPPRESS}
24690
24691 @item  @code{WARNINGS}
24692
24693 @item  @code{WEAK_EXTERNAL}
24694 @end itemize
24695
24696 @noindent
24697 For full details on these GNAT implementation-defined pragmas,
24698 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
24699 Manual}.
24700
24701 @menu
24702 * Restrictions on the Pragma INLINE::
24703 * Restrictions on the Pragma INTERFACE::
24704 * Restrictions on the Pragma SYSTEM_NAME::
24705 @end menu
24706
24707 @node Restrictions on the Pragma INLINE
24708 @subsection Restrictions on Pragma @code{INLINE}
24709
24710 @noindent
24711 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
24712 @itemize @bullet
24713 @item  Parameters cannot have a task type.
24714
24715 @item  Function results cannot be task types, unconstrained
24716 array types, or unconstrained types with discriminants.
24717
24718 @item  Bodies cannot declare the following:
24719 @itemize @bullet
24720 @item  Subprogram body or stub (imported subprogram is allowed)
24721
24722 @item  Tasks
24723
24724 @item  Generic declarations
24725
24726 @item  Instantiations
24727
24728 @item  Exceptions
24729
24730 @item  Access types (types derived from access types allowed)
24731
24732 @item  Array or record types
24733
24734 @item  Dependent tasks
24735
24736 @item  Direct recursive calls of subprogram or containing
24737 subprogram, directly or via a renaming
24738
24739 @end itemize
24740 @end itemize
24741
24742 @noindent
24743 In GNAT, the only restriction on pragma @code{INLINE} is that the
24744 body must occur before the call if both are in the same
24745 unit, and the size must be appropriately small. There are
24746 no other specific restrictions which cause subprograms to
24747 be incapable of being inlined.
24748
24749 @node  Restrictions on the Pragma INTERFACE
24750 @subsection  Restrictions on Pragma @code{INTERFACE}
24751
24752 @noindent
24753 The following restrictions on pragma @code{INTERFACE}
24754 are enforced by both HP Ada and GNAT:
24755 @itemize @bullet
24756 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
24757 Default is the default on OpenVMS Alpha systems.
24758
24759 @item  Parameter passing: Language specifies default
24760 mechanisms but can be overridden with an @code{EXPORT} pragma.
24761
24762 @itemize @bullet
24763 @item  Ada: Use internal Ada rules.
24764
24765 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
24766 record or task type. Result cannot be a string, an
24767 array, or a record.
24768
24769 @item  Fortran: Parameters cannot have a task type. Result cannot
24770 be a string, an array, or a record.
24771 @end itemize
24772 @end itemize
24773
24774 @noindent
24775 GNAT is entirely upwards compatible with HP Ada, and in addition allows
24776 record parameters for all languages.
24777
24778 @node  Restrictions on the Pragma SYSTEM_NAME
24779 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
24780
24781 @noindent
24782 For HP Ada for OpenVMS Alpha, the enumeration literal
24783 for the type @code{NAME} is @code{OPENVMS_AXP}.
24784 In GNAT, the enumeration
24785 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
24786
24787 @node  Library of Predefined Units
24788 @section  Library of Predefined Units
24789
24790 @noindent
24791 A library of predefined units is provided as part of the
24792 HP Ada and GNAT implementations. HP Ada does not provide
24793 the package @code{MACHINE_CODE} but instead recommends importing
24794 assembler code.
24795
24796 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
24797 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
24798 version.
24799 The HP Ada Predefined Library units are modified to remove post-Ada 83
24800 incompatibilities and to make them interoperable with GNAT
24801 (@pxref{Changes to DECLIB}, for details).
24802 The units are located in the @file{DECLIB} directory.
24803
24804 The GNAT RTL is contained in
24805 the @file{ADALIB} directory, and
24806 the default search path is set up to find @code{DECLIB} units in preference
24807 to @code{ADALIB} units with the same name (@code{TEXT_IO},
24808 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
24809
24810 @menu
24811 * Changes to DECLIB::
24812 @end menu
24813
24814 @node Changes to DECLIB
24815 @subsection Changes to @code{DECLIB}
24816
24817 @noindent
24818 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
24819 compatibility are minor and include the following:
24820
24821 @itemize @bullet
24822 @item  Adjusting the location of pragmas and record representation
24823 clauses to obey Ada 95 (and thus Ada 2005) rules
24824
24825 @item  Adding the proper notation to generic formal parameters
24826 that take unconstrained types in instantiation
24827
24828 @item  Adding pragma @code{ELABORATE_BODY} to package specs
24829 that have package bodies not otherwise allowed
24830
24831 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
24832 ``@code{PROTECTD}''.
24833 Currently these are found only in the @code{STARLET} package spec.
24834
24835 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
24836 where the address size is constrained to 32 bits.
24837 @end itemize
24838
24839 @noindent
24840 None of the above changes is visible to users.
24841
24842 @node Bindings
24843 @section Bindings
24844
24845 @noindent
24846 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
24847 @itemize @bullet
24848
24849 @item  Command Language Interpreter (CLI interface)
24850
24851 @item  DECtalk Run-Time Library (DTK interface)
24852
24853 @item  Librarian utility routines (LBR interface)
24854
24855 @item  General Purpose Run-Time Library (LIB interface)
24856
24857 @item  Math Run-Time Library (MTH interface)
24858
24859 @item  National Character Set Run-Time Library (NCS interface)
24860
24861 @item  Compiled Code Support Run-Time Library (OTS interface)
24862
24863 @item  Parallel Processing Run-Time Library (PPL interface)
24864
24865 @item  Screen Management Run-Time Library (SMG interface)
24866
24867 @item  Sort Run-Time Library (SOR interface)
24868
24869 @item  String Run-Time Library (STR interface)
24870
24871 @item STARLET System Library
24872 @findex Starlet
24873
24874 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
24875
24876 @item  X Windows Toolkit (XT interface)
24877
24878 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
24879 @end itemize
24880
24881 @noindent
24882 GNAT provides implementations of these HP bindings in the @code{DECLIB}
24883 directory, on both the Alpha and I64 OpenVMS platforms.
24884
24885 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
24886 in the
24887 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
24888 A pragma @code{Linker_Options} has been added to packages @code{Xm},
24889 @code{Xt}, and @code{X_Lib}
24890 causing the default X/Motif sharable image libraries to be linked in. This
24891 is done via options files named @file{xm.opt}, @file{xt.opt}, and
24892 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
24893
24894 It may be necessary to edit these options files to update or correct the
24895 library names if, for example, the newer X/Motif bindings from
24896 @file{ADA$EXAMPLES}
24897 had been (previous to installing GNAT) copied and renamed to supersede the
24898 default @file{ADA$PREDEFINED} versions.
24899
24900 @menu
24901 * Shared Libraries and Options Files::
24902 * Interfaces to C::
24903 @end menu
24904
24905 @node Shared Libraries and Options Files
24906 @subsection Shared Libraries and Options Files
24907
24908 @noindent
24909 When using the HP Ada
24910 predefined X and Motif bindings, the linking with their sharable images is
24911 done automatically by @command{GNAT LINK}.
24912 When using other X and Motif bindings, you need
24913 to add the corresponding sharable images to the command line for
24914 @code{GNAT LINK}. When linking with shared libraries, or with
24915 @file{.OPT} files, you must
24916 also add them to the command line for @command{GNAT LINK}.
24917
24918 A shared library to be used with GNAT is built in the same way as other
24919 libraries under VMS. The VMS Link command can be used in standard fashion.
24920
24921 @node Interfaces to C
24922 @subsection Interfaces to C
24923
24924 @noindent
24925 HP Ada
24926 provides the following Ada types and operations:
24927
24928 @itemize @bullet
24929 @item C types package (@code{C_TYPES})
24930
24931 @item C strings (@code{C_TYPES.NULL_TERMINATED})
24932
24933 @item Other_types (@code{SHORT_INT})
24934 @end itemize
24935
24936 @noindent
24937 Interfacing to C with GNAT, you can use the above approach
24938 described for HP Ada or the facilities of Annex B of
24939 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
24940 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
24941 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
24942
24943 The @option{-gnatF} qualifier forces default and explicit
24944 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
24945 to be uppercased for compatibility with the default behavior
24946 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
24947
24948 @node Main Program Definition
24949 @section Main Program Definition
24950
24951 @noindent
24952 The following section discusses differences in the
24953 definition of main programs on HP Ada and GNAT.
24954 On HP Ada, main programs are defined to meet the
24955 following conditions:
24956 @itemize @bullet
24957 @item  Procedure with no formal parameters (returns @code{0} upon
24958 normal completion)
24959
24960 @item  Procedure with no formal parameters (returns @code{42} when
24961 an unhandled exception is raised)
24962
24963 @item  Function with no formal parameters whose returned value
24964 is of a discrete type
24965
24966 @item  Procedure with one @code{out} formal of a discrete type for
24967 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
24968
24969 @end itemize
24970
24971 @noindent
24972 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
24973 a main function or main procedure returns a discrete
24974 value whose size is less than 64 bits (32 on VAX systems),
24975 the value is zero- or sign-extended as appropriate.
24976 On GNAT, main programs are defined as follows:
24977 @itemize @bullet
24978 @item  Must be a non-generic, parameterless subprogram that
24979 is either a procedure or function returning an Ada
24980 @code{STANDARD.INTEGER} (the predefined type)
24981
24982 @item  Cannot be a generic subprogram or an instantiation of a
24983 generic subprogram
24984 @end itemize
24985
24986 @node Implementation-Defined Attributes
24987 @section Implementation-Defined Attributes
24988
24989 @noindent
24990 GNAT provides all HP Ada implementation-defined
24991 attributes.
24992
24993 @node Compiler and Run-Time Interfacing
24994 @section Compiler and Run-Time Interfacing
24995
24996 @noindent
24997 HP Ada provides the following qualifiers to pass options to the linker
24998 (ACS LINK):
24999 @itemize @bullet
25000 @item  @option{/WAIT} and @option{/SUBMIT}
25001
25002 @item  @option{/COMMAND}
25003
25004 @item  @option{/@r{[}NO@r{]}MAP}
25005
25006 @item  @option{/OUTPUT=@var{file-spec}}
25007
25008 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
25009 @end itemize
25010
25011 @noindent
25012 To pass options to the linker, GNAT provides the following
25013 switches:
25014
25015 @itemize @bullet
25016 @item   @option{/EXECUTABLE=@var{exec-name}}
25017
25018 @item   @option{/VERBOSE}
25019
25020 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
25021 @end itemize
25022
25023 @noindent
25024 For more information on these switches, see
25025 @ref{Switches for gnatlink}.
25026 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
25027 to control optimization. HP Ada also supplies the
25028 following pragmas:
25029 @itemize @bullet
25030 @item  @code{OPTIMIZE}
25031
25032 @item  @code{INLINE}
25033
25034 @item  @code{INLINE_GENERIC}
25035
25036 @item  @code{SUPPRESS_ALL}
25037
25038 @item  @code{PASSIVE}
25039 @end itemize
25040
25041 @noindent
25042 In GNAT, optimization is controlled strictly by command
25043 line parameters, as described in the corresponding section of this guide.
25044 The HP pragmas for control of optimization are
25045 recognized but ignored.
25046
25047 Note that in GNAT, the default is optimization off, whereas in HP Ada
25048 the default is that optimization is turned on.
25049
25050 @node Program Compilation and Library Management
25051 @section Program Compilation and Library Management
25052
25053 @noindent
25054 HP Ada and GNAT provide a comparable set of commands to
25055 build programs. HP Ada also provides a program library,
25056 which is a concept that does not exist on GNAT. Instead,
25057 GNAT provides directories of sources that are compiled as
25058 needed.
25059
25060 The following table summarizes
25061 the HP Ada commands and provides
25062 equivalent GNAT commands. In this table, some GNAT
25063 equivalents reflect the fact that GNAT does not use the
25064 concept of a program library. Instead, it uses a model
25065 in which collections of source and object files are used
25066 in a manner consistent with other languages like C and
25067 Fortran. Therefore, standard system file commands are used
25068 to manipulate these elements. Those GNAT commands are marked with
25069 an asterisk.
25070 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
25071
25072 @need 1500
25073 @multitable @columnfractions .35 .65
25074
25075 @item @emph{HP Ada Command}
25076 @tab @emph{GNAT Equivalent / Description}
25077
25078 @item @command{ADA}
25079 @tab @command{GNAT COMPILE}@*
25080 Invokes the compiler to compile one or more Ada source files.
25081
25082 @item @command{ACS ATTACH}@*
25083 @tab [No equivalent]@*
25084 Switches control of terminal from current process running the program
25085 library manager.
25086
25087 @item @command{ACS CHECK}
25088 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
25089 Forms the execution closure of one
25090 or more compiled units and checks completeness and currency.
25091
25092 @item @command{ACS COMPILE}
25093 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
25094 Forms the execution closure of one or
25095 more specified units, checks completeness and currency,
25096 identifies units that have revised source files, compiles same,
25097 and recompiles units that are or will become obsolete.
25098 Also completes incomplete generic instantiations.
25099
25100 @item @command{ACS COPY FOREIGN}
25101 @tab Copy (*)@*
25102 Copies a foreign object file into the program library as a
25103 library unit body.
25104
25105 @item @command{ACS COPY UNIT}
25106 @tab Copy (*)@*
25107 Copies a compiled unit from one program library to another.
25108
25109 @item @command{ACS CREATE LIBRARY}
25110 @tab Create /directory (*)@*
25111 Creates a program library.
25112
25113 @item @command{ACS CREATE SUBLIBRARY}
25114 @tab Create /directory (*)@*
25115 Creates a program sublibrary.
25116
25117 @item @command{ACS DELETE LIBRARY}
25118 @tab @*
25119 Deletes a program library and its contents.
25120
25121 @item @command{ACS DELETE SUBLIBRARY}
25122 @tab @*
25123 Deletes a program sublibrary and its contents.
25124
25125 @item @command{ACS DELETE UNIT}
25126 @tab Delete file (*)@*
25127 On OpenVMS systems, deletes one or more compiled units from
25128 the current program library.
25129
25130 @item @command{ACS DIRECTORY}
25131 @tab Directory (*)@*
25132 On OpenVMS systems, lists units contained in the current
25133 program library.
25134
25135 @item @command{ACS ENTER FOREIGN}
25136 @tab Copy (*)@*
25137 Allows the import of a foreign body as an Ada library
25138 spec and enters a reference to a pointer.
25139
25140 @item @command{ACS ENTER UNIT}
25141 @tab Copy (*)@*
25142 Enters a reference (pointer) from the current program library to
25143 a unit compiled into another program library.
25144
25145 @item @command{ACS EXIT}
25146 @tab [No equivalent]@*
25147 Exits from the program library manager.
25148
25149 @item @command{ACS EXPORT}
25150 @tab Copy (*)@*
25151 Creates an object file that contains system-specific object code
25152 for one or more units. With GNAT, object files can simply be copied
25153 into the desired directory.
25154
25155 @item @command{ACS EXTRACT SOURCE}
25156 @tab Copy (*)@*
25157 Allows access to the copied source file for each Ada compilation unit
25158
25159 @item @command{ACS HELP}
25160 @tab @command{HELP GNAT}@*
25161 Provides online help.
25162
25163 @item @command{ACS LINK}
25164 @tab @command{GNAT LINK}@*
25165 Links an object file containing Ada units into an executable file.
25166
25167 @item @command{ACS LOAD}
25168 @tab Copy (*)@*
25169 Loads (partially compiles) Ada units into the program library.
25170 Allows loading a program from a collection of files into a library
25171 without knowing the relationship among units.
25172
25173 @item @command{ACS MERGE}
25174 @tab Copy (*)@*
25175 Merges into the current program library, one or more units from
25176 another library where they were modified.
25177
25178 @item @command{ACS RECOMPILE}
25179 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
25180 Recompiles from   external or copied source files any obsolete
25181 unit in the closure. Also, completes any incomplete generic
25182 instantiations.
25183
25184 @item @command{ACS REENTER}
25185 @tab @command{GNAT MAKE}@*
25186 Reenters current references to units compiled after last entered
25187 with the @command{ACS ENTER UNIT} command.
25188
25189 @item @command{ACS SET LIBRARY}
25190 @tab Set default (*)@*
25191 Defines a program library to be the compilation context as well
25192 as the target library for compiler output and commands in general.
25193
25194 @item @command{ACS SET PRAGMA}
25195 @tab Edit @file{gnat.adc} (*)@*
25196 Redefines specified  values of the library characteristics
25197 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
25198 and @code{Float_Representation}.
25199
25200 @item @command{ACS SET SOURCE}
25201 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
25202 Defines the source file search list for the @command{ACS COMPILE} command.
25203
25204 @item @command{ACS SHOW LIBRARY}
25205 @tab Directory (*)@*
25206 Lists information about one or more program libraries.
25207
25208 @item @command{ACS SHOW PROGRAM}
25209 @tab [No equivalent]@*
25210 Lists information about the execution closure of one or
25211 more units in the program library.
25212
25213 @item @command{ACS SHOW SOURCE}
25214 @tab Show logical @code{ADA_INCLUDE_PATH}@*
25215 Shows the source file search used when compiling units.
25216
25217 @item @command{ACS SHOW VERSION}
25218 @tab Compile with @option{VERBOSE} option
25219 Displays the version number of the compiler and program library
25220 manager used.
25221
25222 @item @command{ACS SPAWN}
25223 @tab [No equivalent]@*
25224 Creates a subprocess of the current process (same as @command{DCL SPAWN}
25225 command).
25226
25227 @item @command{ACS VERIFY}
25228 @tab [No equivalent]@*
25229 Performs a series of consistency checks on a program library to
25230 determine whether the library structure and library files are in
25231 valid form.
25232 @end multitable
25233
25234 @noindent
25235
25236 @node Input-Output
25237 @section Input-Output
25238
25239 @noindent
25240 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
25241 Management Services (RMS) to perform operations on
25242 external files.
25243
25244 @noindent
25245 HP Ada and GNAT predefine an identical set of input-
25246 output packages. To make the use of the
25247 generic @code{TEXT_IO} operations more convenient, HP Ada
25248 provides predefined library packages that instantiate the
25249 integer and floating-point operations for the predefined
25250 integer and floating-point types as shown in the following table.
25251
25252 @multitable @columnfractions .45 .55
25253 @item @emph{Package Name} @tab Instantiation
25254
25255 @item @code{INTEGER_TEXT_IO}
25256 @tab @code{INTEGER_IO(INTEGER)}
25257
25258 @item @code{SHORT_INTEGER_TEXT_IO}
25259 @tab @code{INTEGER_IO(SHORT_INTEGER)}
25260
25261 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
25262 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
25263
25264 @item @code{FLOAT_TEXT_IO}
25265 @tab @code{FLOAT_IO(FLOAT)}
25266
25267 @item @code{LONG_FLOAT_TEXT_IO}
25268 @tab @code{FLOAT_IO(LONG_FLOAT)}
25269 @end multitable
25270
25271 @noindent
25272 The HP Ada predefined packages and their operations
25273 are implemented using OpenVMS Alpha files and input-output
25274 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
25275 Familiarity with the following is recommended:
25276 @itemize @bullet
25277 @item  RMS file organizations and access methods
25278
25279 @item  OpenVMS file specifications and directories
25280
25281 @item  OpenVMS File Definition Language (FDL)
25282 @end itemize
25283
25284 @noindent
25285 GNAT provides I/O facilities that are completely
25286 compatible with HP Ada. The distribution includes the
25287 standard HP Ada versions of all I/O packages, operating
25288 in a manner compatible with HP Ada. In particular, the
25289 following packages are by default the HP Ada (Ada 83)
25290 versions of these packages rather than the renamings
25291 suggested in Annex J of the Ada Reference Manual:
25292 @itemize @bullet
25293 @item  @code{TEXT_IO}
25294
25295 @item  @code{SEQUENTIAL_IO}
25296
25297 @item  @code{DIRECT_IO}
25298 @end itemize
25299
25300 @noindent
25301 The use of the standard child package syntax (for
25302 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
25303 packages.
25304 GNAT provides HP-compatible predefined instantiations
25305 of the @code{TEXT_IO} packages, and also
25306 provides the standard predefined instantiations required
25307 by the @cite{Ada Reference Manual}.
25308
25309 For further information on how GNAT interfaces to the file
25310 system or how I/O is implemented in programs written in
25311 mixed languages, see @ref{Implementation of the Standard I/O,,,
25312 gnat_rm, GNAT Reference Manual}.
25313 This chapter covers the following:
25314 @itemize @bullet
25315 @item  Standard I/O packages
25316
25317 @item  @code{FORM} strings
25318
25319 @item  @code{ADA.DIRECT_IO}
25320
25321 @item  @code{ADA.SEQUENTIAL_IO}
25322
25323 @item  @code{ADA.TEXT_IO}
25324
25325 @item  Stream pointer positioning
25326
25327 @item  Reading and writing non-regular files
25328
25329 @item  @code{GET_IMMEDIATE}
25330
25331 @item  Treating @code{TEXT_IO} files as streams
25332
25333 @item  Shared files
25334
25335 @item  Open modes
25336 @end itemize
25337
25338 @node Implementation Limits
25339 @section Implementation Limits
25340
25341 @noindent
25342 The following table lists implementation limits for HP Ada
25343 and GNAT systems.
25344 @multitable @columnfractions .60 .20 .20
25345 @sp 1
25346 @item  @emph{Compilation Parameter}
25347 @tab   @emph{HP Ada}
25348 @tab   @emph{GNAT}
25349 @sp 1
25350
25351 @item  In a subprogram or entry  declaration, maximum number of
25352 formal parameters that are of an unconstrained record type
25353 @tab   32
25354 @tab   No set limit
25355 @sp 1
25356
25357 @item  Maximum identifier length (number of characters)
25358 @tab   255
25359 @tab   32766
25360 @sp 1
25361
25362 @item  Maximum number of characters in a source line
25363 @tab   255
25364 @tab   32766
25365 @sp 1
25366
25367 @item  Maximum collection size   (number of bytes)
25368 @tab   2**31-1
25369 @tab   2**31-1
25370 @sp 1
25371
25372 @item  Maximum number of discriminants for a record type
25373 @tab   245
25374 @tab   No set limit
25375 @sp 1
25376
25377 @item  Maximum number of formal parameters in an entry or
25378 subprogram declaration
25379 @tab   246
25380 @tab    No set limit
25381 @sp 1
25382
25383 @item  Maximum number of dimensions in an array type
25384 @tab   255
25385 @tab   No set limit
25386 @sp 1
25387
25388 @item  Maximum number of library  units and subunits in a compilation.
25389 @tab   4095
25390 @tab   No set limit
25391 @sp 1
25392
25393 @item  Maximum number of library units and subunits in an execution.
25394 @tab   16383
25395 @tab   No set limit
25396 @sp 1
25397
25398 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
25399 or @code{PSECT_OBJECT}
25400 @tab   32757
25401 @tab   No set limit
25402 @sp 1
25403
25404 @item  Maximum number of enumeration literals in an enumeration type
25405 definition
25406 @tab   65535
25407 @tab   No set limit
25408 @sp 1
25409
25410 @item  Maximum number of lines in a source file
25411 @tab   65534
25412 @tab   No set limit
25413 @sp 1
25414
25415 @item  Maximum number of bits in any object
25416 @tab   2**31-1
25417 @tab   2**31-1
25418 @sp 1
25419
25420 @item  Maximum size of the static portion of a stack frame (approximate)
25421 @tab   2**31-1
25422 @tab   2**31-1
25423 @end multitable
25424
25425 @node Tools and Utilities
25426 @section Tools and Utilities
25427
25428 @noindent
25429 The following table lists some of the OpenVMS development tools
25430 available for HP Ada, and the corresponding tools for
25431 use with @value{EDITION} on Alpha and I64 platforms.
25432 Aside from the debugger, all the OpenVMS tools identified are part
25433 of the DECset package.
25434
25435 @iftex
25436 @c Specify table in TeX since Texinfo does a poor job
25437 @tex
25438 \smallskip
25439 \smallskip
25440 \settabs\+Language-Sensitive Editor\quad
25441    &Product with HP Ada\quad
25442    &\cr
25443 \+\it Tool
25444    &\it Product with HP Ada
25445    & \it Product with GNAT Pro\cr
25446 \smallskip
25447 \+Code Management System
25448    &HP CMS
25449    & HP CMS\cr
25450 \smallskip
25451 \+Language-Sensitive Editor
25452    &HP LSE
25453    & emacs or HP LSE (Alpha)\cr
25454 \+
25455    &
25456    & HP LSE (I64)\cr
25457 \smallskip
25458 \+Debugger
25459    &OpenVMS Debug
25460    & gdb (Alpha),\cr
25461 \+
25462    &
25463    & OpenVMS Debug (I64)\cr
25464 \smallskip
25465 \+Source Code Analyzer /
25466    &HP SCA
25467    & GNAT XREF\cr
25468 \+Cross Referencer
25469    &
25470    &\cr
25471 \smallskip
25472 \+Test Manager
25473    &HP Digital Test
25474    & HP DTM\cr
25475 \+
25476    &Manager (DTM)
25477    &\cr
25478 \smallskip
25479 \+Performance and
25480    & HP PCA
25481    & HP PCA\cr
25482 \+Coverage Analyzer
25483    &
25484    &\cr
25485 \smallskip
25486 \+Module Management
25487    & HP MMS
25488    & Not applicable\cr
25489 \+ System
25490    &
25491    &\cr
25492 \smallskip
25493 \smallskip
25494 @end tex
25495 @end iftex
25496
25497 @ifnottex
25498 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
25499 @c the TeX version above for the printed version
25500 @flushleft
25501 @c @multitable @columnfractions .3 .4 .4
25502 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
25503 @item @i{Tool}
25504 @tab @i{Tool with HP Ada}
25505 @tab @i{Tool with @value{EDITION}}
25506 @item Code Management@*System
25507 @tab HP CMS
25508 @tab HP CMS
25509 @item Language-Sensitive@*Editor
25510 @tab HP LSE
25511 @tab emacs or HP LSE (Alpha)
25512 @item
25513 @tab
25514 @tab HP LSE (I64)
25515 @item Debugger
25516 @tab OpenVMS Debug
25517 @tab gdb (Alpha),
25518 @item
25519 @tab
25520 @tab OpenVMS Debug (I64)
25521 @item Source Code Analyzer /@*Cross Referencer
25522 @tab HP SCA
25523 @tab GNAT XREF
25524 @item Test Manager
25525 @tab HP Digital Test@*Manager (DTM)
25526 @tab HP DTM
25527 @item Performance and@*Coverage Analyzer
25528 @tab HP PCA
25529 @tab HP PCA
25530 @item Module Management@*System
25531 @tab HP MMS
25532 @tab Not applicable
25533 @end multitable
25534 @end flushleft
25535 @end ifnottex
25536
25537 @end ifset
25538
25539 @c **************************************
25540 @node Platform-Specific Information for the Run-Time Libraries
25541 @appendix Platform-Specific Information for the Run-Time Libraries
25542 @cindex Tasking and threads libraries
25543 @cindex Threads libraries and tasking
25544 @cindex Run-time libraries (platform-specific information)
25545
25546 @noindent
25547 The GNAT run-time implementation may vary with respect to both the
25548 underlying threads library and the exception handling scheme.
25549 For threads support, one or more of the following are supplied:
25550 @itemize @bullet
25551 @item @b{native threads library}, a binding to the thread package from
25552 the underlying operating system
25553
25554 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
25555 POSIX thread package
25556 @end itemize
25557
25558 @noindent
25559 For exception handling, either or both of two models are supplied:
25560 @itemize @bullet
25561 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
25562 Most programs should experience a substantial speed improvement by
25563 being compiled with a ZCX run-time.
25564 This is especially true for
25565 tasking applications or applications with many exception handlers.}
25566 @cindex Zero-Cost Exceptions
25567 @cindex ZCX (Zero-Cost Exceptions)
25568 which uses binder-generated tables that
25569 are interrogated at run time to locate a handler
25570
25571 @item @b{setjmp / longjmp} (``SJLJ''),
25572 @cindex setjmp/longjmp Exception Model
25573 @cindex SJLJ (setjmp/longjmp Exception Model)
25574 which uses dynamically-set data to establish
25575 the set of handlers
25576 @end itemize
25577
25578 @noindent
25579 This appendix summarizes which combinations of threads and exception support
25580 are supplied on various GNAT platforms.
25581 It then shows how to select a particular library either
25582 permanently or temporarily,
25583 explains the properties of (and tradeoffs among) the various threads
25584 libraries, and provides some additional
25585 information about several specific platforms.
25586
25587 @menu
25588 * Summary of Run-Time Configurations::
25589 * Specifying a Run-Time Library::
25590 * Choosing the Scheduling Policy::
25591 * Solaris-Specific Considerations::
25592 * Linux-Specific Considerations::
25593 * AIX-Specific Considerations::
25594 * Irix-Specific Considerations::
25595 * RTX-Specific Considerations::
25596 @end menu
25597
25598 @node Summary of Run-Time Configurations
25599 @section Summary of Run-Time Configurations
25600
25601 @multitable @columnfractions .30 .70
25602 @item @b{alpha-openvms}
25603 @item @code{@ @ }@i{rts-native (default)}
25604 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
25605 @item @code{@ @ @ @ }Exceptions @tab ZCX
25606 @*
25607 @item @b{alpha-tru64}
25608 @item @code{@ @ }@i{rts-native (default)}
25609 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
25610 @item @code{@ @ @ @ }Exceptions @tab ZCX
25611 @*
25612 @item @code{@ @ }@i{rts-sjlj}
25613 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
25614 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25615 @*
25616 @item @b{ia64-hp_linux}
25617 @item @code{@ @ }@i{rts-native (default)}
25618 @item @code{@ @ @ @ }Tasking    @tab pthread library
25619 @item @code{@ @ @ @ }Exceptions @tab ZCX
25620 @*
25621 @item @b{ia64-hpux}
25622 @item @code{@ @ }@i{rts-native (default)}
25623 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
25624 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25625 @*
25626 @item @b{ia64-openvms}
25627 @item @code{@ @ }@i{rts-native (default)}
25628 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
25629 @item @code{@ @ @ @ }Exceptions @tab ZCX
25630 @*
25631 @item @b{ia64-sgi_linux}
25632 @item @code{@ @ }@i{rts-native (default)}
25633 @item @code{@ @ @ @ }Tasking    @tab pthread library
25634 @item @code{@ @ @ @ }Exceptions @tab ZCX
25635 @*
25636 @item @b{mips-irix}
25637 @item @code{@ @ }@i{rts-native (default)}
25638 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
25639 @item @code{@ @ @ @ }Exceptions @tab ZCX
25640 @*
25641 @item @b{pa-hpux}
25642 @item @code{@ @ }@i{rts-native (default)}
25643 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
25644 @item @code{@ @ @ @ }Exceptions @tab ZCX
25645 @*
25646 @item @code{@ @ }@i{rts-sjlj}
25647 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
25648 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25649 @*
25650 @item @b{ppc-aix}
25651 @item @code{@ @ }@i{rts-native (default)}
25652 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
25653 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25654 @*
25655 @item @b{ppc-darwin}
25656 @item @code{@ @ }@i{rts-native (default)}
25657 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
25658 @item @code{@ @ @ @ }Exceptions @tab ZCX
25659 @*
25660 @item @b{sparc-solaris}  @tab
25661 @item @code{@ @ }@i{rts-native (default)}
25662 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
25663 @item @code{@ @ @ @ }Exceptions @tab ZCX
25664 @*
25665 @item @code{@ @ }@i{rts-pthread}
25666 @item @code{@ @ @ @ }Tasking    @tab pthread library
25667 @item @code{@ @ @ @ }Exceptions @tab ZCX
25668 @*
25669 @item @code{@ @ }@i{rts-sjlj}
25670 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
25671 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25672 @*
25673 @item @b{sparc64-solaris}  @tab
25674 @item @code{@ @ }@i{rts-native (default)}
25675 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
25676 @item @code{@ @ @ @ }Exceptions @tab ZCX
25677 @*
25678 @item @b{x86-linux}
25679 @item @code{@ @ }@i{rts-native (default)}
25680 @item @code{@ @ @ @ }Tasking    @tab pthread library
25681 @item @code{@ @ @ @ }Exceptions @tab ZCX
25682 @*
25683 @item @code{@ @ }@i{rts-sjlj}
25684 @item @code{@ @ @ @ }Tasking    @tab pthread library
25685 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25686 @*
25687 @item @b{x86-lynx}
25688 @item @code{@ @ }@i{rts-native (default)}
25689 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
25690 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25691 @*
25692 @item @b{x86-solaris}
25693 @item @code{@ @ }@i{rts-native (default)}
25694 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
25695 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25696 @*
25697 @item @b{x86-windows}
25698 @item @code{@ @ }@i{rts-native (default)}
25699 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
25700 @item @code{@ @ @ @ }Exceptions @tab ZCX
25701 @*
25702 @item @code{@ @ }@i{rts-sjlj (default)}
25703 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
25704 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25705 @*
25706 @item @b{x86-windows-rtx}
25707 @item @code{@ @ }@i{rts-rtx-rtss (default)}
25708 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
25709 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25710 @*
25711 @item @code{@ @ }@i{rts-rtx-w32}
25712 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
25713 @item @code{@ @ @ @ }Exceptions @tab ZCX
25714 @*
25715 @item @b{x86_64-linux}
25716 @item @code{@ @ }@i{rts-native (default)}
25717 @item @code{@ @ @ @ }Tasking    @tab pthread library
25718 @item @code{@ @ @ @ }Exceptions @tab ZCX
25719 @*
25720 @item @code{@ @ }@i{rts-sjlj}
25721 @item @code{@ @ @ @ }Tasking    @tab pthread library
25722 @item @code{@ @ @ @ }Exceptions @tab SJLJ
25723 @*
25724 @end multitable
25725
25726 @node Specifying a Run-Time Library
25727 @section Specifying a Run-Time Library
25728
25729 @noindent
25730 The @file{adainclude} subdirectory containing the sources of the GNAT
25731 run-time library, and the @file{adalib} subdirectory containing the
25732 @file{ALI} files and the static and/or shared GNAT library, are located
25733 in the gcc target-dependent area:
25734
25735 @smallexample
25736 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
25737 @end smallexample
25738
25739 @noindent
25740 As indicated above, on some platforms several run-time libraries are supplied.
25741 These libraries are installed in the target dependent area and
25742 contain a complete source and binary subdirectory. The detailed description
25743 below explains the differences between the different libraries in terms of
25744 their thread support.
25745
25746 The default run-time library (when GNAT is installed) is @emph{rts-native}.
25747 This default run time is selected by the means of soft links.
25748 For example on x86-linux:
25749
25750 @smallexample
25751 @group
25752  $(target-dir)
25753      |
25754      +--- adainclude----------+
25755      |                        |
25756      +--- adalib-----------+  |
25757      |                     |  |
25758      +--- rts-native       |  |
25759      |    |                |  |
25760      |    +--- adainclude <---+
25761      |    |                |
25762      |    +--- adalib <----+
25763      |
25764      +--- rts-sjlj
25765           |
25766           +--- adainclude
25767           |
25768           +--- adalib
25769 @end group
25770 @end smallexample
25771
25772 @noindent
25773 If the @i{rts-sjlj} library is to be selected on a permanent basis,
25774 these soft links can be modified with the following commands:
25775
25776 @smallexample
25777 $ cd $target
25778 $ rm -f adainclude adalib
25779 $ ln -s rts-sjlj/adainclude adainclude
25780 $ ln -s rts-sjlj/adalib adalib
25781 @end smallexample
25782
25783 @noindent
25784 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
25785 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
25786 @file{$target/ada_object_path}.
25787
25788 Selecting another run-time library temporarily can be
25789 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
25790 @cindex @option{--RTS} option
25791
25792 @node Choosing the Scheduling Policy
25793 @section Choosing the Scheduling Policy
25794
25795 @noindent
25796 When using a POSIX threads implementation, you have a choice of several
25797 scheduling policies: @code{SCHED_FIFO},
25798 @cindex @code{SCHED_FIFO} scheduling policy
25799 @code{SCHED_RR}
25800 @cindex @code{SCHED_RR} scheduling policy
25801 and @code{SCHED_OTHER}.
25802 @cindex @code{SCHED_OTHER} scheduling policy
25803 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
25804 or @code{SCHED_RR} requires special (e.g., root) privileges.
25805
25806 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
25807 @code{SCHED_FIFO},
25808 @cindex @code{SCHED_FIFO} scheduling policy
25809 you can use one of the following:
25810
25811 @itemize @bullet
25812 @item
25813 @code{pragma Time_Slice (0.0)}
25814 @cindex pragma Time_Slice
25815 @item
25816 the corresponding binder option @option{-T0}
25817 @cindex @option{-T0} option
25818 @item
25819 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
25820 @cindex pragma Task_Dispatching_Policy
25821 @end itemize
25822
25823 @noindent
25824 To specify @code{SCHED_RR},
25825 @cindex @code{SCHED_RR} scheduling policy
25826 you should use @code{pragma Time_Slice} with a
25827 value greater than @code{0.0}, or else use the corresponding @option{-T}
25828 binder option.
25829
25830 @node Solaris-Specific Considerations
25831 @section Solaris-Specific Considerations
25832 @cindex Solaris Sparc threads libraries
25833
25834 @noindent
25835 This section addresses some topics related to the various threads libraries
25836 on Sparc Solaris.
25837
25838 @menu
25839 * Solaris Threads Issues::
25840 @end menu
25841
25842 @node Solaris Threads Issues
25843 @subsection Solaris Threads Issues
25844
25845 @noindent
25846 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
25847 library based on POSIX threads --- @emph{rts-pthread}.
25848 @cindex rts-pthread threads library
25849 This run-time library has the advantage of being mostly shared across all
25850 POSIX-compliant thread implementations, and it also provides under
25851 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
25852 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
25853 and @code{PTHREAD_PRIO_PROTECT}
25854 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
25855 semantics that can be selected using the predefined pragma
25856 @code{Locking_Policy}
25857 @cindex pragma Locking_Policy (under rts-pthread)
25858 with respectively
25859 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
25860 @cindex @code{Inheritance_Locking} (under rts-pthread)
25861 @cindex @code{Ceiling_Locking} (under rts-pthread)
25862
25863 As explained above, the native run-time library is based on the Solaris thread
25864 library (@code{libthread}) and is the default library.
25865
25866 When the Solaris threads library is used (this is the default), programs
25867 compiled with GNAT can automatically take advantage of
25868 and can thus execute on multiple processors.
25869 The user can alternatively specify a processor on which the program should run
25870 to emulate a single-processor system. The multiprocessor / uniprocessor choice
25871 is made by
25872 setting the environment variable @env{GNAT_PROCESSOR}
25873 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
25874 to one of the following:
25875
25876 @table @code
25877 @item -2
25878 Use the default configuration (run the program on all
25879 available processors) - this is the same as having @code{GNAT_PROCESSOR}
25880 unset
25881
25882 @item -1
25883 Let the run-time implementation choose one processor and run the program on
25884 that processor
25885
25886 @item 0 .. Last_Proc
25887 Run the program on the specified processor.
25888 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
25889 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
25890 @end table
25891
25892 @node Linux-Specific Considerations
25893 @section Linux-Specific Considerations
25894 @cindex Linux threads libraries
25895
25896 @noindent
25897 On GNU/Linux without NPTL support (usually system with GNU C Library
25898 older than 2.3), the signal model is not POSIX compliant, which means
25899 that to send a signal to the process, you need to send the signal to all
25900 threads, e.g.@: by using @code{killpg()}.
25901
25902 @node AIX-Specific Considerations
25903 @section AIX-Specific Considerations
25904 @cindex AIX resolver library
25905
25906 @noindent
25907 On AIX, the resolver library initializes some internal structure on
25908 the first call to @code{get*by*} functions, which are used to implement
25909 @code{GNAT.Sockets.Get_Host_By_Name} and
25910 @code{GNAT.Sockets.Get_Host_By_Address}.
25911 If such initialization occurs within an Ada task, and the stack size for
25912 the task is the default size, a stack overflow may occur.
25913
25914 To avoid this overflow, the user should either ensure that the first call
25915 to @code{GNAT.Sockets.Get_Host_By_Name} or
25916 @code{GNAT.Sockets.Get_Host_By_Addrss}
25917 occurs in the environment task, or use @code{pragma Storage_Size} to
25918 specify a sufficiently large size for the stack of the task that contains
25919 this call.
25920
25921 @node Irix-Specific Considerations
25922 @section Irix-Specific Considerations
25923 @cindex Irix libraries
25924
25925 @noindent
25926 The GCC support libraries coming with the Irix compiler have moved to
25927 their canonical place with respect to the general Irix ABI related
25928 conventions. Running applications built with the default shared GNAT
25929 run-time now requires the LD_LIBRARY_PATH environment variable to
25930 include this location. A possible way to achieve this is to issue the
25931 following command line on a bash prompt:
25932
25933 @smallexample
25934 @group
25935 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
25936 @end group
25937 @end smallexample
25938
25939 @node RTX-Specific Considerations
25940 @section RTX-Specific Considerations
25941 @cindex RTX libraries
25942
25943 @noindent
25944 The Real-time Extension (RTX) to Windows is based on the Windows Win32
25945 API. Applications can be built to work in two different modes:
25946
25947 @itemize @bullet
25948 @item
25949 Windows executables that run in Ring 3 to utilize memory protection
25950 (@emph{rts-rtx-w32}).
25951
25952 @item
25953 Real-time subsystem (RTSS) executables that run in Ring 0, where
25954 performance can be optimized with RTSS applications taking precedent
25955 over all Windows applications (@emph{rts-rtx-rtss}).
25956
25957 @end itemize
25958
25959 @c *******************************
25960 @node Example of Binder Output File
25961 @appendix Example of Binder Output File
25962
25963 @noindent
25964 This Appendix displays the source code for @command{gnatbind}'s output
25965 file generated for a simple ``Hello World'' program.
25966 Comments have been added for clarification purposes.
25967
25968 @smallexample @c adanocomment
25969 @iftex
25970 @leftskip=0cm
25971 @end iftex
25972 --  The package is called Ada_Main unless this name is actually used
25973 --  as a unit name in the partition, in which case some other unique
25974 --  name is used.
25975
25976 with System;
25977 package ada_main is
25978
25979    Elab_Final_Code : Integer;
25980    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
25981
25982    --  The main program saves the parameters (argument count,
25983    --  argument values, environment pointer) in global variables
25984    --  for later access by other units including
25985    --  Ada.Command_Line.
25986
25987    gnat_argc : Integer;
25988    gnat_argv : System.Address;
25989    gnat_envp : System.Address;
25990
25991    --  The actual variables are stored in a library routine. This
25992    --  is useful for some shared library situations, where there
25993    --  are problems if variables are not in the library.
25994
25995    pragma Import (C, gnat_argc);
25996    pragma Import (C, gnat_argv);
25997    pragma Import (C, gnat_envp);
25998
25999    --  The exit status is similarly an external location
26000
26001    gnat_exit_status : Integer;
26002    pragma Import (C, gnat_exit_status);
26003
26004    GNAT_Version : constant String :=
26005                     "GNAT Version: 6.0.0w (20061115)";
26006    pragma Export (C, GNAT_Version, "__gnat_version");
26007
26008    --  This is the generated adafinal routine that performs
26009    --  finalization at the end of execution. In the case where
26010    --  Ada is the main program, this main program makes a call
26011    --  to adafinal at program termination.
26012
26013    procedure adafinal;
26014    pragma Export (C, adafinal, "adafinal");
26015
26016    --  This is the generated adainit routine that performs
26017    --  initialization at the start of execution. In the case
26018    --  where Ada is the main program, this main program makes
26019    --  a call to adainit at program startup.
26020
26021    procedure adainit;
26022    pragma Export (C, adainit, "adainit");
26023
26024    --  This routine is called at the start of execution. It is
26025    --  a dummy routine that is used by the debugger to breakpoint
26026    --  at the start of execution.
26027
26028    procedure Break_Start;
26029    pragma Import (C, Break_Start, "__gnat_break_start");
26030
26031    --  This is the actual generated main program (it would be
26032    --  suppressed if the no main program switch were used). As
26033    --  required by standard system conventions, this program has
26034    --  the external name main.
26035
26036    function main
26037      (argc : Integer;
26038       argv : System.Address;
26039       envp : System.Address)
26040       return Integer;
26041    pragma Export (C, main, "main");
26042
26043    --  The following set of constants give the version
26044    --  identification values for every unit in the bound
26045    --  partition. This identification is computed from all
26046    --  dependent semantic units, and corresponds to the
26047    --  string that would be returned by use of the
26048    --  Body_Version or Version attributes.
26049
26050    type Version_32 is mod 2 ** 32;
26051    u00001 : constant Version_32 := 16#7880BEB3#;
26052    u00002 : constant Version_32 := 16#0D24CBD0#;
26053    u00003 : constant Version_32 := 16#3283DBEB#;
26054    u00004 : constant Version_32 := 16#2359F9ED#;
26055    u00005 : constant Version_32 := 16#664FB847#;
26056    u00006 : constant Version_32 := 16#68E803DF#;
26057    u00007 : constant Version_32 := 16#5572E604#;
26058    u00008 : constant Version_32 := 16#46B173D8#;
26059    u00009 : constant Version_32 := 16#156A40CF#;
26060    u00010 : constant Version_32 := 16#033DABE0#;
26061    u00011 : constant Version_32 := 16#6AB38FEA#;
26062    u00012 : constant Version_32 := 16#22B6217D#;
26063    u00013 : constant Version_32 := 16#68A22947#;
26064    u00014 : constant Version_32 := 16#18CC4A56#;
26065    u00015 : constant Version_32 := 16#08258E1B#;
26066    u00016 : constant Version_32 := 16#367D5222#;
26067    u00017 : constant Version_32 := 16#20C9ECA4#;
26068    u00018 : constant Version_32 := 16#50D32CB6#;
26069    u00019 : constant Version_32 := 16#39A8BB77#;
26070    u00020 : constant Version_32 := 16#5CF8FA2B#;
26071    u00021 : constant Version_32 := 16#2F1EB794#;
26072    u00022 : constant Version_32 := 16#31AB6444#;
26073    u00023 : constant Version_32 := 16#1574B6E9#;
26074    u00024 : constant Version_32 := 16#5109C189#;
26075    u00025 : constant Version_32 := 16#56D770CD#;
26076    u00026 : constant Version_32 := 16#02F9DE3D#;
26077    u00027 : constant Version_32 := 16#08AB6B2C#;
26078    u00028 : constant Version_32 := 16#3FA37670#;
26079    u00029 : constant Version_32 := 16#476457A0#;
26080    u00030 : constant Version_32 := 16#731E1B6E#;
26081    u00031 : constant Version_32 := 16#23C2E789#;
26082    u00032 : constant Version_32 := 16#0F1BD6A1#;
26083    u00033 : constant Version_32 := 16#7C25DE96#;
26084    u00034 : constant Version_32 := 16#39ADFFA2#;
26085    u00035 : constant Version_32 := 16#571DE3E7#;
26086    u00036 : constant Version_32 := 16#5EB646AB#;
26087    u00037 : constant Version_32 := 16#4249379B#;
26088    u00038 : constant Version_32 := 16#0357E00A#;
26089    u00039 : constant Version_32 := 16#3784FB72#;
26090    u00040 : constant Version_32 := 16#2E723019#;
26091    u00041 : constant Version_32 := 16#623358EA#;
26092    u00042 : constant Version_32 := 16#107F9465#;
26093    u00043 : constant Version_32 := 16#6843F68A#;
26094    u00044 : constant Version_32 := 16#63305874#;
26095    u00045 : constant Version_32 := 16#31E56CE1#;
26096    u00046 : constant Version_32 := 16#02917970#;
26097    u00047 : constant Version_32 := 16#6CCBA70E#;
26098    u00048 : constant Version_32 := 16#41CD4204#;
26099    u00049 : constant Version_32 := 16#572E3F58#;
26100    u00050 : constant Version_32 := 16#20729FF5#;
26101    u00051 : constant Version_32 := 16#1D4F93E8#;
26102    u00052 : constant Version_32 := 16#30B2EC3D#;
26103    u00053 : constant Version_32 := 16#34054F96#;
26104    u00054 : constant Version_32 := 16#5A199860#;
26105    u00055 : constant Version_32 := 16#0E7F912B#;
26106    u00056 : constant Version_32 := 16#5760634A#;
26107    u00057 : constant Version_32 := 16#5D851835#;
26108
26109    --  The following Export pragmas export the version numbers
26110    --  with symbolic names ending in B (for body) or S
26111    --  (for spec) so that they can be located in a link. The
26112    --  information provided here is sufficient to track down
26113    --  the exact versions of units used in a given build.
26114
26115    pragma Export (C, u00001, "helloB");
26116    pragma Export (C, u00002, "system__standard_libraryB");
26117    pragma Export (C, u00003, "system__standard_libraryS");
26118    pragma Export (C, u00004, "adaS");
26119    pragma Export (C, u00005, "ada__text_ioB");
26120    pragma Export (C, u00006, "ada__text_ioS");
26121    pragma Export (C, u00007, "ada__exceptionsB");
26122    pragma Export (C, u00008, "ada__exceptionsS");
26123    pragma Export (C, u00009, "gnatS");
26124    pragma Export (C, u00010, "gnat__heap_sort_aB");
26125    pragma Export (C, u00011, "gnat__heap_sort_aS");
26126    pragma Export (C, u00012, "systemS");
26127    pragma Export (C, u00013, "system__exception_tableB");
26128    pragma Export (C, u00014, "system__exception_tableS");
26129    pragma Export (C, u00015, "gnat__htableB");
26130    pragma Export (C, u00016, "gnat__htableS");
26131    pragma Export (C, u00017, "system__exceptionsS");
26132    pragma Export (C, u00018, "system__machine_state_operationsB");
26133    pragma Export (C, u00019, "system__machine_state_operationsS");
26134    pragma Export (C, u00020, "system__machine_codeS");
26135    pragma Export (C, u00021, "system__storage_elementsB");
26136    pragma Export (C, u00022, "system__storage_elementsS");
26137    pragma Export (C, u00023, "system__secondary_stackB");
26138    pragma Export (C, u00024, "system__secondary_stackS");
26139    pragma Export (C, u00025, "system__parametersB");
26140    pragma Export (C, u00026, "system__parametersS");
26141    pragma Export (C, u00027, "system__soft_linksB");
26142    pragma Export (C, u00028, "system__soft_linksS");
26143    pragma Export (C, u00029, "system__stack_checkingB");
26144    pragma Export (C, u00030, "system__stack_checkingS");
26145    pragma Export (C, u00031, "system__tracebackB");
26146    pragma Export (C, u00032, "system__tracebackS");
26147    pragma Export (C, u00033, "ada__streamsS");
26148    pragma Export (C, u00034, "ada__tagsB");
26149    pragma Export (C, u00035, "ada__tagsS");
26150    pragma Export (C, u00036, "system__string_opsB");
26151    pragma Export (C, u00037, "system__string_opsS");
26152    pragma Export (C, u00038, "interfacesS");
26153    pragma Export (C, u00039, "interfaces__c_streamsB");
26154    pragma Export (C, u00040, "interfaces__c_streamsS");
26155    pragma Export (C, u00041, "system__file_ioB");
26156    pragma Export (C, u00042, "system__file_ioS");
26157    pragma Export (C, u00043, "ada__finalizationB");
26158    pragma Export (C, u00044, "ada__finalizationS");
26159    pragma Export (C, u00045, "system__finalization_rootB");
26160    pragma Export (C, u00046, "system__finalization_rootS");
26161    pragma Export (C, u00047, "system__finalization_implementationB");
26162    pragma Export (C, u00048, "system__finalization_implementationS");
26163    pragma Export (C, u00049, "system__string_ops_concat_3B");
26164    pragma Export (C, u00050, "system__string_ops_concat_3S");
26165    pragma Export (C, u00051, "system__stream_attributesB");
26166    pragma Export (C, u00052, "system__stream_attributesS");
26167    pragma Export (C, u00053, "ada__io_exceptionsS");
26168    pragma Export (C, u00054, "system__unsigned_typesS");
26169    pragma Export (C, u00055, "system__file_control_blockS");
26170    pragma Export (C, u00056, "ada__finalization__list_controllerB");
26171    pragma Export (C, u00057, "ada__finalization__list_controllerS");
26172
26173    -- BEGIN ELABORATION ORDER
26174    -- ada (spec)
26175    -- gnat (spec)
26176    -- gnat.heap_sort_a (spec)
26177    -- gnat.heap_sort_a (body)
26178    -- gnat.htable (spec)
26179    -- gnat.htable (body)
26180    -- interfaces (spec)
26181    -- system (spec)
26182    -- system.machine_code (spec)
26183    -- system.parameters (spec)
26184    -- system.parameters (body)
26185    -- interfaces.c_streams (spec)
26186    -- interfaces.c_streams (body)
26187    -- system.standard_library (spec)
26188    -- ada.exceptions (spec)
26189    -- system.exception_table (spec)
26190    -- system.exception_table (body)
26191    -- ada.io_exceptions (spec)
26192    -- system.exceptions (spec)
26193    -- system.storage_elements (spec)
26194    -- system.storage_elements (body)
26195    -- system.machine_state_operations (spec)
26196    -- system.machine_state_operations (body)
26197    -- system.secondary_stack (spec)
26198    -- system.stack_checking (spec)
26199    -- system.soft_links (spec)
26200    -- system.soft_links (body)
26201    -- system.stack_checking (body)
26202    -- system.secondary_stack (body)
26203    -- system.standard_library (body)
26204    -- system.string_ops (spec)
26205    -- system.string_ops (body)
26206    -- ada.tags (spec)
26207    -- ada.tags (body)
26208    -- ada.streams (spec)
26209    -- system.finalization_root (spec)
26210    -- system.finalization_root (body)
26211    -- system.string_ops_concat_3 (spec)
26212    -- system.string_ops_concat_3 (body)
26213    -- system.traceback (spec)
26214    -- system.traceback (body)
26215    -- ada.exceptions (body)
26216    -- system.unsigned_types (spec)
26217    -- system.stream_attributes (spec)
26218    -- system.stream_attributes (body)
26219    -- system.finalization_implementation (spec)
26220    -- system.finalization_implementation (body)
26221    -- ada.finalization (spec)
26222    -- ada.finalization (body)
26223    -- ada.finalization.list_controller (spec)
26224    -- ada.finalization.list_controller (body)
26225    -- system.file_control_block (spec)
26226    -- system.file_io (spec)
26227    -- system.file_io (body)
26228    -- ada.text_io (spec)
26229    -- ada.text_io (body)
26230    -- hello (body)
26231    -- END ELABORATION ORDER
26232
26233 end ada_main;
26234
26235 --  The following source file name pragmas allow the generated file
26236 --  names to be unique for different main programs. They are needed
26237 --  since the package name will always be Ada_Main.
26238
26239 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
26240 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
26241
26242 --  Generated package body for Ada_Main starts here
26243
26244 package body ada_main is
26245
26246    --  The actual finalization is performed by calling the
26247    --  library routine in System.Standard_Library.Adafinal
26248
26249    procedure Do_Finalize;
26250    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
26251
26252    -------------
26253    -- adainit --
26254    -------------
26255
26256 @findex adainit
26257    procedure adainit is
26258
26259       --  These booleans are set to True once the associated unit has
26260       --  been elaborated. It is also used to avoid elaborating the
26261       --  same unit twice.
26262
26263       E040 : Boolean;
26264       pragma Import (Ada, E040, "interfaces__c_streams_E");
26265
26266       E008 : Boolean;
26267       pragma Import (Ada, E008, "ada__exceptions_E");
26268
26269       E014 : Boolean;
26270       pragma Import (Ada, E014, "system__exception_table_E");
26271
26272       E053 : Boolean;
26273       pragma Import (Ada, E053, "ada__io_exceptions_E");
26274
26275       E017 : Boolean;
26276       pragma Import (Ada, E017, "system__exceptions_E");
26277
26278       E024 : Boolean;
26279       pragma Import (Ada, E024, "system__secondary_stack_E");
26280
26281       E030 : Boolean;
26282       pragma Import (Ada, E030, "system__stack_checking_E");
26283
26284       E028 : Boolean;
26285       pragma Import (Ada, E028, "system__soft_links_E");
26286
26287       E035 : Boolean;
26288       pragma Import (Ada, E035, "ada__tags_E");
26289
26290       E033 : Boolean;
26291       pragma Import (Ada, E033, "ada__streams_E");
26292
26293       E046 : Boolean;
26294       pragma Import (Ada, E046, "system__finalization_root_E");
26295
26296       E048 : Boolean;
26297       pragma Import (Ada, E048, "system__finalization_implementation_E");
26298
26299       E044 : Boolean;
26300       pragma Import (Ada, E044, "ada__finalization_E");
26301
26302       E057 : Boolean;
26303       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
26304
26305       E055 : Boolean;
26306       pragma Import (Ada, E055, "system__file_control_block_E");
26307
26308       E042 : Boolean;
26309       pragma Import (Ada, E042, "system__file_io_E");
26310
26311       E006 : Boolean;
26312       pragma Import (Ada, E006, "ada__text_io_E");
26313
26314       --  Set_Globals is a library routine that stores away the
26315       --  value of the indicated set of global values in global
26316       --  variables within the library.
26317
26318       procedure Set_Globals
26319         (Main_Priority            : Integer;
26320          Time_Slice_Value         : Integer;
26321          WC_Encoding              : Character;
26322          Locking_Policy           : Character;
26323          Queuing_Policy           : Character;
26324          Task_Dispatching_Policy  : Character;
26325          Adafinal                 : System.Address;
26326          Unreserve_All_Interrupts : Integer;
26327          Exception_Tracebacks     : Integer);
26328 @findex __gnat_set_globals
26329       pragma Import (C, Set_Globals, "__gnat_set_globals");
26330
26331       --  SDP_Table_Build is a library routine used to build the
26332       --  exception tables. See unit Ada.Exceptions in files
26333       --  a-except.ads/adb for full details of how zero cost
26334       --  exception handling works. This procedure, the call to
26335       --  it, and the two following tables are all omitted if the
26336       --  build is in longjmp/setjmp exception mode.
26337
26338 @findex SDP_Table_Build
26339 @findex Zero Cost Exceptions
26340       procedure SDP_Table_Build
26341         (SDP_Addresses   : System.Address;
26342          SDP_Count       : Natural;
26343          Elab_Addresses  : System.Address;
26344          Elab_Addr_Count : Natural);
26345       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
26346
26347       --  Table of Unit_Exception_Table addresses. Used for zero
26348       --  cost exception handling to build the top level table.
26349
26350       ST : aliased constant array (1 .. 23) of System.Address := (
26351         Hello'UET_Address,
26352         Ada.Text_Io'UET_Address,
26353         Ada.Exceptions'UET_Address,
26354         Gnat.Heap_Sort_A'UET_Address,
26355         System.Exception_Table'UET_Address,
26356         System.Machine_State_Operations'UET_Address,
26357         System.Secondary_Stack'UET_Address,
26358         System.Parameters'UET_Address,
26359         System.Soft_Links'UET_Address,
26360         System.Stack_Checking'UET_Address,
26361         System.Traceback'UET_Address,
26362         Ada.Streams'UET_Address,
26363         Ada.Tags'UET_Address,
26364         System.String_Ops'UET_Address,
26365         Interfaces.C_Streams'UET_Address,
26366         System.File_Io'UET_Address,
26367         Ada.Finalization'UET_Address,
26368         System.Finalization_Root'UET_Address,
26369         System.Finalization_Implementation'UET_Address,
26370         System.String_Ops_Concat_3'UET_Address,
26371         System.Stream_Attributes'UET_Address,
26372         System.File_Control_Block'UET_Address,
26373         Ada.Finalization.List_Controller'UET_Address);
26374
26375       --  Table of addresses of elaboration routines. Used for
26376       --  zero cost exception handling to make sure these
26377       --  addresses are included in the top level procedure
26378       --  address table.
26379
26380       EA : aliased constant array (1 .. 23) of System.Address := (
26381         adainit'Code_Address,
26382         Do_Finalize'Code_Address,
26383         Ada.Exceptions'Elab_Spec'Address,
26384         System.Exceptions'Elab_Spec'Address,
26385         Interfaces.C_Streams'Elab_Spec'Address,
26386         System.Exception_Table'Elab_Body'Address,
26387         Ada.Io_Exceptions'Elab_Spec'Address,
26388         System.Stack_Checking'Elab_Spec'Address,
26389         System.Soft_Links'Elab_Body'Address,
26390         System.Secondary_Stack'Elab_Body'Address,
26391         Ada.Tags'Elab_Spec'Address,
26392         Ada.Tags'Elab_Body'Address,
26393         Ada.Streams'Elab_Spec'Address,
26394         System.Finalization_Root'Elab_Spec'Address,
26395         Ada.Exceptions'Elab_Body'Address,
26396         System.Finalization_Implementation'Elab_Spec'Address,
26397         System.Finalization_Implementation'Elab_Body'Address,
26398         Ada.Finalization'Elab_Spec'Address,
26399         Ada.Finalization.List_Controller'Elab_Spec'Address,
26400         System.File_Control_Block'Elab_Spec'Address,
26401         System.File_Io'Elab_Body'Address,
26402         Ada.Text_Io'Elab_Spec'Address,
26403         Ada.Text_Io'Elab_Body'Address);
26404
26405    --  Start of processing for adainit
26406
26407    begin
26408
26409       --  Call SDP_Table_Build to build the top level procedure
26410       --  table for zero cost exception handling (omitted in
26411       --  longjmp/setjmp mode).
26412
26413       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
26414
26415       --  Call Set_Globals to record various information for
26416       --  this partition.  The values are derived by the binder
26417       --  from information stored in the ali files by the compiler.
26418
26419 @findex __gnat_set_globals
26420       Set_Globals
26421         (Main_Priority            => -1,
26422          --  Priority of main program, -1 if no pragma Priority used
26423
26424          Time_Slice_Value         => -1,
26425          --  Time slice from Time_Slice pragma, -1 if none used
26426
26427          WC_Encoding              => 'b',
26428          --  Wide_Character encoding used, default is brackets
26429
26430          Locking_Policy           => ' ',
26431          --  Locking_Policy used, default of space means not
26432          --  specified, otherwise it is the first character of
26433          --  the policy name.
26434
26435          Queuing_Policy           => ' ',
26436          --  Queuing_Policy used, default of space means not
26437          --  specified, otherwise it is the first character of
26438          --  the policy name.
26439
26440          Task_Dispatching_Policy  => ' ',
26441          --  Task_Dispatching_Policy used, default of space means
26442          --  not specified, otherwise first character of the
26443          --  policy name.
26444
26445          Adafinal                 => System.Null_Address,
26446          --  Address of Adafinal routine, not used anymore
26447
26448          Unreserve_All_Interrupts => 0,
26449          --  Set true if pragma Unreserve_All_Interrupts was used
26450
26451          Exception_Tracebacks     => 0);
26452          --  Indicates if exception tracebacks are enabled
26453
26454       Elab_Final_Code := 1;
26455
26456       --  Now we have the elaboration calls for all units in the partition.
26457       --  The Elab_Spec and Elab_Body attributes generate references to the
26458       --  implicit elaboration procedures generated by the compiler for
26459       --  each unit that requires elaboration.
26460
26461       if not E040 then
26462          Interfaces.C_Streams'Elab_Spec;
26463       end if;
26464       E040 := True;
26465       if not E008 then
26466          Ada.Exceptions'Elab_Spec;
26467       end if;
26468       if not E014 then
26469          System.Exception_Table'Elab_Body;
26470          E014 := True;
26471       end if;
26472       if not E053 then
26473          Ada.Io_Exceptions'Elab_Spec;
26474          E053 := True;
26475       end if;
26476       if not E017 then
26477          System.Exceptions'Elab_Spec;
26478          E017 := True;
26479       end if;
26480       if not E030 then
26481          System.Stack_Checking'Elab_Spec;
26482       end if;
26483       if not E028 then
26484          System.Soft_Links'Elab_Body;
26485          E028 := True;
26486       end if;
26487       E030 := True;
26488       if not E024 then
26489          System.Secondary_Stack'Elab_Body;
26490          E024 := True;
26491       end if;
26492       if not E035 then
26493          Ada.Tags'Elab_Spec;
26494       end if;
26495       if not E035 then
26496          Ada.Tags'Elab_Body;
26497          E035 := True;
26498       end if;
26499       if not E033 then
26500          Ada.Streams'Elab_Spec;
26501          E033 := True;
26502       end if;
26503       if not E046 then
26504          System.Finalization_Root'Elab_Spec;
26505       end if;
26506       E046 := True;
26507       if not E008 then
26508          Ada.Exceptions'Elab_Body;
26509          E008 := True;
26510       end if;
26511       if not E048 then
26512          System.Finalization_Implementation'Elab_Spec;
26513       end if;
26514       if not E048 then
26515          System.Finalization_Implementation'Elab_Body;
26516          E048 := True;
26517       end if;
26518       if not E044 then
26519          Ada.Finalization'Elab_Spec;
26520       end if;
26521       E044 := True;
26522       if not E057 then
26523          Ada.Finalization.List_Controller'Elab_Spec;
26524       end if;
26525       E057 := True;
26526       if not E055 then
26527          System.File_Control_Block'Elab_Spec;
26528          E055 := True;
26529       end if;
26530       if not E042 then
26531          System.File_Io'Elab_Body;
26532          E042 := True;
26533       end if;
26534       if not E006 then
26535          Ada.Text_Io'Elab_Spec;
26536       end if;
26537       if not E006 then
26538          Ada.Text_Io'Elab_Body;
26539          E006 := True;
26540       end if;
26541
26542       Elab_Final_Code := 0;
26543    end adainit;
26544
26545    --------------
26546    -- adafinal --
26547    --------------
26548
26549 @findex adafinal
26550    procedure adafinal is
26551    begin
26552       Do_Finalize;
26553    end adafinal;
26554
26555    ----------
26556    -- main --
26557    ----------
26558
26559    --  main is actually a function, as in the ANSI C standard,
26560    --  defined to return the exit status. The three parameters
26561    --  are the argument count, argument values and environment
26562    --  pointer.
26563
26564 @findex Main Program
26565    function main
26566      (argc : Integer;
26567       argv : System.Address;
26568       envp : System.Address)
26569       return Integer
26570    is
26571       --  The initialize routine performs low level system
26572       --  initialization using a standard library routine which
26573       --  sets up signal handling and performs any other
26574       --  required setup. The routine can be found in file
26575       --  a-init.c.
26576
26577 @findex __gnat_initialize
26578       procedure initialize;
26579       pragma Import (C, initialize, "__gnat_initialize");
26580
26581       --  The finalize routine performs low level system
26582       --  finalization using a standard library routine. The
26583       --  routine is found in file a-final.c and in the standard
26584       --  distribution is a dummy routine that does nothing, so
26585       --  really this is a hook for special user finalization.
26586
26587 @findex __gnat_finalize
26588       procedure finalize;
26589       pragma Import (C, finalize, "__gnat_finalize");
26590
26591       --  We get to the main program of the partition by using
26592       --  pragma Import because if we try to with the unit and
26593       --  call it Ada style, then not only do we waste time
26594       --  recompiling it, but also, we don't really know the right
26595       --  switches (e.g.@: identifier character set) to be used
26596       --  to compile it.
26597
26598       procedure Ada_Main_Program;
26599       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
26600
26601    --  Start of processing for main
26602
26603    begin
26604       --  Save global variables
26605
26606       gnat_argc := argc;
26607       gnat_argv := argv;
26608       gnat_envp := envp;
26609
26610       --  Call low level system initialization
26611
26612       Initialize;
26613
26614       --  Call our generated Ada initialization routine
26615
26616       adainit;
26617
26618       --  This is the point at which we want the debugger to get
26619       --  control
26620
26621       Break_Start;
26622
26623       --  Now we call the main program of the partition
26624
26625       Ada_Main_Program;
26626
26627       --  Perform Ada finalization
26628
26629       adafinal;
26630
26631       --  Perform low level system finalization
26632
26633       Finalize;
26634
26635       --  Return the proper exit status
26636       return (gnat_exit_status);
26637    end;
26638
26639 --  This section is entirely comments, so it has no effect on the
26640 --  compilation of the Ada_Main package. It provides the list of
26641 --  object files and linker options, as well as some standard
26642 --  libraries needed for the link. The gnatlink utility parses
26643 --  this b~hello.adb file to read these comment lines to generate
26644 --  the appropriate command line arguments for the call to the
26645 --  system linker. The BEGIN/END lines are used for sentinels for
26646 --  this parsing operation.
26647
26648 --  The exact file names will of course depend on the environment,
26649 --  host/target and location of files on the host system.
26650
26651 @findex Object file list
26652 -- BEGIN Object file/option list
26653    --   ./hello.o
26654    --   -L./
26655    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
26656    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
26657 -- END Object file/option list
26658
26659 end ada_main;
26660 @end smallexample
26661
26662 @noindent
26663 The Ada code in the above example is exactly what is generated by the
26664 binder. We have added comments to more clearly indicate the function
26665 of each part of the generated @code{Ada_Main} package.
26666
26667 The code is standard Ada in all respects, and can be processed by any
26668 tools that handle Ada. In particular, it is possible to use the debugger
26669 in Ada mode to debug the generated @code{Ada_Main} package. For example,
26670 suppose that for reasons that you do not understand, your program is crashing
26671 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
26672 you can place a breakpoint on the call:
26673
26674 @smallexample @c ada
26675 Ada.Text_Io'Elab_Body;
26676 @end smallexample
26677
26678 @noindent
26679 and trace the elaboration routine for this package to find out where
26680 the problem might be (more usually of course you would be debugging
26681 elaboration code in your own application).
26682
26683 @node Elaboration Order Handling in GNAT
26684 @appendix Elaboration Order Handling in GNAT
26685 @cindex Order of elaboration
26686 @cindex Elaboration control
26687
26688 @menu
26689 * Elaboration Code::
26690 * Checking the Elaboration Order::
26691 * Controlling the Elaboration Order::
26692 * Controlling Elaboration in GNAT - Internal Calls::
26693 * Controlling Elaboration in GNAT - External Calls::
26694 * Default Behavior in GNAT - Ensuring Safety::
26695 * Treatment of Pragma Elaborate::
26696 * Elaboration Issues for Library Tasks::
26697 * Mixing Elaboration Models::
26698 * What to Do If the Default Elaboration Behavior Fails::
26699 * Elaboration for Access-to-Subprogram Values::
26700 * Summary of Procedures for Elaboration Control::
26701 * Other Elaboration Order Considerations::
26702 @end menu
26703
26704 @noindent
26705 This chapter describes the handling of elaboration code in Ada and
26706 in GNAT, and discusses how the order of elaboration of program units can
26707 be controlled in GNAT, either automatically or with explicit programming
26708 features.
26709
26710 @node Elaboration Code
26711 @section Elaboration Code
26712
26713 @noindent
26714 Ada provides rather general mechanisms for executing code at elaboration
26715 time, that is to say before the main program starts executing. Such code arises
26716 in three contexts:
26717
26718 @table @asis
26719 @item Initializers for variables.
26720 Variables declared at the library level, in package specs or bodies, can
26721 require initialization that is performed at elaboration time, as in:
26722 @smallexample @c ada
26723 @cartouche
26724 Sqrt_Half : Float := Sqrt (0.5);
26725 @end cartouche
26726 @end smallexample
26727
26728 @item Package initialization code
26729 Code in a @code{BEGIN-END} section at the outer level of a package body is
26730 executed as part of the package body elaboration code.
26731
26732 @item Library level task allocators
26733 Tasks that are declared using task allocators at the library level
26734 start executing immediately and hence can execute at elaboration time.
26735 @end table
26736
26737 @noindent
26738 Subprogram calls are possible in any of these contexts, which means that
26739 any arbitrary part of the program may be executed as part of the elaboration
26740 code. It is even possible to write a program which does all its work at
26741 elaboration time, with a null main program, although stylistically this
26742 would usually be considered an inappropriate way to structure
26743 a program.
26744
26745 An important concern arises in the context of elaboration code:
26746 we have to be sure that it is executed in an appropriate order. What we
26747 have is a series of elaboration code sections, potentially one section
26748 for each unit in the program. It is important that these execute
26749 in the correct order. Correctness here means that, taking the above
26750 example of the declaration of @code{Sqrt_Half},
26751 if some other piece of
26752 elaboration code references @code{Sqrt_Half},
26753 then it must run after the
26754 section of elaboration code that contains the declaration of
26755 @code{Sqrt_Half}.
26756
26757 There would never be any order of elaboration problem if we made a rule
26758 that whenever you @code{with} a unit, you must elaborate both the spec and body
26759 of that unit before elaborating the unit doing the @code{with}'ing:
26760
26761 @smallexample @c ada
26762 @group
26763 @cartouche
26764 with Unit_1;
26765 package Unit_2 is @dots{}
26766 @end cartouche
26767 @end group
26768 @end smallexample
26769
26770 @noindent
26771 would require that both the body and spec of @code{Unit_1} be elaborated
26772 before the spec of @code{Unit_2}. However, a rule like that would be far too
26773 restrictive. In particular, it would make it impossible to have routines
26774 in separate packages that were mutually recursive.
26775
26776 You might think that a clever enough compiler could look at the actual
26777 elaboration code and determine an appropriate correct order of elaboration,
26778 but in the general case, this is not possible. Consider the following
26779 example.
26780
26781 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
26782 that references
26783 the variable @code{Sqrt_1}, which is declared in the elaboration code
26784 of the body of @code{Unit_1}:
26785
26786 @smallexample @c ada
26787 @cartouche
26788 Sqrt_1 : Float := Sqrt (0.1);
26789 @end cartouche
26790 @end smallexample
26791
26792 @noindent
26793 The elaboration code of the body of @code{Unit_1} also contains:
26794
26795 @smallexample @c ada
26796 @group
26797 @cartouche
26798 if expression_1 = 1 then
26799    Q := Unit_2.Func_2;
26800 end if;
26801 @end cartouche
26802 @end group
26803 @end smallexample
26804
26805 @noindent
26806 @code{Unit_2} is exactly parallel,
26807 it has a procedure @code{Func_2} that references
26808 the variable @code{Sqrt_2}, which is declared in the elaboration code of
26809 the body @code{Unit_2}:
26810
26811 @smallexample @c ada
26812 @cartouche
26813 Sqrt_2 : Float := Sqrt (0.1);
26814 @end cartouche
26815 @end smallexample
26816
26817 @noindent
26818 The elaboration code of the body of @code{Unit_2} also contains:
26819
26820 @smallexample @c ada
26821 @group
26822 @cartouche
26823 if expression_2 = 2 then
26824    Q := Unit_1.Func_1;
26825 end if;
26826 @end cartouche
26827 @end group
26828 @end smallexample
26829
26830 @noindent
26831 Now the question is, which of the following orders of elaboration is
26832 acceptable:
26833
26834 @smallexample
26835 @group
26836 Spec of Unit_1
26837 Spec of Unit_2
26838 Body of Unit_1
26839 Body of Unit_2
26840 @end group
26841 @end smallexample
26842
26843 @noindent
26844 or
26845
26846 @smallexample
26847 @group
26848 Spec of Unit_2
26849 Spec of Unit_1
26850 Body of Unit_2
26851 Body of Unit_1
26852 @end group
26853 @end smallexample
26854
26855 @noindent
26856 If you carefully analyze the flow here, you will see that you cannot tell
26857 at compile time the answer to this question.
26858 If @code{expression_1} is not equal to 1,
26859 and @code{expression_2} is not equal to 2,
26860 then either order is acceptable, because neither of the function calls is
26861 executed. If both tests evaluate to true, then neither order is acceptable
26862 and in fact there is no correct order.
26863
26864 If one of the two expressions is true, and the other is false, then one
26865 of the above orders is correct, and the other is incorrect. For example,
26866 if @code{expression_1} /= 1 and @code{expression_2} = 2,
26867 then the call to @code{Func_1}
26868 will occur, but not the call to @code{Func_2.}
26869 This means that it is essential
26870 to elaborate the body of @code{Unit_1} before
26871 the body of @code{Unit_2}, so the first
26872 order of elaboration is correct and the second is wrong.
26873
26874 By making @code{expression_1} and @code{expression_2}
26875 depend on input data, or perhaps
26876 the time of day, we can make it impossible for the compiler or binder
26877 to figure out which of these expressions will be true, and hence it
26878 is impossible to guarantee a safe order of elaboration at run time.
26879
26880 @node Checking the Elaboration Order
26881 @section Checking the Elaboration Order
26882
26883 @noindent
26884 In some languages that involve the same kind of elaboration problems,
26885 e.g.@: Java and C++, the programmer is expected to worry about these
26886 ordering problems himself, and it is common to
26887 write a program in which an incorrect elaboration order  gives
26888 surprising results, because it references variables before they
26889 are initialized.
26890 Ada is designed to be a safe language, and a programmer-beware approach is
26891 clearly not sufficient. Consequently, the language provides three lines
26892 of defense:
26893
26894 @table @asis
26895 @item Standard rules
26896 Some standard rules restrict the possible choice of elaboration
26897 order. In particular, if you @code{with} a unit, then its spec is always
26898 elaborated before the unit doing the @code{with}. Similarly, a parent
26899 spec is always elaborated before the child spec, and finally
26900 a spec is always elaborated before its corresponding body.
26901
26902 @item Dynamic elaboration checks
26903 @cindex Elaboration checks
26904 @cindex Checks, elaboration
26905 Dynamic checks are made at run time, so that if some entity is accessed
26906 before it is elaborated (typically  by means of a subprogram call)
26907 then the exception (@code{Program_Error}) is raised.
26908
26909 @item Elaboration control
26910 Facilities are provided for the programmer to specify the desired order
26911 of elaboration.
26912 @end table
26913
26914 Let's look at these facilities in more detail. First, the rules for
26915 dynamic checking. One possible rule would be simply to say that the
26916 exception is raised if you access a variable which has not yet been
26917 elaborated. The trouble with this approach is that it could require
26918 expensive checks on every variable reference. Instead Ada has two
26919 rules which are a little more restrictive, but easier to check, and
26920 easier to state:
26921
26922 @table @asis
26923 @item Restrictions on calls
26924 A subprogram can only be called at elaboration time if its body
26925 has been elaborated. The rules for elaboration given above guarantee
26926 that the spec of the subprogram has been elaborated before the
26927 call, but not the body. If this rule is violated, then the
26928 exception @code{Program_Error} is raised.
26929
26930 @item Restrictions on instantiations
26931 A generic unit can only be instantiated if the body of the generic
26932 unit has been elaborated. Again, the rules for elaboration given above
26933 guarantee that the spec of the generic unit has been elaborated
26934 before the instantiation, but not the body. If this rule is
26935 violated, then the exception @code{Program_Error} is raised.
26936 @end table
26937
26938 @noindent
26939 The idea is that if the body has been elaborated, then any variables
26940 it references must have been elaborated; by checking for the body being
26941 elaborated we guarantee that none of its references causes any
26942 trouble. As we noted above, this is a little too restrictive, because a
26943 subprogram that has no non-local references in its body may in fact be safe
26944 to call. However, it really would be unsafe to rely on this, because
26945 it would mean that the caller was aware of details of the implementation
26946 in the body. This goes against the basic tenets of Ada.
26947
26948 A plausible implementation can be described as follows.
26949 A Boolean variable is associated with each subprogram
26950 and each generic unit. This variable is initialized to False, and is set to
26951 True at the point body is elaborated. Every call or instantiation checks the
26952 variable, and raises @code{Program_Error} if the variable is False.
26953
26954 Note that one might think that it would be good enough to have one Boolean
26955 variable for each package, but that would not deal with cases of trying
26956 to call a body in the same package as the call
26957 that has not been elaborated yet.
26958 Of course a compiler may be able to do enough analysis to optimize away
26959 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
26960 does such optimizations, but still the easiest conceptual model is to
26961 think of there being one variable per subprogram.
26962
26963 @node Controlling the Elaboration Order
26964 @section Controlling the Elaboration Order
26965
26966 @noindent
26967 In the previous section we discussed the rules in Ada which ensure
26968 that @code{Program_Error} is raised if an incorrect elaboration order is
26969 chosen. This prevents erroneous executions, but we need mechanisms to
26970 specify a correct execution and avoid the exception altogether.
26971 To achieve this, Ada provides a number of features for controlling
26972 the order of elaboration. We discuss these features in this section.
26973
26974 First, there are several ways of indicating to the compiler that a given
26975 unit has no elaboration problems:
26976
26977 @table @asis
26978 @item packages that do not require a body
26979 A library package that does not require a body does not permit
26980 a body (this rule was introduced in Ada 95).
26981 Thus if we have a such a package, as in:
26982
26983 @smallexample @c ada
26984 @group
26985 @cartouche
26986 package Definitions is
26987    generic
26988       type m is new integer;
26989    package Subp is
26990       type a is array (1 .. 10) of m;
26991       type b is array (1 .. 20) of m;
26992    end Subp;
26993 end Definitions;
26994 @end cartouche
26995 @end group
26996 @end smallexample
26997
26998 @noindent
26999 A package that @code{with}'s @code{Definitions} may safely instantiate
27000 @code{Definitions.Subp} because the compiler can determine that there
27001 definitely is no package body to worry about in this case
27002
27003 @item pragma Pure
27004 @cindex pragma Pure
27005 @findex Pure
27006 Places sufficient restrictions on a unit to guarantee that
27007 no call to any subprogram in the unit can result in an
27008 elaboration problem. This means that the compiler does not need
27009 to worry about the point of elaboration of such units, and in
27010 particular, does not need to check any calls to any subprograms
27011 in this unit.
27012
27013 @item pragma Preelaborate
27014 @findex Preelaborate
27015 @cindex pragma Preelaborate
27016 This pragma places slightly less stringent restrictions on a unit than
27017 does pragma Pure,
27018 but these restrictions are still sufficient to ensure that there
27019 are no elaboration problems with any calls to the unit.
27020
27021 @item pragma Elaborate_Body
27022 @findex Elaborate_Body
27023 @cindex pragma Elaborate_Body
27024 This pragma requires that the body of a unit be elaborated immediately
27025 after its spec. Suppose a unit @code{A} has such a pragma,
27026 and unit @code{B} does
27027 a @code{with} of unit @code{A}. Recall that the standard rules require
27028 the spec of unit @code{A}
27029 to be elaborated before the @code{with}'ing unit; given the pragma in
27030 @code{A}, we also know that the body of @code{A}
27031 will be elaborated before @code{B}, so
27032 that calls to @code{A} are safe and do not need a check.
27033 @end table
27034
27035 @noindent
27036 Note that,
27037 unlike pragma @code{Pure} and pragma @code{Preelaborate},
27038 the use of
27039 @code{Elaborate_Body} does not guarantee that the program is
27040 free of elaboration problems, because it may not be possible
27041 to satisfy the requested elaboration order.
27042 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
27043 If a programmer
27044 marks @code{Unit_1} as @code{Elaborate_Body},
27045 and not @code{Unit_2,} then the order of
27046 elaboration will be:
27047
27048 @smallexample
27049 @group
27050 Spec of Unit_2
27051 Spec of Unit_1
27052 Body of Unit_1
27053 Body of Unit_2
27054 @end group
27055 @end smallexample
27056
27057 @noindent
27058 Now that means that the call to @code{Func_1} in @code{Unit_2}
27059 need not be checked,
27060 it must be safe. But the call to @code{Func_2} in
27061 @code{Unit_1} may still fail if
27062 @code{Expression_1} is equal to 1,
27063 and the programmer must still take
27064 responsibility for this not being the case.
27065
27066 If all units carry a pragma @code{Elaborate_Body}, then all problems are
27067 eliminated, except for calls entirely within a body, which are
27068 in any case fully under programmer control. However, using the pragma
27069 everywhere is not always possible.
27070 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
27071 we marked both of them as having pragma @code{Elaborate_Body}, then
27072 clearly there would be no possible elaboration order.
27073
27074 The above pragmas allow a server to guarantee safe use by clients, and
27075 clearly this is the preferable approach. Consequently a good rule
27076 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
27077 and if this is not possible,
27078 mark them as @code{Elaborate_Body} if possible.
27079 As we have seen, there are situations where neither of these
27080 three pragmas can be used.
27081 So we also provide methods for clients to control the
27082 order of elaboration of the servers on which they depend:
27083
27084 @table @asis
27085 @item pragma Elaborate (unit)
27086 @findex Elaborate
27087 @cindex pragma Elaborate
27088 This pragma is placed in the context clause, after a @code{with} clause,
27089 and it requires that the body of the named unit be elaborated before
27090 the unit in which the pragma occurs. The idea is to use this pragma
27091 if the current unit calls at elaboration time, directly or indirectly,
27092 some subprogram in the named unit.
27093
27094 @item pragma Elaborate_All (unit)
27095 @findex Elaborate_All
27096 @cindex pragma Elaborate_All
27097 This is a stronger version of the Elaborate pragma. Consider the
27098 following example:
27099
27100 @smallexample
27101 Unit A @code{with}'s unit B and calls B.Func in elab code
27102 Unit B @code{with}'s unit C, and B.Func calls C.Func
27103 @end smallexample
27104
27105 @noindent
27106 Now if we put a pragma @code{Elaborate (B)}
27107 in unit @code{A}, this ensures that the
27108 body of @code{B} is elaborated before the call, but not the
27109 body of @code{C}, so
27110 the call to @code{C.Func} could still cause @code{Program_Error} to
27111 be raised.
27112
27113 The effect of a pragma @code{Elaborate_All} is stronger, it requires
27114 not only that the body of the named unit be elaborated before the
27115 unit doing the @code{with}, but also the bodies of all units that the
27116 named unit uses, following @code{with} links transitively. For example,
27117 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
27118 then it requires
27119 not only that the body of @code{B} be elaborated before @code{A},
27120 but also the
27121 body of @code{C}, because @code{B} @code{with}'s @code{C}.
27122 @end table
27123
27124 @noindent
27125 We are now in a position to give a usage rule in Ada for avoiding
27126 elaboration problems, at least if dynamic dispatching and access to
27127 subprogram values are not used. We will handle these cases separately
27128 later.
27129
27130 The rule is simple. If a unit has elaboration code that can directly or
27131 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
27132 a generic package in a @code{with}'ed unit,
27133 then if the @code{with}'ed unit does not have
27134 pragma @code{Pure} or @code{Preelaborate}, then the client should have
27135 a pragma @code{Elaborate_All}
27136 for the @code{with}'ed unit. By following this rule a client is
27137 assured that calls can be made without risk of an exception.
27138
27139 For generic subprogram instantiations, the rule can be relaxed to
27140 require only a pragma @code{Elaborate} since elaborating the body
27141 of a subprogram cannot cause any transitive elaboration (we are
27142 not calling the subprogram in this case, just elaborating its
27143 declaration).
27144
27145 If this rule is not followed, then a program may be in one of four
27146 states:
27147
27148 @table @asis
27149 @item No order exists
27150 No order of elaboration exists which follows the rules, taking into
27151 account any @code{Elaborate}, @code{Elaborate_All},
27152 or @code{Elaborate_Body} pragmas. In
27153 this case, an Ada compiler must diagnose the situation at bind
27154 time, and refuse to build an executable program.
27155
27156 @item One or more orders exist, all incorrect
27157 One or more acceptable elaboration orders exist, and all of them
27158 generate an elaboration order problem. In this case, the binder
27159 can build an executable program, but @code{Program_Error} will be raised
27160 when the program is run.
27161
27162 @item Several orders exist, some right, some incorrect
27163 One or more acceptable elaboration orders exists, and some of them
27164 work, and some do not. The programmer has not controlled
27165 the order of elaboration, so the binder may or may not pick one of
27166 the correct orders, and the program may or may not raise an
27167 exception when it is run. This is the worst case, because it means
27168 that the program may fail when moved to another compiler, or even
27169 another version of the same compiler.
27170
27171 @item One or more orders exists, all correct
27172 One ore more acceptable elaboration orders exist, and all of them
27173 work. In this case the program runs successfully. This state of
27174 affairs can be guaranteed by following the rule we gave above, but
27175 may be true even if the rule is not followed.
27176 @end table
27177
27178 @noindent
27179 Note that one additional advantage of following our rules on the use
27180 of @code{Elaborate} and @code{Elaborate_All}
27181 is that the program continues to stay in the ideal (all orders OK) state
27182 even if maintenance
27183 changes some bodies of some units. Conversely, if a program that does
27184 not follow this rule happens to be safe at some point, this state of affairs
27185 may deteriorate silently as a result of maintenance changes.
27186
27187 You may have noticed that the above discussion did not mention
27188 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
27189 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
27190 code in the body makes calls to some other unit, so it is still necessary
27191 to use @code{Elaborate_All} on such units.
27192
27193 @node Controlling Elaboration in GNAT - Internal Calls
27194 @section Controlling Elaboration in GNAT - Internal Calls
27195
27196 @noindent
27197 In the case of internal calls, i.e., calls within a single package, the
27198 programmer has full control over the order of elaboration, and it is up
27199 to the programmer to elaborate declarations in an appropriate order. For
27200 example writing:
27201
27202 @smallexample @c ada
27203 @group
27204 @cartouche
27205 function One return Float;
27206
27207 Q : Float := One;
27208
27209 function One return Float is
27210 begin
27211      return 1.0;
27212 end One;
27213 @end cartouche
27214 @end group
27215 @end smallexample
27216
27217 @noindent
27218 will obviously raise @code{Program_Error} at run time, because function
27219 One will be called before its body is elaborated. In this case GNAT will
27220 generate a warning that the call will raise @code{Program_Error}:
27221
27222 @smallexample
27223 @group
27224 @cartouche
27225  1. procedure y is
27226  2.    function One return Float;
27227  3.
27228  4.    Q : Float := One;
27229                     |
27230     >>> warning: cannot call "One" before body is elaborated
27231     >>> warning: Program_Error will be raised at run time
27232
27233  5.
27234  6.    function One return Float is
27235  7.    begin
27236  8.         return 1.0;
27237  9.    end One;
27238 10.
27239 11. begin
27240 12.    null;
27241 13. end;
27242 @end cartouche
27243 @end group
27244 @end smallexample
27245
27246 @noindent
27247 Note that in this particular case, it is likely that the call is safe, because
27248 the function @code{One} does not access any global variables.
27249 Nevertheless in Ada, we do not want the validity of the check to depend on
27250 the contents of the body (think about the separate compilation case), so this
27251 is still wrong, as we discussed in the previous sections.
27252
27253 The error is easily corrected by rearranging the declarations so that the
27254 body of @code{One} appears before the declaration containing the call
27255 (note that in Ada 95 and Ada 2005,
27256 declarations can appear in any order, so there is no restriction that
27257 would prevent this reordering, and if we write:
27258
27259 @smallexample @c ada
27260 @group
27261 @cartouche
27262 function One return Float;
27263
27264 function One return Float is
27265 begin
27266      return 1.0;
27267 end One;
27268
27269 Q : Float := One;
27270 @end cartouche
27271 @end group
27272 @end smallexample
27273
27274 @noindent
27275 then all is well, no warning is generated, and no
27276 @code{Program_Error} exception
27277 will be raised.
27278 Things are more complicated when a chain of subprograms is executed:
27279
27280 @smallexample @c ada
27281 @group
27282 @cartouche
27283 function A return Integer;
27284 function B return Integer;
27285 function C return Integer;
27286
27287 function B return Integer is begin return A; end;
27288 function C return Integer is begin return B; end;
27289
27290 X : Integer := C;
27291
27292 function A return Integer is begin return 1; end;
27293 @end cartouche
27294 @end group
27295 @end smallexample
27296
27297 @noindent
27298 Now the call to @code{C}
27299 at elaboration time in the declaration of @code{X} is correct, because
27300 the body of @code{C} is already elaborated,
27301 and the call to @code{B} within the body of
27302 @code{C} is correct, but the call
27303 to @code{A} within the body of @code{B} is incorrect, because the body
27304 of @code{A} has not been elaborated, so @code{Program_Error}
27305 will be raised on the call to @code{A}.
27306 In this case GNAT will generate a
27307 warning that @code{Program_Error} may be
27308 raised at the point of the call. Let's look at the warning:
27309
27310 @smallexample
27311 @group
27312 @cartouche
27313  1. procedure x is
27314  2.    function A return Integer;
27315  3.    function B return Integer;
27316  4.    function C return Integer;
27317  5.
27318  6.    function B return Integer is begin return A; end;
27319                                                     |
27320     >>> warning: call to "A" before body is elaborated may
27321                  raise Program_Error
27322     >>> warning: "B" called at line 7
27323     >>> warning: "C" called at line 9
27324
27325  7.    function C return Integer is begin return B; end;
27326  8.
27327  9.    X : Integer := C;
27328 10.
27329 11.    function A return Integer is begin return 1; end;
27330 12.
27331 13. begin
27332 14.    null;
27333 15. end;
27334 @end cartouche
27335 @end group
27336 @end smallexample
27337
27338 @noindent
27339 Note that the message here says ``may raise'', instead of the direct case,
27340 where the message says ``will be raised''. That's because whether
27341 @code{A} is
27342 actually called depends in general on run-time flow of control.
27343 For example, if the body of @code{B} said
27344
27345 @smallexample @c ada
27346 @group
27347 @cartouche
27348 function B return Integer is
27349 begin
27350    if some-condition-depending-on-input-data then
27351       return A;
27352    else
27353       return 1;
27354    end if;
27355 end B;
27356 @end cartouche
27357 @end group
27358 @end smallexample
27359
27360 @noindent
27361 then we could not know until run time whether the incorrect call to A would
27362 actually occur, so @code{Program_Error} might
27363 or might not be raised. It is possible for a compiler to
27364 do a better job of analyzing bodies, to
27365 determine whether or not @code{Program_Error}
27366 might be raised, but it certainly
27367 couldn't do a perfect job (that would require solving the halting problem
27368 and is provably impossible), and because this is a warning anyway, it does
27369 not seem worth the effort to do the analysis. Cases in which it
27370 would be relevant are rare.
27371
27372 In practice, warnings of either of the forms given
27373 above will usually correspond to
27374 real errors, and should be examined carefully and eliminated.
27375 In the rare case where a warning is bogus, it can be suppressed by any of
27376 the following methods:
27377
27378 @itemize @bullet
27379 @item
27380 Compile with the @option{-gnatws} switch set
27381
27382 @item
27383 Suppress @code{Elaboration_Check} for the called subprogram
27384
27385 @item
27386 Use pragma @code{Warnings_Off} to turn warnings off for the call
27387 @end itemize
27388
27389 @noindent
27390 For the internal elaboration check case,
27391 GNAT by default generates the
27392 necessary run-time checks to ensure
27393 that @code{Program_Error} is raised if any
27394 call fails an elaboration check. Of course this can only happen if a
27395 warning has been issued as described above. The use of pragma
27396 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
27397 some of these checks, meaning that it may be possible (but is not
27398 guaranteed) for a program to be able to call a subprogram whose body
27399 is not yet elaborated, without raising a @code{Program_Error} exception.
27400
27401 @node Controlling Elaboration in GNAT - External Calls
27402 @section Controlling Elaboration in GNAT - External Calls
27403
27404 @noindent
27405 The previous section discussed the case in which the execution of a
27406 particular thread of elaboration code occurred entirely within a
27407 single unit. This is the easy case to handle, because a programmer
27408 has direct and total control over the order of elaboration, and
27409 furthermore, checks need only be generated in cases which are rare
27410 and which the compiler can easily detect.
27411 The situation is more complex when separate compilation is taken into account.
27412 Consider the following:
27413
27414 @smallexample @c ada
27415 @cartouche
27416 @group
27417 package Math is
27418    function Sqrt (Arg : Float) return Float;
27419 end Math;
27420
27421 package body Math is
27422    function Sqrt (Arg : Float) return Float is
27423    begin
27424          @dots{}
27425    end Sqrt;
27426 end Math;
27427 @end group
27428 @group
27429 with Math;
27430 package Stuff is
27431    X : Float := Math.Sqrt (0.5);
27432 end Stuff;
27433
27434 with Stuff;
27435 procedure Main is
27436 begin
27437    @dots{}
27438 end Main;
27439 @end group
27440 @end cartouche
27441 @end smallexample
27442
27443 @noindent
27444 where @code{Main} is the main program. When this program is executed, the
27445 elaboration code must first be executed, and one of the jobs of the
27446 binder is to determine the order in which the units of a program are
27447 to be elaborated. In this case we have four units: the spec and body
27448 of @code{Math},
27449 the spec of @code{Stuff} and the body of @code{Main}).
27450 In what order should the four separate sections of elaboration code
27451 be executed?
27452
27453 There are some restrictions in the order of elaboration that the binder
27454 can choose. In particular, if unit U has a @code{with}
27455 for a package @code{X}, then you
27456 are assured that the spec of @code{X}
27457 is elaborated before U , but you are
27458 not assured that the body of @code{X}
27459 is elaborated before U.
27460 This means that in the above case, the binder is allowed to choose the
27461 order:
27462
27463 @smallexample
27464 spec of Math
27465 spec of Stuff
27466 body of Math
27467 body of Main
27468 @end smallexample
27469
27470 @noindent
27471 but that's not good, because now the call to @code{Math.Sqrt}
27472 that happens during
27473 the elaboration of the @code{Stuff}
27474 spec happens before the body of @code{Math.Sqrt} is
27475 elaborated, and hence causes @code{Program_Error} exception to be raised.
27476 At first glance, one might say that the binder is misbehaving, because
27477 obviously you want to elaborate the body of something you @code{with}
27478 first, but
27479 that is not a general rule that can be followed in all cases. Consider
27480
27481 @smallexample @c ada
27482 @group
27483 @cartouche
27484 package X is @dots{}
27485
27486 package Y is @dots{}
27487
27488 with X;
27489 package body Y is @dots{}
27490
27491 with Y;
27492 package body X is @dots{}
27493 @end cartouche
27494 @end group
27495 @end smallexample
27496
27497 @noindent
27498 This is a common arrangement, and, apart from the order of elaboration
27499 problems that might arise in connection with elaboration code, this works fine.
27500 A rule that says that you must first elaborate the body of anything you
27501 @code{with} cannot work in this case:
27502 the body of @code{X} @code{with}'s @code{Y},
27503 which means you would have to
27504 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
27505 which means
27506 you have to elaborate the body of @code{X} first, but @dots{} and we have a
27507 loop that cannot be broken.
27508
27509 It is true that the binder can in many cases guess an order of elaboration
27510 that is unlikely to cause a @code{Program_Error}
27511 exception to be raised, and it tries to do so (in the
27512 above example of @code{Math/Stuff/Spec}, the GNAT binder will
27513 by default
27514 elaborate the body of @code{Math} right after its spec, so all will be well).
27515
27516 However, a program that blindly relies on the binder to be helpful can
27517 get into trouble, as we discussed in the previous sections, so
27518 GNAT
27519 provides a number of facilities for assisting the programmer in
27520 developing programs that are robust with respect to elaboration order.
27521
27522 @node Default Behavior in GNAT - Ensuring Safety
27523 @section Default Behavior in GNAT - Ensuring Safety
27524
27525 @noindent
27526 The default behavior in GNAT ensures elaboration safety. In its
27527 default mode GNAT implements the
27528 rule we previously described as the right approach. Let's restate it:
27529
27530 @itemize
27531 @item
27532 @emph{If a unit has elaboration code that can directly or indirectly make a
27533 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
27534 package in a @code{with}'ed unit, then if the @code{with}'ed unit
27535 does not have pragma @code{Pure} or
27536 @code{Preelaborate}, then the client should have an
27537 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
27538
27539 @emph{In the case of instantiating a generic subprogram, it is always
27540 sufficient to have only an @code{Elaborate} pragma for the
27541 @code{with}'ed unit.}
27542 @end itemize
27543
27544 @noindent
27545 By following this rule a client is assured that calls and instantiations
27546 can be made without risk of an exception.
27547
27548 In this mode GNAT traces all calls that are potentially made from
27549 elaboration code, and puts in any missing implicit @code{Elaborate}
27550 and @code{Elaborate_All} pragmas.
27551 The advantage of this approach is that no elaboration problems
27552 are possible if the binder can find an elaboration order that is
27553 consistent with these implicit @code{Elaborate} and
27554 @code{Elaborate_All} pragmas. The
27555 disadvantage of this approach is that no such order may exist.
27556
27557 If the binder does not generate any diagnostics, then it means that it has
27558 found an elaboration order that is guaranteed to be safe. However, the binder
27559 may still be relying on implicitly generated @code{Elaborate} and
27560 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
27561 guaranteed.
27562
27563 If it is important to guarantee portability, then the compilations should
27564 use the
27565 @option{-gnatwl}
27566 (warn on elaboration problems) switch. This will cause warning messages
27567 to be generated indicating the missing @code{Elaborate} and
27568 @code{Elaborate_All} pragmas.
27569 Consider the following source program:
27570
27571 @smallexample @c ada
27572 @group
27573 @cartouche
27574 with k;
27575 package j is
27576   m : integer := k.r;
27577 end;
27578 @end cartouche
27579 @end group
27580 @end smallexample
27581
27582 @noindent
27583 where it is clear that there
27584 should be a pragma @code{Elaborate_All}
27585 for unit @code{k}. An implicit pragma will be generated, and it is
27586 likely that the binder will be able to honor it. However, if you want
27587 to port this program to some other Ada compiler than GNAT.
27588 it is safer to include the pragma explicitly in the source. If this
27589 unit is compiled with the
27590 @option{-gnatwl}
27591 switch, then the compiler outputs a warning:
27592
27593 @smallexample
27594 @group
27595 @cartouche
27596 1. with k;
27597 2. package j is
27598 3.   m : integer := k.r;
27599                      |
27600    >>> warning: call to "r" may raise Program_Error
27601    >>> warning: missing pragma Elaborate_All for "k"
27602
27603 4. end;
27604 @end cartouche
27605 @end group
27606 @end smallexample
27607
27608 @noindent
27609 and these warnings can be used as a guide for supplying manually
27610 the missing pragmas. It is usually a bad idea to use this warning
27611 option during development. That's because it will warn you when
27612 you need to put in a pragma, but cannot warn you when it is time
27613 to take it out. So the use of pragma @code{Elaborate_All} may lead to
27614 unnecessary dependencies and even false circularities.
27615
27616 This default mode is more restrictive than the Ada Reference
27617 Manual, and it is possible to construct programs which will compile
27618 using the dynamic model described there, but will run into a
27619 circularity using the safer static model we have described.
27620
27621 Of course any Ada compiler must be able to operate in a mode
27622 consistent with the requirements of the Ada Reference Manual,
27623 and in particular must have the capability of implementing the
27624 standard dynamic model of elaboration with run-time checks.
27625
27626 In GNAT, this standard mode can be achieved either by the use of
27627 the @option{-gnatE} switch on the compiler (@command{gcc} or
27628 @command{gnatmake}) command, or by the use of the configuration pragma:
27629
27630 @smallexample @c ada
27631 pragma Elaboration_Checks (RM);
27632 @end smallexample
27633
27634 @noindent
27635 Either approach will cause the unit affected to be compiled using the
27636 standard dynamic run-time elaboration checks described in the Ada
27637 Reference Manual. The static model is generally preferable, since it
27638 is clearly safer to rely on compile and link time checks rather than
27639 run-time checks. However, in the case of legacy code, it may be
27640 difficult to meet the requirements of the static model. This
27641 issue is further discussed in
27642 @ref{What to Do If the Default Elaboration Behavior Fails}.
27643
27644 Note that the static model provides a strict subset of the allowed
27645 behavior and programs of the Ada Reference Manual, so if you do
27646 adhere to the static model and no circularities exist,
27647 then you are assured that your program will
27648 work using the dynamic model, providing that you remove any
27649 pragma Elaborate statements from the source.
27650
27651 @node Treatment of Pragma Elaborate
27652 @section Treatment of Pragma Elaborate
27653 @cindex Pragma Elaborate
27654
27655 @noindent
27656 The use of @code{pragma Elaborate}
27657 should generally be avoided in Ada 95 and Ada 2005 programs,
27658 since there is no guarantee that transitive calls
27659 will be properly handled. Indeed at one point, this pragma was placed
27660 in Annex J (Obsolescent Features), on the grounds that it is never useful.
27661
27662 Now that's a bit restrictive. In practice, the case in which
27663 @code{pragma Elaborate} is useful is when the caller knows that there
27664 are no transitive calls, or that the called unit contains all necessary
27665 transitive @code{pragma Elaborate} statements, and legacy code often
27666 contains such uses.
27667
27668 Strictly speaking the static mode in GNAT should ignore such pragmas,
27669 since there is no assurance at compile time that the necessary safety
27670 conditions are met. In practice, this would cause GNAT to be incompatible
27671 with correctly written Ada 83 code that had all necessary
27672 @code{pragma Elaborate} statements in place. Consequently, we made the
27673 decision that GNAT in its default mode will believe that if it encounters
27674 a @code{pragma Elaborate} then the programmer knows what they are doing,
27675 and it will trust that no elaboration errors can occur.
27676
27677 The result of this decision is two-fold. First to be safe using the
27678 static mode, you should remove all @code{pragma Elaborate} statements.
27679 Second, when fixing circularities in existing code, you can selectively
27680 use @code{pragma Elaborate} statements to convince the static mode of
27681 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
27682 statement.
27683
27684 When using the static mode with @option{-gnatwl}, any use of
27685 @code{pragma Elaborate} will generate a warning about possible
27686 problems.
27687
27688 @node Elaboration Issues for Library Tasks
27689 @section Elaboration Issues for Library Tasks
27690 @cindex Library tasks, elaboration issues
27691 @cindex Elaboration of library tasks
27692
27693 @noindent
27694 In this section we examine special elaboration issues that arise for
27695 programs that declare library level tasks.
27696
27697 Generally the model of execution of an Ada program is that all units are
27698 elaborated, and then execution of the program starts. However, the
27699 declaration of library tasks definitely does not fit this model. The
27700 reason for this is that library tasks start as soon as they are declared
27701 (more precisely, as soon as the statement part of the enclosing package
27702 body is reached), that is to say before elaboration
27703 of the program is complete. This means that if such a task calls a
27704 subprogram, or an entry in another task, the callee may or may not be
27705 elaborated yet, and in the standard
27706 Reference Manual model of dynamic elaboration checks, you can even
27707 get timing dependent Program_Error exceptions, since there can be
27708 a race between the elaboration code and the task code.
27709
27710 The static model of elaboration in GNAT seeks to avoid all such
27711 dynamic behavior, by being conservative, and the conservative
27712 approach in this particular case is to assume that all the code
27713 in a task body is potentially executed at elaboration time if
27714 a task is declared at the library level.
27715
27716 This can definitely result in unexpected circularities. Consider
27717 the following example
27718
27719 @smallexample @c ada
27720 package Decls is
27721   task Lib_Task is
27722      entry Start;
27723   end Lib_Task;
27724
27725   type My_Int is new Integer;
27726
27727   function Ident (M : My_Int) return My_Int;
27728 end Decls;
27729
27730 with Utils;
27731 package body Decls is
27732   task body Lib_Task is
27733   begin
27734      accept Start;
27735      Utils.Put_Val (2);
27736   end Lib_Task;
27737
27738   function Ident (M : My_Int) return My_Int is
27739   begin
27740      return M;
27741   end Ident;
27742 end Decls;
27743
27744 with Decls;
27745 package Utils is
27746   procedure Put_Val (Arg : Decls.My_Int);
27747 end Utils;
27748
27749 with Text_IO;
27750 package body Utils is
27751   procedure Put_Val (Arg : Decls.My_Int) is
27752   begin
27753      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
27754   end Put_Val;
27755 end Utils;
27756
27757 with Decls;
27758 procedure Main is
27759 begin
27760    Decls.Lib_Task.Start;
27761 end;
27762 @end smallexample
27763
27764 @noindent
27765 If the above example is compiled in the default static elaboration
27766 mode, then a circularity occurs. The circularity comes from the call
27767 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
27768 this call occurs in elaboration code, we need an implicit pragma
27769 @code{Elaborate_All} for @code{Utils}. This means that not only must
27770 the spec and body of @code{Utils} be elaborated before the body
27771 of @code{Decls}, but also the spec and body of any unit that is
27772 @code{with'ed} by the body of @code{Utils} must also be elaborated before
27773 the body of @code{Decls}. This is the transitive implication of
27774 pragma @code{Elaborate_All} and it makes sense, because in general
27775 the body of @code{Put_Val} might have a call to something in a
27776 @code{with'ed} unit.
27777
27778 In this case, the body of Utils (actually its spec) @code{with's}
27779 @code{Decls}. Unfortunately this means that the body of @code{Decls}
27780 must be elaborated before itself, in case there is a call from the
27781 body of @code{Utils}.
27782
27783 Here is the exact chain of events we are worrying about:
27784
27785 @enumerate
27786 @item
27787 In the body of @code{Decls} a call is made from within the body of a library
27788 task to a subprogram in the package @code{Utils}. Since this call may
27789 occur at elaboration time (given that the task is activated at elaboration
27790 time), we have to assume the worst, i.e., that the
27791 call does happen at elaboration time.
27792
27793 @item
27794 This means that the body and spec of @code{Util} must be elaborated before
27795 the body of @code{Decls} so that this call does not cause an access before
27796 elaboration.
27797
27798 @item
27799 Within the body of @code{Util}, specifically within the body of
27800 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
27801 by this package.
27802
27803 @item
27804 One such @code{with}'ed package is package @code{Decls}, so there
27805 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
27806 In fact there is such a call in this example, but we would have to
27807 assume that there was such a call even if it were not there, since
27808 we are not supposed to write the body of @code{Decls} knowing what
27809 is in the body of @code{Utils}; certainly in the case of the
27810 static elaboration model, the compiler does not know what is in
27811 other bodies and must assume the worst.
27812
27813 @item
27814 This means that the spec and body of @code{Decls} must also be
27815 elaborated before we elaborate the unit containing the call, but
27816 that unit is @code{Decls}! This means that the body of @code{Decls}
27817 must be elaborated before itself, and that's a circularity.
27818 @end enumerate
27819
27820 @noindent
27821 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
27822 the body of @code{Decls} you will get a true Ada Reference Manual
27823 circularity that makes the program illegal.
27824
27825 In practice, we have found that problems with the static model of
27826 elaboration in existing code often arise from library tasks, so
27827 we must address this particular situation.
27828
27829 Note that if we compile and run the program above, using the dynamic model of
27830 elaboration (that is to say use the @option{-gnatE} switch),
27831 then it compiles, binds,
27832 links, and runs, printing the expected result of 2. Therefore in some sense
27833 the circularity here is only apparent, and we need to capture
27834 the properties of this program that  distinguish it from other library-level
27835 tasks that have real elaboration problems.
27836
27837 We have four possible answers to this question:
27838
27839 @itemize @bullet
27840
27841 @item
27842 Use the dynamic model of elaboration.
27843
27844 If we use the @option{-gnatE} switch, then as noted above, the program works.
27845 Why is this? If we examine the task body, it is apparent that the task cannot
27846 proceed past the
27847 @code{accept} statement until after elaboration has been completed, because
27848 the corresponding entry call comes from the main program, not earlier.
27849 This is why the dynamic model works here. But that's really giving
27850 up on a precise analysis, and we prefer to take this approach only if we cannot
27851 solve the
27852 problem in any other manner. So let us examine two ways to reorganize
27853 the program to avoid the potential elaboration problem.
27854
27855 @item
27856 Split library tasks into separate packages.
27857
27858 Write separate packages, so that library tasks are isolated from
27859 other declarations as much as possible. Let us look at a variation on
27860 the above program.
27861
27862 @smallexample @c ada
27863 package Decls1 is
27864   task Lib_Task is
27865      entry Start;
27866   end Lib_Task;
27867 end Decls1;
27868
27869 with Utils;
27870 package body Decls1 is
27871   task body Lib_Task is
27872   begin
27873      accept Start;
27874      Utils.Put_Val (2);
27875   end Lib_Task;
27876 end Decls1;
27877
27878 package Decls2 is
27879   type My_Int is new Integer;
27880   function Ident (M : My_Int) return My_Int;
27881 end Decls2;
27882
27883 with Utils;
27884 package body Decls2 is
27885   function Ident (M : My_Int) return My_Int is
27886   begin
27887      return M;
27888   end Ident;
27889 end Decls2;
27890
27891 with Decls2;
27892 package Utils is
27893   procedure Put_Val (Arg : Decls2.My_Int);
27894 end Utils;
27895
27896 with Text_IO;
27897 package body Utils is
27898   procedure Put_Val (Arg : Decls2.My_Int) is
27899   begin
27900      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
27901   end Put_Val;
27902 end Utils;
27903
27904 with Decls1;
27905 procedure Main is
27906 begin
27907    Decls1.Lib_Task.Start;
27908 end;
27909 @end smallexample
27910
27911 @noindent
27912 All we have done is to split @code{Decls} into two packages, one
27913 containing the library task, and one containing everything else. Now
27914 there is no cycle, and the program compiles, binds, links and executes
27915 using the default static model of elaboration.
27916
27917 @item
27918 Declare separate task types.
27919
27920 A significant part of the problem arises because of the use of the
27921 single task declaration form. This means that the elaboration of
27922 the task type, and the elaboration of the task itself (i.e.@: the
27923 creation of the task) happen at the same time. A good rule
27924 of style in Ada is to always create explicit task types. By
27925 following the additional step of placing task objects in separate
27926 packages from the task type declaration, many elaboration problems
27927 are avoided. Here is another modified example of the example program:
27928
27929 @smallexample @c ada
27930 package Decls is
27931   task type Lib_Task_Type is
27932      entry Start;
27933   end Lib_Task_Type;
27934
27935   type My_Int is new Integer;
27936
27937   function Ident (M : My_Int) return My_Int;
27938 end Decls;
27939
27940 with Utils;
27941 package body Decls is
27942   task body Lib_Task_Type is
27943   begin
27944      accept Start;
27945      Utils.Put_Val (2);
27946   end Lib_Task_Type;
27947
27948   function Ident (M : My_Int) return My_Int is
27949   begin
27950      return M;
27951   end Ident;
27952 end Decls;
27953
27954 with Decls;
27955 package Utils is
27956   procedure Put_Val (Arg : Decls.My_Int);
27957 end Utils;
27958
27959 with Text_IO;
27960 package body Utils is
27961   procedure Put_Val (Arg : Decls.My_Int) is
27962   begin
27963      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
27964   end Put_Val;
27965 end Utils;
27966
27967 with Decls;
27968 package Declst is
27969    Lib_Task : Decls.Lib_Task_Type;
27970 end Declst;
27971
27972 with Declst;
27973 procedure Main is
27974 begin
27975    Declst.Lib_Task.Start;
27976 end;
27977 @end smallexample
27978
27979 @noindent
27980 What we have done here is to replace the @code{task} declaration in
27981 package @code{Decls} with a @code{task type} declaration. Then we
27982 introduce a separate package @code{Declst} to contain the actual
27983 task object. This separates the elaboration issues for
27984 the @code{task type}
27985 declaration, which causes no trouble, from the elaboration issues
27986 of the task object, which is also unproblematic, since it is now independent
27987 of the elaboration of  @code{Utils}.
27988 This separation of concerns also corresponds to
27989 a generally sound engineering principle of separating declarations
27990 from instances. This version of the program also compiles, binds, links,
27991 and executes, generating the expected output.
27992
27993 @item
27994 Use No_Entry_Calls_In_Elaboration_Code restriction.
27995 @cindex No_Entry_Calls_In_Elaboration_Code
27996
27997 The previous two approaches described how a program can be restructured
27998 to avoid the special problems caused by library task bodies. in practice,
27999 however, such restructuring may be difficult to apply to existing legacy code,
28000 so we must consider solutions that do not require massive rewriting.
28001
28002 Let us consider more carefully why our original sample program works
28003 under the dynamic model of elaboration. The reason is that the code
28004 in the task body blocks immediately on the @code{accept}
28005 statement. Now of course there is nothing to prohibit elaboration
28006 code from making entry calls (for example from another library level task),
28007 so we cannot tell in isolation that
28008 the task will not execute the accept statement  during elaboration.
28009
28010 However, in practice it is very unusual to see elaboration code
28011 make any entry calls, and the pattern of tasks starting
28012 at elaboration time and then immediately blocking on @code{accept} or
28013 @code{select} statements is very common. What this means is that
28014 the compiler is being too pessimistic when it analyzes the
28015 whole package body as though it might be executed at elaboration
28016 time.
28017
28018 If we know that the elaboration code contains no entry calls, (a very safe
28019 assumption most of the time, that could almost be made the default
28020 behavior), then we can compile all units of the program under control
28021 of the following configuration pragma:
28022
28023 @smallexample
28024 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
28025 @end smallexample
28026
28027 @noindent
28028 This pragma can be placed in the @file{gnat.adc} file in the usual
28029 manner. If we take our original unmodified program and compile it
28030 in the presence of a @file{gnat.adc} containing the above pragma,
28031 then once again, we can compile, bind, link, and execute, obtaining
28032 the expected result. In the presence of this pragma, the compiler does
28033 not trace calls in a task body, that appear after the first @code{accept}
28034 or @code{select} statement, and therefore does not report a potential
28035 circularity in the original program.
28036
28037 The compiler will check to the extent it can that the above
28038 restriction is not violated, but it is not always possible to do a
28039 complete check at compile time, so it is important to use this
28040 pragma only if the stated restriction is in fact met, that is to say
28041 no task receives an entry call before elaboration of all units is completed.
28042
28043 @end itemize
28044
28045 @node Mixing Elaboration Models
28046 @section Mixing Elaboration Models
28047 @noindent
28048 So far, we have assumed that the entire program is either compiled
28049 using the dynamic model or static model, ensuring consistency. It
28050 is possible to mix the two models, but rules have to be followed
28051 if this mixing is done to ensure that elaboration checks are not
28052 omitted.
28053
28054 The basic rule is that @emph{a unit compiled with the static model cannot
28055 be @code{with'ed} by a unit compiled with the dynamic model}. The
28056 reason for this is that in the static model, a unit assumes that
28057 its clients guarantee to use (the equivalent of) pragma
28058 @code{Elaborate_All} so that no elaboration checks are required
28059 in inner subprograms, and this assumption is violated if the
28060 client is compiled with dynamic checks.
28061
28062 The precise rule is as follows. A unit that is compiled with dynamic
28063 checks can only @code{with} a unit that meets at least one of the
28064 following criteria:
28065
28066 @itemize @bullet
28067
28068 @item
28069 The @code{with'ed} unit is itself compiled with dynamic elaboration
28070 checks (that is with the @option{-gnatE} switch.
28071
28072 @item
28073 The @code{with'ed} unit is an internal GNAT implementation unit from
28074 the System, Interfaces, Ada, or GNAT hierarchies.
28075
28076 @item
28077 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
28078
28079 @item
28080 The @code{with'ing} unit (that is the client) has an explicit pragma
28081 @code{Elaborate_All} for the @code{with'ed} unit.
28082
28083 @end itemize
28084
28085 @noindent
28086 If this rule is violated, that is if a unit with dynamic elaboration
28087 checks @code{with's} a unit that does not meet one of the above four
28088 criteria, then the binder (@code{gnatbind}) will issue a warning
28089 similar to that in the following example:
28090
28091 @smallexample
28092 warning: "x.ads" has dynamic elaboration checks and with's
28093 warning:   "y.ads" which has static elaboration checks
28094 @end smallexample
28095
28096 @noindent
28097 These warnings indicate that the rule has been violated, and that as a result
28098 elaboration checks may be missed in the resulting executable file.
28099 This warning may be suppressed using the @option{-ws} binder switch
28100 in the usual manner.
28101
28102 One useful application of this mixing rule is in the case of a subsystem
28103 which does not itself @code{with} units from the remainder of the
28104 application. In this case, the entire subsystem can be compiled with
28105 dynamic checks to resolve a circularity in the subsystem, while
28106 allowing the main application that uses this subsystem to be compiled
28107 using the more reliable default static model.
28108
28109 @node What to Do If the Default Elaboration Behavior Fails
28110 @section What to Do If the Default Elaboration Behavior Fails
28111
28112 @noindent
28113 If the binder cannot find an acceptable order, it outputs detailed
28114 diagnostics. For example:
28115 @smallexample
28116 @group
28117 @iftex
28118 @leftskip=0cm
28119 @end iftex
28120 error: elaboration circularity detected
28121 info:   "proc (body)" must be elaborated before "pack (body)"
28122 info:     reason: Elaborate_All probably needed in unit "pack (body)"
28123 info:     recompile "pack (body)" with -gnatwl
28124 info:                             for full details
28125 info:       "proc (body)"
28126 info:         is needed by its spec:
28127 info:       "proc (spec)"
28128 info:         which is withed by:
28129 info:       "pack (body)"
28130 info:  "pack (body)" must be elaborated before "proc (body)"
28131 info:     reason: pragma Elaborate in unit "proc (body)"
28132 @end group
28133
28134 @end smallexample
28135
28136 @noindent
28137 In this case we have a cycle that the binder cannot break. On the one
28138 hand, there is an explicit pragma Elaborate in @code{proc} for
28139 @code{pack}. This means that the body of @code{pack} must be elaborated
28140 before the body of @code{proc}. On the other hand, there is elaboration
28141 code in @code{pack} that calls a subprogram in @code{proc}. This means
28142 that for maximum safety, there should really be a pragma
28143 Elaborate_All in @code{pack} for @code{proc} which would require that
28144 the body of @code{proc} be elaborated before the body of
28145 @code{pack}. Clearly both requirements cannot be satisfied.
28146 Faced with a circularity of this kind, you have three different options.
28147
28148 @table @asis
28149 @item Fix the program
28150 The most desirable option from the point of view of long-term maintenance
28151 is to rearrange the program so that the elaboration problems are avoided.
28152 One useful technique is to place the elaboration code into separate
28153 child packages. Another is to move some of the initialization code to
28154 explicitly called subprograms, where the program controls the order
28155 of initialization explicitly. Although this is the most desirable option,
28156 it may be impractical and involve too much modification, especially in
28157 the case of complex legacy code.
28158
28159 @item Perform dynamic checks
28160 If the compilations are done using the
28161 @option{-gnatE}
28162 (dynamic elaboration check) switch, then GNAT behaves in a quite different
28163 manner. Dynamic checks are generated for all calls that could possibly result
28164 in raising an exception. With this switch, the compiler does not generate
28165 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
28166 exactly as specified in the @cite{Ada Reference Manual}.
28167 The binder will generate
28168 an executable program that may or may not raise @code{Program_Error}, and then
28169 it is the programmer's job to ensure that it does not raise an exception. Note
28170 that it is important to compile all units with the switch, it cannot be used
28171 selectively.
28172
28173 @item Suppress checks
28174 The drawback of dynamic checks is that they generate a
28175 significant overhead at run time, both in space and time. If you
28176 are absolutely sure that your program cannot raise any elaboration
28177 exceptions, and you still want to use the dynamic elaboration model,
28178 then you can use the configuration pragma
28179 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
28180 example this pragma could be placed in the @file{gnat.adc} file.
28181
28182 @item Suppress checks selectively
28183 When you know that certain calls or instantiations in elaboration code cannot
28184 possibly lead to an elaboration error, and the binder nevertheless complains
28185 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
28186 elaboration circularities, it is possible to remove those warnings locally and
28187 obtain a program that will bind. Clearly this can be unsafe, and it is the
28188 responsibility of the programmer to make sure that the resulting program has no
28189 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
28190 used with different granularity to suppress warnings and break elaboration
28191 circularities:
28192
28193 @itemize @bullet
28194 @item
28195 Place the pragma that names the called subprogram in the declarative part
28196 that contains the call.
28197
28198 @item
28199 Place the pragma in the declarative part, without naming an entity. This
28200 disables warnings on all calls in the corresponding  declarative region.
28201
28202 @item
28203 Place the pragma in the package spec that declares the called subprogram,
28204 and name the subprogram. This disables warnings on all elaboration calls to
28205 that subprogram.
28206
28207 @item
28208 Place the pragma in the package spec that declares the called subprogram,
28209 without naming any entity. This disables warnings on all elaboration calls to
28210 all subprograms declared in this spec.
28211
28212 @item Use Pragma Elaborate
28213 As previously described in section @xref{Treatment of Pragma Elaborate},
28214 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
28215 that no elaboration checks are required on calls to the designated unit.
28216 There may be cases in which the caller knows that no transitive calls
28217 can occur, so that a @code{pragma Elaborate} will be sufficient in a
28218 case where @code{pragma Elaborate_All} would cause a circularity.
28219 @end itemize
28220
28221 @noindent
28222 These five cases are listed in order of decreasing safety, and therefore
28223 require increasing programmer care in their application. Consider the
28224 following program:
28225
28226 @smallexample @c adanocomment
28227 package Pack1 is
28228   function F1 return Integer;
28229   X1 : Integer;
28230 end Pack1;
28231
28232 package Pack2 is
28233   function F2 return Integer;
28234   function Pure (x : integer) return integer;
28235   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
28236   --  pragma Suppress (Elaboration_Check);              -- (4)
28237 end Pack2;
28238
28239 with Pack2;
28240 package body Pack1 is
28241   function F1 return Integer is
28242   begin
28243     return 100;
28244   end F1;
28245   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
28246 begin
28247   declare
28248     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
28249     --  pragma Suppress(Elaboration_Check);             -- (2)
28250   begin
28251     X1 := Pack2.F2 + 1;                --  Elab. call (2)
28252   end;
28253 end Pack1;
28254
28255 with Pack1;
28256 package body Pack2 is
28257   function F2 return Integer is
28258   begin
28259      return Pack1.F1;
28260   end F2;
28261   function Pure (x : integer) return integer is
28262   begin
28263      return x ** 3 - 3 * x;
28264   end;
28265 end Pack2;
28266
28267 with Pack1, Ada.Text_IO;
28268 procedure Proc3 is
28269 begin
28270   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
28271 end Proc3;
28272 @end smallexample
28273 In the absence of any pragmas, an attempt to bind this program produces
28274 the following diagnostics:
28275 @smallexample
28276 @group
28277 @iftex
28278 @leftskip=.5cm
28279 @end iftex
28280 error: elaboration circularity detected
28281 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
28282 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
28283 info:       recompile "pack1 (body)" with -gnatwl for full details
28284 info:          "pack1 (body)"
28285 info:             must be elaborated along with its spec:
28286 info:          "pack1 (spec)"
28287 info:             which is withed by:
28288 info:          "pack2 (body)"
28289 info:             which must be elaborated along with its spec:
28290 info:          "pack2 (spec)"
28291 info:             which is withed by:
28292 info:          "pack1 (body)"
28293 @end group
28294 @end smallexample
28295 The sources of the circularity are the two calls to @code{Pack2.Pure} and
28296 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
28297 F2 is safe, even though F2 calls F1, because the call appears after the
28298 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
28299 remove the warning on the call. It is also possible to use pragma (2)
28300 because there are no other potentially unsafe calls in the block.
28301
28302 @noindent
28303 The call to @code{Pure} is safe because this function does not depend on the
28304 state of @code{Pack2}. Therefore any call to this function is safe, and it
28305 is correct to place pragma (3) in the corresponding package spec.
28306
28307 @noindent
28308 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
28309 warnings on all calls to functions declared therein. Note that this is not
28310 necessarily safe, and requires more detailed examination of the subprogram
28311 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
28312 be already elaborated.
28313 @end table
28314
28315 @noindent
28316 It is hard to generalize on which of these four approaches should be
28317 taken. Obviously if it is possible to fix the program so that the default
28318 treatment works, this is preferable, but this may not always be practical.
28319 It is certainly simple enough to use
28320 @option{-gnatE}
28321 but the danger in this case is that, even if the GNAT binder
28322 finds a correct elaboration order, it may not always do so,
28323 and certainly a binder from another Ada compiler might not. A
28324 combination of testing and analysis (for which the warnings generated
28325 with the
28326 @option{-gnatwl}
28327 switch can be useful) must be used to ensure that the program is free
28328 of errors. One switch that is useful in this testing is the
28329 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
28330 switch for
28331 @code{gnatbind}.
28332 Normally the binder tries to find an order that has the best chance
28333 of avoiding elaboration problems. However, if this switch is used, the binder
28334 plays a devil's advocate role, and tries to choose the order that
28335 has the best chance of failing. If your program works even with this
28336 switch, then it has a better chance of being error free, but this is still
28337 not a guarantee.
28338
28339 For an example of this approach in action, consider the C-tests (executable
28340 tests) from the ACVC suite. If these are compiled and run with the default
28341 treatment, then all but one of them succeed without generating any error
28342 diagnostics from the binder. However, there is one test that fails, and
28343 this is not surprising, because the whole point of this test is to ensure
28344 that the compiler can handle cases where it is impossible to determine
28345 a correct order statically, and it checks that an exception is indeed
28346 raised at run time.
28347
28348 This one test must be compiled and run using the
28349 @option{-gnatE}
28350 switch, and then it passes. Alternatively, the entire suite can
28351 be run using this switch. It is never wrong to run with the dynamic
28352 elaboration switch if your code is correct, and we assume that the
28353 C-tests are indeed correct (it is less efficient, but efficiency is
28354 not a factor in running the ACVC tests.)
28355
28356 @node Elaboration for Access-to-Subprogram Values
28357 @section Elaboration for Access-to-Subprogram Values
28358 @cindex Access-to-subprogram
28359
28360 @noindent
28361 Access-to-subprogram types (introduced in Ada 95) complicate
28362 the handling of elaboration. The trouble is that it becomes
28363 impossible to tell at compile time which procedure
28364 is being called. This means that it is not possible for the binder
28365 to analyze the elaboration requirements in this case.
28366
28367 If at the point at which the access value is created
28368 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
28369 the body of the subprogram is
28370 known to have been elaborated, then the access value is safe, and its use
28371 does not require a check. This may be achieved by appropriate arrangement
28372 of the order of declarations if the subprogram is in the current unit,
28373 or, if the subprogram is in another unit, by using pragma
28374 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
28375 on the referenced unit.
28376
28377 If the referenced body is not known to have been elaborated at the point
28378 the access value is created, then any use of the access value must do a
28379 dynamic check, and this dynamic check will fail and raise a
28380 @code{Program_Error} exception if the body has not been elaborated yet.
28381 GNAT will generate the necessary checks, and in addition, if the
28382 @option{-gnatwl}
28383 switch is set, will generate warnings that such checks are required.
28384
28385 The use of dynamic dispatching for tagged types similarly generates
28386 a requirement for dynamic checks, and premature calls to any primitive
28387 operation of a tagged type before the body of the operation has been
28388 elaborated, will result in the raising of @code{Program_Error}.
28389
28390 @node Summary of Procedures for Elaboration Control
28391 @section Summary of Procedures for Elaboration Control
28392 @cindex Elaboration control
28393
28394 @noindent
28395 First, compile your program with the default options, using none of
28396 the special elaboration control switches. If the binder successfully
28397 binds your program, then you can be confident that, apart from issues
28398 raised by the use of access-to-subprogram types and dynamic dispatching,
28399 the program is free of elaboration errors. If it is important that the
28400 program be portable, then use the
28401 @option{-gnatwl}
28402 switch to generate warnings about missing @code{Elaborate} or
28403 @code{Elaborate_All} pragmas, and supply the missing pragmas.
28404
28405 If the program fails to bind using the default static elaboration
28406 handling, then you can fix the program to eliminate the binder
28407 message, or recompile the entire program with the
28408 @option{-gnatE} switch to generate dynamic elaboration checks,
28409 and, if you are sure there really are no elaboration problems,
28410 use a global pragma @code{Suppress (Elaboration_Check)}.
28411
28412 @node Other Elaboration Order Considerations
28413 @section Other Elaboration Order Considerations
28414 @noindent
28415 This section has been entirely concerned with the issue of finding a valid
28416 elaboration order, as defined by the Ada Reference Manual. In a case
28417 where several elaboration orders are valid, the task is to find one
28418 of the possible valid elaboration orders (and the static model in GNAT
28419 will ensure that this is achieved).
28420
28421 The purpose of the elaboration rules in the Ada Reference Manual is to
28422 make sure that no entity is accessed before it has been elaborated. For
28423 a subprogram, this means that the spec and body must have been elaborated
28424 before the subprogram is called. For an object, this means that the object
28425 must have been elaborated before its value is read or written. A violation
28426 of either of these two requirements is an access before elaboration order,
28427 and this section has been all about avoiding such errors.
28428
28429 In the case where more than one order of elaboration is possible, in the
28430 sense that access before elaboration errors are avoided, then any one of
28431 the orders is ``correct'' in the sense that it meets the requirements of
28432 the Ada Reference Manual, and no such error occurs.
28433
28434 However, it may be the case for a given program, that there are
28435 constraints on the order of elaboration that come not from consideration
28436 of avoiding elaboration errors, but rather from extra-lingual logic
28437 requirements. Consider this example:
28438
28439 @smallexample @c ada
28440 with Init_Constants;
28441 package Constants is
28442    X : Integer := 0;
28443    Y : Integer := 0;
28444 end Constants;
28445
28446 package Init_Constants is
28447    procedure P; -- require a body
28448 end Init_Constants;
28449
28450 with Constants;
28451 package body Init_Constants is
28452    procedure P is begin null; end;
28453 begin
28454    Constants.X := 3;
28455    Constants.Y := 4;
28456 end Init_Constants;
28457
28458 with Constants;
28459 package Calc is
28460    Z : Integer := Constants.X + Constants.Y;
28461 end Calc;
28462
28463 with Calc;
28464 with Text_IO; use Text_IO;
28465 procedure Main is
28466 begin
28467    Put_Line (Calc.Z'Img);
28468 end Main;
28469 @end smallexample
28470
28471 @noindent
28472 In this example, there is more than one valid order of elaboration. For
28473 example both the following are correct orders:
28474
28475 @smallexample
28476 Init_Constants spec
28477 Constants spec
28478 Calc spec
28479 Init_Constants body
28480 Main body
28481
28482   and
28483
28484 Init_Constants spec
28485 Init_Constants body
28486 Constants spec
28487 Calc spec
28488 Main body
28489 @end smallexample
28490
28491 @noindent
28492 There is no language rule to prefer one or the other, both are correct
28493 from an order of elaboration point of view. But the programmatic effects
28494 of the two orders are very different. In the first, the elaboration routine
28495 of @code{Calc} initializes @code{Z} to zero, and then the main program
28496 runs with this value of zero. But in the second order, the elaboration
28497 routine of @code{Calc} runs after the body of Init_Constants has set
28498 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
28499 runs.
28500
28501 One could perhaps by applying pretty clever non-artificial intelligence
28502 to the situation guess that it is more likely that the second order of
28503 elaboration is the one desired, but there is no formal linguistic reason
28504 to prefer one over the other. In fact in this particular case, GNAT will
28505 prefer the second order, because of the rule that bodies are elaborated
28506 as soon as possible, but it's just luck that this is what was wanted
28507 (if indeed the second order was preferred).
28508
28509 If the program cares about the order of elaboration routines in a case like
28510 this, it is important to specify the order required. In this particular
28511 case, that could have been achieved by adding to the spec of Calc:
28512
28513 @smallexample @c ada
28514 pragma Elaborate_All (Constants);
28515 @end smallexample
28516
28517 @noindent
28518 which requires that the body (if any) and spec of @code{Constants},
28519 as well as the body and spec of any unit @code{with}'ed by
28520 @code{Constants} be elaborated before @code{Calc} is elaborated.
28521
28522 Clearly no automatic method can always guess which alternative you require,
28523 and if you are working with legacy code that had constraints of this kind
28524 which were not properly specified by adding @code{Elaborate} or
28525 @code{Elaborate_All} pragmas, then indeed it is possible that two different
28526 compilers can choose different orders.
28527
28528 However, GNAT does attempt to diagnose the common situation where there
28529 are uninitialized variables in the visible part of a package spec, and the
28530 corresponding package body has an elaboration block that directly or
28531 indirectly initialized one or more of these variables. This is the situation
28532 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
28533 a warning that suggests this addition if it detects this situation.
28534
28535 The @code{gnatbind}
28536 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
28537 out problems. This switch causes bodies to be elaborated as late as possible
28538 instead of as early as possible. In the example above, it would have forced
28539 the choice of the first elaboration order. If you get different results
28540 when using this switch, and particularly if one set of results is right,
28541 and one is wrong as far as you are concerned, it shows that you have some
28542 missing @code{Elaborate} pragmas. For the example above, we have the
28543 following output:
28544
28545 @smallexample
28546 gnatmake -f -q main
28547 main
28548  7
28549 gnatmake -f -q main -bargs -p
28550 main
28551  0
28552 @end smallexample
28553
28554 @noindent
28555 It is of course quite unlikely that both these results are correct, so
28556 it is up to you in a case like this to investigate the source of the
28557 difference, by looking at the two elaboration orders that are chosen,
28558 and figuring out which is correct, and then adding the necessary
28559 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
28560
28561
28562
28563 @c *******************************
28564 @node Conditional Compilation
28565 @appendix Conditional Compilation
28566 @c *******************************
28567 @cindex Conditional compilation
28568
28569 @noindent
28570 It is often necessary to arrange for a single source program
28571 to serve multiple purposes, where it is compiled in different
28572 ways to achieve these different goals. Some examples of the
28573 need for this feature are
28574
28575 @itemize @bullet
28576 @item  Adapting a program to a different hardware environment
28577 @item  Adapting a program to a different target architecture
28578 @item  Turning debugging features on and off
28579 @item  Arranging for a program to compile with different compilers
28580 @end itemize
28581
28582 @noindent
28583 In C, or C++, the typical approach would be to use the preprocessor
28584 that is defined as part of the language. The Ada language does not
28585 contain such a feature. This is not an oversight, but rather a very
28586 deliberate design decision, based on the experience that overuse of
28587 the preprocessing features in C and C++ can result in programs that
28588 are extremely difficult to maintain. For example, if we have ten
28589 switches that can be on or off, this means that there are a thousand
28590 separate programs, any one of which might not even be syntactically
28591 correct, and even if syntactically correct, the resulting program
28592 might not work correctly. Testing all combinations can quickly become
28593 impossible.
28594
28595 Nevertheless, the need to tailor programs certainly exists, and in
28596 this Appendix we will discuss how this can
28597 be achieved using Ada in general, and GNAT in particular.
28598
28599 @menu
28600 * Use of Boolean Constants::
28601 * Debugging - A Special Case::
28602 * Conditionalizing Declarations::
28603 * Use of Alternative Implementations::
28604 * Preprocessing::
28605 @end menu
28606
28607 @node Use of Boolean Constants
28608 @section Use of Boolean Constants
28609
28610 @noindent
28611 In the case where the difference is simply which code
28612 sequence is executed, the cleanest solution is to use Boolean
28613 constants to control which code is executed.
28614
28615 @smallexample @c ada
28616 @group
28617 FP_Initialize_Required : constant Boolean := True;
28618 @dots{}
28619 if FP_Initialize_Required then
28620 @dots{}
28621 end if;
28622 @end group
28623 @end smallexample
28624
28625 @noindent
28626 Not only will the code inside the @code{if} statement not be executed if
28627 the constant Boolean is @code{False}, but it will also be completely
28628 deleted from the program.
28629 However, the code is only deleted after the @code{if} statement
28630 has been checked for syntactic and semantic correctness.
28631 (In contrast, with preprocessors the code is deleted before the
28632 compiler ever gets to see it, so it is not checked until the switch
28633 is turned on.)
28634 @cindex Preprocessors (contrasted with conditional compilation)
28635
28636 Typically the Boolean constants will be in a separate package,
28637 something like:
28638
28639 @smallexample @c ada
28640 @group
28641 package Config is
28642    FP_Initialize_Required : constant Boolean := True;
28643    Reset_Available        : constant Boolean := False;
28644    @dots{}
28645 end Config;
28646 @end group
28647 @end smallexample
28648
28649 @noindent
28650 The @code{Config} package exists in multiple forms for the various targets,
28651 with an appropriate script selecting the version of @code{Config} needed.
28652 Then any other unit requiring conditional compilation can do a @code{with}
28653 of @code{Config} to make the constants visible.
28654
28655
28656 @node Debugging - A Special Case
28657 @section Debugging - A Special Case
28658
28659 @noindent
28660 A common use of conditional code is to execute statements (for example
28661 dynamic checks, or output of intermediate results) under control of a
28662 debug switch, so that the debugging behavior can be turned on and off.
28663 This can be done using a Boolean constant to control whether the code
28664 is active:
28665
28666 @smallexample @c ada
28667 @group
28668 if Debugging then
28669    Put_Line ("got to the first stage!");
28670 end if;
28671 @end group
28672 @end smallexample
28673
28674 @noindent
28675 or
28676
28677 @smallexample @c ada
28678 @group
28679 if Debugging and then Temperature > 999.0 then
28680    raise Temperature_Crazy;
28681 end if;
28682 @end group
28683 @end smallexample
28684
28685 @noindent
28686 Since this is a common case, there are special features to deal with
28687 this in a convenient manner. For the case of tests, Ada 2005 has added
28688 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
28689 @cindex pragma @code{Assert}
28690 on the @code{Assert} pragma that has always been available in GNAT, so this
28691 feature may be used with GNAT even if you are not using Ada 2005 features.
28692 The use of pragma @code{Assert} is described in
28693 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
28694 example, the last test could be written:
28695
28696 @smallexample @c ada
28697 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
28698 @end smallexample
28699
28700 @noindent
28701 or simply
28702
28703 @smallexample @c ada
28704 pragma Assert (Temperature <= 999.0);
28705 @end smallexample
28706
28707 @noindent
28708 In both cases, if assertions are active and the temperature is excessive,
28709 the exception @code{Assert_Failure} will be raised, with the given string in
28710 the first case or a string indicating the location of the pragma in the second
28711 case used as the exception message.
28712
28713 You can turn assertions on and off by using the @code{Assertion_Policy}
28714 pragma.
28715 @cindex pragma @code{Assertion_Policy}
28716 This is an Ada 2005 pragma which is implemented in all modes by
28717 GNAT, but only in the latest versions of GNAT which include Ada 2005
28718 capability. Alternatively, you can use the @option{-gnata} switch
28719 @cindex @option{-gnata} switch
28720 to enable assertions from the command line (this is recognized by all versions
28721 of GNAT).
28722
28723 For the example above with the @code{Put_Line}, the GNAT-specific pragma
28724 @code{Debug} can be used:
28725 @cindex pragma @code{Debug}
28726
28727 @smallexample @c ada
28728 pragma Debug (Put_Line ("got to the first stage!"));
28729 @end smallexample
28730
28731 @noindent
28732 If debug pragmas are enabled, the argument, which must be of the form of
28733 a procedure call, is executed (in this case, @code{Put_Line} will be called).
28734 Only one call can be present, but of course a special debugging procedure
28735 containing any code you like can be included in the program and then
28736 called in a pragma @code{Debug} argument as needed.
28737
28738 One advantage of pragma @code{Debug} over the @code{if Debugging then}
28739 construct is that pragma @code{Debug} can appear in declarative contexts,
28740 such as at the very beginning of a procedure, before local declarations have
28741 been elaborated.
28742
28743 Debug pragmas are enabled using either the @option{-gnata} switch that also
28744 controls assertions, or with a separate Debug_Policy pragma.
28745 @cindex pragma @code{Debug_Policy}
28746 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
28747 in Ada 95 and Ada 83 programs as well), and is analogous to
28748 pragma @code{Assertion_Policy} to control assertions.
28749
28750 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
28751 and thus they can appear in @file{gnat.adc} if you are not using a
28752 project file, or in the file designated to contain configuration pragmas
28753 in a project file.
28754 They then apply to all subsequent compilations. In practice the use of
28755 the @option{-gnata} switch is often the most convenient method of controlling
28756 the status of these pragmas.
28757
28758 Note that a pragma is not a statement, so in contexts where a statement
28759 sequence is required, you can't just write a pragma on its own. You have
28760 to add a @code{null} statement.
28761
28762 @smallexample @c ada
28763 @group
28764 if @dots{} then
28765    @dots{} -- some statements
28766 else
28767    pragma Assert (Num_Cases < 10);
28768    null;
28769 end if;
28770 @end group
28771 @end smallexample
28772
28773
28774 @node Conditionalizing Declarations
28775 @section Conditionalizing Declarations
28776
28777 @noindent
28778 In some cases, it may be necessary to conditionalize declarations to meet
28779 different requirements. For example we might want a bit string whose length
28780 is set to meet some hardware message requirement.
28781
28782 In some cases, it may be possible to do this using declare blocks controlled
28783 by conditional constants:
28784
28785 @smallexample @c ada
28786 @group
28787 if Small_Machine then
28788    declare
28789       X : Bit_String (1 .. 10);
28790    begin
28791       @dots{}
28792    end;
28793 else
28794    declare
28795       X : Large_Bit_String (1 .. 1000);
28796    begin
28797       @dots{}
28798    end;
28799 end if;
28800 @end group
28801 @end smallexample
28802
28803 @noindent
28804 Note that in this approach, both declarations are analyzed by the
28805 compiler so this can only be used where both declarations are legal,
28806 even though one of them will not be used.
28807
28808 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
28809 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
28810 that are parameterized by these constants. For example
28811
28812 @smallexample @c ada
28813 @group
28814 for Rec use
28815   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
28816 end record;
28817 @end group
28818 @end smallexample
28819
28820 @noindent
28821 If @code{Bits_Per_Word} is set to 32, this generates either
28822
28823 @smallexample @c ada
28824 @group
28825 for Rec use
28826   Field1 at 0 range 0 .. 32;
28827 end record;
28828 @end group
28829 @end smallexample
28830
28831 @noindent
28832 for the big endian case, or
28833
28834 @smallexample @c ada
28835 @group
28836 for Rec use record
28837   Field1 at 0 range 10 .. 32;
28838 end record;
28839 @end group
28840 @end smallexample
28841
28842 @noindent
28843 for the little endian case. Since a powerful subset of Ada expression
28844 notation is usable for creating static constants, clever use of this
28845 feature can often solve quite difficult problems in conditionalizing
28846 compilation (note incidentally that in Ada 95, the little endian
28847 constant was introduced as @code{System.Default_Bit_Order}, so you do not
28848 need to define this one yourself).
28849
28850
28851 @node Use of Alternative Implementations
28852 @section Use of Alternative Implementations
28853
28854 @noindent
28855 In some cases, none of the approaches described above are adequate. This
28856 can occur for example if the set of declarations required is radically
28857 different for two different configurations.
28858
28859 In this situation, the official Ada way of dealing with conditionalizing
28860 such code is to write separate units for the different cases. As long as
28861 this does not result in excessive duplication of code, this can be done
28862 without creating maintenance problems. The approach is to share common
28863 code as far as possible, and then isolate the code and declarations
28864 that are different. Subunits are often a convenient method for breaking
28865 out a piece of a unit that is to be conditionalized, with separate files
28866 for different versions of the subunit for different targets, where the
28867 build script selects the right one to give to the compiler.
28868 @cindex Subunits (and conditional compilation)
28869
28870 As an example, consider a situation where a new feature in Ada 2005
28871 allows something to be done in a really nice way. But your code must be able
28872 to compile with an Ada 95 compiler. Conceptually you want to say:
28873
28874 @smallexample @c ada
28875 @group
28876 if Ada_2005 then
28877    @dots{} neat Ada 2005 code
28878 else
28879    @dots{} not quite as neat Ada 95 code
28880 end if;
28881 @end group
28882 @end smallexample
28883
28884 @noindent
28885 where @code{Ada_2005} is a Boolean constant.
28886
28887 But this won't work when @code{Ada_2005} is set to @code{False},
28888 since the @code{then} clause will be illegal for an Ada 95 compiler.
28889 (Recall that although such unreachable code would eventually be deleted
28890 by the compiler, it still needs to be legal.  If it uses features
28891 introduced in Ada 2005, it will be illegal in Ada 95.)
28892
28893 So instead we write
28894
28895 @smallexample @c ada
28896 procedure Insert is separate;
28897 @end smallexample
28898
28899 @noindent
28900 Then we have two files for the subunit @code{Insert}, with the two sets of
28901 code.
28902 If the package containing this is called @code{File_Queries}, then we might
28903 have two files
28904
28905 @itemize @bullet
28906 @item    @file{file_queries-insert-2005.adb}
28907 @item    @file{file_queries-insert-95.adb}
28908 @end itemize
28909
28910 @noindent
28911 and the build script renames the appropriate file to
28912
28913 @smallexample
28914 file_queries-insert.adb
28915 @end smallexample
28916
28917 @noindent
28918 and then carries out the compilation.
28919
28920 This can also be done with project files' naming schemes. For example:
28921
28922 @smallexample @c project
28923 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
28924 @end smallexample
28925
28926 @noindent
28927 Note also that with project files it is desirable to use a different extension
28928 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
28929 conflict may arise through another commonly used feature: to declare as part
28930 of the project a set of directories containing all the sources obeying the
28931 default naming scheme.
28932
28933 The use of alternative units is certainly feasible in all situations,
28934 and for example the Ada part of the GNAT run-time is conditionalized
28935 based on the target architecture using this approach. As a specific example,
28936 consider the implementation of the AST feature in VMS. There is one
28937 spec:
28938
28939 @smallexample
28940 s-asthan.ads
28941 @end smallexample
28942
28943 @noindent
28944 which is the same for all architectures, and three bodies:
28945
28946 @table @file
28947 @item    s-asthan.adb
28948 used for all non-VMS operating systems
28949 @item    s-asthan-vms-alpha.adb
28950 used for VMS on the Alpha
28951 @item    s-asthan-vms-ia64.adb
28952 used for VMS on the ia64
28953 @end table
28954
28955 @noindent
28956 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
28957 this operating system feature is not available, and the two remaining
28958 versions interface with the corresponding versions of VMS to provide
28959 VMS-compatible AST handling. The GNAT build script knows the architecture
28960 and operating system, and automatically selects the right version,
28961 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
28962
28963 Another style for arranging alternative implementations is through Ada's
28964 access-to-subprogram facility.
28965 In case some functionality is to be conditionally included,
28966 you can declare an access-to-procedure variable @code{Ref} that is initialized
28967 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
28968 when appropriate.
28969 In some library package, set @code{Ref} to @code{Proc'Access} for some
28970 procedure @code{Proc} that performs the relevant processing.
28971 The initialization only occurs if the library package is included in the
28972 program.
28973 The same idea can also be implemented using tagged types and dispatching
28974 calls.
28975
28976
28977 @node Preprocessing
28978 @section Preprocessing
28979 @cindex Preprocessing
28980
28981 @noindent
28982 Although it is quite possible to conditionalize code without the use of
28983 C-style preprocessing, as described earlier in this section, it is
28984 nevertheless convenient in some cases to use the C approach. Moreover,
28985 older Ada compilers have often provided some preprocessing capability,
28986 so legacy code may depend on this approach, even though it is not
28987 standard.
28988
28989 To accommodate such use, GNAT provides a preprocessor (modeled to a large
28990 extent on the various preprocessors that have been used
28991 with legacy code on other compilers, to enable easier transition).
28992
28993 The preprocessor may be used in two separate modes. It can be used quite
28994 separately from the compiler, to generate a separate output source file
28995 that is then fed to the compiler as a separate step. This is the
28996 @code{gnatprep} utility, whose use is fully described in
28997 @ref{Preprocessing Using gnatprep}.
28998 @cindex @code{gnatprep}
28999
29000 The preprocessing language allows such constructs as
29001
29002 @smallexample
29003 @group
29004 #if DEBUG or PRIORITY > 4 then
29005    bunch of declarations
29006 #else
29007    completely different bunch of declarations
29008 #end if;
29009 @end group
29010 @end smallexample
29011
29012 @noindent
29013 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
29014 defined either on the command line or in a separate file.
29015
29016 The other way of running the preprocessor is even closer to the C style and
29017 often more convenient. In this approach the preprocessing is integrated into
29018 the compilation process. The compiler is fed the preprocessor input which
29019 includes @code{#if} lines etc, and then the compiler carries out the
29020 preprocessing internally and processes the resulting output.
29021 For more details on this approach, see @ref{Integrated Preprocessing}.
29022
29023
29024 @c *******************************
29025 @node Inline Assembler
29026 @appendix Inline Assembler
29027 @c *******************************
29028
29029 @noindent
29030 If you need to write low-level software that interacts directly
29031 with the hardware, Ada provides two ways to incorporate assembly
29032 language code into your program.  First, you can import and invoke
29033 external routines written in assembly language, an Ada feature fully
29034 supported by GNAT@.  However, for small sections of code it may be simpler
29035 or more efficient to include assembly language statements directly
29036 in your Ada source program, using the facilities of the implementation-defined
29037 package @code{System.Machine_Code}, which incorporates the gcc
29038 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
29039 including the following:
29040
29041 @itemize @bullet
29042 @item No need to use non-Ada tools
29043 @item Consistent interface over different targets
29044 @item Automatic usage of the proper calling conventions
29045 @item Access to Ada constants and variables
29046 @item Definition of intrinsic routines
29047 @item Possibility of inlining a subprogram comprising assembler code
29048 @item Code optimizer can take Inline Assembler code into account
29049 @end itemize
29050
29051 This chapter presents a series of examples to show you how to use
29052 the Inline Assembler.  Although it focuses on the Intel x86,
29053 the general approach applies also to other processors.
29054 It is assumed that you are familiar with Ada
29055 and with assembly language programming.
29056
29057 @menu
29058 * Basic Assembler Syntax::
29059 * A Simple Example of Inline Assembler::
29060 * Output Variables in Inline Assembler::
29061 * Input Variables in Inline Assembler::
29062 * Inlining Inline Assembler Code::
29063 * Other Asm Functionality::
29064 @end menu
29065
29066 @c ---------------------------------------------------------------------------
29067 @node Basic Assembler Syntax
29068 @section Basic Assembler Syntax
29069
29070 @noindent
29071 The assembler used by GNAT and gcc is based not on the Intel assembly
29072 language, but rather on a language that descends from the AT&T Unix
29073 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
29074 The following table summarizes the main features of @emph{as} syntax
29075 and points out the differences from the Intel conventions.
29076 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
29077 pre-processor) documentation for further information.
29078
29079 @table @asis
29080 @item Register names
29081 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
29082 @*
29083 Intel: No extra punctuation; for example @code{eax}
29084
29085 @item Immediate operand
29086 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
29087 @*
29088 Intel: No extra punctuation; for example @code{4}
29089
29090 @item Address
29091 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
29092 @*
29093 Intel: No extra punctuation; for example @code{loc}
29094
29095 @item Memory contents
29096 gcc / @emph{as}: No extra punctuation; for example @code{loc}
29097 @*
29098 Intel: Square brackets; for example @code{[loc]}
29099
29100 @item Register contents
29101 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
29102 @*
29103 Intel: Square brackets; for example @code{[eax]}
29104
29105 @item Hexadecimal numbers
29106 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
29107 @*
29108 Intel: Trailing ``h''; for example @code{A0h}
29109
29110 @item Operand size
29111 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
29112 a 16-bit word
29113 @*
29114 Intel: Implicit, deduced by assembler; for example @code{mov}
29115
29116 @item Instruction repetition
29117 gcc / @emph{as}: Split into two lines; for example
29118 @*
29119 @code{rep}
29120 @*
29121 @code{stosl}
29122 @*
29123 Intel: Keep on one line; for example @code{rep stosl}
29124
29125 @item Order of operands
29126 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
29127 @*
29128 Intel: Destination first; for example @code{mov eax, 4}
29129 @end table
29130
29131 @c ---------------------------------------------------------------------------
29132 @node A Simple Example of Inline Assembler
29133 @section A Simple Example of Inline Assembler
29134
29135 @noindent
29136 The following example will generate a single assembly language statement,
29137 @code{nop}, which does nothing.  Despite its lack of run-time effect,
29138 the example will be useful in illustrating the basics of
29139 the Inline Assembler facility.
29140
29141 @smallexample @c ada
29142 @group
29143 with System.Machine_Code; use System.Machine_Code;
29144 procedure Nothing is
29145 begin
29146    Asm ("nop");
29147 end Nothing;
29148 @end group
29149 @end smallexample
29150
29151 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
29152 here it takes one parameter, a @emph{template string} that must be a static
29153 expression and that will form the generated instruction.
29154 @code{Asm} may be regarded as a compile-time procedure that parses
29155 the template string and additional parameters (none here),
29156 from which it generates a sequence of assembly language instructions.
29157
29158 The examples in this chapter will illustrate several of the forms
29159 for invoking @code{Asm}; a complete specification of the syntax
29160 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
29161 Manual}.
29162
29163 Under the standard GNAT conventions, the @code{Nothing} procedure
29164 should be in a file named @file{nothing.adb}.
29165 You can build the executable in the usual way:
29166 @smallexample
29167 gnatmake nothing
29168 @end smallexample
29169 However, the interesting aspect of this example is not its run-time behavior
29170 but rather the generated assembly code.
29171 To see this output, invoke the compiler as follows:
29172 @smallexample
29173    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
29174 @end smallexample
29175 where the options are:
29176
29177 @table @code
29178 @item -c
29179 compile only (no bind or link)
29180 @item -S
29181 generate assembler listing
29182 @item -fomit-frame-pointer
29183 do not set up separate stack frames
29184 @item -gnatp
29185 do not add runtime checks
29186 @end table
29187
29188 This gives a human-readable assembler version of the code. The resulting
29189 file will have the same name as the Ada source file, but with a @code{.s}
29190 extension. In our example, the file @file{nothing.s} has the following
29191 contents:
29192
29193 @smallexample
29194 @group
29195 .file "nothing.adb"
29196 gcc2_compiled.:
29197 ___gnu_compiled_ada:
29198 .text
29199    .align 4
29200 .globl __ada_nothing
29201 __ada_nothing:
29202 #APP
29203    nop
29204 #NO_APP
29205    jmp L1
29206    .align 2,0x90
29207 L1:
29208    ret
29209 @end group
29210 @end smallexample
29211
29212 The assembly code you included is clearly indicated by
29213 the compiler, between the @code{#APP} and @code{#NO_APP}
29214 delimiters. The character before the 'APP' and 'NOAPP'
29215 can differ on different targets. For example, GNU/Linux uses '#APP' while
29216 on NT you will see '/APP'.
29217
29218 If you make a mistake in your assembler code (such as using the
29219 wrong size modifier, or using a wrong operand for the instruction) GNAT
29220 will report this error in a temporary file, which will be deleted when
29221 the compilation is finished.  Generating an assembler file will help
29222 in such cases, since you can assemble this file separately using the
29223 @emph{as} assembler that comes with gcc.
29224
29225 Assembling the file using the command
29226
29227 @smallexample
29228 as @file{nothing.s}
29229 @end smallexample
29230 @noindent
29231 will give you error messages whose lines correspond to the assembler
29232 input file, so you can easily find and correct any mistakes you made.
29233 If there are no errors, @emph{as} will generate an object file
29234 @file{nothing.out}.
29235
29236 @c ---------------------------------------------------------------------------
29237 @node Output Variables in Inline Assembler
29238 @section Output Variables in Inline Assembler
29239
29240 @noindent
29241 The examples in this section, showing how to access the processor flags,
29242 illustrate how to specify the destination operands for assembly language
29243 statements.
29244
29245 @smallexample @c ada
29246 @group
29247 with Interfaces; use Interfaces;
29248 with Ada.Text_IO; use Ada.Text_IO;
29249 with System.Machine_Code; use System.Machine_Code;
29250 procedure Get_Flags is
29251    Flags : Unsigned_32;
29252    use ASCII;
29253 begin
29254    Asm ("pushfl"          & LF & HT & -- push flags on stack
29255         "popl %%eax"      & LF & HT & -- load eax with flags
29256         "movl %%eax, %0",             -- store flags in variable
29257         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29258    Put_Line ("Flags register:" & Flags'Img);
29259 end Get_Flags;
29260 @end group
29261 @end smallexample
29262
29263 In order to have a nicely aligned assembly listing, we have separated
29264 multiple assembler statements in the Asm template string with linefeed
29265 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
29266 The resulting section of the assembly output file is:
29267
29268 @smallexample
29269 @group
29270 #APP
29271    pushfl
29272    popl %eax
29273    movl %eax, -40(%ebp)
29274 #NO_APP
29275 @end group
29276 @end smallexample
29277
29278 It would have been legal to write the Asm invocation as:
29279
29280 @smallexample
29281 Asm ("pushfl popl %%eax movl %%eax, %0")
29282 @end smallexample
29283
29284 but in the generated assembler file, this would come out as:
29285
29286 @smallexample
29287 #APP
29288    pushfl popl %eax movl %eax, -40(%ebp)
29289 #NO_APP
29290 @end smallexample
29291
29292 which is not so convenient for the human reader.
29293
29294 We use Ada comments
29295 at the end of each line to explain what the assembler instructions
29296 actually do.  This is a useful convention.
29297
29298 When writing Inline Assembler instructions, you need to precede each register
29299 and variable name with a percent sign.  Since the assembler already requires
29300 a percent sign at the beginning of a register name, you need two consecutive
29301 percent signs for such names in the Asm template string, thus @code{%%eax}.
29302 In the generated assembly code, one of the percent signs will be stripped off.
29303
29304 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
29305 variables: operands you later define using @code{Input} or @code{Output}
29306 parameters to @code{Asm}.
29307 An output variable is illustrated in
29308 the third statement in the Asm template string:
29309 @smallexample
29310 movl %%eax, %0
29311 @end smallexample
29312 The intent is to store the contents of the eax register in a variable that can
29313 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
29314 necessarily work, since the compiler might optimize by using a register
29315 to hold Flags, and the expansion of the @code{movl} instruction would not be
29316 aware of this optimization.  The solution is not to store the result directly
29317 but rather to advise the compiler to choose the correct operand form;
29318 that is the purpose of the @code{%0} output variable.
29319
29320 Information about the output variable is supplied in the @code{Outputs}
29321 parameter to @code{Asm}:
29322 @smallexample
29323 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29324 @end smallexample
29325
29326 The output is defined by the @code{Asm_Output} attribute of the target type;
29327 the general format is
29328 @smallexample
29329 Type'Asm_Output (constraint_string, variable_name)
29330 @end smallexample
29331
29332 The constraint string directs the compiler how
29333 to store/access the associated variable.  In the example
29334 @smallexample
29335 Unsigned_32'Asm_Output ("=m", Flags);
29336 @end smallexample
29337 the @code{"m"} (memory) constraint tells the compiler that the variable
29338 @code{Flags} should be stored in a memory variable, thus preventing
29339 the optimizer from keeping it in a register.  In contrast,
29340 @smallexample
29341 Unsigned_32'Asm_Output ("=r", Flags);
29342 @end smallexample
29343 uses the @code{"r"} (register) constraint, telling the compiler to
29344 store the variable in a register.
29345
29346 If the constraint is preceded by the equal character (@strong{=}), it tells
29347 the compiler that the variable will be used to store data into it.
29348
29349 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
29350 allowing the optimizer to choose whatever it deems best.
29351
29352 There are a fairly large number of constraints, but the ones that are
29353 most useful (for the Intel x86 processor) are the following:
29354
29355 @table @code
29356 @item =
29357 output constraint
29358 @item g
29359 global (i.e.@: can be stored anywhere)
29360 @item m
29361 in memory
29362 @item I
29363 a constant
29364 @item a
29365 use eax
29366 @item b
29367 use ebx
29368 @item c
29369 use ecx
29370 @item d
29371 use edx
29372 @item S
29373 use esi
29374 @item D
29375 use edi
29376 @item r
29377 use one of eax, ebx, ecx or edx
29378 @item q
29379 use one of eax, ebx, ecx, edx, esi or edi
29380 @end table
29381
29382 The full set of constraints is described in the gcc and @emph{as}
29383 documentation; note that it is possible to combine certain constraints
29384 in one constraint string.
29385
29386 You specify the association of an output variable with an assembler operand
29387 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
29388 integer.  Thus in
29389 @smallexample @c ada
29390 @group
29391 Asm ("pushfl"          & LF & HT & -- push flags on stack
29392      "popl %%eax"      & LF & HT & -- load eax with flags
29393      "movl %%eax, %0",             -- store flags in variable
29394      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29395 @end group
29396 @end smallexample
29397 @noindent
29398 @code{%0} will be replaced in the expanded code by the appropriate operand,
29399 whatever
29400 the compiler decided for the @code{Flags} variable.
29401
29402 In general, you may have any number of output variables:
29403 @itemize @bullet
29404 @item
29405 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
29406 @item
29407 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
29408 of @code{Asm_Output} attributes
29409 @end itemize
29410
29411 For example:
29412 @smallexample @c ada
29413 @group
29414 Asm ("movl %%eax, %0" & LF & HT &
29415      "movl %%ebx, %1" & LF & HT &
29416      "movl %%ecx, %2",
29417      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
29418                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
29419                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
29420 @end group
29421 @end smallexample
29422 @noindent
29423 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
29424 in the Ada program.
29425
29426 As a variation on the @code{Get_Flags} example, we can use the constraints
29427 string to direct the compiler to store the eax register into the @code{Flags}
29428 variable, instead of including the store instruction explicitly in the
29429 @code{Asm} template string:
29430
29431 @smallexample @c ada
29432 @group
29433 with Interfaces; use Interfaces;
29434 with Ada.Text_IO; use Ada.Text_IO;
29435 with System.Machine_Code; use System.Machine_Code;
29436 procedure Get_Flags_2 is
29437    Flags : Unsigned_32;
29438    use ASCII;
29439 begin
29440    Asm ("pushfl"      & LF & HT & -- push flags on stack
29441         "popl %%eax",             -- save flags in eax
29442         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
29443    Put_Line ("Flags register:" & Flags'Img);
29444 end Get_Flags_2;
29445 @end group
29446 @end smallexample
29447
29448 @noindent
29449 The @code{"a"} constraint tells the compiler that the @code{Flags}
29450 variable will come from the eax register. Here is the resulting code:
29451
29452 @smallexample
29453 @group
29454 #APP
29455    pushfl
29456    popl %eax
29457 #NO_APP
29458    movl %eax,-40(%ebp)
29459 @end group
29460 @end smallexample
29461
29462 @noindent
29463 The compiler generated the store of eax into Flags after
29464 expanding the assembler code.
29465
29466 Actually, there was no need to pop the flags into the eax register;
29467 more simply, we could just pop the flags directly into the program variable:
29468
29469 @smallexample @c ada
29470 @group
29471 with Interfaces; use Interfaces;
29472 with Ada.Text_IO; use Ada.Text_IO;
29473 with System.Machine_Code; use System.Machine_Code;
29474 procedure Get_Flags_3 is
29475    Flags : Unsigned_32;
29476    use ASCII;
29477 begin
29478    Asm ("pushfl"  & LF & HT & -- push flags on stack
29479         "pop %0",             -- save flags in Flags
29480         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29481    Put_Line ("Flags register:" & Flags'Img);
29482 end Get_Flags_3;
29483 @end group
29484 @end smallexample
29485
29486 @c ---------------------------------------------------------------------------
29487 @node Input Variables in Inline Assembler
29488 @section Input Variables in Inline Assembler
29489
29490 @noindent
29491 The example in this section illustrates how to specify the source operands
29492 for assembly language statements.
29493 The program simply increments its input value by 1:
29494
29495 @smallexample @c ada
29496 @group
29497 with Interfaces; use Interfaces;
29498 with Ada.Text_IO; use Ada.Text_IO;
29499 with System.Machine_Code; use System.Machine_Code;
29500 procedure Increment is
29501
29502    function Incr (Value : Unsigned_32) return Unsigned_32 is
29503       Result : Unsigned_32;
29504    begin
29505       Asm ("incl %0",
29506            Inputs  => Unsigned_32'Asm_Input ("a", Value),
29507            Outputs => Unsigned_32'Asm_Output ("=a", Result));
29508       return Result;
29509    end Incr;
29510
29511    Value : Unsigned_32;
29512
29513 begin
29514    Value := 5;
29515    Put_Line ("Value before is" & Value'Img);
29516    Value := Incr (Value);
29517    Put_Line ("Value after is" & Value'Img);
29518 end Increment;
29519 @end group
29520 @end smallexample
29521
29522 The @code{Outputs} parameter to @code{Asm} specifies
29523 that the result will be in the eax register and that it is to be stored
29524 in the @code{Result} variable.
29525
29526 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
29527 but with an @code{Asm_Input} attribute.
29528 The @code{"="} constraint, indicating an output value, is not present.
29529
29530 You can have multiple input variables, in the same way that you can have more
29531 than one output variable.
29532
29533 The parameter count (%0, %1) etc, now starts at the first input
29534 statement, and continues with the output statements.
29535 When both parameters use the same variable, the
29536 compiler will treat them as the same %n operand, which is the case here.
29537
29538 Just as the @code{Outputs} parameter causes the register to be stored into the
29539 target variable after execution of the assembler statements, so does the
29540 @code{Inputs} parameter cause its variable to be loaded into the register
29541 before execution of the assembler statements.
29542
29543 Thus the effect of the @code{Asm} invocation is:
29544 @enumerate
29545 @item load the 32-bit value of @code{Value} into eax
29546 @item execute the @code{incl %eax} instruction
29547 @item store the contents of eax into the @code{Result} variable
29548 @end enumerate
29549
29550 The resulting assembler file (with @option{-O2} optimization) contains:
29551 @smallexample
29552 @group
29553 _increment__incr.1:
29554    subl $4,%esp
29555    movl 8(%esp),%eax
29556 #APP
29557    incl %eax
29558 #NO_APP
29559    movl %eax,%edx
29560    movl %ecx,(%esp)
29561    addl $4,%esp
29562    ret
29563 @end group
29564 @end smallexample
29565
29566 @c ---------------------------------------------------------------------------
29567 @node Inlining Inline Assembler Code
29568 @section Inlining Inline Assembler Code
29569
29570 @noindent
29571 For a short subprogram such as the @code{Incr} function in the previous
29572 section, the overhead of the call and return (creating / deleting the stack
29573 frame) can be significant, compared to the amount of code in the subprogram
29574 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
29575 which directs the compiler to expand invocations of the subprogram at the
29576 point(s) of call, instead of setting up a stack frame for out-of-line calls.
29577 Here is the resulting program:
29578
29579 @smallexample @c ada
29580 @group
29581 with Interfaces; use Interfaces;
29582 with Ada.Text_IO; use Ada.Text_IO;
29583 with System.Machine_Code; use System.Machine_Code;
29584 procedure Increment_2 is
29585
29586    function Incr (Value : Unsigned_32) return Unsigned_32 is
29587       Result : Unsigned_32;
29588    begin
29589       Asm ("incl %0",
29590            Inputs  => Unsigned_32'Asm_Input ("a", Value),
29591            Outputs => Unsigned_32'Asm_Output ("=a", Result));
29592       return Result;
29593    end Incr;
29594    pragma Inline (Increment);
29595
29596    Value : Unsigned_32;
29597
29598 begin
29599    Value := 5;
29600    Put_Line ("Value before is" & Value'Img);
29601    Value := Increment (Value);
29602    Put_Line ("Value after is" & Value'Img);
29603 end Increment_2;
29604 @end group
29605 @end smallexample
29606
29607 Compile the program with both optimization (@option{-O2}) and inlining
29608 (@option{-gnatn}) enabled.
29609
29610 The @code{Incr} function is still compiled as usual, but at the
29611 point in @code{Increment} where our function used to be called:
29612
29613 @smallexample
29614 @group
29615 pushl %edi
29616 call _increment__incr.1
29617 @end group
29618 @end smallexample
29619
29620 @noindent
29621 the code for the function body directly appears:
29622
29623 @smallexample
29624 @group
29625 movl %esi,%eax
29626 #APP
29627    incl %eax
29628 #NO_APP
29629    movl %eax,%edx
29630 @end group
29631 @end smallexample
29632
29633 @noindent
29634 thus saving the overhead of stack frame setup and an out-of-line call.
29635
29636 @c ---------------------------------------------------------------------------
29637 @node Other Asm Functionality
29638 @section Other @code{Asm} Functionality
29639
29640 @noindent
29641 This section describes two important parameters to the @code{Asm}
29642 procedure: @code{Clobber}, which identifies register usage;
29643 and @code{Volatile}, which inhibits unwanted optimizations.
29644
29645 @menu
29646 * The Clobber Parameter::
29647 * The Volatile Parameter::
29648 @end menu
29649
29650 @c ---------------------------------------------------------------------------
29651 @node The Clobber Parameter
29652 @subsection The @code{Clobber} Parameter
29653
29654 @noindent
29655 One of the dangers of intermixing assembly language and a compiled language
29656 such as Ada is that the compiler needs to be aware of which registers are
29657 being used by the assembly code.  In some cases, such as the earlier examples,
29658 the constraint string is sufficient to indicate register usage (e.g.,
29659 @code{"a"} for
29660 the eax register).  But more generally, the compiler needs an explicit
29661 identification of the registers that are used by the Inline Assembly
29662 statements.
29663
29664 Using a register that the compiler doesn't know about
29665 could be a side effect of an instruction (like @code{mull}
29666 storing its result in both eax and edx).
29667 It can also arise from explicit register usage in your
29668 assembly code; for example:
29669 @smallexample
29670 @group
29671 Asm ("movl %0, %%ebx" & LF & HT &
29672      "movl %%ebx, %1",
29673      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
29674      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
29675 @end group
29676 @end smallexample
29677 @noindent
29678 where the compiler (since it does not analyze the @code{Asm} template string)
29679 does not know you are using the ebx register.
29680
29681 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
29682 to identify the registers that will be used by your assembly code:
29683
29684 @smallexample
29685 @group
29686 Asm ("movl %0, %%ebx" & LF & HT &
29687      "movl %%ebx, %1",
29688      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
29689      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
29690      Clobber => "ebx");
29691 @end group
29692 @end smallexample
29693
29694 The Clobber parameter is a static string expression specifying the
29695 register(s) you are using.  Note that register names are @emph{not} prefixed
29696 by a percent sign. Also, if more than one register is used then their names
29697 are separated by commas; e.g., @code{"eax, ebx"}
29698
29699 The @code{Clobber} parameter has several additional uses:
29700 @enumerate
29701 @item Use ``register'' name @code{cc} to indicate that flags might have changed
29702 @item Use ``register'' name @code{memory} if you changed a memory location
29703 @end enumerate
29704
29705 @c ---------------------------------------------------------------------------
29706 @node The Volatile Parameter
29707 @subsection The @code{Volatile} Parameter
29708 @cindex Volatile parameter
29709
29710 @noindent
29711 Compiler optimizations in the presence of Inline Assembler may sometimes have
29712 unwanted effects.  For example, when an @code{Asm} invocation with an input
29713 variable is inside a loop, the compiler might move the loading of the input
29714 variable outside the loop, regarding it as a one-time initialization.
29715
29716 If this effect is not desired, you can disable such optimizations by setting
29717 the @code{Volatile} parameter to @code{True}; for example:
29718
29719 @smallexample @c ada
29720 @group
29721 Asm ("movl %0, %%ebx" & LF & HT &
29722      "movl %%ebx, %1",
29723      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
29724      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
29725      Clobber  => "ebx",
29726      Volatile => True);
29727 @end group
29728 @end smallexample
29729
29730 By default, @code{Volatile} is set to @code{False} unless there is no
29731 @code{Outputs} parameter.
29732
29733 Although setting @code{Volatile} to @code{True} prevents unwanted
29734 optimizations, it will also disable other optimizations that might be
29735 important for efficiency. In general, you should set @code{Volatile}
29736 to @code{True} only if the compiler's optimizations have created
29737 problems.
29738 @c END OF INLINE ASSEMBLER CHAPTER
29739 @c ===============================
29740
29741 @c ***********************************
29742 @c * Compatibility and Porting Guide *
29743 @c ***********************************
29744 @node Compatibility and Porting Guide
29745 @appendix Compatibility and Porting Guide
29746
29747 @noindent
29748 This chapter describes the compatibility issues that may arise between
29749 GNAT and other Ada compilation systems (including those for Ada 83),
29750 and shows how GNAT can expedite porting
29751 applications developed in other Ada environments.
29752
29753 @menu
29754 * Compatibility with Ada 83::
29755 * Compatibility between Ada 95 and Ada 2005::
29756 * Implementation-dependent characteristics::
29757 * Compatibility with Other Ada Systems::
29758 * Representation Clauses::
29759 @ifclear vms
29760 @c Brief section is only in non-VMS version
29761 @c Full chapter is in VMS version
29762 * Compatibility with HP Ada 83::
29763 @end ifclear
29764 @ifset vms
29765 * Transitioning to 64-Bit GNAT for OpenVMS::
29766 @end ifset
29767 @end menu
29768
29769 @node Compatibility with Ada 83
29770 @section Compatibility with Ada 83
29771 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
29772
29773 @noindent
29774 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
29775 particular, the design intention was that the difficulties associated
29776 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
29777 that occur when moving from one Ada 83 system to another.
29778
29779 However, there are a number of points at which there are minor
29780 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
29781 full details of these issues,
29782 and should be consulted for a complete treatment.
29783 In practice the
29784 following subsections treat the most likely issues to be encountered.
29785
29786 @menu
29787 * Legal Ada 83 programs that are illegal in Ada 95::
29788 * More deterministic semantics::
29789 * Changed semantics::
29790 * Other language compatibility issues::
29791 @end menu
29792
29793 @node Legal Ada 83 programs that are illegal in Ada 95
29794 @subsection Legal Ada 83 programs that are illegal in Ada 95
29795
29796 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
29797 Ada 95 and thus also in Ada 2005:
29798
29799 @table @emph
29800 @item Character literals
29801 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
29802 @code{Wide_Character} as a new predefined character type, some uses of
29803 character literals that were legal in Ada 83 are illegal in Ada 95.
29804 For example:
29805 @smallexample @c ada
29806    for Char in 'A' .. 'Z' loop @dots{} end loop;
29807 @end smallexample
29808
29809 @noindent
29810 The problem is that @code{'A'} and @code{'Z'} could be from either
29811 @code{Character} or @code{Wide_Character}.  The simplest correction
29812 is to make the type explicit; e.g.:
29813 @smallexample @c ada
29814    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
29815 @end smallexample
29816
29817 @item New reserved words
29818 The identifiers @code{abstract}, @code{aliased}, @code{protected},
29819 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
29820 Existing Ada 83 code using any of these identifiers must be edited to
29821 use some alternative name.
29822
29823 @item Freezing rules
29824 The rules in Ada 95 are slightly different with regard to the point at
29825 which entities are frozen, and representation pragmas and clauses are
29826 not permitted past the freeze point.  This shows up most typically in
29827 the form of an error message complaining that a representation item
29828 appears too late, and the appropriate corrective action is to move
29829 the item nearer to the declaration of the entity to which it refers.
29830
29831 A particular case is that representation pragmas
29832 @ifset vms
29833 (including the
29834 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
29835 @end ifset
29836 cannot be applied to a subprogram body.  If necessary, a separate subprogram
29837 declaration must be introduced to which the pragma can be applied.
29838
29839 @item Optional bodies for library packages
29840 In Ada 83, a package that did not require a package body was nevertheless
29841 allowed to have one.  This lead to certain surprises in compiling large
29842 systems (situations in which the body could be unexpectedly ignored by the
29843 binder).  In Ada 95, if a package does not require a body then it is not
29844 permitted to have a body.  To fix this problem, simply remove a redundant
29845 body if it is empty, or, if it is non-empty, introduce a dummy declaration
29846 into the spec that makes the body required.  One approach is to add a private
29847 part to the package declaration (if necessary), and define a parameterless
29848 procedure called @code{Requires_Body}, which must then be given a dummy
29849 procedure body in the package body, which then becomes required.
29850 Another approach (assuming that this does not introduce elaboration
29851 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
29852 since one effect of this pragma is to require the presence of a package body.
29853
29854 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
29855 In Ada 95, the exception @code{Numeric_Error} is a renaming of
29856 @code{Constraint_Error}.
29857 This means that it is illegal to have separate exception handlers for
29858 the two exceptions.  The fix is simply to remove the handler for the
29859 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
29860 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
29861
29862 @item Indefinite subtypes in generics
29863 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
29864 as the actual for a generic formal private type, but then the instantiation
29865 would be illegal if there were any instances of declarations of variables
29866 of this type in the generic body.  In Ada 95, to avoid this clear violation
29867 of the methodological principle known as the ``contract model'',
29868 the generic declaration explicitly indicates whether
29869 or not such instantiations are permitted.  If a generic formal parameter
29870 has explicit unknown discriminants, indicated by using @code{(<>)} after the
29871 type name, then it can be instantiated with indefinite types, but no
29872 stand-alone variables can be declared of this type.  Any attempt to declare
29873 such a variable will result in an illegality at the time the generic is
29874 declared.  If the @code{(<>)} notation is not used, then it is illegal
29875 to instantiate the generic with an indefinite type.
29876 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
29877 It will show up as a compile time error, and
29878 the fix is usually simply to add the @code{(<>)} to the generic declaration.
29879 @end table
29880
29881 @node More deterministic semantics
29882 @subsection More deterministic semantics
29883
29884 @table @emph
29885 @item Conversions
29886 Conversions from real types to integer types round away from 0.  In Ada 83
29887 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
29888 implementation freedom was intended to support unbiased rounding in
29889 statistical applications, but in practice it interfered with portability.
29890 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
29891 is required.  Numeric code may be affected by this change in semantics.
29892 Note, though, that this issue is no worse than already existed in Ada 83
29893 when porting code from one vendor to another.
29894
29895 @item Tasking
29896 The Real-Time Annex introduces a set of policies that define the behavior of
29897 features that were implementation dependent in Ada 83, such as the order in
29898 which open select branches are executed.
29899 @end table
29900
29901 @node Changed semantics
29902 @subsection Changed semantics
29903
29904 @noindent
29905 The worst kind of incompatibility is one where a program that is legal in
29906 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
29907 possible in Ada 83.  Fortunately this is extremely rare, but the one
29908 situation that you should be alert to is the change in the predefined type
29909 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
29910
29911 @table @emph
29912 @item Range of type @code{Character}
29913 The range of @code{Standard.Character} is now the full 256 characters
29914 of Latin-1, whereas in most Ada 83 implementations it was restricted
29915 to 128 characters. Although some of the effects of
29916 this change will be manifest in compile-time rejection of legal
29917 Ada 83 programs it is possible for a working Ada 83 program to have
29918 a different effect in Ada 95, one that was not permitted in Ada 83.
29919 As an example, the expression
29920 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
29921 delivers @code{255} as its value.
29922 In general, you should look at the logic of any
29923 character-processing Ada 83 program and see whether it needs to be adapted
29924 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
29925 character handling package that may be relevant if code needs to be adapted
29926 to account for the additional Latin-1 elements.
29927 The desirable fix is to
29928 modify the program to accommodate the full character set, but in some cases
29929 it may be convenient to define a subtype or derived type of Character that
29930 covers only the restricted range.
29931 @cindex Latin-1
29932 @end table
29933
29934 @node Other language compatibility issues
29935 @subsection Other language compatibility issues
29936
29937 @table @emph
29938 @item @option{-gnat83} switch
29939 All implementations of GNAT provide a switch that causes GNAT to operate
29940 in Ada 83 mode.  In this mode, some but not all compatibility problems
29941 of the type described above are handled automatically.  For example, the
29942 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
29943 as identifiers as in Ada 83.
29944 However,
29945 in practice, it is usually advisable to make the necessary modifications
29946 to the program to remove the need for using this switch.
29947 See @ref{Compiling Different Versions of Ada}.
29948
29949 @item Support for removed Ada 83 pragmas and attributes
29950 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
29951 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
29952 compilers are allowed, but not required, to implement these missing
29953 elements.  In contrast with some other compilers, GNAT implements all
29954 such pragmas and attributes, eliminating this compatibility concern.  These
29955 include @code{pragma Interface} and the floating point type attributes
29956 (@code{Emax}, @code{Mantissa}, etc.), among other items.
29957 @end table
29958
29959
29960 @node Compatibility between Ada 95 and Ada 2005
29961 @section Compatibility between Ada 95 and Ada 2005
29962 @cindex Compatibility between Ada 95 and Ada 2005
29963
29964 @noindent
29965 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
29966 a number of incompatibilities. Several are enumerated below;
29967 for a complete description please see the
29968 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
29969 @cite{Rationale for Ada 2005}.
29970
29971 @table @emph
29972 @item New reserved words.
29973 The words @code{interface}, @code{overriding} and @code{synchronized} are
29974 reserved in Ada 2005.
29975 A pre-Ada 2005 program that uses any of these as an identifier will be
29976 illegal.
29977
29978 @item New declarations in predefined packages.
29979 A number of packages in the predefined environment contain new declarations:
29980 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
29981 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
29982 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
29983 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
29984 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
29985 If an Ada 95 program does a @code{with} and @code{use} of any of these
29986 packages, the new declarations may cause name clashes.
29987
29988 @item Access parameters.
29989 A nondispatching subprogram with an access parameter cannot be renamed
29990 as a dispatching operation.  This was permitted in Ada 95.
29991
29992 @item Access types, discriminants, and constraints.
29993 Rule changes in this area have led to some incompatibilities; for example,
29994 constrained subtypes of some access types are not permitted in Ada 2005.
29995
29996 @item Aggregates for limited types.
29997 The allowance of aggregates for limited types in Ada 2005 raises the
29998 possibility of ambiguities in legal Ada 95 programs, since additional types
29999 now need to be considered in expression resolution.
30000
30001 @item Fixed-point multiplication and division.
30002 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
30003 were legal in Ada 95 and invoked the predefined versions of these operations,
30004 are now ambiguous.
30005 The ambiguity may be resolved either by applying a type conversion to the
30006 expression, or by explicitly invoking the operation from package
30007 @code{Standard}.
30008
30009 @item Return-by-reference types.
30010 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
30011 can declare a function returning a value from an anonymous access type.
30012 @end table
30013
30014
30015 @node Implementation-dependent characteristics
30016 @section Implementation-dependent characteristics
30017 @noindent
30018 Although the Ada language defines the semantics of each construct as
30019 precisely as practical, in some situations (for example for reasons of
30020 efficiency, or where the effect is heavily dependent on the host or target
30021 platform) the implementation is allowed some freedom.  In porting Ada 83
30022 code to GNAT, you need to be aware of whether / how the existing code
30023 exercised such implementation dependencies.  Such characteristics fall into
30024 several categories, and GNAT offers specific support in assisting the
30025 transition from certain Ada 83 compilers.
30026
30027 @menu
30028 * Implementation-defined pragmas::
30029 * Implementation-defined attributes::
30030 * Libraries::
30031 * Elaboration order::
30032 * Target-specific aspects::
30033 @end menu
30034
30035 @node Implementation-defined pragmas
30036 @subsection Implementation-defined pragmas
30037
30038 @noindent
30039 Ada compilers are allowed to supplement the language-defined pragmas, and
30040 these are a potential source of non-portability.  All GNAT-defined pragmas
30041 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
30042 Reference Manual}, and these include several that are specifically
30043 intended to correspond to other vendors' Ada 83 pragmas.
30044 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
30045 For compatibility with HP Ada 83, GNAT supplies the pragmas
30046 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
30047 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
30048 and @code{Volatile}.
30049 Other relevant pragmas include @code{External} and @code{Link_With}.
30050 Some vendor-specific
30051 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
30052 recognized, thus
30053 avoiding compiler rejection of units that contain such pragmas; they are not
30054 relevant in a GNAT context and hence are not otherwise implemented.
30055
30056 @node Implementation-defined attributes
30057 @subsection Implementation-defined attributes
30058
30059 Analogous to pragmas, the set of attributes may be extended by an
30060 implementation.  All GNAT-defined attributes are described in
30061 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
30062 Manual}, and these include several that are specifically intended
30063 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
30064 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
30065 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
30066 @code{Type_Class}.
30067
30068 @node Libraries
30069 @subsection Libraries
30070 @noindent
30071 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
30072 code uses vendor-specific libraries then there are several ways to manage
30073 this in Ada 95 or Ada 2005:
30074 @enumerate
30075 @item
30076 If the source code for the libraries (specs and bodies) are
30077 available, then the libraries can be migrated in the same way as the
30078 application.
30079 @item
30080 If the source code for the specs but not the bodies are
30081 available, then you can reimplement the bodies.
30082 @item
30083 Some features introduced by Ada 95 obviate the need for library support.  For
30084 example most Ada 83 vendors supplied a package for unsigned integers.  The
30085 Ada 95 modular type feature is the preferred way to handle this need, so
30086 instead of migrating or reimplementing the unsigned integer package it may
30087 be preferable to retrofit the application using modular types.
30088 @end enumerate
30089
30090 @node Elaboration order
30091 @subsection Elaboration order
30092 @noindent
30093 The implementation can choose any elaboration order consistent with the unit
30094 dependency relationship.  This freedom means that some orders can result in
30095 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
30096 to invoke a subprogram its body has been elaborated, or to instantiate a
30097 generic before the generic body has been elaborated.  By default GNAT
30098 attempts to choose a safe order (one that will not encounter access before
30099 elaboration problems) by implicitly inserting @code{Elaborate} or
30100 @code{Elaborate_All} pragmas where
30101 needed.  However, this can lead to the creation of elaboration circularities
30102 and a resulting rejection of the program by gnatbind.  This issue is
30103 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
30104 In brief, there are several
30105 ways to deal with this situation:
30106
30107 @itemize @bullet
30108 @item
30109 Modify the program to eliminate the circularities, e.g.@: by moving
30110 elaboration-time code into explicitly-invoked procedures
30111 @item
30112 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
30113 @code{Elaborate} pragmas, and then inhibit the generation of implicit
30114 @code{Elaborate_All}
30115 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
30116 (by selectively suppressing elaboration checks via pragma
30117 @code{Suppress(Elaboration_Check)} when it is safe to do so).
30118 @end itemize
30119
30120 @node Target-specific aspects
30121 @subsection Target-specific aspects
30122 @noindent
30123 Low-level applications need to deal with machine addresses, data
30124 representations, interfacing with assembler code, and similar issues.  If
30125 such an Ada 83 application is being ported to different target hardware (for
30126 example where the byte endianness has changed) then you will need to
30127 carefully examine the program logic; the porting effort will heavily depend
30128 on the robustness of the original design.  Moreover, Ada 95 (and thus
30129 Ada 2005) are sometimes
30130 incompatible with typical Ada 83 compiler practices regarding implicit
30131 packing, the meaning of the Size attribute, and the size of access values.
30132 GNAT's approach to these issues is described in @ref{Representation Clauses}.
30133
30134 @node Compatibility with Other Ada Systems
30135 @section Compatibility with Other Ada Systems
30136
30137 @noindent
30138 If programs avoid the use of implementation dependent and
30139 implementation defined features, as documented in the @cite{Ada
30140 Reference Manual}, there should be a high degree of portability between
30141 GNAT and other Ada systems.  The following are specific items which
30142 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
30143 compilers, but do not affect porting code to GNAT@.
30144 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
30145 the following issues may or may not arise for Ada 2005 programs
30146 when other compilers appear.)
30147
30148 @table @emph
30149 @item Ada 83 Pragmas and Attributes
30150 Ada 95 compilers are allowed, but not required, to implement the missing
30151 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
30152 GNAT implements all such pragmas and attributes, eliminating this as
30153 a compatibility concern, but some other Ada 95 compilers reject these
30154 pragmas and attributes.
30155
30156 @item Specialized Needs Annexes
30157 GNAT implements the full set of special needs annexes.  At the
30158 current time, it is the only Ada 95 compiler to do so.  This means that
30159 programs making use of these features may not be portable to other Ada
30160 95 compilation systems.
30161
30162 @item Representation Clauses
30163 Some other Ada 95 compilers implement only the minimal set of
30164 representation clauses required by the Ada 95 reference manual.  GNAT goes
30165 far beyond this minimal set, as described in the next section.
30166 @end table
30167
30168 @node Representation Clauses
30169 @section Representation Clauses
30170
30171 @noindent
30172 The Ada 83 reference manual was quite vague in describing both the minimal
30173 required implementation of representation clauses, and also their precise
30174 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
30175 minimal set of capabilities required is still quite limited.
30176
30177 GNAT implements the full required set of capabilities in
30178 Ada 95 and Ada 2005, but also goes much further, and in particular
30179 an effort has been made to be compatible with existing Ada 83 usage to the
30180 greatest extent possible.
30181
30182 A few cases exist in which Ada 83 compiler behavior is incompatible with
30183 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
30184 intentional or accidental dependence on specific implementation dependent
30185 characteristics of these Ada 83 compilers.  The following is a list of
30186 the cases most likely to arise in existing Ada 83 code.
30187
30188 @table @emph
30189 @item Implicit Packing
30190 Some Ada 83 compilers allowed a Size specification to cause implicit
30191 packing of an array or record.  This could cause expensive implicit
30192 conversions for change of representation in the presence of derived
30193 types, and the Ada design intends to avoid this possibility.
30194 Subsequent AI's were issued to make it clear that such implicit
30195 change of representation in response to a Size clause is inadvisable,
30196 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
30197 Reference Manuals as implementation advice that is followed by GNAT@.
30198 The problem will show up as an error
30199 message rejecting the size clause.  The fix is simply to provide
30200 the explicit pragma @code{Pack}, or for more fine tuned control, provide
30201 a Component_Size clause.
30202
30203 @item Meaning of Size Attribute
30204 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
30205 the minimal number of bits required to hold values of the type.  For example,
30206 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
30207 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
30208 some 32 in this situation.  This problem will usually show up as a compile
30209 time error, but not always.  It is a good idea to check all uses of the
30210 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
30211 Object_Size can provide a useful way of duplicating the behavior of
30212 some Ada 83 compiler systems.
30213
30214 @item Size of Access Types
30215 A common assumption in Ada 83 code is that an access type is in fact a pointer,
30216 and that therefore it will be the same size as a System.Address value.  This
30217 assumption is true for GNAT in most cases with one exception.  For the case of
30218 a pointer to an unconstrained array type (where the bounds may vary from one
30219 value of the access type to another), the default is to use a ``fat pointer'',
30220 which is represented as two separate pointers, one to the bounds, and one to
30221 the array.  This representation has a number of advantages, including improved
30222 efficiency.  However, it may cause some difficulties in porting existing Ada 83
30223 code which makes the assumption that, for example, pointers fit in 32 bits on
30224 a machine with 32-bit addressing.
30225
30226 To get around this problem, GNAT also permits the use of ``thin pointers'' for
30227 access types in this case (where the designated type is an unconstrained array
30228 type).  These thin pointers are indeed the same size as a System.Address value.
30229 To specify a thin pointer, use a size clause for the type, for example:
30230
30231 @smallexample @c ada
30232 type X is access all String;
30233 for X'Size use Standard'Address_Size;
30234 @end smallexample
30235
30236 @noindent
30237 which will cause the type X to be represented using a single pointer.
30238 When using this representation, the bounds are right behind the array.
30239 This representation is slightly less efficient, and does not allow quite
30240 such flexibility in the use of foreign pointers or in using the
30241 Unrestricted_Access attribute to create pointers to non-aliased objects.
30242 But for any standard portable use of the access type it will work in
30243 a functionally correct manner and allow porting of existing code.
30244 Note that another way of forcing a thin pointer representation
30245 is to use a component size clause for the element size in an array,
30246 or a record representation clause for an access field in a record.
30247 @end table
30248
30249 @ifclear vms
30250 @c This brief section is only in the non-VMS version
30251 @c The complete chapter on HP Ada is in the VMS version
30252 @node Compatibility with HP Ada 83
30253 @section Compatibility with HP Ada 83
30254
30255 @noindent
30256 The VMS version of GNAT fully implements all the pragmas and attributes
30257 provided by HP Ada 83, as well as providing the standard HP Ada 83
30258 libraries, including Starlet.  In addition, data layouts and parameter
30259 passing conventions are highly compatible.  This means that porting
30260 existing HP Ada 83 code to GNAT in VMS systems should be easier than
30261 most other porting efforts.  The following are some of the most
30262 significant differences between GNAT and HP Ada 83.
30263
30264 @table @emph
30265 @item Default floating-point representation
30266 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
30267 it is VMS format.  GNAT does implement the necessary pragmas
30268 (Long_Float, Float_Representation) for changing this default.
30269
30270 @item System
30271 The package System in GNAT exactly corresponds to the definition in the
30272 Ada 95 reference manual, which means that it excludes many of the
30273 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
30274 that contains the additional definitions, and a special pragma,
30275 Extend_System allows this package to be treated transparently as an
30276 extension of package System.
30277
30278 @item To_Address
30279 The definitions provided by Aux_DEC are exactly compatible with those
30280 in the HP Ada 83 version of System, with one exception.
30281 HP Ada provides the following declarations:
30282
30283 @smallexample @c ada
30284 TO_ADDRESS (INTEGER)
30285 TO_ADDRESS (UNSIGNED_LONGWORD)
30286 TO_ADDRESS (@i{universal_integer})
30287 @end smallexample
30288
30289 @noindent
30290 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
30291 an extension to Ada 83 not strictly compatible with the reference manual.
30292 In GNAT, we are constrained to be exactly compatible with the standard,
30293 and this means we cannot provide this capability.  In HP Ada 83, the
30294 point of this definition is to deal with a call like:
30295
30296 @smallexample @c ada
30297 TO_ADDRESS (16#12777#);
30298 @end smallexample
30299
30300 @noindent
30301 Normally, according to the Ada 83 standard, one would expect this to be
30302 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
30303 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
30304 definition using @i{universal_integer} takes precedence.
30305
30306 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
30307 is not possible to be 100% compatible.  Since there are many programs using
30308 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
30309 to change the name of the function in the UNSIGNED_LONGWORD case, so the
30310 declarations provided in the GNAT version of AUX_Dec are:
30311
30312 @smallexample @c ada
30313 function To_Address (X : Integer) return Address;
30314 pragma Pure_Function (To_Address);
30315
30316 function To_Address_Long (X : Unsigned_Longword)
30317  return Address;
30318 pragma Pure_Function (To_Address_Long);
30319 @end smallexample
30320
30321 @noindent
30322 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
30323 change the name to TO_ADDRESS_LONG@.
30324
30325 @item Task_Id values
30326 The Task_Id values assigned will be different in the two systems, and GNAT
30327 does not provide a specified value for the Task_Id of the environment task,
30328 which in GNAT is treated like any other declared task.
30329 @end table
30330
30331 @noindent
30332 For full details on these and other less significant compatibility issues,
30333 see appendix E of the HP publication entitled @cite{HP Ada, Technical
30334 Overview and Comparison on HP Platforms}.
30335
30336 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
30337 attributes are recognized, although only a subset of them can sensibly
30338 be implemented.  The description of pragmas in @ref{Implementation
30339 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
30340 indicates whether or not they are applicable to non-VMS systems.
30341 @end ifclear
30342
30343 @ifset vms
30344 @node Transitioning to 64-Bit GNAT for OpenVMS
30345 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
30346
30347 @noindent
30348 This section is meant to assist users of pre-2006 @value{EDITION}
30349 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
30350 the version of the GNAT technology supplied in 2006 and later for
30351 OpenVMS on both Alpha and I64.
30352
30353 @menu
30354 * Introduction to transitioning::
30355 * Migration of 32 bit code::
30356 * Taking advantage of 64 bit addressing::
30357 * Technical details::
30358 @end menu
30359
30360 @node Introduction to transitioning
30361 @subsection Introduction
30362
30363 @noindent
30364 64-bit @value{EDITION} for Open VMS has been designed to meet
30365 three main goals:
30366
30367 @enumerate
30368 @item
30369 Providing a full conforming implementation of Ada 95 and Ada 2005
30370
30371 @item
30372 Allowing maximum backward compatibility, thus easing migration of existing
30373 Ada source code
30374
30375 @item
30376 Supplying a path for exploiting the full 64-bit address range
30377 @end enumerate
30378
30379 @noindent
30380 Ada's strong typing semantics has made it
30381 impractical to have different 32-bit and 64-bit modes. As soon as
30382 one object could possibly be outside the 32-bit address space, this
30383 would make it necessary for the @code{System.Address} type to be 64 bits.
30384 In particular, this would cause inconsistencies if 32-bit code is
30385 called from 64-bit code that raises an exception.
30386
30387 This issue has been resolved by always using 64-bit addressing
30388 at the system level, but allowing for automatic conversions between
30389 32-bit and 64-bit addresses where required. Thus users who
30390 do not currently require 64-bit addressing capabilities, can
30391 recompile their code with only minimal changes (and indeed
30392 if the code is written in portable Ada, with no assumptions about
30393 the size of the @code{Address} type, then no changes at all are necessary).
30394 At the same time,
30395 this approach provides a simple, gradual upgrade path to future
30396 use of larger memories than available for 32-bit systems.
30397 Also, newly written applications or libraries will by default
30398 be fully compatible with future systems exploiting 64-bit
30399 addressing capabilities.
30400
30401 @ref{Migration of 32 bit code}, will focus on porting applications
30402 that do not require more than 2 GB of
30403 addressable memory. This code will be referred to as
30404 @emph{32-bit code}.
30405 For applications intending to exploit the full 64-bit address space,
30406 @ref{Taking advantage of 64 bit addressing},
30407 will consider further changes that may be required.
30408 Such code will be referred to below as @emph{64-bit code}.
30409
30410 @node Migration of 32 bit code
30411 @subsection Migration of 32-bit code
30412
30413 @menu
30414 * Address types::
30415 * Access types::
30416 * Unchecked conversions::
30417 * Predefined constants::
30418 * Interfacing with C::
30419 * Experience with source compatibility::
30420 @end menu
30421
30422 @node Address types
30423 @subsubsection Address types
30424
30425 @noindent
30426 To solve the problem of mixing 64-bit and 32-bit addressing,
30427 while maintaining maximum backward compatibility, the following
30428 approach has been taken:
30429
30430 @itemize @bullet
30431 @item
30432 @code{System.Address} always has a size of 64 bits
30433
30434 @item
30435 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
30436 @end itemize
30437
30438 @noindent
30439 Since @code{System.Short_Address} is a subtype of @code{System.Address},
30440 a @code{Short_Address}
30441 may be used where an @code{Address} is required, and vice versa, without
30442 needing explicit type conversions.
30443 By virtue of the Open VMS parameter passing conventions,
30444 even imported
30445 and exported subprograms that have 32-bit address parameters are
30446 compatible with those that have 64-bit address parameters.
30447 (See @ref{Making code 64 bit clean} for details.)
30448
30449 The areas that may need attention are those where record types have
30450 been defined that contain components of the type @code{System.Address}, and
30451 where objects of this type are passed to code expecting a record layout with
30452 32-bit addresses.
30453
30454 Different compilers on different platforms cannot be
30455 expected to represent the same type in the same way,
30456 since alignment constraints
30457 and other system-dependent properties affect the compiler's decision.
30458 For that reason, Ada code
30459 generally uses representation clauses to specify the expected
30460 layout where required.
30461
30462 If such a representation clause uses 32 bits for a component having
30463 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
30464 will detect that error and produce a specific diagnostic message.
30465 The developer should then determine whether the representation
30466 should be 64 bits or not and make either of two changes:
30467 change the size to 64 bits and leave the type as @code{System.Address}, or
30468 leave the size as 32 bits and change the type to @code{System.Short_Address}.
30469 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
30470 required in any code setting or accessing the field; the compiler will
30471 automatically perform any needed conversions between address
30472 formats.
30473
30474 @node Access types
30475 @subsubsection Access types
30476
30477 @noindent
30478 By default, objects designated by access values are always
30479 allocated in the 32-bit
30480 address space. Thus legacy code will never contain
30481 any objects that are not addressable with 32-bit addresses, and
30482 the compiler will never raise exceptions as result of mixing
30483 32-bit and 64-bit addresses.
30484
30485 However, the access values themselves are represented in 64 bits, for optimum
30486 performance and future compatibility with 64-bit code. As was
30487 the case with @code{System.Address}, the compiler will give an error message
30488 if an object or record component has a representation clause that
30489 requires the access value to fit in 32 bits. In such a situation,
30490 an explicit size clause for the access type, specifying 32 bits,
30491 will have the desired effect.
30492
30493 General access types (declared with @code{access all}) can never be
30494 32 bits, as values of such types must be able to refer to any object
30495 of the  designated type,
30496 including objects residing outside the 32-bit address range.
30497 Existing Ada 83 code will not contain such type definitions,
30498 however, since general access types were introduced in Ada 95.
30499
30500 @node Unchecked conversions
30501 @subsubsection Unchecked conversions
30502
30503 @noindent
30504 In the case of an @code{Unchecked_Conversion} where the source type is a
30505 64-bit access type or the type @code{System.Address}, and the target
30506 type is a 32-bit type, the compiler will generate a warning.
30507 Even though the generated code will still perform the required
30508 conversions, it is highly recommended in these cases to use
30509 respectively a 32-bit access type or @code{System.Short_Address}
30510 as the source type.
30511
30512 @node Predefined constants
30513 @subsubsection Predefined constants
30514
30515 @noindent
30516 The following table shows the correspondence between pre-2006 versions of
30517 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
30518 (``New''):
30519
30520 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
30521 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
30522 @item   @code{System.Word_Size}          @tab 32      @tab 64
30523 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
30524 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
30525 @item   @code{System.Address_Size}       @tab 32      @tab 64
30526 @end multitable
30527
30528 @noindent
30529 If you need to refer to the specific
30530 memory size of a 32-bit implementation, instead of the
30531 actual memory size, use @code{System.Short_Memory_Size}
30532 rather than @code{System.Memory_Size}.
30533 Similarly, references to @code{System.Address_Size} may need
30534 to be replaced by @code{System.Short_Address'Size}.
30535 The program @command{gnatfind} may be useful for locating
30536 references to the above constants, so that you can verify that they
30537 are still correct.
30538
30539 @node Interfacing with C
30540 @subsubsection Interfacing with C
30541
30542 @noindent
30543 In order to minimize the impact of the transition to 64-bit addresses on
30544 legacy programs, some fundamental types in the @code{Interfaces.C}
30545 package hierarchy continue to be represented in 32 bits.
30546 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
30547 This eases integration with the default HP C layout choices, for example
30548 as found in the system routines in @code{DECC$SHR.EXE}.
30549 Because of this implementation choice, the type fully compatible with
30550 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
30551 Depending on the context the compiler will issue a
30552 warning or an error when type @code{Address} is used, alerting the user to a
30553 potential problem. Otherwise 32-bit programs that use
30554 @code{Interfaces.C} should normally not require code modifications
30555
30556 The other issue arising with C interfacing concerns pragma @code{Convention}.
30557 For VMS 64-bit systems, there is an issue of the appropriate default size
30558 of C convention pointers in the absence of an explicit size clause. The HP
30559 C compiler can choose either 32 or 64 bits depending on compiler options.
30560 GNAT chooses 32-bits rather than 64-bits in the default case where no size
30561 clause is given. This proves a better choice for porting 32-bit legacy
30562 applications. In order to have a 64-bit representation, it is necessary to
30563 specify a size representation clause. For example:
30564
30565 @smallexample @c ada
30566 type int_star is access Interfaces.C.int;
30567 pragma Convention(C, int_star);
30568 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
30569 @end smallexample
30570
30571 @node Experience with source compatibility
30572 @subsubsection Experience with source compatibility
30573
30574 @noindent
30575 The Security Server and STARLET on I64 provide an interesting ``test case''
30576 for source compatibility issues, since it is in such system code
30577 where assumptions about @code{Address} size might be expected to occur.
30578 Indeed, there were a small number of occasions in the Security Server
30579 file @file{jibdef.ads}
30580 where a representation clause for a record type specified
30581 32 bits for a component of type @code{Address}.
30582 All of these errors were detected by the compiler.
30583 The repair was obvious and immediate; to simply replace @code{Address} by
30584 @code{Short_Address}.
30585
30586 In the case of STARLET, there were several record types that should
30587 have had representation clauses but did not.  In these record types
30588 there was an implicit assumption that an @code{Address} value occupied
30589 32 bits.
30590 These compiled without error, but their usage resulted in run-time error
30591 returns from STARLET system calls.
30592 Future GNAT technology enhancements may include a tool that detects and flags
30593 these sorts of potential source code porting problems.
30594
30595 @c ****************************************
30596 @node Taking advantage of 64 bit addressing
30597 @subsection Taking advantage of 64-bit addressing
30598
30599 @menu
30600 * Making code 64 bit clean::
30601 * Allocating memory from the 64 bit storage pool::
30602 * Restrictions on use of 64 bit objects::
30603 * Using 64 bit storage pools by default::
30604 * General access types::
30605 * STARLET and other predefined libraries::
30606 @end menu
30607
30608 @node Making code 64 bit clean
30609 @subsubsection Making code 64-bit clean
30610
30611 @noindent
30612 In order to prevent problems that may occur when (parts of) a
30613 system start using memory outside the 32-bit address range,
30614 we recommend some additional guidelines:
30615
30616 @itemize @bullet
30617 @item
30618 For imported subprograms that take parameters of the
30619 type @code{System.Address}, ensure that these subprograms can
30620 indeed handle 64-bit addresses. If not, or when in doubt,
30621 change the subprogram declaration to specify
30622 @code{System.Short_Address} instead.
30623
30624 @item
30625 Resolve all warnings related to size mismatches in
30626 unchecked conversions. Failing to do so causes
30627 erroneous execution if the source object is outside
30628 the 32-bit address space.
30629
30630 @item
30631 (optional) Explicitly use the 32-bit storage pool
30632 for access types used in a 32-bit context, or use
30633 generic access types where possible
30634 (@pxref{Restrictions on use of 64 bit objects}).
30635 @end itemize
30636
30637 @noindent
30638 If these rules are followed, the compiler will automatically insert
30639 any necessary checks to ensure that no addresses or access values
30640 passed to 32-bit code ever refer to objects outside the 32-bit
30641 address range.
30642 Any attempt to do this will raise @code{Constraint_Error}.
30643
30644 @node Allocating memory from the 64 bit storage pool
30645 @subsubsection Allocating memory from the 64-bit storage pool
30646
30647 @noindent
30648 For any access type @code{T} that potentially requires memory allocations
30649 beyond the 32-bit address space,
30650 use the following representation clause:
30651
30652 @smallexample @c ada
30653    for T'Storage_Pool use System.Pool_64;
30654 @end smallexample
30655
30656 @node Restrictions on use of 64 bit objects
30657 @subsubsection Restrictions on use of 64-bit objects
30658
30659 @noindent
30660 Taking the address of an object allocated from a 64-bit storage pool,
30661 and then passing this address to a subprogram expecting
30662 @code{System.Short_Address},
30663 or assigning it to a variable of type @code{Short_Address}, will cause
30664 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
30665 (@pxref{Making code 64 bit clean}), or checks are suppressed,
30666 no exception is raised and execution
30667 will become erroneous.
30668
30669 @node Using 64 bit storage pools by default
30670 @subsubsection Using 64-bit storage pools by default
30671
30672 @noindent
30673 In some cases it may be desirable to have the compiler allocate
30674 from 64-bit storage pools by default. This may be the case for
30675 libraries that are 64-bit clean, but may be used in both 32-bit
30676 and 64-bit contexts. For these cases the following configuration
30677 pragma may be specified:
30678
30679 @smallexample @c ada
30680   pragma Pool_64_Default;
30681 @end smallexample
30682
30683 @noindent
30684 Any code compiled in the context of this pragma will by default
30685 use the @code{System.Pool_64} storage pool. This default may be overridden
30686 for a specific access type @code{T} by the representation clause:
30687
30688 @smallexample @c ada
30689    for T'Storage_Pool use System.Pool_32;
30690 @end smallexample
30691
30692 @noindent
30693 Any object whose address may be passed to a subprogram with a
30694 @code{Short_Address} argument, or assigned to a variable of type
30695 @code{Short_Address}, needs to be allocated from this pool.
30696
30697 @node General access types
30698 @subsubsection General access types
30699
30700 @noindent
30701 Objects designated by access values from a
30702 general access type (declared with @code{access all}) are never allocated
30703 from a 64-bit storage pool. Code that uses general access types will
30704 accept objects allocated in either 32-bit or 64-bit address spaces,
30705 but never allocate objects outside the 32-bit address space.
30706 Using general access types ensures maximum compatibility with both
30707 32-bit and 64-bit code.
30708
30709 @node STARLET and other predefined libraries
30710 @subsubsection STARLET and other predefined libraries
30711
30712 @noindent
30713 All code that comes as part of GNAT is 64-bit clean, but the
30714 restrictions given in @ref{Restrictions on use of 64 bit objects},
30715 still apply. Look at the package
30716 specs to see in which contexts objects allocated
30717 in 64-bit address space are acceptable.
30718
30719 @node Technical details
30720 @subsection Technical details
30721
30722 @noindent
30723 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
30724 Ada standard with respect to the type of @code{System.Address}. Previous
30725 versions of GNAT Pro have defined this type as private and implemented it as a
30726 modular type.
30727
30728 In order to allow defining @code{System.Short_Address} as a proper subtype,
30729 and to match the implicit sign extension in parameter passing,
30730 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
30731 visible (i.e., non-private) integer type.
30732 Standard operations on the type, such as the binary operators ``+'', ``-'',
30733 etc., that take @code{Address} operands and return an @code{Address} result,
30734 have been hidden by declaring these
30735 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
30736 ambiguities that would otherwise result from overloading.
30737 (Note that, although @code{Address} is a visible integer type,
30738 good programming practice dictates against exploiting the type's
30739 integer properties such as literals, since this will compromise
30740 code portability.)
30741
30742 Defining @code{Address} as a visible integer type helps achieve
30743 maximum compatibility for existing Ada code,
30744 without sacrificing the capabilities of the 64-bit architecture.
30745 @end ifset
30746
30747 @c ************************************************
30748 @ifset unw
30749 @node Microsoft Windows Topics
30750 @appendix Microsoft Windows Topics
30751 @cindex Windows NT
30752 @cindex Windows 95
30753 @cindex Windows 98
30754
30755 @noindent
30756 This chapter describes topics that are specific to the Microsoft Windows
30757 platforms (NT, 2000, and XP Professional).
30758
30759 @menu
30760 * Using GNAT on Windows::
30761 * Using a network installation of GNAT::
30762 * CONSOLE and WINDOWS subsystems::
30763 * Temporary Files::
30764 * Mixed-Language Programming on Windows::
30765 * Windows Calling Conventions::
30766 * Introduction to Dynamic Link Libraries (DLLs)::
30767 * Using DLLs with GNAT::
30768 * Building DLLs with GNAT::
30769 * Building DLLs with GNAT Project files::
30770 * Building DLLs with gnatdll::
30771 * GNAT and Windows Resources::
30772 * Debugging a DLL::
30773 * Setting Stack Size from gnatlink::
30774 * Setting Heap Size from gnatlink::
30775 @end menu
30776
30777 @node Using GNAT on Windows
30778 @section Using GNAT on Windows
30779
30780 @noindent
30781 One of the strengths of the GNAT technology is that its tool set
30782 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
30783 @code{gdb} debugger, etc.) is used in the same way regardless of the
30784 platform.
30785
30786 On Windows this tool set is complemented by a number of Microsoft-specific
30787 tools that have been provided to facilitate interoperability with Windows
30788 when this is required. With these tools:
30789
30790 @itemize @bullet
30791
30792 @item
30793 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
30794 subsystems.
30795
30796 @item
30797 You can use any Dynamically Linked Library (DLL) in your Ada code (both
30798 relocatable and non-relocatable DLLs are supported).
30799
30800 @item
30801 You can build Ada DLLs for use in other applications. These applications
30802 can be written in a language other than Ada (e.g., C, C++, etc). Again both
30803 relocatable and non-relocatable Ada DLLs are supported.
30804
30805 @item
30806 You can include Windows resources in your Ada application.
30807
30808 @item
30809 You can use or create COM/DCOM objects.
30810 @end itemize
30811
30812 @noindent
30813 Immediately below are listed all known general GNAT-for-Windows restrictions.
30814 Other restrictions about specific features like Windows Resources and DLLs
30815 are listed in separate sections below.
30816
30817 @itemize @bullet
30818
30819 @item
30820 It is not possible to use @code{GetLastError} and @code{SetLastError}
30821 when tasking, protected records, or exceptions are used. In these
30822 cases, in order to implement Ada semantics, the GNAT run-time system
30823 calls certain Win32 routines that set the last error variable to 0 upon
30824 success. It should be possible to use @code{GetLastError} and
30825 @code{SetLastError} when tasking, protected record, and exception
30826 features are not used, but it is not guaranteed to work.
30827
30828 @item
30829 It is not possible to link against Microsoft libraries except for
30830 import libraries. The library must be built to be compatible with
30831 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
30832 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
30833 not be compatible with the GNAT runtime. Even if the library is
30834 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
30835
30836 @item
30837 When the compilation environment is located on FAT32 drives, users may
30838 experience recompilations of the source files that have not changed if
30839 Daylight Saving Time (DST) state has changed since the last time files
30840 were compiled. NTFS drives do not have this problem.
30841
30842 @item
30843 No components of the GNAT toolset use any entries in the Windows
30844 registry. The only entries that can be created are file associations and
30845 PATH settings, provided the user has chosen to create them at installation
30846 time, as well as some minimal book-keeping information needed to correctly
30847 uninstall or integrate different GNAT products.
30848 @end itemize
30849
30850 @node Using a network installation of GNAT
30851 @section Using a network installation of GNAT
30852
30853 @noindent
30854 Make sure the system on which GNAT is installed is accessible from the
30855 current machine, i.e., the install location is shared over the network.
30856 Shared resources are accessed on Windows by means of UNC paths, which
30857 have the format @code{\\server\sharename\path}
30858
30859 In order to use such a network installation, simply add the UNC path of the
30860 @file{bin} directory of your GNAT installation in front of your PATH. For
30861 example, if GNAT is installed in @file{\GNAT} directory of a share location
30862 called @file{c-drive} on a machine @file{LOKI}, the following command will
30863 make it available:
30864
30865 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
30866
30867 Be aware that every compilation using the network installation results in the
30868 transfer of large amounts of data across the network and will likely cause
30869 serious performance penalty.
30870
30871 @node CONSOLE and WINDOWS subsystems
30872 @section CONSOLE and WINDOWS subsystems
30873 @cindex CONSOLE Subsystem
30874 @cindex WINDOWS Subsystem
30875 @cindex -mwindows
30876
30877 @noindent
30878 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
30879 (which is the default subsystem) will always create a console when
30880 launching the application. This is not something desirable when the
30881 application has a Windows GUI. To get rid of this console the
30882 application must be using the @code{WINDOWS} subsystem. To do so
30883 the @option{-mwindows} linker option must be specified.
30884
30885 @smallexample
30886 $ gnatmake winprog -largs -mwindows
30887 @end smallexample
30888
30889 @node Temporary Files
30890 @section Temporary Files
30891 @cindex Temporary files
30892
30893 @noindent
30894 It is possible to control where temporary files gets created by setting
30895 the @env{TMP} environment variable. The file will be created:
30896
30897 @itemize
30898 @item Under the directory pointed to by the @env{TMP} environment variable if
30899 this directory exists.
30900
30901 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
30902 set (or not pointing to a directory) and if this directory exists.
30903
30904 @item Under the current working directory otherwise.
30905 @end itemize
30906
30907 @noindent
30908 This allows you to determine exactly where the temporary
30909 file will be created. This is particularly useful in networked
30910 environments where you may not have write access to some
30911 directories.
30912
30913 @node Mixed-Language Programming on Windows
30914 @section Mixed-Language Programming on Windows
30915
30916 @noindent
30917 Developing pure Ada applications on Windows is no different than on
30918 other GNAT-supported platforms. However, when developing or porting an
30919 application that contains a mix of Ada and C/C++, the choice of your
30920 Windows C/C++ development environment conditions your overall
30921 interoperability strategy.
30922
30923 If you use @command{gcc} to compile the non-Ada part of your application,
30924 there are no Windows-specific restrictions that affect the overall
30925 interoperability with your Ada code. If you plan to use
30926 Microsoft tools (e.g.@: Microsoft Visual C/C++), you should be aware of
30927 the following limitations:
30928
30929 @itemize @bullet
30930 @item
30931 You cannot link your Ada code with an object or library generated with
30932 Microsoft tools if these use the @code{.tls} section (Thread Local
30933 Storage section) since the GNAT linker does not yet support this section.
30934
30935 @item
30936 You cannot link your Ada code with an object or library generated with
30937 Microsoft tools if these use I/O routines other than those provided in
30938 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
30939 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
30940 libraries can cause a conflict with @code{msvcrt.dll} services. For
30941 instance Visual C++ I/O stream routines conflict with those in
30942 @code{msvcrt.dll}.
30943 @end itemize
30944
30945 @noindent
30946 If you do want to use the Microsoft tools for your non-Ada code and hit one
30947 of the above limitations, you have two choices:
30948
30949 @enumerate
30950 @item
30951 Encapsulate your non-Ada code in a DLL to be linked with your Ada
30952 application. In this case, use the Microsoft or whatever environment to
30953 build the DLL and use GNAT to build your executable
30954 (@pxref{Using DLLs with GNAT}).
30955
30956 @item
30957 Or you can encapsulate your Ada code in a DLL to be linked with the
30958 other part of your application. In this case, use GNAT to build the DLL
30959 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
30960 environment to build your executable.
30961 @end enumerate
30962
30963 @node Windows Calling Conventions
30964 @section Windows Calling Conventions
30965 @findex Stdcall
30966 @findex APIENTRY
30967
30968 @menu
30969 * C Calling Convention::
30970 * Stdcall Calling Convention::
30971 * Win32 Calling Convention::
30972 * DLL Calling Convention::
30973 @end menu
30974
30975 @noindent
30976 When a subprogram @code{F} (caller) calls a subprogram @code{G}
30977 (callee), there are several ways to push @code{G}'s parameters on the
30978 stack and there are several possible scenarios to clean up the stack
30979 upon @code{G}'s return. A calling convention is an agreed upon software
30980 protocol whereby the responsibilities between the caller (@code{F}) and
30981 the callee (@code{G}) are clearly defined. Several calling conventions
30982 are available for Windows:
30983
30984 @itemize @bullet
30985 @item
30986 @code{C} (Microsoft defined)
30987
30988 @item
30989 @code{Stdcall} (Microsoft defined)
30990
30991 @item
30992 @code{Win32} (GNAT specific)
30993
30994 @item
30995 @code{DLL} (GNAT specific)
30996 @end itemize
30997
30998 @node C Calling Convention
30999 @subsection @code{C} Calling Convention
31000
31001 @noindent
31002 This is the default calling convention used when interfacing to C/C++
31003 routines compiled with either @command{gcc} or Microsoft Visual C++.
31004
31005 In the @code{C} calling convention subprogram parameters are pushed on the
31006 stack by the caller from right to left. The caller itself is in charge of
31007 cleaning up the stack after the call. In addition, the name of a routine
31008 with @code{C} calling convention is mangled by adding a leading underscore.
31009
31010 The name to use on the Ada side when importing (or exporting) a routine
31011 with @code{C} calling convention is the name of the routine. For
31012 instance the C function:
31013
31014 @smallexample
31015 int get_val (long);
31016 @end smallexample
31017
31018 @noindent
31019 should be imported from Ada as follows:
31020
31021 @smallexample @c ada
31022 @group
31023 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31024 pragma Import (C, Get_Val, External_Name => "get_val");
31025 @end group
31026 @end smallexample
31027
31028 @noindent
31029 Note that in this particular case the @code{External_Name} parameter could
31030 have been omitted since, when missing, this parameter is taken to be the
31031 name of the Ada entity in lower case. When the @code{Link_Name} parameter
31032 is missing, as in the above example, this parameter is set to be the
31033 @code{External_Name} with a leading underscore.
31034
31035 When importing a variable defined in C, you should always use the @code{C}
31036 calling convention unless the object containing the variable is part of a
31037 DLL (in which case you should use the @code{Stdcall} calling
31038 convention, @pxref{Stdcall Calling Convention}).
31039
31040 @node Stdcall Calling Convention
31041 @subsection @code{Stdcall} Calling Convention
31042
31043 @noindent
31044 This convention, which was the calling convention used for Pascal
31045 programs, is used by Microsoft for all the routines in the Win32 API for
31046 efficiency reasons. It must be used to import any routine for which this
31047 convention was specified.
31048
31049 In the @code{Stdcall} calling convention subprogram parameters are pushed
31050 on the stack by the caller from right to left. The callee (and not the
31051 caller) is in charge of cleaning the stack on routine exit. In addition,
31052 the name of a routine with @code{Stdcall} calling convention is mangled by
31053 adding a leading underscore (as for the @code{C} calling convention) and a
31054 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
31055 bytes) of the parameters passed to the routine.
31056
31057 The name to use on the Ada side when importing a C routine with a
31058 @code{Stdcall} calling convention is the name of the C routine. The leading
31059 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
31060 the compiler. For instance the Win32 function:
31061
31062 @smallexample
31063 @b{APIENTRY} int get_val (long);
31064 @end smallexample
31065
31066 @noindent
31067 should be imported from Ada as follows:
31068
31069 @smallexample @c ada
31070 @group
31071 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31072 pragma Import (Stdcall, Get_Val);
31073 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
31074 @end group
31075 @end smallexample
31076
31077 @noindent
31078 As for the @code{C} calling convention, when the @code{External_Name}
31079 parameter is missing, it is taken to be the name of the Ada entity in lower
31080 case. If instead of writing the above import pragma you write:
31081
31082 @smallexample @c ada
31083 @group
31084 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31085 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
31086 @end group
31087 @end smallexample
31088
31089 @noindent
31090 then the imported routine is @code{_retrieve_val@@4}. However, if instead
31091 of specifying the @code{External_Name} parameter you specify the
31092 @code{Link_Name} as in the following example:
31093
31094 @smallexample @c ada
31095 @group
31096 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
31097 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
31098 @end group
31099 @end smallexample
31100
31101 @noindent
31102 then the imported routine is @code{retrieve_val}, that is, there is no
31103 decoration at all. No leading underscore and no Stdcall suffix
31104 @code{@@}@code{@var{nn}}.
31105
31106 @noindent
31107 This is especially important as in some special cases a DLL's entry
31108 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
31109 name generated for a call has it.
31110
31111 @noindent
31112 It is also possible to import variables defined in a DLL by using an
31113 import pragma for a variable. As an example, if a DLL contains a
31114 variable defined as:
31115
31116 @smallexample
31117 int my_var;
31118 @end smallexample
31119
31120 @noindent
31121 then, to access this variable from Ada you should write:
31122
31123 @smallexample @c ada
31124 @group
31125 My_Var : Interfaces.C.int;
31126 pragma Import (Stdcall, My_Var);
31127 @end group
31128 @end smallexample
31129
31130 @noindent
31131 Note that to ease building cross-platform bindings this convention
31132 will be handled as a @code{C} calling convention on non-Windows platforms.
31133
31134 @node Win32 Calling Convention
31135 @subsection @code{Win32} Calling Convention
31136
31137 @noindent
31138 This convention, which is GNAT-specific is fully equivalent to the
31139 @code{Stdcall} calling convention described above.
31140
31141 @node DLL Calling Convention
31142 @subsection @code{DLL} Calling Convention
31143
31144 @noindent
31145 This convention, which is GNAT-specific is fully equivalent to the
31146 @code{Stdcall} calling convention described above.
31147
31148 @node Introduction to Dynamic Link Libraries (DLLs)
31149 @section Introduction to Dynamic Link Libraries (DLLs)
31150 @findex DLL
31151
31152 @noindent
31153 A Dynamically Linked Library (DLL) is a library that can be shared by
31154 several applications running under Windows. A DLL can contain any number of
31155 routines and variables.
31156
31157 One advantage of DLLs is that you can change and enhance them without
31158 forcing all the applications that depend on them to be relinked or
31159 recompiled. However, you should be aware than all calls to DLL routines are
31160 slower since, as you will understand below, such calls are indirect.
31161
31162 To illustrate the remainder of this section, suppose that an application
31163 wants to use the services of a DLL @file{API.dll}. To use the services
31164 provided by @file{API.dll} you must statically link against the DLL or
31165 an import library which contains a jump table with an entry for each
31166 routine and variable exported by the DLL. In the Microsoft world this
31167 import library is called @file{API.lib}. When using GNAT this import
31168 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
31169 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
31170
31171 After you have linked your application with the DLL or the import library
31172 and you run your application, here is what happens:
31173
31174 @enumerate
31175 @item
31176 Your application is loaded into memory.
31177
31178 @item
31179 The DLL @file{API.dll} is mapped into the address space of your
31180 application. This means that:
31181
31182 @itemize @bullet
31183 @item
31184 The DLL will use the stack of the calling thread.
31185
31186 @item
31187 The DLL will use the virtual address space of the calling process.
31188
31189 @item
31190 The DLL will allocate memory from the virtual address space of the calling
31191 process.
31192
31193 @item
31194 Handles (pointers) can be safely exchanged between routines in the DLL
31195 routines and routines in the application using the DLL.
31196 @end itemize
31197
31198 @item
31199 The entries in the jump table (from the import library @file{libAPI.dll.a}
31200 or @file{API.lib} or automatically created when linking against a DLL)
31201 which is part of your application are initialized with the addresses
31202 of the routines and variables in @file{API.dll}.
31203
31204 @item
31205 If present in @file{API.dll}, routines @code{DllMain} or
31206 @code{DllMainCRTStartup} are invoked. These routines typically contain
31207 the initialization code needed for the well-being of the routines and
31208 variables exported by the DLL.
31209 @end enumerate
31210
31211 @noindent
31212 There is an additional point which is worth mentioning. In the Windows
31213 world there are two kind of DLLs: relocatable and non-relocatable
31214 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
31215 in the target application address space. If the addresses of two
31216 non-relocatable DLLs overlap and these happen to be used by the same
31217 application, a conflict will occur and the application will run
31218 incorrectly. Hence, when possible, it is always preferable to use and
31219 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
31220 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
31221 User's Guide) removes the debugging symbols from the DLL but the DLL can
31222 still be relocated.
31223
31224 As a side note, an interesting difference between Microsoft DLLs and
31225 Unix shared libraries, is the fact that on most Unix systems all public
31226 routines are exported by default in a Unix shared library, while under
31227 Windows it is possible (but not required) to list exported routines in
31228 a definition file (@pxref{The Definition File}).
31229
31230 @node Using DLLs with GNAT
31231 @section Using DLLs with GNAT
31232
31233 @menu
31234 * Creating an Ada Spec for the DLL Services::
31235 * Creating an Import Library::
31236 @end menu
31237
31238 @noindent
31239 To use the services of a DLL, say @file{API.dll}, in your Ada application
31240 you must have:
31241
31242 @enumerate
31243 @item
31244 The Ada spec for the routines and/or variables you want to access in
31245 @file{API.dll}. If not available this Ada spec must be built from the C/C++
31246 header files provided with the DLL.
31247
31248 @item
31249 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
31250 mentioned an import library is a statically linked library containing the
31251 import table which will be filled at load time to point to the actual
31252 @file{API.dll} routines. Sometimes you don't have an import library for the
31253 DLL you want to use. The following sections will explain how to build
31254 one. Note that this is optional.
31255
31256 @item
31257 The actual DLL, @file{API.dll}.
31258 @end enumerate
31259
31260 @noindent
31261 Once you have all the above, to compile an Ada application that uses the
31262 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
31263 you simply issue the command
31264
31265 @smallexample
31266 $ gnatmake my_ada_app -largs -lAPI
31267 @end smallexample
31268
31269 @noindent
31270 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
31271 tells the GNAT linker to look first for a library named @file{API.lib}
31272 (Microsoft-style name) and if not found for a libraries named
31273 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
31274 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
31275 contains the following pragma
31276
31277 @smallexample @c ada
31278 pragma Linker_Options ("-lAPI");
31279 @end smallexample
31280
31281 @noindent
31282 you do not have to add @option{-largs -lAPI} at the end of the
31283 @command{gnatmake} command.
31284
31285 If any one of the items above is missing you will have to create it
31286 yourself. The following sections explain how to do so using as an
31287 example a fictitious DLL called @file{API.dll}.
31288
31289 @node Creating an Ada Spec for the DLL Services
31290 @subsection Creating an Ada Spec for the DLL Services
31291
31292 @noindent
31293 A DLL typically comes with a C/C++ header file which provides the
31294 definitions of the routines and variables exported by the DLL. The Ada
31295 equivalent of this header file is a package spec that contains definitions
31296 for the imported entities. If the DLL you intend to use does not come with
31297 an Ada spec you have to generate one such spec yourself. For example if
31298 the header file of @file{API.dll} is a file @file{api.h} containing the
31299 following two definitions:
31300
31301 @smallexample
31302 @group
31303 @cartouche
31304 int some_var;
31305 int get (char *);
31306 @end cartouche
31307 @end group
31308 @end smallexample
31309
31310 @noindent
31311 then the equivalent Ada spec could be:
31312
31313 @smallexample @c ada
31314 @group
31315 @cartouche
31316 with Interfaces.C.Strings;
31317 package API is
31318    use Interfaces;
31319
31320    Some_Var : C.int;
31321    function Get (Str : C.Strings.Chars_Ptr) return C.int;
31322
31323 private
31324    pragma Import (C, Get);
31325    pragma Import (DLL, Some_Var);
31326 end API;
31327 @end cartouche
31328 @end group
31329 @end smallexample
31330
31331 @noindent
31332 Note that a variable is
31333 @strong{always imported with a Stdcall convention}. A function
31334 can have @code{C} or @code{Stdcall} convention.
31335 (@pxref{Windows Calling Conventions}).
31336
31337 @node Creating an Import Library
31338 @subsection Creating an Import Library
31339 @cindex Import library
31340
31341 @menu
31342 * The Definition File::
31343 * GNAT-Style Import Library::
31344 * Microsoft-Style Import Library::
31345 @end menu
31346
31347 @noindent
31348 If a Microsoft-style import library @file{API.lib} or a GNAT-style
31349 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
31350 with @file{API.dll} you can skip this section. You can also skip this
31351 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
31352 as in this case it is possible to link directly against the
31353 DLL. Otherwise read on.
31354
31355 @node The Definition File
31356 @subsubsection The Definition File
31357 @cindex Definition file
31358 @findex .def
31359
31360 @noindent
31361 As previously mentioned, and unlike Unix systems, the list of symbols
31362 that are exported from a DLL must be provided explicitly in Windows.
31363 The main goal of a definition file is precisely that: list the symbols
31364 exported by a DLL. A definition file (usually a file with a @code{.def}
31365 suffix) has the following structure:
31366
31367 @smallexample
31368 @group
31369 @cartouche
31370 @r{[}LIBRARY @var{name}@r{]}
31371 @r{[}DESCRIPTION @var{string}@r{]}
31372 EXPORTS
31373    @var{symbol1}
31374    @var{symbol2}
31375    @dots{}
31376 @end cartouche
31377 @end group
31378 @end smallexample
31379
31380 @table @code
31381 @item LIBRARY @var{name}
31382 This section, which is optional, gives the name of the DLL.
31383
31384 @item DESCRIPTION @var{string}
31385 This section, which is optional, gives a description string that will be
31386 embedded in the import library.
31387
31388 @item EXPORTS
31389 This section gives the list of exported symbols (procedures, functions or
31390 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
31391 section of @file{API.def} looks like:
31392
31393 @smallexample
31394 @group
31395 @cartouche
31396 EXPORTS
31397    some_var
31398    get
31399 @end cartouche
31400 @end group
31401 @end smallexample
31402 @end table
31403
31404 @noindent
31405 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
31406 (@pxref{Windows Calling Conventions}) for a Stdcall
31407 calling convention function in the exported symbols list.
31408
31409 @noindent
31410 There can actually be other sections in a definition file, but these
31411 sections are not relevant to the discussion at hand.
31412
31413 @node GNAT-Style Import Library
31414 @subsubsection GNAT-Style Import Library
31415
31416 @noindent
31417 To create a static import library from @file{API.dll} with the GNAT tools
31418 you should proceed as follows:
31419
31420 @enumerate
31421 @item
31422 Create the definition file @file{API.def} (@pxref{The Definition File}).
31423 For that use the @code{dll2def} tool as follows:
31424
31425 @smallexample
31426 $ dll2def API.dll > API.def
31427 @end smallexample
31428
31429 @noindent
31430 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
31431 to standard output the list of entry points in the DLL. Note that if
31432 some routines in the DLL have the @code{Stdcall} convention
31433 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
31434 suffix then you'll have to edit @file{api.def} to add it, and specify
31435 @option{-k} to @command{gnatdll} when creating the import library.
31436
31437 @noindent
31438 Here are some hints to find the right @code{@@}@var{nn} suffix.
31439
31440 @enumerate
31441 @item
31442 If you have the Microsoft import library (.lib), it is possible to get
31443 the right symbols by using Microsoft @code{dumpbin} tool (see the
31444 corresponding Microsoft documentation for further details).
31445
31446 @smallexample
31447 $ dumpbin /exports api.lib
31448 @end smallexample
31449
31450 @item
31451 If you have a message about a missing symbol at link time the compiler
31452 tells you what symbol is expected. You just have to go back to the
31453 definition file and add the right suffix.
31454 @end enumerate
31455
31456 @item
31457 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
31458 (@pxref{Using gnatdll}) as follows:
31459
31460 @smallexample
31461 $ gnatdll -e API.def -d API.dll
31462 @end smallexample
31463
31464 @noindent
31465 @code{gnatdll} takes as input a definition file @file{API.def} and the
31466 name of the DLL containing the services listed in the definition file
31467 @file{API.dll}. The name of the static import library generated is
31468 computed from the name of the definition file as follows: if the
31469 definition file name is @var{xyz}@code{.def}, the import library name will
31470 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
31471 @option{-e} could have been removed because the name of the definition
31472 file (before the ``@code{.def}'' suffix) is the same as the name of the
31473 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
31474 @end enumerate
31475
31476 @node Microsoft-Style Import Library
31477 @subsubsection Microsoft-Style Import Library
31478
31479 @noindent
31480 With GNAT you can either use a GNAT-style or Microsoft-style import
31481 library. A Microsoft import library is needed only if you plan to make an
31482 Ada DLL available to applications developed with Microsoft
31483 tools (@pxref{Mixed-Language Programming on Windows}).
31484
31485 To create a Microsoft-style import library for @file{API.dll} you
31486 should proceed as follows:
31487
31488 @enumerate
31489 @item
31490 Create the definition file @file{API.def} from the DLL. For this use either
31491 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
31492 tool (see the corresponding Microsoft documentation for further details).
31493
31494 @item
31495 Build the actual import library using Microsoft's @code{lib} utility:
31496
31497 @smallexample
31498 $ lib -machine:IX86 -def:API.def -out:API.lib
31499 @end smallexample
31500
31501 @noindent
31502 If you use the above command the definition file @file{API.def} must
31503 contain a line giving the name of the DLL:
31504
31505 @smallexample
31506 LIBRARY      "API"
31507 @end smallexample
31508
31509 @noindent
31510 See the Microsoft documentation for further details about the usage of
31511 @code{lib}.
31512 @end enumerate
31513
31514 @node Building DLLs with GNAT
31515 @section Building DLLs with GNAT
31516 @cindex DLLs, building
31517
31518 @noindent
31519 This section explain how to build DLLs using the GNAT built-in DLL
31520 support. With the following procedure it is straight forward to build
31521 and use DLLs with GNAT.
31522
31523 @enumerate
31524
31525 @item building object files
31526
31527 The first step is to build all objects files that are to be included
31528 into the DLL. This is done by using the standard @command{gnatmake} tool.
31529
31530 @item building the DLL
31531
31532 To build the DLL you must use @command{gcc}'s @option{-shared}
31533 option. It is quite simple to use this method:
31534
31535 @smallexample
31536 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
31537 @end smallexample
31538
31539 It is important to note that in this case all symbols found in the
31540 object files are automatically exported. It is possible to restrict
31541 the set of symbols to export by passing to @command{gcc} a definition
31542 file, @pxref{The Definition File}. For example:
31543
31544 @smallexample
31545 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
31546 @end smallexample
31547
31548 If you use a definition file you must export the elaboration procedures
31549 for every package that required one. Elaboration procedures are named
31550 using the package name followed by "_E".
31551
31552 @item preparing DLL to be used
31553
31554 For the DLL to be used by client programs the bodies must be hidden
31555 from it and the .ali set with read-only attribute. This is very important
31556 otherwise GNAT will recompile all packages and will not actually use
31557 the code in the DLL. For example:
31558
31559 @smallexample
31560 $ mkdir apilib
31561 $ copy *.ads *.ali api.dll apilib
31562 $ attrib +R apilib\*.ali
31563 @end smallexample
31564
31565 @end enumerate
31566
31567 At this point it is possible to use the DLL by directly linking
31568 against it. Note that you must use the GNAT shared runtime when using
31569 GNAT shared libraries. This is achieved by using @option{-shared} binder's
31570 option.
31571
31572 @smallexample
31573 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
31574 @end smallexample
31575
31576 @node Building DLLs with GNAT Project files
31577 @section Building DLLs with GNAT Project files
31578 @cindex DLLs, building
31579
31580 @noindent
31581 There is nothing specific to Windows in the build process.
31582 @pxref{Library Projects}.
31583
31584 @noindent
31585 Due to a system limitation, it is not possible under Windows to create threads
31586 when inside the @code{DllMain} routine which is used for auto-initialization
31587 of shared libraries, so it is not possible to have library level tasks in SALs.
31588
31589 @node Building DLLs with gnatdll
31590 @section Building DLLs with gnatdll
31591 @cindex DLLs, building
31592
31593 @menu
31594 * Limitations When Using Ada DLLs from Ada::
31595 * Exporting Ada Entities::
31596 * Ada DLLs and Elaboration::
31597 * Ada DLLs and Finalization::
31598 * Creating a Spec for Ada DLLs::
31599 * Creating the Definition File::
31600 * Using gnatdll::
31601 @end menu
31602
31603 @noindent
31604 Note that it is preferred to use the built-in GNAT DLL support
31605 (@pxref{Building DLLs with GNAT}) or GNAT Project files
31606 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
31607
31608 This section explains how to build DLLs containing Ada code using
31609 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
31610 remainder of this section.
31611
31612 The steps required to build an Ada DLL that is to be used by Ada as well as
31613 non-Ada applications are as follows:
31614
31615 @enumerate
31616 @item
31617 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
31618 @code{Stdcall} calling convention to avoid any Ada name mangling for the
31619 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
31620 skip this step if you plan to use the Ada DLL only from Ada applications.
31621
31622 @item
31623 Your Ada code must export an initialization routine which calls the routine
31624 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
31625 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
31626 routine exported by the Ada DLL must be invoked by the clients of the DLL
31627 to initialize the DLL.
31628
31629 @item
31630 When useful, the DLL should also export a finalization routine which calls
31631 routine @code{adafinal} generated by @command{gnatbind} to perform the
31632 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
31633 The finalization routine exported by the Ada DLL must be invoked by the
31634 clients of the DLL when the DLL services are no further needed.
31635
31636 @item
31637 You must provide a spec for the services exported by the Ada DLL in each
31638 of the programming languages to which you plan to make the DLL available.
31639
31640 @item
31641 You must provide a definition file listing the exported entities
31642 (@pxref{The Definition File}).
31643
31644 @item
31645 Finally you must use @code{gnatdll} to produce the DLL and the import
31646 library (@pxref{Using gnatdll}).
31647 @end enumerate
31648
31649 @noindent
31650 Note that a relocatable DLL stripped using the @code{strip}
31651 binutils tool will not be relocatable anymore. To build a DLL without
31652 debug information pass @code{-largs -s} to @code{gnatdll}. This
31653 restriction does not apply to a DLL built using a Library Project.
31654 @pxref{Library Projects}.
31655
31656 @node Limitations When Using Ada DLLs from Ada
31657 @subsection Limitations When Using Ada DLLs from Ada
31658
31659 @noindent
31660 When using Ada DLLs from Ada applications there is a limitation users
31661 should be aware of. Because on Windows the GNAT run time is not in a DLL of
31662 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
31663 each Ada DLL includes the services of the GNAT run time that are necessary
31664 to the Ada code inside the DLL. As a result, when an Ada program uses an
31665 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
31666 one in the main program.
31667
31668 It is therefore not possible to exchange GNAT run-time objects between the
31669 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
31670 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
31671 types, etc.
31672
31673 It is completely safe to exchange plain elementary, array or record types,
31674 Windows object handles, etc.
31675
31676 @node Exporting Ada Entities
31677 @subsection Exporting Ada Entities
31678 @cindex Export table
31679
31680 @noindent
31681 Building a DLL is a way to encapsulate a set of services usable from any
31682 application. As a result, the Ada entities exported by a DLL should be
31683 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
31684 any Ada name mangling. As an example here is an Ada package
31685 @code{API}, spec and body, exporting two procedures, a function, and a
31686 variable:
31687
31688 @smallexample @c ada
31689 @group
31690 @cartouche
31691 with Interfaces.C; use Interfaces;
31692 package API is
31693    Count : C.int := 0;
31694    function Factorial (Val : C.int) return C.int;
31695
31696    procedure Initialize_API;
31697    procedure Finalize_API;
31698    --  Initialization & Finalization routines. More in the next section.
31699 private
31700    pragma Export (C, Initialize_API);
31701    pragma Export (C, Finalize_API);
31702    pragma Export (C, Count);
31703    pragma Export (C, Factorial);
31704 end API;
31705 @end cartouche
31706 @end group
31707 @end smallexample
31708
31709 @smallexample @c ada
31710 @group
31711 @cartouche
31712 package body API is
31713    function Factorial (Val : C.int) return C.int is
31714       Fact : C.int := 1;
31715    begin
31716       Count := Count + 1;
31717       for K in 1 .. Val loop
31718          Fact := Fact * K;
31719       end loop;
31720       return Fact;
31721    end Factorial;
31722
31723    procedure Initialize_API is
31724       procedure Adainit;
31725       pragma Import (C, Adainit);
31726    begin
31727       Adainit;
31728    end Initialize_API;
31729
31730    procedure Finalize_API is
31731       procedure Adafinal;
31732       pragma Import (C, Adafinal);
31733    begin
31734       Adafinal;
31735    end Finalize_API;
31736 end API;
31737 @end cartouche
31738 @end group
31739 @end smallexample
31740
31741 @noindent
31742 If the Ada DLL you are building will only be used by Ada applications
31743 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
31744 convention. As an example, the previous package could be written as
31745 follows:
31746
31747 @smallexample @c ada
31748 @group
31749 @cartouche
31750 package API is
31751    Count : Integer := 0;
31752    function Factorial (Val : Integer) return Integer;
31753
31754    procedure Initialize_API;
31755    procedure Finalize_API;
31756    --  Initialization and Finalization routines.
31757 end API;
31758 @end cartouche
31759 @end group
31760 @end smallexample
31761
31762 @smallexample @c ada
31763 @group
31764 @cartouche
31765 package body API is
31766    function Factorial (Val : Integer) return Integer is
31767       Fact : Integer := 1;
31768    begin
31769       Count := Count + 1;
31770       for K in 1 .. Val loop
31771          Fact := Fact * K;
31772       end loop;
31773       return Fact;
31774    end Factorial;
31775
31776    @dots{}
31777    --  The remainder of this package body is unchanged.
31778 end API;
31779 @end cartouche
31780 @end group
31781 @end smallexample
31782
31783 @noindent
31784 Note that if you do not export the Ada entities with a @code{C} or
31785 @code{Stdcall} convention you will have to provide the mangled Ada names
31786 in the definition file of the Ada DLL
31787 (@pxref{Creating the Definition File}).
31788
31789 @node Ada DLLs and Elaboration
31790 @subsection Ada DLLs and Elaboration
31791 @cindex DLLs and elaboration
31792
31793 @noindent
31794 The DLL that you are building contains your Ada code as well as all the
31795 routines in the Ada library that are needed by it. The first thing a
31796 user of your DLL must do is elaborate the Ada code
31797 (@pxref{Elaboration Order Handling in GNAT}).
31798
31799 To achieve this you must export an initialization routine
31800 (@code{Initialize_API} in the previous example), which must be invoked
31801 before using any of the DLL services. This elaboration routine must call
31802 the Ada elaboration routine @code{adainit} generated by the GNAT binder
31803 (@pxref{Binding with Non-Ada Main Programs}). See the body of
31804 @code{Initialize_Api} for an example. Note that the GNAT binder is
31805 automatically invoked during the DLL build process by the @code{gnatdll}
31806 tool (@pxref{Using gnatdll}).
31807
31808 When a DLL is loaded, Windows systematically invokes a routine called
31809 @code{DllMain}. It would therefore be possible to call @code{adainit}
31810 directly from @code{DllMain} without having to provide an explicit
31811 initialization routine. Unfortunately, it is not possible to call
31812 @code{adainit} from the @code{DllMain} if your program has library level
31813 tasks because access to the @code{DllMain} entry point is serialized by
31814 the system (that is, only a single thread can execute ``through'' it at a
31815 time), which means that the GNAT run time will deadlock waiting for the
31816 newly created task to complete its initialization.
31817
31818 @node Ada DLLs and Finalization
31819 @subsection Ada DLLs and Finalization
31820 @cindex DLLs and finalization
31821
31822 @noindent
31823 When the services of an Ada DLL are no longer needed, the client code should
31824 invoke the DLL finalization routine, if available. The DLL finalization
31825 routine is in charge of releasing all resources acquired by the DLL. In the
31826 case of the Ada code contained in the DLL, this is achieved by calling
31827 routine @code{adafinal} generated by the GNAT binder
31828 (@pxref{Binding with Non-Ada Main Programs}).
31829 See the body of @code{Finalize_Api} for an
31830 example. As already pointed out the GNAT binder is automatically invoked
31831 during the DLL build process by the @code{gnatdll} tool
31832 (@pxref{Using gnatdll}).
31833
31834 @node Creating a Spec for Ada DLLs
31835 @subsection Creating a Spec for Ada DLLs
31836
31837 @noindent
31838 To use the services exported by the Ada DLL from another programming
31839 language (e.g.@: C), you have to translate the specs of the exported Ada
31840 entities in that language. For instance in the case of @code{API.dll},
31841 the corresponding C header file could look like:
31842
31843 @smallexample
31844 @group
31845 @cartouche
31846 extern int *_imp__count;
31847 #define count (*_imp__count)
31848 int factorial (int);
31849 @end cartouche
31850 @end group
31851 @end smallexample
31852
31853 @noindent
31854 It is important to understand that when building an Ada DLL to be used by
31855 other Ada applications, you need two different specs for the packages
31856 contained in the DLL: one for building the DLL and the other for using
31857 the DLL. This is because the @code{DLL} calling convention is needed to
31858 use a variable defined in a DLL, but when building the DLL, the variable
31859 must have either the @code{Ada} or @code{C} calling convention. As an
31860 example consider a DLL comprising the following package @code{API}:
31861
31862 @smallexample @c ada
31863 @group
31864 @cartouche
31865 package API is
31866    Count : Integer := 0;
31867    @dots{}
31868    --  Remainder of the package omitted.
31869 end API;
31870 @end cartouche
31871 @end group
31872 @end smallexample
31873
31874 @noindent
31875 After producing a DLL containing package @code{API}, the spec that
31876 must be used to import @code{API.Count} from Ada code outside of the
31877 DLL is:
31878
31879 @smallexample @c ada
31880 @group
31881 @cartouche
31882 package API is
31883    Count : Integer;
31884    pragma Import (DLL, Count);
31885 end API;
31886 @end cartouche
31887 @end group
31888 @end smallexample
31889
31890 @node Creating the Definition File
31891 @subsection Creating the Definition File
31892
31893 @noindent
31894 The definition file is the last file needed to build the DLL. It lists
31895 the exported symbols. As an example, the definition file for a DLL
31896 containing only package @code{API} (where all the entities are exported
31897 with a @code{C} calling convention) is:
31898
31899 @smallexample
31900 @group
31901 @cartouche
31902 EXPORTS
31903     count
31904     factorial
31905     finalize_api
31906     initialize_api
31907 @end cartouche
31908 @end group
31909 @end smallexample
31910
31911 @noindent
31912 If the @code{C} calling convention is missing from package @code{API},
31913 then the definition file contains the mangled Ada names of the above
31914 entities, which in this case are:
31915
31916 @smallexample
31917 @group
31918 @cartouche
31919 EXPORTS
31920     api__count
31921     api__factorial
31922     api__finalize_api
31923     api__initialize_api
31924 @end cartouche
31925 @end group
31926 @end smallexample
31927
31928 @node Using gnatdll
31929 @subsection Using @code{gnatdll}
31930 @findex gnatdll
31931
31932 @menu
31933 * gnatdll Example::
31934 * gnatdll behind the Scenes::
31935 * Using dlltool::
31936 @end menu
31937
31938 @noindent
31939 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
31940 and non-Ada sources that make up your DLL have been compiled.
31941 @code{gnatdll} is actually in charge of two distinct tasks: build the
31942 static import library for the DLL and the actual DLL. The form of the
31943 @code{gnatdll} command is
31944
31945 @smallexample
31946 @cartouche
31947 $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
31948 @end cartouche
31949 @end smallexample
31950
31951 @noindent
31952 where @var{list-of-files} is a list of ALI and object files. The object
31953 file list must be the exact list of objects corresponding to the non-Ada
31954 sources whose services are to be included in the DLL. The ALI file list
31955 must be the exact list of ALI files for the corresponding Ada sources
31956 whose services are to be included in the DLL. If @var{list-of-files} is
31957 missing, only the static import library is generated.
31958
31959 @noindent
31960 You may specify any of the following switches to @code{gnatdll}:
31961
31962 @table @code
31963 @item -a@ovar{address}
31964 @cindex @option{-a} (@code{gnatdll})
31965 Build a non-relocatable DLL at @var{address}. If @var{address} is not
31966 specified the default address @var{0x11000000} will be used. By default,
31967 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
31968 advise the reader to build relocatable DLL.
31969
31970 @item -b @var{address}
31971 @cindex @option{-b} (@code{gnatdll})
31972 Set the relocatable DLL base address. By default the address is
31973 @code{0x11000000}.
31974
31975 @item -bargs @var{opts}
31976 @cindex @option{-bargs} (@code{gnatdll})
31977 Binder options. Pass @var{opts} to the binder.
31978
31979 @item -d @var{dllfile}
31980 @cindex @option{-d} (@code{gnatdll})
31981 @var{dllfile} is the name of the DLL. This switch must be present for
31982 @code{gnatdll} to do anything. The name of the generated import library is
31983 obtained algorithmically from @var{dllfile} as shown in the following
31984 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
31985 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
31986 by option @option{-e}) is obtained algorithmically from @var{dllfile}
31987 as shown in the following example:
31988 if @var{dllfile} is @code{xyz.dll}, the definition
31989 file used is @code{xyz.def}.
31990
31991 @item -e @var{deffile}
31992 @cindex @option{-e} (@code{gnatdll})
31993 @var{deffile} is the name of the definition file.
31994
31995 @item -g
31996 @cindex @option{-g} (@code{gnatdll})
31997 Generate debugging information. This information is stored in the object
31998 file and copied from there to the final DLL file by the linker,
31999 where it can be read by the debugger. You must use the
32000 @option{-g} switch if you plan on using the debugger or the symbolic
32001 stack traceback.
32002
32003 @item -h
32004 @cindex @option{-h} (@code{gnatdll})
32005 Help mode. Displays @code{gnatdll} switch usage information.
32006
32007 @item -Idir
32008 @cindex @option{-I} (@code{gnatdll})
32009 Direct @code{gnatdll} to search the @var{dir} directory for source and
32010 object files needed to build the DLL.
32011 (@pxref{Search Paths and the Run-Time Library (RTL)}).
32012
32013 @item -k
32014 @cindex @option{-k} (@code{gnatdll})
32015 Removes the @code{@@}@var{nn} suffix from the import library's exported
32016 names, but keeps them for the link names. You must specify this
32017 option if you want to use a @code{Stdcall} function in a DLL for which
32018 the @code{@@}@var{nn} suffix has been removed. This is the case for most
32019 of the Windows NT DLL for example. This option has no effect when
32020 @option{-n} option is specified.
32021
32022 @item -l @var{file}
32023 @cindex @option{-l} (@code{gnatdll})
32024 The list of ALI and object files used to build the DLL are listed in
32025 @var{file}, instead of being given in the command line. Each line in
32026 @var{file} contains the name of an ALI or object file.
32027
32028 @item -n
32029 @cindex @option{-n} (@code{gnatdll})
32030 No Import. Do not create the import library.
32031
32032 @item -q
32033 @cindex @option{-q} (@code{gnatdll})
32034 Quiet mode. Do not display unnecessary messages.
32035
32036 @item -v
32037 @cindex @option{-v} (@code{gnatdll})
32038 Verbose mode. Display extra information.
32039
32040 @item -largs @var{opts}
32041 @cindex @option{-largs} (@code{gnatdll})
32042 Linker options. Pass @var{opts} to the linker.
32043 @end table
32044
32045 @node gnatdll Example
32046 @subsubsection @code{gnatdll} Example
32047
32048 @noindent
32049 As an example the command to build a relocatable DLL from @file{api.adb}
32050 once @file{api.adb} has been compiled and @file{api.def} created is
32051
32052 @smallexample
32053 $ gnatdll -d api.dll api.ali
32054 @end smallexample
32055
32056 @noindent
32057 The above command creates two files: @file{libapi.dll.a} (the import
32058 library) and @file{api.dll} (the actual DLL). If you want to create
32059 only the DLL, just type:
32060
32061 @smallexample
32062 $ gnatdll -d api.dll -n api.ali
32063 @end smallexample
32064
32065 @noindent
32066 Alternatively if you want to create just the import library, type:
32067
32068 @smallexample
32069 $ gnatdll -d api.dll
32070 @end smallexample
32071
32072 @node gnatdll behind the Scenes
32073 @subsubsection @code{gnatdll} behind the Scenes
32074
32075 @noindent
32076 This section details the steps involved in creating a DLL. @code{gnatdll}
32077 does these steps for you. Unless you are interested in understanding what
32078 goes on behind the scenes, you should skip this section.
32079
32080 We use the previous example of a DLL containing the Ada package @code{API},
32081 to illustrate the steps necessary to build a DLL. The starting point is a
32082 set of objects that will make up the DLL and the corresponding ALI
32083 files. In the case of this example this means that @file{api.o} and
32084 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
32085 the following:
32086
32087 @enumerate
32088 @item
32089 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
32090 the information necessary to generate relocation information for the
32091 DLL.
32092
32093 @smallexample
32094 @group
32095 $ gnatbind -n api
32096 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
32097 @end group
32098 @end smallexample
32099
32100 @noindent
32101 In addition to the base file, the @command{gnatlink} command generates an
32102 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
32103 asks @command{gnatlink} to generate the routines @code{DllMain} and
32104 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
32105 is loaded into memory.
32106
32107 @item
32108 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
32109 export table (@file{api.exp}). The export table contains the relocation
32110 information in a form which can be used during the final link to ensure
32111 that the Windows loader is able to place the DLL anywhere in memory.
32112
32113 @smallexample
32114 @group
32115 $ dlltool --dllname api.dll --def api.def --base-file api.base \
32116           --output-exp api.exp
32117 @end group
32118 @end smallexample
32119
32120 @item
32121 @code{gnatdll} builds the base file using the new export table. Note that
32122 @command{gnatbind} must be called once again since the binder generated file
32123 has been deleted during the previous call to @command{gnatlink}.
32124
32125 @smallexample
32126 @group
32127 $ gnatbind -n api
32128 $ gnatlink api -o api.jnk api.exp -mdll
32129       -Wl,--base-file,api.base
32130 @end group
32131 @end smallexample
32132
32133 @item
32134 @code{gnatdll} builds the new export table using the new base file and
32135 generates the DLL import library @file{libAPI.dll.a}.
32136
32137 @smallexample
32138 @group
32139 $ dlltool --dllname api.dll --def api.def --base-file api.base \
32140           --output-exp api.exp --output-lib libAPI.a
32141 @end group
32142 @end smallexample
32143
32144 @item
32145 Finally @code{gnatdll} builds the relocatable DLL using the final export
32146 table.
32147
32148 @smallexample
32149 @group
32150 $ gnatbind -n api
32151 $ gnatlink api api.exp -o api.dll -mdll
32152 @end group
32153 @end smallexample
32154 @end enumerate
32155
32156 @node Using dlltool
32157 @subsubsection Using @code{dlltool}
32158
32159 @noindent
32160 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
32161 DLLs and static import libraries. This section summarizes the most
32162 common @code{dlltool} switches. The form of the @code{dlltool} command
32163 is
32164
32165 @smallexample
32166 $ dlltool @ovar{switches}
32167 @end smallexample
32168
32169 @noindent
32170 @code{dlltool} switches include:
32171
32172 @table @option
32173 @item --base-file @var{basefile}
32174 @cindex @option{--base-file} (@command{dlltool})
32175 Read the base file @var{basefile} generated by the linker. This switch
32176 is used to create a relocatable DLL.
32177
32178 @item --def @var{deffile}
32179 @cindex @option{--def} (@command{dlltool})
32180 Read the definition file.
32181
32182 @item --dllname @var{name}
32183 @cindex @option{--dllname} (@command{dlltool})
32184 Gives the name of the DLL. This switch is used to embed the name of the
32185 DLL in the static import library generated by @code{dlltool} with switch
32186 @option{--output-lib}.
32187
32188 @item -k
32189 @cindex @option{-k} (@command{dlltool})
32190 Kill @code{@@}@var{nn} from exported names
32191 (@pxref{Windows Calling Conventions}
32192 for a discussion about @code{Stdcall}-style symbols.
32193
32194 @item --help
32195 @cindex @option{--help} (@command{dlltool})
32196 Prints the @code{dlltool} switches with a concise description.
32197
32198 @item --output-exp @var{exportfile}
32199 @cindex @option{--output-exp} (@command{dlltool})
32200 Generate an export file @var{exportfile}. The export file contains the
32201 export table (list of symbols in the DLL) and is used to create the DLL.
32202
32203 @item --output-lib @var{libfile}
32204 @cindex @option{--output-lib} (@command{dlltool})
32205 Generate a static import library @var{libfile}.
32206
32207 @item -v
32208 @cindex @option{-v} (@command{dlltool})
32209 Verbose mode.
32210
32211 @item --as @var{assembler-name}
32212 @cindex @option{--as} (@command{dlltool})
32213 Use @var{assembler-name} as the assembler. The default is @code{as}.
32214 @end table
32215
32216 @node GNAT and Windows Resources
32217 @section GNAT and Windows Resources
32218 @cindex Resources, windows
32219
32220 @menu
32221 * Building Resources::
32222 * Compiling Resources::
32223 * Using Resources::
32224 @end menu
32225
32226 @noindent
32227 Resources are an easy way to add Windows specific objects to your
32228 application. The objects that can be added as resources include:
32229
32230 @itemize @bullet
32231 @item
32232 menus
32233
32234 @item
32235 accelerators
32236
32237 @item
32238 dialog boxes
32239
32240 @item
32241 string tables
32242
32243 @item
32244 bitmaps
32245
32246 @item
32247 cursors
32248
32249 @item
32250 icons
32251
32252 @item
32253 fonts
32254 @end itemize
32255
32256 @noindent
32257 This section explains how to build, compile and use resources.
32258
32259 @node Building Resources
32260 @subsection Building Resources
32261 @cindex Resources, building
32262
32263 @noindent
32264 A resource file is an ASCII file. By convention resource files have an
32265 @file{.rc} extension.
32266 The easiest way to build a resource file is to use Microsoft tools
32267 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
32268 @code{dlgedit.exe} to build dialogs.
32269 It is always possible to build an @file{.rc} file yourself by writing a
32270 resource script.
32271
32272 It is not our objective to explain how to write a resource file. A
32273 complete description of the resource script language can be found in the
32274 Microsoft documentation.
32275
32276 @node Compiling Resources
32277 @subsection Compiling Resources
32278 @findex rc
32279 @findex windres
32280 @cindex Resources, compiling
32281
32282 @noindent
32283 This section describes how to build a GNAT-compatible (COFF) object file
32284 containing the resources. This is done using the Resource Compiler
32285 @code{windres} as follows:
32286
32287 @smallexample
32288 $ windres -i myres.rc -o myres.o
32289 @end smallexample
32290
32291 @noindent
32292 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
32293 file. You can specify an alternate preprocessor (usually named
32294 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
32295 parameter. A list of all possible options may be obtained by entering
32296 the command @code{windres} @option{--help}.
32297
32298 It is also possible to use the Microsoft resource compiler @code{rc.exe}
32299 to produce a @file{.res} file (binary resource file). See the
32300 corresponding Microsoft documentation for further details. In this case
32301 you need to use @code{windres} to translate the @file{.res} file to a
32302 GNAT-compatible object file as follows:
32303
32304 @smallexample
32305 $ windres -i myres.res -o myres.o
32306 @end smallexample
32307
32308 @node Using Resources
32309 @subsection Using Resources
32310 @cindex Resources, using
32311
32312 @noindent
32313 To include the resource file in your program just add the
32314 GNAT-compatible object file for the resource(s) to the linker
32315 arguments. With @command{gnatmake} this is done by using the @option{-largs}
32316 option:
32317
32318 @smallexample
32319 $ gnatmake myprog -largs myres.o
32320 @end smallexample
32321
32322 @node Debugging a DLL
32323 @section Debugging a DLL
32324 @cindex DLL debugging
32325
32326 @menu
32327 * Program and DLL Both Built with GCC/GNAT::
32328 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
32329 @end menu
32330
32331 @noindent
32332 Debugging a DLL is similar to debugging a standard program. But
32333 we have to deal with two different executable parts: the DLL and the
32334 program that uses it. We have the following four possibilities:
32335
32336 @enumerate 1
32337 @item
32338 The program and the DLL are built with @code{GCC/GNAT}.
32339 @item
32340 The program is built with foreign tools and the DLL is built with
32341 @code{GCC/GNAT}.
32342 @item
32343 The program is built with @code{GCC/GNAT} and the DLL is built with
32344 foreign tools.
32345 @item
32346 @end enumerate
32347
32348 @noindent
32349 In this section we address only cases one and two above.
32350 There is no point in trying to debug
32351 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
32352 information in it. To do so you must use a debugger compatible with the
32353 tools suite used to build the DLL.
32354
32355 @node Program and DLL Both Built with GCC/GNAT
32356 @subsection Program and DLL Both Built with GCC/GNAT
32357
32358 @noindent
32359 This is the simplest case. Both the DLL and the program have @code{GDB}
32360 compatible debugging information. It is then possible to break anywhere in
32361 the process. Let's suppose here that the main procedure is named
32362 @code{ada_main} and that in the DLL there is an entry point named
32363 @code{ada_dll}.
32364
32365 @noindent
32366 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
32367 program must have been built with the debugging information (see GNAT -g
32368 switch). Here are the step-by-step instructions for debugging it:
32369
32370 @enumerate 1
32371 @item Launch @code{GDB} on the main program.
32372
32373 @smallexample
32374 $ gdb -nw ada_main
32375 @end smallexample
32376
32377 @item Start the program and stop at the beginning of the main procedure
32378
32379 @smallexample
32380 (gdb) start
32381 @end smallexample
32382
32383 @noindent
32384 This step is required to be able to set a breakpoint inside the DLL. As long
32385 as the program is not run, the DLL is not loaded. This has the
32386 consequence that the DLL debugging information is also not loaded, so it is not
32387 possible to set a breakpoint in the DLL.
32388
32389 @item Set a breakpoint inside the DLL
32390
32391 @smallexample
32392 (gdb) break ada_dll
32393 (gdb) cont
32394 @end smallexample
32395
32396 @end enumerate
32397
32398 @noindent
32399 At this stage a breakpoint is set inside the DLL. From there on
32400 you can use the standard approach to debug the whole program
32401 (@pxref{Running and Debugging Ada Programs}).
32402
32403 @ignore
32404 @c This used to work, probably because the DLLs were non-relocatable
32405 @c keep this section around until the problem is sorted out.
32406
32407 To break on the @code{DllMain} routine it is not possible to follow
32408 the procedure above. At the time the program stop on @code{ada_main}
32409 the @code{DllMain} routine as already been called. Either you can use
32410 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
32411
32412 @enumerate 1
32413 @item Launch @code{GDB} on the main program.
32414
32415 @smallexample
32416 $ gdb ada_main
32417 @end smallexample
32418
32419 @item Load DLL symbols
32420
32421 @smallexample
32422 (gdb) add-sym api.dll
32423 @end smallexample
32424
32425 @item Set a breakpoint inside the DLL
32426
32427 @smallexample
32428 (gdb) break ada_dll.adb:45
32429 @end smallexample
32430
32431 Note that at this point it is not possible to break using the routine symbol
32432 directly as the program is not yet running. The solution is to break
32433 on the proper line (break in @file{ada_dll.adb} line 45).
32434
32435 @item Start the program
32436
32437 @smallexample
32438 (gdb) run
32439 @end smallexample
32440
32441 @end enumerate
32442 @end ignore
32443
32444 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
32445 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
32446
32447 @menu
32448 * Debugging the DLL Directly::
32449 * Attaching to a Running Process::
32450 @end menu
32451
32452 @noindent
32453 In this case things are slightly more complex because it is not possible to
32454 start the main program and then break at the beginning to load the DLL and the
32455 associated DLL debugging information. It is not possible to break at the
32456 beginning of the program because there is no @code{GDB} debugging information,
32457 and therefore there is no direct way of getting initial control. This
32458 section addresses this issue by describing some methods that can be used
32459 to break somewhere in the DLL to debug it.
32460
32461 @noindent
32462 First suppose that the main procedure is named @code{main} (this is for
32463 example some C code built with Microsoft Visual C) and that there is a
32464 DLL named @code{test.dll} containing an Ada entry point named
32465 @code{ada_dll}.
32466
32467 @noindent
32468 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
32469 been built with debugging information (see GNAT -g option).
32470
32471 @node Debugging the DLL Directly
32472 @subsubsection Debugging the DLL Directly
32473
32474 @enumerate 1
32475 @item
32476 Find out the executable starting address
32477
32478 @smallexample
32479 $ objdump --file-header main.exe
32480 @end smallexample
32481
32482 The starting address is reported on the last line. For example:
32483
32484 @smallexample
32485 main.exe:     file format pei-i386
32486 architecture: i386, flags 0x0000010a:
32487 EXEC_P, HAS_DEBUG, D_PAGED
32488 start address 0x00401010
32489 @end smallexample
32490
32491 @item
32492 Launch the debugger on the executable.
32493
32494 @smallexample
32495 $ gdb main.exe
32496 @end smallexample
32497
32498 @item
32499 Set a breakpoint at the starting address, and launch the program.
32500
32501 @smallexample
32502 $ (gdb) break *0x00401010
32503 $ (gdb) run
32504 @end smallexample
32505
32506 The program will stop at the given address.
32507
32508 @item
32509 Set a breakpoint on a DLL subroutine.
32510
32511 @smallexample
32512 (gdb) break ada_dll.adb:45
32513 @end smallexample
32514
32515 Or if you want to break using a symbol on the DLL, you need first to
32516 select the Ada language (language used by the DLL).
32517
32518 @smallexample
32519 (gdb) set language ada
32520 (gdb) break ada_dll
32521 @end smallexample
32522
32523 @item
32524 Continue the program.
32525
32526 @smallexample
32527 (gdb) cont
32528 @end smallexample
32529
32530 @noindent
32531 This will run the program until it reaches the breakpoint that has been
32532 set. From that point you can use the standard way to debug a program
32533 as described in (@pxref{Running and Debugging Ada Programs}).
32534
32535 @end enumerate
32536
32537 @noindent
32538 It is also possible to debug the DLL by attaching to a running process.
32539
32540 @node Attaching to a Running Process
32541 @subsubsection Attaching to a Running Process
32542 @cindex DLL debugging, attach to process
32543
32544 @noindent
32545 With @code{GDB} it is always possible to debug a running process by
32546 attaching to it. It is possible to debug a DLL this way. The limitation
32547 of this approach is that the DLL must run long enough to perform the
32548 attach operation. It may be useful for instance to insert a time wasting
32549 loop in the code of the DLL to meet this criterion.
32550
32551 @enumerate 1
32552
32553 @item Launch the main program @file{main.exe}.
32554
32555 @smallexample
32556 $ main
32557 @end smallexample
32558
32559 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
32560 that the process PID for @file{main.exe} is 208.
32561
32562 @item Launch gdb.
32563
32564 @smallexample
32565 $ gdb
32566 @end smallexample
32567
32568 @item Attach to the running process to be debugged.
32569
32570 @smallexample
32571 (gdb) attach 208
32572 @end smallexample
32573
32574 @item Load the process debugging information.
32575
32576 @smallexample
32577 (gdb) symbol-file main.exe
32578 @end smallexample
32579
32580 @item Break somewhere in the DLL.
32581
32582 @smallexample
32583 (gdb) break ada_dll
32584 @end smallexample
32585
32586 @item Continue process execution.
32587
32588 @smallexample
32589 (gdb) cont
32590 @end smallexample
32591
32592 @end enumerate
32593
32594 @noindent
32595 This last step will resume the process execution, and stop at
32596 the breakpoint we have set. From there you can use the standard
32597 approach to debug a program as described in
32598 (@pxref{Running and Debugging Ada Programs}).
32599
32600 @node Setting Stack Size from gnatlink
32601 @section Setting Stack Size from @command{gnatlink}
32602
32603 @noindent
32604 It is possible to specify the program stack size at link time. On modern
32605 versions of Windows, starting with XP, this is mostly useful to set the size of
32606 the main stack (environment task). The other task stacks are set with pragma
32607 Storage_Size or with the @command{gnatbind -d} command.
32608
32609 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
32610 reserve size of individual tasks, the link-time stack size applies to all
32611 tasks, and pragma Storage_Size has no effect.
32612 In particular, Stack Overflow checks are made against this
32613 link-time specified size.
32614
32615 This setting can be done with
32616 @command{gnatlink} using either:
32617
32618 @itemize @bullet
32619
32620 @item using @option{-Xlinker} linker option
32621
32622 @smallexample
32623 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
32624 @end smallexample
32625
32626 This sets the stack reserve size to 0x10000 bytes and the stack commit
32627 size to 0x1000 bytes.
32628
32629 @item using @option{-Wl} linker option
32630
32631 @smallexample
32632 $ gnatlink hello -Wl,--stack=0x1000000
32633 @end smallexample
32634
32635 This sets the stack reserve size to 0x1000000 bytes. Note that with
32636 @option{-Wl} option it is not possible to set the stack commit size
32637 because the coma is a separator for this option.
32638
32639 @end itemize
32640
32641 @node Setting Heap Size from gnatlink
32642 @section Setting Heap Size from @command{gnatlink}
32643
32644 @noindent
32645 Under Windows systems, it is possible to specify the program heap size from
32646 @command{gnatlink} using either:
32647
32648 @itemize @bullet
32649
32650 @item using @option{-Xlinker} linker option
32651
32652 @smallexample
32653 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
32654 @end smallexample
32655
32656 This sets the heap reserve size to 0x10000 bytes and the heap commit
32657 size to 0x1000 bytes.
32658
32659 @item using @option{-Wl} linker option
32660
32661 @smallexample
32662 $ gnatlink hello -Wl,--heap=0x1000000
32663 @end smallexample
32664
32665 This sets the heap reserve size to 0x1000000 bytes. Note that with
32666 @option{-Wl} option it is not possible to set the heap commit size
32667 because the coma is a separator for this option.
32668
32669 @end itemize
32670
32671 @end ifset
32672
32673 @c **********************************
32674 @c * GNU Free Documentation License *
32675 @c **********************************
32676 @include fdl.texi
32677 @c GNU Free Documentation License
32678
32679 @node Index,,GNU Free Documentation License, Top
32680 @unnumbered Index
32681
32682 @printindex cp
32683
32684 @contents
32685 @c Put table of contents at end, otherwise it precedes the "title page" in
32686 @c the .txt version
32687 @c Edit the pdf file to move the contents to the beginning, after the title
32688 @c page
32689
32690 @bye