OSDN Git Service

2010-06-17 Vincent Celier <celier@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-2009 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.3 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 @c Status as of November 2009:
111 @c Unfortunately texi2pdf and texi2html treat the trailing "@c"
112 @c differently, and faulty output is produced by one or the other
113 @c depending on whether the "@c" is present or absent.
114 @c As a result, the @ovar macro is not used, and all invocations
115 @c of the @ovar macro have been expanded inline.
116
117
118 @settitle @value{EDITION} User's Guide @value{PLATFORM}
119 @dircategory GNU Ada tools
120 @direntry
121 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
122 @end direntry
123
124 @include gcc-common.texi
125
126 @setchapternewpage odd
127 @syncodeindex fn cp
128 @c %**end of header
129
130 @titlepage
131 @title @value{EDITION} User's Guide
132 @ifset vms
133 @sp 1
134 @flushright
135 @titlefont{@i{@value{PLATFORM}}}
136 @end flushright
137 @end ifset
138
139 @sp 2
140
141 @subtitle GNAT, The GNU Ada Compiler
142 @versionsubtitle
143 @author AdaCore
144
145 @page
146 @vskip 0pt plus 1filll
147
148 @insertcopying
149
150 @end titlepage
151
152 @ifnottex
153 @node Top, About This Guide, (dir), (dir)
154 @top @value{EDITION} User's Guide
155
156 @noindent
157 @value{EDITION} User's Guide @value{PLATFORM}
158
159 @noindent
160 GNAT, The GNU Ada Compiler@*
161 GCC version @value{version-GCC}@*
162
163 @noindent
164 AdaCore@*
165
166 @menu
167 * About This Guide::
168 * Getting Started with GNAT::
169 * The GNAT Compilation Model::
170 * Compiling Using gcc::
171 * Binding Using gnatbind::
172 * Linking Using gnatlink::
173 * The GNAT Make Program gnatmake::
174 * Improving Performance::
175 * Renaming Files Using gnatchop::
176 * Configuration Pragmas::
177 * Handling Arbitrary File Naming Conventions Using gnatname::
178 * GNAT Project Manager::
179 * The Cross-Referencing Tools gnatxref and gnatfind::
180 * The GNAT Pretty-Printer gnatpp::
181 * The GNAT Metric Tool gnatmetric::
182 * File Name Krunching Using gnatkr::
183 * Preprocessing Using gnatprep::
184 @ifset vms
185 * The GNAT Run-Time Library Builder gnatlbr::
186 @end ifset
187 * The GNAT Library Browser gnatls::
188 * Cleaning Up Using gnatclean::
189 @ifclear vms
190 * GNAT and Libraries::
191 * Using the GNU make Utility::
192 @end ifclear
193 * Memory Management Issues::
194 * Stack Related Facilities::
195 * Verifying Properties Using gnatcheck::
196 * Creating Sample Bodies Using gnatstub::
197 * Generating Ada Bindings for C and C++ headers::
198 * Other Utility Programs::
199 * Running and Debugging Ada Programs::
200 @ifclear vms
201 * Code Coverage and Profiling::
202 @end ifclear
203 @ifset vms
204 * Compatibility with HP Ada::
205 @end ifset
206 * Platform-Specific Information for the Run-Time Libraries::
207 * Example of Binder Output File::
208 * Elaboration Order Handling in GNAT::
209 * Conditional Compilation::
210 * Inline Assembler::
211 * Compatibility and Porting Guide::
212 @ifset unw
213 * Microsoft Windows Topics::
214 @end ifset
215 * GNU Free Documentation License::
216 * Index::
217
218  --- The Detailed Node Listing ---
219
220 About This Guide
221
222 * What This Guide Contains::
223 * What You Should Know before Reading This Guide::
224 * Related Information::
225 * Conventions::
226
227 Getting Started with GNAT
228
229 * Running GNAT::
230 * Running a Simple Ada Program::
231 * Running a Program with Multiple Units::
232 * Using the gnatmake Utility::
233 @ifset vms
234 * Editing with Emacs::
235 @end ifset
236 @ifclear vms
237 * Introduction to GPS::
238 @end ifclear
239
240 The GNAT Compilation Model
241
242 * Source Representation::
243 * Foreign Language Representation::
244 * File Naming Rules::
245 * Using Other File Names::
246 * Alternative File Naming Schemes::
247 * Generating Object Files::
248 * Source Dependencies::
249 * The Ada Library Information Files::
250 * Binding an Ada Program::
251 * Mixed Language Programming::
252 @ifclear vms
253 * Building Mixed Ada & C++ Programs::
254 * Comparison between GNAT and C/C++ Compilation Models::
255 @end ifclear
256 * Comparison between GNAT and Conventional Ada Library Models::
257 @ifset vms
258 * Placement of temporary files::
259 @end ifset
260
261 Foreign Language Representation
262
263 * Latin-1::
264 * Other 8-Bit Codes::
265 * Wide Character Encodings::
266
267 Compiling Ada Programs With gcc
268
269 * Compiling Programs::
270 * Switches for gcc::
271 * Search Paths and the Run-Time Library (RTL)::
272 * Order of Compilation Issues::
273 * Examples::
274
275 Switches for gcc
276
277 * Output and Error Message Control::
278 * Warning Message Control::
279 * Debugging and Assertion Control::
280 * Validity Checking::
281 * Style Checking::
282 * Run-Time Checks::
283 * Using gcc for Syntax Checking::
284 * Using gcc for Semantic Checking::
285 * Compiling Different Versions of Ada::
286 * Character Set Control::
287 * File Naming Control::
288 * Subprogram Inlining Control::
289 * Auxiliary Output Control::
290 * Debugging Control::
291 * Exception Handling Control::
292 * Units to Sources Mapping Files::
293 * Integrated Preprocessing::
294 @ifset vms
295 * Return Codes::
296 @end ifset
297
298 Binding Ada Programs With gnatbind
299
300 * Running gnatbind::
301 * Switches for gnatbind::
302 * Command-Line Access::
303 * Search Paths for gnatbind::
304 * Examples of gnatbind Usage::
305
306 Switches for gnatbind
307
308 * Consistency-Checking Modes::
309 * Binder Error Message Control::
310 * Elaboration Control::
311 * Output Control::
312 * Binding with Non-Ada Main Programs::
313 * Binding Programs with No Main Subprogram::
314
315 Linking Using gnatlink
316
317 * Running gnatlink::
318 * Switches for gnatlink::
319
320 The GNAT Make Program gnatmake
321
322 * Running gnatmake::
323 * Switches for gnatmake::
324 * Mode Switches for gnatmake::
325 * Notes on the Command Line::
326 * How gnatmake Works::
327 * Examples of gnatmake Usage::
328
329 Improving Performance
330 * Performance Considerations::
331 * Text_IO Suggestions::
332 * Reducing Size of Ada Executables with gnatelim::
333 * Reducing Size of Executables with unused subprogram/data elimination::
334
335 Performance Considerations
336 * Controlling Run-Time Checks::
337 * Use of Restrictions::
338 * Optimization Levels::
339 * Debugging Optimized Code::
340 * Inlining of Subprograms::
341 * Other Optimization Switches::
342 * Optimization and Strict Aliasing::
343 @ifset vms
344 * Coverage Analysis::
345 @end ifset
346
347 Reducing Size of Ada Executables with gnatelim
348 * About gnatelim::
349 * Running gnatelim::
350 * Processing Precompiled Libraries::
351 * Correcting the List of Eliminate Pragmas::
352 * Making Your Executables Smaller::
353 * Summary of the gnatelim Usage Cycle::
354
355 Reducing Size of Executables with unused subprogram/data elimination
356 * About unused subprogram/data elimination::
357 * Compilation options::
358
359 Renaming Files Using gnatchop
360
361 * Handling Files with Multiple Units::
362 * Operating gnatchop in Compilation Mode::
363 * Command Line for gnatchop::
364 * Switches for gnatchop::
365 * Examples of gnatchop Usage::
366
367 Configuration Pragmas
368
369 * Handling of Configuration Pragmas::
370 * The Configuration Pragmas Files::
371
372 Handling Arbitrary File Naming Conventions Using gnatname
373
374 * Arbitrary File Naming Conventions::
375 * Running gnatname::
376 * Switches for gnatname::
377 * Examples of gnatname Usage::
378
379 GNAT Project Manager
380
381 * Introduction::
382 * Examples of Project Files::
383 * Project File Syntax::
384 * Objects and Sources in Project Files::
385 * Importing Projects::
386 * Project Extension::
387 * Project Hierarchy Extension::
388 * External References in Project Files::
389 * Packages in Project Files::
390 * Variables from Imported Projects::
391 * Naming Schemes::
392 * Library Projects::
393 * Stand-alone Library Projects::
394 * Switches Related to Project Files::
395 * Tools Supporting Project Files::
396 * An Extended Example::
397 * Project File Complete Syntax::
398
399 The Cross-Referencing Tools gnatxref and gnatfind
400
401 * Switches for gnatxref::
402 * Switches for gnatfind::
403 * Project Files for gnatxref and gnatfind::
404 * Regular Expressions in gnatfind and gnatxref::
405 * Examples of gnatxref Usage::
406 * Examples of gnatfind Usage::
407
408 The GNAT Pretty-Printer gnatpp
409
410 * Switches for gnatpp::
411 * Formatting Rules::
412
413 The GNAT Metrics Tool gnatmetric
414
415 * Switches for gnatmetric::
416
417 File Name Krunching Using gnatkr
418
419 * About gnatkr::
420 * Using gnatkr::
421 * Krunching Method::
422 * Examples of gnatkr Usage::
423
424 Preprocessing Using gnatprep
425 * Preprocessing Symbols::
426 * Using gnatprep::
427 * Switches for gnatprep::
428 * Form of Definitions File::
429 * Form of Input Text for gnatprep::
430
431 @ifset vms
432 The GNAT Run-Time Library Builder gnatlbr
433
434 * Running gnatlbr::
435 * Switches for gnatlbr::
436 * Examples of gnatlbr Usage::
437 @end ifset
438
439 The GNAT Library Browser gnatls
440
441 * Running gnatls::
442 * Switches for gnatls::
443 * Examples of gnatls Usage::
444
445 Cleaning Up Using gnatclean
446
447 * Running gnatclean::
448 * Switches for gnatclean::
449 @c * Examples of gnatclean Usage::
450
451 @ifclear vms
452
453 GNAT and Libraries
454
455 * Introduction to Libraries in GNAT::
456 * General Ada Libraries::
457 * Stand-alone Ada Libraries::
458 * Rebuilding the GNAT Run-Time Library::
459
460 Using the GNU make Utility
461
462 * Using gnatmake in a Makefile::
463 * Automatically Creating a List of Directories::
464 * Generating the Command Line Switches::
465 * Overcoming Command Line Length Limits::
466 @end ifclear
467
468 Memory Management Issues
469
470 * Some Useful Memory Pools::
471 * The GNAT Debug Pool Facility::
472 @ifclear vms
473 * The gnatmem Tool::
474 @end ifclear
475
476 Stack Related Facilities
477
478 * Stack Overflow Checking::
479 * Static Stack Usage Analysis::
480 * Dynamic Stack Usage Analysis::
481
482 Some Useful Memory Pools
483
484 The GNAT Debug Pool Facility
485
486 @ifclear vms
487 The gnatmem Tool
488
489 * Running gnatmem::
490 * Switches for gnatmem::
491 * Example of gnatmem Usage::
492 @end ifclear
493
494 Verifying Properties Using gnatcheck
495
496 * Format of the Report File::
497 * General gnatcheck Switches::
498 * gnatcheck Rule Options::
499 * Adding the Results of Compiler Checks to gnatcheck Output::
500 * Project-Wide Checks::
501 * Rule exemption::
502 * Predefined Rules::
503 * Example of gnatcheck Usage::
504
505 Sample Bodies Using gnatstub
506
507 * Running gnatstub::
508 * Switches for gnatstub::
509
510 Other Utility Programs
511
512 * Using Other Utility Programs with GNAT::
513 * The External Symbol Naming Scheme of GNAT::
514 * Converting Ada Files to html with gnathtml::
515
516 @ifclear vms
517 Code Coverage and Profiling
518
519 * Code Coverage of Ada Programs using gcov::
520 * Profiling an Ada Program using gprof::
521 @end ifclear
522
523 Running and Debugging Ada Programs
524
525 * The GNAT Debugger GDB::
526 * Running GDB::
527 * Introduction to GDB Commands::
528 * Using Ada Expressions::
529 * Calling User-Defined Subprograms::
530 * Using the Next Command in a Function::
531 * Ada Exceptions::
532 * Ada Tasks::
533 * Debugging Generic Units::
534 * GNAT Abnormal Termination or Failure to Terminate::
535 * Naming Conventions for GNAT Source Files::
536 * Getting Internal Debugging Information::
537 * Stack Traceback::
538
539 @ifset vms
540 * LSE::
541 @end ifset
542
543 @ifset vms
544 Compatibility with HP Ada
545
546 * Ada Language Compatibility::
547 * Differences in the Definition of Package System::
548 * Language-Related Features::
549 * The Package STANDARD::
550 * The Package SYSTEM::
551 * Tasking and Task-Related Features::
552 * Pragmas and Pragma-Related Features::
553 * Library of Predefined Units::
554 * Bindings::
555 * Main Program Definition::
556 * Implementation-Defined Attributes::
557 * Compiler and Run-Time Interfacing::
558 * Program Compilation and Library Management::
559 * Input-Output::
560 * Implementation Limits::
561 * Tools and Utilities::
562
563 Language-Related Features
564
565 * Integer Types and Representations::
566 * Floating-Point Types and Representations::
567 * Pragmas Float_Representation and Long_Float::
568 * Fixed-Point Types and Representations::
569 * Record and Array Component Alignment::
570 * Address Clauses::
571 * Other Representation Clauses::
572
573 Tasking and Task-Related Features
574
575 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
576 * Assigning Task IDs::
577 * Task IDs and Delays::
578 * Task-Related Pragmas::
579 * Scheduling and Task Priority::
580 * The Task Stack::
581 * External Interrupts::
582
583 Pragmas and Pragma-Related Features
584
585 * Restrictions on the Pragma INLINE::
586 * Restrictions on the Pragma INTERFACE::
587 * Restrictions on the Pragma SYSTEM_NAME::
588
589 Library of Predefined Units
590
591 * Changes to DECLIB::
592
593 Bindings
594
595 * Shared Libraries and Options Files::
596 * Interfaces to C::
597 @end ifset
598
599 Platform-Specific Information for the Run-Time Libraries
600
601 * Summary of Run-Time Configurations::
602 * Specifying a Run-Time Library::
603 * Choosing the Scheduling Policy::
604 * Solaris-Specific Considerations::
605 * Linux-Specific Considerations::
606 * AIX-Specific Considerations::
607 * Irix-Specific Considerations::
608 * RTX-Specific Considerations::
609 * HP-UX-Specific Considerations::
610
611 Example of Binder Output File
612
613 Elaboration Order Handling in GNAT
614
615 * Elaboration Code::
616 * Checking the Elaboration Order::
617 * Controlling the Elaboration Order::
618 * Controlling Elaboration in GNAT - Internal Calls::
619 * Controlling Elaboration in GNAT - External Calls::
620 * Default Behavior in GNAT - Ensuring Safety::
621 * Treatment of Pragma Elaborate::
622 * Elaboration Issues for Library Tasks::
623 * Mixing Elaboration Models::
624 * What to Do If the Default Elaboration Behavior Fails::
625 * Elaboration for Access-to-Subprogram Values::
626 * Summary of Procedures for Elaboration Control::
627 * Other Elaboration Order Considerations::
628
629 Conditional Compilation
630 * Use of Boolean Constants::
631 * Debugging - A Special Case::
632 * Conditionalizing Declarations::
633 * Use of Alternative Implementations::
634 * Preprocessing::
635
636 Inline Assembler
637
638 * Basic Assembler Syntax::
639 * A Simple Example of Inline Assembler::
640 * Output Variables in Inline Assembler::
641 * Input Variables in Inline Assembler::
642 * Inlining Inline Assembler Code::
643 * Other Asm Functionality::
644
645 Compatibility and Porting Guide
646
647 * Compatibility with Ada 83::
648 * Compatibility between Ada 95 and Ada 2005::
649 * Implementation-dependent characteristics::
650 @ifclear vms
651 @c This brief section is only in the non-VMS version
652 @c The complete chapter on HP Ada issues is in the VMS version
653 * Compatibility with HP Ada 83::
654 @end ifclear
655 * Compatibility with Other Ada Systems::
656 * Representation Clauses::
657 @ifset vms
658 * Transitioning to 64-Bit GNAT for OpenVMS::
659 @end ifset
660
661 @ifset unw
662 Microsoft Windows Topics
663
664 * Using GNAT on Windows::
665 * CONSOLE and WINDOWS subsystems::
666 * Temporary Files::
667 * Mixed-Language Programming on Windows::
668 * Windows Calling Conventions::
669 * Introduction to Dynamic Link Libraries (DLLs)::
670 * Using DLLs with GNAT::
671 * Building DLLs with GNAT::
672 * GNAT and Windows Resources::
673 * Debugging a DLL::
674 * Setting Stack Size from gnatlink::
675 * Setting Heap Size from gnatlink::
676 @end ifset
677
678 * Index::
679 @end menu
680 @end ifnottex
681
682 @node About This Guide
683 @unnumbered About This Guide
684
685 @noindent
686 @ifset vms
687 This guide describes the use of @value{EDITION},
688 a compiler and software development toolset for the full Ada
689 programming language, implemented on OpenVMS for HP's Alpha and
690 Integrity server (I64) platforms.
691 @end ifset
692 @ifclear vms
693 This guide describes the use of @value{EDITION},
694 a compiler and software development
695 toolset for the full Ada programming language.
696 @end ifclear
697 It documents the features of the compiler and tools, and explains
698 how to use them to build Ada applications.
699
700 @value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in
701 Ada 83 compatibility mode.
702 By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
703 but you can override with a compiler switch
704 (@pxref{Compiling Different Versions of Ada})
705 to explicitly specify the language version.
706 Throughout this manual, references to ``Ada'' without a year suffix
707 apply to both the Ada 95 and Ada 2005 versions of the language.
708
709
710 @ifclear FSFEDITION
711 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
712 ``GNAT'' in the remainder of this document.
713 @end ifclear
714
715
716
717
718 @menu
719 * What This Guide Contains::
720 * What You Should Know before Reading This Guide::
721 * Related Information::
722 * Conventions::
723 @end menu
724
725 @node What This Guide Contains
726 @unnumberedsec What This Guide Contains
727
728 @noindent
729 This guide contains the following chapters:
730 @itemize @bullet
731
732 @item
733 @ref{Getting Started with GNAT}, describes how to get started compiling
734 and running Ada programs with the GNAT Ada programming environment.
735 @item
736 @ref{The GNAT Compilation Model}, describes the compilation model used
737 by GNAT.
738
739 @item
740 @ref{Compiling Using gcc}, describes how to compile
741 Ada programs with @command{gcc}, the Ada compiler.
742
743 @item
744 @ref{Binding Using gnatbind}, describes how to
745 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
746 utility.
747
748 @item
749 @ref{Linking Using gnatlink},
750 describes @command{gnatlink}, a
751 program that provides for linking using the GNAT run-time library to
752 construct a program. @command{gnatlink} can also incorporate foreign language
753 object units into the executable.
754
755 @item
756 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
757 utility that automatically determines the set of sources
758 needed by an Ada compilation unit, and executes the necessary compilations
759 binding and link.
760
761 @item
762 @ref{Improving Performance}, shows various techniques for making your
763 Ada program run faster or take less space.
764 It discusses the effect of the compiler's optimization switch and
765 also describes the @command{gnatelim} tool and unused subprogram/data
766 elimination.
767
768 @item
769 @ref{Renaming Files Using gnatchop}, describes
770 @code{gnatchop}, a utility that allows you to preprocess a file that
771 contains Ada source code, and split it into one or more new files, one
772 for each compilation unit.
773
774 @item
775 @ref{Configuration Pragmas}, describes the configuration pragmas
776 handled by GNAT.
777
778 @item
779 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
780 shows how to override the default GNAT file naming conventions,
781 either for an individual unit or globally.
782
783 @item
784 @ref{GNAT Project Manager}, describes how to use project files
785 to organize large projects.
786
787 @item
788 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
789 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
790 way to navigate through sources.
791
792 @item
793 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
794 version of an Ada source file with control over casing, indentation,
795 comment placement, and other elements of program presentation style.
796
797 @item
798 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
799 metrics for an Ada source file, such as the number of types and subprograms,
800 and assorted complexity measures.
801
802 @item
803 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
804 file name krunching utility, used to handle shortened
805 file names on operating systems with a limit on the length of names.
806
807 @item
808 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
809 preprocessor utility that allows a single source file to be used to
810 generate multiple or parameterized source files by means of macro
811 substitution.
812
813 @ifset vms
814 @item
815 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
816 a tool for rebuilding the GNAT run time with user-supplied
817 configuration pragmas.
818 @end ifset
819
820 @item
821 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
822 utility that displays information about compiled units, including dependences
823 on the corresponding sources files, and consistency of compilations.
824
825 @item
826 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
827 to delete files that are produced by the compiler, binder and linker.
828
829 @ifclear vms
830 @item
831 @ref{GNAT and Libraries}, describes the process of creating and using
832 Libraries with GNAT. It also describes how to recompile the GNAT run-time
833 library.
834
835 @item
836 @ref{Using the GNU make Utility}, describes some techniques for using
837 the GNAT toolset in Makefiles.
838 @end ifclear
839
840 @item
841 @ref{Memory Management Issues}, describes some useful predefined storage pools
842 and in particular the GNAT Debug Pool facility, which helps detect incorrect
843 memory references.
844 @ifclear vms
845 It also describes @command{gnatmem}, a utility that monitors dynamic
846 allocation and deallocation and helps detect ``memory leaks''.
847 @end ifclear
848
849 @item
850 @ref{Stack Related Facilities}, describes some useful tools associated with
851 stack checking and analysis.
852
853 @item
854 @ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck},
855 a utility that checks Ada code against a set of rules.
856
857 @item
858 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
859 a utility that generates empty but compilable bodies for library units.
860
861 @item
862 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
863 generate automatically Ada bindings from C and C++ headers.
864
865 @item
866 @ref{Other Utility Programs}, discusses several other GNAT utilities,
867 including @code{gnathtml}.
868
869 @ifclear vms
870 @item
871 @ref{Code Coverage and Profiling}, describes how to perform a structural
872 coverage and profile the execution of Ada programs.
873 @end ifclear
874
875 @item
876 @ref{Running and Debugging Ada Programs}, describes how to run and debug
877 Ada programs.
878
879 @ifset vms
880 @item
881 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
882 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
883 developed by Digital Equipment Corporation and currently supported by HP.}
884 for OpenVMS Alpha. This product was formerly known as DEC Ada,
885 @cindex DEC Ada
886 and for
887 historical compatibility reasons, the relevant libraries still use the
888 DEC prefix.
889 @end ifset
890
891 @item
892 @ref{Platform-Specific Information for the Run-Time Libraries},
893 describes the various run-time
894 libraries supported by GNAT on various platforms and explains how to
895 choose a particular library.
896
897 @item
898 @ref{Example of Binder Output File}, shows the source code for the binder
899 output file for a sample program.
900
901 @item
902 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
903 you deal with elaboration order issues.
904
905 @item
906 @ref{Conditional Compilation}, describes how to model conditional compilation,
907 both with Ada in general and with GNAT facilities in particular.
908
909 @item
910 @ref{Inline Assembler}, shows how to use the inline assembly facility
911 in an Ada program.
912
913 @item
914 @ref{Compatibility and Porting Guide}, contains sections on compatibility
915 of GNAT with other Ada development environments (including Ada 83 systems),
916 to assist in porting code from those environments.
917
918 @ifset unw
919 @item
920 @ref{Microsoft Windows Topics}, presents information relevant to the
921 Microsoft Windows platform.
922 @end ifset
923 @end itemize
924
925 @c *************************************************
926 @node What You Should Know before Reading This Guide
927 @c *************************************************
928 @unnumberedsec What You Should Know before Reading This Guide
929
930 @cindex Ada 95 Language Reference Manual
931 @cindex Ada 2005 Language Reference Manual
932 @noindent
933 This guide assumes a basic familiarity with the Ada 95 language, as
934 described in the International Standard ANSI/ISO/IEC-8652:1995, January
935 1995.
936 It does not require knowledge of the new features introduced by Ada 2005,
937 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
938 and Amendment 1).
939 Both reference manuals are included in the GNAT documentation
940 package.
941
942 @node Related Information
943 @unnumberedsec Related Information
944
945 @noindent
946 For further information about related tools, refer to the following
947 documents:
948
949 @itemize @bullet
950 @item
951 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
952 Reference Manual}, which contains all reference material for the GNAT
953 implementation of Ada.
954
955 @ifset unw
956 @item
957 @cite{Using the GNAT Programming Studio}, which describes the GPS
958 Integrated Development Environment.
959
960 @item
961 @cite{GNAT Programming Studio Tutorial}, which introduces the
962 main GPS features through examples.
963 @end ifset
964
965 @item
966 @cite{Ada 95 Reference Manual}, which contains reference
967 material for the Ada 95 programming language.
968
969 @item
970 @cite{Ada 2005 Reference Manual}, which contains reference
971 material for the Ada 2005 programming language.
972
973 @item
974 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
975 @ifset vms
976 in the GNU:[DOCS] directory,
977 @end ifset
978 for all details on the use of the GNU source-level debugger.
979
980 @item
981 @xref{Top,, The extensible self-documenting text editor, emacs,
982 GNU Emacs Manual},
983 @ifset vms
984 located in the GNU:[DOCS] directory if the EMACS kit is installed,
985 @end ifset
986 for full information on the extensible editor and programming
987 environment Emacs.
988
989 @end itemize
990
991 @c **************
992 @node Conventions
993 @unnumberedsec Conventions
994 @cindex Conventions
995 @cindex Typographical conventions
996
997 @noindent
998 Following are examples of the typographical and graphic conventions used
999 in this guide:
1000
1001 @itemize @bullet
1002 @item
1003 @code{Functions}, @command{utility program names}, @code{standard names},
1004 and @code{classes}.
1005
1006 @item
1007 @option{Option flags}
1008
1009 @item
1010 @file{File names}, @samp{button names}, and @samp{field names}.
1011
1012 @item
1013 @code{Variables}, @env{environment variables}, and @var{metasyntactic
1014 variables}.
1015
1016 @item
1017 @emph{Emphasis}.
1018
1019 @item
1020 @r{[}optional information or parameters@r{]}
1021
1022 @item
1023 Examples are described by text
1024 @smallexample
1025 and then shown this way.
1026 @end smallexample
1027 @end itemize
1028
1029 @noindent
1030 Commands that are entered by the user are preceded in this manual by the
1031 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
1032 uses this sequence as a prompt, then the commands will appear exactly as
1033 you see them in the manual. If your system uses some other prompt, then
1034 the command will appear with the @code{$} replaced by whatever prompt
1035 character you are using.
1036
1037 @ifset unw
1038 Full file names are shown with the ``@code{/}'' character
1039 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
1040 If you are using GNAT on a Windows platform, please note that
1041 the ``@code{\}'' character should be used instead.
1042 @end ifset
1043
1044 @c ****************************
1045 @node Getting Started with GNAT
1046 @chapter Getting Started with GNAT
1047
1048 @noindent
1049 This chapter describes some simple ways of using GNAT to build
1050 executable Ada programs.
1051 @ifset unw
1052 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
1053 show how to use the command line environment.
1054 @ref{Introduction to GPS}, provides a brief
1055 introduction to the GNAT Programming Studio, a visually-oriented
1056 Integrated Development Environment for GNAT.
1057 GPS offers a graphical ``look and feel'', support for development in
1058 other programming languages, comprehensive browsing features, and
1059 many other capabilities.
1060 For information on GPS please refer to
1061 @cite{Using the GNAT Programming Studio}.
1062 @end ifset
1063
1064 @menu
1065 * Running GNAT::
1066 * Running a Simple Ada Program::
1067 * Running a Program with Multiple Units::
1068 * Using the gnatmake Utility::
1069 @ifset vms
1070 * Editing with Emacs::
1071 @end ifset
1072 @ifclear vms
1073 * Introduction to GPS::
1074 @end ifclear
1075 @end menu
1076
1077 @node Running GNAT
1078 @section Running GNAT
1079
1080 @noindent
1081 Three steps are needed to create an executable file from an Ada source
1082 file:
1083
1084 @enumerate
1085 @item
1086 The source file(s) must be compiled.
1087 @item
1088 The file(s) must be bound using the GNAT binder.
1089 @item
1090 All appropriate object files must be linked to produce an executable.
1091 @end enumerate
1092
1093 @noindent
1094 All three steps are most commonly handled by using the @command{gnatmake}
1095 utility program that, given the name of the main program, automatically
1096 performs the necessary compilation, binding and linking steps.
1097
1098 @node Running a Simple Ada Program
1099 @section Running a Simple Ada Program
1100
1101 @noindent
1102 Any text editor may be used to prepare an Ada program.
1103 (If @code{Emacs} is
1104 used, the optional Ada mode may be helpful in laying out the program.)
1105 The
1106 program text is a normal text file. We will assume in our initial
1107 example that you have used your editor to prepare the following
1108 standard format text file:
1109
1110 @smallexample @c ada
1111 @cartouche
1112 with Ada.Text_IO; use Ada.Text_IO;
1113 procedure Hello is
1114 begin
1115    Put_Line ("Hello WORLD!");
1116 end Hello;
1117 @end cartouche
1118 @end smallexample
1119
1120 @noindent
1121 This file should be named @file{hello.adb}.
1122 With the normal default file naming conventions, GNAT requires
1123 that each file
1124 contain a single compilation unit whose file name is the
1125 unit name,
1126 with periods replaced by hyphens; the
1127 extension is @file{ads} for a
1128 spec and @file{adb} for a body.
1129 You can override this default file naming convention by use of the
1130 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1131 Alternatively, if you want to rename your files according to this default
1132 convention, which is probably more convenient if you will be using GNAT
1133 for all your compilations, then the @code{gnatchop} utility
1134 can be used to generate correctly-named source files
1135 (@pxref{Renaming Files Using gnatchop}).
1136
1137 You can compile the program using the following command (@code{$} is used
1138 as the command prompt in the examples in this document):
1139
1140 @smallexample
1141 $ gcc -c hello.adb
1142 @end smallexample
1143
1144 @noindent
1145 @command{gcc} is the command used to run the compiler. This compiler is
1146 capable of compiling programs in several languages, including Ada and
1147 C. It assumes that you have given it an Ada program if the file extension is
1148 either @file{.ads} or @file{.adb}, and it will then call
1149 the GNAT compiler to compile the specified file.
1150
1151 @ifclear vms
1152 The @option{-c} switch is required. It tells @command{gcc} to only do a
1153 compilation. (For C programs, @command{gcc} can also do linking, but this
1154 capability is not used directly for Ada programs, so the @option{-c}
1155 switch must always be present.)
1156 @end ifclear
1157
1158 This compile command generates a file
1159 @file{hello.o}, which is the object
1160 file corresponding to your Ada program. It also generates
1161 an ``Ada Library Information'' file @file{hello.ali},
1162 which contains additional information used to check
1163 that an Ada program is consistent.
1164 To build an executable file,
1165 use @code{gnatbind} to bind the program
1166 and @command{gnatlink} to link it. The
1167 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1168 @file{ALI} file, but the default extension of @file{.ali} can
1169 be omitted. This means that in the most common case, the argument
1170 is simply the name of the main program:
1171
1172 @smallexample
1173 $ gnatbind hello
1174 $ gnatlink hello
1175 @end smallexample
1176
1177 @noindent
1178 A simpler method of carrying out these steps is to use
1179 @command{gnatmake},
1180 a master program that invokes all the required
1181 compilation, binding and linking tools in the correct order. In particular,
1182 @command{gnatmake} automatically recompiles any sources that have been
1183 modified since they were last compiled, or sources that depend
1184 on such modified sources, so that ``version skew'' is avoided.
1185 @cindex Version skew (avoided by @command{gnatmake})
1186
1187 @smallexample
1188 $ gnatmake hello.adb
1189 @end smallexample
1190
1191 @noindent
1192 The result is an executable program called @file{hello}, which can be
1193 run by entering:
1194
1195 @smallexample
1196 $ ^hello^RUN HELLO^
1197 @end smallexample
1198
1199 @noindent
1200 assuming that the current directory is on the search path
1201 for executable programs.
1202
1203 @noindent
1204 and, if all has gone well, you will see
1205
1206 @smallexample
1207 Hello WORLD!
1208 @end smallexample
1209
1210 @noindent
1211 appear in response to this command.
1212
1213 @c ****************************************
1214 @node Running a Program with Multiple Units
1215 @section Running a Program with Multiple Units
1216
1217 @noindent
1218 Consider a slightly more complicated example that has three files: a
1219 main program, and the spec and body of a package:
1220
1221 @smallexample @c ada
1222 @cartouche
1223 @group
1224 package Greetings is
1225    procedure Hello;
1226    procedure Goodbye;
1227 end Greetings;
1228
1229 with Ada.Text_IO; use Ada.Text_IO;
1230 package body Greetings is
1231    procedure Hello is
1232    begin
1233       Put_Line ("Hello WORLD!");
1234    end Hello;
1235
1236    procedure Goodbye is
1237    begin
1238       Put_Line ("Goodbye WORLD!");
1239    end Goodbye;
1240 end Greetings;
1241 @end group
1242
1243 @group
1244 with Greetings;
1245 procedure Gmain is
1246 begin
1247    Greetings.Hello;
1248    Greetings.Goodbye;
1249 end Gmain;
1250 @end group
1251 @end cartouche
1252 @end smallexample
1253
1254 @noindent
1255 Following the one-unit-per-file rule, place this program in the
1256 following three separate files:
1257
1258 @table @file
1259 @item greetings.ads
1260 spec of package @code{Greetings}
1261
1262 @item greetings.adb
1263 body of package @code{Greetings}
1264
1265 @item gmain.adb
1266 body of main program
1267 @end table
1268
1269 @noindent
1270 To build an executable version of
1271 this program, we could use four separate steps to compile, bind, and link
1272 the program, as follows:
1273
1274 @smallexample
1275 $ gcc -c gmain.adb
1276 $ gcc -c greetings.adb
1277 $ gnatbind gmain
1278 $ gnatlink gmain
1279 @end smallexample
1280
1281 @noindent
1282 Note that there is no required order of compilation when using GNAT.
1283 In particular it is perfectly fine to compile the main program first.
1284 Also, it is not necessary to compile package specs in the case where
1285 there is an accompanying body; you only need to compile the body. If you want
1286 to submit these files to the compiler for semantic checking and not code
1287 generation, then use the
1288 @option{-gnatc} switch:
1289
1290 @smallexample
1291 $ gcc -c greetings.ads -gnatc
1292 @end smallexample
1293
1294 @noindent
1295 Although the compilation can be done in separate steps as in the
1296 above example, in practice it is almost always more convenient
1297 to use the @command{gnatmake} tool. All you need to know in this case
1298 is the name of the main program's source file. The effect of the above four
1299 commands can be achieved with a single one:
1300
1301 @smallexample
1302 $ gnatmake gmain.adb
1303 @end smallexample
1304
1305 @noindent
1306 In the next section we discuss the advantages of using @command{gnatmake} in
1307 more detail.
1308
1309 @c *****************************
1310 @node Using the gnatmake Utility
1311 @section Using the @command{gnatmake} Utility
1312
1313 @noindent
1314 If you work on a program by compiling single components at a time using
1315 @command{gcc}, you typically keep track of the units you modify. In order to
1316 build a consistent system, you compile not only these units, but also any
1317 units that depend on the units you have modified.
1318 For example, in the preceding case,
1319 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1320 you edit @file{greetings.ads}, you must recompile both
1321 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1322 units that depend on @file{greetings.ads}.
1323
1324 @code{gnatbind} will warn you if you forget one of these compilation
1325 steps, so that it is impossible to generate an inconsistent program as a
1326 result of forgetting to do a compilation. Nevertheless it is tedious and
1327 error-prone to keep track of dependencies among units.
1328 One approach to handle the dependency-bookkeeping is to use a
1329 makefile. However, makefiles present maintenance problems of their own:
1330 if the dependencies change as you change the program, you must make
1331 sure that the makefile is kept up-to-date manually, which is also an
1332 error-prone process.
1333
1334 The @command{gnatmake} utility takes care of these details automatically.
1335 Invoke it using either one of the following forms:
1336
1337 @smallexample
1338 $ gnatmake gmain.adb
1339 $ gnatmake ^gmain^GMAIN^
1340 @end smallexample
1341
1342 @noindent
1343 The argument is the name of the file containing the main program;
1344 you may omit the extension. @command{gnatmake}
1345 examines the environment, automatically recompiles any files that need
1346 recompiling, and binds and links the resulting set of object files,
1347 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1348 In a large program, it
1349 can be extremely helpful to use @command{gnatmake}, because working out by hand
1350 what needs to be recompiled can be difficult.
1351
1352 Note that @command{gnatmake}
1353 takes into account all the Ada rules that
1354 establish dependencies among units. These include dependencies that result
1355 from inlining subprogram bodies, and from
1356 generic instantiation. Unlike some other
1357 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1358 found by the compiler on a previous compilation, which may possibly
1359 be wrong when sources change. @command{gnatmake} determines the exact set of
1360 dependencies from scratch each time it is run.
1361
1362 @ifset vms
1363 @node Editing with Emacs
1364 @section Editing with Emacs
1365 @cindex Emacs
1366
1367 @noindent
1368 Emacs is an extensible self-documenting text editor that is available in a
1369 separate VMSINSTAL kit.
1370
1371 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1372 click on the Emacs Help menu and run the Emacs Tutorial.
1373 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1374 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1375
1376 Documentation on Emacs and other tools is available in Emacs under the
1377 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1378 use the middle mouse button to select a topic (e.g.@: Emacs).
1379
1380 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1381 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1382 get to the Emacs manual.
1383 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1384 prompt.
1385
1386 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1387 which is sufficiently extensible to provide for a complete programming
1388 environment and shell for the sophisticated user.
1389 @end ifset
1390
1391 @ifclear vms
1392 @node Introduction to GPS
1393 @section Introduction to GPS
1394 @cindex GPS (GNAT Programming Studio)
1395 @cindex GNAT Programming Studio (GPS)
1396 @noindent
1397 Although the command line interface (@command{gnatmake}, etc.) alone
1398 is sufficient, a graphical Interactive Development
1399 Environment can make it easier for you to compose, navigate, and debug
1400 programs.  This section describes the main features of GPS
1401 (``GNAT Programming Studio''), the GNAT graphical IDE.
1402 You will see how to use GPS to build and debug an executable, and
1403 you will also learn some of the basics of the GNAT ``project'' facility.
1404
1405 GPS enables you to do much more than is presented here;
1406 e.g., you can produce a call graph, interface to a third-party
1407 Version Control System, and inspect the generated assembly language
1408 for a program.
1409 Indeed, GPS also supports languages other than Ada.
1410 Such additional information, and an explanation of all of the GPS menu
1411 items. may be found in the on-line help, which includes
1412 a user's guide and a tutorial (these are also accessible from the GNAT
1413 startup menu).
1414
1415 @menu
1416 * Building a New Program with GPS::
1417 * Simple Debugging with GPS::
1418 @end menu
1419
1420 @node Building a New Program with GPS
1421 @subsection Building a New Program with GPS
1422 @noindent
1423 GPS invokes the GNAT compilation tools using information
1424 contained in a @emph{project} (also known as a @emph{project file}):
1425 a collection of properties such
1426 as source directories, identities of main subprograms, tool switches, etc.,
1427 and their associated values.
1428 See @ref{GNAT Project Manager} for details.
1429 In order to run GPS, you will need to either create a new project
1430 or else open an existing one.
1431
1432 This section will explain how you can use GPS to create a project,
1433 to associate Ada source files with a project, and to build and run
1434 programs.
1435
1436 @enumerate
1437 @item @emph{Creating a project}
1438
1439 Invoke GPS, either from the command line or the platform's IDE.
1440 After it starts, GPS will display a ``Welcome'' screen with three
1441 radio buttons:
1442
1443 @itemize @bullet
1444 @item
1445 @code{Start with default project in directory}
1446
1447 @item
1448 @code{Create new project with wizard}
1449
1450 @item
1451 @code{Open existing project}
1452 @end itemize
1453
1454 @noindent
1455 Select @code{Create new project with wizard} and press @code{OK}.
1456 A new window will appear.  In the text box labeled with
1457 @code{Enter the name of the project to create}, type @file{sample}
1458 as the project name.
1459 In the next box, browse to choose the directory in which you
1460 would like to create the project file.
1461 After selecting an appropriate directory, press @code{Forward}.
1462
1463 A window will appear with the title
1464 @code{Version Control System Configuration}.
1465 Simply press @code{Forward}.
1466
1467 A window will appear with the title
1468 @code{Please select the source directories for this project}.
1469 The directory that you specified for the project file will be selected
1470 by default as the one to use for sources; simply press @code{Forward}.
1471
1472 A window will appear with the title
1473 @code{Please select the build directory for this project}.
1474 The directory that you specified for the project file will be selected
1475 by default for object files and executables;
1476 simply press @code{Forward}.
1477
1478 A window will appear with the title
1479 @code{Please select the main units for this project}.
1480 You will supply this information later, after creating the source file.
1481 Simply press @code{Forward} for now.
1482
1483 A window will appear with the title
1484 @code{Please select the switches to build the project}.
1485 Press @code{Apply}.  This will create a project file named
1486 @file{sample.prj} in the directory that you had specified.
1487
1488 @item @emph{Creating and saving the source file}
1489
1490 After you create the new project, a GPS window will appear, which is
1491 partitioned into two main sections:
1492
1493 @itemize @bullet
1494 @item
1495 A @emph{Workspace area}, initially greyed out, which you will use for
1496 creating and editing source files
1497
1498 @item
1499 Directly below, a @emph{Messages area}, which initially displays a
1500 ``Welcome'' message.
1501 (If the Messages area is not visible, drag its border upward to expand it.)
1502 @end itemize
1503
1504 @noindent
1505 Select @code{File} on the menu bar, and then the @code{New} command.
1506 The Workspace area will become white, and you can now
1507 enter the source program explicitly.
1508 Type the following text
1509
1510 @smallexample @c ada
1511 @group
1512 with Ada.Text_IO; use Ada.Text_IO;
1513 procedure Hello is
1514 begin
1515   Put_Line("Hello from GPS!");
1516 end Hello;
1517 @end group
1518 @end smallexample
1519
1520 @noindent
1521 Select @code{File}, then @code{Save As}, and enter the source file name
1522 @file{hello.adb}.
1523 The file will be saved in the same directory you specified as the
1524 location of the default project file.
1525
1526 @item @emph{Updating the project file}
1527
1528 You need to add the new source file to the project.
1529 To do this, select
1530 the @code{Project} menu and then @code{Edit project properties}.
1531 Click the @code{Main files} tab on the left, and then the
1532 @code{Add} button.
1533 Choose @file{hello.adb} from the list, and press @code{Open}.
1534 The project settings window will reflect this action.
1535 Click @code{OK}.
1536
1537 @item @emph{Building and running the program}
1538
1539 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1540 and select @file{hello.adb}.
1541 The Messages window will display the resulting invocations of @command{gcc},
1542 @command{gnatbind}, and @command{gnatlink}
1543 (reflecting the default switch settings from the
1544 project file that you created) and then a ``successful compilation/build''
1545 message.
1546
1547 To run the program, choose the @code{Build} menu, then @code{Run}, and
1548 select @command{hello}.
1549 An @emph{Arguments Selection} window will appear.
1550 There are no command line arguments, so just click @code{OK}.
1551
1552 The Messages window will now display the program's output (the string
1553 @code{Hello from GPS}), and at the bottom of the GPS window a status
1554 update is displayed (@code{Run: hello}).
1555 Close the GPS window (or select @code{File}, then @code{Exit}) to
1556 terminate this GPS session.
1557 @end enumerate
1558
1559 @node Simple Debugging with GPS
1560 @subsection Simple Debugging with GPS
1561 @noindent
1562 This section illustrates basic debugging techniques (setting breakpoints,
1563 examining/modifying variables, single stepping).
1564
1565 @enumerate
1566 @item @emph{Opening a project}
1567
1568 Start GPS and select @code{Open existing project}; browse to
1569 specify the project file @file{sample.prj} that you had created in the
1570 earlier example.
1571
1572 @item @emph{Creating a source file}
1573
1574 Select @code{File}, then @code{New}, and type in the following program:
1575
1576 @smallexample @c ada
1577 @group
1578 with Ada.Text_IO; use Ada.Text_IO;
1579 procedure Example is
1580    Line : String (1..80);
1581    N    : Natural;
1582 begin
1583    Put_Line("Type a line of text at each prompt; an empty line to exit");
1584    loop
1585       Put(": ");
1586       Get_Line (Line, N);
1587       Put_Line (Line (1..N) );
1588       exit when N=0;
1589    end loop;
1590 end Example;
1591 @end group
1592 @end smallexample
1593
1594 @noindent
1595 Select @code{File}, then @code{Save as}, and enter the file name
1596 @file{example.adb}.
1597
1598 @item @emph{Updating the project file}
1599
1600 Add @code{Example} as a new main unit for the project:
1601 @enumerate a
1602 @item
1603 Select @code{Project}, then @code{Edit Project Properties}.
1604
1605 @item
1606 Select the @code{Main files} tab, click @code{Add}, then
1607 select the file @file{example.adb} from the list, and
1608 click @code{Open}.
1609 You will see the file name appear in the list of main units
1610
1611 @item
1612 Click @code{OK}
1613 @end enumerate
1614
1615 @item @emph{Building/running the executable}
1616
1617 To build the executable
1618 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1619
1620 Run the program to see its effect (in the Messages area).
1621 Each line that you enter is displayed; an empty line will
1622 cause the loop to exit and the program to terminate.
1623
1624 @item @emph{Debugging the program}
1625
1626 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1627 which are required for debugging, are on by default when you create
1628 a new project.
1629 Thus unless you intentionally remove these settings, you will be able
1630 to debug any program that you develop using GPS.
1631
1632 @enumerate a
1633 @item @emph{Initializing}
1634
1635 Select @code{Debug}, then @code{Initialize}, then @file{example}
1636
1637 @item @emph{Setting a breakpoint}
1638
1639 After performing the initialization step, you will observe a small
1640 icon to the right of each line number.
1641 This serves as a toggle for breakpoints; clicking the icon will
1642 set a breakpoint at the corresponding line (the icon will change to
1643 a red circle with an ``x''), and clicking it again
1644 will remove the breakpoint / reset the icon.
1645
1646 For purposes of this example, set a breakpoint at line 10 (the
1647 statement @code{Put_Line@ (Line@ (1..N));}
1648
1649 @item @emph{Starting program execution}
1650
1651 Select @code{Debug}, then @code{Run}.  When the
1652 @code{Program Arguments} window appears, click @code{OK}.
1653 A console window will appear; enter some line of text,
1654 e.g.@: @code{abcde}, at the prompt.
1655 The program will pause execution when it gets to the
1656 breakpoint, and the corresponding line is highlighted.
1657
1658 @item @emph{Examining a variable}
1659
1660 Move the mouse over one of the occurrences of the variable @code{N}.
1661 You will see the value (5) displayed, in ``tool tip'' fashion.
1662 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1663 You will see information about @code{N} appear in the @code{Debugger Data}
1664 pane, showing the value as 5.
1665
1666 @item @emph{Assigning a new value to a variable}
1667
1668 Right click on the @code{N} in the @code{Debugger Data} pane, and
1669 select @code{Set value of N}.
1670 When the input window appears, enter the value @code{4} and click
1671 @code{OK}.
1672 This value does not automatically appear in the @code{Debugger Data}
1673 pane; to see it, right click again on the @code{N} in the
1674 @code{Debugger Data} pane and select @code{Update value}.
1675 The new value, 4, will appear in red.
1676
1677 @item @emph{Single stepping}
1678
1679 Select @code{Debug}, then @code{Next}.
1680 This will cause the next statement to be executed, in this case the
1681 call of @code{Put_Line} with the string slice.
1682 Notice in the console window that the displayed string is simply
1683 @code{abcd} and not @code{abcde} which you had entered.
1684 This is because the upper bound of the slice is now 4 rather than 5.
1685
1686 @item @emph{Removing a breakpoint}
1687
1688 Toggle the breakpoint icon at line 10.
1689
1690 @item @emph{Resuming execution from a breakpoint}
1691
1692 Select @code{Debug}, then @code{Continue}.
1693 The program will reach the next iteration of the loop, and
1694 wait for input after displaying the prompt.
1695 This time, just hit the @kbd{Enter} key.
1696 The value of @code{N} will be 0, and the program will terminate.
1697 The console window will disappear.
1698 @end enumerate
1699 @end enumerate
1700 @end ifclear
1701
1702 @node The GNAT Compilation Model
1703 @chapter The GNAT Compilation Model
1704 @cindex GNAT compilation model
1705 @cindex Compilation model
1706
1707 @menu
1708 * Source Representation::
1709 * Foreign Language Representation::
1710 * File Naming Rules::
1711 * Using Other File Names::
1712 * Alternative File Naming Schemes::
1713 * Generating Object Files::
1714 * Source Dependencies::
1715 * The Ada Library Information Files::
1716 * Binding an Ada Program::
1717 * Mixed Language Programming::
1718 @ifclear vms
1719 * Building Mixed Ada & C++ Programs::
1720 * Comparison between GNAT and C/C++ Compilation Models::
1721 @end ifclear
1722 * Comparison between GNAT and Conventional Ada Library Models::
1723 @ifset vms
1724 * Placement of temporary files::
1725 @end ifset
1726 @end menu
1727
1728 @noindent
1729 This chapter describes the compilation model used by GNAT. Although
1730 similar to that used by other languages, such as C and C++, this model
1731 is substantially different from the traditional Ada compilation models,
1732 which are based on a library. The model is initially described without
1733 reference to the library-based model. If you have not previously used an
1734 Ada compiler, you need only read the first part of this chapter. The
1735 last section describes and discusses the differences between the GNAT
1736 model and the traditional Ada compiler models. If you have used other
1737 Ada compilers, this section will help you to understand those
1738 differences, and the advantages of the GNAT model.
1739
1740 @node Source Representation
1741 @section Source Representation
1742 @cindex Latin-1
1743
1744 @noindent
1745 Ada source programs are represented in standard text files, using
1746 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1747 7-bit ASCII set, plus additional characters used for
1748 representing foreign languages (@pxref{Foreign Language Representation}
1749 for support of non-USA character sets). The format effector characters
1750 are represented using their standard ASCII encodings, as follows:
1751
1752 @table @code
1753 @item VT
1754 @findex VT
1755 Vertical tab, @code{16#0B#}
1756
1757 @item HT
1758 @findex HT
1759 Horizontal tab, @code{16#09#}
1760
1761 @item CR
1762 @findex CR
1763 Carriage return, @code{16#0D#}
1764
1765 @item LF
1766 @findex LF
1767 Line feed, @code{16#0A#}
1768
1769 @item FF
1770 @findex FF
1771 Form feed, @code{16#0C#}
1772 @end table
1773
1774 @noindent
1775 Source files are in standard text file format. In addition, GNAT will
1776 recognize a wide variety of stream formats, in which the end of
1777 physical lines is marked by any of the following sequences:
1778 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1779 in accommodating files that are imported from other operating systems.
1780
1781 @cindex End of source file
1782 @cindex Source file, end
1783 @findex SUB
1784 The end of a source file is normally represented by the physical end of
1785 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1786 recognized as signalling the end of the source file. Again, this is
1787 provided for compatibility with other operating systems where this
1788 code is used to represent the end of file.
1789
1790 Each file contains a single Ada compilation unit, including any pragmas
1791 associated with the unit. For example, this means you must place a
1792 package declaration (a package @dfn{spec}) and the corresponding body in
1793 separate files. An Ada @dfn{compilation} (which is a sequence of
1794 compilation units) is represented using a sequence of files. Similarly,
1795 you will place each subunit or child unit in a separate file.
1796
1797 @node Foreign Language Representation
1798 @section Foreign Language Representation
1799
1800 @noindent
1801 GNAT supports the standard character sets defined in Ada as well as
1802 several other non-standard character sets for use in localized versions
1803 of the compiler (@pxref{Character Set Control}).
1804 @menu
1805 * Latin-1::
1806 * Other 8-Bit Codes::
1807 * Wide Character Encodings::
1808 @end menu
1809
1810 @node Latin-1
1811 @subsection Latin-1
1812 @cindex Latin-1
1813
1814 @noindent
1815 The basic character set is Latin-1. This character set is defined by ISO
1816 standard 8859, part 1. The lower half (character codes @code{16#00#}
1817 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1818 is used to represent additional characters. These include extended letters
1819 used by European languages, such as French accents, the vowels with umlauts
1820 used in German, and the extra letter A-ring used in Swedish.
1821
1822 @findex Ada.Characters.Latin_1
1823 For a complete list of Latin-1 codes and their encodings, see the source
1824 file of library unit @code{Ada.Characters.Latin_1} in file
1825 @file{a-chlat1.ads}.
1826 You may use any of these extended characters freely in character or
1827 string literals. In addition, the extended characters that represent
1828 letters can be used in identifiers.
1829
1830 @node Other 8-Bit Codes
1831 @subsection Other 8-Bit Codes
1832
1833 @noindent
1834 GNAT also supports several other 8-bit coding schemes:
1835
1836 @table @asis
1837 @item ISO 8859-2 (Latin-2)
1838 @cindex Latin-2
1839 @cindex ISO 8859-2
1840 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1841 equivalence.
1842
1843 @item ISO 8859-3 (Latin-3)
1844 @cindex Latin-3
1845 @cindex ISO 8859-3
1846 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1847 equivalence.
1848
1849 @item ISO 8859-4 (Latin-4)
1850 @cindex Latin-4
1851 @cindex ISO 8859-4
1852 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1853 equivalence.
1854
1855 @item ISO 8859-5 (Cyrillic)
1856 @cindex ISO 8859-5
1857 @cindex Cyrillic
1858 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1859 lowercase equivalence.
1860
1861 @item ISO 8859-15 (Latin-9)
1862 @cindex ISO 8859-15
1863 @cindex Latin-9
1864 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1865 lowercase equivalence
1866
1867 @item IBM PC (code page 437)
1868 @cindex code page 437
1869 This code page is the normal default for PCs in the U.S. It corresponds
1870 to the original IBM PC character set. This set has some, but not all, of
1871 the extended Latin-1 letters, but these letters do not have the same
1872 encoding as Latin-1. In this mode, these letters are allowed in
1873 identifiers with uppercase and lowercase equivalence.
1874
1875 @item IBM PC (code page 850)
1876 @cindex code page 850
1877 This code page is a modification of 437 extended to include all the
1878 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1879 mode, all these letters are allowed in identifiers with uppercase and
1880 lowercase equivalence.
1881
1882 @item Full Upper 8-bit
1883 Any character in the range 80-FF allowed in identifiers, and all are
1884 considered distinct. In other words, there are no uppercase and lowercase
1885 equivalences in this range. This is useful in conjunction with
1886 certain encoding schemes used for some foreign character sets (e.g.,
1887 the typical method of representing Chinese characters on the PC).
1888
1889 @item No Upper-Half
1890 No upper-half characters in the range 80-FF are allowed in identifiers.
1891 This gives Ada 83 compatibility for identifier names.
1892 @end table
1893
1894 @noindent
1895 For precise data on the encodings permitted, and the uppercase and lowercase
1896 equivalences that are recognized, see the file @file{csets.adb} in
1897 the GNAT compiler sources. You will need to obtain a full source release
1898 of GNAT to obtain this file.
1899
1900 @node Wide Character Encodings
1901 @subsection Wide Character Encodings
1902
1903 @noindent
1904 GNAT allows wide character codes to appear in character and string
1905 literals, and also optionally in identifiers, by means of the following
1906 possible encoding schemes:
1907
1908 @table @asis
1909
1910 @item Hex Coding
1911 In this encoding, a wide character is represented by the following five
1912 character sequence:
1913
1914 @smallexample
1915 ESC a b c d
1916 @end smallexample
1917
1918 @noindent
1919 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1920 characters (using uppercase letters) of the wide character code. For
1921 example, ESC A345 is used to represent the wide character with code
1922 @code{16#A345#}.
1923 This scheme is compatible with use of the full Wide_Character set.
1924
1925 @item Upper-Half Coding
1926 @cindex Upper-Half Coding
1927 The wide character with encoding @code{16#abcd#} where the upper bit is on
1928 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1929 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1930 character, but is not required to be in the upper half. This method can
1931 be also used for shift-JIS or EUC, where the internal coding matches the
1932 external coding.
1933
1934 @item Shift JIS Coding
1935 @cindex Shift JIS Coding
1936 A wide character is represented by a two-character sequence,
1937 @code{16#ab#} and
1938 @code{16#cd#}, with the restrictions described for upper-half encoding as
1939 described above. The internal character code is the corresponding JIS
1940 character according to the standard algorithm for Shift-JIS
1941 conversion. Only characters defined in the JIS code set table can be
1942 used with this encoding method.
1943
1944 @item EUC Coding
1945 @cindex EUC Coding
1946 A wide character is represented by a two-character sequence
1947 @code{16#ab#} and
1948 @code{16#cd#}, with both characters being in the upper half. The internal
1949 character code is the corresponding JIS character according to the EUC
1950 encoding algorithm. Only characters defined in the JIS code set table
1951 can be used with this encoding method.
1952
1953 @item UTF-8 Coding
1954 A wide character is represented using
1955 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1956 10646-1/Am.2. Depending on the character value, the representation
1957 is a one, two, or three byte sequence:
1958 @smallexample
1959 @iftex
1960 @leftskip=.7cm
1961 @end iftex
1962 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1963 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1964 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1965
1966 @end smallexample
1967
1968 @noindent
1969 where the @var{xxx} bits correspond to the left-padded bits of the
1970 16-bit character value. Note that all lower half ASCII characters
1971 are represented as ASCII bytes and all upper half characters and
1972 other wide characters are represented as sequences of upper-half
1973 (The full UTF-8 scheme allows for encoding 31-bit characters as
1974 6-byte sequences, but in this implementation, all UTF-8 sequences
1975 of four or more bytes length will be treated as illegal).
1976 @item Brackets Coding
1977 In this encoding, a wide character is represented by the following eight
1978 character sequence:
1979
1980 @smallexample
1981 [ " a b c d " ]
1982 @end smallexample
1983
1984 @noindent
1985 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1986 characters (using uppercase letters) of the wide character code. For
1987 example, [``A345''] is used to represent the wide character with code
1988 @code{16#A345#}. It is also possible (though not required) to use the
1989 Brackets coding for upper half characters. For example, the code
1990 @code{16#A3#} can be represented as @code{[``A3'']}.
1991
1992 This scheme is compatible with use of the full Wide_Character set,
1993 and is also the method used for wide character encoding in the standard
1994 ACVC (Ada Compiler Validation Capability) test suite distributions.
1995
1996 @end table
1997
1998 @noindent
1999 Note: Some of these coding schemes do not permit the full use of the
2000 Ada character set. For example, neither Shift JIS, nor EUC allow the
2001 use of the upper half of the Latin-1 set.
2002
2003 @node File Naming Rules
2004 @section File Naming Rules
2005
2006 @noindent
2007 The default file name is determined by the name of the unit that the
2008 file contains. The name is formed by taking the full expanded name of
2009 the unit and replacing the separating dots with hyphens and using
2010 ^lowercase^uppercase^ for all letters.
2011
2012 An exception arises if the file name generated by the above rules starts
2013 with one of the characters
2014 @ifset vms
2015 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
2016 @end ifset
2017 @ifclear vms
2018 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
2019 @end ifclear
2020 and the second character is a
2021 minus. In this case, the character ^tilde^dollar sign^ is used in place
2022 of the minus. The reason for this special rule is to avoid clashes with
2023 the standard names for child units of the packages System, Ada,
2024 Interfaces, and GNAT, which use the prefixes
2025 @ifset vms
2026 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
2027 @end ifset
2028 @ifclear vms
2029 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
2030 @end ifclear
2031 respectively.
2032
2033 The file extension is @file{.ads} for a spec and
2034 @file{.adb} for a body. The following list shows some
2035 examples of these rules.
2036
2037 @table @file
2038 @item main.ads
2039 Main (spec)
2040 @item main.adb
2041 Main (body)
2042 @item arith_functions.ads
2043 Arith_Functions (package spec)
2044 @item arith_functions.adb
2045 Arith_Functions (package body)
2046 @item func-spec.ads
2047 Func.Spec (child package spec)
2048 @item func-spec.adb
2049 Func.Spec (child package body)
2050 @item main-sub.adb
2051 Sub (subunit of Main)
2052 @item ^a~bad.adb^A$BAD.ADB^
2053 A.Bad (child package body)
2054 @end table
2055
2056 @noindent
2057 Following these rules can result in excessively long
2058 file names if corresponding
2059 unit names are long (for example, if child units or subunits are
2060 heavily nested). An option is available to shorten such long file names
2061 (called file name ``krunching''). This may be particularly useful when
2062 programs being developed with GNAT are to be used on operating systems
2063 with limited file name lengths. @xref{Using gnatkr}.
2064
2065 Of course, no file shortening algorithm can guarantee uniqueness over
2066 all possible unit names; if file name krunching is used, it is your
2067 responsibility to ensure no name clashes occur. Alternatively you
2068 can specify the exact file names that you want used, as described
2069 in the next section. Finally, if your Ada programs are migrating from a
2070 compiler with a different naming convention, you can use the gnatchop
2071 utility to produce source files that follow the GNAT naming conventions.
2072 (For details @pxref{Renaming Files Using gnatchop}.)
2073
2074 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2075 systems, case is not significant. So for example on @code{Windows XP}
2076 if the canonical name is @code{main-sub.adb}, you can use the file name
2077 @code{Main-Sub.adb} instead. However, case is significant for other
2078 operating systems, so for example, if you want to use other than
2079 canonically cased file names on a Unix system, you need to follow
2080 the procedures described in the next section.
2081
2082 @node Using Other File Names
2083 @section Using Other File Names
2084 @cindex File names
2085
2086 @noindent
2087 In the previous section, we have described the default rules used by
2088 GNAT to determine the file name in which a given unit resides. It is
2089 often convenient to follow these default rules, and if you follow them,
2090 the compiler knows without being explicitly told where to find all
2091 the files it needs.
2092
2093 However, in some cases, particularly when a program is imported from
2094 another Ada compiler environment, it may be more convenient for the
2095 programmer to specify which file names contain which units. GNAT allows
2096 arbitrary file names to be used by means of the Source_File_Name pragma.
2097 The form of this pragma is as shown in the following examples:
2098 @cindex Source_File_Name pragma
2099
2100 @smallexample @c ada
2101 @cartouche
2102 pragma Source_File_Name (My_Utilities.Stacks,
2103   Spec_File_Name => "myutilst_a.ada");
2104 pragma Source_File_name (My_Utilities.Stacks,
2105   Body_File_Name => "myutilst.ada");
2106 @end cartouche
2107 @end smallexample
2108
2109 @noindent
2110 As shown in this example, the first argument for the pragma is the unit
2111 name (in this example a child unit). The second argument has the form
2112 of a named association. The identifier
2113 indicates whether the file name is for a spec or a body;
2114 the file name itself is given by a string literal.
2115
2116 The source file name pragma is a configuration pragma, which means that
2117 normally it will be placed in the @file{gnat.adc}
2118 file used to hold configuration
2119 pragmas that apply to a complete compilation environment.
2120 For more details on how the @file{gnat.adc} file is created and used
2121 see @ref{Handling of Configuration Pragmas}.
2122 @cindex @file{gnat.adc}
2123
2124 @ifclear vms
2125 GNAT allows completely arbitrary file names to be specified using the
2126 source file name pragma. However, if the file name specified has an
2127 extension other than @file{.ads} or @file{.adb} it is necessary to use
2128 a special syntax when compiling the file. The name in this case must be
2129 preceded by the special sequence @option{-x} followed by a space and the name
2130 of the language, here @code{ada}, as in:
2131
2132 @smallexample
2133 $ gcc -c -x ada peculiar_file_name.sim
2134 @end smallexample
2135 @end ifclear
2136
2137 @noindent
2138 @command{gnatmake} handles non-standard file names in the usual manner (the
2139 non-standard file name for the main program is simply used as the
2140 argument to gnatmake). Note that if the extension is also non-standard,
2141 then it must be included in the @command{gnatmake} command, it may not
2142 be omitted.
2143
2144 @node Alternative File Naming Schemes
2145 @section Alternative File Naming Schemes
2146 @cindex File naming schemes, alternative
2147 @cindex File names
2148
2149 In the previous section, we described the use of the @code{Source_File_Name}
2150 pragma to allow arbitrary names to be assigned to individual source files.
2151 However, this approach requires one pragma for each file, and especially in
2152 large systems can result in very long @file{gnat.adc} files, and also create
2153 a maintenance problem.
2154
2155 GNAT also provides a facility for specifying systematic file naming schemes
2156 other than the standard default naming scheme previously described. An
2157 alternative scheme for naming is specified by the use of
2158 @code{Source_File_Name} pragmas having the following format:
2159 @cindex Source_File_Name pragma
2160
2161 @smallexample @c ada
2162 pragma Source_File_Name (
2163    Spec_File_Name  => FILE_NAME_PATTERN
2164  @r{[},Casing          => CASING_SPEC@r{]}
2165  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2166
2167 pragma Source_File_Name (
2168    Body_File_Name  => FILE_NAME_PATTERN
2169  @r{[},Casing          => CASING_SPEC@r{]}
2170  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
2171
2172 pragma Source_File_Name (
2173    Subunit_File_Name  => FILE_NAME_PATTERN
2174  @r{[},Casing             => CASING_SPEC@r{]}
2175  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
2176
2177 FILE_NAME_PATTERN ::= STRING_LITERAL
2178 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2179 @end smallexample
2180
2181 @noindent
2182 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2183 It contains a single asterisk character, and the unit name is substituted
2184 systematically for this asterisk. The optional parameter
2185 @code{Casing} indicates
2186 whether the unit name is to be all upper-case letters, all lower-case letters,
2187 or mixed-case. If no
2188 @code{Casing} parameter is used, then the default is all
2189 ^lower-case^upper-case^.
2190
2191 The optional @code{Dot_Replacement} string is used to replace any periods
2192 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2193 argument is used then separating dots appear unchanged in the resulting
2194 file name.
2195 Although the above syntax indicates that the
2196 @code{Casing} argument must appear
2197 before the @code{Dot_Replacement} argument, but it
2198 is also permissible to write these arguments in the opposite order.
2199
2200 As indicated, it is possible to specify different naming schemes for
2201 bodies, specs, and subunits. Quite often the rule for subunits is the
2202 same as the rule for bodies, in which case, there is no need to give
2203 a separate @code{Subunit_File_Name} rule, and in this case the
2204 @code{Body_File_name} rule is used for subunits as well.
2205
2206 The separate rule for subunits can also be used to implement the rather
2207 unusual case of a compilation environment (e.g.@: a single directory) which
2208 contains a subunit and a child unit with the same unit name. Although
2209 both units cannot appear in the same partition, the Ada Reference Manual
2210 allows (but does not require) the possibility of the two units coexisting
2211 in the same environment.
2212
2213 The file name translation works in the following steps:
2214
2215 @itemize @bullet
2216
2217 @item
2218 If there is a specific @code{Source_File_Name} pragma for the given unit,
2219 then this is always used, and any general pattern rules are ignored.
2220
2221 @item
2222 If there is a pattern type @code{Source_File_Name} pragma that applies to
2223 the unit, then the resulting file name will be used if the file exists. If
2224 more than one pattern matches, the latest one will be tried first, and the
2225 first attempt resulting in a reference to a file that exists will be used.
2226
2227 @item
2228 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2229 for which the corresponding file exists, then the standard GNAT default
2230 naming rules are used.
2231
2232 @end itemize
2233
2234 @noindent
2235 As an example of the use of this mechanism, consider a commonly used scheme
2236 in which file names are all lower case, with separating periods copied
2237 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2238 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2239 two pragmas appear:
2240
2241 @smallexample @c ada
2242 pragma Source_File_Name
2243   (Spec_File_Name => "*.1.ada");
2244 pragma Source_File_Name
2245   (Body_File_Name => "*.2.ada");
2246 @end smallexample
2247
2248 @noindent
2249 The default GNAT scheme is actually implemented by providing the following
2250 default pragmas internally:
2251
2252 @smallexample @c ada
2253 pragma Source_File_Name
2254   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2255 pragma Source_File_Name
2256   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2257 @end smallexample
2258
2259 @noindent
2260 Our final example implements a scheme typically used with one of the
2261 Ada 83 compilers, where the separator character for subunits was ``__''
2262 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2263 by adding @file{.ADA}, and subunits by
2264 adding @file{.SEP}. All file names were
2265 upper case. Child units were not present of course since this was an
2266 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2267 the same double underscore separator for child units.
2268
2269 @smallexample @c ada
2270 pragma Source_File_Name
2271   (Spec_File_Name => "*_.ADA",
2272    Dot_Replacement => "__",
2273    Casing = Uppercase);
2274 pragma Source_File_Name
2275   (Body_File_Name => "*.ADA",
2276    Dot_Replacement => "__",
2277    Casing = Uppercase);
2278 pragma Source_File_Name
2279   (Subunit_File_Name => "*.SEP",
2280    Dot_Replacement => "__",
2281    Casing = Uppercase);
2282 @end smallexample
2283
2284 @node Generating Object Files
2285 @section Generating Object Files
2286
2287 @noindent
2288 An Ada program consists of a set of source files, and the first step in
2289 compiling the program is to generate the corresponding object files.
2290 These are generated by compiling a subset of these source files.
2291 The files you need to compile are the following:
2292
2293 @itemize @bullet
2294 @item
2295 If a package spec has no body, compile the package spec to produce the
2296 object file for the package.
2297
2298 @item
2299 If a package has both a spec and a body, compile the body to produce the
2300 object file for the package. The source file for the package spec need
2301 not be compiled in this case because there is only one object file, which
2302 contains the code for both the spec and body of the package.
2303
2304 @item
2305 For a subprogram, compile the subprogram body to produce the object file
2306 for the subprogram. The spec, if one is present, is as usual in a
2307 separate file, and need not be compiled.
2308
2309 @item
2310 @cindex Subunits
2311 In the case of subunits, only compile the parent unit. A single object
2312 file is generated for the entire subunit tree, which includes all the
2313 subunits.
2314
2315 @item
2316 Compile child units independently of their parent units
2317 (though, of course, the spec of all the ancestor unit must be present in order
2318 to compile a child unit).
2319
2320 @item
2321 @cindex Generics
2322 Compile generic units in the same manner as any other units. The object
2323 files in this case are small dummy files that contain at most the
2324 flag used for elaboration checking. This is because GNAT always handles generic
2325 instantiation by means of macro expansion. However, it is still necessary to
2326 compile generic units, for dependency checking and elaboration purposes.
2327 @end itemize
2328
2329 @noindent
2330 The preceding rules describe the set of files that must be compiled to
2331 generate the object files for a program. Each object file has the same
2332 name as the corresponding source file, except that the extension is
2333 @file{.o} as usual.
2334
2335 You may wish to compile other files for the purpose of checking their
2336 syntactic and semantic correctness. For example, in the case where a
2337 package has a separate spec and body, you would not normally compile the
2338 spec. However, it is convenient in practice to compile the spec to make
2339 sure it is error-free before compiling clients of this spec, because such
2340 compilations will fail if there is an error in the spec.
2341
2342 GNAT provides an option for compiling such files purely for the
2343 purposes of checking correctness; such compilations are not required as
2344 part of the process of building a program. To compile a file in this
2345 checking mode, use the @option{-gnatc} switch.
2346
2347 @node Source Dependencies
2348 @section Source Dependencies
2349
2350 @noindent
2351 A given object file clearly depends on the source file which is compiled
2352 to produce it. Here we are using @dfn{depends} in the sense of a typical
2353 @code{make} utility; in other words, an object file depends on a source
2354 file if changes to the source file require the object file to be
2355 recompiled.
2356 In addition to this basic dependency, a given object may depend on
2357 additional source files as follows:
2358
2359 @itemize @bullet
2360 @item
2361 If a file being compiled @code{with}'s a unit @var{X}, the object file
2362 depends on the file containing the spec of unit @var{X}. This includes
2363 files that are @code{with}'ed implicitly either because they are parents
2364 of @code{with}'ed child units or they are run-time units required by the
2365 language constructs used in a particular unit.
2366
2367 @item
2368 If a file being compiled instantiates a library level generic unit, the
2369 object file depends on both the spec and body files for this generic
2370 unit.
2371
2372 @item
2373 If a file being compiled instantiates a generic unit defined within a
2374 package, the object file depends on the body file for the package as
2375 well as the spec file.
2376
2377 @item
2378 @findex Inline
2379 @cindex @option{-gnatn} switch
2380 If a file being compiled contains a call to a subprogram for which
2381 pragma @code{Inline} applies and inlining is activated with the
2382 @option{-gnatn} switch, the object file depends on the file containing the
2383 body of this subprogram as well as on the file containing the spec. Note
2384 that for inlining to actually occur as a result of the use of this switch,
2385 it is necessary to compile in optimizing mode.
2386
2387 @cindex @option{-gnatN} switch
2388 The use of @option{-gnatN} activates  inlining optimization
2389 that is performed by the front end of the compiler. This inlining does
2390 not require that the code generation be optimized. Like @option{-gnatn},
2391 the use of this switch generates additional dependencies.
2392
2393 When using a gcc-based back end (in practice this means using any version
2394 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
2395 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
2396 Historically front end inlining was more extensive than the gcc back end
2397 inlining, but that is no longer the case.
2398
2399 @item
2400 If an object file @file{O} depends on the proper body of a subunit through
2401 inlining or instantiation, it depends on the parent unit of the subunit.
2402 This means that any modification of the parent unit or one of its subunits
2403 affects the compilation of @file{O}.
2404
2405 @item
2406 The object file for a parent unit depends on all its subunit body files.
2407
2408 @item
2409 The previous two rules meant that for purposes of computing dependencies and
2410 recompilation, a body and all its subunits are treated as an indivisible whole.
2411
2412 @noindent
2413 These rules are applied transitively: if unit @code{A} @code{with}'s
2414 unit @code{B}, whose elaboration calls an inlined procedure in package
2415 @code{C}, the object file for unit @code{A} will depend on the body of
2416 @code{C}, in file @file{c.adb}.
2417
2418 The set of dependent files described by these rules includes all the
2419 files on which the unit is semantically dependent, as dictated by the
2420 Ada language standard. However, it is a superset of what the
2421 standard describes, because it includes generic, inline, and subunit
2422 dependencies.
2423
2424 An object file must be recreated by recompiling the corresponding source
2425 file if any of the source files on which it depends are modified. For
2426 example, if the @code{make} utility is used to control compilation,
2427 the rule for an Ada object file must mention all the source files on
2428 which the object file depends, according to the above definition.
2429 The determination of the necessary
2430 recompilations is done automatically when one uses @command{gnatmake}.
2431 @end itemize
2432
2433 @node The Ada Library Information Files
2434 @section The Ada Library Information Files
2435 @cindex Ada Library Information files
2436 @cindex @file{ALI} files
2437
2438 @noindent
2439 Each compilation actually generates two output files. The first of these
2440 is the normal object file that has a @file{.o} extension. The second is a
2441 text file containing full dependency information. It has the same
2442 name as the source file, but an @file{.ali} extension.
2443 This file is known as the Ada Library Information (@file{ALI}) file.
2444 The following information is contained in the @file{ALI} file.
2445
2446 @itemize @bullet
2447 @item
2448 Version information (indicates which version of GNAT was used to compile
2449 the unit(s) in question)
2450
2451 @item
2452 Main program information (including priority and time slice settings,
2453 as well as the wide character encoding used during compilation).
2454
2455 @item
2456 List of arguments used in the @command{gcc} command for the compilation
2457
2458 @item
2459 Attributes of the unit, including configuration pragmas used, an indication
2460 of whether the compilation was successful, exception model used etc.
2461
2462 @item
2463 A list of relevant restrictions applying to the unit (used for consistency)
2464 checking.
2465
2466 @item
2467 Categorization information (e.g.@: use of pragma @code{Pure}).
2468
2469 @item
2470 Information on all @code{with}'ed units, including presence of
2471 @code{Elaborate} or @code{Elaborate_All} pragmas.
2472
2473 @item
2474 Information from any @code{Linker_Options} pragmas used in the unit
2475
2476 @item
2477 Information on the use of @code{Body_Version} or @code{Version}
2478 attributes in the unit.
2479
2480 @item
2481 Dependency information. This is a list of files, together with
2482 time stamp and checksum information. These are files on which
2483 the unit depends in the sense that recompilation is required
2484 if any of these units are modified.
2485
2486 @item
2487 Cross-reference data. Contains information on all entities referenced
2488 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2489 provide cross-reference information.
2490
2491 @end itemize
2492
2493 @noindent
2494 For a full detailed description of the format of the @file{ALI} file,
2495 see the source of the body of unit @code{Lib.Writ}, contained in file
2496 @file{lib-writ.adb} in the GNAT compiler sources.
2497
2498 @node Binding an Ada Program
2499 @section Binding an Ada Program
2500
2501 @noindent
2502 When using languages such as C and C++, once the source files have been
2503 compiled the only remaining step in building an executable program
2504 is linking the object modules together. This means that it is possible to
2505 link an inconsistent version of a program, in which two units have
2506 included different versions of the same header.
2507
2508 The rules of Ada do not permit such an inconsistent program to be built.
2509 For example, if two clients have different versions of the same package,
2510 it is illegal to build a program containing these two clients.
2511 These rules are enforced by the GNAT binder, which also determines an
2512 elaboration order consistent with the Ada rules.
2513
2514 The GNAT binder is run after all the object files for a program have
2515 been created. It is given the name of the main program unit, and from
2516 this it determines the set of units required by the program, by reading the
2517 corresponding ALI files. It generates error messages if the program is
2518 inconsistent or if no valid order of elaboration exists.
2519
2520 If no errors are detected, the binder produces a main program, in Ada by
2521 default, that contains calls to the elaboration procedures of those
2522 compilation unit that require them, followed by
2523 a call to the main program. This Ada program is compiled to generate the
2524 object file for the main program. The name of
2525 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2526 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2527 main program unit.
2528
2529 Finally, the linker is used to build the resulting executable program,
2530 using the object from the main program from the bind step as well as the
2531 object files for the Ada units of the program.
2532
2533 @node Mixed Language Programming
2534 @section Mixed Language Programming
2535 @cindex Mixed Language Programming
2536
2537 @noindent
2538 This section describes how to develop a mixed-language program,
2539 specifically one that comprises units in both Ada and C.
2540
2541 @menu
2542 * Interfacing to C::
2543 * Calling Conventions::
2544 @end menu
2545
2546 @node Interfacing to C
2547 @subsection Interfacing to C
2548 @noindent
2549 Interfacing Ada with a foreign language such as C involves using
2550 compiler directives to import and/or export entity definitions in each
2551 language---using @code{extern} statements in C, for instance, and the
2552 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2553 A full treatment of these topics is provided in Appendix B, section 1
2554 of the Ada Reference Manual.
2555
2556 There are two ways to build a program using GNAT that contains some Ada
2557 sources and some foreign language sources, depending on whether or not
2558 the main subprogram is written in Ada.  Here is a source example with
2559 the main subprogram in Ada:
2560
2561 @smallexample
2562 /* file1.c */
2563 #include <stdio.h>
2564
2565 void print_num (int num)
2566 @{
2567   printf ("num is %d.\n", num);
2568   return;
2569 @}
2570
2571 /* file2.c */
2572
2573 /* num_from_Ada is declared in my_main.adb */
2574 extern int num_from_Ada;
2575
2576 int get_num (void)
2577 @{
2578   return num_from_Ada;
2579 @}
2580 @end smallexample
2581
2582 @smallexample @c ada
2583 --  my_main.adb
2584 procedure My_Main is
2585
2586    --  Declare then export an Integer entity called num_from_Ada
2587    My_Num : Integer := 10;
2588    pragma Export (C, My_Num, "num_from_Ada");
2589
2590    --  Declare an Ada function spec for Get_Num, then use
2591    --  C function get_num for the implementation.
2592    function Get_Num return Integer;
2593    pragma Import (C, Get_Num, "get_num");
2594
2595    --  Declare an Ada procedure spec for Print_Num, then use
2596    --  C function print_num for the implementation.
2597    procedure Print_Num (Num : Integer);
2598    pragma Import (C, Print_Num, "print_num");
2599
2600 begin
2601    Print_Num (Get_Num);
2602 end My_Main;
2603 @end smallexample
2604
2605 @enumerate
2606 @item
2607 To build this example, first compile the foreign language files to
2608 generate object files:
2609 @smallexample
2610 ^gcc -c file1.c^gcc -c FILE1.C^
2611 ^gcc -c file2.c^gcc -c FILE2.C^
2612 @end smallexample
2613
2614 @item
2615 Then, compile the Ada units to produce a set of object files and ALI
2616 files:
2617 @smallexample
2618 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2619 @end smallexample
2620
2621 @item
2622 Run the Ada binder on the Ada main program:
2623 @smallexample
2624 gnatbind my_main.ali
2625 @end smallexample
2626
2627 @item
2628 Link the Ada main program, the Ada objects and the other language
2629 objects:
2630 @smallexample
2631 gnatlink my_main.ali file1.o file2.o
2632 @end smallexample
2633 @end enumerate
2634
2635 The last three steps can be grouped in a single command:
2636 @smallexample
2637 gnatmake my_main.adb -largs file1.o file2.o
2638 @end smallexample
2639
2640 @cindex Binder output file
2641 @noindent
2642 If the main program is in a language other than Ada, then you may have
2643 more than one entry point into the Ada subsystem. You must use a special
2644 binder option to generate callable routines that initialize and
2645 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2646 Calls to the initialization and finalization routines must be inserted
2647 in the main program, or some other appropriate point in the code. The
2648 call to initialize the Ada units must occur before the first Ada
2649 subprogram is called, and the call to finalize the Ada units must occur
2650 after the last Ada subprogram returns. The binder will place the
2651 initialization and finalization subprograms into the
2652 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2653 sources.  To illustrate, we have the following example:
2654
2655 @smallexample
2656 /* main.c */
2657 extern void adainit (void);
2658 extern void adafinal (void);
2659 extern int add (int, int);
2660 extern int sub (int, int);
2661
2662 int main (int argc, char *argv[])
2663 @{
2664   int a = 21, b = 7;
2665
2666   adainit();
2667
2668   /* Should print "21 + 7 = 28" */
2669   printf ("%d + %d = %d\n", a, b, add (a, b));
2670   /* Should print "21 - 7 = 14" */
2671   printf ("%d - %d = %d\n", a, b, sub (a, b));
2672
2673   adafinal();
2674 @}
2675 @end smallexample
2676
2677 @smallexample @c ada
2678 --  unit1.ads
2679 package Unit1 is
2680    function Add (A, B : Integer) return Integer;
2681    pragma Export (C, Add, "add");
2682 end Unit1;
2683
2684 --  unit1.adb
2685 package body Unit1 is
2686    function Add (A, B : Integer) return Integer is
2687    begin
2688       return A + B;
2689    end Add;
2690 end Unit1;
2691
2692 --  unit2.ads
2693 package Unit2 is
2694    function Sub (A, B : Integer) return Integer;
2695    pragma Export (C, Sub, "sub");
2696 end Unit2;
2697
2698 --  unit2.adb
2699 package body Unit2 is
2700    function Sub (A, B : Integer) return Integer is
2701    begin
2702       return A - B;
2703    end Sub;
2704 end Unit2;
2705 @end smallexample
2706
2707 @enumerate
2708 @item
2709 The build procedure for this application is similar to the last
2710 example's.  First, compile the foreign language files to generate object
2711 files:
2712 @smallexample
2713 ^gcc -c main.c^gcc -c main.c^
2714 @end smallexample
2715
2716 @item
2717 Next, compile the Ada units to produce a set of object files and ALI
2718 files:
2719 @smallexample
2720 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2721 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2722 @end smallexample
2723
2724 @item
2725 Run the Ada binder on every generated ALI file.  Make sure to use the
2726 @option{-n} option to specify a foreign main program:
2727 @smallexample
2728 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2729 @end smallexample
2730
2731 @item
2732 Link the Ada main program, the Ada objects and the foreign language
2733 objects. You need only list the last ALI file here:
2734 @smallexample
2735 gnatlink unit2.ali main.o -o exec_file
2736 @end smallexample
2737
2738 This procedure yields a binary executable called @file{exec_file}.
2739 @end enumerate
2740
2741 @noindent
2742 Depending on the circumstances (for example when your non-Ada main object
2743 does not provide symbol @code{main}), you may also need to instruct the
2744 GNAT linker not to include the standard startup objects by passing the
2745 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2746
2747 @node Calling Conventions
2748 @subsection Calling Conventions
2749 @cindex Foreign Languages
2750 @cindex Calling Conventions
2751 GNAT follows standard calling sequence conventions and will thus interface
2752 to any other language that also follows these conventions. The following
2753 Convention identifiers are recognized by GNAT:
2754
2755 @table @code
2756 @cindex Interfacing to Ada
2757 @cindex Other Ada compilers
2758 @cindex Convention Ada
2759 @item Ada
2760 This indicates that the standard Ada calling sequence will be
2761 used and all Ada data items may be passed without any limitations in the
2762 case where GNAT is used to generate both the caller and callee. It is also
2763 possible to mix GNAT generated code and code generated by another Ada
2764 compiler. In this case, the data types should be restricted to simple
2765 cases, including primitive types. Whether complex data types can be passed
2766 depends on the situation. Probably it is safe to pass simple arrays, such
2767 as arrays of integers or floats. Records may or may not work, depending
2768 on whether both compilers lay them out identically. Complex structures
2769 involving variant records, access parameters, tasks, or protected types,
2770 are unlikely to be able to be passed.
2771
2772 Note that in the case of GNAT running
2773 on a platform that supports HP Ada 83, a higher degree of compatibility
2774 can be guaranteed, and in particular records are layed out in an identical
2775 manner in the two compilers. Note also that if output from two different
2776 compilers is mixed, the program is responsible for dealing with elaboration
2777 issues. Probably the safest approach is to write the main program in the
2778 version of Ada other than GNAT, so that it takes care of its own elaboration
2779 requirements, and then call the GNAT-generated adainit procedure to ensure
2780 elaboration of the GNAT components. Consult the documentation of the other
2781 Ada compiler for further details on elaboration.
2782
2783 However, it is not possible to mix the tasking run time of GNAT and
2784 HP Ada 83, All the tasking operations must either be entirely within
2785 GNAT compiled sections of the program, or entirely within HP Ada 83
2786 compiled sections of the program.
2787
2788 @cindex Interfacing to Assembly
2789 @cindex Convention Assembler
2790 @item Assembler
2791 Specifies assembler as the convention. In practice this has the
2792 same effect as convention Ada (but is not equivalent in the sense of being
2793 considered the same convention).
2794
2795 @cindex Convention Asm
2796 @findex Asm
2797 @item Asm
2798 Equivalent to Assembler.
2799
2800 @cindex Interfacing to COBOL
2801 @cindex Convention COBOL
2802 @findex COBOL
2803 @item COBOL
2804 Data will be passed according to the conventions described
2805 in section B.4 of the Ada Reference Manual.
2806
2807 @findex C
2808 @cindex Interfacing to C
2809 @cindex Convention C
2810 @item C
2811 Data will be passed according to the conventions described
2812 in section B.3 of the Ada Reference Manual.
2813
2814 A note on interfacing to a C ``varargs'' function:
2815 @findex C varargs function
2816 @cindex Interfacing to C varargs function
2817 @cindex varargs function interfaces
2818
2819 @itemize @bullet
2820 @item
2821 In C, @code{varargs} allows a function to take a variable number of
2822 arguments. There is no direct equivalent in this to Ada. One
2823 approach that can be used is to create a C wrapper for each
2824 different profile and then interface to this C wrapper. For
2825 example, to print an @code{int} value using @code{printf},
2826 create a C function @code{printfi} that takes two arguments, a
2827 pointer to a string and an int, and calls @code{printf}.
2828 Then in the Ada program, use pragma @code{Import} to
2829 interface to @code{printfi}.
2830
2831 @item
2832 It may work on some platforms to directly interface to
2833 a @code{varargs} function by providing a specific Ada profile
2834 for a particular call. However, this does not work on
2835 all platforms, since there is no guarantee that the
2836 calling sequence for a two argument normal C function
2837 is the same as for calling a @code{varargs} C function with
2838 the same two arguments.
2839 @end itemize
2840
2841 @cindex Convention Default
2842 @findex Default
2843 @item Default
2844 Equivalent to C.
2845
2846 @cindex Convention External
2847 @findex External
2848 @item External
2849 Equivalent to C.
2850
2851 @ifclear vms
2852 @findex C++
2853 @cindex Interfacing to C++
2854 @cindex Convention C++
2855 @item C_Plus_Plus (or CPP)
2856 This stands for C++. For most purposes this is identical to C.
2857 See the separate description of the specialized GNAT pragmas relating to
2858 C++ interfacing for further details.
2859 @end ifclear
2860
2861 @findex Fortran
2862 @cindex Interfacing to Fortran
2863 @cindex Convention Fortran
2864 @item Fortran
2865 Data will be passed according to the conventions described
2866 in section B.5 of the Ada Reference Manual.
2867
2868 @item Intrinsic
2869 This applies to an intrinsic operation, as defined in the Ada
2870 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2871 this means that the body of the subprogram is provided by the compiler itself,
2872 usually by means of an efficient code sequence, and that the user does not
2873 supply an explicit body for it. In an application program, the pragma may
2874 be applied to the following sets of names:
2875
2876 @itemize @bullet
2877 @item
2878 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2879 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2880 two formal parameters. The
2881 first one must be a signed integer type or a modular type with a binary
2882 modulus, and the second parameter must be of type Natural.
2883 The return type must be the same as the type of the first argument. The size
2884 of this type can only be 8, 16, 32, or 64.
2885
2886 @item
2887 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2888 The corresponding operator declaration must have parameters and result type
2889 that have the same root numeric type (for example, all three are long_float
2890 types). This simplifies the definition of operations that use type checking
2891 to perform dimensional checks:
2892
2893 @smallexample @c ada
2894 type Distance is new Long_Float;
2895 type Time     is new Long_Float;
2896 type Velocity is new Long_Float;
2897 function "/" (D : Distance; T : Time)
2898   return Velocity;
2899 pragma Import (Intrinsic, "/");
2900 @end smallexample
2901
2902 @noindent
2903 This common idiom is often programmed with a generic definition and an
2904 explicit body. The pragma makes it simpler to introduce such declarations.
2905 It incurs no overhead in compilation time or code size, because it is
2906 implemented as a single machine instruction.
2907
2908 @item
2909 General subprogram entities, to bind an Ada subprogram declaration to
2910 a compiler builtin by name with back-ends where such interfaces are
2911 available. A typical example is the set of ``__builtin'' functions
2912 exposed by the GCC back-end, as in the following example:
2913
2914 @smallexample @c ada
2915    function builtin_sqrt (F : Float) return Float;
2916    pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2917 @end smallexample
2918
2919 Most of the GCC builtins are accessible this way, and as for other
2920 import conventions (e.g. C), it is the user's responsibility to ensure
2921 that the Ada subprogram profile matches the underlying builtin
2922 expectations.
2923 @end itemize
2924
2925 @noindent
2926
2927 @ifset unw
2928 @findex Stdcall
2929 @cindex Convention Stdcall
2930 @item Stdcall
2931 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2932 and specifies that the @code{Stdcall} calling sequence will be used,
2933 as defined by the NT API. Nevertheless, to ease building
2934 cross-platform bindings this convention will be handled as a @code{C} calling
2935 convention on non-Windows platforms.
2936
2937 @findex DLL
2938 @cindex Convention DLL
2939 @item DLL
2940 This is equivalent to @code{Stdcall}.
2941
2942 @findex Win32
2943 @cindex Convention Win32
2944 @item Win32
2945 This is equivalent to @code{Stdcall}.
2946 @end ifset
2947
2948 @findex Stubbed
2949 @cindex Convention Stubbed
2950 @item Stubbed
2951 This is a special convention that indicates that the compiler
2952 should provide a stub body that raises @code{Program_Error}.
2953 @end table
2954
2955 @noindent
2956 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2957 that can be used to parametrize conventions and allow additional synonyms
2958 to be specified. For example if you have legacy code in which the convention
2959 identifier Fortran77 was used for Fortran, you can use the configuration
2960 pragma:
2961
2962 @smallexample @c ada
2963 pragma Convention_Identifier (Fortran77, Fortran);
2964 @end smallexample
2965
2966 @noindent
2967 And from now on the identifier Fortran77 may be used as a convention
2968 identifier (for example in an @code{Import} pragma) with the same
2969 meaning as Fortran.
2970
2971 @ifclear vms
2972 @node Building Mixed Ada & C++ Programs
2973 @section Building Mixed Ada and C++ Programs
2974
2975 @noindent
2976 A programmer inexperienced with mixed-language development may find that
2977 building an application containing both Ada and C++ code can be a
2978 challenge.  This section gives a few
2979 hints that should make this task easier. The first section addresses
2980 the differences between interfacing with C and interfacing with C++.
2981 The second section
2982 looks into the delicate problem of linking the complete application from
2983 its Ada and C++ parts. The last section gives some hints on how the GNAT
2984 run-time library can be adapted in order to allow inter-language dispatching
2985 with a new C++ compiler.
2986
2987 @menu
2988 * Interfacing to C++::
2989 * Linking a Mixed C++ & Ada Program::
2990 * A Simple Example::
2991 * Interfacing with C++ constructors::
2992 * Interfacing with C++ at the Class Level::
2993 @end menu
2994
2995 @node Interfacing to C++
2996 @subsection Interfacing to C++
2997
2998 @noindent
2999 GNAT supports interfacing with the G++ compiler (or any C++ compiler
3000 generating code that is compatible with the G++ Application Binary
3001 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
3002
3003 @noindent
3004 Interfacing can be done at 3 levels: simple data, subprograms, and
3005 classes. In the first two cases, GNAT offers a specific @code{Convention
3006 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
3007 Usually, C++ mangles the names of subprograms. To generate proper mangled
3008 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
3009 This problem can also be addressed manually in two ways:
3010
3011 @itemize @bullet
3012 @item
3013 by modifying the C++ code in order to force a C convention using
3014 the @code{extern "C"} syntax.
3015
3016 @item
3017 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
3018 Link_Name argument of the pragma import.
3019 @end itemize
3020
3021 @noindent
3022 Interfacing at the class level can be achieved by using the GNAT specific
3023 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
3024 gnat_rm, GNAT Reference Manual}, for additional information.
3025
3026 @node Linking a Mixed C++ & Ada Program
3027 @subsection Linking a Mixed C++ & Ada Program
3028
3029 @noindent
3030 Usually the linker of the C++ development system must be used to link
3031 mixed applications because most C++ systems will resolve elaboration
3032 issues (such as calling constructors on global class instances)
3033 transparently during the link phase. GNAT has been adapted to ease the
3034 use of a foreign linker for the last phase. Three cases can be
3035 considered:
3036 @enumerate
3037
3038 @item
3039 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3040 The C++ linker can simply be called by using the C++ specific driver
3041 called @code{g++}.
3042
3043 Note that if the C++ code uses inline functions, you will need to
3044 compile your C++ code with the @code{-fkeep-inline-functions} switch in
3045 order to provide an existing function implementation that the Ada code can
3046 link with.
3047
3048 @smallexample
3049 $ g++ -c -fkeep-inline-functions file1.C
3050 $ g++ -c -fkeep-inline-functions file2.C
3051 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
3052 @end smallexample
3053
3054 @item
3055 Using GNAT and G++ from two different GCC installations: If both
3056 compilers are on the @env{PATH}, the previous method may be used. It is
3057 important to note that environment variables such as
3058 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
3059 @env{GCC_ROOT} will affect both compilers
3060 at the same time and may make one of the two compilers operate
3061 improperly if set during invocation of the wrong compiler.  It is also
3062 very important that the linker uses the proper @file{libgcc.a} GCC
3063 library -- that is, the one from the C++ compiler installation. The
3064 implicit link command as suggested in the @command{gnatmake} command
3065 from the former example can be replaced by an explicit link command with
3066 the full-verbosity option in order to verify which library is used:
3067 @smallexample
3068 $ gnatbind ada_unit
3069 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3070 @end smallexample
3071 If there is a problem due to interfering environment variables, it can
3072 be worked around by using an intermediate script. The following example
3073 shows the proper script to use when GNAT has not been installed at its
3074 default location and g++ has been installed at its default location:
3075
3076 @smallexample
3077 $ cat ./my_script
3078 #!/bin/sh
3079 unset BINUTILS_ROOT
3080 unset GCC_ROOT
3081 c++ $*
3082 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3083 @end smallexample
3084
3085 @item
3086 Using a non-GNU C++ compiler: The commands previously described can be
3087 used to insure that the C++ linker is used. Nonetheless, you need to add
3088 a few more parameters to the link command line, depending on the exception
3089 mechanism used.
3090
3091 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3092 to the libgcc libraries are required:
3093
3094 @smallexample
3095 $ cat ./my_script
3096 #!/bin/sh
3097 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3098 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3099 @end smallexample
3100
3101 Where CC is the name of the non-GNU C++ compiler.
3102
3103 If the @code{zero cost} exception mechanism is used, and the platform
3104 supports automatic registration of exception tables (e.g.@: Solaris or IRIX),
3105 paths to more objects are required:
3106
3107 @smallexample
3108 $ cat ./my_script
3109 #!/bin/sh
3110 CC `gcc -print-file-name=crtbegin.o` $* \
3111 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3112 `gcc -print-file-name=crtend.o`
3113 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3114 @end smallexample
3115
3116 If the @code{zero cost} exception mechanism is used, and the platform
3117 doesn't support automatic registration of exception tables (e.g.@: HP-UX,
3118 Tru64 or AIX), the simple approach described above will not work and
3119 a pre-linking phase using GNAT will be necessary.
3120
3121 @end enumerate
3122
3123 Another alternative is to use the @command{gprbuild} multi-language builder
3124 which has a large knowledge base and knows how to link Ada and C++ code
3125 together automatically in most cases.
3126
3127 @node A Simple Example
3128 @subsection  A Simple Example
3129 @noindent
3130 The following example, provided as part of the GNAT examples, shows how
3131 to achieve procedural interfacing between Ada and C++ in both
3132 directions. The C++ class A has two methods. The first method is exported
3133 to Ada by the means of an extern C wrapper function. The second method
3134 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3135 a limited record with a layout comparable to the C++ class. The Ada
3136 subprogram, in turn, calls the C++ method. So, starting from the C++
3137 main program, the process passes back and forth between the two
3138 languages.
3139
3140 @noindent
3141 Here are the compilation commands:
3142 @smallexample
3143 $ gnatmake -c simple_cpp_interface
3144 $ g++ -c cpp_main.C
3145 $ g++ -c ex7.C
3146 $ gnatbind -n simple_cpp_interface
3147 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
3148       -lstdc++ ex7.o cpp_main.o
3149 @end smallexample
3150
3151 @noindent
3152 Here are the corresponding sources:
3153 @smallexample
3154
3155 //cpp_main.C
3156
3157 #include "ex7.h"
3158
3159 extern "C" @{
3160   void adainit (void);
3161   void adafinal (void);
3162   void method1 (A *t);
3163 @}
3164
3165 void method1 (A *t)
3166 @{
3167   t->method1 ();
3168 @}
3169
3170 int main ()
3171 @{
3172   A obj;
3173   adainit ();
3174   obj.method2 (3030);
3175   adafinal ();
3176 @}
3177
3178 //ex7.h
3179
3180 class Origin @{
3181  public:
3182   int o_value;
3183 @};
3184 class A : public Origin @{
3185  public:
3186   void method1 (void);
3187   void method2 (int v);
3188   A();
3189   int   a_value;
3190 @};
3191
3192 //ex7.C
3193
3194 #include "ex7.h"
3195 #include <stdio.h>
3196
3197 extern "C" @{ void ada_method2 (A *t, int v);@}
3198
3199 void A::method1 (void)
3200 @{
3201   a_value = 2020;
3202   printf ("in A::method1, a_value = %d \n",a_value);
3203
3204 @}
3205
3206 void A::method2 (int v)
3207 @{
3208    ada_method2 (this, v);
3209    printf ("in A::method2, a_value = %d \n",a_value);
3210
3211 @}
3212
3213 A::A(void)
3214 @{
3215    a_value = 1010;
3216   printf ("in A::A, a_value = %d \n",a_value);
3217 @}
3218 @end smallexample
3219
3220 @smallexample @c ada
3221 -- Ada sources
3222 package body Simple_Cpp_Interface is
3223
3224    procedure Ada_Method2 (This : in out A; V : Integer) is
3225    begin
3226       Method1 (This);
3227       This.A_Value := V;
3228    end Ada_Method2;
3229
3230 end Simple_Cpp_Interface;
3231
3232 with System;
3233 package Simple_Cpp_Interface is
3234    type A is limited
3235       record
3236          Vptr    : System.Address;
3237          O_Value : Integer;
3238          A_Value : Integer;
3239       end record;
3240    pragma Convention (C, A);
3241
3242    procedure Method1 (This : in out A);
3243    pragma Import (C, Method1);
3244
3245    procedure Ada_Method2 (This : in out A; V : Integer);
3246    pragma Export (C, Ada_Method2);
3247
3248 end Simple_Cpp_Interface;
3249 @end smallexample
3250
3251 @node Interfacing with C++ constructors
3252 @subsection Interfacing with C++ constructors
3253 @noindent
3254
3255 In order to interface with C++ constructors GNAT provides the
3256 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
3257 gnat_rm, GNAT Reference Manual}, for additional information).
3258 In this section we present some common uses of C++ constructors
3259 in mixed-languages programs in GNAT.
3260
3261 Let us assume that we need to interface with the following
3262 C++ class:
3263
3264 @smallexample
3265 @b{class} Root @{
3266 @b{public}:
3267   int  a_value;
3268   int  b_value;
3269   @b{virtual} int Get_Value ();
3270   Root();              // Default constructor
3271   Root(int v);         // 1st non-default constructor
3272   Root(int v, int w);  // 2nd non-default constructor
3273 @};
3274 @end smallexample
3275
3276 For this purpose we can write the following package spec (further
3277 information on how to build this spec is available in
3278 @ref{Interfacing with C++ at the Class Level} and
3279 @ref{Generating Ada Bindings for C and C++ headers}).
3280
3281 @smallexample @c ada
3282 with Interfaces.C; use Interfaces.C;
3283 package Pkg_Root is
3284   type Root is tagged limited record
3285      A_Value : int;
3286      B_Value : int;
3287   end record;
3288   pragma Import (CPP, Root);
3289
3290   function Get_Value (Obj : Root) return int;
3291   pragma Import (CPP, Get_Value);
3292
3293   function Constructor return Root;
3294   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
3295
3296   function Constructor (v : Integer) return Root;
3297   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
3298
3299   function Constructor (v, w : Integer) return Root;
3300   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
3301 end Pkg_Root;
3302 @end smallexample
3303
3304 On the Ada side the constructor is represented by a function (whose
3305 name is arbitrary) that returns the classwide type corresponding to
3306 the imported C++ class. Although the constructor is described as a
3307 function, it is typically a procedure with an extra implicit argument
3308 (the object being initialized) at the implementation level. GNAT
3309 issues the appropriate call, whatever it is, to get the object
3310 properly initialized.
3311
3312 Constructors can only appear in the following contexts:
3313
3314 @itemize @bullet
3315 @item
3316 On the right side of an initialization of an object of type @var{T}.
3317 @item
3318 On the right side of an initialization of a record component of type @var{T}.
3319 @item
3320 In an Ada 2005 limited aggregate.
3321 @item
3322 In an Ada 2005 nested limited aggregate.
3323 @item
3324 In an Ada 2005 limited aggregate that initializes an object built in
3325 place by an extended return statement.
3326 @end itemize
3327
3328 @noindent
3329 In a declaration of an object whose type is a class imported from C++,
3330 either the default C++ constructor is implicitly called by GNAT, or
3331 else the required C++ constructor must be explicitly called in the
3332 expression that initializes the object. For example:
3333
3334 @smallexample @c ada
3335   Obj1 : Root;
3336   Obj2 : Root := Constructor;
3337   Obj3 : Root := Constructor (v => 10);
3338   Obj4 : Root := Constructor (30, 40);
3339 @end smallexample
3340
3341 The first two declarations are equivalent: in both cases the default C++
3342 constructor is invoked (in the former case the call to the constructor is
3343 implicit, and in the latter case the call is explicit in the object
3344 declaration). @code{Obj3} is initialized by the C++ non-default constructor
3345 that takes an integer argument, and @code{Obj4} is initialized by the
3346 non-default C++ constructor that takes two integers.
3347
3348 Let us derive the imported C++ class in the Ada side. For example:
3349
3350 @smallexample @c ada
3351   type DT is new Root with record
3352      C_Value : Natural := 2009;
3353   end record;
3354 @end smallexample
3355
3356 In this case the components DT inherited from the C++ side must be
3357 initialized by a C++ constructor, and the additional Ada components
3358 of type DT are initialized by GNAT. The initialization of such an
3359 object is done either by default, or by means of a function returning
3360 an aggregate of type DT, or by means of an extension aggregate.
3361
3362 @smallexample @c ada
3363   Obj5 : DT;
3364   Obj6 : DT := Function_Returning_DT (50);
3365   Obj7 : DT := (Constructor (30,40) with C_Value => 50);
3366 @end smallexample
3367
3368 The declaration of @code{Obj5} invokes the default constructors: the
3369 C++ default constructor of the parent type takes care of the initialization
3370 of the components inherited from Root, and GNAT takes care of the default
3371 initialization of the additional Ada components of type DT (that is,
3372 @code{C_Value} is initialized to value 2009). The order of invocation of
3373 the constructors is consistent with the order of elaboration required by
3374 Ada and C++. That is, the constructor of the parent type is always called
3375 before the constructor of the derived type.
3376
3377 Let us now consider a record that has components whose type is imported
3378 from C++. For example:
3379
3380 @smallexample @c ada
3381   type Rec1 is limited record
3382      Data1 : Root := Constructor (10);
3383      Value : Natural := 1000;
3384   end record;
3385
3386   type Rec2 (D : Integer := 20) is limited record
3387      Rec   : Rec1;
3388      Data2 : Root := Constructor (D, 30);
3389   end record;
3390 @end smallexample
3391
3392 The initialization of an object of type @code{Rec2} will call the
3393 non-default C++ constructors specified for the imported components.
3394 For example:
3395
3396 @smallexample @c ada
3397   Obj8 : Rec2 (40);
3398 @end smallexample
3399
3400 Using Ada 2005 we can use limited aggregates to initialize an object
3401 invoking C++ constructors that differ from those specified in the type
3402 declarations. For example:
3403
3404 @smallexample @c ada
3405   Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
3406                           others => <>),
3407                   others => <>);
3408 @end smallexample
3409
3410 The above declaration uses an Ada 2005 limited aggregate to
3411 initialize @code{Obj9}, and the C++ constructor that has two integer
3412 arguments is invoked to initialize the @code{Data1} component instead
3413 of the constructor specified in the declaration of type @code{Rec1}. In
3414 Ada 2005 the box in the aggregate indicates that unspecified components
3415 are initialized using the expression (if any) available in the component
3416 declaration. That is, in this case discriminant @code{D} is initialized
3417 to value @code{20}, @code{Value} is initialized to value 1000, and the
3418 non-default C++ constructor that handles two integers takes care of
3419 initializing component @code{Data2} with values @code{20,30}.
3420
3421 In Ada 2005 we can use the extended return statement to build the Ada
3422 equivalent to C++ non-default constructors. For example:
3423
3424 @smallexample @c ada
3425   function Constructor (V : Integer) return Rec2 is
3426   begin
3427      return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
3428                                    others => <>),
3429                            others => <>) do
3430         --  Further actions required for construction of
3431         --  objects of type Rec2
3432         ...
3433      end record;
3434   end Constructor;
3435 @end smallexample
3436
3437 In this example the extended return statement construct is used to
3438 build in place the returned object whose components are initialized
3439 by means of a limited aggregate. Any further action associated with
3440 the constructor can be placed inside the construct.
3441
3442 @node Interfacing with C++ at the Class Level
3443 @subsection Interfacing with C++ at the Class Level
3444 @noindent
3445 In this section we demonstrate the GNAT features for interfacing with
3446 C++ by means of an example making use of Ada 2005 abstract interface
3447 types. This example consists of a classification of animals; classes
3448 have been used to model our main classification of animals, and
3449 interfaces provide support for the management of secondary
3450 classifications. We first demonstrate a case in which the types and
3451 constructors are defined on the C++ side and imported from the Ada
3452 side, and latter the reverse case.
3453
3454 The root of our derivation will be the @code{Animal} class, with a
3455 single private attribute (the @code{Age} of the animal) and two public
3456 primitives to set and get the value of this attribute.
3457
3458 @smallexample
3459 @b{class} Animal @{
3460  @b{public}:
3461    @b{virtual} void Set_Age (int New_Age);
3462    @b{virtual} int Age ();
3463  @b{private}:
3464    int Age_Count;
3465 @};
3466 @end smallexample
3467
3468 Abstract interface types are defined in C++ by means of classes with pure
3469 virtual functions and no data members. In our example we will use two
3470 interfaces that provide support for the common management of @code{Carnivore}
3471 and @code{Domestic} animals:
3472
3473 @smallexample
3474 @b{class} Carnivore @{
3475 @b{public}:
3476    @b{virtual} int Number_Of_Teeth () = 0;
3477 @};
3478
3479 @b{class} Domestic @{
3480 @b{public}:
3481    @b{virtual void} Set_Owner (char* Name) = 0;
3482 @};
3483 @end smallexample
3484
3485 Using these declarations, we can now say that a @code{Dog} is an animal that is
3486 both Carnivore and Domestic, that is:
3487
3488 @smallexample
3489 @b{class} Dog : Animal, Carnivore, Domestic @{
3490  @b{public}:
3491    @b{virtual} int  Number_Of_Teeth ();
3492    @b{virtual} void Set_Owner (char* Name);
3493
3494    Dog(); // Constructor
3495  @b{private}:
3496    int  Tooth_Count;
3497    char *Owner;
3498 @};
3499 @end smallexample
3500
3501 In the following examples we will assume that the previous declarations are
3502 located in a file named @code{animals.h}. The following package demonstrates
3503 how to import these C++ declarations from the Ada side:
3504
3505 @smallexample @c ada
3506 with Interfaces.C.Strings; use Interfaces.C.Strings;
3507 package Animals is
3508   type Carnivore is interface;
3509   pragma Convention (C_Plus_Plus, Carnivore);
3510   function Number_Of_Teeth (X : Carnivore)
3511      return Natural is abstract;
3512
3513   type Domestic is interface;
3514   pragma Convention (C_Plus_Plus, Set_Owner);
3515   procedure Set_Owner
3516     (X    : in out Domestic;
3517      Name : Chars_Ptr) is abstract;
3518
3519   type Animal is tagged record
3520     Age : Natural := 0;
3521   end record;
3522   pragma Import (C_Plus_Plus, Animal);
3523
3524   procedure Set_Age (X : in out Animal; Age : Integer);
3525   pragma Import (C_Plus_Plus, Set_Age);
3526
3527   function Age (X : Animal) return Integer;
3528   pragma Import (C_Plus_Plus, Age);
3529
3530   type Dog is new Animal and Carnivore and Domestic with record
3531     Tooth_Count : Natural;
3532     Owner       : String (1 .. 30);
3533   end record;
3534   pragma Import (C_Plus_Plus, Dog);
3535
3536   function Number_Of_Teeth (A : Dog) return Integer;
3537   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3538
3539   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3540   pragma Import (C_Plus_Plus, Set_Owner);
3541
3542   function New_Dog return Dog;
3543   pragma CPP_Constructor (New_Dog);
3544   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3545 end Animals;
3546 @end smallexample
3547
3548 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3549 interfacing with these C++ classes is easy. The only requirement is that all
3550 the primitives and components must be declared exactly in the same order in
3551 the two languages.
3552
3553 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3554 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3555 the arguments to the called primitives will be the same as for C++. For the
3556 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3557 to indicate that they have been defined on the C++ side; this is required
3558 because the dispatch table associated with these tagged types will be built
3559 in the C++ side and therefore will not contain the predefined Ada primitives
3560 which Ada would otherwise expect.
3561
3562 As the reader can see there is no need to indicate the C++ mangled names
3563 associated with each subprogram because it is assumed that all the calls to
3564 these primitives will be dispatching calls. The only exception is the
3565 constructor, which must be registered with the compiler by means of
3566 @code{pragma CPP_Constructor} and needs to provide its associated C++
3567 mangled name because the Ada compiler generates direct calls to it.
3568
3569 With the above packages we can now declare objects of type Dog on the Ada side
3570 and dispatch calls to the corresponding subprograms on the C++ side. We can
3571 also extend the tagged type Dog with further fields and primitives, and
3572 override some of its C++ primitives on the Ada side. For example, here we have
3573 a type derivation defined on the Ada side that inherits all the dispatching
3574 primitives of the ancestor from the C++ side.
3575
3576 @smallexample
3577 @b{with} Animals; @b{use} Animals;
3578 @b{package} Vaccinated_Animals @b{is}
3579   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3580   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3581 @b{end} Vaccinated_Animals;
3582 @end smallexample
3583
3584 It is important to note that, because of the ABI compatibility, the programmer
3585 does not need to add any further information to indicate either the object
3586 layout or the dispatch table entry associated with each dispatching operation.
3587
3588 Now let us define all the types and constructors on the Ada side and export
3589 them to C++, using the same hierarchy of our previous example:
3590
3591 @smallexample @c ada
3592 with Interfaces.C.Strings;
3593 use Interfaces.C.Strings;
3594 package Animals is
3595   type Carnivore is interface;
3596   pragma Convention (C_Plus_Plus, Carnivore);
3597   function Number_Of_Teeth (X : Carnivore)
3598      return Natural is abstract;
3599
3600   type Domestic is interface;
3601   pragma Convention (C_Plus_Plus, Set_Owner);
3602   procedure Set_Owner
3603     (X    : in out Domestic;
3604      Name : Chars_Ptr) is abstract;
3605
3606   type Animal is tagged record
3607     Age : Natural := 0;
3608   end record;
3609   pragma Convention (C_Plus_Plus, Animal);
3610
3611   procedure Set_Age (X : in out Animal; Age : Integer);
3612   pragma Export (C_Plus_Plus, Set_Age);
3613
3614   function Age (X : Animal) return Integer;
3615   pragma Export (C_Plus_Plus, Age);
3616
3617   type Dog is new Animal and Carnivore and Domestic with record
3618     Tooth_Count : Natural;
3619     Owner       : String (1 .. 30);
3620   end record;
3621   pragma Convention (C_Plus_Plus, Dog);
3622
3623   function Number_Of_Teeth (A : Dog) return Integer;
3624   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3625
3626   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3627   pragma Export (C_Plus_Plus, Set_Owner);
3628
3629   function New_Dog return Dog'Class;
3630   pragma Export (C_Plus_Plus, New_Dog);
3631 end Animals;
3632 @end smallexample
3633
3634 Compared with our previous example the only difference is the use of
3635 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3636 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3637 nothing else to be done; as explained above, the only requirement is that all
3638 the primitives and components are declared in exactly the same order.
3639
3640 For completeness, let us see a brief C++ main program that uses the
3641 declarations available in @code{animals.h} (presented in our first example) to
3642 import and use the declarations from the Ada side, properly initializing and
3643 finalizing the Ada run-time system along the way:
3644
3645 @smallexample
3646 @b{#include} "animals.h"
3647 @b{#include} <iostream>
3648 @b{using namespace} std;
3649
3650 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3651 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3652 void Check_Animal (Animal *obj)       @{@dots{}@}
3653 void Check_Dog (Dog *obj)             @{@dots{}@}
3654
3655 @b{extern} "C" @{
3656   void adainit (void);
3657   void adafinal (void);
3658   Dog* new_dog ();
3659 @}
3660
3661 void test ()
3662 @{
3663   Dog *obj = new_dog();  // Ada constructor
3664   Check_Carnivore (obj); // Check secondary DT
3665   Check_Domestic (obj);  // Check secondary DT
3666   Check_Animal (obj);    // Check primary DT
3667   Check_Dog (obj);       // Check primary DT
3668 @}
3669
3670 int main ()
3671 @{
3672   adainit ();  test();  adafinal ();
3673   return 0;
3674 @}
3675 @end smallexample
3676
3677 @node Comparison between GNAT and C/C++ Compilation Models
3678 @section Comparison between GNAT and C/C++ Compilation Models
3679
3680 @noindent
3681 The GNAT model of compilation is close to the C and C++ models. You can
3682 think of Ada specs as corresponding to header files in C. As in C, you
3683 don't need to compile specs; they are compiled when they are used. The
3684 Ada @code{with} is similar in effect to the @code{#include} of a C
3685 header.
3686
3687 One notable difference is that, in Ada, you may compile specs separately
3688 to check them for semantic and syntactic accuracy. This is not always
3689 possible with C headers because they are fragments of programs that have
3690 less specific syntactic or semantic rules.
3691
3692 The other major difference is the requirement for running the binder,
3693 which performs two important functions. First, it checks for
3694 consistency. In C or C++, the only defense against assembling
3695 inconsistent programs lies outside the compiler, in a makefile, for
3696 example. The binder satisfies the Ada requirement that it be impossible
3697 to construct an inconsistent program when the compiler is used in normal
3698 mode.
3699
3700 @cindex Elaboration order control
3701 The other important function of the binder is to deal with elaboration
3702 issues. There are also elaboration issues in C++ that are handled
3703 automatically. This automatic handling has the advantage of being
3704 simpler to use, but the C++ programmer has no control over elaboration.
3705 Where @code{gnatbind} might complain there was no valid order of
3706 elaboration, a C++ compiler would simply construct a program that
3707 malfunctioned at run time.
3708 @end ifclear
3709
3710 @node Comparison between GNAT and Conventional Ada Library Models
3711 @section Comparison between GNAT and Conventional Ada Library Models
3712
3713 @noindent
3714 This section is intended for Ada programmers who have
3715 used an Ada compiler implementing the traditional Ada library
3716 model, as described in the Ada Reference Manual.
3717
3718 @cindex GNAT library
3719 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3720 source files themselves acts as the library. Compiling Ada programs does
3721 not generate any centralized information, but rather an object file and
3722 a ALI file, which are of interest only to the binder and linker.
3723 In a traditional system, the compiler reads information not only from
3724 the source file being compiled, but also from the centralized library.
3725 This means that the effect of a compilation depends on what has been
3726 previously compiled. In particular:
3727
3728 @itemize @bullet
3729 @item
3730 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3731 to the version of the unit most recently compiled into the library.
3732
3733 @item
3734 Inlining is effective only if the necessary body has already been
3735 compiled into the library.
3736
3737 @item
3738 Compiling a unit may obsolete other units in the library.
3739 @end itemize
3740
3741 @noindent
3742 In GNAT, compiling one unit never affects the compilation of any other
3743 units because the compiler reads only source files. Only changes to source
3744 files can affect the results of a compilation. In particular:
3745
3746 @itemize @bullet
3747 @item
3748 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3749 to the source version of the unit that is currently accessible to the
3750 compiler.
3751
3752 @item
3753 @cindex Inlining
3754 Inlining requires the appropriate source files for the package or
3755 subprogram bodies to be available to the compiler. Inlining is always
3756 effective, independent of the order in which units are complied.
3757
3758 @item
3759 Compiling a unit never affects any other compilations. The editing of
3760 sources may cause previous compilations to be out of date if they
3761 depended on the source file being modified.
3762 @end itemize
3763
3764 @noindent
3765 The most important result of these differences is that order of compilation
3766 is never significant in GNAT. There is no situation in which one is
3767 required to do one compilation before another. What shows up as order of
3768 compilation requirements in the traditional Ada library becomes, in
3769 GNAT, simple source dependencies; in other words, there is only a set
3770 of rules saying what source files must be present when a file is
3771 compiled.
3772
3773 @ifset vms
3774 @node Placement of temporary files
3775 @section Placement of temporary files
3776 @cindex Temporary files (user control over placement)
3777
3778 @noindent
3779 GNAT creates temporary files in the directory designated by the environment
3780 variable @env{TMPDIR}.
3781 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3782 for detailed information on how environment variables are resolved.
3783 For most users the easiest way to make use of this feature is to simply
3784 define @env{TMPDIR} as a job level logical name).
3785 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3786 for compiler temporary files, then you can include something like the
3787 following command in your @file{LOGIN.COM} file:
3788
3789 @smallexample
3790 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3791 @end smallexample
3792
3793 @noindent
3794 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3795 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3796 designated by @env{TEMP}.
3797 If none of these environment variables are defined then GNAT uses the
3798 directory designated by the logical name @code{SYS$SCRATCH:}
3799 (by default the user's home directory). If all else fails
3800 GNAT uses the current directory for temporary files.
3801 @end ifset
3802
3803 @c *************************
3804 @node Compiling Using gcc
3805 @chapter Compiling Using @command{gcc}
3806
3807 @noindent
3808 This chapter discusses how to compile Ada programs using the @command{gcc}
3809 command. It also describes the set of switches
3810 that can be used to control the behavior of the compiler.
3811 @menu
3812 * Compiling Programs::
3813 * Switches for gcc::
3814 * Search Paths and the Run-Time Library (RTL)::
3815 * Order of Compilation Issues::
3816 * Examples::
3817 @end menu
3818
3819 @node Compiling Programs
3820 @section Compiling Programs
3821
3822 @noindent
3823 The first step in creating an executable program is to compile the units
3824 of the program using the @command{gcc} command. You must compile the
3825 following files:
3826
3827 @itemize @bullet
3828 @item
3829 the body file (@file{.adb}) for a library level subprogram or generic
3830 subprogram
3831
3832 @item
3833 the spec file (@file{.ads}) for a library level package or generic
3834 package that has no body
3835
3836 @item
3837 the body file (@file{.adb}) for a library level package
3838 or generic package that has a body
3839
3840 @end itemize
3841
3842 @noindent
3843 You need @emph{not} compile the following files
3844
3845 @itemize @bullet
3846
3847 @item
3848 the spec of a library unit which has a body
3849
3850 @item
3851 subunits
3852 @end itemize
3853
3854 @noindent
3855 because they are compiled as part of compiling related units. GNAT
3856 package specs
3857 when the corresponding body is compiled, and subunits when the parent is
3858 compiled.
3859
3860 @cindex cannot generate code
3861 If you attempt to compile any of these files, you will get one of the
3862 following error messages (where @var{fff} is the name of the file you compiled):
3863
3864 @smallexample
3865 cannot generate code for file @var{fff} (package spec)
3866 to check package spec, use -gnatc
3867
3868 cannot generate code for file @var{fff} (missing subunits)
3869 to check parent unit, use -gnatc
3870
3871 cannot generate code for file @var{fff} (subprogram spec)
3872 to check subprogram spec, use -gnatc
3873
3874 cannot generate code for file @var{fff} (subunit)
3875 to check subunit, use -gnatc
3876 @end smallexample
3877
3878 @noindent
3879 As indicated by the above error messages, if you want to submit
3880 one of these files to the compiler to check for correct semantics
3881 without generating code, then use the @option{-gnatc} switch.
3882
3883 The basic command for compiling a file containing an Ada unit is
3884
3885 @smallexample
3886 @c $ gcc -c @ovar{switches} @file{file name}
3887 @c Expanding @ovar macro inline (explanation in macro def comments)
3888 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3889 @end smallexample
3890
3891 @noindent
3892 where @var{file name} is the name of the Ada file (usually
3893 having an extension
3894 @file{.ads} for a spec or @file{.adb} for a body).
3895 @ifclear vms
3896 You specify the
3897 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3898 @end ifclear
3899 The result of a successful compilation is an object file, which has the
3900 same name as the source file but an extension of @file{.o} and an Ada
3901 Library Information (ALI) file, which also has the same name as the
3902 source file, but with @file{.ali} as the extension. GNAT creates these
3903 two output files in the current directory, but you may specify a source
3904 file in any directory using an absolute or relative path specification
3905 containing the directory information.
3906
3907 @findex gnat1
3908 @command{gcc} is actually a driver program that looks at the extensions of
3909 the file arguments and loads the appropriate compiler. For example, the
3910 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3911 These programs are in directories known to the driver program (in some
3912 configurations via environment variables you set), but need not be in
3913 your path. The @command{gcc} driver also calls the assembler and any other
3914 utilities needed to complete the generation of the required object
3915 files.
3916
3917 It is possible to supply several file names on the same @command{gcc}
3918 command. This causes @command{gcc} to call the appropriate compiler for
3919 each file. For example, the following command lists three separate
3920 files to be compiled:
3921
3922 @smallexample
3923 $ gcc -c x.adb y.adb z.c
3924 @end smallexample
3925
3926 @noindent
3927 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3928 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3929 The compiler generates three object files @file{x.o}, @file{y.o} and
3930 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3931 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3932 @ifclear vms
3933 except for
3934 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3935 @end ifclear
3936
3937 @node Switches for gcc
3938 @section Switches for @command{gcc}
3939
3940 @noindent
3941 The @command{gcc} command accepts switches that control the
3942 compilation process. These switches are fully described in this section.
3943 First we briefly list all the switches, in alphabetical order, then we
3944 describe the switches in more detail in functionally grouped sections.
3945
3946 More switches exist for GCC than those documented here, especially
3947 for specific targets. However, their use is not recommended as
3948 they may change code generation in ways that are incompatible with
3949 the Ada run-time library, or can cause inconsistencies between
3950 compilation units.
3951
3952 @menu
3953 * Output and Error Message Control::
3954 * Warning Message Control::
3955 * Debugging and Assertion Control::
3956 * Validity Checking::
3957 * Style Checking::
3958 * Run-Time Checks::
3959 * Using gcc for Syntax Checking::
3960 * Using gcc for Semantic Checking::
3961 * Compiling Different Versions of Ada::
3962 * Character Set Control::
3963 * File Naming Control::
3964 * Subprogram Inlining Control::
3965 * Auxiliary Output Control::
3966 * Debugging Control::
3967 * Exception Handling Control::
3968 * Units to Sources Mapping Files::
3969 * Integrated Preprocessing::
3970 * Code Generation Control::
3971 @ifset vms
3972 * Return Codes::
3973 @end ifset
3974 @end menu
3975
3976 @table @option
3977 @c !sort!
3978 @ifclear vms
3979 @cindex @option{-b} (@command{gcc})
3980 @item -b @var{target}
3981 Compile your program to run on @var{target}, which is the name of a
3982 system configuration. You must have a GNAT cross-compiler built if
3983 @var{target} is not the same as your host system.
3984
3985 @item -B@var{dir}
3986 @cindex @option{-B} (@command{gcc})
3987 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3988 from @var{dir} instead of the default location. Only use this switch
3989 when multiple versions of the GNAT compiler are available.
3990 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3991 GNU Compiler Collection (GCC)}, for further details. You would normally
3992 use the @option{-b} or @option{-V} switch instead.
3993
3994 @item -c
3995 @cindex @option{-c} (@command{gcc})
3996 Compile. Always use this switch when compiling Ada programs.
3997
3998 Note: for some other languages when using @command{gcc}, notably in
3999 the case of C and C++, it is possible to use
4000 use @command{gcc} without a @option{-c} switch to
4001 compile and link in one step. In the case of GNAT, you
4002 cannot use this approach, because the binder must be run
4003 and @command{gcc} cannot be used to run the GNAT binder.
4004 @end ifclear
4005
4006 @item -fno-inline
4007 @cindex @option{-fno-inline} (@command{gcc})
4008 Suppresses all back-end inlining, even if other optimization or inlining
4009 switches are set.
4010 This includes suppression of inlining that results
4011 from the use of the pragma @code{Inline_Always}.
4012 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
4013 are ignored, and @option{-gnatn} and @option{-gnatN} have no
4014 effect if this switch is present.
4015
4016 @item -fno-inline-functions
4017 @cindex @option{-fno-inline-functions} (@command{gcc})
4018 Suppresses automatic inlining of simple subprograms, which is enabled
4019 if @option{-O3} is used.
4020
4021 @item -fno-inline-small-functions
4022 @cindex @option{-fno-inline-small-functions} (@command{gcc})
4023 Suppresses automatic inlining of small subprograms, which is enabled
4024 if @option{-O2} is used.
4025
4026 @item -fno-inline-functions-called-once
4027 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
4028 Suppresses inlining of subprograms local to the unit and called once
4029 from within it, which is enabled if @option{-O1} is used.
4030
4031 @item -fno-ivopts
4032 @cindex @option{-fno-ivopts} (@command{gcc})
4033 Suppresses high-level loop induction variable optimizations, which are
4034 enabled if @option{-O1} is used. These optimizations are generally
4035 profitable but, for some specific cases of loops with numerous uses
4036 of the iteration variable that follow a common pattern, they may end
4037 up destroying the regularity that could be exploited at a lower level
4038 and thus producing inferior code.
4039
4040 @item -fno-strict-aliasing
4041 @cindex @option{-fno-strict-aliasing} (@command{gcc})
4042 Causes the compiler to avoid assumptions regarding non-aliasing
4043 of objects of different types. See
4044 @ref{Optimization and Strict Aliasing} for details.
4045
4046 @item -fstack-check
4047 @cindex @option{-fstack-check} (@command{gcc})
4048 Activates stack checking.
4049 See @ref{Stack Overflow Checking} for details.
4050
4051 @item -fstack-usage
4052 @cindex @option{-fstack-usage} (@command{gcc})
4053 Makes the compiler output stack usage information for the program, on a
4054 per-function basis. See @ref{Static Stack Usage Analysis} for details.
4055
4056 @item -fcallgraph-info@r{[}=su@r{]}
4057 @cindex @option{-fcallgraph-info} (@command{gcc})
4058 Makes the compiler output callgraph information for the program, on a
4059 per-file basis.  The information is generated in the VCG format.  It can
4060 be decorated with stack-usage per-node information.
4061
4062 @item ^-g^/DEBUG^
4063 @cindex @option{^-g^/DEBUG^} (@command{gcc})
4064 Generate debugging information. This information is stored in the object
4065 file and copied from there to the final executable file by the linker,
4066 where it can be read by the debugger. You must use the
4067 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
4068
4069 @item -gnat83
4070 @cindex @option{-gnat83} (@command{gcc})
4071 Enforce Ada 83 restrictions.
4072
4073 @item -gnat95
4074 @cindex @option{-gnat95} (@command{gcc})
4075 Enforce Ada 95 restrictions.
4076
4077 @item -gnat05
4078 @cindex @option{-gnat05} (@command{gcc})
4079 Allow full Ada 2005 features.
4080
4081 @item -gnata
4082 @cindex @option{-gnata} (@command{gcc})
4083 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
4084 activated. Note that these pragmas can also be controlled using the
4085 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
4086 It also activates pragmas @code{Check}, @code{Precondition}, and
4087 @code{Postcondition}. Note that these pragmas can also be controlled
4088 using the configuration pragma @code{Check_Policy}.
4089
4090 @item -gnatA
4091 @cindex @option{-gnatA} (@command{gcc})
4092 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
4093 it will be ignored.
4094
4095 @item -gnatb
4096 @cindex @option{-gnatb} (@command{gcc})
4097 Generate brief messages to @file{stderr} even if verbose mode set.
4098
4099 @item -gnatB
4100 @cindex @option{-gnatB} (@command{gcc})
4101 Assume no invalid (bad) values except for 'Valid attribute use
4102 (@pxref{Validity Checking}).
4103
4104 @item -gnatc
4105 @cindex @option{-gnatc} (@command{gcc})
4106 Check syntax and semantics only (no code generation attempted).
4107
4108 @item -gnatC
4109 @cindex @option{-gnatC} (@command{gcc})
4110 Generate CodePeer information (no code generation attempted).
4111 This switch will generate an intermediate representation suitable for
4112 use by CodePeer (@file{.scil} files). This switch is not compatible with
4113 code generation (it will, among other things, disable some switches such
4114 as -gnatn, and enable others such as -gnata).
4115
4116 @item -gnatd
4117 @cindex @option{-gnatd} (@command{gcc})
4118 Specify debug options for the compiler. The string of characters after
4119 the @option{-gnatd} specify the specific debug options. The possible
4120 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
4121 compiler source file @file{debug.adb} for details of the implemented
4122 debug options. Certain debug options are relevant to applications
4123 programmers, and these are documented at appropriate points in this
4124 users guide.
4125
4126 @ifclear vms
4127 @item -gnatD
4128 @cindex @option{-gnatD[nn]} (@command{gcc})
4129 @end ifclear
4130 @ifset vms
4131 @item /XDEBUG /LXDEBUG=nnn
4132 @end ifset
4133 Create expanded source files for source level debugging. This switch
4134 also suppress generation of cross-reference information
4135 (see @option{-gnatx}).
4136
4137 @item -gnatec=@var{path}
4138 @cindex @option{-gnatec} (@command{gcc})
4139 Specify a configuration pragma file
4140 @ifclear vms
4141 (the equal sign is optional)
4142 @end ifclear
4143 (@pxref{The Configuration Pragmas Files}).
4144
4145 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
4146 @cindex @option{-gnateD} (@command{gcc})
4147 Defines a symbol, associated with @var{value}, for preprocessing.
4148 (@pxref{Integrated Preprocessing}).
4149
4150 @item -gnatef
4151 @cindex @option{-gnatef} (@command{gcc})
4152 Display full source path name in brief error messages.
4153
4154 @item -gnateG
4155 @cindex @option{-gnateG} (@command{gcc})
4156 Save result of preprocessing in a text file.
4157
4158 @item -gnatem=@var{path}
4159 @cindex @option{-gnatem} (@command{gcc})
4160 Specify a mapping file
4161 @ifclear vms
4162 (the equal sign is optional)
4163 @end ifclear
4164 (@pxref{Units to Sources Mapping Files}).
4165
4166 @item -gnatep=@var{file}
4167 @cindex @option{-gnatep} (@command{gcc})
4168 Specify a preprocessing data file
4169 @ifclear vms
4170 (the equal sign is optional)
4171 @end ifclear
4172 (@pxref{Integrated Preprocessing}).
4173
4174 @item -gnateS
4175 @cindex @option{-gnateS} (@command{gcc})
4176 Generate SCO (Source Coverage Obligation) information in the ALI
4177 file. This information is used by advanced coverage tools. See
4178 unit @file{SCOs} in the compiler sources for details in files
4179 @file{scos.ads} and @file{scos.adb}.
4180
4181 @item -gnatE
4182 @cindex @option{-gnatE} (@command{gcc})
4183 Full dynamic elaboration checks.
4184
4185 @item -gnatf
4186 @cindex @option{-gnatf} (@command{gcc})
4187 Full errors. Multiple errors per line, all undefined references, do not
4188 attempt to suppress cascaded errors.
4189
4190 @item -gnatF
4191 @cindex @option{-gnatF} (@command{gcc})
4192 Externals names are folded to all uppercase.
4193
4194 @item ^-gnatg^/GNAT_INTERNAL^
4195 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4196 Internal GNAT implementation mode. This should not be used for
4197 applications programs, it is intended only for use by the compiler
4198 and its run-time library. For documentation, see the GNAT sources.
4199 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4200 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
4201 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4202 so that all standard warnings and all standard style options are turned on.
4203 All warnings and style error messages are treated as errors.
4204
4205 @ifclear vms
4206 @item -gnatG=nn
4207 @cindex @option{-gnatG[nn]} (@command{gcc})
4208 @end ifclear
4209 @ifset vms
4210 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4211 @end ifset
4212 List generated expanded code in source form.
4213
4214 @item ^-gnath^/HELP^
4215 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4216 Output usage information. The output is written to @file{stdout}.
4217
4218 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4219 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4220 Identifier character set
4221 @ifclear vms
4222 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4223 @end ifclear
4224 For details of the possible selections for @var{c},
4225 see @ref{Character Set Control}.
4226
4227 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4228 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4229 Ignore representation clauses. When this switch is used,
4230 representation clauses are treated as comments. This is useful
4231 when initially porting code where you want to ignore rep clause
4232 problems, and also for compiling foreign code (particularly
4233 for use with ASIS). The representation clauses that are ignored
4234 are: enumeration_representation_clause, record_representation_clause,
4235 and attribute_definition_clause for the following attributes:
4236 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4237 Object_Size, Size, Small, Stream_Size, and Value_Size.
4238 Note that this option should be used only for compiling -- the
4239 code is likely to malfunction at run time.
4240
4241 @item -gnatjnn
4242 @cindex @option{-gnatjnn} (@command{gcc})
4243 Reformat error messages to fit on nn character lines
4244
4245 @item -gnatk=@var{n}
4246 @cindex @option{-gnatk} (@command{gcc})
4247 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4248
4249 @item -gnatl
4250 @cindex @option{-gnatl} (@command{gcc})
4251 Output full source listing with embedded error messages.
4252
4253 @item -gnatL
4254 @cindex @option{-gnatL} (@command{gcc})
4255 Used in conjunction with -gnatG or -gnatD to intersperse original
4256 source lines (as comment lines with line numbers) in the expanded
4257 source output.
4258
4259 @item -gnatm=@var{n}
4260 @cindex @option{-gnatm} (@command{gcc})
4261 Limit number of detected error or warning messages to @var{n}
4262 where @var{n} is in the range 1..999999. The default setting if
4263 no switch is given is 9999. If the number of warnings reaches this
4264 limit, then a message is output and further warnings are suppressed,
4265 but the compilation is continued. If the number of error messages
4266 reaches this limit, then a message is output and the compilation
4267 is abandoned. The equal sign here is optional. A value of zero
4268 means that no limit applies.
4269
4270 @item -gnatn
4271 @cindex @option{-gnatn} (@command{gcc})
4272 Activate inlining for subprograms for which
4273 pragma @code{inline} is specified. This inlining is performed
4274 by the GCC back-end.
4275
4276 @item -gnatN
4277 @cindex @option{-gnatN} (@command{gcc})
4278 Activate front end inlining for subprograms for which
4279 pragma @code{Inline} is specified. This inlining is performed
4280 by the front end and will be visible in the
4281 @option{-gnatG} output.
4282
4283 When using a gcc-based back end (in practice this means using any version
4284 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4285 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4286 Historically front end inlining was more extensive than the gcc back end
4287 inlining, but that is no longer the case.
4288
4289 @item -gnato
4290 @cindex @option{-gnato} (@command{gcc})
4291 Enable numeric overflow checking (which is not normally enabled by
4292 default). Note that division by zero is a separate check that is not
4293 controlled by this switch (division by zero checking is on by default).
4294
4295 @item -gnatp
4296 @cindex @option{-gnatp} (@command{gcc})
4297 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4298 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4299
4300 @item -gnat-p
4301 @cindex @option{-gnat-p} (@command{gcc})
4302 Cancel effect of previous @option{-gnatp} switch.
4303
4304 @item -gnatP
4305 @cindex @option{-gnatP} (@command{gcc})
4306 Enable polling. This is required on some systems (notably Windows NT) to
4307 obtain asynchronous abort and asynchronous transfer of control capability.
4308 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4309 details.
4310
4311 @item -gnatq
4312 @cindex @option{-gnatq} (@command{gcc})
4313 Don't quit. Try semantics, even if parse errors.
4314
4315 @item -gnatQ
4316 @cindex @option{-gnatQ} (@command{gcc})
4317 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4318
4319 @item -gnatr
4320 @cindex @option{-gnatr} (@command{gcc})
4321 Treat pragma Restrictions as Restriction_Warnings.
4322
4323 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4324 @cindex @option{-gnatR} (@command{gcc})
4325 Output representation information for declared types and objects.
4326
4327 @item -gnats
4328 @cindex @option{-gnats} (@command{gcc})
4329 Syntax check only.
4330
4331 @item -gnatS
4332 @cindex @option{-gnatS} (@command{gcc})
4333 Print package Standard.
4334
4335 @item -gnatt
4336 @cindex @option{-gnatt} (@command{gcc})
4337 Generate tree output file.
4338
4339 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4340 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4341 All compiler tables start at @var{nnn} times usual starting size.
4342
4343 @item -gnatu
4344 @cindex @option{-gnatu} (@command{gcc})
4345 List units for this compilation.
4346
4347 @item -gnatU
4348 @cindex @option{-gnatU} (@command{gcc})
4349 Tag all error messages with the unique string ``error:''
4350
4351 @item -gnatv
4352 @cindex @option{-gnatv} (@command{gcc})
4353 Verbose mode. Full error output with source lines to @file{stdout}.
4354
4355 @item -gnatV
4356 @cindex @option{-gnatV} (@command{gcc})
4357 Control level of validity checking (@pxref{Validity Checking}).
4358
4359 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4360 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4361 Warning mode where
4362 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4363 the exact warnings that
4364 are enabled or disabled (@pxref{Warning Message Control}).
4365
4366 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4367 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4368 Wide character encoding method
4369 @ifclear vms
4370 (@var{e}=n/h/u/s/e/8).
4371 @end ifclear
4372 @ifset vms
4373 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4374 @end ifset
4375
4376 @item -gnatx
4377 @cindex @option{-gnatx} (@command{gcc})
4378 Suppress generation of cross-reference information.
4379
4380 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4381 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4382 Enable built-in style checks (@pxref{Style Checking}).
4383
4384 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4385 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4386 Distribution stub generation and compilation
4387 @ifclear vms
4388 (@var{m}=r/c for receiver/caller stubs).
4389 @end ifclear
4390 @ifset vms
4391 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4392 to be generated and compiled).
4393 @end ifset
4394
4395 @item ^-I^/SEARCH=^@var{dir}
4396 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4397 @cindex RTL
4398 Direct GNAT to search the @var{dir} directory for source files needed by
4399 the current compilation
4400 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4401
4402 @item ^-I-^/NOCURRENT_DIRECTORY^
4403 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4404 @cindex RTL
4405 Except for the source file named in the command line, do not look for source
4406 files in the directory containing the source file named in the command line
4407 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4408
4409 @ifclear vms
4410 @item -mbig-switch
4411 @cindex @option{-mbig-switch} (@command{gcc})
4412 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4413 This standard gcc switch causes the compiler to use larger offsets in its
4414 jump table representation for @code{case} statements.
4415 This may result in less efficient code, but is sometimes necessary
4416 (for example on HP-UX targets)
4417 @cindex HP-UX and @option{-mbig-switch} option
4418 in order to compile large and/or nested @code{case} statements.
4419
4420 @item -o @var{file}
4421 @cindex @option{-o} (@command{gcc})
4422 This switch is used in @command{gcc} to redirect the generated object file
4423 and its associated ALI file. Beware of this switch with GNAT, because it may
4424 cause the object file and ALI file to have different names which in turn
4425 may confuse the binder and the linker.
4426 @end ifclear
4427
4428 @item -nostdinc
4429 @cindex @option{-nostdinc} (@command{gcc})
4430 Inhibit the search of the default location for the GNAT Run Time
4431 Library (RTL) source files.
4432
4433 @item -nostdlib
4434 @cindex @option{-nostdlib} (@command{gcc})
4435 Inhibit the search of the default location for the GNAT Run Time
4436 Library (RTL) ALI files.
4437
4438 @ifclear vms
4439 @c @item -O@ovar{n}
4440 @c Expanding @ovar macro inline (explanation in macro def comments)
4441 @item -O@r{[}@var{n}@r{]}
4442 @cindex @option{-O} (@command{gcc})
4443 @var{n} controls the optimization level.
4444
4445 @table @asis
4446 @item n = 0
4447 No optimization, the default setting if no @option{-O} appears
4448
4449 @item n = 1
4450 Normal optimization, the default if you specify @option{-O} without
4451 an operand. A good compromise between code quality and compilation
4452 time.
4453
4454 @item n = 2
4455 Extensive optimization, may improve execution time, possibly at the cost of
4456 substantially increased compilation time.
4457
4458 @item n = 3
4459 Same as @option{-O2}, and also includes inline expansion for small subprograms
4460 in the same unit.
4461
4462 @item n = s
4463 Optimize space usage
4464 @end table
4465
4466 @noindent
4467 See also @ref{Optimization Levels}.
4468 @end ifclear
4469
4470 @ifset vms
4471 @item  /NOOPTIMIZE
4472 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4473 Equivalent to @option{/OPTIMIZE=NONE}.
4474 This is the default behavior in the absence of an @option{/OPTIMIZE}
4475 qualifier.
4476
4477 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4478 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4479 Selects the level of optimization for your program. The supported
4480 keywords are as follows:
4481 @table @code
4482 @item   ALL
4483 Perform most optimizations, including those that
4484 are expensive.
4485 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4486 without keyword options.
4487
4488 @item   NONE
4489 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4490
4491 @item SOME
4492 Perform some optimizations, but omit ones that are costly.
4493
4494 @item   DEVELOPMENT
4495 Same as @code{SOME}.
4496
4497 @item INLINING
4498 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4499 automatic inlining of small subprograms within a unit
4500
4501 @item   UNROLL_LOOPS
4502 Try to unroll loops. This keyword may be specified together with
4503 any keyword above other than @code{NONE}. Loop unrolling
4504 usually, but not always, improves the performance of programs.
4505
4506 @item SPACE
4507 Optimize space usage
4508 @end table
4509
4510 @noindent
4511 See also @ref{Optimization Levels}.
4512 @end ifset
4513
4514 @ifclear vms
4515 @item -pass-exit-codes
4516 @cindex @option{-pass-exit-codes} (@command{gcc})
4517 Catch exit codes from the compiler and use the most meaningful as
4518 exit status.
4519 @end ifclear
4520
4521 @item --RTS=@var{rts-path}
4522 @cindex @option{--RTS} (@command{gcc})
4523 Specifies the default location of the runtime library. Same meaning as the
4524 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4525
4526 @item ^-S^/ASM^
4527 @cindex @option{^-S^/ASM^} (@command{gcc})
4528 ^Used in place of @option{-c} to^Used to^
4529 cause the assembler source file to be
4530 generated, using @file{^.s^.S^} as the extension,
4531 instead of the object file.
4532 This may be useful if you need to examine the generated assembly code.
4533
4534 @item ^-fverbose-asm^/VERBOSE_ASM^
4535 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4536 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4537 to cause the generated assembly code file to be annotated with variable
4538 names, making it significantly easier to follow.
4539
4540 @item ^-v^/VERBOSE^
4541 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4542 Show commands generated by the @command{gcc} driver. Normally used only for
4543 debugging purposes or if you need to be sure what version of the
4544 compiler you are executing.
4545
4546 @ifclear vms
4547 @item -V @var{ver}
4548 @cindex @option{-V} (@command{gcc})
4549 Execute @var{ver} version of the compiler. This is the @command{gcc}
4550 version, not the GNAT version.
4551 @end ifclear
4552
4553 @item ^-w^/NO_BACK_END_WARNINGS^
4554 @cindex @option{-w} (@command{gcc})
4555 Turn off warnings generated by the back end of the compiler. Use of
4556 this switch also causes the default for front end warnings to be set
4557 to suppress (as though @option{-gnatws} had appeared at the start of
4558 the options).
4559
4560 @end table
4561
4562 @ifclear vms
4563 @c Combining qualifiers does not work on VMS
4564 You may combine a sequence of GNAT switches into a single switch. For
4565 example, the combined switch
4566
4567 @cindex Combining GNAT switches
4568 @smallexample
4569 -gnatofi3
4570 @end smallexample
4571
4572 @noindent
4573 is equivalent to specifying the following sequence of switches:
4574
4575 @smallexample
4576 -gnato -gnatf -gnati3
4577 @end smallexample
4578 @end ifclear
4579
4580 @noindent
4581 The following restrictions apply to the combination of switches
4582 in this manner:
4583
4584 @itemize @bullet
4585 @item
4586 The switch @option{-gnatc} if combined with other switches must come
4587 first in the string.
4588
4589 @item
4590 The switch @option{-gnats} if combined with other switches must come
4591 first in the string.
4592
4593 @item
4594 The switches
4595 ^^@option{/DISTRIBUTION_STUBS=},^
4596 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4597 switches, and only one of them may appear in the command line.
4598
4599 @item
4600 The switch @option{-gnat-p} may not be combined with any other switch.
4601
4602 @ifclear vms
4603 @item
4604 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4605 switch), then all further characters in the switch are interpreted
4606 as style modifiers (see description of @option{-gnaty}).
4607
4608 @item
4609 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4610 switch), then all further characters in the switch are interpreted
4611 as debug flags (see description of @option{-gnatd}).
4612
4613 @item
4614 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4615 switch), then all further characters in the switch are interpreted
4616 as warning mode modifiers (see description of @option{-gnatw}).
4617
4618 @item
4619 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4620 switch), then all further characters in the switch are interpreted
4621 as validity checking options (@pxref{Validity Checking}).
4622
4623 @item
4624 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4625 a combined list of options.
4626 @end ifclear
4627 @end itemize
4628
4629 @node Output and Error Message Control
4630 @subsection Output and Error Message Control
4631 @findex stderr
4632
4633 @noindent
4634 The standard default format for error messages is called ``brief format''.
4635 Brief format messages are written to @file{stderr} (the standard error
4636 file) and have the following form:
4637
4638 @smallexample
4639 e.adb:3:04: Incorrect spelling of keyword "function"
4640 e.adb:4:20: ";" should be "is"
4641 @end smallexample
4642
4643 @noindent
4644 The first integer after the file name is the line number in the file,
4645 and the second integer is the column number within the line.
4646 @ifclear vms
4647 @code{GPS} can parse the error messages
4648 and point to the referenced character.
4649 @end ifclear
4650 The following switches provide control over the error message
4651 format:
4652
4653 @table @option
4654 @c !sort!
4655 @item -gnatv
4656 @cindex @option{-gnatv} (@command{gcc})
4657 @findex stdout
4658 @ifclear vms
4659 The v stands for verbose.
4660 @end ifclear
4661 The effect of this setting is to write long-format error
4662 messages to @file{stdout} (the standard output file.
4663 The same program compiled with the
4664 @option{-gnatv} switch would generate:
4665
4666 @smallexample
4667 @cartouche
4668 3. funcion X (Q : Integer)
4669    |
4670 >>> Incorrect spelling of keyword "function"
4671 4. return Integer;
4672                  |
4673 >>> ";" should be "is"
4674 @end cartouche
4675 @end smallexample
4676
4677 @noindent
4678 The vertical bar indicates the location of the error, and the @samp{>>>}
4679 prefix can be used to search for error messages. When this switch is
4680 used the only source lines output are those with errors.
4681
4682 @item -gnatl
4683 @cindex @option{-gnatl} (@command{gcc})
4684 @ifclear vms
4685 The @code{l} stands for list.
4686 @end ifclear
4687 This switch causes a full listing of
4688 the file to be generated. In the case where a body is
4689 compiled, the corresponding spec is also listed, along
4690 with any subunits. Typical output from compiling a package
4691 body @file{p.adb} might look like:
4692
4693 @smallexample @c ada
4694 @cartouche
4695  Compiling: p.adb
4696
4697      1. package body p is
4698      2.    procedure a;
4699      3.    procedure a is separate;
4700      4. begin
4701      5.    null
4702                |
4703         >>> missing ";"
4704
4705      6. end;
4706
4707 Compiling: p.ads
4708
4709      1. package p is
4710      2.    pragma Elaborate_Body
4711                                 |
4712         >>> missing ";"
4713
4714      3. end p;
4715
4716 Compiling: p-a.adb
4717
4718      1. separate p
4719                 |
4720         >>> missing "("
4721
4722      2. procedure a is
4723      3. begin
4724      4.    null
4725                |
4726         >>> missing ";"
4727
4728      5. end;
4729 @end cartouche
4730 @end smallexample
4731
4732 @noindent
4733 @findex stderr
4734 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4735 standard output is redirected, a brief summary is written to
4736 @file{stderr} (standard error) giving the number of error messages and
4737 warning messages generated.
4738
4739 @item -^gnatl^OUTPUT_FILE^=file
4740 @cindex @option{^-gnatl^OUTPUT_FILE^=fname} (@command{gcc})
4741 This has the same effect as @option{-gnatl} except that the output is
4742 written to a file instead of to standard output. If the given name
4743 @file{fname} does not start with a period, then it is the full name
4744 of the file to be written. If @file{fname} is an extension, it is
4745 appended to the name of the file being compiled. For example, if
4746 file @file{xyz.adb} is compiled with @option{^-gnatl^OUTPUT_FILE^=.lst},
4747 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4748
4749 @item -gnatU
4750 @cindex @option{-gnatU} (@command{gcc})
4751 This switch forces all error messages to be preceded by the unique
4752 string ``error:''. This means that error messages take a few more
4753 characters in space, but allows easy searching for and identification
4754 of error messages.
4755
4756 @item -gnatb
4757 @cindex @option{-gnatb} (@command{gcc})
4758 @ifclear vms
4759 The @code{b} stands for brief.
4760 @end ifclear
4761 This switch causes GNAT to generate the
4762 brief format error messages to @file{stderr} (the standard error
4763 file) as well as the verbose
4764 format message or full listing (which as usual is written to
4765 @file{stdout} (the standard output file).
4766
4767 @item -gnatm=@var{n}
4768 @cindex @option{-gnatm} (@command{gcc})
4769 @ifclear vms
4770 The @code{m} stands for maximum.
4771 @end ifclear
4772 @var{n} is a decimal integer in the
4773 range of 1 to 999999 and limits the number of error or warning
4774 messages to be generated. For example, using
4775 @option{-gnatm2} might yield
4776
4777 @smallexample
4778 e.adb:3:04: Incorrect spelling of keyword "function"
4779 e.adb:5:35: missing ".."
4780 fatal error: maximum number of errors detected
4781 compilation abandoned
4782 @end smallexample
4783
4784 @noindent
4785 The default setting if
4786 no switch is given is 9999. If the number of warnings reaches this
4787 limit, then a message is output and further warnings are suppressed,
4788 but the compilation is continued. If the number of error messages
4789 reaches this limit, then a message is output and the compilation
4790 is abandoned. A value of zero means that no limit applies.
4791
4792 @noindent
4793 Note that the equal sign is optional, so the switches
4794 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4795
4796 @item -gnatf
4797 @cindex @option{-gnatf} (@command{gcc})
4798 @cindex Error messages, suppressing
4799 @ifclear vms
4800 The @code{f} stands for full.
4801 @end ifclear
4802 Normally, the compiler suppresses error messages that are likely to be
4803 redundant. This switch causes all error
4804 messages to be generated. In particular, in the case of
4805 references to undefined variables. If a given variable is referenced
4806 several times, the normal format of messages is
4807 @smallexample
4808 e.adb:7:07: "V" is undefined (more references follow)
4809 @end smallexample
4810
4811 @noindent
4812 where the parenthetical comment warns that there are additional
4813 references to the variable @code{V}. Compiling the same program with the
4814 @option{-gnatf} switch yields
4815
4816 @smallexample
4817 e.adb:7:07: "V" is undefined
4818 e.adb:8:07: "V" is undefined
4819 e.adb:8:12: "V" is undefined
4820 e.adb:8:16: "V" is undefined
4821 e.adb:9:07: "V" is undefined
4822 e.adb:9:12: "V" is undefined
4823 @end smallexample
4824
4825 @noindent
4826 The @option{-gnatf} switch also generates additional information for
4827 some error messages.  Some examples are:
4828
4829 @itemize @bullet
4830 @item
4831 Details on possibly non-portable unchecked conversion
4832 @item
4833 List possible interpretations for ambiguous calls
4834 @item
4835 Additional details on incorrect parameters
4836 @end itemize
4837
4838 @item -gnatjnn
4839 @cindex @option{-gnatjnn} (@command{gcc})
4840 In normal operation mode (or if @option{-gnatj0} is used, then error messages
4841 with continuation lines are treated as though the continuation lines were
4842 separate messages (and so a warning with two continuation lines counts as
4843 three warnings, and is listed as three separate messages).
4844
4845 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4846 messages are output in a different manner. A message and all its continuation
4847 lines are treated as a unit, and count as only one warning or message in the
4848 statistics totals. Furthermore, the message is reformatted so that no line
4849 is longer than nn characters.
4850
4851 @item -gnatq
4852 @cindex @option{-gnatq} (@command{gcc})
4853 @ifclear vms
4854 The @code{q} stands for quit (really ``don't quit'').
4855 @end ifclear
4856 In normal operation mode, the compiler first parses the program and
4857 determines if there are any syntax errors. If there are, appropriate
4858 error messages are generated and compilation is immediately terminated.
4859 This switch tells
4860 GNAT to continue with semantic analysis even if syntax errors have been
4861 found. This may enable the detection of more errors in a single run. On
4862 the other hand, the semantic analyzer is more likely to encounter some
4863 internal fatal error when given a syntactically invalid tree.
4864
4865 @item -gnatQ
4866 @cindex @option{-gnatQ} (@command{gcc})
4867 In normal operation mode, the @file{ALI} file is not generated if any
4868 illegalities are detected in the program. The use of @option{-gnatQ} forces
4869 generation of the @file{ALI} file. This file is marked as being in
4870 error, so it cannot be used for binding purposes, but it does contain
4871 reasonably complete cross-reference information, and thus may be useful
4872 for use by tools (e.g., semantic browsing tools or integrated development
4873 environments) that are driven from the @file{ALI} file. This switch
4874 implies @option{-gnatq}, since the semantic phase must be run to get a
4875 meaningful ALI file.
4876
4877 In addition, if @option{-gnatt} is also specified, then the tree file is
4878 generated even if there are illegalities. It may be useful in this case
4879 to also specify @option{-gnatq} to ensure that full semantic processing
4880 occurs. The resulting tree file can be processed by ASIS, for the purpose
4881 of providing partial information about illegal units, but if the error
4882 causes the tree to be badly malformed, then ASIS may crash during the
4883 analysis.
4884
4885 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4886 being in error, @command{gnatmake} will attempt to recompile the source when it
4887 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4888
4889 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4890 since ALI files are never generated if @option{-gnats} is set.
4891
4892 @end table
4893
4894 @node Warning Message Control
4895 @subsection Warning Message Control
4896 @cindex Warning messages
4897 @noindent
4898 In addition to error messages, which correspond to illegalities as defined
4899 in the Ada Reference Manual, the compiler detects two kinds of warning
4900 situations.
4901
4902 First, the compiler considers some constructs suspicious and generates a
4903 warning message to alert you to a possible error. Second, if the
4904 compiler detects a situation that is sure to raise an exception at
4905 run time, it generates a warning message. The following shows an example
4906 of warning messages:
4907 @smallexample
4908 e.adb:4:24: warning: creation of object may raise Storage_Error
4909 e.adb:10:17: warning: static value out of range
4910 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4911 @end smallexample
4912
4913 @noindent
4914 GNAT considers a large number of situations as appropriate
4915 for the generation of warning messages. As always, warnings are not
4916 definite indications of errors. For example, if you do an out-of-range
4917 assignment with the deliberate intention of raising a
4918 @code{Constraint_Error} exception, then the warning that may be
4919 issued does not indicate an error. Some of the situations for which GNAT
4920 issues warnings (at least some of the time) are given in the following
4921 list. This list is not complete, and new warnings are often added to
4922 subsequent versions of GNAT. The list is intended to give a general idea
4923 of the kinds of warnings that are generated.
4924
4925 @itemize @bullet
4926 @item
4927 Possible infinitely recursive calls
4928
4929 @item
4930 Out-of-range values being assigned
4931
4932 @item
4933 Possible order of elaboration problems
4934
4935 @item
4936 Assertions (pragma Assert) that are sure to fail
4937
4938 @item
4939 Unreachable code
4940
4941 @item
4942 Address clauses with possibly unaligned values, or where an attempt is
4943 made to overlay a smaller variable with a larger one.
4944
4945 @item
4946 Fixed-point type declarations with a null range
4947
4948 @item
4949 Direct_IO or Sequential_IO instantiated with a type that has access values
4950
4951 @item
4952 Variables that are never assigned a value
4953
4954 @item
4955 Variables that are referenced before being initialized
4956
4957 @item
4958 Task entries with no corresponding @code{accept} statement
4959
4960 @item
4961 Duplicate accepts for the same task entry in a @code{select}
4962
4963 @item
4964 Objects that take too much storage
4965
4966 @item
4967 Unchecked conversion between types of differing sizes
4968
4969 @item
4970 Missing @code{return} statement along some execution path in a function
4971
4972 @item
4973 Incorrect (unrecognized) pragmas
4974
4975 @item
4976 Incorrect external names
4977
4978 @item
4979 Allocation from empty storage pool
4980
4981 @item
4982 Potentially blocking operation in protected type
4983
4984 @item
4985 Suspicious parenthesization of expressions
4986
4987 @item
4988 Mismatching bounds in an aggregate
4989
4990 @item
4991 Attempt to return local value by reference
4992
4993 @item
4994 Premature instantiation of a generic body
4995
4996 @item
4997 Attempt to pack aliased components
4998
4999 @item
5000 Out of bounds array subscripts
5001
5002 @item
5003 Wrong length on string assignment
5004
5005 @item
5006 Violations of style rules if style checking is enabled
5007
5008 @item
5009 Unused @code{with} clauses
5010
5011 @item
5012 @code{Bit_Order} usage that does not have any effect
5013
5014 @item
5015 @code{Standard.Duration} used to resolve universal fixed expression
5016
5017 @item
5018 Dereference of possibly null value
5019
5020 @item
5021 Declaration that is likely to cause storage error
5022
5023 @item
5024 Internal GNAT unit @code{with}'ed by application unit
5025
5026 @item
5027 Values known to be out of range at compile time
5028
5029 @item
5030 Unreferenced labels and variables
5031
5032 @item
5033 Address overlays that could clobber memory
5034
5035 @item
5036 Unexpected initialization when address clause present
5037
5038 @item
5039 Bad alignment for address clause
5040
5041 @item
5042 Useless type conversions
5043
5044 @item
5045 Redundant assignment statements and other redundant constructs
5046
5047 @item
5048 Useless exception handlers
5049
5050 @item
5051 Accidental hiding of name by child unit
5052
5053 @item
5054 Access before elaboration detected at compile time
5055
5056 @item
5057 A range in a @code{for} loop that is known to be null or might be null
5058
5059 @end itemize
5060
5061 @noindent
5062 The following section lists compiler switches that are available
5063 to control the handling of warning messages. It is also possible
5064 to exercise much finer control over what warnings are issued and
5065 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
5066 gnat_rm, GNAT Reference manual}.
5067
5068 @table @option
5069 @c !sort!
5070 @item -gnatwa
5071 @emph{Activate all optional errors.}
5072 @cindex @option{-gnatwa} (@command{gcc})
5073 This switch activates most optional warning messages, see remaining list
5074 in this section for details on optional warning messages that can be
5075 individually controlled.  The warnings that are not turned on by this
5076 switch are
5077 @option{-gnatwd} (implicit dereferencing),
5078 @option{-gnatwh} (hiding),
5079 @option{-gnatwl} (elaboration warnings),
5080 @option{-gnatw.o} (warn on values set by out parameters ignored)
5081 and @option{-gnatwt} (tracking of deleted conditional code).
5082 All other optional warnings are turned on.
5083
5084 @item -gnatwA
5085 @emph{Suppress all optional errors.}
5086 @cindex @option{-gnatwA} (@command{gcc})
5087 This switch suppresses all optional warning messages, see remaining list
5088 in this section for details on optional warning messages that can be
5089 individually controlled.
5090
5091 @item -gnatw.a
5092 @emph{Activate warnings on failing assertions.}
5093 @cindex @option{-gnatw.a} (@command{gcc})
5094 @cindex Assert failures
5095 This switch activates warnings for assertions where the compiler can tell at
5096 compile time that the assertion will fail. Note that this warning is given
5097 even if assertions are disabled. The default is that such warnings are
5098 generated.
5099
5100 @item -gnatw.A
5101 @emph{Suppress warnings on failing assertions.}
5102 @cindex @option{-gnatw.A} (@command{gcc})
5103 @cindex Assert failures
5104 This switch suppresses warnings for assertions where the compiler can tell at
5105 compile time that the assertion will fail.
5106
5107 @item -gnatwb
5108 @emph{Activate warnings on bad fixed values.}
5109 @cindex @option{-gnatwb} (@command{gcc})
5110 @cindex Bad fixed values
5111 @cindex Fixed-point Small value
5112 @cindex Small value
5113 This switch activates warnings for static fixed-point expressions whose
5114 value is not an exact multiple of Small. Such values are implementation
5115 dependent, since an implementation is free to choose either of the multiples
5116 that surround the value. GNAT always chooses the closer one, but this is not
5117 required behavior, and it is better to specify a value that is an exact
5118 multiple, ensuring predictable execution. The default is that such warnings
5119 are not generated.
5120
5121 @item -gnatwB
5122 @emph{Suppress warnings on bad fixed values.}
5123 @cindex @option{-gnatwB} (@command{gcc})
5124 This switch suppresses warnings for static fixed-point expressions whose
5125 value is not an exact multiple of Small.
5126
5127 @item -gnatw.b
5128 @emph{Activate warnings on biased representation.}
5129 @cindex @option{-gnatw.b} (@command{gcc})
5130 @cindex Biased representation
5131 This switch activates warnings when a size clause, value size clause, component
5132 clause, or component size clause forces the use of biased representation for an
5133 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5134 to represent 10/11). The default is that such warnings are generated.
5135
5136 @item -gnatw.B
5137 @emph{Suppress warnings on biased representation.}
5138 @cindex @option{-gnatwB} (@command{gcc})
5139 This switch suppresses warnings for representation clauses that force the use
5140 of biased representation.
5141
5142 @item -gnatwc
5143 @emph{Activate warnings on conditionals.}
5144 @cindex @option{-gnatwc} (@command{gcc})
5145 @cindex Conditionals, constant
5146 This switch activates warnings for conditional expressions used in
5147 tests that are known to be True or False at compile time. The default
5148 is that such warnings are not generated.
5149 Note that this warning does
5150 not get issued for the use of boolean variables or constants whose
5151 values are known at compile time, since this is a standard technique
5152 for conditional compilation in Ada, and this would generate too many
5153 false positive warnings.
5154
5155 This warning option also activates a special test for comparisons using
5156 the operators ``>='' and`` <=''.
5157 If the compiler can tell that only the equality condition is possible,
5158 then it will warn that the ``>'' or ``<'' part of the test
5159 is useless and that the operator could be replaced by ``=''.
5160 An example would be comparing a @code{Natural} variable <= 0.
5161
5162 This warning option also generates warnings if
5163 one or both tests is optimized away in a membership test for integer
5164 values if the result can be determined at compile time. Range tests on
5165 enumeration types are not included, since it is common for such tests
5166 to include an end point.
5167
5168 This warning can also be turned on using @option{-gnatwa}.
5169
5170 @item -gnatwC
5171 @emph{Suppress warnings on conditionals.}
5172 @cindex @option{-gnatwC} (@command{gcc})
5173 This switch suppresses warnings for conditional expressions used in
5174 tests that are known to be True or False at compile time.
5175
5176 @item -gnatw.c
5177 @emph{Activate warnings on missing component clauses.}
5178 @cindex @option{-gnatw.c} (@command{gcc})
5179 @cindex Component clause, missing
5180 This switch activates warnings for record components where a record
5181 representation clause is present and has component clauses for the
5182 majority, but not all, of the components. A warning is given for each
5183 component for which no component clause is present.
5184
5185 This warning can also be turned on using @option{-gnatwa}.
5186
5187 @item -gnatw.C
5188 @emph{Suppress warnings on missing component clauses.}
5189 @cindex @option{-gnatwC} (@command{gcc})
5190 This switch suppresses warnings for record components that are
5191 missing a component clause in the situation described above.
5192
5193 @item -gnatwd
5194 @emph{Activate warnings on implicit dereferencing.}
5195 @cindex @option{-gnatwd} (@command{gcc})
5196 If this switch is set, then the use of a prefix of an access type
5197 in an indexed component, slice, or selected component without an
5198 explicit @code{.all} will generate a warning. With this warning
5199 enabled, access checks occur only at points where an explicit
5200 @code{.all} appears in the source code (assuming no warnings are
5201 generated as a result of this switch). The default is that such
5202 warnings are not generated.
5203 Note that @option{-gnatwa} does not affect the setting of
5204 this warning option.
5205
5206 @item -gnatwD
5207 @emph{Suppress warnings on implicit dereferencing.}
5208 @cindex @option{-gnatwD} (@command{gcc})
5209 @cindex Implicit dereferencing
5210 @cindex Dereferencing, implicit
5211 This switch suppresses warnings for implicit dereferences in
5212 indexed components, slices, and selected components.
5213
5214 @item -gnatwe
5215 @emph{Treat warnings as errors.}
5216 @cindex @option{-gnatwe} (@command{gcc})
5217 @cindex Warnings, treat as error
5218 This switch causes warning messages to be treated as errors.
5219 The warning string still appears, but the warning messages are counted
5220 as errors, and prevent the generation of an object file.
5221
5222 @item -gnatw.e
5223 @emph{Activate every optional warning}
5224 @cindex @option{-gnatw.e} (@command{gcc})
5225 @cindex Warnings, activate every optional warning
5226 This switch activates all optional warnings, including those which
5227 are not activated by @code{-gnatwa}.
5228
5229 @item -gnatwf
5230 @emph{Activate warnings on unreferenced formals.}
5231 @cindex @option{-gnatwf} (@command{gcc})
5232 @cindex Formals, unreferenced
5233 This switch causes a warning to be generated if a formal parameter
5234 is not referenced in the body of the subprogram. This warning can
5235 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5236 default is that these warnings are not generated.
5237
5238 @item -gnatwF
5239 @emph{Suppress warnings on unreferenced formals.}
5240 @cindex @option{-gnatwF} (@command{gcc})
5241 This switch suppresses warnings for unreferenced formal
5242 parameters. Note that the
5243 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5244 effect of warning on unreferenced entities other than subprogram
5245 formals.
5246
5247 @item -gnatwg
5248 @emph{Activate warnings on unrecognized pragmas.}
5249 @cindex @option{-gnatwg} (@command{gcc})
5250 @cindex Pragmas, unrecognized
5251 This switch causes a warning to be generated if an unrecognized
5252 pragma is encountered. Apart from issuing this warning, the
5253 pragma is ignored and has no effect. This warning can
5254 also be turned on using @option{-gnatwa}. The default
5255 is that such warnings are issued (satisfying the Ada Reference
5256 Manual requirement that such warnings appear).
5257
5258 @item -gnatwG
5259 @emph{Suppress warnings on unrecognized pragmas.}
5260 @cindex @option{-gnatwG} (@command{gcc})
5261 This switch suppresses warnings for unrecognized pragmas.
5262
5263 @item -gnatwh
5264 @emph{Activate warnings on hiding.}
5265 @cindex @option{-gnatwh} (@command{gcc})
5266 @cindex Hiding of Declarations
5267 This switch activates warnings on hiding declarations.
5268 A declaration is considered hiding
5269 if it is for a non-overloadable entity, and it declares an entity with the
5270 same name as some other entity that is directly or use-visible. The default
5271 is that such warnings are not generated.
5272 Note that @option{-gnatwa} does not affect the setting of this warning option.
5273
5274 @item -gnatwH
5275 @emph{Suppress warnings on hiding.}
5276 @cindex @option{-gnatwH} (@command{gcc})
5277 This switch suppresses warnings on hiding declarations.
5278
5279 @item -gnatwi
5280 @emph{Activate warnings on implementation units.}
5281 @cindex @option{-gnatwi} (@command{gcc})
5282 This switch activates warnings for a @code{with} of an internal GNAT
5283 implementation unit, defined as any unit from the @code{Ada},
5284 @code{Interfaces}, @code{GNAT},
5285 ^^@code{DEC},^ or @code{System}
5286 hierarchies that is not
5287 documented in either the Ada Reference Manual or the GNAT
5288 Programmer's Reference Manual. Such units are intended only
5289 for internal implementation purposes and should not be @code{with}'ed
5290 by user programs. The default is that such warnings are generated
5291 This warning can also be turned on using @option{-gnatwa}.
5292
5293 @item -gnatwI
5294 @emph{Disable warnings on implementation units.}
5295 @cindex @option{-gnatwI} (@command{gcc})
5296 This switch disables warnings for a @code{with} of an internal GNAT
5297 implementation unit.
5298
5299 @item -gnatw.i
5300 @emph{Activate warnings on overlapping actuals.}
5301 @cindex @option{-gnatw.i} (@command{gcc})
5302 This switch enables a warning on statically detectable overlapping actuals in
5303 a subprogram call, when one of the actuals is an in-out parameter, and the
5304 types of the actuals are not by-copy types. The warning is off by default,
5305 and is not included under -gnatwa.
5306
5307 @item -gnatw.I
5308 @emph{Disable warnings on overlapping actuals.}
5309 @cindex @option{-gnatw.I} (@command{gcc})
5310 This switch disables warnings on overlapping actuals in a call..
5311
5312 @item -gnatwj
5313 @emph{Activate warnings on obsolescent features (Annex J).}
5314 @cindex @option{-gnatwj} (@command{gcc})
5315 @cindex Features, obsolescent
5316 @cindex Obsolescent features
5317 If this warning option is activated, then warnings are generated for
5318 calls to subprograms marked with @code{pragma Obsolescent} and
5319 for use of features in Annex J of the Ada Reference Manual. In the
5320 case of Annex J, not all features are flagged. In particular use
5321 of the renamed packages (like @code{Text_IO}) and use of package
5322 @code{ASCII} are not flagged, since these are very common and
5323 would generate many annoying positive warnings. The default is that
5324 such warnings are not generated. This warning is also turned on by
5325 the use of @option{-gnatwa}.
5326
5327 In addition to the above cases, warnings are also generated for
5328 GNAT features that have been provided in past versions but which
5329 have been superseded (typically by features in the new Ada standard).
5330 For example, @code{pragma Ravenscar} will be flagged since its
5331 function is replaced by @code{pragma Profile(Ravenscar)}.
5332
5333 Note that this warning option functions differently from the
5334 restriction @code{No_Obsolescent_Features} in two respects.
5335 First, the restriction applies only to annex J features.
5336 Second, the restriction does flag uses of package @code{ASCII}.
5337
5338 @item -gnatwJ
5339 @emph{Suppress warnings on obsolescent features (Annex J).}
5340 @cindex @option{-gnatwJ} (@command{gcc})
5341 This switch disables warnings on use of obsolescent features.
5342
5343 @item -gnatwk
5344 @emph{Activate warnings on variables that could be constants.}
5345 @cindex @option{-gnatwk} (@command{gcc})
5346 This switch activates warnings for variables that are initialized but
5347 never modified, and then could be declared constants. The default is that
5348 such warnings are not given.
5349 This warning can also be turned on using @option{-gnatwa}.
5350
5351 @item -gnatwK
5352 @emph{Suppress warnings on variables that could be constants.}
5353 @cindex @option{-gnatwK} (@command{gcc})
5354 This switch disables warnings on variables that could be declared constants.
5355
5356 @item -gnatwl
5357 @emph{Activate warnings for elaboration pragmas.}
5358 @cindex @option{-gnatwl} (@command{gcc})
5359 @cindex Elaboration, warnings
5360 This switch activates warnings on missing
5361 @code{Elaborate_All} and @code{Elaborate} pragmas.
5362 See the section in this guide on elaboration checking for details on
5363 when such pragmas should be used. In dynamic elaboration mode, this switch
5364 generations warnings about the need to add elaboration pragmas. Note however,
5365 that if you blindly follow these warnings, and add @code{Elaborate_All}
5366 warnings wherever they are recommended, you basically end up with the
5367 equivalent of the static elaboration model, which may not be what you want for
5368 legacy code for which the static model does not work.
5369
5370 For the static model, the messages generated are labeled "info:" (for
5371 information messages). They are not warnings to add elaboration pragmas,
5372 merely informational messages showing what implicit elaboration pragmas
5373 have been added, for use in analyzing elaboration circularity problems.
5374
5375 Warnings are also generated if you
5376 are using the static mode of elaboration, and a @code{pragma Elaborate}
5377 is encountered. The default is that such warnings
5378 are not generated.
5379 This warning is not automatically turned on by the use of @option{-gnatwa}.
5380
5381 @item -gnatwL
5382 @emph{Suppress warnings for elaboration pragmas.}
5383 @cindex @option{-gnatwL} (@command{gcc})
5384 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5385 See the section in this guide on elaboration checking for details on
5386 when such pragmas should be used.
5387
5388 @item -gnatwm
5389 @emph{Activate warnings on modified but unreferenced variables.}
5390 @cindex @option{-gnatwm} (@command{gcc})
5391 This switch activates warnings for variables that are assigned (using
5392 an initialization value or with one or more assignment statements) but
5393 whose value is never read. The warning is suppressed for volatile
5394 variables and also for variables that are renamings of other variables
5395 or for which an address clause is given.
5396 This warning can also be turned on using @option{-gnatwa}.
5397 The default is that these warnings are not given.
5398
5399 @item -gnatwM
5400 @emph{Disable warnings on modified but unreferenced variables.}
5401 @cindex @option{-gnatwM} (@command{gcc})
5402 This switch disables warnings for variables that are assigned or
5403 initialized, but never read.
5404
5405 @item -gnatw.m
5406 @emph{Activate warnings on suspicious modulus values.}
5407 @cindex @option{-gnatw.m} (@command{gcc})
5408 This switch activates warnings for modulus values that seem suspicious.
5409 The cases caught are where the size is the same as the modulus (e.g.
5410 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5411 with no size clause. The guess in both cases is that 2**x was intended
5412 rather than x. The default is that these warnings are given.
5413
5414 @item -gnatw.M
5415 @emph{Disable warnings on suspicious modulus values.}
5416 @cindex @option{-gnatw.M} (@command{gcc})
5417 This switch disables warnings for suspicious modulus values.
5418
5419 @item -gnatwn
5420 @emph{Set normal warnings mode.}
5421 @cindex @option{-gnatwn} (@command{gcc})
5422 This switch sets normal warning mode, in which enabled warnings are
5423 issued and treated as warnings rather than errors. This is the default
5424 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5425 an explicit @option{-gnatws} or
5426 @option{-gnatwe}. It also cancels the effect of the
5427 implicit @option{-gnatwe} that is activated by the
5428 use of @option{-gnatg}.
5429
5430 @item -gnatwo
5431 @emph{Activate warnings on address clause overlays.}
5432 @cindex @option{-gnatwo} (@command{gcc})
5433 @cindex Address Clauses, warnings
5434 This switch activates warnings for possibly unintended initialization
5435 effects of defining address clauses that cause one variable to overlap
5436 another. The default is that such warnings are generated.
5437 This warning can also be turned on using @option{-gnatwa}.
5438
5439 @item -gnatwO
5440 @emph{Suppress warnings on address clause overlays.}
5441 @cindex @option{-gnatwO} (@command{gcc})
5442 This switch suppresses warnings on possibly unintended initialization
5443 effects of defining address clauses that cause one variable to overlap
5444 another.
5445
5446 @item -gnatw.o
5447 @emph{Activate warnings on modified but unreferenced out parameters.}
5448 @cindex @option{-gnatw.o} (@command{gcc})
5449 This switch activates warnings for variables that are modified by using
5450 them as actuals for a call to a procedure with an out mode formal, where
5451 the resulting assigned value is never read. It is applicable in the case
5452 where there is more than one out mode formal. If there is only one out
5453 mode formal, the warning is issued by default (controlled by -gnatwu).
5454 The warning is suppressed for volatile
5455 variables and also for variables that are renamings of other variables
5456 or for which an address clause is given.
5457 The default is that these warnings are not given. Note that this warning
5458 is not included in -gnatwa, it must be activated explicitly.
5459
5460 @item -gnatw.O
5461 @emph{Disable warnings on modified but unreferenced out parameters.}
5462 @cindex @option{-gnatw.O} (@command{gcc})
5463 This switch suppresses warnings for variables that are modified by using
5464 them as actuals for a call to a procedure with an out mode formal, where
5465 the resulting assigned value is never read.
5466
5467 @item -gnatwp
5468 @emph{Activate warnings on ineffective pragma Inlines.}
5469 @cindex @option{-gnatwp} (@command{gcc})
5470 @cindex Inlining, warnings
5471 This switch activates warnings for failure of front end inlining
5472 (activated by @option{-gnatN}) to inline a particular call. There are
5473 many reasons for not being able to inline a call, including most
5474 commonly that the call is too complex to inline. The default is
5475 that such warnings are not given.
5476 This warning can also be turned on using @option{-gnatwa}.
5477 Warnings on ineffective inlining by the gcc back-end can be activated
5478 separately, using the gcc switch -Winline.
5479
5480 @item -gnatwP
5481 @emph{Suppress warnings on ineffective pragma Inlines.}
5482 @cindex @option{-gnatwP} (@command{gcc})
5483 This switch suppresses warnings on ineffective pragma Inlines. If the
5484 inlining mechanism cannot inline a call, it will simply ignore the
5485 request silently.
5486
5487 @item -gnatw.p
5488 @emph{Activate warnings on parameter ordering.}
5489 @cindex @option{-gnatw.p} (@command{gcc})
5490 @cindex Parameter order, warnings
5491 This switch activates warnings for cases of suspicious parameter
5492 ordering when the list of arguments are all simple identifiers that
5493 match the names of the formals, but are in a different order. The
5494 warning is suppressed if any use of named parameter notation is used,
5495 so this is the appropriate way to suppress a false positive (and
5496 serves to emphasize that the "misordering" is deliberate). The
5497 default is
5498 that such warnings are not given.
5499 This warning can also be turned on using @option{-gnatwa}.
5500
5501 @item -gnatw.P
5502 @emph{Suppress warnings on parameter ordering.}
5503 @cindex @option{-gnatw.P} (@command{gcc})
5504 This switch suppresses warnings on cases of suspicious parameter
5505 ordering.
5506
5507 @item -gnatwq
5508 @emph{Activate warnings on questionable missing parentheses.}
5509 @cindex @option{-gnatwq} (@command{gcc})
5510 @cindex Parentheses, warnings
5511 This switch activates warnings for cases where parentheses are not used and
5512 the result is potential ambiguity from a readers point of view. For example
5513 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5514 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5515 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5516 follow the rule of always parenthesizing to make the association clear, and
5517 this warning switch warns if such parentheses are not present. The default
5518 is that these warnings are given.
5519 This warning can also be turned on using @option{-gnatwa}.
5520
5521 @item -gnatwQ
5522 @emph{Suppress warnings on questionable missing parentheses.}
5523 @cindex @option{-gnatwQ} (@command{gcc})
5524 This switch suppresses warnings for cases where the association is not
5525 clear and the use of parentheses is preferred.
5526
5527 @item -gnatwr
5528 @emph{Activate warnings on redundant constructs.}
5529 @cindex @option{-gnatwr} (@command{gcc})
5530 This switch activates warnings for redundant constructs. The following
5531 is the current list of constructs regarded as redundant:
5532
5533 @itemize @bullet
5534 @item
5535 Assignment of an item to itself.
5536 @item
5537 Type conversion that converts an expression to its own type.
5538 @item
5539 Use of the attribute @code{Base} where @code{typ'Base} is the same
5540 as @code{typ}.
5541 @item
5542 Use of pragma @code{Pack} when all components are placed by a record
5543 representation clause.
5544 @item
5545 Exception handler containing only a reraise statement (raise with no
5546 operand) which has no effect.
5547 @item
5548 Use of the operator abs on an operand that is known at compile time
5549 to be non-negative
5550 @item
5551 Comparison of boolean expressions to an explicit True value.
5552 @end itemize
5553
5554 This warning can also be turned on using @option{-gnatwa}.
5555 The default is that warnings for redundant constructs are not given.
5556
5557 @item -gnatwR
5558 @emph{Suppress warnings on redundant constructs.}
5559 @cindex @option{-gnatwR} (@command{gcc})
5560 This switch suppresses warnings for redundant constructs.
5561
5562 @item -gnatw.r
5563 @emph{Activate warnings for object renaming function.}
5564 @cindex @option{-gnatw.r} (@command{gcc})
5565 This switch activates warnings for an object renaming that renames a
5566 function call, which is equivalent to a constant declaration (as
5567 opposed to renaming the function itself).  The default is that these
5568 warnings are given.  This warning can also be turned on using
5569 @option{-gnatwa}.
5570
5571 @item -gnatw.R
5572 @emph{Suppress warnings for object renaming function.}
5573 @cindex @option{-gnatwT} (@command{gcc})
5574 This switch suppresses warnings for object renaming function.
5575
5576 @item -gnatws
5577 @emph{Suppress all warnings.}
5578 @cindex @option{-gnatws} (@command{gcc})
5579 This switch completely suppresses the
5580 output of all warning messages from the GNAT front end.
5581 Note that it does not suppress warnings from the @command{gcc} back end.
5582 To suppress these back end warnings as well, use the switch @option{-w}
5583 in addition to @option{-gnatws}.
5584
5585 @item -gnatwt
5586 @emph{Activate warnings for tracking of deleted conditional code.}
5587 @cindex @option{-gnatwt} (@command{gcc})
5588 @cindex Deactivated code, warnings
5589 @cindex Deleted code, warnings
5590 This switch activates warnings for tracking of code in conditionals (IF and
5591 CASE statements) that is detected to be dead code which cannot be executed, and
5592 which is removed by the front end. This warning is off by default, and is not
5593 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5594 useful for detecting deactivated code in certified applications.
5595
5596 @item -gnatwT
5597 @emph{Suppress warnings for tracking of deleted conditional code.}
5598 @cindex @option{-gnatwT} (@command{gcc})
5599 This switch suppresses warnings for tracking of deleted conditional code.
5600
5601 @item -gnatwu
5602 @emph{Activate warnings on unused entities.}
5603 @cindex @option{-gnatwu} (@command{gcc})
5604 This switch activates warnings to be generated for entities that
5605 are declared but not referenced, and for units that are @code{with}'ed
5606 and not
5607 referenced. In the case of packages, a warning is also generated if
5608 no entities in the package are referenced. This means that if the package
5609 is referenced but the only references are in @code{use}
5610 clauses or @code{renames}
5611 declarations, a warning is still generated. A warning is also generated
5612 for a generic package that is @code{with}'ed but never instantiated.
5613 In the case where a package or subprogram body is compiled, and there
5614 is a @code{with} on the corresponding spec
5615 that is only referenced in the body,
5616 a warning is also generated, noting that the
5617 @code{with} can be moved to the body. The default is that
5618 such warnings are not generated.
5619 This switch also activates warnings on unreferenced formals
5620 (it includes the effect of @option{-gnatwf}).
5621 This warning can also be turned on using @option{-gnatwa}.
5622
5623 @item -gnatwU
5624 @emph{Suppress warnings on unused entities.}
5625 @cindex @option{-gnatwU} (@command{gcc})
5626 This switch suppresses warnings for unused entities and packages.
5627 It also turns off warnings on unreferenced formals (and thus includes
5628 the effect of @option{-gnatwF}).
5629
5630 @item -gnatwv
5631 @emph{Activate warnings on unassigned variables.}
5632 @cindex @option{-gnatwv} (@command{gcc})
5633 @cindex Unassigned variable warnings
5634 This switch activates warnings for access to variables which
5635 may not be properly initialized. The default is that
5636 such warnings are generated.
5637 This warning can also be turned on using @option{-gnatwa}.
5638
5639 @item -gnatwV
5640 @emph{Suppress warnings on unassigned variables.}
5641 @cindex @option{-gnatwV} (@command{gcc})
5642 This switch suppresses warnings for access to variables which
5643 may not be properly initialized.
5644 For variables of a composite type, the warning can also be suppressed in
5645 Ada 2005 by using a default initialization with a box. For example, if
5646 Table is an array of records whose components are only partially uninitialized,
5647 then the following code:
5648
5649 @smallexample @c ada
5650    Tab : Table := (others => <>);
5651 @end smallexample
5652
5653 will suppress warnings on subsequent statements that access components
5654 of variable Tab.
5655
5656 @item -gnatww
5657 @emph{Activate warnings on wrong low bound assumption.}
5658 @cindex @option{-gnatww} (@command{gcc})
5659 @cindex String indexing warnings
5660 This switch activates warnings for indexing an unconstrained string parameter
5661 with a literal or S'Length. This is a case where the code is assuming that the
5662 low bound is one, which is in general not true (for example when a slice is
5663 passed). The default is that such warnings are generated.
5664 This warning can also be turned on using @option{-gnatwa}.
5665
5666 @item -gnatwW
5667 @emph{Suppress warnings on wrong low bound assumption.}
5668 @cindex @option{-gnatwW} (@command{gcc})
5669 This switch suppresses warnings for indexing an unconstrained string parameter
5670 with a literal or S'Length. Note that this warning can also be suppressed
5671 in a particular case by adding an
5672 assertion that the lower bound is 1,
5673 as shown in the following example.
5674
5675 @smallexample @c ada
5676    procedure K (S : String) is
5677       pragma Assert (S'First = 1);
5678       @dots{}
5679 @end smallexample
5680
5681 @item -gnatw.w
5682 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5683 @cindex @option{-gnatw.w} (@command{gcc})
5684 @cindex Warnings Off control
5685 This switch activates warnings for use of @code{pragma Warnings (Off, entity}
5686 where either the pragma is entirely useless (because it suppresses no
5687 warnings), or it could be replaced by @code{pragma Unreferenced} or
5688 @code{pragma Unmodified}.The default is that these warnings are not given.
5689 Note that this warning is not included in -gnatwa, it must be
5690 activated explicitly.
5691
5692 @item -gnatw.W
5693 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5694 @cindex @option{-gnatw.W} (@command{gcc})
5695 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity}.
5696
5697 @item -gnatwx
5698 @emph{Activate warnings on Export/Import pragmas.}
5699 @cindex @option{-gnatwx} (@command{gcc})
5700 @cindex Export/Import pragma warnings
5701 This switch activates warnings on Export/Import pragmas when
5702 the compiler detects a possible conflict between the Ada and
5703 foreign language calling sequences. For example, the use of
5704 default parameters in a convention C procedure is dubious
5705 because the C compiler cannot supply the proper default, so
5706 a warning is issued. The default is that such warnings are
5707 generated.
5708 This warning can also be turned on using @option{-gnatwa}.
5709
5710 @item -gnatwX
5711 @emph{Suppress warnings on Export/Import pragmas.}
5712 @cindex @option{-gnatwX} (@command{gcc})
5713 This switch suppresses warnings on Export/Import pragmas.
5714 The sense of this is that you are telling the compiler that
5715 you know what you are doing in writing the pragma, and it
5716 should not complain at you.
5717
5718 @item -gnatw.x
5719 @emph{Activate warnings for No_Exception_Propagation mode.}
5720 @cindex @option{-gnatwm} (@command{gcc})
5721 This switch activates warnings for exception usage when pragma Restrictions
5722 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5723 explicit exception raises which are not covered by a local handler, and for
5724 exception handlers which do not cover a local raise. The default is that these
5725 warnings are not given.
5726
5727 @item -gnatw.X
5728 @emph{Disable warnings for No_Exception_Propagation mode.}
5729 This switch disables warnings for exception usage when pragma Restrictions
5730 (No_Exception_Propagation) is in effect.
5731
5732 @item -gnatwy
5733 @emph{Activate warnings for Ada 2005 compatibility issues.}
5734 @cindex @option{-gnatwy} (@command{gcc})
5735 @cindex Ada 2005 compatibility issues warnings
5736 For the most part Ada 2005 is upwards compatible with Ada 95,
5737 but there are some exceptions (for example the fact that
5738 @code{interface} is now a reserved word in Ada 2005). This
5739 switch activates several warnings to help in identifying
5740 and correcting such incompatibilities. The default is that
5741 these warnings are generated. Note that at one point Ada 2005
5742 was called Ada 0Y, hence the choice of character.
5743 This warning can also be turned on using @option{-gnatwa}.
5744
5745 @item -gnatwY
5746 @emph{Disable warnings for Ada 2005 compatibility issues.}
5747 @cindex @option{-gnatwY} (@command{gcc})
5748 @cindex Ada 2005 compatibility issues warnings
5749 This switch suppresses several warnings intended to help in identifying
5750 incompatibilities between Ada 95 and Ada 2005.
5751
5752 @item -gnatwz
5753 @emph{Activate warnings on unchecked conversions.}
5754 @cindex @option{-gnatwz} (@command{gcc})
5755 @cindex Unchecked_Conversion warnings
5756 This switch activates warnings for unchecked conversions
5757 where the types are known at compile time to have different
5758 sizes. The default
5759 is that such warnings are generated. Warnings are also
5760 generated for subprogram pointers with different conventions,
5761 and, on VMS only, for data pointers with different conventions.
5762 This warning can also be turned on using @option{-gnatwa}.
5763
5764 @item -gnatwZ
5765 @emph{Suppress warnings on unchecked conversions.}
5766 @cindex @option{-gnatwZ} (@command{gcc})
5767 This switch suppresses warnings for unchecked conversions
5768 where the types are known at compile time to have different
5769 sizes or conventions.
5770
5771 @item ^-Wunused^WARNINGS=UNUSED^
5772 @cindex @option{-Wunused}
5773 The warnings controlled by the @option{-gnatw} switch are generated by
5774 the front end of the compiler. The @option{GCC} back end can provide
5775 additional warnings and they are controlled by the @option{-W} switch.
5776 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5777 warnings for entities that are declared but not referenced.
5778
5779 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5780 @cindex @option{-Wuninitialized}
5781 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5782 the back end warning for uninitialized variables. This switch must be
5783 used in conjunction with an optimization level greater than zero.
5784
5785 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5786 @cindex @option{-Wall}
5787 This switch enables all the above warnings from the @option{GCC} back end.
5788 The code generator detects a number of warning situations that are missed
5789 by the @option{GNAT} front end, and this switch can be used to activate them.
5790 The use of this switch also sets the default front end warning mode to
5791 @option{-gnatwa}, that is, most front end warnings activated as well.
5792
5793 @item ^-w^/NO_BACK_END_WARNINGS^
5794 @cindex @option{-w}
5795 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5796 The use of this switch also sets the default front end warning mode to
5797 @option{-gnatws}, that is, front end warnings suppressed as well.
5798
5799 @end table
5800
5801 @noindent
5802 @ifclear vms
5803 A string of warning parameters can be used in the same parameter. For example:
5804
5805 @smallexample
5806 -gnatwaLe
5807 @end smallexample
5808
5809 @noindent
5810 will turn on all optional warnings except for elaboration pragma warnings,
5811 and also specify that warnings should be treated as errors.
5812 @end ifclear
5813 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5814
5815 @table @option
5816 @c !sort!
5817 @item -gnatwC
5818 @item -gnatwD
5819 @item -gnatwF
5820 @item -gnatwg
5821 @item -gnatwH
5822 @item -gnatwi
5823 @item -gnatwJ
5824 @item -gnatwK
5825 @item -gnatwL
5826 @item -gnatwM
5827 @item -gnatwn
5828 @item -gnatwo
5829 @item -gnatwP
5830 @item -gnatwR
5831 @item -gnatwU
5832 @item -gnatwv
5833 @item -gnatwz
5834 @item -gnatwx
5835
5836 @end table
5837
5838 @node Debugging and Assertion Control
5839 @subsection Debugging and Assertion Control
5840
5841 @table @option
5842 @item -gnata
5843 @cindex @option{-gnata} (@command{gcc})
5844 @findex Assert
5845 @findex Debug
5846 @cindex Assertions
5847
5848 @noindent
5849 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5850 are ignored. This switch, where @samp{a} stands for assert, causes
5851 @code{Assert} and @code{Debug} pragmas to be activated.
5852
5853 The pragmas have the form:
5854
5855 @smallexample
5856 @cartouche
5857    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5858                       @var{static-string-expression}@r{]})
5859    @b{pragma} Debug (@var{procedure call})
5860 @end cartouche
5861 @end smallexample
5862
5863 @noindent
5864 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5865 If the result is @code{True}, the pragma has no effect (other than
5866 possible side effects from evaluating the expression). If the result is
5867 @code{False}, the exception @code{Assert_Failure} declared in the package
5868 @code{System.Assertions} is
5869 raised (passing @var{static-string-expression}, if present, as the
5870 message associated with the exception). If no string expression is
5871 given the default is a string giving the file name and line number
5872 of the pragma.
5873
5874 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5875 @code{pragma Debug} may appear within a declaration sequence, allowing
5876 debugging procedures to be called between declarations.
5877
5878 @ifset vms
5879 @item /DEBUG@r{[}=debug-level@r{]}
5880 @itemx  /NODEBUG
5881 Specifies how much debugging information is to be included in
5882 the resulting object file where 'debug-level' is one of the following:
5883 @table @code
5884 @item   TRACEBACK
5885 Include both debugger symbol records and traceback
5886 the object file.
5887 This is the default setting.
5888 @item   ALL
5889 Include both debugger symbol records and traceback in
5890 object file.
5891 @item   NONE
5892 Excludes both debugger symbol records and traceback
5893 the object file. Same as /NODEBUG.
5894 @item   SYMBOLS
5895 Includes only debugger symbol records in the object
5896 file. Note that this doesn't include traceback information.
5897 @end table
5898 @end ifset
5899 @end table
5900
5901 @node Validity Checking
5902 @subsection Validity Checking
5903 @findex Validity Checking
5904
5905 @noindent
5906 The Ada Reference Manual defines the concept of invalid values (see
5907 RM 13.9.1). The primary source of invalid values is uninitialized
5908 variables. A scalar variable that is left uninitialized may contain
5909 an invalid value; the concept of invalid does not apply to access or
5910 composite types.
5911
5912 It is an error to read an invalid value, but the RM does not require
5913 run-time checks to detect such errors, except for some minimal
5914 checking to prevent erroneous execution (i.e. unpredictable
5915 behavior). This corresponds to the @option{-gnatVd} switch below,
5916 which is the default. For example, by default, if the expression of a
5917 case statement is invalid, it will raise Constraint_Error rather than
5918 causing a wild jump, and if an array index on the left-hand side of an
5919 assignment is invalid, it will raise Constraint_Error rather than
5920 overwriting an arbitrary memory location.
5921
5922 The @option{-gnatVa} may be used to enable additional validity checks,
5923 which are not required by the RM. These checks are often very
5924 expensive (which is why the RM does not require them). These checks
5925 are useful in tracking down uninitialized variables, but they are
5926 not usually recommended for production builds.
5927
5928 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
5929 control; you can enable whichever validity checks you desire. However,
5930 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5931 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5932 sufficient for non-debugging use.
5933
5934 The @option{-gnatB} switch tells the compiler to assume that all
5935 values are valid (that is, within their declared subtype range)
5936 except in the context of a use of the Valid attribute. This means
5937 the compiler can generate more efficient code, since the range
5938 of values is better known at compile time. However, an uninitialized
5939 variable can cause wild jumps and memory corruption in this mode.
5940
5941 The @option{-gnatV^@var{x}^^} switch allows control over the validity
5942 checking mode as described below.
5943 @ifclear vms
5944 The @code{x} argument is a string of letters that
5945 indicate validity checks that are performed or not performed in addition
5946 to the default checks required by Ada as described above.
5947 @end ifclear
5948 @ifset vms
5949 The options allowed for this qualifier
5950 indicate validity checks that are performed or not performed in addition
5951 to the default checks required by Ada as described above.
5952 @end ifset
5953
5954 @table @option
5955 @c !sort!
5956 @item -gnatVa
5957 @emph{All validity checks.}
5958 @cindex @option{-gnatVa} (@command{gcc})
5959 All validity checks are turned on.
5960 @ifclear vms
5961 That is, @option{-gnatVa} is
5962 equivalent to @option{gnatVcdfimorst}.
5963 @end ifclear
5964
5965 @item -gnatVc
5966 @emph{Validity checks for copies.}
5967 @cindex @option{-gnatVc} (@command{gcc})
5968 The right hand side of assignments, and the initializing values of
5969 object declarations are validity checked.
5970
5971 @item -gnatVd
5972 @emph{Default (RM) validity checks.}
5973 @cindex @option{-gnatVd} (@command{gcc})
5974 Some validity checks are done by default following normal Ada semantics
5975 (RM 13.9.1 (9-11)).
5976 A check is done in case statements that the expression is within the range
5977 of the subtype. If it is not, Constraint_Error is raised.
5978 For assignments to array components, a check is done that the expression used
5979 as index is within the range. If it is not, Constraint_Error is raised.
5980 Both these validity checks may be turned off using switch @option{-gnatVD}.
5981 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5982 switch @option{-gnatVd} will leave the checks turned on.
5983 Switch @option{-gnatVD} should be used only if you are sure that all such
5984 expressions have valid values. If you use this switch and invalid values
5985 are present, then the program is erroneous, and wild jumps or memory
5986 overwriting may occur.
5987
5988 @item -gnatVe
5989 @emph{Validity checks for elementary components.}
5990 @cindex @option{-gnatVe} (@command{gcc})
5991 In the absence of this switch, assignments to record or array components are
5992 not validity checked, even if validity checks for assignments generally
5993 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5994 require valid data, but assignment of individual components does. So for
5995 example, there is a difference between copying the elements of an array with a
5996 slice assignment, compared to assigning element by element in a loop. This
5997 switch allows you to turn off validity checking for components, even when they
5998 are assigned component by component.
5999
6000 @item -gnatVf
6001 @emph{Validity checks for floating-point values.}
6002 @cindex @option{-gnatVf} (@command{gcc})
6003 In the absence of this switch, validity checking occurs only for discrete
6004 values. If @option{-gnatVf} is specified, then validity checking also applies
6005 for floating-point values, and NaNs and infinities are considered invalid,
6006 as well as out of range values for constrained types. Note that this means
6007 that standard IEEE infinity mode is not allowed. The exact contexts
6008 in which floating-point values are checked depends on the setting of other
6009 options. For example,
6010 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6011 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6012 (the order does not matter) specifies that floating-point parameters of mode
6013 @code{in} should be validity checked.
6014
6015 @item -gnatVi
6016 @emph{Validity checks for @code{in} mode parameters}
6017 @cindex @option{-gnatVi} (@command{gcc})
6018 Arguments for parameters of mode @code{in} are validity checked in function
6019 and procedure calls at the point of call.
6020
6021 @item -gnatVm
6022 @emph{Validity checks for @code{in out} mode parameters.}
6023 @cindex @option{-gnatVm} (@command{gcc})
6024 Arguments for parameters of mode @code{in out} are validity checked in
6025 procedure calls at the point of call. The @code{'m'} here stands for
6026 modify, since this concerns parameters that can be modified by the call.
6027 Note that there is no specific option to test @code{out} parameters,
6028 but any reference within the subprogram will be tested in the usual
6029 manner, and if an invalid value is copied back, any reference to it
6030 will be subject to validity checking.
6031
6032 @item -gnatVn
6033 @emph{No validity checks.}
6034 @cindex @option{-gnatVn} (@command{gcc})
6035 This switch turns off all validity checking, including the default checking
6036 for case statements and left hand side subscripts. Note that the use of
6037 the switch @option{-gnatp} suppresses all run-time checks, including
6038 validity checks, and thus implies @option{-gnatVn}. When this switch
6039 is used, it cancels any other @option{-gnatV} previously issued.
6040
6041 @item -gnatVo
6042 @emph{Validity checks for operator and attribute operands.}
6043 @cindex @option{-gnatVo} (@command{gcc})
6044 Arguments for predefined operators and attributes are validity checked.
6045 This includes all operators in package @code{Standard},
6046 the shift operators defined as intrinsic in package @code{Interfaces}
6047 and operands for attributes such as @code{Pos}. Checks are also made
6048 on individual component values for composite comparisons, and on the
6049 expressions in type conversions and qualified expressions. Checks are
6050 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6051
6052 @item -gnatVp
6053 @emph{Validity checks for parameters.}
6054 @cindex @option{-gnatVp} (@command{gcc})
6055 This controls the treatment of parameters within a subprogram (as opposed
6056 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6057 of parameters on a call. If either of these call options is used, then
6058 normally an assumption is made within a subprogram that the input arguments
6059 have been validity checking at the point of call, and do not need checking
6060 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6061 is not made, and parameters are not assumed to be valid, so their validity
6062 will be checked (or rechecked) within the subprogram.
6063
6064 @item -gnatVr
6065 @emph{Validity checks for function returns.}
6066 @cindex @option{-gnatVr} (@command{gcc})
6067 The expression in @code{return} statements in functions is validity
6068 checked.
6069
6070 @item -gnatVs
6071 @emph{Validity checks for subscripts.}
6072 @cindex @option{-gnatVs} (@command{gcc})
6073 All subscripts expressions are checked for validity, whether they appear
6074 on the right side or left side (in default mode only left side subscripts
6075 are validity checked).
6076
6077 @item -gnatVt
6078 @emph{Validity checks for tests.}
6079 @cindex @option{-gnatVt} (@command{gcc})
6080 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6081 statements are checked, as well as guard expressions in entry calls.
6082
6083 @end table
6084
6085 @noindent
6086 The @option{-gnatV} switch may be followed by
6087 ^a string of letters^a list of options^
6088 to turn on a series of validity checking options.
6089 For example,
6090 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6091 specifies that in addition to the default validity checking, copies and
6092 function return expressions are to be validity checked.
6093 In order to make it easier
6094 to specify the desired combination of effects,
6095 @ifclear vms
6096 the upper case letters @code{CDFIMORST} may
6097 be used to turn off the corresponding lower case option.
6098 @end ifclear
6099 @ifset vms
6100 the prefix @code{NO} on an option turns off the corresponding validity
6101 checking:
6102 @itemize @bullet
6103 @item @code{NOCOPIES}
6104 @item @code{NODEFAULT}
6105 @item @code{NOFLOATS}
6106 @item @code{NOIN_PARAMS}
6107 @item @code{NOMOD_PARAMS}
6108 @item @code{NOOPERANDS}
6109 @item @code{NORETURNS}
6110 @item @code{NOSUBSCRIPTS}
6111 @item @code{NOTESTS}
6112 @end itemize
6113 @end ifset
6114 Thus
6115 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6116 turns on all validity checking options except for
6117 checking of @code{@b{in out}} procedure arguments.
6118
6119 The specification of additional validity checking generates extra code (and
6120 in the case of @option{-gnatVa} the code expansion can be substantial).
6121 However, these additional checks can be very useful in detecting
6122 uninitialized variables, incorrect use of unchecked conversion, and other
6123 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6124 is useful in conjunction with the extra validity checking, since this
6125 ensures that wherever possible uninitialized variables have invalid values.
6126
6127 See also the pragma @code{Validity_Checks} which allows modification of
6128 the validity checking mode at the program source level, and also allows for
6129 temporary disabling of validity checks.
6130
6131 @node Style Checking
6132 @subsection Style Checking
6133 @findex Style checking
6134
6135 @noindent
6136 The @option{-gnaty^x^(option,option,@dots{})^} switch
6137 @cindex @option{-gnaty} (@command{gcc})
6138 causes the compiler to
6139 enforce specified style rules. A limited set of style rules has been used
6140 in writing the GNAT sources themselves. This switch allows user programs
6141 to activate all or some of these checks. If the source program fails a
6142 specified style check, an appropriate warning message is given, preceded by
6143 the character sequence ``(style)''.
6144 @ifset vms
6145 @code{(option,option,@dots{})} is a sequence of keywords
6146 @end ifset
6147 @ifclear vms
6148 The string @var{x} is a sequence of letters or digits
6149 @end ifclear
6150 indicating the particular style
6151 checks to be performed. The following checks are defined:
6152
6153 @table @option
6154 @c !sort!
6155 @item 0-9
6156 @emph{Specify indentation level.}
6157 If a digit from 1-9 appears
6158 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6159 then proper indentation is checked, with the digit indicating the
6160 indentation level required. A value of zero turns off this style check.
6161 The general style of required indentation is as specified by
6162 the examples in the Ada Reference Manual. Full line comments must be
6163 aligned with the @code{--} starting on a column that is a multiple of
6164 the alignment level, or they may be aligned the same way as the following
6165 non-blank line (this is useful when full line comments appear in the middle
6166 of a statement.
6167
6168 @item ^a^ATTRIBUTE^
6169 @emph{Check attribute casing.}
6170 Attribute names, including the case of keywords such as @code{digits}
6171 used as attributes names, must be written in mixed case, that is, the
6172 initial letter and any letter following an underscore must be uppercase.
6173 All other letters must be lowercase.
6174
6175 @item ^A^ARRAY_INDEXES^
6176 @emph{Use of array index numbers in array attributes.}
6177 When using the array attributes First, Last, Range,
6178 or Length, the index number must be omitted for one-dimensional arrays
6179 and is required for multi-dimensional arrays.
6180
6181 @item ^b^BLANKS^
6182 @emph{Blanks not allowed at statement end.}
6183 Trailing blanks are not allowed at the end of statements. The purpose of this
6184 rule, together with h (no horizontal tabs), is to enforce a canonical format
6185 for the use of blanks to separate source tokens.
6186
6187 @item ^B^BOOLEAN_OPERATORS^
6188 @emph{Check Boolean operators.}
6189 The use of AND/OR operators is not permitted except in the cases of modular
6190 operands, array operands, and simple stand-alone boolean variables or
6191 boolean constants. In all other cases AND THEN/OR ELSE are required.
6192
6193 @item ^c^COMMENTS^
6194 @emph{Check comments.}
6195 Comments must meet the following set of rules:
6196
6197 @itemize @bullet
6198
6199 @item
6200 The ``@code{--}'' that starts the column must either start in column one,
6201 or else at least one blank must precede this sequence.
6202
6203 @item
6204 Comments that follow other tokens on a line must have at least one blank
6205 following the ``@code{--}'' at the start of the comment.
6206
6207 @item
6208 Full line comments must have two blanks following the ``@code{--}'' that
6209 starts the comment, with the following exceptions.
6210
6211 @item
6212 A line consisting only of the ``@code{--}'' characters, possibly preceded
6213 by blanks is permitted.
6214
6215 @item
6216 A comment starting with ``@code{--x}'' where @code{x} is a special character
6217 is permitted.
6218 This allows proper processing of the output generated by specialized tools
6219 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6220 annotation
6221 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6222 special character is defined as being in one of the ASCII ranges
6223 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6224 Note that this usage is not permitted
6225 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6226
6227 @item
6228 A line consisting entirely of minus signs, possibly preceded by blanks, is
6229 permitted. This allows the construction of box comments where lines of minus
6230 signs are used to form the top and bottom of the box.
6231
6232 @item
6233 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6234 least one blank follows the initial ``@code{--}''. Together with the preceding
6235 rule, this allows the construction of box comments, as shown in the following
6236 example:
6237 @smallexample
6238 ---------------------------
6239 -- This is a box comment --
6240 -- with two text lines.  --
6241 ---------------------------
6242 @end smallexample
6243 @end itemize
6244
6245 @item ^d^DOS_LINE_ENDINGS^
6246 @emph{Check no DOS line terminators present.}
6247 All lines must be terminated by a single ASCII.LF
6248 character (in particular the DOS line terminator sequence CR/LF is not
6249 allowed).
6250
6251 @item ^e^END^
6252 @emph{Check end/exit labels.}
6253 Optional labels on @code{end} statements ending subprograms and on
6254 @code{exit} statements exiting named loops, are required to be present.
6255
6256 @item ^f^VTABS^
6257 @emph{No form feeds or vertical tabs.}
6258 Neither form feeds nor vertical tab characters are permitted
6259 in the source text.
6260
6261 @item ^g^GNAT^
6262 @emph{GNAT style mode}
6263 The set of style check switches is set to match that used by the GNAT sources.
6264 This may be useful when developing code that is eventually intended to be
6265 incorporated into GNAT. For further details, see GNAT sources.
6266
6267 @item ^h^HTABS^
6268 @emph{No horizontal tabs.}
6269 Horizontal tab characters are not permitted in the source text.
6270 Together with the b (no blanks at end of line) check, this
6271 enforces a canonical form for the use of blanks to separate
6272 source tokens.
6273
6274 @item ^i^IF_THEN^
6275 @emph{Check if-then layout.}
6276 The keyword @code{then} must appear either on the same
6277 line as corresponding @code{if}, or on a line on its own, lined
6278 up under the @code{if} with at least one non-blank line in between
6279 containing all or part of the condition to be tested.
6280
6281 @item ^I^IN_MODE^
6282 @emph{check mode IN keywords}
6283 Mode @code{in} (the default mode) is not
6284 allowed to be given explicitly. @code{in out} is fine,
6285 but not @code{in} on its own.
6286
6287 @item ^k^KEYWORD^
6288 @emph{Check keyword casing.}
6289 All keywords must be in lower case (with the exception of keywords
6290 such as @code{digits} used as attribute names to which this check
6291 does not apply).
6292
6293 @item ^l^LAYOUT^
6294 @emph{Check layout.}
6295 Layout of statement and declaration constructs must follow the
6296 recommendations in the Ada Reference Manual, as indicated by the
6297 form of the syntax rules. For example an @code{else} keyword must
6298 be lined up with the corresponding @code{if} keyword.
6299
6300 There are two respects in which the style rule enforced by this check
6301 option are more liberal than those in the Ada Reference Manual. First
6302 in the case of record declarations, it is permissible to put the
6303 @code{record} keyword on the same line as the @code{type} keyword, and
6304 then the @code{end} in @code{end record} must line up under @code{type}.
6305 This is also permitted when the type declaration is split on two lines.
6306 For example, any of the following three layouts is acceptable:
6307
6308 @smallexample @c ada
6309 @cartouche
6310 type q is record
6311    a : integer;
6312    b : integer;
6313 end record;
6314
6315 type q is
6316    record
6317       a : integer;
6318       b : integer;
6319    end record;
6320
6321 type q is
6322    record
6323       a : integer;
6324       b : integer;
6325 end record;
6326
6327 @end cartouche
6328 @end smallexample
6329
6330 @noindent
6331 Second, in the case of a block statement, a permitted alternative
6332 is to put the block label on the same line as the @code{declare} or
6333 @code{begin} keyword, and then line the @code{end} keyword up under
6334 the block label. For example both the following are permitted:
6335
6336 @smallexample @c ada
6337 @cartouche
6338 Block : declare
6339    A : Integer := 3;
6340 begin
6341    Proc (A, A);
6342 end Block;
6343
6344 Block :
6345    declare
6346       A : Integer := 3;
6347    begin
6348       Proc (A, A);
6349    end Block;
6350 @end cartouche
6351 @end smallexample
6352
6353 @noindent
6354 The same alternative format is allowed for loops. For example, both of
6355 the following are permitted:
6356
6357 @smallexample @c ada
6358 @cartouche
6359 Clear : while J < 10 loop
6360    A (J) := 0;
6361 end loop Clear;
6362
6363 Clear :
6364    while J < 10 loop
6365       A (J) := 0;
6366    end loop Clear;
6367 @end cartouche
6368 @end smallexample
6369
6370 @item ^Lnnn^MAX_NESTING=nnn^
6371 @emph{Set maximum nesting level}
6372 The maximum level of nesting of constructs (including subprograms, loops,
6373 blocks, packages, and conditionals) may not exceed the given value
6374 @option{nnn}. A value of zero disconnects this style check.
6375
6376 @item ^m^LINE_LENGTH^
6377 @emph{Check maximum line length.}
6378 The length of source lines must not exceed 79 characters, including
6379 any trailing blanks. The value of 79 allows convenient display on an
6380 80 character wide device or window, allowing for possible special
6381 treatment of 80 character lines. Note that this count is of
6382 characters in the source text. This means that a tab character counts
6383 as one character in this count but a wide character sequence counts as
6384 a single character (however many bytes are needed in the encoding).
6385
6386 @item ^Mnnn^MAX_LENGTH=nnn^
6387 @emph{Set maximum line length.}
6388 The length of lines must not exceed the
6389 given value @option{nnn}. The maximum value that can be specified is 32767.
6390
6391 @item ^n^STANDARD_CASING^
6392 @emph{Check casing of entities in Standard.}
6393 Any identifier from Standard must be cased
6394 to match the presentation in the Ada Reference Manual (for example,
6395 @code{Integer} and @code{ASCII.NUL}).
6396
6397 @item ^N^NONE^
6398 @emph{Turn off all style checks}
6399 All style check options are turned off.
6400
6401 @item ^o^ORDERED_SUBPROGRAMS^
6402 @emph{Check order of subprogram bodies.}
6403 All subprogram bodies in a given scope
6404 (e.g.@: a package body) must be in alphabetical order. The ordering
6405 rule uses normal Ada rules for comparing strings, ignoring casing
6406 of letters, except that if there is a trailing numeric suffix, then
6407 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6408 before Junk10).
6409
6410 @item ^O^OVERRIDING_INDICATORS^
6411 @emph{Check that overriding subprograms are explicitly marked as such.}
6412 The declaration of a primitive operation of a type extension that overrides
6413 an inherited operation must carry an overriding indicator.
6414
6415 @item ^p^PRAGMA^
6416 @emph{Check pragma casing.}
6417 Pragma names must be written in mixed case, that is, the
6418 initial letter and any letter following an underscore must be uppercase.
6419 All other letters must be lowercase.
6420
6421 @item ^r^REFERENCES^
6422 @emph{Check references.}
6423 All identifier references must be cased in the same way as the
6424 corresponding declaration. No specific casing style is imposed on
6425 identifiers. The only requirement is for consistency of references
6426 with declarations.
6427
6428 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6429 @emph{Check no statements after THEN/ELSE.}
6430 No statements are allowed
6431 on the same line as a THEN or ELSE keyword following the
6432 keyword in an IF statement. OR ELSE and AND THEN are not affected,
6433 and a special exception allows a pragma to appear after ELSE.
6434
6435 @item ^s^SPECS^
6436 @emph{Check separate specs.}
6437 Separate declarations (``specs'') are required for subprograms (a
6438 body is not allowed to serve as its own declaration). The only
6439 exception is that parameterless library level procedures are
6440 not required to have a separate declaration. This exception covers
6441 the most frequent form of main program procedures.
6442
6443 @item ^t^TOKEN^
6444 @emph{Check token spacing.}
6445 The following token spacing rules are enforced:
6446
6447 @itemize @bullet
6448
6449 @item
6450 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
6451
6452 @item
6453 The token @code{=>} must be surrounded by spaces.
6454
6455 @item
6456 The token @code{<>} must be preceded by a space or a left parenthesis.
6457
6458 @item
6459 Binary operators other than @code{**} must be surrounded by spaces.
6460 There is no restriction on the layout of the @code{**} binary operator.
6461
6462 @item
6463 Colon must be surrounded by spaces.
6464
6465 @item
6466 Colon-equal (assignment, initialization) must be surrounded by spaces.
6467
6468 @item
6469 Comma must be the first non-blank character on the line, or be
6470 immediately preceded by a non-blank character, and must be followed
6471 by a space.
6472
6473 @item
6474 If the token preceding a left parenthesis ends with a letter or digit, then
6475 a space must separate the two tokens.
6476
6477 @item
6478 if the token following a right parenthesis starts with a letter or digit, then
6479 a space must separate the two tokens.
6480
6481 @item
6482 A right parenthesis must either be the first non-blank character on
6483 a line, or it must be preceded by a non-blank character.
6484
6485 @item
6486 A semicolon must not be preceded by a space, and must not be followed by
6487 a non-blank character.
6488
6489 @item
6490 A unary plus or minus may not be followed by a space.
6491
6492 @item
6493 A vertical bar must be surrounded by spaces.
6494 @end itemize
6495
6496 @item ^u^UNNECESSARY_BLANK_LINES^
6497 @emph{Check unnecessary blank lines.}
6498 Unnecessary blank lines are not allowed. A blank line is considered
6499 unnecessary if it appears at the end of the file, or if more than
6500 one blank line occurs in sequence.
6501
6502 @item ^x^XTRA_PARENS^
6503 @emph{Check extra parentheses.}
6504 Unnecessary extra level of parentheses (C-style) are not allowed
6505 around conditions in @code{if} statements, @code{while} statements and
6506 @code{exit} statements.
6507
6508 @item ^y^ALL_BUILTIN^
6509 @emph{Set all standard style check options}
6510 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6511 options enabled with the exception of @option{-gnatyo}, @option{-gnatyI},
6512 @option{-gnatyS}, @option{-gnatyLnnn},
6513 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
6514
6515 @ifclear vms
6516 @item -
6517 @emph{Remove style check options}
6518 This causes any subsequent options in the string to act as canceling the
6519 corresponding style check option. To cancel maximum nesting level control,
6520 use @option{L} parameter witout any integer value after that, because any
6521 digit following @option{-} in the parameter string of the @option{-gnaty}
6522 option will be threated as canceling indentation check. The same is true
6523 for @option{M} parameter. @option{y} and @option{N} parameters are not
6524 allowed after @option{-}.
6525
6526 @item +
6527 This causes any subsequent options in the string to enable the corresponding
6528 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6529 if any.
6530 @end ifclear
6531
6532 @ifset vms
6533 @item NOxxx
6534 @emph{Removing style check options}
6535 If the name of a style check is preceded by @option{NO} then the corresponding
6536 style check is turned off. For example @option{NOCOMMENTS} turns off style
6537 checking for comments.
6538 @end ifset
6539 @end table
6540
6541 @noindent
6542 In the above rules, appearing in column one is always permitted, that is,
6543 counts as meeting either a requirement for a required preceding space,
6544 or as meeting a requirement for no preceding space.
6545
6546 Appearing at the end of a line is also always permitted, that is, counts
6547 as meeting either a requirement for a following space, or as meeting
6548 a requirement for no following space.
6549
6550 @noindent
6551 If any of these style rules is violated, a message is generated giving
6552 details on the violation. The initial characters of such messages are
6553 always ``@code{(style)}''. Note that these messages are treated as warning
6554 messages, so they normally do not prevent the generation of an object
6555 file. The @option{-gnatwe} switch can be used to treat warning messages,
6556 including style messages, as fatal errors.
6557
6558 The switch
6559 @ifclear vms
6560 @option{-gnaty} on its own (that is not
6561 followed by any letters or digits), then the effect is equivalent
6562 to the use of @option{-gnatyy}, as described above, that is all
6563 built-in standard style check options are enabled.
6564
6565 @end ifclear
6566 @ifset vms
6567 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6568 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6569 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6570 @end ifset
6571
6572 The switch
6573 @ifclear vms
6574 @option{-gnatyN}
6575 @end ifclear
6576 @ifset vms
6577 /STYLE_CHECKS=NONE
6578 @end ifset
6579 clears any previously set style checks.
6580
6581 @node Run-Time Checks
6582 @subsection Run-Time Checks
6583 @cindex Division by zero
6584 @cindex Access before elaboration
6585 @cindex Checks, division by zero
6586 @cindex Checks, access before elaboration
6587 @cindex Checks, stack overflow checking
6588
6589 @noindent
6590 By default, the following checks are suppressed: integer overflow
6591 checks, stack overflow checks, and checks for access before
6592 elaboration on subprogram calls. All other checks, including range
6593 checks and array bounds checks, are turned on by default. The
6594 following @command{gcc} switches refine this default behavior.
6595
6596 @table @option
6597 @c !sort!
6598 @item -gnatp
6599 @cindex @option{-gnatp} (@command{gcc})
6600 @cindex Suppressing checks
6601 @cindex Checks, suppressing
6602 @findex Suppress
6603 This switch causes the unit to be compiled
6604 as though @code{pragma Suppress (All_checks)}
6605 had been present in the source. Validity checks are also eliminated (in
6606 other words @option{-gnatp} also implies @option{-gnatVn}.
6607 Use this switch to improve the performance
6608 of the code at the expense of safety in the presence of invalid data or
6609 program bugs.
6610
6611 Note that when checks are suppressed, the compiler is allowed, but not
6612 required, to omit the checking code. If the run-time cost of the
6613 checking code is zero or near-zero, the compiler will generate it even
6614 if checks are suppressed. In particular, if the compiler can prove
6615 that a certain check will necessarily fail, it will generate code to
6616 do an unconditional ``raise'', even if checks are suppressed. The
6617 compiler warns in this case. Another case in which checks may not be
6618 eliminated is when they are embedded in certain run time routines such
6619 as math library routines.
6620
6621 Of course, run-time checks are omitted whenever the compiler can prove
6622 that they will not fail, whether or not checks are suppressed.
6623
6624 Note that if you suppress a check that would have failed, program
6625 execution is erroneous, which means the behavior is totally
6626 unpredictable. The program might crash, or print wrong answers, or
6627 do anything else. It might even do exactly what you wanted it to do
6628 (and then it might start failing mysteriously next week or next
6629 year). The compiler will generate code based on the assumption that
6630 the condition being checked is true, which can result in disaster if
6631 that assumption is wrong.
6632
6633 The @option{-gnatp} switch has no effect if a subsequent
6634 @option{-gnat-p} switch appears.
6635
6636 @item -gnat-p
6637 @cindex @option{-gnat-p} (@command{gcc})
6638 @cindex Suppressing checks
6639 @cindex Checks, suppressing
6640 @findex Suppress
6641 This switch cancels the effect of a previous @option{gnatp} switch.
6642
6643 @item -gnato
6644 @cindex @option{-gnato} (@command{gcc})
6645 @cindex Overflow checks
6646 @cindex Check, overflow
6647 Enables overflow checking for integer operations.
6648 This causes GNAT to generate slower and larger executable
6649 programs by adding code to check for overflow (resulting in raising
6650 @code{Constraint_Error} as required by standard Ada
6651 semantics). These overflow checks correspond to situations in which
6652 the true value of the result of an operation may be outside the base
6653 range of the result type. The following example shows the distinction:
6654
6655 @smallexample @c ada
6656 X1 : Integer := "Integer'Last";
6657 X2 : Integer range 1 .. 5 := "5";
6658 X3 : Integer := "Integer'Last";
6659 X4 : Integer range 1 .. 5 := "5";
6660 F  : Float := "2.0E+20";
6661 @dots{}
6662 X1 := X1 + 1;
6663 X2 := X2 + 1;
6664 X3 := Integer (F);
6665 X4 := Integer (F);
6666 @end smallexample
6667
6668 @noindent
6669 Note that if explicit values are assigned at compile time, the
6670 compiler may be able to detect overflow at compile time, in which case
6671 no actual run-time checking code is required, and Constraint_Error
6672 will be raised unconditionally, with or without
6673 @option{-gnato}. That's why the assigned values in the above fragment
6674 are in quotes, the meaning is "assign a value not known to the
6675 compiler that happens to be equal to ...". The remaining discussion
6676 assumes that the compiler cannot detect the values at compile time.
6677
6678 Here the first addition results in a value that is outside the base range
6679 of Integer, and hence requires an overflow check for detection of the
6680 constraint error. Thus the first assignment to @code{X1} raises a
6681 @code{Constraint_Error} exception only if @option{-gnato} is set.
6682
6683 The second increment operation results in a violation of the explicit
6684 range constraint; such range checks are performed by default, and are
6685 unaffected by @option{-gnato}.
6686
6687 The two conversions of @code{F} both result in values that are outside
6688 the base range of type @code{Integer} and thus will raise
6689 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
6690 The fact that the result of the second conversion is assigned to
6691 variable @code{X4} with a restricted range is irrelevant, since the problem
6692 is in the conversion, not the assignment.
6693
6694 Basically the rule is that in the default mode (@option{-gnato} not
6695 used), the generated code assures that all integer variables stay
6696 within their declared ranges, or within the base range if there is
6697 no declared range. This prevents any serious problems like indexes
6698 out of range for array operations.
6699
6700 What is not checked in default mode is an overflow that results in
6701 an in-range, but incorrect value. In the above example, the assignments
6702 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
6703 range of the target variable, but the result is wrong in the sense that
6704 it is too large to be represented correctly. Typically the assignment
6705 to @code{X1} will result in wrap around to the largest negative number.
6706 The conversions of @code{F} will result in some @code{Integer} value
6707 and if that integer value is out of the @code{X4} range then the
6708 subsequent assignment would generate an exception.
6709
6710 @findex Machine_Overflows
6711 Note that the @option{-gnato} switch does not affect the code generated
6712 for any floating-point operations; it applies only to integer
6713 semantics).
6714 For floating-point, GNAT has the @code{Machine_Overflows}
6715 attribute set to @code{False} and the normal mode of operation is to
6716 generate IEEE NaN and infinite values on overflow or invalid operations
6717 (such as dividing 0.0 by 0.0).
6718
6719 The reason that we distinguish overflow checking from other kinds of
6720 range constraint checking is that a failure of an overflow check, unlike
6721 for example the failure of a range check, can result in an incorrect
6722 value, but cannot cause random memory destruction (like an out of range
6723 subscript), or a wild jump (from an out of range case value). Overflow
6724 checking is also quite expensive in time and space, since in general it
6725 requires the use of double length arithmetic.
6726
6727 Note again that @option{-gnato} is off by default, so overflow checking is
6728 not performed in default mode. This means that out of the box, with the
6729 default settings, GNAT does not do all the checks expected from the
6730 language description in the Ada Reference Manual. If you want all constraint
6731 checks to be performed, as described in this Manual, then you must
6732 explicitly use the -gnato switch either on the @command{gnatmake} or
6733 @command{gcc} command.
6734
6735 @item -gnatE
6736 @cindex @option{-gnatE} (@command{gcc})
6737 @cindex Elaboration checks
6738 @cindex Check, elaboration
6739 Enables dynamic checks for access-before-elaboration
6740 on subprogram calls and generic instantiations.
6741 Note that @option{-gnatE} is not necessary for safety, because in the
6742 default mode, GNAT ensures statically that the checks would not fail.
6743 For full details of the effect and use of this switch,
6744 @xref{Compiling Using gcc}.
6745
6746 @item -fstack-check
6747 @cindex @option{-fstack-check} (@command{gcc})
6748 @cindex Stack Overflow Checking
6749 @cindex Checks, stack overflow checking
6750 Activates stack overflow checking. For full details of the effect and use of
6751 this switch see @ref{Stack Overflow Checking}.
6752 @end table
6753
6754 @findex Unsuppress
6755 @noindent
6756 The setting of these switches only controls the default setting of the
6757 checks. You may modify them using either @code{Suppress} (to remove
6758 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6759 the program source.
6760
6761 @node Using gcc for Syntax Checking
6762 @subsection Using @command{gcc} for Syntax Checking
6763 @table @option
6764 @item -gnats
6765 @cindex @option{-gnats} (@command{gcc})
6766 @ifclear vms
6767
6768 @noindent
6769 The @code{s} stands for ``syntax''.
6770 @end ifclear
6771
6772 Run GNAT in syntax checking only mode. For
6773 example, the command
6774
6775 @smallexample
6776 $ gcc -c -gnats x.adb
6777 @end smallexample
6778
6779 @noindent
6780 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6781 series of files in a single command
6782 @ifclear vms
6783 , and can use wild cards to specify such a group of files.
6784 Note that you must specify the @option{-c} (compile
6785 only) flag in addition to the @option{-gnats} flag.
6786 @end ifclear
6787 .
6788 You may use other switches in conjunction with @option{-gnats}. In
6789 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6790 format of any generated error messages.
6791
6792 When the source file is empty or contains only empty lines and/or comments,
6793 the output is a warning:
6794
6795 @smallexample
6796 $ gcc -c -gnats -x ada toto.txt
6797 toto.txt:1:01: warning: empty file, contains no compilation units
6798 $
6799 @end smallexample
6800
6801 Otherwise, the output is simply the error messages, if any. No object file or
6802 ALI file is generated by a syntax-only compilation. Also, no units other
6803 than the one specified are accessed. For example, if a unit @code{X}
6804 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6805 check only mode does not access the source file containing unit
6806 @code{Y}.
6807
6808 @cindex Multiple units, syntax checking
6809 Normally, GNAT allows only a single unit in a source file. However, this
6810 restriction does not apply in syntax-check-only mode, and it is possible
6811 to check a file containing multiple compilation units concatenated
6812 together. This is primarily used by the @code{gnatchop} utility
6813 (@pxref{Renaming Files Using gnatchop}).
6814 @end table
6815
6816 @node Using gcc for Semantic Checking
6817 @subsection Using @command{gcc} for Semantic Checking
6818 @table @option
6819 @item -gnatc
6820 @cindex @option{-gnatc} (@command{gcc})
6821
6822 @ifclear vms
6823 @noindent
6824 The @code{c} stands for ``check''.
6825 @end ifclear
6826 Causes the compiler to operate in semantic check mode,
6827 with full checking for all illegalities specified in the
6828 Ada Reference Manual, but without generation of any object code
6829 (no object file is generated).
6830
6831 Because dependent files must be accessed, you must follow the GNAT
6832 semantic restrictions on file structuring to operate in this mode:
6833
6834 @itemize @bullet
6835 @item
6836 The needed source files must be accessible
6837 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6838
6839 @item
6840 Each file must contain only one compilation unit.
6841
6842 @item
6843 The file name and unit name must match (@pxref{File Naming Rules}).
6844 @end itemize
6845
6846 The output consists of error messages as appropriate. No object file is
6847 generated. An @file{ALI} file is generated for use in the context of
6848 cross-reference tools, but this file is marked as not being suitable
6849 for binding (since no object file is generated).
6850 The checking corresponds exactly to the notion of
6851 legality in the Ada Reference Manual.
6852
6853 Any unit can be compiled in semantics-checking-only mode, including
6854 units that would not normally be compiled (subunits,
6855 and specifications where a separate body is present).
6856 @end table
6857
6858 @node Compiling Different Versions of Ada
6859 @subsection Compiling Different Versions of Ada
6860
6861 @noindent
6862 The switches described in this section allow you to explicitly specify
6863 the version of the Ada language that your programs are written in.
6864 By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION},
6865 but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or
6866 indicate Ada 83 compatibility mode.
6867
6868 @table @option
6869 @cindex Compatibility with Ada 83
6870
6871 @item -gnat83 (Ada 83 Compatibility Mode)
6872 @cindex @option{-gnat83} (@command{gcc})
6873 @cindex ACVC, Ada 83 tests
6874 @cindex Ada 83 mode
6875
6876 @noindent
6877 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6878 specifies that the program is to be compiled in Ada 83 mode. With
6879 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6880 semantics where this can be done easily.
6881 It is not possible to guarantee this switch does a perfect
6882 job; some subtle tests, such as are
6883 found in earlier ACVC tests (and that have been removed from the ACATS suite
6884 for Ada 95), might not compile correctly.
6885 Nevertheless, this switch may be useful in some circumstances, for example
6886 where, due to contractual reasons, existing code needs to be maintained
6887 using only Ada 83 features.
6888
6889 With few exceptions (most notably the need to use @code{<>} on
6890 @cindex Generic formal parameters
6891 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6892 reserved words, and the use of packages
6893 with optional bodies), it is not necessary to specify the
6894 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6895 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6896 a correct Ada 83 program is usually also a correct program
6897 in these later versions of the language standard.
6898 For further information, please refer to @ref{Compatibility and Porting Guide}.
6899
6900 @item -gnat95 (Ada 95 mode)
6901 @cindex @option{-gnat95} (@command{gcc})
6902 @cindex Ada 95 mode
6903
6904 @noindent
6905 This switch directs the compiler to implement the Ada 95 version of the
6906 language.
6907 Since Ada 95 is almost completely upwards
6908 compatible with Ada 83, Ada 83 programs may generally be compiled using
6909 this switch (see the description of the @option{-gnat83} switch for further
6910 information about Ada 83 mode).
6911 If an Ada 2005 program is compiled in Ada 95 mode,
6912 uses of the new Ada 2005 features will cause error
6913 messages or warnings.
6914
6915 This switch also can be used to cancel the effect of a previous
6916 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6917
6918 @item -gnat05 (Ada 2005 mode)
6919 @cindex @option{-gnat05} (@command{gcc})
6920 @cindex Ada 2005 mode
6921
6922 @noindent
6923 This switch directs the compiler to implement the Ada 2005 version of the
6924 language.
6925 Since Ada 2005 is almost completely upwards
6926 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6927 may generally be compiled using this switch (see the description of the
6928 @option{-gnat83} and @option{-gnat95} switches for further
6929 information).
6930
6931 For information about the approved ``Ada Issues'' that have been incorporated
6932 into Ada 2005, see @url{http://www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}.
6933 Included with GNAT releases is a file @file{features-ada0y} that describes
6934 the set of implemented Ada 2005 features.
6935 @end table
6936
6937
6938 @node Character Set Control
6939 @subsection Character Set Control
6940 @table @option
6941 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6942 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6943
6944 @noindent
6945 Normally GNAT recognizes the Latin-1 character set in source program
6946 identifiers, as described in the Ada Reference Manual.
6947 This switch causes
6948 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6949 single character ^^or word^ indicating the character set, as follows:
6950
6951 @table @code
6952 @item 1
6953 ISO 8859-1 (Latin-1) identifiers
6954
6955 @item 2
6956 ISO 8859-2 (Latin-2) letters allowed in identifiers
6957
6958 @item 3
6959 ISO 8859-3 (Latin-3) letters allowed in identifiers
6960
6961 @item 4
6962 ISO 8859-4 (Latin-4) letters allowed in identifiers
6963
6964 @item 5
6965 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6966
6967 @item 9
6968 ISO 8859-15 (Latin-9) letters allowed in identifiers
6969
6970 @item ^p^PC^
6971 IBM PC letters (code page 437) allowed in identifiers
6972
6973 @item ^8^PC850^
6974 IBM PC letters (code page 850) allowed in identifiers
6975
6976 @item ^f^FULL_UPPER^
6977 Full upper-half codes allowed in identifiers
6978
6979 @item ^n^NO_UPPER^
6980 No upper-half codes allowed in identifiers
6981
6982 @item ^w^WIDE^
6983 Wide-character codes (that is, codes greater than 255)
6984 allowed in identifiers
6985 @end table
6986
6987 @xref{Foreign Language Representation}, for full details on the
6988 implementation of these character sets.
6989
6990 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6991 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6992 Specify the method of encoding for wide characters.
6993 @var{e} is one of the following:
6994
6995 @table @code
6996
6997 @item ^h^HEX^
6998 Hex encoding (brackets coding also recognized)
6999
7000 @item ^u^UPPER^
7001 Upper half encoding (brackets encoding also recognized)
7002
7003 @item ^s^SHIFT_JIS^
7004 Shift/JIS encoding (brackets encoding also recognized)
7005
7006 @item ^e^EUC^
7007 EUC encoding (brackets encoding also recognized)
7008
7009 @item ^8^UTF8^
7010 UTF-8 encoding (brackets encoding also recognized)
7011
7012 @item ^b^BRACKETS^
7013 Brackets encoding only (default value)
7014 @end table
7015 For full details on these encoding
7016 methods see @ref{Wide Character Encodings}.
7017 Note that brackets coding is always accepted, even if one of the other
7018 options is specified, so for example @option{-gnatW8} specifies that both
7019 brackets and UTF-8 encodings will be recognized. The units that are
7020 with'ed directly or indirectly will be scanned using the specified
7021 representation scheme, and so if one of the non-brackets scheme is
7022 used, it must be used consistently throughout the program. However,
7023 since brackets encoding is always recognized, it may be conveniently
7024 used in standard libraries, allowing these libraries to be used with
7025 any of the available coding schemes.
7026 scheme.
7027
7028 If no @option{-gnatW?} parameter is present, then the default
7029 representation is normally Brackets encoding only. However, if the
7030 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7031 byte order mark or BOM for UTF-8), then these three characters are
7032 skipped and the default representation for the file is set to UTF-8.
7033
7034 Note that the wide character representation that is specified (explicitly
7035 or by default) for the main program also acts as the default encoding used
7036 for Wide_Text_IO files if not specifically overridden by a WCEM form
7037 parameter.
7038
7039 @end table
7040 @node File Naming Control
7041 @subsection File Naming Control
7042
7043 @table @option
7044 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7045 @cindex @option{-gnatk} (@command{gcc})
7046 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7047 1-999, indicates the maximum allowable length of a file name (not
7048 including the @file{.ads} or @file{.adb} extension). The default is not
7049 to enable file name krunching.
7050
7051 For the source file naming rules, @xref{File Naming Rules}.
7052 @end table
7053
7054 @node Subprogram Inlining Control
7055 @subsection Subprogram Inlining Control
7056
7057 @table @option
7058 @c !sort!
7059 @item -gnatn
7060 @cindex @option{-gnatn} (@command{gcc})
7061 @ifclear vms
7062 The @code{n} here is intended to suggest the first syllable of the
7063 word ``inline''.
7064 @end ifclear
7065 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7066 inlining to actually occur, optimization must be enabled. To enable
7067 inlining of subprograms specified by pragma @code{Inline},
7068 you must also specify this switch.
7069 In the absence of this switch, GNAT does not attempt
7070 inlining and does not need to access the bodies of
7071 subprograms for which @code{pragma Inline} is specified if they are not
7072 in the current unit.
7073
7074 If you specify this switch the compiler will access these bodies,
7075 creating an extra source dependency for the resulting object file, and
7076 where possible, the call will be inlined.
7077 For further details on when inlining is possible
7078 see @ref{Inlining of Subprograms}.
7079
7080 @item -gnatN
7081 @cindex @option{-gnatN} (@command{gcc})
7082 This switch activates front-end inlining which also
7083 generates additional dependencies.
7084
7085 When using a gcc-based back end (in practice this means using any version
7086 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7087 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7088 Historically front end inlining was more extensive than the gcc back end
7089 inlining, but that is no longer the case.
7090 @end table
7091
7092 @node Auxiliary Output Control
7093 @subsection Auxiliary Output Control
7094
7095 @table @option
7096 @item -gnatt
7097 @cindex @option{-gnatt} (@command{gcc})
7098 @cindex Writing internal trees
7099 @cindex Internal trees, writing to file
7100 Causes GNAT to write the internal tree for a unit to a file (with the
7101 extension @file{.adt}.
7102 This not normally required, but is used by separate analysis tools.
7103 Typically
7104 these tools do the necessary compilations automatically, so you should
7105 not have to specify this switch in normal operation.
7106 Note that the combination of switches @option{-gnatct}
7107 generates a tree in the form required by ASIS applications.
7108
7109 @item -gnatu
7110 @cindex @option{-gnatu} (@command{gcc})
7111 Print a list of units required by this compilation on @file{stdout}.
7112 The listing includes all units on which the unit being compiled depends
7113 either directly or indirectly.
7114
7115 @ifclear vms
7116 @item -pass-exit-codes
7117 @cindex @option{-pass-exit-codes} (@command{gcc})
7118 If this switch is not used, the exit code returned by @command{gcc} when
7119 compiling multiple files indicates whether all source files have
7120 been successfully used to generate object files or not.
7121
7122 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7123 exit status and allows an integrated development environment to better
7124 react to a compilation failure. Those exit status are:
7125
7126 @table @asis
7127 @item 5
7128 There was an error in at least one source file.
7129 @item 3
7130 At least one source file did not generate an object file.
7131 @item 2
7132 The compiler died unexpectedly (internal error for example).
7133 @item 0
7134 An object file has been generated for every source file.
7135 @end table
7136 @end ifclear
7137 @end table
7138
7139 @node Debugging Control
7140 @subsection Debugging Control
7141
7142 @table @option
7143 @c !sort!
7144 @cindex Debugging options
7145 @ifclear vms
7146 @item -gnatd@var{x}
7147 @cindex @option{-gnatd} (@command{gcc})
7148 Activate internal debugging switches. @var{x} is a letter or digit, or
7149 string of letters or digits, which specifies the type of debugging
7150 outputs desired. Normally these are used only for internal development
7151 or system debugging purposes. You can find full documentation for these
7152 switches in the body of the @code{Debug} unit in the compiler source
7153 file @file{debug.adb}.
7154 @end ifclear
7155
7156 @item -gnatG[=nn]
7157 @cindex @option{-gnatG} (@command{gcc})
7158 This switch causes the compiler to generate auxiliary output containing
7159 a pseudo-source listing of the generated expanded code. Like most Ada
7160 compilers, GNAT works by first transforming the high level Ada code into
7161 lower level constructs. For example, tasking operations are transformed
7162 into calls to the tasking run-time routines. A unique capability of GNAT
7163 is to list this expanded code in a form very close to normal Ada source.
7164 This is very useful in understanding the implications of various Ada
7165 usage on the efficiency of the generated code. There are many cases in
7166 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7167 generate a lot of run-time code. By using @option{-gnatG} you can identify
7168 these cases, and consider whether it may be desirable to modify the coding
7169 approach to improve efficiency.
7170
7171 The optional parameter @code{nn} if present after -gnatG specifies an
7172 alternative maximum line length that overrides the normal default of 72.
7173 This value is in the range 40-999999, values less than 40 being silently
7174 reset to 40. The equal sign is optional.
7175
7176 The format of the output is very similar to standard Ada source, and is
7177 easily understood by an Ada programmer. The following special syntactic
7178 additions correspond to low level features used in the generated code that
7179 do not have any exact analogies in pure Ada source form. The following
7180 is a partial list of these special constructions. See the spec
7181 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7182
7183 If the switch @option{-gnatL} is used in conjunction with
7184 @cindex @option{-gnatL} (@command{gcc})
7185 @option{-gnatG}, then the original source lines are interspersed
7186 in the expanded source (as comment lines with the original line number).
7187
7188 @table @code
7189 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7190 Shows the storage pool being used for an allocator.
7191
7192 @item at end @var{procedure-name};
7193 Shows the finalization (cleanup) procedure for a scope.
7194
7195 @item (if @var{expr} then @var{expr} else @var{expr})
7196 Conditional expression equivalent to the @code{x?y:z} construction in C.
7197
7198 @item @var{target}^^^(@var{source})
7199 A conversion with floating-point truncation instead of rounding.
7200
7201 @item @var{target}?(@var{source})
7202 A conversion that bypasses normal Ada semantic checking. In particular
7203 enumeration types and fixed-point types are treated simply as integers.
7204
7205 @item @var{target}?^^^(@var{source})
7206 Combines the above two cases.
7207
7208 @item @var{x} #/ @var{y}
7209 @itemx @var{x} #mod @var{y}
7210 @itemx @var{x} #* @var{y}
7211 @itemx @var{x} #rem @var{y}
7212 A division or multiplication of fixed-point values which are treated as
7213 integers without any kind of scaling.
7214
7215 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7216 Shows the storage pool associated with a @code{free} statement.
7217
7218 @item [subtype or type declaration]
7219 Used to list an equivalent declaration for an internally generated
7220 type that is referenced elsewhere in the listing.
7221
7222 @c @item freeze @var{type-name} @ovar{actions}
7223 @c Expanding @ovar macro inline (explanation in macro def comments)
7224 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7225 Shows the point at which @var{type-name} is frozen, with possible
7226 associated actions to be performed at the freeze point.
7227
7228 @item reference @var{itype}
7229 Reference (and hence definition) to internal type @var{itype}.
7230
7231 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7232 Intrinsic function call.
7233
7234 @item @var{label-name} : label
7235 Declaration of label @var{labelname}.
7236
7237 @item #$ @var{subprogram-name}
7238 An implicit call to a run-time support routine
7239 (to meet the requirement of H.3.1(9) in a
7240 convenient manner).
7241
7242 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7243 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7244 @var{expr}, but handled more efficiently).
7245
7246 @item [constraint_error]
7247 Raise the @code{Constraint_Error} exception.
7248
7249 @item @var{expression}'reference
7250 A pointer to the result of evaluating @var{expression}.
7251
7252 @item @var{target-type}!(@var{source-expression})
7253 An unchecked conversion of @var{source-expression} to @var{target-type}.
7254
7255 @item [@var{numerator}/@var{denominator}]
7256 Used to represent internal real literals (that) have no exact
7257 representation in base 2-16 (for example, the result of compile time
7258 evaluation of the expression 1.0/27.0).
7259 @end table
7260
7261 @item -gnatD[=nn]
7262 @cindex @option{-gnatD} (@command{gcc})
7263 When used in conjunction with @option{-gnatG}, this switch causes
7264 the expanded source, as described above for
7265 @option{-gnatG} to be written to files with names
7266 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7267 instead of to the standard output file. For
7268 example, if the source file name is @file{hello.adb}, then a file
7269 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7270 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7271 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7272 you to do source level debugging using the generated code which is
7273 sometimes useful for complex code, for example to find out exactly
7274 which part of a complex construction raised an exception. This switch
7275 also suppress generation of cross-reference information (see
7276 @option{-gnatx}) since otherwise the cross-reference information
7277 would refer to the @file{^.dg^.DG^} file, which would cause
7278 confusion since this is not the original source file.
7279
7280 Note that @option{-gnatD} actually implies @option{-gnatG}
7281 automatically, so it is not necessary to give both options.
7282 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7283
7284 If the switch @option{-gnatL} is used in conjunction with
7285 @cindex @option{-gnatL} (@command{gcc})
7286 @option{-gnatDG}, then the original source lines are interspersed
7287 in the expanded source (as comment lines with the original line number).
7288
7289 The optional parameter @code{nn} if present after -gnatD specifies an
7290 alternative maximum line length that overrides the normal default of 72.
7291 This value is in the range 40-999999, values less than 40 being silently
7292 reset to 40. The equal sign is optional.
7293
7294 @item -gnatr
7295 @cindex @option{-gnatr} (@command{gcc})
7296 @cindex pragma Restrictions
7297 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7298 so that violation of restrictions causes warnings rather than illegalities.
7299 This is useful during the development process when new restrictions are added
7300 or investigated. The switch also causes pragma Profile to be treated as
7301 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7302 restriction warnings rather than restrictions.
7303
7304 @ifclear vms
7305 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7306 @cindex @option{-gnatR} (@command{gcc})
7307 This switch controls output from the compiler of a listing showing
7308 representation information for declared types and objects. For
7309 @option{-gnatR0}, no information is output (equivalent to omitting
7310 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7311 so @option{-gnatR} with no parameter has the same effect), size and alignment
7312 information is listed for declared array and record types. For
7313 @option{-gnatR2}, size and alignment information is listed for all
7314 declared types and objects. Finally @option{-gnatR3} includes symbolic
7315 expressions for values that are computed at run time for
7316 variant records. These symbolic expressions have a mostly obvious
7317 format with #n being used to represent the value of the n'th
7318 discriminant. See source files @file{repinfo.ads/adb} in the
7319 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7320 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7321 the output is to a file with the name @file{^file.rep^file_REP^} where
7322 file is the name of the corresponding source file.
7323 @end ifclear
7324 @ifset vms
7325 @item /REPRESENTATION_INFO
7326 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7327 This qualifier controls output from the compiler of a listing showing
7328 representation information for declared types and objects. For
7329 @option{/REPRESENTATION_INFO=NONE}, no information is output
7330 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7331 @option{/REPRESENTATION_INFO} without option is equivalent to
7332 @option{/REPRESENTATION_INFO=ARRAYS}.
7333 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7334 information is listed for declared array and record types. For
7335 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7336 is listed for all expression information for values that are computed
7337 at run time for variant records. These symbolic expressions have a mostly
7338 obvious format with #n being used to represent the value of the n'th
7339 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7340 @code{GNAT} sources for full details on the format of
7341 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7342 If _FILE is added at the end of an option
7343 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7344 then the output is to a file with the name @file{file_REP} where
7345 file is the name of the corresponding source file.
7346 @end ifset
7347 Note that it is possible for record components to have zero size. In
7348 this case, the component clause uses an obvious extension of permitted
7349 Ada syntax, for example @code{at 0 range 0 .. -1}.
7350
7351 Representation information requires that code be generated (since it is the
7352 code generator that lays out complex data structures). If an attempt is made
7353 to output representation information when no code is generated, for example
7354 when a subunit is compiled on its own, then no information can be generated
7355 and the compiler outputs a message to this effect.
7356
7357 @item -gnatS
7358 @cindex @option{-gnatS} (@command{gcc})
7359 The use of the switch @option{-gnatS} for an
7360 Ada compilation will cause the compiler to output a
7361 representation of package Standard in a form very
7362 close to standard Ada. It is not quite possible to
7363 do this entirely in standard Ada (since new
7364 numeric base types cannot be created in standard
7365 Ada), but the output is easily
7366 readable to any Ada programmer, and is useful to
7367 determine the characteristics of target dependent
7368 types in package Standard.
7369
7370 @item -gnatx
7371 @cindex @option{-gnatx} (@command{gcc})
7372 Normally the compiler generates full cross-referencing information in
7373 the @file{ALI} file. This information is used by a number of tools,
7374 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7375 suppresses this information. This saves some space and may slightly
7376 speed up compilation, but means that these tools cannot be used.
7377 @end table
7378
7379 @node Exception Handling Control
7380 @subsection Exception Handling Control
7381
7382 @noindent
7383 GNAT uses two methods for handling exceptions at run-time. The
7384 @code{setjmp/longjmp} method saves the context when entering
7385 a frame with an exception handler. Then when an exception is
7386 raised, the context can be restored immediately, without the
7387 need for tracing stack frames. This method provides very fast
7388 exception propagation, but introduces significant overhead for
7389 the use of exception handlers, even if no exception is raised.
7390
7391 The other approach is called ``zero cost'' exception handling.
7392 With this method, the compiler builds static tables to describe
7393 the exception ranges. No dynamic code is required when entering
7394 a frame containing an exception handler. When an exception is
7395 raised, the tables are used to control a back trace of the
7396 subprogram invocation stack to locate the required exception
7397 handler. This method has considerably poorer performance for
7398 the propagation of exceptions, but there is no overhead for
7399 exception handlers if no exception is raised. Note that in this
7400 mode and in the context of mixed Ada and C/C++ programming,
7401 to propagate an exception through a C/C++ code, the C/C++ code
7402 must be compiled with the @option{-funwind-tables} GCC's
7403 option.
7404
7405 The following switches may be used to control which of the
7406 two exception handling methods is used.
7407
7408 @table @option
7409 @c !sort!
7410
7411 @item --RTS=sjlj
7412 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7413 This switch causes the setjmp/longjmp run-time (when available) to be used
7414 for exception handling. If the default
7415 mechanism for the target is zero cost exceptions, then
7416 this switch can be used to modify this default, and must be
7417 used for all units in the partition.
7418 This option is rarely used. One case in which it may be
7419 advantageous is if you have an application where exception
7420 raising is common and the overall performance of the
7421 application is improved by favoring exception propagation.
7422
7423 @item --RTS=zcx
7424 @cindex @option{--RTS=zcx} (@command{gnatmake})
7425 @cindex Zero Cost Exceptions
7426 This switch causes the zero cost approach to be used
7427 for exception handling. If this is the default mechanism for the
7428 target (see below), then this switch is unneeded. If the default
7429 mechanism for the target is setjmp/longjmp exceptions, then
7430 this switch can be used to modify this default, and must be
7431 used for all units in the partition.
7432 This option can only be used if the zero cost approach
7433 is available for the target in use, otherwise it will generate an error.
7434 @end table
7435
7436 @noindent
7437 The same option @option{--RTS} must be used both for @command{gcc}
7438 and @command{gnatbind}. Passing this option to @command{gnatmake}
7439 (@pxref{Switches for gnatmake}) will ensure the required consistency
7440 through the compilation and binding steps.
7441
7442 @node Units to Sources Mapping Files
7443 @subsection Units to Sources Mapping Files
7444
7445 @table @option
7446
7447 @item -gnatem=@var{path}
7448 @cindex @option{-gnatem} (@command{gcc})
7449 A mapping file is a way to communicate to the compiler two mappings:
7450 from unit names to file names (without any directory information) and from
7451 file names to path names (with full directory information). These mappings
7452 are used by the compiler to short-circuit the path search.
7453
7454 The use of mapping files is not required for correct operation of the
7455 compiler, but mapping files can improve efficiency, particularly when
7456 sources are read over a slow network connection. In normal operation,
7457 you need not be concerned with the format or use of mapping files,
7458 and the @option{-gnatem} switch is not a switch that you would use
7459 explicitly. It is intended primarily for use by automatic tools such as
7460 @command{gnatmake} running under the project file facility. The
7461 description here of the format of mapping files is provided
7462 for completeness and for possible use by other tools.
7463
7464 A mapping file is a sequence of sets of three lines. In each set, the
7465 first line is the unit name, in lower case, with @code{%s} appended
7466 for specs and @code{%b} appended for bodies; the second line is the
7467 file name; and the third line is the path name.
7468
7469 Example:
7470 @smallexample
7471    main%b
7472    main.2.ada
7473    /gnat/project1/sources/main.2.ada
7474 @end smallexample
7475
7476 When the switch @option{-gnatem} is specified, the compiler will
7477 create in memory the two mappings from the specified file. If there is
7478 any problem (nonexistent file, truncated file or duplicate entries),
7479 no mapping will be created.
7480
7481 Several @option{-gnatem} switches may be specified; however, only the
7482 last one on the command line will be taken into account.
7483
7484 When using a project file, @command{gnatmake} creates a temporary
7485 mapping file and communicates it to the compiler using this switch.
7486
7487 @end table
7488
7489 @node Integrated Preprocessing
7490 @subsection Integrated Preprocessing
7491
7492 @noindent
7493 GNAT sources may be preprocessed immediately before compilation.
7494 In this case, the actual
7495 text of the source is not the text of the source file, but is derived from it
7496 through a process called preprocessing. Integrated preprocessing is specified
7497 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7498 indicates, through a text file, the preprocessing data to be used.
7499 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7500
7501 @noindent
7502 Note that when integrated preprocessing is used, the output from the
7503 preprocessor is not written to any external file. Instead it is passed
7504 internally to the compiler. If you need to preserve the result of
7505 preprocessing in a file, then you should use @command{gnatprep}
7506 to perform the desired preprocessing in stand-alone mode.
7507
7508 @noindent
7509 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7510 used when Integrated Preprocessing is used. The reason is that preprocessing
7511 with another Preprocessing Data file without changing the sources will
7512 not trigger recompilation without this switch.
7513
7514 @noindent
7515 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7516 always trigger recompilation for sources that are preprocessed,
7517 because @command{gnatmake} cannot compute the checksum of the source after
7518 preprocessing.
7519
7520 @noindent
7521 The actual preprocessing function is described in details in section
7522 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
7523 preprocessing is triggered and parameterized.
7524
7525 @table @code
7526
7527 @item -gnatep=@var{file}
7528 @cindex @option{-gnatep} (@command{gcc})
7529 This switch indicates to the compiler the file name (without directory
7530 information) of the preprocessor data file to use. The preprocessor data file
7531 should be found in the source directories.
7532
7533 @noindent
7534 A preprocessing data file is a text file with significant lines indicating
7535 how should be preprocessed either a specific source or all sources not
7536 mentioned in other lines. A significant line is a nonempty, non-comment line.
7537 Comments are similar to Ada comments.
7538
7539 @noindent
7540 Each significant line starts with either a literal string or the character '*'.
7541 A literal string is the file name (without directory information) of the source
7542 to preprocess. A character '*' indicates the preprocessing for all the sources
7543 that are not specified explicitly on other lines (order of the lines is not
7544 significant). It is an error to have two lines with the same file name or two
7545 lines starting with the character '*'.
7546
7547 @noindent
7548 After the file name or the character '*', another optional literal string
7549 indicating the file name of the definition file to be used for preprocessing
7550 (@pxref{Form of Definitions File}). The definition files are found by the
7551 compiler in one of the source directories. In some cases, when compiling
7552 a source in a directory other than the current directory, if the definition
7553 file is in the current directory, it may be necessary to add the current
7554 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7555 the compiler would not find the definition file.
7556
7557 @noindent
7558 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7559 be found. Those ^switches^switches^ are:
7560
7561 @table @code
7562
7563 @item -b
7564 Causes both preprocessor lines and the lines deleted by
7565 preprocessing to be replaced by blank lines, preserving the line number.
7566 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7567 it cancels the effect of @option{-c}.
7568
7569 @item -c
7570 Causes both preprocessor lines and the lines deleted
7571 by preprocessing to be retained as comments marked
7572 with the special string ``@code{--! }''.
7573
7574 @item -Dsymbol=value
7575 Define or redefine a symbol, associated with value. A symbol is an Ada
7576 identifier, or an Ada reserved word, with the exception of @code{if},
7577 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7578 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7579 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7580 same name defined in a definition file.
7581
7582 @item -s
7583 Causes a sorted list of symbol names and values to be
7584 listed on the standard output file.
7585
7586 @item -u
7587 Causes undefined symbols to be treated as having the value @code{FALSE}
7588 in the context
7589 of a preprocessor test. In the absence of this option, an undefined symbol in
7590 a @code{#if} or @code{#elsif} test will be treated as an error.
7591
7592 @end table
7593
7594 @noindent
7595 Examples of valid lines in a preprocessor data file:
7596
7597 @smallexample
7598   "toto.adb"  "prep.def" -u
7599   --  preprocess "toto.adb", using definition file "prep.def",
7600   --  undefined symbol are False.
7601
7602   * -c -DVERSION=V101
7603   --  preprocess all other sources without a definition file;
7604   --  suppressed lined are commented; symbol VERSION has the value V101.
7605
7606   "titi.adb" "prep2.def" -s
7607   --  preprocess "titi.adb", using definition file "prep2.def";
7608   --  list all symbols with their values.
7609 @end smallexample
7610
7611 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7612 @cindex @option{-gnateD} (@command{gcc})
7613 Define or redefine a preprocessing symbol, associated with value. If no value
7614 is given on the command line, then the value of the symbol is @code{True}.
7615 A symbol is an identifier, following normal Ada (case-insensitive)
7616 rules for its syntax, and value is any sequence (including an empty sequence)
7617 of characters from the set (letters, digits, period, underline).
7618 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7619 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7620
7621 @noindent
7622 A symbol declared with this ^switch^switch^ on the command line replaces a
7623 symbol with the same name either in a definition file or specified with a
7624 ^switch^switch^ -D in the preprocessor data file.
7625
7626 @noindent
7627 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7628
7629 @item -gnateG
7630 When integrated preprocessing is performed and the preprocessor modifies
7631 the source text, write the result of this preprocessing into a file
7632 <source>^.prep^_prep^.
7633
7634 @end table
7635
7636 @node Code Generation Control
7637 @subsection Code Generation Control
7638
7639 @noindent
7640
7641 The GCC technology provides a wide range of target dependent
7642 @option{-m} switches for controlling
7643 details of code generation with respect to different versions of
7644 architectures. This includes variations in instruction sets (e.g.@:
7645 different members of the power pc family), and different requirements
7646 for optimal arrangement of instructions (e.g.@: different members of
7647 the x86 family). The list of available @option{-m} switches may be
7648 found in the GCC documentation.
7649
7650 Use of these @option{-m} switches may in some cases result in improved
7651 code performance.
7652
7653 The GNAT Pro technology is tested and qualified without any
7654 @option{-m} switches,
7655 so generally the most reliable approach is to avoid the use of these
7656 switches. However, we generally expect most of these switches to work
7657 successfully with GNAT Pro, and many customers have reported successful
7658 use of these options.
7659
7660 Our general advice is to avoid the use of @option{-m} switches unless
7661 special needs lead to requirements in this area. In particular,
7662 there is no point in using @option{-m} switches to improve performance
7663 unless you actually see a performance improvement.
7664
7665 @ifset vms
7666 @node Return Codes
7667 @subsection Return Codes
7668 @cindex Return Codes
7669 @cindex @option{/RETURN_CODES=VMS}
7670
7671 @noindent
7672 On VMS, GNAT compiled programs return POSIX-style codes by default,
7673 e.g.@: @option{/RETURN_CODES=POSIX}.
7674
7675 To enable VMS style return codes, use GNAT BIND and LINK with the option
7676 @option{/RETURN_CODES=VMS}. For example:
7677
7678 @smallexample
7679 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7680 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7681 @end smallexample
7682
7683 @noindent
7684 Programs built with /RETURN_CODES=VMS are suitable to be called in
7685 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7686 are suitable for spawning with appropriate GNAT RTL routines.
7687
7688 @end ifset
7689
7690 @node Search Paths and the Run-Time Library (RTL)
7691 @section Search Paths and the Run-Time Library (RTL)
7692
7693 @noindent
7694 With the GNAT source-based library system, the compiler must be able to
7695 find source files for units that are needed by the unit being compiled.
7696 Search paths are used to guide this process.
7697
7698 The compiler compiles one source file whose name must be given
7699 explicitly on the command line. In other words, no searching is done
7700 for this file. To find all other source files that are needed (the most
7701 common being the specs of units), the compiler examines the following
7702 directories, in the following order:
7703
7704 @enumerate
7705 @item
7706 The directory containing the source file of the main unit being compiled
7707 (the file name on the command line).
7708
7709 @item
7710 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7711 @command{gcc} command line, in the order given.
7712
7713 @item
7714 @findex ADA_PRJ_INCLUDE_FILE
7715 Each of the directories listed in the text file whose name is given
7716 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7717
7718 @noindent
7719 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7720 driver when project files are used. It should not normally be set
7721 by other means.
7722
7723 @item
7724 @findex ADA_INCLUDE_PATH
7725 Each of the directories listed in the value of the
7726 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7727 @ifclear vms
7728 Construct this value
7729 exactly as the @env{PATH} environment variable: a list of directory
7730 names separated by colons (semicolons when working with the NT version).
7731 @end ifclear
7732 @ifset vms
7733 Normally, define this value as a logical name containing a comma separated
7734 list of directory names.
7735
7736 This variable can also be defined by means of an environment string
7737 (an argument to the HP C exec* set of functions).
7738
7739 Logical Name:
7740 @smallexample
7741 DEFINE ANOTHER_PATH FOO:[BAG]
7742 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7743 @end smallexample
7744
7745 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7746 first, followed by the standard Ada
7747 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7748 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7749 (Text_IO, Sequential_IO, etc)
7750 instead of the standard Ada packages. Thus, in order to get the standard Ada
7751 packages by default, ADA_INCLUDE_PATH must be redefined.
7752 @end ifset
7753
7754 @item
7755 The content of the @file{ada_source_path} file which is part of the GNAT
7756 installation tree and is used to store standard libraries such as the
7757 GNAT Run Time Library (RTL) source files.
7758 @ifclear vms
7759 @ref{Installing a library}
7760 @end ifclear
7761 @end enumerate
7762
7763 @noindent
7764 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7765 inhibits the use of the directory
7766 containing the source file named in the command line. You can still
7767 have this directory on your search path, but in this case it must be
7768 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7769
7770 Specifying the switch @option{-nostdinc}
7771 inhibits the search of the default location for the GNAT Run Time
7772 Library (RTL) source files.
7773
7774 The compiler outputs its object files and ALI files in the current
7775 working directory.
7776 @ifclear vms
7777 Caution: The object file can be redirected with the @option{-o} switch;
7778 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7779 so the @file{ALI} file will not go to the right place. Therefore, you should
7780 avoid using the @option{-o} switch.
7781 @end ifclear
7782
7783 @findex System.IO
7784 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7785 children make up the GNAT RTL, together with the simple @code{System.IO}
7786 package used in the @code{"Hello World"} example. The sources for these units
7787 are needed by the compiler and are kept together in one directory. Not
7788 all of the bodies are needed, but all of the sources are kept together
7789 anyway. In a normal installation, you need not specify these directory
7790 names when compiling or binding. Either the environment variables or
7791 the built-in defaults cause these files to be found.
7792
7793 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7794 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7795 consisting of child units of @code{GNAT}. This is a collection of generally
7796 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7797 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7798
7799 Besides simplifying access to the RTL, a major use of search paths is
7800 in compiling sources from multiple directories. This can make
7801 development environments much more flexible.
7802
7803 @node Order of Compilation Issues
7804 @section Order of Compilation Issues
7805
7806 @noindent
7807 If, in our earlier example, there was a spec for the @code{hello}
7808 procedure, it would be contained in the file @file{hello.ads}; yet this
7809 file would not have to be explicitly compiled. This is the result of the
7810 model we chose to implement library management. Some of the consequences
7811 of this model are as follows:
7812
7813 @itemize @bullet
7814 @item
7815 There is no point in compiling specs (except for package
7816 specs with no bodies) because these are compiled as needed by clients. If
7817 you attempt a useless compilation, you will receive an error message.
7818 It is also useless to compile subunits because they are compiled as needed
7819 by the parent.
7820
7821 @item
7822 There are no order of compilation requirements: performing a
7823 compilation never obsoletes anything. The only way you can obsolete
7824 something and require recompilations is to modify one of the
7825 source files on which it depends.
7826
7827 @item
7828 There is no library as such, apart from the ALI files
7829 (@pxref{The Ada Library Information Files}, for information on the format
7830 of these files). For now we find it convenient to create separate ALI files,
7831 but eventually the information therein may be incorporated into the object
7832 file directly.
7833
7834 @item
7835 When you compile a unit, the source files for the specs of all units
7836 that it @code{with}'s, all its subunits, and the bodies of any generics it
7837 instantiates must be available (reachable by the search-paths mechanism
7838 described above), or you will receive a fatal error message.
7839 @end itemize
7840
7841 @node Examples
7842 @section Examples
7843
7844 @noindent
7845 The following are some typical Ada compilation command line examples:
7846
7847 @table @code
7848 @item $ gcc -c xyz.adb
7849 Compile body in file @file{xyz.adb} with all default options.
7850
7851 @ifclear vms
7852 @item $ gcc -c -O2 -gnata xyz-def.adb
7853 @end ifclear
7854 @ifset vms
7855 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7856 @end ifset
7857
7858 Compile the child unit package in file @file{xyz-def.adb} with extensive
7859 optimizations, and pragma @code{Assert}/@code{Debug} statements
7860 enabled.
7861
7862 @item $ gcc -c -gnatc abc-def.adb
7863 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7864 mode.
7865 @end table
7866
7867 @node Binding Using gnatbind
7868 @chapter Binding Using @code{gnatbind}
7869 @findex gnatbind
7870
7871 @menu
7872 * Running gnatbind::
7873 * Switches for gnatbind::
7874 * Command-Line Access::
7875 * Search Paths for gnatbind::
7876 * Examples of gnatbind Usage::
7877 @end menu
7878
7879 @noindent
7880 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7881 to bind compiled GNAT objects.
7882
7883 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7884 driver (see @ref{The GNAT Driver and Project Files}).
7885
7886 The @code{gnatbind} program performs four separate functions:
7887
7888 @enumerate
7889 @item
7890 Checks that a program is consistent, in accordance with the rules in
7891 Chapter 10 of the Ada Reference Manual. In particular, error
7892 messages are generated if a program uses inconsistent versions of a
7893 given unit.
7894
7895 @item
7896 Checks that an acceptable order of elaboration exists for the program
7897 and issues an error message if it cannot find an order of elaboration
7898 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7899
7900 @item
7901 Generates a main program incorporating the given elaboration order.
7902 This program is a small Ada package (body and spec) that
7903 must be subsequently compiled
7904 using the GNAT compiler. The necessary compilation step is usually
7905 performed automatically by @command{gnatlink}. The two most important
7906 functions of this program
7907 are to call the elaboration routines of units in an appropriate order
7908 and to call the main program.
7909
7910 @item
7911 Determines the set of object files required by the given main program.
7912 This information is output in the forms of comments in the generated program,
7913 to be read by the @command{gnatlink} utility used to link the Ada application.
7914 @end enumerate
7915
7916 @node Running gnatbind
7917 @section Running @code{gnatbind}
7918
7919 @noindent
7920 The form of the @code{gnatbind} command is
7921
7922 @smallexample
7923 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7924 @c Expanding @ovar macro inline (explanation in macro def comments)
7925 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
7926 @end smallexample
7927
7928 @noindent
7929 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7930 unit body. @code{gnatbind} constructs an Ada
7931 package in two files whose names are
7932 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7933 For example, if given the
7934 parameter @file{hello.ali}, for a main program contained in file
7935 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7936 and @file{b~hello.adb}.
7937
7938 When doing consistency checking, the binder takes into consideration
7939 any source files it can locate. For example, if the binder determines
7940 that the given main program requires the package @code{Pack}, whose
7941 @file{.ALI}
7942 file is @file{pack.ali} and whose corresponding source spec file is
7943 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7944 (using the same search path conventions as previously described for the
7945 @command{gcc} command). If it can locate this source file, it checks that
7946 the time stamps
7947 or source checksums of the source and its references to in @file{ALI} files
7948 match. In other words, any @file{ALI} files that mentions this spec must have
7949 resulted from compiling this version of the source file (or in the case
7950 where the source checksums match, a version close enough that the
7951 difference does not matter).
7952
7953 @cindex Source files, use by binder
7954 The effect of this consistency checking, which includes source files, is
7955 that the binder ensures that the program is consistent with the latest
7956 version of the source files that can be located at bind time. Editing a
7957 source file without compiling files that depend on the source file cause
7958 error messages to be generated by the binder.
7959
7960 For example, suppose you have a main program @file{hello.adb} and a
7961 package @code{P}, from file @file{p.ads} and you perform the following
7962 steps:
7963
7964 @enumerate
7965 @item
7966 Enter @code{gcc -c hello.adb} to compile the main program.
7967
7968 @item
7969 Enter @code{gcc -c p.ads} to compile package @code{P}.
7970
7971 @item
7972 Edit file @file{p.ads}.
7973
7974 @item
7975 Enter @code{gnatbind hello}.
7976 @end enumerate
7977
7978 @noindent
7979 At this point, the file @file{p.ali} contains an out-of-date time stamp
7980 because the file @file{p.ads} has been edited. The attempt at binding
7981 fails, and the binder generates the following error messages:
7982
7983 @smallexample
7984 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7985 error: "p.ads" has been modified and must be recompiled
7986 @end smallexample
7987
7988 @noindent
7989 Now both files must be recompiled as indicated, and then the bind can
7990 succeed, generating a main program. You need not normally be concerned
7991 with the contents of this file, but for reference purposes a sample
7992 binder output file is given in @ref{Example of Binder Output File}.
7993
7994 In most normal usage, the default mode of @command{gnatbind} which is to
7995 generate the main package in Ada, as described in the previous section.
7996 In particular, this means that any Ada programmer can read and understand
7997 the generated main program. It can also be debugged just like any other
7998 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7999 @command{gnatbind} and @command{gnatlink}.
8000
8001 @node Switches for gnatbind
8002 @section Switches for @command{gnatbind}
8003
8004 @noindent
8005 The following switches are available with @code{gnatbind}; details will
8006 be presented in subsequent sections.
8007
8008 @menu
8009 * Consistency-Checking Modes::
8010 * Binder Error Message Control::
8011 * Elaboration Control::
8012 * Output Control::
8013 * Binding with Non-Ada Main Programs::
8014 * Binding Programs with No Main Subprogram::
8015 @end menu
8016
8017 @table @option
8018 @c !sort!
8019
8020 @item --version
8021 @cindex @option{--version} @command{gnatbind}
8022 Display Copyright and version, then exit disregarding all other options.
8023
8024 @item --help
8025 @cindex @option{--help} @command{gnatbind}
8026 If @option{--version} was not used, display usage, then exit disregarding
8027 all other options.
8028
8029 @item -a
8030 @cindex @option{-a} @command{gnatbind}
8031 Indicates that, if supported by the platform, the adainit procedure should
8032 be treated as an initialisation routine by the linker (a constructor). This
8033 is intended to be used by the Project Manager to automatically initialize
8034 shared Stand-Alone Libraries.
8035
8036 @item ^-aO^/OBJECT_SEARCH^
8037 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8038 Specify directory to be searched for ALI files.
8039
8040 @item ^-aI^/SOURCE_SEARCH^
8041 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8042 Specify directory to be searched for source file.
8043
8044 @item ^-b^/REPORT_ERRORS=BRIEF^
8045 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8046 Generate brief messages to @file{stderr} even if verbose mode set.
8047
8048 @item ^-c^/NOOUTPUT^
8049 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8050 Check only, no generation of binder output file.
8051
8052 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8053 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8054 This switch can be used to change the default task stack size value
8055 to a specified size @var{nn}, which is expressed in bytes by default, or
8056 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8057 with @var{m}.
8058 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8059 in effect, to completing all task specs with
8060 @smallexample @c ada
8061    pragma Storage_Size (nn);
8062 @end smallexample
8063 When they do not already have such a pragma.
8064
8065 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8066 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8067 This switch can be used to change the default secondary stack size value
8068 to a specified size @var{nn}, which is expressed in bytes by default, or
8069 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8070 with @var{m}.
8071
8072 The secondary stack is used to deal with functions that return a variable
8073 sized result, for example a function returning an unconstrained
8074 String. There are two ways in which this secondary stack is allocated.
8075
8076 For most targets, the secondary stack is growing on demand and is allocated
8077 as a chain of blocks in the heap. The -D option is not very
8078 relevant. It only give some control over the size of the allocated
8079 blocks (whose size is the minimum of the default secondary stack size value,
8080 and the actual size needed for the current allocation request).
8081
8082 For certain targets, notably VxWorks 653,
8083 the secondary stack is allocated by carving off a fixed ratio chunk of the
8084 primary task stack. The -D option is used to define the
8085 size of the environment task's secondary stack.
8086
8087 @item ^-e^/ELABORATION_DEPENDENCIES^
8088 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8089 Output complete list of elaboration-order dependencies.
8090
8091 @item ^-E^/STORE_TRACEBACKS^
8092 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8093 Store tracebacks in exception occurrences when the target supports it.
8094 This is the default with the zero cost exception mechanism.
8095 @ignore
8096 @c The following may get moved to an appendix
8097 This option is currently supported on the following targets:
8098 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8099 @end ignore
8100 See also the packages @code{GNAT.Traceback} and
8101 @code{GNAT.Traceback.Symbolic} for more information.
8102 @ifclear vms
8103 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8104 @command{gcc} option.
8105 @end ifclear
8106
8107 @item ^-F^/FORCE_ELABS_FLAGS^
8108 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8109 Force the checks of elaboration flags. @command{gnatbind} does not normally
8110 generate checks of elaboration flags for the main executable, except when
8111 a Stand-Alone Library is used. However, there are cases when this cannot be
8112 detected by gnatbind. An example is importing an interface of a Stand-Alone
8113 Library through a pragma Import and only specifying through a linker switch
8114 this Stand-Alone Library. This switch is used to guarantee that elaboration
8115 flag checks are generated.
8116
8117 @item ^-h^/HELP^
8118 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8119 Output usage (help) information
8120
8121 @item ^-I^/SEARCH^
8122 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8123 Specify directory to be searched for source and ALI files.
8124
8125 @item ^-I-^/NOCURRENT_DIRECTORY^
8126 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8127 Do not look for sources in the current directory where @code{gnatbind} was
8128 invoked, and do not look for ALI files in the directory containing the
8129 ALI file named in the @code{gnatbind} command line.
8130
8131 @item ^-l^/ORDER_OF_ELABORATION^
8132 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8133 Output chosen elaboration order.
8134
8135 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8136 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8137 Bind the units for library building. In this case the adainit and
8138 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8139 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8140 ^@var{xxx}final^@var{XXX}FINAL^.
8141 Implies ^-n^/NOCOMPILE^.
8142 @ifclear vms
8143 (@xref{GNAT and Libraries}, for more details.)
8144 @end ifclear
8145 @ifset vms
8146 On OpenVMS, these init and final procedures are exported in uppercase
8147 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8148 the init procedure will be "TOTOINIT" and the exported name of the final
8149 procedure will be "TOTOFINAL".
8150 @end ifset
8151
8152 @item ^-Mxyz^/RENAME_MAIN=xyz^
8153 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8154 Rename generated main program from main to xyz. This option is
8155 supported on cross environments only.
8156
8157 @item ^-m^/ERROR_LIMIT=^@var{n}
8158 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8159 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8160 in the range 1..999999. The default value if no switch is
8161 given is 9999. If the number of warnings reaches this limit, then a
8162 message is output and further warnings are suppressed, the bind
8163 continues in this case. If the number of errors reaches this
8164 limit, then a message is output and the bind is abandoned.
8165 A value of zero means that no limit is enforced. The equal
8166 sign is optional.
8167
8168 @ifset unw
8169 Furthermore, under Windows, the sources pointed to by the libraries path
8170 set in the registry are not searched for.
8171 @end ifset
8172
8173 @item ^-n^/NOMAIN^
8174 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8175 No main program.
8176
8177 @item -nostdinc
8178 @cindex @option{-nostdinc} (@command{gnatbind})
8179 Do not look for sources in the system default directory.
8180
8181 @item -nostdlib
8182 @cindex @option{-nostdlib} (@command{gnatbind})
8183 Do not look for library files in the system default directory.
8184
8185 @item --RTS=@var{rts-path}
8186 @cindex @option{--RTS} (@code{gnatbind})
8187 Specifies the default location of the runtime library. Same meaning as the
8188 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8189
8190 @item ^-o ^/OUTPUT=^@var{file}
8191 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8192 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8193 Note that if this option is used, then linking must be done manually,
8194 gnatlink cannot be used.
8195
8196 @item ^-O^/OBJECT_LIST^
8197 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8198 Output object list.
8199
8200 @item ^-p^/PESSIMISTIC_ELABORATION^
8201 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8202 Pessimistic (worst-case) elaboration order
8203
8204 @item ^-R^-R^
8205 @cindex @option{^-R^-R^} (@command{gnatbind})
8206 Output closure source list.
8207
8208 @item ^-s^/READ_SOURCES=ALL^
8209 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8210 Require all source files to be present.
8211
8212 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8213 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8214 Specifies the value to be used when detecting uninitialized scalar
8215 objects with pragma Initialize_Scalars.
8216 The @var{xxx} ^string specified with the switch^option^ may be either
8217 @itemize @bullet
8218 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8219 @item ``@option{^lo^LOW^}'' for the lowest possible value
8220 @item ``@option{^hi^HIGH^}'' for the highest possible value
8221 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8222 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8223 @end itemize
8224
8225 In addition, you can specify @option{-Sev} to indicate that the value is
8226 to be set at run time. In this case, the program will look for an environment
8227 @cindex GNAT_INIT_SCALARS
8228 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8229 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8230 If no environment variable is found, or if it does not have a valid value,
8231 then the default is @option{in} (invalid values).
8232
8233 @ifclear vms
8234 @item -static
8235 @cindex @option{-static} (@code{gnatbind})
8236 Link against a static GNAT run time.
8237
8238 @item -shared
8239 @cindex @option{-shared} (@code{gnatbind})
8240 Link against a shared GNAT run time when available.
8241 @end ifclear
8242
8243 @item ^-t^/NOTIME_STAMP_CHECK^
8244 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8245 Tolerate time stamp and other consistency errors
8246
8247 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8248 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8249 Set the time slice value to @var{n} milliseconds. If the system supports
8250 the specification of a specific time slice value, then the indicated value
8251 is used. If the system does not support specific time slice values, but
8252 does support some general notion of round-robin scheduling, then any
8253 nonzero value will activate round-robin scheduling.
8254
8255 A value of zero is treated specially. It turns off time
8256 slicing, and in addition, indicates to the tasking run time that the
8257 semantics should match as closely as possible the Annex D
8258 requirements of the Ada RM, and in particular sets the default
8259 scheduling policy to @code{FIFO_Within_Priorities}.
8260
8261 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8262 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8263 Enable dynamic stack usage, with @var{n} results stored and displayed
8264 at program termination. A result is generated when a task
8265 terminates. Results that can't be stored are displayed on the fly, at
8266 task termination. This option is currently not supported on Itanium
8267 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8268
8269 @item ^-v^/REPORT_ERRORS=VERBOSE^
8270 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8271 Verbose mode. Write error messages, header, summary output to
8272 @file{stdout}.
8273
8274 @ifclear vms
8275 @item -w@var{x}
8276 @cindex @option{-w} (@code{gnatbind})
8277 Warning mode (@var{x}=s/e for suppress/treat as error)
8278 @end ifclear
8279
8280 @ifset vms
8281 @item /WARNINGS=NORMAL
8282 @cindex @option{/WARNINGS} (@code{gnatbind})
8283 Normal warnings mode. Warnings are issued but ignored
8284
8285 @item /WARNINGS=SUPPRESS
8286 @cindex @option{/WARNINGS} (@code{gnatbind})
8287 All warning messages are suppressed
8288
8289 @item /WARNINGS=ERROR
8290 @cindex @option{/WARNINGS} (@code{gnatbind})
8291 Warning messages are treated as fatal errors
8292 @end ifset
8293
8294 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8295 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8296 Override default wide character encoding for standard Text_IO files.
8297
8298 @item ^-x^/READ_SOURCES=NONE^
8299 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8300 Exclude source files (check object consistency only).
8301
8302 @ifset vms
8303 @item /READ_SOURCES=AVAILABLE
8304 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8305 Default mode, in which sources are checked for consistency only if
8306 they are available.
8307 @end ifset
8308
8309 @item ^-y^/ENABLE_LEAP_SECONDS^
8310 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8311 Enable leap seconds support in @code{Ada.Calendar} and its children.
8312
8313 @item ^-z^/ZERO_MAIN^
8314 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8315 No main subprogram.
8316 @end table
8317
8318 @ifclear vms
8319 @noindent
8320 You may obtain this listing of switches by running @code{gnatbind} with
8321 no arguments.
8322 @end ifclear
8323
8324 @node Consistency-Checking Modes
8325 @subsection Consistency-Checking Modes
8326
8327 @noindent
8328 As described earlier, by default @code{gnatbind} checks
8329 that object files are consistent with one another and are consistent
8330 with any source files it can locate. The following switches control binder
8331 access to sources.
8332
8333 @table @option
8334 @c !sort!
8335 @item ^-s^/READ_SOURCES=ALL^
8336 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8337 Require source files to be present. In this mode, the binder must be
8338 able to locate all source files that are referenced, in order to check
8339 their consistency. In normal mode, if a source file cannot be located it
8340 is simply ignored. If you specify this switch, a missing source
8341 file is an error.
8342
8343 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8344 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8345 Override default wide character encoding for standard Text_IO files.
8346 Normally the default wide character encoding method used for standard
8347 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8348 the main source input (see description of switch
8349 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8350 use of this switch for the binder (which has the same set of
8351 possible arguments) overrides this default as specified.
8352
8353 @item ^-x^/READ_SOURCES=NONE^
8354 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8355 Exclude source files. In this mode, the binder only checks that ALI
8356 files are consistent with one another. Source files are not accessed.
8357 The binder runs faster in this mode, and there is still a guarantee that
8358 the resulting program is self-consistent.
8359 If a source file has been edited since it was last compiled, and you
8360 specify this switch, the binder will not detect that the object
8361 file is out of date with respect to the source file. Note that this is the
8362 mode that is automatically used by @command{gnatmake} because in this
8363 case the checking against sources has already been performed by
8364 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8365
8366 @ifset vms
8367 @item /READ_SOURCES=AVAILABLE
8368 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8369 This is the default mode in which source files are checked if they are
8370 available, and ignored if they are not available.
8371 @end ifset
8372 @end table
8373
8374 @node Binder Error Message Control
8375 @subsection Binder Error Message Control
8376
8377 @noindent
8378 The following switches provide control over the generation of error
8379 messages from the binder:
8380
8381 @table @option
8382 @c !sort!
8383 @item ^-v^/REPORT_ERRORS=VERBOSE^
8384 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8385 Verbose mode. In the normal mode, brief error messages are generated to
8386 @file{stderr}. If this switch is present, a header is written
8387 to @file{stdout} and any error messages are directed to @file{stdout}.
8388 All that is written to @file{stderr} is a brief summary message.
8389
8390 @item ^-b^/REPORT_ERRORS=BRIEF^
8391 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8392 Generate brief error messages to @file{stderr} even if verbose mode is
8393 specified. This is relevant only when used with the
8394 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8395
8396 @ifclear vms
8397 @item -m@var{n}
8398 @cindex @option{-m} (@code{gnatbind})
8399 Limits the number of error messages to @var{n}, a decimal integer in the
8400 range 1-999. The binder terminates immediately if this limit is reached.
8401
8402 @item -M@var{xxx}
8403 @cindex @option{-M} (@code{gnatbind})
8404 Renames the generated main program from @code{main} to @code{xxx}.
8405 This is useful in the case of some cross-building environments, where
8406 the actual main program is separate from the one generated
8407 by @code{gnatbind}.
8408 @end ifclear
8409
8410 @item ^-ws^/WARNINGS=SUPPRESS^
8411 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8412 @cindex Warnings
8413 Suppress all warning messages.
8414
8415 @item ^-we^/WARNINGS=ERROR^
8416 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8417 Treat any warning messages as fatal errors.
8418
8419 @ifset vms
8420 @item /WARNINGS=NORMAL
8421 Standard mode with warnings generated, but warnings do not get treated
8422 as errors.
8423 @end ifset
8424
8425 @item ^-t^/NOTIME_STAMP_CHECK^
8426 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8427 @cindex Time stamp checks, in binder
8428 @cindex Binder consistency checks
8429 @cindex Consistency checks, in binder
8430 The binder performs a number of consistency checks including:
8431
8432 @itemize @bullet
8433 @item
8434 Check that time stamps of a given source unit are consistent
8435 @item
8436 Check that checksums of a given source unit are consistent
8437 @item
8438 Check that consistent versions of @code{GNAT} were used for compilation
8439 @item
8440 Check consistency of configuration pragmas as required
8441 @end itemize
8442
8443 @noindent
8444 Normally failure of such checks, in accordance with the consistency
8445 requirements of the Ada Reference Manual, causes error messages to be
8446 generated which abort the binder and prevent the output of a binder
8447 file and subsequent link to obtain an executable.
8448
8449 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8450 into warnings, so that
8451 binding and linking can continue to completion even in the presence of such
8452 errors. The result may be a failed link (due to missing symbols), or a
8453 non-functional executable which has undefined semantics.
8454 @emph{This means that
8455 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8456 with extreme care.}
8457 @end table
8458
8459 @node Elaboration Control
8460 @subsection Elaboration Control
8461
8462 @noindent
8463 The following switches provide additional control over the elaboration
8464 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8465
8466 @table @option
8467 @item ^-p^/PESSIMISTIC_ELABORATION^
8468 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8469 Normally the binder attempts to choose an elaboration order that is
8470 likely to minimize the likelihood of an elaboration order error resulting
8471 in raising a @code{Program_Error} exception. This switch reverses the
8472 action of the binder, and requests that it deliberately choose an order
8473 that is likely to maximize the likelihood of an elaboration error.
8474 This is useful in ensuring portability and avoiding dependence on
8475 accidental fortuitous elaboration ordering.
8476
8477 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8478 switch if dynamic
8479 elaboration checking is used (@option{-gnatE} switch used for compilation).
8480 This is because in the default static elaboration mode, all necessary
8481 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8482 These implicit pragmas are still respected by the binder in
8483 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8484 safe elaboration order is assured.
8485 @end table
8486
8487 @node Output Control
8488 @subsection Output Control
8489
8490 @noindent
8491 The following switches allow additional control over the output
8492 generated by the binder.
8493
8494 @table @option
8495 @c !sort!
8496
8497 @item ^-c^/NOOUTPUT^
8498 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8499 Check only. Do not generate the binder output file. In this mode the
8500 binder performs all error checks but does not generate an output file.
8501
8502 @item ^-e^/ELABORATION_DEPENDENCIES^
8503 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8504 Output complete list of elaboration-order dependencies, showing the
8505 reason for each dependency. This output can be rather extensive but may
8506 be useful in diagnosing problems with elaboration order. The output is
8507 written to @file{stdout}.
8508
8509 @item ^-h^/HELP^
8510 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8511 Output usage information. The output is written to @file{stdout}.
8512
8513 @item ^-K^/LINKER_OPTION_LIST^
8514 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8515 Output linker options to @file{stdout}. Includes library search paths,
8516 contents of pragmas Ident and Linker_Options, and libraries added
8517 by @code{gnatbind}.
8518
8519 @item ^-l^/ORDER_OF_ELABORATION^
8520 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8521 Output chosen elaboration order. The output is written to @file{stdout}.
8522
8523 @item ^-O^/OBJECT_LIST^
8524 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8525 Output full names of all the object files that must be linked to provide
8526 the Ada component of the program. The output is written to @file{stdout}.
8527 This list includes the files explicitly supplied and referenced by the user
8528 as well as implicitly referenced run-time unit files. The latter are
8529 omitted if the corresponding units reside in shared libraries. The
8530 directory names for the run-time units depend on the system configuration.
8531
8532 @item ^-o ^/OUTPUT=^@var{file}
8533 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8534 Set name of output file to @var{file} instead of the normal
8535 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8536 binder generated body filename.
8537 Note that if this option is used, then linking must be done manually.
8538 It is not possible to use gnatlink in this case, since it cannot locate
8539 the binder file.
8540
8541 @item ^-r^/RESTRICTION_LIST^
8542 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8543 Generate list of @code{pragma Restrictions} that could be applied to
8544 the current unit. This is useful for code audit purposes, and also may
8545 be used to improve code generation in some cases.
8546
8547 @end table
8548
8549 @node Binding with Non-Ada Main Programs
8550 @subsection Binding with Non-Ada Main Programs
8551
8552 @noindent
8553 In our description so far we have assumed that the main
8554 program is in Ada, and that the task of the binder is to generate a
8555 corresponding function @code{main} that invokes this Ada main
8556 program. GNAT also supports the building of executable programs where
8557 the main program is not in Ada, but some of the called routines are
8558 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8559 The following switch is used in this situation:
8560
8561 @table @option
8562 @item ^-n^/NOMAIN^
8563 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8564 No main program. The main program is not in Ada.
8565 @end table
8566
8567 @noindent
8568 In this case, most of the functions of the binder are still required,
8569 but instead of generating a main program, the binder generates a file
8570 containing the following callable routines:
8571
8572 @table @code
8573 @item adainit
8574 @findex adainit
8575 You must call this routine to initialize the Ada part of the program by
8576 calling the necessary elaboration routines. A call to @code{adainit} is
8577 required before the first call to an Ada subprogram.
8578
8579 Note that it is assumed that the basic execution environment must be setup
8580 to be appropriate for Ada execution at the point where the first Ada
8581 subprogram is called. In particular, if the Ada code will do any
8582 floating-point operations, then the FPU must be setup in an appropriate
8583 manner. For the case of the x86, for example, full precision mode is
8584 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8585 that the FPU is in the right state.
8586
8587 @item adafinal
8588 @findex adafinal
8589 You must call this routine to perform any library-level finalization
8590 required by the Ada subprograms. A call to @code{adafinal} is required
8591 after the last call to an Ada subprogram, and before the program
8592 terminates.
8593 @end table
8594
8595 @noindent
8596 If the @option{^-n^/NOMAIN^} switch
8597 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8598 @cindex Binder, multiple input files
8599 is given, more than one ALI file may appear on
8600 the command line for @code{gnatbind}. The normal @dfn{closure}
8601 calculation is performed for each of the specified units. Calculating
8602 the closure means finding out the set of units involved by tracing
8603 @code{with} references. The reason it is necessary to be able to
8604 specify more than one ALI file is that a given program may invoke two or
8605 more quite separate groups of Ada units.
8606
8607 The binder takes the name of its output file from the last specified ALI
8608 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8609 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8610 The output is an Ada unit in source form that can be compiled with GNAT.
8611 This compilation occurs automatically as part of the @command{gnatlink}
8612 processing.
8613
8614 Currently the GNAT run time requires a FPU using 80 bits mode
8615 precision. Under targets where this is not the default it is required to
8616 call GNAT.Float_Control.Reset before using floating point numbers (this
8617 include float computation, float input and output) in the Ada code. A
8618 side effect is that this could be the wrong mode for the foreign code
8619 where floating point computation could be broken after this call.
8620
8621 @node Binding Programs with No Main Subprogram
8622 @subsection Binding Programs with No Main Subprogram
8623
8624 @noindent
8625 It is possible to have an Ada program which does not have a main
8626 subprogram. This program will call the elaboration routines of all the
8627 packages, then the finalization routines.
8628
8629 The following switch is used to bind programs organized in this manner:
8630
8631 @table @option
8632 @item ^-z^/ZERO_MAIN^
8633 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8634 Normally the binder checks that the unit name given on the command line
8635 corresponds to a suitable main subprogram. When this switch is used,
8636 a list of ALI files can be given, and the execution of the program
8637 consists of elaboration of these units in an appropriate order. Note
8638 that the default wide character encoding method for standard Text_IO
8639 files is always set to Brackets if this switch is set (you can use
8640 the binder switch
8641 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8642 @end table
8643
8644 @node Command-Line Access
8645 @section Command-Line Access
8646
8647 @noindent
8648 The package @code{Ada.Command_Line} provides access to the command-line
8649 arguments and program name. In order for this interface to operate
8650 correctly, the two variables
8651
8652 @smallexample
8653 @group
8654 int gnat_argc;
8655 char **gnat_argv;
8656 @end group
8657 @end smallexample
8658
8659 @noindent
8660 @findex gnat_argv
8661 @findex gnat_argc
8662 are declared in one of the GNAT library routines. These variables must
8663 be set from the actual @code{argc} and @code{argv} values passed to the
8664 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8665 generates the C main program to automatically set these variables.
8666 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8667 set these variables. If they are not set, the procedures in
8668 @code{Ada.Command_Line} will not be available, and any attempt to use
8669 them will raise @code{Constraint_Error}. If command line access is
8670 required, your main program must set @code{gnat_argc} and
8671 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8672 it.
8673
8674 @node Search Paths for gnatbind
8675 @section Search Paths for @code{gnatbind}
8676
8677 @noindent
8678 The binder takes the name of an ALI file as its argument and needs to
8679 locate source files as well as other ALI files to verify object consistency.
8680
8681 For source files, it follows exactly the same search rules as @command{gcc}
8682 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8683 directories searched are:
8684
8685 @enumerate
8686 @item
8687 The directory containing the ALI file named in the command line, unless
8688 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8689
8690 @item
8691 All directories specified by @option{^-I^/SEARCH^}
8692 switches on the @code{gnatbind}
8693 command line, in the order given.
8694
8695 @item
8696 @findex ADA_PRJ_OBJECTS_FILE
8697 Each of the directories listed in the text file whose name is given
8698 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8699
8700 @noindent
8701 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8702 driver when project files are used. It should not normally be set
8703 by other means.
8704
8705 @item
8706 @findex ADA_OBJECTS_PATH
8707 Each of the directories listed in the value of the
8708 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8709 @ifset unw
8710 Construct this value
8711 exactly as the @env{PATH} environment variable: a list of directory
8712 names separated by colons (semicolons when working with the NT version
8713 of GNAT).
8714 @end ifset
8715 @ifset vms
8716 Normally, define this value as a logical name containing a comma separated
8717 list of directory names.
8718
8719 This variable can also be defined by means of an environment string
8720 (an argument to the HP C exec* set of functions).
8721
8722 Logical Name:
8723 @smallexample
8724 DEFINE ANOTHER_PATH FOO:[BAG]
8725 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8726 @end smallexample
8727
8728 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8729 first, followed by the standard Ada
8730 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8731 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8732 (Text_IO, Sequential_IO, etc)
8733 instead of the standard Ada packages. Thus, in order to get the standard Ada
8734 packages by default, ADA_OBJECTS_PATH must be redefined.
8735 @end ifset
8736
8737 @item
8738 The content of the @file{ada_object_path} file which is part of the GNAT
8739 installation tree and is used to store standard libraries such as the
8740 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8741 specified.
8742 @ifclear vms
8743 @ref{Installing a library}
8744 @end ifclear
8745 @end enumerate
8746
8747 @noindent
8748 In the binder the switch @option{^-I^/SEARCH^}
8749 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8750 is used to specify both source and
8751 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8752 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8753 instead if you want to specify
8754 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8755 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8756 if you want to specify library paths
8757 only. This means that for the binder
8758 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8759 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8760 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8761 The binder generates the bind file (a C language source file) in the
8762 current working directory.
8763
8764 @findex Ada
8765 @findex System
8766 @findex Interfaces
8767 @findex GNAT
8768 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8769 children make up the GNAT Run-Time Library, together with the package
8770 GNAT and its children, which contain a set of useful additional
8771 library functions provided by GNAT. The sources for these units are
8772 needed by the compiler and are kept together in one directory. The ALI
8773 files and object files generated by compiling the RTL are needed by the
8774 binder and the linker and are kept together in one directory, typically
8775 different from the directory containing the sources. In a normal
8776 installation, you need not specify these directory names when compiling
8777 or binding. Either the environment variables or the built-in defaults
8778 cause these files to be found.
8779
8780 Besides simplifying access to the RTL, a major use of search paths is
8781 in compiling sources from multiple directories. This can make
8782 development environments much more flexible.
8783
8784 @node Examples of gnatbind Usage
8785 @section Examples of @code{gnatbind} Usage
8786
8787 @noindent
8788 This section contains a number of examples of using the GNAT binding
8789 utility @code{gnatbind}.
8790
8791 @table @code
8792 @item gnatbind hello
8793 The main program @code{Hello} (source program in @file{hello.adb}) is
8794 bound using the standard switch settings. The generated main program is
8795 @file{b~hello.adb}. This is the normal, default use of the binder.
8796
8797 @ifclear vms
8798 @item gnatbind hello -o mainprog.adb
8799 @end ifclear
8800 @ifset vms
8801 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8802 @end ifset
8803 The main program @code{Hello} (source program in @file{hello.adb}) is
8804 bound using the standard switch settings. The generated main program is
8805 @file{mainprog.adb} with the associated spec in
8806 @file{mainprog.ads}. Note that you must specify the body here not the
8807 spec. Note that if this option is used, then linking must be done manually,
8808 since gnatlink will not be able to find the generated file.
8809 @end table
8810
8811 @c ------------------------------------
8812 @node Linking Using gnatlink
8813 @chapter Linking Using @command{gnatlink}
8814 @c ------------------------------------
8815 @findex gnatlink
8816
8817 @noindent
8818 This chapter discusses @command{gnatlink}, a tool that links
8819 an Ada program and builds an executable file. This utility
8820 invokes the system linker ^(via the @command{gcc} command)^^
8821 with a correct list of object files and library references.
8822 @command{gnatlink} automatically determines the list of files and
8823 references for the Ada part of a program. It uses the binder file
8824 generated by the @command{gnatbind} to determine this list.
8825
8826 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8827 driver (see @ref{The GNAT Driver and Project Files}).
8828
8829 @menu
8830 * Running gnatlink::
8831 * Switches for gnatlink::
8832 @end menu
8833
8834 @node Running gnatlink
8835 @section Running @command{gnatlink}
8836
8837 @noindent
8838 The form of the @command{gnatlink} command is
8839
8840 @smallexample
8841 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8842 @c            @ovar{non-Ada objects} @ovar{linker options}
8843 @c Expanding @ovar macro inline (explanation in macro def comments)
8844 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
8845            @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
8846
8847 @end smallexample
8848
8849 @noindent
8850 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8851 non-Ada objects
8852 or linker options) may be in any order, provided that no non-Ada object may
8853 be mistaken for a main @file{ALI} file.
8854 Any file name @file{F} without the @file{.ali}
8855 extension will be taken as the main @file{ALI} file if a file exists
8856 whose name is the concatenation of @file{F} and @file{.ali}.
8857
8858 @noindent
8859 @file{@var{mainprog}.ali} references the ALI file of the main program.
8860 The @file{.ali} extension of this file can be omitted. From this
8861 reference, @command{gnatlink} locates the corresponding binder file
8862 @file{b~@var{mainprog}.adb} and, using the information in this file along
8863 with the list of non-Ada objects and linker options, constructs a
8864 linker command file to create the executable.
8865
8866 The arguments other than the @command{gnatlink} switches and the main
8867 @file{ALI} file are passed to the linker uninterpreted.
8868 They typically include the names of
8869 object files for units written in other languages than Ada and any library
8870 references required to resolve references in any of these foreign language
8871 units, or in @code{Import} pragmas in any Ada units.
8872
8873 @var{linker options} is an optional list of linker specific
8874 switches.
8875 The default linker called by gnatlink is @command{gcc} which in
8876 turn calls the appropriate system linker.
8877 Standard options for the linker such as @option{-lmy_lib} or
8878 @option{-Ldir} can be added as is.
8879 For options that are not recognized by
8880 @command{gcc} as linker options, use the @command{gcc} switches
8881 @option{-Xlinker} or @option{-Wl,}.
8882 Refer to the GCC documentation for
8883 details. Here is an example showing how to generate a linker map:
8884
8885 @smallexample
8886 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8887 @end smallexample
8888
8889 Using @var{linker options} it is possible to set the program stack and
8890 heap size.
8891 @ifset unw
8892 See @ref{Setting Stack Size from gnatlink} and
8893 @ref{Setting Heap Size from gnatlink}.
8894 @end ifset
8895
8896 @command{gnatlink} determines the list of objects required by the Ada
8897 program and prepends them to the list of objects passed to the linker.
8898 @command{gnatlink} also gathers any arguments set by the use of
8899 @code{pragma Linker_Options} and adds them to the list of arguments
8900 presented to the linker.
8901
8902 @ifset vms
8903 @command{gnatlink} accepts the following types of extra files on the command
8904 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8905 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8906 handled according to their extension.
8907 @end ifset
8908
8909 @node Switches for gnatlink
8910 @section Switches for @command{gnatlink}
8911
8912 @noindent
8913 The following switches are available with the @command{gnatlink} utility:
8914
8915 @table @option
8916 @c !sort!
8917
8918 @item --version
8919 @cindex @option{--version} @command{gnatlink}
8920 Display Copyright and version, then exit disregarding all other options.
8921
8922 @item --help
8923 @cindex @option{--help} @command{gnatlink}
8924 If @option{--version} was not used, display usage, then exit disregarding
8925 all other options.
8926
8927 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8928 @cindex Command line length
8929 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8930 On some targets, the command line length is limited, and @command{gnatlink}
8931 will generate a separate file for the linker if the list of object files
8932 is too long.
8933 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8934 to be generated even if
8935 the limit is not exceeded. This is useful in some cases to deal with
8936 special situations where the command line length is exceeded.
8937
8938 @item ^-g^/DEBUG^
8939 @cindex Debugging information, including
8940 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8941 The option to include debugging information causes the Ada bind file (in
8942 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8943 @option{^-g^/DEBUG^}.
8944 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8945 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8946 Without @option{^-g^/DEBUG^}, the binder removes these files by
8947 default. The same procedure apply if a C bind file was generated using
8948 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8949 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8950
8951 @item ^-n^/NOCOMPILE^
8952 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8953 Do not compile the file generated by the binder. This may be used when
8954 a link is rerun with different options, but there is no need to recompile
8955 the binder file.
8956
8957 @item ^-v^/VERBOSE^
8958 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8959 Causes additional information to be output, including a full list of the
8960 included object files. This switch option is most useful when you want
8961 to see what set of object files are being used in the link step.
8962
8963 @item ^-v -v^/VERBOSE/VERBOSE^
8964 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8965 Very verbose mode. Requests that the compiler operate in verbose mode when
8966 it compiles the binder file, and that the system linker run in verbose mode.
8967
8968 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8969 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8970 @var{exec-name} specifies an alternate name for the generated
8971 executable program. If this switch is omitted, the executable has the same
8972 name as the main unit. For example, @code{gnatlink try.ali} creates
8973 an executable called @file{^try^TRY.EXE^}.
8974
8975 @ifclear vms
8976 @item -b @var{target}
8977 @cindex @option{-b} (@command{gnatlink})
8978 Compile your program to run on @var{target}, which is the name of a
8979 system configuration. You must have a GNAT cross-compiler built if
8980 @var{target} is not the same as your host system.
8981
8982 @item -B@var{dir}
8983 @cindex @option{-B} (@command{gnatlink})
8984 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8985 from @var{dir} instead of the default location. Only use this switch
8986 when multiple versions of the GNAT compiler are available.
8987 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
8988 for further details. You would normally use the @option{-b} or
8989 @option{-V} switch instead.
8990
8991 @item --GCC=@var{compiler_name}
8992 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8993 Program used for compiling the binder file. The default is
8994 @command{gcc}. You need to use quotes around @var{compiler_name} if
8995 @code{compiler_name} contains spaces or other separator characters.
8996 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8997 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8998 inserted after your command name. Thus in the above example the compiler
8999 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9000 A limitation of this syntax is that the name and path name of the executable
9001 itself must not include any embedded spaces. If the compiler executable is
9002 different from the default one (gcc or <prefix>-gcc), then the back-end
9003 switches in the ALI file are not used to compile the binder generated source.
9004 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9005 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9006 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9007 is taken into account. However, all the additional switches are also taken
9008 into account. Thus,
9009 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9010 @option{--GCC="bar -x -y -z -t"}.
9011
9012 @item --LINK=@var{name}
9013 @cindex @option{--LINK=} (@command{gnatlink})
9014 @var{name} is the name of the linker to be invoked. This is especially
9015 useful in mixed language programs since languages such as C++ require
9016 their own linker to be used. When this switch is omitted, the default
9017 name for the linker is @command{gcc}. When this switch is used, the
9018 specified linker is called instead of @command{gcc} with exactly the same
9019 parameters that would have been passed to @command{gcc} so if the desired
9020 linker requires different parameters it is necessary to use a wrapper
9021 script that massages the parameters before invoking the real linker. It
9022 may be useful to control the exact invocation by using the verbose
9023 switch.
9024
9025 @end ifclear
9026
9027 @ifset vms
9028 @item /DEBUG=TRACEBACK
9029 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9030 This qualifier causes sufficient information to be included in the
9031 executable file to allow a traceback, but does not include the full
9032 symbol information needed by the debugger.
9033
9034 @item /IDENTIFICATION="<string>"
9035 @code{"<string>"} specifies the string to be stored in the image file
9036 identification field in the image header.
9037 It overrides any pragma @code{Ident} specified string.
9038
9039 @item /NOINHIBIT-EXEC
9040 Generate the executable file even if there are linker warnings.
9041
9042 @item /NOSTART_FILES
9043 Don't link in the object file containing the ``main'' transfer address.
9044 Used when linking with a foreign language main program compiled with an
9045 HP compiler.
9046
9047 @item /STATIC
9048 Prefer linking with object libraries over sharable images, even without
9049 /DEBUG.
9050 @end ifset
9051
9052 @end table
9053
9054 @node The GNAT Make Program gnatmake
9055 @chapter The GNAT Make Program @command{gnatmake}
9056 @findex gnatmake
9057
9058 @menu
9059 * Running gnatmake::
9060 * Switches for gnatmake::
9061 * Mode Switches for gnatmake::
9062 * Notes on the Command Line::
9063 * How gnatmake Works::
9064 * Examples of gnatmake Usage::
9065 @end menu
9066 @noindent
9067 A typical development cycle when working on an Ada program consists of
9068 the following steps:
9069
9070 @enumerate
9071 @item
9072 Edit some sources to fix bugs.
9073
9074 @item
9075 Add enhancements.
9076
9077 @item
9078 Compile all sources affected.
9079
9080 @item
9081 Rebind and relink.
9082
9083 @item
9084 Test.
9085 @end enumerate
9086
9087 @noindent
9088 The third step can be tricky, because not only do the modified files
9089 @cindex Dependency rules
9090 have to be compiled, but any files depending on these files must also be
9091 recompiled. The dependency rules in Ada can be quite complex, especially
9092 in the presence of overloading, @code{use} clauses, generics and inlined
9093 subprograms.
9094
9095 @command{gnatmake} automatically takes care of the third and fourth steps
9096 of this process. It determines which sources need to be compiled,
9097 compiles them, and binds and links the resulting object files.
9098
9099 Unlike some other Ada make programs, the dependencies are always
9100 accurately recomputed from the new sources. The source based approach of
9101 the GNAT compilation model makes this possible. This means that if
9102 changes to the source program cause corresponding changes in
9103 dependencies, they will always be tracked exactly correctly by
9104 @command{gnatmake}.
9105
9106 @node Running gnatmake
9107 @section Running @command{gnatmake}
9108
9109 @noindent
9110 The usual form of the @command{gnatmake} command is
9111
9112 @smallexample
9113 @c $ gnatmake @ovar{switches} @var{file_name}
9114 @c       @ovar{file_names} @ovar{mode_switches}
9115 @c Expanding @ovar macro inline (explanation in macro def comments)
9116 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9117       @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9118 @end smallexample
9119
9120 @noindent
9121 The only required argument is one @var{file_name}, which specifies
9122 a compilation unit that is a main program. Several @var{file_names} can be
9123 specified: this will result in several executables being built.
9124 If @code{switches} are present, they can be placed before the first
9125 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9126 If @var{mode_switches} are present, they must always be placed after
9127 the last @var{file_name} and all @code{switches}.
9128
9129 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9130 extension may be omitted from the @var{file_name} arguments. However, if
9131 you are using non-standard extensions, then it is required that the
9132 extension be given. A relative or absolute directory path can be
9133 specified in a @var{file_name}, in which case, the input source file will
9134 be searched for in the specified directory only. Otherwise, the input
9135 source file will first be searched in the directory where
9136 @command{gnatmake} was invoked and if it is not found, it will be search on
9137 the source path of the compiler as described in
9138 @ref{Search Paths and the Run-Time Library (RTL)}.
9139
9140 All @command{gnatmake} output (except when you specify
9141 @option{^-M^/DEPENDENCIES_LIST^}) is to
9142 @file{stderr}. The output produced by the
9143 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9144 @file{stdout}.
9145
9146 @node Switches for gnatmake
9147 @section Switches for @command{gnatmake}
9148
9149 @noindent
9150 You may specify any of the following switches to @command{gnatmake}:
9151
9152 @table @option
9153 @c !sort!
9154
9155 @item --version
9156 @cindex @option{--version} @command{gnatmake}
9157 Display Copyright and version, then exit disregarding all other options.
9158
9159 @item --help
9160 @cindex @option{--help} @command{gnatmake}
9161 If @option{--version} was not used, display usage, then exit disregarding
9162 all other options.
9163
9164 @ifclear vms
9165 @item --GCC=@var{compiler_name}
9166 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9167 Program used for compiling. The default is `@command{gcc}'. You need to use
9168 quotes around @var{compiler_name} if @code{compiler_name} contains
9169 spaces or other separator characters. As an example @option{--GCC="foo -x
9170 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9171 compiler. A limitation of this syntax is that the name and path name of
9172 the executable itself must not include any embedded spaces. Note that
9173 switch @option{-c} is always inserted after your command name. Thus in the
9174 above example the compiler command that will be used by @command{gnatmake}
9175 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9176 used, only the last @var{compiler_name} is taken into account. However,
9177 all the additional switches are also taken into account. Thus,
9178 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9179 @option{--GCC="bar -x -y -z -t"}.
9180
9181 @item --GNATBIND=@var{binder_name}
9182 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9183 Program used for binding. The default is `@code{gnatbind}'. You need to
9184 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9185 or other separator characters. As an example @option{--GNATBIND="bar -x
9186 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9187 binder. Binder switches that are normally appended by @command{gnatmake}
9188 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9189 A limitation of this syntax is that the name and path name of the executable
9190 itself must not include any embedded spaces.
9191
9192 @item --GNATLINK=@var{linker_name}
9193 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9194 Program used for linking. The default is `@command{gnatlink}'. You need to
9195 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9196 or other separator characters. As an example @option{--GNATLINK="lan -x
9197 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9198 linker. Linker switches that are normally appended by @command{gnatmake} to
9199 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9200 A limitation of this syntax is that the name and path name of the executable
9201 itself must not include any embedded spaces.
9202
9203 @end ifclear
9204
9205 @item ^-a^/ALL_FILES^
9206 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9207 Consider all files in the make process, even the GNAT internal system
9208 files (for example, the predefined Ada library files), as well as any
9209 locked files. Locked files are files whose ALI file is write-protected.
9210 By default,
9211 @command{gnatmake} does not check these files,
9212 because the assumption is that the GNAT internal files are properly up
9213 to date, and also that any write protected ALI files have been properly
9214 installed. Note that if there is an installation problem, such that one
9215 of these files is not up to date, it will be properly caught by the
9216 binder.
9217 You may have to specify this switch if you are working on GNAT
9218 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9219 in conjunction with @option{^-f^/FORCE_COMPILE^}
9220 if you need to recompile an entire application,
9221 including run-time files, using special configuration pragmas,
9222 such as a @code{Normalize_Scalars} pragma.
9223
9224 By default
9225 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9226 internal files with
9227 @ifclear vms
9228 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9229 @end ifclear
9230 @ifset vms
9231 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9232 @end ifset
9233
9234 @item ^-b^/ACTIONS=BIND^
9235 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9236 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9237 compilation and binding, but no link.
9238 Can be combined with @option{^-l^/ACTIONS=LINK^}
9239 to do binding and linking. When not combined with
9240 @option{^-c^/ACTIONS=COMPILE^}
9241 all the units in the closure of the main program must have been previously
9242 compiled and must be up to date. The root unit specified by @var{file_name}
9243 may be given without extension, with the source extension or, if no GNAT
9244 Project File is specified, with the ALI file extension.
9245
9246 @item ^-c^/ACTIONS=COMPILE^
9247 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9248 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9249 is also specified. Do not perform linking, except if both
9250 @option{^-b^/ACTIONS=BIND^} and
9251 @option{^-l^/ACTIONS=LINK^} are also specified.
9252 If the root unit specified by @var{file_name} is not a main unit, this is the
9253 default. Otherwise @command{gnatmake} will attempt binding and linking
9254 unless all objects are up to date and the executable is more recent than
9255 the objects.
9256
9257 @item ^-C^/MAPPING^
9258 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9259 Use a temporary mapping file. A mapping file is a way to communicate
9260 to the compiler two mappings: from unit names to file names (without
9261 any directory information) and from file names to path names (with
9262 full directory information). A mapping file can make the compiler's
9263 file searches faster, especially if there are many source directories,
9264 or the sources are read over a slow network connection. If
9265 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9266 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9267 is initially populated based on the project file. If
9268 @option{^-C^/MAPPING^} is used without
9269 @option{^-P^/PROJECT_FILE^},
9270 the mapping file is initially empty. Each invocation of the compiler
9271 will add any newly accessed sources to the mapping file.
9272
9273 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9274 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9275 Use a specific mapping file. The file, specified as a path name (absolute or
9276 relative) by this switch, should already exist, otherwise the switch is
9277 ineffective. The specified mapping file will be communicated to the compiler.
9278 This switch is not compatible with a project file
9279 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9280 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9281
9282 @item ^-d^/DISPLAY_PROGRESS^
9283 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9284 Display progress for each source, up to date or not, as a single line
9285
9286 @smallexample
9287 completed x out of y (zz%)
9288 @end smallexample
9289
9290 If the file needs to be compiled this is displayed after the invocation of
9291 the compiler. These lines are displayed even in quiet output mode.
9292
9293 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9294 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9295 Put all object files and ALI file in directory @var{dir}.
9296 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9297 and ALI files go in the current working directory.
9298
9299 This switch cannot be used when using a project file.
9300
9301 @ifclear vms
9302 @item -eL
9303 @cindex @option{-eL} (@command{gnatmake})
9304 @cindex symbolic links
9305 Follow all symbolic links when processing project files.
9306 This should be used if your project uses symbolic links for files or
9307 directories, but is not needed in other cases.
9308
9309 @cindex naming scheme
9310 This also assumes that no directory matches the naming scheme for files (for
9311 instance that you do not have a directory called "sources.ads" when using the
9312 default GNAT naming scheme).
9313
9314 When you do not have to use this switch (ie by default), gnatmake is able to
9315 save a lot of system calls (several per source file and object file), which
9316 can result in a significant speed up to load and manipulate a project file,
9317 especially when using source files from a remote system.
9318
9319 @end ifclear
9320
9321 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9322 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9323 Output the commands for the compiler, the binder and the linker
9324 on ^standard output^SYS$OUTPUT^,
9325 instead of ^standard error^SYS$ERROR^.
9326
9327 @item ^-f^/FORCE_COMPILE^
9328 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9329 Force recompilations. Recompile all sources, even though some object
9330 files may be up to date, but don't recompile predefined or GNAT internal
9331 files or locked files (files with a write-protected ALI file),
9332 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9333
9334 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9335 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9336 When using project files, if some errors or warnings are detected during
9337 parsing and verbose mode is not in effect (no use of switch
9338 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9339 file, rather than its simple file name.
9340
9341 @item ^-g^/DEBUG^
9342 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9343 Enable debugging. This switch is simply passed to the compiler and to the
9344 linker.
9345
9346 @item ^-i^/IN_PLACE^
9347 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9348 In normal mode, @command{gnatmake} compiles all object files and ALI files
9349 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9350 then instead object files and ALI files that already exist are overwritten
9351 in place. This means that once a large project is organized into separate
9352 directories in the desired manner, then @command{gnatmake} will automatically
9353 maintain and update this organization. If no ALI files are found on the
9354 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9355 the new object and ALI files are created in the
9356 directory containing the source being compiled. If another organization
9357 is desired, where objects and sources are kept in different directories,
9358 a useful technique is to create dummy ALI files in the desired directories.
9359 When detecting such a dummy file, @command{gnatmake} will be forced to
9360 recompile the corresponding source file, and it will be put the resulting
9361 object and ALI files in the directory where it found the dummy file.
9362
9363 @item ^-j^/PROCESSES=^@var{n}
9364 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9365 @cindex Parallel make
9366 Use @var{n} processes to carry out the (re)compilations. On a
9367 multiprocessor machine compilations will occur in parallel. In the
9368 event of compilation errors, messages from various compilations might
9369 get interspersed (but @command{gnatmake} will give you the full ordered
9370 list of failing compiles at the end). If this is problematic, rerun
9371 the make process with n set to 1 to get a clean list of messages.
9372
9373 @item ^-k^/CONTINUE_ON_ERROR^
9374 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9375 Keep going. Continue as much as possible after a compilation error. To
9376 ease the programmer's task in case of compilation errors, the list of
9377 sources for which the compile fails is given when @command{gnatmake}
9378 terminates.
9379
9380 If @command{gnatmake} is invoked with several @file{file_names} and with this
9381 switch, if there are compilation errors when building an executable,
9382 @command{gnatmake} will not attempt to build the following executables.
9383
9384 @item ^-l^/ACTIONS=LINK^
9385 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9386 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9387 and linking. Linking will not be performed if combined with
9388 @option{^-c^/ACTIONS=COMPILE^}
9389 but not with @option{^-b^/ACTIONS=BIND^}.
9390 When not combined with @option{^-b^/ACTIONS=BIND^}
9391 all the units in the closure of the main program must have been previously
9392 compiled and must be up to date, and the main program needs to have been bound.
9393 The root unit specified by @var{file_name}
9394 may be given without extension, with the source extension or, if no GNAT
9395 Project File is specified, with the ALI file extension.
9396
9397 @item ^-m^/MINIMAL_RECOMPILATION^
9398 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9399 Specify that the minimum necessary amount of recompilations
9400 be performed. In this mode @command{gnatmake} ignores time
9401 stamp differences when the only
9402 modifications to a source file consist in adding/removing comments,
9403 empty lines, spaces or tabs. This means that if you have changed the
9404 comments in a source file or have simply reformatted it, using this
9405 switch will tell @command{gnatmake} not to recompile files that depend on it
9406 (provided other sources on which these files depend have undergone no
9407 semantic modifications). Note that the debugging information may be
9408 out of date with respect to the sources if the @option{-m} switch causes
9409 a compilation to be switched, so the use of this switch represents a
9410 trade-off between compilation time and accurate debugging information.
9411
9412 @item ^-M^/DEPENDENCIES_LIST^
9413 @cindex Dependencies, producing list
9414 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9415 Check if all objects are up to date. If they are, output the object
9416 dependences to @file{stdout} in a form that can be directly exploited in
9417 a @file{Makefile}. By default, each source file is prefixed with its
9418 (relative or absolute) directory name. This name is whatever you
9419 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9420 and @option{^-I^/SEARCH^} switches. If you use
9421 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9422 @option{^-q^/QUIET^}
9423 (see below), only the source file names,
9424 without relative paths, are output. If you just specify the
9425 @option{^-M^/DEPENDENCIES_LIST^}
9426 switch, dependencies of the GNAT internal system files are omitted. This
9427 is typically what you want. If you also specify
9428 the @option{^-a^/ALL_FILES^} switch,
9429 dependencies of the GNAT internal files are also listed. Note that
9430 dependencies of the objects in external Ada libraries (see switch
9431 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9432 are never reported.
9433
9434 @item ^-n^/DO_OBJECT_CHECK^
9435 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9436 Don't compile, bind, or link. Checks if all objects are up to date.
9437 If they are not, the full name of the first file that needs to be
9438 recompiled is printed.
9439 Repeated use of this option, followed by compiling the indicated source
9440 file, will eventually result in recompiling all required units.
9441
9442 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9443 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9444 Output executable name. The name of the final executable program will be
9445 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9446 name for the executable will be the name of the input file in appropriate form
9447 for an executable file on the host system.
9448
9449 This switch cannot be used when invoking @command{gnatmake} with several
9450 @file{file_names}.
9451
9452 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9453 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9454 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9455 automatically missing object directories, library directories and exec
9456 directories.
9457
9458 @item ^-P^/PROJECT_FILE=^@var{project}
9459 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9460 Use project file @var{project}. Only one such switch can be used.
9461 @xref{gnatmake and Project Files}.
9462
9463 @item ^-q^/QUIET^
9464 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9465 Quiet. When this flag is not set, the commands carried out by
9466 @command{gnatmake} are displayed.
9467
9468 @item ^-s^/SWITCH_CHECK/^
9469 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9470 Recompile if compiler switches have changed since last compilation.
9471 All compiler switches but -I and -o are taken into account in the
9472 following way:
9473 orders between different ``first letter'' switches are ignored, but
9474 orders between same switches are taken into account. For example,
9475 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9476 is equivalent to @option{-O -g}.
9477
9478 This switch is recommended when Integrated Preprocessing is used.
9479
9480 @item ^-u^/UNIQUE^
9481 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9482 Unique. Recompile at most the main files. It implies -c. Combined with
9483 -f, it is equivalent to calling the compiler directly. Note that using
9484 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9485 (@pxref{Project Files and Main Subprograms}).
9486
9487 @item ^-U^/ALL_PROJECTS^
9488 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9489 When used without a project file or with one or several mains on the command
9490 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9491 on the command line, all sources of all project files are checked and compiled
9492 if not up to date, and libraries are rebuilt, if necessary.
9493
9494 @item ^-v^/REASONS^
9495 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9496 Verbose. Display the reason for all recompilations @command{gnatmake}
9497 decides are necessary, with the highest verbosity level.
9498
9499 @item ^-vl^/LOW_VERBOSITY^
9500 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9501 Verbosity level Low. Display fewer lines than in verbosity Medium.
9502
9503 @item ^-vm^/MEDIUM_VERBOSITY^
9504 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9505 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9506
9507 @item ^-vh^/HIGH_VERBOSITY^
9508 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9509 Verbosity level High. Equivalent to ^-v^/REASONS^.
9510
9511 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9512 Indicate the verbosity of the parsing of GNAT project files.
9513 @xref{Switches Related to Project Files}.
9514
9515 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9516 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9517 Indicate that sources that are not part of any Project File may be compiled.
9518 Normally, when using Project Files, only sources that are part of a Project
9519 File may be compile. When this switch is used, a source outside of all Project
9520 Files may be compiled. The ALI file and the object file will be put in the
9521 object directory of the main Project. The compilation switches used will only
9522 be those specified on the command line. Even when
9523 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9524 command line need to be sources of a project file.
9525
9526 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9527 Indicate that external variable @var{name} has the value @var{value}.
9528 The Project Manager will use this value for occurrences of
9529 @code{external(name)} when parsing the project file.
9530 @xref{Switches Related to Project Files}.
9531
9532 @item ^-z^/NOMAIN^
9533 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9534 No main subprogram. Bind and link the program even if the unit name
9535 given on the command line is a package name. The resulting executable
9536 will execute the elaboration routines of the package and its closure,
9537 then the finalization routines.
9538
9539 @end table
9540
9541 @table @asis
9542 @item @command{gcc} @asis{switches}
9543 @ifclear vms
9544 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9545 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9546 @end ifclear
9547 @ifset vms
9548 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9549 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9550 automatically treated as a compiler switch, and passed on to all
9551 compilations that are carried out.
9552 @end ifset
9553 @end table
9554
9555 @noindent
9556 Source and library search path switches:
9557
9558 @table @option
9559 @c !sort!
9560 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9561 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9562 When looking for source files also look in directory @var{dir}.
9563 The order in which source files search is undertaken is
9564 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9565
9566 @item ^-aL^/SKIP_MISSING=^@var{dir}
9567 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9568 Consider @var{dir} as being an externally provided Ada library.
9569 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9570 files have been located in directory @var{dir}. This allows you to have
9571 missing bodies for the units in @var{dir} and to ignore out of date bodies
9572 for the same units. You still need to specify
9573 the location of the specs for these units by using the switches
9574 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9575 or @option{^-I^/SEARCH=^@var{dir}}.
9576 Note: this switch is provided for compatibility with previous versions
9577 of @command{gnatmake}. The easier method of causing standard libraries
9578 to be excluded from consideration is to write-protect the corresponding
9579 ALI files.
9580
9581 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9582 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9583 When searching for library and object files, look in directory
9584 @var{dir}. The order in which library files are searched is described in
9585 @ref{Search Paths for gnatbind}.
9586
9587 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9588 @cindex Search paths, for @command{gnatmake}
9589 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9590 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9591 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9592
9593 @item ^-I^/SEARCH=^@var{dir}
9594 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9595 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9596 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9597
9598 @item ^-I-^/NOCURRENT_DIRECTORY^
9599 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9600 @cindex Source files, suppressing search
9601 Do not look for source files in the directory containing the source
9602 file named in the command line.
9603 Do not look for ALI or object files in the directory
9604 where @command{gnatmake} was invoked.
9605
9606 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9607 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9608 @cindex Linker libraries
9609 Add directory @var{dir} to the list of directories in which the linker
9610 will search for libraries. This is equivalent to
9611 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9612 @ifclear vms
9613 Furthermore, under Windows, the sources pointed to by the libraries path
9614 set in the registry are not searched for.
9615 @end ifclear
9616
9617 @item -nostdinc
9618 @cindex @option{-nostdinc} (@command{gnatmake})
9619 Do not look for source files in the system default directory.
9620
9621 @item -nostdlib
9622 @cindex @option{-nostdlib} (@command{gnatmake})
9623 Do not look for library files in the system default directory.
9624
9625 @item --RTS=@var{rts-path}
9626 @cindex @option{--RTS} (@command{gnatmake})
9627 Specifies the default location of the runtime library. GNAT looks for the
9628 runtime
9629 in the following directories, and stops as soon as a valid runtime is found
9630 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9631 @file{ada_object_path} present):
9632
9633 @itemize @bullet
9634 @item <current directory>/$rts_path
9635
9636 @item <default-search-dir>/$rts_path
9637
9638 @item <default-search-dir>/rts-$rts_path
9639 @end itemize
9640
9641 @noindent
9642 The selected path is handled like a normal RTS path.
9643
9644 @end table
9645
9646 @node Mode Switches for gnatmake
9647 @section Mode Switches for @command{gnatmake}
9648
9649 @noindent
9650 The mode switches (referred to as @code{mode_switches}) allow the
9651 inclusion of switches that are to be passed to the compiler itself, the
9652 binder or the linker. The effect of a mode switch is to cause all
9653 subsequent switches up to the end of the switch list, or up to the next
9654 mode switch, to be interpreted as switches to be passed on to the
9655 designated component of GNAT.
9656
9657 @table @option
9658 @c !sort!
9659 @item -cargs @var{switches}
9660 @cindex @option{-cargs} (@command{gnatmake})
9661 Compiler switches. Here @var{switches} is a list of switches
9662 that are valid switches for @command{gcc}. They will be passed on to
9663 all compile steps performed by @command{gnatmake}.
9664
9665 @item -bargs @var{switches}
9666 @cindex @option{-bargs} (@command{gnatmake})
9667 Binder switches. Here @var{switches} is a list of switches
9668 that are valid switches for @code{gnatbind}. They will be passed on to
9669 all bind steps performed by @command{gnatmake}.
9670
9671 @item -largs @var{switches}
9672 @cindex @option{-largs} (@command{gnatmake})
9673 Linker switches. Here @var{switches} is a list of switches
9674 that are valid switches for @command{gnatlink}. They will be passed on to
9675 all link steps performed by @command{gnatmake}.
9676
9677 @item -margs @var{switches}
9678 @cindex @option{-margs} (@command{gnatmake})
9679 Make switches. The switches are directly interpreted by @command{gnatmake},
9680 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9681 or @option{-largs}.
9682 @end table
9683
9684 @node Notes on the Command Line
9685 @section Notes on the Command Line
9686
9687 @noindent
9688 This section contains some additional useful notes on the operation
9689 of the @command{gnatmake} command.
9690
9691 @itemize @bullet
9692 @item
9693 @cindex Recompilation, by @command{gnatmake}
9694 If @command{gnatmake} finds no ALI files, it recompiles the main program
9695 and all other units required by the main program.
9696 This means that @command{gnatmake}
9697 can be used for the initial compile, as well as during subsequent steps of
9698 the development cycle.
9699
9700 @item
9701 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9702 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9703 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9704 warning.
9705
9706 @item
9707 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9708 is used to specify both source and
9709 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9710 instead if you just want to specify
9711 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9712 if you want to specify library paths
9713 only.
9714
9715 @item
9716 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9717 This may conveniently be used to exclude standard libraries from
9718 consideration and in particular it means that the use of the
9719 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9720 unless @option{^-a^/ALL_FILES^} is also specified.
9721
9722 @item
9723 @command{gnatmake} has been designed to make the use of Ada libraries
9724 particularly convenient. Assume you have an Ada library organized
9725 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9726 of your Ada compilation units,
9727 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9728 specs of these units, but no bodies. Then to compile a unit
9729 stored in @code{main.adb}, which uses this Ada library you would just type
9730
9731 @smallexample
9732 @ifclear vms
9733 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9734 @end ifclear
9735 @ifset vms
9736 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9737            /SKIP_MISSING=@i{[OBJ_DIR]} main
9738 @end ifset
9739 @end smallexample
9740
9741 @item
9742 Using @command{gnatmake} along with the
9743 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9744 switch provides a mechanism for avoiding unnecessary recompilations. Using
9745 this switch,
9746 you can update the comments/format of your
9747 source files without having to recompile everything. Note, however, that
9748 adding or deleting lines in a source files may render its debugging
9749 info obsolete. If the file in question is a spec, the impact is rather
9750 limited, as that debugging info will only be useful during the
9751 elaboration phase of your program. For bodies the impact can be more
9752 significant. In all events, your debugger will warn you if a source file
9753 is more recent than the corresponding object, and alert you to the fact
9754 that the debugging information may be out of date.
9755 @end itemize
9756
9757 @node How gnatmake Works
9758 @section How @command{gnatmake} Works
9759
9760 @noindent
9761 Generally @command{gnatmake} automatically performs all necessary
9762 recompilations and you don't need to worry about how it works. However,
9763 it may be useful to have some basic understanding of the @command{gnatmake}
9764 approach and in particular to understand how it uses the results of
9765 previous compilations without incorrectly depending on them.
9766
9767 First a definition: an object file is considered @dfn{up to date} if the
9768 corresponding ALI file exists and if all the source files listed in the
9769 dependency section of this ALI file have time stamps matching those in
9770 the ALI file. This means that neither the source file itself nor any
9771 files that it depends on have been modified, and hence there is no need
9772 to recompile this file.
9773
9774 @command{gnatmake} works by first checking if the specified main unit is up
9775 to date. If so, no compilations are required for the main unit. If not,
9776 @command{gnatmake} compiles the main program to build a new ALI file that
9777 reflects the latest sources. Then the ALI file of the main unit is
9778 examined to find all the source files on which the main program depends,
9779 and @command{gnatmake} recursively applies the above procedure on all these
9780 files.
9781
9782 This process ensures that @command{gnatmake} only trusts the dependencies
9783 in an existing ALI file if they are known to be correct. Otherwise it
9784 always recompiles to determine a new, guaranteed accurate set of
9785 dependencies. As a result the program is compiled ``upside down'' from what may
9786 be more familiar as the required order of compilation in some other Ada
9787 systems. In particular, clients are compiled before the units on which
9788 they depend. The ability of GNAT to compile in any order is critical in
9789 allowing an order of compilation to be chosen that guarantees that
9790 @command{gnatmake} will recompute a correct set of new dependencies if
9791 necessary.
9792
9793 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9794 imported by several of the executables, it will be recompiled at most once.
9795
9796 Note: when using non-standard naming conventions
9797 (@pxref{Using Other File Names}), changing through a configuration pragmas
9798 file the version of a source and invoking @command{gnatmake} to recompile may
9799 have no effect, if the previous version of the source is still accessible
9800 by @command{gnatmake}. It may be necessary to use the switch
9801 ^-f^/FORCE_COMPILE^.
9802
9803 @node Examples of gnatmake Usage
9804 @section Examples of @command{gnatmake} Usage
9805
9806 @table @code
9807 @item gnatmake hello.adb
9808 Compile all files necessary to bind and link the main program
9809 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9810 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9811
9812 @item gnatmake main1 main2 main3
9813 Compile all files necessary to bind and link the main programs
9814 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9815 (containing unit @code{Main2}) and @file{main3.adb}
9816 (containing unit @code{Main3}) and bind and link the resulting object files
9817 to generate three executable files @file{^main1^MAIN1.EXE^},
9818 @file{^main2^MAIN2.EXE^}
9819 and @file{^main3^MAIN3.EXE^}.
9820
9821 @ifclear vms
9822 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9823 @end ifclear
9824
9825 @ifset vms
9826 @item gnatmake Main_Unit /QUIET
9827 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9828 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9829 @end ifset
9830 Compile all files necessary to bind and link the main program unit
9831 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9832 be done with optimization level 2 and the order of elaboration will be
9833 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9834 displaying commands it is executing.
9835 @end table
9836
9837 @c *************************
9838 @node Improving Performance
9839 @chapter Improving Performance
9840 @cindex Improving performance
9841
9842 @noindent
9843 This chapter presents several topics related to program performance.
9844 It first describes some of the tradeoffs that need to be considered
9845 and some of the techniques for making your program run faster.
9846 It then documents the @command{gnatelim} tool and unused subprogram/data
9847 elimination feature, which can reduce the size of program executables.
9848
9849 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
9850 driver (see @ref{The GNAT Driver and Project Files}).
9851
9852 @ifnottex
9853 @menu
9854 * Performance Considerations::
9855 * Text_IO Suggestions::
9856 * Reducing Size of Ada Executables with gnatelim::
9857 * Reducing Size of Executables with unused subprogram/data elimination::
9858 @end menu
9859 @end ifnottex
9860
9861 @c *****************************
9862 @node Performance Considerations
9863 @section Performance Considerations
9864
9865 @noindent
9866 The GNAT system provides a number of options that allow a trade-off
9867 between
9868
9869 @itemize @bullet
9870 @item
9871 performance of the generated code
9872
9873 @item
9874 speed of compilation
9875
9876 @item
9877 minimization of dependences and recompilation
9878
9879 @item
9880 the degree of run-time checking.
9881 @end itemize
9882
9883 @noindent
9884 The defaults (if no options are selected) aim at improving the speed
9885 of compilation and minimizing dependences, at the expense of performance
9886 of the generated code:
9887
9888 @itemize @bullet
9889 @item
9890 no optimization
9891
9892 @item
9893 no inlining of subprogram calls
9894
9895 @item
9896 all run-time checks enabled except overflow and elaboration checks
9897 @end itemize
9898
9899 @noindent
9900 These options are suitable for most program development purposes. This
9901 chapter describes how you can modify these choices, and also provides
9902 some guidelines on debugging optimized code.
9903
9904 @menu
9905 * Controlling Run-Time Checks::
9906 * Use of Restrictions::
9907 * Optimization Levels::
9908 * Debugging Optimized Code::
9909 * Inlining of Subprograms::
9910 * Other Optimization Switches::
9911 * Optimization and Strict Aliasing::
9912
9913 @ifset vms
9914 * Coverage Analysis::
9915 @end ifset
9916 @end menu
9917
9918 @node Controlling Run-Time Checks
9919 @subsection Controlling Run-Time Checks
9920
9921 @noindent
9922 By default, GNAT generates all run-time checks, except integer overflow
9923 checks, stack overflow checks, and checks for access before elaboration on
9924 subprogram calls. The latter are not required in default mode, because all
9925 necessary checking is done at compile time.
9926 @cindex @option{-gnatp} (@command{gcc})
9927 @cindex @option{-gnato} (@command{gcc})
9928 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
9929 be modified. @xref{Run-Time Checks}.
9930
9931 Our experience is that the default is suitable for most development
9932 purposes.
9933
9934 We treat integer overflow specially because these
9935 are quite expensive and in our experience are not as important as other
9936 run-time checks in the development process. Note that division by zero
9937 is not considered an overflow check, and divide by zero checks are
9938 generated where required by default.
9939
9940 Elaboration checks are off by default, and also not needed by default, since
9941 GNAT uses a static elaboration analysis approach that avoids the need for
9942 run-time checking. This manual contains a full chapter discussing the issue
9943 of elaboration checks, and if the default is not satisfactory for your use,
9944 you should read this chapter.
9945
9946 For validity checks, the minimal checks required by the Ada Reference
9947 Manual (for case statements and assignments to array elements) are on
9948 by default. These can be suppressed by use of the @option{-gnatVn} switch.
9949 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
9950 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
9951 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
9952 are also suppressed entirely if @option{-gnatp} is used.
9953
9954 @cindex Overflow checks
9955 @cindex Checks, overflow
9956 @findex Suppress
9957 @findex Unsuppress
9958 @cindex pragma Suppress
9959 @cindex pragma Unsuppress
9960 Note that the setting of the switches controls the default setting of
9961 the checks. They may be modified using either @code{pragma Suppress} (to
9962 remove checks) or @code{pragma Unsuppress} (to add back suppressed
9963 checks) in the program source.
9964
9965 @node Use of Restrictions
9966 @subsection Use of Restrictions
9967
9968 @noindent
9969 The use of pragma Restrictions allows you to control which features are
9970 permitted in your program. Apart from the obvious point that if you avoid
9971 relatively expensive features like finalization (enforceable by the use
9972 of pragma Restrictions (No_Finalization), the use of this pragma does not
9973 affect the generated code in most cases.
9974
9975 One notable exception to this rule is that the possibility of task abort
9976 results in some distributed overhead, particularly if finalization or
9977 exception handlers are used. The reason is that certain sections of code
9978 have to be marked as non-abortable.
9979
9980 If you use neither the @code{abort} statement, nor asynchronous transfer
9981 of control (@code{select @dots{} then abort}), then this distributed overhead
9982 is removed, which may have a general positive effect in improving
9983 overall performance.  Especially code involving frequent use of tasking
9984 constructs and controlled types will show much improved performance.
9985 The relevant restrictions pragmas are
9986
9987 @smallexample @c ada
9988    pragma Restrictions (No_Abort_Statements);
9989    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9990 @end smallexample
9991
9992 @noindent
9993 It is recommended that these restriction pragmas be used if possible. Note
9994 that this also means that you can write code without worrying about the
9995 possibility of an immediate abort at any point.
9996
9997 @node Optimization Levels
9998 @subsection Optimization Levels
9999 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10000
10001 @noindent
10002 Without any optimization ^option,^qualifier,^
10003 the compiler's goal is to reduce the cost of
10004 compilation and to make debugging produce the expected results.
10005 Statements are independent: if you stop the program with a breakpoint between
10006 statements, you can then assign a new value to any variable or change
10007 the program counter to any other statement in the subprogram and get exactly
10008 the results you would expect from the source code.
10009
10010 Turning on optimization makes the compiler attempt to improve the
10011 performance and/or code size at the expense of compilation time and
10012 possibly the ability to debug the program.
10013
10014 If you use multiple
10015 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10016 the last such option is the one that is effective.
10017
10018 @noindent
10019 The default is optimization off. This results in the fastest compile
10020 times, but GNAT makes absolutely no attempt to optimize, and the
10021 generated programs are considerably larger and slower than when
10022 optimization is enabled. You can use the
10023 @ifclear vms
10024 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10025 @option{-O2}, @option{-O3}, and @option{-Os})
10026 @end ifclear
10027 @ifset vms
10028 @code{OPTIMIZE} qualifier
10029 @end ifset
10030 to @command{gcc} to control the optimization level:
10031
10032 @table @option
10033 @item ^-O0^/OPTIMIZE=NONE^
10034 No optimization (the default);
10035 generates unoptimized code but has
10036 the fastest compilation time.
10037
10038 Note that many other compilers do fairly extensive optimization
10039 even if ``no optimization'' is specified. With gcc, it is
10040 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10041 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10042 really does mean no optimization at all. This difference between
10043 gcc and other compilers should be kept in mind when doing
10044 performance comparisons.
10045
10046 @item ^-O1^/OPTIMIZE=SOME^
10047 Moderate optimization;
10048 optimizes reasonably well but does not
10049 degrade compilation time significantly.
10050
10051 @item ^-O2^/OPTIMIZE=ALL^
10052 @ifset vms
10053 @itemx /OPTIMIZE=DEVELOPMENT
10054 @end ifset
10055 Full optimization;
10056 generates highly optimized code and has
10057 the slowest compilation time.
10058
10059 @item ^-O3^/OPTIMIZE=INLINING^
10060 Full optimization as in @option{-O2},
10061 and also attempts automatic inlining of small
10062 subprograms within a unit (@pxref{Inlining of Subprograms}).
10063
10064 @item ^-Os^/OPTIMIZE=SPACE^
10065 Optimize space usage of resulting program.
10066 @end table
10067
10068 @noindent
10069 Higher optimization levels perform more global transformations on the
10070 program and apply more expensive analysis algorithms in order to generate
10071 faster and more compact code. The price in compilation time, and the
10072 resulting improvement in execution time,
10073 both depend on the particular application and the hardware environment.
10074 You should experiment to find the best level for your application.
10075
10076 Since the precise set of optimizations done at each level will vary from
10077 release to release (and sometime from target to target), it is best to think
10078 of the optimization settings in general terms.
10079 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10080 the GNU Compiler Collection (GCC)}, for details about
10081 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10082 individually enable or disable specific optimizations.
10083
10084 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10085 been tested extensively at all optimization levels. There are some bugs
10086 which appear only with optimization turned on, but there have also been
10087 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10088 level of optimization does not improve the reliability of the code
10089 generator, which in practice is highly reliable at all optimization
10090 levels.
10091
10092 Note regarding the use of @option{-O3}: The use of this optimization level
10093 is generally discouraged with GNAT, since it often results in larger
10094 executables which run more slowly. See further discussion of this point
10095 in @ref{Inlining of Subprograms}.
10096
10097 @node Debugging Optimized Code
10098 @subsection Debugging Optimized Code
10099 @cindex Debugging optimized code
10100 @cindex Optimization and debugging
10101
10102 @noindent
10103 Although it is possible to do a reasonable amount of debugging at
10104 @ifclear vms
10105 nonzero optimization levels,
10106 the higher the level the more likely that
10107 @end ifclear
10108 @ifset vms
10109 @option{/OPTIMIZE} settings other than @code{NONE},
10110 such settings will make it more likely that
10111 @end ifset
10112 source-level constructs will have been eliminated by optimization.
10113 For example, if a loop is strength-reduced, the loop
10114 control variable may be completely eliminated and thus cannot be
10115 displayed in the debugger.
10116 This can only happen at @option{-O2} or @option{-O3}.
10117 Explicit temporary variables that you code might be eliminated at
10118 ^level^setting^ @option{-O1} or higher.
10119
10120 The use of the @option{^-g^/DEBUG^} switch,
10121 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10122 which is needed for source-level debugging,
10123 affects the size of the program executable on disk,
10124 and indeed the debugging information can be quite large.
10125 However, it has no effect on the generated code (and thus does not
10126 degrade performance)
10127
10128 Since the compiler generates debugging tables for a compilation unit before
10129 it performs optimizations, the optimizing transformations may invalidate some
10130 of the debugging data.  You therefore need to anticipate certain
10131 anomalous situations that may arise while debugging optimized code.
10132 These are the most common cases:
10133
10134 @enumerate
10135 @item
10136 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10137 commands show
10138 the PC bouncing back and forth in the code.  This may result from any of
10139 the following optimizations:
10140
10141 @itemize @bullet
10142 @item
10143 @i{Common subexpression elimination:} using a single instance of code for a
10144 quantity that the source computes several times.  As a result you
10145 may not be able to stop on what looks like a statement.
10146
10147 @item
10148 @i{Invariant code motion:} moving an expression that does not change within a
10149 loop, to the beginning of the loop.
10150
10151 @item
10152 @i{Instruction scheduling:} moving instructions so as to
10153 overlap loads and stores (typically) with other code, or in
10154 general to move computations of values closer to their uses. Often
10155 this causes you to pass an assignment statement without the assignment
10156 happening and then later bounce back to the statement when the
10157 value is actually needed.  Placing a breakpoint on a line of code
10158 and then stepping over it may, therefore, not always cause all the
10159 expected side-effects.
10160 @end itemize
10161
10162 @item
10163 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10164 two identical pieces of code are merged and the program counter suddenly
10165 jumps to a statement that is not supposed to be executed, simply because
10166 it (and the code following) translates to the same thing as the code
10167 that @emph{was} supposed to be executed.  This effect is typically seen in
10168 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10169 a @code{break} in a C @code{^switch^switch^} statement.
10170
10171 @item
10172 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10173 There are various reasons for this effect:
10174
10175 @itemize @bullet
10176 @item
10177 In a subprogram prologue, a parameter may not yet have been moved to its
10178 ``home''.
10179
10180 @item
10181 A variable may be dead, and its register re-used.  This is
10182 probably the most common cause.
10183
10184 @item
10185 As mentioned above, the assignment of a value to a variable may
10186 have been moved.
10187
10188 @item
10189 A variable may be eliminated entirely by value propagation or
10190 other means.  In this case, GCC may incorrectly generate debugging
10191 information for the variable
10192 @end itemize
10193
10194 @noindent
10195 In general, when an unexpected value appears for a local variable or parameter
10196 you should first ascertain if that value was actually computed by
10197 your program, as opposed to being incorrectly reported by the debugger.
10198 Record fields or
10199 array elements in an object designated by an access value
10200 are generally less of a problem, once you have ascertained that the access
10201 value is sensible.
10202 Typically, this means checking variables in the preceding code and in the
10203 calling subprogram to verify that the value observed is explainable from other
10204 values (one must apply the procedure recursively to those
10205 other values); or re-running the code and stopping a little earlier
10206 (perhaps before the call) and stepping to better see how the variable obtained
10207 the value in question; or continuing to step @emph{from} the point of the
10208 strange value to see if code motion had simply moved the variable's
10209 assignments later.
10210 @end enumerate
10211
10212 @noindent
10213 In light of such anomalies, a recommended technique is to use @option{-O0}
10214 early in the software development cycle, when extensive debugging capabilities
10215 are most needed, and then move to @option{-O1} and later @option{-O2} as
10216 the debugger becomes less critical.
10217 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10218 a release management issue.
10219 @ifclear vms
10220 Note that if you use @option{-g} you can then use the @command{strip} program
10221 on the resulting executable,
10222 which removes both debugging information and global symbols.
10223 @end ifclear
10224
10225 @node Inlining of Subprograms
10226 @subsection Inlining of Subprograms
10227
10228 @noindent
10229 A call to a subprogram in the current unit is inlined if all the
10230 following conditions are met:
10231
10232 @itemize @bullet
10233 @item
10234 The optimization level is at least @option{-O1}.
10235
10236 @item
10237 The called subprogram is suitable for inlining: It must be small enough
10238 and not contain something that @command{gcc} cannot support in inlined
10239 subprograms.
10240
10241 @item
10242 @cindex pragma Inline
10243 @findex Inline
10244 Either @code{pragma Inline} applies to the subprogram, or it is local
10245 to the unit and called once from within it, or it is small and automatic
10246 inlining (optimization level @option{-O3}) is specified.
10247 @end itemize
10248
10249 @noindent
10250 Calls to subprograms in @code{with}'ed units are normally not inlined.
10251 To achieve actual inlining (that is, replacement of the call by the code
10252 in the body of the subprogram), the following conditions must all be true.
10253
10254 @itemize @bullet
10255 @item
10256 The optimization level is at least @option{-O1}.
10257
10258 @item
10259 The called subprogram is suitable for inlining: It must be small enough
10260 and not contain something that @command{gcc} cannot support in inlined
10261 subprograms.
10262
10263 @item
10264 The call appears in a body (not in a package spec).
10265
10266 @item
10267 There is a @code{pragma Inline} for the subprogram.
10268
10269 @item
10270 @cindex @option{-gnatn} (@command{gcc})
10271 The @option{^-gnatn^/INLINE^} switch
10272 is used in the @command{gcc} command line
10273 @end itemize
10274
10275 Even if all these conditions are met, it may not be possible for
10276 the compiler to inline the call, due to the length of the body,
10277 or features in the body that make it impossible for the compiler
10278 to do the inlining.
10279
10280 Note that specifying the @option{-gnatn} switch causes additional
10281 compilation dependencies. Consider the following:
10282
10283 @smallexample @c ada
10284 @cartouche
10285 package R is
10286    procedure Q;
10287    pragma Inline (Q);
10288 end R;
10289 package body R is
10290    @dots{}
10291 end R;
10292
10293 with R;
10294 procedure Main is
10295 begin
10296    @dots{}
10297    R.Q;
10298 end Main;
10299 @end cartouche
10300 @end smallexample
10301
10302 @noindent
10303 With the default behavior (no @option{-gnatn} switch specified), the
10304 compilation of the @code{Main} procedure depends only on its own source,
10305 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10306 means that editing the body of @code{R} does not require recompiling
10307 @code{Main}.
10308
10309 On the other hand, the call @code{R.Q} is not inlined under these
10310 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10311 is compiled, the call will be inlined if the body of @code{Q} is small
10312 enough, but now @code{Main} depends on the body of @code{R} in
10313 @file{r.adb} as well as on the spec. This means that if this body is edited,
10314 the main program must be recompiled. Note that this extra dependency
10315 occurs whether or not the call is in fact inlined by @command{gcc}.
10316
10317 The use of front end inlining with @option{-gnatN} generates similar
10318 additional dependencies.
10319
10320 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10321 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10322 can be used to prevent
10323 all inlining. This switch overrides all other conditions and ensures
10324 that no inlining occurs. The extra dependences resulting from
10325 @option{-gnatn} will still be active, even if
10326 this switch is used to suppress the resulting inlining actions.
10327
10328 @cindex @option{-fno-inline-functions} (@command{gcc})
10329 Note: The @option{-fno-inline-functions} switch can be used to prevent
10330 automatic inlining of small subprograms if @option{-O3} is used.
10331
10332 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10333 Note: The @option{-fno-inline-functions-called-once} switch
10334 can be used to prevent inlining of subprograms local to the unit
10335 and called once from within it if @option{-O1} is used.
10336
10337 Note regarding the use of @option{-O3}: There is no difference in inlining
10338 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
10339 pragma @code{Inline} assuming the use of @option{-gnatn}
10340 or @option{-gnatN} (the switches that activate inlining). If you have used
10341 pragma @code{Inline} in appropriate cases, then it is usually much better
10342 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
10343 in this case only has the effect of inlining subprograms you did not
10344 think should be inlined. We often find that the use of @option{-O3} slows
10345 down code by performing excessive inlining, leading to increased instruction
10346 cache pressure from the increased code size. So the bottom line here is
10347 that you should not automatically assume that @option{-O3} is better than
10348 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
10349 it actually improves performance.
10350
10351 @node Other Optimization Switches
10352 @subsection Other Optimization Switches
10353 @cindex Optimization Switches
10354
10355 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10356 @command{gcc} optimization switches are potentially usable. These switches
10357 have not been extensively tested with GNAT but can generally be expected
10358 to work. Examples of switches in this category are
10359 @option{-funroll-loops} and
10360 the various target-specific @option{-m} options (in particular, it has been
10361 observed that @option{-march=pentium4} can significantly improve performance
10362 on appropriate machines). For full details of these switches, see
10363 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10364 the GNU Compiler Collection (GCC)}.
10365
10366 @node Optimization and Strict Aliasing
10367 @subsection Optimization and Strict Aliasing
10368 @cindex Aliasing
10369 @cindex Strict Aliasing
10370 @cindex No_Strict_Aliasing
10371
10372 @noindent
10373 The strong typing capabilities of Ada allow an optimizer to generate
10374 efficient code in situations where other languages would be forced to
10375 make worst case assumptions preventing such optimizations. Consider
10376 the following example:
10377
10378 @smallexample @c ada
10379 @cartouche
10380 procedure R is
10381    type Int1 is new Integer;
10382    type Int2 is new Integer;
10383    type Int1A is access Int1;
10384    type Int2A is access Int2;
10385    Int1V : Int1A;
10386    Int2V : Int2A;
10387    @dots{}
10388
10389 begin
10390    @dots{}
10391    for J in Data'Range loop
10392       if Data (J) = Int1V.all then
10393          Int2V.all := Int2V.all + 1;
10394       end if;
10395    end loop;
10396    @dots{}
10397 end R;
10398 @end cartouche
10399 @end smallexample
10400
10401 @noindent
10402 In this example, since the variable @code{Int1V} can only access objects
10403 of type @code{Int1}, and @code{Int2V} can only access objects of type
10404 @code{Int2}, there is no possibility that the assignment to
10405 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10406 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10407 for all iterations of the loop and avoid the extra memory reference
10408 required to dereference it each time through the loop.
10409
10410 This kind of optimization, called strict aliasing analysis, is
10411 triggered by specifying an optimization level of @option{-O2} or
10412 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10413 when access values are involved.
10414
10415 However, although this optimization is always correct in terms of
10416 the formal semantics of the Ada Reference Manual, difficulties can
10417 arise if features like @code{Unchecked_Conversion} are used to break
10418 the typing system. Consider the following complete program example:
10419
10420 @smallexample @c ada
10421 @cartouche
10422 package p1 is
10423    type int1 is new integer;
10424    type int2 is new integer;
10425    type a1 is access int1;
10426    type a2 is access int2;
10427 end p1;
10428
10429 with p1; use p1;
10430 package p2 is
10431    function to_a2 (Input : a1) return a2;
10432 end p2;
10433
10434 with Unchecked_Conversion;
10435 package body p2 is
10436    function to_a2 (Input : a1) return a2 is
10437       function to_a2u is
10438         new Unchecked_Conversion (a1, a2);
10439    begin
10440       return to_a2u (Input);
10441    end to_a2;
10442 end p2;
10443
10444 with p2; use p2;
10445 with p1; use p1;
10446 with Text_IO; use Text_IO;
10447 procedure m is
10448    v1 : a1 := new int1;
10449    v2 : a2 := to_a2 (v1);
10450 begin
10451    v1.all := 1;
10452    v2.all := 0;
10453    put_line (int1'image (v1.all));
10454 end;
10455 @end cartouche
10456 @end smallexample
10457
10458 @noindent
10459 This program prints out 0 in @option{-O0} or @option{-O1}
10460 mode, but it prints out 1 in @option{-O2} mode. That's
10461 because in strict aliasing mode, the compiler can and
10462 does assume that the assignment to @code{v2.all} could not
10463 affect the value of @code{v1.all}, since different types
10464 are involved.
10465
10466 This behavior is not a case of non-conformance with the standard, since
10467 the Ada RM specifies that an unchecked conversion where the resulting
10468 bit pattern is not a correct value of the target type can result in an
10469 abnormal value and attempting to reference an abnormal value makes the
10470 execution of a program erroneous.  That's the case here since the result
10471 does not point to an object of type @code{int2}.  This means that the
10472 effect is entirely unpredictable.
10473
10474 However, although that explanation may satisfy a language
10475 lawyer, in practice an applications programmer expects an
10476 unchecked conversion involving pointers to create true
10477 aliases and the behavior of printing 1 seems plain wrong.
10478 In this case, the strict aliasing optimization is unwelcome.
10479
10480 Indeed the compiler recognizes this possibility, and the
10481 unchecked conversion generates a warning:
10482
10483 @smallexample
10484 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10485 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10486 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10487 @end smallexample
10488
10489 @noindent
10490 Unfortunately the problem is recognized when compiling the body of
10491 package @code{p2}, but the actual "bad" code is generated while
10492 compiling the body of @code{m} and this latter compilation does not see
10493 the suspicious @code{Unchecked_Conversion}.
10494
10495 As implied by the warning message, there are approaches you can use to
10496 avoid the unwanted strict aliasing optimization in a case like this.
10497
10498 One possibility is to simply avoid the use of @option{-O2}, but
10499 that is a bit drastic, since it throws away a number of useful
10500 optimizations that do not involve strict aliasing assumptions.
10501
10502 A less drastic approach is to compile the program using the
10503 option @option{-fno-strict-aliasing}. Actually it is only the
10504 unit containing the dereferencing of the suspicious pointer
10505 that needs to be compiled. So in this case, if we compile
10506 unit @code{m} with this switch, then we get the expected
10507 value of zero printed. Analyzing which units might need
10508 the switch can be painful, so a more reasonable approach
10509 is to compile the entire program with options @option{-O2}
10510 and @option{-fno-strict-aliasing}. If the performance is
10511 satisfactory with this combination of options, then the
10512 advantage is that the entire issue of possible "wrong"
10513 optimization due to strict aliasing is avoided.
10514
10515 To avoid the use of compiler switches, the configuration
10516 pragma @code{No_Strict_Aliasing} with no parameters may be
10517 used to specify that for all access types, the strict
10518 aliasing optimization should be suppressed.
10519
10520 However, these approaches are still overkill, in that they causes
10521 all manipulations of all access values to be deoptimized. A more
10522 refined approach is to concentrate attention on the specific
10523 access type identified as problematic.
10524
10525 First, if a careful analysis of uses of the pointer shows
10526 that there are no possible problematic references, then
10527 the warning can be suppressed by bracketing the
10528 instantiation of @code{Unchecked_Conversion} to turn
10529 the warning off:
10530
10531 @smallexample @c ada
10532    pragma Warnings (Off);
10533    function to_a2u is
10534      new Unchecked_Conversion (a1, a2);
10535    pragma Warnings (On);
10536 @end smallexample
10537
10538 @noindent
10539 Of course that approach is not appropriate for this particular
10540 example, since indeed there is a problematic reference. In this
10541 case we can take one of two other approaches.
10542
10543 The first possibility is to move the instantiation of unchecked
10544 conversion to the unit in which the type is declared. In
10545 this example, we would move the instantiation of
10546 @code{Unchecked_Conversion} from the body of package
10547 @code{p2} to the spec of package @code{p1}. Now the
10548 warning disappears. That's because any use of the
10549 access type knows there is a suspicious unchecked
10550 conversion, and the strict aliasing optimization
10551 is automatically suppressed for the type.
10552
10553 If it is not practical to move the unchecked conversion to the same unit
10554 in which the destination access type is declared (perhaps because the
10555 source type is not visible in that unit), you may use pragma
10556 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10557 same declarative sequence as the declaration of the access type:
10558
10559 @smallexample @c ada
10560    type a2 is access int2;
10561    pragma No_Strict_Aliasing (a2);
10562 @end smallexample
10563
10564 @noindent
10565 Here again, the compiler now knows that the strict aliasing optimization
10566 should be suppressed for any reference to type @code{a2} and the
10567 expected behavior is obtained.
10568
10569 Finally, note that although the compiler can generate warnings for
10570 simple cases of unchecked conversions, there are tricker and more
10571 indirect ways of creating type incorrect aliases which the compiler
10572 cannot detect. Examples are the use of address overlays and unchecked
10573 conversions involving composite types containing access types as
10574 components. In such cases, no warnings are generated, but there can
10575 still be aliasing problems. One safe coding practice is to forbid the
10576 use of address clauses for type overlaying, and to allow unchecked
10577 conversion only for primitive types. This is not really a significant
10578 restriction since any possible desired effect can be achieved by
10579 unchecked conversion of access values.
10580
10581 The aliasing analysis done in strict aliasing mode can certainly
10582 have significant benefits. We have seen cases of large scale
10583 application code where the time is increased by up to 5% by turning
10584 this optimization off. If you have code that includes significant
10585 usage of unchecked conversion, you might want to just stick with
10586 @option{-O1} and avoid the entire issue. If you get adequate
10587 performance at this level of optimization level, that's probably
10588 the safest approach. If tests show that you really need higher
10589 levels of optimization, then you can experiment with @option{-O2}
10590 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10591 has on size and speed of the code. If you really need to use
10592 @option{-O2} with strict aliasing in effect, then you should
10593 review any uses of unchecked conversion of access types,
10594 particularly if you are getting the warnings described above.
10595
10596 @ifset vms
10597 @node Coverage Analysis
10598 @subsection Coverage Analysis
10599
10600 @noindent
10601 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10602 the user to determine the distribution of execution time across a program,
10603 @pxref{Profiling} for details of usage.
10604 @end ifset
10605
10606
10607 @node Text_IO Suggestions
10608 @section @code{Text_IO} Suggestions
10609 @cindex @code{Text_IO} and performance
10610
10611 @noindent
10612 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10613 the requirement of maintaining page and line counts. If performance
10614 is critical, a recommendation is to use @code{Stream_IO} instead of
10615 @code{Text_IO} for volume output, since this package has less overhead.
10616
10617 If @code{Text_IO} must be used, note that by default output to the standard
10618 output and standard error files is unbuffered (this provides better
10619 behavior when output statements are used for debugging, or if the
10620 progress of a program is observed by tracking the output, e.g. by
10621 using the Unix @command{tail -f} command to watch redirected output.
10622
10623 If you are generating large volumes of output with @code{Text_IO} and
10624 performance is an important factor, use a designated file instead
10625 of the standard output file, or change the standard output file to
10626 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10627
10628
10629
10630 @node Reducing Size of Ada Executables with gnatelim
10631 @section Reducing Size of Ada Executables with @code{gnatelim}
10632 @findex gnatelim
10633
10634 @noindent
10635 This section describes @command{gnatelim}, a tool which detects unused
10636 subprograms and helps the compiler to create a smaller executable for your
10637 program.
10638
10639 @menu
10640 * About gnatelim::
10641 * Running gnatelim::
10642 * Processing Precompiled Libraries::
10643 * Correcting the List of Eliminate Pragmas::
10644 * Making Your Executables Smaller::
10645 * Summary of the gnatelim Usage Cycle::
10646 @end menu
10647
10648 @node About gnatelim
10649 @subsection About @code{gnatelim}
10650
10651 @noindent
10652 When a program shares a set of Ada
10653 packages with other programs, it may happen that this program uses
10654 only a fraction of the subprograms defined in these packages. The code
10655 created for these unused subprograms increases the size of the executable.
10656
10657 @code{gnatelim} tracks unused subprograms in an Ada program and
10658 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10659 subprograms that are declared but never called. By placing the list of
10660 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10661 recompiling your program, you may decrease the size of its executable,
10662 because the compiler will not generate the code for 'eliminated' subprograms.
10663 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10664 information about this pragma.
10665
10666 @code{gnatelim} needs as its input data the name of the main subprogram.
10667
10668 If a set of source files is specified as @code{gnatelim} arguments, it
10669 treats these files as a complete set of sources making up a program to
10670 analyse, and analyses only these sources.
10671
10672 After a full successful build of the main subprogram @code{gnatelim} can be
10673 called without  specifying sources to analyse, in this case it computes
10674 the source closure of the main unit from the @file{ALI} files.
10675
10676 The following command will create the set of @file{ALI} files needed for
10677 @code{gnatelim}:
10678
10679 @smallexample
10680 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10681 @end smallexample
10682
10683 Note that @code{gnatelim} does not need object files.
10684
10685 @node Running gnatelim
10686 @subsection Running @code{gnatelim}
10687
10688 @noindent
10689 @code{gnatelim} has the following command-line interface:
10690
10691 @smallexample
10692 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
10693 @end smallexample
10694
10695 @noindent
10696 @var{main_unit_name} should be a name of a source file that contains the main
10697 subprogram of a program (partition).
10698
10699 Each @var{filename} is the name (including the extension) of a source
10700 file to process. ``Wildcards'' are allowed, and
10701 the file name may contain path information.
10702
10703 @samp{@var{gcc_switches}} is a list of switches for
10704 @command{gcc}. They will be passed on to all compiler invocations made by
10705 @command{gnatelim} to generate the ASIS trees. Here you can provide
10706 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
10707 use the @option{-gnatec} switch to set the configuration file etc.
10708
10709 @code{gnatelim} has the following switches:
10710
10711 @table @option
10712 @c !sort!
10713 @item ^-files^/FILES^=@var{filename}
10714 @cindex @option{^-files^/FILES^} (@code{gnatelim})
10715 Take the argument source files from the specified file. This file should be an
10716 ordinary text file containing file names separated by spaces or
10717 line breaks. You can use this switch more than once in the same call to
10718 @command{gnatelim}. You also can combine this switch with
10719 an explicit list of files.
10720
10721 @item ^-log^/LOG^
10722 @cindex @option{^-log^/LOG^} (@command{gnatelim})
10723 Duplicate all the output sent to @file{stderr} into a log file. The log file
10724 is named @file{gnatelim.log} and is located in the current directory.
10725
10726 @item ^-log^/LOGFILE^=@var{filename}
10727 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
10728 Duplicate all the output sent to @file{stderr} into a specified log file.
10729
10730 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
10731 @item ^--no-elim-dispatch^/NO_DISPATCH^
10732 Do not generate pragmas for dispatching operations.
10733
10734 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
10735 @item ^-o^/OUTPUT^=@var{report_file}
10736 Put @command{gnatelim} output into a specified file. If this file already exists,
10737 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
10738 into @file{stderr}
10739
10740 @item ^-q^/QUIET^
10741 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
10742 Quiet mode: by default @code{gnatelim} outputs to the standard error
10743 stream the number of program units left to be processed. This option turns
10744 this trace off.
10745
10746 @cindex @option{^-t^/TIME^} (@command{gnatelim})
10747 @item ^-t^/TIME^
10748 Print out execution time.
10749
10750 @item ^-v^/VERBOSE^
10751 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
10752 Verbose mode: @code{gnatelim} version information is printed as Ada
10753 comments to the standard output stream. Also, in addition to the number of
10754 program units left @code{gnatelim} will output the name of the current unit
10755 being processed.
10756
10757 @item ^-wq^/WARNINGS=QUIET^
10758 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
10759 Quet warning mode - some warnings are suppressed. In particular warnings that
10760 indicate that the analysed set of sources is incomplete to make up a
10761 partition and that some subprogram bodies are missing are not generated.
10762 @end table
10763
10764 @node Processing Precompiled Libraries
10765 @subsection Processing Precompiled Libraries
10766
10767 @noindent
10768 If some program uses a precompiled Ada library, it can be processed by
10769 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
10770 Eliminate pragma for a subprogram if the body of this subprogram has not
10771 been analysed, this is a typical case for subprograms from precompiled
10772 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
10773 warnings about missing source files and non-analyzed subprogram bodies
10774 that can be generated when processing precompiled Ada libraries.
10775
10776 @node Correcting the List of Eliminate Pragmas
10777 @subsection Correcting the List of Eliminate Pragmas
10778
10779 @noindent
10780 In some rare cases @code{gnatelim} may try to eliminate
10781 subprograms that are actually called in the program. In this case, the
10782 compiler will generate an error message of the form:
10783
10784 @smallexample
10785 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
10786 @end smallexample
10787
10788 @noindent
10789 You will need to manually remove the wrong @code{Eliminate} pragmas from
10790 the configuration file indicated in the error message. You should recompile
10791 your program from scratch after that, because you need a consistent
10792 configuration file(s) during the entire compilation.
10793
10794 @node Making Your Executables Smaller
10795 @subsection Making Your Executables Smaller
10796
10797 @noindent
10798 In order to get a smaller executable for your program you now have to
10799 recompile the program completely with the configuration file containing
10800 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
10801 @file{gnat.adc} file located in your current directory, just do:
10802
10803 @smallexample
10804 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10805 @end smallexample
10806
10807 @noindent
10808 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
10809 recompile everything
10810 with the set of pragmas @code{Eliminate} that you have obtained with
10811 @command{gnatelim}).
10812
10813 Be aware that the set of @code{Eliminate} pragmas is specific to each
10814 program. It is not recommended to merge sets of @code{Eliminate}
10815 pragmas created for different programs in one configuration file.
10816
10817 @node Summary of the gnatelim Usage Cycle
10818 @subsection Summary of the @code{gnatelim} Usage Cycle
10819
10820 @noindent
10821 Here is a quick summary of the steps to be taken in order to reduce
10822 the size of your executables with @code{gnatelim}. You may use
10823 other GNAT options to control the optimization level,
10824 to produce the debugging information, to set search path, etc.
10825
10826 @enumerate
10827 @item
10828 Create a complete set of @file{ALI} files (if the program has not been
10829 built already)
10830
10831 @smallexample
10832 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
10833 @end smallexample
10834
10835 @item
10836 Generate a list of @code{Eliminate} pragmas in default configuration file
10837 @file{gnat.adc} in the current directory
10838 @smallexample
10839 @ifset vms
10840 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
10841 @end ifset
10842 @ifclear vms
10843 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
10844 @end ifclear
10845 @end smallexample
10846
10847 @item
10848 Recompile the application
10849
10850 @smallexample
10851 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
10852 @end smallexample
10853
10854 @end enumerate
10855
10856 @node Reducing Size of Executables with unused subprogram/data elimination
10857 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
10858 @findex unused subprogram/data elimination
10859
10860 @noindent
10861 This section describes how you can eliminate unused subprograms and data from
10862 your executable just by setting options at compilation time.
10863
10864 @menu
10865 * About unused subprogram/data elimination::
10866 * Compilation options::
10867 * Example of unused subprogram/data elimination::
10868 @end menu
10869
10870 @node About unused subprogram/data elimination
10871 @subsection About unused subprogram/data elimination
10872
10873 @noindent
10874 By default, an executable contains all code and data of its composing objects
10875 (directly linked or coming from statically linked libraries), even data or code
10876 never used by this executable.
10877
10878 This feature will allow you to eliminate such unused code from your
10879 executable, making it smaller (in disk and in memory).
10880
10881 This functionality is available on all Linux platforms except for the IA-64
10882 architecture and on all cross platforms using the ELF binary file format.
10883 In both cases GNU binutils version 2.16 or later are required to enable it.
10884
10885 @node Compilation options
10886 @subsection Compilation options
10887
10888 @noindent
10889 The operation of eliminating the unused code and data from the final executable
10890 is directly performed by the linker.
10891
10892 In order to do this, it has to work with objects compiled with the
10893 following options:
10894 @option{-ffunction-sections} @option{-fdata-sections}.
10895 @cindex @option{-ffunction-sections} (@command{gcc})
10896 @cindex @option{-fdata-sections} (@command{gcc})
10897 These options are usable with C and Ada files.
10898 They will place respectively each
10899 function or data in a separate section in the resulting object file.
10900
10901 Once the objects and static libraries are created with these options, the
10902 linker can perform the dead code elimination. You can do this by setting
10903 the @option{-Wl,--gc-sections} option to gcc command or in the
10904 @option{-largs} section of @command{gnatmake}. This will perform a
10905 garbage collection of code and data never referenced.
10906
10907 If the linker performs a partial link (@option{-r} ld linker option), then you
10908 will need to provide one or several entry point using the
10909 @option{-e} / @option{--entry} ld option.
10910
10911 Note that objects compiled without the @option{-ffunction-sections} and
10912 @option{-fdata-sections} options can still be linked with the executable.
10913 However, no dead code elimination will be performed on those objects (they will
10914 be linked as is).
10915
10916 The GNAT static library is now compiled with -ffunction-sections and
10917 -fdata-sections on some platforms. This allows you to eliminate the unused code
10918 and data of the GNAT library from your executable.
10919
10920 @node Example of unused subprogram/data elimination
10921 @subsection Example of unused subprogram/data elimination
10922
10923 @noindent
10924 Here is a simple example:
10925
10926 @smallexample @c ada
10927 with Aux;
10928
10929 procedure Test is
10930 begin
10931    Aux.Used (10);
10932 end Test;
10933
10934 package Aux is
10935    Used_Data   : Integer;
10936    Unused_Data : Integer;
10937
10938    procedure Used   (Data : Integer);
10939    procedure Unused (Data : Integer);
10940 end Aux;
10941
10942 package body Aux is
10943    procedure Used (Data : Integer) is
10944    begin
10945       Used_Data := Data;
10946    end Used;
10947
10948    procedure Unused (Data : Integer) is
10949    begin
10950       Unused_Data := Data;
10951    end Unused;
10952 end Aux;
10953 @end smallexample
10954
10955 @noindent
10956 @code{Unused} and @code{Unused_Data} are never referenced in this code
10957 excerpt, and hence they may be safely removed from the final executable.
10958
10959 @smallexample
10960 $ gnatmake test
10961
10962 $ nm test | grep used
10963 020015f0 T aux__unused
10964 02005d88 B aux__unused_data
10965 020015cc T aux__used
10966 02005d84 B aux__used_data
10967
10968 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
10969      -largs -Wl,--gc-sections
10970
10971 $ nm test | grep used
10972 02005350 T aux__used
10973 0201ffe0 B aux__used_data
10974 @end smallexample
10975
10976 @noindent
10977 It can be observed that the procedure @code{Unused} and the object
10978 @code{Unused_Data} are removed by the linker when using the
10979 appropriate options.
10980
10981 @c ********************************
10982 @node Renaming Files Using gnatchop
10983 @chapter Renaming Files Using @code{gnatchop}
10984 @findex gnatchop
10985
10986 @noindent
10987 This chapter discusses how to handle files with multiple units by using
10988 the @code{gnatchop} utility. This utility is also useful in renaming
10989 files to meet the standard GNAT default file naming conventions.
10990
10991 @menu
10992 * Handling Files with Multiple Units::
10993 * Operating gnatchop in Compilation Mode::
10994 * Command Line for gnatchop::
10995 * Switches for gnatchop::
10996 * Examples of gnatchop Usage::
10997 @end menu
10998
10999 @node Handling Files with Multiple Units
11000 @section Handling Files with Multiple Units
11001
11002 @noindent
11003 The basic compilation model of GNAT requires that a file submitted to the
11004 compiler have only one unit and there be a strict correspondence
11005 between the file name and the unit name.
11006
11007 The @code{gnatchop} utility allows both of these rules to be relaxed,
11008 allowing GNAT to process files which contain multiple compilation units
11009 and files with arbitrary file names. @code{gnatchop}
11010 reads the specified file and generates one or more output files,
11011 containing one unit per file. The unit and the file name correspond,
11012 as required by GNAT.
11013
11014 If you want to permanently restructure a set of ``foreign'' files so that
11015 they match the GNAT rules, and do the remaining development using the
11016 GNAT structure, you can simply use @command{gnatchop} once, generate the
11017 new set of files and work with them from that point on.
11018
11019 Alternatively, if you want to keep your files in the ``foreign'' format,
11020 perhaps to maintain compatibility with some other Ada compilation
11021 system, you can set up a procedure where you use @command{gnatchop} each
11022 time you compile, regarding the source files that it writes as temporary
11023 files that you throw away.
11024
11025 Note that if your file containing multiple units starts with a byte order
11026 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11027 will each start with a copy of this BOM, meaning that they can be compiled
11028 automatically in UTF-8 mode without needing to specify an explicit encoding.
11029
11030 @node Operating gnatchop in Compilation Mode
11031 @section Operating gnatchop in Compilation Mode
11032
11033 @noindent
11034 The basic function of @code{gnatchop} is to take a file with multiple units
11035 and split it into separate files. The boundary between files is reasonably
11036 clear, except for the issue of comments and pragmas. In default mode, the
11037 rule is that any pragmas between units belong to the previous unit, except
11038 that configuration pragmas always belong to the following unit. Any comments
11039 belong to the following unit. These rules
11040 almost always result in the right choice of
11041 the split point without needing to mark it explicitly and most users will
11042 find this default to be what they want. In this default mode it is incorrect to
11043 submit a file containing only configuration pragmas, or one that ends in
11044 configuration pragmas, to @code{gnatchop}.
11045
11046 However, using a special option to activate ``compilation mode'',
11047 @code{gnatchop}
11048 can perform another function, which is to provide exactly the semantics
11049 required by the RM for handling of configuration pragmas in a compilation.
11050 In the absence of configuration pragmas (at the main file level), this
11051 option has no effect, but it causes such configuration pragmas to be handled
11052 in a quite different manner.
11053
11054 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11055 only configuration pragmas, then this file is appended to the
11056 @file{gnat.adc} file in the current directory. This behavior provides
11057 the required behavior described in the RM for the actions to be taken
11058 on submitting such a file to the compiler, namely that these pragmas
11059 should apply to all subsequent compilations in the same compilation
11060 environment. Using GNAT, the current directory, possibly containing a
11061 @file{gnat.adc} file is the representation
11062 of a compilation environment. For more information on the
11063 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11064
11065 Second, in compilation mode, if @code{gnatchop}
11066 is given a file that starts with
11067 configuration pragmas, and contains one or more units, then these
11068 configuration pragmas are prepended to each of the chopped files. This
11069 behavior provides the required behavior described in the RM for the
11070 actions to be taken on compiling such a file, namely that the pragmas
11071 apply to all units in the compilation, but not to subsequently compiled
11072 units.
11073
11074 Finally, if configuration pragmas appear between units, they are appended
11075 to the previous unit. This results in the previous unit being illegal,
11076 since the compiler does not accept configuration pragmas that follow
11077 a unit. This provides the required RM behavior that forbids configuration
11078 pragmas other than those preceding the first compilation unit of a
11079 compilation.
11080
11081 For most purposes, @code{gnatchop} will be used in default mode. The
11082 compilation mode described above is used only if you need exactly
11083 accurate behavior with respect to compilations, and you have files
11084 that contain multiple units and configuration pragmas. In this
11085 circumstance the use of @code{gnatchop} with the compilation mode
11086 switch provides the required behavior, and is for example the mode
11087 in which GNAT processes the ACVC tests.
11088
11089 @node Command Line for gnatchop
11090 @section Command Line for @code{gnatchop}
11091
11092 @noindent
11093 The @code{gnatchop} command has the form:
11094
11095 @smallexample
11096 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11097 @c      @ovar{directory}
11098 @c Expanding @ovar macro inline (explanation in macro def comments)
11099 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11100       @r{[}@var{directory}@r{]}
11101 @end smallexample
11102
11103 @noindent
11104 The only required argument is the file name of the file to be chopped.
11105 There are no restrictions on the form of this file name. The file itself
11106 contains one or more Ada units, in normal GNAT format, concatenated
11107 together. As shown, more than one file may be presented to be chopped.
11108
11109 When run in default mode, @code{gnatchop} generates one output file in
11110 the current directory for each unit in each of the files.
11111
11112 @var{directory}, if specified, gives the name of the directory to which
11113 the output files will be written. If it is not specified, all files are
11114 written to the current directory.
11115
11116 For example, given a
11117 file called @file{hellofiles} containing
11118
11119 @smallexample @c ada
11120 @group
11121 @cartouche
11122 procedure hello;
11123
11124 with Text_IO; use Text_IO;
11125 procedure hello is
11126 begin
11127    Put_Line ("Hello");
11128 end hello;
11129 @end cartouche
11130 @end group
11131 @end smallexample
11132
11133 @noindent
11134 the command
11135
11136 @smallexample
11137 $ gnatchop ^hellofiles^HELLOFILES.^
11138 @end smallexample
11139
11140 @noindent
11141 generates two files in the current directory, one called
11142 @file{hello.ads} containing the single line that is the procedure spec,
11143 and the other called @file{hello.adb} containing the remaining text. The
11144 original file is not affected. The generated files can be compiled in
11145 the normal manner.
11146
11147 @noindent
11148 When gnatchop is invoked on a file that is empty or that contains only empty
11149 lines and/or comments, gnatchop will not fail, but will not produce any
11150 new sources.
11151
11152 For example, given a
11153 file called @file{toto.txt} containing
11154
11155 @smallexample @c ada
11156 @group
11157 @cartouche
11158 --  Just a comment
11159 @end cartouche
11160 @end group
11161 @end smallexample
11162
11163 @noindent
11164 the command
11165
11166 @smallexample
11167 $ gnatchop ^toto.txt^TOT.TXT^
11168 @end smallexample
11169
11170 @noindent
11171 will not produce any new file and will result in the following warnings:
11172
11173 @smallexample
11174 toto.txt:1:01: warning: empty file, contains no compilation units
11175 no compilation units found
11176 no source files written
11177 @end smallexample
11178
11179 @node Switches for gnatchop
11180 @section Switches for @code{gnatchop}
11181
11182 @noindent
11183 @command{gnatchop} recognizes the following switches:
11184
11185 @table @option
11186 @c !sort!
11187
11188 @item --version
11189 @cindex @option{--version} @command{gnatchop}
11190 Display Copyright and version, then exit disregarding all other options.
11191
11192 @item --help
11193 @cindex @option{--help} @command{gnatchop}
11194 If @option{--version} was not used, display usage, then exit disregarding
11195 all other options.
11196
11197 @item ^-c^/COMPILATION^
11198 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11199 Causes @code{gnatchop} to operate in compilation mode, in which
11200 configuration pragmas are handled according to strict RM rules. See
11201 previous section for a full description of this mode.
11202
11203 @ifclear vms
11204 @item -gnat@var{xxx}
11205 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11206 used to parse the given file. Not all @var{xxx} options make sense,
11207 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11208 process a source file that uses Latin-2 coding for identifiers.
11209 @end ifclear
11210
11211 @item ^-h^/HELP^
11212 Causes @code{gnatchop} to generate a brief help summary to the standard
11213 output file showing usage information.
11214
11215 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11216 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11217 Limit generated file names to the specified number @code{mm}
11218 of characters.
11219 This is useful if the
11220 resulting set of files is required to be interoperable with systems
11221 which limit the length of file names.
11222 @ifset vms
11223 If no value is given, or
11224 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11225 a default of 39, suitable for OpenVMS Alpha
11226 Systems, is assumed
11227 @end ifset
11228 @ifclear vms
11229 No space is allowed between the @option{-k} and the numeric value. The numeric
11230 value may be omitted in which case a default of @option{-k8},
11231 suitable for use
11232 with DOS-like file systems, is used. If no @option{-k} switch
11233 is present then
11234 there is no limit on the length of file names.
11235 @end ifclear
11236
11237 @item ^-p^/PRESERVE^
11238 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11239 Causes the file ^modification^creation^ time stamp of the input file to be
11240 preserved and used for the time stamp of the output file(s). This may be
11241 useful for preserving coherency of time stamps in an environment where
11242 @code{gnatchop} is used as part of a standard build process.
11243
11244 @item ^-q^/QUIET^
11245 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11246 Causes output of informational messages indicating the set of generated
11247 files to be suppressed. Warnings and error messages are unaffected.
11248
11249 @item ^-r^/REFERENCE^
11250 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11251 @findex Source_Reference
11252 Generate @code{Source_Reference} pragmas. Use this switch if the output
11253 files are regarded as temporary and development is to be done in terms
11254 of the original unchopped file. This switch causes
11255 @code{Source_Reference} pragmas to be inserted into each of the
11256 generated files to refers back to the original file name and line number.
11257 The result is that all error messages refer back to the original
11258 unchopped file.
11259 In addition, the debugging information placed into the object file (when
11260 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11261 specified)
11262 also refers back to this original file so that tools like profilers and
11263 debuggers will give information in terms of the original unchopped file.
11264
11265 If the original file to be chopped itself contains
11266 a @code{Source_Reference}
11267 pragma referencing a third file, then gnatchop respects
11268 this pragma, and the generated @code{Source_Reference} pragmas
11269 in the chopped file refer to the original file, with appropriate
11270 line numbers. This is particularly useful when @code{gnatchop}
11271 is used in conjunction with @code{gnatprep} to compile files that
11272 contain preprocessing statements and multiple units.
11273
11274 @item ^-v^/VERBOSE^
11275 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11276 Causes @code{gnatchop} to operate in verbose mode. The version
11277 number and copyright notice are output, as well as exact copies of
11278 the gnat1 commands spawned to obtain the chop control information.
11279
11280 @item ^-w^/OVERWRITE^
11281 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11282 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11283 fatal error if there is already a file with the same name as a
11284 file it would otherwise output, in other words if the files to be
11285 chopped contain duplicated units. This switch bypasses this
11286 check, and causes all but the last instance of such duplicated
11287 units to be skipped.
11288
11289 @ifclear vms
11290 @item --GCC=@var{xxxx}
11291 @cindex @option{--GCC=} (@code{gnatchop})
11292 Specify the path of the GNAT parser to be used. When this switch is used,
11293 no attempt is made to add the prefix to the GNAT parser executable.
11294 @end ifclear
11295 @end table
11296
11297 @node Examples of gnatchop Usage
11298 @section Examples of @code{gnatchop} Usage
11299
11300 @table @code
11301 @ifset vms
11302 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11303 @end ifset
11304 @ifclear vms
11305 @item gnatchop -w hello_s.ada prerelease/files
11306 @end ifclear
11307
11308 Chops the source file @file{hello_s.ada}. The output files will be
11309 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11310 overwriting any
11311 files with matching names in that directory (no files in the current
11312 directory are modified).
11313
11314 @item gnatchop ^archive^ARCHIVE.^
11315 Chops the source file @file{^archive^ARCHIVE.^}
11316 into the current directory. One
11317 useful application of @code{gnatchop} is in sending sets of sources
11318 around, for example in email messages. The required sources are simply
11319 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11320 command), and then
11321 @command{gnatchop} is used at the other end to reconstitute the original
11322 file names.
11323
11324 @item gnatchop file1 file2 file3 direc
11325 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11326 the resulting files in the directory @file{direc}. Note that if any units
11327 occur more than once anywhere within this set of files, an error message
11328 is generated, and no files are written. To override this check, use the
11329 @option{^-w^/OVERWRITE^} switch,
11330 in which case the last occurrence in the last file will
11331 be the one that is output, and earlier duplicate occurrences for a given
11332 unit will be skipped.
11333 @end table
11334
11335 @node Configuration Pragmas
11336 @chapter Configuration Pragmas
11337 @cindex Configuration pragmas
11338 @cindex Pragmas, configuration
11339
11340 @noindent
11341 Configuration pragmas include those pragmas described as
11342 such in the Ada Reference Manual, as well as
11343 implementation-dependent pragmas that are configuration pragmas.
11344 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11345 for details on these additional GNAT-specific configuration pragmas.
11346 Most notably, the pragma @code{Source_File_Name}, which allows
11347 specifying non-default names for source files, is a configuration
11348 pragma. The following is a complete list of configuration pragmas
11349 recognized by GNAT:
11350
11351 @smallexample
11352    Ada_83
11353    Ada_95
11354    Ada_05
11355    Ada_2005
11356    Assertion_Policy
11357    Assume_No_Invalid_Values
11358    C_Pass_By_Copy
11359    Check_Name
11360    Check_Policy
11361    Compile_Time_Error
11362    Compile_Time_Warning
11363    Compiler_Unit
11364    Component_Alignment
11365    Convention_Identifier
11366    Debug_Policy
11367    Detect_Blocking
11368    Discard_Names
11369    Elaboration_Checks
11370    Eliminate
11371    Extend_System
11372    Extensions_Allowed
11373    External_Name_Casing
11374    Fast_Math
11375    Favor_Top_Level
11376    Float_Representation
11377    Implicit_Packing
11378    Initialize_Scalars
11379    Interrupt_State
11380    License
11381    Locking_Policy
11382    Long_Float
11383    No_Run_Time
11384    No_Strict_Aliasing
11385    Normalize_Scalars
11386    Optimize_Alignment
11387    Persistent_BSS
11388    Polling
11389    Priority_Specific_Dispatching
11390    Profile
11391    Profile_Warnings
11392    Propagate_Exceptions
11393    Queuing_Policy
11394    Ravenscar
11395    Restricted_Run_Time
11396    Restrictions
11397    Restrictions_Warnings
11398    Reviewable
11399    Source_File_Name
11400    Source_File_Name_Project
11401    Style_Checks
11402    Suppress
11403    Suppress_Exception_Locations
11404    Task_Dispatching_Policy
11405    Universal_Data
11406    Unsuppress
11407    Use_VADS_Size
11408    Validity_Checks
11409    Warnings
11410    Wide_Character_Encoding
11411
11412 @end smallexample
11413
11414 @menu
11415 * Handling of Configuration Pragmas::
11416 * The Configuration Pragmas Files::
11417 @end menu
11418
11419 @node Handling of Configuration Pragmas
11420 @section Handling of Configuration Pragmas
11421
11422 Configuration pragmas may either appear at the start of a compilation
11423 unit, in which case they apply only to that unit, or they may apply to
11424 all compilations performed in a given compilation environment.
11425
11426 GNAT also provides the @code{gnatchop} utility to provide an automatic
11427 way to handle configuration pragmas following the semantics for
11428 compilations (that is, files with multiple units), described in the RM.
11429 See @ref{Operating gnatchop in Compilation Mode} for details.
11430 However, for most purposes, it will be more convenient to edit the
11431 @file{gnat.adc} file that contains configuration pragmas directly,
11432 as described in the following section.
11433
11434 @node The Configuration Pragmas Files
11435 @section The Configuration Pragmas Files
11436 @cindex @file{gnat.adc}
11437
11438 @noindent
11439 In GNAT a compilation environment is defined by the current
11440 directory at the time that a compile command is given. This current
11441 directory is searched for a file whose name is @file{gnat.adc}. If
11442 this file is present, it is expected to contain one or more
11443 configuration pragmas that will be applied to the current compilation.
11444 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11445 considered.
11446
11447 Configuration pragmas may be entered into the @file{gnat.adc} file
11448 either by running @code{gnatchop} on a source file that consists only of
11449 configuration pragmas, or more conveniently  by
11450 direct editing of the @file{gnat.adc} file, which is a standard format
11451 source file.
11452
11453 In addition to @file{gnat.adc}, additional files containing configuration
11454 pragmas may be applied to the current compilation using the switch
11455 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11456 contains only configuration pragmas. These configuration pragmas are
11457 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11458 is present and switch @option{-gnatA} is not used).
11459
11460 It is allowed to specify several switches @option{-gnatec}, all of which
11461 will be taken into account.
11462
11463 If you are using project file, a separate mechanism is provided using
11464 project attributes, see @ref{Specifying Configuration Pragmas} for more
11465 details.
11466
11467 @ifset vms
11468 Of special interest to GNAT OpenVMS Alpha is the following
11469 configuration pragma:
11470
11471 @smallexample @c ada
11472 @cartouche
11473 pragma Extend_System (Aux_DEC);
11474 @end cartouche
11475 @end smallexample
11476
11477 @noindent
11478 In the presence of this pragma, GNAT adds to the definition of the
11479 predefined package SYSTEM all the additional types and subprograms that are
11480 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11481 @end ifset
11482
11483 @node Handling Arbitrary File Naming Conventions Using gnatname
11484 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
11485 @cindex Arbitrary File Naming Conventions
11486
11487 @menu
11488 * Arbitrary File Naming Conventions::
11489 * Running gnatname::
11490 * Switches for gnatname::
11491 * Examples of gnatname Usage::
11492 @end menu
11493
11494 @node Arbitrary File Naming Conventions
11495 @section Arbitrary File Naming Conventions
11496
11497 @noindent
11498 The GNAT compiler must be able to know the source file name of a compilation
11499 unit.  When using the standard GNAT default file naming conventions
11500 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11501 does not need additional information.
11502
11503 @noindent
11504 When the source file names do not follow the standard GNAT default file naming
11505 conventions, the GNAT compiler must be given additional information through
11506 a configuration pragmas file (@pxref{Configuration Pragmas})
11507 or a project file.
11508 When the non-standard file naming conventions are well-defined,
11509 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11510 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11511 if the file naming conventions are irregular or arbitrary, a number
11512 of pragma @code{Source_File_Name} for individual compilation units
11513 must be defined.
11514 To help maintain the correspondence between compilation unit names and
11515 source file names within the compiler,
11516 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11517 set of files.
11518
11519 @node Running gnatname
11520 @section Running @code{gnatname}
11521
11522 @noindent
11523 The usual form of the @code{gnatname} command is
11524
11525 @smallexample
11526 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11527 @c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11528 @c Expanding @ovar macro inline (explanation in macro def comments)
11529 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11530       @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11531 @end smallexample
11532
11533 @noindent
11534 All of the arguments are optional. If invoked without any argument,
11535 @code{gnatname} will display its usage.
11536
11537 @noindent
11538 When used with at least one naming pattern, @code{gnatname} will attempt to
11539 find all the compilation units in files that follow at least one of the
11540 naming patterns. To find these compilation units,
11541 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11542 regular files.
11543
11544 @noindent
11545 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11546 Each Naming Pattern is enclosed between double quotes.
11547 A Naming Pattern is a regular expression similar to the wildcard patterns
11548 used in file names by the Unix shells or the DOS prompt.
11549
11550 @noindent
11551 @code{gnatname} may be called with several sections of directories/patterns.
11552 Sections are separated by switch @code{--and}. In each section, there must be
11553 at least one pattern. If no directory is specified in a section, the current
11554 directory (or the project directory is @code{-P} is used) is implied.
11555 The options other that the directory switches and the patterns apply globally
11556 even if they are in different sections.
11557
11558 @noindent
11559 Examples of Naming Patterns are
11560
11561 @smallexample
11562    "*.[12].ada"
11563    "*.ad[sb]*"
11564    "body_*"    "spec_*"
11565 @end smallexample
11566
11567 @noindent
11568 For a more complete description of the syntax of Naming Patterns,
11569 see the second kind of regular expressions described in @file{g-regexp.ads}
11570 (the ``Glob'' regular expressions).
11571
11572 @noindent
11573 When invoked with no switch @code{-P}, @code{gnatname} will create a
11574 configuration pragmas file @file{gnat.adc} in the current working directory,
11575 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11576 unit.
11577
11578 @node Switches for gnatname
11579 @section Switches for @code{gnatname}
11580
11581 @noindent
11582 Switches for @code{gnatname} must precede any specified Naming Pattern.
11583
11584 @noindent
11585 You may specify any of the following switches to @code{gnatname}:
11586
11587 @table @option
11588 @c !sort!
11589
11590 @item --version
11591 @cindex @option{--version} @command{gnatname}
11592 Display Copyright and version, then exit disregarding all other options.
11593
11594 @item --help
11595 @cindex @option{--help} @command{gnatname}
11596 If @option{--version} was not used, display usage, then exit disregarding
11597 all other options.
11598
11599 @item --and
11600 Start another section of directories/patterns.
11601
11602 @item ^-c^/CONFIG_FILE=^@file{file}
11603 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11604 Create a configuration pragmas file @file{file} (instead of the default
11605 @file{gnat.adc}).
11606 @ifclear vms
11607 There may be zero, one or more space between @option{-c} and
11608 @file{file}.
11609 @end ifclear
11610 @file{file} may include directory information. @file{file} must be
11611 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11612 When a switch @option{^-c^/CONFIG_FILE^} is
11613 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11614
11615 @item ^-d^/SOURCE_DIRS=^@file{dir}
11616 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11617 Look for source files in directory @file{dir}. There may be zero, one or more
11618 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11619 When a switch @option{^-d^/SOURCE_DIRS^}
11620 is specified, the current working directory will not be searched for source
11621 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11622 or @option{^-D^/DIR_FILES^} switch.
11623 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11624 If @file{dir} is a relative path, it is relative to the directory of
11625 the configuration pragmas file specified with switch
11626 @option{^-c^/CONFIG_FILE^},
11627 or to the directory of the project file specified with switch
11628 @option{^-P^/PROJECT_FILE^} or,
11629 if neither switch @option{^-c^/CONFIG_FILE^}
11630 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11631 current working directory. The directory
11632 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11633
11634 @item ^-D^/DIRS_FILE=^@file{file}
11635 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11636 Look for source files in all directories listed in text file @file{file}.
11637 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11638 and @file{file}.
11639 @file{file} must be an existing, readable text file.
11640 Each nonempty line in @file{file} must be a directory.
11641 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11642 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11643 @file{file}.
11644
11645 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11646 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11647 Foreign patterns. Using this switch, it is possible to add sources of languages
11648 other than Ada to the list of sources of a project file.
11649 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11650 For example,
11651 @smallexample
11652 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11653 @end smallexample
11654 @noindent
11655 will look for Ada units in all files with the @file{.ada} extension,
11656 and will add to the list of file for project @file{prj.gpr} the C files
11657 with extension @file{.^c^C^}.
11658
11659 @item ^-h^/HELP^
11660 @cindex @option{^-h^/HELP^} (@code{gnatname})
11661 Output usage (help) information. The output is written to @file{stdout}.
11662
11663 @item ^-P^/PROJECT_FILE=^@file{proj}
11664 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11665 Create or update project file @file{proj}. There may be zero, one or more space
11666 between @option{-P} and @file{proj}. @file{proj} may include directory
11667 information. @file{proj} must be writable.
11668 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11669 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11670 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11671
11672 @item ^-v^/VERBOSE^
11673 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
11674 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
11675 This includes name of the file written, the name of the directories to search
11676 and, for each file in those directories whose name matches at least one of
11677 the Naming Patterns, an indication of whether the file contains a unit,
11678 and if so the name of the unit.
11679
11680 @item ^-v -v^/VERBOSE /VERBOSE^
11681 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
11682 Very Verbose mode. In addition to the output produced in verbose mode,
11683 for each file in the searched directories whose name matches none of
11684 the Naming Patterns, an indication is given that there is no match.
11685
11686 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
11687 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
11688 Excluded patterns. Using this switch, it is possible to exclude some files
11689 that would match the name patterns. For example,
11690 @smallexample
11691 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
11692 @end smallexample
11693 @noindent
11694 will look for Ada units in all files with the @file{.ada} extension,
11695 except those whose names end with @file{_nt.ada}.
11696
11697 @end table
11698
11699 @node Examples of gnatname Usage
11700 @section Examples of @code{gnatname} Usage
11701
11702 @ifset vms
11703 @smallexample
11704 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
11705 @end smallexample
11706 @end ifset
11707
11708 @ifclear vms
11709 @smallexample
11710 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
11711 @end smallexample
11712 @end ifclear
11713
11714 @noindent
11715 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
11716 and be writable. In addition, the directory
11717 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
11718 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
11719
11720 @ifclear vms
11721 Note the optional spaces after @option{-c} and @option{-d}.
11722 @end ifclear
11723
11724 @smallexample
11725 @ifclear vms
11726 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
11727   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
11728 @end ifclear
11729 @ifset vms
11730 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
11731   /EXCLUDED_PATTERN=*_nt_body.ada
11732   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
11733   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
11734 @end ifset
11735 @end smallexample
11736
11737 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
11738 even in conjunction with one or several switches
11739 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
11740 are used in this example.
11741
11742 @c *****************************************
11743 @c * G N A T  P r o j e c t  M a n a g e r *
11744 @c *****************************************
11745 @node GNAT Project Manager
11746 @chapter GNAT Project Manager
11747
11748 @menu
11749 * Introduction::
11750 * Examples of Project Files::
11751 * Project File Syntax::
11752 * Objects and Sources in Project Files::
11753 * Importing Projects::
11754 * Project Extension::
11755 * Project Hierarchy Extension::
11756 * External References in Project Files::
11757 * Packages in Project Files::
11758 * Variables from Imported Projects::
11759 * Naming Schemes::
11760 * Library Projects::
11761 * Stand-alone Library Projects::
11762 * Switches Related to Project Files::
11763 * Tools Supporting Project Files::
11764 * An Extended Example::
11765 * Project File Complete Syntax::
11766 @end menu
11767
11768 @c ****************
11769 @c * Introduction *
11770 @c ****************
11771
11772 @node Introduction
11773 @section Introduction
11774
11775 @noindent
11776 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
11777 you to manage complex builds involving a number of source files, directories,
11778 and compilation options for different system configurations. In particular,
11779 project files allow you to specify:
11780 @itemize @bullet
11781 @item
11782 The directory or set of directories containing the source files, and/or the
11783 names of the specific source files themselves
11784 @item
11785 The directory in which the compiler's output
11786 (@file{ALI} files, object files, tree files) is to be placed
11787 @item
11788 The directory in which the executable programs is to be placed
11789 @item
11790 ^Switch^Switch^ settings for any of the project-enabled tools
11791 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
11792 @code{gnatfind}); you can apply these settings either globally or to individual
11793 compilation units.
11794 @item
11795 The source files containing the main subprogram(s) to be built
11796 @item
11797 The source programming language(s) (currently Ada and/or C)
11798 @item
11799 Source file naming conventions; you can specify these either globally or for
11800 individual compilation units
11801 @end itemize
11802
11803 @menu
11804 * Project Files::
11805 @end menu
11806
11807 @node Project Files
11808 @subsection Project Files
11809
11810 @noindent
11811 Project files are written in a syntax close to that of Ada, using  familiar
11812 notions such as packages, context clauses, declarations, default values,
11813 assignments, and inheritance. Finally, project files can be built
11814 hierarchically from other project files, simplifying complex system
11815 integration and project reuse.
11816
11817 A @dfn{project} is a specific set of values for various compilation properties.
11818 The settings for a given project are described by means of
11819 a @dfn{project file}, which is a text file written in an Ada-like syntax.
11820 Property values in project files are either strings or lists of strings.
11821 Properties that are not explicitly set receive default values.  A project
11822 file may interrogate the values of @dfn{external variables} (user-defined
11823 command-line switches or environment variables), and it may specify property
11824 settings conditionally, based on the value of such variables.
11825
11826 In simple cases, a project's source files depend only on other source files
11827 in the same project, or on the predefined libraries.  (@emph{Dependence} is
11828 used in
11829 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
11830 the Project Manager also allows more sophisticated arrangements,
11831 where the source files in one project depend on source files in other
11832 projects:
11833 @itemize @bullet
11834 @item
11835 One project can @emph{import} other projects containing needed source files.
11836 @item
11837 You can organize GNAT projects in a hierarchy: a @emph{child} project
11838 can extend a @emph{parent} project, inheriting the parent's source files and
11839 optionally overriding any of them with alternative versions
11840 @end itemize
11841
11842 @noindent
11843 More generally, the Project Manager lets you structure large development
11844 efforts into hierarchical subsystems, where build decisions are delegated
11845 to the subsystem level, and thus different compilation environments
11846 (^switch^switch^ settings) used for different subsystems.
11847
11848 The Project Manager is invoked through the
11849 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
11850 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
11851 @ifclear vms
11852 There may be zero, one or more spaces between @option{-P} and
11853 @option{@emph{projectfile}}.
11854 @end ifclear
11855 If you want to define (on the command line) an external variable that is
11856 queried by the project file, you must use the
11857 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
11858 The Project Manager parses and interprets the project file, and drives the
11859 invoked tool based on the project settings.
11860
11861 The Project Manager supports a wide range of development strategies,
11862 for systems of all sizes.  Here are some typical practices that are
11863 easily handled:
11864 @itemize @bullet
11865 @item
11866 Using a common set of source files, but generating object files in different
11867 directories via different ^switch^switch^ settings
11868 @item
11869 Using a mostly-shared set of source files, but with different versions of
11870 some unit or units
11871 @end itemize
11872
11873 @noindent
11874 The destination of an executable can be controlled inside a project file
11875 using the @option{^-o^-o^}
11876 ^switch^switch^.
11877 In the absence of such a ^switch^switch^ either inside
11878 the project file or on the command line, any executable files generated by
11879 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
11880 in the project file. If no @code{Exec_Dir} is specified, they will be placed
11881 in the object directory of the project.
11882
11883 You can use project files to achieve some of the effects of a source
11884 versioning system (for example, defining separate projects for
11885 the different sets of sources that comprise different releases) but the
11886 Project Manager is independent of any source configuration management tools
11887 that might be used by the developers.
11888
11889 The next section introduces the main features of GNAT's project facility
11890 through a sequence of examples; subsequent sections will present the syntax
11891 and semantics in more detail. A more formal description of the project
11892 facility appears in @ref{Project File Reference,,, gnat_rm, GNAT
11893 Reference Manual}.
11894
11895 @c *****************************
11896 @c * Examples of Project Files *
11897 @c *****************************
11898
11899 @node Examples of Project Files
11900 @section Examples of Project Files
11901 @noindent
11902 This section illustrates some of the typical uses of project files and
11903 explains their basic structure and behavior.
11904
11905 @menu
11906 * Common Sources with Different ^Switches^Switches^ and Directories::
11907 * Using External Variables::
11908 * Importing Other Projects::
11909 * Extending a Project::
11910 @end menu
11911
11912 @node Common Sources with Different ^Switches^Switches^ and Directories
11913 @subsection Common Sources with Different ^Switches^Switches^ and Directories
11914
11915 @menu
11916 * Source Files::
11917 * Specifying the Object Directory::
11918 * Specifying the Exec Directory::
11919 * Project File Packages::
11920 * Specifying ^Switch^Switch^ Settings::
11921 * Main Subprograms::
11922 * Executable File Names::
11923 * Source File Naming Conventions::
11924 * Source Language(s)::
11925 @end menu
11926
11927 @noindent
11928 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
11929 @file{proc.adb} are in the @file{/common} directory.  The file
11930 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
11931 package @code{Pack}.  We want to compile these source files under two sets
11932 of ^switches^switches^:
11933 @itemize @bullet
11934 @item
11935 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
11936 and the @option{^-gnata^-gnata^},
11937 @option{^-gnato^-gnato^},
11938 and @option{^-gnatE^-gnatE^} switches to the
11939 compiler; the compiler's output is to appear in @file{/common/debug}
11940 @item
11941 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
11942 to the compiler; the compiler's output is to appear in @file{/common/release}
11943 @end itemize
11944
11945 @noindent
11946 The GNAT project files shown below, respectively @file{debug.gpr} and
11947 @file{release.gpr} in the @file{/common} directory, achieve these effects.
11948
11949 Schematically:
11950 @smallexample
11951 @group
11952 ^/common^[COMMON]^
11953   debug.gpr
11954   release.gpr
11955   pack.ads
11956   pack.adb
11957   proc.adb
11958 @end group
11959 @group
11960 ^/common/debug^[COMMON.DEBUG]^
11961   proc.ali, proc.o
11962   pack.ali, pack.o
11963 @end group
11964 @group
11965 ^/common/release^[COMMON.RELEASE]^
11966   proc.ali, proc.o
11967   pack.ali, pack.o
11968 @end group
11969 @end smallexample
11970 Here are the corresponding project files:
11971
11972 @smallexample @c projectfile
11973 @group
11974 project Debug is
11975   for Object_Dir use "debug";
11976   for Main use ("proc");
11977
11978   package Builder is
11979     for ^Default_Switches^Default_Switches^ ("Ada")
11980         use ("^-g^-g^");
11981     for Executable ("proc.adb") use "proc1";
11982   end Builder;
11983 @end group
11984
11985 @group
11986   package Compiler is
11987     for ^Default_Switches^Default_Switches^ ("Ada")
11988        use ("-fstack-check",
11989             "^-gnata^-gnata^",
11990             "^-gnato^-gnato^",
11991             "^-gnatE^-gnatE^");
11992   end Compiler;
11993 end Debug;
11994 @end group
11995 @end smallexample
11996
11997 @smallexample @c projectfile
11998 @group
11999 project Release is
12000   for Object_Dir use "release";
12001   for Exec_Dir use ".";
12002   for Main use ("proc");
12003
12004   package Compiler is
12005     for ^Default_Switches^Default_Switches^ ("Ada")
12006         use ("^-O2^-O2^");
12007   end Compiler;
12008 end Release;
12009 @end group
12010 @end smallexample
12011
12012 @noindent
12013 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
12014 insensitive), and analogously the project defined by @file{release.gpr} is
12015 @code{"Release"}.  For consistency the file should have the same name as the
12016 project, and the project file's extension should be @code{"gpr"}. These
12017 conventions are not required, but a warning is issued if they are not followed.
12018
12019 If the current directory is @file{^/temp^[TEMP]^}, then the command
12020 @smallexample
12021 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
12022 @end smallexample
12023
12024 @noindent
12025 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
12026 as well as the @code{^proc1^PROC1.EXE^} executable,
12027 using the ^switch^switch^ settings defined in the project file.
12028
12029 Likewise, the command
12030 @smallexample
12031 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
12032 @end smallexample
12033
12034 @noindent
12035 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
12036 and the @code{^proc^PROC.EXE^}
12037 executable in @file{^/common^[COMMON]^},
12038 using the ^switch^switch^ settings from the project file.
12039
12040 @node Source Files
12041 @unnumberedsubsubsec Source Files
12042
12043 @noindent
12044 If a project file does not explicitly specify a set of source directories or
12045 a set of source files, then by default the project's source files are the
12046 Ada source files in the project file directory.  Thus @file{pack.ads},
12047 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
12048
12049 @node Specifying the Object Directory
12050 @unnumberedsubsubsec Specifying the Object Directory
12051
12052 @noindent
12053 Several project properties are modeled by Ada-style @emph{attributes};
12054 a property is defined by supplying the equivalent of an Ada attribute
12055 definition clause in the project file.
12056 A project's object directory is another such a property; the corresponding
12057 attribute is @code{Object_Dir}, and its value is also a string expression,
12058 specified either as absolute or relative. In the later case,
12059 it is relative to the project file directory. Thus the compiler's
12060 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
12061 (for the @code{Debug} project)
12062 and to @file{^/common/release^[COMMON.RELEASE]^}
12063 (for the @code{Release} project).
12064 If @code{Object_Dir} is not specified, then the default is the project file
12065 directory itself.
12066
12067 @node Specifying the Exec Directory
12068 @unnumberedsubsubsec Specifying the Exec Directory
12069
12070 @noindent
12071 A project's exec directory is another property; the corresponding
12072 attribute is @code{Exec_Dir}, and its value is also a string expression,
12073 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
12074 then the default is the object directory (which may also be the project file
12075 directory if attribute @code{Object_Dir} is not specified). Thus the executable
12076 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
12077 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
12078 and in @file{^/common^[COMMON]^} for the @code{Release} project.
12079
12080 @node Project File Packages
12081 @unnumberedsubsubsec Project File Packages
12082
12083 @noindent
12084 A GNAT tool that is integrated with the Project Manager is modeled by a
12085 corresponding package in the project file. In the example above,
12086 The @code{Debug} project defines the packages @code{Builder}
12087 (for @command{gnatmake}) and @code{Compiler};
12088 the @code{Release} project defines only the @code{Compiler} package.
12089
12090 The Ada-like package syntax is not to be taken literally.  Although packages in
12091 project files bear a surface resemblance to packages in Ada source code, the
12092 notation is simply a way to convey a grouping of properties for a named
12093 entity.  Indeed, the package names permitted in project files are restricted
12094 to a predefined set, corresponding to the project-aware tools, and the contents
12095 of packages are limited to a small set of constructs.
12096 The packages in the example above contain attribute definitions.
12097
12098 @node Specifying ^Switch^Switch^ Settings
12099 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
12100
12101 @noindent
12102 ^Switch^Switch^ settings for a project-aware tool can be specified through
12103 attributes in the package that corresponds to the tool.
12104 The example above illustrates one of the relevant attributes,
12105 @code{^Default_Switches^Default_Switches^}, which is defined in packages
12106 in both project files.
12107 Unlike simple attributes like @code{Source_Dirs},
12108 @code{^Default_Switches^Default_Switches^} is
12109 known as an @emph{associative array}.  When you define this attribute, you must
12110 supply an ``index'' (a literal string), and the effect of the attribute
12111 definition is to set the value of the array at the specified index.
12112 For the @code{^Default_Switches^Default_Switches^} attribute,
12113 the index is a programming language (in our case, Ada),
12114 and the value specified (after @code{use}) must be a list
12115 of string expressions.
12116
12117 The attributes permitted in project files are restricted to a predefined set.
12118 Some may appear at project level, others in packages.
12119 For any attribute that is an associative array, the index must always be a
12120 literal string, but the restrictions on this string (e.g., a file name or a
12121 language name) depend on the individual attribute.
12122 Also depending on the attribute, its specified value will need to be either a
12123 string or a string list.
12124
12125 In the @code{Debug} project, we set the switches for two tools,
12126 @command{gnatmake} and the compiler, and thus we include the two corresponding
12127 packages; each package defines the @code{^Default_Switches^Default_Switches^}
12128 attribute with index @code{"Ada"}.
12129 Note that the package corresponding to
12130 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
12131 similar, but only includes the @code{Compiler} package.
12132
12133 In project @code{Debug} above, the ^switches^switches^ starting with
12134 @option{-gnat} that are specified in package @code{Compiler}
12135 could have been placed in package @code{Builder}, since @command{gnatmake}
12136 transmits all such ^switches^switches^ to the compiler.
12137
12138 @node Main Subprograms
12139 @unnumberedsubsubsec Main Subprograms
12140
12141 @noindent
12142 One of the specifiable properties of a project is a list of files that contain
12143 main subprograms.  This property is captured in the @code{Main} attribute,
12144 whose value is a list of strings.  If a project defines the @code{Main}
12145 attribute, it is not necessary to identify the main subprogram(s) when
12146 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
12147
12148 @node Executable File Names
12149 @unnumberedsubsubsec Executable File Names
12150
12151 @noindent
12152 By default, the executable file name corresponding to a main source is
12153 deduced from the main source file name. Through the attributes
12154 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
12155 it is possible to change this default.
12156 In project @code{Debug} above, the executable file name
12157 for main source @file{^proc.adb^PROC.ADB^} is
12158 @file{^proc1^PROC1.EXE^}.
12159 Attribute @code{Executable_Suffix}, when specified, may change the suffix
12160 of the executable files, when no attribute @code{Executable} applies:
12161 its value replace the platform-specific executable suffix.
12162 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
12163 specify a non-default executable file name when several mains are built at once
12164 in a single @command{gnatmake} command.
12165
12166 @node Source File Naming Conventions
12167 @unnumberedsubsubsec Source File Naming Conventions
12168
12169 @noindent
12170 Since the project files above do not specify any source file naming
12171 conventions, the GNAT defaults are used.  The mechanism for defining source
12172 file naming conventions -- a package named @code{Naming} --
12173 is described below (@pxref{Naming Schemes}).
12174
12175 @node Source Language(s)
12176 @unnumberedsubsubsec Source Language(s)
12177
12178 @noindent
12179 Since the project files do not specify a @code{Languages} attribute, by
12180 default the GNAT tools assume that the language of the project file is Ada.
12181 More generally, a project can comprise source files
12182 in Ada, C, and/or other languages.
12183
12184 @node Using External Variables
12185 @subsection Using External Variables
12186
12187 @noindent
12188 Instead of supplying different project files for debug and release, we can
12189 define a single project file that queries an external variable (set either
12190 on the command line or via an ^environment variable^logical name^) in order to
12191 conditionally define the appropriate settings.  Again, assume that the
12192 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
12193 located in directory @file{^/common^[COMMON]^}.  The following project file,
12194 @file{build.gpr}, queries the external variable named @code{STYLE} and
12195 defines an object directory and ^switch^switch^ settings based on whether
12196 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
12197 the default is @code{"deb"}.
12198
12199 @smallexample @c projectfile
12200 @group
12201 project Build is
12202   for Main use ("proc");
12203
12204   type Style_Type is ("deb", "rel");
12205   Style : Style_Type := external ("STYLE", "deb");
12206
12207   case Style is
12208     when "deb" =>
12209       for Object_Dir use "debug";
12210
12211     when "rel" =>
12212       for Object_Dir use "release";
12213       for Exec_Dir use ".";
12214   end case;
12215 @end group
12216
12217 @group
12218   package Builder is
12219
12220     case Style is
12221       when "deb" =>
12222         for ^Default_Switches^Default_Switches^ ("Ada")
12223             use ("^-g^-g^");
12224         for Executable ("proc") use "proc1";
12225       when others =>
12226         null;
12227     end case;
12228
12229   end Builder;
12230 @end group
12231
12232 @group
12233   package Compiler is
12234
12235     case Style is
12236       when "deb" =>
12237         for ^Default_Switches^Default_Switches^ ("Ada")
12238             use ("^-gnata^-gnata^",
12239                  "^-gnato^-gnato^",
12240                  "^-gnatE^-gnatE^");
12241
12242       when "rel" =>
12243         for ^Default_Switches^Default_Switches^ ("Ada")
12244             use ("^-O2^-O2^");
12245     end case;
12246
12247   end Compiler;
12248
12249 end Build;
12250 @end group
12251 @end smallexample
12252
12253 @noindent
12254 @code{Style_Type} is an example of a @emph{string type}, which is the project
12255 file analog of an Ada enumeration type but whose components are string literals
12256 rather than identifiers.  @code{Style} is declared as a variable of this type.
12257
12258 The form @code{external("STYLE", "deb")} is known as an
12259 @emph{external reference}; its first argument is the name of an
12260 @emph{external variable}, and the second argument is a default value to be
12261 used if the external variable doesn't exist.  You can define an external
12262 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
12263 or you can use ^an environment variable^a logical name^
12264 as an external variable.
12265
12266 Each @code{case} construct is expanded by the Project Manager based on the
12267 value of @code{Style}. Thus the command
12268 @ifclear vms
12269 @smallexample
12270 gnatmake -P/common/build.gpr -XSTYLE=deb
12271 @end smallexample
12272 @end ifclear
12273
12274 @ifset vms
12275 @smallexample
12276 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
12277 @end smallexample
12278 @end ifset
12279
12280 @noindent
12281 is equivalent to the @command{gnatmake} invocation using the project file
12282 @file{debug.gpr} in the earlier example.  So is the command
12283 @smallexample
12284 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
12285 @end smallexample
12286
12287 @noindent
12288 since @code{"deb"} is the default for @code{STYLE}.
12289
12290 Analogously,
12291
12292 @ifclear vms
12293 @smallexample
12294 gnatmake -P/common/build.gpr -XSTYLE=rel
12295 @end smallexample
12296 @end ifclear
12297
12298 @ifset vms
12299 @smallexample
12300 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
12301 @end smallexample
12302 @end ifset
12303
12304 @noindent
12305 is equivalent to the @command{gnatmake} invocation using the project file
12306 @file{release.gpr} in the earlier example.
12307
12308 @node Importing Other Projects
12309 @subsection Importing Other Projects
12310 @cindex @code{ADA_PROJECT_PATH}
12311 @cindex @code{GPR_PROJECT_PATH}
12312
12313 @noindent
12314 A compilation unit in a source file in one project may depend on compilation
12315 units in source files in other projects.  To compile this unit under
12316 control of a project file, the
12317 dependent project must @emph{import} the projects containing the needed source
12318 files.
12319 This effect is obtained using syntax similar to an Ada @code{with} clause,
12320 but where @code{with}ed entities are strings that denote project files.
12321
12322 As an example, suppose that the two projects @code{GUI_Proj} and
12323 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
12324 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
12325 and @file{^/comm^[COMM]^}, respectively.
12326 Suppose that the source files for @code{GUI_Proj} are
12327 @file{gui.ads} and @file{gui.adb}, and that the source files for
12328 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
12329 files is located in its respective project file directory.  Schematically:
12330
12331 @smallexample
12332 @group
12333 ^/gui^[GUI]^
12334   gui_proj.gpr
12335   gui.ads
12336   gui.adb
12337 @end group
12338
12339 @group
12340 ^/comm^[COMM]^
12341   comm_proj.gpr
12342   comm.ads
12343   comm.adb
12344 @end group
12345 @end smallexample
12346
12347 @noindent
12348 We want to develop an application in directory @file{^/app^[APP]^} that
12349 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
12350 the corresponding project files (e.g.@: the ^switch^switch^ settings
12351 and object directory).
12352 Skeletal code for a main procedure might be something like the following:
12353
12354 @smallexample @c ada
12355 @group
12356 with GUI, Comm;
12357 procedure App_Main is
12358    @dots{}
12359 begin
12360    @dots{}
12361 end App_Main;
12362 @end group
12363 @end smallexample
12364
12365 @noindent
12366 Here is a project file, @file{app_proj.gpr}, that achieves the desired
12367 effect:
12368
12369 @smallexample @c projectfile
12370 @group
12371 with "/gui/gui_proj", "/comm/comm_proj";
12372 project App_Proj is
12373    for Main use ("app_main");
12374 end App_Proj;
12375 @end group
12376 @end smallexample
12377
12378 @noindent
12379 Building an executable is achieved through the command:
12380 @smallexample
12381 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
12382 @end smallexample
12383 @noindent
12384 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
12385 in the directory where @file{app_proj.gpr} resides.
12386
12387 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
12388 (as illustrated above) the @code{with} clause can omit the extension.
12389
12390 Our example specified an absolute path for each imported project file.
12391 Alternatively, the directory name of an imported object can be omitted
12392 if either
12393 @itemize @bullet
12394 @item
12395 The imported project file is in the same directory as the importing project
12396 file, or
12397 @item
12398 You have defined one or two ^environment variables^logical names^
12399 that includes the directory containing
12400 the needed project file. The syntax of @code{GPR_PROJECT_PATH} and
12401 @code{ADA_PROJECT_PATH} is the same as
12402 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
12403 directory names separated by colons (semicolons on Windows).
12404 @end itemize
12405
12406 @noindent
12407 Thus, if we define @code{ADA_PROJECT_PATH} or @code{GPR_PROJECT_PATH}
12408 to include @file{^/gui^[GUI]^} and
12409 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
12410 as follows:
12411
12412 @smallexample @c projectfile
12413 @group
12414 with "gui_proj", "comm_proj";
12415 project App_Proj is
12416    for Main use ("app_main");
12417 end App_Proj;
12418 @end group
12419 @end smallexample
12420
12421 @noindent
12422 Importing other projects can create ambiguities.
12423 For example, the same unit might be present in different imported projects, or
12424 it might be present in both the importing project and in an imported project.
12425 Both of these conditions are errors.  Note that in the current version of
12426 the Project Manager, it is illegal to have an ambiguous unit even if the
12427 unit is never referenced by the importing project.  This restriction may be
12428 relaxed in a future release.
12429
12430 @node Extending a Project
12431 @subsection Extending a Project
12432
12433 @noindent
12434 In large software systems it is common to have multiple
12435 implementations of a common interface; in Ada terms, multiple versions of a
12436 package body for the same spec.  For example, one implementation
12437 might be safe for use in tasking programs, while another might only be used
12438 in sequential applications.  This can be modeled in GNAT using the concept
12439 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
12440 another project (the ``parent'') then by default all source files of the
12441 parent project are inherited by the child, but the child project can
12442 override any of the parent's source files with new versions, and can also
12443 add new files.  This facility is the project analog of a type extension in
12444 Object-Oriented Programming.  Project hierarchies are permitted (a child
12445 project may be the parent of yet another project), and a project that
12446 inherits one project can also import other projects.
12447
12448 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
12449 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
12450 @file{pack.adb}, and @file{proc.adb}:
12451
12452 @smallexample
12453 @group
12454 ^/seq^[SEQ]^
12455   pack.ads
12456   pack.adb
12457   proc.adb
12458   seq_proj.gpr
12459 @end group
12460 @end smallexample
12461
12462 @noindent
12463 Note that the project file can simply be empty (that is, no attribute or
12464 package is defined):
12465
12466 @smallexample @c projectfile
12467 @group
12468 project Seq_Proj is
12469 end Seq_Proj;
12470 @end group
12471 @end smallexample
12472
12473 @noindent
12474 implying that its source files are all the Ada source files in the project
12475 directory.
12476
12477 Suppose we want to supply an alternate version of @file{pack.adb}, in
12478 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
12479 @file{pack.ads} and @file{proc.adb}.  We can define a project
12480 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
12481
12482 @smallexample
12483 @group
12484 ^/tasking^[TASKING]^
12485   pack.adb
12486   tasking_proj.gpr
12487 @end group
12488
12489 @group
12490 project Tasking_Proj extends "/seq/seq_proj" is
12491 end Tasking_Proj;
12492 @end group
12493 @end smallexample
12494
12495 @noindent
12496 The version of @file{pack.adb} used in a build depends on which project file
12497 is specified.
12498
12499 Note that we could have obtained the desired behavior using project import
12500 rather than project inheritance; a @code{base} project would contain the
12501 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
12502 import @code{base} and add @file{pack.adb}, and likewise a tasking project
12503 would import @code{base} and add a different version of @file{pack.adb}.  The
12504 choice depends on whether other sources in the original project need to be
12505 overridden.  If they do, then project extension is necessary, otherwise,
12506 importing is sufficient.
12507
12508 @noindent
12509 In a project file that extends another project file, it is possible to
12510 indicate that an inherited source is not part of the sources of the extending
12511 project. This is necessary sometimes when a package spec has been overloaded
12512 and no longer requires a body: in this case, it is necessary to indicate that
12513 the inherited body is not part of the sources of the project, otherwise there
12514 will be a compilation error when compiling the spec.
12515
12516 For that purpose, the attribute @code{Excluded_Source_Files} is used.
12517 Its value is a string list: a list of file names. It is also possible to use
12518 attribute @code{Excluded_Source_List_File}. Its value is a single string:
12519 the file name of a text file containing a list of file names, one per line.
12520
12521 @smallexample @c @projectfile
12522 project B extends "a" is
12523    for Source_Files use ("pkg.ads");
12524    --  New spec of Pkg does not need a completion
12525    for Excluded_Source_Files use ("pkg.adb");
12526 end B;
12527 @end smallexample
12528
12529 Attribute @code{Excluded_Source_Files} may also be used to check if a source
12530 is still needed: if it is possible to build using @command{gnatmake} when such
12531 a source is put in attribute @code{Excluded_Source_Files} of a project P, then
12532 it is possible to remove the source completely from a system that includes
12533 project P.
12534
12535 @c ***********************
12536 @c * Project File Syntax *
12537 @c ***********************
12538
12539 @node Project File Syntax
12540 @section Project File Syntax
12541
12542 @menu
12543 * Basic Syntax::
12544 * Qualified Projects::
12545 * Packages::
12546 * Expressions::
12547 * String Types::
12548 * Variables::
12549 * Attributes::
12550 * Associative Array Attributes::
12551 * case Constructions::
12552 @end menu
12553
12554 @noindent
12555 This section describes the structure of project files.
12556
12557 A project may be an @emph{independent project}, entirely defined by a single
12558 project file. Any Ada source file in an independent project depends only
12559 on the predefined library and other Ada source files in the same project.
12560
12561 @noindent
12562 A project may also @dfn{depend on} other projects, in either or both of
12563 the following ways:
12564 @itemize @bullet
12565 @item It may import any number of projects
12566 @item It may extend at most one other project
12567 @end itemize
12568
12569 @noindent
12570 The dependence relation is a directed acyclic graph (the subgraph reflecting
12571 the ``extends'' relation is a tree).
12572
12573 A project's @dfn{immediate sources} are the source files directly defined by
12574 that project, either implicitly by residing in the project file's directory,
12575 or explicitly through any of the source-related attributes described below.
12576 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
12577 of @var{proj} together with the immediate sources (unless overridden) of any
12578 project on which @var{proj} depends (either directly or indirectly).
12579
12580 @node Basic Syntax
12581 @subsection Basic Syntax
12582
12583 @noindent
12584 As seen in the earlier examples, project files have an Ada-like syntax.
12585 The minimal project file is:
12586 @smallexample @c projectfile
12587 @group
12588 project Empty is
12589
12590 end Empty;
12591 @end group
12592 @end smallexample
12593
12594 @noindent
12595 The identifier @code{Empty} is the name of the project.
12596 This project name must be present after the reserved
12597 word @code{end} at the end of the project file, followed by a semi-colon.
12598
12599 Any name in a project file, such as the project name or a variable name,
12600 has the same syntax as an Ada identifier.
12601
12602 The reserved words of project files are the Ada 95 reserved words plus
12603 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
12604 reserved words currently used in project file syntax are:
12605
12606 @itemize @bullet
12607 @item
12608 @code{all}
12609 @item
12610 @code{at}
12611 @item
12612 @code{case}
12613 @item
12614 @code{end}
12615 @item
12616 @code{for}
12617 @item
12618 @code{is}
12619 @item
12620 @code{limited}
12621 @item
12622 @code{null}
12623 @item
12624 @code{others}
12625 @item
12626 @code{package}
12627 @item
12628 @code{renames}
12629 @item
12630 @code{type}
12631 @item
12632 @code{use}
12633 @item
12634 @code{when}
12635 @item
12636 @code{with}
12637 @end itemize
12638
12639 @noindent
12640 Comments in project files have the same syntax as in Ada, two consecutive
12641 hyphens through the end of the line.
12642
12643 @node Qualified Projects
12644 @subsection Qualified Projects
12645
12646 @noindent
12647 Before the reserved @code{project}, there may be one or two "qualifiers", that
12648 is identifiers or other reserved words, to qualify the project.
12649
12650 The current list of qualifiers is:
12651
12652 @itemize @bullet
12653 @item
12654 @code{abstract}: qualify a project with no sources. A qualified abstract
12655 project must either have no declaration of attributes @code{Source_Dirs},
12656 @code{Source_Files}, @code{Languages} or @code{Source_List_File}, or one of
12657 @code{Source_Dirs}, @code{Source_Files}, or @code{Languages} must be declared
12658 as empty. If it extends another project, the project it extends must also be a
12659 qualified abstract project.
12660
12661 @item
12662 @code{standard}: a standard project is a non library project with sources.
12663
12664 @item
12665 @code{aggregate}: for future extension
12666
12667 @item
12668 @code{aggregate library}: for future extension
12669
12670 @item
12671 @code{library}: a library project must declare both attributes
12672 @code{Library_Name} and @code{Library_Dir}.
12673
12674 @item
12675 @code{configuration}: a configuration project cannot be in a project tree.
12676 @end itemize
12677
12678 @node Packages
12679 @subsection Packages
12680
12681 @noindent
12682 A project file may contain @emph{packages}. The name of a package must be one
12683 of the identifiers from the following list. A package
12684 with a given name may only appear once in a project file. Package names are
12685 case insensitive. The following package names are legal:
12686
12687 @itemize @bullet
12688 @item
12689 @code{Naming}
12690 @item
12691 @code{Builder}
12692 @item
12693 @code{Compiler}
12694 @item
12695 @code{Binder}
12696 @item
12697 @code{Linker}
12698 @item
12699 @code{Finder}
12700 @item
12701 @code{Cross_Reference}
12702 @item
12703 @code{Check}
12704 @item
12705 @code{Eliminate}
12706 @item
12707 @code{Pretty_Printer}
12708 @item
12709 @code{Metrics}
12710 @item
12711 @code{gnatls}
12712 @item
12713 @code{gnatstub}
12714 @item
12715 @code{IDE}
12716 @item
12717 @code{Language_Processing}
12718 @end itemize
12719
12720 @noindent
12721 In its simplest form, a package may be empty:
12722
12723 @smallexample @c projectfile
12724 @group
12725 project Simple is
12726   package Builder is
12727   end Builder;
12728 end Simple;
12729 @end group
12730 @end smallexample
12731
12732 @noindent
12733 A package may contain @emph{attribute declarations},
12734 @emph{variable declarations} and @emph{case constructions}, as will be
12735 described below.
12736
12737 When there is ambiguity between a project name and a package name,
12738 the name always designates the project. To avoid possible confusion, it is
12739 always a good idea to avoid naming a project with one of the
12740 names allowed for packages or any name that starts with @code{gnat}.
12741
12742 @node Expressions
12743 @subsection Expressions
12744
12745 @noindent
12746 An @emph{expression} is either a @emph{string expression} or a
12747 @emph{string list expression}.
12748
12749 A @emph{string expression} is either a @emph{simple string expression} or a
12750 @emph{compound string expression}.
12751
12752 A @emph{simple string expression} is one of the following:
12753 @itemize @bullet
12754 @item A literal string; e.g.@: @code{"comm/my_proj.gpr"}
12755 @item A string-valued variable reference (@pxref{Variables})
12756 @item A string-valued attribute reference (@pxref{Attributes})
12757 @item An external reference (@pxref{External References in Project Files})
12758 @end itemize
12759
12760 @noindent
12761 A @emph{compound string expression} is a concatenation of string expressions,
12762 using the operator @code{"&"}
12763 @smallexample
12764        Path & "/" & File_Name & ".ads"
12765 @end smallexample
12766
12767 @noindent
12768 A @emph{string list expression} is either a
12769 @emph{simple string list expression} or a
12770 @emph{compound string list expression}.
12771
12772 A @emph{simple string list expression} is one of the following:
12773 @itemize @bullet
12774 @item A parenthesized list of zero or more string expressions,
12775 separated by commas
12776 @smallexample
12777    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
12778    Empty_List := ();
12779 @end smallexample
12780 @item A string list-valued variable reference
12781 @item A string list-valued attribute reference
12782 @end itemize
12783
12784 @noindent
12785 A @emph{compound string list expression} is the concatenation (using
12786 @code{"&"}) of a simple string list expression and an expression.  Note that
12787 each term in a compound string list expression, except the first, may be
12788 either a string expression or a string list expression.
12789
12790 @smallexample @c projectfile
12791 @group
12792    File_Name_List := () & File_Name; --  One string in this list
12793    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
12794    --  Two strings
12795    Big_List := File_Name_List & Extended_File_Name_List;
12796    --  Concatenation of two string lists: three strings
12797    Illegal_List := "gnat.adc" & Extended_File_Name_List;
12798    --  Illegal: must start with a string list
12799 @end group
12800 @end smallexample
12801
12802 @node String Types
12803 @subsection String Types
12804
12805 @noindent
12806 A @emph{string type declaration} introduces a discrete set of string literals.
12807 If a string variable is declared to have this type, its value
12808 is restricted to the given set of literals.
12809
12810 Here is an example of a string type declaration:
12811
12812 @smallexample @c projectfile
12813    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
12814 @end smallexample
12815
12816 @noindent
12817 Variables of a string type are called @emph{typed variables}; all other
12818 variables are called @emph{untyped variables}. Typed variables are
12819 particularly useful in @code{case} constructions, to support conditional
12820 attribute declarations.
12821 (@pxref{case Constructions}).
12822
12823 The string literals in the list are case sensitive and must all be different.
12824 They may include any graphic characters allowed in Ada, including spaces.
12825
12826 A string type may only be declared at the project level, not inside a package.
12827
12828 A string type may be referenced by its name if it has been declared in the same
12829 project file, or by an expanded name whose prefix is the name of the project
12830 in which it is declared.
12831
12832 @node Variables
12833 @subsection Variables
12834
12835 @noindent
12836 A variable may be declared at the project file level, or within a package.
12837 Here are some examples of variable declarations:
12838
12839 @smallexample @c projectfile
12840 @group
12841    This_OS : OS := external ("OS"); --  a typed variable declaration
12842    That_OS := "GNU/Linux";          --  an untyped variable declaration
12843 @end group
12844 @end smallexample
12845
12846 @noindent
12847 The syntax of a @emph{typed variable declaration} is identical to the Ada
12848 syntax for an object declaration. By contrast, the syntax of an untyped
12849 variable declaration is identical to an Ada assignment statement. In fact,
12850 variable declarations in project files have some of the characteristics of
12851 an assignment, in that successive declarations for the same variable are
12852 allowed. Untyped variable declarations do establish the expected kind of the
12853 variable (string or string list), and successive declarations for it must
12854 respect the initial kind.
12855
12856 @noindent
12857 A string variable declaration (typed or untyped) declares a variable
12858 whose value is a string. This variable may be used as a string expression.
12859 @smallexample @c projectfile
12860    File_Name       := "readme.txt";
12861    Saved_File_Name := File_Name & ".saved";
12862 @end smallexample
12863
12864 @noindent
12865 A string list variable declaration declares a variable whose value is a list
12866 of strings. The list may contain any number (zero or more) of strings.
12867
12868 @smallexample @c projectfile
12869    Empty_List := ();
12870    List_With_One_Element := ("^-gnaty^-gnaty^");
12871    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
12872    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
12873                  "pack2.ada", "util_.ada", "util.ada");
12874 @end smallexample
12875
12876 @noindent
12877 The same typed variable may not be declared more than once at project level,
12878 and it may not be declared more than once in any package; it is in effect
12879 a constant.
12880
12881 The same untyped variable may be declared several times. Declarations are
12882 elaborated in the order in which they appear, so  the new value replaces
12883 the old one, and any subsequent reference to the variable uses the new value.
12884 However, as noted above, if a variable has been declared as a string, all
12885 subsequent
12886 declarations must give it a string value. Similarly, if a variable has
12887 been declared as a string list, all subsequent declarations
12888 must give it a string list value.
12889
12890 A @emph{variable reference} may take several forms:
12891
12892 @itemize @bullet
12893 @item The simple variable name, for a variable in the current package (if any)
12894 or in the current project
12895 @item An expanded name, whose prefix is a context name.
12896 @end itemize
12897
12898 @noindent
12899 A @emph{context} may be one of the following:
12900
12901 @itemize @bullet
12902 @item The name of an existing package in the current project
12903 @item The name of an imported project of the current project
12904 @item The name of an ancestor project (i.e., a project extended by the current
12905 project, either directly or indirectly)
12906 @item An expanded name whose prefix is an imported/parent project name, and
12907 whose selector is a package name in that project.
12908 @end itemize
12909
12910 @noindent
12911 A variable reference may be used in an expression.
12912
12913 @node Attributes
12914 @subsection Attributes
12915
12916 @noindent
12917 A project (and its packages) may have @emph{attributes} that define
12918 the project's properties.  Some attributes have values that are strings;
12919 others have values that are string lists.
12920
12921 There are two categories of attributes: @emph{simple attributes}
12922 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
12923
12924 Legal project attribute names, and attribute names for each legal package are
12925 listed below. Attributes names are case-insensitive.
12926
12927 The following attributes are defined on projects (all are simple attributes):
12928
12929 @multitable @columnfractions .4 .3
12930 @item @emph{Attribute Name}
12931 @tab @emph{Value}
12932 @item @code{Source_Files}
12933 @tab string list
12934 @item @code{Source_Dirs}
12935 @tab string list
12936 @item @code{Source_List_File}
12937 @tab string
12938 @item @code{Object_Dir}
12939 @tab string
12940 @item @code{Exec_Dir}
12941 @tab string
12942 @item @code{Excluded_Source_Dirs}
12943 @tab string list
12944 @item @code{Excluded_Source_Files}
12945 @tab string list
12946 @item @code{Excluded_Source_List_File}
12947 @tab string
12948 @item @code{Languages}
12949 @tab string list
12950 @item @code{Main}
12951 @tab string list
12952 @item @code{Library_Dir}
12953 @tab string
12954 @item @code{Library_Name}
12955 @tab string
12956 @item @code{Library_Kind}
12957 @tab string
12958 @item @code{Library_Version}
12959 @tab string
12960 @item @code{Library_Interface}
12961 @tab string
12962 @item @code{Library_Auto_Init}
12963 @tab string
12964 @item @code{Library_Options}
12965 @tab string list
12966 @item @code{Library_Src_Dir}
12967 @tab string
12968 @item @code{Library_ALI_Dir}
12969 @tab string
12970 @item @code{Library_GCC}
12971 @tab string
12972 @item @code{Library_Symbol_File}
12973 @tab string
12974 @item @code{Library_Symbol_Policy}
12975 @tab string
12976 @item @code{Library_Reference_Symbol_File}
12977 @tab string
12978 @item @code{Externally_Built}
12979 @tab string
12980 @end multitable
12981
12982 @noindent
12983 The following attributes are defined for package  @code{Naming}
12984 (@pxref{Naming Schemes}):
12985
12986 @multitable @columnfractions .4 .2 .2 .2
12987 @item Attribute Name @tab Category @tab Index @tab Value
12988 @item @code{Spec_Suffix}
12989 @tab associative array
12990 @tab language name
12991 @tab string
12992 @item @code{Body_Suffix}
12993 @tab associative array
12994 @tab language name
12995 @tab string
12996 @item @code{Separate_Suffix}
12997 @tab simple attribute
12998 @tab n/a
12999 @tab string
13000 @item @code{Casing}
13001 @tab simple attribute
13002 @tab n/a
13003 @tab string
13004 @item @code{Dot_Replacement}
13005 @tab simple attribute
13006 @tab n/a
13007 @tab string
13008 @item @code{Spec}
13009 @tab associative array
13010 @tab Ada unit name
13011 @tab string
13012 @item @code{Body}
13013 @tab associative array
13014 @tab Ada unit name
13015 @tab string
13016 @item @code{Specification_Exceptions}
13017 @tab associative array
13018 @tab language name
13019 @tab string list
13020 @item @code{Implementation_Exceptions}
13021 @tab associative array
13022 @tab language name
13023 @tab string list
13024 @end multitable
13025
13026 @noindent
13027 The following attributes are defined for packages @code{Builder},
13028 @code{Compiler}, @code{Binder},
13029 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
13030 (@pxref{^Switches^Switches^ and Project Files}).
13031
13032 @multitable @columnfractions .4 .2 .2 .2
13033 @item Attribute Name @tab Category @tab Index @tab Value
13034 @item @code{^Default_Switches^Default_Switches^}
13035 @tab associative array
13036 @tab language name
13037 @tab string list
13038 @item @code{^Switches^Switches^}
13039 @tab associative array
13040 @tab file name
13041 @tab string list
13042 @end multitable
13043
13044 @noindent
13045 In addition, package @code{Compiler} has a single string attribute
13046 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
13047 string attribute @code{Global_Configuration_Pragmas}.
13048
13049 @noindent
13050 Each simple attribute has a default value: the empty string (for string-valued
13051 attributes) and the empty list (for string list-valued attributes).
13052
13053 An attribute declaration defines a new value for an attribute.
13054
13055 Examples of simple attribute declarations:
13056
13057 @smallexample @c projectfile
13058    for Object_Dir use "objects";
13059    for Source_Dirs use ("units", "test/drivers");
13060 @end smallexample
13061
13062 @noindent
13063 The syntax of a @dfn{simple attribute declaration} is similar to that of an
13064 attribute definition clause in Ada.
13065
13066 Attributes references may be appear in expressions.
13067 The general form for such a reference is @code{<entity>'<attribute>}:
13068 Associative array attributes are functions. Associative
13069 array attribute references must have an argument that is a string literal.
13070
13071 Examples are:
13072
13073 @smallexample @c projectfile
13074   project'Object_Dir
13075   Naming'Dot_Replacement
13076   Imported_Project'Source_Dirs
13077   Imported_Project.Naming'Casing
13078   Builder'^Default_Switches^Default_Switches^("Ada")
13079 @end smallexample
13080
13081 @noindent
13082 The prefix of an attribute may be:
13083 @itemize @bullet
13084 @item @code{project} for an attribute of the current project
13085 @item The name of an existing package of the current project
13086 @item The name of an imported project
13087 @item The name of a parent project that is extended by the current project
13088 @item An expanded name whose prefix is imported/parent project name,
13089 and whose selector is a package name
13090 @end itemize
13091
13092 @noindent
13093 Example:
13094 @smallexample @c projectfile
13095 @group
13096    project Prj is
13097      for Source_Dirs use project'Source_Dirs & "units";
13098      for Source_Dirs use project'Source_Dirs & "test/drivers"
13099    end Prj;
13100 @end group
13101 @end smallexample
13102
13103 @noindent
13104 In the first attribute declaration, initially the attribute @code{Source_Dirs}
13105 has the default value: an empty string list. After this declaration,
13106 @code{Source_Dirs} is a string list of one element: @code{"units"}.
13107 After the second attribute declaration @code{Source_Dirs} is a string list of
13108 two elements: @code{"units"} and @code{"test/drivers"}.
13109
13110 Note: this example is for illustration only. In practice,
13111 the project file would contain only one attribute declaration:
13112
13113 @smallexample @c projectfile
13114    for Source_Dirs use ("units", "test/drivers");
13115 @end smallexample
13116
13117 @node Associative Array Attributes
13118 @subsection Associative Array Attributes
13119
13120 @noindent
13121 Some attributes are defined as @emph{associative arrays}. An associative
13122 array may be regarded as a function that takes a string as a parameter
13123 and delivers a string or string list value as its result.
13124
13125 Here are some examples of single associative array attribute associations:
13126
13127 @smallexample @c projectfile
13128    for Body ("main") use "Main.ada";
13129    for ^Switches^Switches^ ("main.ada")
13130        use ("^-v^-v^",
13131             "^-gnatv^-gnatv^");
13132    for ^Switches^Switches^ ("main.ada")
13133             use Builder'^Switches^Switches^ ("main.ada")
13134               & "^-g^-g^";
13135 @end smallexample
13136
13137 @noindent
13138 Like untyped variables and simple attributes, associative array attributes
13139 may be declared several times. Each declaration supplies a new value for the
13140 attribute, and replaces the previous setting.
13141
13142 @noindent
13143 An associative array attribute may be declared as a full associative array
13144 declaration, with the value of the same attribute in an imported or extended
13145 project.
13146
13147 @smallexample @c projectfile
13148    package Builder is
13149       for Default_Switches use Default.Builder'Default_Switches;
13150    end Builder;
13151 @end smallexample
13152
13153 @noindent
13154 In this example, @code{Default} must be either a project imported by the
13155 current project, or the project that the current project extends. If the
13156 attribute is in a package (in this case, in package @code{Builder}), the same
13157 package needs to be specified.
13158
13159 @noindent
13160 A full associative array declaration replaces any other declaration for the
13161 attribute, including other full associative array declaration. Single
13162 associative array associations may be declare after a full associative
13163 declaration, modifying the value for a single association of the attribute.
13164
13165 @node case Constructions
13166 @subsection @code{case} Constructions
13167
13168 @noindent
13169 A @code{case} construction is used in a project file to effect conditional
13170 behavior.
13171 Here is a typical example:
13172
13173 @smallexample @c projectfile
13174 @group
13175 project MyProj is
13176    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
13177
13178    OS : OS_Type := external ("OS", "GNU/Linux");
13179 @end group
13180
13181 @group
13182    package Compiler is
13183      case OS is
13184        when "GNU/Linux" | "Unix" =>
13185          for ^Default_Switches^Default_Switches^ ("Ada")
13186              use ("^-gnath^-gnath^");
13187        when "NT" =>
13188          for ^Default_Switches^Default_Switches^ ("Ada")
13189              use ("^-gnatP^-gnatP^");
13190        when others =>
13191      end case;
13192    end Compiler;
13193 end MyProj;
13194 @end group
13195 @end smallexample
13196
13197 @noindent
13198 The syntax of a @code{case} construction is based on the Ada case statement
13199 (although there is no @code{null} construction for empty alternatives).
13200
13201 The case expression must be a typed string variable.
13202 Each alternative comprises the reserved word @code{when}, either a list of
13203 literal strings separated by the @code{"|"} character or the reserved word
13204 @code{others},  and the @code{"=>"} token.
13205 Each literal string must belong to the string type that is the type of the
13206 case variable.
13207 An @code{others} alternative, if present, must occur last.
13208
13209 After each @code{=>}, there are zero or more constructions.  The only
13210 constructions allowed in a case construction are other case constructions,
13211 attribute declarations and variable declarations. String type declarations and
13212 package declarations are not allowed. Variable declarations are restricted to
13213 variables that have already been declared before the case construction.
13214
13215 The value of the case variable is often given by an external reference
13216 (@pxref{External References in Project Files}).
13217
13218 @c ****************************************
13219 @c * Objects and Sources in Project Files *
13220 @c ****************************************
13221
13222 @node Objects and Sources in Project Files
13223 @section Objects and Sources in Project Files
13224
13225 @menu
13226 * Object Directory::
13227 * Exec Directory::
13228 * Source Directories::
13229 * Source File Names::
13230 @end menu
13231
13232 @noindent
13233 Each project has exactly one object directory and one or more source
13234 directories. The source directories must contain at least one source file,
13235 unless  the project file explicitly specifies that no source files are present
13236 (@pxref{Source File Names}).
13237
13238 @node Object Directory
13239 @subsection Object Directory
13240
13241 @noindent
13242 The object directory for a project is the directory containing the compiler's
13243 output (such as @file{ALI} files and object files) for the project's immediate
13244 sources.
13245
13246 The object directory is given by the value of the attribute @code{Object_Dir}
13247 in the project file.
13248
13249 @smallexample @c projectfile
13250    for Object_Dir use "objects";
13251 @end smallexample
13252
13253 @noindent
13254 The attribute @code{Object_Dir} has a string value, the path name of the object
13255 directory. The path name may be absolute or relative to the directory of the
13256 project file. This directory must already exist, and be readable and writable.
13257
13258 By default, when the attribute @code{Object_Dir} is not given an explicit value
13259 or when its value is the empty string, the object directory is the same as the
13260 directory containing the project file.
13261
13262 @node Exec Directory
13263 @subsection Exec Directory
13264
13265 @noindent
13266 The exec directory for a project is the directory containing the executables
13267 for the project's main subprograms.
13268
13269 The exec directory is given by the value of the attribute @code{Exec_Dir}
13270 in the project file.
13271
13272 @smallexample @c projectfile
13273    for Exec_Dir use "executables";
13274 @end smallexample
13275
13276 @noindent
13277 The attribute @code{Exec_Dir} has a string value, the path name of the exec
13278 directory. The path name may be absolute or relative to the directory of the
13279 project file. This directory must already exist, and be writable.
13280
13281 By default, when the attribute @code{Exec_Dir} is not given an explicit value
13282 or when its value is the empty string, the exec directory is the same as the
13283 object directory of the project file.
13284
13285 @node Source Directories
13286 @subsection Source Directories
13287
13288 @noindent
13289 The source directories of a project are specified by the project file
13290 attribute @code{Source_Dirs}.
13291
13292 This attribute's value is a string list. If the attribute is not given an
13293 explicit value, then there is only one source directory, the one where the
13294 project file resides.
13295
13296 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
13297 as in
13298
13299 @smallexample @c projectfile
13300     for Source_Dirs use ();
13301 @end smallexample
13302
13303 @noindent
13304 indicates that the project contains no source files.
13305
13306 Otherwise, each string in the string list designates one or more
13307 source directories.
13308
13309 @smallexample @c projectfile
13310    for Source_Dirs use ("sources", "test/drivers");
13311 @end smallexample
13312
13313 @noindent
13314 If a string in the list ends with @code{"/**"},  then the directory whose path
13315 name precedes the two asterisks, as well as all its subdirectories
13316 (recursively), are source directories.
13317
13318 @smallexample @c projectfile
13319    for Source_Dirs use ("/system/sources/**");
13320 @end smallexample
13321
13322 @noindent
13323 Here the directory @code{/system/sources} and all of its subdirectories
13324 (recursively) are source directories.
13325
13326 To specify that the source directories are the directory of the project file
13327 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
13328 @smallexample @c projectfile
13329    for Source_Dirs use ("./**");
13330 @end smallexample
13331
13332 @noindent
13333 Each of the source directories must exist and be readable.
13334
13335 @node Source File Names
13336 @subsection Source File Names
13337
13338 @noindent
13339 In a project that contains source files, their names may be specified by the
13340 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
13341 (a string). Source file names never include any directory information.
13342
13343 If the attribute @code{Source_Files} is given an explicit value, then each
13344 element of the list is a source file name.
13345
13346 @smallexample @c projectfile
13347    for Source_Files use ("main.adb");
13348    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
13349 @end smallexample
13350
13351 @noindent
13352 If the attribute @code{Source_Files} is not given an explicit value,
13353 but the attribute @code{Source_List_File} is given a string value,
13354 then the source file names are contained in the text file whose path name
13355 (absolute or relative to the directory of the project file) is the
13356 value of the attribute @code{Source_List_File}.
13357
13358 Each line in the file that is not empty or is not a comment
13359 contains a source file name.
13360
13361 @smallexample @c projectfile
13362    for Source_List_File use "source_list.txt";
13363 @end smallexample
13364
13365 @noindent
13366 By default, if neither the attribute @code{Source_Files} nor the attribute
13367 @code{Source_List_File} is given an explicit value, then each file in the
13368 source directories that conforms to the project's naming scheme
13369 (@pxref{Naming Schemes}) is an immediate source of the project.
13370
13371 A warning is issued if both attributes @code{Source_Files} and
13372 @code{Source_List_File} are given explicit values. In this case, the attribute
13373 @code{Source_Files} prevails.
13374
13375 Each source file name must be the name of one existing source file
13376 in one of the source directories.
13377
13378 A @code{Source_Files} attribute whose value is an empty list
13379 indicates that there are no source files in the project.
13380
13381 If the order of the source directories is known statically, that is if
13382 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
13383 be several files with the same source file name. In this case, only the file
13384 in the first directory is considered as an immediate source of the project
13385 file. If the order of the source directories is not known statically, it is
13386 an error to have several files with the same source file name.
13387
13388 Projects can be specified to have no Ada source
13389 files: the value of @code{Source_Dirs} or @code{Source_Files} may be an empty
13390 list, or the @code{"Ada"} may be absent from @code{Languages}:
13391
13392 @smallexample @c projectfile
13393    for Source_Dirs use ();
13394    for Source_Files use ();
13395    for Languages use ("C", "C++");
13396 @end smallexample
13397
13398 @noindent
13399 Otherwise, a project must contain at least one immediate source.
13400
13401 Projects with no source files are useful as template packages
13402 (@pxref{Packages in Project Files}) for other projects; in particular to
13403 define a package @code{Naming} (@pxref{Naming Schemes}).
13404
13405 @c ****************************
13406 @c * Importing Projects *
13407 @c ****************************
13408
13409 @node  Importing Projects
13410 @section Importing Projects
13411 @cindex @code{ADA_PROJECT_PATH}
13412 @cindex @code{GPR_PROJECT_PATH}
13413
13414 @noindent
13415 An immediate source of a project P may depend on source files that
13416 are neither immediate sources of P nor in the predefined library.
13417 To get this effect, P must @emph{import} the projects that contain the needed
13418 source files.
13419
13420 @smallexample @c projectfile
13421 @group
13422   with "project1", "utilities.gpr";
13423   with "/namings/apex.gpr";
13424   project Main is
13425     @dots{}
13426 @end group
13427 @end smallexample
13428
13429 @noindent
13430 As can be seen in this example, the syntax for importing projects is similar
13431 to the syntax for importing compilation units in Ada. However, project files
13432 use literal strings instead of names, and the @code{with} clause identifies
13433 project files rather than packages.
13434
13435 Each literal string is the file name or path name (absolute or relative) of a
13436 project file. If a string corresponds to a file name, with no path or a
13437 relative path, then its location is determined by the @emph{project path}. The
13438 latter can be queried using @code{gnatls -v}. It contains:
13439
13440 @itemize @bullet
13441 @item
13442 In first position, the directory containing the current project file.
13443 @item
13444 In last position, the default project directory. This default project directory
13445 is part of the GNAT installation and is the standard place to install project
13446 files giving access to standard support libraries.
13447 @ifclear vms
13448 @ref{Installing a library}
13449 @end ifclear
13450
13451 @item
13452 In between, all the directories referenced in the
13453 ^environment variables^logical names^ @env{GPR_PROJECT_PATH}
13454 and @env{ADA_PROJECT_PATH} if they exist, and in that order.
13455 @end itemize
13456
13457 @noindent
13458 If a relative pathname is used, as in
13459
13460 @smallexample @c projectfile
13461   with "tests/proj";
13462 @end smallexample
13463
13464 @noindent
13465 then the full path for the project is constructed by concatenating this
13466 relative path to those in the project path, in order, until a matching file is
13467 found. Any symbolic link will be fully resolved in the directory of the
13468 importing project file before the imported project file is examined.
13469
13470 If the @code{with}'ed project file name does not have an extension,
13471 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
13472 then the file name as specified in the @code{with} clause (no extension) will
13473 be used. In the above example, if a file @code{project1.gpr} is found, then it
13474 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
13475 then it will be used; if neither file exists, this is an error.
13476
13477 A warning is issued if the name of the project file does not match the
13478 name of the project; this check is case insensitive.
13479
13480 Any source file that is an immediate source of the imported project can be
13481 used by the immediate sources of the importing project, transitively. Thus
13482 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
13483 sources of @code{A} may depend on the immediate sources of @code{C}, even if
13484 @code{A} does not import @code{C} explicitly. However, this is not recommended,
13485 because if and when @code{B} ceases to import @code{C}, some sources in
13486 @code{A} will no longer compile.
13487
13488 A side effect of this capability is that normally cyclic dependencies are not
13489 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
13490 is not allowed to import @code{A}. However, there are cases when cyclic
13491 dependencies would be beneficial. For these cases, another form of import
13492 between projects exists, the @code{limited with}: a project @code{A} that
13493 imports a project @code{B} with a straight @code{with} may also be imported,
13494 directly or indirectly, by @code{B} on the condition that imports from @code{B}
13495 to @code{A} include at least one @code{limited with}.
13496
13497 @smallexample @c 0projectfile
13498 with "../b/b.gpr";
13499 with "../c/c.gpr";
13500 project A is
13501 end A;
13502
13503 limited with "../a/a.gpr";
13504 project B is
13505 end B;
13506
13507 with "../d/d.gpr";
13508 project C is
13509 end C;
13510
13511 limited with "../a/a.gpr";
13512 project D is
13513 end D;
13514 @end smallexample
13515
13516 @noindent
13517 In the above legal example, there are two project cycles:
13518 @itemize @bullet
13519 @item A-> B-> A
13520 @item A -> C -> D -> A
13521 @end itemize
13522
13523 @noindent
13524 In each of these cycle there is one @code{limited with}: import of @code{A}
13525 from @code{B} and import of @code{A} from @code{D}.
13526
13527 The difference between straight @code{with} and @code{limited with} is that
13528 the name of a project imported with a @code{limited with} cannot be used in the
13529 project that imports it. In particular, its packages cannot be renamed and
13530 its variables cannot be referred to.
13531
13532 An exception to the above rules for @code{limited with} is that for the main
13533 project specified to @command{gnatmake} or to the @command{GNAT} driver a
13534 @code{limited with} is equivalent to a straight @code{with}. For example,
13535 in the example above, projects @code{B} and @code{D} could not be main
13536 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
13537 each have a @code{limited with} that is the only one in a cycle of importing
13538 projects.
13539
13540 @c *********************
13541 @c * Project Extension *
13542 @c *********************
13543
13544 @node Project Extension
13545 @section Project Extension
13546
13547 @noindent
13548 During development of a large system, it is sometimes necessary to use
13549 modified versions of some of the source files, without changing the original
13550 sources. This can be achieved through the @emph{project extension} facility.
13551
13552 @smallexample @c projectfile
13553    project Modified_Utilities extends "/baseline/utilities.gpr" is @dots{}
13554 @end smallexample
13555
13556 @noindent
13557 A project extension declaration introduces an extending project
13558 (the @emph{child}) and a project being extended (the @emph{parent}).
13559
13560 By default, a child project inherits all the sources of its parent.
13561 However, inherited sources can be overridden: a unit in a parent is hidden
13562 by a unit of the same name in the child.
13563
13564 Inherited sources are considered to be sources (but not immediate sources)
13565 of the child project; see @ref{Project File Syntax}.
13566
13567 An inherited source file retains any switches specified in the parent project.
13568
13569 For example if the project @code{Utilities} contains the spec and the
13570 body of an Ada package @code{Util_IO}, then the project
13571 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
13572 The original body of @code{Util_IO} will not be considered in program builds.
13573 However, the package spec will still be found in the project
13574 @code{Utilities}.
13575
13576 A child project can have only one parent, except when it is qualified as
13577 abstract. But it may import any number of other projects.
13578
13579 A project is not allowed to import directly or indirectly at the same time a
13580 child project and any of its ancestors.
13581
13582 @c *******************************
13583 @c * Project Hierarchy Extension *
13584 @c *******************************
13585
13586 @node Project Hierarchy Extension
13587 @section Project Hierarchy Extension
13588
13589 @noindent
13590 When extending a large system spanning multiple projects, it is often
13591 inconvenient to extend every project in the hierarchy that is impacted by a
13592 small change introduced. In such cases, it is possible to create a virtual
13593 extension of entire hierarchy using @code{extends all} relationship.
13594
13595 When the project is extended using @code{extends all} inheritance, all projects
13596 that are imported by it, both directly and indirectly, are considered virtually
13597 extended. That is, the Project Manager creates "virtual projects"
13598 that extend every project in the hierarchy; all these virtual projects have
13599 no sources of their own and have as object directory the object directory of
13600 the root of "extending all" project.
13601
13602 It is possible to explicitly extend one or more projects in the hierarchy
13603 in order to modify the sources. These extending projects must be imported by
13604 the "extending all" project, which will replace the corresponding virtual
13605 projects with the explicit ones.
13606
13607 When building such a project hierarchy extension, the Project Manager will
13608 ensure that both modified sources and sources in virtual extending projects
13609 that depend on them, are recompiled.
13610
13611 By means of example, consider the following hierarchy of projects.
13612
13613 @enumerate
13614 @item
13615 project A, containing package P1
13616 @item
13617 project B importing A and containing package P2 which depends on P1
13618 @item
13619 project C importing B and containing package P3 which depends on P2
13620 @end enumerate
13621
13622 @noindent
13623 We want to modify packages P1 and P3.
13624
13625 This project hierarchy will need to be extended as follows:
13626
13627 @enumerate
13628 @item
13629 Create project A1 that extends A, placing modified P1 there:
13630
13631 @smallexample @c 0projectfile
13632 project A1 extends "(@dots{})/A" is
13633 end A1;
13634 @end smallexample
13635
13636 @item
13637 Create project C1 that "extends all" C and imports A1, placing modified
13638 P3 there:
13639
13640 @smallexample @c 0projectfile
13641 with "(@dots{})/A1";
13642 project C1 extends all "(@dots{})/C" is
13643 end C1;
13644 @end smallexample
13645 @end enumerate
13646
13647 When you build project C1, your entire modified project space will be
13648 recompiled, including the virtual project B1 that has been impacted by the
13649 "extending all" inheritance of project C.
13650
13651 Note that if a Library Project in the hierarchy is virtually extended,
13652 the virtual project that extends the Library Project is not a Library Project.
13653
13654 @c ****************************************
13655 @c * External References in Project Files *
13656 @c ****************************************
13657
13658 @node  External References in Project Files
13659 @section External References in Project Files
13660
13661 @noindent
13662 A project file may contain references to external variables; such references
13663 are called @emph{external references}.
13664
13665 An external variable is either defined as part of the environment (an
13666 environment variable in Unix, for example) or else specified on the command
13667 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
13668 If both, then the command line value is used.
13669
13670 The value of an external reference is obtained by means of the built-in
13671 function @code{external}, which returns a string value.
13672 This function has two forms:
13673 @itemize @bullet
13674 @item @code{external (external_variable_name)}
13675 @item @code{external (external_variable_name, default_value)}
13676 @end itemize
13677
13678 @noindent
13679 Each parameter must be a string literal.  For example:
13680
13681 @smallexample @c projectfile
13682    external ("USER")
13683    external ("OS", "GNU/Linux")
13684 @end smallexample
13685
13686 @noindent
13687 In the form with one parameter, the function returns the value of
13688 the external variable given as parameter. If this name is not present in the
13689 environment, the function returns an empty string.
13690
13691 In the form with two string parameters, the second argument is
13692 the value returned when the variable given as the first argument is not
13693 present in the environment. In the example above, if @code{"OS"} is not
13694 the name of ^an environment variable^a logical name^ and is not passed on
13695 the command line, then the returned value is @code{"GNU/Linux"}.
13696
13697 An external reference may be part of a string expression or of a string
13698 list expression, and can therefore appear in a variable declaration or
13699 an attribute declaration.
13700
13701 @smallexample @c projectfile
13702 @group
13703    type Mode_Type is ("Debug", "Release");
13704    Mode : Mode_Type := external ("MODE");
13705    case Mode is
13706      when "Debug" =>
13707         @dots{}
13708 @end group
13709 @end smallexample
13710
13711 @c *****************************
13712 @c * Packages in Project Files *
13713 @c *****************************
13714
13715 @node  Packages in Project Files
13716 @section Packages in Project Files
13717
13718 @noindent
13719 A @emph{package} defines the settings for project-aware tools within a
13720 project.
13721 For each such tool one can declare a package; the names for these
13722 packages are preset (@pxref{Packages}).
13723 A package may contain variable declarations, attribute declarations, and case
13724 constructions.
13725
13726 @smallexample @c projectfile
13727 @group
13728    project Proj is
13729       package Builder is  -- used by gnatmake
13730          for ^Default_Switches^Default_Switches^ ("Ada")
13731              use ("^-v^-v^",
13732                   "^-g^-g^");
13733       end Builder;
13734    end Proj;
13735 @end group
13736 @end smallexample
13737
13738 @noindent
13739 The syntax of package declarations mimics that of package in Ada.
13740
13741 Most of the packages have an attribute
13742 @code{^Default_Switches^Default_Switches^}.
13743 This attribute is an associative array, and its value is a string list.
13744 The index of the associative array is the name of a programming language (case
13745 insensitive). This attribute indicates the ^switch^switch^
13746 or ^switches^switches^ to be used
13747 with the corresponding tool.
13748
13749 Some packages also have another attribute, @code{^Switches^Switches^},
13750 an associative array whose value is a string list.
13751 The index is the name of a source file.
13752 This attribute indicates the ^switch^switch^
13753 or ^switches^switches^ to be used by the corresponding
13754 tool when dealing with this specific file.
13755
13756 Further information on these ^switch^switch^-related attributes is found in
13757 @ref{^Switches^Switches^ and Project Files}.
13758
13759 A package may be declared as a @emph{renaming} of another package; e.g., from
13760 the project file for an imported project.
13761
13762 @smallexample @c projectfile
13763 @group
13764   with "/global/apex.gpr";
13765   project Example is
13766     package Naming renames Apex.Naming;
13767     @dots{}
13768   end Example;
13769 @end group
13770 @end smallexample
13771
13772 @noindent
13773 Packages that are renamed in other project files often come from project files
13774 that have no sources: they are just used as templates. Any modification in the
13775 template will be reflected automatically in all the project files that rename
13776 a package from the template.
13777
13778 In addition to the tool-oriented packages, you can also declare a package
13779 named @code{Naming} to establish specialized source file naming conventions
13780 (@pxref{Naming Schemes}).
13781
13782 @c ************************************
13783 @c * Variables from Imported Projects *
13784 @c ************************************
13785
13786 @node Variables from Imported Projects
13787 @section Variables from Imported Projects
13788
13789 @noindent
13790 An attribute or variable defined in an imported or parent project can
13791 be used in expressions in the importing / extending project.
13792 Such an attribute or variable is denoted by an expanded name whose prefix
13793 is either the name of the project or the expanded name of a package within
13794 a project.
13795
13796 @smallexample @c projectfile
13797 @group
13798   with "imported";
13799   project Main extends "base" is
13800      Var1 := Imported.Var;
13801      Var2 := Base.Var & ".new";
13802 @end group
13803
13804 @group
13805      package Builder is
13806         for ^Default_Switches^Default_Switches^ ("Ada")
13807             use Imported.Builder'Ada_^Switches^Switches^ &
13808                 "^-gnatg^-gnatg^" &
13809                 "^-v^-v^";
13810      end Builder;
13811 @end group
13812
13813 @group
13814      package Compiler is
13815         for ^Default_Switches^Default_Switches^ ("Ada")
13816             use Base.Compiler'Ada_^Switches^Switches^;
13817      end Compiler;
13818   end Main;
13819 @end group
13820 @end smallexample
13821
13822 @noindent
13823 In this example:
13824
13825 @itemize @bullet
13826 @item
13827 The value of @code{Var1} is a copy of the variable @code{Var} defined
13828 in the project file @file{"imported.gpr"}
13829 @item
13830 the value of @code{Var2} is a copy of the value of variable @code{Var}
13831 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
13832 @item
13833 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13834 @code{Builder} is a string list that includes in its value a copy of the value
13835 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
13836 in project file @file{imported.gpr} plus two new elements:
13837 @option{"^-gnatg^-gnatg^"}
13838 and @option{"^-v^-v^"};
13839 @item
13840 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
13841 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
13842 defined in the @code{Compiler} package in project file @file{base.gpr},
13843 the project being extended.
13844 @end itemize
13845
13846 @c ******************
13847 @c * Naming Schemes *
13848 @c ******************
13849
13850 @node  Naming Schemes
13851 @section Naming Schemes
13852
13853 @noindent
13854 Sometimes an Ada software system is ported from a foreign compilation
13855 environment to GNAT, and the file names do not use the default GNAT
13856 conventions. Instead of changing all the file names (which for a variety
13857 of reasons might not be possible), you can define the relevant file
13858 naming scheme in the @code{Naming} package in your project file.
13859
13860 @noindent
13861 Note that the use of pragmas described in
13862 @ref{Alternative File Naming Schemes} by mean of a configuration
13863 pragmas file is not supported when using project files. You must use
13864 the features described in this paragraph. You can however use specify
13865 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
13866
13867 @ifclear vms
13868 For example, the following
13869 package models the Apex file naming rules:
13870
13871 @smallexample @c projectfile
13872 @group
13873   package Naming is
13874     for Casing               use "lowercase";
13875     for Dot_Replacement      use ".";
13876     for Spec_Suffix ("Ada")  use ".1.ada";
13877     for Body_Suffix ("Ada")  use ".2.ada";
13878   end Naming;
13879 @end group
13880 @end smallexample
13881 @end ifclear
13882
13883 @ifset vms
13884 For example, the following package models the HP Ada file naming rules:
13885
13886 @smallexample @c projectfile
13887 @group
13888   package Naming is
13889     for Casing               use "lowercase";
13890     for Dot_Replacement      use "__";
13891     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
13892     for Body_Suffix ("Ada")  use ".^ada^ada^";
13893   end Naming;
13894 @end group
13895 @end smallexample
13896
13897 @noindent
13898 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
13899 names in lower case)
13900 @end ifset
13901
13902 @noindent
13903 You can define the following attributes in package @code{Naming}:
13904
13905 @table @code
13906
13907 @item @code{Casing}
13908 This must be a string with one of the three values @code{"lowercase"},
13909 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
13910
13911 @noindent
13912 If @code{Casing} is not specified, then the default is @code{"lowercase"}.
13913
13914 @item @code{Dot_Replacement}
13915 This must be a string whose value satisfies the following conditions:
13916
13917 @itemize @bullet
13918 @item It must not be empty
13919 @item It cannot start or end with an alphanumeric character
13920 @item It cannot be a single underscore
13921 @item It cannot start with an underscore followed by an alphanumeric
13922 @item It cannot contain a dot @code{'.'} except if the entire string
13923 is @code{"."}
13924 @end itemize
13925
13926 @noindent
13927 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
13928
13929 @item @code{Spec_Suffix}
13930 This is an associative array (indexed by the programming language name, case
13931 insensitive) whose value is a string that must satisfy the following
13932 conditions:
13933
13934 @itemize @bullet
13935 @item It must not be empty
13936 @item It must include at least one dot
13937 @end itemize
13938 @noindent
13939 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
13940 @code{"^.ads^.ADS^"}.
13941
13942 @item @code{Body_Suffix}
13943 This is an associative array (indexed by the programming language name, case
13944 insensitive) whose value is a string that must satisfy the following
13945 conditions:
13946
13947 @itemize @bullet
13948 @item It must not be empty
13949 @item It must include at least one dot
13950 @item It cannot be the same as @code{Spec_Suffix ("Ada")}
13951 @end itemize
13952 @noindent
13953 If @code{Body_Suffix ("Ada")} and @code{Spec_Suffix ("Ada")} end with the
13954 same string, then a file name that ends with the longest of these two suffixes
13955 will be a body if the longest suffix is @code{Body_Suffix ("Ada")} or a spec
13956 if the longest suffix is @code{Spec_Suffix ("Ada")}.
13957
13958 If the suffix does not start with a '.', a file with a name exactly equal
13959 to the suffix will also be part of the project (for instance if you define
13960 the suffix as @code{Makefile}, a file called @file{Makefile} will be part
13961 of the project. This is not interesting in general when using projects to
13962 compile. However, it might become useful when a project is also used to
13963 find the list of source files in an editor, like the GNAT Programming System
13964 (GPS).
13965
13966 If @code{Body_Suffix ("Ada")} is not specified, then the default is
13967 @code{"^.adb^.ADB^"}.
13968
13969 @item @code{Separate_Suffix}
13970 This must be a string whose value satisfies the same conditions as
13971 @code{Body_Suffix}. The same "longest suffix" rules apply.
13972
13973 @noindent
13974 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
13975 value as @code{Body_Suffix ("Ada")}.
13976
13977 @item @code{Spec}
13978 @noindent
13979 You can use the associative array attribute @code{Spec}  to define
13980 the source file name for an individual Ada compilation unit's spec. The array
13981 index must be a string literal that identifies the Ada unit (case insensitive).
13982 The value of this attribute must be a string that identifies the file that
13983 contains this unit's spec (case sensitive or insensitive depending on the
13984 operating system).
13985
13986 @smallexample @c projectfile
13987    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
13988 @end smallexample
13989
13990 When the source file contains several units, you can indicate at what
13991 position the unit occurs in the file, with the following. The first unit
13992 in the file has index 1
13993
13994 @smallexample @c projectfile
13995   for Body ("top") use "foo.a" at 1;
13996   for Body ("foo") use "foo.a" at 2;
13997 @end smallexample
13998
13999 @item @code{Body}
14000
14001 You can use the associative array attribute @code{Body} to
14002 define the source file name for an individual Ada compilation unit's body
14003 (possibly a subunit).  The array index must be a string literal that identifies
14004 the Ada unit (case insensitive).  The value of this attribute must be a string
14005 that identifies the file that contains this unit's body or subunit (case
14006 sensitive or insensitive depending on the operating system).
14007
14008 @smallexample @c projectfile
14009    for Body ("MyPack.MyChild") use "mypack.mychild.body";
14010 @end smallexample
14011 @end table
14012
14013 @c ********************
14014 @c * Library Projects *
14015 @c ********************
14016
14017 @node Library Projects
14018 @section Library Projects
14019
14020 @noindent
14021 @emph{Library projects} are projects whose object code is placed in a library.
14022 (Note that this facility is not yet supported on all platforms).
14023
14024 @code{gnatmake} or @code{gprbuild} will collect all object files into a
14025 single archive, which might either be a shared or a static library. This
14026 library can later on be linked with multiple executables, potentially
14027 reducing their sizes.
14028
14029 If your project file specifies languages other than Ada, but you are still
14030 using @code{gnatmake} to compile and link, the latter will not try to
14031 compile your sources other than Ada (you should use @code{gprbuild} if that
14032 is your intent). However, @code{gnatmake} will automatically link all object
14033 files found in the object directory, whether or not they were compiled from
14034 an Ada source file. This specific behavior only applies when multiple
14035 languages are specified.
14036
14037 To create a library project, you need to define in its project file
14038 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
14039 Additionally, you may define other library-related attributes such as
14040 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
14041 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
14042
14043 The @code{Library_Name} attribute has a string value. There is no restriction
14044 on the name of a library. It is the responsibility of the developer to
14045 choose a name that will be accepted by the platform. It is recommended to
14046 choose names that could be Ada identifiers; such names are almost guaranteed
14047 to be acceptable on all platforms.
14048
14049 The @code{Library_Dir} attribute has a string value that designates the path
14050 (absolute or relative) of the directory where the library will reside.
14051 It must designate an existing directory. When the project is not externally
14052 built, this directory must be writable, different from the project's object
14053 directory and from any source directory in the project tree.
14054
14055 If both @code{Library_Name} and @code{Library_Dir} are specified and
14056 are legal, then the project file defines a library project.  The optional
14057 library-related attributes are checked only for such project files.
14058
14059 The @code{Library_Kind} attribute has a string value that must be one of the
14060 following (case insensitive): @code{"static"}, @code{"dynamic"} or
14061 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
14062 attribute is not specified, the library is a static library, that is
14063 an archive of object files that can be potentially linked into a
14064 static executable. Otherwise, the library may be dynamic or
14065 relocatable, that is a library that is loaded only at the start of execution.
14066
14067 If you need to build both a static and a dynamic library, you should use two
14068 different object directories, since in some cases some extra code needs to
14069 be generated for the latter. For such cases, it is recommended to either use
14070 two different project files, or a single one which uses external variables
14071 to indicate what kind of library should be build.
14072
14073 The @code{Library_ALI_Dir} attribute may be specified to indicate the
14074 directory where the ALI files of the library will be copied. When it is
14075 not specified, the ALI files are copied to the directory specified in
14076 attribute @code{Library_Dir}. Except when the project is externally built, the
14077 directory specified by @code{Library_ALI_Dir} must be writable and different
14078 from the project's object directory and from any source directory in the
14079 project tree.
14080
14081 The @code{Library_Version} attribute has a string value whose interpretation
14082 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
14083 used only for dynamic/relocatable libraries as the internal name of the
14084 library (the @code{"soname"}). If the library file name (built from the
14085 @code{Library_Name}) is different from the @code{Library_Version}, then the
14086 library file will be a symbolic link to the actual file whose name will be
14087 @code{Library_Version}.
14088
14089 Example (on Unix):
14090
14091 @smallexample @c projectfile
14092 @group
14093 project Plib is
14094
14095    Version := "1";
14096
14097    for Library_Dir use "lib_dir";
14098    for Library_Name use "dummy";
14099    for Library_Kind use "relocatable";
14100    for Library_Version use "libdummy.so." & Version;
14101
14102 end Plib;
14103 @end group
14104 @end smallexample
14105
14106 @noindent
14107 Directory @file{lib_dir} will contain the internal library file whose name
14108 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
14109 @file{libdummy.so.1}.
14110
14111 When @command{gnatmake} detects that a project file
14112 is a library project file, it will check all immediate sources of the project
14113 and rebuild the library if any of the sources have been recompiled.
14114
14115 Standard project files can import library project files. In such cases,
14116 the libraries will only be rebuilt if some of its sources are recompiled
14117 because they are in the closure of some other source in an importing project.
14118 Sources of the library project files that are not in such a closure will
14119 not be checked, unless the full library is checked, because one of its sources
14120 needs to be recompiled.
14121
14122 For instance, assume the project file @code{A} imports the library project file
14123 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
14124 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
14125 @file{l2.ads}, @file{l2.adb}.
14126
14127 If @file{l1.adb} has been modified, then the library associated with @code{L}
14128 will be rebuilt when compiling all the immediate sources of @code{A} only
14129 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
14130 @code{"with L1;"}.
14131
14132 To be sure that all the sources in the library associated with @code{L} are
14133 up to date, and that all the sources of project @code{A} are also up to date,
14134 the following two commands needs to be used:
14135
14136 @smallexample
14137 gnatmake -Pl.gpr
14138 gnatmake -Pa.gpr
14139 @end smallexample
14140
14141 When a library is built or rebuilt, an attempt is made first to delete all
14142 files in the library directory.
14143 All @file{ALI} files will also be copied from the object directory to the
14144 library directory. To build executables, @command{gnatmake} will use the
14145 library rather than the individual object files.
14146
14147 @ifclear vms
14148 It is also possible to create library project files for third-party libraries
14149 that are precompiled and cannot be compiled locally thanks to the
14150 @code{externally_built} attribute. (See @ref{Installing a library}).
14151 @end ifclear
14152
14153 @c *******************************
14154 @c * Stand-alone Library Projects *
14155 @c *******************************
14156
14157 @node Stand-alone Library Projects
14158 @section Stand-alone Library Projects
14159
14160 @noindent
14161 A Stand-alone Library is a library that contains the necessary code to
14162 elaborate the Ada units that are included in the library. A Stand-alone
14163 Library is suitable to be used in an executable when the main is not
14164 in Ada. However, Stand-alone Libraries may also be used with an Ada main
14165 subprogram.
14166
14167 A Stand-alone Library Project is a Library Project where the library is
14168 a Stand-alone Library.
14169
14170 To be a Stand-alone Library Project, in addition to the two attributes
14171 that make a project a Library Project (@code{Library_Name} and
14172 @code{Library_Dir}, see @ref{Library Projects}), the attribute
14173 @code{Library_Interface} must be defined.
14174
14175 @smallexample @c projectfile
14176 @group
14177    for Library_Dir use "lib_dir";
14178    for Library_Name use "dummy";
14179    for Library_Interface use ("int1", "int1.child");
14180 @end group
14181 @end smallexample
14182
14183 Attribute @code{Library_Interface} has a nonempty string list value,
14184 each string in the list designating a unit contained in an immediate source
14185 of the project file.
14186
14187 When a Stand-alone Library is built, first the binder is invoked to build
14188 a package whose name depends on the library name
14189 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
14190 This binder-generated package includes initialization and
14191 finalization procedures whose
14192 names depend on the library name (dummyinit and dummyfinal in the example
14193 above). The object corresponding to this package is included in the library.
14194
14195 A dynamic or relocatable Stand-alone Library is automatically initialized
14196 if automatic initialization of Stand-alone Libraries is supported on the
14197 platform and if attribute @code{Library_Auto_Init} is not specified or
14198 is specified with the value "true". A static Stand-alone Library is never
14199 automatically initialized.
14200
14201 Single string attribute @code{Library_Auto_Init} may be specified with only
14202 two possible values: "false" or "true" (case-insensitive). Specifying
14203 "false" for attribute @code{Library_Auto_Init} will prevent automatic
14204 initialization of dynamic or relocatable libraries.
14205
14206 When a non-automatically initialized Stand-alone Library is used
14207 in an executable, its initialization procedure must be called before
14208 any service of the library is used.
14209 When the main subprogram is in Ada, it may mean that the initialization
14210 procedure has to be called during elaboration of another package.
14211
14212 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
14213 (those that are listed in attribute @code{Library_Interface}) are copied to
14214 the Library Directory. As a consequence, only the Interface Units may be
14215 imported from Ada units outside of the library. If other units are imported,
14216 the binding phase will fail.
14217
14218 When a Stand-Alone Library is bound, the switches that are specified in
14219 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
14220 used in the call to @command{gnatbind}.
14221
14222 The string list attribute @code{Library_Options} may be used to specified
14223 additional switches to the call to @command{gcc} to link the library.
14224
14225 The attribute @code{Library_Src_Dir}, may be specified for a
14226 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
14227 single string value. Its value must be the path (absolute or relative to the
14228 project directory) of an existing directory. This directory cannot be the
14229 object directory or one of the source directories, but it can be the same as
14230 the library directory. The sources of the Interface
14231 Units of the library, necessary to an Ada client of the library, will be
14232 copied to the designated directory, called Interface Copy directory.
14233 These sources includes the specs of the Interface Units, but they may also
14234 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
14235 are used, or when there is a generic units in the spec. Before the sources
14236 are copied to the Interface Copy directory, an attempt is made to delete all
14237 files in the Interface Copy directory.
14238
14239 @c *************************************
14240 @c * Switches Related to Project Files *
14241 @c *************************************
14242 @node Switches Related to Project Files
14243 @section Switches Related to Project Files
14244
14245 @noindent
14246 The following switches are used by GNAT tools that support project files:
14247
14248 @table @option
14249
14250 @item ^-P^/PROJECT_FILE=^@var{project}
14251 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
14252 Indicates the name of a project file. This project file will be parsed with
14253 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
14254 if any, and using the external references indicated
14255 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
14256 @ifclear vms
14257 There may zero, one or more spaces between @option{-P} and @var{project}.
14258 @end ifclear
14259
14260 @noindent
14261 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
14262
14263 @noindent
14264 Since the Project Manager parses the project file only after all the switches
14265 on the command line are checked, the order of the switches
14266 @option{^-P^/PROJECT_FILE^},
14267 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
14268 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
14269
14270 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
14271 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
14272 Indicates that external variable @var{name} has the value @var{value}.
14273 The Project Manager will use this value for occurrences of
14274 @code{external(name)} when parsing the project file.
14275
14276 @ifclear vms
14277 @noindent
14278 If @var{name} or @var{value} includes a space, then @var{name=value} should be
14279 put between quotes.
14280 @smallexample
14281   -XOS=NT
14282   -X"user=John Doe"
14283 @end smallexample
14284 @end ifclear
14285
14286 @noindent
14287 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
14288 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
14289 @var{name}, only the last one is used.
14290
14291 @noindent
14292 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
14293 takes precedence over the value of the same name in the environment.
14294
14295 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
14296 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
14297 Indicates the verbosity of the parsing of GNAT project files.
14298
14299 @ifclear vms
14300 @option{-vP0} means Default;
14301 @option{-vP1} means Medium;
14302 @option{-vP2} means High.
14303 @end ifclear
14304
14305 @ifset vms
14306 There are three possible options for this qualifier: DEFAULT, MEDIUM and
14307 HIGH.
14308 @end ifset
14309
14310 @noindent
14311 The default is ^Default^DEFAULT^: no output for syntactically correct
14312 project files.
14313 @noindent
14314 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
14315 only the last one is used.
14316
14317 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
14318 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
14319 Add directory <dir> at the beginning of the project search path, in order,
14320 after the current working directory.
14321
14322 @ifclear vms
14323 @item -eL
14324 @cindex @option{-eL} (any project-aware tool)
14325 Follow all symbolic links when processing project files.
14326 @end ifclear
14327
14328 @item ^--subdirs^/SUBDIRS^=<subdir>
14329 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
14330 This switch is recognized by gnatmake and gnatclean. It indicate that the real
14331 directories (except the source directories) are the subdirectories <subdir>
14332 of the directories specified in the project files. This applies in particular
14333 to object directories, library directories and exec directories. If the
14334 subdirectories do not exist, they are created automatically.
14335
14336 @end table
14337
14338 @c **********************************
14339 @c * Tools Supporting Project Files *
14340 @c **********************************
14341
14342 @node  Tools Supporting Project Files
14343 @section Tools Supporting Project Files
14344
14345 @menu
14346 * gnatmake and Project Files::
14347 * The GNAT Driver and Project Files::
14348 @end menu
14349
14350 @node gnatmake and Project Files
14351 @subsection gnatmake and Project Files
14352
14353 @noindent
14354 This section covers several topics related to @command{gnatmake} and
14355 project files: defining ^switches^switches^ for @command{gnatmake}
14356 and for the tools that it invokes; specifying configuration pragmas;
14357 the use of the @code{Main} attribute; building and rebuilding library project
14358 files.
14359
14360 @menu
14361 * ^Switches^Switches^ and Project Files::
14362 * Specifying Configuration Pragmas::
14363 * Project Files and Main Subprograms::
14364 * Library Project Files::
14365 @end menu
14366
14367 @node ^Switches^Switches^ and Project Files
14368 @subsubsection ^Switches^Switches^ and Project Files
14369
14370 @ifset vms
14371 It is not currently possible to specify VMS style qualifiers in the project
14372 files; only Unix style ^switches^switches^ may be specified.
14373 @end ifset
14374
14375 @noindent
14376 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
14377 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
14378 attribute, a @code{^Switches^Switches^} attribute, or both;
14379 as their names imply, these ^switch^switch^-related
14380 attributes affect the ^switches^switches^ that are used for each of these GNAT
14381 components when
14382 @command{gnatmake} is invoked.  As will be explained below, these
14383 component-specific ^switches^switches^ precede
14384 the ^switches^switches^ provided on the @command{gnatmake} command line.
14385
14386 The @code{^Default_Switches^Default_Switches^} attribute is an associative
14387 array indexed by language name (case insensitive) whose value is a string list.
14388 For example:
14389
14390 @smallexample @c projectfile
14391 @group
14392 package Compiler is
14393   for ^Default_Switches^Default_Switches^ ("Ada")
14394       use ("^-gnaty^-gnaty^",
14395            "^-v^-v^");
14396 end Compiler;
14397 @end group
14398 @end smallexample
14399
14400 @noindent
14401 The @code{^Switches^Switches^} attribute is also an associative array,
14402 indexed by a file name (which may or may not be case sensitive, depending
14403 on the operating system) whose value is a string list.  For example:
14404
14405 @smallexample @c projectfile
14406 @group
14407 package Builder is
14408    for ^Switches^Switches^ ("main1.adb")
14409        use ("^-O2^-O2^");
14410    for ^Switches^Switches^ ("main2.adb")
14411        use ("^-g^-g^");
14412 end Builder;
14413 @end group
14414 @end smallexample
14415
14416 @noindent
14417 For the @code{Builder} package, the file names must designate source files
14418 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
14419 file names must designate @file{ALI} or source files for main subprograms.
14420 In each case just the file name without an explicit extension is acceptable.
14421
14422 For each tool used in a program build (@command{gnatmake}, the compiler, the
14423 binder, and the linker), the corresponding package @dfn{contributes} a set of
14424 ^switches^switches^ for each file on which the tool is invoked, based on the
14425 ^switch^switch^-related attributes defined in the package.
14426 In particular, the ^switches^switches^
14427 that each of these packages contributes for a given file @var{f} comprise:
14428
14429 @itemize @bullet
14430 @item
14431 the value of attribute @code{^Switches^Switches^ (@var{f})},
14432 if it is specified in the package for the given file,
14433 @item
14434 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
14435 if it is specified in the package.
14436 @end itemize
14437
14438 @noindent
14439 If neither of these attributes is defined in the package, then the package does
14440 not contribute any ^switches^switches^ for the given file.
14441
14442 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
14443 two sets, in the following order: those contributed for the file
14444 by the @code{Builder} package;
14445 and the switches passed on the command line.
14446
14447 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
14448 the ^switches^switches^ passed to the tool comprise three sets,
14449 in the following order:
14450
14451 @enumerate
14452 @item
14453 the applicable ^switches^switches^ contributed for the file
14454 by the @code{Builder} package in the project file supplied on the command line;
14455
14456 @item
14457 those contributed for the file by the package (in the relevant project file --
14458 see below) corresponding to the tool; and
14459
14460 @item
14461 the applicable switches passed on the command line.
14462 @end enumerate
14463
14464 @noindent
14465 The term @emph{applicable ^switches^switches^} reflects the fact that
14466 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
14467 tools, depending on the individual ^switch^switch^.
14468
14469 @command{gnatmake} may invoke the compiler on source files from different
14470 projects. The Project Manager will use the appropriate project file to
14471 determine the @code{Compiler} package for each source file being compiled.
14472 Likewise for the @code{Binder} and @code{Linker} packages.
14473
14474 As an example, consider the following package in a project file:
14475
14476 @smallexample @c projectfile
14477 @group
14478 project Proj1 is
14479    package Compiler is
14480       for ^Default_Switches^Default_Switches^ ("Ada")
14481           use ("^-g^-g^");
14482       for ^Switches^Switches^ ("a.adb")
14483           use ("^-O1^-O1^");
14484       for ^Switches^Switches^ ("b.adb")
14485           use ("^-O2^-O2^",
14486                "^-gnaty^-gnaty^");
14487    end Compiler;
14488 end Proj1;
14489 @end group
14490 @end smallexample
14491
14492 @noindent
14493 If @command{gnatmake} is invoked with this project file, and it needs to
14494 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
14495 @file{a.adb} will be compiled with the ^switch^switch^
14496 @option{^-O1^-O1^},
14497 @file{b.adb} with ^switches^switches^
14498 @option{^-O2^-O2^}
14499 and @option{^-gnaty^-gnaty^},
14500 and @file{c.adb} with @option{^-g^-g^}.
14501
14502 The following example illustrates the ordering of the ^switches^switches^
14503 contributed by different packages:
14504
14505 @smallexample @c projectfile
14506 @group
14507 project Proj2 is
14508    package Builder is
14509       for ^Switches^Switches^ ("main.adb")
14510           use ("^-g^-g^",
14511                "^-O1^-)1^",
14512                "^-f^-f^");
14513    end Builder;
14514 @end group
14515
14516 @group
14517    package Compiler is
14518       for ^Switches^Switches^ ("main.adb")
14519           use ("^-O2^-O2^");
14520    end Compiler;
14521 end Proj2;
14522 @end group
14523 @end smallexample
14524
14525 @noindent
14526 If you issue the command:
14527
14528 @smallexample
14529     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
14530 @end smallexample
14531
14532 @noindent
14533 then the compiler will be invoked on @file{main.adb} with the following
14534 sequence of ^switches^switches^
14535
14536 @smallexample
14537    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
14538 @end smallexample
14539
14540 with the last @option{^-O^-O^}
14541 ^switch^switch^ having precedence over the earlier ones;
14542 several other ^switches^switches^
14543 (such as @option{^-c^-c^}) are added implicitly.
14544
14545 The ^switches^switches^
14546 @option{^-g^-g^}
14547 and @option{^-O1^-O1^} are contributed by package
14548 @code{Builder},  @option{^-O2^-O2^} is contributed
14549 by the package @code{Compiler}
14550 and @option{^-O0^-O0^} comes from the command line.
14551
14552 The @option{^-g^-g^}
14553 ^switch^switch^ will also be passed in the invocation of
14554 @command{Gnatlink.}
14555
14556 A final example illustrates switch contributions from packages in different
14557 project files:
14558
14559 @smallexample @c projectfile
14560 @group
14561 project Proj3 is
14562    for Source_Files use ("pack.ads", "pack.adb");
14563    package Compiler is
14564       for ^Default_Switches^Default_Switches^ ("Ada")
14565           use ("^-gnata^-gnata^");
14566    end Compiler;
14567 end Proj3;
14568 @end group
14569
14570 @group
14571 with "Proj3";
14572 project Proj4 is
14573    for Source_Files use ("foo_main.adb", "bar_main.adb");
14574    package Builder is
14575       for ^Switches^Switches^ ("foo_main.adb")
14576           use ("^-s^-s^",
14577                "^-g^-g^");
14578    end Builder;
14579 end Proj4;
14580 @end group
14581
14582 @group
14583 -- Ada source file:
14584 with Pack;
14585 procedure Foo_Main is
14586    @dots{}
14587 end Foo_Main;
14588 @end group
14589 @end smallexample
14590
14591 If the command is
14592 @smallexample
14593 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
14594 @end smallexample
14595
14596 @noindent
14597 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
14598 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
14599 @option{^-gnato^-gnato^} (passed on the command line).
14600 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
14601 are @option{^-g^-g^} from @code{Proj4.Builder},
14602 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
14603 and @option{^-gnato^-gnato^} from the command line.
14604
14605 @noindent
14606 When using @command{gnatmake} with project files, some ^switches^switches^ or
14607 arguments may be expressed as relative paths. As the working directory where
14608 compilation occurs may change, these relative paths are converted to absolute
14609 paths. For the ^switches^switches^ found in a project file, the relative paths
14610 are relative to the project file directory, for the switches on the command
14611 line, they are relative to the directory where @command{gnatmake} is invoked.
14612 The ^switches^switches^ for which this occurs are:
14613 ^-I^-I^,
14614 ^-A^-A^,
14615 ^-L^-L^,
14616 ^-aO^-aO^,
14617 ^-aL^-aL^,
14618 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
14619 ^switch^switch^
14620 ^-o^-o^, object files specified in package @code{Linker} or after
14621 -largs on the command line). The exception to this rule is the ^switch^switch^
14622 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
14623
14624 @node Specifying Configuration Pragmas
14625 @subsubsection Specifying Configuration Pragmas
14626
14627 When using @command{gnatmake} with project files, if there exists a file
14628 @file{gnat.adc} that contains configuration pragmas, this file will be
14629 ignored.
14630
14631 Configuration pragmas can be defined by means of the following attributes in
14632 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
14633 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
14634
14635 Both these attributes are single string attributes. Their values is the path
14636 name of a file containing configuration pragmas. If a path name is relative,
14637 then it is relative to the project directory of the project file where the
14638 attribute is defined.
14639
14640 When compiling a source, the configuration pragmas used are, in order,
14641 those listed in the file designated by attribute
14642 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
14643 project file, if it is specified, and those listed in the file designated by
14644 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
14645 the project file of the source, if it exists.
14646
14647 @node Project Files and Main Subprograms
14648 @subsubsection Project Files and Main Subprograms
14649
14650 @noindent
14651 When using a project file, you can invoke @command{gnatmake}
14652 with one or several main subprograms, by specifying their source files on the
14653 command line.
14654
14655 @smallexample
14656     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
14657 @end smallexample
14658
14659 @noindent
14660 Each of these needs to be a source file of the same project, except
14661 when the switch ^-u^/UNIQUE^ is used.
14662
14663 @noindent
14664 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
14665 same project, one of the project in the tree rooted at the project specified
14666 on the command line. The package @code{Builder} of this common project, the
14667 "main project" is the one that is considered by @command{gnatmake}.
14668
14669 @noindent
14670 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
14671 imported directly or indirectly by the project specified on the command line.
14672 Note that if such a source file is not part of the project specified on the
14673 command line, the ^switches^switches^ found in package @code{Builder} of the
14674 project specified on the command line, if any, that are transmitted
14675 to the compiler will still be used, not those found in the project file of
14676 the source file.
14677
14678 @noindent
14679 When using a project file, you can also invoke @command{gnatmake} without
14680 explicitly specifying any main, and the effect depends on whether you have
14681 defined the @code{Main} attribute.  This attribute has a string list value,
14682 where each element in the list is the name of a source file (the file
14683 extension is optional) that contains a unit that can be a main subprogram.
14684
14685 If the @code{Main} attribute is defined in a project file as a non-empty
14686 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
14687 line, then invoking @command{gnatmake} with this project file but without any
14688 main on the command line is equivalent to invoking @command{gnatmake} with all
14689 the file names in the @code{Main} attribute on the command line.
14690
14691 Example:
14692 @smallexample @c projectfile
14693 @group
14694    project Prj is
14695       for Main use ("main1", "main2", "main3");
14696    end Prj;
14697 @end group
14698 @end smallexample
14699
14700 @noindent
14701 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
14702 is equivalent to
14703 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
14704
14705 When the project attribute @code{Main} is not specified, or is specified
14706 as an empty string list, or when the switch @option{-u} is used on the command
14707 line, then invoking @command{gnatmake} with no main on the command line will
14708 result in all immediate sources of the project file being checked, and
14709 potentially recompiled. Depending on the presence of the switch @option{-u},
14710 sources from other project files on which the immediate sources of the main
14711 project file depend are also checked and potentially recompiled. In other
14712 words, the @option{-u} switch is applied to all of the immediate sources of the
14713 main project file.
14714
14715 When no main is specified on the command line and attribute @code{Main} exists
14716 and includes several mains, or when several mains are specified on the
14717 command line, the default ^switches^switches^ in package @code{Builder} will
14718 be used for all mains, even if there are specific ^switches^switches^
14719 specified for one or several mains.
14720
14721 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
14722 the specific ^switches^switches^ for each main, if they are specified.
14723
14724 @node Library Project Files
14725 @subsubsection Library Project Files
14726
14727 @noindent
14728 When @command{gnatmake} is invoked with a main project file that is a library
14729 project file, it is not allowed to specify one or more mains on the command
14730 line.
14731
14732 @noindent
14733 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
14734 ^-l^/ACTION=LINK^ have special meanings.
14735
14736 @itemize @bullet
14737 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
14738 to @command{gnatmake} that @command{gnatbind} should be invoked for the
14739 library.
14740
14741 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
14742 to @command{gnatmake} that the binder generated file should be compiled
14743 (in the case of a stand-alone library) and that the library should be built.
14744
14745 @end itemize
14746
14747 @node The GNAT Driver and Project Files
14748 @subsection The GNAT Driver and Project Files
14749
14750 @noindent
14751 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
14752 can benefit from project files:
14753 (@command{^gnatbind^gnatbind^},
14754 @command{^gnatcheck^gnatcheck^},
14755 @command{^gnatclean^gnatclean^},
14756 @command{^gnatelim^gnatelim^},
14757 @command{^gnatfind^gnatfind^},
14758 @command{^gnatlink^gnatlink^},
14759 @command{^gnatls^gnatls^},
14760 @command{^gnatmetric^gnatmetric^},
14761 @command{^gnatpp^gnatpp^},
14762 @command{^gnatstub^gnatstub^},
14763 and @command{^gnatxref^gnatxref^}). However, none of these tools can be invoked
14764 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
14765 They must be invoked through the @command{gnat} driver.
14766
14767 The @command{gnat} driver is a wrapper that accepts a number of commands and
14768 calls the corresponding tool. It was designed initially for VMS platforms (to
14769 convert VMS qualifiers to Unix-style switches), but it is now available on all
14770 GNAT platforms.
14771
14772 On non-VMS platforms, the @command{gnat} driver accepts the following commands
14773 (case insensitive):
14774
14775 @itemize @bullet
14776 @item
14777 BIND to invoke @command{^gnatbind^gnatbind^}
14778 @item
14779 CHOP to invoke @command{^gnatchop^gnatchop^}
14780 @item
14781 CLEAN to invoke @command{^gnatclean^gnatclean^}
14782 @item
14783 COMP or COMPILE to invoke the compiler
14784 @item
14785 ELIM to invoke @command{^gnatelim^gnatelim^}
14786 @item
14787 FIND to invoke @command{^gnatfind^gnatfind^}
14788 @item
14789 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
14790 @item
14791 LINK to invoke @command{^gnatlink^gnatlink^}
14792 @item
14793 LS or LIST to invoke @command{^gnatls^gnatls^}
14794 @item
14795 MAKE to invoke @command{^gnatmake^gnatmake^}
14796 @item
14797 NAME to invoke @command{^gnatname^gnatname^}
14798 @item
14799 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
14800 @item
14801 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
14802 @item
14803 METRIC to invoke @command{^gnatmetric^gnatmetric^}
14804 @item
14805 STUB to invoke @command{^gnatstub^gnatstub^}
14806 @item
14807 XREF to invoke @command{^gnatxref^gnatxref^}
14808 @end itemize
14809
14810 @noindent
14811 (note that the compiler is invoked using the command
14812 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
14813
14814 @noindent
14815 On non-VMS platforms, between @command{gnat} and the command, two
14816 special switches may be used:
14817
14818 @itemize @bullet
14819 @item
14820 @command{-v} to display the invocation of the tool.
14821 @item
14822 @command{-dn} to prevent the @command{gnat} driver from removing
14823 the temporary files it has created. These temporary files are
14824 configuration files and temporary file list files.
14825 @end itemize
14826
14827 @noindent
14828 The command may be followed by switches and arguments for the invoked
14829 tool.
14830
14831 @smallexample
14832   gnat bind -C main.ali
14833   gnat ls -a main
14834   gnat chop foo.txt
14835 @end smallexample
14836
14837 @noindent
14838 Switches may also be put in text files, one switch per line, and the text
14839 files may be specified with their path name preceded by '@@'.
14840
14841 @smallexample
14842    gnat bind @@args.txt main.ali
14843 @end smallexample
14844
14845 @noindent
14846 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
14847 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
14848 (@option{^-P^/PROJECT_FILE^},
14849 @option{^-X^/EXTERNAL_REFERENCE^} and
14850 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
14851 the switches of the invoking tool.
14852
14853 @noindent
14854 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
14855 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
14856 the immediate sources of the specified project file.
14857
14858 @noindent
14859 When GNAT METRIC is used with a project file, but with no source
14860 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
14861 with all the immediate sources of the specified project file and with
14862 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
14863 of the project.
14864
14865 @noindent
14866 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
14867 a project file, no source is specified on the command line and
14868 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
14869 the underlying tool (^gnatpp^gnatpp^ or
14870 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
14871 not only for the immediate sources of the main project.
14872 @ifclear vms
14873 (-U stands for Universal or Union of the project files of the project tree)
14874 @end ifclear
14875
14876 @noindent
14877 For each of the following commands, there is optionally a corresponding
14878 package in the main project.
14879
14880 @itemize @bullet
14881 @item
14882 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
14883
14884 @item
14885 package @code{Check} for command CHECK (invoking
14886 @code{^gnatcheck^gnatcheck^})
14887
14888 @item
14889 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
14890
14891 @item
14892 package @code{Cross_Reference} for command XREF (invoking
14893 @code{^gnatxref^gnatxref^})
14894
14895 @item
14896 package @code{Eliminate} for command ELIM (invoking
14897 @code{^gnatelim^gnatelim^})
14898
14899 @item
14900 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
14901
14902 @item
14903 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
14904
14905 @item
14906 package @code{Gnatstub} for command STUB
14907 (invoking @code{^gnatstub^gnatstub^})
14908
14909 @item
14910 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
14911
14912 @item
14913 package @code{Check} for command CHECK
14914 (invoking @code{^gnatcheck^gnatcheck^})
14915
14916 @item
14917 package @code{Metrics} for command METRIC
14918 (invoking @code{^gnatmetric^gnatmetric^})
14919
14920 @item
14921 package @code{Pretty_Printer} for command PP or PRETTY
14922 (invoking @code{^gnatpp^gnatpp^})
14923
14924 @end itemize
14925
14926 @noindent
14927 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
14928 a simple variable with a string list value. It contains ^switches^switches^
14929 for the invocation of @code{^gnatls^gnatls^}.
14930
14931 @smallexample @c projectfile
14932 @group
14933 project Proj1 is
14934    package gnatls is
14935       for ^Switches^Switches^
14936           use ("^-a^-a^",
14937                "^-v^-v^");
14938    end gnatls;
14939 end Proj1;
14940 @end group
14941 @end smallexample
14942
14943 @noindent
14944 All other packages have two attribute @code{^Switches^Switches^} and
14945 @code{^Default_Switches^Default_Switches^}.
14946
14947 @noindent
14948 @code{^Switches^Switches^} is an associative array attribute, indexed by the
14949 source file name, that has a string list value: the ^switches^switches^ to be
14950 used when the tool corresponding to the package is invoked for the specific
14951 source file.
14952
14953 @noindent
14954 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
14955 indexed by  the programming language that has a string list value.
14956 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14957 ^switches^switches^ for the invocation of the tool corresponding
14958 to the package, except if a specific @code{^Switches^Switches^} attribute
14959 is specified for the source file.
14960
14961 @smallexample @c projectfile
14962 @group
14963 project Proj is
14964
14965    for Source_Dirs use ("./**");
14966
14967    package gnatls is
14968       for ^Switches^Switches^ use
14969           ("^-a^-a^",
14970            "^-v^-v^");
14971    end gnatls;
14972 @end group
14973 @group
14974
14975    package Compiler is
14976       for ^Default_Switches^Default_Switches^ ("Ada")
14977           use ("^-gnatv^-gnatv^",
14978                "^-gnatwa^-gnatwa^");
14979    end Binder;
14980 @end group
14981 @group
14982
14983    package Binder is
14984       for ^Default_Switches^Default_Switches^ ("Ada")
14985           use ("^-C^-C^",
14986                "^-e^-e^");
14987    end Binder;
14988 @end group
14989 @group
14990
14991    package Linker is
14992       for ^Default_Switches^Default_Switches^ ("Ada")
14993           use ("^-C^-C^");
14994       for ^Switches^Switches^ ("main.adb")
14995           use ("^-C^-C^",
14996                "^-v^-v^",
14997                "^-v^-v^");
14998    end Linker;
14999 @end group
15000 @group
15001
15002    package Finder is
15003       for ^Default_Switches^Default_Switches^ ("Ada")
15004            use ("^-a^-a^",
15005                 "^-f^-f^");
15006    end Finder;
15007 @end group
15008 @group
15009
15010    package Cross_Reference is
15011       for ^Default_Switches^Default_Switches^ ("Ada")
15012           use ("^-a^-a^",
15013                "^-f^-f^",
15014                "^-d^-d^",
15015                "^-u^-u^");
15016    end Cross_Reference;
15017 end Proj;
15018 @end group
15019 @end smallexample
15020
15021 @noindent
15022 With the above project file, commands such as
15023
15024 @smallexample
15025    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
15026    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
15027    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
15028    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
15029    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
15030 @end smallexample
15031
15032 @noindent
15033 will set up the environment properly and invoke the tool with the switches
15034 found in the package corresponding to the tool:
15035 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
15036 except @code{^Switches^Switches^ ("main.adb")}
15037 for @code{^gnatlink^gnatlink^}.
15038 It is also possible to invoke some of the tools,
15039 (@code{^gnatcheck^gnatcheck^},
15040 @code{^gnatmetric^gnatmetric^},
15041 and @code{^gnatpp^gnatpp^})
15042 on a set of project units thanks to the combination of the switches
15043 @option{-P}, @option{-U} and possibly the main unit when one is interested
15044 in its closure. For instance,
15045 @smallexample
15046 gnat metric -Pproj
15047 @end smallexample
15048 will compute the metrics for all the immediate units of project
15049 @code{proj}.
15050 @smallexample
15051 gnat metric -Pproj -U
15052 @end smallexample
15053 will compute the metrics for all the units of the closure of projects
15054 rooted at @code{proj}.
15055 @smallexample
15056 gnat metric -Pproj -U main_unit
15057 @end smallexample
15058 will compute the metrics for the closure of units rooted at
15059 @code{main_unit}. This last possibility relies implicitly
15060 on @command{gnatbind}'s option @option{-R}. But if the argument files for the
15061 tool invoked by the the @command{gnat} driver are explicitly  specified
15062 either directly or through the tool @option{-files} option, then the tool
15063 is called only for these explicitly specified files.
15064
15065 @c **********************
15066 @node An Extended Example
15067 @section An Extended Example
15068
15069 @noindent
15070 Suppose that we have two programs, @var{prog1} and @var{prog2},
15071 whose sources are in corresponding directories. We would like
15072 to build them with a single @command{gnatmake} command, and we want to place
15073 their object files into @file{build} subdirectories of the source directories.
15074 Furthermore, we want to have to have two separate subdirectories
15075 in @file{build}  -- @file{release} and @file{debug} -- which will contain
15076 the object files compiled with different set of compilation flags.
15077
15078 In other words, we have the following structure:
15079
15080 @smallexample
15081 @group
15082    main
15083      |- prog1
15084      |    |- build
15085      |         | debug
15086      |         | release
15087      |- prog2
15088           |- build
15089                | debug
15090                | release
15091 @end group
15092 @end smallexample
15093
15094 @noindent
15095 Here are the project files that we must place in a directory @file{main}
15096 to maintain this structure:
15097
15098 @enumerate
15099
15100 @item We create a @code{Common} project with a package @code{Compiler} that
15101 specifies the compilation ^switches^switches^:
15102
15103 @smallexample
15104 File "common.gpr":
15105 @group
15106 @b{project} Common @b{is}
15107
15108    @b{for} Source_Dirs @b{use} (); -- No source files
15109 @end group
15110
15111 @group
15112    @b{type} Build_Type @b{is} ("release", "debug");
15113    Build : Build_Type := External ("BUILD", "debug");
15114 @end group
15115 @group
15116    @b{package} Compiler @b{is}
15117       @b{case} Build @b{is}
15118          @b{when} "release" =>
15119            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15120                    @b{use} ("^-O2^-O2^");
15121          @b{when} "debug"   =>
15122            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15123                    @b{use} ("^-g^-g^");
15124       @b{end case};
15125    @b{end} Compiler;
15126
15127 @b{end} Common;
15128 @end group
15129 @end smallexample
15130
15131 @item We create separate projects for the two programs:
15132
15133 @smallexample
15134 @group
15135 File "prog1.gpr":
15136
15137 @b{with} "common";
15138 @b{project} Prog1 @b{is}
15139
15140     @b{for} Source_Dirs @b{use} ("prog1");
15141     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
15142
15143     @b{package} Compiler @b{renames} Common.Compiler;
15144
15145 @b{end} Prog1;
15146 @end group
15147 @end smallexample
15148
15149 @smallexample
15150 @group
15151 File "prog2.gpr":
15152
15153 @b{with} "common";
15154 @b{project} Prog2 @b{is}
15155
15156     @b{for} Source_Dirs @b{use} ("prog2");
15157     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
15158
15159     @b{package} Compiler @b{renames} Common.Compiler;
15160
15161 @end group
15162 @b{end} Prog2;
15163 @end smallexample
15164
15165 @item We create a wrapping project @code{Main}:
15166
15167 @smallexample
15168 @group
15169 File "main.gpr":
15170
15171 @b{with} "common";
15172 @b{with} "prog1";
15173 @b{with} "prog2";
15174 @b{project} Main @b{is}
15175
15176    @b{package} Compiler @b{renames} Common.Compiler;
15177
15178 @b{end} Main;
15179 @end group
15180 @end smallexample
15181
15182 @item Finally we need to create a dummy procedure that @code{with}s (either
15183 explicitly or implicitly) all the sources of our two programs.
15184
15185 @end enumerate
15186
15187 @noindent
15188 Now we can build the programs using the command
15189
15190 @smallexample
15191    gnatmake ^-P^/PROJECT_FILE=^main dummy
15192 @end smallexample
15193
15194 @noindent
15195 for the Debug mode, or
15196
15197 @ifclear vms
15198 @smallexample
15199    gnatmake -Pmain -XBUILD=release
15200 @end smallexample
15201 @end ifclear
15202
15203 @ifset vms
15204 @smallexample
15205    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
15206 @end smallexample
15207 @end ifset
15208
15209 @noindent
15210 for the Release mode.
15211
15212 @c ********************************
15213 @c * Project File Complete Syntax *
15214 @c ********************************
15215
15216 @node Project File Complete Syntax
15217 @section Project File Complete Syntax
15218
15219 @smallexample
15220 project ::=
15221   context_clause project_declaration
15222
15223 context_clause ::=
15224   @{with_clause@}
15225
15226 with_clause ::=
15227   @b{with} path_name @{ , path_name @} ;
15228
15229 path_name ::=
15230    string_literal
15231
15232 project_declaration ::=
15233   simple_project_declaration | project_extension
15234
15235 simple_project_declaration ::=
15236   @b{project} <project_>simple_name @b{is}
15237     @{declarative_item@}
15238   @b{end} <project_>simple_name;
15239
15240 project_extension ::=
15241   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
15242     @{declarative_item@}
15243   @b{end} <project_>simple_name;
15244
15245 declarative_item ::=
15246   package_declaration |
15247   typed_string_declaration |
15248   other_declarative_item
15249
15250 package_declaration ::=
15251   package_spec | package_renaming
15252
15253 package_spec ::=
15254   @b{package} package_identifier @b{is}
15255     @{simple_declarative_item@}
15256   @b{end} package_identifier ;
15257
15258 package_identifier ::=
15259   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
15260   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
15261   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
15262
15263 package_renaming ::==
15264   @b{package} package_identifier @b{renames}
15265        <project_>simple_name.package_identifier ;
15266
15267 typed_string_declaration ::=
15268   @b{type} <typed_string_>_simple_name @b{is}
15269    ( string_literal @{, string_literal@} );
15270
15271 other_declarative_item ::=
15272   attribute_declaration |
15273   typed_variable_declaration |
15274   variable_declaration |
15275   case_construction
15276
15277 attribute_declaration ::=
15278   full_associative_array_declaration |
15279   @b{for} attribute_designator @b{use} expression ;
15280
15281 full_associative_array_declaration ::=
15282   @b{for} <associative_array_attribute_>simple_name @b{use}
15283   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
15284
15285 attribute_designator ::=
15286   <simple_attribute_>simple_name |
15287   <associative_array_attribute_>simple_name ( string_literal )
15288
15289 typed_variable_declaration ::=
15290   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
15291
15292 variable_declaration ::=
15293   <variable_>simple_name := expression;
15294
15295 expression ::=
15296   term @{& term@}
15297
15298 term ::=
15299   literal_string |
15300   string_list |
15301   <variable_>name |
15302   external_value |
15303   attribute_reference
15304
15305 string_literal ::=
15306   (same as Ada)
15307
15308 string_list ::=
15309   ( <string_>expression @{ , <string_>expression @} )
15310
15311 external_value ::=
15312   @b{external} ( string_literal [, string_literal] )
15313
15314 attribute_reference ::=
15315   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
15316
15317 attribute_prefix ::=
15318   @b{project} |
15319   <project_>simple_name | package_identifier |
15320   <project_>simple_name . package_identifier
15321
15322 case_construction ::=
15323   @b{case} <typed_variable_>name @b{is}
15324     @{case_item@}
15325   @b{end case} ;
15326
15327 case_item ::=
15328   @b{when} discrete_choice_list =>
15329       @{case_construction | attribute_declaration@}
15330
15331 discrete_choice_list ::=
15332   string_literal @{| string_literal@} |
15333   @b{others}
15334
15335 name ::=
15336   simple_name @{. simple_name@}
15337
15338 simple_name ::=
15339   identifier (same as Ada)
15340
15341 @end smallexample
15342
15343 @node The Cross-Referencing Tools gnatxref and gnatfind
15344 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
15345 @findex gnatxref
15346 @findex gnatfind
15347
15348 @noindent
15349 The compiler generates cross-referencing information (unless
15350 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
15351 This information indicates where in the source each entity is declared and
15352 referenced. Note that entities in package Standard are not included, but
15353 entities in all other predefined units are included in the output.
15354
15355 Before using any of these two tools, you need to compile successfully your
15356 application, so that GNAT gets a chance to generate the cross-referencing
15357 information.
15358
15359 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
15360 information to provide the user with the capability to easily locate the
15361 declaration and references to an entity. These tools are quite similar,
15362 the difference being that @code{gnatfind} is intended for locating
15363 definitions and/or references to a specified entity or entities, whereas
15364 @code{gnatxref} is oriented to generating a full report of all
15365 cross-references.
15366
15367 To use these tools, you must not compile your application using the
15368 @option{-gnatx} switch on the @command{gnatmake} command line
15369 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
15370 information will not be generated.
15371
15372 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
15373 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
15374
15375 @menu
15376 * Switches for gnatxref::
15377 * Switches for gnatfind::
15378 * Project Files for gnatxref and gnatfind::
15379 * Regular Expressions in gnatfind and gnatxref::
15380 * Examples of gnatxref Usage::
15381 * Examples of gnatfind Usage::
15382 @end menu
15383
15384 @node Switches for gnatxref
15385 @section @code{gnatxref} Switches
15386
15387 @noindent
15388 The command invocation for @code{gnatxref} is:
15389 @smallexample
15390 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
15391 @c Expanding @ovar macro inline (explanation in macro def comments)
15392 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
15393 @end smallexample
15394
15395 @noindent
15396 where
15397
15398 @table @var
15399 @item sourcefile1
15400 @itemx sourcefile2
15401 identifies the source files for which a report is to be generated. The
15402 ``with''ed units will be processed too. You must provide at least one file.
15403
15404 These file names are considered to be regular expressions, so for instance
15405 specifying @file{source*.adb} is the same as giving every file in the current
15406 directory whose name starts with @file{source} and whose extension is
15407 @file{adb}.
15408
15409 You shouldn't specify any directory name, just base names. @command{gnatxref}
15410 and @command{gnatfind} will be able to locate these files by themselves using
15411 the source path. If you specify directories, no result is produced.
15412
15413 @end table
15414
15415 @noindent
15416 The switches can be:
15417 @table @option
15418 @c !sort!
15419 @item --version
15420 @cindex @option{--version} @command{gnatxref}
15421 Display Copyright and version, then exit disregarding all other options.
15422
15423 @item --help
15424 @cindex @option{--help} @command{gnatxref}
15425 If @option{--version} was not used, display usage, then exit disregarding
15426 all other options.
15427
15428 @item ^-a^/ALL_FILES^
15429 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
15430 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15431 the read-only files found in the library search path. Otherwise, these files
15432 will be ignored. This option can be used to protect Gnat sources or your own
15433 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15434 much faster, and their output much smaller. Read-only here refers to access
15435 or permissions status in the file system for the current user.
15436
15437 @item -aIDIR
15438 @cindex @option{-aIDIR} (@command{gnatxref})
15439 When looking for source files also look in directory DIR. The order in which
15440 source file search is undertaken is the same as for @command{gnatmake}.
15441
15442 @item -aODIR
15443 @cindex @option{-aODIR} (@command{gnatxref})
15444 When searching for library and object files, look in directory
15445 DIR. The order in which library files are searched is the same as for
15446 @command{gnatmake}.
15447
15448 @item -nostdinc
15449 @cindex @option{-nostdinc} (@command{gnatxref})
15450 Do not look for sources in the system default directory.
15451
15452 @item -nostdlib
15453 @cindex @option{-nostdlib} (@command{gnatxref})
15454 Do not look for library files in the system default directory.
15455
15456 @item --RTS=@var{rts-path}
15457 @cindex @option{--RTS} (@command{gnatxref})
15458 Specifies the default location of the runtime library. Same meaning as the
15459 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15460
15461 @item ^-d^/DERIVED_TYPES^
15462 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
15463 If this switch is set @code{gnatxref} will output the parent type
15464 reference for each matching derived types.
15465
15466 @item ^-f^/FULL_PATHNAME^
15467 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
15468 If this switch is set, the output file names will be preceded by their
15469 directory (if the file was found in the search path). If this switch is
15470 not set, the directory will not be printed.
15471
15472 @item ^-g^/IGNORE_LOCALS^
15473 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
15474 If this switch is set, information is output only for library-level
15475 entities, ignoring local entities. The use of this switch may accelerate
15476 @code{gnatfind} and @code{gnatxref}.
15477
15478 @item -IDIR
15479 @cindex @option{-IDIR} (@command{gnatxref})
15480 Equivalent to @samp{-aODIR -aIDIR}.
15481
15482 @item -pFILE
15483 @cindex @option{-pFILE} (@command{gnatxref})
15484 Specify a project file to use @xref{Project Files}.
15485 If you need to use the @file{.gpr}
15486 project files, you should use gnatxref through the GNAT driver
15487 (@command{gnat xref -Pproject}).
15488
15489 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15490 project file in the current directory.
15491
15492 If a project file is either specified or found by the tools, then the content
15493 of the source directory and object directory lines are added as if they
15494 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
15495 and @samp{^-aO^OBJECT_SEARCH^}.
15496 @item ^-u^/UNUSED^
15497 Output only unused symbols. This may be really useful if you give your
15498 main compilation unit on the command line, as @code{gnatxref} will then
15499 display every unused entity and 'with'ed package.
15500
15501 @ifclear vms
15502 @item -v
15503 Instead of producing the default output, @code{gnatxref} will generate a
15504 @file{tags} file that can be used by vi. For examples how to use this
15505 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
15506 to the standard output, thus you will have to redirect it to a file.
15507 @end ifclear
15508
15509 @end table
15510
15511 @noindent
15512 All these switches may be in any order on the command line, and may even
15513 appear after the file names. They need not be separated by spaces, thus
15514 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15515 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15516
15517 @node Switches for gnatfind
15518 @section @code{gnatfind} Switches
15519
15520 @noindent
15521 The command line for @code{gnatfind} is:
15522
15523 @smallexample
15524 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
15525 @c       @r{[}@var{file1} @var{file2} @dots{}]
15526 @c Expanding @ovar macro inline (explanation in macro def comments)
15527 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
15528       @r{[}@var{file1} @var{file2} @dots{}@r{]}
15529 @end smallexample
15530
15531 @noindent
15532 where
15533
15534 @table @var
15535 @item pattern
15536 An entity will be output only if it matches the regular expression found
15537 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
15538
15539 Omitting the pattern is equivalent to specifying @samp{*}, which
15540 will match any entity. Note that if you do not provide a pattern, you
15541 have to provide both a sourcefile and a line.
15542
15543 Entity names are given in Latin-1, with uppercase/lowercase equivalence
15544 for matching purposes. At the current time there is no support for
15545 8-bit codes other than Latin-1, or for wide characters in identifiers.
15546
15547 @item sourcefile
15548 @code{gnatfind} will look for references, bodies or declarations
15549 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
15550 and column @var{column}. See @ref{Examples of gnatfind Usage}
15551 for syntax examples.
15552
15553 @item line
15554 is a decimal integer identifying the line number containing
15555 the reference to the entity (or entities) to be located.
15556
15557 @item column
15558 is a decimal integer identifying the exact location on the
15559 line of the first character of the identifier for the
15560 entity reference. Columns are numbered from 1.
15561
15562 @item file1 file2 @dots{}
15563 The search will be restricted to these source files. If none are given, then
15564 the search will be done for every library file in the search path.
15565 These file must appear only after the pattern or sourcefile.
15566
15567 These file names are considered to be regular expressions, so for instance
15568 specifying @file{source*.adb} is the same as giving every file in the current
15569 directory whose name starts with @file{source} and whose extension is
15570 @file{adb}.
15571
15572 The location of the spec of the entity will always be displayed, even if it
15573 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
15574 occurrences of the entity in the separate units of the ones given on the
15575 command line will also be displayed.
15576
15577 Note that if you specify at least one file in this part, @code{gnatfind} may
15578 sometimes not be able to find the body of the subprograms.
15579
15580 @end table
15581
15582 @noindent
15583 At least one of 'sourcefile' or 'pattern' has to be present on
15584 the command line.
15585
15586 The following switches are available:
15587 @table @option
15588 @c !sort!
15589
15590 @cindex @option{--version} @command{gnatfind}
15591 Display Copyright and version, then exit disregarding all other options.
15592
15593 @item --help
15594 @cindex @option{--help} @command{gnatfind}
15595 If @option{--version} was not used, display usage, then exit disregarding
15596 all other options.
15597
15598 @item ^-a^/ALL_FILES^
15599 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
15600 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15601 the read-only files found in the library search path. Otherwise, these files
15602 will be ignored. This option can be used to protect Gnat sources or your own
15603 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15604 much faster, and their output much smaller. Read-only here refers to access
15605 or permission status in the file system for the current user.
15606
15607 @item -aIDIR
15608 @cindex @option{-aIDIR} (@command{gnatfind})
15609 When looking for source files also look in directory DIR. The order in which
15610 source file search is undertaken is the same as for @command{gnatmake}.
15611
15612 @item -aODIR
15613 @cindex @option{-aODIR} (@command{gnatfind})
15614 When searching for library and object files, look in directory
15615 DIR. The order in which library files are searched is the same as for
15616 @command{gnatmake}.
15617
15618 @item -nostdinc
15619 @cindex @option{-nostdinc} (@command{gnatfind})
15620 Do not look for sources in the system default directory.
15621
15622 @item -nostdlib
15623 @cindex @option{-nostdlib} (@command{gnatfind})
15624 Do not look for library files in the system default directory.
15625
15626 @item --ext=@var{extension}
15627 @cindex @option{--ext} (@command{gnatfind})
15628 Specify an alternate ali file extension. The default is @code{ali} and other
15629 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
15630 switch. Note that if this switch overrides the default, which means that only
15631 the new extension will be considered.
15632
15633 @item --RTS=@var{rts-path}
15634 @cindex @option{--RTS} (@command{gnatfind})
15635 Specifies the default location of the runtime library. Same meaning as the
15636 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15637
15638 @item ^-d^/DERIVED_TYPE_INFORMATION^
15639 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
15640 If this switch is set, then @code{gnatfind} will output the parent type
15641 reference for each matching derived types.
15642
15643 @item ^-e^/EXPRESSIONS^
15644 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
15645 By default, @code{gnatfind} accept the simple regular expression set for
15646 @samp{pattern}. If this switch is set, then the pattern will be
15647 considered as full Unix-style regular expression.
15648
15649 @item ^-f^/FULL_PATHNAME^
15650 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
15651 If this switch is set, the output file names will be preceded by their
15652 directory (if the file was found in the search path). If this switch is
15653 not set, the directory will not be printed.
15654
15655 @item ^-g^/IGNORE_LOCALS^
15656 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
15657 If this switch is set, information is output only for library-level
15658 entities, ignoring local entities. The use of this switch may accelerate
15659 @code{gnatfind} and @code{gnatxref}.
15660
15661 @item -IDIR
15662 @cindex @option{-IDIR} (@command{gnatfind})
15663 Equivalent to @samp{-aODIR -aIDIR}.
15664
15665 @item -pFILE
15666 @cindex @option{-pFILE} (@command{gnatfind})
15667 Specify a project file (@pxref{Project Files}) to use.
15668 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15669 project file in the current directory.
15670
15671 If a project file is either specified or found by the tools, then the content
15672 of the source directory and object directory lines are added as if they
15673 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
15674 @samp{^-aO^/OBJECT_SEARCH^}.
15675
15676 @item ^-r^/REFERENCES^
15677 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
15678 By default, @code{gnatfind} will output only the information about the
15679 declaration, body or type completion of the entities. If this switch is
15680 set, the @code{gnatfind} will locate every reference to the entities in
15681 the files specified on the command line (or in every file in the search
15682 path if no file is given on the command line).
15683
15684 @item ^-s^/PRINT_LINES^
15685 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
15686 If this switch is set, then @code{gnatfind} will output the content
15687 of the Ada source file lines were the entity was found.
15688
15689 @item ^-t^/TYPE_HIERARCHY^
15690 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
15691 If this switch is set, then @code{gnatfind} will output the type hierarchy for
15692 the specified type. It act like -d option but recursively from parent
15693 type to parent type. When this switch is set it is not possible to
15694 specify more than one file.
15695
15696 @end table
15697
15698 @noindent
15699 All these switches may be in any order on the command line, and may even
15700 appear after the file names. They need not be separated by spaces, thus
15701 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15702 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15703
15704 As stated previously, gnatfind will search in every directory in the
15705 search path. You can force it to look only in the current directory if
15706 you specify @code{*} at the end of the command line.
15707
15708 @node Project Files for gnatxref and gnatfind
15709 @section Project Files for @command{gnatxref} and @command{gnatfind}
15710
15711 @noindent
15712 Project files allow a programmer to specify how to compile its
15713 application, where to find sources, etc.  These files are used
15714 @ifclear vms
15715 primarily by GPS, but they can also be used
15716 @end ifclear
15717 by the two tools
15718 @code{gnatxref} and @code{gnatfind}.
15719
15720 A project file name must end with @file{.gpr}. If a single one is
15721 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
15722 extract the information from it. If multiple project files are found, none of
15723 them is read, and you have to use the @samp{-p} switch to specify the one
15724 you want to use.
15725
15726 The following lines can be included, even though most of them have default
15727 values which can be used in most cases.
15728 The lines can be entered in any order in the file.
15729 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
15730 each line. If you have multiple instances, only the last one is taken into
15731 account.
15732
15733 @table @code
15734 @item src_dir=DIR
15735 [default: @code{"^./^[]^"}]
15736 specifies a directory where to look for source files. Multiple @code{src_dir}
15737 lines can be specified and they will be searched in the order they
15738 are specified.
15739
15740 @item obj_dir=DIR
15741 [default: @code{"^./^[]^"}]
15742 specifies a directory where to look for object and library files. Multiple
15743 @code{obj_dir} lines can be specified, and they will be searched in the order
15744 they are specified
15745
15746 @item comp_opt=SWITCHES
15747 [default: @code{""}]
15748 creates a variable which can be referred to subsequently by using
15749 the @code{$@{comp_opt@}} notation. This is intended to store the default
15750 switches given to @command{gnatmake} and @command{gcc}.
15751
15752 @item bind_opt=SWITCHES
15753 [default: @code{""}]
15754 creates a variable which can be referred to subsequently by using
15755 the @samp{$@{bind_opt@}} notation. This is intended to store the default
15756 switches given to @command{gnatbind}.
15757
15758 @item link_opt=SWITCHES
15759 [default: @code{""}]
15760 creates a variable which can be referred to subsequently by using
15761 the @samp{$@{link_opt@}} notation. This is intended to store the default
15762 switches given to @command{gnatlink}.
15763
15764 @item main=EXECUTABLE
15765 [default: @code{""}]
15766 specifies the name of the executable for the application. This variable can
15767 be referred to in the following lines by using the @samp{$@{main@}} notation.
15768
15769 @ifset vms
15770 @item comp_cmd=COMMAND
15771 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
15772 @end ifset
15773 @ifclear vms
15774 @item comp_cmd=COMMAND
15775 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
15776 @end ifclear
15777 specifies the command used to compile a single file in the application.
15778
15779 @ifset vms
15780 @item make_cmd=COMMAND
15781 [default: @code{"GNAT MAKE $@{main@}
15782 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
15783 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
15784 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
15785 @end ifset
15786 @ifclear vms
15787 @item make_cmd=COMMAND
15788 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
15789 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
15790 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
15791 @end ifclear
15792 specifies the command used to recompile the whole application.
15793
15794 @item run_cmd=COMMAND
15795 [default: @code{"$@{main@}"}]
15796 specifies the command used to run the application.
15797
15798 @item debug_cmd=COMMAND
15799 [default: @code{"gdb $@{main@}"}]
15800 specifies the command used to debug the application
15801
15802 @end table
15803
15804 @noindent
15805 @command{gnatxref} and @command{gnatfind} only take into account the
15806 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
15807
15808 @node Regular Expressions in gnatfind and gnatxref
15809 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
15810
15811 @noindent
15812 As specified in the section about @command{gnatfind}, the pattern can be a
15813 regular expression. Actually, there are to set of regular expressions
15814 which are recognized by the program:
15815
15816 @table @code
15817 @item globbing patterns
15818 These are the most usual regular expression. They are the same that you
15819 generally used in a Unix shell command line, or in a DOS session.
15820
15821 Here is a more formal grammar:
15822 @smallexample
15823 @group
15824 @iftex
15825 @leftskip=.5cm
15826 @end iftex
15827 regexp ::= term
15828 term   ::= elmt            -- matches elmt
15829 term   ::= elmt elmt       -- concatenation (elmt then elmt)
15830 term   ::= *               -- any string of 0 or more characters
15831 term   ::= ?               -- matches any character
15832 term   ::= [char @{char@}]   -- matches any character listed
15833 term   ::= [char - char]   -- matches any character in range
15834 @end group
15835 @end smallexample
15836
15837 @item full regular expression
15838 The second set of regular expressions is much more powerful. This is the
15839 type of regular expressions recognized by utilities such a @file{grep}.
15840
15841 The following is the form of a regular expression, expressed in Ada
15842 reference manual style BNF is as follows
15843
15844 @smallexample
15845 @iftex
15846 @leftskip=.5cm
15847 @end iftex
15848 @group
15849 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
15850
15851 term ::= item @{item@}       -- concatenation (item then item)
15852
15853 item ::= elmt              -- match elmt
15854 item ::= elmt *            -- zero or more elmt's
15855 item ::= elmt +            -- one or more elmt's
15856 item ::= elmt ?            -- matches elmt or nothing
15857 @end group
15858 @group
15859 elmt ::= nschar            -- matches given character
15860 elmt ::= [nschar @{nschar@}]   -- matches any character listed
15861 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
15862 elmt ::= [char - char]     -- matches chars in given range
15863 elmt ::= \ char            -- matches given character
15864 elmt ::= .                 -- matches any single character
15865 elmt ::= ( regexp )        -- parens used for grouping
15866
15867 char ::= any character, including special characters
15868 nschar ::= any character except ()[].*+?^^^
15869 @end group
15870 @end smallexample
15871
15872 Following are a few examples:
15873
15874 @table @samp
15875 @item abcde|fghi
15876 will match any of the two strings @samp{abcde} and @samp{fghi},
15877
15878 @item abc*d
15879 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
15880 @samp{abcccd}, and so on,
15881
15882 @item [a-z]+
15883 will match any string which has only lowercase characters in it (and at
15884 least one character.
15885
15886 @end table
15887 @end table
15888
15889 @node Examples of gnatxref Usage
15890 @section Examples of @code{gnatxref} Usage
15891
15892 @subsection General Usage
15893
15894 @noindent
15895 For the following examples, we will consider the following units:
15896
15897 @smallexample @c ada
15898 @group
15899 @cartouche
15900 main.ads:
15901 1: with Bar;
15902 2: package Main is
15903 3:     procedure Foo (B : in Integer);
15904 4:     C : Integer;
15905 5: private
15906 6:     D : Integer;
15907 7: end Main;
15908
15909 main.adb:
15910 1: package body Main is
15911 2:     procedure Foo (B : in Integer) is
15912 3:     begin
15913 4:        C := B;
15914 5:        D := B;
15915 6:        Bar.Print (B);
15916 7:        Bar.Print (C);
15917 8:     end Foo;
15918 9: end Main;
15919
15920 bar.ads:
15921 1: package Bar is
15922 2:     procedure Print (B : Integer);
15923 3: end bar;
15924 @end cartouche
15925 @end group
15926 @end smallexample
15927
15928 @table @code
15929
15930 @noindent
15931 The first thing to do is to recompile your application (for instance, in
15932 that case just by doing a @samp{gnatmake main}, so that GNAT generates
15933 the cross-referencing information.
15934 You can then issue any of the following commands:
15935
15936 @item gnatxref main.adb
15937 @code{gnatxref} generates cross-reference information for main.adb
15938 and every unit 'with'ed by main.adb.
15939
15940 The output would be:
15941 @smallexample
15942 @iftex
15943 @leftskip=0cm
15944 @end iftex
15945 B                                                      Type: Integer
15946   Decl: bar.ads           2:22
15947 B                                                      Type: Integer
15948   Decl: main.ads          3:20
15949   Body: main.adb          2:20
15950   Ref:  main.adb          4:13     5:13     6:19
15951 Bar                                                    Type: Unit
15952   Decl: bar.ads           1:9
15953   Ref:  main.adb          6:8      7:8
15954        main.ads           1:6
15955 C                                                      Type: Integer
15956   Decl: main.ads          4:5
15957   Modi: main.adb          4:8
15958   Ref:  main.adb          7:19
15959 D                                                      Type: Integer
15960   Decl: main.ads          6:5
15961   Modi: main.adb          5:8
15962 Foo                                                    Type: Unit
15963   Decl: main.ads          3:15
15964   Body: main.adb          2:15
15965 Main                                                    Type: Unit
15966   Decl: main.ads          2:9
15967   Body: main.adb          1:14
15968 Print                                                   Type: Unit
15969   Decl: bar.ads           2:15
15970   Ref:  main.adb          6:12     7:12
15971 @end smallexample
15972
15973 @noindent
15974 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
15975 its body is in main.adb, line 1, column 14 and is not referenced any where.
15976
15977 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
15978 it referenced in main.adb, line 6 column 12 and line 7 column 12.
15979
15980 @item gnatxref package1.adb package2.ads
15981 @code{gnatxref} will generates cross-reference information for
15982 package1.adb, package2.ads and any other package 'with'ed by any
15983 of these.
15984
15985 @end table
15986
15987 @ifclear vms
15988 @subsection Using gnatxref with vi
15989
15990 @code{gnatxref} can generate a tags file output, which can be used
15991 directly from @command{vi}. Note that the standard version of @command{vi}
15992 will not work properly with overloaded symbols. Consider using another
15993 free implementation of @command{vi}, such as @command{vim}.
15994
15995 @smallexample
15996 $ gnatxref -v gnatfind.adb > tags
15997 @end smallexample
15998
15999 @noindent
16000 will generate the tags file for @code{gnatfind} itself (if the sources
16001 are in the search path!).
16002
16003 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
16004 (replacing @var{entity} by whatever you are looking for), and vi will
16005 display a new file with the corresponding declaration of entity.
16006 @end ifclear
16007
16008 @node Examples of gnatfind Usage
16009 @section Examples of @code{gnatfind} Usage
16010
16011 @table @code
16012
16013 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
16014 Find declarations for all entities xyz referenced at least once in
16015 main.adb. The references are search in every library file in the search
16016 path.
16017
16018 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
16019 switch is set)
16020
16021 The output will look like:
16022 @smallexample
16023 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
16024 ^directory/^[directory]^main.adb:24:10: xyz <= body
16025 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
16026 @end smallexample
16027
16028 @noindent
16029 that is to say, one of the entities xyz found in main.adb is declared at
16030 line 12 of main.ads (and its body is in main.adb), and another one is
16031 declared at line 45 of foo.ads
16032
16033 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
16034 This is the same command as the previous one, instead @code{gnatfind} will
16035 display the content of the Ada source file lines.
16036
16037 The output will look like:
16038
16039 @smallexample
16040 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
16041    procedure xyz;
16042 ^directory/^[directory]^main.adb:24:10: xyz <= body
16043    procedure xyz is
16044 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
16045    xyz : Integer;
16046 @end smallexample
16047
16048 @noindent
16049 This can make it easier to find exactly the location your are looking
16050 for.
16051
16052 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
16053 Find references to all entities containing an x that are
16054 referenced on line 123 of main.ads.
16055 The references will be searched only in main.ads and foo.adb.
16056
16057 @item gnatfind main.ads:123
16058 Find declarations and bodies for all entities that are referenced on
16059 line 123 of main.ads.
16060
16061 This is the same as @code{gnatfind "*":main.adb:123}.
16062
16063 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
16064 Find the declaration for the entity referenced at column 45 in
16065 line 123 of file main.adb in directory mydir. Note that it
16066 is usual to omit the identifier name when the column is given,
16067 since the column position identifies a unique reference.
16068
16069 The column has to be the beginning of the identifier, and should not
16070 point to any character in the middle of the identifier.
16071
16072 @end table
16073
16074 @c *********************************
16075 @node The GNAT Pretty-Printer gnatpp
16076 @chapter The GNAT Pretty-Printer @command{gnatpp}
16077 @findex gnatpp
16078 @cindex Pretty-Printer
16079
16080 @noindent
16081 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
16082 for source reformatting / pretty-printing.
16083 It takes an Ada source file as input and generates a reformatted
16084 version as output.
16085 You can specify various style directives via switches; e.g.,
16086 identifier case conventions, rules of indentation, and comment layout.
16087
16088 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
16089 tree for the input source and thus requires the input to be syntactically and
16090 semantically legal.
16091 If this condition is not met, @command{gnatpp} will terminate with an
16092 error message; no output file will be generated.
16093
16094 If the source files presented to @command{gnatpp} contain
16095 preprocessing directives, then the output file will
16096 correspond to the generated source after all
16097 preprocessing is carried out. There is no way
16098 using @command{gnatpp} to obtain pretty printed files that
16099 include the preprocessing directives.
16100
16101 If the compilation unit
16102 contained in the input source depends semantically upon units located
16103 outside the current directory, you have to provide the source search path
16104 when invoking @command{gnatpp}, if these units are contained in files with
16105 names that do not follow the GNAT file naming rules, you have to provide
16106 the configuration file describing the corresponding naming scheme;
16107 see the description of the @command{gnatpp}
16108 switches below. Another possibility is to use a project file and to
16109 call @command{gnatpp} through the @command{gnat} driver
16110
16111 The @command{gnatpp} command has the form
16112
16113 @smallexample
16114 @c $ gnatpp @ovar{switches} @var{filename}
16115 @c Expanding @ovar macro inline (explanation in macro def comments)
16116 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
16117 @end smallexample
16118
16119 @noindent
16120 where
16121 @itemize @bullet
16122 @item
16123 @var{switches} is an optional sequence of switches defining such properties as
16124 the formatting rules, the source search path, and the destination for the
16125 output source file
16126
16127 @item
16128 @var{filename} is the name (including the extension) of the source file to
16129 reformat; ``wildcards'' or several file names on the same gnatpp command are
16130 allowed.  The file name may contain path information; it does not have to
16131 follow the GNAT file naming rules
16132
16133 @item
16134 @samp{@var{gcc_switches}} is a list of switches for
16135 @command{gcc}. They will be passed on to all compiler invocations made by
16136 @command{gnatelim} to generate the ASIS trees. Here you can provide
16137 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
16138 use the @option{-gnatec} switch to set the configuration file etc.
16139 @end itemize
16140
16141 @menu
16142 * Switches for gnatpp::
16143 * Formatting Rules::
16144 @end menu
16145
16146 @node Switches for gnatpp
16147 @section Switches for @command{gnatpp}
16148
16149 @noindent
16150 The following subsections describe the various switches accepted by
16151 @command{gnatpp}, organized by category.
16152
16153 @ifclear vms
16154 You specify a switch by supplying a name and generally also a value.
16155 In many cases the values for a switch with a given name are incompatible with
16156 each other
16157 (for example the switch that controls the casing of a reserved word may have
16158 exactly one value: upper case, lower case, or
16159 mixed case) and thus exactly one such switch can be in effect for an
16160 invocation of @command{gnatpp}.
16161 If more than one is supplied, the last one is used.
16162 However, some values for the same switch are mutually compatible.
16163 You may supply several such switches to @command{gnatpp}, but then
16164 each must be specified in full, with both the name and the value.
16165 Abbreviated forms (the name appearing once, followed by each value) are
16166 not permitted.
16167 For example, to set
16168 the alignment of the assignment delimiter both in declarations and in
16169 assignment statements, you must write @option{-A2A3}
16170 (or @option{-A2 -A3}), but not @option{-A23}.
16171 @end ifclear
16172
16173 @ifset vms
16174 In many cases the set of options for a given qualifier are incompatible with
16175 each other (for example the qualifier that controls the casing of a reserved
16176 word may have exactly one option, which specifies either upper case, lower
16177 case, or mixed case), and thus exactly one such option can be in effect for
16178 an invocation of @command{gnatpp}.
16179 If more than one is supplied, the last one is used.
16180 However, some qualifiers have options that are mutually compatible,
16181 and then you may then supply several such options when invoking
16182 @command{gnatpp}.
16183 @end ifset
16184
16185 In most cases, it is obvious whether or not the
16186 ^values for a switch with a given name^options for a given qualifier^
16187 are compatible with each other.
16188 When the semantics might not be evident, the summaries below explicitly
16189 indicate the effect.
16190
16191 @menu
16192 * Alignment Control::
16193 * Casing Control::
16194 * Construct Layout Control::
16195 * General Text Layout Control::
16196 * Other Formatting Options::
16197 * Setting the Source Search Path::
16198 * Output File Control::
16199 * Other gnatpp Switches::
16200 @end menu
16201
16202 @node Alignment Control
16203 @subsection Alignment Control
16204 @cindex Alignment control in @command{gnatpp}
16205
16206 @noindent
16207 Programs can be easier to read if certain constructs are vertically aligned.
16208 By default all alignments are set ON.
16209 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
16210 OFF, and then use one or more of the other
16211 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
16212 to activate alignment for specific constructs.
16213
16214 @table @option
16215 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
16216
16217 @ifset vms
16218 @item /ALIGN=ON
16219 Set all alignments to ON
16220 @end ifset
16221
16222 @item ^-A0^/ALIGN=OFF^
16223 Set all alignments to OFF
16224
16225 @item ^-A1^/ALIGN=COLONS^
16226 Align @code{:} in declarations
16227
16228 @item ^-A2^/ALIGN=DECLARATIONS^
16229 Align @code{:=} in initializations in declarations
16230
16231 @item ^-A3^/ALIGN=STATEMENTS^
16232 Align @code{:=} in assignment statements
16233
16234 @item ^-A4^/ALIGN=ARROWS^
16235 Align @code{=>} in associations
16236
16237 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
16238 Align @code{at} keywords in the component clauses in record
16239 representation clauses
16240 @end table
16241
16242 @noindent
16243 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
16244 is allowed.
16245
16246 @node Casing Control
16247 @subsection Casing Control
16248 @cindex Casing control in @command{gnatpp}
16249
16250 @noindent
16251 @command{gnatpp} allows you to specify the casing for reserved words,
16252 pragma names, attribute designators and identifiers.
16253 For identifiers you may define a
16254 general rule for name casing but also override this rule
16255 via a set of dictionary files.
16256
16257 Three types of casing are supported: lower case, upper case, and mixed case.
16258 Lower and upper case are self-explanatory (but since some letters in
16259 Latin1 and other GNAT-supported character sets
16260 exist only in lower-case form, an upper case conversion will have no
16261 effect on them.)
16262 ``Mixed case'' means that the first letter, and also each letter immediately
16263 following an underscore, are converted to their uppercase forms;
16264 all the other letters are converted to their lowercase forms.
16265
16266 @table @option
16267 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
16268 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
16269 Attribute designators are lower case
16270
16271 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
16272 Attribute designators are upper case
16273
16274 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
16275 Attribute designators are mixed case (this is the default)
16276
16277 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
16278 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
16279 Keywords (technically, these are known in Ada as @emph{reserved words}) are
16280 lower case (this is the default)
16281
16282 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
16283 Keywords are upper case
16284
16285 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
16286 @item ^-nD^/NAME_CASING=AS_DECLARED^
16287 Name casing for defining occurrences are as they appear in the source file
16288 (this is the default)
16289
16290 @item ^-nU^/NAME_CASING=UPPER_CASE^
16291 Names are in upper case
16292
16293 @item ^-nL^/NAME_CASING=LOWER_CASE^
16294 Names are in lower case
16295
16296 @item ^-nM^/NAME_CASING=MIXED_CASE^
16297 Names are in mixed case
16298
16299 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
16300 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
16301 Pragma names are lower case
16302
16303 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
16304 Pragma names are upper case
16305
16306 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
16307 Pragma names are mixed case (this is the default)
16308
16309 @item ^-D@var{file}^/DICTIONARY=@var{file}^
16310 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
16311 Use @var{file} as a @emph{dictionary file} that defines
16312 the casing for a set of specified names,
16313 thereby overriding the effect on these names by
16314 any explicit or implicit
16315 ^-n^/NAME_CASING^ switch.
16316 To supply more than one dictionary file,
16317 use ^several @option{-D} switches^a list of files as options^.
16318
16319 @noindent
16320 @option{gnatpp} implicitly uses a @emph{default dictionary file}
16321 to define the casing for the Ada predefined names and
16322 the names declared in the GNAT libraries.
16323
16324 @item ^-D-^/SPECIFIC_CASING^
16325 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
16326 Do not use the default dictionary file;
16327 instead, use the casing
16328 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
16329 dictionary file(s)
16330 @end table
16331
16332 @noindent
16333 The structure of a dictionary file, and details on the conventions
16334 used in the default dictionary file, are defined in @ref{Name Casing}.
16335
16336 The @option{^-D-^/SPECIFIC_CASING^} and
16337 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
16338 compatible.
16339
16340 @node Construct Layout Control
16341 @subsection Construct Layout Control
16342 @cindex Layout control in @command{gnatpp}
16343
16344 @noindent
16345 This group of @command{gnatpp} switches controls the layout of comments and
16346 complex syntactic constructs.  See @ref{Formatting Comments} for details
16347 on their effect.
16348
16349 @table @option
16350 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
16351 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
16352 All the comments remain unchanged
16353
16354 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
16355 GNAT-style comment line indentation (this is the default).
16356
16357 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
16358 Reference-manual comment line indentation.
16359
16360 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
16361 GNAT-style comment beginning
16362
16363 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
16364 Reformat comment blocks
16365
16366 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
16367 Keep unchanged special form comments
16368
16369 Reformat comment blocks
16370
16371 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
16372 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
16373 GNAT-style layout (this is the default)
16374
16375 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
16376 Compact layout
16377
16378 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
16379 Uncompact layout
16380
16381 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
16382 @item ^-N^/NOTABS^
16383 All the VT characters are removed from the comment text. All the HT characters
16384 are expanded with the sequences of space characters to get to the next tab
16385 stops.
16386
16387 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
16388 @item ^--no-separate-is^/NO_SEPARATE_IS^
16389 Do not place the keyword @code{is} on a separate line in a subprogram body in
16390 case if the spec occupies more then one line.
16391
16392 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
16393 @item ^--separate-label^/SEPARATE_LABEL^
16394 Place statement label(s) on a separate line, with the following statement
16395 on the next line.
16396
16397 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
16398 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
16399 Place the keyword @code{loop} in FOR and WHILE loop statements and the
16400 keyword @code{then} in IF statements on a separate line.
16401
16402 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
16403 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
16404 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
16405 keyword @code{then} in IF statements on a separate line. This option is
16406 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
16407
16408 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
16409 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
16410 Start each USE clause in a context clause from a separate line.
16411
16412 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
16413 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
16414 Use a separate line for a loop or block statement name, but do not use an extra
16415 indentation level for the statement itself.
16416
16417 @end table
16418
16419 @ifclear vms
16420 @noindent
16421 The @option{-c1} and @option{-c2} switches are incompatible.
16422 The @option{-c3} and @option{-c4} switches are compatible with each other and
16423 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
16424 the other comment formatting switches.
16425
16426 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
16427 @end ifclear
16428
16429 @ifset vms
16430 @noindent
16431 For the @option{/COMMENTS_LAYOUT} qualifier:
16432 @itemize @bullet
16433 @item
16434 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
16435 @item
16436 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
16437 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
16438 @end itemize
16439
16440 @noindent
16441 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
16442 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
16443 @end ifset
16444
16445 @node General Text Layout Control
16446 @subsection General Text Layout Control
16447
16448 @noindent
16449 These switches allow control over line length and indentation.
16450
16451 @table @option
16452 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
16453 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
16454 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
16455
16456 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
16457 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
16458 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
16459
16460 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
16461 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
16462 Indentation level for continuation lines (relative to the line being
16463 continued), @var{nnn} from 1@dots{}9.
16464 The default
16465 value is one less then the (normal) indentation level, unless the
16466 indentation is set to 1 (in which case the default value for continuation
16467 line indentation is also 1)
16468 @end table
16469
16470 @node Other Formatting Options
16471 @subsection Other Formatting Options
16472
16473 @noindent
16474 These switches control the inclusion of missing end/exit labels, and
16475 the indentation level in @b{case} statements.
16476
16477 @table @option
16478 @item ^-e^/NO_MISSED_LABELS^
16479 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
16480 Do not insert missing end/exit labels. An end label is the name of
16481 a construct that may optionally be repeated at the end of the
16482 construct's declaration;
16483 e.g., the names of packages, subprograms, and tasks.
16484 An exit label is the name of a loop that may appear as target
16485 of an exit statement within the loop.
16486 By default, @command{gnatpp} inserts these end/exit labels when
16487 they are absent from the original source. This option suppresses such
16488 insertion, so that the formatted source reflects the original.
16489
16490 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
16491 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
16492 Insert a Form Feed character after a pragma Page.
16493
16494 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
16495 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
16496 Do not use an additional indentation level for @b{case} alternatives
16497 and variants if there are @var{nnn} or more (the default
16498 value is 10).
16499 If @var{nnn} is 0, an additional indentation level is
16500 used for @b{case} alternatives and variants regardless of their number.
16501 @end table
16502
16503 @node Setting the Source Search Path
16504 @subsection Setting the Source Search Path
16505
16506 @noindent
16507 To define the search path for the input source file, @command{gnatpp}
16508 uses the same switches as the GNAT compiler, with the same effects.
16509
16510 @table @option
16511 @item ^-I^/SEARCH=^@var{dir}
16512 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
16513 The same as the corresponding gcc switch
16514
16515 @item ^-I-^/NOCURRENT_DIRECTORY^
16516 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
16517 The same as the corresponding gcc switch
16518
16519 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
16520 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
16521 The same as the corresponding gcc switch
16522
16523 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
16524 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
16525 The same as the corresponding gcc switch
16526
16527 @end table
16528
16529 @node Output File Control
16530 @subsection Output File Control
16531
16532 @noindent
16533 By default the output is sent to the file whose name is obtained by appending
16534 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
16535 (if the file with this name already exists, it is unconditionally overwritten).
16536 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
16537 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
16538 as output file.
16539 The output may be redirected by the following switches:
16540
16541 @table @option
16542 @item ^-pipe^/STANDARD_OUTPUT^
16543 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
16544 Send the output to @code{Standard_Output}
16545
16546 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
16547 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
16548 Write the output into @var{output_file}.
16549 If @var{output_file} already exists, @command{gnatpp} terminates without
16550 reading or processing the input file.
16551
16552 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
16553 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
16554 Write the output into @var{output_file}, overwriting the existing file
16555 (if one is present).
16556
16557 @item ^-r^/REPLACE^
16558 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
16559 Replace the input source file with the reformatted output, and copy the
16560 original input source into the file whose name is obtained by appending the
16561 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
16562 If a file with this name already exists, @command{gnatpp} terminates without
16563 reading or processing the input file.
16564
16565 @item ^-rf^/OVERRIDING_REPLACE^
16566 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
16567 Like @option{^-r^/REPLACE^} except that if the file with the specified name
16568 already exists, it is overwritten.
16569
16570 @item ^-rnb^/REPLACE_NO_BACKUP^
16571 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
16572 Replace the input source file with the reformatted output without
16573 creating any backup copy of the input source.
16574
16575 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
16576 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
16577 Specifies the format of the reformatted output file. The @var{xxx}
16578 ^string specified with the switch^option^ may be either
16579 @itemize @bullet
16580 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
16581 @item ``@option{^crlf^CRLF^}''
16582 the same as @option{^crlf^CRLF^}
16583 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
16584 @item ``@option{^lf^LF^}''
16585 the same as @option{^unix^UNIX^}
16586 @end itemize
16587
16588 @item ^-W^/RESULT_ENCODING=^@var{e}
16589 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
16590 Specify the wide character encoding method used to write the code in the
16591 result file
16592 @var{e} is one of the following:
16593
16594 @itemize @bullet
16595
16596 @item ^h^HEX^
16597 Hex encoding
16598
16599 @item ^u^UPPER^
16600 Upper half encoding
16601
16602 @item ^s^SHIFT_JIS^
16603 Shift/JIS encoding
16604
16605 @item ^e^EUC^
16606 EUC encoding
16607
16608 @item ^8^UTF8^
16609 UTF-8 encoding
16610
16611 @item ^b^BRACKETS^
16612 Brackets encoding (default value)
16613 @end itemize
16614
16615 @end table
16616
16617 @noindent
16618 Options @option{^-pipe^/STANDARD_OUTPUT^},
16619 @option{^-o^/OUTPUT^} and
16620 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
16621 contains only one file to reformat.
16622 Option
16623 @option{^--eol^/END_OF_LINE^}
16624 and
16625 @option{^-W^/RESULT_ENCODING^}
16626 cannot be used together
16627 with @option{^-pipe^/STANDARD_OUTPUT^} option.
16628
16629 @node Other gnatpp Switches
16630 @subsection Other @code{gnatpp} Switches
16631
16632 @noindent
16633 The additional @command{gnatpp} switches are defined in this subsection.
16634
16635 @table @option
16636 @item ^-files @var{filename}^/FILES=@var{filename}^
16637 @cindex @option{^-files^/FILES^} (@code{gnatpp})
16638 Take the argument source files from the specified file. This file should be an
16639 ordinary text file containing file names separated by spaces or
16640 line breaks. You can use this switch more than once in the same call to
16641 @command{gnatpp}. You also can combine this switch with an explicit list of
16642 files.
16643
16644 @item ^-v^/VERBOSE^
16645 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
16646 Verbose mode;
16647 @command{gnatpp} generates version information and then
16648 a trace of the actions it takes to produce or obtain the ASIS tree.
16649
16650 @item ^-w^/WARNINGS^
16651 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
16652 Warning mode;
16653 @command{gnatpp} generates a warning whenever it cannot provide
16654 a required layout in the result source.
16655 @end table
16656
16657 @node Formatting Rules
16658 @section Formatting Rules
16659
16660 @noindent
16661 The following subsections show how @command{gnatpp} treats ``white space'',
16662 comments, program layout, and name casing.
16663 They provide the detailed descriptions of the switches shown above.
16664
16665 @menu
16666 * White Space and Empty Lines::
16667 * Formatting Comments::
16668 * Construct Layout::
16669 * Name Casing::
16670 @end menu
16671
16672 @node White Space and Empty Lines
16673 @subsection White Space and Empty Lines
16674
16675 @noindent
16676 @command{gnatpp} does not have an option to control space characters.
16677 It will add or remove spaces according to the style illustrated by the
16678 examples in the @cite{Ada Reference Manual}.
16679
16680 The only format effectors
16681 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
16682 that will appear in the output file are platform-specific line breaks,
16683 and also format effectors within (but not at the end of) comments.
16684 In particular, each horizontal tab character that is not inside
16685 a comment will be treated as a space and thus will appear in the
16686 output file as zero or more spaces depending on
16687 the reformatting of the line in which it appears.
16688 The only exception is a Form Feed character, which is inserted after a
16689 pragma @code{Page} when @option{-ff} is set.
16690
16691 The output file will contain no lines with trailing ``white space'' (spaces,
16692 format effectors).
16693
16694 Empty lines in the original source are preserved
16695 only if they separate declarations or statements.
16696 In such contexts, a
16697 sequence of two or more empty lines is replaced by exactly one empty line.
16698 Note that a blank line will be removed if it separates two ``comment blocks''
16699 (a comment block is a sequence of whole-line comments).
16700 In order to preserve a visual separation between comment blocks, use an
16701 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
16702 Likewise, if for some reason you wish to have a sequence of empty lines,
16703 use a sequence of empty comments instead.
16704
16705 @node Formatting Comments
16706 @subsection Formatting Comments
16707
16708 @noindent
16709 Comments in Ada code are of two kinds:
16710 @itemize @bullet
16711 @item
16712 a @emph{whole-line comment}, which appears by itself (possibly preceded by
16713 ``white space'') on a line
16714
16715 @item
16716 an @emph{end-of-line comment}, which follows some other Ada lexical element
16717 on the same line.
16718 @end itemize
16719
16720 @noindent
16721 The indentation of a whole-line comment is that of either
16722 the preceding or following line in
16723 the formatted source, depending on switch settings as will be described below.
16724
16725 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
16726 between the end of the preceding Ada lexical element and the beginning
16727 of the comment as appear in the original source,
16728 unless either the comment has to be split to
16729 satisfy the line length limitation, or else the next line contains a
16730 whole line comment that is considered a continuation of this end-of-line
16731 comment (because it starts at the same position).
16732 In the latter two
16733 cases, the start of the end-of-line comment is moved right to the nearest
16734 multiple of the indentation level.
16735 This may result in a ``line overflow'' (the right-shifted comment extending
16736 beyond the maximum line length), in which case the comment is split as
16737 described below.
16738
16739 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
16740 (GNAT-style comment line indentation)
16741 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
16742 (reference-manual comment line indentation).
16743 With reference-manual style, a whole-line comment is indented as if it
16744 were a declaration or statement at the same place
16745 (i.e., according to the indentation of the preceding line(s)).
16746 With GNAT style, a whole-line comment that is immediately followed by an
16747 @b{if} or @b{case} statement alternative, a record variant, or the reserved
16748 word @b{begin}, is indented based on the construct that follows it.
16749
16750 For example:
16751 @smallexample @c ada
16752 @cartouche
16753 if A then
16754     null;
16755        -- some comment
16756 else
16757    null;
16758 end if;
16759 @end cartouche
16760 @end smallexample
16761
16762 @noindent
16763 Reference-manual indentation produces:
16764
16765 @smallexample @c ada
16766 @cartouche
16767 if A then
16768    null;
16769    --  some comment
16770 else
16771    null;
16772 end if;
16773 @end cartouche
16774 @end smallexample
16775
16776 @noindent
16777 while GNAT-style indentation produces:
16778
16779 @smallexample @c ada
16780 @cartouche
16781 if A then
16782    null;
16783 --  some comment
16784 else
16785    null;
16786 end if;
16787 @end cartouche
16788 @end smallexample
16789
16790 @noindent
16791 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
16792 (GNAT style comment beginning) has the following
16793 effect:
16794
16795 @itemize @bullet
16796 @item
16797 For each whole-line comment that does not end with two hyphens,
16798 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
16799 to ensure that there are at least two spaces between these hyphens and the
16800 first non-blank character of the comment.
16801 @end itemize
16802
16803 @noindent
16804 For an end-of-line comment, if in the original source the next line is a
16805 whole-line comment that starts at the same position
16806 as the end-of-line comment,
16807 then the whole-line comment (and all whole-line comments
16808 that follow it and that start at the same position)
16809 will start at this position in the output file.
16810
16811 @noindent
16812 That is, if in the original source we have:
16813
16814 @smallexample @c ada
16815 @cartouche
16816 begin
16817 A := B + C;            --  B must be in the range Low1..High1
16818                        --  C must be in the range Low2..High2
16819              --B+C will be in the range Low1+Low2..High1+High2
16820 X := X + 1;
16821 @end cartouche
16822 @end smallexample
16823
16824 @noindent
16825 Then in the formatted source we get
16826
16827 @smallexample @c ada
16828 @cartouche
16829 begin
16830    A := B + C;            --  B must be in the range Low1..High1
16831                           --  C must be in the range Low2..High2
16832    --  B+C will be in the range Low1+Low2..High1+High2
16833    X := X + 1;
16834 @end cartouche
16835 @end smallexample
16836
16837 @noindent
16838 A comment that exceeds the line length limit will be split.
16839 Unless switch
16840 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
16841 the line belongs to a reformattable block, splitting the line generates a
16842 @command{gnatpp} warning.
16843 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
16844 comments may be reformatted in typical
16845 word processor style (that is, moving words between lines and putting as
16846 many words in a line as possible).
16847
16848 @noindent
16849 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
16850 that has a special format (that is, a character that is neither a letter nor digit
16851 not white space nor line break immediately following the leading @code{--} of
16852 the comment) should be without any change moved from the argument source
16853 into reformatted source. This switch allows to preserve comments that are used
16854 as a special marks in the code (e.g.@: SPARK annotation).
16855
16856 @node Construct Layout
16857 @subsection Construct Layout
16858
16859 @noindent
16860 In several cases the suggested layout in the Ada Reference Manual includes
16861 an extra level of indentation that many programmers prefer to avoid. The
16862 affected cases include:
16863
16864 @itemize @bullet
16865
16866 @item Record type declaration (RM 3.8)
16867
16868 @item Record representation clause (RM 13.5.1)
16869
16870 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
16871
16872 @item Block statement in case if a block has a statement identifier (RM 5.6)
16873 @end itemize
16874
16875 @noindent
16876 In compact mode (when GNAT style layout or compact layout is set),
16877 the pretty printer uses one level of indentation instead
16878 of two. This is achieved in the record definition and record representation
16879 clause cases by putting the @code{record} keyword on the same line as the
16880 start of the declaration or representation clause, and in the block and loop
16881 case by putting the block or loop header on the same line as the statement
16882 identifier.
16883
16884 @noindent
16885 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
16886 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
16887 layout on the one hand, and uncompact layout
16888 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
16889 can be illustrated by the following examples:
16890
16891 @iftex
16892 @cartouche
16893 @multitable @columnfractions .5 .5
16894 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
16895
16896 @item
16897 @smallexample @c ada
16898 type q is record
16899    a : integer;
16900    b : integer;
16901 end record;
16902 @end smallexample
16903 @tab
16904 @smallexample @c ada
16905 type q is
16906    record
16907       a : integer;
16908       b : integer;
16909    end record;
16910 @end smallexample
16911
16912 @item
16913 @smallexample @c ada
16914 for q use record
16915    a at 0 range  0 .. 31;
16916    b at 4 range  0 .. 31;
16917 end record;
16918 @end smallexample
16919 @tab
16920 @smallexample @c ada
16921 for q use
16922    record
16923       a at 0 range  0 .. 31;
16924       b at 4 range  0 .. 31;
16925    end record;
16926 @end smallexample
16927
16928 @item
16929 @smallexample @c ada
16930 Block : declare
16931    A : Integer := 3;
16932 begin
16933    Proc (A, A);
16934 end Block;
16935 @end smallexample
16936 @tab
16937 @smallexample @c ada
16938 Block :
16939    declare
16940       A : Integer := 3;
16941    begin
16942       Proc (A, A);
16943    end Block;
16944 @end smallexample
16945
16946 @item
16947 @smallexample @c ada
16948 Clear : for J in 1 .. 10 loop
16949    A (J) := 0;
16950 end loop Clear;
16951 @end smallexample
16952 @tab
16953 @smallexample @c ada
16954 Clear :
16955    for J in 1 .. 10 loop
16956       A (J) := 0;
16957    end loop Clear;
16958 @end smallexample
16959 @end multitable
16960 @end cartouche
16961 @end iftex
16962
16963 @ifnottex
16964 @smallexample
16965 @cartouche
16966 GNAT style, compact layout              Uncompact layout
16967
16968 type q is record                        type q is
16969    a : integer;                            record
16970    b : integer;                               a : integer;
16971 end record;                                   b : integer;
16972                                            end record;
16973
16974 for q use record                        for q use
16975    a at 0 range  0 .. 31;                  record
16976    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
16977 end record;                                   b at 4 range  0 .. 31;
16978                                            end record;
16979
16980 Block : declare                         Block :
16981    A : Integer := 3;                       declare
16982 begin                                         A : Integer := 3;
16983    Proc (A, A);                            begin
16984 end Block;                                    Proc (A, A);
16985                                            end Block;
16986
16987 Clear : for J in 1 .. 10 loop           Clear :
16988    A (J) := 0;                             for J in 1 .. 10 loop
16989 end loop Clear;                               A (J) := 0;
16990                                            end loop Clear;
16991 @end cartouche
16992 @end smallexample
16993 @end ifnottex
16994
16995 @noindent
16996 A further difference between GNAT style layout and compact layout is that
16997 GNAT style layout inserts empty lines as separation for
16998 compound statements, return statements and bodies.
16999
17000 Note that the layout specified by
17001 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
17002 for named block and loop statements overrides the layout defined by these
17003 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
17004 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
17005 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
17006
17007 @node Name Casing
17008 @subsection Name Casing
17009
17010 @noindent
17011 @command{gnatpp} always converts the usage occurrence of a (simple) name to
17012 the same casing as the corresponding defining identifier.
17013
17014 You control the casing for defining occurrences via the
17015 @option{^-n^/NAME_CASING^} switch.
17016 @ifclear vms
17017 With @option{-nD} (``as declared'', which is the default),
17018 @end ifclear
17019 @ifset vms
17020 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
17021 @end ifset
17022 defining occurrences appear exactly as in the source file
17023 where they are declared.
17024 The other ^values for this switch^options for this qualifier^ ---
17025 @option{^-nU^UPPER_CASE^},
17026 @option{^-nL^LOWER_CASE^},
17027 @option{^-nM^MIXED_CASE^} ---
17028 result in
17029 ^upper, lower, or mixed case, respectively^the corresponding casing^.
17030 If @command{gnatpp} changes the casing of a defining
17031 occurrence, it analogously changes the casing of all the
17032 usage occurrences of this name.
17033
17034 If the defining occurrence of a name is not in the source compilation unit
17035 currently being processed by @command{gnatpp}, the casing of each reference to
17036 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
17037 switch (subject to the dictionary file mechanism described below).
17038 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
17039 had affected the
17040 casing for the defining occurrence of the name.
17041
17042 Some names may need to be spelled with casing conventions that are not
17043 covered by the upper-, lower-, and mixed-case transformations.
17044 You can arrange correct casing by placing such names in a
17045 @emph{dictionary file},
17046 and then supplying a @option{^-D^/DICTIONARY^} switch.
17047 The casing of names from dictionary files overrides
17048 any @option{^-n^/NAME_CASING^} switch.
17049
17050 To handle the casing of Ada predefined names and the names from GNAT libraries,
17051 @command{gnatpp} assumes a default dictionary file.
17052 The name of each predefined entity is spelled with the same casing as is used
17053 for the entity in the @cite{Ada Reference Manual}.
17054 The name of each entity in the GNAT libraries is spelled with the same casing
17055 as is used in the declaration of that entity.
17056
17057 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
17058 default dictionary file.
17059 Instead, the casing for predefined and GNAT-defined names will be established
17060 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
17061 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
17062 will appear as just shown,
17063 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
17064 To ensure that even such names are rendered in uppercase,
17065 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
17066 (or else, less conveniently, place these names in upper case in a dictionary
17067 file).
17068
17069 A dictionary file is
17070 a plain text file; each line in this file can be either a blank line
17071 (containing only space characters and ASCII.HT characters), an Ada comment
17072 line, or the specification of exactly one @emph{casing schema}.
17073
17074 A casing schema is a string that has the following syntax:
17075
17076 @smallexample
17077 @cartouche
17078   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
17079
17080   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
17081 @end cartouche
17082 @end smallexample
17083
17084 @noindent
17085 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
17086 @var{identifier} lexical element and the @var{letter_or_digit} category.)
17087
17088 The casing schema string can be followed by white space and/or an Ada-style
17089 comment; any amount of white space is allowed before the string.
17090
17091 If a dictionary file is passed as
17092 @ifclear vms
17093 the value of a @option{-D@var{file}} switch
17094 @end ifclear
17095 @ifset vms
17096 an option to the @option{/DICTIONARY} qualifier
17097 @end ifset
17098 then for every
17099 simple name and every identifier, @command{gnatpp} checks if the dictionary
17100 defines the casing for the name or for some of its parts (the term ``subword''
17101 is used below to denote the part of a name which is delimited by ``_'' or by
17102 the beginning or end of the word and which does not contain any ``_'' inside):
17103
17104 @itemize @bullet
17105 @item
17106 if the whole name is in the dictionary, @command{gnatpp} uses for this name
17107 the casing defined by the dictionary; no subwords are checked for this word
17108
17109 @item
17110 for every subword @command{gnatpp} checks if the dictionary contains the
17111 corresponding string of the form @code{*@var{simple_identifier}*},
17112 and if it does, the casing of this @var{simple_identifier} is used
17113 for this subword
17114
17115 @item
17116 if the whole name does not contain any ``_'' inside, and if for this name
17117 the dictionary contains two entries - one of the form @var{identifier},
17118 and another - of the form *@var{simple_identifier}*, then the first one
17119 is applied to define the casing of this name
17120
17121 @item
17122 if more than one dictionary file is passed as @command{gnatpp} switches, each
17123 dictionary adds new casing exceptions and overrides all the existing casing
17124 exceptions set by the previous dictionaries
17125
17126 @item
17127 when @command{gnatpp} checks if the word or subword is in the dictionary,
17128 this check is not case sensitive
17129 @end itemize
17130
17131 @noindent
17132 For example, suppose we have the following source to reformat:
17133
17134 @smallexample @c ada
17135 @cartouche
17136 procedure test is
17137    name1 : integer := 1;
17138    name4_name3_name2 : integer := 2;
17139    name2_name3_name4 : Boolean;
17140    name1_var : Float;
17141 begin
17142    name2_name3_name4 := name4_name3_name2 > name1;
17143 end;
17144 @end cartouche
17145 @end smallexample
17146
17147 @noindent
17148 And suppose we have two dictionaries:
17149
17150 @smallexample
17151 @cartouche
17152 @i{dict1:}
17153    NAME1
17154    *NaMe3*
17155    *Name1*
17156 @end cartouche
17157
17158 @cartouche
17159 @i{dict2:}
17160   *NAME3*
17161 @end cartouche
17162 @end smallexample
17163
17164 @noindent
17165 If @command{gnatpp} is called with the following switches:
17166
17167 @smallexample
17168 @ifclear vms
17169 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
17170 @end ifclear
17171 @ifset vms
17172 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
17173 @end ifset
17174 @end smallexample
17175
17176 @noindent
17177 then we will get the following name casing in the @command{gnatpp} output:
17178
17179 @smallexample @c ada
17180 @cartouche
17181 procedure Test is
17182    NAME1             : Integer := 1;
17183    Name4_NAME3_Name2 : Integer := 2;
17184    Name2_NAME3_Name4 : Boolean;
17185    Name1_Var         : Float;
17186 begin
17187    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
17188 end Test;
17189 @end cartouche
17190 @end smallexample
17191
17192 @c *********************************
17193 @node The GNAT Metric Tool gnatmetric
17194 @chapter The GNAT Metric Tool @command{gnatmetric}
17195 @findex gnatmetric
17196 @cindex Metric tool
17197
17198 @noindent
17199 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
17200 for computing various program metrics.
17201 It takes an Ada source file as input and generates a file containing the
17202 metrics data as output. Various switches control which
17203 metrics are computed and output.
17204
17205 @command{gnatmetric} generates and uses the ASIS
17206 tree for the input source and thus requires the input to be syntactically and
17207 semantically legal.
17208 If this condition is not met, @command{gnatmetric} will generate
17209 an error message; no metric information for this file will be
17210 computed and reported.
17211
17212 If the compilation unit contained in the input source depends semantically
17213 upon units in files located outside the current directory, you have to provide
17214 the source search path when invoking @command{gnatmetric}.
17215 If it depends semantically upon units that are contained
17216 in files with names that do not follow the GNAT file naming rules, you have to
17217 provide the configuration file describing the corresponding naming scheme (see
17218 the description of the @command{gnatmetric} switches below.)
17219 Alternatively, you may use a project file and invoke @command{gnatmetric}
17220 through the @command{gnat} driver.
17221
17222 The @command{gnatmetric} command has the form
17223
17224 @smallexample
17225 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
17226 @c Expanding @ovar macro inline (explanation in macro def comments)
17227 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
17228 @end smallexample
17229
17230 @noindent
17231 where
17232 @itemize @bullet
17233 @item
17234 @var{switches} specify the metrics to compute and define the destination for
17235 the output
17236
17237 @item
17238 Each @var{filename} is the name (including the extension) of a source
17239 file to process. ``Wildcards'' are allowed, and
17240 the file name may contain path information.
17241 If no @var{filename} is supplied, then the @var{switches} list must contain
17242 at least one
17243 @option{-files} switch (@pxref{Other gnatmetric Switches}).
17244 Including both a @option{-files} switch and one or more
17245 @var{filename} arguments is permitted.
17246
17247 @item
17248 @samp{@var{gcc_switches}} is a list of switches for
17249 @command{gcc}. They will be passed on to all compiler invocations made by
17250 @command{gnatmetric} to generate the ASIS trees. Here you can provide
17251 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17252 and use the @option{-gnatec} switch to set the configuration file.
17253 @end itemize
17254
17255 @menu
17256 * Switches for gnatmetric::
17257 @end menu
17258
17259 @node Switches for gnatmetric
17260 @section Switches for @command{gnatmetric}
17261
17262 @noindent
17263 The following subsections describe the various switches accepted by
17264 @command{gnatmetric}, organized by category.
17265
17266 @menu
17267 * Output Files Control::
17268 * Disable Metrics For Local Units::
17269 * Specifying a set of metrics to compute::
17270 * Other gnatmetric Switches::
17271 * Generate project-wide metrics::
17272 @end menu
17273
17274 @node Output Files Control
17275 @subsection Output File Control
17276 @cindex Output file control in @command{gnatmetric}
17277
17278 @noindent
17279 @command{gnatmetric} has two output formats. It can generate a
17280 textual (human-readable) form, and also XML. By default only textual
17281 output is generated.
17282
17283 When generating the output in textual form, @command{gnatmetric} creates
17284 for each Ada source file a corresponding text file
17285 containing the computed metrics, except for the case when the set of metrics
17286 specified by gnatmetric parameters consists only of metrics that are computed
17287 for the whole set of analyzed sources, but not for each Ada source.
17288 By default, this file is placed in the same directory as where the source
17289 file is located, and its name is obtained
17290 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
17291 input file.
17292
17293 All the output information generated in XML format is placed in a single
17294 file. By default this file is placed in the current directory and has the
17295 name ^@file{metrix.xml}^@file{METRIX$XML}^.
17296
17297 Some of the computed metrics are summed over the units passed to
17298 @command{gnatmetric}; for example, the total number of lines of code.
17299 By default this information is sent to @file{stdout}, but a file
17300 can be specified with the @option{-og} switch.
17301
17302 The following switches control the @command{gnatmetric} output:
17303
17304 @table @option
17305 @cindex @option{^-x^/XML^} (@command{gnatmetric})
17306 @item ^-x^/XML^
17307 Generate the XML output
17308
17309 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
17310 @item ^-xs^/XSD^
17311 Generate the XML output and the XML schema file that describes the structure
17312 of the XML metric report, this schema is assigned to the XML file. The schema
17313 file has the same name as the XML output file with @file{.xml} suffix replaced
17314 with @file{.xsd}
17315
17316 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
17317 @item ^-nt^/NO_TEXT^
17318 Do not generate the output in text form (implies @option{^-x^/XML^})
17319
17320 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
17321 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
17322 Put text files with detailed metrics into @var{output_dir}
17323
17324 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
17325 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
17326 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
17327 in the name of the output file.
17328
17329 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
17330 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
17331 Put global metrics into @var{file_name}
17332
17333 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
17334 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
17335 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
17336
17337 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
17338 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
17339 Use ``short'' source file names in the output.  (The @command{gnatmetric}
17340 output includes the name(s) of the Ada source file(s) from which the metrics
17341 are computed.  By default each name includes the absolute path. The
17342 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
17343 to exclude all directory information from the file names that are output.)
17344
17345 @end table
17346
17347 @node Disable Metrics For Local Units
17348 @subsection Disable Metrics For Local Units
17349 @cindex Disable Metrics For Local Units in @command{gnatmetric}
17350
17351 @noindent
17352 @command{gnatmetric} relies on the GNAT compilation model @minus{}
17353 one compilation
17354 unit per one source file. It computes line metrics for the whole source
17355 file, and it also computes syntax
17356 and complexity metrics for the file's outermost unit.
17357
17358 By default, @command{gnatmetric} will also compute all metrics for certain
17359 kinds of locally declared program units:
17360
17361 @itemize @bullet
17362 @item
17363 subprogram (and generic subprogram) bodies;
17364
17365 @item
17366 package (and generic package) specs and bodies;
17367
17368 @item
17369 task object and type specifications and bodies;
17370
17371 @item
17372 protected object and type specifications and bodies.
17373 @end itemize
17374
17375 @noindent
17376 These kinds of entities will be referred to as
17377 @emph{eligible local program units}, or simply @emph{eligible local units},
17378 @cindex Eligible local unit (for @command{gnatmetric})
17379 in the discussion below.
17380
17381 Note that a subprogram declaration, generic instantiation,
17382 or renaming declaration only receives metrics
17383 computation when it appear as the outermost entity
17384 in a source file.
17385
17386 Suppression of metrics computation for eligible local units can be
17387 obtained via the following switch:
17388
17389 @table @option
17390 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
17391 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
17392 Do not compute detailed metrics for eligible local program units
17393
17394 @end table
17395
17396 @node Specifying a set of metrics to compute
17397 @subsection Specifying a set of metrics to compute
17398
17399 @noindent
17400 By default all the metrics are computed and reported. The switches
17401 described in this subsection allow you to control, on an individual
17402 basis, whether metrics are computed and
17403 reported. If at least one positive metric
17404 switch is specified (that is, a switch that defines that a given
17405 metric or set of metrics is to be computed), then only
17406 explicitly specified metrics are reported.
17407
17408 @menu
17409 * Line Metrics Control::
17410 * Syntax Metrics Control::
17411 * Complexity Metrics Control::
17412 * Object-Oriented Metrics Control::
17413 @end menu
17414
17415 @node Line Metrics Control
17416 @subsubsection Line Metrics Control
17417 @cindex Line metrics control in @command{gnatmetric}
17418
17419 @noindent
17420 For any (legal) source file, and for each of its
17421 eligible local program units, @command{gnatmetric} computes the following
17422 metrics:
17423
17424 @itemize @bullet
17425 @item
17426 the total number of lines;
17427
17428 @item
17429 the total number of code lines (i.e., non-blank lines that are not comments)
17430
17431 @item
17432 the number of comment lines
17433
17434 @item
17435 the number of code lines containing end-of-line comments;
17436
17437 @item
17438 the comment percentage: the ratio between the number of lines that contain
17439 comments and the number of all non-blank lines, expressed as a percentage;
17440
17441 @item
17442 the number of empty lines and lines containing only space characters and/or
17443 format effectors (blank lines)
17444
17445 @item
17446 the average number of code lines in subprogram bodies, task bodies, entry
17447 bodies and statement sequences in package bodies (this metric is only computed
17448 across the whole set of the analyzed units)
17449
17450 @end itemize
17451
17452 @noindent
17453 @command{gnatmetric} sums the values of the line metrics for all the
17454 files being processed and then generates the cumulative results. The tool
17455 also computes for all the files being processed the average number of code
17456 lines in bodies.
17457
17458 You can use the following switches to select the specific line metrics
17459 to be computed and reported.
17460
17461 @table @option
17462 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
17463
17464 @ifclear vms
17465 @cindex @option{--no-lines@var{x}}
17466 @end ifclear
17467
17468 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
17469 Report all the line metrics
17470
17471 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
17472 Do not report any of line metrics
17473
17474 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
17475 Report the number of all lines
17476
17477 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
17478 Do not report the number of all lines
17479
17480 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
17481 Report the number of code lines
17482
17483 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
17484 Do not report the number of code lines
17485
17486 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
17487 Report the number of comment lines
17488
17489 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
17490 Do not report the number of comment lines
17491
17492 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
17493 Report the number of code lines containing
17494 end-of-line comments
17495
17496 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
17497 Do not report the number of code lines containing
17498 end-of-line comments
17499
17500 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
17501 Report the comment percentage in the program text
17502
17503 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
17504 Do not report the comment percentage in the program text
17505
17506 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
17507 Report the number of blank lines
17508
17509 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
17510 Do not report the number of blank lines
17511
17512 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
17513 Report the average number of code lines in subprogram bodies, task bodies,
17514 entry bodies and statement sequences in package bodies. The metric is computed
17515 and reported for the whole set of processed Ada sources only.
17516
17517 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
17518 Do not report the average number of code lines in subprogram bodies,
17519 task bodies, entry bodies and statement sequences in package bodies.
17520
17521 @end table
17522
17523 @node Syntax Metrics Control
17524 @subsubsection Syntax Metrics Control
17525 @cindex Syntax metrics control in @command{gnatmetric}
17526
17527 @noindent
17528 @command{gnatmetric} computes various syntactic metrics for the
17529 outermost unit and for each eligible local unit:
17530
17531 @table @emph
17532 @item LSLOC (``Logical Source Lines Of Code'')
17533 The total number of declarations and the total number of statements
17534
17535 @item Maximal static nesting level of inner program units
17536 According to
17537 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
17538 package, a task unit, a protected unit, a
17539 protected entry, a generic unit, or an explicitly declared subprogram other
17540 than an enumeration literal.''
17541
17542 @item Maximal nesting level of composite syntactic constructs
17543 This corresponds to the notion of the
17544 maximum nesting level in the GNAT built-in style checks
17545 (@pxref{Style Checking})
17546 @end table
17547
17548 @noindent
17549 For the outermost unit in the file, @command{gnatmetric} additionally computes
17550 the following metrics:
17551
17552 @table @emph
17553 @item Public subprograms
17554 This metric is computed for package specs. It is the
17555 number of subprograms and generic subprograms declared in the visible
17556 part (including the visible part of nested packages, protected objects, and
17557 protected types).
17558
17559 @item All subprograms
17560 This metric is computed for bodies and subunits. The
17561 metric is equal to a total number of subprogram bodies in the compilation
17562 unit.
17563 Neither generic instantiations nor renamings-as-a-body nor body stubs
17564 are counted. Any subprogram body is counted, independently of its nesting
17565 level and enclosing constructs. Generic bodies and bodies of protected
17566 subprograms are counted in the same way as ``usual'' subprogram bodies.
17567
17568 @item Public types
17569 This metric is computed for package specs and
17570 generic package declarations. It is the total number of types
17571 that can be referenced from outside this compilation unit, plus the
17572 number of types from all the visible parts of all the visible generic
17573 packages. Generic formal types are not counted.  Only types, not subtypes,
17574 are included.
17575
17576 @noindent
17577 Along with the total number of public types, the following
17578 types are counted and reported separately:
17579
17580 @itemize @bullet
17581 @item
17582 Abstract types
17583
17584 @item
17585 Root tagged types (abstract, non-abstract, private, non-private). Type
17586 extensions are @emph{not} counted
17587
17588 @item
17589 Private types (including private extensions)
17590
17591 @item
17592 Task types
17593
17594 @item
17595 Protected types
17596
17597 @end itemize
17598
17599 @item All types
17600 This metric is computed for any compilation unit. It is equal to the total
17601 number of the declarations of different types given in the compilation unit.
17602 The private and the corresponding full type declaration are counted as one
17603 type declaration. Incomplete type declarations and generic formal types
17604 are not counted.
17605 No distinction is made among different kinds of types (abstract,
17606 private etc.); the total number of types is computed and reported.
17607
17608 @end table
17609
17610 @noindent
17611 By default, all the syntax metrics are computed and reported. You can use the
17612 following switches to select specific syntax metrics.
17613
17614 @table @option
17615
17616 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
17617
17618 @ifclear vms
17619 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
17620 @end ifclear
17621
17622 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
17623 Report all the syntax metrics
17624
17625 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
17626 Do not report any of syntax metrics
17627
17628 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
17629 Report the total number of declarations
17630
17631 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
17632 Do not report the total number of declarations
17633
17634 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
17635 Report the total number of statements
17636
17637 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
17638 Do not report the total number of statements
17639
17640 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
17641 Report the number of public subprograms in a compilation unit
17642
17643 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
17644 Do not report the number of public subprograms in a compilation unit
17645
17646 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
17647 Report the number of all the subprograms in a compilation unit
17648
17649 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
17650 Do not report the number of all the subprograms in a compilation unit
17651
17652 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
17653 Report the number of public types in a compilation unit
17654
17655 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
17656 Do not report the number of public types in a compilation unit
17657
17658 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
17659 Report the number of all the types in a compilation unit
17660
17661 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
17662 Do not report the number of all the types in a compilation unit
17663
17664 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
17665 Report the maximal program unit nesting level
17666
17667 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
17668 Do not report the maximal program unit nesting level
17669
17670 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
17671 Report the maximal construct nesting level
17672
17673 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
17674 Do not report the maximal construct nesting level
17675
17676 @end table
17677
17678 @node Complexity Metrics Control
17679 @subsubsection Complexity Metrics Control
17680 @cindex Complexity metrics control in @command{gnatmetric}
17681
17682 @noindent
17683 For a program unit that is an executable body (a subprogram body (including
17684 generic bodies), task body, entry body or a package body containing
17685 its own statement sequence) @command{gnatmetric} computes the following
17686 complexity metrics:
17687
17688 @itemize @bullet
17689 @item
17690 McCabe cyclomatic complexity;
17691
17692 @item
17693 McCabe essential complexity;
17694
17695 @item
17696 maximal loop nesting level
17697
17698 @end itemize
17699
17700 @noindent
17701 The McCabe complexity metrics are defined
17702 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
17703
17704 According to McCabe, both control statements and short-circuit control forms
17705 should be taken into account when computing cyclomatic complexity. For each
17706 body, we compute three metric values:
17707
17708 @itemize @bullet
17709 @item
17710 the complexity introduced by control
17711 statements only, without taking into account short-circuit forms,
17712
17713 @item
17714 the complexity introduced by short-circuit control forms only, and
17715
17716 @item
17717 the total
17718 cyclomatic complexity, which is the sum of these two values.
17719 @end itemize
17720
17721 @noindent
17722 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
17723 the code in the exception handlers and in all the nested program units.
17724
17725 By default, all the complexity metrics are computed and reported.
17726 For more fine-grained control you can use
17727 the following switches:
17728
17729 @table @option
17730 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
17731
17732 @ifclear vms
17733 @cindex @option{--no-complexity@var{x}}
17734 @end ifclear
17735
17736 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
17737 Report all the complexity metrics
17738
17739 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
17740 Do not report any of complexity metrics
17741
17742 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
17743 Report the McCabe Cyclomatic Complexity
17744
17745 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
17746 Do not report the McCabe Cyclomatic Complexity
17747
17748 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
17749 Report the Essential Complexity
17750
17751 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
17752 Do not report the Essential Complexity
17753
17754 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
17755 Report maximal loop nesting level
17756
17757 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
17758 Do not report maximal loop nesting level
17759
17760 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
17761 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
17762 task bodies, entry bodies and statement sequences in package bodies.
17763 The metric is computed and reported for whole set of processed Ada sources
17764 only.
17765
17766 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
17767 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
17768 bodies, task bodies, entry bodies and statement sequences in package bodies
17769
17770 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
17771 @item ^-ne^/NO_EXITS_AS_GOTOS^
17772 Do not consider @code{exit} statements as @code{goto}s when
17773 computing Essential Complexity
17774
17775 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
17776 Report the extra exit points for subprogram bodies. As an exit point, this
17777 metric counts @code{return} statements and raise statements in case when the
17778 raised exception is not handled in the same body. In case of a function this
17779 metric subtracts 1 from the number of exit points, because a function body
17780 must contain at least one @code{return} statement.
17781
17782 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
17783 Do not report the extra exit points for subprogram bodies
17784 @end table
17785
17786
17787 @node Object-Oriented Metrics Control
17788 @subsubsection Object-Oriented Metrics Control
17789 @cindex Object-Oriented metrics control in @command{gnatmetric}
17790
17791 @noindent
17792 @cindex Coupling metrics (in in @command{gnatmetric})
17793 Coupling metrics are object-oriented metrics that measure the
17794 dependencies between a given class (or a group of classes) and the
17795 ``external world'' (that is, the other classes in the program). In this
17796 subsection the term ``class'' is used in its
17797 traditional object-oriented programming sense
17798 (an instantiable module that contains data and/or method members).
17799 A @emph{category} (of classes)
17800 is a group of closely related classes that are reused and/or
17801 modified together.
17802
17803 A class @code{K}'s @emph{efferent coupling} is the number of classes
17804 that @code{K} depends upon.
17805 A category's efferent coupling is the number of classes outside the
17806 category that the classes inside the category depend upon.
17807
17808 A class @code{K}'s @emph{afferent coupling} is the number of classes
17809 that depend upon @code{K}.
17810 A category's afferent coupling is the number of classes outside the
17811 category that depend on classes belonging to the category.
17812
17813 Ada's implementation of the object-oriented paradigm does not use the
17814 traditional class notion, so the definition of the coupling
17815 metrics for Ada maps the class and class category notions
17816 onto Ada constructs.
17817
17818 For the coupling metrics, several kinds of modules -- a library package,
17819 a library generic package, and a library generic package instantiation --
17820 that define a tagged type or an interface type are
17821 considered to be a class. A category consists of a library package (or
17822 a library generic package) that defines a tagged or an interface type,
17823 together with all its descendant (generic) packages that define tagged
17824 or interface types. For any package counted as a class,
17825 its body and subunits (if any) are considered
17826 together with its spec when counting the dependencies, and coupling
17827 metrics are reported for spec units only. For dependencies
17828 between classes, the Ada semantic dependencies are considered.
17829 For coupling metrics, only dependencies on units that are considered as
17830 classes, are considered.
17831
17832 When computing coupling metrics, @command{gnatmetric} counts only
17833 dependencies between units that are arguments of the gnatmetric call.
17834 Coupling metrics are program-wide (or project-wide) metrics, so to
17835 get a valid result, you should call @command{gnatmetric} for
17836 the whole set of sources that make up your program. It can be done
17837 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
17838 option (see See @ref{The GNAT Driver and Project Files} for details.
17839
17840 By default, all the coupling metrics are disabled. You can use the following
17841 switches to specify the coupling metrics to be computed and reported:
17842
17843 @table @option
17844
17845 @ifclear vms
17846 @cindex @option{--package@var{x}} (@command{gnatmetric})
17847 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
17848 @cindex @option{--category@var{x}} (@command{gnatmetric})
17849 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
17850 @end ifclear
17851
17852 @ifset vms
17853 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
17854 @end ifset
17855
17856 @item ^--coupling-all^/COUPLING_METRICS=ALL^
17857 Report all the coupling metrics
17858
17859 @item ^--no-coupling-all^/COUPLING_METRICS=NONE^
17860 Do not report any of  metrics
17861
17862 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT^
17863 Report package efferent coupling
17864
17865 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=NOPACKAGE_EFFERENT^
17866 Do not report package efferent coupling
17867
17868 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT^
17869 Report package afferent coupling
17870
17871 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=NOPACKAGE_AFFERENT^
17872 Do not report package afferent coupling
17873
17874 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT^
17875 Report category efferent coupling
17876
17877 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=NOCATEGORY_EFFERENT^
17878 Do not report category efferent coupling
17879
17880 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT^
17881 Report category afferent coupling
17882
17883 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=NOCATEGORY_AFFERENT^
17884 Do not report category afferent coupling
17885
17886 @end table
17887
17888 @node Other gnatmetric Switches
17889 @subsection Other @code{gnatmetric} Switches
17890
17891 @noindent
17892 Additional @command{gnatmetric} switches are as follows:
17893
17894 @table @option
17895 @item ^-files @var{filename}^/FILES=@var{filename}^
17896 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
17897 Take the argument source files from the specified file. This file should be an
17898 ordinary text file containing file names separated by spaces or
17899 line breaks. You can use this switch more than once in the same call to
17900 @command{gnatmetric}. You also can combine this switch with
17901 an explicit list of files.
17902
17903 @item ^-v^/VERBOSE^
17904 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
17905 Verbose mode;
17906 @command{gnatmetric} generates version information and then
17907 a trace of sources being processed.
17908
17909 @item ^-dv^/DEBUG_OUTPUT^
17910 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
17911 Debug mode;
17912 @command{gnatmetric} generates various messages useful to understand what
17913 happens during the metrics computation
17914
17915 @item ^-q^/QUIET^
17916 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
17917 Quiet mode.
17918 @end table
17919
17920 @node Generate project-wide metrics
17921 @subsection Generate project-wide metrics
17922
17923 In order to compute metrics on all units of a given project, you can use
17924 the @command{gnat} driver along with the @option{-P} option:
17925 @smallexample
17926    gnat metric -Pproj
17927 @end smallexample
17928
17929 @noindent
17930 If the project @code{proj} depends upon other projects, you can compute
17931 the metrics on the project closure using the @option{-U} option:
17932 @smallexample
17933    gnat metric -Pproj -U
17934 @end smallexample
17935
17936 @noindent
17937 Finally, if not all the units are relevant to a particular main
17938 program in the project closure, you can generate metrics for the set
17939 of units needed to create a given main program (unit closure) using
17940 the @option{-U} option followed by the name of the main unit:
17941 @smallexample
17942    gnat metric -Pproj -U main
17943 @end smallexample
17944
17945
17946 @c ***********************************
17947 @node File Name Krunching Using gnatkr
17948 @chapter File Name Krunching Using @code{gnatkr}
17949 @findex gnatkr
17950
17951 @noindent
17952 This chapter discusses the method used by the compiler to shorten
17953 the default file names chosen for Ada units so that they do not
17954 exceed the maximum length permitted. It also describes the
17955 @code{gnatkr} utility that can be used to determine the result of
17956 applying this shortening.
17957 @menu
17958 * About gnatkr::
17959 * Using gnatkr::
17960 * Krunching Method::
17961 * Examples of gnatkr Usage::
17962 @end menu
17963
17964 @node About gnatkr
17965 @section About @code{gnatkr}
17966
17967 @noindent
17968 The default file naming rule in GNAT
17969 is that the file name must be derived from
17970 the unit name. The exact default rule is as follows:
17971 @itemize @bullet
17972 @item
17973 Take the unit name and replace all dots by hyphens.
17974 @item
17975 If such a replacement occurs in the
17976 second character position of a name, and the first character is
17977 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
17978 then replace the dot by the character
17979 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
17980 instead of a minus.
17981 @end itemize
17982 The reason for this exception is to avoid clashes
17983 with the standard names for children of System, Ada, Interfaces,
17984 and GNAT, which use the prefixes
17985 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
17986 respectively.
17987
17988 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
17989 switch of the compiler activates a ``krunching''
17990 circuit that limits file names to nn characters (where nn is a decimal
17991 integer). For example, using OpenVMS,
17992 where the maximum file name length is
17993 39, the value of nn is usually set to 39, but if you want to generate
17994 a set of files that would be usable if ported to a system with some
17995 different maximum file length, then a different value can be specified.
17996 The default value of 39 for OpenVMS need not be specified.
17997
17998 The @code{gnatkr} utility can be used to determine the krunched name for
17999 a given file, when krunched to a specified maximum length.
18000
18001 @node Using gnatkr
18002 @section Using @code{gnatkr}
18003
18004 @noindent
18005 The @code{gnatkr} command has the form
18006
18007 @ifclear vms
18008 @smallexample
18009 @c $ gnatkr @var{name} @ovar{length}
18010 @c Expanding @ovar macro inline (explanation in macro def comments)
18011 $ gnatkr @var{name} @r{[}@var{length}@r{]}
18012 @end smallexample
18013 @end ifclear
18014
18015 @ifset vms
18016 @smallexample
18017 $ gnatkr @var{name} /COUNT=nn
18018 @end smallexample
18019 @end ifset
18020
18021 @noindent
18022 @var{name} is the uncrunched file name, derived from the name of the unit
18023 in the standard manner described in the previous section (i.e., in particular
18024 all dots are replaced by hyphens). The file name may or may not have an
18025 extension (defined as a suffix of the form period followed by arbitrary
18026 characters other than period). If an extension is present then it will
18027 be preserved in the output. For example, when krunching @file{hellofile.ads}
18028 to eight characters, the result will be hellofil.ads.
18029
18030 Note: for compatibility with previous versions of @code{gnatkr} dots may
18031 appear in the name instead of hyphens, but the last dot will always be
18032 taken as the start of an extension. So if @code{gnatkr} is given an argument
18033 such as @file{Hello.World.adb} it will be treated exactly as if the first
18034 period had been a hyphen, and for example krunching to eight characters
18035 gives the result @file{hellworl.adb}.
18036
18037 Note that the result is always all lower case (except on OpenVMS where it is
18038 all upper case). Characters of the other case are folded as required.
18039
18040 @var{length} represents the length of the krunched name. The default
18041 when no argument is given is ^8^39^ characters. A length of zero stands for
18042 unlimited, in other words do not chop except for system files where the
18043 implied crunching length is always eight characters.
18044
18045 @noindent
18046 The output is the krunched name. The output has an extension only if the
18047 original argument was a file name with an extension.
18048
18049 @node Krunching Method
18050 @section Krunching Method
18051
18052 @noindent
18053 The initial file name is determined by the name of the unit that the file
18054 contains. The name is formed by taking the full expanded name of the
18055 unit and replacing the separating dots with hyphens and
18056 using ^lowercase^uppercase^
18057 for all letters, except that a hyphen in the second character position is
18058 replaced by a ^tilde^dollar sign^ if the first character is
18059 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
18060 The extension is @code{.ads} for a
18061 spec and @code{.adb} for a body.
18062 Krunching does not affect the extension, but the file name is shortened to
18063 the specified length by following these rules:
18064
18065 @itemize @bullet
18066 @item
18067 The name is divided into segments separated by hyphens, tildes or
18068 underscores and all hyphens, tildes, and underscores are
18069 eliminated. If this leaves the name short enough, we are done.
18070
18071 @item
18072 If the name is too long, the longest segment is located (left-most
18073 if there are two of equal length), and shortened by dropping
18074 its last character. This is repeated until the name is short enough.
18075
18076 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
18077 to fit the name into 8 characters as required by some operating systems.
18078
18079 @smallexample
18080 our-strings-wide_fixed 22
18081 our strings wide fixed 19
18082 our string  wide fixed 18
18083 our strin   wide fixed 17
18084 our stri    wide fixed 16
18085 our stri    wide fixe  15
18086 our str     wide fixe  14
18087 our str     wid  fixe  13
18088 our str     wid  fix   12
18089 ou  str     wid  fix   11
18090 ou  st      wid  fix   10
18091 ou  st      wi   fix   9
18092 ou  st      wi   fi    8
18093 Final file name: oustwifi.adb
18094 @end smallexample
18095
18096 @item
18097 The file names for all predefined units are always krunched to eight
18098 characters. The krunching of these predefined units uses the following
18099 special prefix replacements:
18100
18101 @table @file
18102 @item ada-
18103 replaced by @file{^a^A^-}
18104
18105 @item gnat-
18106 replaced by @file{^g^G^-}
18107
18108 @item interfaces-
18109 replaced by @file{^i^I^-}
18110
18111 @item system-
18112 replaced by @file{^s^S^-}
18113 @end table
18114
18115 These system files have a hyphen in the second character position. That
18116 is why normal user files replace such a character with a
18117 ^tilde^dollar sign^, to
18118 avoid confusion with system file names.
18119
18120 As an example of this special rule, consider
18121 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
18122
18123 @smallexample
18124 ada-strings-wide_fixed 22
18125 a-  strings wide fixed 18
18126 a-  string  wide fixed 17
18127 a-  strin   wide fixed 16
18128 a-  stri    wide fixed 15
18129 a-  stri    wide fixe  14
18130 a-  str     wide fixe  13
18131 a-  str     wid  fixe  12
18132 a-  str     wid  fix   11
18133 a-  st      wid  fix   10
18134 a-  st      wi   fix   9
18135 a-  st      wi   fi    8
18136 Final file name: a-stwifi.adb
18137 @end smallexample
18138 @end itemize
18139
18140 Of course no file shortening algorithm can guarantee uniqueness over all
18141 possible unit names, and if file name krunching is used then it is your
18142 responsibility to ensure that no name clashes occur. The utility
18143 program @code{gnatkr} is supplied for conveniently determining the
18144 krunched name of a file.
18145
18146 @node Examples of gnatkr Usage
18147 @section Examples of @code{gnatkr} Usage
18148
18149 @smallexample
18150 @iftex
18151 @leftskip=0cm
18152 @end iftex
18153 @ifclear vms
18154 $ gnatkr very_long_unit_name.ads      --> velounna.ads
18155 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
18156 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
18157 $ gnatkr grandparent-parent-child     --> grparchi
18158 @end ifclear
18159 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
18160 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
18161 @end smallexample
18162
18163 @node Preprocessing Using gnatprep
18164 @chapter Preprocessing Using @code{gnatprep}
18165 @findex gnatprep
18166
18167 @noindent
18168 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
18169 preprocessing.
18170 Although designed for use with GNAT, @code{gnatprep} does not depend on any
18171 special GNAT features.
18172 For further discussion of conditional compilation in general, see
18173 @ref{Conditional Compilation}.
18174
18175 @menu
18176 * Preprocessing Symbols::
18177 * Using gnatprep::
18178 * Switches for gnatprep::
18179 * Form of Definitions File::
18180 * Form of Input Text for gnatprep::
18181 @end menu
18182
18183 @node Preprocessing Symbols
18184 @section Preprocessing Symbols
18185
18186 @noindent
18187 Preprocessing symbols are defined in definition files and referred to in
18188 sources to be preprocessed. A Preprocessing symbol is an identifier, following
18189 normal Ada (case-insensitive) rules for its syntax, with the restriction that
18190 all characters need to be in the ASCII set (no accented letters).
18191
18192 @node Using gnatprep
18193 @section Using @code{gnatprep}
18194
18195 @noindent
18196 To call @code{gnatprep} use
18197
18198 @smallexample
18199 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
18200 @c Expanding @ovar macro inline (explanation in macro def comments)
18201 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
18202 @end smallexample
18203
18204 @noindent
18205 where
18206 @table @var
18207 @item switches
18208 is an optional sequence of switches as described in the next section.
18209
18210 @item infile
18211 is the full name of the input file, which is an Ada source
18212 file containing preprocessor directives.
18213
18214 @item outfile
18215 is the full name of the output file, which is an Ada source
18216 in standard Ada form. When used with GNAT, this file name will
18217 normally have an ads or adb suffix.
18218
18219 @item deffile
18220 is the full name of a text file containing definitions of
18221 preprocessing symbols to be referenced by the preprocessor. This argument is
18222 optional, and can be replaced by the use of the @option{-D} switch.
18223
18224 @end table
18225
18226 @node Switches for gnatprep
18227 @section Switches for @code{gnatprep}
18228
18229 @table @option
18230 @c !sort!
18231
18232 @item ^-b^/BLANK_LINES^
18233 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
18234 Causes both preprocessor lines and the lines deleted by
18235 preprocessing to be replaced by blank lines in the output source file,
18236 preserving line numbers in the output file.
18237
18238 @item ^-c^/COMMENTS^
18239 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
18240 Causes both preprocessor lines and the lines deleted
18241 by preprocessing to be retained in the output source as comments marked
18242 with the special string @code{"--! "}. This option will result in line numbers
18243 being preserved in the output file.
18244
18245 @item ^-C^/REPLACE_IN_COMMENTS^
18246 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
18247 Causes comments to be scanned. Normally comments are ignored by gnatprep.
18248 If this option is specified, then comments are scanned and any $symbol
18249 substitutions performed as in program text. This is particularly useful
18250 when structured comments are used (e.g., when writing programs in the
18251 SPARK dialect of Ada). Note that this switch is not available when
18252 doing integrated preprocessing (it would be useless in this context
18253 since comments are ignored by the compiler in any case).
18254
18255 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
18256 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
18257 Defines a new preprocessing symbol, associated with value. If no value is given
18258 on the command line, then symbol is considered to be @code{True}. This switch
18259 can be used in place of a definition file.
18260
18261 @ifset vms
18262 @item /REMOVE
18263 @cindex @option{/REMOVE} (@command{gnatprep})
18264 This is the default setting which causes lines deleted by preprocessing
18265 to be entirely removed from the output file.
18266 @end ifset
18267
18268 @item ^-r^/REFERENCE^
18269 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
18270 Causes a @code{Source_Reference} pragma to be generated that
18271 references the original input file, so that error messages will use
18272 the file name of this original file. The use of this switch implies
18273 that preprocessor lines are not to be removed from the file, so its
18274 use will force @option{^-b^/BLANK_LINES^} mode if
18275 @option{^-c^/COMMENTS^}
18276 has not been specified explicitly.
18277
18278 Note that if the file to be preprocessed contains multiple units, then
18279 it will be necessary to @code{gnatchop} the output file from
18280 @code{gnatprep}. If a @code{Source_Reference} pragma is present
18281 in the preprocessed file, it will be respected by
18282 @code{gnatchop ^-r^/REFERENCE^}
18283 so that the final chopped files will correctly refer to the original
18284 input source file for @code{gnatprep}.
18285
18286 @item ^-s^/SYMBOLS^
18287 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
18288 Causes a sorted list of symbol names and values to be
18289 listed on the standard output file.
18290
18291 @item ^-u^/UNDEFINED^
18292 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
18293 Causes undefined symbols to be treated as having the value FALSE in the context
18294 of a preprocessor test. In the absence of this option, an undefined symbol in
18295 a @code{#if} or @code{#elsif} test will be treated as an error.
18296
18297 @end table
18298
18299 @ifclear vms
18300 @noindent
18301 Note: if neither @option{-b} nor @option{-c} is present,
18302 then preprocessor lines and
18303 deleted lines are completely removed from the output, unless -r is
18304 specified, in which case -b is assumed.
18305 @end ifclear
18306
18307 @node Form of Definitions File
18308 @section Form of Definitions File
18309
18310 @noindent
18311 The definitions file contains lines of the form
18312
18313 @smallexample
18314 symbol := value
18315 @end smallexample
18316
18317 @noindent
18318 where symbol is a preprocessing symbol, and value is one of the following:
18319
18320 @itemize @bullet
18321 @item
18322 Empty, corresponding to a null substitution
18323 @item
18324 A string literal using normal Ada syntax
18325 @item
18326 Any sequence of characters from the set
18327 (letters, digits, period, underline).
18328 @end itemize
18329
18330 @noindent
18331 Comment lines may also appear in the definitions file, starting with
18332 the usual @code{--},
18333 and comments may be added to the definitions lines.
18334
18335 @node Form of Input Text for gnatprep
18336 @section Form of Input Text for @code{gnatprep}
18337
18338 @noindent
18339 The input text may contain preprocessor conditional inclusion lines,
18340 as well as general symbol substitution sequences.
18341
18342 The preprocessor conditional inclusion commands have the form
18343
18344 @smallexample
18345 @group
18346 @cartouche
18347 #if @i{expression} @r{[}then@r{]}
18348    lines
18349 #elsif @i{expression} @r{[}then@r{]}
18350    lines
18351 #elsif @i{expression} @r{[}then@r{]}
18352    lines
18353 @dots{}
18354 #else
18355    lines
18356 #end if;
18357 @end cartouche
18358 @end group
18359 @end smallexample
18360
18361 @noindent
18362 In this example, @i{expression} is defined by the following grammar:
18363 @smallexample
18364 @i{expression} ::=  <symbol>
18365 @i{expression} ::=  <symbol> = "<value>"
18366 @i{expression} ::=  <symbol> = <symbol>
18367 @i{expression} ::=  <symbol> 'Defined
18368 @i{expression} ::=  not @i{expression}
18369 @i{expression} ::=  @i{expression} and @i{expression}
18370 @i{expression} ::=  @i{expression} or @i{expression}
18371 @i{expression} ::=  @i{expression} and then @i{expression}
18372 @i{expression} ::=  @i{expression} or else @i{expression}
18373 @i{expression} ::=  ( @i{expression} )
18374 @end smallexample
18375
18376 The following restriction exists: it is not allowed to have "and" or "or"
18377 following "not" in the same expression without parentheses. For example, this
18378 is not allowed:
18379
18380 @smallexample
18381    not X or Y
18382 @end smallexample
18383
18384 This should be one of the following:
18385
18386 @smallexample
18387    (not X) or Y
18388    not (X or Y)
18389 @end smallexample
18390
18391 @noindent
18392 For the first test (@i{expression} ::= <symbol>) the symbol must have
18393 either the value true or false, that is to say the right-hand of the
18394 symbol definition must be one of the (case-insensitive) literals
18395 @code{True} or @code{False}. If the value is true, then the
18396 corresponding lines are included, and if the value is false, they are
18397 excluded.
18398
18399 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
18400 the symbol has been defined in the definition file or by a @option{-D}
18401 switch on the command line. Otherwise, the test is false.
18402
18403 The equality tests are case insensitive, as are all the preprocessor lines.
18404
18405 If the symbol referenced is not defined in the symbol definitions file,
18406 then the effect depends on whether or not switch @option{-u}
18407 is specified. If so, then the symbol is treated as if it had the value
18408 false and the test fails. If this switch is not specified, then
18409 it is an error to reference an undefined symbol. It is also an error to
18410 reference a symbol that is defined with a value other than @code{True}
18411 or @code{False}.
18412
18413 The use of the @code{not} operator inverts the sense of this logical test.
18414 The @code{not} operator cannot be combined with the @code{or} or @code{and}
18415 operators, without parentheses. For example, "if not X or Y then" is not
18416 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
18417
18418 The @code{then} keyword is optional as shown
18419
18420 The @code{#} must be the first non-blank character on a line, but
18421 otherwise the format is free form. Spaces or tabs may appear between
18422 the @code{#} and the keyword. The keywords and the symbols are case
18423 insensitive as in normal Ada code. Comments may be used on a
18424 preprocessor line, but other than that, no other tokens may appear on a
18425 preprocessor line. Any number of @code{elsif} clauses can be present,
18426 including none at all. The @code{else} is optional, as in Ada.
18427
18428 The @code{#} marking the start of a preprocessor line must be the first
18429 non-blank character on the line, i.e., it must be preceded only by
18430 spaces or horizontal tabs.
18431
18432 Symbol substitution outside of preprocessor lines is obtained by using
18433 the sequence
18434
18435 @smallexample
18436 $symbol
18437 @end smallexample
18438
18439 @noindent
18440 anywhere within a source line, except in a comment or within a
18441 string literal. The identifier
18442 following the @code{$} must match one of the symbols defined in the symbol
18443 definition file, and the result is to substitute the value of the
18444 symbol in place of @code{$symbol} in the output file.
18445
18446 Note that although the substitution of strings within a string literal
18447 is not possible, it is possible to have a symbol whose defined value is
18448 a string literal. So instead of setting XYZ to @code{hello} and writing:
18449
18450 @smallexample
18451 Header : String := "$XYZ";
18452 @end smallexample
18453
18454 @noindent
18455 you should set XYZ to @code{"hello"} and write:
18456
18457 @smallexample
18458 Header : String := $XYZ;
18459 @end smallexample
18460
18461 @noindent
18462 and then the substitution will occur as desired.
18463
18464 @ifset vms
18465 @node The GNAT Run-Time Library Builder gnatlbr
18466 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
18467 @findex gnatlbr
18468 @cindex Library builder
18469
18470 @noindent
18471 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
18472 supplied configuration pragmas.
18473
18474 @menu
18475 * Running gnatlbr::
18476 * Switches for gnatlbr::
18477 * Examples of gnatlbr Usage::
18478 @end menu
18479
18480 @node Running gnatlbr
18481 @section Running @code{gnatlbr}
18482
18483 @noindent
18484 The @code{gnatlbr} command has the form
18485
18486 @smallexample
18487 $ GNAT LIBRARY /@r{[}CREATE@r{|}SET@r{|}DELETE@r{]}=directory @r{[}/CONFIG=file@r{]}
18488 @end smallexample
18489
18490 @node Switches for gnatlbr
18491 @section Switches for @code{gnatlbr}
18492
18493 @noindent
18494 @code{gnatlbr} recognizes the following switches:
18495
18496 @table @option
18497 @c !sort!
18498 @item /CREATE=directory
18499 @cindex @code{/CREATE} (@code{gnatlbr})
18500 Create the new run-time library in the specified directory.
18501
18502 @item /SET=directory
18503 @cindex @code{/SET} (@code{gnatlbr})
18504 Make the library in the specified directory the current run-time library.
18505
18506 @item /DELETE=directory
18507 @cindex @code{/DELETE} (@code{gnatlbr})
18508 Delete the run-time library in the specified directory.
18509
18510 @item /CONFIG=file
18511 @cindex @code{/CONFIG} (@code{gnatlbr})
18512 With /CREATE: Use the configuration pragmas in the specified file when
18513 building the library.
18514
18515 With /SET: Use the configuration pragmas in the specified file when
18516 compiling.
18517
18518 @end table
18519
18520 @node Examples of gnatlbr Usage
18521 @section Example of @code{gnatlbr} Usage
18522
18523 @smallexample
18524 Contents of VAXFLOAT.ADC:
18525 pragma Float_Representation (VAX_Float);
18526
18527 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
18528
18529 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
18530
18531 @end smallexample
18532 @end ifset
18533
18534 @node The GNAT Library Browser gnatls
18535 @chapter The GNAT Library Browser @code{gnatls}
18536 @findex gnatls
18537 @cindex Library browser
18538
18539 @noindent
18540 @code{gnatls} is a tool that outputs information about compiled
18541 units. It gives the relationship between objects, unit names and source
18542 files. It can also be used to check the source dependencies of a unit
18543 as well as various characteristics.
18544
18545 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
18546 driver (see @ref{The GNAT Driver and Project Files}).
18547
18548 @menu
18549 * Running gnatls::
18550 * Switches for gnatls::
18551 * Examples of gnatls Usage::
18552 @end menu
18553
18554 @node Running gnatls
18555 @section Running @code{gnatls}
18556
18557 @noindent
18558 The @code{gnatls} command has the form
18559
18560 @smallexample
18561 $ gnatls switches @var{object_or_ali_file}
18562 @end smallexample
18563
18564 @noindent
18565 The main argument is the list of object or @file{ali} files
18566 (@pxref{The Ada Library Information Files})
18567 for which information is requested.
18568
18569 In normal mode, without additional option, @code{gnatls} produces a
18570 four-column listing. Each line represents information for a specific
18571 object. The first column gives the full path of the object, the second
18572 column gives the name of the principal unit in this object, the third
18573 column gives the status of the source and the fourth column gives the
18574 full path of the source representing this unit.
18575 Here is a simple example of use:
18576
18577 @smallexample
18578 $ gnatls *.o
18579 ^./^[]^demo1.o            demo1            DIF demo1.adb
18580 ^./^[]^demo2.o            demo2             OK demo2.adb
18581 ^./^[]^hello.o            h1                OK hello.adb
18582 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
18583 ^./^[]^instr.o            instr             OK instr.adb
18584 ^./^[]^tef.o              tef              DIF tef.adb
18585 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
18586 ^./^[]^tgef.o             tgef             DIF tgef.adb
18587 @end smallexample
18588
18589 @noindent
18590 The first line can be interpreted as follows: the main unit which is
18591 contained in
18592 object file @file{demo1.o} is demo1, whose main source is in
18593 @file{demo1.adb}. Furthermore, the version of the source used for the
18594 compilation of demo1 has been modified (DIF). Each source file has a status
18595 qualifier which can be:
18596
18597 @table @code
18598 @item OK (unchanged)
18599 The version of the source file used for the compilation of the
18600 specified unit corresponds exactly to the actual source file.
18601
18602 @item MOK (slightly modified)
18603 The version of the source file used for the compilation of the
18604 specified unit differs from the actual source file but not enough to
18605 require recompilation. If you use gnatmake with the qualifier
18606 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
18607 MOK will not be recompiled.
18608
18609 @item DIF (modified)
18610 No version of the source found on the path corresponds to the source
18611 used to build this object.
18612
18613 @item ??? (file not found)
18614 No source file was found for this unit.
18615
18616 @item HID (hidden,  unchanged version not first on PATH)
18617 The version of the source that corresponds exactly to the source used
18618 for compilation has been found on the path but it is hidden by another
18619 version of the same source that has been modified.
18620
18621 @end table
18622
18623 @node Switches for gnatls
18624 @section Switches for @code{gnatls}
18625
18626 @noindent
18627 @code{gnatls} recognizes the following switches:
18628
18629 @table @option
18630 @c !sort!
18631 @cindex @option{--version} @command{gnatls}
18632 Display Copyright and version, then exit disregarding all other options.
18633
18634 @item --help
18635 @cindex @option{--help} @command{gnatls}
18636 If @option{--version} was not used, display usage, then exit disregarding
18637 all other options.
18638
18639 @item ^-a^/ALL_UNITS^
18640 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
18641 Consider all units, including those of the predefined Ada library.
18642 Especially useful with @option{^-d^/DEPENDENCIES^}.
18643
18644 @item ^-d^/DEPENDENCIES^
18645 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
18646 List sources from which specified units depend on.
18647
18648 @item ^-h^/OUTPUT=OPTIONS^
18649 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
18650 Output the list of options.
18651
18652 @item ^-o^/OUTPUT=OBJECTS^
18653 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
18654 Only output information about object files.
18655
18656 @item ^-s^/OUTPUT=SOURCES^
18657 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
18658 Only output information about source files.
18659
18660 @item ^-u^/OUTPUT=UNITS^
18661 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
18662 Only output information about compilation units.
18663
18664 @item ^-files^/FILES^=@var{file}
18665 @cindex @option{^-files^/FILES^} (@code{gnatls})
18666 Take as arguments the files listed in text file @var{file}.
18667 Text file @var{file} may contain empty lines that are ignored.
18668 Each nonempty line should contain the name of an existing file.
18669 Several such switches may be specified simultaneously.
18670
18671 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18672 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
18673 @itemx ^-I^/SEARCH=^@var{dir}
18674 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
18675 @itemx -nostdinc
18676 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
18677 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
18678 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
18679 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
18680 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
18681 flags (@pxref{Switches for gnatmake}).
18682
18683 @item --RTS=@var{rts-path}
18684 @cindex @option{--RTS} (@code{gnatls})
18685 Specifies the default location of the runtime library. Same meaning as the
18686 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
18687
18688 @item ^-v^/OUTPUT=VERBOSE^
18689 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
18690 Verbose mode. Output the complete source, object and project paths. Do not use
18691 the default column layout but instead use long format giving as much as
18692 information possible on each requested units, including special
18693 characteristics such as:
18694
18695 @table @code
18696 @item  Preelaborable
18697 The unit is preelaborable in the Ada sense.
18698
18699 @item No_Elab_Code
18700 No elaboration code has been produced by the compiler for this unit.
18701
18702 @item Pure
18703 The unit is pure in the Ada sense.
18704
18705 @item Elaborate_Body
18706 The unit contains a pragma Elaborate_Body.
18707
18708 @item Remote_Types
18709 The unit contains a pragma Remote_Types.
18710
18711 @item Shared_Passive
18712 The unit contains a pragma Shared_Passive.
18713
18714 @item Predefined
18715 This unit is part of the predefined environment and cannot be modified
18716 by the user.
18717
18718 @item Remote_Call_Interface
18719 The unit contains a pragma Remote_Call_Interface.
18720
18721 @end table
18722
18723 @end table
18724
18725 @node Examples of gnatls Usage
18726 @section Example of @code{gnatls} Usage
18727 @ifclear vms
18728
18729 @noindent
18730 Example of using the verbose switch. Note how the source and
18731 object paths are affected by the -I switch.
18732
18733 @smallexample
18734 $ gnatls -v -I.. demo1.o
18735
18736 GNATLS 5.03w (20041123-34)
18737 Copyright 1997-2004 Free Software Foundation, Inc.
18738
18739 Source Search Path:
18740    <Current_Directory>
18741    ../
18742    /home/comar/local/adainclude/
18743
18744 Object Search Path:
18745    <Current_Directory>
18746    ../
18747    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18748
18749 Project Search Path:
18750    <Current_Directory>
18751    /home/comar/local/lib/gnat/
18752
18753 ./demo1.o
18754    Unit =>
18755      Name   => demo1
18756      Kind   => subprogram body
18757      Flags  => No_Elab_Code
18758      Source => demo1.adb    modified
18759 @end smallexample
18760
18761 @noindent
18762 The following is an example of use of the dependency list.
18763 Note the use of the -s switch
18764 which gives a straight list of source files. This can be useful for
18765 building specialized scripts.
18766
18767 @smallexample
18768 $ gnatls -d demo2.o
18769 ./demo2.o   demo2        OK demo2.adb
18770                          OK gen_list.ads
18771                          OK gen_list.adb
18772                          OK instr.ads
18773                          OK instr-child.ads
18774
18775 $ gnatls -d -s -a demo1.o
18776 demo1.adb
18777 /home/comar/local/adainclude/ada.ads
18778 /home/comar/local/adainclude/a-finali.ads
18779 /home/comar/local/adainclude/a-filico.ads
18780 /home/comar/local/adainclude/a-stream.ads
18781 /home/comar/local/adainclude/a-tags.ads
18782 gen_list.ads
18783 gen_list.adb
18784 /home/comar/local/adainclude/gnat.ads
18785 /home/comar/local/adainclude/g-io.ads
18786 instr.ads
18787 /home/comar/local/adainclude/system.ads
18788 /home/comar/local/adainclude/s-exctab.ads
18789 /home/comar/local/adainclude/s-finimp.ads
18790 /home/comar/local/adainclude/s-finroo.ads
18791 /home/comar/local/adainclude/s-secsta.ads
18792 /home/comar/local/adainclude/s-stalib.ads
18793 /home/comar/local/adainclude/s-stoele.ads
18794 /home/comar/local/adainclude/s-stratt.ads
18795 /home/comar/local/adainclude/s-tasoli.ads
18796 /home/comar/local/adainclude/s-unstyp.ads
18797 /home/comar/local/adainclude/unchconv.ads
18798 @end smallexample
18799 @end ifclear
18800
18801 @ifset vms
18802 @smallexample
18803 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
18804
18805 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
18806 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
18807 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
18808 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
18809 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
18810 demo1.adb
18811 gen_list.ads
18812 gen_list.adb
18813 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
18814 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
18815 instr.ads
18816 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
18817 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
18818 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
18819 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
18820 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
18821 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
18822 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
18823 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
18824 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
18825 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
18826 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
18827 @end smallexample
18828 @end ifset
18829
18830 @node Cleaning Up Using gnatclean
18831 @chapter Cleaning Up Using @code{gnatclean}
18832 @findex gnatclean
18833 @cindex Cleaning tool
18834
18835 @noindent
18836 @code{gnatclean} is a tool that allows the deletion of files produced by the
18837 compiler, binder and linker, including ALI files, object files, tree files,
18838 expanded source files, library files, interface copy source files, binder
18839 generated files and executable files.
18840
18841 @menu
18842 * Running gnatclean::
18843 * Switches for gnatclean::
18844 @c * Examples of gnatclean Usage::
18845 @end menu
18846
18847 @node Running gnatclean
18848 @section Running @code{gnatclean}
18849
18850 @noindent
18851 The @code{gnatclean} command has the form:
18852
18853 @smallexample
18854 $ gnatclean switches @var{names}
18855 @end smallexample
18856
18857 @noindent
18858 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
18859 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
18860 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
18861
18862 @noindent
18863 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
18864 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
18865 the linker. In informative-only mode, specified by switch
18866 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
18867 normal mode is listed, but no file is actually deleted.
18868
18869 @node Switches for gnatclean
18870 @section Switches for @code{gnatclean}
18871
18872 @noindent
18873 @code{gnatclean} recognizes the following switches:
18874
18875 @table @option
18876 @c !sort!
18877 @cindex @option{--version} @command{gnatclean}
18878 Display Copyright and version, then exit disregarding all other options.
18879
18880 @item --help
18881 @cindex @option{--help} @command{gnatclean}
18882 If @option{--version} was not used, display usage, then exit disregarding
18883 all other options.
18884
18885 @item ^-c^/COMPILER_FILES_ONLY^
18886 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
18887 Only attempt to delete the files produced by the compiler, not those produced
18888 by the binder or the linker. The files that are not to be deleted are library
18889 files, interface copy files, binder generated files and executable files.
18890
18891 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
18892 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
18893 Indicate that ALI and object files should normally be found in directory
18894 @var{dir}.
18895
18896 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
18897 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
18898 When using project files, if some errors or warnings are detected during
18899 parsing and verbose mode is not in effect (no use of switch
18900 ^-v^/VERBOSE^), then error lines start with the full path name of the project
18901 file, rather than its simple file name.
18902
18903 @item ^-h^/HELP^
18904 @cindex @option{^-h^/HELP^} (@code{gnatclean})
18905 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
18906
18907 @item ^-n^/NODELETE^
18908 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
18909 Informative-only mode. Do not delete any files. Output the list of the files
18910 that would have been deleted if this switch was not specified.
18911
18912 @item ^-P^/PROJECT_FILE=^@var{project}
18913 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
18914 Use project file @var{project}. Only one such switch can be used.
18915 When cleaning a project file, the files produced by the compilation of the
18916 immediate sources or inherited sources of the project files are to be
18917 deleted. This is not depending on the presence or not of executable names
18918 on the command line.
18919
18920 @item ^-q^/QUIET^
18921 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
18922 Quiet output. If there are no errors, do not output anything, except in
18923 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
18924 (switch ^-n^/NODELETE^).
18925
18926 @item ^-r^/RECURSIVE^
18927 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
18928 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
18929 clean all imported and extended project files, recursively. If this switch
18930 is not specified, only the files related to the main project file are to be
18931 deleted. This switch has no effect if no project file is specified.
18932
18933 @item ^-v^/VERBOSE^
18934 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
18935 Verbose mode.
18936
18937 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
18938 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
18939 Indicates the verbosity of the parsing of GNAT project files.
18940 @xref{Switches Related to Project Files}.
18941
18942 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
18943 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
18944 Indicates that external variable @var{name} has the value @var{value}.
18945 The Project Manager will use this value for occurrences of
18946 @code{external(name)} when parsing the project file.
18947 @xref{Switches Related to Project Files}.
18948
18949 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18950 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
18951 When searching for ALI and object files, look in directory
18952 @var{dir}.
18953
18954 @item ^-I^/SEARCH=^@var{dir}
18955 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
18956 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
18957
18958 @item ^-I-^/NOCURRENT_DIRECTORY^
18959 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
18960 @cindex Source files, suppressing search
18961 Do not look for ALI or object files in the directory
18962 where @code{gnatclean} was invoked.
18963
18964 @end table
18965
18966 @c @node Examples of gnatclean Usage
18967 @c @section Examples of @code{gnatclean} Usage
18968
18969 @ifclear vms
18970 @node GNAT and Libraries
18971 @chapter GNAT and Libraries
18972 @cindex Library, building, installing, using
18973
18974 @noindent
18975 This chapter describes how to build and use libraries with GNAT, and also shows
18976 how to recompile the GNAT run-time library. You should be familiar with the
18977 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
18978 chapter.
18979
18980 @menu
18981 * Introduction to Libraries in GNAT::
18982 * General Ada Libraries::
18983 * Stand-alone Ada Libraries::
18984 * Rebuilding the GNAT Run-Time Library::
18985 @end menu
18986
18987 @node Introduction to Libraries in GNAT
18988 @section Introduction to Libraries in GNAT
18989
18990 @noindent
18991 A library is, conceptually, a collection of objects which does not have its
18992 own main thread of execution, but rather provides certain services to the
18993 applications that use it. A library can be either statically linked with the
18994 application, in which case its code is directly included in the application,
18995 or, on platforms that support it, be dynamically linked, in which case
18996 its code is shared by all applications making use of this library.
18997
18998 GNAT supports both types of libraries.
18999 In the static case, the compiled code can be provided in different ways. The
19000 simplest approach is to provide directly the set of objects resulting from
19001 compilation of the library source files. Alternatively, you can group the
19002 objects into an archive using whatever commands are provided by the operating
19003 system. For the latter case, the objects are grouped into a shared library.
19004
19005 In the GNAT environment, a library has three types of components:
19006 @itemize @bullet
19007 @item
19008 Source files.
19009 @item
19010 @file{ALI} files.
19011 @xref{The Ada Library Information Files}.
19012 @item
19013 Object files, an archive or a shared library.
19014 @end itemize
19015
19016 @noindent
19017 A GNAT library may expose all its source files, which is useful for
19018 documentation purposes. Alternatively, it may expose only the units needed by
19019 an external user to make use of the library. That is to say, the specs
19020 reflecting the library services along with all the units needed to compile
19021 those specs, which can include generic bodies or any body implementing an
19022 inlined routine. In the case of @emph{stand-alone libraries} those exposed
19023 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
19024
19025 All compilation units comprising an application, including those in a library,
19026 need to be elaborated in an order partially defined by Ada's semantics. GNAT
19027 computes the elaboration order from the @file{ALI} files and this is why they
19028 constitute a mandatory part of GNAT libraries.
19029 @emph{Stand-alone libraries} are the exception to this rule because a specific
19030 library elaboration routine is produced independently of the application(s)
19031 using the library.
19032
19033 @node General Ada Libraries
19034 @section General Ada Libraries
19035
19036 @menu
19037 * Building a library::
19038 * Installing a library::
19039 * Using a library::
19040 @end menu
19041
19042 @node Building a library
19043 @subsection Building a library
19044
19045 @noindent
19046 The easiest way to build a library is to use the Project Manager,
19047 which supports a special type of project called a @emph{Library Project}
19048 (@pxref{Library Projects}).
19049
19050 A project is considered a library project, when two project-level attributes
19051 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
19052 control different aspects of library configuration, additional optional
19053 project-level attributes can be specified:
19054 @table @code
19055 @item Library_Kind
19056 This attribute controls whether the library is to be static or dynamic
19057
19058 @item Library_Version
19059 This attribute specifies the library version; this value is used
19060 during dynamic linking of shared libraries to determine if the currently
19061 installed versions of the binaries are compatible.
19062
19063 @item Library_Options
19064 @item Library_GCC
19065 These attributes specify additional low-level options to be used during
19066 library generation, and redefine the actual application used to generate
19067 library.
19068 @end table
19069
19070 @noindent
19071 The GNAT Project Manager takes full care of the library maintenance task,
19072 including recompilation of the source files for which objects do not exist
19073 or are not up to date, assembly of the library archive, and installation of
19074 the library (i.e., copying associated source, object and @file{ALI} files
19075 to the specified location).
19076
19077 Here is a simple library project file:
19078 @smallexample @c ada
19079 project My_Lib is
19080    for Source_Dirs use ("src1", "src2");
19081    for Object_Dir use "obj";
19082    for Library_Name use "mylib";
19083    for Library_Dir use "lib";
19084    for Library_Kind use "dynamic";
19085 end My_lib;
19086 @end smallexample
19087
19088 @noindent
19089 and the compilation command to build and install the library:
19090
19091 @smallexample @c ada
19092   $ gnatmake -Pmy_lib
19093 @end smallexample
19094
19095 @noindent
19096 It is not entirely trivial to perform manually all the steps required to
19097 produce a library. We recommend that you use the GNAT Project Manager
19098 for this task. In special cases where this is not desired, the necessary
19099 steps are discussed below.
19100
19101 There are various possibilities for compiling the units that make up the
19102 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
19103 with a conventional script. For simple libraries, it is also possible to create
19104 a dummy main program which depends upon all the packages that comprise the
19105 interface of the library. This dummy main program can then be given to
19106 @command{gnatmake}, which will ensure that all necessary objects are built.
19107
19108 After this task is accomplished, you should follow the standard procedure
19109 of the underlying operating system to produce the static or shared library.
19110
19111 Here is an example of such a dummy program:
19112 @smallexample @c ada
19113 @group
19114 with My_Lib.Service1;
19115 with My_Lib.Service2;
19116 with My_Lib.Service3;
19117 procedure My_Lib_Dummy is
19118 begin
19119    null;
19120 end;
19121 @end group
19122 @end smallexample
19123
19124 @noindent
19125 Here are the generic commands that will build an archive or a shared library.
19126
19127 @smallexample
19128 # compiling the library
19129 $ gnatmake -c my_lib_dummy.adb
19130
19131 # we don't need the dummy object itself
19132 $ rm my_lib_dummy.o my_lib_dummy.ali
19133
19134 # create an archive with the remaining objects
19135 $ ar rc libmy_lib.a *.o
19136 # some systems may require "ranlib" to be run as well
19137
19138 # or create a shared library
19139 $ gcc -shared -o libmy_lib.so *.o
19140 # some systems may require the code to have been compiled with -fPIC
19141
19142 # remove the object files that are now in the library
19143 $ rm *.o
19144
19145 # Make the ALI files read-only so that gnatmake will not try to
19146 # regenerate the objects that are in the library
19147 $ chmod -w *.ali
19148 @end smallexample
19149
19150 @noindent
19151 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
19152 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
19153 be accessed by the directive @option{-l@var{xxx}} at link time.
19154
19155 @node Installing a library
19156 @subsection Installing a library
19157 @cindex @code{ADA_PROJECT_PATH}
19158 @cindex @code{GPR_PROJECT_PATH}
19159
19160 @noindent
19161 If you use project files, library installation is part of the library build
19162 process. Thus no further action is needed in order to make use of the
19163 libraries that are built as part of the general application build. A usable
19164 version of the library is installed in the directory specified by the
19165 @code{Library_Dir} attribute of the library project file.
19166
19167 You may want to install a library in a context different from where the library
19168 is built. This situation arises with third party suppliers, who may want
19169 to distribute a library in binary form where the user is not expected to be
19170 able to recompile the library. The simplest option in this case is to provide
19171 a project file slightly different from the one used to build the library, by
19172 using the @code{externally_built} attribute. For instance, the project
19173 file used to build the library in the previous section can be changed into the
19174 following one when the library is installed:
19175
19176 @smallexample @c projectfile
19177 project My_Lib is
19178    for Source_Dirs use ("src1", "src2");
19179    for Library_Name use "mylib";
19180    for Library_Dir use "lib";
19181    for Library_Kind use "dynamic";
19182    for Externally_Built use "true";
19183 end My_lib;
19184 @end smallexample
19185
19186 @noindent
19187 This project file assumes that the directories @file{src1},
19188 @file{src2}, and @file{lib} exist in
19189 the directory containing the project file. The @code{externally_built}
19190 attribute makes it clear to the GNAT builder that it should not attempt to
19191 recompile any of the units from this library. It allows the library provider to
19192 restrict the source set to the minimum necessary for clients to make use of the
19193 library as described in the first section of this chapter. It is the
19194 responsibility of the library provider to install the necessary sources, ALI
19195 files and libraries in the directories mentioned in the project file. For
19196 convenience, the user's library project file should be installed in a location
19197 that will be searched automatically by the GNAT
19198 builder. These are the directories referenced in the @env{GPR_PROJECT_PATH}
19199 environment variable (@pxref{Importing Projects}), and also the default GNAT
19200 library location that can be queried with @command{gnatls -v} and is usually of
19201 the form $gnat_install_root/lib/gnat.
19202
19203 When project files are not an option, it is also possible, but not recommended,
19204 to install the library so that the sources needed to use the library are on the
19205 Ada source path and the ALI files & libraries be on the Ada Object path (see
19206 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
19207 administrator can place general-purpose libraries in the default compiler
19208 paths, by specifying the libraries' location in the configuration files
19209 @file{ada_source_path} and @file{ada_object_path}. These configuration files
19210 must be located in the GNAT installation tree at the same place as the gcc spec
19211 file. The location of the gcc spec file can be determined as follows:
19212 @smallexample
19213 $ gcc -v
19214 @end smallexample
19215
19216 @noindent
19217 The configuration files mentioned above have a simple format: each line
19218 must contain one unique directory name.
19219 Those names are added to the corresponding path
19220 in their order of appearance in the file. The names can be either absolute
19221 or relative; in the latter case, they are relative to where theses files
19222 are located.
19223
19224 The files @file{ada_source_path} and @file{ada_object_path} might not be
19225 present in a
19226 GNAT installation, in which case, GNAT will look for its run-time library in
19227 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
19228 objects and @file{ALI} files). When the files exist, the compiler does not
19229 look in @file{adainclude} and @file{adalib}, and thus the
19230 @file{ada_source_path} file
19231 must contain the location for the GNAT run-time sources (which can simply
19232 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
19233 contain the location for the GNAT run-time objects (which can simply
19234 be @file{adalib}).
19235
19236 You can also specify a new default path to the run-time library at compilation
19237 time with the switch @option{--RTS=rts-path}. You can thus choose / change
19238 the run-time library you want your program to be compiled with. This switch is
19239 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
19240 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
19241
19242 It is possible to install a library before or after the standard GNAT
19243 library, by reordering the lines in the configuration files. In general, a
19244 library must be installed before the GNAT library if it redefines
19245 any part of it.
19246
19247 @node Using a library
19248 @subsection Using a library
19249
19250 @noindent Once again, the project facility greatly simplifies the use of
19251 libraries. In this context, using a library is just a matter of adding a
19252 @code{with} clause in the user project. For instance, to make use of the
19253 library @code{My_Lib} shown in examples in earlier sections, you can
19254 write:
19255
19256 @smallexample @c projectfile
19257 with "my_lib";
19258 project My_Proj is
19259   @dots{}
19260 end My_Proj;
19261 @end smallexample
19262
19263 Even if you have a third-party, non-Ada library, you can still use GNAT's
19264 Project Manager facility to provide a wrapper for it. For example, the
19265 following project, when @code{with}ed by your main project, will link with the
19266 third-party library @file{liba.a}:
19267
19268 @smallexample @c projectfile
19269 @group
19270 project Liba is
19271    for Externally_Built use "true";
19272    for Source_Files use ();
19273    for Library_Dir use "lib";
19274    for Library_Name use "a";
19275    for Library_Kind use "static";
19276 end Liba;
19277 @end group
19278 @end smallexample
19279 This is an alternative to the use of @code{pragma Linker_Options}. It is
19280 especially interesting in the context of systems with several interdependent
19281 static libraries where finding a proper linker order is not easy and best be
19282 left to the tools having visibility over project dependence information.
19283
19284 @noindent
19285 In order to use an Ada library manually, you need to make sure that this
19286 library is on both your source and object path
19287 (see @ref{Search Paths and the Run-Time Library (RTL)}
19288 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
19289 in an archive or a shared library, you need to specify the desired
19290 library at link time.
19291
19292 For example, you can use the library @file{mylib} installed in
19293 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
19294
19295 @smallexample
19296 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
19297   -largs -lmy_lib
19298 @end smallexample
19299
19300 @noindent
19301 This can be expressed more simply:
19302 @smallexample
19303 $ gnatmake my_appl
19304 @end smallexample
19305 @noindent
19306 when the following conditions are met:
19307 @itemize @bullet
19308 @item
19309 @file{/dir/my_lib_src} has been added by the user to the environment
19310 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
19311 @file{ada_source_path}
19312 @item
19313 @file{/dir/my_lib_obj} has been added by the user to the environment
19314 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
19315 @file{ada_object_path}
19316 @item
19317 a pragma @code{Linker_Options} has been added to one of the sources.
19318 For example:
19319
19320 @smallexample @c ada
19321 pragma Linker_Options ("-lmy_lib");
19322 @end smallexample
19323 @end itemize
19324
19325 @node Stand-alone Ada Libraries
19326 @section Stand-alone Ada Libraries
19327 @cindex Stand-alone library, building, using
19328
19329 @menu
19330 * Introduction to Stand-alone Libraries::
19331 * Building a Stand-alone Library::
19332 * Creating a Stand-alone Library to be used in a non-Ada context::
19333 * Restrictions in Stand-alone Libraries::
19334 @end menu
19335
19336 @node Introduction to Stand-alone Libraries
19337 @subsection Introduction to Stand-alone Libraries
19338
19339 @noindent
19340 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
19341 necessary code to
19342 elaborate the Ada units that are included in the library. In contrast with
19343 an ordinary library, which consists of all sources, objects and @file{ALI}
19344 files of the
19345 library, a SAL may specify a restricted subset of compilation units
19346 to serve as a library interface. In this case, the fully
19347 self-sufficient set of files will normally consist of an objects
19348 archive, the sources of interface units' specs, and the @file{ALI}
19349 files of interface units.
19350 If an interface spec contains a generic unit or an inlined subprogram,
19351 the body's
19352 source must also be provided; if the units that must be provided in the source
19353 form depend on other units, the source and @file{ALI} files of those must
19354 also be provided.
19355
19356 The main purpose of a SAL is to minimize the recompilation overhead of client
19357 applications when a new version of the library is installed. Specifically,
19358 if the interface sources have not changed, client applications do not need to
19359 be recompiled. If, furthermore, a SAL is provided in the shared form and its
19360 version, controlled by @code{Library_Version} attribute, is not changed,
19361 then the clients do not need to be relinked.
19362
19363 SALs also allow the library providers to minimize the amount of library source
19364 text exposed to the clients.  Such ``information hiding'' might be useful or
19365 necessary for various reasons.
19366
19367 Stand-alone libraries are also well suited to be used in an executable whose
19368 main routine is not written in Ada.
19369
19370 @node Building a Stand-alone Library
19371 @subsection Building a Stand-alone Library
19372
19373 @noindent
19374 GNAT's Project facility provides a simple way of building and installing
19375 stand-alone libraries; see @ref{Stand-alone Library Projects}.
19376 To be a Stand-alone Library Project, in addition to the two attributes
19377 that make a project a Library Project (@code{Library_Name} and
19378 @code{Library_Dir}; see @ref{Library Projects}), the attribute
19379 @code{Library_Interface} must be defined.  For example:
19380
19381 @smallexample @c projectfile
19382 @group
19383    for Library_Dir use "lib_dir";
19384    for Library_Name use "dummy";
19385    for Library_Interface use ("int1", "int1.child");
19386 @end group
19387 @end smallexample
19388
19389 @noindent
19390 Attribute @code{Library_Interface} has a non-empty string list value,
19391 each string in the list designating a unit contained in an immediate source
19392 of the project file.
19393
19394 When a Stand-alone Library is built, first the binder is invoked to build
19395 a package whose name depends on the library name
19396 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
19397 This binder-generated package includes initialization and
19398 finalization procedures whose
19399 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
19400 in the example
19401 above). The object corresponding to this package is included in the library.
19402
19403 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
19404 calling of these procedures if a static SAL is built, or if a shared SAL
19405 is built
19406 with the project-level attribute @code{Library_Auto_Init} set to
19407 @code{"false"}.
19408
19409 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
19410 (those that are listed in attribute @code{Library_Interface}) are copied to
19411 the Library Directory. As a consequence, only the Interface Units may be
19412 imported from Ada units outside of the library. If other units are imported,
19413 the binding phase will fail.
19414
19415 The attribute @code{Library_Src_Dir} may be specified for a
19416 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
19417 single string value. Its value must be the path (absolute or relative to the
19418 project directory) of an existing directory. This directory cannot be the
19419 object directory or one of the source directories, but it can be the same as
19420 the library directory. The sources of the Interface
19421 Units of the library that are needed by an Ada client of the library will be
19422 copied to the designated directory, called the Interface Copy directory.
19423 These sources include the specs of the Interface Units, but they may also
19424 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
19425 are used, or when there is a generic unit in the spec. Before the sources
19426 are copied to the Interface Copy directory, an attempt is made to delete all
19427 files in the Interface Copy directory.
19428
19429 Building stand-alone libraries by hand is somewhat tedious, but for those
19430 occasions when it is necessary here are the steps that you need to perform:
19431 @itemize @bullet
19432 @item
19433 Compile all library sources.
19434
19435 @item
19436 Invoke the binder with the switch @option{-n} (No Ada main program),
19437 with all the @file{ALI} files of the interfaces, and
19438 with the switch @option{-L} to give specific names to the @code{init}
19439 and @code{final} procedures.  For example:
19440 @smallexample
19441   gnatbind -n int1.ali int2.ali -Lsal1
19442 @end smallexample
19443
19444 @item
19445 Compile the binder generated file:
19446 @smallexample
19447   gcc -c b~int2.adb
19448 @end smallexample
19449
19450 @item
19451 Link the dynamic library with all the necessary object files,
19452 indicating to the linker the names of the @code{init} (and possibly
19453 @code{final}) procedures for automatic initialization (and finalization).
19454 The built library should be placed in a directory different from
19455 the object directory.
19456
19457 @item
19458 Copy the @code{ALI} files of the interface to the library directory,
19459 add in this copy an indication that it is an interface to a SAL
19460 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
19461 with letter ``P'') and make the modified copy of the @file{ALI} file
19462 read-only.
19463 @end itemize
19464
19465 @noindent
19466 Using SALs is not different from using other libraries
19467 (see @ref{Using a library}).
19468
19469 @node Creating a Stand-alone Library to be used in a non-Ada context
19470 @subsection Creating a Stand-alone Library to be used in a non-Ada context
19471
19472 @noindent
19473 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
19474 a non-Ada context.
19475
19476 The only extra step required is to ensure that library interface subprograms
19477 are compatible with the main program, by means of @code{pragma Export}
19478 or @code{pragma Convention}.
19479
19480 Here is an example of simple library interface for use with C main program:
19481
19482 @smallexample @c ada
19483 package My_Package is
19484
19485    procedure Do_Something;
19486    pragma Export (C, Do_Something, "do_something");
19487
19488    procedure Do_Something_Else;
19489    pragma Export (C, Do_Something_Else, "do_something_else");
19490
19491 end My_Package;
19492 @end smallexample
19493
19494 @noindent
19495 On the foreign language side, you must provide a ``foreign'' view of the
19496 library interface; remember that it should contain elaboration routines in
19497 addition to interface subprograms.
19498
19499 The example below shows the content of @code{mylib_interface.h} (note
19500 that there is no rule for the naming of this file, any name can be used)
19501 @smallexample
19502 /* the library elaboration procedure */
19503 extern void mylibinit (void);
19504
19505 /* the library finalization procedure */
19506 extern void mylibfinal (void);
19507
19508 /* the interface exported by the library */
19509 extern void do_something (void);
19510 extern void do_something_else (void);
19511 @end smallexample
19512
19513 @noindent
19514 Libraries built as explained above can be used from any program, provided
19515 that the elaboration procedures (named @code{mylibinit} in the previous
19516 example) are called before the library services are used. Any number of
19517 libraries can be used simultaneously, as long as the elaboration
19518 procedure of each library is called.
19519
19520 Below is an example of a C program that uses the @code{mylib} library.
19521
19522 @smallexample
19523 #include "mylib_interface.h"
19524
19525 int
19526 main (void)
19527 @{
19528    /* First, elaborate the library before using it */
19529    mylibinit ();
19530
19531    /* Main program, using the library exported entities */
19532    do_something ();
19533    do_something_else ();
19534
19535    /* Library finalization at the end of the program */
19536    mylibfinal ();
19537    return 0;
19538 @}
19539 @end smallexample
19540
19541 @noindent
19542 Note that invoking any library finalization procedure generated by
19543 @code{gnatbind} shuts down the Ada run-time environment.
19544 Consequently, the
19545 finalization of all Ada libraries must be performed at the end of the program.
19546 No call to these libraries or to the Ada run-time library should be made
19547 after the finalization phase.
19548
19549 @node Restrictions in Stand-alone Libraries
19550 @subsection Restrictions in Stand-alone Libraries
19551
19552 @noindent
19553 The pragmas listed below should be used with caution inside libraries,
19554 as they can create incompatibilities with other Ada libraries:
19555 @itemize @bullet
19556 @item pragma @code{Locking_Policy}
19557 @item pragma @code{Queuing_Policy}
19558 @item pragma @code{Task_Dispatching_Policy}
19559 @item pragma @code{Unreserve_All_Interrupts}
19560 @end itemize
19561
19562 @noindent
19563 When using a library that contains such pragmas, the user must make sure
19564 that all libraries use the same pragmas with the same values. Otherwise,
19565 @code{Program_Error} will
19566 be raised during the elaboration of the conflicting
19567 libraries. The usage of these pragmas and its consequences for the user
19568 should therefore be well documented.
19569
19570 Similarly, the traceback in the exception occurrence mechanism should be
19571 enabled or disabled in a consistent manner across all libraries.
19572 Otherwise, Program_Error will be raised during the elaboration of the
19573 conflicting libraries.
19574
19575 If the @code{Version} or @code{Body_Version}
19576 attributes are used inside a library, then you need to
19577 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
19578 libraries, so that version identifiers can be properly computed.
19579 In practice these attributes are rarely used, so this is unlikely
19580 to be a consideration.
19581
19582 @node  Rebuilding the GNAT Run-Time Library
19583 @section Rebuilding the GNAT Run-Time Library
19584 @cindex GNAT Run-Time Library, rebuilding
19585 @cindex Building the GNAT Run-Time Library
19586 @cindex Rebuilding the GNAT Run-Time Library
19587 @cindex Run-Time Library, rebuilding
19588
19589 @noindent
19590 It may be useful to recompile the GNAT library in various contexts, the
19591 most important one being the use of partition-wide configuration pragmas
19592 such as @code{Normalize_Scalars}. A special Makefile called
19593 @code{Makefile.adalib} is provided to that effect and can be found in
19594 the directory containing the GNAT library. The location of this
19595 directory depends on the way the GNAT environment has been installed and can
19596 be determined by means of the command:
19597
19598 @smallexample
19599 $ gnatls -v
19600 @end smallexample
19601
19602 @noindent
19603 The last entry in the object search path usually contains the
19604 gnat library. This Makefile contains its own documentation and in
19605 particular the set of instructions needed to rebuild a new library and
19606 to use it.
19607
19608 @node Using the GNU make Utility
19609 @chapter Using the GNU @code{make} Utility
19610 @findex make
19611
19612 @noindent
19613 This chapter offers some examples of makefiles that solve specific
19614 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
19615 make, make, GNU @code{make}}), nor does it try to replace the
19616 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
19617
19618 All the examples in this section are specific to the GNU version of
19619 make. Although @command{make} is a standard utility, and the basic language
19620 is the same, these examples use some advanced features found only in
19621 @code{GNU make}.
19622
19623 @menu
19624 * Using gnatmake in a Makefile::
19625 * Automatically Creating a List of Directories::
19626 * Generating the Command Line Switches::
19627 * Overcoming Command Line Length Limits::
19628 @end menu
19629
19630 @node Using gnatmake in a Makefile
19631 @section Using gnatmake in a Makefile
19632 @findex makefile
19633 @cindex GNU make
19634
19635 @noindent
19636 Complex project organizations can be handled in a very powerful way by
19637 using GNU make combined with gnatmake. For instance, here is a Makefile
19638 which allows you to build each subsystem of a big project into a separate
19639 shared library. Such a makefile allows you to significantly reduce the link
19640 time of very big applications while maintaining full coherence at
19641 each step of the build process.
19642
19643 The list of dependencies are handled automatically by
19644 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
19645 the appropriate directories.
19646
19647 Note that you should also read the example on how to automatically
19648 create the list of directories
19649 (@pxref{Automatically Creating a List of Directories})
19650 which might help you in case your project has a lot of subdirectories.
19651
19652 @smallexample
19653 @iftex
19654 @leftskip=0cm
19655 @font@heightrm=cmr8
19656 @heightrm
19657 @end iftex
19658 ## This Makefile is intended to be used with the following directory
19659 ## configuration:
19660 ##  - The sources are split into a series of csc (computer software components)
19661 ##    Each of these csc is put in its own directory.
19662 ##    Their name are referenced by the directory names.
19663 ##    They will be compiled into shared library (although this would also work
19664 ##    with static libraries
19665 ##  - The main program (and possibly other packages that do not belong to any
19666 ##    csc is put in the top level directory (where the Makefile is).
19667 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
19668 ##                    \_ second_csc (sources) __ lib (will contain the library)
19669 ##                    \_ @dots{}
19670 ## Although this Makefile is build for shared library, it is easy to modify
19671 ## to build partial link objects instead (modify the lines with -shared and
19672 ## gnatlink below)
19673 ##
19674 ## With this makefile, you can change any file in the system or add any new
19675 ## file, and everything will be recompiled correctly (only the relevant shared
19676 ## objects will be recompiled, and the main program will be re-linked).
19677
19678 # The list of computer software component for your project. This might be
19679 # generated automatically.
19680 CSC_LIST=aa bb cc
19681
19682 # Name of the main program (no extension)
19683 MAIN=main
19684
19685 # If we need to build objects with -fPIC, uncomment the following line
19686 #NEED_FPIC=-fPIC
19687
19688 # The following variable should give the directory containing libgnat.so
19689 # You can get this directory through 'gnatls -v'. This is usually the last
19690 # directory in the Object_Path.
19691 GLIB=@dots{}
19692
19693 # The directories for the libraries
19694 # (This macro expands the list of CSC to the list of shared libraries, you
19695 # could simply use the expanded form:
19696 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
19697 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
19698
19699 $@{MAIN@}: objects $@{LIB_DIR@}
19700     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
19701     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
19702
19703 objects::
19704     # recompile the sources
19705     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
19706
19707 # Note: In a future version of GNAT, the following commands will be simplified
19708 # by a new tool, gnatmlib
19709 $@{LIB_DIR@}:
19710     mkdir -p $@{dir $@@ @}
19711     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
19712     cd $@{dir $@@ @} && cp -f ../*.ali .
19713
19714 # The dependencies for the modules
19715 # Note that we have to force the expansion of *.o, since in some cases
19716 # make won't be able to do it itself.
19717 aa/lib/libaa.so: $@{wildcard aa/*.o@}
19718 bb/lib/libbb.so: $@{wildcard bb/*.o@}
19719 cc/lib/libcc.so: $@{wildcard cc/*.o@}
19720
19721 # Make sure all of the shared libraries are in the path before starting the
19722 # program
19723 run::
19724     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
19725
19726 clean::
19727     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
19728     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
19729     $@{RM@} $@{CSC_LIST:%=%/*.o@}
19730     $@{RM@} *.o *.ali $@{MAIN@}
19731 @end smallexample
19732
19733 @node Automatically Creating a List of Directories
19734 @section Automatically Creating a List of Directories
19735
19736 @noindent
19737 In most makefiles, you will have to specify a list of directories, and
19738 store it in a variable. For small projects, it is often easier to
19739 specify each of them by hand, since you then have full control over what
19740 is the proper order for these directories, which ones should be
19741 included.
19742
19743 However, in larger projects, which might involve hundreds of
19744 subdirectories, it might be more convenient to generate this list
19745 automatically.
19746
19747 The example below presents two methods. The first one, although less
19748 general, gives you more control over the list. It involves wildcard
19749 characters, that are automatically expanded by @command{make}. Its
19750 shortcoming is that you need to explicitly specify some of the
19751 organization of your project, such as for instance the directory tree
19752 depth, whether some directories are found in a separate tree, @enddots{}
19753
19754 The second method is the most general one. It requires an external
19755 program, called @command{find}, which is standard on all Unix systems. All
19756 the directories found under a given root directory will be added to the
19757 list.
19758
19759 @smallexample
19760 @iftex
19761 @leftskip=0cm
19762 @font@heightrm=cmr8
19763 @heightrm
19764 @end iftex
19765 # The examples below are based on the following directory hierarchy:
19766 # All the directories can contain any number of files
19767 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
19768 #                       ->  ab
19769 #                       ->  ac
19770 #                ->  b  ->  ba  ->  baa
19771 #                       ->  bb
19772 #                       ->  bc
19773 # This Makefile creates a variable called DIRS, that can be reused any time
19774 # you need this list (see the other examples in this section)
19775
19776 # The root of your project's directory hierarchy
19777 ROOT_DIRECTORY=.
19778
19779 ####
19780 # First method: specify explicitly the list of directories
19781 # This allows you to specify any subset of all the directories you need.
19782 ####
19783
19784 DIRS := a/aa/ a/ab/ b/ba/
19785
19786 ####
19787 # Second method: use wildcards
19788 # Note that the argument(s) to wildcard below should end with a '/'.
19789 # Since wildcards also return file names, we have to filter them out
19790 # to avoid duplicate directory names.
19791 # We thus use make's @code{dir} and @code{sort} functions.
19792 # It sets DIRs to the following value (note that the directories aaa and baa
19793 # are not given, unless you change the arguments to wildcard).
19794 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
19795 ####
19796
19797 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
19798                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
19799
19800 ####
19801 # Third method: use an external program
19802 # This command is much faster if run on local disks, avoiding NFS slowdowns.
19803 # This is the most complete command: it sets DIRs to the following value:
19804 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
19805 ####
19806
19807 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
19808
19809 @end smallexample
19810
19811 @node Generating the Command Line Switches
19812 @section Generating the Command Line Switches
19813
19814 @noindent
19815 Once you have created the list of directories as explained in the
19816 previous section (@pxref{Automatically Creating a List of Directories}),
19817 you can easily generate the command line arguments to pass to gnatmake.
19818
19819 For the sake of completeness, this example assumes that the source path
19820 is not the same as the object path, and that you have two separate lists
19821 of directories.
19822
19823 @smallexample
19824 # see "Automatically creating a list of directories" to create
19825 # these variables
19826 SOURCE_DIRS=
19827 OBJECT_DIRS=
19828
19829 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
19830 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
19831
19832 all:
19833         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
19834 @end smallexample
19835
19836 @node Overcoming Command Line Length Limits
19837 @section Overcoming Command Line Length Limits
19838
19839 @noindent
19840 One problem that might be encountered on big projects is that many
19841 operating systems limit the length of the command line. It is thus hard to give
19842 gnatmake the list of source and object directories.
19843
19844 This example shows how you can set up environment variables, which will
19845 make @command{gnatmake} behave exactly as if the directories had been
19846 specified on the command line, but have a much higher length limit (or
19847 even none on most systems).
19848
19849 It assumes that you have created a list of directories in your Makefile,
19850 using one of the methods presented in
19851 @ref{Automatically Creating a List of Directories}.
19852 For the sake of completeness, we assume that the object
19853 path (where the ALI files are found) is different from the sources patch.
19854
19855 Note a small trick in the Makefile below: for efficiency reasons, we
19856 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
19857 expanded immediately by @code{make}. This way we overcome the standard
19858 make behavior which is to expand the variables only when they are
19859 actually used.
19860
19861 On Windows, if you are using the standard Windows command shell, you must
19862 replace colons with semicolons in the assignments to these variables.
19863
19864 @smallexample
19865 @iftex
19866 @leftskip=0cm
19867 @font@heightrm=cmr8
19868 @heightrm
19869 @end iftex
19870 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
19871 # This is the same thing as putting the -I arguments on the command line.
19872 # (the equivalent of using -aI on the command line would be to define
19873 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
19874 # You can of course have different values for these variables.
19875 #
19876 # Note also that we need to keep the previous values of these variables, since
19877 # they might have been set before running 'make' to specify where the GNAT
19878 # library is installed.
19879
19880 # see "Automatically creating a list of directories" to create these
19881 # variables
19882 SOURCE_DIRS=
19883 OBJECT_DIRS=
19884
19885 empty:=
19886 space:=$@{empty@} $@{empty@}
19887 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
19888 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
19889 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
19890 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
19891 export ADA_INCLUDE_PATH
19892 export ADA_OBJECT_PATH
19893
19894 all:
19895         gnatmake main_unit
19896 @end smallexample
19897 @end ifclear
19898
19899 @node Memory Management Issues
19900 @chapter Memory Management Issues
19901
19902 @noindent
19903 This chapter describes some useful memory pools provided in the GNAT library
19904 and in particular the GNAT Debug Pool facility, which can be used to detect
19905 incorrect uses of access values (including ``dangling references'').
19906 @ifclear vms
19907 It also describes the @command{gnatmem} tool, which can be used to track down
19908 ``memory leaks''.
19909 @end ifclear
19910
19911 @menu
19912 * Some Useful Memory Pools::
19913 * The GNAT Debug Pool Facility::
19914 @ifclear vms
19915 * The gnatmem Tool::
19916 @end ifclear
19917 @end menu
19918
19919 @node Some Useful Memory Pools
19920 @section Some Useful Memory Pools
19921 @findex Memory Pool
19922 @cindex storage, pool
19923
19924 @noindent
19925 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
19926 storage pool. Allocations use the standard system call @code{malloc} while
19927 deallocations use the standard system call @code{free}. No reclamation is
19928 performed when the pool goes out of scope. For performance reasons, the
19929 standard default Ada allocators/deallocators do not use any explicit storage
19930 pools but if they did, they could use this storage pool without any change in
19931 behavior. That is why this storage pool is used  when the user
19932 manages to make the default implicit allocator explicit as in this example:
19933 @smallexample @c ada
19934    type T1 is access Something;
19935     -- no Storage pool is defined for T2
19936    type T2 is access Something_Else;
19937    for T2'Storage_Pool use T1'Storage_Pool;
19938    -- the above is equivalent to
19939    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
19940 @end smallexample
19941
19942 @noindent
19943 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
19944 pool. The allocation strategy is similar to @code{Pool_Local}'s
19945 except that the all
19946 storage allocated with this pool is reclaimed when the pool object goes out of
19947 scope. This pool provides a explicit mechanism similar to the implicit one
19948 provided by several Ada 83 compilers for allocations performed through a local
19949 access type and whose purpose was to reclaim memory when exiting the
19950 scope of a given local access. As an example, the following program does not
19951 leak memory even though it does not perform explicit deallocation:
19952
19953 @smallexample @c ada
19954 with System.Pool_Local;
19955 procedure Pooloc1 is
19956    procedure Internal is
19957       type A is access Integer;
19958       X : System.Pool_Local.Unbounded_Reclaim_Pool;
19959       for A'Storage_Pool use X;
19960       v : A;
19961    begin
19962       for I in  1 .. 50 loop
19963          v := new Integer;
19964       end loop;
19965    end Internal;
19966 begin
19967    for I in  1 .. 100 loop
19968       Internal;
19969    end loop;
19970 end Pooloc1;
19971 @end smallexample
19972
19973 @noindent
19974 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
19975 @code{Storage_Size} is specified for an access type.
19976 The whole storage for the pool is
19977 allocated at once, usually on the stack at the point where the access type is
19978 elaborated. It is automatically reclaimed when exiting the scope where the
19979 access type is defined. This package is not intended to be used directly by the
19980 user and it is implicitly used for each such declaration:
19981
19982 @smallexample @c ada
19983    type T1 is access Something;
19984    for T1'Storage_Size use 10_000;
19985 @end smallexample
19986
19987 @node The GNAT Debug Pool Facility
19988 @section The GNAT Debug Pool Facility
19989 @findex Debug Pool
19990 @cindex storage, pool, memory corruption
19991
19992 @noindent
19993 The use of unchecked deallocation and unchecked conversion can easily
19994 lead to incorrect memory references. The problems generated by such
19995 references are usually difficult to tackle because the symptoms can be
19996 very remote from the origin of the problem. In such cases, it is
19997 very helpful to detect the problem as early as possible. This is the
19998 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
19999
20000 In order to use the GNAT specific debugging pool, the user must
20001 associate a debug pool object with each of the access types that may be
20002 related to suspected memory problems. See Ada Reference Manual 13.11.
20003 @smallexample @c ada
20004 type Ptr is access Some_Type;
20005 Pool : GNAT.Debug_Pools.Debug_Pool;
20006 for Ptr'Storage_Pool use Pool;
20007 @end smallexample
20008
20009 @noindent
20010 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
20011 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
20012 allow the user to redefine allocation and deallocation strategies. They
20013 also provide a checkpoint for each dereference, through the use of
20014 the primitive operation @code{Dereference} which is implicitly called at
20015 each dereference of an access value.
20016
20017 Once an access type has been associated with a debug pool, operations on
20018 values of the type may raise four distinct exceptions,
20019 which correspond to four potential kinds of memory corruption:
20020 @itemize @bullet
20021 @item
20022 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
20023 @item
20024 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
20025 @item
20026 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
20027 @item
20028 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
20029 @end itemize
20030
20031 @noindent
20032 For types associated with a Debug_Pool, dynamic allocation is performed using
20033 the standard GNAT allocation routine. References to all allocated chunks of
20034 memory are kept in an internal dictionary. Several deallocation strategies are
20035 provided, whereupon the user can choose to release the memory to the system,
20036 keep it allocated for further invalid access checks, or fill it with an easily
20037 recognizable pattern for debug sessions. The memory pattern is the old IBM
20038 hexadecimal convention: @code{16#DEADBEEF#}.
20039
20040 See the documentation in the file g-debpoo.ads for more information on the
20041 various strategies.
20042
20043 Upon each dereference, a check is made that the access value denotes a
20044 properly allocated memory location. Here is a complete example of use of
20045 @code{Debug_Pools}, that includes typical instances of  memory corruption:
20046 @smallexample @c ada
20047 @iftex
20048 @leftskip=0cm
20049 @end iftex
20050 with Gnat.Io; use Gnat.Io;
20051 with Unchecked_Deallocation;
20052 with Unchecked_Conversion;
20053 with GNAT.Debug_Pools;
20054 with System.Storage_Elements;
20055 with Ada.Exceptions; use Ada.Exceptions;
20056 procedure Debug_Pool_Test is
20057
20058    type T is access Integer;
20059    type U is access all T;
20060
20061    P : GNAT.Debug_Pools.Debug_Pool;
20062    for T'Storage_Pool use P;
20063
20064    procedure Free is new Unchecked_Deallocation (Integer, T);
20065    function UC is new Unchecked_Conversion (U, T);
20066    A, B : aliased T;
20067
20068    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
20069
20070 begin
20071    Info (P);
20072    A := new Integer;
20073    B := new Integer;
20074    B := A;
20075    Info (P);
20076    Free (A);
20077    begin
20078       Put_Line (Integer'Image(B.all));
20079    exception
20080       when E : others => Put_Line ("raised: " & Exception_Name (E));
20081    end;
20082    begin
20083       Free (B);
20084    exception
20085       when E : others => Put_Line ("raised: " & Exception_Name (E));
20086    end;
20087    B := UC(A'Access);
20088    begin
20089       Put_Line (Integer'Image(B.all));
20090    exception
20091       when E : others => Put_Line ("raised: " & Exception_Name (E));
20092    end;
20093    begin
20094       Free (B);
20095    exception
20096       when E : others => Put_Line ("raised: " & Exception_Name (E));
20097    end;
20098    Info (P);
20099 end Debug_Pool_Test;
20100 @end smallexample
20101
20102 @noindent
20103 The debug pool mechanism provides the following precise diagnostics on the
20104 execution of this erroneous program:
20105 @smallexample
20106 Debug Pool info:
20107   Total allocated bytes :  0
20108   Total deallocated bytes :  0
20109   Current Water Mark:  0
20110   High Water Mark:  0
20111
20112 Debug Pool info:
20113   Total allocated bytes :  8
20114   Total deallocated bytes :  0
20115   Current Water Mark:  8
20116   High Water Mark:  8
20117
20118 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
20119 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
20120 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
20121 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
20122 Debug Pool info:
20123   Total allocated bytes :  8
20124   Total deallocated bytes :  4
20125   Current Water Mark:  4
20126   High Water Mark:  8
20127 @end smallexample
20128
20129 @ifclear vms
20130 @node The gnatmem Tool
20131 @section The @command{gnatmem} Tool
20132 @findex gnatmem
20133
20134 @noindent
20135 The @code{gnatmem} utility monitors dynamic allocation and
20136 deallocation activity in a program, and displays information about
20137 incorrect deallocations and possible sources of memory leaks.
20138 It is designed to work in association with a static runtime library
20139 only and in this context provides three types of information:
20140 @itemize @bullet
20141 @item
20142 General information concerning memory management, such as the total
20143 number of allocations and deallocations, the amount of allocated
20144 memory and the high water mark, i.e.@: the largest amount of allocated
20145 memory in the course of program execution.
20146
20147 @item
20148 Backtraces for all incorrect deallocations, that is to say deallocations
20149 which do not correspond to a valid allocation.
20150
20151 @item
20152 Information on each allocation that is potentially the origin of a memory
20153 leak.
20154 @end itemize
20155
20156 @menu
20157 * Running gnatmem::
20158 * Switches for gnatmem::
20159 * Example of gnatmem Usage::
20160 @end menu
20161
20162 @node Running gnatmem
20163 @subsection Running @code{gnatmem}
20164
20165 @noindent
20166 @code{gnatmem} makes use of the output created by the special version of
20167 allocation and deallocation routines that record call information. This
20168 allows to obtain accurate dynamic memory usage history at a minimal cost to
20169 the execution speed. Note however, that @code{gnatmem} is not supported on
20170 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
20171 Solaris and Windows NT/2000/XP (x86).
20172
20173 @noindent
20174 The @code{gnatmem} command has the form
20175
20176 @smallexample
20177 @c    $ gnatmem @ovar{switches} user_program
20178 @c Expanding @ovar macro inline (explanation in macro def comments)
20179       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
20180 @end smallexample
20181
20182 @noindent
20183 The program must have been linked with the instrumented version of the
20184 allocation and deallocation routines. This is done by linking with the
20185 @file{libgmem.a} library. For correct symbolic backtrace information,
20186 the user program should be compiled with debugging options
20187 (see @ref{Switches for gcc}). For example to build @file{my_program}:
20188
20189 @smallexample
20190 $ gnatmake -g my_program -largs -lgmem
20191 @end smallexample
20192
20193 @noindent
20194 As library @file{libgmem.a} contains an alternate body for package
20195 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
20196 when an executable is linked with library @file{libgmem.a}. It is then not
20197 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
20198
20199 @noindent
20200 When @file{my_program} is executed, the file @file{gmem.out} is produced.
20201 This file contains information about all allocations and deallocations
20202 performed by the program. It is produced by the instrumented allocations and
20203 deallocations routines and will be used by @code{gnatmem}.
20204
20205 In order to produce symbolic backtrace information for allocations and
20206 deallocations performed by the GNAT run-time library, you need to use a
20207 version of that library that has been compiled with the @option{-g} switch
20208 (see @ref{Rebuilding the GNAT Run-Time Library}).
20209
20210 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
20211 examine. If the location of @file{gmem.out} file was not explicitly supplied by
20212 @option{-i} switch, gnatmem will assume that this file can be found in the
20213 current directory. For example, after you have executed @file{my_program},
20214 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
20215
20216 @smallexample
20217 $ gnatmem my_program
20218 @end smallexample
20219
20220 @noindent
20221 This will produce the output with the following format:
20222
20223 *************** debut cc
20224 @smallexample
20225 $ gnatmem my_program
20226
20227 Global information
20228 ------------------
20229    Total number of allocations        :  45
20230    Total number of deallocations      :   6
20231    Final Water Mark (non freed mem)   :  11.29 Kilobytes
20232    High Water Mark                    :  11.40 Kilobytes
20233
20234 .
20235 .
20236 .
20237 Allocation Root # 2
20238 -------------------
20239  Number of non freed allocations    :  11
20240  Final Water Mark (non freed mem)   :   1.16 Kilobytes
20241  High Water Mark                    :   1.27 Kilobytes
20242  Backtrace                          :
20243    my_program.adb:23 my_program.alloc
20244 .
20245 .
20246 .
20247 @end smallexample
20248
20249 The first block of output gives general information. In this case, the
20250 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
20251 Unchecked_Deallocation routine occurred.
20252
20253 @noindent
20254 Subsequent paragraphs display  information on all allocation roots.
20255 An allocation root is a specific point in the execution of the program
20256 that generates some dynamic allocation, such as a ``@code{@b{new}}''
20257 construct. This root is represented by an execution backtrace (or subprogram
20258 call stack). By default the backtrace depth for allocations roots is 1, so
20259 that a root corresponds exactly to a source location. The backtrace can
20260 be made deeper, to make the root more specific.
20261
20262 @node Switches for gnatmem
20263 @subsection Switches for @code{gnatmem}
20264
20265 @noindent
20266 @code{gnatmem} recognizes the following switches:
20267
20268 @table @option
20269
20270 @item -q
20271 @cindex @option{-q} (@code{gnatmem})
20272 Quiet. Gives the minimum output needed to identify the origin of the
20273 memory leaks. Omits statistical information.
20274
20275 @item @var{N}
20276 @cindex @var{N} (@code{gnatmem})
20277 N is an integer literal (usually between 1 and 10) which controls the
20278 depth of the backtraces defining allocation root. The default value for
20279 N is 1. The deeper the backtrace, the more precise the localization of
20280 the root. Note that the total number of roots can depend on this
20281 parameter. This parameter must be specified @emph{before} the name of the
20282 executable to be analyzed, to avoid ambiguity.
20283
20284 @item -b n
20285 @cindex @option{-b} (@code{gnatmem})
20286 This switch has the same effect as just depth parameter.
20287
20288 @item -i @var{file}
20289 @cindex @option{-i} (@code{gnatmem})
20290 Do the @code{gnatmem} processing starting from @file{file}, rather than
20291 @file{gmem.out} in the current directory.
20292
20293 @item -m n
20294 @cindex @option{-m} (@code{gnatmem})
20295 This switch causes @code{gnatmem} to mask the allocation roots that have less
20296 than n leaks. The default value is 1. Specifying the value of 0 will allow to
20297 examine even the roots that didn't result in leaks.
20298
20299 @item -s order
20300 @cindex @option{-s} (@code{gnatmem})
20301 This switch causes @code{gnatmem} to sort the allocation roots according to the
20302 specified order of sort criteria, each identified by a single letter. The
20303 currently supported criteria are @code{n, h, w} standing respectively for
20304 number of unfreed allocations, high watermark, and final watermark
20305 corresponding to a specific root. The default order is @code{nwh}.
20306
20307 @end table
20308
20309 @node Example of gnatmem Usage
20310 @subsection Example of @code{gnatmem} Usage
20311
20312 @noindent
20313 The following example shows the use of @code{gnatmem}
20314 on a simple memory-leaking program.
20315 Suppose that we have the following Ada program:
20316
20317 @smallexample @c ada
20318 @group
20319 @cartouche
20320 with Unchecked_Deallocation;
20321 procedure Test_Gm is
20322
20323    type T is array (1..1000) of Integer;
20324    type Ptr is access T;
20325    procedure Free is new Unchecked_Deallocation (T, Ptr);
20326    A : Ptr;
20327
20328    procedure My_Alloc is
20329    begin
20330       A := new T;
20331    end My_Alloc;
20332
20333    procedure My_DeAlloc is
20334       B : Ptr := A;
20335    begin
20336       Free (B);
20337    end My_DeAlloc;
20338
20339 begin
20340    My_Alloc;
20341    for I in 1 .. 5 loop
20342       for J in I .. 5 loop
20343          My_Alloc;
20344       end loop;
20345       My_Dealloc;
20346    end loop;
20347 end;
20348 @end cartouche
20349 @end group
20350 @end smallexample
20351
20352 @noindent
20353 The program needs to be compiled with debugging option and linked with
20354 @code{gmem} library:
20355
20356 @smallexample
20357 $ gnatmake -g test_gm -largs -lgmem
20358 @end smallexample
20359
20360 @noindent
20361 Then we execute the program as usual:
20362
20363 @smallexample
20364 $ test_gm
20365 @end smallexample
20366
20367 @noindent
20368 Then @code{gnatmem} is invoked simply with
20369 @smallexample
20370 $ gnatmem test_gm
20371 @end smallexample
20372
20373 @noindent
20374 which produces the following output (result may vary on different platforms):
20375
20376 @smallexample
20377 Global information
20378 ------------------
20379    Total number of allocations        :  18
20380    Total number of deallocations      :   5
20381    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20382    High Water Mark                    :  56.90 Kilobytes
20383
20384 Allocation Root # 1
20385 -------------------
20386  Number of non freed allocations    :  11
20387  Final Water Mark (non freed mem)   :  42.97 Kilobytes
20388  High Water Mark                    :  46.88 Kilobytes
20389  Backtrace                          :
20390    test_gm.adb:11 test_gm.my_alloc
20391
20392 Allocation Root # 2
20393 -------------------
20394  Number of non freed allocations    :   1
20395  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20396  High Water Mark                    :  10.02 Kilobytes
20397  Backtrace                          :
20398    s-secsta.adb:81 system.secondary_stack.ss_init
20399
20400 Allocation Root # 3
20401 -------------------
20402  Number of non freed allocations    :   1
20403  Final Water Mark (non freed mem)   :  12 Bytes
20404  High Water Mark                    :  12 Bytes
20405  Backtrace                          :
20406    s-secsta.adb:181 system.secondary_stack.ss_init
20407 @end smallexample
20408
20409 @noindent
20410 Note that the GNAT run time contains itself a certain number of
20411 allocations that have no  corresponding deallocation,
20412 as shown here for root #2 and root
20413 #3. This is a normal behavior when the number of non-freed allocations
20414 is one, it allocates dynamic data structures that the run time needs for
20415 the complete lifetime of the program. Note also that there is only one
20416 allocation root in the user program with a single line back trace:
20417 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
20418 program shows that 'My_Alloc' is called at 2 different points in the
20419 source (line 21 and line 24). If those two allocation roots need to be
20420 distinguished, the backtrace depth parameter can be used:
20421
20422 @smallexample
20423 $ gnatmem 3 test_gm
20424 @end smallexample
20425
20426 @noindent
20427 which will give the following output:
20428
20429 @smallexample
20430 Global information
20431 ------------------
20432    Total number of allocations        :  18
20433    Total number of deallocations      :   5
20434    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20435    High Water Mark                    :  56.90 Kilobytes
20436
20437 Allocation Root # 1
20438 -------------------
20439  Number of non freed allocations    :  10
20440  Final Water Mark (non freed mem)   :  39.06 Kilobytes
20441  High Water Mark                    :  42.97 Kilobytes
20442  Backtrace                          :
20443    test_gm.adb:11 test_gm.my_alloc
20444    test_gm.adb:24 test_gm
20445    b_test_gm.c:52 main
20446
20447 Allocation Root # 2
20448 -------------------
20449  Number of non freed allocations    :   1
20450  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20451  High Water Mark                    :  10.02 Kilobytes
20452  Backtrace                          :
20453    s-secsta.adb:81  system.secondary_stack.ss_init
20454    s-secsta.adb:283 <system__secondary_stack___elabb>
20455    b_test_gm.c:33   adainit
20456
20457 Allocation Root # 3
20458 -------------------
20459  Number of non freed allocations    :   1
20460  Final Water Mark (non freed mem)   :   3.91 Kilobytes
20461  High Water Mark                    :   3.91 Kilobytes
20462  Backtrace                          :
20463    test_gm.adb:11 test_gm.my_alloc
20464    test_gm.adb:21 test_gm
20465    b_test_gm.c:52 main
20466
20467 Allocation Root # 4
20468 -------------------
20469  Number of non freed allocations    :   1
20470  Final Water Mark (non freed mem)   :  12 Bytes
20471  High Water Mark                    :  12 Bytes
20472  Backtrace                          :
20473    s-secsta.adb:181 system.secondary_stack.ss_init
20474    s-secsta.adb:283 <system__secondary_stack___elabb>
20475    b_test_gm.c:33   adainit
20476 @end smallexample
20477
20478 @noindent
20479 The allocation root #1 of the first example has been split in 2 roots #1
20480 and #3 thanks to the more precise associated backtrace.
20481
20482 @end ifclear
20483
20484 @node Stack Related Facilities
20485 @chapter Stack Related Facilities
20486
20487 @noindent
20488 This chapter describes some useful tools associated with stack
20489 checking and analysis. In
20490 particular, it deals with dynamic and static stack usage measurements.
20491
20492 @menu
20493 * Stack Overflow Checking::
20494 * Static Stack Usage Analysis::
20495 * Dynamic Stack Usage Analysis::
20496 @end menu
20497
20498 @node Stack Overflow Checking
20499 @section Stack Overflow Checking
20500 @cindex Stack Overflow Checking
20501 @cindex -fstack-check
20502
20503 @noindent
20504 For most operating systems, @command{gcc} does not perform stack overflow
20505 checking by default. This means that if the main environment task or
20506 some other task exceeds the available stack space, then unpredictable
20507 behavior will occur. Most native systems offer some level of protection by
20508 adding a guard page at the end of each task stack. This mechanism is usually
20509 not enough for dealing properly with stack overflow situations because
20510 a large local variable could ``jump'' above the guard page.
20511 Furthermore, when the
20512 guard page is hit, there may not be any space left on the stack for executing
20513 the exception propagation code. Enabling stack checking avoids
20514 such situations.
20515
20516 To activate stack checking, compile all units with the gcc option
20517 @option{-fstack-check}. For example:
20518
20519 @smallexample
20520 gcc -c -fstack-check package1.adb
20521 @end smallexample
20522
20523 @noindent
20524 Units compiled with this option will generate extra instructions to check
20525 that any use of the stack (for procedure calls or for declaring local
20526 variables in declare blocks) does not exceed the available stack space.
20527 If the space is exceeded, then a @code{Storage_Error} exception is raised.
20528
20529 For declared tasks, the stack size is controlled by the size
20530 given in an applicable @code{Storage_Size} pragma or by the value specified
20531 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
20532 the default size as defined in the GNAT runtime otherwise.
20533
20534 For the environment task, the stack size depends on
20535 system defaults and is unknown to the compiler. Stack checking
20536 may still work correctly if a fixed
20537 size stack is allocated, but this cannot be guaranteed.
20538 @ifclear vms
20539 To ensure that a clean exception is signalled for stack
20540 overflow, set the environment variable
20541 @env{GNAT_STACK_LIMIT} to indicate the maximum
20542 stack area that can be used, as in:
20543 @cindex GNAT_STACK_LIMIT
20544
20545 @smallexample
20546 SET GNAT_STACK_LIMIT 1600
20547 @end smallexample
20548
20549 @noindent
20550 The limit is given in kilobytes, so the above declaration would
20551 set the stack limit of the environment task to 1.6 megabytes.
20552 Note that the only purpose of this usage is to limit the amount
20553 of stack used by the environment task. If it is necessary to
20554 increase the amount of stack for the environment task, then this
20555 is an operating systems issue, and must be addressed with the
20556 appropriate operating systems commands.
20557 @end ifclear
20558 @ifset vms
20559 To have a fixed size stack in the environment task, the stack must be put
20560 in the P0 address space and its size specified.  Use these switches to
20561 create a p0 image:
20562
20563 @smallexample
20564 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
20565 @end smallexample
20566
20567 @noindent
20568 The quotes are required to keep case.  The number after @samp{STACK=} is the
20569 size of the environmental task stack in pagelets (512 bytes).  In this example
20570 the stack size is about 2 megabytes.
20571
20572 @noindent
20573 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
20574 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
20575 more details about the @option{/p0image} qualifier and the @option{stack}
20576 option.
20577 @end ifset
20578
20579 @node Static Stack Usage Analysis
20580 @section Static Stack Usage Analysis
20581 @cindex Static Stack Usage Analysis
20582 @cindex -fstack-usage
20583
20584 @noindent
20585 A unit compiled with @option{-fstack-usage} will generate an extra file
20586 that specifies
20587 the maximum amount of stack used, on a per-function basis.
20588 The file has the same
20589 basename as the target object file with a @file{.su} extension.
20590 Each line of this file is made up of three fields:
20591
20592 @itemize
20593 @item
20594 The name of the function.
20595 @item
20596 A number of bytes.
20597 @item
20598 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
20599 @end itemize
20600
20601 The second field corresponds to the size of the known part of the function
20602 frame.
20603
20604 The qualifier @code{static} means that the function frame size
20605 is purely static.
20606 It usually means that all local variables have a static size.
20607 In this case, the second field is a reliable measure of the function stack
20608 utilization.
20609
20610 The qualifier @code{dynamic} means that the function frame size is not static.
20611 It happens mainly when some local variables have a dynamic size. When this
20612 qualifier appears alone, the second field is not a reliable measure
20613 of the function stack analysis. When it is qualified with  @code{bounded}, it
20614 means that the second field is a reliable maximum of the function stack
20615 utilization.
20616
20617 @node Dynamic Stack Usage Analysis
20618 @section Dynamic Stack Usage Analysis
20619
20620 @noindent
20621 It is possible to measure the maximum amount of stack used by a task, by
20622 adding a switch to @command{gnatbind}, as:
20623
20624 @smallexample
20625 $ gnatbind -u0 file
20626 @end smallexample
20627
20628 @noindent
20629 With this option, at each task termination, its stack usage is  output on
20630 @file{stderr}.
20631 It is not always convenient to output the stack usage when the program
20632 is still running. Hence, it is possible to delay this output until program
20633 termination. for a given number of tasks specified as the argument of the
20634 @option{-u} option. For instance:
20635
20636 @smallexample
20637 $ gnatbind -u100 file
20638 @end smallexample
20639
20640 @noindent
20641 will buffer the stack usage information of the first 100 tasks to terminate and
20642 output this info at program termination. Results are displayed in four
20643 columns:
20644
20645 @noindent
20646 Index | Task Name | Stack Size | Stack Usage [Value +/- Variation]
20647
20648 @noindent
20649 where:
20650
20651 @table @emph
20652 @item Index
20653 is a number associated with each task.
20654
20655 @item Task Name
20656 is the name of the task analyzed.
20657
20658 @item Stack Size
20659 is the maximum size for the stack.
20660
20661 @item Stack Usage
20662 is the measure done by the stack analyzer. In order to prevent overflow, the stack
20663 is not entirely analyzed, and it's not possible to know exactly how
20664 much has actually been used. The report thus contains the theoretical stack usage
20665 (Value) and the possible variation (Variation) around this value.
20666
20667 @end table
20668
20669 @noindent
20670 The environment task stack, e.g., the stack that contains the main unit, is
20671 only processed when the environment variable GNAT_STACK_LIMIT is set.
20672
20673
20674 @c *********************************
20675 @c *            GNATCHECK          *
20676 @c *********************************
20677 @node Verifying Properties Using gnatcheck
20678 @chapter Verifying Properties Using @command{gnatcheck}
20679 @findex gnatcheck
20680 @cindex @command{gnatcheck}
20681
20682 @noindent
20683 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
20684 of Ada source files according to a given set of semantic rules.
20685 @cindex ASIS
20686
20687 In order to check compliance with a given rule, @command{gnatcheck} has to
20688 semantically analyze the Ada sources.
20689 Therefore, checks can only be performed on
20690 legal Ada units. Moreover, when a unit depends semantically upon units located
20691 outside the current directory, the source search path has to be provided when
20692 calling @command{gnatcheck}, either through a specified project file or
20693 through @command{gnatcheck} switches as described below.
20694
20695 A number of rules are predefined in @command{gnatcheck} and are described
20696 later in this chapter.
20697 You can also add new rules, by modifying the @command{gnatcheck} code and
20698 rebuilding the tool. In order to add a simple rule making some local checks,
20699 a small amount of straightforward ASIS-based programming is usually needed.
20700
20701 Project support for @command{gnatcheck} is provided by the GNAT
20702 driver (see @ref{The GNAT Driver and Project Files}).
20703
20704 Invoking @command{gnatcheck} on the command line has the form:
20705
20706 @smallexample
20707 @c $ gnatcheck @ovar{switches}  @{@var{filename}@}
20708 @c       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
20709 @c       @r{[}-cargs @var{gcc_switches}@r{]} -rules @var{rule_options}
20710 @c Expanding @ovar macro inline (explanation in macro def comments)
20711 $ gnatcheck @r{[}@var{switches}@r{]}  @{@var{filename}@}
20712       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
20713       @r{[}-cargs @var{gcc_switches}@r{]} -rules @var{rule_options}
20714 @end smallexample
20715
20716 @noindent
20717 where
20718 @itemize @bullet
20719 @item
20720 @var{switches} specify the general tool options
20721
20722 @item
20723 Each @var{filename} is the name (including the extension) of a source
20724 file to process. ``Wildcards'' are allowed, and
20725 the file name may contain path information.
20726
20727 @item
20728 Each @var{arg_list_filename} is the name (including the extension) of a text
20729 file containing the names of the source files to process, separated by spaces
20730 or line breaks.
20731
20732 @item
20733 @var{gcc_switches} is a list of switches for
20734 @command{gcc}. They will be passed on to all compiler invocations made by
20735 @command{gnatcheck} to generate the ASIS trees. Here you can provide
20736 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
20737 and use the @option{-gnatec} switch to set the configuration file.
20738
20739 @item
20740 @var{rule_options} is a list of options for controlling a set of
20741 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
20742 @end itemize
20743
20744 @noindent
20745 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be
20746 supplied.
20747
20748 @menu
20749 * Format of the Report File::
20750 * General gnatcheck Switches::
20751 * gnatcheck Rule Options::
20752 * Adding the Results of Compiler Checks to gnatcheck Output::
20753 * Project-Wide Checks::
20754 * Rule exemption::
20755 * Predefined Rules::
20756 * Example of gnatcheck Usage::
20757 @end menu
20758
20759 @node Format of the Report File
20760 @section Format of the Report File
20761 @cindex Report file (for @code{gnatcheck})
20762
20763 @noindent
20764 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
20765 rule violations.
20766 It also creates a text file  that
20767 contains the complete report of the last gnatcheck run. By default this file
20768 is named named @file{^gnatcheck.out^GNATCHECK.OUT^} and it is located in the
20769 current directory; the @option{^-o^/OUTPUT^} option can be used to change the
20770 name and/or location of the report file. This report contains:
20771 @itemize @bullet
20772 @item date and time of @command{gnatcheck} run, the version of
20773 the tool that has generated this report and the full parameters
20774 of the  @command{gnatcheck} invocation;
20775 @item list of enabled rules;
20776 @item total number of detected violations;
20777 @item list of source files where rule violations have been detected;
20778 @item list of source files where no violations have been detected.
20779 @end itemize
20780
20781 @node General gnatcheck Switches
20782 @section General @command{gnatcheck} Switches
20783
20784 @noindent
20785 The following switches control the general @command{gnatcheck} behavior
20786
20787 @table @option
20788 @c !sort!
20789 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
20790 @item ^-a^/ALL^
20791 Process all units including those with read-only ALI files such as
20792 those from the GNAT Run-Time library.
20793
20794 @ifclear vms
20795 @ignore
20796 @cindex @option{-d} (@command{gnatcheck})
20797 @item -d
20798 Debug mode
20799 @end ignore
20800
20801 @cindex @option{-dd} (@command{gnatcheck})
20802 @item -dd
20803 Progress indicator mode (for use in GPS).
20804 @end ifclear
20805
20806 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
20807 @item ^-h^/HELP^
20808 List the predefined and user-defined rules. For more details see
20809 @ref{Predefined Rules}.
20810
20811 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
20812 @item ^-l^/LOCS^
20813 Use full source locations references in the report file. For a construct from
20814 a generic instantiation a full source location is a chain from the location
20815 of this construct in the generic unit to the place where this unit is
20816 instantiated.
20817
20818 @cindex @option{^-log^/LOG^} (@command{gnatcheck})
20819 @item ^-log^/LOG^
20820 Duplicate all the output sent to @file{stderr} into a log file. The log file
20821 is named @file{gnatcheck.log} and is located in the current directory.
20822
20823 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
20824 @item ^-m@i{nnnn}^/DIAGNOSTIC_LIMIT=@i{nnnn}^
20825 Maximum number of diagnostics to be sent to @file{stdout}, where @i{nnnn} is in
20826 the range 0@dots{}1000;
20827 the default value is 500. Zero means that there is no limitation on
20828 the number of diagnostic messages to be output.
20829
20830 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
20831 @item ^-q^/QUIET^
20832 Quiet mode. All the diagnostics about rule violations are placed in the
20833 @command{gnatcheck} report file only, without duplication on @file{stdout}.
20834
20835 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
20836 @item ^-s^/SHORT^
20837 Short format of the report file (no version information, no list of applied
20838 rules, no list of checked sources is included)
20839
20840 @cindex @option{^--include-file=@var{file}^/INCLUDE_FILE=@var{file}^} (@command{gnatcheck})
20841 @item ^--include-file^/INCLUDE_FILE^
20842 Append the content of the specified text file to the report file
20843
20844 @cindex @option{^-t^/TIME^} (@command{gnatcheck})
20845 @item ^-t^/TIME^
20846 Print out execution time.
20847
20848 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
20849 @item ^-v^/VERBOSE^
20850 Verbose mode; @command{gnatcheck} generates version information and then
20851 a trace of sources being processed.
20852
20853 @cindex @option{^-o ^/OUTPUT^} (@command{gnatcheck})
20854 @item ^-o ^/OUTPUT=^@var{report_file}
20855 Set name of report file file to @var{report_file} .
20856
20857 @end table
20858
20859 @node gnatcheck Rule Options
20860 @section @command{gnatcheck} Rule Options
20861
20862 @noindent
20863 The following options control the processing performed by
20864 @command{gnatcheck}.
20865
20866 @table @option
20867 @cindex @option{+ALL} (@command{gnatcheck})
20868 @item +ALL
20869 Turn all the rule checks ON.
20870
20871 @cindex @option{-ALL} (@command{gnatcheck})
20872 @item -ALL
20873 Turn all the rule checks OFF.
20874
20875 @cindex @option{+R} (@command{gnatcheck})
20876 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
20877 Turn on the check for a specified rule with the specified parameter, if any.
20878 @var{rule_id} must be the identifier of one of the currently implemented rules
20879 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
20880 are not case-sensitive. The @var{param} item must
20881 be a string representing a valid parameter(s) for the specified rule.
20882 If it contains any space characters then this string must be enclosed in
20883 quotation marks.
20884
20885 @cindex @option{-R} (@command{gnatcheck})
20886 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
20887 Turn off the check for a specified rule with the specified parameter, if any.
20888
20889 @cindex @option{-from} (@command{gnatcheck})
20890 @item -from=@var{rule_option_filename}
20891 Read the rule options from the text file @var{rule_option_filename}, referred
20892 to as a ``coding standard file'' below.
20893
20894 @end table
20895
20896 @noindent
20897 The default behavior is that all the rule checks are disabled.
20898
20899 A coding standard file is a text file that contains a set of rule options
20900 described above.
20901 @cindex Coding standard file (for @code{gnatcheck})
20902 The file may contain empty lines and Ada-style comments (comment
20903 lines and end-of-line comments). There can be several rule options on a
20904 single line (separated by a space).
20905
20906 A coding standard file may reference other coding standard files by including
20907 more @option{-from=@var{rule_option_filename}}
20908 options, each such option being replaced with the content of the
20909 corresponding coding standard file during processing. In case a
20910 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
20911 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
20912 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
20913 processing fails with an error message.
20914
20915
20916 @node Adding the Results of Compiler Checks to gnatcheck Output
20917 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
20918
20919 @noindent
20920 The @command{gnatcheck} tool can include in the generated diagnostic messages
20921 and in
20922 the report file the results of the checks performed by the compiler. Though
20923 disabled by default, this effect may be obtained by using @option{+R} with
20924 the following rule identifiers and parameters:
20925
20926 @table @option
20927 @item Restrictions
20928 To record restrictions violations (which are performed by the compiler if the
20929 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
20930 use the @code{Restrictions} rule
20931 with the same parameters as pragma
20932 @code{Restrictions} or @code{Restriction_Warnings}.
20933
20934 @item Style_Checks
20935 To record compiler style checks (@pxref{Style Checking}), use the
20936 @code{Style_Checks} rule.
20937 This rule takes a parameter in one of the following forms:
20938 @itemize
20939 @item
20940 @code{All_Checks},
20941 which enables the standard style checks corresponding to the @option{-gnatyy}
20942 GNAT style check option, or
20943
20944 @item
20945 a string with the same
20946 structure and semantics as the @code{string_LITERAL} parameter of the
20947 GNAT pragma @code{Style_Checks}
20948 (for further information about this pragma,
20949 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}).
20950 @end itemize
20951
20952 @noindent
20953 For example, the
20954 @code{+RStyle_Checks:O} rule option activates
20955 the compiler style check that corresponds to
20956 @code{-gnatyO} style check option.
20957
20958 @item Warnings
20959 To record compiler warnings (@pxref{Warning Message Control}), use the
20960 @code{Warnings} rule with a parameter that is a valid
20961 @i{static_string_expression} argument of the GNAT pragma @code{Warnings}
20962 (for further information about this pragma,
20963 @pxref{Pragma Warnings,,,gnat_rm, GNAT Reference Manual}).
20964 Note that in case of gnatcheck
20965 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
20966 all the specific warnings, but not suppresses the warning mode,
20967 and 'e' parameter, corresponding to @option{-gnatwe} that means
20968 "treat warnings as errors", does not have any effect.
20969
20970 @end table
20971
20972 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
20973 option with the corresponding restriction name as a parameter. @code{-R} is
20974 not available for @code{Style_Checks} and @code{Warnings} options, to disable
20975 warnings and style checks, use the corresponding warning and style options.
20976
20977 @node Project-Wide Checks
20978 @section Project-Wide Checks
20979 @cindex Project-wide checks (for @command{gnatcheck})
20980
20981 @noindent
20982 In order to perform checks on all units of a given project, you can use
20983 the GNAT driver along with the @option{-P} option:
20984 @smallexample
20985    gnat check -Pproj -rules -from=my_rules
20986 @end smallexample
20987
20988 @noindent
20989 If the project @code{proj} depends upon other projects, you can perform
20990 checks on the project closure using the @option{-U} option:
20991 @smallexample
20992    gnat check -Pproj -U -rules -from=my_rules
20993 @end smallexample
20994
20995 @noindent
20996 Finally, if not all the units are relevant to a particular main
20997 program in the project closure, you can perform checks for the set
20998 of units needed to create a given main program (unit closure) using
20999 the @option{-U} option followed by the name of the main unit:
21000 @smallexample
21001    gnat check -Pproj -U main -rules -from=my_rules
21002 @end smallexample
21003
21004
21005 @node Rule exemption
21006 @section Rule exemption
21007 @cindex Rule exemption (for @command{gnatcheck})
21008
21009 @noindent
21010 One of the most useful applications of @command{gnatcheck} is to
21011 automate the enforcement of project-specific coding standards,
21012 for example in safety-critical systems where particular features
21013 must be restricted in order to simplify the certification effort.
21014 However, it may sometimes be appropriate to violate a coding standard rule,
21015 and in such cases the rationale for the violation should be provided
21016 in the source program itself so that the individuals
21017 reviewing or maintaining the program can immediately understand the intent.
21018
21019 The @command{gnatcheck} tool supports this practice with the notion of
21020 a ``rule exemption'' covering a specific source code section. Normally
21021 rule violation messages are issued both on @file{stderr}
21022 and in a report file. In contrast, exempted violations are not listed on
21023 @file{stderr}; thus users invoking @command{gnatcheck} interactively
21024 (e.g. in its GPS interface) do not need to pay attention to known and
21025 justified violations. However, exempted violations along with their
21026 justification are documented in a special section of the report file that
21027 @command{gnatcheck} generates.
21028
21029 @menu
21030 * Using pragma Annotate to Control Rule Exemption::
21031 * gnatcheck Annotations Rules::
21032 @end menu
21033
21034 @node Using pragma Annotate to Control Rule Exemption
21035 @subsection Using pragma @code{Annotate} to Control Rule Exemption
21036 @cindex Using pragma Annotate to control rule exemption
21037
21038 @noindent
21039 Rule exemption is controlled by pragma @code{Annotate} when its first
21040 argument is ``gnatcheck''. The syntax of @command{gnatcheck}'s
21041 exemption control annotations is as follows:
21042
21043 @smallexample @c ada
21044 @group
21045 pragma Annotate (gnatcheck, @i{exemption_control}, @i{Rule_Name}, [@i{justification}]);
21046
21047 @i{exemption_control} ::= Exempt_On | Exempt_Off
21048
21049 @i{Rule_Name}         ::= string_literal
21050
21051 @i{justification}     ::= string_literal
21052 @end group
21053 @end smallexample
21054
21055 @noindent
21056 When a @command{gnatcheck} annotation has more then four arguments,
21057 @command{gnatcheck} issues a warning and ignores the additional arguments.
21058 If the additional arguments do not follow the syntax above,
21059 @command{gnatcheck} emits a warning and ignores the annotation.
21060
21061 The @i{@code{Rule_Name}} argument should be the name of some existing
21062 @command{gnatcheck} rule.
21063 Otherwise a warning message is generated and the pragma is
21064 ignored. If @code{Rule_Name} denotes a rule that is not activated by the given
21065 @command{gnatcheck} call, the pragma is ignored and no warning is issued.
21066
21067 A source code section where an exemption is active for a given rule is
21068 delimited by an @code{exempt_on} and @code{exempt_off} annotation pair:
21069
21070 @smallexample @c ada
21071 pragma Annotate (gnatcheck, Exempt_On, Rule_Name, "justification");
21072 -- source code section
21073 pragma Annotate (gnatcheck, Exempt_Off, Rule_Name);
21074 @end smallexample
21075
21076
21077 @node gnatcheck Annotations Rules
21078 @subsection @command{gnatcheck} Annotations Rules
21079 @cindex @command{gnatcheck} annotations rules
21080
21081 @itemize @bullet
21082
21083 @item
21084 An ``Exempt_Off'' annotation can only appear after a corresponding
21085 ``Exempt_On'' annotation.
21086
21087 @item
21088 Exempted source code sections are only based on the source location of the
21089 annotations. Any source construct between the two
21090 annotations is part of the exempted source code section.
21091
21092 @item
21093 Exempted source code sections for different rules are independent. They can
21094 be nested or intersect with one another without limitation.
21095 Creating nested or intersecting source code sections for the same rule is
21096 not allowed.
21097
21098 @item
21099 Malformed exempted source code sections are reported by a warning, and
21100 the corresponding rule exemptions are ignored.
21101
21102 @item
21103 When an exempted source code section does not contain at least one violation
21104 of the exempted rule, a warning is emitted on @file{stderr}.
21105
21106 @item
21107 If an ``Exempt_On'' annotation pragma does not have a matching
21108 ``Exempt_Off'' annotation pragma in the same compilation unit, then the
21109 exemption for the given rule is ignored and a warning is issued.
21110 @end itemize
21111
21112
21113 @node Predefined Rules
21114 @section Predefined Rules
21115 @cindex Predefined rules (for @command{gnatcheck})
21116
21117 @ignore
21118 @c (Jan 2007) Since the global rules are still under development and are not
21119 @c documented, there is no point in explaining the difference between
21120 @c global and local rules
21121 @noindent
21122 A rule in @command{gnatcheck} is either local or global.
21123 A @emph{local rule} is a rule that applies to a well-defined section
21124 of a program and that can be checked by analyzing only this section.
21125 A @emph{global rule} requires analysis of some global properties of the
21126 whole program (mostly related to the program call graph).
21127 As of @value{NOW}, the implementation of global rules should be
21128 considered to be at a preliminary stage. You can use the
21129 @option{+GLOBAL} option to enable all the global rules, and the
21130 @option{-GLOBAL} rule option to disable all the global rules.
21131
21132 All the global rules in the list below are
21133 so indicated by marking them ``GLOBAL''.
21134 This +GLOBAL and -GLOBAL options are not
21135 included in the list of gnatcheck options above, because at the moment they
21136 are considered as a temporary debug options.
21137
21138 @command{gnatcheck} performs rule checks for generic
21139 instances only for global rules.  This limitation may be relaxed in a later
21140 release.
21141 @end ignore
21142
21143 @noindent
21144 The following subsections document the rules implemented in
21145 @command{gnatcheck}.
21146 The subsection title is the same as the rule identifier, which may be
21147 used as a parameter of the @option{+R} or @option{-R} options.
21148
21149
21150 @menu
21151 * Abstract_Type_Declarations::
21152 * Anonymous_Arrays::
21153 * Anonymous_Subtypes::
21154 * Blocks::
21155 * Boolean_Relational_Operators::
21156 @ignore
21157 * Ceiling_Violations::
21158 @end ignore
21159 * Complex_Inlined_Subprograms::
21160 * Controlled_Type_Declarations::
21161 * Declarations_In_Blocks::
21162 * Deep_Inheritance_Hierarchies::
21163 * Deeply_Nested_Generics::
21164 * Deeply_Nested_Inlining::
21165 @ignore
21166 * Deeply_Nested_Local_Inlining::
21167 @end ignore
21168 * Default_Parameters::
21169 * Direct_Calls_To_Primitives::
21170 * Discriminated_Records::
21171 * Enumeration_Ranges_In_CASE_Statements::
21172 * Exceptions_As_Control_Flow::
21173 * Exits_From_Conditional_Loops::
21174 * EXIT_Statements_With_No_Loop_Name::
21175 * Expanded_Loop_Exit_Names::
21176 * Explicit_Full_Discrete_Ranges::
21177 * Float_Equality_Checks::
21178 * Forbidden_Attributes::
21179 * Forbidden_Pragmas::
21180 * Function_Style_Procedures::
21181 * Generics_In_Subprograms::
21182 * GOTO_Statements::
21183 * Implicit_IN_Mode_Parameters::
21184 * Implicit_SMALL_For_Fixed_Point_Types::
21185 * Improperly_Located_Instantiations::
21186 * Improper_Returns::
21187 * Library_Level_Subprograms::
21188 * Local_Packages::
21189 @ignore
21190 * Improperly_Called_Protected_Entries::
21191 @end ignore
21192 * Metrics::
21193 * Misnamed_Controlling_Parameters::
21194 * Misnamed_Identifiers::
21195 * Multiple_Entries_In_Protected_Definitions::
21196 * Name_Clashes::
21197 * Non_Qualified_Aggregates::
21198 * Non_Short_Circuit_Operators::
21199 * Non_SPARK_Attributes::
21200 * Non_Tagged_Derived_Types::
21201 * Non_Visible_Exceptions::
21202 * Numeric_Literals::
21203 * OTHERS_In_Aggregates::
21204 * OTHERS_In_CASE_Statements::
21205 * OTHERS_In_Exception_Handlers::
21206 * Outer_Loop_Exits::
21207 * Overloaded_Operators::
21208 * Overly_Nested_Control_Structures::
21209 * Parameters_Out_Of_Order::
21210 * Positional_Actuals_For_Defaulted_Generic_Parameters::
21211 * Positional_Actuals_For_Defaulted_Parameters::
21212 * Positional_Components::
21213 * Positional_Generic_Parameters::
21214 * Positional_Parameters::
21215 * Predefined_Numeric_Types::
21216 * Raising_External_Exceptions::
21217 * Raising_Predefined_Exceptions::
21218 * Separate_Numeric_Error_Handlers::
21219 @ignore
21220 * Recursion::
21221 * Side_Effect_Functions::
21222 @end ignore
21223 * Slices::
21224 * Too_Many_Parents::
21225 * Unassigned_OUT_Parameters::
21226 * Uncommented_BEGIN_In_Package_Bodies::
21227 * Unconditional_Exits::
21228 * Unconstrained_Array_Returns::
21229 * Universal_Ranges::
21230 * Unnamed_Blocks_And_Loops::
21231 @ignore
21232 * Unused_Subprograms::
21233 @end ignore
21234 * USE_PACKAGE_Clauses::
21235 * Visible_Components::
21236 * Volatile_Objects_Without_Address_Clauses::
21237 @end menu
21238
21239
21240 @node Abstract_Type_Declarations
21241 @subsection @code{Abstract_Type_Declarations}
21242 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
21243
21244 @noindent
21245 Flag all declarations of abstract types. For an abstract private
21246 type, both the private and full type declarations are flagged.
21247
21248 This rule has no parameters.
21249
21250
21251 @node Anonymous_Arrays
21252 @subsection @code{Anonymous_Arrays}
21253 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
21254
21255 @noindent
21256 Flag all anonymous array type definitions (by Ada semantics these can only
21257 occur in object declarations).
21258
21259 This rule has no parameters.
21260
21261 @node Anonymous_Subtypes
21262 @subsection @code{Anonymous_Subtypes}
21263 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
21264
21265 @noindent
21266 Flag all uses of anonymous subtypes (except cases when subtype indication
21267 is a part of a record component definition, and this subtype indication
21268 depends on a discriminant). A use of an anonymous subtype is
21269 any instance of a subtype indication with a constraint, other than one
21270 that occurs immediately within a subtype declaration. Any use of a range
21271 other than as a constraint used immediately within a subtype declaration
21272 is considered as an anonymous subtype.
21273
21274 An effect of this rule is that @code{for} loops such as the following are
21275 flagged (since @code{1..N} is formally a ``range''):
21276
21277 @smallexample @c ada
21278 for I in 1 .. N loop
21279    @dots{}
21280 end loop;
21281 @end smallexample
21282
21283 @noindent
21284 Declaring an explicit subtype solves the problem:
21285
21286 @smallexample @c ada
21287 subtype S is Integer range 1..N;
21288 @dots{}
21289 for I in S loop
21290    @dots{}
21291 end loop;
21292 @end smallexample
21293
21294 @noindent
21295 This rule has no parameters.
21296
21297 @node Blocks
21298 @subsection @code{Blocks}
21299 @cindex @code{Blocks} rule (for @command{gnatcheck})
21300
21301 @noindent
21302 Flag each block statement.
21303
21304 This rule has no parameters.
21305
21306 @node Boolean_Relational_Operators
21307 @subsection @code{Boolean_Relational_Operators}
21308 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
21309
21310 @noindent
21311 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
21312 ``>='', ``='' and ``/='') for the predefined Boolean type.
21313 (This rule is useful in enforcing the SPARK language restrictions.)
21314
21315 Calls to predefined relational operators of any type derived from
21316 @code{Standard.Boolean} are not detected.  Calls to user-defined functions
21317 with these designators, and uses of operators that are renamings
21318 of the predefined relational operators for @code{Standard.Boolean},
21319 are likewise not detected.
21320
21321 This rule has no parameters.
21322
21323 @ignore
21324 @node Ceiling_Violations
21325 @subsection @code{Ceiling5_Violations} (under construction, GLOBAL)
21326 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
21327
21328 @noindent
21329 Flag invocations of a protected operation by a task whose priority exceeds
21330 the protected object's ceiling.
21331
21332 As of @value{NOW}, this rule has the following limitations:
21333
21334 @itemize @bullet
21335
21336 @item
21337  We consider only pragmas Priority and Interrupt_Priority as means to define
21338   a task/protected operation priority. We do not consider the effect of using
21339   Ada.Dynamic_Priorities.Set_Priority procedure;
21340
21341 @item
21342  We consider only base task priorities, and no priority inheritance. That is,
21343   we do not make a difference between calls issued during task activation and
21344   execution of the sequence of statements from task body;
21345
21346 @item
21347  Any situation when the priority of protected operation caller is set by a
21348   dynamic expression (that is, the corresponding Priority or
21349   Interrupt_Priority pragma has a non-static expression as an argument) we
21350   treat as a priority inconsistency (and, therefore, detect this situation).
21351 @end itemize
21352
21353 @noindent
21354 At the moment the notion of the main subprogram is not implemented in
21355 gnatcheck, so any pragma Priority in a library level subprogram body (in case
21356 if this subprogram can be a main subprogram of a partition) changes the
21357 priority of an environment task. So if we have more then one such pragma in
21358 the set of processed sources, the pragma that is processed last, defines the
21359 priority of an environment task.
21360
21361 This rule has no parameters.
21362 @end ignore
21363
21364 @node Controlled_Type_Declarations
21365 @subsection @code{Controlled_Type_Declarations}
21366 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
21367
21368 @noindent
21369 Flag all declarations of controlled types. A declaration of a private type
21370 is flagged if its full declaration declares a controlled type. A declaration
21371 of a derived type is flagged if its ancestor type is controlled. Subtype
21372 declarations are not checked. A declaration of a type that itself is not a
21373 descendant of a type declared in @code{Ada.Finalization} but has a controlled
21374 component is not checked.
21375
21376 This rule has no parameters.
21377
21378
21379 @node Complex_Inlined_Subprograms
21380 @subsection @code{Complex_Inlined_Subprograms}
21381 @cindex @code{Complex_Inlined_Subprograms} rule (for @command{gnatcheck})
21382
21383 @noindent
21384 Flags a subprogram (or generic subprogram) if
21385 pragma Inline is applied to the subprogram and at least one of the following
21386 conditions is met:
21387
21388 @itemize @bullet
21389 @item
21390 it contains at least one complex declaration such as a subprogram body,
21391 package, task, protected declaration, or a generic instantiation
21392 (except instantiation of @code{Ada.Unchecked_Conversion});
21393
21394 @item
21395 it contains at least one complex statement such as a loop, a case
21396 or a if statement, or a short circuit control form;
21397
21398 @item
21399 the number of statements exceeds
21400 a value specified by the @option{N} rule parameter;
21401 @end itemize
21402
21403 @noindent
21404 This rule has the following (mandatory) parameter for the @option{+R} option:
21405
21406 @table @emph
21407 @item N
21408 Positive integer specifying the maximum allowed total number of statements
21409 in the subprogram body.
21410 @end table
21411
21412
21413 @node Declarations_In_Blocks
21414 @subsection @code{Declarations_In_Blocks}
21415 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
21416
21417 @noindent
21418 Flag all block statements containing local declarations. A @code{declare}
21419 block with an empty @i{declarative_part} or with a @i{declarative part}
21420 containing only pragmas and/or @code{use} clauses is not flagged.
21421
21422 This rule has no parameters.
21423
21424
21425 @node Deep_Inheritance_Hierarchies
21426 @subsection @code{Deep_Inheritance_Hierarchies}
21427 @cindex @code{Deep_Inheritance_Hierarchies} rule (for @command{gnatcheck})
21428
21429 @noindent
21430 Flags a tagged derived type declaration or an interface type declaration if
21431 its depth (in its inheritance
21432 hierarchy) exceeds the value specified by the @option{N} rule parameter.
21433
21434 The inheritance depth of a tagged type or interface type is defined as 0 for
21435 a type  with no parent and no progenitor, and otherwise as 1 + max of the
21436 depths of the immediate parent and immediate progenitors.
21437
21438 This rule does not flag private extension
21439 declarations. In the case of a private extension, the corresponding full
21440 declaration is checked.
21441
21442 This rule has the following (mandatory) parameter for the @option{+R} option:
21443
21444 @table @emph
21445 @item N
21446 Integer not less than -1 specifying the maximal allowed depth of any inheritance
21447 hierarchy. If the rule parameter is set to -1, the rule flags all the declarations
21448 of tagged and interface types.
21449 @end table
21450
21451
21452 @node Deeply_Nested_Generics
21453 @subsection @code{Deeply_Nested_Generics}
21454 @cindex @code{Deeply_Nested_Generics} rule (for @command{gnatcheck})
21455
21456 @noindent
21457 Flags a generic declaration nested in another generic declaration if
21458 the nesting level of the inner generic exceeds
21459 a value specified by the @option{N} rule parameter.
21460 The nesting level is the number of generic declaratons that enclose the given
21461 (generic) declaration. Formal packages are not flagged by this rule.
21462
21463 This rule has the following (mandatory) parameters for the @option{+R} option:
21464
21465 @table @emph
21466 @item N
21467 Positive integer specifying the maximal allowed nesting level
21468 for a generic declaration.
21469 @end table
21470
21471 @node Deeply_Nested_Inlining
21472 @subsection @code{Deeply_Nested_Inlining}
21473 @cindex @code{Deeply_Nested_Inlining} rule (for @command{gnatcheck})
21474
21475 @noindent
21476 Flags a subprogram (or generic subprogram) if
21477 pragma Inline has been applied to the subprogram but the subprogram
21478 calls to another inlined subprogram that results in nested inlining
21479 with nesting depth exceeding the value specified by the
21480 @option{N} rule parameter.
21481
21482 This rule requires the global analysis of all the compilation units that
21483 are @command{gnatcheck} arguments; such analysis may affect the tool's
21484 performance.
21485
21486 This rule has the following (mandatory) parameter for the @option{+R} option:
21487
21488 @table @emph
21489 @item N
21490 Positive integer specifying the maximal allowed level of nested inlining.
21491 @end table
21492
21493
21494 @ignore
21495 @node Deeply_Nested_Local_Inlining
21496 @subsection @code{Deeply_Nested_Local_Inlining}
21497 @cindex @code{Deeply_Nested_Local_Inlining} rule (for @command{gnatcheck})
21498
21499 @noindent
21500 Flags a subprogram body if a pragma @code{Inline} is applied to the
21501 corresponding subprogram (or generic subprogram) and the body contains a call
21502 to another inlined subprogram that results in nested inlining with nesting
21503 depth more then a value specified by the @option{N} rule parameter.
21504 This rule is similar to @code{Deeply_Nested_Inlining} rule, but it
21505 assumes that calls to subprograms in
21506 with'ed units are not inlided, so all the analysis of the depth of inlining is
21507 limited by the compilation unit where the subprogram body is located and the
21508 units it depends semantically upon. Such analysis may be usefull for the case
21509 when neiter @option{-gnatn} nor @option{-gnatN} option is used when building
21510 the executable.
21511
21512 This rule has the following (mandatory) parameters for the @option{+R} option:
21513
21514 @table @emph
21515 @item N
21516 Positive integer specifying the maximal allowed level of nested inlining.
21517 @end table
21518
21519 @end ignore
21520
21521 @node Default_Parameters
21522 @subsection @code{Default_Parameters}
21523 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
21524
21525 @noindent
21526 Flag all default expressions for subprogram parameters. Parameter
21527 declarations of formal and generic subprograms are also checked.
21528
21529 This rule has no parameters.
21530
21531
21532 @node Direct_Calls_To_Primitives
21533 @subsection @code{Direct_Calls_To_Primitives}
21534 @cindex @code{Direct_Calls_To_Primitives} rule (for @command{gnatcheck})
21535
21536 @noindent
21537 Flags any non-dispatching call to a dispatching primitive operation, except
21538 for the common idiom where a primitive subprogram for a tagged type
21539 directly calls the same primitive subprogram of the type's immediate ancestor.
21540
21541 This rule has no parameters.
21542
21543
21544 @node Discriminated_Records
21545 @subsection @code{Discriminated_Records}
21546 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
21547
21548 @noindent
21549 Flag all declarations of record types with discriminants. Only the
21550 declarations of record and record extension types are checked. Incomplete,
21551 formal, private, derived and private extension type declarations are not
21552 checked. Task and protected type declarations also are not checked.
21553
21554 This rule has no parameters.
21555
21556
21557 @node Enumeration_Ranges_In_CASE_Statements
21558 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
21559 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
21560
21561 @noindent
21562 Flag each use of a range of enumeration literals as a choice in a
21563 @code{case} statement.
21564 All forms for specifying a range (explicit ranges
21565 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
21566 An enumeration range is
21567 flagged even if contains exactly one enumeration value or no values at all. A
21568 type derived from an enumeration type is considered as an enumeration type.
21569
21570 This rule helps prevent maintenance problems arising from adding an
21571 enumeration value to a type and having it implicitly handled by an existing
21572 @code{case} statement with an enumeration range that includes the new literal.
21573
21574 This rule has no parameters.
21575
21576
21577 @node Exceptions_As_Control_Flow
21578 @subsection @code{Exceptions_As_Control_Flow}
21579 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
21580
21581 @noindent
21582 Flag each place where an exception is explicitly raised and handled in the
21583 same subprogram body. A @code{raise} statement in an exception handler,
21584 package body, task body or entry body is not flagged.
21585
21586 The rule has no parameters.
21587
21588 @node Exits_From_Conditional_Loops
21589 @subsection @code{Exits_From_Conditional_Loops}
21590 @cindex @code{Exits_From_Conditional_Loops} (for @command{gnatcheck})
21591
21592 @noindent
21593 Flag any exit statement if it transfers the control out of a @code{for} loop
21594 or a @code{while} loop. This includes cases when the @code{exit} statement
21595 applies to a @code{FOR} or @code{while} loop, and cases when it is enclosed
21596 in some @code{for} or @code{while} loop, but transfers the control from some
21597 outer (inconditional) @code{loop} statement.
21598
21599 The rule has no parameters.
21600
21601
21602 @node EXIT_Statements_With_No_Loop_Name
21603 @subsection @code{EXIT_Statements_With_No_Loop_Name}
21604 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
21605
21606 @noindent
21607 Flag each @code{exit} statement that does not specify the name of the loop
21608 being exited.
21609
21610 The rule has no parameters.
21611
21612
21613 @node Expanded_Loop_Exit_Names
21614 @subsection @code{Expanded_Loop_Exit_Names}
21615 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
21616
21617 @noindent
21618 Flag all expanded loop names in @code{exit} statements.
21619
21620 This rule has no parameters.
21621
21622 @node Explicit_Full_Discrete_Ranges
21623 @subsection @code{Explicit_Full_Discrete_Ranges}
21624 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
21625
21626 @noindent
21627 Flag each discrete range that has the form @code{A'First .. A'Last}.
21628
21629 This rule has no parameters.
21630
21631 @node Float_Equality_Checks
21632 @subsection @code{Float_Equality_Checks}
21633 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
21634
21635 @noindent
21636 Flag all calls to the predefined equality operations for floating-point types.
21637 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
21638 User-defined equality operations are not flagged, nor are ``@code{=}''
21639 and ``@code{/=}'' operations for fixed-point types.
21640
21641 This rule has no parameters.
21642
21643
21644 @node Forbidden_Attributes
21645 @subsection @code{Forbidden_Attributes}
21646 @cindex @code{Forbidden_Attributes} rule (for @command{gnatcheck})
21647
21648 @noindent
21649 Flag each use of the specified attributes. The attributes to be detected are
21650 named in the rule's parameters.
21651
21652 This rule has the following parameters:
21653
21654 @itemize @bullet
21655 @item For the @option{+R} option
21656
21657 @table @asis
21658 @item @emph{Attribute_Designator}
21659 Adds the specified attribute to the set of attributes to be detected and sets
21660 the detection checks for all the specified attributes ON.
21661 If @emph{Attribute_Designator}
21662 does not denote any attribute defined in the Ada standard
21663 or in
21664 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
21665 Manual}, it is treated as the name of unknown attribute.
21666
21667 @item @code{GNAT}
21668 All the GNAT-specific attributes are detected; this sets
21669 the detection checks for all the specified attributes ON.
21670
21671 @item @code{ALL}
21672 All attributes are detected; this sets the rule ON.
21673 @end table
21674
21675 @item For the @option{-R} option
21676 @table @asis
21677 @item @emph{Attribute_Designator}
21678 Removes the specified attribute from the set of attributes to be
21679 detected without affecting detection checks for
21680 other attributes. If @emph{Attribute_Designator} does not correspond to any
21681 attribute defined in the Ada standard or in
21682 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference Manual},
21683 this option is treated as turning OFF detection of all unknown attributes.
21684
21685 @item GNAT
21686 Turn OFF detection of all GNAT-specific attributes
21687
21688 @item ALL
21689 Clear the list of the attributes to be detected and
21690 turn the rule OFF.
21691 @end table
21692 @end itemize
21693
21694 @noindent
21695 Parameters are not case sensitive. If @emph{Attribute_Designator} does not
21696 have the syntax of an Ada identifier and therefore can not be considered as a
21697 (part of an) attribute designator, a diagnostic message is generated and the
21698 corresponding parameter is ignored. (If an attribute allows a static
21699 expression to be a part of the attribute designator, this expression is
21700 ignored by this rule.)
21701
21702 When more then one parameter is given in the same rule option, the parameters
21703 must be separated by commas.
21704
21705 If more then one option for this rule is specified for the gnatcheck call, a
21706 new option overrides the previous one(s).
21707
21708 The @option{+R} option with no parameters turns the rule ON, with the set of
21709 attributes to be detected defined by the previous rule options.
21710 (By default this set is empty, so if the only option specified for the rule is
21711 @option{+RForbidden_Attributes} (with
21712 no parameter), then the rule is enabled, but it does not detect anything).
21713 The @option{-R} option with no parameter turns the rule OFF, but it does not
21714 affect the set of attributes to be detected.
21715
21716
21717 @node Forbidden_Pragmas
21718 @subsection @code{Forbidden_Pragmas}
21719 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
21720
21721 @noindent
21722 Flag each use of the specified pragmas.  The pragmas to be detected
21723 are named in the rule's  parameters.
21724
21725 This rule has the following parameters:
21726
21727 @itemize @bullet
21728 @item For the @option{+R} option
21729
21730 @table @asis
21731 @item @emph{Pragma_Name}
21732 Adds the specified pragma to the set of pragmas to be
21733 checked and sets the checks for all the specified pragmas
21734 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
21735 does not correspond to any pragma name defined in the Ada
21736 standard or to the name of a GNAT-specific pragma defined
21737 in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21738 Manual}, it is treated as the name of unknown pragma.
21739
21740 @item @code{GNAT}
21741 All the GNAT-specific pragmas are detected; this sets
21742 the checks for all the specified pragmas ON.
21743
21744 @item @code{ALL}
21745 All pragmas are detected; this sets the rule ON.
21746 @end table
21747
21748 @item For the @option{-R} option
21749 @table @asis
21750 @item @emph{Pragma_Name}
21751 Removes the specified pragma from the set of pragmas to be
21752 checked without affecting checks for
21753 other pragmas. @emph{Pragma_Name} is treated as a name
21754 of a pragma. If it does not correspond to any pragma
21755 defined in the Ada standard or to any name defined in
21756 @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
21757 this option is treated as turning OFF detection of all unknown pragmas.
21758
21759 @item GNAT
21760 Turn OFF detection of all GNAT-specific pragmas
21761
21762 @item ALL
21763 Clear the list of the pragmas to be detected and
21764 turn the rule OFF.
21765 @end table
21766 @end itemize
21767
21768 @noindent
21769 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
21770 the syntax of an Ada identifier and therefore can not be considered
21771 as a pragma name, a diagnostic message is generated and the corresponding
21772 parameter is ignored.
21773
21774 When more then one parameter is given in the same rule option, the parameters
21775 must be separated by a comma.
21776
21777 If more then one option for this rule is specified for the @command{gnatcheck}
21778 call, a new option overrides the previous one(s).
21779
21780 The @option{+R} option with no parameters turns the rule ON with the set of
21781 pragmas to be detected defined by the previous rule options.
21782 (By default this set is empty, so if the only option specified for the rule is
21783 @option{+RForbidden_Pragmas} (with
21784 no parameter), then the rule is enabled, but it does not detect anything).
21785 The @option{-R} option with no parameter turns the rule OFF, but it does not
21786 affect the set of pragmas to be detected.
21787
21788
21789
21790
21791 @node Function_Style_Procedures
21792 @subsection @code{Function_Style_Procedures}
21793 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
21794
21795 @noindent
21796 Flag each procedure that can be rewritten as a function. A procedure can be
21797 converted into a function if it has exactly one parameter of mode @code{out}
21798 and no parameters of mode @code{in out}. Procedure declarations,
21799 formal procedure declarations, and generic procedure declarations are always
21800 checked. Procedure
21801 bodies and body stubs are flagged only if they do not have corresponding
21802 separate declarations. Procedure renamings and procedure instantiations are
21803 not flagged.
21804
21805 If a procedure can be rewritten as a function, but its @code{out} parameter is
21806 of a limited type, it is not flagged.
21807
21808 Protected procedures are not flagged. Null procedures also are not flagged.
21809
21810 This rule has no parameters.
21811
21812
21813 @node Generics_In_Subprograms
21814 @subsection @code{Generics_In_Subprograms}
21815 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
21816
21817 @noindent
21818 Flag each declaration of a generic unit in a subprogram. Generic
21819 declarations in the bodies of generic subprograms are also flagged.
21820 A generic unit nested in another generic unit is not flagged.
21821 If a generic unit is
21822 declared in a local package that is declared in a subprogram body, the
21823 generic unit is flagged.
21824
21825 This rule has no parameters.
21826
21827
21828 @node GOTO_Statements
21829 @subsection @code{GOTO_Statements}
21830 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
21831
21832 @noindent
21833 Flag each occurrence of a @code{goto} statement.
21834
21835 This rule has no parameters.
21836
21837
21838 @node Implicit_IN_Mode_Parameters
21839 @subsection @code{Implicit_IN_Mode_Parameters}
21840 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
21841
21842 @noindent
21843 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
21844 Note that @code{access} parameters, although they technically behave
21845 like @code{in} parameters, are not flagged.
21846
21847 This rule has no parameters.
21848
21849
21850 @node Implicit_SMALL_For_Fixed_Point_Types
21851 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
21852 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
21853
21854 @noindent
21855 Flag each fixed point type declaration that lacks an explicit
21856 representation  clause to define its @code{'Small} value.
21857 Since @code{'Small} can be  defined only for ordinary fixed point types,
21858 decimal fixed point type declarations are not checked.
21859
21860 This rule has no parameters.
21861
21862
21863 @node Improperly_Located_Instantiations
21864 @subsection @code{Improperly_Located_Instantiations}
21865 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
21866
21867 @noindent
21868 Flag all generic instantiations in library-level package specs
21869 (including library generic packages) and in all subprogram bodies.
21870
21871 Instantiations in task and entry bodies are not flagged. Instantiations in the
21872 bodies of protected subprograms are flagged.
21873
21874 This rule has no parameters.
21875
21876
21877
21878 @node Improper_Returns
21879 @subsection @code{Improper_Returns}
21880 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
21881
21882 @noindent
21883 Flag each explicit @code{return} statement in procedures, and
21884 multiple @code{return} statements in functions.
21885 Diagnostic messages are generated for all @code{return} statements
21886 in a procedure (thus each procedure must be written so that it
21887 returns implicitly at the end of its statement part),
21888 and for all @code{return} statements in a function after the first one.
21889 This rule supports the stylistic convention that each subprogram
21890 should have no more than one point of normal return.
21891
21892 This rule has no parameters.
21893
21894
21895 @node Library_Level_Subprograms
21896 @subsection @code{Library_Level_Subprograms}
21897 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
21898
21899 @noindent
21900 Flag all library-level subprograms (including generic subprogram instantiations).
21901
21902 This rule has no parameters.
21903
21904
21905 @node Local_Packages
21906 @subsection @code{Local_Packages}
21907 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
21908
21909 @noindent
21910 Flag all local packages declared in package and generic package
21911 specs.
21912 Local packages in bodies are not flagged.
21913
21914 This rule has no parameters.
21915
21916 @ignore
21917 @node Improperly_Called_Protected_Entries
21918 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
21919 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
21920
21921 @noindent
21922 Flag each protected entry that can be called from more than one task.
21923
21924 This rule has no parameters.
21925 @end ignore
21926
21927 @node Metrics
21928 @subsection @code{Metrics}
21929 @cindex @code{Metrics} rule (for @command{gnatcheck})
21930
21931 @noindent
21932 There is a set of checks based on computing a metric value and comparing the
21933 result with the specified upper (or lower, depending on a specific metric)
21934 value specified for a given metric. A construct is flagged if a given metric
21935 is applicable (can be computed) for it and the computed value is greater
21936 then (lover then) the specified upper (lower) bound.
21937
21938 The name of any metric-based rule consists of the prefix @code{Metrics_}
21939 followed by the name of the corresponding metric (see the table below).
21940 For @option{+R} option, each metric-based rule has a numeric parameter
21941 specifying the bound (integer or real, depending on a metric), @option{-R}
21942 option for metric rules does not have a parameter.
21943
21944 The following table shows the metric names for that the corresponding
21945 metrics-based checks are supported by gnatcheck, including the
21946 constraint that must be satisfied by the bound that is specified for the check
21947 and what bound - upper (U) or lower (L) - should be specified.
21948
21949 @multitable {@code{Cyclomatic_Complexity}}{Cyclomatic complexity}{Positive integer}
21950 @ifnothtml
21951 @headitem Check Name @tab Description @tab Bounds Value
21952 @end ifnothtml
21953 @ifhtml
21954 @item @b{Check Name} @tab @b{Description} @tab @b{Bounds Value}
21955 @end ifhtml
21956 @c Above conditional code is workaround to bug in texi2html (Feb 2008)
21957 @item @code{Essential_Complexity} @tab Essential complexity @tab Positive integer (U)
21958 @item @code{Cyclomatic_Complexity} @tab Cyclomatic complexity @tab Positive integer (U)
21959 @item @code{LSLOC} @tab Logical Source Lines of Code @tab Positive integer (U)
21960 @end multitable
21961
21962 @noindent
21963 The meaning and the computed values for all these metrics are exactly
21964 the same as for the corresponding metrics in @command{gnatmetric}.
21965
21966 @emph{Example:} the rule
21967 @smallexample
21968 +RMetrics_Cyclomatic_Complexity : 7
21969 @end smallexample
21970 @noindent
21971 means that all bodies with cyclomatic complexity exceeding 7 will be flagged.
21972
21973 To turn OFF the check for cyclomatic complexity metric, use the following option:
21974 @smallexample
21975 -RMetrics_Cyclomatic_Complexity
21976 @end smallexample
21977
21978
21979 @node Misnamed_Controlling_Parameters
21980 @subsection @code{Misnamed_Controlling_Parameters}
21981 @cindex @code{Misnamed_Controlling_Parameters} rule (for @command{gnatcheck})
21982
21983 @noindent
21984 Flags a declaration of a dispatching operation, if the first parameter is
21985 not a controlling one and its name is not @code{This} (the check for
21986 parameter name is not case-sensitive). Declarations of dispatching functions
21987 with controlling result and no controlling parameter are never flagged.
21988
21989 A subprogram body declaration, subprogram renaming declaration or subprogram
21990 body stub is flagged only if it is not a completion of a prior subprogram
21991 declaration.
21992
21993 This rule has no parameters.
21994
21995
21996
21997 @node Misnamed_Identifiers
21998 @subsection @code{Misnamed_Identifiers}
21999 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
22000
22001 @noindent
22002 Flag the declaration of each identifier that does not have a suffix
22003 corresponding to the kind of entity being declared.
22004 The following declarations are checked:
22005
22006 @itemize @bullet
22007 @item
22008 type declarations
22009
22010 @item
22011 subtype declarations
22012
22013 @item
22014 constant declarations (but not number declarations)
22015
22016 @item
22017 package renaming declarations (but not generic package renaming
22018 declarations)
22019 @end itemize
22020
22021 @noindent
22022 This rule may have parameters. When used without parameters, the rule enforces
22023 the following checks:
22024
22025 @itemize @bullet
22026 @item
22027 type-defining names end with @code{_T}, unless the type is an access type,
22028 in which case the suffix must be @code{_A}
22029 @item
22030 constant names end with @code{_C}
22031 @item
22032 names defining package renamings end with @code{_R}
22033 @end itemize
22034
22035 @noindent
22036 Defining identifiers from incomplete type declarations are never flagged.
22037
22038 For a private type declaration (including private extensions), the defining
22039 identifier from the private type declaration is checked against the type
22040 suffix (even if the corresponding full declaration is an access type
22041 declaration), and the defining identifier from the corresponding full type
22042 declaration is not checked.
22043
22044 @noindent
22045 For a deferred constant, the defining name in the corresponding full constant
22046 declaration is not checked.
22047
22048 Defining names of formal types are not checked.
22049
22050 The rule may have the following parameters:
22051
22052 @itemize @bullet
22053 @item
22054 For the @option{+R} option:
22055 @table @code
22056 @item Default
22057 Sets the default listed above for all the names to be checked.
22058
22059 @item Type_Suffix=@emph{string}
22060 Specifies the suffix for a type name.
22061
22062 @item Access_Suffix=@emph{string}
22063 Specifies the suffix for an access type name. If
22064 this parameter is set, it overrides for access
22065 types the suffix set by the @code{Type_Suffix} parameter.
22066 For access types, @emph{string} may have the following format:
22067 @emph{suffix1(suffix2)}. That means that an access type name
22068 should have the @emph{suffix1} suffix except for the case when
22069 the designated type is also an access type, in this case the
22070 type name should have the @emph{suffix1 & suffix2} suffix.
22071
22072 @item Class_Access_Suffix=@emph{string}
22073 Specifies the suffix for the name of an access type that points to some class-wide
22074 type. If this parameter is set, it overrides for such access
22075 types the suffix set by the @code{Type_Suffix} or @code{Access_Suffix}
22076 parameter.
22077
22078 @item Class_Subtype_Suffix=@emph{string}
22079 Specifies the suffix for the name of a subtype that denotes a class-wide type.
22080
22081 @item Constant_Suffix=@emph{string}
22082 Specifies the suffix for a constant name.
22083
22084 @item Renaming_Suffix=@emph{string}
22085 Specifies the suffix for a package renaming name.
22086 @end table
22087
22088 @item
22089 For the @option{-R} option:
22090 @table @code
22091 @item All_Suffixes
22092 Remove all the suffixes specified for the
22093 identifier suffix checks, whether by default or
22094 as specified by other rule parameters. All the
22095 checks for this rule are disabled as a result.
22096
22097 @item Type_Suffix
22098 Removes the suffix specified for types. This
22099 disables checks for types but does not disable
22100 any other checks for this rule (including the
22101 check for access type names if @code{Access_Suffix} is
22102 set).
22103
22104 @item Access_Suffix
22105 Removes the suffix specified for access types.
22106 This disables checks for access type names but
22107 does not disable any other checks for this rule.
22108 If @code{Type_Suffix} is set, access type names are
22109 checked as ordinary type names.
22110
22111 @item Class_Access_Suffix
22112 Removes the suffix specified for access types pointing to class-wide
22113 type. This disables specific checks for names of access types pointing to
22114 class-wide types but does not disable any other checks for this rule.
22115 If @code{Type_Suffix} is set, access type names are
22116 checked as ordinary type names. If @code{Access_Suffix} is set, these
22117 access types are checked as any other access type name.
22118
22119 @item Class_Subtype_Suffix=@emph{string}
22120 Removes the suffix specified for subtype names.
22121 This disables checks for subtype names but
22122 does not disable any other checks for this rule.
22123
22124 @item Constant_Suffix
22125 Removes the suffix specified for constants. This
22126 disables checks for constant names but does not
22127 disable any other checks for this rule.
22128
22129 @item Renaming_Suffix
22130 Removes the suffix specified for package
22131 renamings. This disables checks for package
22132 renamings but does not disable any other checks
22133 for this rule.
22134 @end table
22135 @end itemize
22136
22137 @noindent
22138 If more than one parameter is used, parameters must be separated by commas.
22139
22140 If more than one  option is specified for the @command{gnatcheck} invocation,
22141 a new option overrides the previous one(s).
22142
22143 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
22144 checks for all the
22145 name suffixes specified by previous options used for this rule.
22146
22147 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
22148 all the checks but keeps
22149 all the suffixes specified by previous options used for this rule.
22150
22151 The @emph{string} value must be a valid suffix for an Ada identifier (after
22152 trimming all the leading and trailing space characters, if any).
22153 Parameters are not case sensitive, except the @emph{string} part.
22154
22155 If any error is detected in a rule parameter, the parameter is ignored.
22156 In such a case the options that are set for the rule are not
22157 specified.
22158
22159
22160
22161 @node Multiple_Entries_In_Protected_Definitions
22162 @subsection @code{Multiple_Entries_In_Protected_Definitions}
22163 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
22164
22165 @noindent
22166 Flag each protected definition (i.e., each protected object/type declaration)
22167 that defines more than one entry.
22168 Diagnostic messages are generated for all the entry declarations
22169 except the first one. An entry family is counted as one entry. Entries from
22170 the private part of the protected definition are also checked.
22171
22172 This rule has no parameters.
22173
22174 @node Name_Clashes
22175 @subsection @code{Name_Clashes}
22176 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
22177
22178 @noindent
22179 Check that certain names are not used as defining identifiers. To activate
22180 this rule, you need to supply a reference to the dictionary file(s) as a rule
22181 parameter(s) (more then one dictionary file can be specified). If no
22182 dictionary file is set, this rule will not cause anything to be flagged.
22183 Only defining occurrences, not references, are checked.
22184 The check is not case-sensitive.
22185
22186 This rule is enabled by default, but without setting any corresponding
22187 dictionary file(s); thus the default effect is to do no checks.
22188
22189 A dictionary file is a plain text file. The maximum line length for this file
22190 is 1024 characters.  If the line is longer then this limit, extra characters
22191 are ignored.
22192
22193 Each line can be either an empty line, a comment line, or a line containing
22194 a list of identifiers separated by space or HT characters.
22195 A comment is an Ada-style comment (from @code{--} to end-of-line).
22196 Identifiers must follow the Ada syntax for identifiers.
22197 A line containing one or more identifiers may end with a comment.
22198
22199 @node Non_Qualified_Aggregates
22200 @subsection @code{Non_Qualified_Aggregates}
22201 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
22202
22203 @noindent
22204 Flag each non-qualified aggregate.
22205 A non-qualified aggregate is an
22206 aggregate that is not the expression of a qualified expression. A
22207 string literal is not considered an aggregate, but an array
22208 aggregate of a string type is considered as a normal aggregate.
22209 Aggregates of anonymous array types are not flagged.
22210
22211 This rule has no parameters.
22212
22213
22214 @node Non_Short_Circuit_Operators
22215 @subsection @code{Non_Short_Circuit_Operators}
22216 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
22217
22218 @noindent
22219 Flag all calls to predefined @code{and} and @code{or} operators for
22220 any boolean type. Calls to
22221 user-defined @code{and} and @code{or} and to operators defined by renaming
22222 declarations are not flagged. Calls to predefined @code{and} and @code{or}
22223 operators for modular types or boolean array types are not flagged.
22224
22225 This rule has no parameters.
22226
22227
22228
22229 @node Non_SPARK_Attributes
22230 @subsection @code{Non_SPARK_Attributes}
22231 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
22232
22233 @noindent
22234 The SPARK language defines the following subset of Ada 95 attribute
22235 designators as those that can be used in SPARK programs. The use of
22236 any other attribute is flagged.
22237
22238 @itemize @bullet
22239 @item @code{'Adjacent}
22240 @item @code{'Aft}
22241 @item @code{'Base}
22242 @item @code{'Ceiling}
22243 @item @code{'Component_Size}
22244 @item @code{'Compose}
22245 @item @code{'Copy_Sign}
22246 @item @code{'Delta}
22247 @item @code{'Denorm}
22248 @item @code{'Digits}
22249 @item @code{'Exponent}
22250 @item @code{'First}
22251 @item @code{'Floor}
22252 @item @code{'Fore}
22253 @item @code{'Fraction}
22254 @item @code{'Last}
22255 @item @code{'Leading_Part}
22256 @item @code{'Length}
22257 @item @code{'Machine}
22258 @item @code{'Machine_Emax}
22259 @item @code{'Machine_Emin}
22260 @item @code{'Machine_Mantissa}
22261 @item @code{'Machine_Overflows}
22262 @item @code{'Machine_Radix}
22263 @item @code{'Machine_Rounds}
22264 @item @code{'Max}
22265 @item @code{'Min}
22266 @item @code{'Model}
22267 @item @code{'Model_Emin}
22268 @item @code{'Model_Epsilon}
22269 @item @code{'Model_Mantissa}
22270 @item @code{'Model_Small}
22271 @item @code{'Modulus}
22272 @item @code{'Pos}
22273 @item @code{'Pred}
22274 @item @code{'Range}
22275 @item @code{'Remainder}
22276 @item @code{'Rounding}
22277 @item @code{'Safe_First}
22278 @item @code{'Safe_Last}
22279 @item @code{'Scaling}
22280 @item @code{'Signed_Zeros}
22281 @item @code{'Size}
22282 @item @code{'Small}
22283 @item @code{'Succ}
22284 @item @code{'Truncation}
22285 @item @code{'Unbiased_Rounding}
22286 @item @code{'Val}
22287 @item @code{'Valid}
22288 @end itemize
22289
22290 @noindent
22291 This rule has no parameters.
22292
22293
22294 @node Non_Tagged_Derived_Types
22295 @subsection @code{Non_Tagged_Derived_Types}
22296 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
22297
22298 @noindent
22299 Flag all derived type declarations that do not have a record extension part.
22300
22301 This rule has no parameters.
22302
22303
22304
22305 @node Non_Visible_Exceptions
22306 @subsection @code{Non_Visible_Exceptions}
22307 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
22308
22309 @noindent
22310 Flag constructs leading to the possibility of propagating an exception
22311 out of the scope in which the exception is declared.
22312 Two cases are detected:
22313
22314 @itemize @bullet
22315 @item
22316 An exception declaration in a subprogram body, task body or block
22317 statement is flagged if the body or statement does not contain a handler for
22318 that exception or a handler with an @code{others} choice.
22319
22320 @item
22321 A @code{raise} statement in an exception handler of a subprogram body,
22322 task body or block statement is flagged if it (re)raises a locally
22323 declared exception.  This may occur under the following circumstances:
22324 @itemize @minus
22325 @item
22326 it explicitly raises a locally declared exception, or
22327 @item
22328 it does not specify an exception name (i.e., it is simply @code{raise;})
22329 and the enclosing handler contains a locally declared exception in its
22330 exception choices.
22331 @end itemize
22332 @end itemize
22333
22334 @noindent
22335 Renamings of local exceptions are not flagged.
22336
22337 This rule has no parameters.
22338
22339
22340 @node Numeric_Literals
22341 @subsection @code{Numeric_Literals}
22342 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
22343
22344 @noindent
22345 Flag each use of a numeric literal in an index expression, and in any
22346 circumstance except for the following:
22347
22348 @itemize @bullet
22349 @item
22350 a literal occurring in the initialization expression for a constant
22351 declaration or a named number declaration, or
22352
22353 @item
22354 an integer literal that is less than or equal to a value
22355 specified by the @option{N} rule parameter.
22356 @end itemize
22357
22358 @noindent
22359 This rule may have the following parameters for the @option{+R} option:
22360
22361 @table @asis
22362 @item @emph{N}
22363 @emph{N} is an integer literal used as the maximal value that is not flagged
22364 (i.e., integer literals not exceeding this value are allowed)
22365
22366 @item @code{ALL}
22367 All integer literals are flagged
22368 @end table
22369
22370 @noindent
22371 If no parameters are set, the maximum unflagged value is 1.
22372
22373 The last specified check limit (or the fact that there is no limit at
22374 all) is used when multiple @option{+R} options appear.
22375
22376 The @option{-R} option for this rule has no parameters.
22377 It disables the rule but retains the last specified maximum unflagged value.
22378 If the @option{+R} option subsequently appears, this value is used as the
22379 threshold for the check.
22380
22381
22382 @node OTHERS_In_Aggregates
22383 @subsection @code{OTHERS_In_Aggregates}
22384 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
22385
22386 @noindent
22387 Flag each use of an @code{others} choice in extension aggregates.
22388 In record and array aggregates, an @code{others} choice is flagged unless
22389 it is used to refer to all components, or to all but one component.
22390
22391 If, in case of a named array aggregate, there are two associations, one
22392 with an @code{others} choice and another with a discrete range, the
22393 @code{others} choice is flagged even if the discrete range specifies
22394 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
22395
22396 This rule has no parameters.
22397
22398 @node OTHERS_In_CASE_Statements
22399 @subsection @code{OTHERS_In_CASE_Statements}
22400 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
22401
22402 @noindent
22403 Flag any use of an @code{others} choice in a @code{case} statement.
22404
22405 This rule has no parameters.
22406
22407 @node OTHERS_In_Exception_Handlers
22408 @subsection @code{OTHERS_In_Exception_Handlers}
22409 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
22410
22411 @noindent
22412 Flag any use of an @code{others} choice in an exception handler.
22413
22414 This rule has no parameters.
22415
22416
22417 @node Outer_Loop_Exits
22418 @subsection @code{Outer_Loop_Exits}
22419 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
22420
22421 @noindent
22422 Flag each @code{exit} statement containing a loop name that is not the name
22423 of the immediately enclosing @code{loop} statement.
22424
22425 This rule has no parameters.
22426
22427
22428 @node Overloaded_Operators
22429 @subsection @code{Overloaded_Operators}
22430 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
22431
22432 @noindent
22433 Flag each function declaration that overloads an operator symbol.
22434 A function body is checked only if the body does not have a
22435 separate spec. Formal functions are also checked. For a
22436 renaming declaration, only renaming-as-declaration is checked
22437
22438 This rule has no parameters.
22439
22440
22441 @node Overly_Nested_Control_Structures
22442 @subsection @code{Overly_Nested_Control_Structures}
22443 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
22444
22445 @noindent
22446 Flag each control structure whose nesting level exceeds the value provided
22447 in the rule parameter.
22448
22449 The control structures checked are the following:
22450
22451 @itemize @bullet
22452 @item    @code{if} statement
22453 @item    @code{case} statement
22454 @item    @code{loop} statement
22455 @item    Selective accept statement
22456 @item    Timed entry call statement
22457 @item    Conditional entry call
22458 @item    Asynchronous select statement
22459 @end itemize
22460
22461 @noindent
22462 The rule has the following parameter for the @option{+R} option:
22463
22464 @table @emph
22465 @item N
22466 Positive integer specifying the maximal control structure nesting
22467 level that is not flagged
22468 @end table
22469
22470 @noindent
22471 If the parameter for the @option{+R} option is not specified or
22472 if it is not a positive integer, @option{+R} option is ignored.
22473
22474 If more then one  option is specified for the gnatcheck call, the later option and
22475 new parameter override the previous one(s).
22476
22477
22478 @node Parameters_Out_Of_Order
22479 @subsection @code{Parameters_Out_Of_Order}
22480 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
22481
22482 @noindent
22483 Flag each subprogram and entry declaration whose formal parameters are not
22484 ordered according to the following scheme:
22485
22486 @itemize @bullet
22487
22488 @item @code{in} and @code{access} parameters first,
22489 then @code{in out} parameters,
22490 and then @code{out} parameters;
22491
22492 @item for @code{in} mode, parameters with default initialization expressions
22493 occur last
22494 @end itemize
22495
22496 @noindent
22497 Only the first violation of the described order is flagged.
22498
22499 The following constructs are checked:
22500
22501 @itemize @bullet
22502 @item   subprogram declarations (including null procedures);
22503 @item   generic subprogram declarations;
22504 @item   formal subprogram declarations;
22505 @item   entry declarations;
22506 @item   subprogram bodies and subprogram body stubs that do not
22507 have separate specifications
22508 @end itemize
22509
22510 @noindent
22511 Subprogram renamings are not checked.
22512
22513 This rule has no parameters.
22514
22515
22516 @node Positional_Actuals_For_Defaulted_Generic_Parameters
22517 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
22518 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
22519
22520 @noindent
22521 Flag each generic actual parameter corresponding to a generic formal
22522 parameter with a default initialization, if positional notation is used.
22523
22524 This rule has no parameters.
22525
22526 @node Positional_Actuals_For_Defaulted_Parameters
22527 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
22528 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
22529
22530 @noindent
22531 Flag each actual parameter to a subprogram or entry call where the
22532 corresponding formal parameter has a default expression, if positional
22533 notation is used.
22534
22535 This rule has no parameters.
22536
22537 @node Positional_Components
22538 @subsection @code{Positional_Components}
22539 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
22540
22541 @noindent
22542 Flag each array, record and extension aggregate that includes positional
22543 notation.
22544
22545 This rule has no parameters.
22546
22547
22548 @node Positional_Generic_Parameters
22549 @subsection @code{Positional_Generic_Parameters}
22550 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
22551
22552 @noindent
22553 Flag each positional actual generic parameter except for the case when
22554 the generic unit being iinstantiated has exactly one generic formal
22555 parameter.
22556
22557 This rule has no parameters.
22558
22559
22560 @node Positional_Parameters
22561 @subsection @code{Positional_Parameters}
22562 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
22563
22564 @noindent
22565 Flag each positional parameter notation in a subprogram or entry call,
22566 except for the following:
22567
22568 @itemize @bullet
22569 @item
22570 Parameters of calls to of prefix or infix operators are not flagged
22571 @item
22572 If the called subprogram or entry has only one formal parameter,
22573 the parameter of the call is not flagged;
22574 @item
22575 If a subprogram call uses the @emph{Object.Operation} notation, then
22576 @itemize @minus
22577 @item
22578 the first parameter (that is, @emph{Object}) is not flagged;
22579 @item
22580 if the called subprogram has only two parameters, the second parameter
22581 of the call is not flagged;
22582 @end itemize
22583 @end itemize
22584
22585 @noindent
22586 This rule has no parameters.
22587
22588
22589
22590
22591 @node Predefined_Numeric_Types
22592 @subsection @code{Predefined_Numeric_Types}
22593 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
22594
22595 @noindent
22596 Flag each explicit use of the name of any numeric type or subtype defined
22597 in package @code{Standard}.
22598
22599 The rationale for this rule is to detect when the
22600 program may depend on platform-specific characteristics of the implementation
22601 of the predefined numeric types. Note that this rule is over-pessimistic;
22602 for example, a program that uses @code{String} indexing
22603 likely needs a variable of type @code{Integer}.
22604 Another example is the flagging of predefined numeric types with explicit
22605 constraints:
22606
22607 @smallexample @c ada
22608     subtype My_Integer is Integer range Left .. Right;
22609     Vy_Var : My_Integer;
22610 @end smallexample
22611
22612 @noindent
22613 This rule detects only numeric types and subtypes defined in
22614 @code{Standard}. The use of numeric types and subtypes defined in other
22615 predefined packages (such as @code{System.Any_Priority} or
22616 @code{Ada.Text_IO.Count}) is not flagged
22617
22618 This rule has no parameters.
22619
22620
22621
22622 @node Raising_External_Exceptions
22623 @subsection @code{Raising_External_Exceptions}
22624 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
22625
22626 @noindent
22627 Flag any @code{raise} statement, in a program unit declared in a library
22628 package or in a generic library package, for an exception that is
22629 neither a predefined exception nor an exception that is also declared (or
22630 renamed) in the visible part of the package.
22631
22632 This rule has no parameters.
22633
22634
22635
22636 @node Raising_Predefined_Exceptions
22637 @subsection @code{Raising_Predefined_Exceptions}
22638 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
22639
22640 @noindent
22641 Flag each @code{raise} statement that raises a predefined exception
22642 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
22643 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
22644
22645 This rule has no parameters.
22646
22647 @node Separate_Numeric_Error_Handlers
22648 @subsection @code{Separate_Numeric_Error_Handlers}
22649 @cindex @code{Separate_Numeric_Error_Handlers} rule (for @command{gnatcheck})
22650
22651 @noindent
22652 Flags each exception handler that contains a choice for
22653 the predefined @code{Constraint_Error} exception, but does not contain
22654 the choice for the predefined @code{Numeric_Error} exception, or
22655 that contains the choice for @code{Numeric_Error}, but does not contain the
22656 choice for @code{Constraint_Error}.
22657
22658 This rule has no parameters.
22659
22660 @ignore
22661 @node Recursion
22662 @subsection @code{Recursion} (under construction, GLOBAL)
22663 @cindex @code{Recursion} rule (for @command{gnatcheck})
22664
22665 @noindent
22666 Flag recursive subprograms (cycles in the call graph). Declarations, and not
22667 calls, of recursive subprograms are detected.
22668
22669 This rule has no parameters.
22670 @end ignore
22671
22672 @ignore
22673 @node Side_Effect_Functions
22674 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
22675 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
22676
22677 @noindent
22678 Flag functions with side effects.
22679
22680 We define a side effect as changing any data object that is not local for the
22681 body of this function.
22682
22683 At the moment, we do NOT consider a side effect any input-output operations
22684 (changing a state or a content of any file).
22685
22686 We do not consider protected functions for this rule (???)
22687
22688 There are the following sources of side effect:
22689
22690 @enumerate
22691 @item Explicit (or direct) side-effect:
22692
22693 @itemize @bullet
22694 @item
22695 direct assignment to a non-local variable;
22696
22697 @item
22698 direct call to an entity that is known to change some data object that is
22699      not local for the body of this function (Note, that if F1 calls F2 and F2
22700      does have a side effect, this does not automatically mean that F1 also
22701      have a side effect, because it may be the case that F2 is declared in
22702      F1's body and it changes some data object that is global for F2, but
22703      local for F1);
22704 @end itemize
22705
22706 @item Indirect side-effect:
22707 @itemize @bullet
22708 @item
22709 Subprogram calls implicitly issued by:
22710 @itemize @bullet
22711 @item
22712 computing initialization expressions from type declarations as a part
22713          of object elaboration or allocator evaluation;
22714 @item
22715 computing implicit parameters of subprogram or entry calls or generic
22716          instantiations;
22717 @end itemize
22718
22719 @item
22720 activation of a task that change some non-local data object (directly or
22721      indirectly);
22722
22723 @item
22724 elaboration code of a package that is a result of a package instantiation;
22725
22726 @item
22727 controlled objects;
22728 @end itemize
22729
22730 @item Situations when we can suspect a side-effect, but the full static check
22731 is either impossible or too hard:
22732 @itemize @bullet
22733 @item
22734 assignment to access variables or to the objects pointed by access
22735      variables;
22736
22737 @item
22738 call to a subprogram pointed by access-to-subprogram value
22739
22740 @item
22741 dispatching calls;
22742 @end itemize
22743 @end enumerate
22744
22745 @noindent
22746 This rule has no parameters.
22747 @end ignore
22748
22749 @node Slices
22750 @subsection @code{Slices}
22751 @cindex @code{Slices} rule (for @command{gnatcheck})
22752
22753 @noindent
22754 Flag all uses of array slicing
22755
22756 This rule has no parameters.
22757
22758
22759 @node Too_Many_Parents
22760 @subsection @code{Too_Many_Parents}
22761 @cindex @code{Too_Many_Parents} rule (for @command{gnatcheck})
22762
22763 @noindent
22764 Flags any type declaration, single task declaration or single protected
22765 declaration that has more then  @option{N} parents,  @option{N} is a parameter
22766 of the rule.
22767 A parent here is either a (sub)type denoted by the subtype mark from the
22768 parent_subtype_indication (in case of a derived type declaration), or
22769 any of the progenitors from the interface list, if any.
22770
22771 This rule has the following (mandatory) parameters for the @option{+R} option:
22772
22773 @table @emph
22774 @item N
22775 Positive integer specifying the maximal allowed number of parents.
22776 @end table
22777
22778
22779 @node Unassigned_OUT_Parameters
22780 @subsection @code{Unassigned_OUT_Parameters}
22781 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
22782
22783 @noindent
22784 Flags procedures' @code{out} parameters that are not assigned, and
22785 identifies the contexts in which the assignments are missing.
22786
22787 An @code{out} parameter is flagged in the statements in the procedure
22788 body's handled sequence of statements (before the procedure body's
22789 @code{exception} part, if any) if this sequence of statements contains
22790 no assignments to the parameter.
22791
22792 An @code{out} parameter is flagged in an exception handler in the exception
22793 part of the procedure body's handled sequence of statements if the handler
22794 contains no assignment to the parameter.
22795
22796 Bodies of generic procedures are also considered.
22797
22798 The following are treated as assignments to an @code{out} parameter:
22799
22800 @itemize @bullet
22801 @item
22802 an assignment statement, with the parameter or some component as the target;
22803
22804 @item
22805 passing the parameter (or one of its components) as an @code{out} or
22806 @code{in out} parameter.
22807 @end itemize
22808
22809 @noindent
22810 This rule does not have any parameters.
22811
22812
22813
22814 @node Uncommented_BEGIN_In_Package_Bodies
22815 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
22816 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
22817
22818 @noindent
22819 Flags each package body with declarations and a statement part that does not
22820 include a trailing comment on the line containing the @code{begin} keyword;
22821 this trailing comment needs to specify the package name and nothing else.
22822 The @code{begin} is not flagged if the package body does not
22823 contain any declarations.
22824
22825 If the @code{begin} keyword is placed on the
22826 same line as the last declaration or the first statement, it is flagged
22827 independently of whether the line contains a trailing comment. The
22828 diagnostic message is attached to the line containing the first statement.
22829
22830 This rule has no parameters.
22831
22832 @node Unconditional_Exits
22833 @subsection @code{Unconditional_Exits}
22834 @cindex @code{Unconditional_Exits} rule (for @command{gnatcheck})
22835
22836 @noindent
22837 Flag unconditional @code{exit} statements.
22838
22839 This rule has no parameters.
22840
22841 @node Unconstrained_Array_Returns
22842 @subsection @code{Unconstrained_Array_Returns}
22843 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
22844
22845 @noindent
22846 Flag each function returning an unconstrained array. Function declarations,
22847 function bodies (and body stubs) having no separate specifications,
22848 and generic function instantiations are checked.
22849 Function calls and function renamings are
22850 not checked.
22851
22852 Generic function declarations, and function declarations in generic
22853 packages are not checked, instead this rule checks the results of
22854 generic instantiations (that is, expanded specification and expanded
22855 body corresponding to an instantiation).
22856
22857 This rule has no parameters.
22858
22859 @node Universal_Ranges
22860 @subsection @code{Universal_Ranges}
22861 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
22862
22863 @noindent
22864 Flag discrete ranges that are a part of an index constraint, constrained
22865 array definition, or @code{for}-loop parameter specification, and whose bounds
22866 are both of type @i{universal_integer}. Ranges that have at least one
22867 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
22868 or an expression of non-universal type) are not flagged.
22869
22870 This rule has no parameters.
22871
22872
22873 @node Unnamed_Blocks_And_Loops
22874 @subsection @code{Unnamed_Blocks_And_Loops}
22875 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
22876
22877 @noindent
22878 Flag each unnamed block statement and loop statement.
22879
22880 The rule has no parameters.
22881
22882
22883
22884 @ignore
22885 @node Unused_Subprograms
22886 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
22887 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
22888
22889 @noindent
22890 Flag all unused subprograms.
22891
22892 This rule has no parameters.
22893 @end ignore
22894
22895
22896
22897
22898 @node USE_PACKAGE_Clauses
22899 @subsection @code{USE_PACKAGE_Clauses}
22900 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
22901
22902 @noindent
22903 Flag all @code{use} clauses for packages; @code{use type} clauses are
22904 not flagged.
22905
22906 This rule has no parameters.
22907
22908
22909 @node Visible_Components
22910 @subsection @code{Visible_Components}
22911 @cindex @code{Visible_Components} rule (for @command{gnatcheck})
22912
22913 @noindent
22914 Flags all the type declarations located in the visible part of a library
22915 package or a library generic package that can declare a visible component. A
22916 type is considered as declaring a visible component if it contains a record
22917 definition by its own or as a part of a record extension. Type declaration is
22918 flagged even if it contains a record definition that defines no components.
22919
22920 Declarations located in private parts of local (generic) packages are not
22921 flagged. Declarations in private packages are not flagged.
22922
22923 This rule has no parameters.
22924
22925
22926 @node Volatile_Objects_Without_Address_Clauses
22927 @subsection @code{Volatile_Objects_Without_Address_Clauses}
22928 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
22929
22930 @noindent
22931 Flag each volatile object that does not have an address clause.
22932
22933 The following check is made: if the pragma @code{Volatile} is applied to a
22934 data object or to its type, then an address clause must
22935 be supplied for this object.
22936
22937 This rule does not check the components of data objects,
22938 array components that are volatile as a result of the pragma
22939 @code{Volatile_Components}, or objects that are volatile because
22940 they are atomic as a result of pragmas @code{Atomic} or
22941 @code{Atomic_Components}.
22942
22943 Only variable declarations, and not constant declarations, are checked.
22944
22945 This rule has no parameters.
22946
22947 @node Example of gnatcheck Usage
22948 @section Example of @command{gnatcheck} Usage
22949
22950 @noindent
22951 Here is a simple example. Suppose that in the current directory we have a
22952 project file named @file{gnatcheck_example.gpr} with the following content:
22953
22954 @smallexample @c projectfile
22955 project Gnatcheck_Example is
22956
22957    for Source_Dirs use ("src");
22958    for Object_Dir use "obj";
22959    for Main use ("main.adb");
22960
22961    package Check is
22962       for Default_Switches ("ada") use ("-rules", "-from=coding_standard");
22963    end Check;
22964
22965 end Gnatcheck_Example;
22966 @end smallexample
22967
22968 @noindent
22969 And the file named @file{coding_standard} is also located in the current
22970 directory and has the following content:
22971
22972 @smallexample
22973 -----------------------------------------------------
22974 -- This is a sample gnatcheck coding standard file --
22975 -----------------------------------------------------
22976
22977 --  First, turning on rules, that are directly implemented in gnatcheck
22978 +RAbstract_Type_Declarations
22979 +RAnonymous_Arrays
22980 +RLocal_Packages
22981 +RFloat_Equality_Checks
22982 +REXIT_Statements_With_No_Loop_Name
22983
22984 --  Then, activating compiler checks of interest:
22985 +RStyle_Checks:e
22986 --  This style check checks if a unit name is present on END keyword that
22987 --  is the end of the unit declaration
22988 @end smallexample
22989
22990 @noindent
22991 And the subdirectory @file{src} contains the following Ada sources:
22992
22993 @file{pack.ads}:
22994
22995 @smallexample @c ada
22996 package Pack is
22997    type T is abstract tagged private;
22998    procedure P (X : T) is abstract;
22999
23000    package Inner is
23001       type My_Float is digits 8;
23002       function Is_Equal (L, R : My_Float) return Boolean;
23003    end Inner;
23004 private
23005    type T is abstract tagged null record;
23006 end;
23007 @end smallexample
23008
23009 @noindent
23010 @file{pack.adb}:
23011
23012 @smallexample @c ada
23013 package body Pack is
23014    package body Inner is
23015       function Is_Equal (L, R : My_Float) return Boolean is
23016       begin
23017          return L = R;
23018       end;
23019    end Inner;
23020 end Pack;
23021 @end smallexample
23022
23023 @noindent
23024 and @file{main.adb}
23025
23026 @smallexample @c ada
23027 with Pack; use Pack;
23028 procedure Main is
23029
23030    pragma Annotate
23031      (gnatcheck, Exempt_On, "Anonymous_Arrays", "this one is fine");
23032    Float_Array : array (1 .. 10) of Inner.My_Float;
23033    pragma Annotate (gnatcheck, Exempt_Off, "Anonymous_Arrays");
23034
23035    Another_Float_Array : array (1 .. 10) of Inner.My_Float;
23036
23037    use Inner;
23038
23039    B : Boolean := False;
23040
23041 begin
23042    for J in Float_Array'Range loop
23043       if Is_Equal (Float_Array (J), Another_Float_Array (J)) then
23044          B := True;
23045          exit;
23046       end if;
23047    end loop;
23048 end Main;
23049 @end smallexample
23050
23051 @noindent
23052 And suppose we call @command{gnatcheck} from the current directory using
23053 the @command{gnat} driver:
23054
23055 @smallexample
23056    gnat check -Pgnatcheck_example.gpr
23057 @end smallexample
23058
23059 @noindent
23060 As a result, @command{gnatcheck} is called to check all the files from the
23061 project @file{gnatcheck_example.gpr} using the coding standard defined by
23062 the file @file{coding_standard}. As the result, the @command{gnatcheck}
23063 report file named @file{gnatcheck.out} will be created in the current
23064 directory, and it will have the following content:
23065
23066 @smallexample
23067 RULE CHECKING REPORT
23068
23069 1. OVERVIEW
23070
23071 Date and time of execution: 2009.10.28 14:17
23072 Tool version: GNATCHECK (built with ASIS 2.0.R for GNAT Pro 6.3.0w (20091016))
23073 Command line:
23074
23075 gnatcheck -files=.../GNAT-TEMP-000004.TMP -cargs -gnatec=.../GNAT-TEMP-000003.TMP -rules -from=coding_standard
23076
23077 Coding standard (applied rules):
23078    Abstract_Type_Declarations
23079    Anonymous_Arrays
23080    EXIT_Statements_With_No_Loop_Name
23081    Float_Equality_Checks
23082    Local_Packages
23083
23084    Compiler style checks: -gnatye
23085
23086 Number of coding standard violations: 6
23087 Number of exempted coding standard violations: 1
23088
23089 2. DETECTED RULE VIOLATIONS
23090
23091 2.1. NON-EXEMPTED VIOLATIONS
23092
23093 Source files with non-exempted violations
23094    pack.ads
23095    pack.adb
23096    main.adb
23097
23098 List of violations grouped by files, and ordered by increasing source location:
23099
23100 pack.ads:2:4: declaration of abstract type
23101 pack.ads:5:4: declaration of local package
23102 pack.ads:10:30: declaration of abstract type
23103 pack.ads:11:1: (style) "end Pack" required
23104 pack.adb:5:19: use of equality operation for float values
23105 pack.adb:6:7: (style) "end Is_Equal" required
23106 main.adb:9:26: anonymous array type
23107 main.adb:19:10: exit statement with no loop name
23108
23109 2.2. EXEMPTED VIOLATIONS
23110
23111 Source files with exempted violations
23112    main.adb
23113
23114 List of violations grouped by files, and ordered by increasing source location:
23115
23116 main.adb:6:18: anonymous array type
23117    (this one is fine)
23118
23119 2.3. SOURCE FILES WITH NO VIOLATION
23120
23121    No files without violations
23122
23123 END OF REPORT
23124 @end smallexample
23125
23126
23127 @c *********************************
23128 @node Creating Sample Bodies Using gnatstub
23129 @chapter Creating Sample Bodies Using @command{gnatstub}
23130 @findex gnatstub
23131
23132 @noindent
23133 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
23134 for library unit declarations.
23135
23136 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
23137 driver (see @ref{The GNAT Driver and Project Files}).
23138
23139 To create a body stub, @command{gnatstub} has to compile the library
23140 unit declaration. Therefore, bodies can be created only for legal
23141 library units. Moreover, if a library unit depends semantically upon
23142 units located outside the current directory, you have to provide
23143 the source search path when calling @command{gnatstub}, see the description
23144 of @command{gnatstub} switches below.
23145
23146 By default, all the program unit body stubs generated by @code{gnatstub}
23147 raise the predefined @code{Program_Error} exception, which will catch
23148 accidental calls of generated stubs. This behavior can be changed with
23149 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
23150
23151 @menu
23152 * Running gnatstub::
23153 * Switches for gnatstub::
23154 @end menu
23155
23156 @node Running gnatstub
23157 @section Running @command{gnatstub}
23158
23159 @noindent
23160 @command{gnatstub} has the command-line interface of the form
23161
23162 @smallexample
23163 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
23164 @c Expanding @ovar macro inline (explanation in macro def comments)
23165 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
23166 @end smallexample
23167
23168 @noindent
23169 where
23170 @table @var
23171 @item filename
23172 is the name of the source file that contains a library unit declaration
23173 for which a body must be created. The file name may contain the path
23174 information.
23175 The file name does not have to follow the GNAT file name conventions. If the
23176 name
23177 does not follow GNAT file naming conventions, the name of the body file must
23178 be provided
23179 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
23180 If the file name follows the GNAT file naming
23181 conventions and the name of the body file is not provided,
23182 @command{gnatstub}
23183 creates the name
23184 of the body file from the argument file name by replacing the @file{.ads}
23185 suffix
23186 with the @file{.adb} suffix.
23187
23188 @item directory
23189 indicates the directory in which the body stub is to be placed (the default
23190 is the
23191 current directory)
23192
23193 @item @samp{@var{gcc_switches}} is a list of switches for
23194 @command{gcc}. They will be passed on to all compiler invocations made by
23195 @command{gnatelim} to generate the ASIS trees. Here you can provide
23196 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
23197 use the @option{-gnatec} switch to set the configuration file etc.
23198
23199 @item switches
23200 is an optional sequence of switches as described in the next section
23201 @end table
23202
23203 @node Switches for gnatstub
23204 @section Switches for @command{gnatstub}
23205
23206 @table @option
23207 @c !sort!
23208
23209 @item ^-f^/FULL^
23210 @cindex @option{^-f^/FULL^} (@command{gnatstub})
23211 If the destination directory already contains a file with the name of the
23212 body file
23213 for the argument spec file, replace it with the generated body stub.
23214
23215 @item ^-hs^/HEADER=SPEC^
23216 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
23217 Put the comment header (i.e., all the comments preceding the
23218 compilation unit) from the source of the library unit declaration
23219 into the body stub.
23220
23221 @item ^-hg^/HEADER=GENERAL^
23222 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
23223 Put a sample comment header into the body stub.
23224
23225 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
23226 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
23227 Use the content of the file as the comment header for a generated body stub.
23228
23229 @ifclear vms
23230 @item -IDIR
23231 @cindex @option{-IDIR} (@command{gnatstub})
23232 @itemx -I-
23233 @cindex @option{-I-} (@command{gnatstub})
23234 @end ifclear
23235 @ifset vms
23236 @item /NOCURRENT_DIRECTORY
23237 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
23238 @end ifset
23239 ^These switches have ^This switch has^ the same meaning as in calls to
23240 @command{gcc}.
23241 ^They define ^It defines ^ the source search path in the call to
23242 @command{gcc} issued
23243 by @command{gnatstub} to compile an argument source file.
23244
23245 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
23246 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
23247 This switch has the same meaning as in calls to @command{gcc}.
23248 It defines the additional configuration file to be passed to the call to
23249 @command{gcc} issued
23250 by @command{gnatstub} to compile an argument source file.
23251
23252 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
23253 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
23254 (@var{n} is a non-negative integer). Set the maximum line length in the
23255 body stub to @var{n}; the default is 79. The maximum value that can be
23256 specified is 32767. Note that in the special case of configuration
23257 pragma files, the maximum is always 32767 regardless of whether or
23258 not this switch appears.
23259
23260 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
23261 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
23262 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
23263 the generated body sample to @var{n}.
23264 The default indentation is 3.
23265
23266 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
23267 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
23268 Order local bodies alphabetically. (By default local bodies are ordered
23269 in the same way as the corresponding local specs in the argument spec file.)
23270
23271 @item ^-i^/INDENTATION=^@var{n}
23272 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
23273 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
23274
23275 @item ^-k^/TREE_FILE=SAVE^
23276 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
23277 Do not remove the tree file (i.e., the snapshot of the compiler internal
23278 structures used by @command{gnatstub}) after creating the body stub.
23279
23280 @item ^-l^/LINE_LENGTH=^@var{n}
23281 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
23282 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
23283
23284 @item ^--no-exception^/NO_EXCEPTION^
23285 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
23286 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
23287 This is not always possible for function stubs.
23288
23289 @item ^--no-local-header^/NO_LOCAL_HEADER^
23290 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
23291 Do not place local comment header with unit name before body stub for a
23292 unit.
23293
23294 @item ^-o ^/BODY=^@var{body-name}
23295 @cindex @option{^-o^/BODY^} (@command{gnatstub})
23296 Body file name.  This should be set if the argument file name does not
23297 follow
23298 the GNAT file naming
23299 conventions. If this switch is omitted the default name for the body will be
23300 obtained
23301 from the argument file name according to the GNAT file naming conventions.
23302
23303 @item ^-q^/QUIET^
23304 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
23305 Quiet mode: do not generate a confirmation when a body is
23306 successfully created, and do not generate a message when a body is not
23307 required for an
23308 argument unit.
23309
23310 @item ^-r^/TREE_FILE=REUSE^
23311 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
23312 Reuse the tree file (if it exists) instead of creating it.  Instead of
23313 creating the tree file for the library unit declaration, @command{gnatstub}
23314 tries to find it in the current directory and use it for creating
23315 a body. If the tree file is not found, no body is created. This option
23316 also implies @option{^-k^/SAVE^}, whether or not
23317 the latter is set explicitly.
23318
23319 @item ^-t^/TREE_FILE=OVERWRITE^
23320 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
23321 Overwrite the existing tree file.  If the current directory already
23322 contains the file which, according to the GNAT file naming rules should
23323 be considered as a tree file for the argument source file,
23324 @command{gnatstub}
23325 will refuse to create the tree file needed to create a sample body
23326 unless this option is set.
23327
23328 @item ^-v^/VERBOSE^
23329 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
23330 Verbose mode: generate version information.
23331
23332 @end table
23333
23334 @c *********************************
23335 @node Generating Ada Bindings for C and C++ headers
23336 @chapter Generating Ada Bindings for C and C++ headers
23337 @findex binding
23338
23339 @noindent
23340 GNAT now comes with a binding generator for C and C++ headers which is
23341 intended to do 95% of the tedious work of generating Ada specs from C
23342 or C++ header files.
23343
23344 Note that this capability is not intended to generate 100% correct Ada specs,
23345 and will is some cases require manual adjustments, although it can often
23346 be used out of the box in practice.
23347
23348 Some of the known limitations include:
23349
23350 @itemize @bullet
23351 @item only very simple character constant macros are translated into Ada
23352 constants. Function macros (macros with arguments) are partially translated
23353 as comments, to be completed manually if needed.
23354 @item some extensions (e.g. vector types) are not supported
23355 @item pointers to pointers or complex structures are mapped to System.Address
23356 @end itemize
23357
23358 The code generated is using the Ada 2005 syntax, which makes it
23359 easier to interface with other languages than previous versions of Ada.
23360
23361 @menu
23362 * Running the binding generator::
23363 * Generating bindings for C++ headers::
23364 * Switches::
23365 @end menu
23366
23367 @node Running the binding generator
23368 @section Running the binding generator
23369
23370 @noindent
23371 The binding generator is part of the @command{gcc} compiler and can be
23372 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
23373 spec files for the header files specified on the command line, and all
23374 header files needed by these files transitivitely. For example:
23375
23376 @smallexample
23377 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
23378 $ gcc -c -gnat05 *.ads
23379 @end smallexample
23380
23381 will generate, under GNU/Linux, the following files: @file{time_h.ads},
23382 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
23383 correspond to the files @file{/usr/include/time.h},
23384 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
23385 mode these Ada specs.
23386
23387 The @code{-C} switch tells @command{gcc} to extract comments from headers,
23388 and will attempt to generate corresponding Ada comments.
23389
23390 If you want to generate a single Ada file and not the transitive closure, you
23391 can use instead the @option{-fdump-ada-spec-slim} switch.
23392
23393 Note that we recommend when possible to use the @command{g++} driver to
23394 generate bindings, even for most C headers, since this will in general
23395 generate better Ada specs. For generating bindings for C++ headers, it is
23396 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
23397 is equivalent in this case. If @command{g++} cannot work on your C headers
23398 because of incompatibilities between C and C++, then you can fallback to
23399 @command{gcc} instead.
23400
23401 For an example of better bindings generated from the C++ front-end,
23402 the name of the parameters (when available) are actually ignored by the C
23403 front-end. Consider the following C header:
23404
23405 @smallexample
23406 extern void foo (int variable);
23407 @end smallexample
23408
23409 with the C front-end, @code{variable} is ignored, and the above is handled as:
23410
23411 @smallexample
23412 extern void foo (int);
23413 @end smallexample
23414
23415 generating a generic:
23416
23417 @smallexample
23418 procedure foo (param1 : int);
23419 @end smallexample
23420
23421 with the C++ front-end, the name is available, and we generate:
23422
23423 @smallexample
23424 procedure foo (variable : int);
23425 @end smallexample
23426
23427 In some cases, the generated bindings will be more complete or more meaningful
23428 when defining some macros, which you can do via the @option{-D} switch. This
23429 is for example the case with @file{Xlib.h} under GNU/Linux:
23430
23431 @smallexample
23432 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
23433 @end smallexample
23434
23435 The above will generate more complete bindings than a straight call without
23436 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
23437
23438 In other cases, it is not possible to parse a header file in a stand alone
23439 manner, because other include files need to be included first. In this
23440 case, the solution is to create a small header file including the needed
23441 @code{#include} and possible @code{#define} directives. For example, to
23442 generate Ada bindings for @file{readline/readline.h}, you need to first
23443 include @file{stdio.h}, so you can create a file with the following two
23444 lines in e.g. @file{readline1.h}:
23445
23446 @smallexample
23447 #include <stdio.h>
23448 #include <readline/readline.h>
23449 @end smallexample
23450
23451 and then generate Ada bindings from this file:
23452
23453 @smallexample
23454 $ g++ -c -fdump-ada-spec readline1.h
23455 @end smallexample
23456
23457 @node Generating bindings for C++ headers
23458 @section Generating bindings for C++ headers
23459
23460 @noindent
23461 Generating bindings for C++ headers is done using the same options, always
23462 with the @command{g++} compiler.
23463
23464 In this mode, C++ classes will be mapped to Ada tagged types, constructors
23465 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
23466 multiple inheritance of abstract classes will be mapped to Ada interfaces
23467 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
23468 information on interfacing to C++).
23469
23470 For example, given the following C++ header file:
23471
23472 @smallexample
23473 @group
23474 @cartouche
23475 class Carnivore @{
23476 public:
23477    virtual int Number_Of_Teeth () = 0;
23478 @};
23479
23480 class Domestic @{
23481 public:
23482    virtual void Set_Owner (char* Name) = 0;
23483 @};
23484
23485 class Animal @{
23486 public:
23487   int Age_Count;
23488   virtual void Set_Age (int New_Age);
23489 @};
23490
23491 class Dog : Animal, Carnivore, Domestic @{
23492  public:
23493   int  Tooth_Count;
23494   char *Owner;
23495
23496   virtual int  Number_Of_Teeth ();
23497   virtual void Set_Owner (char* Name);
23498
23499   Dog();
23500 @};
23501 @end cartouche
23502 @end group
23503 @end smallexample
23504
23505 The corresponding Ada code is generated:
23506
23507 @smallexample @c ada
23508 @group
23509 @cartouche
23510   package Class_Carnivore is
23511     type Carnivore is limited interface;
23512     pragma Import (CPP, Carnivore);
23513
23514     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
23515   end;
23516   use Class_Carnivore;
23517
23518   package Class_Domestic is
23519     type Domestic is limited interface;
23520     pragma Import (CPP, Domestic);
23521
23522     procedure Set_Owner
23523       (this : access Domestic;
23524        Name : Interfaces.C.Strings.chars_ptr) is abstract;
23525   end;
23526   use Class_Domestic;
23527
23528   package Class_Animal is
23529     type Animal is tagged limited record
23530       Age_Count : aliased int;
23531     end record;
23532     pragma Import (CPP, Animal);
23533
23534     procedure Set_Age (this : access Animal; New_Age : int);
23535     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
23536   end;
23537   use Class_Animal;
23538
23539   package Class_Dog is
23540     type Dog is new Animal and Carnivore and Domestic with record
23541       Tooth_Count : aliased int;
23542       Owner : Interfaces.C.Strings.chars_ptr;
23543     end record;
23544     pragma Import (CPP, Dog);
23545
23546     function Number_Of_Teeth (this : access Dog) return int;
23547     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
23548
23549     procedure Set_Owner
23550       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
23551     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
23552
23553     function New_Dog return Dog;
23554     pragma CPP_Constructor (New_Dog);
23555     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
23556   end;
23557   use Class_Dog;
23558 @end cartouche
23559 @end group
23560 @end smallexample
23561
23562 @node Switches
23563 @section Switches
23564
23565 @table @option
23566 @item -fdump-ada-spec
23567 @cindex @option{-fdump-ada-spec} (@command{gcc})
23568 Generate Ada spec files for the given header files transitively (including
23569 all header files that these headers depend upon).
23570
23571 @item -fdump-ada-spec-slim
23572 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
23573 Generate Ada spec files for the header files specified on the command line
23574 only.
23575
23576 @item -C
23577 @cindex @option{-C} (@command{gcc})
23578 Extract comments from headers and generate Ada comments in the Ada spec files.
23579 @end table
23580
23581 @node Other Utility Programs
23582 @chapter Other Utility Programs
23583
23584 @noindent
23585 This chapter discusses some other utility programs available in the Ada
23586 environment.
23587
23588 @menu
23589 * Using Other Utility Programs with GNAT::
23590 * The External Symbol Naming Scheme of GNAT::
23591 * Converting Ada Files to html with gnathtml::
23592 * Installing gnathtml::
23593 @ifset vms
23594 * LSE::
23595 * Profiling::
23596 @end ifset
23597 @end menu
23598
23599 @node Using Other Utility Programs with GNAT
23600 @section Using Other Utility Programs with GNAT
23601
23602 @noindent
23603 The object files generated by GNAT are in standard system format and in
23604 particular the debugging information uses this format. This means
23605 programs generated by GNAT can be used with existing utilities that
23606 depend on these formats.
23607
23608 @ifclear vms
23609 In general, any utility program that works with C will also often work with
23610 Ada programs generated by GNAT. This includes software utilities such as
23611 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
23612 as Purify.
23613 @end ifclear
23614
23615 @node The External Symbol Naming Scheme of GNAT
23616 @section The External Symbol Naming Scheme of GNAT
23617
23618 @noindent
23619 In order to interpret the output from GNAT, when using tools that are
23620 originally intended for use with other languages, it is useful to
23621 understand the conventions used to generate link names from the Ada
23622 entity names.
23623
23624 All link names are in all lowercase letters. With the exception of library
23625 procedure names, the mechanism used is simply to use the full expanded
23626 Ada name with dots replaced by double underscores. For example, suppose
23627 we have the following package spec:
23628
23629 @smallexample @c ada
23630 @group
23631 @cartouche
23632 package QRS is
23633    MN : Integer;
23634 end QRS;
23635 @end cartouche
23636 @end group
23637 @end smallexample
23638
23639 @noindent
23640 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
23641 the corresponding link name is @code{qrs__mn}.
23642 @findex Export
23643 Of course if a @code{pragma Export} is used this may be overridden:
23644
23645 @smallexample @c ada
23646 @group
23647 @cartouche
23648 package Exports is
23649    Var1 : Integer;
23650    pragma Export (Var1, C, External_Name => "var1_name");
23651    Var2 : Integer;
23652    pragma Export (Var2, C, Link_Name => "var2_link_name");
23653 end Exports;
23654 @end cartouche
23655 @end group
23656 @end smallexample
23657
23658 @noindent
23659 In this case, the link name for @var{Var1} is whatever link name the
23660 C compiler would assign for the C function @var{var1_name}. This typically
23661 would be either @var{var1_name} or @var{_var1_name}, depending on operating
23662 system conventions, but other possibilities exist. The link name for
23663 @var{Var2} is @var{var2_link_name}, and this is not operating system
23664 dependent.
23665
23666 @findex _main
23667 One exception occurs for library level procedures. A potential ambiguity
23668 arises between the required name @code{_main} for the C main program,
23669 and the name we would otherwise assign to an Ada library level procedure
23670 called @code{Main} (which might well not be the main program).
23671
23672 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
23673 names. So if we have a library level procedure such as
23674
23675 @smallexample @c ada
23676 @group
23677 @cartouche
23678 procedure Hello (S : String);
23679 @end cartouche
23680 @end group
23681 @end smallexample
23682
23683 @noindent
23684 the external name of this procedure will be @var{_ada_hello}.
23685
23686
23687 @node Converting Ada Files to html with gnathtml
23688 @section Converting Ada Files to HTML with @code{gnathtml}
23689
23690 @noindent
23691 This @code{Perl} script allows Ada source files to be browsed using
23692 standard Web browsers. For installation procedure, see the section
23693 @xref{Installing gnathtml}.
23694
23695 Ada reserved keywords are highlighted in a bold font and Ada comments in
23696 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
23697 switch to suppress the generation of cross-referencing information, user
23698 defined variables and types will appear in a different color; you will
23699 be able to click on any identifier and go to its declaration.
23700
23701 The command line is as follow:
23702 @smallexample
23703 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
23704 @c Expanding @ovar macro inline (explanation in macro def comments)
23705 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
23706 @end smallexample
23707
23708 @noindent
23709 You can pass it as many Ada files as you want. @code{gnathtml} will generate
23710 an html file for every ada file, and a global file called @file{index.htm}.
23711 This file is an index of every identifier defined in the files.
23712
23713 The available ^switches^options^ are the following ones:
23714
23715 @table @option
23716 @item -83
23717 @cindex @option{-83} (@code{gnathtml})
23718 Only the Ada 83 subset of keywords will be highlighted.
23719
23720 @item -cc @var{color}
23721 @cindex @option{-cc} (@code{gnathtml})
23722 This option allows you to change the color used for comments. The default
23723 value is green. The color argument can be any name accepted by html.
23724
23725 @item -d
23726 @cindex @option{-d} (@code{gnathtml})
23727 If the Ada files depend on some other files (for instance through
23728 @code{with} clauses, the latter files will also be converted to html.
23729 Only the files in the user project will be converted to html, not the files
23730 in the run-time library itself.
23731
23732 @item -D
23733 @cindex @option{-D} (@code{gnathtml})
23734 This command is the same as @option{-d} above, but @command{gnathtml} will
23735 also look for files in the run-time library, and generate html files for them.
23736
23737 @item -ext @var{extension}
23738 @cindex @option{-ext} (@code{gnathtml})
23739 This option allows you to change the extension of the generated HTML files.
23740 If you do not specify an extension, it will default to @file{htm}.
23741
23742 @item -f
23743 @cindex @option{-f} (@code{gnathtml})
23744 By default, gnathtml will generate html links only for global entities
23745 ('with'ed units, global variables and types,@dots{}).  If you specify
23746 @option{-f} on the command line, then links will be generated for local
23747 entities too.
23748
23749 @item -l @var{number}
23750 @cindex @option{-l} (@code{gnathtml})
23751 If this ^switch^option^ is provided and @var{number} is not 0, then
23752 @code{gnathtml} will number the html files every @var{number} line.
23753
23754 @item -I @var{dir}
23755 @cindex @option{-I} (@code{gnathtml})
23756 Specify a directory to search for library files (@file{.ALI} files) and
23757 source files. You can provide several -I switches on the command line,
23758 and the directories will be parsed in the order of the command line.
23759
23760 @item -o @var{dir}
23761 @cindex @option{-o} (@code{gnathtml})
23762 Specify the output directory for html files. By default, gnathtml will
23763 saved the generated html files in a subdirectory named @file{html/}.
23764
23765 @item -p @var{file}
23766 @cindex @option{-p} (@code{gnathtml})
23767 If you are using Emacs and the most recent Emacs Ada mode, which provides
23768 a full Integrated Development Environment for compiling, checking,
23769 running and debugging applications, you may use @file{.gpr} files
23770 to give the directories where Emacs can find sources and object files.
23771
23772 Using this ^switch^option^, you can tell gnathtml to use these files.
23773 This allows you to get an html version of your application, even if it
23774 is spread over multiple directories.
23775
23776 @item -sc @var{color}
23777 @cindex @option{-sc} (@code{gnathtml})
23778 This ^switch^option^ allows you to change the color used for symbol
23779 definitions.
23780 The default value is red. The color argument can be any name accepted by html.
23781
23782 @item -t @var{file}
23783 @cindex @option{-t} (@code{gnathtml})
23784 This ^switch^option^ provides the name of a file. This file contains a list of
23785 file names to be converted, and the effect is exactly as though they had
23786 appeared explicitly on the command line. This
23787 is the recommended way to work around the command line length limit on some
23788 systems.
23789
23790 @end table
23791
23792 @node Installing gnathtml
23793 @section Installing @code{gnathtml}
23794
23795 @noindent
23796 @code{Perl} needs to be installed on your machine to run this script.
23797 @code{Perl} is freely available for almost every architecture and
23798 Operating System via the Internet.
23799
23800 On Unix systems, you  may want to modify  the  first line of  the script
23801 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
23802 is. The syntax of this line is:
23803 @smallexample
23804 #!full_path_name_to_perl
23805 @end smallexample
23806
23807 @noindent
23808 Alternatively, you may run the script using the following command line:
23809
23810 @smallexample
23811 @c $ perl gnathtml.pl @ovar{switches} @var{files}
23812 @c Expanding @ovar macro inline (explanation in macro def comments)
23813 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
23814 @end smallexample
23815
23816 @ifset vms
23817 @node LSE
23818 @section LSE
23819 @findex LSE
23820
23821 @noindent
23822 The GNAT distribution provides an Ada 95 template for the HP Language
23823 Sensitive Editor (LSE), a component of DECset. In order to
23824 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
23825
23826 @node Profiling
23827 @section Profiling
23828 @findex PCA
23829
23830 @noindent
23831 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
23832 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
23833 the collection phase with the /DEBUG qualifier.
23834
23835 @smallexample
23836 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
23837 $ DEFINE LIB$DEBUG PCA$COLLECTOR
23838 $ RUN/DEBUG <PROGRAM_NAME>
23839 @end smallexample
23840 @noindent
23841 @end ifset
23842
23843 @ifclear vms
23844 @c ******************************
23845 @node Code Coverage and Profiling
23846 @chapter Code Coverage and Profiling
23847 @cindex Code Coverage
23848 @cindex Profiling
23849
23850 @noindent
23851 This chapter describes how to use @code{gcov} - coverage testing tool - and
23852 @code{gprof} - profiler tool - on your Ada programs.
23853
23854 @menu
23855 * Code Coverage of Ada Programs using gcov::
23856 * Profiling an Ada Program using gprof::
23857 @end menu
23858
23859 @node Code Coverage of Ada Programs using gcov
23860 @section Code Coverage of Ada Programs using gcov
23861 @cindex gcov
23862 @cindex -fprofile-arcs
23863 @cindex -ftest-coverage
23864 @cindex -coverage
23865 @cindex Code Coverage
23866
23867 @noindent
23868 @code{gcov} is a test coverage program: it analyzes the execution of a given
23869 program on selected tests, to help you determine the portions of the program
23870 that are still untested.
23871
23872 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
23873 User's Guide. You can refer to this documentation for a more complete
23874 description.
23875
23876 This chapter provides a quick startup guide, and
23877 details some Gnat-specific features.
23878
23879 @menu
23880 * Quick startup guide::
23881 * Gnat specifics::
23882 @end menu
23883
23884 @node Quick startup guide
23885 @subsection Quick startup guide
23886
23887 In order to perform coverage analysis of a program using @code{gcov}, 3
23888 steps are needed:
23889
23890 @itemize @bullet
23891 @item
23892 Code instrumentation during the compilation process
23893 @item
23894 Execution of the instrumented program
23895 @item
23896 Execution of the @code{gcov} tool to generate the result.
23897 @end itemize
23898
23899 The code instrumentation needed by gcov is created at the object level:
23900 The source code is not modified in any way, because the instrumentation code is
23901 inserted by gcc during the compilation process. To compile your code with code
23902 coverage activated, you need to recompile your whole project using the
23903 switches
23904 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
23905 @code{-fprofile-arcs}.
23906
23907 @smallexample
23908 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
23909    -largs -fprofile-arcs
23910 @end smallexample
23911
23912 This compilation process will create @file{.gcno} files together with
23913 the usual object files.
23914
23915 Once the program is compiled with coverage instrumentation, you can
23916 run it as many times as needed - on portions of a test suite for
23917 example. The first execution will produce @file{.gcda} files at the
23918 same location as the @file{.gcno} files.  The following executions
23919 will update those files, so that a cumulative result of the covered
23920 portions of the program is generated.
23921
23922 Finally, you need to call the @code{gcov} tool. The different options of
23923 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
23924
23925 This will create annotated source files with a @file{.gcov} extension:
23926 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
23927
23928 @node Gnat specifics
23929 @subsection Gnat specifics
23930
23931 Because Ada semantics, portions of the source code may be shared among
23932 several object files. This is the case for example when generics are
23933 involved, when inlining is active  or when declarations generate  initialisation
23934 calls. In order to take
23935 into account this shared code, you need to call @code{gcov} on all
23936 source files of the tested program at once.
23937
23938 The list of source files might exceed the system's maximum command line
23939 length. In order to bypass this limitation, a new mechanism has been
23940 implemented in @code{gcov}: you can now list all your project's files into a
23941 text file, and provide this file to gcov as a parameter,  preceded by a @@
23942 (e.g. @samp{gcov @@mysrclist.txt}).
23943
23944 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
23945 not supported as there can be unresolved symbols during the final link.
23946
23947 @node Profiling an Ada Program using gprof
23948 @section Profiling an Ada Program using gprof
23949 @cindex gprof
23950 @cindex -pg
23951 @cindex Profiling
23952
23953 @noindent
23954 This section is not meant to be an exhaustive documentation of @code{gprof}.
23955 Full documentation for it can be found in the GNU Profiler User's Guide
23956 documentation that is part of this GNAT distribution.
23957
23958 Profiling a program helps determine the parts of a program that are executed
23959 most often, and are therefore the most time-consuming.
23960
23961 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
23962 better handle Ada programs and multitasking.
23963 It is currently supported on the following platforms
23964 @itemize @bullet
23965 @item
23966 linux x86/x86_64
23967 @item
23968 solaris sparc/sparc64/x86
23969 @item
23970 windows x86
23971 @end itemize
23972
23973 @noindent
23974 In order to profile a program using @code{gprof}, 3 steps are needed:
23975
23976 @itemize @bullet
23977 @item
23978 Code instrumentation, requiring a full recompilation of the project with the
23979 proper switches.
23980 @item
23981 Execution of the program under the analysis conditions, i.e. with the desired
23982 input.
23983 @item
23984 Analysis of the results using the @code{gprof} tool.
23985 @end itemize
23986
23987 @noindent
23988 The following sections detail the different steps, and indicate how
23989 to interpret the results:
23990 @menu
23991 * Compilation for profiling::
23992 * Program execution::
23993 * Running gprof::
23994 * Interpretation of profiling results::
23995 @end menu
23996
23997 @node Compilation for profiling
23998 @subsection Compilation for profiling
23999 @cindex -pg
24000 @cindex Profiling
24001
24002 In order to profile a program the first step is to tell the compiler
24003 to generate the necessary profiling information. The compiler switch to be used
24004 is @code{-pg}, which must be added to other compilation switches. This
24005 switch needs to be specified both during compilation and link stages, and can
24006 be specified once when using gnatmake:
24007
24008 @smallexample
24009 gnatmake -f -pg -P my_project
24010 @end smallexample
24011
24012 @noindent
24013 Note that only the objects that were compiled with the @samp{-pg} switch will be
24014 profiled; if you need to profile your whole project, use the
24015 @samp{-f} gnatmake switch to force full recompilation.
24016
24017 @node Program execution
24018 @subsection Program execution
24019
24020 @noindent
24021 Once the program has been compiled for profiling, you can run it as usual.
24022
24023 The only constraint imposed by profiling is that the program must terminate
24024 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
24025 properly analyzed.
24026
24027 Once the program completes execution, a data file called @file{gmon.out} is
24028 generated in the directory where the program was launched from. If this file
24029 already exists, it will be overwritten.
24030
24031 @node Running gprof
24032 @subsection Running gprof
24033
24034 @noindent
24035 The @code{gprof} tool is called as follow:
24036
24037 @smallexample
24038 gprof my_prog gmon.out
24039 @end smallexample
24040
24041 @noindent
24042 or simpler:
24043
24044 @smallexample
24045 gprof my_prog
24046 @end smallexample
24047
24048 @noindent
24049 The complete form of the gprof command line is the following:
24050
24051 @smallexample
24052 gprof [^switches^options^] [executable [data-file]]
24053 @end smallexample
24054
24055 @noindent
24056 @code{gprof} supports numerous ^switch^options^. The order of these
24057 ^switch^options^ does not matter. The full list of options can be found in
24058 the GNU Profiler User's Guide documentation that comes with this documentation.
24059
24060 The following is the subset of those switches that is most relevant:
24061
24062 @table @option
24063
24064 @item --demangle[=@var{style}]
24065 @itemx --no-demangle
24066 @cindex @option{--demangle} (@code{gprof})
24067 These options control whether symbol names should be demangled when
24068 printing output.  The default is to demangle C++ symbols.  The
24069 @code{--no-demangle} option may be used to turn off demangling. Different
24070 compilers have different mangling styles.  The optional demangling style
24071 argument can be used to choose an appropriate demangling style for your
24072 compiler, in particular Ada symbols generated by GNAT can be demangled using
24073 @code{--demangle=gnat}.
24074
24075 @item -e @var{function_name}
24076 @cindex @option{-e} (@code{gprof})
24077 The @samp{-e @var{function}} option tells @code{gprof} not to print
24078 information about the function @var{function_name} (and its
24079 children@dots{}) in the call graph.  The function will still be listed
24080 as a child of any functions that call it, but its index number will be
24081 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
24082 given; only one @var{function_name} may be indicated with each @samp{-e}
24083 option.
24084
24085 @item -E @var{function_name}
24086 @cindex @option{-E} (@code{gprof})
24087 The @code{-E @var{function}} option works like the @code{-e} option, but
24088 execution time spent in the function (and children who were not called from
24089 anywhere else), will not be used to compute the percentages-of-time for
24090 the call graph.  More than one @samp{-E} option may be given; only one
24091 @var{function_name} may be indicated with each @samp{-E} option.
24092
24093 @item -f @var{function_name}
24094 @cindex @option{-f} (@code{gprof})
24095 The @samp{-f @var{function}} option causes @code{gprof} to limit the
24096 call graph to the function @var{function_name} and its children (and
24097 their children@dots{}).  More than one @samp{-f} option may be given;
24098 only one @var{function_name} may be indicated with each @samp{-f}
24099 option.
24100
24101 @item -F @var{function_name}
24102 @cindex @option{-F} (@code{gprof})
24103 The @samp{-F @var{function}} option works like the @code{-f} option, but
24104 only time spent in the function and its children (and their
24105 children@dots{}) will be used to determine total-time and
24106 percentages-of-time for the call graph.  More than one @samp{-F} option
24107 may be given; only one @var{function_name} may be indicated with each
24108 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
24109
24110 @end table
24111
24112 @node Interpretation of profiling results
24113 @subsection Interpretation of profiling results
24114
24115 @noindent
24116
24117 The results of the profiling analysis are represented by two arrays: the
24118 'flat profile' and the 'call graph'. Full documentation of those outputs
24119 can be found in the GNU Profiler User's Guide.
24120
24121 The flat profile shows the time spent in each function of the program, and how
24122 many time it has been called. This allows you to locate easily the most
24123 time-consuming functions.
24124
24125 The call graph shows, for each subprogram, the subprograms that call it,
24126 and the subprograms that it calls. It also provides an estimate of the time
24127 spent in each of those callers/called subprograms.
24128 @end ifclear
24129
24130 @c ******************************
24131 @node Running and Debugging Ada Programs
24132 @chapter Running and Debugging Ada Programs
24133 @cindex Debugging
24134
24135 @noindent
24136 This chapter discusses how to debug Ada programs.
24137 @ifset vms
24138 It applies to GNAT on the Alpha OpenVMS platform;
24139 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
24140 since HP has implemented Ada support in the OpenVMS debugger on I64.
24141 @end ifset
24142
24143 An incorrect Ada program may be handled in three ways by the GNAT compiler:
24144
24145 @enumerate
24146 @item
24147 The illegality may be a violation of the static semantics of Ada. In
24148 that case GNAT diagnoses the constructs in the program that are illegal.
24149 It is then a straightforward matter for the user to modify those parts of
24150 the program.
24151
24152 @item
24153 The illegality may be a violation of the dynamic semantics of Ada. In
24154 that case the program compiles and executes, but may generate incorrect
24155 results, or may terminate abnormally with some exception.
24156
24157 @item
24158 When presented with a program that contains convoluted errors, GNAT
24159 itself may terminate abnormally without providing full diagnostics on
24160 the incorrect user program.
24161 @end enumerate
24162
24163 @menu
24164 * The GNAT Debugger GDB::
24165 * Running GDB::
24166 * Introduction to GDB Commands::
24167 * Using Ada Expressions::
24168 * Calling User-Defined Subprograms::
24169 * Using the Next Command in a Function::
24170 * Ada Exceptions::
24171 * Ada Tasks::
24172 * Debugging Generic Units::
24173 * GNAT Abnormal Termination or Failure to Terminate::
24174 * Naming Conventions for GNAT Source Files::
24175 * Getting Internal Debugging Information::
24176 * Stack Traceback::
24177 @end menu
24178
24179 @cindex Debugger
24180 @findex gdb
24181
24182 @node The GNAT Debugger GDB
24183 @section The GNAT Debugger GDB
24184
24185 @noindent
24186 @code{GDB} is a general purpose, platform-independent debugger that
24187 can be used to debug mixed-language programs compiled with @command{gcc},
24188 and in particular is capable of debugging Ada programs compiled with
24189 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
24190 complex Ada data structures.
24191
24192 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
24193 @ifset vms
24194 located in the GNU:[DOCS] directory,
24195 @end ifset
24196 for full details on the usage of @code{GDB}, including a section on
24197 its usage on programs. This manual should be consulted for full
24198 details. The section that follows is a brief introduction to the
24199 philosophy and use of @code{GDB}.
24200
24201 When GNAT programs are compiled, the compiler optionally writes debugging
24202 information into the generated object file, including information on
24203 line numbers, and on declared types and variables. This information is
24204 separate from the generated code. It makes the object files considerably
24205 larger, but it does not add to the size of the actual executable that
24206 will be loaded into memory, and has no impact on run-time performance. The
24207 generation of debug information is triggered by the use of the
24208 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
24209 used to carry out the compilations. It is important to emphasize that
24210 the use of these options does not change the generated code.
24211
24212 The debugging information is written in standard system formats that
24213 are used by many tools, including debuggers and profilers. The format
24214 of the information is typically designed to describe C types and
24215 semantics, but GNAT implements a translation scheme which allows full
24216 details about Ada types and variables to be encoded into these
24217 standard C formats. Details of this encoding scheme may be found in
24218 the file exp_dbug.ads in the GNAT source distribution. However, the
24219 details of this encoding are, in general, of no interest to a user,
24220 since @code{GDB} automatically performs the necessary decoding.
24221
24222 When a program is bound and linked, the debugging information is
24223 collected from the object files, and stored in the executable image of
24224 the program. Again, this process significantly increases the size of
24225 the generated executable file, but it does not increase the size of
24226 the executable program itself. Furthermore, if this program is run in
24227 the normal manner, it runs exactly as if the debug information were
24228 not present, and takes no more actual memory.
24229
24230 However, if the program is run under control of @code{GDB}, the
24231 debugger is activated.  The image of the program is loaded, at which
24232 point it is ready to run.  If a run command is given, then the program
24233 will run exactly as it would have if @code{GDB} were not present. This
24234 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
24235 entirely non-intrusive until a breakpoint is encountered.  If no
24236 breakpoint is ever hit, the program will run exactly as it would if no
24237 debugger were present. When a breakpoint is hit, @code{GDB} accesses
24238 the debugging information and can respond to user commands to inspect
24239 variables, and more generally to report on the state of execution.
24240
24241 @c **************
24242 @node Running GDB
24243 @section Running GDB
24244
24245 @noindent
24246 This section describes how to initiate the debugger.
24247 @c The above sentence is really just filler, but it was otherwise
24248 @c clumsy to get the first paragraph nonindented given the conditional
24249 @c nature of the description
24250
24251 @ifclear vms
24252 The debugger can be launched from a @code{GPS} menu or
24253 directly from the command line. The description below covers the latter use.
24254 All the commands shown can be used in the @code{GPS} debug console window,
24255 but there are usually more GUI-based ways to achieve the same effect.
24256 @end ifclear
24257
24258 The command to run @code{GDB} is
24259
24260 @smallexample
24261 $ ^gdb program^GDB PROGRAM^
24262 @end smallexample
24263
24264 @noindent
24265 where @code{^program^PROGRAM^} is the name of the executable file. This
24266 activates the debugger and results in a prompt for debugger commands.
24267 The simplest command is simply @code{run}, which causes the program to run
24268 exactly as if the debugger were not present. The following section
24269 describes some of the additional commands that can be given to @code{GDB}.
24270
24271 @c *******************************
24272 @node Introduction to GDB Commands
24273 @section Introduction to GDB Commands
24274
24275 @noindent
24276 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
24277 Debugging with GDB, gdb, Debugging with GDB},
24278 @ifset vms
24279 located in the GNU:[DOCS] directory,
24280 @end ifset
24281 for extensive documentation on the use
24282 of these commands, together with examples of their use. Furthermore,
24283 the command @command{help} invoked from within GDB activates a simple help
24284 facility which summarizes the available commands and their options.
24285 In this section we summarize a few of the most commonly
24286 used commands to give an idea of what @code{GDB} is about. You should create
24287 a simple program with debugging information and experiment with the use of
24288 these @code{GDB} commands on the program as you read through the
24289 following section.
24290
24291 @table @code
24292 @item set args @var{arguments}
24293 The @var{arguments} list above is a list of arguments to be passed to
24294 the program on a subsequent run command, just as though the arguments
24295 had been entered on a normal invocation of the program. The @code{set args}
24296 command is not needed if the program does not require arguments.
24297
24298 @item run
24299 The @code{run} command causes execution of the program to start from
24300 the beginning. If the program is already running, that is to say if
24301 you are currently positioned at a breakpoint, then a prompt will ask
24302 for confirmation that you want to abandon the current execution and
24303 restart.
24304
24305 @item breakpoint @var{location}
24306 The breakpoint command sets a breakpoint, that is to say a point at which
24307 execution will halt and @code{GDB} will await further
24308 commands. @var{location} is
24309 either a line number within a file, given in the format @code{file:linenumber},
24310 or it is the name of a subprogram. If you request that a breakpoint be set on
24311 a subprogram that is overloaded, a prompt will ask you to specify on which of
24312 those subprograms you want to breakpoint. You can also
24313 specify that all of them should be breakpointed. If the program is run
24314 and execution encounters the breakpoint, then the program
24315 stops and @code{GDB} signals that the breakpoint was encountered by
24316 printing the line of code before which the program is halted.
24317
24318 @item breakpoint exception @var{name}
24319 A special form of the breakpoint command which breakpoints whenever
24320 exception @var{name} is raised.
24321 If @var{name} is omitted,
24322 then a breakpoint will occur when any exception is raised.
24323
24324 @item print @var{expression}
24325 This will print the value of the given expression. Most simple
24326 Ada expression formats are properly handled by @code{GDB}, so the expression
24327 can contain function calls, variables, operators, and attribute references.
24328
24329 @item continue
24330 Continues execution following a breakpoint, until the next breakpoint or the
24331 termination of the program.
24332
24333 @item step
24334 Executes a single line after a breakpoint. If the next statement
24335 is a subprogram call, execution continues into (the first statement of)
24336 the called subprogram.
24337
24338 @item next
24339 Executes a single line. If this line is a subprogram call, executes and
24340 returns from the call.
24341
24342 @item list
24343 Lists a few lines around the current source location. In practice, it
24344 is usually more convenient to have a separate edit window open with the
24345 relevant source file displayed. Successive applications of this command
24346 print subsequent lines. The command can be given an argument which is a
24347 line number, in which case it displays a few lines around the specified one.
24348
24349 @item backtrace
24350 Displays a backtrace of the call chain. This command is typically
24351 used after a breakpoint has occurred, to examine the sequence of calls that
24352 leads to the current breakpoint. The display includes one line for each
24353 activation record (frame) corresponding to an active subprogram.
24354
24355 @item up
24356 At a breakpoint, @code{GDB} can display the values of variables local
24357 to the current frame. The command @code{up} can be used to
24358 examine the contents of other active frames, by moving the focus up
24359 the stack, that is to say from callee to caller, one frame at a time.
24360
24361 @item down
24362 Moves the focus of @code{GDB} down from the frame currently being
24363 examined to the frame of its callee (the reverse of the previous command),
24364
24365 @item frame @var{n}
24366 Inspect the frame with the given number. The value 0 denotes the frame
24367 of the current breakpoint, that is to say the top of the call stack.
24368
24369 @end table
24370
24371 @noindent
24372 The above list is a very short introduction to the commands that
24373 @code{GDB} provides. Important additional capabilities, including conditional
24374 breakpoints, the ability to execute command sequences on a breakpoint,
24375 the ability to debug at the machine instruction level and many other
24376 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
24377 Debugging with GDB}.  Note that most commands can be abbreviated
24378 (for example, c for continue, bt for backtrace).
24379
24380 @node Using Ada Expressions
24381 @section Using Ada Expressions
24382 @cindex Ada expressions
24383
24384 @noindent
24385 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
24386 extensions. The philosophy behind the design of this subset is
24387
24388 @itemize @bullet
24389 @item
24390 That @code{GDB} should provide basic literals and access to operations for
24391 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
24392 leaving more sophisticated computations to subprograms written into the
24393 program (which therefore may be called from @code{GDB}).
24394
24395 @item
24396 That type safety and strict adherence to Ada language restrictions
24397 are not particularly important to the @code{GDB} user.
24398
24399 @item
24400 That brevity is important to the @code{GDB} user.
24401 @end itemize
24402
24403 @noindent
24404 Thus, for brevity, the debugger acts as if there were
24405 implicit @code{with} and @code{use} clauses in effect for all user-written
24406 packages, thus making it unnecessary to fully qualify most names with
24407 their packages, regardless of context. Where this causes ambiguity,
24408 @code{GDB} asks the user's intent.
24409
24410 For details on the supported Ada syntax, see @ref{Top,, Debugging with
24411 GDB, gdb, Debugging with GDB}.
24412
24413 @node Calling User-Defined Subprograms
24414 @section Calling User-Defined Subprograms
24415
24416 @noindent
24417 An important capability of @code{GDB} is the ability to call user-defined
24418 subprograms while debugging. This is achieved simply by entering
24419 a subprogram call statement in the form:
24420
24421 @smallexample
24422 call subprogram-name (parameters)
24423 @end smallexample
24424
24425 @noindent
24426 The keyword @code{call} can be omitted in the normal case where the
24427 @code{subprogram-name} does not coincide with any of the predefined
24428 @code{GDB} commands.
24429
24430 The effect is to invoke the given subprogram, passing it the
24431 list of parameters that is supplied. The parameters can be expressions and
24432 can include variables from the program being debugged. The
24433 subprogram must be defined
24434 at the library level within your program, and @code{GDB} will call the
24435 subprogram within the environment of your program execution (which
24436 means that the subprogram is free to access or even modify variables
24437 within your program).
24438
24439 The most important use of this facility is in allowing the inclusion of
24440 debugging routines that are tailored to particular data structures
24441 in your program. Such debugging routines can be written to provide a suitably
24442 high-level description of an abstract type, rather than a low-level dump
24443 of its physical layout. After all, the standard
24444 @code{GDB print} command only knows the physical layout of your
24445 types, not their abstract meaning. Debugging routines can provide information
24446 at the desired semantic level and are thus enormously useful.
24447
24448 For example, when debugging GNAT itself, it is crucial to have access to
24449 the contents of the tree nodes used to represent the program internally.
24450 But tree nodes are represented simply by an integer value (which in turn
24451 is an index into a table of nodes).
24452 Using the @code{print} command on a tree node would simply print this integer
24453 value, which is not very useful. But the PN routine (defined in file
24454 treepr.adb in the GNAT sources) takes a tree node as input, and displays
24455 a useful high level representation of the tree node, which includes the
24456 syntactic category of the node, its position in the source, the integers
24457 that denote descendant nodes and parent node, as well as varied
24458 semantic information. To study this example in more detail, you might want to
24459 look at the body of the PN procedure in the stated file.
24460
24461 @node Using the Next Command in a Function
24462 @section Using the Next Command in a Function
24463
24464 @noindent
24465 When you use the @code{next} command in a function, the current source
24466 location will advance to the next statement as usual. A special case
24467 arises in the case of a @code{return} statement.
24468
24469 Part of the code for a return statement is the ``epilog'' of the function.
24470 This is the code that returns to the caller. There is only one copy of
24471 this epilog code, and it is typically associated with the last return
24472 statement in the function if there is more than one return. In some
24473 implementations, this epilog is associated with the first statement
24474 of the function.
24475
24476 The result is that if you use the @code{next} command from a return
24477 statement that is not the last return statement of the function you
24478 may see a strange apparent jump to the last return statement or to
24479 the start of the function. You should simply ignore this odd jump.
24480 The value returned is always that from the first return statement
24481 that was stepped through.
24482
24483 @node Ada Exceptions
24484 @section Breaking on Ada Exceptions
24485 @cindex Exceptions
24486
24487 @noindent
24488 You can set breakpoints that trip when your program raises
24489 selected exceptions.
24490
24491 @table @code
24492 @item break exception
24493 Set a breakpoint that trips whenever (any task in the) program raises
24494 any exception.
24495
24496 @item break exception @var{name}
24497 Set a breakpoint that trips whenever (any task in the) program raises
24498 the exception @var{name}.
24499
24500 @item break exception unhandled
24501 Set a breakpoint that trips whenever (any task in the) program raises an
24502 exception for which there is no handler.
24503
24504 @item info exceptions
24505 @itemx info exceptions @var{regexp}
24506 The @code{info exceptions} command permits the user to examine all defined
24507 exceptions within Ada programs. With a regular expression, @var{regexp}, as
24508 argument, prints out only those exceptions whose name matches @var{regexp}.
24509 @end table
24510
24511 @node Ada Tasks
24512 @section Ada Tasks
24513 @cindex Tasks
24514
24515 @noindent
24516 @code{GDB} allows the following task-related commands:
24517
24518 @table @code
24519 @item info tasks
24520 This command shows a list of current Ada tasks, as in the following example:
24521
24522 @smallexample
24523 @iftex
24524 @leftskip=0cm
24525 @end iftex
24526 (gdb) info tasks
24527   ID       TID P-ID   Thread Pri State                 Name
24528    1   8088000   0   807e000  15 Child Activation Wait main_task
24529    2   80a4000   1   80ae000  15 Accept/Select Wait    b
24530    3   809a800   1   80a4800  15 Child Activation Wait a
24531 *  4   80ae800   3   80b8000  15 Running               c
24532 @end smallexample
24533
24534 @noindent
24535 In this listing, the asterisk before the first task indicates it to be the
24536 currently running task. The first column lists the task ID that is used
24537 to refer to tasks in the following commands.
24538
24539 @item break @var{linespec} task @var{taskid}
24540 @itemx break @var{linespec} task @var{taskid} if @dots{}
24541 @cindex Breakpoints and tasks
24542 These commands are like the @code{break @dots{} thread @dots{}}.
24543 @var{linespec} specifies source lines.
24544
24545 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
24546 to specify that you only want @code{GDB} to stop the program when a
24547 particular Ada task reaches this breakpoint. @var{taskid} is one of the
24548 numeric task identifiers assigned by @code{GDB}, shown in the first
24549 column of the @samp{info tasks} display.
24550
24551 If you do not specify @samp{task @var{taskid}} when you set a
24552 breakpoint, the breakpoint applies to @emph{all} tasks of your
24553 program.
24554
24555 You can use the @code{task} qualifier on conditional breakpoints as
24556 well; in this case, place @samp{task @var{taskid}} before the
24557 breakpoint condition (before the @code{if}).
24558
24559 @item task @var{taskno}
24560 @cindex Task switching
24561
24562 This command allows to switch to the task referred by @var{taskno}. In
24563 particular, This allows to browse the backtrace of the specified
24564 task. It is advised to switch back to the original task before
24565 continuing execution otherwise the scheduling of the program may be
24566 perturbed.
24567 @end table
24568
24569 @noindent
24570 For more detailed information on the tasking support,
24571 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
24572
24573 @node Debugging Generic Units
24574 @section Debugging Generic Units
24575 @cindex Debugging Generic Units
24576 @cindex Generics
24577
24578 @noindent
24579 GNAT always uses code expansion for generic instantiation. This means that
24580 each time an instantiation occurs, a complete copy of the original code is
24581 made, with appropriate substitutions of formals by actuals.
24582
24583 It is not possible to refer to the original generic entities in
24584 @code{GDB}, but it is always possible to debug a particular instance of
24585 a generic, by using the appropriate expanded names. For example, if we have
24586
24587 @smallexample @c ada
24588 @group
24589 @cartouche
24590 procedure g is
24591
24592    generic package k is
24593       procedure kp (v1 : in out integer);
24594    end k;
24595
24596    package body k is
24597       procedure kp (v1 : in out integer) is
24598       begin
24599          v1 := v1 + 1;
24600       end kp;
24601    end k;
24602
24603    package k1 is new k;
24604    package k2 is new k;
24605
24606    var : integer := 1;
24607
24608 begin
24609    k1.kp (var);
24610    k2.kp (var);
24611    k1.kp (var);
24612    k2.kp (var);
24613 end;
24614 @end cartouche
24615 @end group
24616 @end smallexample
24617
24618 @noindent
24619 Then to break on a call to procedure kp in the k2 instance, simply
24620 use the command:
24621
24622 @smallexample
24623 (gdb) break g.k2.kp
24624 @end smallexample
24625
24626 @noindent
24627 When the breakpoint occurs, you can step through the code of the
24628 instance in the normal manner and examine the values of local variables, as for
24629 other units.
24630
24631 @node GNAT Abnormal Termination or Failure to Terminate
24632 @section GNAT Abnormal Termination or Failure to Terminate
24633 @cindex GNAT Abnormal Termination or Failure to Terminate
24634
24635 @noindent
24636 When presented with programs that contain serious errors in syntax
24637 or semantics,
24638 GNAT may on rare occasions  experience problems in operation, such
24639 as aborting with a
24640 segmentation fault or illegal memory access, raising an internal
24641 exception, terminating abnormally, or failing to terminate at all.
24642 In such cases, you can activate
24643 various features of GNAT that can help you pinpoint the construct in your
24644 program that is the likely source of the problem.
24645
24646 The following strategies are presented in increasing order of
24647 difficulty, corresponding to your experience in using GNAT and your
24648 familiarity with compiler internals.
24649
24650 @enumerate
24651 @item
24652 Run @command{gcc} with the @option{-gnatf}. This first
24653 switch causes all errors on a given line to be reported. In its absence,
24654 only the first error on a line is displayed.
24655
24656 The @option{-gnatdO} switch causes errors to be displayed as soon as they
24657 are encountered, rather than after compilation is terminated. If GNAT
24658 terminates prematurely or goes into an infinite loop, the last error
24659 message displayed may help to pinpoint the culprit.
24660
24661 @item
24662 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
24663 mode, @command{gcc} produces ongoing information about the progress of the
24664 compilation and provides the name of each procedure as code is
24665 generated. This switch allows you to find which Ada procedure was being
24666 compiled when it encountered a code generation problem.
24667
24668 @item
24669 @cindex @option{-gnatdc} switch
24670 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
24671 switch that does for the front-end what @option{^-v^VERBOSE^} does
24672 for the back end. The system prints the name of each unit,
24673 either a compilation unit or nested unit, as it is being analyzed.
24674 @item
24675 Finally, you can start
24676 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
24677 front-end of GNAT, and can be run independently (normally it is just
24678 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
24679 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
24680 @code{where} command is the first line of attack; the variable
24681 @code{lineno} (seen by @code{print lineno}), used by the second phase of
24682 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
24683 which the execution stopped, and @code{input_file name} indicates the name of
24684 the source file.
24685 @end enumerate
24686
24687 @node Naming Conventions for GNAT Source Files
24688 @section Naming Conventions for GNAT Source Files
24689
24690 @noindent
24691 In order to examine the workings of the GNAT system, the following
24692 brief description of its organization may be helpful:
24693
24694 @itemize @bullet
24695 @item
24696 Files with prefix @file{^sc^SC^} contain the lexical scanner.
24697
24698 @item
24699 All files prefixed with @file{^par^PAR^} are components of the parser. The
24700 numbers correspond to chapters of the Ada Reference Manual. For example,
24701 parsing of select statements can be found in @file{par-ch9.adb}.
24702
24703 @item
24704 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
24705 numbers correspond to chapters of the Ada standard. For example, all
24706 issues involving context clauses can be found in @file{sem_ch10.adb}. In
24707 addition, some features of the language require sufficient special processing
24708 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
24709 dynamic dispatching, etc.
24710
24711 @item
24712 All files prefixed with @file{^exp^EXP^} perform normalization and
24713 expansion of the intermediate representation (abstract syntax tree, or AST).
24714 these files use the same numbering scheme as the parser and semantics files.
24715 For example, the construction of record initialization procedures is done in
24716 @file{exp_ch3.adb}.
24717
24718 @item
24719 The files prefixed with @file{^bind^BIND^} implement the binder, which
24720 verifies the consistency of the compilation, determines an order of
24721 elaboration, and generates the bind file.
24722
24723 @item
24724 The files @file{atree.ads} and @file{atree.adb} detail the low-level
24725 data structures used by the front-end.
24726
24727 @item
24728 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
24729 the abstract syntax tree as produced by the parser.
24730
24731 @item
24732 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
24733 all entities, computed during semantic analysis.
24734
24735 @item
24736 Library management issues are dealt with in files with prefix
24737 @file{^lib^LIB^}.
24738
24739 @item
24740 @findex Ada
24741 @cindex Annex A
24742 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
24743 defined in Annex A.
24744
24745 @item
24746 @findex Interfaces
24747 @cindex Annex B
24748 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
24749 defined in Annex B.
24750
24751 @item
24752 @findex System
24753 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
24754 both language-defined children and GNAT run-time routines.
24755
24756 @item
24757 @findex GNAT
24758 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
24759 general-purpose packages, fully documented in their specs. All
24760 the other @file{.c} files are modifications of common @command{gcc} files.
24761 @end itemize
24762
24763 @node Getting Internal Debugging Information
24764 @section Getting Internal Debugging Information
24765
24766 @noindent
24767 Most compilers have internal debugging switches and modes. GNAT
24768 does also, except GNAT internal debugging switches and modes are not
24769 secret. A summary and full description of all the compiler and binder
24770 debug flags are in the file @file{debug.adb}. You must obtain the
24771 sources of the compiler to see the full detailed effects of these flags.
24772
24773 The switches that print the source of the program (reconstructed from
24774 the internal tree) are of general interest for user programs, as are the
24775 options to print
24776 the full internal tree, and the entity table (the symbol table
24777 information). The reconstructed source provides a readable version of the
24778 program after the front-end has completed analysis and  expansion,
24779 and is useful when studying the performance of specific constructs.
24780 For example, constraint checks are indicated, complex aggregates
24781 are replaced with loops and assignments, and tasking primitives
24782 are replaced with run-time calls.
24783
24784 @node Stack Traceback
24785 @section Stack Traceback
24786 @cindex traceback
24787 @cindex stack traceback
24788 @cindex stack unwinding
24789
24790 @noindent
24791 Traceback is a mechanism to display the sequence of subprogram calls that
24792 leads to a specified execution point in a program. Often (but not always)
24793 the execution point is an instruction at which an exception has been raised.
24794 This mechanism is also known as @i{stack unwinding} because it obtains
24795 its information by scanning the run-time stack and recovering the activation
24796 records of all active subprograms. Stack unwinding is one of the most
24797 important tools for program debugging.
24798
24799 The first entry stored in traceback corresponds to the deepest calling level,
24800 that is to say the subprogram currently executing the instruction
24801 from which we want to obtain the traceback.
24802
24803 Note that there is no runtime performance penalty when stack traceback
24804 is enabled, and no exception is raised during program execution.
24805
24806 @menu
24807 * Non-Symbolic Traceback::
24808 * Symbolic Traceback::
24809 @end menu
24810
24811 @node Non-Symbolic Traceback
24812 @subsection Non-Symbolic Traceback
24813 @cindex traceback, non-symbolic
24814
24815 @noindent
24816 Note: this feature is not supported on all platforms. See
24817 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
24818 platforms.
24819
24820 @menu
24821 * Tracebacks From an Unhandled Exception::
24822 * Tracebacks From Exception Occurrences (non-symbolic)::
24823 * Tracebacks From Anywhere in a Program (non-symbolic)::
24824 @end menu
24825
24826 @node Tracebacks From an Unhandled Exception
24827 @subsubsection Tracebacks From an Unhandled Exception
24828
24829 @noindent
24830 A runtime non-symbolic traceback is a list of addresses of call instructions.
24831 To enable this feature you must use the @option{-E}
24832 @code{gnatbind}'s option. With this option a stack traceback is stored as part
24833 of exception information. You can retrieve this information using the
24834 @code{addr2line} tool.
24835
24836 Here is a simple example:
24837
24838 @smallexample @c ada
24839 @cartouche
24840 procedure STB is
24841
24842    procedure P1 is
24843    begin
24844       raise Constraint_Error;
24845    end P1;
24846
24847    procedure P2 is
24848    begin
24849       P1;
24850    end P2;
24851
24852 begin
24853    P2;
24854 end STB;
24855 @end cartouche
24856 @end smallexample
24857
24858 @smallexample
24859 $ gnatmake stb -bargs -E
24860 $ stb
24861
24862 Execution terminated by unhandled exception
24863 Exception name: CONSTRAINT_ERROR
24864 Message: stb.adb:5
24865 Call stack traceback locations:
24866 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24867 @end smallexample
24868
24869 @noindent
24870 As we see the traceback lists a sequence of addresses for the unhandled
24871 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
24872 guess that this exception come from procedure P1. To translate these
24873 addresses into the source lines where the calls appear, the
24874 @code{addr2line} tool, described below, is invaluable. The use of this tool
24875 requires the program to be compiled with debug information.
24876
24877 @smallexample
24878 $ gnatmake -g stb -bargs -E
24879 $ stb
24880
24881 Execution terminated by unhandled exception
24882 Exception name: CONSTRAINT_ERROR
24883 Message: stb.adb:5
24884 Call stack traceback locations:
24885 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24886
24887 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
24888    0x4011f1 0x77e892a4
24889
24890 00401373 at d:/stb/stb.adb:5
24891 0040138B at d:/stb/stb.adb:10
24892 0040139C at d:/stb/stb.adb:14
24893 00401335 at d:/stb/b~stb.adb:104
24894 004011C4 at /build/@dots{}/crt1.c:200
24895 004011F1 at /build/@dots{}/crt1.c:222
24896 77E892A4 in ?? at ??:0
24897 @end smallexample
24898
24899 @noindent
24900 The @code{addr2line} tool has several other useful options:
24901
24902 @table @code
24903 @item --functions
24904 to get the function name corresponding to any location
24905
24906 @item --demangle=gnat
24907 to use the gnat decoding mode for the function names. Note that
24908 for binutils version 2.9.x the option is simply @option{--demangle}.
24909 @end table
24910
24911 @smallexample
24912 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
24913    0x40139c 0x401335 0x4011c4 0x4011f1
24914
24915 00401373 in stb.p1 at d:/stb/stb.adb:5
24916 0040138B in stb.p2 at d:/stb/stb.adb:10
24917 0040139C in stb at d:/stb/stb.adb:14
24918 00401335 in main at d:/stb/b~stb.adb:104
24919 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
24920 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
24921 @end smallexample
24922
24923 @noindent
24924 From this traceback we can see that the exception was raised in
24925 @file{stb.adb} at line 5, which was reached from a procedure call in
24926 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
24927 which contains the call to the main program.
24928 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
24929 and the output will vary from platform to platform.
24930
24931 It is also possible to use @code{GDB} with these traceback addresses to debug
24932 the program. For example, we can break at a given code location, as reported
24933 in the stack traceback:
24934
24935 @smallexample
24936 $ gdb -nw stb
24937 @ifclear vms
24938 @noindent
24939 Furthermore, this feature is not implemented inside Windows DLL. Only
24940 the non-symbolic traceback is reported in this case.
24941 @end ifclear
24942
24943 (gdb) break *0x401373
24944 Breakpoint 1 at 0x401373: file stb.adb, line 5.
24945 @end smallexample
24946
24947 @noindent
24948 It is important to note that the stack traceback addresses
24949 do not change when debug information is included. This is particularly useful
24950 because it makes it possible to release software without debug information (to
24951 minimize object size), get a field report that includes a stack traceback
24952 whenever an internal bug occurs, and then be able to retrieve the sequence
24953 of calls with the same program compiled with debug information.
24954
24955 @node Tracebacks From Exception Occurrences (non-symbolic)
24956 @subsubsection Tracebacks From Exception Occurrences
24957
24958 @noindent
24959 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
24960 The stack traceback is attached to the exception information string, and can
24961 be retrieved in an exception handler within the Ada program, by means of the
24962 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
24963
24964 @smallexample @c ada
24965 with Ada.Text_IO;
24966 with Ada.Exceptions;
24967
24968 procedure STB is
24969
24970    use Ada;
24971    use Ada.Exceptions;
24972
24973    procedure P1 is
24974       K : Positive := 1;
24975    begin
24976       K := K - 1;
24977    exception
24978       when E : others =>
24979          Text_IO.Put_Line (Exception_Information (E));
24980    end P1;
24981
24982    procedure P2 is
24983    begin
24984       P1;
24985    end P2;
24986
24987 begin
24988    P2;
24989 end STB;
24990 @end smallexample
24991
24992 @noindent
24993 This program will output:
24994
24995 @smallexample
24996 $ stb
24997
24998 Exception name: CONSTRAINT_ERROR
24999 Message: stb.adb:12
25000 Call stack traceback locations:
25001 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
25002 @end smallexample
25003
25004 @node Tracebacks From Anywhere in a Program (non-symbolic)
25005 @subsubsection Tracebacks From Anywhere in a Program
25006
25007 @noindent
25008 It is also possible to retrieve a stack traceback from anywhere in a
25009 program. For this you need to
25010 use the @code{GNAT.Traceback} API. This package includes a procedure called
25011 @code{Call_Chain} that computes a complete stack traceback, as well as useful
25012 display procedures described below. It is not necessary to use the
25013 @option{-E gnatbind} option in this case, because the stack traceback mechanism
25014 is invoked explicitly.
25015
25016 @noindent
25017 In the following example we compute a traceback at a specific location in
25018 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
25019 convert addresses to strings:
25020
25021 @smallexample @c ada
25022 with Ada.Text_IO;
25023 with GNAT.Traceback;
25024 with GNAT.Debug_Utilities;
25025
25026 procedure STB is
25027
25028    use Ada;
25029    use GNAT;
25030    use GNAT.Traceback;
25031
25032    procedure P1 is
25033       TB  : Tracebacks_Array (1 .. 10);
25034       --  We are asking for a maximum of 10 stack frames.
25035       Len : Natural;
25036       --  Len will receive the actual number of stack frames returned.
25037    begin
25038       Call_Chain (TB, Len);
25039
25040       Text_IO.Put ("In STB.P1 : ");
25041
25042       for K in 1 .. Len loop
25043          Text_IO.Put (Debug_Utilities.Image (TB (K)));
25044          Text_IO.Put (' ');
25045       end loop;
25046
25047       Text_IO.New_Line;
25048    end P1;
25049
25050    procedure P2 is
25051    begin
25052       P1;
25053    end P2;
25054
25055 begin
25056    P2;
25057 end STB;
25058 @end smallexample
25059
25060 @smallexample
25061 $ gnatmake -g stb
25062 $ stb
25063
25064 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
25065 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
25066 @end smallexample
25067
25068 @noindent
25069 You can then get further information by invoking the @code{addr2line}
25070 tool as described earlier (note that the hexadecimal addresses
25071 need to be specified in C format, with a leading ``0x'').
25072
25073 @node Symbolic Traceback
25074 @subsection Symbolic Traceback
25075 @cindex traceback, symbolic
25076
25077 @noindent
25078 A symbolic traceback is a stack traceback in which procedure names are
25079 associated with each code location.
25080
25081 @noindent
25082 Note that this feature is not supported on all platforms. See
25083 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
25084 list of currently supported platforms.
25085
25086 @noindent
25087 Note that the symbolic traceback requires that the program be compiled
25088 with debug information. If it is not compiled with debug information
25089 only the non-symbolic information will be valid.
25090
25091 @menu
25092 * Tracebacks From Exception Occurrences (symbolic)::
25093 * Tracebacks From Anywhere in a Program (symbolic)::
25094 @end menu
25095
25096 @node Tracebacks From Exception Occurrences (symbolic)
25097 @subsubsection Tracebacks From Exception Occurrences
25098
25099 @smallexample @c ada
25100 with Ada.Text_IO;
25101 with GNAT.Traceback.Symbolic;
25102
25103 procedure STB is
25104
25105    procedure P1 is
25106    begin
25107       raise Constraint_Error;
25108    end P1;
25109
25110    procedure P2 is
25111    begin
25112       P1;
25113    end P2;
25114
25115    procedure P3 is
25116    begin
25117       P2;
25118    end P3;
25119
25120 begin
25121    P3;
25122 exception
25123    when E : others =>
25124       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
25125 end STB;
25126 @end smallexample
25127
25128 @smallexample
25129 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
25130 $ stb
25131
25132 0040149F in stb.p1 at stb.adb:8
25133 004014B7 in stb.p2 at stb.adb:13
25134 004014CF in stb.p3 at stb.adb:18
25135 004015DD in ada.stb at stb.adb:22
25136 00401461 in main at b~stb.adb:168
25137 004011C4 in __mingw_CRTStartup at crt1.c:200
25138 004011F1 in mainCRTStartup at crt1.c:222
25139 77E892A4 in ?? at ??:0
25140 @end smallexample
25141
25142 @noindent
25143 In the above example the ``.\'' syntax in the @command{gnatmake} command
25144 is currently required by @command{addr2line} for files that are in
25145 the current working directory.
25146 Moreover, the exact sequence of linker options may vary from platform
25147 to platform.
25148 The above @option{-largs} section is for Windows platforms. By contrast,
25149 under Unix there is no need for the @option{-largs} section.
25150 Differences across platforms are due to details of linker implementation.
25151
25152 @node Tracebacks From Anywhere in a Program (symbolic)
25153 @subsubsection Tracebacks From Anywhere in a Program
25154
25155 @noindent
25156 It is possible to get a symbolic stack traceback
25157 from anywhere in a program, just as for non-symbolic tracebacks.
25158 The first step is to obtain a non-symbolic
25159 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
25160 information. Here is an example:
25161
25162 @smallexample @c ada
25163 with Ada.Text_IO;
25164 with GNAT.Traceback;
25165 with GNAT.Traceback.Symbolic;
25166
25167 procedure STB is
25168
25169    use Ada;
25170    use GNAT.Traceback;
25171    use GNAT.Traceback.Symbolic;
25172
25173    procedure P1 is
25174       TB  : Tracebacks_Array (1 .. 10);
25175       --  We are asking for a maximum of 10 stack frames.
25176       Len : Natural;
25177       --  Len will receive the actual number of stack frames returned.
25178    begin
25179       Call_Chain (TB, Len);
25180       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
25181    end P1;
25182
25183    procedure P2 is
25184    begin
25185       P1;
25186    end P2;
25187
25188 begin
25189    P2;
25190 end STB;
25191 @end smallexample
25192
25193 @c ******************************
25194 @ifset vms
25195 @node Compatibility with HP Ada
25196 @chapter Compatibility with HP Ada
25197 @cindex Compatibility
25198
25199 @noindent
25200 @cindex DEC Ada
25201 @cindex HP Ada
25202 @cindex Compatibility between GNAT and HP Ada
25203 This chapter compares HP Ada (formerly known as ``DEC Ada'')
25204 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
25205 GNAT is highly compatible
25206 with HP Ada, and it should generally be straightforward to port code
25207 from the HP Ada environment to GNAT. However, there are a few language
25208 and implementation differences of which the user must be aware. These
25209 differences are discussed in this chapter. In
25210 addition, the operating environment and command structure for the
25211 compiler are different, and these differences are also discussed.
25212
25213 For further details on these and other compatibility issues,
25214 see Appendix E of the HP publication
25215 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
25216
25217 Except where otherwise indicated, the description of GNAT for OpenVMS
25218 applies to both the Alpha and I64 platforms.
25219
25220 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
25221 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
25222
25223 The discussion in this chapter addresses specifically the implementation
25224 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
25225 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
25226 GNAT always follows the Alpha implementation.
25227
25228 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
25229 attributes are recognized, although only a subset of them can sensibly
25230 be implemented.  The description of pragmas in
25231 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
25232 indicates whether or not they are applicable to non-VMS systems.
25233
25234 @menu
25235 * Ada Language Compatibility::
25236 * Differences in the Definition of Package System::
25237 * Language-Related Features::
25238 * The Package STANDARD::
25239 * The Package SYSTEM::
25240 * Tasking and Task-Related Features::
25241 * Pragmas and Pragma-Related Features::
25242 * Library of Predefined Units::
25243 * Bindings::
25244 * Main Program Definition::
25245 * Implementation-Defined Attributes::
25246 * Compiler and Run-Time Interfacing::
25247 * Program Compilation and Library Management::
25248 * Input-Output::
25249 * Implementation Limits::
25250 * Tools and Utilities::
25251 @end menu
25252
25253 @node Ada Language Compatibility
25254 @section Ada Language Compatibility
25255
25256 @noindent
25257 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
25258 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
25259 with Ada 83, and therefore Ada 83 programs will compile
25260 and run under GNAT with
25261 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
25262 provides details on specific incompatibilities.
25263
25264 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
25265 as well as the pragma @code{ADA_83}, to force the compiler to
25266 operate in Ada 83 mode. This mode does not guarantee complete
25267 conformance to Ada 83, but in practice is sufficient to
25268 eliminate most sources of incompatibilities.
25269 In particular, it eliminates the recognition of the
25270 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
25271 in Ada 83 programs is legal, and handles the cases of packages
25272 with optional bodies, and generics that instantiate unconstrained
25273 types without the use of @code{(<>)}.
25274
25275 @node Differences in the Definition of Package System
25276 @section Differences in the Definition of Package @code{System}
25277
25278 @noindent
25279 An Ada compiler is allowed to add
25280 implementation-dependent declarations to package @code{System}.
25281 In normal mode,
25282 GNAT does not take advantage of this permission, and the version of
25283 @code{System} provided by GNAT exactly matches that defined in the Ada
25284 Reference Manual.
25285
25286 However, HP Ada adds an extensive set of declarations to package
25287 @code{System},
25288 as fully documented in the HP Ada manuals. To minimize changes required
25289 for programs that make use of these extensions, GNAT provides the pragma
25290 @code{Extend_System} for extending the definition of package System. By using:
25291 @cindex pragma @code{Extend_System}
25292 @cindex @code{Extend_System} pragma
25293
25294 @smallexample @c ada
25295 @group
25296 @cartouche
25297 pragma Extend_System (Aux_DEC);
25298 @end cartouche
25299 @end group
25300 @end smallexample
25301
25302 @noindent
25303 the set of definitions in @code{System} is extended to include those in
25304 package @code{System.Aux_DEC}.
25305 @cindex @code{System.Aux_DEC} package
25306 @cindex @code{Aux_DEC} package (child of @code{System})
25307 These definitions are incorporated directly into package @code{System},
25308 as though they had been declared there. For a
25309 list of the declarations added, see the spec of this package,
25310 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
25311 @cindex @file{s-auxdec.ads} file
25312 The pragma @code{Extend_System} is a configuration pragma, which means that
25313 it can be placed in the file @file{gnat.adc}, so that it will automatically
25314 apply to all subsequent compilations. See @ref{Configuration Pragmas},
25315 for further details.
25316
25317 An alternative approach that avoids the use of the non-standard
25318 @code{Extend_System} pragma is to add a context clause to the unit that
25319 references these facilities:
25320
25321 @smallexample @c ada
25322 @cartouche
25323 with System.Aux_DEC;
25324 use  System.Aux_DEC;
25325 @end cartouche
25326 @end smallexample
25327
25328 @noindent
25329 The effect is not quite semantically identical to incorporating
25330 the declarations directly into package @code{System},
25331 but most programs will not notice a difference
25332 unless they use prefix notation (e.g.@: @code{System.Integer_8})
25333 to reference the entities directly in package @code{System}.
25334 For units containing such references,
25335 the prefixes must either be removed, or the pragma @code{Extend_System}
25336 must be used.
25337
25338 @node Language-Related Features
25339 @section Language-Related Features
25340
25341 @noindent
25342 The following sections highlight differences in types,
25343 representations of types, operations, alignment, and
25344 related topics.
25345
25346 @menu
25347 * Integer Types and Representations::
25348 * Floating-Point Types and Representations::
25349 * Pragmas Float_Representation and Long_Float::
25350 * Fixed-Point Types and Representations::
25351 * Record and Array Component Alignment::
25352 * Address Clauses::
25353 * Other Representation Clauses::
25354 @end menu
25355
25356 @node Integer Types and Representations
25357 @subsection Integer Types and Representations
25358
25359 @noindent
25360 The set of predefined integer types is identical in HP Ada and GNAT.
25361 Furthermore the representation of these integer types is also identical,
25362 including the capability of size clauses forcing biased representation.
25363
25364 In addition,
25365 HP Ada for OpenVMS Alpha systems has defined the
25366 following additional integer types in package @code{System}:
25367
25368 @itemize @bullet
25369
25370 @item
25371 @code{INTEGER_8}
25372
25373 @item
25374 @code{INTEGER_16}
25375
25376 @item
25377 @code{INTEGER_32}
25378
25379 @item
25380 @code{INTEGER_64}
25381
25382 @item
25383 @code{LARGEST_INTEGER}
25384 @end itemize
25385
25386 @noindent
25387 In GNAT, the first four of these types may be obtained from the
25388 standard Ada package @code{Interfaces}.
25389 Alternatively, by use of the pragma @code{Extend_System}, identical
25390 declarations can be referenced directly in package @code{System}.
25391 On both GNAT and HP Ada, the maximum integer size is 64 bits.
25392
25393 @node Floating-Point Types and Representations
25394 @subsection Floating-Point Types and Representations
25395 @cindex Floating-Point types
25396
25397 @noindent
25398 The set of predefined floating-point types is identical in HP Ada and GNAT.
25399 Furthermore the representation of these floating-point
25400 types is also identical. One important difference is that the default
25401 representation for HP Ada is @code{VAX_Float}, but the default representation
25402 for GNAT is IEEE.
25403
25404 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
25405 pragma @code{Float_Representation} as described in the HP Ada
25406 documentation.
25407 For example, the declarations:
25408
25409 @smallexample @c ada
25410 @cartouche
25411 type F_Float is digits 6;
25412 pragma Float_Representation (VAX_Float, F_Float);
25413 @end cartouche
25414 @end smallexample
25415
25416 @noindent
25417 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
25418 format.
25419 This set of declarations actually appears in @code{System.Aux_DEC},
25420 which contains
25421 the full set of additional floating-point declarations provided in
25422 the HP Ada version of package @code{System}.
25423 This and similar declarations may be accessed in a user program
25424 by using pragma @code{Extend_System}. The use of this
25425 pragma, and the related pragma @code{Long_Float} is described in further
25426 detail in the following section.
25427
25428 @node Pragmas Float_Representation and Long_Float
25429 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
25430
25431 @noindent
25432 HP Ada provides the pragma @code{Float_Representation}, which
25433 acts as a program library switch to allow control over
25434 the internal representation chosen for the predefined
25435 floating-point types declared in the package @code{Standard}.
25436 The format of this pragma is as follows:
25437
25438 @smallexample @c ada
25439 @cartouche
25440 pragma Float_Representation(VAX_Float | IEEE_Float);
25441 @end cartouche
25442 @end smallexample
25443
25444 @noindent
25445 This pragma controls the representation of floating-point
25446 types as follows:
25447
25448 @itemize @bullet
25449 @item
25450 @code{VAX_Float} specifies that floating-point
25451 types are represented by default with the VAX system hardware types
25452 @code{F-floating}, @code{D-floating}, @code{G-floating}.
25453 Note that the @code{H-floating}
25454 type was available only on VAX systems, and is not available
25455 in either HP Ada or GNAT.
25456
25457 @item
25458 @code{IEEE_Float} specifies that floating-point
25459 types are represented by default with the IEEE single and
25460 double floating-point types.
25461 @end itemize
25462
25463 @noindent
25464 GNAT provides an identical implementation of the pragma
25465 @code{Float_Representation}, except that it functions as a
25466 configuration pragma. Note that the
25467 notion of configuration pragma corresponds closely to the
25468 HP Ada notion of a program library switch.
25469
25470 When no pragma is used in GNAT, the default is @code{IEEE_Float},
25471 which is different
25472 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
25473 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
25474 advisable to change the format of numbers passed to standard library
25475 routines, and if necessary explicit type conversions may be needed.
25476
25477 The use of @code{IEEE_Float} is recommended in GNAT since it is more
25478 efficient, and (given that it conforms to an international standard)
25479 potentially more portable.
25480 The situation in which @code{VAX_Float} may be useful is in interfacing
25481 to existing code and data that expect the use of @code{VAX_Float}.
25482 In such a situation use the predefined @code{VAX_Float}
25483 types in package @code{System}, as extended by
25484 @code{Extend_System}. For example, use @code{System.F_Float}
25485 to specify the 32-bit @code{F-Float} format.
25486
25487 @noindent
25488 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
25489 to allow control over the internal representation chosen
25490 for the predefined type @code{Long_Float} and for floating-point
25491 type declarations with digits specified in the range 7 .. 15.
25492 The format of this pragma is as follows:
25493
25494 @smallexample @c ada
25495 @cartouche
25496 pragma Long_Float (D_FLOAT | G_FLOAT);
25497 @end cartouche
25498 @end smallexample
25499
25500 @node Fixed-Point Types and Representations
25501 @subsection Fixed-Point Types and Representations
25502
25503 @noindent
25504 On HP Ada for OpenVMS Alpha systems, rounding is
25505 away from zero for both positive and negative numbers.
25506 Therefore, @code{+0.5} rounds to @code{1},
25507 and @code{-0.5} rounds to @code{-1}.
25508
25509 On GNAT the results of operations
25510 on fixed-point types are in accordance with the Ada
25511 rules. In particular, results of operations on decimal
25512 fixed-point types are truncated.
25513
25514 @node Record and Array Component Alignment
25515 @subsection Record and Array Component Alignment
25516
25517 @noindent
25518 On HP Ada for OpenVMS Alpha, all non-composite components
25519 are aligned on natural boundaries. For example, 1-byte
25520 components are aligned on byte boundaries, 2-byte
25521 components on 2-byte boundaries, 4-byte components on 4-byte
25522 byte boundaries, and so on. The OpenVMS Alpha hardware
25523 runs more efficiently with naturally aligned data.
25524
25525 On GNAT, alignment rules are compatible
25526 with HP Ada for OpenVMS Alpha.
25527
25528 @node Address Clauses
25529 @subsection Address Clauses
25530
25531 @noindent
25532 In HP Ada and GNAT, address clauses are supported for
25533 objects and imported subprograms.
25534 The predefined type @code{System.Address} is a private type
25535 in both compilers on Alpha OpenVMS, with the same representation
25536 (it is simply a machine pointer). Addition, subtraction, and comparison
25537 operations are available in the standard Ada package
25538 @code{System.Storage_Elements}, or in package @code{System}
25539 if it is extended to include @code{System.Aux_DEC} using a
25540 pragma @code{Extend_System} as previously described.
25541
25542 Note that code that @code{with}'s both this extended package @code{System}
25543 and the package @code{System.Storage_Elements} should not @code{use}
25544 both packages, or ambiguities will result. In general it is better
25545 not to mix these two sets of facilities. The Ada package was
25546 designed specifically to provide the kind of features that HP Ada
25547 adds directly to package @code{System}.
25548
25549 The type @code{System.Address} is a 64-bit integer type in GNAT for
25550 I64 OpenVMS.  For more information,
25551 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
25552
25553 GNAT is compatible with HP Ada in its handling of address
25554 clauses, except for some limitations in
25555 the form of address clauses for composite objects with
25556 initialization. Such address clauses are easily replaced
25557 by the use of an explicitly-defined constant as described
25558 in the Ada Reference Manual (13.1(22)). For example, the sequence
25559 of declarations:
25560
25561 @smallexample @c ada
25562 @cartouche
25563 X, Y : Integer := Init_Func;
25564 Q : String (X .. Y) := "abc";
25565 @dots{}
25566 for Q'Address use Compute_Address;
25567 @end cartouche
25568 @end smallexample
25569
25570 @noindent
25571 will be rejected by GNAT, since the address cannot be computed at the time
25572 that @code{Q} is declared. To achieve the intended effect, write instead:
25573
25574 @smallexample @c ada
25575 @group
25576 @cartouche
25577 X, Y : Integer := Init_Func;
25578 Q_Address : constant Address := Compute_Address;
25579 Q : String (X .. Y) := "abc";
25580 @dots{}
25581 for Q'Address use Q_Address;
25582 @end cartouche
25583 @end group
25584 @end smallexample
25585
25586 @noindent
25587 which will be accepted by GNAT (and other Ada compilers), and is also
25588 compatible with Ada 83. A fuller description of the restrictions
25589 on address specifications is found in @ref{Top, GNAT Reference Manual,
25590 About This Guide, gnat_rm, GNAT Reference Manual}.
25591
25592 @node Other Representation Clauses
25593 @subsection Other Representation Clauses
25594
25595 @noindent
25596 GNAT implements in a compatible manner all the representation
25597 clauses supported by HP Ada. In addition, GNAT
25598 implements the representation clause forms that were introduced in Ada 95,
25599 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
25600
25601 @node The Package STANDARD
25602 @section The Package @code{STANDARD}
25603
25604 @noindent
25605 The package @code{STANDARD}, as implemented by HP Ada, is fully
25606 described in the @cite{Ada Reference Manual} and in the
25607 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
25608 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
25609
25610 In addition, HP Ada supports the Latin-1 character set in
25611 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
25612 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
25613 the type @code{WIDE_CHARACTER}.
25614
25615 The floating-point types supported by GNAT are those
25616 supported by HP Ada, but the defaults are different, and are controlled by
25617 pragmas. See @ref{Floating-Point Types and Representations}, for details.
25618
25619 @node The Package SYSTEM
25620 @section The Package @code{SYSTEM}
25621
25622 @noindent
25623 HP Ada provides a specific version of the package
25624 @code{SYSTEM} for each platform on which the language is implemented.
25625 For the complete spec of the package @code{SYSTEM}, see
25626 Appendix F of the @cite{HP Ada Language Reference Manual}.
25627
25628 On HP Ada, the package @code{SYSTEM} includes the following conversion
25629 functions:
25630 @itemize @bullet
25631 @item @code{TO_ADDRESS(INTEGER)}
25632
25633 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
25634
25635 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
25636
25637 @item @code{TO_INTEGER(ADDRESS)}
25638
25639 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
25640
25641 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
25642 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
25643 @end itemize
25644
25645 @noindent
25646 By default, GNAT supplies a version of @code{SYSTEM} that matches
25647 the definition given in the @cite{Ada Reference Manual}.
25648 This
25649 is a subset of the HP system definitions, which is as
25650 close as possible to the original definitions. The only difference
25651 is that the definition of @code{SYSTEM_NAME} is different:
25652
25653 @smallexample @c ada
25654 @cartouche
25655 type Name is (SYSTEM_NAME_GNAT);
25656 System_Name : constant Name := SYSTEM_NAME_GNAT;
25657 @end cartouche
25658 @end smallexample
25659
25660 @noindent
25661 Also, GNAT adds the Ada declarations for
25662 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
25663
25664 However, the use of the following pragma causes GNAT
25665 to extend the definition of package @code{SYSTEM} so that it
25666 encompasses the full set of HP-specific extensions,
25667 including the functions listed above:
25668
25669 @smallexample @c ada
25670 @cartouche
25671 pragma Extend_System (Aux_DEC);
25672 @end cartouche
25673 @end smallexample
25674
25675 @noindent
25676 The pragma @code{Extend_System} is a configuration pragma that
25677 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
25678 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
25679
25680 HP Ada does not allow the recompilation of the package
25681 @code{SYSTEM}. Instead HP Ada provides several pragmas
25682 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
25683 to modify values in the package @code{SYSTEM}.
25684 On OpenVMS Alpha systems, the pragma
25685 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
25686 its single argument.
25687
25688 GNAT does permit the recompilation of package @code{SYSTEM} using
25689 the special switch @option{-gnatg}, and this switch can be used if
25690 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
25691 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
25692 or @code{MEMORY_SIZE} by any other means.
25693
25694 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
25695 enumeration literal @code{SYSTEM_NAME_GNAT}.
25696
25697 The definitions provided by the use of
25698
25699 @smallexample @c ada
25700 pragma Extend_System (AUX_Dec);
25701 @end smallexample
25702
25703 @noindent
25704 are virtually identical to those provided by the HP Ada 83 package
25705 @code{SYSTEM}. One important difference is that the name of the
25706 @code{TO_ADDRESS}
25707 function for type @code{UNSIGNED_LONGWORD} is changed to
25708 @code{TO_ADDRESS_LONG}.
25709 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
25710 discussion of why this change was necessary.
25711
25712 @noindent
25713 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
25714 is in fact
25715 an extension to Ada 83 not strictly compatible with the reference manual.
25716 GNAT, in order to be exactly compatible with the standard,
25717 does not provide this capability. In HP Ada 83, the
25718 point of this definition is to deal with a call like:
25719
25720 @smallexample @c ada
25721 TO_ADDRESS (16#12777#);
25722 @end smallexample
25723
25724 @noindent
25725 Normally, according to Ada 83 semantics, one would expect this to be
25726 ambiguous, since it matches both the @code{INTEGER} and
25727 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
25728 However, in HP Ada 83, there is no ambiguity, since the
25729 definition using @i{universal_integer} takes precedence.
25730
25731 In GNAT, since the version with @i{universal_integer} cannot be supplied,
25732 it is
25733 not possible to be 100% compatible. Since there are many programs using
25734 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
25735 GNAT was
25736 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
25737 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
25738
25739 @smallexample @c ada
25740 function To_Address (X : Integer) return Address;
25741 pragma Pure_Function (To_Address);
25742
25743 function To_Address_Long (X : Unsigned_Longword) return Address;
25744 pragma Pure_Function (To_Address_Long);
25745 @end smallexample
25746
25747 @noindent
25748 This means that programs using @code{TO_ADDRESS} for
25749 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
25750
25751 @node Tasking and Task-Related Features
25752 @section Tasking and Task-Related Features
25753
25754 @noindent
25755 This section compares the treatment of tasking in GNAT
25756 and in HP Ada for OpenVMS Alpha.
25757 The GNAT description applies to both Alpha and I64 OpenVMS.
25758 For detailed information on tasking in
25759 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
25760 relevant run-time reference manual.
25761
25762 @menu
25763 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
25764 * Assigning Task IDs::
25765 * Task IDs and Delays::
25766 * Task-Related Pragmas::
25767 * Scheduling and Task Priority::
25768 * The Task Stack::
25769 * External Interrupts::
25770 @end menu
25771
25772 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25773 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25774
25775 @noindent
25776 On OpenVMS Alpha systems, each Ada task (except a passive
25777 task) is implemented as a single stream of execution
25778 that is created and managed by the kernel. On these
25779 systems, HP Ada tasking support is based on DECthreads,
25780 an implementation of the POSIX standard for threads.
25781
25782 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
25783 code that calls DECthreads routines can be used together.
25784 The interaction between Ada tasks and DECthreads routines
25785 can have some benefits. For example when on OpenVMS Alpha,
25786 HP Ada can call C code that is already threaded.
25787
25788 GNAT uses the facilities of DECthreads,
25789 and Ada tasks are mapped to threads.
25790
25791 @node Assigning Task IDs
25792 @subsection Assigning Task IDs
25793
25794 @noindent
25795 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
25796 the environment task that executes the main program. On
25797 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
25798 that have been created but are not yet activated.
25799
25800 On OpenVMS Alpha systems, task IDs are assigned at
25801 activation. On GNAT systems, task IDs are also assigned at
25802 task creation but do not have the same form or values as
25803 task ID values in HP Ada. There is no null task, and the
25804 environment task does not have a specific task ID value.
25805
25806 @node Task IDs and Delays
25807 @subsection Task IDs and Delays
25808
25809 @noindent
25810 On OpenVMS Alpha systems, tasking delays are implemented
25811 using Timer System Services. The Task ID is used for the
25812 identification of the timer request (the @code{REQIDT} parameter).
25813 If Timers are used in the application take care not to use
25814 @code{0} for the identification, because cancelling such a timer
25815 will cancel all timers and may lead to unpredictable results.
25816
25817 @node Task-Related Pragmas
25818 @subsection Task-Related Pragmas
25819
25820 @noindent
25821 Ada supplies the pragma @code{TASK_STORAGE}, which allows
25822 specification of the size of the guard area for a task
25823 stack. (The guard area forms an area of memory that has no
25824 read or write access and thus helps in the detection of
25825 stack overflow.) On OpenVMS Alpha systems, if the pragma
25826 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
25827 area is created. In the absence of a pragma @code{TASK_STORAGE},
25828 a default guard area is created.
25829
25830 GNAT supplies the following task-related pragmas:
25831
25832 @itemize @bullet
25833 @item  @code{TASK_INFO}
25834
25835 This pragma appears within a task definition and
25836 applies to the task in which it appears. The argument
25837 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
25838
25839 @item  @code{TASK_STORAGE}
25840
25841 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
25842 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
25843 @code{SUPPRESS}, and @code{VOLATILE}.
25844 @end itemize
25845 @node Scheduling and Task Priority
25846 @subsection Scheduling and Task Priority
25847
25848 @noindent
25849 HP Ada implements the Ada language requirement that
25850 when two tasks are eligible for execution and they have
25851 different priorities, the lower priority task does not
25852 execute while the higher priority task is waiting. The HP
25853 Ada Run-Time Library keeps a task running until either the
25854 task is suspended or a higher priority task becomes ready.
25855
25856 On OpenVMS Alpha systems, the default strategy is round-
25857 robin with preemption. Tasks of equal priority take turns
25858 at the processor. A task is run for a certain period of
25859 time and then placed at the tail of the ready queue for
25860 its priority level.
25861
25862 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
25863 which can be used to enable or disable round-robin
25864 scheduling of tasks with the same priority.
25865 See the relevant HP Ada run-time reference manual for
25866 information on using the pragmas to control HP Ada task
25867 scheduling.
25868
25869 GNAT follows the scheduling rules of Annex D (Real-Time
25870 Annex) of the @cite{Ada Reference Manual}. In general, this
25871 scheduling strategy is fully compatible with HP Ada
25872 although it provides some additional constraints (as
25873 fully documented in Annex D).
25874 GNAT implements time slicing control in a manner compatible with
25875 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
25876 are identical to the HP Ada 83 pragma of the same name.
25877 Note that it is not possible to mix GNAT tasking and
25878 HP Ada 83 tasking in the same program, since the two run-time
25879 libraries are not compatible.
25880
25881 @node The Task Stack
25882 @subsection The Task Stack
25883
25884 @noindent
25885 In HP Ada, a task stack is allocated each time a
25886 non-passive task is activated. As soon as the task is
25887 terminated, the storage for the task stack is deallocated.
25888 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
25889 a default stack size is used. Also, regardless of the size
25890 specified, some additional space is allocated for task
25891 management purposes. On OpenVMS Alpha systems, at least
25892 one page is allocated.
25893
25894 GNAT handles task stacks in a similar manner. In accordance with
25895 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
25896 an alternative method for controlling the task stack size.
25897 The specification of the attribute @code{T'STORAGE_SIZE} is also
25898 supported in a manner compatible with HP Ada.
25899
25900 @node External Interrupts
25901 @subsection External Interrupts
25902
25903 @noindent
25904 On HP Ada, external interrupts can be associated with task entries.
25905 GNAT is compatible with HP Ada in its handling of external interrupts.
25906
25907 @node Pragmas and Pragma-Related Features
25908 @section Pragmas and Pragma-Related Features
25909
25910 @noindent
25911 Both HP Ada and GNAT supply all language-defined pragmas
25912 as specified by the Ada 83 standard. GNAT also supplies all
25913 language-defined pragmas introduced by Ada 95 and Ada 2005.
25914 In addition, GNAT implements the implementation-defined pragmas
25915 from HP Ada 83.
25916
25917 @itemize @bullet
25918 @item  @code{AST_ENTRY}
25919
25920 @item  @code{COMMON_OBJECT}
25921
25922 @item  @code{COMPONENT_ALIGNMENT}
25923
25924 @item  @code{EXPORT_EXCEPTION}
25925
25926 @item  @code{EXPORT_FUNCTION}
25927
25928 @item  @code{EXPORT_OBJECT}
25929
25930 @item  @code{EXPORT_PROCEDURE}
25931
25932 @item  @code{EXPORT_VALUED_PROCEDURE}
25933
25934 @item  @code{FLOAT_REPRESENTATION}
25935
25936 @item  @code{IDENT}
25937
25938 @item  @code{IMPORT_EXCEPTION}
25939
25940 @item  @code{IMPORT_FUNCTION}
25941
25942 @item  @code{IMPORT_OBJECT}
25943
25944 @item  @code{IMPORT_PROCEDURE}
25945
25946 @item  @code{IMPORT_VALUED_PROCEDURE}
25947
25948 @item  @code{INLINE_GENERIC}
25949
25950 @item  @code{INTERFACE_NAME}
25951
25952 @item  @code{LONG_FLOAT}
25953
25954 @item  @code{MAIN_STORAGE}
25955
25956 @item  @code{PASSIVE}
25957
25958 @item  @code{PSECT_OBJECT}
25959
25960 @item  @code{SHARE_GENERIC}
25961
25962 @item  @code{SUPPRESS_ALL}
25963
25964 @item  @code{TASK_STORAGE}
25965
25966 @item  @code{TIME_SLICE}
25967
25968 @item  @code{TITLE}
25969 @end itemize
25970
25971 @noindent
25972 These pragmas are all fully implemented, with the exception of @code{TITLE},
25973 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
25974 recognized, but which have no
25975 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
25976 use of Ada protected objects. In GNAT, all generics are inlined.
25977
25978 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
25979 a separate subprogram specification which must appear before the
25980 subprogram body.
25981
25982 GNAT also supplies a number of implementation-defined pragmas as follows:
25983 @itemize @bullet
25984 @item  @code{ABORT_DEFER}
25985
25986 @item  @code{ADA_83}
25987
25988 @item  @code{ADA_95}
25989
25990 @item  @code{ADA_05}
25991
25992 @item  @code{ANNOTATE}
25993
25994 @item  @code{ASSERT}
25995
25996 @item  @code{C_PASS_BY_COPY}
25997
25998 @item  @code{CPP_CLASS}
25999
26000 @item  @code{CPP_CONSTRUCTOR}
26001
26002 @item  @code{CPP_DESTRUCTOR}
26003
26004 @item  @code{DEBUG}
26005
26006 @item  @code{EXTEND_SYSTEM}
26007
26008 @item  @code{LINKER_ALIAS}
26009
26010 @item  @code{LINKER_SECTION}
26011
26012 @item  @code{MACHINE_ATTRIBUTE}
26013
26014 @item  @code{NO_RETURN}
26015
26016 @item  @code{PURE_FUNCTION}
26017
26018 @item  @code{SOURCE_FILE_NAME}
26019
26020 @item  @code{SOURCE_REFERENCE}
26021
26022 @item  @code{TASK_INFO}
26023
26024 @item  @code{UNCHECKED_UNION}
26025
26026 @item  @code{UNIMPLEMENTED_UNIT}
26027
26028 @item  @code{UNIVERSAL_DATA}
26029
26030 @item  @code{UNSUPPRESS}
26031
26032 @item  @code{WARNINGS}
26033
26034 @item  @code{WEAK_EXTERNAL}
26035 @end itemize
26036
26037 @noindent
26038 For full details on these GNAT implementation-defined pragmas,
26039 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
26040 Manual}.
26041
26042 @menu
26043 * Restrictions on the Pragma INLINE::
26044 * Restrictions on the Pragma INTERFACE::
26045 * Restrictions on the Pragma SYSTEM_NAME::
26046 @end menu
26047
26048 @node Restrictions on the Pragma INLINE
26049 @subsection Restrictions on Pragma @code{INLINE}
26050
26051 @noindent
26052 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
26053 @itemize @bullet
26054 @item  Parameters cannot have a task type.
26055
26056 @item  Function results cannot be task types, unconstrained
26057 array types, or unconstrained types with discriminants.
26058
26059 @item  Bodies cannot declare the following:
26060 @itemize @bullet
26061 @item  Subprogram body or stub (imported subprogram is allowed)
26062
26063 @item  Tasks
26064
26065 @item  Generic declarations
26066
26067 @item  Instantiations
26068
26069 @item  Exceptions
26070
26071 @item  Access types (types derived from access types allowed)
26072
26073 @item  Array or record types
26074
26075 @item  Dependent tasks
26076
26077 @item  Direct recursive calls of subprogram or containing
26078 subprogram, directly or via a renaming
26079
26080 @end itemize
26081 @end itemize
26082
26083 @noindent
26084 In GNAT, the only restriction on pragma @code{INLINE} is that the
26085 body must occur before the call if both are in the same
26086 unit, and the size must be appropriately small. There are
26087 no other specific restrictions which cause subprograms to
26088 be incapable of being inlined.
26089
26090 @node  Restrictions on the Pragma INTERFACE
26091 @subsection  Restrictions on Pragma @code{INTERFACE}
26092
26093 @noindent
26094 The following restrictions on pragma @code{INTERFACE}
26095 are enforced by both HP Ada and GNAT:
26096 @itemize @bullet
26097 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
26098 Default is the default on OpenVMS Alpha systems.
26099
26100 @item  Parameter passing: Language specifies default
26101 mechanisms but can be overridden with an @code{EXPORT} pragma.
26102
26103 @itemize @bullet
26104 @item  Ada: Use internal Ada rules.
26105
26106 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
26107 record or task type. Result cannot be a string, an
26108 array, or a record.
26109
26110 @item  Fortran: Parameters cannot have a task type. Result cannot
26111 be a string, an array, or a record.
26112 @end itemize
26113 @end itemize
26114
26115 @noindent
26116 GNAT is entirely upwards compatible with HP Ada, and in addition allows
26117 record parameters for all languages.
26118
26119 @node  Restrictions on the Pragma SYSTEM_NAME
26120 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
26121
26122 @noindent
26123 For HP Ada for OpenVMS Alpha, the enumeration literal
26124 for the type @code{NAME} is @code{OPENVMS_AXP}.
26125 In GNAT, the enumeration
26126 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
26127
26128 @node  Library of Predefined Units
26129 @section  Library of Predefined Units
26130
26131 @noindent
26132 A library of predefined units is provided as part of the
26133 HP Ada and GNAT implementations. HP Ada does not provide
26134 the package @code{MACHINE_CODE} but instead recommends importing
26135 assembler code.
26136
26137 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
26138 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
26139 version.
26140 The HP Ada Predefined Library units are modified to remove post-Ada 83
26141 incompatibilities and to make them interoperable with GNAT
26142 (@pxref{Changes to DECLIB}, for details).
26143 The units are located in the @file{DECLIB} directory.
26144
26145 The GNAT RTL is contained in
26146 the @file{ADALIB} directory, and
26147 the default search path is set up to find @code{DECLIB} units in preference
26148 to @code{ADALIB} units with the same name (@code{TEXT_IO},
26149 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
26150
26151 @menu
26152 * Changes to DECLIB::
26153 @end menu
26154
26155 @node Changes to DECLIB
26156 @subsection Changes to @code{DECLIB}
26157
26158 @noindent
26159 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
26160 compatibility are minor and include the following:
26161
26162 @itemize @bullet
26163 @item  Adjusting the location of pragmas and record representation
26164 clauses to obey Ada 95 (and thus Ada 2005) rules
26165
26166 @item  Adding the proper notation to generic formal parameters
26167 that take unconstrained types in instantiation
26168
26169 @item  Adding pragma @code{ELABORATE_BODY} to package specs
26170 that have package bodies not otherwise allowed
26171
26172 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
26173 ``@code{PROTECTD}''.
26174 Currently these are found only in the @code{STARLET} package spec.
26175
26176 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
26177 where the address size is constrained to 32 bits.
26178 @end itemize
26179
26180 @noindent
26181 None of the above changes is visible to users.
26182
26183 @node Bindings
26184 @section Bindings
26185
26186 @noindent
26187 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
26188 @itemize @bullet
26189
26190 @item  Command Language Interpreter (CLI interface)
26191
26192 @item  DECtalk Run-Time Library (DTK interface)
26193
26194 @item  Librarian utility routines (LBR interface)
26195
26196 @item  General Purpose Run-Time Library (LIB interface)
26197
26198 @item  Math Run-Time Library (MTH interface)
26199
26200 @item  National Character Set Run-Time Library (NCS interface)
26201
26202 @item  Compiled Code Support Run-Time Library (OTS interface)
26203
26204 @item  Parallel Processing Run-Time Library (PPL interface)
26205
26206 @item  Screen Management Run-Time Library (SMG interface)
26207
26208 @item  Sort Run-Time Library (SOR interface)
26209
26210 @item  String Run-Time Library (STR interface)
26211
26212 @item STARLET System Library
26213 @findex Starlet
26214
26215 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
26216
26217 @item  X Windows Toolkit (XT interface)
26218
26219 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
26220 @end itemize
26221
26222 @noindent
26223 GNAT provides implementations of these HP bindings in the @code{DECLIB}
26224 directory, on both the Alpha and I64 OpenVMS platforms.
26225
26226 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
26227 in the
26228 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
26229 A pragma @code{Linker_Options} has been added to packages @code{Xm},
26230 @code{Xt}, and @code{X_Lib}
26231 causing the default X/Motif sharable image libraries to be linked in. This
26232 is done via options files named @file{xm.opt}, @file{xt.opt}, and
26233 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
26234
26235 It may be necessary to edit these options files to update or correct the
26236 library names if, for example, the newer X/Motif bindings from
26237 @file{ADA$EXAMPLES}
26238 had been (previous to installing GNAT) copied and renamed to supersede the
26239 default @file{ADA$PREDEFINED} versions.
26240
26241 @menu
26242 * Shared Libraries and Options Files::
26243 * Interfaces to C::
26244 @end menu
26245
26246 @node Shared Libraries and Options Files
26247 @subsection Shared Libraries and Options Files
26248
26249 @noindent
26250 When using the HP Ada
26251 predefined X and Motif bindings, the linking with their sharable images is
26252 done automatically by @command{GNAT LINK}.
26253 When using other X and Motif bindings, you need
26254 to add the corresponding sharable images to the command line for
26255 @code{GNAT LINK}. When linking with shared libraries, or with
26256 @file{.OPT} files, you must
26257 also add them to the command line for @command{GNAT LINK}.
26258
26259 A shared library to be used with GNAT is built in the same way as other
26260 libraries under VMS. The VMS Link command can be used in standard fashion.
26261
26262 @node Interfaces to C
26263 @subsection Interfaces to C
26264
26265 @noindent
26266 HP Ada
26267 provides the following Ada types and operations:
26268
26269 @itemize @bullet
26270 @item C types package (@code{C_TYPES})
26271
26272 @item C strings (@code{C_TYPES.NULL_TERMINATED})
26273
26274 @item Other_types (@code{SHORT_INT})
26275 @end itemize
26276
26277 @noindent
26278 Interfacing to C with GNAT, you can use the above approach
26279 described for HP Ada or the facilities of Annex B of
26280 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
26281 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
26282 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
26283
26284 The @option{-gnatF} qualifier forces default and explicit
26285 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
26286 to be uppercased for compatibility with the default behavior
26287 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
26288
26289 @node Main Program Definition
26290 @section Main Program Definition
26291
26292 @noindent
26293 The following section discusses differences in the
26294 definition of main programs on HP Ada and GNAT.
26295 On HP Ada, main programs are defined to meet the
26296 following conditions:
26297 @itemize @bullet
26298 @item  Procedure with no formal parameters (returns @code{0} upon
26299 normal completion)
26300
26301 @item  Procedure with no formal parameters (returns @code{42} when
26302 an unhandled exception is raised)
26303
26304 @item  Function with no formal parameters whose returned value
26305 is of a discrete type
26306
26307 @item  Procedure with one @code{out} formal of a discrete type for
26308 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
26309
26310 @end itemize
26311
26312 @noindent
26313 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
26314 a main function or main procedure returns a discrete
26315 value whose size is less than 64 bits (32 on VAX systems),
26316 the value is zero- or sign-extended as appropriate.
26317 On GNAT, main programs are defined as follows:
26318 @itemize @bullet
26319 @item  Must be a non-generic, parameterless subprogram that
26320 is either a procedure or function returning an Ada
26321 @code{STANDARD.INTEGER} (the predefined type)
26322
26323 @item  Cannot be a generic subprogram or an instantiation of a
26324 generic subprogram
26325 @end itemize
26326
26327 @node Implementation-Defined Attributes
26328 @section Implementation-Defined Attributes
26329
26330 @noindent
26331 GNAT provides all HP Ada implementation-defined
26332 attributes.
26333
26334 @node Compiler and Run-Time Interfacing
26335 @section Compiler and Run-Time Interfacing
26336
26337 @noindent
26338 HP Ada provides the following qualifiers to pass options to the linker
26339 (ACS LINK):
26340 @itemize @bullet
26341 @item  @option{/WAIT} and @option{/SUBMIT}
26342
26343 @item  @option{/COMMAND}
26344
26345 @item  @option{/@r{[}NO@r{]}MAP}
26346
26347 @item  @option{/OUTPUT=@var{file-spec}}
26348
26349 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
26350 @end itemize
26351
26352 @noindent
26353 To pass options to the linker, GNAT provides the following
26354 switches:
26355
26356 @itemize @bullet
26357 @item   @option{/EXECUTABLE=@var{exec-name}}
26358
26359 @item   @option{/VERBOSE}
26360
26361 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
26362 @end itemize
26363
26364 @noindent
26365 For more information on these switches, see
26366 @ref{Switches for gnatlink}.
26367 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
26368 to control optimization. HP Ada also supplies the
26369 following pragmas:
26370 @itemize @bullet
26371 @item  @code{OPTIMIZE}
26372
26373 @item  @code{INLINE}
26374
26375 @item  @code{INLINE_GENERIC}
26376
26377 @item  @code{SUPPRESS_ALL}
26378
26379 @item  @code{PASSIVE}
26380 @end itemize
26381
26382 @noindent
26383 In GNAT, optimization is controlled strictly by command
26384 line parameters, as described in the corresponding section of this guide.
26385 The HP pragmas for control of optimization are
26386 recognized but ignored.
26387
26388 Note that in GNAT, the default is optimization off, whereas in HP Ada
26389 the default is that optimization is turned on.
26390
26391 @node Program Compilation and Library Management
26392 @section Program Compilation and Library Management
26393
26394 @noindent
26395 HP Ada and GNAT provide a comparable set of commands to
26396 build programs. HP Ada also provides a program library,
26397 which is a concept that does not exist on GNAT. Instead,
26398 GNAT provides directories of sources that are compiled as
26399 needed.
26400
26401 The following table summarizes
26402 the HP Ada commands and provides
26403 equivalent GNAT commands. In this table, some GNAT
26404 equivalents reflect the fact that GNAT does not use the
26405 concept of a program library. Instead, it uses a model
26406 in which collections of source and object files are used
26407 in a manner consistent with other languages like C and
26408 Fortran. Therefore, standard system file commands are used
26409 to manipulate these elements. Those GNAT commands are marked with
26410 an asterisk.
26411 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
26412
26413 @need 1500
26414 @multitable @columnfractions .35 .65
26415
26416 @item @emph{HP Ada Command}
26417 @tab @emph{GNAT Equivalent / Description}
26418
26419 @item @command{ADA}
26420 @tab @command{GNAT COMPILE}@*
26421 Invokes the compiler to compile one or more Ada source files.
26422
26423 @item @command{ACS ATTACH}@*
26424 @tab [No equivalent]@*
26425 Switches control of terminal from current process running the program
26426 library manager.
26427
26428 @item @command{ACS CHECK}
26429 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
26430 Forms the execution closure of one
26431 or more compiled units and checks completeness and currency.
26432
26433 @item @command{ACS COMPILE}
26434 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
26435 Forms the execution closure of one or
26436 more specified units, checks completeness and currency,
26437 identifies units that have revised source files, compiles same,
26438 and recompiles units that are or will become obsolete.
26439 Also completes incomplete generic instantiations.
26440
26441 @item @command{ACS COPY FOREIGN}
26442 @tab Copy (*)@*
26443 Copies a foreign object file into the program library as a
26444 library unit body.
26445
26446 @item @command{ACS COPY UNIT}
26447 @tab Copy (*)@*
26448 Copies a compiled unit from one program library to another.
26449
26450 @item @command{ACS CREATE LIBRARY}
26451 @tab Create /directory (*)@*
26452 Creates a program library.
26453
26454 @item @command{ACS CREATE SUBLIBRARY}
26455 @tab Create /directory (*)@*
26456 Creates a program sublibrary.
26457
26458 @item @command{ACS DELETE LIBRARY}
26459 @tab @*
26460 Deletes a program library and its contents.
26461
26462 @item @command{ACS DELETE SUBLIBRARY}
26463 @tab @*
26464 Deletes a program sublibrary and its contents.
26465
26466 @item @command{ACS DELETE UNIT}
26467 @tab Delete file (*)@*
26468 On OpenVMS systems, deletes one or more compiled units from
26469 the current program library.
26470
26471 @item @command{ACS DIRECTORY}
26472 @tab Directory (*)@*
26473 On OpenVMS systems, lists units contained in the current
26474 program library.
26475
26476 @item @command{ACS ENTER FOREIGN}
26477 @tab Copy (*)@*
26478 Allows the import of a foreign body as an Ada library
26479 spec and enters a reference to a pointer.
26480
26481 @item @command{ACS ENTER UNIT}
26482 @tab Copy (*)@*
26483 Enters a reference (pointer) from the current program library to
26484 a unit compiled into another program library.
26485
26486 @item @command{ACS EXIT}
26487 @tab [No equivalent]@*
26488 Exits from the program library manager.
26489
26490 @item @command{ACS EXPORT}
26491 @tab Copy (*)@*
26492 Creates an object file that contains system-specific object code
26493 for one or more units. With GNAT, object files can simply be copied
26494 into the desired directory.
26495
26496 @item @command{ACS EXTRACT SOURCE}
26497 @tab Copy (*)@*
26498 Allows access to the copied source file for each Ada compilation unit
26499
26500 @item @command{ACS HELP}
26501 @tab @command{HELP GNAT}@*
26502 Provides online help.
26503
26504 @item @command{ACS LINK}
26505 @tab @command{GNAT LINK}@*
26506 Links an object file containing Ada units into an executable file.
26507
26508 @item @command{ACS LOAD}
26509 @tab Copy (*)@*
26510 Loads (partially compiles) Ada units into the program library.
26511 Allows loading a program from a collection of files into a library
26512 without knowing the relationship among units.
26513
26514 @item @command{ACS MERGE}
26515 @tab Copy (*)@*
26516 Merges into the current program library, one or more units from
26517 another library where they were modified.
26518
26519 @item @command{ACS RECOMPILE}
26520 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
26521 Recompiles from   external or copied source files any obsolete
26522 unit in the closure. Also, completes any incomplete generic
26523 instantiations.
26524
26525 @item @command{ACS REENTER}
26526 @tab @command{GNAT MAKE}@*
26527 Reenters current references to units compiled after last entered
26528 with the @command{ACS ENTER UNIT} command.
26529
26530 @item @command{ACS SET LIBRARY}
26531 @tab Set default (*)@*
26532 Defines a program library to be the compilation context as well
26533 as the target library for compiler output and commands in general.
26534
26535 @item @command{ACS SET PRAGMA}
26536 @tab Edit @file{gnat.adc} (*)@*
26537 Redefines specified  values of the library characteristics
26538 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
26539 and @code{Float_Representation}.
26540
26541 @item @command{ACS SET SOURCE}
26542 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
26543 Defines the source file search list for the @command{ACS COMPILE} command.
26544
26545 @item @command{ACS SHOW LIBRARY}
26546 @tab Directory (*)@*
26547 Lists information about one or more program libraries.
26548
26549 @item @command{ACS SHOW PROGRAM}
26550 @tab [No equivalent]@*
26551 Lists information about the execution closure of one or
26552 more units in the program library.
26553
26554 @item @command{ACS SHOW SOURCE}
26555 @tab Show logical @code{ADA_INCLUDE_PATH}@*
26556 Shows the source file search used when compiling units.
26557
26558 @item @command{ACS SHOW VERSION}
26559 @tab Compile with @option{VERBOSE} option
26560 Displays the version number of the compiler and program library
26561 manager used.
26562
26563 @item @command{ACS SPAWN}
26564 @tab [No equivalent]@*
26565 Creates a subprocess of the current process (same as @command{DCL SPAWN}
26566 command).
26567
26568 @item @command{ACS VERIFY}
26569 @tab [No equivalent]@*
26570 Performs a series of consistency checks on a program library to
26571 determine whether the library structure and library files are in
26572 valid form.
26573 @end multitable
26574
26575 @noindent
26576
26577 @node Input-Output
26578 @section Input-Output
26579
26580 @noindent
26581 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
26582 Management Services (RMS) to perform operations on
26583 external files.
26584
26585 @noindent
26586 HP Ada and GNAT predefine an identical set of input-
26587 output packages. To make the use of the
26588 generic @code{TEXT_IO} operations more convenient, HP Ada
26589 provides predefined library packages that instantiate the
26590 integer and floating-point operations for the predefined
26591 integer and floating-point types as shown in the following table.
26592
26593 @multitable @columnfractions .45 .55
26594 @item @emph{Package Name} @tab Instantiation
26595
26596 @item @code{INTEGER_TEXT_IO}
26597 @tab @code{INTEGER_IO(INTEGER)}
26598
26599 @item @code{SHORT_INTEGER_TEXT_IO}
26600 @tab @code{INTEGER_IO(SHORT_INTEGER)}
26601
26602 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
26603 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
26604
26605 @item @code{FLOAT_TEXT_IO}
26606 @tab @code{FLOAT_IO(FLOAT)}
26607
26608 @item @code{LONG_FLOAT_TEXT_IO}
26609 @tab @code{FLOAT_IO(LONG_FLOAT)}
26610 @end multitable
26611
26612 @noindent
26613 The HP Ada predefined packages and their operations
26614 are implemented using OpenVMS Alpha files and input-output
26615 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
26616 Familiarity with the following is recommended:
26617 @itemize @bullet
26618 @item  RMS file organizations and access methods
26619
26620 @item  OpenVMS file specifications and directories
26621
26622 @item  OpenVMS File Definition Language (FDL)
26623 @end itemize
26624
26625 @noindent
26626 GNAT provides I/O facilities that are completely
26627 compatible with HP Ada. The distribution includes the
26628 standard HP Ada versions of all I/O packages, operating
26629 in a manner compatible with HP Ada. In particular, the
26630 following packages are by default the HP Ada (Ada 83)
26631 versions of these packages rather than the renamings
26632 suggested in Annex J of the Ada Reference Manual:
26633 @itemize @bullet
26634 @item  @code{TEXT_IO}
26635
26636 @item  @code{SEQUENTIAL_IO}
26637
26638 @item  @code{DIRECT_IO}
26639 @end itemize
26640
26641 @noindent
26642 The use of the standard child package syntax (for
26643 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
26644 packages.
26645 GNAT provides HP-compatible predefined instantiations
26646 of the @code{TEXT_IO} packages, and also
26647 provides the standard predefined instantiations required
26648 by the @cite{Ada Reference Manual}.
26649
26650 For further information on how GNAT interfaces to the file
26651 system or how I/O is implemented in programs written in
26652 mixed languages, see @ref{Implementation of the Standard I/O,,,
26653 gnat_rm, GNAT Reference Manual}.
26654 This chapter covers the following:
26655 @itemize @bullet
26656 @item  Standard I/O packages
26657
26658 @item  @code{FORM} strings
26659
26660 @item  @code{ADA.DIRECT_IO}
26661
26662 @item  @code{ADA.SEQUENTIAL_IO}
26663
26664 @item  @code{ADA.TEXT_IO}
26665
26666 @item  Stream pointer positioning
26667
26668 @item  Reading and writing non-regular files
26669
26670 @item  @code{GET_IMMEDIATE}
26671
26672 @item  Treating @code{TEXT_IO} files as streams
26673
26674 @item  Shared files
26675
26676 @item  Open modes
26677 @end itemize
26678
26679 @node Implementation Limits
26680 @section Implementation Limits
26681
26682 @noindent
26683 The following table lists implementation limits for HP Ada
26684 and GNAT systems.
26685 @multitable @columnfractions .60 .20 .20
26686 @sp 1
26687 @item  @emph{Compilation Parameter}
26688 @tab   @emph{HP Ada}
26689 @tab   @emph{GNAT}
26690 @sp 1
26691
26692 @item  In a subprogram or entry  declaration, maximum number of
26693 formal parameters that are of an unconstrained record type
26694 @tab   32
26695 @tab   No set limit
26696 @sp 1
26697
26698 @item  Maximum identifier length (number of characters)
26699 @tab   255
26700 @tab   32766
26701 @sp 1
26702
26703 @item  Maximum number of characters in a source line
26704 @tab   255
26705 @tab   32766
26706 @sp 1
26707
26708 @item  Maximum collection size   (number of bytes)
26709 @tab   2**31-1
26710 @tab   2**31-1
26711 @sp 1
26712
26713 @item  Maximum number of discriminants for a record type
26714 @tab   245
26715 @tab   No set limit
26716 @sp 1
26717
26718 @item  Maximum number of formal parameters in an entry or
26719 subprogram declaration
26720 @tab   246
26721 @tab    No set limit
26722 @sp 1
26723
26724 @item  Maximum number of dimensions in an array type
26725 @tab   255
26726 @tab   No set limit
26727 @sp 1
26728
26729 @item  Maximum number of library  units and subunits in a compilation.
26730 @tab   4095
26731 @tab   No set limit
26732 @sp 1
26733
26734 @item  Maximum number of library units and subunits in an execution.
26735 @tab   16383
26736 @tab   No set limit
26737 @sp 1
26738
26739 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
26740 or @code{PSECT_OBJECT}
26741 @tab   32757
26742 @tab   No set limit
26743 @sp 1
26744
26745 @item  Maximum number of enumeration literals in an enumeration type
26746 definition
26747 @tab   65535
26748 @tab   No set limit
26749 @sp 1
26750
26751 @item  Maximum number of lines in a source file
26752 @tab   65534
26753 @tab   No set limit
26754 @sp 1
26755
26756 @item  Maximum number of bits in any object
26757 @tab   2**31-1
26758 @tab   2**31-1
26759 @sp 1
26760
26761 @item  Maximum size of the static portion of a stack frame (approximate)
26762 @tab   2**31-1
26763 @tab   2**31-1
26764 @end multitable
26765
26766 @node Tools and Utilities
26767 @section Tools and Utilities
26768
26769 @noindent
26770 The following table lists some of the OpenVMS development tools
26771 available for HP Ada, and the corresponding tools for
26772 use with @value{EDITION} on Alpha and I64 platforms.
26773 Aside from the debugger, all the OpenVMS tools identified are part
26774 of the DECset package.
26775
26776 @iftex
26777 @c Specify table in TeX since Texinfo does a poor job
26778 @tex
26779 \smallskip
26780 \smallskip
26781 \settabs\+Language-Sensitive Editor\quad
26782    &Product with HP Ada\quad
26783    &\cr
26784 \+\it Tool
26785    &\it Product with HP Ada
26786    & \it Product with GNAT Pro\cr
26787 \smallskip
26788 \+Code Management System
26789    &HP CMS
26790    & HP CMS\cr
26791 \smallskip
26792 \+Language-Sensitive Editor
26793    &HP LSE
26794    & emacs or HP LSE (Alpha)\cr
26795 \+
26796    &
26797    & HP LSE (I64)\cr
26798 \smallskip
26799 \+Debugger
26800    &OpenVMS Debug
26801    & gdb (Alpha),\cr
26802 \+
26803    &
26804    & OpenVMS Debug (I64)\cr
26805 \smallskip
26806 \+Source Code Analyzer /
26807    &HP SCA
26808    & GNAT XREF\cr
26809 \+Cross Referencer
26810    &
26811    &\cr
26812 \smallskip
26813 \+Test Manager
26814    &HP Digital Test
26815    & HP DTM\cr
26816 \+
26817    &Manager (DTM)
26818    &\cr
26819 \smallskip
26820 \+Performance and
26821    & HP PCA
26822    & HP PCA\cr
26823 \+Coverage Analyzer
26824    &
26825    &\cr
26826 \smallskip
26827 \+Module Management
26828    & HP MMS
26829    & Not applicable\cr
26830 \+ System
26831    &
26832    &\cr
26833 \smallskip
26834 \smallskip
26835 @end tex
26836 @end iftex
26837
26838 @ifnottex
26839 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
26840 @c the TeX version above for the printed version
26841 @flushleft
26842 @c @multitable @columnfractions .3 .4 .4
26843 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
26844 @item @i{Tool}
26845 @tab @i{Tool with HP Ada}
26846 @tab @i{Tool with @value{EDITION}}
26847 @item Code Management@*System
26848 @tab HP CMS
26849 @tab HP CMS
26850 @item Language-Sensitive@*Editor
26851 @tab HP LSE
26852 @tab emacs or HP LSE (Alpha)
26853 @item
26854 @tab
26855 @tab HP LSE (I64)
26856 @item Debugger
26857 @tab OpenVMS Debug
26858 @tab gdb (Alpha),
26859 @item
26860 @tab
26861 @tab OpenVMS Debug (I64)
26862 @item Source Code Analyzer /@*Cross Referencer
26863 @tab HP SCA
26864 @tab GNAT XREF
26865 @item Test Manager
26866 @tab HP Digital Test@*Manager (DTM)
26867 @tab HP DTM
26868 @item Performance and@*Coverage Analyzer
26869 @tab HP PCA
26870 @tab HP PCA
26871 @item Module Management@*System
26872 @tab HP MMS
26873 @tab Not applicable
26874 @end multitable
26875 @end flushleft
26876 @end ifnottex
26877
26878 @end ifset
26879
26880 @c **************************************
26881 @node Platform-Specific Information for the Run-Time Libraries
26882 @appendix Platform-Specific Information for the Run-Time Libraries
26883 @cindex Tasking and threads libraries
26884 @cindex Threads libraries and tasking
26885 @cindex Run-time libraries (platform-specific information)
26886
26887 @noindent
26888 The GNAT run-time implementation may vary with respect to both the
26889 underlying threads library and the exception handling scheme.
26890 For threads support, one or more of the following are supplied:
26891 @itemize @bullet
26892 @item @b{native threads library}, a binding to the thread package from
26893 the underlying operating system
26894
26895 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
26896 POSIX thread package
26897 @end itemize
26898
26899 @noindent
26900 For exception handling, either or both of two models are supplied:
26901 @itemize @bullet
26902 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
26903 Most programs should experience a substantial speed improvement by
26904 being compiled with a ZCX run-time.
26905 This is especially true for
26906 tasking applications or applications with many exception handlers.}
26907 @cindex Zero-Cost Exceptions
26908 @cindex ZCX (Zero-Cost Exceptions)
26909 which uses binder-generated tables that
26910 are interrogated at run time to locate a handler
26911
26912 @item @b{setjmp / longjmp} (``SJLJ''),
26913 @cindex setjmp/longjmp Exception Model
26914 @cindex SJLJ (setjmp/longjmp Exception Model)
26915 which uses dynamically-set data to establish
26916 the set of handlers
26917 @end itemize
26918
26919 @noindent
26920 This appendix summarizes which combinations of threads and exception support
26921 are supplied on various GNAT platforms.
26922 It then shows how to select a particular library either
26923 permanently or temporarily,
26924 explains the properties of (and tradeoffs among) the various threads
26925 libraries, and provides some additional
26926 information about several specific platforms.
26927
26928 @menu
26929 * Summary of Run-Time Configurations::
26930 * Specifying a Run-Time Library::
26931 * Choosing the Scheduling Policy::
26932 * Solaris-Specific Considerations::
26933 * Linux-Specific Considerations::
26934 * AIX-Specific Considerations::
26935 * Irix-Specific Considerations::
26936 * RTX-Specific Considerations::
26937 * HP-UX-Specific Considerations::
26938 @end menu
26939
26940 @node Summary of Run-Time Configurations
26941 @section Summary of Run-Time Configurations
26942
26943 @multitable @columnfractions .30 .70
26944 @item @b{alpha-openvms}
26945 @item @code{@ @ }@i{rts-native (default)}
26946 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26947 @item @code{@ @ @ @ }Exceptions @tab ZCX
26948 @*
26949 @item @b{alpha-tru64}
26950 @item @code{@ @ }@i{rts-native (default)}
26951 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26952 @item @code{@ @ @ @ }Exceptions @tab ZCX
26953 @*
26954 @item @code{@ @ }@i{rts-sjlj}
26955 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26956 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26957 @*
26958 @item @b{ia64-hp_linux}
26959 @item @code{@ @ }@i{rts-native (default)}
26960 @item @code{@ @ @ @ }Tasking    @tab pthread library
26961 @item @code{@ @ @ @ }Exceptions @tab ZCX
26962 @*
26963 @item @b{ia64-hpux}
26964 @item @code{@ @ }@i{rts-native (default)}
26965 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26966 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26967 @*
26968 @item @b{ia64-openvms}
26969 @item @code{@ @ }@i{rts-native (default)}
26970 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26971 @item @code{@ @ @ @ }Exceptions @tab ZCX
26972 @*
26973 @item @b{ia64-sgi_linux}
26974 @item @code{@ @ }@i{rts-native (default)}
26975 @item @code{@ @ @ @ }Tasking    @tab pthread library
26976 @item @code{@ @ @ @ }Exceptions @tab ZCX
26977 @*
26978 @item @b{mips-irix}
26979 @item @code{@ @ }@i{rts-native (default)}
26980 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
26981 @item @code{@ @ @ @ }Exceptions @tab ZCX
26982 @*
26983 @item @b{pa-hpux}
26984 @item @code{@ @ }@i{rts-native (default)}
26985 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26986 @item @code{@ @ @ @ }Exceptions @tab ZCX
26987 @*
26988 @item @code{@ @ }@i{rts-sjlj}
26989 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26990 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26991 @*
26992 @item @b{ppc-aix}
26993 @item @code{@ @ }@i{rts-native (default)}
26994 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
26995 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26996 @*
26997 @item @b{ppc-darwin}
26998 @item @code{@ @ }@i{rts-native (default)}
26999 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
27000 @item @code{@ @ @ @ }Exceptions @tab ZCX
27001 @*
27002 @item @b{sparc-solaris}  @tab
27003 @item @code{@ @ }@i{rts-native (default)}
27004 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
27005 @item @code{@ @ @ @ }Exceptions @tab ZCX
27006 @*
27007 @item @code{@ @ }@i{rts-pthread}
27008 @item @code{@ @ @ @ }Tasking    @tab pthread library
27009 @item @code{@ @ @ @ }Exceptions @tab ZCX
27010 @*
27011 @item @code{@ @ }@i{rts-sjlj}
27012 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
27013 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27014 @*
27015 @item @b{sparc64-solaris}  @tab
27016 @item @code{@ @ }@i{rts-native (default)}
27017 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
27018 @item @code{@ @ @ @ }Exceptions @tab ZCX
27019 @*
27020 @item @b{x86-linux}
27021 @item @code{@ @ }@i{rts-native (default)}
27022 @item @code{@ @ @ @ }Tasking    @tab pthread library
27023 @item @code{@ @ @ @ }Exceptions @tab ZCX
27024 @*
27025 @item @code{@ @ }@i{rts-sjlj}
27026 @item @code{@ @ @ @ }Tasking    @tab pthread library
27027 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27028 @*
27029 @item @b{x86-lynx}
27030 @item @code{@ @ }@i{rts-native (default)}
27031 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
27032 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27033 @*
27034 @item @b{x86-solaris}
27035 @item @code{@ @ }@i{rts-native (default)}
27036 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
27037 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27038 @*
27039 @item @b{x86-windows}
27040 @item @code{@ @ }@i{rts-native (default)}
27041 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
27042 @item @code{@ @ @ @ }Exceptions @tab ZCX
27043 @*
27044 @item @code{@ @ }@i{rts-sjlj (default)}
27045 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
27046 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27047 @*
27048 @item @b{x86-windows-rtx}
27049 @item @code{@ @ }@i{rts-rtx-rtss (default)}
27050 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
27051 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27052 @*
27053 @item @code{@ @ }@i{rts-rtx-w32}
27054 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
27055 @item @code{@ @ @ @ }Exceptions @tab ZCX
27056 @*
27057 @item @b{x86_64-linux}
27058 @item @code{@ @ }@i{rts-native (default)}
27059 @item @code{@ @ @ @ }Tasking    @tab pthread library
27060 @item @code{@ @ @ @ }Exceptions @tab ZCX
27061 @*
27062 @item @code{@ @ }@i{rts-sjlj}
27063 @item @code{@ @ @ @ }Tasking    @tab pthread library
27064 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27065 @*
27066 @end multitable
27067
27068 @node Specifying a Run-Time Library
27069 @section Specifying a Run-Time Library
27070
27071 @noindent
27072 The @file{adainclude} subdirectory containing the sources of the GNAT
27073 run-time library, and the @file{adalib} subdirectory containing the
27074 @file{ALI} files and the static and/or shared GNAT library, are located
27075 in the gcc target-dependent area:
27076
27077 @smallexample
27078 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
27079 @end smallexample
27080
27081 @noindent
27082 As indicated above, on some platforms several run-time libraries are supplied.
27083 These libraries are installed in the target dependent area and
27084 contain a complete source and binary subdirectory. The detailed description
27085 below explains the differences between the different libraries in terms of
27086 their thread support.
27087
27088 The default run-time library (when GNAT is installed) is @emph{rts-native}.
27089 This default run time is selected by the means of soft links.
27090 For example on x86-linux:
27091
27092 @smallexample
27093 @group
27094  $(target-dir)
27095      |
27096      +--- adainclude----------+
27097      |                        |
27098      +--- adalib-----------+  |
27099      |                     |  |
27100      +--- rts-native       |  |
27101      |    |                |  |
27102      |    +--- adainclude <---+
27103      |    |                |
27104      |    +--- adalib <----+
27105      |
27106      +--- rts-sjlj
27107           |
27108           +--- adainclude
27109           |
27110           +--- adalib
27111 @end group
27112 @end smallexample
27113
27114 @noindent
27115 If the @i{rts-sjlj} library is to be selected on a permanent basis,
27116 these soft links can be modified with the following commands:
27117
27118 @smallexample
27119 $ cd $target
27120 $ rm -f adainclude adalib
27121 $ ln -s rts-sjlj/adainclude adainclude
27122 $ ln -s rts-sjlj/adalib adalib
27123 @end smallexample
27124
27125 @noindent
27126 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
27127 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
27128 @file{$target/ada_object_path}.
27129
27130 Selecting another run-time library temporarily can be
27131 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
27132 @cindex @option{--RTS} option
27133
27134 @node Choosing the Scheduling Policy
27135 @section Choosing the Scheduling Policy
27136
27137 @noindent
27138 When using a POSIX threads implementation, you have a choice of several
27139 scheduling policies: @code{SCHED_FIFO},
27140 @cindex @code{SCHED_FIFO} scheduling policy
27141 @code{SCHED_RR}
27142 @cindex @code{SCHED_RR} scheduling policy
27143 and @code{SCHED_OTHER}.
27144 @cindex @code{SCHED_OTHER} scheduling policy
27145 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
27146 or @code{SCHED_RR} requires special (e.g., root) privileges.
27147
27148 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
27149 @code{SCHED_FIFO},
27150 @cindex @code{SCHED_FIFO} scheduling policy
27151 you can use one of the following:
27152
27153 @itemize @bullet
27154 @item
27155 @code{pragma Time_Slice (0.0)}
27156 @cindex pragma Time_Slice
27157 @item
27158 the corresponding binder option @option{-T0}
27159 @cindex @option{-T0} option
27160 @item
27161 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
27162 @cindex pragma Task_Dispatching_Policy
27163 @end itemize
27164
27165 @noindent
27166 To specify @code{SCHED_RR},
27167 @cindex @code{SCHED_RR} scheduling policy
27168 you should use @code{pragma Time_Slice} with a
27169 value greater than @code{0.0}, or else use the corresponding @option{-T}
27170 binder option.
27171
27172 @node Solaris-Specific Considerations
27173 @section Solaris-Specific Considerations
27174 @cindex Solaris Sparc threads libraries
27175
27176 @noindent
27177 This section addresses some topics related to the various threads libraries
27178 on Sparc Solaris.
27179
27180 @menu
27181 * Solaris Threads Issues::
27182 @end menu
27183
27184 @node Solaris Threads Issues
27185 @subsection Solaris Threads Issues
27186
27187 @noindent
27188 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
27189 library based on POSIX threads --- @emph{rts-pthread}.
27190 @cindex rts-pthread threads library
27191 This run-time library has the advantage of being mostly shared across all
27192 POSIX-compliant thread implementations, and it also provides under
27193 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
27194 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
27195 and @code{PTHREAD_PRIO_PROTECT}
27196 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
27197 semantics that can be selected using the predefined pragma
27198 @code{Locking_Policy}
27199 @cindex pragma Locking_Policy (under rts-pthread)
27200 with respectively
27201 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
27202 @cindex @code{Inheritance_Locking} (under rts-pthread)
27203 @cindex @code{Ceiling_Locking} (under rts-pthread)
27204
27205 As explained above, the native run-time library is based on the Solaris thread
27206 library (@code{libthread}) and is the default library.
27207
27208 When the Solaris threads library is used (this is the default), programs
27209 compiled with GNAT can automatically take advantage of
27210 and can thus execute on multiple processors.
27211 The user can alternatively specify a processor on which the program should run
27212 to emulate a single-processor system. The multiprocessor / uniprocessor choice
27213 is made by
27214 setting the environment variable @env{GNAT_PROCESSOR}
27215 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
27216 to one of the following:
27217
27218 @table @code
27219 @item -2
27220 Use the default configuration (run the program on all
27221 available processors) - this is the same as having @code{GNAT_PROCESSOR}
27222 unset
27223
27224 @item -1
27225 Let the run-time implementation choose one processor and run the program on
27226 that processor
27227
27228 @item 0 .. Last_Proc
27229 Run the program on the specified processor.
27230 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
27231 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
27232 @end table
27233
27234 @node Linux-Specific Considerations
27235 @section Linux-Specific Considerations
27236 @cindex Linux threads libraries
27237
27238 @noindent
27239 On GNU/Linux without NPTL support (usually system with GNU C Library
27240 older than 2.3), the signal model is not POSIX compliant, which means
27241 that to send a signal to the process, you need to send the signal to all
27242 threads, e.g.@: by using @code{killpg()}.
27243
27244 @node AIX-Specific Considerations
27245 @section AIX-Specific Considerations
27246 @cindex AIX resolver library
27247
27248 @noindent
27249 On AIX, the resolver library initializes some internal structure on
27250 the first call to @code{get*by*} functions, which are used to implement
27251 @code{GNAT.Sockets.Get_Host_By_Name} and
27252 @code{GNAT.Sockets.Get_Host_By_Address}.
27253 If such initialization occurs within an Ada task, and the stack size for
27254 the task is the default size, a stack overflow may occur.
27255
27256 To avoid this overflow, the user should either ensure that the first call
27257 to @code{GNAT.Sockets.Get_Host_By_Name} or
27258 @code{GNAT.Sockets.Get_Host_By_Addrss}
27259 occurs in the environment task, or use @code{pragma Storage_Size} to
27260 specify a sufficiently large size for the stack of the task that contains
27261 this call.
27262
27263 @node Irix-Specific Considerations
27264 @section Irix-Specific Considerations
27265 @cindex Irix libraries
27266
27267 @noindent
27268 The GCC support libraries coming with the Irix compiler have moved to
27269 their canonical place with respect to the general Irix ABI related
27270 conventions. Running applications built with the default shared GNAT
27271 run-time now requires the LD_LIBRARY_PATH environment variable to
27272 include this location. A possible way to achieve this is to issue the
27273 following command line on a bash prompt:
27274
27275 @smallexample
27276 @group
27277 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
27278 @end group
27279 @end smallexample
27280
27281 @node RTX-Specific Considerations
27282 @section RTX-Specific Considerations
27283 @cindex RTX libraries
27284
27285 @noindent
27286 The Real-time Extension (RTX) to Windows is based on the Windows Win32
27287 API. Applications can be built to work in two different modes:
27288
27289 @itemize @bullet
27290 @item
27291 Windows executables that run in Ring 3 to utilize memory protection
27292 (@emph{rts-rtx-w32}).
27293
27294 @item
27295 Real-time subsystem (RTSS) executables that run in Ring 0, where
27296 performance can be optimized with RTSS applications taking precedent
27297 over all Windows applications (@emph{rts-rtx-rtss}).
27298
27299 @end itemize
27300
27301 @node HP-UX-Specific Considerations
27302 @section HP-UX-Specific Considerations
27303 @cindex HP-UX Scheduling
27304
27305 @noindent
27306 On HP-UX, appropriate privileges are required to change the scheduling
27307 parameters of a task. The calling process must have appropriate
27308 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
27309 successfully change the scheduling parameters.
27310
27311 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
27312 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
27313 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
27314
27315 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
27316 one of the following:
27317
27318 @itemize @bullet
27319 @item
27320 @code{pragma Time_Slice (0.0)}
27321 @cindex pragma Time_Slice
27322 @item
27323 the corresponding binder option @option{-T0}
27324 @cindex @option{-T0} option
27325 @item
27326 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
27327 @cindex pragma Task_Dispatching_Policy
27328 @end itemize
27329
27330 @noindent
27331 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
27332 you should use @code{pragma Time_Slice} with a
27333 value greater than @code{0.0}, or use the corresponding @option{-T}
27334 binder option, or set the @code{pragma Task_Dispatching_Policy
27335 (Round_Robin_Within_Priorities)}.
27336
27337 @c *******************************
27338 @node Example of Binder Output File
27339 @appendix Example of Binder Output File
27340
27341 @noindent
27342 This Appendix displays the source code for @command{gnatbind}'s output
27343 file generated for a simple ``Hello World'' program.
27344 Comments have been added for clarification purposes.
27345
27346 @smallexample @c adanocomment
27347 @iftex
27348 @leftskip=0cm
27349 @end iftex
27350 --  The package is called Ada_Main unless this name is actually used
27351 --  as a unit name in the partition, in which case some other unique
27352 --  name is used.
27353
27354 with System;
27355 package ada_main is
27356
27357    Elab_Final_Code : Integer;
27358    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
27359
27360    --  The main program saves the parameters (argument count,
27361    --  argument values, environment pointer) in global variables
27362    --  for later access by other units including
27363    --  Ada.Command_Line.
27364
27365    gnat_argc : Integer;
27366    gnat_argv : System.Address;
27367    gnat_envp : System.Address;
27368
27369    --  The actual variables are stored in a library routine. This
27370    --  is useful for some shared library situations, where there
27371    --  are problems if variables are not in the library.
27372
27373    pragma Import (C, gnat_argc);
27374    pragma Import (C, gnat_argv);
27375    pragma Import (C, gnat_envp);
27376
27377    --  The exit status is similarly an external location
27378
27379    gnat_exit_status : Integer;
27380    pragma Import (C, gnat_exit_status);
27381
27382    GNAT_Version : constant String :=
27383                     "GNAT Version: 6.0.0w (20061115)";
27384    pragma Export (C, GNAT_Version, "__gnat_version");
27385
27386    --  This is the generated adafinal routine that performs
27387    --  finalization at the end of execution. In the case where
27388    --  Ada is the main program, this main program makes a call
27389    --  to adafinal at program termination.
27390
27391    procedure adafinal;
27392    pragma Export (C, adafinal, "adafinal");
27393
27394    --  This is the generated adainit routine that performs
27395    --  initialization at the start of execution. In the case
27396    --  where Ada is the main program, this main program makes
27397    --  a call to adainit at program startup.
27398
27399    procedure adainit;
27400    pragma Export (C, adainit, "adainit");
27401
27402    --  This routine is called at the start of execution. It is
27403    --  a dummy routine that is used by the debugger to breakpoint
27404    --  at the start of execution.
27405
27406    procedure Break_Start;
27407    pragma Import (C, Break_Start, "__gnat_break_start");
27408
27409    --  This is the actual generated main program (it would be
27410    --  suppressed if the no main program switch were used). As
27411    --  required by standard system conventions, this program has
27412    --  the external name main.
27413
27414    function main
27415      (argc : Integer;
27416       argv : System.Address;
27417       envp : System.Address)
27418       return Integer;
27419    pragma Export (C, main, "main");
27420
27421    --  The following set of constants give the version
27422    --  identification values for every unit in the bound
27423    --  partition. This identification is computed from all
27424    --  dependent semantic units, and corresponds to the
27425    --  string that would be returned by use of the
27426    --  Body_Version or Version attributes.
27427
27428    type Version_32 is mod 2 ** 32;
27429    u00001 : constant Version_32 := 16#7880BEB3#;
27430    u00002 : constant Version_32 := 16#0D24CBD0#;
27431    u00003 : constant Version_32 := 16#3283DBEB#;
27432    u00004 : constant Version_32 := 16#2359F9ED#;
27433    u00005 : constant Version_32 := 16#664FB847#;
27434    u00006 : constant Version_32 := 16#68E803DF#;
27435    u00007 : constant Version_32 := 16#5572E604#;
27436    u00008 : constant Version_32 := 16#46B173D8#;
27437    u00009 : constant Version_32 := 16#156A40CF#;
27438    u00010 : constant Version_32 := 16#033DABE0#;
27439    u00011 : constant Version_32 := 16#6AB38FEA#;
27440    u00012 : constant Version_32 := 16#22B6217D#;
27441    u00013 : constant Version_32 := 16#68A22947#;
27442    u00014 : constant Version_32 := 16#18CC4A56#;
27443    u00015 : constant Version_32 := 16#08258E1B#;
27444    u00016 : constant Version_32 := 16#367D5222#;
27445    u00017 : constant Version_32 := 16#20C9ECA4#;
27446    u00018 : constant Version_32 := 16#50D32CB6#;
27447    u00019 : constant Version_32 := 16#39A8BB77#;
27448    u00020 : constant Version_32 := 16#5CF8FA2B#;
27449    u00021 : constant Version_32 := 16#2F1EB794#;
27450    u00022 : constant Version_32 := 16#31AB6444#;
27451    u00023 : constant Version_32 := 16#1574B6E9#;
27452    u00024 : constant Version_32 := 16#5109C189#;
27453    u00025 : constant Version_32 := 16#56D770CD#;
27454    u00026 : constant Version_32 := 16#02F9DE3D#;
27455    u00027 : constant Version_32 := 16#08AB6B2C#;
27456    u00028 : constant Version_32 := 16#3FA37670#;
27457    u00029 : constant Version_32 := 16#476457A0#;
27458    u00030 : constant Version_32 := 16#731E1B6E#;
27459    u00031 : constant Version_32 := 16#23C2E789#;
27460    u00032 : constant Version_32 := 16#0F1BD6A1#;
27461    u00033 : constant Version_32 := 16#7C25DE96#;
27462    u00034 : constant Version_32 := 16#39ADFFA2#;
27463    u00035 : constant Version_32 := 16#571DE3E7#;
27464    u00036 : constant Version_32 := 16#5EB646AB#;
27465    u00037 : constant Version_32 := 16#4249379B#;
27466    u00038 : constant Version_32 := 16#0357E00A#;
27467    u00039 : constant Version_32 := 16#3784FB72#;
27468    u00040 : constant Version_32 := 16#2E723019#;
27469    u00041 : constant Version_32 := 16#623358EA#;
27470    u00042 : constant Version_32 := 16#107F9465#;
27471    u00043 : constant Version_32 := 16#6843F68A#;
27472    u00044 : constant Version_32 := 16#63305874#;
27473    u00045 : constant Version_32 := 16#31E56CE1#;
27474    u00046 : constant Version_32 := 16#02917970#;
27475    u00047 : constant Version_32 := 16#6CCBA70E#;
27476    u00048 : constant Version_32 := 16#41CD4204#;
27477    u00049 : constant Version_32 := 16#572E3F58#;
27478    u00050 : constant Version_32 := 16#20729FF5#;
27479    u00051 : constant Version_32 := 16#1D4F93E8#;
27480    u00052 : constant Version_32 := 16#30B2EC3D#;
27481    u00053 : constant Version_32 := 16#34054F96#;
27482    u00054 : constant Version_32 := 16#5A199860#;
27483    u00055 : constant Version_32 := 16#0E7F912B#;
27484    u00056 : constant Version_32 := 16#5760634A#;
27485    u00057 : constant Version_32 := 16#5D851835#;
27486
27487    --  The following Export pragmas export the version numbers
27488    --  with symbolic names ending in B (for body) or S
27489    --  (for spec) so that they can be located in a link. The
27490    --  information provided here is sufficient to track down
27491    --  the exact versions of units used in a given build.
27492
27493    pragma Export (C, u00001, "helloB");
27494    pragma Export (C, u00002, "system__standard_libraryB");
27495    pragma Export (C, u00003, "system__standard_libraryS");
27496    pragma Export (C, u00004, "adaS");
27497    pragma Export (C, u00005, "ada__text_ioB");
27498    pragma Export (C, u00006, "ada__text_ioS");
27499    pragma Export (C, u00007, "ada__exceptionsB");
27500    pragma Export (C, u00008, "ada__exceptionsS");
27501    pragma Export (C, u00009, "gnatS");
27502    pragma Export (C, u00010, "gnat__heap_sort_aB");
27503    pragma Export (C, u00011, "gnat__heap_sort_aS");
27504    pragma Export (C, u00012, "systemS");
27505    pragma Export (C, u00013, "system__exception_tableB");
27506    pragma Export (C, u00014, "system__exception_tableS");
27507    pragma Export (C, u00015, "gnat__htableB");
27508    pragma Export (C, u00016, "gnat__htableS");
27509    pragma Export (C, u00017, "system__exceptionsS");
27510    pragma Export (C, u00018, "system__machine_state_operationsB");
27511    pragma Export (C, u00019, "system__machine_state_operationsS");
27512    pragma Export (C, u00020, "system__machine_codeS");
27513    pragma Export (C, u00021, "system__storage_elementsB");
27514    pragma Export (C, u00022, "system__storage_elementsS");
27515    pragma Export (C, u00023, "system__secondary_stackB");
27516    pragma Export (C, u00024, "system__secondary_stackS");
27517    pragma Export (C, u00025, "system__parametersB");
27518    pragma Export (C, u00026, "system__parametersS");
27519    pragma Export (C, u00027, "system__soft_linksB");
27520    pragma Export (C, u00028, "system__soft_linksS");
27521    pragma Export (C, u00029, "system__stack_checkingB");
27522    pragma Export (C, u00030, "system__stack_checkingS");
27523    pragma Export (C, u00031, "system__tracebackB");
27524    pragma Export (C, u00032, "system__tracebackS");
27525    pragma Export (C, u00033, "ada__streamsS");
27526    pragma Export (C, u00034, "ada__tagsB");
27527    pragma Export (C, u00035, "ada__tagsS");
27528    pragma Export (C, u00036, "system__string_opsB");
27529    pragma Export (C, u00037, "system__string_opsS");
27530    pragma Export (C, u00038, "interfacesS");
27531    pragma Export (C, u00039, "interfaces__c_streamsB");
27532    pragma Export (C, u00040, "interfaces__c_streamsS");
27533    pragma Export (C, u00041, "system__file_ioB");
27534    pragma Export (C, u00042, "system__file_ioS");
27535    pragma Export (C, u00043, "ada__finalizationB");
27536    pragma Export (C, u00044, "ada__finalizationS");
27537    pragma Export (C, u00045, "system__finalization_rootB");
27538    pragma Export (C, u00046, "system__finalization_rootS");
27539    pragma Export (C, u00047, "system__finalization_implementationB");
27540    pragma Export (C, u00048, "system__finalization_implementationS");
27541    pragma Export (C, u00049, "system__string_ops_concat_3B");
27542    pragma Export (C, u00050, "system__string_ops_concat_3S");
27543    pragma Export (C, u00051, "system__stream_attributesB");
27544    pragma Export (C, u00052, "system__stream_attributesS");
27545    pragma Export (C, u00053, "ada__io_exceptionsS");
27546    pragma Export (C, u00054, "system__unsigned_typesS");
27547    pragma Export (C, u00055, "system__file_control_blockS");
27548    pragma Export (C, u00056, "ada__finalization__list_controllerB");
27549    pragma Export (C, u00057, "ada__finalization__list_controllerS");
27550
27551    -- BEGIN ELABORATION ORDER
27552    -- ada (spec)
27553    -- gnat (spec)
27554    -- gnat.heap_sort_a (spec)
27555    -- gnat.heap_sort_a (body)
27556    -- gnat.htable (spec)
27557    -- gnat.htable (body)
27558    -- interfaces (spec)
27559    -- system (spec)
27560    -- system.machine_code (spec)
27561    -- system.parameters (spec)
27562    -- system.parameters (body)
27563    -- interfaces.c_streams (spec)
27564    -- interfaces.c_streams (body)
27565    -- system.standard_library (spec)
27566    -- ada.exceptions (spec)
27567    -- system.exception_table (spec)
27568    -- system.exception_table (body)
27569    -- ada.io_exceptions (spec)
27570    -- system.exceptions (spec)
27571    -- system.storage_elements (spec)
27572    -- system.storage_elements (body)
27573    -- system.machine_state_operations (spec)
27574    -- system.machine_state_operations (body)
27575    -- system.secondary_stack (spec)
27576    -- system.stack_checking (spec)
27577    -- system.soft_links (spec)
27578    -- system.soft_links (body)
27579    -- system.stack_checking (body)
27580    -- system.secondary_stack (body)
27581    -- system.standard_library (body)
27582    -- system.string_ops (spec)
27583    -- system.string_ops (body)
27584    -- ada.tags (spec)
27585    -- ada.tags (body)
27586    -- ada.streams (spec)
27587    -- system.finalization_root (spec)
27588    -- system.finalization_root (body)
27589    -- system.string_ops_concat_3 (spec)
27590    -- system.string_ops_concat_3 (body)
27591    -- system.traceback (spec)
27592    -- system.traceback (body)
27593    -- ada.exceptions (body)
27594    -- system.unsigned_types (spec)
27595    -- system.stream_attributes (spec)
27596    -- system.stream_attributes (body)
27597    -- system.finalization_implementation (spec)
27598    -- system.finalization_implementation (body)
27599    -- ada.finalization (spec)
27600    -- ada.finalization (body)
27601    -- ada.finalization.list_controller (spec)
27602    -- ada.finalization.list_controller (body)
27603    -- system.file_control_block (spec)
27604    -- system.file_io (spec)
27605    -- system.file_io (body)
27606    -- ada.text_io (spec)
27607    -- ada.text_io (body)
27608    -- hello (body)
27609    -- END ELABORATION ORDER
27610
27611 end ada_main;
27612
27613 --  The following source file name pragmas allow the generated file
27614 --  names to be unique for different main programs. They are needed
27615 --  since the package name will always be Ada_Main.
27616
27617 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
27618 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
27619
27620 --  Generated package body for Ada_Main starts here
27621
27622 package body ada_main is
27623
27624    --  The actual finalization is performed by calling the
27625    --  library routine in System.Standard_Library.Adafinal
27626
27627    procedure Do_Finalize;
27628    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
27629
27630    -------------
27631    -- adainit --
27632    -------------
27633
27634 @findex adainit
27635    procedure adainit is
27636
27637       --  These booleans are set to True once the associated unit has
27638       --  been elaborated. It is also used to avoid elaborating the
27639       --  same unit twice.
27640
27641       E040 : Boolean;
27642       pragma Import (Ada, E040, "interfaces__c_streams_E");
27643
27644       E008 : Boolean;
27645       pragma Import (Ada, E008, "ada__exceptions_E");
27646
27647       E014 : Boolean;
27648       pragma Import (Ada, E014, "system__exception_table_E");
27649
27650       E053 : Boolean;
27651       pragma Import (Ada, E053, "ada__io_exceptions_E");
27652
27653       E017 : Boolean;
27654       pragma Import (Ada, E017, "system__exceptions_E");
27655
27656       E024 : Boolean;
27657       pragma Import (Ada, E024, "system__secondary_stack_E");
27658
27659       E030 : Boolean;
27660       pragma Import (Ada, E030, "system__stack_checking_E");
27661
27662       E028 : Boolean;
27663       pragma Import (Ada, E028, "system__soft_links_E");
27664
27665       E035 : Boolean;
27666       pragma Import (Ada, E035, "ada__tags_E");
27667
27668       E033 : Boolean;
27669       pragma Import (Ada, E033, "ada__streams_E");
27670
27671       E046 : Boolean;
27672       pragma Import (Ada, E046, "system__finalization_root_E");
27673
27674       E048 : Boolean;
27675       pragma Import (Ada, E048, "system__finalization_implementation_E");
27676
27677       E044 : Boolean;
27678       pragma Import (Ada, E044, "ada__finalization_E");
27679
27680       E057 : Boolean;
27681       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
27682
27683       E055 : Boolean;
27684       pragma Import (Ada, E055, "system__file_control_block_E");
27685
27686       E042 : Boolean;
27687       pragma Import (Ada, E042, "system__file_io_E");
27688
27689       E006 : Boolean;
27690       pragma Import (Ada, E006, "ada__text_io_E");
27691
27692       --  Set_Globals is a library routine that stores away the
27693       --  value of the indicated set of global values in global
27694       --  variables within the library.
27695
27696       procedure Set_Globals
27697         (Main_Priority            : Integer;
27698          Time_Slice_Value         : Integer;
27699          WC_Encoding              : Character;
27700          Locking_Policy           : Character;
27701          Queuing_Policy           : Character;
27702          Task_Dispatching_Policy  : Character;
27703          Adafinal                 : System.Address;
27704          Unreserve_All_Interrupts : Integer;
27705          Exception_Tracebacks     : Integer);
27706 @findex __gnat_set_globals
27707       pragma Import (C, Set_Globals, "__gnat_set_globals");
27708
27709       --  SDP_Table_Build is a library routine used to build the
27710       --  exception tables. See unit Ada.Exceptions in files
27711       --  a-except.ads/adb for full details of how zero cost
27712       --  exception handling works. This procedure, the call to
27713       --  it, and the two following tables are all omitted if the
27714       --  build is in longjmp/setjmp exception mode.
27715
27716 @findex SDP_Table_Build
27717 @findex Zero Cost Exceptions
27718       procedure SDP_Table_Build
27719         (SDP_Addresses   : System.Address;
27720          SDP_Count       : Natural;
27721          Elab_Addresses  : System.Address;
27722          Elab_Addr_Count : Natural);
27723       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
27724
27725       --  Table of Unit_Exception_Table addresses. Used for zero
27726       --  cost exception handling to build the top level table.
27727
27728       ST : aliased constant array (1 .. 23) of System.Address := (
27729         Hello'UET_Address,
27730         Ada.Text_Io'UET_Address,
27731         Ada.Exceptions'UET_Address,
27732         Gnat.Heap_Sort_A'UET_Address,
27733         System.Exception_Table'UET_Address,
27734         System.Machine_State_Operations'UET_Address,
27735         System.Secondary_Stack'UET_Address,
27736         System.Parameters'UET_Address,
27737         System.Soft_Links'UET_Address,
27738         System.Stack_Checking'UET_Address,
27739         System.Traceback'UET_Address,
27740         Ada.Streams'UET_Address,
27741         Ada.Tags'UET_Address,
27742         System.String_Ops'UET_Address,
27743         Interfaces.C_Streams'UET_Address,
27744         System.File_Io'UET_Address,
27745         Ada.Finalization'UET_Address,
27746         System.Finalization_Root'UET_Address,
27747         System.Finalization_Implementation'UET_Address,
27748         System.String_Ops_Concat_3'UET_Address,
27749         System.Stream_Attributes'UET_Address,
27750         System.File_Control_Block'UET_Address,
27751         Ada.Finalization.List_Controller'UET_Address);
27752
27753       --  Table of addresses of elaboration routines. Used for
27754       --  zero cost exception handling to make sure these
27755       --  addresses are included in the top level procedure
27756       --  address table.
27757
27758       EA : aliased constant array (1 .. 23) of System.Address := (
27759         adainit'Code_Address,
27760         Do_Finalize'Code_Address,
27761         Ada.Exceptions'Elab_Spec'Address,
27762         System.Exceptions'Elab_Spec'Address,
27763         Interfaces.C_Streams'Elab_Spec'Address,
27764         System.Exception_Table'Elab_Body'Address,
27765         Ada.Io_Exceptions'Elab_Spec'Address,
27766         System.Stack_Checking'Elab_Spec'Address,
27767         System.Soft_Links'Elab_Body'Address,
27768         System.Secondary_Stack'Elab_Body'Address,
27769         Ada.Tags'Elab_Spec'Address,
27770         Ada.Tags'Elab_Body'Address,
27771         Ada.Streams'Elab_Spec'Address,
27772         System.Finalization_Root'Elab_Spec'Address,
27773         Ada.Exceptions'Elab_Body'Address,
27774         System.Finalization_Implementation'Elab_Spec'Address,
27775         System.Finalization_Implementation'Elab_Body'Address,
27776         Ada.Finalization'Elab_Spec'Address,
27777         Ada.Finalization.List_Controller'Elab_Spec'Address,
27778         System.File_Control_Block'Elab_Spec'Address,
27779         System.File_Io'Elab_Body'Address,
27780         Ada.Text_Io'Elab_Spec'Address,
27781         Ada.Text_Io'Elab_Body'Address);
27782
27783    --  Start of processing for adainit
27784
27785    begin
27786
27787       --  Call SDP_Table_Build to build the top level procedure
27788       --  table for zero cost exception handling (omitted in
27789       --  longjmp/setjmp mode).
27790
27791       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
27792
27793       --  Call Set_Globals to record various information for
27794       --  this partition.  The values are derived by the binder
27795       --  from information stored in the ali files by the compiler.
27796
27797 @findex __gnat_set_globals
27798       Set_Globals
27799         (Main_Priority            => -1,
27800          --  Priority of main program, -1 if no pragma Priority used
27801
27802          Time_Slice_Value         => -1,
27803          --  Time slice from Time_Slice pragma, -1 if none used
27804
27805          WC_Encoding              => 'b',
27806          --  Wide_Character encoding used, default is brackets
27807
27808          Locking_Policy           => ' ',
27809          --  Locking_Policy used, default of space means not
27810          --  specified, otherwise it is the first character of
27811          --  the policy name.
27812
27813          Queuing_Policy           => ' ',
27814          --  Queuing_Policy used, default of space means not
27815          --  specified, otherwise it is the first character of
27816          --  the policy name.
27817
27818          Task_Dispatching_Policy  => ' ',
27819          --  Task_Dispatching_Policy used, default of space means
27820          --  not specified, otherwise first character of the
27821          --  policy name.
27822
27823          Adafinal                 => System.Null_Address,
27824          --  Address of Adafinal routine, not used anymore
27825
27826          Unreserve_All_Interrupts => 0,
27827          --  Set true if pragma Unreserve_All_Interrupts was used
27828
27829          Exception_Tracebacks     => 0);
27830          --  Indicates if exception tracebacks are enabled
27831
27832       Elab_Final_Code := 1;
27833
27834       --  Now we have the elaboration calls for all units in the partition.
27835       --  The Elab_Spec and Elab_Body attributes generate references to the
27836       --  implicit elaboration procedures generated by the compiler for
27837       --  each unit that requires elaboration.
27838
27839       if not E040 then
27840          Interfaces.C_Streams'Elab_Spec;
27841       end if;
27842       E040 := True;
27843       if not E008 then
27844          Ada.Exceptions'Elab_Spec;
27845       end if;
27846       if not E014 then
27847          System.Exception_Table'Elab_Body;
27848          E014 := True;
27849       end if;
27850       if not E053 then
27851          Ada.Io_Exceptions'Elab_Spec;
27852          E053 := True;
27853       end if;
27854       if not E017 then
27855          System.Exceptions'Elab_Spec;
27856          E017 := True;
27857       end if;
27858       if not E030 then
27859          System.Stack_Checking'Elab_Spec;
27860       end if;
27861       if not E028 then
27862          System.Soft_Links'Elab_Body;
27863          E028 := True;
27864       end if;
27865       E030 := True;
27866       if not E024 then
27867          System.Secondary_Stack'Elab_Body;
27868          E024 := True;
27869       end if;
27870       if not E035 then
27871          Ada.Tags'Elab_Spec;
27872       end if;
27873       if not E035 then
27874          Ada.Tags'Elab_Body;
27875          E035 := True;
27876       end if;
27877       if not E033 then
27878          Ada.Streams'Elab_Spec;
27879          E033 := True;
27880       end if;
27881       if not E046 then
27882          System.Finalization_Root'Elab_Spec;
27883       end if;
27884       E046 := True;
27885       if not E008 then
27886          Ada.Exceptions'Elab_Body;
27887          E008 := True;
27888       end if;
27889       if not E048 then
27890          System.Finalization_Implementation'Elab_Spec;
27891       end if;
27892       if not E048 then
27893          System.Finalization_Implementation'Elab_Body;
27894          E048 := True;
27895       end if;
27896       if not E044 then
27897          Ada.Finalization'Elab_Spec;
27898       end if;
27899       E044 := True;
27900       if not E057 then
27901          Ada.Finalization.List_Controller'Elab_Spec;
27902       end if;
27903       E057 := True;
27904       if not E055 then
27905          System.File_Control_Block'Elab_Spec;
27906          E055 := True;
27907       end if;
27908       if not E042 then
27909          System.File_Io'Elab_Body;
27910          E042 := True;
27911       end if;
27912       if not E006 then
27913          Ada.Text_Io'Elab_Spec;
27914       end if;
27915       if not E006 then
27916          Ada.Text_Io'Elab_Body;
27917          E006 := True;
27918       end if;
27919
27920       Elab_Final_Code := 0;
27921    end adainit;
27922
27923    --------------
27924    -- adafinal --
27925    --------------
27926
27927 @findex adafinal
27928    procedure adafinal is
27929    begin
27930       Do_Finalize;
27931    end adafinal;
27932
27933    ----------
27934    -- main --
27935    ----------
27936
27937    --  main is actually a function, as in the ANSI C standard,
27938    --  defined to return the exit status. The three parameters
27939    --  are the argument count, argument values and environment
27940    --  pointer.
27941
27942 @findex Main Program
27943    function main
27944      (argc : Integer;
27945       argv : System.Address;
27946       envp : System.Address)
27947       return Integer
27948    is
27949       --  The initialize routine performs low level system
27950       --  initialization using a standard library routine which
27951       --  sets up signal handling and performs any other
27952       --  required setup. The routine can be found in file
27953       --  a-init.c.
27954
27955 @findex __gnat_initialize
27956       procedure initialize;
27957       pragma Import (C, initialize, "__gnat_initialize");
27958
27959       --  The finalize routine performs low level system
27960       --  finalization using a standard library routine. The
27961       --  routine is found in file a-final.c and in the standard
27962       --  distribution is a dummy routine that does nothing, so
27963       --  really this is a hook for special user finalization.
27964
27965 @findex __gnat_finalize
27966       procedure finalize;
27967       pragma Import (C, finalize, "__gnat_finalize");
27968
27969       --  We get to the main program of the partition by using
27970       --  pragma Import because if we try to with the unit and
27971       --  call it Ada style, then not only do we waste time
27972       --  recompiling it, but also, we don't really know the right
27973       --  switches (e.g.@: identifier character set) to be used
27974       --  to compile it.
27975
27976       procedure Ada_Main_Program;
27977       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
27978
27979    --  Start of processing for main
27980
27981    begin
27982       --  Save global variables
27983
27984       gnat_argc := argc;
27985       gnat_argv := argv;
27986       gnat_envp := envp;
27987
27988       --  Call low level system initialization
27989
27990       Initialize;
27991
27992       --  Call our generated Ada initialization routine
27993
27994       adainit;
27995
27996       --  This is the point at which we want the debugger to get
27997       --  control
27998
27999       Break_Start;
28000
28001       --  Now we call the main program of the partition
28002
28003       Ada_Main_Program;
28004
28005       --  Perform Ada finalization
28006
28007       adafinal;
28008
28009       --  Perform low level system finalization
28010
28011       Finalize;
28012
28013       --  Return the proper exit status
28014       return (gnat_exit_status);
28015    end;
28016
28017 --  This section is entirely comments, so it has no effect on the
28018 --  compilation of the Ada_Main package. It provides the list of
28019 --  object files and linker options, as well as some standard
28020 --  libraries needed for the link. The gnatlink utility parses
28021 --  this b~hello.adb file to read these comment lines to generate
28022 --  the appropriate command line arguments for the call to the
28023 --  system linker. The BEGIN/END lines are used for sentinels for
28024 --  this parsing operation.
28025
28026 --  The exact file names will of course depend on the environment,
28027 --  host/target and location of files on the host system.
28028
28029 @findex Object file list
28030 -- BEGIN Object file/option list
28031    --   ./hello.o
28032    --   -L./
28033    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
28034    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
28035 -- END Object file/option list
28036
28037 end ada_main;
28038 @end smallexample
28039
28040 @noindent
28041 The Ada code in the above example is exactly what is generated by the
28042 binder. We have added comments to more clearly indicate the function
28043 of each part of the generated @code{Ada_Main} package.
28044
28045 The code is standard Ada in all respects, and can be processed by any
28046 tools that handle Ada. In particular, it is possible to use the debugger
28047 in Ada mode to debug the generated @code{Ada_Main} package. For example,
28048 suppose that for reasons that you do not understand, your program is crashing
28049 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
28050 you can place a breakpoint on the call:
28051
28052 @smallexample @c ada
28053 Ada.Text_Io'Elab_Body;
28054 @end smallexample
28055
28056 @noindent
28057 and trace the elaboration routine for this package to find out where
28058 the problem might be (more usually of course you would be debugging
28059 elaboration code in your own application).
28060
28061 @node Elaboration Order Handling in GNAT
28062 @appendix Elaboration Order Handling in GNAT
28063 @cindex Order of elaboration
28064 @cindex Elaboration control
28065
28066 @menu
28067 * Elaboration Code::
28068 * Checking the Elaboration Order::
28069 * Controlling the Elaboration Order::
28070 * Controlling Elaboration in GNAT - Internal Calls::
28071 * Controlling Elaboration in GNAT - External Calls::
28072 * Default Behavior in GNAT - Ensuring Safety::
28073 * Treatment of Pragma Elaborate::
28074 * Elaboration Issues for Library Tasks::
28075 * Mixing Elaboration Models::
28076 * What to Do If the Default Elaboration Behavior Fails::
28077 * Elaboration for Access-to-Subprogram Values::
28078 * Summary of Procedures for Elaboration Control::
28079 * Other Elaboration Order Considerations::
28080 @end menu
28081
28082 @noindent
28083 This chapter describes the handling of elaboration code in Ada and
28084 in GNAT, and discusses how the order of elaboration of program units can
28085 be controlled in GNAT, either automatically or with explicit programming
28086 features.
28087
28088 @node Elaboration Code
28089 @section Elaboration Code
28090
28091 @noindent
28092 Ada provides rather general mechanisms for executing code at elaboration
28093 time, that is to say before the main program starts executing. Such code arises
28094 in three contexts:
28095
28096 @table @asis
28097 @item Initializers for variables.
28098 Variables declared at the library level, in package specs or bodies, can
28099 require initialization that is performed at elaboration time, as in:
28100 @smallexample @c ada
28101 @cartouche
28102 Sqrt_Half : Float := Sqrt (0.5);
28103 @end cartouche
28104 @end smallexample
28105
28106 @item Package initialization code
28107 Code in a @code{BEGIN-END} section at the outer level of a package body is
28108 executed as part of the package body elaboration code.
28109
28110 @item Library level task allocators
28111 Tasks that are declared using task allocators at the library level
28112 start executing immediately and hence can execute at elaboration time.
28113 @end table
28114
28115 @noindent
28116 Subprogram calls are possible in any of these contexts, which means that
28117 any arbitrary part of the program may be executed as part of the elaboration
28118 code. It is even possible to write a program which does all its work at
28119 elaboration time, with a null main program, although stylistically this
28120 would usually be considered an inappropriate way to structure
28121 a program.
28122
28123 An important concern arises in the context of elaboration code:
28124 we have to be sure that it is executed in an appropriate order. What we
28125 have is a series of elaboration code sections, potentially one section
28126 for each unit in the program. It is important that these execute
28127 in the correct order. Correctness here means that, taking the above
28128 example of the declaration of @code{Sqrt_Half},
28129 if some other piece of
28130 elaboration code references @code{Sqrt_Half},
28131 then it must run after the
28132 section of elaboration code that contains the declaration of
28133 @code{Sqrt_Half}.
28134
28135 There would never be any order of elaboration problem if we made a rule
28136 that whenever you @code{with} a unit, you must elaborate both the spec and body
28137 of that unit before elaborating the unit doing the @code{with}'ing:
28138
28139 @smallexample @c ada
28140 @group
28141 @cartouche
28142 with Unit_1;
28143 package Unit_2 is @dots{}
28144 @end cartouche
28145 @end group
28146 @end smallexample
28147
28148 @noindent
28149 would require that both the body and spec of @code{Unit_1} be elaborated
28150 before the spec of @code{Unit_2}. However, a rule like that would be far too
28151 restrictive. In particular, it would make it impossible to have routines
28152 in separate packages that were mutually recursive.
28153
28154 You might think that a clever enough compiler could look at the actual
28155 elaboration code and determine an appropriate correct order of elaboration,
28156 but in the general case, this is not possible. Consider the following
28157 example.
28158
28159 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
28160 that references
28161 the variable @code{Sqrt_1}, which is declared in the elaboration code
28162 of the body of @code{Unit_1}:
28163
28164 @smallexample @c ada
28165 @cartouche
28166 Sqrt_1 : Float := Sqrt (0.1);
28167 @end cartouche
28168 @end smallexample
28169
28170 @noindent
28171 The elaboration code of the body of @code{Unit_1} also contains:
28172
28173 @smallexample @c ada
28174 @group
28175 @cartouche
28176 if expression_1 = 1 then
28177    Q := Unit_2.Func_2;
28178 end if;
28179 @end cartouche
28180 @end group
28181 @end smallexample
28182
28183 @noindent
28184 @code{Unit_2} is exactly parallel,
28185 it has a procedure @code{Func_2} that references
28186 the variable @code{Sqrt_2}, which is declared in the elaboration code of
28187 the body @code{Unit_2}:
28188
28189 @smallexample @c ada
28190 @cartouche
28191 Sqrt_2 : Float := Sqrt (0.1);
28192 @end cartouche
28193 @end smallexample
28194
28195 @noindent
28196 The elaboration code of the body of @code{Unit_2} also contains:
28197
28198 @smallexample @c ada
28199 @group
28200 @cartouche
28201 if expression_2 = 2 then
28202    Q := Unit_1.Func_1;
28203 end if;
28204 @end cartouche
28205 @end group
28206 @end smallexample
28207
28208 @noindent
28209 Now the question is, which of the following orders of elaboration is
28210 acceptable:
28211
28212 @smallexample
28213 @group
28214 Spec of Unit_1
28215 Spec of Unit_2
28216 Body of Unit_1
28217 Body of Unit_2
28218 @end group
28219 @end smallexample
28220
28221 @noindent
28222 or
28223
28224 @smallexample
28225 @group
28226 Spec of Unit_2
28227 Spec of Unit_1
28228 Body of Unit_2
28229 Body of Unit_1
28230 @end group
28231 @end smallexample
28232
28233 @noindent
28234 If you carefully analyze the flow here, you will see that you cannot tell
28235 at compile time the answer to this question.
28236 If @code{expression_1} is not equal to 1,
28237 and @code{expression_2} is not equal to 2,
28238 then either order is acceptable, because neither of the function calls is
28239 executed. If both tests evaluate to true, then neither order is acceptable
28240 and in fact there is no correct order.
28241
28242 If one of the two expressions is true, and the other is false, then one
28243 of the above orders is correct, and the other is incorrect. For example,
28244 if @code{expression_1} /= 1 and @code{expression_2} = 2,
28245 then the call to @code{Func_1}
28246 will occur, but not the call to @code{Func_2.}
28247 This means that it is essential
28248 to elaborate the body of @code{Unit_1} before
28249 the body of @code{Unit_2}, so the first
28250 order of elaboration is correct and the second is wrong.
28251
28252 By making @code{expression_1} and @code{expression_2}
28253 depend on input data, or perhaps
28254 the time of day, we can make it impossible for the compiler or binder
28255 to figure out which of these expressions will be true, and hence it
28256 is impossible to guarantee a safe order of elaboration at run time.
28257
28258 @node Checking the Elaboration Order
28259 @section Checking the Elaboration Order
28260
28261 @noindent
28262 In some languages that involve the same kind of elaboration problems,
28263 e.g.@: Java and C++, the programmer is expected to worry about these
28264 ordering problems himself, and it is common to
28265 write a program in which an incorrect elaboration order  gives
28266 surprising results, because it references variables before they
28267 are initialized.
28268 Ada is designed to be a safe language, and a programmer-beware approach is
28269 clearly not sufficient. Consequently, the language provides three lines
28270 of defense:
28271
28272 @table @asis
28273 @item Standard rules
28274 Some standard rules restrict the possible choice of elaboration
28275 order. In particular, if you @code{with} a unit, then its spec is always
28276 elaborated before the unit doing the @code{with}. Similarly, a parent
28277 spec is always elaborated before the child spec, and finally
28278 a spec is always elaborated before its corresponding body.
28279
28280 @item Dynamic elaboration checks
28281 @cindex Elaboration checks
28282 @cindex Checks, elaboration
28283 Dynamic checks are made at run time, so that if some entity is accessed
28284 before it is elaborated (typically  by means of a subprogram call)
28285 then the exception (@code{Program_Error}) is raised.
28286
28287 @item Elaboration control
28288 Facilities are provided for the programmer to specify the desired order
28289 of elaboration.
28290 @end table
28291
28292 Let's look at these facilities in more detail. First, the rules for
28293 dynamic checking. One possible rule would be simply to say that the
28294 exception is raised if you access a variable which has not yet been
28295 elaborated. The trouble with this approach is that it could require
28296 expensive checks on every variable reference. Instead Ada has two
28297 rules which are a little more restrictive, but easier to check, and
28298 easier to state:
28299
28300 @table @asis
28301 @item Restrictions on calls
28302 A subprogram can only be called at elaboration time if its body
28303 has been elaborated. The rules for elaboration given above guarantee
28304 that the spec of the subprogram has been elaborated before the
28305 call, but not the body. If this rule is violated, then the
28306 exception @code{Program_Error} is raised.
28307
28308 @item Restrictions on instantiations
28309 A generic unit can only be instantiated if the body of the generic
28310 unit has been elaborated. Again, the rules for elaboration given above
28311 guarantee that the spec of the generic unit has been elaborated
28312 before the instantiation, but not the body. If this rule is
28313 violated, then the exception @code{Program_Error} is raised.
28314 @end table
28315
28316 @noindent
28317 The idea is that if the body has been elaborated, then any variables
28318 it references must have been elaborated; by checking for the body being
28319 elaborated we guarantee that none of its references causes any
28320 trouble. As we noted above, this is a little too restrictive, because a
28321 subprogram that has no non-local references in its body may in fact be safe
28322 to call. However, it really would be unsafe to rely on this, because
28323 it would mean that the caller was aware of details of the implementation
28324 in the body. This goes against the basic tenets of Ada.
28325
28326 A plausible implementation can be described as follows.
28327 A Boolean variable is associated with each subprogram
28328 and each generic unit. This variable is initialized to False, and is set to
28329 True at the point body is elaborated. Every call or instantiation checks the
28330 variable, and raises @code{Program_Error} if the variable is False.
28331
28332 Note that one might think that it would be good enough to have one Boolean
28333 variable for each package, but that would not deal with cases of trying
28334 to call a body in the same package as the call
28335 that has not been elaborated yet.
28336 Of course a compiler may be able to do enough analysis to optimize away
28337 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
28338 does such optimizations, but still the easiest conceptual model is to
28339 think of there being one variable per subprogram.
28340
28341 @node Controlling the Elaboration Order
28342 @section Controlling the Elaboration Order
28343
28344 @noindent
28345 In the previous section we discussed the rules in Ada which ensure
28346 that @code{Program_Error} is raised if an incorrect elaboration order is
28347 chosen. This prevents erroneous executions, but we need mechanisms to
28348 specify a correct execution and avoid the exception altogether.
28349 To achieve this, Ada provides a number of features for controlling
28350 the order of elaboration. We discuss these features in this section.
28351
28352 First, there are several ways of indicating to the compiler that a given
28353 unit has no elaboration problems:
28354
28355 @table @asis
28356 @item packages that do not require a body
28357 A library package that does not require a body does not permit
28358 a body (this rule was introduced in Ada 95).
28359 Thus if we have a such a package, as in:
28360
28361 @smallexample @c ada
28362 @group
28363 @cartouche
28364 package Definitions is
28365    generic
28366       type m is new integer;
28367    package Subp is
28368       type a is array (1 .. 10) of m;
28369       type b is array (1 .. 20) of m;
28370    end Subp;
28371 end Definitions;
28372 @end cartouche
28373 @end group
28374 @end smallexample
28375
28376 @noindent
28377 A package that @code{with}'s @code{Definitions} may safely instantiate
28378 @code{Definitions.Subp} because the compiler can determine that there
28379 definitely is no package body to worry about in this case
28380
28381 @item pragma Pure
28382 @cindex pragma Pure
28383 @findex Pure
28384 Places sufficient restrictions on a unit to guarantee that
28385 no call to any subprogram in the unit can result in an
28386 elaboration problem. This means that the compiler does not need
28387 to worry about the point of elaboration of such units, and in
28388 particular, does not need to check any calls to any subprograms
28389 in this unit.
28390
28391 @item pragma Preelaborate
28392 @findex Preelaborate
28393 @cindex pragma Preelaborate
28394 This pragma places slightly less stringent restrictions on a unit than
28395 does pragma Pure,
28396 but these restrictions are still sufficient to ensure that there
28397 are no elaboration problems with any calls to the unit.
28398
28399 @item pragma Elaborate_Body
28400 @findex Elaborate_Body
28401 @cindex pragma Elaborate_Body
28402 This pragma requires that the body of a unit be elaborated immediately
28403 after its spec. Suppose a unit @code{A} has such a pragma,
28404 and unit @code{B} does
28405 a @code{with} of unit @code{A}. Recall that the standard rules require
28406 the spec of unit @code{A}
28407 to be elaborated before the @code{with}'ing unit; given the pragma in
28408 @code{A}, we also know that the body of @code{A}
28409 will be elaborated before @code{B}, so
28410 that calls to @code{A} are safe and do not need a check.
28411 @end table
28412
28413 @noindent
28414 Note that,
28415 unlike pragma @code{Pure} and pragma @code{Preelaborate},
28416 the use of
28417 @code{Elaborate_Body} does not guarantee that the program is
28418 free of elaboration problems, because it may not be possible
28419 to satisfy the requested elaboration order.
28420 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
28421 If a programmer
28422 marks @code{Unit_1} as @code{Elaborate_Body},
28423 and not @code{Unit_2,} then the order of
28424 elaboration will be:
28425
28426 @smallexample
28427 @group
28428 Spec of Unit_2
28429 Spec of Unit_1
28430 Body of Unit_1
28431 Body of Unit_2
28432 @end group
28433 @end smallexample
28434
28435 @noindent
28436 Now that means that the call to @code{Func_1} in @code{Unit_2}
28437 need not be checked,
28438 it must be safe. But the call to @code{Func_2} in
28439 @code{Unit_1} may still fail if
28440 @code{Expression_1} is equal to 1,
28441 and the programmer must still take
28442 responsibility for this not being the case.
28443
28444 If all units carry a pragma @code{Elaborate_Body}, then all problems are
28445 eliminated, except for calls entirely within a body, which are
28446 in any case fully under programmer control. However, using the pragma
28447 everywhere is not always possible.
28448 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
28449 we marked both of them as having pragma @code{Elaborate_Body}, then
28450 clearly there would be no possible elaboration order.
28451
28452 The above pragmas allow a server to guarantee safe use by clients, and
28453 clearly this is the preferable approach. Consequently a good rule
28454 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
28455 and if this is not possible,
28456 mark them as @code{Elaborate_Body} if possible.
28457 As we have seen, there are situations where neither of these
28458 three pragmas can be used.
28459 So we also provide methods for clients to control the
28460 order of elaboration of the servers on which they depend:
28461
28462 @table @asis
28463 @item pragma Elaborate (unit)
28464 @findex Elaborate
28465 @cindex pragma Elaborate
28466 This pragma is placed in the context clause, after a @code{with} clause,
28467 and it requires that the body of the named unit be elaborated before
28468 the unit in which the pragma occurs. The idea is to use this pragma
28469 if the current unit calls at elaboration time, directly or indirectly,
28470 some subprogram in the named unit.
28471
28472 @item pragma Elaborate_All (unit)
28473 @findex Elaborate_All
28474 @cindex pragma Elaborate_All
28475 This is a stronger version of the Elaborate pragma. Consider the
28476 following example:
28477
28478 @smallexample
28479 Unit A @code{with}'s unit B and calls B.Func in elab code
28480 Unit B @code{with}'s unit C, and B.Func calls C.Func
28481 @end smallexample
28482
28483 @noindent
28484 Now if we put a pragma @code{Elaborate (B)}
28485 in unit @code{A}, this ensures that the
28486 body of @code{B} is elaborated before the call, but not the
28487 body of @code{C}, so
28488 the call to @code{C.Func} could still cause @code{Program_Error} to
28489 be raised.
28490
28491 The effect of a pragma @code{Elaborate_All} is stronger, it requires
28492 not only that the body of the named unit be elaborated before the
28493 unit doing the @code{with}, but also the bodies of all units that the
28494 named unit uses, following @code{with} links transitively. For example,
28495 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
28496 then it requires
28497 not only that the body of @code{B} be elaborated before @code{A},
28498 but also the
28499 body of @code{C}, because @code{B} @code{with}'s @code{C}.
28500 @end table
28501
28502 @noindent
28503 We are now in a position to give a usage rule in Ada for avoiding
28504 elaboration problems, at least if dynamic dispatching and access to
28505 subprogram values are not used. We will handle these cases separately
28506 later.
28507
28508 The rule is simple. If a unit has elaboration code that can directly or
28509 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
28510 a generic package in a @code{with}'ed unit,
28511 then if the @code{with}'ed unit does not have
28512 pragma @code{Pure} or @code{Preelaborate}, then the client should have
28513 a pragma @code{Elaborate_All}
28514 for the @code{with}'ed unit. By following this rule a client is
28515 assured that calls can be made without risk of an exception.
28516
28517 For generic subprogram instantiations, the rule can be relaxed to
28518 require only a pragma @code{Elaborate} since elaborating the body
28519 of a subprogram cannot cause any transitive elaboration (we are
28520 not calling the subprogram in this case, just elaborating its
28521 declaration).
28522
28523 If this rule is not followed, then a program may be in one of four
28524 states:
28525
28526 @table @asis
28527 @item No order exists
28528 No order of elaboration exists which follows the rules, taking into
28529 account any @code{Elaborate}, @code{Elaborate_All},
28530 or @code{Elaborate_Body} pragmas. In
28531 this case, an Ada compiler must diagnose the situation at bind
28532 time, and refuse to build an executable program.
28533
28534 @item One or more orders exist, all incorrect
28535 One or more acceptable elaboration orders exist, and all of them
28536 generate an elaboration order problem. In this case, the binder
28537 can build an executable program, but @code{Program_Error} will be raised
28538 when the program is run.
28539
28540 @item Several orders exist, some right, some incorrect
28541 One or more acceptable elaboration orders exists, and some of them
28542 work, and some do not. The programmer has not controlled
28543 the order of elaboration, so the binder may or may not pick one of
28544 the correct orders, and the program may or may not raise an
28545 exception when it is run. This is the worst case, because it means
28546 that the program may fail when moved to another compiler, or even
28547 another version of the same compiler.
28548
28549 @item One or more orders exists, all correct
28550 One ore more acceptable elaboration orders exist, and all of them
28551 work. In this case the program runs successfully. This state of
28552 affairs can be guaranteed by following the rule we gave above, but
28553 may be true even if the rule is not followed.
28554 @end table
28555
28556 @noindent
28557 Note that one additional advantage of following our rules on the use
28558 of @code{Elaborate} and @code{Elaborate_All}
28559 is that the program continues to stay in the ideal (all orders OK) state
28560 even if maintenance
28561 changes some bodies of some units. Conversely, if a program that does
28562 not follow this rule happens to be safe at some point, this state of affairs
28563 may deteriorate silently as a result of maintenance changes.
28564
28565 You may have noticed that the above discussion did not mention
28566 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
28567 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
28568 code in the body makes calls to some other unit, so it is still necessary
28569 to use @code{Elaborate_All} on such units.
28570
28571 @node Controlling Elaboration in GNAT - Internal Calls
28572 @section Controlling Elaboration in GNAT - Internal Calls
28573
28574 @noindent
28575 In the case of internal calls, i.e., calls within a single package, the
28576 programmer has full control over the order of elaboration, and it is up
28577 to the programmer to elaborate declarations in an appropriate order. For
28578 example writing:
28579
28580 @smallexample @c ada
28581 @group
28582 @cartouche
28583 function One return Float;
28584
28585 Q : Float := One;
28586
28587 function One return Float is
28588 begin
28589      return 1.0;
28590 end One;
28591 @end cartouche
28592 @end group
28593 @end smallexample
28594
28595 @noindent
28596 will obviously raise @code{Program_Error} at run time, because function
28597 One will be called before its body is elaborated. In this case GNAT will
28598 generate a warning that the call will raise @code{Program_Error}:
28599
28600 @smallexample
28601 @group
28602 @cartouche
28603  1. procedure y is
28604  2.    function One return Float;
28605  3.
28606  4.    Q : Float := One;
28607                     |
28608     >>> warning: cannot call "One" before body is elaborated
28609     >>> warning: Program_Error will be raised at run time
28610
28611  5.
28612  6.    function One return Float is
28613  7.    begin
28614  8.         return 1.0;
28615  9.    end One;
28616 10.
28617 11. begin
28618 12.    null;
28619 13. end;
28620 @end cartouche
28621 @end group
28622 @end smallexample
28623
28624 @noindent
28625 Note that in this particular case, it is likely that the call is safe, because
28626 the function @code{One} does not access any global variables.
28627 Nevertheless in Ada, we do not want the validity of the check to depend on
28628 the contents of the body (think about the separate compilation case), so this
28629 is still wrong, as we discussed in the previous sections.
28630
28631 The error is easily corrected by rearranging the declarations so that the
28632 body of @code{One} appears before the declaration containing the call
28633 (note that in Ada 95 and Ada 2005,
28634 declarations can appear in any order, so there is no restriction that
28635 would prevent this reordering, and if we write:
28636
28637 @smallexample @c ada
28638 @group
28639 @cartouche
28640 function One return Float;
28641
28642 function One return Float is
28643 begin
28644      return 1.0;
28645 end One;
28646
28647 Q : Float := One;
28648 @end cartouche
28649 @end group
28650 @end smallexample
28651
28652 @noindent
28653 then all is well, no warning is generated, and no
28654 @code{Program_Error} exception
28655 will be raised.
28656 Things are more complicated when a chain of subprograms is executed:
28657
28658 @smallexample @c ada
28659 @group
28660 @cartouche
28661 function A return Integer;
28662 function B return Integer;
28663 function C return Integer;
28664
28665 function B return Integer is begin return A; end;
28666 function C return Integer is begin return B; end;
28667
28668 X : Integer := C;
28669
28670 function A return Integer is begin return 1; end;
28671 @end cartouche
28672 @end group
28673 @end smallexample
28674
28675 @noindent
28676 Now the call to @code{C}
28677 at elaboration time in the declaration of @code{X} is correct, because
28678 the body of @code{C} is already elaborated,
28679 and the call to @code{B} within the body of
28680 @code{C} is correct, but the call
28681 to @code{A} within the body of @code{B} is incorrect, because the body
28682 of @code{A} has not been elaborated, so @code{Program_Error}
28683 will be raised on the call to @code{A}.
28684 In this case GNAT will generate a
28685 warning that @code{Program_Error} may be
28686 raised at the point of the call. Let's look at the warning:
28687
28688 @smallexample
28689 @group
28690 @cartouche
28691  1. procedure x is
28692  2.    function A return Integer;
28693  3.    function B return Integer;
28694  4.    function C return Integer;
28695  5.
28696  6.    function B return Integer is begin return A; end;
28697                                                     |
28698     >>> warning: call to "A" before body is elaborated may
28699                  raise Program_Error
28700     >>> warning: "B" called at line 7
28701     >>> warning: "C" called at line 9
28702
28703  7.    function C return Integer is begin return B; end;
28704  8.
28705  9.    X : Integer := C;
28706 10.
28707 11.    function A return Integer is begin return 1; end;
28708 12.
28709 13. begin
28710 14.    null;
28711 15. end;
28712 @end cartouche
28713 @end group
28714 @end smallexample
28715
28716 @noindent
28717 Note that the message here says ``may raise'', instead of the direct case,
28718 where the message says ``will be raised''. That's because whether
28719 @code{A} is
28720 actually called depends in general on run-time flow of control.
28721 For example, if the body of @code{B} said
28722
28723 @smallexample @c ada
28724 @group
28725 @cartouche
28726 function B return Integer is
28727 begin
28728    if some-condition-depending-on-input-data then
28729       return A;
28730    else
28731       return 1;
28732    end if;
28733 end B;
28734 @end cartouche
28735 @end group
28736 @end smallexample
28737
28738 @noindent
28739 then we could not know until run time whether the incorrect call to A would
28740 actually occur, so @code{Program_Error} might
28741 or might not be raised. It is possible for a compiler to
28742 do a better job of analyzing bodies, to
28743 determine whether or not @code{Program_Error}
28744 might be raised, but it certainly
28745 couldn't do a perfect job (that would require solving the halting problem
28746 and is provably impossible), and because this is a warning anyway, it does
28747 not seem worth the effort to do the analysis. Cases in which it
28748 would be relevant are rare.
28749
28750 In practice, warnings of either of the forms given
28751 above will usually correspond to
28752 real errors, and should be examined carefully and eliminated.
28753 In the rare case where a warning is bogus, it can be suppressed by any of
28754 the following methods:
28755
28756 @itemize @bullet
28757 @item
28758 Compile with the @option{-gnatws} switch set
28759
28760 @item
28761 Suppress @code{Elaboration_Check} for the called subprogram
28762
28763 @item
28764 Use pragma @code{Warnings_Off} to turn warnings off for the call
28765 @end itemize
28766
28767 @noindent
28768 For the internal elaboration check case,
28769 GNAT by default generates the
28770 necessary run-time checks to ensure
28771 that @code{Program_Error} is raised if any
28772 call fails an elaboration check. Of course this can only happen if a
28773 warning has been issued as described above. The use of pragma
28774 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
28775 some of these checks, meaning that it may be possible (but is not
28776 guaranteed) for a program to be able to call a subprogram whose body
28777 is not yet elaborated, without raising a @code{Program_Error} exception.
28778
28779 @node Controlling Elaboration in GNAT - External Calls
28780 @section Controlling Elaboration in GNAT - External Calls
28781
28782 @noindent
28783 The previous section discussed the case in which the execution of a
28784 particular thread of elaboration code occurred entirely within a
28785 single unit. This is the easy case to handle, because a programmer
28786 has direct and total control over the order of elaboration, and
28787 furthermore, checks need only be generated in cases which are rare
28788 and which the compiler can easily detect.
28789 The situation is more complex when separate compilation is taken into account.
28790 Consider the following:
28791
28792 @smallexample @c ada
28793 @cartouche
28794 @group
28795 package Math is
28796    function Sqrt (Arg : Float) return Float;
28797 end Math;
28798
28799 package body Math is
28800    function Sqrt (Arg : Float) return Float is
28801    begin
28802          @dots{}
28803    end Sqrt;
28804 end Math;
28805 @end group
28806 @group
28807 with Math;
28808 package Stuff is
28809    X : Float := Math.Sqrt (0.5);
28810 end Stuff;
28811
28812 with Stuff;
28813 procedure Main is
28814 begin
28815    @dots{}
28816 end Main;
28817 @end group
28818 @end cartouche
28819 @end smallexample
28820
28821 @noindent
28822 where @code{Main} is the main program. When this program is executed, the
28823 elaboration code must first be executed, and one of the jobs of the
28824 binder is to determine the order in which the units of a program are
28825 to be elaborated. In this case we have four units: the spec and body
28826 of @code{Math},
28827 the spec of @code{Stuff} and the body of @code{Main}).
28828 In what order should the four separate sections of elaboration code
28829 be executed?
28830
28831 There are some restrictions in the order of elaboration that the binder
28832 can choose. In particular, if unit U has a @code{with}
28833 for a package @code{X}, then you
28834 are assured that the spec of @code{X}
28835 is elaborated before U , but you are
28836 not assured that the body of @code{X}
28837 is elaborated before U.
28838 This means that in the above case, the binder is allowed to choose the
28839 order:
28840
28841 @smallexample
28842 spec of Math
28843 spec of Stuff
28844 body of Math
28845 body of Main
28846 @end smallexample
28847
28848 @noindent
28849 but that's not good, because now the call to @code{Math.Sqrt}
28850 that happens during
28851 the elaboration of the @code{Stuff}
28852 spec happens before the body of @code{Math.Sqrt} is
28853 elaborated, and hence causes @code{Program_Error} exception to be raised.
28854 At first glance, one might say that the binder is misbehaving, because
28855 obviously you want to elaborate the body of something you @code{with}
28856 first, but
28857 that is not a general rule that can be followed in all cases. Consider
28858
28859 @smallexample @c ada
28860 @group
28861 @cartouche
28862 package X is @dots{}
28863
28864 package Y is @dots{}
28865
28866 with X;
28867 package body Y is @dots{}
28868
28869 with Y;
28870 package body X is @dots{}
28871 @end cartouche
28872 @end group
28873 @end smallexample
28874
28875 @noindent
28876 This is a common arrangement, and, apart from the order of elaboration
28877 problems that might arise in connection with elaboration code, this works fine.
28878 A rule that says that you must first elaborate the body of anything you
28879 @code{with} cannot work in this case:
28880 the body of @code{X} @code{with}'s @code{Y},
28881 which means you would have to
28882 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
28883 which means
28884 you have to elaborate the body of @code{X} first, but @dots{} and we have a
28885 loop that cannot be broken.
28886
28887 It is true that the binder can in many cases guess an order of elaboration
28888 that is unlikely to cause a @code{Program_Error}
28889 exception to be raised, and it tries to do so (in the
28890 above example of @code{Math/Stuff/Spec}, the GNAT binder will
28891 by default
28892 elaborate the body of @code{Math} right after its spec, so all will be well).
28893
28894 However, a program that blindly relies on the binder to be helpful can
28895 get into trouble, as we discussed in the previous sections, so
28896 GNAT
28897 provides a number of facilities for assisting the programmer in
28898 developing programs that are robust with respect to elaboration order.
28899
28900 @node Default Behavior in GNAT - Ensuring Safety
28901 @section Default Behavior in GNAT - Ensuring Safety
28902
28903 @noindent
28904 The default behavior in GNAT ensures elaboration safety. In its
28905 default mode GNAT implements the
28906 rule we previously described as the right approach. Let's restate it:
28907
28908 @itemize
28909 @item
28910 @emph{If a unit has elaboration code that can directly or indirectly make a
28911 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
28912 package in a @code{with}'ed unit, then if the @code{with}'ed unit
28913 does not have pragma @code{Pure} or
28914 @code{Preelaborate}, then the client should have an
28915 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
28916
28917 @emph{In the case of instantiating a generic subprogram, it is always
28918 sufficient to have only an @code{Elaborate} pragma for the
28919 @code{with}'ed unit.}
28920 @end itemize
28921
28922 @noindent
28923 By following this rule a client is assured that calls and instantiations
28924 can be made without risk of an exception.
28925
28926 In this mode GNAT traces all calls that are potentially made from
28927 elaboration code, and puts in any missing implicit @code{Elaborate}
28928 and @code{Elaborate_All} pragmas.
28929 The advantage of this approach is that no elaboration problems
28930 are possible if the binder can find an elaboration order that is
28931 consistent with these implicit @code{Elaborate} and
28932 @code{Elaborate_All} pragmas. The
28933 disadvantage of this approach is that no such order may exist.
28934
28935 If the binder does not generate any diagnostics, then it means that it has
28936 found an elaboration order that is guaranteed to be safe. However, the binder
28937 may still be relying on implicitly generated @code{Elaborate} and
28938 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
28939 guaranteed.
28940
28941 If it is important to guarantee portability, then the compilations should
28942 use the
28943 @option{-gnatwl}
28944 (warn on elaboration problems) switch. This will cause warning messages
28945 to be generated indicating the missing @code{Elaborate} and
28946 @code{Elaborate_All} pragmas.
28947 Consider the following source program:
28948
28949 @smallexample @c ada
28950 @group
28951 @cartouche
28952 with k;
28953 package j is
28954   m : integer := k.r;
28955 end;
28956 @end cartouche
28957 @end group
28958 @end smallexample
28959
28960 @noindent
28961 where it is clear that there
28962 should be a pragma @code{Elaborate_All}
28963 for unit @code{k}. An implicit pragma will be generated, and it is
28964 likely that the binder will be able to honor it. However, if you want
28965 to port this program to some other Ada compiler than GNAT.
28966 it is safer to include the pragma explicitly in the source. If this
28967 unit is compiled with the
28968 @option{-gnatwl}
28969 switch, then the compiler outputs a warning:
28970
28971 @smallexample
28972 @group
28973 @cartouche
28974 1. with k;
28975 2. package j is
28976 3.   m : integer := k.r;
28977                      |
28978    >>> warning: call to "r" may raise Program_Error
28979    >>> warning: missing pragma Elaborate_All for "k"
28980
28981 4. end;
28982 @end cartouche
28983 @end group
28984 @end smallexample
28985
28986 @noindent
28987 and these warnings can be used as a guide for supplying manually
28988 the missing pragmas. It is usually a bad idea to use this warning
28989 option during development. That's because it will warn you when
28990 you need to put in a pragma, but cannot warn you when it is time
28991 to take it out. So the use of pragma @code{Elaborate_All} may lead to
28992 unnecessary dependencies and even false circularities.
28993
28994 This default mode is more restrictive than the Ada Reference
28995 Manual, and it is possible to construct programs which will compile
28996 using the dynamic model described there, but will run into a
28997 circularity using the safer static model we have described.
28998
28999 Of course any Ada compiler must be able to operate in a mode
29000 consistent with the requirements of the Ada Reference Manual,
29001 and in particular must have the capability of implementing the
29002 standard dynamic model of elaboration with run-time checks.
29003
29004 In GNAT, this standard mode can be achieved either by the use of
29005 the @option{-gnatE} switch on the compiler (@command{gcc} or
29006 @command{gnatmake}) command, or by the use of the configuration pragma:
29007
29008 @smallexample @c ada
29009 pragma Elaboration_Checks (DYNAMIC);
29010 @end smallexample
29011
29012 @noindent
29013 Either approach will cause the unit affected to be compiled using the
29014 standard dynamic run-time elaboration checks described in the Ada
29015 Reference Manual. The static model is generally preferable, since it
29016 is clearly safer to rely on compile and link time checks rather than
29017 run-time checks. However, in the case of legacy code, it may be
29018 difficult to meet the requirements of the static model. This
29019 issue is further discussed in
29020 @ref{What to Do If the Default Elaboration Behavior Fails}.
29021
29022 Note that the static model provides a strict subset of the allowed
29023 behavior and programs of the Ada Reference Manual, so if you do
29024 adhere to the static model and no circularities exist,
29025 then you are assured that your program will
29026 work using the dynamic model, providing that you remove any
29027 pragma Elaborate statements from the source.
29028
29029 @node Treatment of Pragma Elaborate
29030 @section Treatment of Pragma Elaborate
29031 @cindex Pragma Elaborate
29032
29033 @noindent
29034 The use of @code{pragma Elaborate}
29035 should generally be avoided in Ada 95 and Ada 2005 programs,
29036 since there is no guarantee that transitive calls
29037 will be properly handled. Indeed at one point, this pragma was placed
29038 in Annex J (Obsolescent Features), on the grounds that it is never useful.
29039
29040 Now that's a bit restrictive. In practice, the case in which
29041 @code{pragma Elaborate} is useful is when the caller knows that there
29042 are no transitive calls, or that the called unit contains all necessary
29043 transitive @code{pragma Elaborate} statements, and legacy code often
29044 contains such uses.
29045
29046 Strictly speaking the static mode in GNAT should ignore such pragmas,
29047 since there is no assurance at compile time that the necessary safety
29048 conditions are met. In practice, this would cause GNAT to be incompatible
29049 with correctly written Ada 83 code that had all necessary
29050 @code{pragma Elaborate} statements in place. Consequently, we made the
29051 decision that GNAT in its default mode will believe that if it encounters
29052 a @code{pragma Elaborate} then the programmer knows what they are doing,
29053 and it will trust that no elaboration errors can occur.
29054
29055 The result of this decision is two-fold. First to be safe using the
29056 static mode, you should remove all @code{pragma Elaborate} statements.
29057 Second, when fixing circularities in existing code, you can selectively
29058 use @code{pragma Elaborate} statements to convince the static mode of
29059 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
29060 statement.
29061
29062 When using the static mode with @option{-gnatwl}, any use of
29063 @code{pragma Elaborate} will generate a warning about possible
29064 problems.
29065
29066 @node Elaboration Issues for Library Tasks
29067 @section Elaboration Issues for Library Tasks
29068 @cindex Library tasks, elaboration issues
29069 @cindex Elaboration of library tasks
29070
29071 @noindent
29072 In this section we examine special elaboration issues that arise for
29073 programs that declare library level tasks.
29074
29075 Generally the model of execution of an Ada program is that all units are
29076 elaborated, and then execution of the program starts. However, the
29077 declaration of library tasks definitely does not fit this model. The
29078 reason for this is that library tasks start as soon as they are declared
29079 (more precisely, as soon as the statement part of the enclosing package
29080 body is reached), that is to say before elaboration
29081 of the program is complete. This means that if such a task calls a
29082 subprogram, or an entry in another task, the callee may or may not be
29083 elaborated yet, and in the standard
29084 Reference Manual model of dynamic elaboration checks, you can even
29085 get timing dependent Program_Error exceptions, since there can be
29086 a race between the elaboration code and the task code.
29087
29088 The static model of elaboration in GNAT seeks to avoid all such
29089 dynamic behavior, by being conservative, and the conservative
29090 approach in this particular case is to assume that all the code
29091 in a task body is potentially executed at elaboration time if
29092 a task is declared at the library level.
29093
29094 This can definitely result in unexpected circularities. Consider
29095 the following example
29096
29097 @smallexample @c ada
29098 package Decls is
29099   task Lib_Task is
29100      entry Start;
29101   end Lib_Task;
29102
29103   type My_Int is new Integer;
29104
29105   function Ident (M : My_Int) return My_Int;
29106 end Decls;
29107
29108 with Utils;
29109 package body Decls is
29110   task body Lib_Task is
29111   begin
29112      accept Start;
29113      Utils.Put_Val (2);
29114   end Lib_Task;
29115
29116   function Ident (M : My_Int) return My_Int is
29117   begin
29118      return M;
29119   end Ident;
29120 end Decls;
29121
29122 with Decls;
29123 package Utils is
29124   procedure Put_Val (Arg : Decls.My_Int);
29125 end Utils;
29126
29127 with Text_IO;
29128 package body Utils is
29129   procedure Put_Val (Arg : Decls.My_Int) is
29130   begin
29131      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
29132   end Put_Val;
29133 end Utils;
29134
29135 with Decls;
29136 procedure Main is
29137 begin
29138    Decls.Lib_Task.Start;
29139 end;
29140 @end smallexample
29141
29142 @noindent
29143 If the above example is compiled in the default static elaboration
29144 mode, then a circularity occurs. The circularity comes from the call
29145 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
29146 this call occurs in elaboration code, we need an implicit pragma
29147 @code{Elaborate_All} for @code{Utils}. This means that not only must
29148 the spec and body of @code{Utils} be elaborated before the body
29149 of @code{Decls}, but also the spec and body of any unit that is
29150 @code{with'ed} by the body of @code{Utils} must also be elaborated before
29151 the body of @code{Decls}. This is the transitive implication of
29152 pragma @code{Elaborate_All} and it makes sense, because in general
29153 the body of @code{Put_Val} might have a call to something in a
29154 @code{with'ed} unit.
29155
29156 In this case, the body of Utils (actually its spec) @code{with's}
29157 @code{Decls}. Unfortunately this means that the body of @code{Decls}
29158 must be elaborated before itself, in case there is a call from the
29159 body of @code{Utils}.
29160
29161 Here is the exact chain of events we are worrying about:
29162
29163 @enumerate
29164 @item
29165 In the body of @code{Decls} a call is made from within the body of a library
29166 task to a subprogram in the package @code{Utils}. Since this call may
29167 occur at elaboration time (given that the task is activated at elaboration
29168 time), we have to assume the worst, i.e., that the
29169 call does happen at elaboration time.
29170
29171 @item
29172 This means that the body and spec of @code{Util} must be elaborated before
29173 the body of @code{Decls} so that this call does not cause an access before
29174 elaboration.
29175
29176 @item
29177 Within the body of @code{Util}, specifically within the body of
29178 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
29179 by this package.
29180
29181 @item
29182 One such @code{with}'ed package is package @code{Decls}, so there
29183 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
29184 In fact there is such a call in this example, but we would have to
29185 assume that there was such a call even if it were not there, since
29186 we are not supposed to write the body of @code{Decls} knowing what
29187 is in the body of @code{Utils}; certainly in the case of the
29188 static elaboration model, the compiler does not know what is in
29189 other bodies and must assume the worst.
29190
29191 @item
29192 This means that the spec and body of @code{Decls} must also be
29193 elaborated before we elaborate the unit containing the call, but
29194 that unit is @code{Decls}! This means that the body of @code{Decls}
29195 must be elaborated before itself, and that's a circularity.
29196 @end enumerate
29197
29198 @noindent
29199 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
29200 the body of @code{Decls} you will get a true Ada Reference Manual
29201 circularity that makes the program illegal.
29202
29203 In practice, we have found that problems with the static model of
29204 elaboration in existing code often arise from library tasks, so
29205 we must address this particular situation.
29206
29207 Note that if we compile and run the program above, using the dynamic model of
29208 elaboration (that is to say use the @option{-gnatE} switch),
29209 then it compiles, binds,
29210 links, and runs, printing the expected result of 2. Therefore in some sense
29211 the circularity here is only apparent, and we need to capture
29212 the properties of this program that  distinguish it from other library-level
29213 tasks that have real elaboration problems.
29214
29215 We have four possible answers to this question:
29216
29217 @itemize @bullet
29218
29219 @item
29220 Use the dynamic model of elaboration.
29221
29222 If we use the @option{-gnatE} switch, then as noted above, the program works.
29223 Why is this? If we examine the task body, it is apparent that the task cannot
29224 proceed past the
29225 @code{accept} statement until after elaboration has been completed, because
29226 the corresponding entry call comes from the main program, not earlier.
29227 This is why the dynamic model works here. But that's really giving
29228 up on a precise analysis, and we prefer to take this approach only if we cannot
29229 solve the
29230 problem in any other manner. So let us examine two ways to reorganize
29231 the program to avoid the potential elaboration problem.
29232
29233 @item
29234 Split library tasks into separate packages.
29235
29236 Write separate packages, so that library tasks are isolated from
29237 other declarations as much as possible. Let us look at a variation on
29238 the above program.
29239
29240 @smallexample @c ada
29241 package Decls1 is
29242   task Lib_Task is
29243      entry Start;
29244   end Lib_Task;
29245 end Decls1;
29246
29247 with Utils;
29248 package body Decls1 is
29249   task body Lib_Task is
29250   begin
29251      accept Start;
29252      Utils.Put_Val (2);
29253   end Lib_Task;
29254 end Decls1;
29255
29256 package Decls2 is
29257   type My_Int is new Integer;
29258   function Ident (M : My_Int) return My_Int;
29259 end Decls2;
29260
29261 with Utils;
29262 package body Decls2 is
29263   function Ident (M : My_Int) return My_Int is
29264   begin
29265      return M;
29266   end Ident;
29267 end Decls2;
29268
29269 with Decls2;
29270 package Utils is
29271   procedure Put_Val (Arg : Decls2.My_Int);
29272 end Utils;
29273
29274 with Text_IO;
29275 package body Utils is
29276   procedure Put_Val (Arg : Decls2.My_Int) is
29277   begin
29278      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
29279   end Put_Val;
29280 end Utils;
29281
29282 with Decls1;
29283 procedure Main is
29284 begin
29285    Decls1.Lib_Task.Start;
29286 end;
29287 @end smallexample
29288
29289 @noindent
29290 All we have done is to split @code{Decls} into two packages, one
29291 containing the library task, and one containing everything else. Now
29292 there is no cycle, and the program compiles, binds, links and executes
29293 using the default static model of elaboration.
29294
29295 @item
29296 Declare separate task types.
29297
29298 A significant part of the problem arises because of the use of the
29299 single task declaration form. This means that the elaboration of
29300 the task type, and the elaboration of the task itself (i.e.@: the
29301 creation of the task) happen at the same time. A good rule
29302 of style in Ada is to always create explicit task types. By
29303 following the additional step of placing task objects in separate
29304 packages from the task type declaration, many elaboration problems
29305 are avoided. Here is another modified example of the example program:
29306
29307 @smallexample @c ada
29308 package Decls is
29309   task type Lib_Task_Type is
29310      entry Start;
29311   end Lib_Task_Type;
29312
29313   type My_Int is new Integer;
29314
29315   function Ident (M : My_Int) return My_Int;
29316 end Decls;
29317
29318 with Utils;
29319 package body Decls is
29320   task body Lib_Task_Type is
29321   begin
29322      accept Start;
29323      Utils.Put_Val (2);
29324   end Lib_Task_Type;
29325
29326   function Ident (M : My_Int) return My_Int is
29327   begin
29328      return M;
29329   end Ident;
29330 end Decls;
29331
29332 with Decls;
29333 package Utils is
29334   procedure Put_Val (Arg : Decls.My_Int);
29335 end Utils;
29336
29337 with Text_IO;
29338 package body Utils is
29339   procedure Put_Val (Arg : Decls.My_Int) is
29340   begin
29341      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
29342   end Put_Val;
29343 end Utils;
29344
29345 with Decls;
29346 package Declst is
29347    Lib_Task : Decls.Lib_Task_Type;
29348 end Declst;
29349
29350 with Declst;
29351 procedure Main is
29352 begin
29353    Declst.Lib_Task.Start;
29354 end;
29355 @end smallexample
29356
29357 @noindent
29358 What we have done here is to replace the @code{task} declaration in
29359 package @code{Decls} with a @code{task type} declaration. Then we
29360 introduce a separate package @code{Declst} to contain the actual
29361 task object. This separates the elaboration issues for
29362 the @code{task type}
29363 declaration, which causes no trouble, from the elaboration issues
29364 of the task object, which is also unproblematic, since it is now independent
29365 of the elaboration of  @code{Utils}.
29366 This separation of concerns also corresponds to
29367 a generally sound engineering principle of separating declarations
29368 from instances. This version of the program also compiles, binds, links,
29369 and executes, generating the expected output.
29370
29371 @item
29372 Use No_Entry_Calls_In_Elaboration_Code restriction.
29373 @cindex No_Entry_Calls_In_Elaboration_Code
29374
29375 The previous two approaches described how a program can be restructured
29376 to avoid the special problems caused by library task bodies. in practice,
29377 however, such restructuring may be difficult to apply to existing legacy code,
29378 so we must consider solutions that do not require massive rewriting.
29379
29380 Let us consider more carefully why our original sample program works
29381 under the dynamic model of elaboration. The reason is that the code
29382 in the task body blocks immediately on the @code{accept}
29383 statement. Now of course there is nothing to prohibit elaboration
29384 code from making entry calls (for example from another library level task),
29385 so we cannot tell in isolation that
29386 the task will not execute the accept statement  during elaboration.
29387
29388 However, in practice it is very unusual to see elaboration code
29389 make any entry calls, and the pattern of tasks starting
29390 at elaboration time and then immediately blocking on @code{accept} or
29391 @code{select} statements is very common. What this means is that
29392 the compiler is being too pessimistic when it analyzes the
29393 whole package body as though it might be executed at elaboration
29394 time.
29395
29396 If we know that the elaboration code contains no entry calls, (a very safe
29397 assumption most of the time, that could almost be made the default
29398 behavior), then we can compile all units of the program under control
29399 of the following configuration pragma:
29400
29401 @smallexample
29402 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
29403 @end smallexample
29404
29405 @noindent
29406 This pragma can be placed in the @file{gnat.adc} file in the usual
29407 manner. If we take our original unmodified program and compile it
29408 in the presence of a @file{gnat.adc} containing the above pragma,
29409 then once again, we can compile, bind, link, and execute, obtaining
29410 the expected result. In the presence of this pragma, the compiler does
29411 not trace calls in a task body, that appear after the first @code{accept}
29412 or @code{select} statement, and therefore does not report a potential
29413 circularity in the original program.
29414
29415 The compiler will check to the extent it can that the above
29416 restriction is not violated, but it is not always possible to do a
29417 complete check at compile time, so it is important to use this
29418 pragma only if the stated restriction is in fact met, that is to say
29419 no task receives an entry call before elaboration of all units is completed.
29420
29421 @end itemize
29422
29423 @node Mixing Elaboration Models
29424 @section Mixing Elaboration Models
29425 @noindent
29426 So far, we have assumed that the entire program is either compiled
29427 using the dynamic model or static model, ensuring consistency. It
29428 is possible to mix the two models, but rules have to be followed
29429 if this mixing is done to ensure that elaboration checks are not
29430 omitted.
29431
29432 The basic rule is that @emph{a unit compiled with the static model cannot
29433 be @code{with'ed} by a unit compiled with the dynamic model}. The
29434 reason for this is that in the static model, a unit assumes that
29435 its clients guarantee to use (the equivalent of) pragma
29436 @code{Elaborate_All} so that no elaboration checks are required
29437 in inner subprograms, and this assumption is violated if the
29438 client is compiled with dynamic checks.
29439
29440 The precise rule is as follows. A unit that is compiled with dynamic
29441 checks can only @code{with} a unit that meets at least one of the
29442 following criteria:
29443
29444 @itemize @bullet
29445
29446 @item
29447 The @code{with'ed} unit is itself compiled with dynamic elaboration
29448 checks (that is with the @option{-gnatE} switch.
29449
29450 @item
29451 The @code{with'ed} unit is an internal GNAT implementation unit from
29452 the System, Interfaces, Ada, or GNAT hierarchies.
29453
29454 @item
29455 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
29456
29457 @item
29458 The @code{with'ing} unit (that is the client) has an explicit pragma
29459 @code{Elaborate_All} for the @code{with'ed} unit.
29460
29461 @end itemize
29462
29463 @noindent
29464 If this rule is violated, that is if a unit with dynamic elaboration
29465 checks @code{with's} a unit that does not meet one of the above four
29466 criteria, then the binder (@code{gnatbind}) will issue a warning
29467 similar to that in the following example:
29468
29469 @smallexample
29470 warning: "x.ads" has dynamic elaboration checks and with's
29471 warning:   "y.ads" which has static elaboration checks
29472 @end smallexample
29473
29474 @noindent
29475 These warnings indicate that the rule has been violated, and that as a result
29476 elaboration checks may be missed in the resulting executable file.
29477 This warning may be suppressed using the @option{-ws} binder switch
29478 in the usual manner.
29479
29480 One useful application of this mixing rule is in the case of a subsystem
29481 which does not itself @code{with} units from the remainder of the
29482 application. In this case, the entire subsystem can be compiled with
29483 dynamic checks to resolve a circularity in the subsystem, while
29484 allowing the main application that uses this subsystem to be compiled
29485 using the more reliable default static model.
29486
29487 @node What to Do If the Default Elaboration Behavior Fails
29488 @section What to Do If the Default Elaboration Behavior Fails
29489
29490 @noindent
29491 If the binder cannot find an acceptable order, it outputs detailed
29492 diagnostics. For example:
29493 @smallexample
29494 @group
29495 @iftex
29496 @leftskip=0cm
29497 @end iftex
29498 error: elaboration circularity detected
29499 info:   "proc (body)" must be elaborated before "pack (body)"
29500 info:     reason: Elaborate_All probably needed in unit "pack (body)"
29501 info:     recompile "pack (body)" with -gnatwl
29502 info:                             for full details
29503 info:       "proc (body)"
29504 info:         is needed by its spec:
29505 info:       "proc (spec)"
29506 info:         which is withed by:
29507 info:       "pack (body)"
29508 info:  "pack (body)" must be elaborated before "proc (body)"
29509 info:     reason: pragma Elaborate in unit "proc (body)"
29510 @end group
29511
29512 @end smallexample
29513
29514 @noindent
29515 In this case we have a cycle that the binder cannot break. On the one
29516 hand, there is an explicit pragma Elaborate in @code{proc} for
29517 @code{pack}. This means that the body of @code{pack} must be elaborated
29518 before the body of @code{proc}. On the other hand, there is elaboration
29519 code in @code{pack} that calls a subprogram in @code{proc}. This means
29520 that for maximum safety, there should really be a pragma
29521 Elaborate_All in @code{pack} for @code{proc} which would require that
29522 the body of @code{proc} be elaborated before the body of
29523 @code{pack}. Clearly both requirements cannot be satisfied.
29524 Faced with a circularity of this kind, you have three different options.
29525
29526 @table @asis
29527 @item Fix the program
29528 The most desirable option from the point of view of long-term maintenance
29529 is to rearrange the program so that the elaboration problems are avoided.
29530 One useful technique is to place the elaboration code into separate
29531 child packages. Another is to move some of the initialization code to
29532 explicitly called subprograms, where the program controls the order
29533 of initialization explicitly. Although this is the most desirable option,
29534 it may be impractical and involve too much modification, especially in
29535 the case of complex legacy code.
29536
29537 @item Perform dynamic checks
29538 If the compilations are done using the
29539 @option{-gnatE}
29540 (dynamic elaboration check) switch, then GNAT behaves in a quite different
29541 manner. Dynamic checks are generated for all calls that could possibly result
29542 in raising an exception. With this switch, the compiler does not generate
29543 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
29544 exactly as specified in the @cite{Ada Reference Manual}.
29545 The binder will generate
29546 an executable program that may or may not raise @code{Program_Error}, and then
29547 it is the programmer's job to ensure that it does not raise an exception. Note
29548 that it is important to compile all units with the switch, it cannot be used
29549 selectively.
29550
29551 @item Suppress checks
29552 The drawback of dynamic checks is that they generate a
29553 significant overhead at run time, both in space and time. If you
29554 are absolutely sure that your program cannot raise any elaboration
29555 exceptions, and you still want to use the dynamic elaboration model,
29556 then you can use the configuration pragma
29557 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
29558 example this pragma could be placed in the @file{gnat.adc} file.
29559
29560 @item Suppress checks selectively
29561 When you know that certain calls or instantiations in elaboration code cannot
29562 possibly lead to an elaboration error, and the binder nevertheless complains
29563 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
29564 elaboration circularities, it is possible to remove those warnings locally and
29565 obtain a program that will bind. Clearly this can be unsafe, and it is the
29566 responsibility of the programmer to make sure that the resulting program has no
29567 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
29568 used with different granularity to suppress warnings and break elaboration
29569 circularities:
29570
29571 @itemize @bullet
29572 @item
29573 Place the pragma that names the called subprogram in the declarative part
29574 that contains the call.
29575
29576 @item
29577 Place the pragma in the declarative part, without naming an entity. This
29578 disables warnings on all calls in the corresponding  declarative region.
29579
29580 @item
29581 Place the pragma in the package spec that declares the called subprogram,
29582 and name the subprogram. This disables warnings on all elaboration calls to
29583 that subprogram.
29584
29585 @item
29586 Place the pragma in the package spec that declares the called subprogram,
29587 without naming any entity. This disables warnings on all elaboration calls to
29588 all subprograms declared in this spec.
29589
29590 @item Use Pragma Elaborate
29591 As previously described in section @xref{Treatment of Pragma Elaborate},
29592 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
29593 that no elaboration checks are required on calls to the designated unit.
29594 There may be cases in which the caller knows that no transitive calls
29595 can occur, so that a @code{pragma Elaborate} will be sufficient in a
29596 case where @code{pragma Elaborate_All} would cause a circularity.
29597 @end itemize
29598
29599 @noindent
29600 These five cases are listed in order of decreasing safety, and therefore
29601 require increasing programmer care in their application. Consider the
29602 following program:
29603
29604 @smallexample @c adanocomment
29605 package Pack1 is
29606   function F1 return Integer;
29607   X1 : Integer;
29608 end Pack1;
29609
29610 package Pack2 is
29611   function F2 return Integer;
29612   function Pure (x : integer) return integer;
29613   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
29614   --  pragma Suppress (Elaboration_Check);              -- (4)
29615 end Pack2;
29616
29617 with Pack2;
29618 package body Pack1 is
29619   function F1 return Integer is
29620   begin
29621     return 100;
29622   end F1;
29623   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
29624 begin
29625   declare
29626     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
29627     --  pragma Suppress(Elaboration_Check);             -- (2)
29628   begin
29629     X1 := Pack2.F2 + 1;                --  Elab. call (2)
29630   end;
29631 end Pack1;
29632
29633 with Pack1;
29634 package body Pack2 is
29635   function F2 return Integer is
29636   begin
29637      return Pack1.F1;
29638   end F2;
29639   function Pure (x : integer) return integer is
29640   begin
29641      return x ** 3 - 3 * x;
29642   end;
29643 end Pack2;
29644
29645 with Pack1, Ada.Text_IO;
29646 procedure Proc3 is
29647 begin
29648   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
29649 end Proc3;
29650 @end smallexample
29651 In the absence of any pragmas, an attempt to bind this program produces
29652 the following diagnostics:
29653 @smallexample
29654 @group
29655 @iftex
29656 @leftskip=.5cm
29657 @end iftex
29658 error: elaboration circularity detected
29659 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
29660 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
29661 info:       recompile "pack1 (body)" with -gnatwl for full details
29662 info:          "pack1 (body)"
29663 info:             must be elaborated along with its spec:
29664 info:          "pack1 (spec)"
29665 info:             which is withed by:
29666 info:          "pack2 (body)"
29667 info:             which must be elaborated along with its spec:
29668 info:          "pack2 (spec)"
29669 info:             which is withed by:
29670 info:          "pack1 (body)"
29671 @end group
29672 @end smallexample
29673 The sources of the circularity are the two calls to @code{Pack2.Pure} and
29674 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
29675 F2 is safe, even though F2 calls F1, because the call appears after the
29676 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
29677 remove the warning on the call. It is also possible to use pragma (2)
29678 because there are no other potentially unsafe calls in the block.
29679
29680 @noindent
29681 The call to @code{Pure} is safe because this function does not depend on the
29682 state of @code{Pack2}. Therefore any call to this function is safe, and it
29683 is correct to place pragma (3) in the corresponding package spec.
29684
29685 @noindent
29686 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
29687 warnings on all calls to functions declared therein. Note that this is not
29688 necessarily safe, and requires more detailed examination of the subprogram
29689 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
29690 be already elaborated.
29691 @end table
29692
29693 @noindent
29694 It is hard to generalize on which of these four approaches should be
29695 taken. Obviously if it is possible to fix the program so that the default
29696 treatment works, this is preferable, but this may not always be practical.
29697 It is certainly simple enough to use
29698 @option{-gnatE}
29699 but the danger in this case is that, even if the GNAT binder
29700 finds a correct elaboration order, it may not always do so,
29701 and certainly a binder from another Ada compiler might not. A
29702 combination of testing and analysis (for which the warnings generated
29703 with the
29704 @option{-gnatwl}
29705 switch can be useful) must be used to ensure that the program is free
29706 of errors. One switch that is useful in this testing is the
29707 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
29708 switch for
29709 @code{gnatbind}.
29710 Normally the binder tries to find an order that has the best chance
29711 of avoiding elaboration problems. However, if this switch is used, the binder
29712 plays a devil's advocate role, and tries to choose the order that
29713 has the best chance of failing. If your program works even with this
29714 switch, then it has a better chance of being error free, but this is still
29715 not a guarantee.
29716
29717 For an example of this approach in action, consider the C-tests (executable
29718 tests) from the ACVC suite. If these are compiled and run with the default
29719 treatment, then all but one of them succeed without generating any error
29720 diagnostics from the binder. However, there is one test that fails, and
29721 this is not surprising, because the whole point of this test is to ensure
29722 that the compiler can handle cases where it is impossible to determine
29723 a correct order statically, and it checks that an exception is indeed
29724 raised at run time.
29725
29726 This one test must be compiled and run using the
29727 @option{-gnatE}
29728 switch, and then it passes. Alternatively, the entire suite can
29729 be run using this switch. It is never wrong to run with the dynamic
29730 elaboration switch if your code is correct, and we assume that the
29731 C-tests are indeed correct (it is less efficient, but efficiency is
29732 not a factor in running the ACVC tests.)
29733
29734 @node Elaboration for Access-to-Subprogram Values
29735 @section Elaboration for Access-to-Subprogram Values
29736 @cindex Access-to-subprogram
29737
29738 @noindent
29739 Access-to-subprogram types (introduced in Ada 95) complicate
29740 the handling of elaboration. The trouble is that it becomes
29741 impossible to tell at compile time which procedure
29742 is being called. This means that it is not possible for the binder
29743 to analyze the elaboration requirements in this case.
29744
29745 If at the point at which the access value is created
29746 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
29747 the body of the subprogram is
29748 known to have been elaborated, then the access value is safe, and its use
29749 does not require a check. This may be achieved by appropriate arrangement
29750 of the order of declarations if the subprogram is in the current unit,
29751 or, if the subprogram is in another unit, by using pragma
29752 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
29753 on the referenced unit.
29754
29755 If the referenced body is not known to have been elaborated at the point
29756 the access value is created, then any use of the access value must do a
29757 dynamic check, and this dynamic check will fail and raise a
29758 @code{Program_Error} exception if the body has not been elaborated yet.
29759 GNAT will generate the necessary checks, and in addition, if the
29760 @option{-gnatwl}
29761 switch is set, will generate warnings that such checks are required.
29762
29763 The use of dynamic dispatching for tagged types similarly generates
29764 a requirement for dynamic checks, and premature calls to any primitive
29765 operation of a tagged type before the body of the operation has been
29766 elaborated, will result in the raising of @code{Program_Error}.
29767
29768 @node Summary of Procedures for Elaboration Control
29769 @section Summary of Procedures for Elaboration Control
29770 @cindex Elaboration control
29771
29772 @noindent
29773 First, compile your program with the default options, using none of
29774 the special elaboration control switches. If the binder successfully
29775 binds your program, then you can be confident that, apart from issues
29776 raised by the use of access-to-subprogram types and dynamic dispatching,
29777 the program is free of elaboration errors. If it is important that the
29778 program be portable, then use the
29779 @option{-gnatwl}
29780 switch to generate warnings about missing @code{Elaborate} or
29781 @code{Elaborate_All} pragmas, and supply the missing pragmas.
29782
29783 If the program fails to bind using the default static elaboration
29784 handling, then you can fix the program to eliminate the binder
29785 message, or recompile the entire program with the
29786 @option{-gnatE} switch to generate dynamic elaboration checks,
29787 and, if you are sure there really are no elaboration problems,
29788 use a global pragma @code{Suppress (Elaboration_Check)}.
29789
29790 @node Other Elaboration Order Considerations
29791 @section Other Elaboration Order Considerations
29792 @noindent
29793 This section has been entirely concerned with the issue of finding a valid
29794 elaboration order, as defined by the Ada Reference Manual. In a case
29795 where several elaboration orders are valid, the task is to find one
29796 of the possible valid elaboration orders (and the static model in GNAT
29797 will ensure that this is achieved).
29798
29799 The purpose of the elaboration rules in the Ada Reference Manual is to
29800 make sure that no entity is accessed before it has been elaborated. For
29801 a subprogram, this means that the spec and body must have been elaborated
29802 before the subprogram is called. For an object, this means that the object
29803 must have been elaborated before its value is read or written. A violation
29804 of either of these two requirements is an access before elaboration order,
29805 and this section has been all about avoiding such errors.
29806
29807 In the case where more than one order of elaboration is possible, in the
29808 sense that access before elaboration errors are avoided, then any one of
29809 the orders is ``correct'' in the sense that it meets the requirements of
29810 the Ada Reference Manual, and no such error occurs.
29811
29812 However, it may be the case for a given program, that there are
29813 constraints on the order of elaboration that come not from consideration
29814 of avoiding elaboration errors, but rather from extra-lingual logic
29815 requirements. Consider this example:
29816
29817 @smallexample @c ada
29818 with Init_Constants;
29819 package Constants is
29820    X : Integer := 0;
29821    Y : Integer := 0;
29822 end Constants;
29823
29824 package Init_Constants is
29825    procedure P; -- require a body
29826 end Init_Constants;
29827
29828 with Constants;
29829 package body Init_Constants is
29830    procedure P is begin null; end;
29831 begin
29832    Constants.X := 3;
29833    Constants.Y := 4;
29834 end Init_Constants;
29835
29836 with Constants;
29837 package Calc is
29838    Z : Integer := Constants.X + Constants.Y;
29839 end Calc;
29840
29841 with Calc;
29842 with Text_IO; use Text_IO;
29843 procedure Main is
29844 begin
29845    Put_Line (Calc.Z'Img);
29846 end Main;
29847 @end smallexample
29848
29849 @noindent
29850 In this example, there is more than one valid order of elaboration. For
29851 example both the following are correct orders:
29852
29853 @smallexample
29854 Init_Constants spec
29855 Constants spec
29856 Calc spec
29857 Init_Constants body
29858 Main body
29859
29860   and
29861
29862 Init_Constants spec
29863 Init_Constants body
29864 Constants spec
29865 Calc spec
29866 Main body
29867 @end smallexample
29868
29869 @noindent
29870 There is no language rule to prefer one or the other, both are correct
29871 from an order of elaboration point of view. But the programmatic effects
29872 of the two orders are very different. In the first, the elaboration routine
29873 of @code{Calc} initializes @code{Z} to zero, and then the main program
29874 runs with this value of zero. But in the second order, the elaboration
29875 routine of @code{Calc} runs after the body of Init_Constants has set
29876 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
29877 runs.
29878
29879 One could perhaps by applying pretty clever non-artificial intelligence
29880 to the situation guess that it is more likely that the second order of
29881 elaboration is the one desired, but there is no formal linguistic reason
29882 to prefer one over the other. In fact in this particular case, GNAT will
29883 prefer the second order, because of the rule that bodies are elaborated
29884 as soon as possible, but it's just luck that this is what was wanted
29885 (if indeed the second order was preferred).
29886
29887 If the program cares about the order of elaboration routines in a case like
29888 this, it is important to specify the order required. In this particular
29889 case, that could have been achieved by adding to the spec of Calc:
29890
29891 @smallexample @c ada
29892 pragma Elaborate_All (Constants);
29893 @end smallexample
29894
29895 @noindent
29896 which requires that the body (if any) and spec of @code{Constants},
29897 as well as the body and spec of any unit @code{with}'ed by
29898 @code{Constants} be elaborated before @code{Calc} is elaborated.
29899
29900 Clearly no automatic method can always guess which alternative you require,
29901 and if you are working with legacy code that had constraints of this kind
29902 which were not properly specified by adding @code{Elaborate} or
29903 @code{Elaborate_All} pragmas, then indeed it is possible that two different
29904 compilers can choose different orders.
29905
29906 However, GNAT does attempt to diagnose the common situation where there
29907 are uninitialized variables in the visible part of a package spec, and the
29908 corresponding package body has an elaboration block that directly or
29909 indirectly initialized one or more of these variables. This is the situation
29910 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
29911 a warning that suggests this addition if it detects this situation.
29912
29913 The @code{gnatbind}
29914 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
29915 out problems. This switch causes bodies to be elaborated as late as possible
29916 instead of as early as possible. In the example above, it would have forced
29917 the choice of the first elaboration order. If you get different results
29918 when using this switch, and particularly if one set of results is right,
29919 and one is wrong as far as you are concerned, it shows that you have some
29920 missing @code{Elaborate} pragmas. For the example above, we have the
29921 following output:
29922
29923 @smallexample
29924 gnatmake -f -q main
29925 main
29926  7
29927 gnatmake -f -q main -bargs -p
29928 main
29929  0
29930 @end smallexample
29931
29932 @noindent
29933 It is of course quite unlikely that both these results are correct, so
29934 it is up to you in a case like this to investigate the source of the
29935 difference, by looking at the two elaboration orders that are chosen,
29936 and figuring out which is correct, and then adding the necessary
29937 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
29938
29939
29940
29941 @c *******************************
29942 @node Conditional Compilation
29943 @appendix Conditional Compilation
29944 @c *******************************
29945 @cindex Conditional compilation
29946
29947 @noindent
29948 It is often necessary to arrange for a single source program
29949 to serve multiple purposes, where it is compiled in different
29950 ways to achieve these different goals. Some examples of the
29951 need for this feature are
29952
29953 @itemize @bullet
29954 @item  Adapting a program to a different hardware environment
29955 @item  Adapting a program to a different target architecture
29956 @item  Turning debugging features on and off
29957 @item  Arranging for a program to compile with different compilers
29958 @end itemize
29959
29960 @noindent
29961 In C, or C++, the typical approach would be to use the preprocessor
29962 that is defined as part of the language. The Ada language does not
29963 contain such a feature. This is not an oversight, but rather a very
29964 deliberate design decision, based on the experience that overuse of
29965 the preprocessing features in C and C++ can result in programs that
29966 are extremely difficult to maintain. For example, if we have ten
29967 switches that can be on or off, this means that there are a thousand
29968 separate programs, any one of which might not even be syntactically
29969 correct, and even if syntactically correct, the resulting program
29970 might not work correctly. Testing all combinations can quickly become
29971 impossible.
29972
29973 Nevertheless, the need to tailor programs certainly exists, and in
29974 this Appendix we will discuss how this can
29975 be achieved using Ada in general, and GNAT in particular.
29976
29977 @menu
29978 * Use of Boolean Constants::
29979 * Debugging - A Special Case::
29980 * Conditionalizing Declarations::
29981 * Use of Alternative Implementations::
29982 * Preprocessing::
29983 @end menu
29984
29985 @node Use of Boolean Constants
29986 @section Use of Boolean Constants
29987
29988 @noindent
29989 In the case where the difference is simply which code
29990 sequence is executed, the cleanest solution is to use Boolean
29991 constants to control which code is executed.
29992
29993 @smallexample @c ada
29994 @group
29995 FP_Initialize_Required : constant Boolean := True;
29996 @dots{}
29997 if FP_Initialize_Required then
29998 @dots{}
29999 end if;
30000 @end group
30001 @end smallexample
30002
30003 @noindent
30004 Not only will the code inside the @code{if} statement not be executed if
30005 the constant Boolean is @code{False}, but it will also be completely
30006 deleted from the program.
30007 However, the code is only deleted after the @code{if} statement
30008 has been checked for syntactic and semantic correctness.
30009 (In contrast, with preprocessors the code is deleted before the
30010 compiler ever gets to see it, so it is not checked until the switch
30011 is turned on.)
30012 @cindex Preprocessors (contrasted with conditional compilation)
30013
30014 Typically the Boolean constants will be in a separate package,
30015 something like:
30016
30017 @smallexample @c ada
30018 @group
30019 package Config is
30020    FP_Initialize_Required : constant Boolean := True;
30021    Reset_Available        : constant Boolean := False;
30022    @dots{}
30023 end Config;
30024 @end group
30025 @end smallexample
30026
30027 @noindent
30028 The @code{Config} package exists in multiple forms for the various targets,
30029 with an appropriate script selecting the version of @code{Config} needed.
30030 Then any other unit requiring conditional compilation can do a @code{with}
30031 of @code{Config} to make the constants visible.
30032
30033
30034 @node Debugging - A Special Case
30035 @section Debugging - A Special Case
30036
30037 @noindent
30038 A common use of conditional code is to execute statements (for example
30039 dynamic checks, or output of intermediate results) under control of a
30040 debug switch, so that the debugging behavior can be turned on and off.
30041 This can be done using a Boolean constant to control whether the code
30042 is active:
30043
30044 @smallexample @c ada
30045 @group
30046 if Debugging then
30047    Put_Line ("got to the first stage!");
30048 end if;
30049 @end group
30050 @end smallexample
30051
30052 @noindent
30053 or
30054
30055 @smallexample @c ada
30056 @group
30057 if Debugging and then Temperature > 999.0 then
30058    raise Temperature_Crazy;
30059 end if;
30060 @end group
30061 @end smallexample
30062
30063 @noindent
30064 Since this is a common case, there are special features to deal with
30065 this in a convenient manner. For the case of tests, Ada 2005 has added
30066 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
30067 @cindex pragma @code{Assert}
30068 on the @code{Assert} pragma that has always been available in GNAT, so this
30069 feature may be used with GNAT even if you are not using Ada 2005 features.
30070 The use of pragma @code{Assert} is described in
30071 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
30072 example, the last test could be written:
30073
30074 @smallexample @c ada
30075 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
30076 @end smallexample
30077
30078 @noindent
30079 or simply
30080
30081 @smallexample @c ada
30082 pragma Assert (Temperature <= 999.0);
30083 @end smallexample
30084
30085 @noindent
30086 In both cases, if assertions are active and the temperature is excessive,
30087 the exception @code{Assert_Failure} will be raised, with the given string in
30088 the first case or a string indicating the location of the pragma in the second
30089 case used as the exception message.
30090
30091 You can turn assertions on and off by using the @code{Assertion_Policy}
30092 pragma.
30093 @cindex pragma @code{Assertion_Policy}
30094 This is an Ada 2005 pragma which is implemented in all modes by
30095 GNAT, but only in the latest versions of GNAT which include Ada 2005
30096 capability. Alternatively, you can use the @option{-gnata} switch
30097 @cindex @option{-gnata} switch
30098 to enable assertions from the command line (this is recognized by all versions
30099 of GNAT).
30100
30101 For the example above with the @code{Put_Line}, the GNAT-specific pragma
30102 @code{Debug} can be used:
30103 @cindex pragma @code{Debug}
30104
30105 @smallexample @c ada
30106 pragma Debug (Put_Line ("got to the first stage!"));
30107 @end smallexample
30108
30109 @noindent
30110 If debug pragmas are enabled, the argument, which must be of the form of
30111 a procedure call, is executed (in this case, @code{Put_Line} will be called).
30112 Only one call can be present, but of course a special debugging procedure
30113 containing any code you like can be included in the program and then
30114 called in a pragma @code{Debug} argument as needed.
30115
30116 One advantage of pragma @code{Debug} over the @code{if Debugging then}
30117 construct is that pragma @code{Debug} can appear in declarative contexts,
30118 such as at the very beginning of a procedure, before local declarations have
30119 been elaborated.
30120
30121 Debug pragmas are enabled using either the @option{-gnata} switch that also
30122 controls assertions, or with a separate Debug_Policy pragma.
30123 @cindex pragma @code{Debug_Policy}
30124 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
30125 in Ada 95 and Ada 83 programs as well), and is analogous to
30126 pragma @code{Assertion_Policy} to control assertions.
30127
30128 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
30129 and thus they can appear in @file{gnat.adc} if you are not using a
30130 project file, or in the file designated to contain configuration pragmas
30131 in a project file.
30132 They then apply to all subsequent compilations. In practice the use of
30133 the @option{-gnata} switch is often the most convenient method of controlling
30134 the status of these pragmas.
30135
30136 Note that a pragma is not a statement, so in contexts where a statement
30137 sequence is required, you can't just write a pragma on its own. You have
30138 to add a @code{null} statement.
30139
30140 @smallexample @c ada
30141 @group
30142 if @dots{} then
30143    @dots{} -- some statements
30144 else
30145    pragma Assert (Num_Cases < 10);
30146    null;
30147 end if;
30148 @end group
30149 @end smallexample
30150
30151
30152 @node Conditionalizing Declarations
30153 @section Conditionalizing Declarations
30154
30155 @noindent
30156 In some cases, it may be necessary to conditionalize declarations to meet
30157 different requirements. For example we might want a bit string whose length
30158 is set to meet some hardware message requirement.
30159
30160 In some cases, it may be possible to do this using declare blocks controlled
30161 by conditional constants:
30162
30163 @smallexample @c ada
30164 @group
30165 if Small_Machine then
30166    declare
30167       X : Bit_String (1 .. 10);
30168    begin
30169       @dots{}
30170    end;
30171 else
30172    declare
30173       X : Large_Bit_String (1 .. 1000);
30174    begin
30175       @dots{}
30176    end;
30177 end if;
30178 @end group
30179 @end smallexample
30180
30181 @noindent
30182 Note that in this approach, both declarations are analyzed by the
30183 compiler so this can only be used where both declarations are legal,
30184 even though one of them will not be used.
30185
30186 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
30187 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
30188 that are parameterized by these constants. For example
30189
30190 @smallexample @c ada
30191 @group
30192 for Rec use
30193   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
30194 end record;
30195 @end group
30196 @end smallexample
30197
30198 @noindent
30199 If @code{Bits_Per_Word} is set to 32, this generates either
30200
30201 @smallexample @c ada
30202 @group
30203 for Rec use
30204   Field1 at 0 range 0 .. 32;
30205 end record;
30206 @end group
30207 @end smallexample
30208
30209 @noindent
30210 for the big endian case, or
30211
30212 @smallexample @c ada
30213 @group
30214 for Rec use record
30215   Field1 at 0 range 10 .. 32;
30216 end record;
30217 @end group
30218 @end smallexample
30219
30220 @noindent
30221 for the little endian case. Since a powerful subset of Ada expression
30222 notation is usable for creating static constants, clever use of this
30223 feature can often solve quite difficult problems in conditionalizing
30224 compilation (note incidentally that in Ada 95, the little endian
30225 constant was introduced as @code{System.Default_Bit_Order}, so you do not
30226 need to define this one yourself).
30227
30228
30229 @node Use of Alternative Implementations
30230 @section Use of Alternative Implementations
30231
30232 @noindent
30233 In some cases, none of the approaches described above are adequate. This
30234 can occur for example if the set of declarations required is radically
30235 different for two different configurations.
30236
30237 In this situation, the official Ada way of dealing with conditionalizing
30238 such code is to write separate units for the different cases. As long as
30239 this does not result in excessive duplication of code, this can be done
30240 without creating maintenance problems. The approach is to share common
30241 code as far as possible, and then isolate the code and declarations
30242 that are different. Subunits are often a convenient method for breaking
30243 out a piece of a unit that is to be conditionalized, with separate files
30244 for different versions of the subunit for different targets, where the
30245 build script selects the right one to give to the compiler.
30246 @cindex Subunits (and conditional compilation)
30247
30248 As an example, consider a situation where a new feature in Ada 2005
30249 allows something to be done in a really nice way. But your code must be able
30250 to compile with an Ada 95 compiler. Conceptually you want to say:
30251
30252 @smallexample @c ada
30253 @group
30254 if Ada_2005 then
30255    @dots{} neat Ada 2005 code
30256 else
30257    @dots{} not quite as neat Ada 95 code
30258 end if;
30259 @end group
30260 @end smallexample
30261
30262 @noindent
30263 where @code{Ada_2005} is a Boolean constant.
30264
30265 But this won't work when @code{Ada_2005} is set to @code{False},
30266 since the @code{then} clause will be illegal for an Ada 95 compiler.
30267 (Recall that although such unreachable code would eventually be deleted
30268 by the compiler, it still needs to be legal.  If it uses features
30269 introduced in Ada 2005, it will be illegal in Ada 95.)
30270
30271 So instead we write
30272
30273 @smallexample @c ada
30274 procedure Insert is separate;
30275 @end smallexample
30276
30277 @noindent
30278 Then we have two files for the subunit @code{Insert}, with the two sets of
30279 code.
30280 If the package containing this is called @code{File_Queries}, then we might
30281 have two files
30282
30283 @itemize @bullet
30284 @item    @file{file_queries-insert-2005.adb}
30285 @item    @file{file_queries-insert-95.adb}
30286 @end itemize
30287
30288 @noindent
30289 and the build script renames the appropriate file to
30290
30291 @smallexample
30292 file_queries-insert.adb
30293 @end smallexample
30294
30295 @noindent
30296 and then carries out the compilation.
30297
30298 This can also be done with project files' naming schemes. For example:
30299
30300 @smallexample @c project
30301 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
30302 @end smallexample
30303
30304 @noindent
30305 Note also that with project files it is desirable to use a different extension
30306 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
30307 conflict may arise through another commonly used feature: to declare as part
30308 of the project a set of directories containing all the sources obeying the
30309 default naming scheme.
30310
30311 The use of alternative units is certainly feasible in all situations,
30312 and for example the Ada part of the GNAT run-time is conditionalized
30313 based on the target architecture using this approach. As a specific example,
30314 consider the implementation of the AST feature in VMS. There is one
30315 spec:
30316
30317 @smallexample
30318 s-asthan.ads
30319 @end smallexample
30320
30321 @noindent
30322 which is the same for all architectures, and three bodies:
30323
30324 @table @file
30325 @item    s-asthan.adb
30326 used for all non-VMS operating systems
30327 @item    s-asthan-vms-alpha.adb
30328 used for VMS on the Alpha
30329 @item    s-asthan-vms-ia64.adb
30330 used for VMS on the ia64
30331 @end table
30332
30333 @noindent
30334 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
30335 this operating system feature is not available, and the two remaining
30336 versions interface with the corresponding versions of VMS to provide
30337 VMS-compatible AST handling. The GNAT build script knows the architecture
30338 and operating system, and automatically selects the right version,
30339 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
30340
30341 Another style for arranging alternative implementations is through Ada's
30342 access-to-subprogram facility.
30343 In case some functionality is to be conditionally included,
30344 you can declare an access-to-procedure variable @code{Ref} that is initialized
30345 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
30346 when appropriate.
30347 In some library package, set @code{Ref} to @code{Proc'Access} for some
30348 procedure @code{Proc} that performs the relevant processing.
30349 The initialization only occurs if the library package is included in the
30350 program.
30351 The same idea can also be implemented using tagged types and dispatching
30352 calls.
30353
30354
30355 @node Preprocessing
30356 @section Preprocessing
30357 @cindex Preprocessing
30358
30359 @noindent
30360 Although it is quite possible to conditionalize code without the use of
30361 C-style preprocessing, as described earlier in this section, it is
30362 nevertheless convenient in some cases to use the C approach. Moreover,
30363 older Ada compilers have often provided some preprocessing capability,
30364 so legacy code may depend on this approach, even though it is not
30365 standard.
30366
30367 To accommodate such use, GNAT provides a preprocessor (modeled to a large
30368 extent on the various preprocessors that have been used
30369 with legacy code on other compilers, to enable easier transition).
30370
30371 The preprocessor may be used in two separate modes. It can be used quite
30372 separately from the compiler, to generate a separate output source file
30373 that is then fed to the compiler as a separate step. This is the
30374 @code{gnatprep} utility, whose use is fully described in
30375 @ref{Preprocessing Using gnatprep}.
30376 @cindex @code{gnatprep}
30377
30378 The preprocessing language allows such constructs as
30379
30380 @smallexample
30381 @group
30382 #if DEBUG or PRIORITY > 4 then
30383    bunch of declarations
30384 #else
30385    completely different bunch of declarations
30386 #end if;
30387 @end group
30388 @end smallexample
30389
30390 @noindent
30391 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
30392 defined either on the command line or in a separate file.
30393
30394 The other way of running the preprocessor is even closer to the C style and
30395 often more convenient. In this approach the preprocessing is integrated into
30396 the compilation process. The compiler is fed the preprocessor input which
30397 includes @code{#if} lines etc, and then the compiler carries out the
30398 preprocessing internally and processes the resulting output.
30399 For more details on this approach, see @ref{Integrated Preprocessing}.
30400
30401
30402 @c *******************************
30403 @node Inline Assembler
30404 @appendix Inline Assembler
30405 @c *******************************
30406
30407 @noindent
30408 If you need to write low-level software that interacts directly
30409 with the hardware, Ada provides two ways to incorporate assembly
30410 language code into your program.  First, you can import and invoke
30411 external routines written in assembly language, an Ada feature fully
30412 supported by GNAT@.  However, for small sections of code it may be simpler
30413 or more efficient to include assembly language statements directly
30414 in your Ada source program, using the facilities of the implementation-defined
30415 package @code{System.Machine_Code}, which incorporates the gcc
30416 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
30417 including the following:
30418
30419 @itemize @bullet
30420 @item No need to use non-Ada tools
30421 @item Consistent interface over different targets
30422 @item Automatic usage of the proper calling conventions
30423 @item Access to Ada constants and variables
30424 @item Definition of intrinsic routines
30425 @item Possibility of inlining a subprogram comprising assembler code
30426 @item Code optimizer can take Inline Assembler code into account
30427 @end itemize
30428
30429 This chapter presents a series of examples to show you how to use
30430 the Inline Assembler.  Although it focuses on the Intel x86,
30431 the general approach applies also to other processors.
30432 It is assumed that you are familiar with Ada
30433 and with assembly language programming.
30434
30435 @menu
30436 * Basic Assembler Syntax::
30437 * A Simple Example of Inline Assembler::
30438 * Output Variables in Inline Assembler::
30439 * Input Variables in Inline Assembler::
30440 * Inlining Inline Assembler Code::
30441 * Other Asm Functionality::
30442 @end menu
30443
30444 @c ---------------------------------------------------------------------------
30445 @node Basic Assembler Syntax
30446 @section Basic Assembler Syntax
30447
30448 @noindent
30449 The assembler used by GNAT and gcc is based not on the Intel assembly
30450 language, but rather on a language that descends from the AT&T Unix
30451 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
30452 The following table summarizes the main features of @emph{as} syntax
30453 and points out the differences from the Intel conventions.
30454 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
30455 pre-processor) documentation for further information.
30456
30457 @table @asis
30458 @item Register names
30459 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
30460 @*
30461 Intel: No extra punctuation; for example @code{eax}
30462
30463 @item Immediate operand
30464 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
30465 @*
30466 Intel: No extra punctuation; for example @code{4}
30467
30468 @item Address
30469 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
30470 @*
30471 Intel: No extra punctuation; for example @code{loc}
30472
30473 @item Memory contents
30474 gcc / @emph{as}: No extra punctuation; for example @code{loc}
30475 @*
30476 Intel: Square brackets; for example @code{[loc]}
30477
30478 @item Register contents
30479 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
30480 @*
30481 Intel: Square brackets; for example @code{[eax]}
30482
30483 @item Hexadecimal numbers
30484 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
30485 @*
30486 Intel: Trailing ``h''; for example @code{A0h}
30487
30488 @item Operand size
30489 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
30490 a 16-bit word
30491 @*
30492 Intel: Implicit, deduced by assembler; for example @code{mov}
30493
30494 @item Instruction repetition
30495 gcc / @emph{as}: Split into two lines; for example
30496 @*
30497 @code{rep}
30498 @*
30499 @code{stosl}
30500 @*
30501 Intel: Keep on one line; for example @code{rep stosl}
30502
30503 @item Order of operands
30504 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
30505 @*
30506 Intel: Destination first; for example @code{mov eax, 4}
30507 @end table
30508
30509 @c ---------------------------------------------------------------------------
30510 @node A Simple Example of Inline Assembler
30511 @section A Simple Example of Inline Assembler
30512
30513 @noindent
30514 The following example will generate a single assembly language statement,
30515 @code{nop}, which does nothing.  Despite its lack of run-time effect,
30516 the example will be useful in illustrating the basics of
30517 the Inline Assembler facility.
30518
30519 @smallexample @c ada
30520 @group
30521 with System.Machine_Code; use System.Machine_Code;
30522 procedure Nothing is
30523 begin
30524    Asm ("nop");
30525 end Nothing;
30526 @end group
30527 @end smallexample
30528
30529 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
30530 here it takes one parameter, a @emph{template string} that must be a static
30531 expression and that will form the generated instruction.
30532 @code{Asm} may be regarded as a compile-time procedure that parses
30533 the template string and additional parameters (none here),
30534 from which it generates a sequence of assembly language instructions.
30535
30536 The examples in this chapter will illustrate several of the forms
30537 for invoking @code{Asm}; a complete specification of the syntax
30538 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
30539 Manual}.
30540
30541 Under the standard GNAT conventions, the @code{Nothing} procedure
30542 should be in a file named @file{nothing.adb}.
30543 You can build the executable in the usual way:
30544 @smallexample
30545 gnatmake nothing
30546 @end smallexample
30547 However, the interesting aspect of this example is not its run-time behavior
30548 but rather the generated assembly code.
30549 To see this output, invoke the compiler as follows:
30550 @smallexample
30551    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
30552 @end smallexample
30553 where the options are:
30554
30555 @table @code
30556 @item -c
30557 compile only (no bind or link)
30558 @item -S
30559 generate assembler listing
30560 @item -fomit-frame-pointer
30561 do not set up separate stack frames
30562 @item -gnatp
30563 do not add runtime checks
30564 @end table
30565
30566 This gives a human-readable assembler version of the code. The resulting
30567 file will have the same name as the Ada source file, but with a @code{.s}
30568 extension. In our example, the file @file{nothing.s} has the following
30569 contents:
30570
30571 @smallexample
30572 @group
30573 .file "nothing.adb"
30574 gcc2_compiled.:
30575 ___gnu_compiled_ada:
30576 .text
30577    .align 4
30578 .globl __ada_nothing
30579 __ada_nothing:
30580 #APP
30581    nop
30582 #NO_APP
30583    jmp L1
30584    .align 2,0x90
30585 L1:
30586    ret
30587 @end group
30588 @end smallexample
30589
30590 The assembly code you included is clearly indicated by
30591 the compiler, between the @code{#APP} and @code{#NO_APP}
30592 delimiters. The character before the 'APP' and 'NOAPP'
30593 can differ on different targets. For example, GNU/Linux uses '#APP' while
30594 on NT you will see '/APP'.
30595
30596 If you make a mistake in your assembler code (such as using the
30597 wrong size modifier, or using a wrong operand for the instruction) GNAT
30598 will report this error in a temporary file, which will be deleted when
30599 the compilation is finished.  Generating an assembler file will help
30600 in such cases, since you can assemble this file separately using the
30601 @emph{as} assembler that comes with gcc.
30602
30603 Assembling the file using the command
30604
30605 @smallexample
30606 as @file{nothing.s}
30607 @end smallexample
30608 @noindent
30609 will give you error messages whose lines correspond to the assembler
30610 input file, so you can easily find and correct any mistakes you made.
30611 If there are no errors, @emph{as} will generate an object file
30612 @file{nothing.out}.
30613
30614 @c ---------------------------------------------------------------------------
30615 @node Output Variables in Inline Assembler
30616 @section Output Variables in Inline Assembler
30617
30618 @noindent
30619 The examples in this section, showing how to access the processor flags,
30620 illustrate how to specify the destination operands for assembly language
30621 statements.
30622
30623 @smallexample @c ada
30624 @group
30625 with Interfaces; use Interfaces;
30626 with Ada.Text_IO; use Ada.Text_IO;
30627 with System.Machine_Code; use System.Machine_Code;
30628 procedure Get_Flags is
30629    Flags : Unsigned_32;
30630    use ASCII;
30631 begin
30632    Asm ("pushfl"          & LF & HT & -- push flags on stack
30633         "popl %%eax"      & LF & HT & -- load eax with flags
30634         "movl %%eax, %0",             -- store flags in variable
30635         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30636    Put_Line ("Flags register:" & Flags'Img);
30637 end Get_Flags;
30638 @end group
30639 @end smallexample
30640
30641 In order to have a nicely aligned assembly listing, we have separated
30642 multiple assembler statements in the Asm template string with linefeed
30643 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
30644 The resulting section of the assembly output file is:
30645
30646 @smallexample
30647 @group
30648 #APP
30649    pushfl
30650    popl %eax
30651    movl %eax, -40(%ebp)
30652 #NO_APP
30653 @end group
30654 @end smallexample
30655
30656 It would have been legal to write the Asm invocation as:
30657
30658 @smallexample
30659 Asm ("pushfl popl %%eax movl %%eax, %0")
30660 @end smallexample
30661
30662 but in the generated assembler file, this would come out as:
30663
30664 @smallexample
30665 #APP
30666    pushfl popl %eax movl %eax, -40(%ebp)
30667 #NO_APP
30668 @end smallexample
30669
30670 which is not so convenient for the human reader.
30671
30672 We use Ada comments
30673 at the end of each line to explain what the assembler instructions
30674 actually do.  This is a useful convention.
30675
30676 When writing Inline Assembler instructions, you need to precede each register
30677 and variable name with a percent sign.  Since the assembler already requires
30678 a percent sign at the beginning of a register name, you need two consecutive
30679 percent signs for such names in the Asm template string, thus @code{%%eax}.
30680 In the generated assembly code, one of the percent signs will be stripped off.
30681
30682 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
30683 variables: operands you later define using @code{Input} or @code{Output}
30684 parameters to @code{Asm}.
30685 An output variable is illustrated in
30686 the third statement in the Asm template string:
30687 @smallexample
30688 movl %%eax, %0
30689 @end smallexample
30690 The intent is to store the contents of the eax register in a variable that can
30691 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
30692 necessarily work, since the compiler might optimize by using a register
30693 to hold Flags, and the expansion of the @code{movl} instruction would not be
30694 aware of this optimization.  The solution is not to store the result directly
30695 but rather to advise the compiler to choose the correct operand form;
30696 that is the purpose of the @code{%0} output variable.
30697
30698 Information about the output variable is supplied in the @code{Outputs}
30699 parameter to @code{Asm}:
30700 @smallexample
30701 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30702 @end smallexample
30703
30704 The output is defined by the @code{Asm_Output} attribute of the target type;
30705 the general format is
30706 @smallexample
30707 Type'Asm_Output (constraint_string, variable_name)
30708 @end smallexample
30709
30710 The constraint string directs the compiler how
30711 to store/access the associated variable.  In the example
30712 @smallexample
30713 Unsigned_32'Asm_Output ("=m", Flags);
30714 @end smallexample
30715 the @code{"m"} (memory) constraint tells the compiler that the variable
30716 @code{Flags} should be stored in a memory variable, thus preventing
30717 the optimizer from keeping it in a register.  In contrast,
30718 @smallexample
30719 Unsigned_32'Asm_Output ("=r", Flags);
30720 @end smallexample
30721 uses the @code{"r"} (register) constraint, telling the compiler to
30722 store the variable in a register.
30723
30724 If the constraint is preceded by the equal character (@strong{=}), it tells
30725 the compiler that the variable will be used to store data into it.
30726
30727 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
30728 allowing the optimizer to choose whatever it deems best.
30729
30730 There are a fairly large number of constraints, but the ones that are
30731 most useful (for the Intel x86 processor) are the following:
30732
30733 @table @code
30734 @item =
30735 output constraint
30736 @item g
30737 global (i.e.@: can be stored anywhere)
30738 @item m
30739 in memory
30740 @item I
30741 a constant
30742 @item a
30743 use eax
30744 @item b
30745 use ebx
30746 @item c
30747 use ecx
30748 @item d
30749 use edx
30750 @item S
30751 use esi
30752 @item D
30753 use edi
30754 @item r
30755 use one of eax, ebx, ecx or edx
30756 @item q
30757 use one of eax, ebx, ecx, edx, esi or edi
30758 @end table
30759
30760 The full set of constraints is described in the gcc and @emph{as}
30761 documentation; note that it is possible to combine certain constraints
30762 in one constraint string.
30763
30764 You specify the association of an output variable with an assembler operand
30765 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
30766 integer.  Thus in
30767 @smallexample @c ada
30768 @group
30769 Asm ("pushfl"          & LF & HT & -- push flags on stack
30770      "popl %%eax"      & LF & HT & -- load eax with flags
30771      "movl %%eax, %0",             -- store flags in variable
30772      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30773 @end group
30774 @end smallexample
30775 @noindent
30776 @code{%0} will be replaced in the expanded code by the appropriate operand,
30777 whatever
30778 the compiler decided for the @code{Flags} variable.
30779
30780 In general, you may have any number of output variables:
30781 @itemize @bullet
30782 @item
30783 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
30784 @item
30785 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
30786 of @code{Asm_Output} attributes
30787 @end itemize
30788
30789 For example:
30790 @smallexample @c ada
30791 @group
30792 Asm ("movl %%eax, %0" & LF & HT &
30793      "movl %%ebx, %1" & LF & HT &
30794      "movl %%ecx, %2",
30795      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
30796                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
30797                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
30798 @end group
30799 @end smallexample
30800 @noindent
30801 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
30802 in the Ada program.
30803
30804 As a variation on the @code{Get_Flags} example, we can use the constraints
30805 string to direct the compiler to store the eax register into the @code{Flags}
30806 variable, instead of including the store instruction explicitly in the
30807 @code{Asm} template string:
30808
30809 @smallexample @c ada
30810 @group
30811 with Interfaces; use Interfaces;
30812 with Ada.Text_IO; use Ada.Text_IO;
30813 with System.Machine_Code; use System.Machine_Code;
30814 procedure Get_Flags_2 is
30815    Flags : Unsigned_32;
30816    use ASCII;
30817 begin
30818    Asm ("pushfl"      & LF & HT & -- push flags on stack
30819         "popl %%eax",             -- save flags in eax
30820         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
30821    Put_Line ("Flags register:" & Flags'Img);
30822 end Get_Flags_2;
30823 @end group
30824 @end smallexample
30825
30826 @noindent
30827 The @code{"a"} constraint tells the compiler that the @code{Flags}
30828 variable will come from the eax register. Here is the resulting code:
30829
30830 @smallexample
30831 @group
30832 #APP
30833    pushfl
30834    popl %eax
30835 #NO_APP
30836    movl %eax,-40(%ebp)
30837 @end group
30838 @end smallexample
30839
30840 @noindent
30841 The compiler generated the store of eax into Flags after
30842 expanding the assembler code.
30843
30844 Actually, there was no need to pop the flags into the eax register;
30845 more simply, we could just pop the flags directly into the program variable:
30846
30847 @smallexample @c ada
30848 @group
30849 with Interfaces; use Interfaces;
30850 with Ada.Text_IO; use Ada.Text_IO;
30851 with System.Machine_Code; use System.Machine_Code;
30852 procedure Get_Flags_3 is
30853    Flags : Unsigned_32;
30854    use ASCII;
30855 begin
30856    Asm ("pushfl"  & LF & HT & -- push flags on stack
30857         "pop %0",             -- save flags in Flags
30858         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30859    Put_Line ("Flags register:" & Flags'Img);
30860 end Get_Flags_3;
30861 @end group
30862 @end smallexample
30863
30864 @c ---------------------------------------------------------------------------
30865 @node Input Variables in Inline Assembler
30866 @section Input Variables in Inline Assembler
30867
30868 @noindent
30869 The example in this section illustrates how to specify the source operands
30870 for assembly language statements.
30871 The program simply increments its input value by 1:
30872
30873 @smallexample @c ada
30874 @group
30875 with Interfaces; use Interfaces;
30876 with Ada.Text_IO; use Ada.Text_IO;
30877 with System.Machine_Code; use System.Machine_Code;
30878 procedure Increment is
30879
30880    function Incr (Value : Unsigned_32) return Unsigned_32 is
30881       Result : Unsigned_32;
30882    begin
30883       Asm ("incl %0",
30884            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30885            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30886       return Result;
30887    end Incr;
30888
30889    Value : Unsigned_32;
30890
30891 begin
30892    Value := 5;
30893    Put_Line ("Value before is" & Value'Img);
30894    Value := Incr (Value);
30895    Put_Line ("Value after is" & Value'Img);
30896 end Increment;
30897 @end group
30898 @end smallexample
30899
30900 The @code{Outputs} parameter to @code{Asm} specifies
30901 that the result will be in the eax register and that it is to be stored
30902 in the @code{Result} variable.
30903
30904 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
30905 but with an @code{Asm_Input} attribute.
30906 The @code{"="} constraint, indicating an output value, is not present.
30907
30908 You can have multiple input variables, in the same way that you can have more
30909 than one output variable.
30910
30911 The parameter count (%0, %1) etc, now starts at the first input
30912 statement, and continues with the output statements.
30913 When both parameters use the same variable, the
30914 compiler will treat them as the same %n operand, which is the case here.
30915
30916 Just as the @code{Outputs} parameter causes the register to be stored into the
30917 target variable after execution of the assembler statements, so does the
30918 @code{Inputs} parameter cause its variable to be loaded into the register
30919 before execution of the assembler statements.
30920
30921 Thus the effect of the @code{Asm} invocation is:
30922 @enumerate
30923 @item load the 32-bit value of @code{Value} into eax
30924 @item execute the @code{incl %eax} instruction
30925 @item store the contents of eax into the @code{Result} variable
30926 @end enumerate
30927
30928 The resulting assembler file (with @option{-O2} optimization) contains:
30929 @smallexample
30930 @group
30931 _increment__incr.1:
30932    subl $4,%esp
30933    movl 8(%esp),%eax
30934 #APP
30935    incl %eax
30936 #NO_APP
30937    movl %eax,%edx
30938    movl %ecx,(%esp)
30939    addl $4,%esp
30940    ret
30941 @end group
30942 @end smallexample
30943
30944 @c ---------------------------------------------------------------------------
30945 @node Inlining Inline Assembler Code
30946 @section Inlining Inline Assembler Code
30947
30948 @noindent
30949 For a short subprogram such as the @code{Incr} function in the previous
30950 section, the overhead of the call and return (creating / deleting the stack
30951 frame) can be significant, compared to the amount of code in the subprogram
30952 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
30953 which directs the compiler to expand invocations of the subprogram at the
30954 point(s) of call, instead of setting up a stack frame for out-of-line calls.
30955 Here is the resulting program:
30956
30957 @smallexample @c ada
30958 @group
30959 with Interfaces; use Interfaces;
30960 with Ada.Text_IO; use Ada.Text_IO;
30961 with System.Machine_Code; use System.Machine_Code;
30962 procedure Increment_2 is
30963
30964    function Incr (Value : Unsigned_32) return Unsigned_32 is
30965       Result : Unsigned_32;
30966    begin
30967       Asm ("incl %0",
30968            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30969            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30970       return Result;
30971    end Incr;
30972    pragma Inline (Increment);
30973
30974    Value : Unsigned_32;
30975
30976 begin
30977    Value := 5;
30978    Put_Line ("Value before is" & Value'Img);
30979    Value := Increment (Value);
30980    Put_Line ("Value after is" & Value'Img);
30981 end Increment_2;
30982 @end group
30983 @end smallexample
30984
30985 Compile the program with both optimization (@option{-O2}) and inlining
30986 (@option{-gnatn}) enabled.
30987
30988 The @code{Incr} function is still compiled as usual, but at the
30989 point in @code{Increment} where our function used to be called:
30990
30991 @smallexample
30992 @group
30993 pushl %edi
30994 call _increment__incr.1
30995 @end group
30996 @end smallexample
30997
30998 @noindent
30999 the code for the function body directly appears:
31000
31001 @smallexample
31002 @group
31003 movl %esi,%eax
31004 #APP
31005    incl %eax
31006 #NO_APP
31007    movl %eax,%edx
31008 @end group
31009 @end smallexample
31010
31011 @noindent
31012 thus saving the overhead of stack frame setup and an out-of-line call.
31013
31014 @c ---------------------------------------------------------------------------
31015 @node Other Asm Functionality
31016 @section Other @code{Asm} Functionality
31017
31018 @noindent
31019 This section describes two important parameters to the @code{Asm}
31020 procedure: @code{Clobber}, which identifies register usage;
31021 and @code{Volatile}, which inhibits unwanted optimizations.
31022
31023 @menu
31024 * The Clobber Parameter::
31025 * The Volatile Parameter::
31026 @end menu
31027
31028 @c ---------------------------------------------------------------------------
31029 @node The Clobber Parameter
31030 @subsection The @code{Clobber} Parameter
31031
31032 @noindent
31033 One of the dangers of intermixing assembly language and a compiled language
31034 such as Ada is that the compiler needs to be aware of which registers are
31035 being used by the assembly code.  In some cases, such as the earlier examples,
31036 the constraint string is sufficient to indicate register usage (e.g.,
31037 @code{"a"} for
31038 the eax register).  But more generally, the compiler needs an explicit
31039 identification of the registers that are used by the Inline Assembly
31040 statements.
31041
31042 Using a register that the compiler doesn't know about
31043 could be a side effect of an instruction (like @code{mull}
31044 storing its result in both eax and edx).
31045 It can also arise from explicit register usage in your
31046 assembly code; for example:
31047 @smallexample
31048 @group
31049 Asm ("movl %0, %%ebx" & LF & HT &
31050      "movl %%ebx, %1",
31051      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
31052      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
31053 @end group
31054 @end smallexample
31055 @noindent
31056 where the compiler (since it does not analyze the @code{Asm} template string)
31057 does not know you are using the ebx register.
31058
31059 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
31060 to identify the registers that will be used by your assembly code:
31061
31062 @smallexample
31063 @group
31064 Asm ("movl %0, %%ebx" & LF & HT &
31065      "movl %%ebx, %1",
31066      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
31067      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
31068      Clobber => "ebx");
31069 @end group
31070 @end smallexample
31071
31072 The Clobber parameter is a static string expression specifying the
31073 register(s) you are using.  Note that register names are @emph{not} prefixed
31074 by a percent sign. Also, if more than one register is used then their names
31075 are separated by commas; e.g., @code{"eax, ebx"}
31076
31077 The @code{Clobber} parameter has several additional uses:
31078 @enumerate
31079 @item Use ``register'' name @code{cc} to indicate that flags might have changed
31080 @item Use ``register'' name @code{memory} if you changed a memory location
31081 @end enumerate
31082
31083 @c ---------------------------------------------------------------------------
31084 @node The Volatile Parameter
31085 @subsection The @code{Volatile} Parameter
31086 @cindex Volatile parameter
31087
31088 @noindent
31089 Compiler optimizations in the presence of Inline Assembler may sometimes have
31090 unwanted effects.  For example, when an @code{Asm} invocation with an input
31091 variable is inside a loop, the compiler might move the loading of the input
31092 variable outside the loop, regarding it as a one-time initialization.
31093
31094 If this effect is not desired, you can disable such optimizations by setting
31095 the @code{Volatile} parameter to @code{True}; for example:
31096
31097 @smallexample @c ada
31098 @group
31099 Asm ("movl %0, %%ebx" & LF & HT &
31100      "movl %%ebx, %1",
31101      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
31102      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
31103      Clobber  => "ebx",
31104      Volatile => True);
31105 @end group
31106 @end smallexample
31107
31108 By default, @code{Volatile} is set to @code{False} unless there is no
31109 @code{Outputs} parameter.
31110
31111 Although setting @code{Volatile} to @code{True} prevents unwanted
31112 optimizations, it will also disable other optimizations that might be
31113 important for efficiency. In general, you should set @code{Volatile}
31114 to @code{True} only if the compiler's optimizations have created
31115 problems.
31116 @c END OF INLINE ASSEMBLER CHAPTER
31117 @c ===============================
31118
31119 @c ***********************************
31120 @c * Compatibility and Porting Guide *
31121 @c ***********************************
31122 @node Compatibility and Porting Guide
31123 @appendix Compatibility and Porting Guide
31124
31125 @noindent
31126 This chapter describes the compatibility issues that may arise between
31127 GNAT and other Ada compilation systems (including those for Ada 83),
31128 and shows how GNAT can expedite porting
31129 applications developed in other Ada environments.
31130
31131 @menu
31132 * Compatibility with Ada 83::
31133 * Compatibility between Ada 95 and Ada 2005::
31134 * Implementation-dependent characteristics::
31135 * Compatibility with Other Ada Systems::
31136 * Representation Clauses::
31137 @ifclear vms
31138 @c Brief section is only in non-VMS version
31139 @c Full chapter is in VMS version
31140 * Compatibility with HP Ada 83::
31141 @end ifclear
31142 @ifset vms
31143 * Transitioning to 64-Bit GNAT for OpenVMS::
31144 @end ifset
31145 @end menu
31146
31147 @node Compatibility with Ada 83
31148 @section Compatibility with Ada 83
31149 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
31150
31151 @noindent
31152 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
31153 particular, the design intention was that the difficulties associated
31154 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
31155 that occur when moving from one Ada 83 system to another.
31156
31157 However, there are a number of points at which there are minor
31158 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
31159 full details of these issues,
31160 and should be consulted for a complete treatment.
31161 In practice the
31162 following subsections treat the most likely issues to be encountered.
31163
31164 @menu
31165 * Legal Ada 83 programs that are illegal in Ada 95::
31166 * More deterministic semantics::
31167 * Changed semantics::
31168 * Other language compatibility issues::
31169 @end menu
31170
31171 @node Legal Ada 83 programs that are illegal in Ada 95
31172 @subsection Legal Ada 83 programs that are illegal in Ada 95
31173
31174 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
31175 Ada 95 and thus also in Ada 2005:
31176
31177 @table @emph
31178 @item Character literals
31179 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
31180 @code{Wide_Character} as a new predefined character type, some uses of
31181 character literals that were legal in Ada 83 are illegal in Ada 95.
31182 For example:
31183 @smallexample @c ada
31184    for Char in 'A' .. 'Z' loop @dots{} end loop;
31185 @end smallexample
31186
31187 @noindent
31188 The problem is that @code{'A'} and @code{'Z'} could be from either
31189 @code{Character} or @code{Wide_Character}.  The simplest correction
31190 is to make the type explicit; e.g.:
31191 @smallexample @c ada
31192    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
31193 @end smallexample
31194
31195 @item New reserved words
31196 The identifiers @code{abstract}, @code{aliased}, @code{protected},
31197 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
31198 Existing Ada 83 code using any of these identifiers must be edited to
31199 use some alternative name.
31200
31201 @item Freezing rules
31202 The rules in Ada 95 are slightly different with regard to the point at
31203 which entities are frozen, and representation pragmas and clauses are
31204 not permitted past the freeze point.  This shows up most typically in
31205 the form of an error message complaining that a representation item
31206 appears too late, and the appropriate corrective action is to move
31207 the item nearer to the declaration of the entity to which it refers.
31208
31209 A particular case is that representation pragmas
31210 @ifset vms
31211 (including the
31212 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
31213 @end ifset
31214 cannot be applied to a subprogram body.  If necessary, a separate subprogram
31215 declaration must be introduced to which the pragma can be applied.
31216
31217 @item Optional bodies for library packages
31218 In Ada 83, a package that did not require a package body was nevertheless
31219 allowed to have one.  This lead to certain surprises in compiling large
31220 systems (situations in which the body could be unexpectedly ignored by the
31221 binder).  In Ada 95, if a package does not require a body then it is not
31222 permitted to have a body.  To fix this problem, simply remove a redundant
31223 body if it is empty, or, if it is non-empty, introduce a dummy declaration
31224 into the spec that makes the body required.  One approach is to add a private
31225 part to the package declaration (if necessary), and define a parameterless
31226 procedure called @code{Requires_Body}, which must then be given a dummy
31227 procedure body in the package body, which then becomes required.
31228 Another approach (assuming that this does not introduce elaboration
31229 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
31230 since one effect of this pragma is to require the presence of a package body.
31231
31232 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
31233 In Ada 95, the exception @code{Numeric_Error} is a renaming of
31234 @code{Constraint_Error}.
31235 This means that it is illegal to have separate exception handlers for
31236 the two exceptions.  The fix is simply to remove the handler for the
31237 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
31238 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
31239
31240 @item Indefinite subtypes in generics
31241 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
31242 as the actual for a generic formal private type, but then the instantiation
31243 would be illegal if there were any instances of declarations of variables
31244 of this type in the generic body.  In Ada 95, to avoid this clear violation
31245 of the methodological principle known as the ``contract model'',
31246 the generic declaration explicitly indicates whether
31247 or not such instantiations are permitted.  If a generic formal parameter
31248 has explicit unknown discriminants, indicated by using @code{(<>)} after the
31249 type name, then it can be instantiated with indefinite types, but no
31250 stand-alone variables can be declared of this type.  Any attempt to declare
31251 such a variable will result in an illegality at the time the generic is
31252 declared.  If the @code{(<>)} notation is not used, then it is illegal
31253 to instantiate the generic with an indefinite type.
31254 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
31255 It will show up as a compile time error, and
31256 the fix is usually simply to add the @code{(<>)} to the generic declaration.
31257 @end table
31258
31259 @node More deterministic semantics
31260 @subsection More deterministic semantics
31261
31262 @table @emph
31263 @item Conversions
31264 Conversions from real types to integer types round away from 0.  In Ada 83
31265 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
31266 implementation freedom was intended to support unbiased rounding in
31267 statistical applications, but in practice it interfered with portability.
31268 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
31269 is required.  Numeric code may be affected by this change in semantics.
31270 Note, though, that this issue is no worse than already existed in Ada 83
31271 when porting code from one vendor to another.
31272
31273 @item Tasking
31274 The Real-Time Annex introduces a set of policies that define the behavior of
31275 features that were implementation dependent in Ada 83, such as the order in
31276 which open select branches are executed.
31277 @end table
31278
31279 @node Changed semantics
31280 @subsection Changed semantics
31281
31282 @noindent
31283 The worst kind of incompatibility is one where a program that is legal in
31284 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
31285 possible in Ada 83.  Fortunately this is extremely rare, but the one
31286 situation that you should be alert to is the change in the predefined type
31287 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
31288
31289 @table @emph
31290 @item Range of type @code{Character}
31291 The range of @code{Standard.Character} is now the full 256 characters
31292 of Latin-1, whereas in most Ada 83 implementations it was restricted
31293 to 128 characters. Although some of the effects of
31294 this change will be manifest in compile-time rejection of legal
31295 Ada 83 programs it is possible for a working Ada 83 program to have
31296 a different effect in Ada 95, one that was not permitted in Ada 83.
31297 As an example, the expression
31298 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
31299 delivers @code{255} as its value.
31300 In general, you should look at the logic of any
31301 character-processing Ada 83 program and see whether it needs to be adapted
31302 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
31303 character handling package that may be relevant if code needs to be adapted
31304 to account for the additional Latin-1 elements.
31305 The desirable fix is to
31306 modify the program to accommodate the full character set, but in some cases
31307 it may be convenient to define a subtype or derived type of Character that
31308 covers only the restricted range.
31309 @cindex Latin-1
31310 @end table
31311
31312 @node Other language compatibility issues
31313 @subsection Other language compatibility issues
31314
31315 @table @emph
31316 @item @option{-gnat83} switch
31317 All implementations of GNAT provide a switch that causes GNAT to operate
31318 in Ada 83 mode.  In this mode, some but not all compatibility problems
31319 of the type described above are handled automatically.  For example, the
31320 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
31321 as identifiers as in Ada 83.
31322 However,
31323 in practice, it is usually advisable to make the necessary modifications
31324 to the program to remove the need for using this switch.
31325 See @ref{Compiling Different Versions of Ada}.
31326
31327 @item Support for removed Ada 83 pragmas and attributes
31328 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
31329 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
31330 compilers are allowed, but not required, to implement these missing
31331 elements.  In contrast with some other compilers, GNAT implements all
31332 such pragmas and attributes, eliminating this compatibility concern.  These
31333 include @code{pragma Interface} and the floating point type attributes
31334 (@code{Emax}, @code{Mantissa}, etc.), among other items.
31335 @end table
31336
31337
31338 @node Compatibility between Ada 95 and Ada 2005
31339 @section Compatibility between Ada 95 and Ada 2005
31340 @cindex Compatibility between Ada 95 and Ada 2005
31341
31342 @noindent
31343 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
31344 a number of incompatibilities. Several are enumerated below;
31345 for a complete description please see the
31346 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
31347 @cite{Rationale for Ada 2005}.
31348
31349 @table @emph
31350 @item New reserved words.
31351 The words @code{interface}, @code{overriding} and @code{synchronized} are
31352 reserved in Ada 2005.
31353 A pre-Ada 2005 program that uses any of these as an identifier will be
31354 illegal.
31355
31356 @item New declarations in predefined packages.
31357 A number of packages in the predefined environment contain new declarations:
31358 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
31359 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
31360 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
31361 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
31362 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
31363 If an Ada 95 program does a @code{with} and @code{use} of any of these
31364 packages, the new declarations may cause name clashes.
31365
31366 @item Access parameters.
31367 A nondispatching subprogram with an access parameter cannot be renamed
31368 as a dispatching operation.  This was permitted in Ada 95.
31369
31370 @item Access types, discriminants, and constraints.
31371 Rule changes in this area have led to some incompatibilities; for example,
31372 constrained subtypes of some access types are not permitted in Ada 2005.
31373
31374 @item Aggregates for limited types.
31375 The allowance of aggregates for limited types in Ada 2005 raises the
31376 possibility of ambiguities in legal Ada 95 programs, since additional types
31377 now need to be considered in expression resolution.
31378
31379 @item Fixed-point multiplication and division.
31380 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
31381 were legal in Ada 95 and invoked the predefined versions of these operations,
31382 are now ambiguous.
31383 The ambiguity may be resolved either by applying a type conversion to the
31384 expression, or by explicitly invoking the operation from package
31385 @code{Standard}.
31386
31387 @item Return-by-reference types.
31388 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
31389 can declare a function returning a value from an anonymous access type.
31390 @end table
31391
31392
31393 @node Implementation-dependent characteristics
31394 @section Implementation-dependent characteristics
31395 @noindent
31396 Although the Ada language defines the semantics of each construct as
31397 precisely as practical, in some situations (for example for reasons of
31398 efficiency, or where the effect is heavily dependent on the host or target
31399 platform) the implementation is allowed some freedom.  In porting Ada 83
31400 code to GNAT, you need to be aware of whether / how the existing code
31401 exercised such implementation dependencies.  Such characteristics fall into
31402 several categories, and GNAT offers specific support in assisting the
31403 transition from certain Ada 83 compilers.
31404
31405 @menu
31406 * Implementation-defined pragmas::
31407 * Implementation-defined attributes::
31408 * Libraries::
31409 * Elaboration order::
31410 * Target-specific aspects::
31411 @end menu
31412
31413 @node Implementation-defined pragmas
31414 @subsection Implementation-defined pragmas
31415
31416 @noindent
31417 Ada compilers are allowed to supplement the language-defined pragmas, and
31418 these are a potential source of non-portability.  All GNAT-defined pragmas
31419 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
31420 Reference Manual}, and these include several that are specifically
31421 intended to correspond to other vendors' Ada 83 pragmas.
31422 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
31423 For compatibility with HP Ada 83, GNAT supplies the pragmas
31424 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
31425 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
31426 and @code{Volatile}.
31427 Other relevant pragmas include @code{External} and @code{Link_With}.
31428 Some vendor-specific
31429 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
31430 recognized, thus
31431 avoiding compiler rejection of units that contain such pragmas; they are not
31432 relevant in a GNAT context and hence are not otherwise implemented.
31433
31434 @node Implementation-defined attributes
31435 @subsection Implementation-defined attributes
31436
31437 Analogous to pragmas, the set of attributes may be extended by an
31438 implementation.  All GNAT-defined attributes are described in
31439 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
31440 Manual}, and these include several that are specifically intended
31441 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
31442 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
31443 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
31444 @code{Type_Class}.
31445
31446 @node Libraries
31447 @subsection Libraries
31448 @noindent
31449 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
31450 code uses vendor-specific libraries then there are several ways to manage
31451 this in Ada 95 or Ada 2005:
31452 @enumerate
31453 @item
31454 If the source code for the libraries (specs and bodies) are
31455 available, then the libraries can be migrated in the same way as the
31456 application.
31457 @item
31458 If the source code for the specs but not the bodies are
31459 available, then you can reimplement the bodies.
31460 @item
31461 Some features introduced by Ada 95 obviate the need for library support.  For
31462 example most Ada 83 vendors supplied a package for unsigned integers.  The
31463 Ada 95 modular type feature is the preferred way to handle this need, so
31464 instead of migrating or reimplementing the unsigned integer package it may
31465 be preferable to retrofit the application using modular types.
31466 @end enumerate
31467
31468 @node Elaboration order
31469 @subsection Elaboration order
31470 @noindent
31471 The implementation can choose any elaboration order consistent with the unit
31472 dependency relationship.  This freedom means that some orders can result in
31473 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
31474 to invoke a subprogram its body has been elaborated, or to instantiate a
31475 generic before the generic body has been elaborated.  By default GNAT
31476 attempts to choose a safe order (one that will not encounter access before
31477 elaboration problems) by implicitly inserting @code{Elaborate} or
31478 @code{Elaborate_All} pragmas where
31479 needed.  However, this can lead to the creation of elaboration circularities
31480 and a resulting rejection of the program by gnatbind.  This issue is
31481 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
31482 In brief, there are several
31483 ways to deal with this situation:
31484
31485 @itemize @bullet
31486 @item
31487 Modify the program to eliminate the circularities, e.g.@: by moving
31488 elaboration-time code into explicitly-invoked procedures
31489 @item
31490 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
31491 @code{Elaborate} pragmas, and then inhibit the generation of implicit
31492 @code{Elaborate_All}
31493 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
31494 (by selectively suppressing elaboration checks via pragma
31495 @code{Suppress(Elaboration_Check)} when it is safe to do so).
31496 @end itemize
31497
31498 @node Target-specific aspects
31499 @subsection Target-specific aspects
31500 @noindent
31501 Low-level applications need to deal with machine addresses, data
31502 representations, interfacing with assembler code, and similar issues.  If
31503 such an Ada 83 application is being ported to different target hardware (for
31504 example where the byte endianness has changed) then you will need to
31505 carefully examine the program logic; the porting effort will heavily depend
31506 on the robustness of the original design.  Moreover, Ada 95 (and thus
31507 Ada 2005) are sometimes
31508 incompatible with typical Ada 83 compiler practices regarding implicit
31509 packing, the meaning of the Size attribute, and the size of access values.
31510 GNAT's approach to these issues is described in @ref{Representation Clauses}.
31511
31512 @node Compatibility with Other Ada Systems
31513 @section Compatibility with Other Ada Systems
31514
31515 @noindent
31516 If programs avoid the use of implementation dependent and
31517 implementation defined features, as documented in the @cite{Ada
31518 Reference Manual}, there should be a high degree of portability between
31519 GNAT and other Ada systems.  The following are specific items which
31520 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
31521 compilers, but do not affect porting code to GNAT@.
31522 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
31523 the following issues may or may not arise for Ada 2005 programs
31524 when other compilers appear.)
31525
31526 @table @emph
31527 @item Ada 83 Pragmas and Attributes
31528 Ada 95 compilers are allowed, but not required, to implement the missing
31529 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
31530 GNAT implements all such pragmas and attributes, eliminating this as
31531 a compatibility concern, but some other Ada 95 compilers reject these
31532 pragmas and attributes.
31533
31534 @item Specialized Needs Annexes
31535 GNAT implements the full set of special needs annexes.  At the
31536 current time, it is the only Ada 95 compiler to do so.  This means that
31537 programs making use of these features may not be portable to other Ada
31538 95 compilation systems.
31539
31540 @item Representation Clauses
31541 Some other Ada 95 compilers implement only the minimal set of
31542 representation clauses required by the Ada 95 reference manual.  GNAT goes
31543 far beyond this minimal set, as described in the next section.
31544 @end table
31545
31546 @node Representation Clauses
31547 @section Representation Clauses
31548
31549 @noindent
31550 The Ada 83 reference manual was quite vague in describing both the minimal
31551 required implementation of representation clauses, and also their precise
31552 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
31553 minimal set of capabilities required is still quite limited.
31554
31555 GNAT implements the full required set of capabilities in
31556 Ada 95 and Ada 2005, but also goes much further, and in particular
31557 an effort has been made to be compatible with existing Ada 83 usage to the
31558 greatest extent possible.
31559
31560 A few cases exist in which Ada 83 compiler behavior is incompatible with
31561 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
31562 intentional or accidental dependence on specific implementation dependent
31563 characteristics of these Ada 83 compilers.  The following is a list of
31564 the cases most likely to arise in existing Ada 83 code.
31565
31566 @table @emph
31567 @item Implicit Packing
31568 Some Ada 83 compilers allowed a Size specification to cause implicit
31569 packing of an array or record.  This could cause expensive implicit
31570 conversions for change of representation in the presence of derived
31571 types, and the Ada design intends to avoid this possibility.
31572 Subsequent AI's were issued to make it clear that such implicit
31573 change of representation in response to a Size clause is inadvisable,
31574 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
31575 Reference Manuals as implementation advice that is followed by GNAT@.
31576 The problem will show up as an error
31577 message rejecting the size clause.  The fix is simply to provide
31578 the explicit pragma @code{Pack}, or for more fine tuned control, provide
31579 a Component_Size clause.
31580
31581 @item Meaning of Size Attribute
31582 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
31583 the minimal number of bits required to hold values of the type.  For example,
31584 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
31585 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
31586 some 32 in this situation.  This problem will usually show up as a compile
31587 time error, but not always.  It is a good idea to check all uses of the
31588 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
31589 Object_Size can provide a useful way of duplicating the behavior of
31590 some Ada 83 compiler systems.
31591
31592 @item Size of Access Types
31593 A common assumption in Ada 83 code is that an access type is in fact a pointer,
31594 and that therefore it will be the same size as a System.Address value.  This
31595 assumption is true for GNAT in most cases with one exception.  For the case of
31596 a pointer to an unconstrained array type (where the bounds may vary from one
31597 value of the access type to another), the default is to use a ``fat pointer'',
31598 which is represented as two separate pointers, one to the bounds, and one to
31599 the array.  This representation has a number of advantages, including improved
31600 efficiency.  However, it may cause some difficulties in porting existing Ada 83
31601 code which makes the assumption that, for example, pointers fit in 32 bits on
31602 a machine with 32-bit addressing.
31603
31604 To get around this problem, GNAT also permits the use of ``thin pointers'' for
31605 access types in this case (where the designated type is an unconstrained array
31606 type).  These thin pointers are indeed the same size as a System.Address value.
31607 To specify a thin pointer, use a size clause for the type, for example:
31608
31609 @smallexample @c ada
31610 type X is access all String;
31611 for X'Size use Standard'Address_Size;
31612 @end smallexample
31613
31614 @noindent
31615 which will cause the type X to be represented using a single pointer.
31616 When using this representation, the bounds are right behind the array.
31617 This representation is slightly less efficient, and does not allow quite
31618 such flexibility in the use of foreign pointers or in using the
31619 Unrestricted_Access attribute to create pointers to non-aliased objects.
31620 But for any standard portable use of the access type it will work in
31621 a functionally correct manner and allow porting of existing code.
31622 Note that another way of forcing a thin pointer representation
31623 is to use a component size clause for the element size in an array,
31624 or a record representation clause for an access field in a record.
31625 @end table
31626
31627 @ifclear vms
31628 @c This brief section is only in the non-VMS version
31629 @c The complete chapter on HP Ada is in the VMS version
31630 @node Compatibility with HP Ada 83
31631 @section Compatibility with HP Ada 83
31632
31633 @noindent
31634 The VMS version of GNAT fully implements all the pragmas and attributes
31635 provided by HP Ada 83, as well as providing the standard HP Ada 83
31636 libraries, including Starlet.  In addition, data layouts and parameter
31637 passing conventions are highly compatible.  This means that porting
31638 existing HP Ada 83 code to GNAT in VMS systems should be easier than
31639 most other porting efforts.  The following are some of the most
31640 significant differences between GNAT and HP Ada 83.
31641
31642 @table @emph
31643 @item Default floating-point representation
31644 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
31645 it is VMS format.  GNAT does implement the necessary pragmas
31646 (Long_Float, Float_Representation) for changing this default.
31647
31648 @item System
31649 The package System in GNAT exactly corresponds to the definition in the
31650 Ada 95 reference manual, which means that it excludes many of the
31651 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
31652 that contains the additional definitions, and a special pragma,
31653 Extend_System allows this package to be treated transparently as an
31654 extension of package System.
31655
31656 @item To_Address
31657 The definitions provided by Aux_DEC are exactly compatible with those
31658 in the HP Ada 83 version of System, with one exception.
31659 HP Ada provides the following declarations:
31660
31661 @smallexample @c ada
31662 TO_ADDRESS (INTEGER)
31663 TO_ADDRESS (UNSIGNED_LONGWORD)
31664 TO_ADDRESS (@i{universal_integer})
31665 @end smallexample
31666
31667 @noindent
31668 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
31669 an extension to Ada 83 not strictly compatible with the reference manual.
31670 In GNAT, we are constrained to be exactly compatible with the standard,
31671 and this means we cannot provide this capability.  In HP Ada 83, the
31672 point of this definition is to deal with a call like:
31673
31674 @smallexample @c ada
31675 TO_ADDRESS (16#12777#);
31676 @end smallexample
31677
31678 @noindent
31679 Normally, according to the Ada 83 standard, one would expect this to be
31680 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
31681 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
31682 definition using @i{universal_integer} takes precedence.
31683
31684 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
31685 is not possible to be 100% compatible.  Since there are many programs using
31686 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
31687 to change the name of the function in the UNSIGNED_LONGWORD case, so the
31688 declarations provided in the GNAT version of AUX_Dec are:
31689
31690 @smallexample @c ada
31691 function To_Address (X : Integer) return Address;
31692 pragma Pure_Function (To_Address);
31693
31694 function To_Address_Long (X : Unsigned_Longword)
31695  return Address;
31696 pragma Pure_Function (To_Address_Long);
31697 @end smallexample
31698
31699 @noindent
31700 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
31701 change the name to TO_ADDRESS_LONG@.
31702
31703 @item Task_Id values
31704 The Task_Id values assigned will be different in the two systems, and GNAT
31705 does not provide a specified value for the Task_Id of the environment task,
31706 which in GNAT is treated like any other declared task.
31707 @end table
31708
31709 @noindent
31710 For full details on these and other less significant compatibility issues,
31711 see appendix E of the HP publication entitled @cite{HP Ada, Technical
31712 Overview and Comparison on HP Platforms}.
31713
31714 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
31715 attributes are recognized, although only a subset of them can sensibly
31716 be implemented.  The description of pragmas in @ref{Implementation
31717 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
31718 indicates whether or not they are applicable to non-VMS systems.
31719 @end ifclear
31720
31721 @ifset vms
31722 @node Transitioning to 64-Bit GNAT for OpenVMS
31723 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
31724
31725 @noindent
31726 This section is meant to assist users of pre-2006 @value{EDITION}
31727 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
31728 the version of the GNAT technology supplied in 2006 and later for
31729 OpenVMS on both Alpha and I64.
31730
31731 @menu
31732 * Introduction to transitioning::
31733 * Migration of 32 bit code::
31734 * Taking advantage of 64 bit addressing::
31735 * Technical details::
31736 @end menu
31737
31738 @node Introduction to transitioning
31739 @subsection Introduction
31740
31741 @noindent
31742 64-bit @value{EDITION} for Open VMS has been designed to meet
31743 three main goals:
31744
31745 @enumerate
31746 @item
31747 Providing a full conforming implementation of Ada 95 and Ada 2005
31748
31749 @item
31750 Allowing maximum backward compatibility, thus easing migration of existing
31751 Ada source code
31752
31753 @item
31754 Supplying a path for exploiting the full 64-bit address range
31755 @end enumerate
31756
31757 @noindent
31758 Ada's strong typing semantics has made it
31759 impractical to have different 32-bit and 64-bit modes. As soon as
31760 one object could possibly be outside the 32-bit address space, this
31761 would make it necessary for the @code{System.Address} type to be 64 bits.
31762 In particular, this would cause inconsistencies if 32-bit code is
31763 called from 64-bit code that raises an exception.
31764
31765 This issue has been resolved by always using 64-bit addressing
31766 at the system level, but allowing for automatic conversions between
31767 32-bit and 64-bit addresses where required. Thus users who
31768 do not currently require 64-bit addressing capabilities, can
31769 recompile their code with only minimal changes (and indeed
31770 if the code is written in portable Ada, with no assumptions about
31771 the size of the @code{Address} type, then no changes at all are necessary).
31772 At the same time,
31773 this approach provides a simple, gradual upgrade path to future
31774 use of larger memories than available for 32-bit systems.
31775 Also, newly written applications or libraries will by default
31776 be fully compatible with future systems exploiting 64-bit
31777 addressing capabilities.
31778
31779 @ref{Migration of 32 bit code}, will focus on porting applications
31780 that do not require more than 2 GB of
31781 addressable memory. This code will be referred to as
31782 @emph{32-bit code}.
31783 For applications intending to exploit the full 64-bit address space,
31784 @ref{Taking advantage of 64 bit addressing},
31785 will consider further changes that may be required.
31786 Such code will be referred to below as @emph{64-bit code}.
31787
31788 @node Migration of 32 bit code
31789 @subsection Migration of 32-bit code
31790
31791 @menu
31792 * Address types::
31793 * Access types::
31794 * Unchecked conversions::
31795 * Predefined constants::
31796 * Interfacing with C::
31797 * Experience with source compatibility::
31798 @end menu
31799
31800 @node Address types
31801 @subsubsection Address types
31802
31803 @noindent
31804 To solve the problem of mixing 64-bit and 32-bit addressing,
31805 while maintaining maximum backward compatibility, the following
31806 approach has been taken:
31807
31808 @itemize @bullet
31809 @item
31810 @code{System.Address} always has a size of 64 bits
31811
31812 @item
31813 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
31814 @end itemize
31815
31816 @noindent
31817 Since @code{System.Short_Address} is a subtype of @code{System.Address},
31818 a @code{Short_Address}
31819 may be used where an @code{Address} is required, and vice versa, without
31820 needing explicit type conversions.
31821 By virtue of the Open VMS parameter passing conventions,
31822 even imported
31823 and exported subprograms that have 32-bit address parameters are
31824 compatible with those that have 64-bit address parameters.
31825 (See @ref{Making code 64 bit clean} for details.)
31826
31827 The areas that may need attention are those where record types have
31828 been defined that contain components of the type @code{System.Address}, and
31829 where objects of this type are passed to code expecting a record layout with
31830 32-bit addresses.
31831
31832 Different compilers on different platforms cannot be
31833 expected to represent the same type in the same way,
31834 since alignment constraints
31835 and other system-dependent properties affect the compiler's decision.
31836 For that reason, Ada code
31837 generally uses representation clauses to specify the expected
31838 layout where required.
31839
31840 If such a representation clause uses 32 bits for a component having
31841 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
31842 will detect that error and produce a specific diagnostic message.
31843 The developer should then determine whether the representation
31844 should be 64 bits or not and make either of two changes:
31845 change the size to 64 bits and leave the type as @code{System.Address}, or
31846 leave the size as 32 bits and change the type to @code{System.Short_Address}.
31847 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
31848 required in any code setting or accessing the field; the compiler will
31849 automatically perform any needed conversions between address
31850 formats.
31851
31852 @node Access types
31853 @subsubsection Access types
31854
31855 @noindent
31856 By default, objects designated by access values are always
31857 allocated in the 32-bit
31858 address space. Thus legacy code will never contain
31859 any objects that are not addressable with 32-bit addresses, and
31860 the compiler will never raise exceptions as result of mixing
31861 32-bit and 64-bit addresses.
31862
31863 However, the access values themselves are represented in 64 bits, for optimum
31864 performance and future compatibility with 64-bit code. As was
31865 the case with @code{System.Address}, the compiler will give an error message
31866 if an object or record component has a representation clause that
31867 requires the access value to fit in 32 bits. In such a situation,
31868 an explicit size clause for the access type, specifying 32 bits,
31869 will have the desired effect.
31870
31871 General access types (declared with @code{access all}) can never be
31872 32 bits, as values of such types must be able to refer to any object
31873 of the  designated type,
31874 including objects residing outside the 32-bit address range.
31875 Existing Ada 83 code will not contain such type definitions,
31876 however, since general access types were introduced in Ada 95.
31877
31878 @node Unchecked conversions
31879 @subsubsection Unchecked conversions
31880
31881 @noindent
31882 In the case of an @code{Unchecked_Conversion} where the source type is a
31883 64-bit access type or the type @code{System.Address}, and the target
31884 type is a 32-bit type, the compiler will generate a warning.
31885 Even though the generated code will still perform the required
31886 conversions, it is highly recommended in these cases to use
31887 respectively a 32-bit access type or @code{System.Short_Address}
31888 as the source type.
31889
31890 @node Predefined constants
31891 @subsubsection Predefined constants
31892
31893 @noindent
31894 The following table shows the correspondence between pre-2006 versions of
31895 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
31896 (``New''):
31897
31898 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
31899 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
31900 @item   @code{System.Word_Size}          @tab 32      @tab 64
31901 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
31902 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
31903 @item   @code{System.Address_Size}       @tab 32      @tab 64
31904 @end multitable
31905
31906 @noindent
31907 If you need to refer to the specific
31908 memory size of a 32-bit implementation, instead of the
31909 actual memory size, use @code{System.Short_Memory_Size}
31910 rather than @code{System.Memory_Size}.
31911 Similarly, references to @code{System.Address_Size} may need
31912 to be replaced by @code{System.Short_Address'Size}.
31913 The program @command{gnatfind} may be useful for locating
31914 references to the above constants, so that you can verify that they
31915 are still correct.
31916
31917 @node Interfacing with C
31918 @subsubsection Interfacing with C
31919
31920 @noindent
31921 In order to minimize the impact of the transition to 64-bit addresses on
31922 legacy programs, some fundamental types in the @code{Interfaces.C}
31923 package hierarchy continue to be represented in 32 bits.
31924 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
31925 This eases integration with the default HP C layout choices, for example
31926 as found in the system routines in @code{DECC$SHR.EXE}.
31927 Because of this implementation choice, the type fully compatible with
31928 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
31929 Depending on the context the compiler will issue a
31930 warning or an error when type @code{Address} is used, alerting the user to a
31931 potential problem. Otherwise 32-bit programs that use
31932 @code{Interfaces.C} should normally not require code modifications
31933
31934 The other issue arising with C interfacing concerns pragma @code{Convention}.
31935 For VMS 64-bit systems, there is an issue of the appropriate default size
31936 of C convention pointers in the absence of an explicit size clause. The HP
31937 C compiler can choose either 32 or 64 bits depending on compiler options.
31938 GNAT chooses 32-bits rather than 64-bits in the default case where no size
31939 clause is given. This proves a better choice for porting 32-bit legacy
31940 applications. In order to have a 64-bit representation, it is necessary to
31941 specify a size representation clause. For example:
31942
31943 @smallexample @c ada
31944 type int_star is access Interfaces.C.int;
31945 pragma Convention(C, int_star);
31946 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
31947 @end smallexample
31948
31949 @node Experience with source compatibility
31950 @subsubsection Experience with source compatibility
31951
31952 @noindent
31953 The Security Server and STARLET on I64 provide an interesting ``test case''
31954 for source compatibility issues, since it is in such system code
31955 where assumptions about @code{Address} size might be expected to occur.
31956 Indeed, there were a small number of occasions in the Security Server
31957 file @file{jibdef.ads}
31958 where a representation clause for a record type specified
31959 32 bits for a component of type @code{Address}.
31960 All of these errors were detected by the compiler.
31961 The repair was obvious and immediate; to simply replace @code{Address} by
31962 @code{Short_Address}.
31963
31964 In the case of STARLET, there were several record types that should
31965 have had representation clauses but did not.  In these record types
31966 there was an implicit assumption that an @code{Address} value occupied
31967 32 bits.
31968 These compiled without error, but their usage resulted in run-time error
31969 returns from STARLET system calls.
31970 Future GNAT technology enhancements may include a tool that detects and flags
31971 these sorts of potential source code porting problems.
31972
31973 @c ****************************************
31974 @node Taking advantage of 64 bit addressing
31975 @subsection Taking advantage of 64-bit addressing
31976
31977 @menu
31978 * Making code 64 bit clean::
31979 * Allocating memory from the 64 bit storage pool::
31980 * Restrictions on use of 64 bit objects::
31981 * Using 64 bit storage pools by default::
31982 * General access types::
31983 * STARLET and other predefined libraries::
31984 @end menu
31985
31986 @node Making code 64 bit clean
31987 @subsubsection Making code 64-bit clean
31988
31989 @noindent
31990 In order to prevent problems that may occur when (parts of) a
31991 system start using memory outside the 32-bit address range,
31992 we recommend some additional guidelines:
31993
31994 @itemize @bullet
31995 @item
31996 For imported subprograms that take parameters of the
31997 type @code{System.Address}, ensure that these subprograms can
31998 indeed handle 64-bit addresses. If not, or when in doubt,
31999 change the subprogram declaration to specify
32000 @code{System.Short_Address} instead.
32001
32002 @item
32003 Resolve all warnings related to size mismatches in
32004 unchecked conversions. Failing to do so causes
32005 erroneous execution if the source object is outside
32006 the 32-bit address space.
32007
32008 @item
32009 (optional) Explicitly use the 32-bit storage pool
32010 for access types used in a 32-bit context, or use
32011 generic access types where possible
32012 (@pxref{Restrictions on use of 64 bit objects}).
32013 @end itemize
32014
32015 @noindent
32016 If these rules are followed, the compiler will automatically insert
32017 any necessary checks to ensure that no addresses or access values
32018 passed to 32-bit code ever refer to objects outside the 32-bit
32019 address range.
32020 Any attempt to do this will raise @code{Constraint_Error}.
32021
32022 @node Allocating memory from the 64 bit storage pool
32023 @subsubsection Allocating memory from the 64-bit storage pool
32024
32025 @noindent
32026 For any access type @code{T} that potentially requires memory allocations
32027 beyond the 32-bit address space,
32028 use the following representation clause:
32029
32030 @smallexample @c ada
32031    for T'Storage_Pool use System.Pool_64;
32032 @end smallexample
32033
32034 @node Restrictions on use of 64 bit objects
32035 @subsubsection Restrictions on use of 64-bit objects
32036
32037 @noindent
32038 Taking the address of an object allocated from a 64-bit storage pool,
32039 and then passing this address to a subprogram expecting
32040 @code{System.Short_Address},
32041 or assigning it to a variable of type @code{Short_Address}, will cause
32042 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
32043 (@pxref{Making code 64 bit clean}), or checks are suppressed,
32044 no exception is raised and execution
32045 will become erroneous.
32046
32047 @node Using 64 bit storage pools by default
32048 @subsubsection Using 64-bit storage pools by default
32049
32050 @noindent
32051 In some cases it may be desirable to have the compiler allocate
32052 from 64-bit storage pools by default. This may be the case for
32053 libraries that are 64-bit clean, but may be used in both 32-bit
32054 and 64-bit contexts. For these cases the following configuration
32055 pragma may be specified:
32056
32057 @smallexample @c ada
32058   pragma Pool_64_Default;
32059 @end smallexample
32060
32061 @noindent
32062 Any code compiled in the context of this pragma will by default
32063 use the @code{System.Pool_64} storage pool. This default may be overridden
32064 for a specific access type @code{T} by the representation clause:
32065
32066 @smallexample @c ada
32067    for T'Storage_Pool use System.Pool_32;
32068 @end smallexample
32069
32070 @noindent
32071 Any object whose address may be passed to a subprogram with a
32072 @code{Short_Address} argument, or assigned to a variable of type
32073 @code{Short_Address}, needs to be allocated from this pool.
32074
32075 @node General access types
32076 @subsubsection General access types
32077
32078 @noindent
32079 Objects designated by access values from a
32080 general access type (declared with @code{access all}) are never allocated
32081 from a 64-bit storage pool. Code that uses general access types will
32082 accept objects allocated in either 32-bit or 64-bit address spaces,
32083 but never allocate objects outside the 32-bit address space.
32084 Using general access types ensures maximum compatibility with both
32085 32-bit and 64-bit code.
32086
32087 @node STARLET and other predefined libraries
32088 @subsubsection STARLET and other predefined libraries
32089
32090 @noindent
32091 All code that comes as part of GNAT is 64-bit clean, but the
32092 restrictions given in @ref{Restrictions on use of 64 bit objects},
32093 still apply. Look at the package
32094 specs to see in which contexts objects allocated
32095 in 64-bit address space are acceptable.
32096
32097 @node Technical details
32098 @subsection Technical details
32099
32100 @noindent
32101 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
32102 Ada standard with respect to the type of @code{System.Address}. Previous
32103 versions of GNAT Pro have defined this type as private and implemented it as a
32104 modular type.
32105
32106 In order to allow defining @code{System.Short_Address} as a proper subtype,
32107 and to match the implicit sign extension in parameter passing,
32108 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
32109 visible (i.e., non-private) integer type.
32110 Standard operations on the type, such as the binary operators ``+'', ``-'',
32111 etc., that take @code{Address} operands and return an @code{Address} result,
32112 have been hidden by declaring these
32113 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
32114 ambiguities that would otherwise result from overloading.
32115 (Note that, although @code{Address} is a visible integer type,
32116 good programming practice dictates against exploiting the type's
32117 integer properties such as literals, since this will compromise
32118 code portability.)
32119
32120 Defining @code{Address} as a visible integer type helps achieve
32121 maximum compatibility for existing Ada code,
32122 without sacrificing the capabilities of the 64-bit architecture.
32123 @end ifset
32124
32125 @c ************************************************
32126 @ifset unw
32127 @node Microsoft Windows Topics
32128 @appendix Microsoft Windows Topics
32129 @cindex Windows NT
32130 @cindex Windows 95
32131 @cindex Windows 98
32132
32133 @noindent
32134 This chapter describes topics that are specific to the Microsoft Windows
32135 platforms (NT, 2000, and XP Professional).
32136
32137 @menu
32138 * Using GNAT on Windows::
32139 * Using a network installation of GNAT::
32140 * CONSOLE and WINDOWS subsystems::
32141 * Temporary Files::
32142 * Mixed-Language Programming on Windows::
32143 * Windows Calling Conventions::
32144 * Introduction to Dynamic Link Libraries (DLLs)::
32145 * Using DLLs with GNAT::
32146 * Building DLLs with GNAT::
32147 * Building DLLs with GNAT Project files::
32148 * Building DLLs with gnatdll::
32149 * GNAT and Windows Resources::
32150 * Debugging a DLL::
32151 * Setting Stack Size from gnatlink::
32152 * Setting Heap Size from gnatlink::
32153 @end menu
32154
32155 @node Using GNAT on Windows
32156 @section Using GNAT on Windows
32157
32158 @noindent
32159 One of the strengths of the GNAT technology is that its tool set
32160 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
32161 @code{gdb} debugger, etc.) is used in the same way regardless of the
32162 platform.
32163
32164 On Windows this tool set is complemented by a number of Microsoft-specific
32165 tools that have been provided to facilitate interoperability with Windows
32166 when this is required. With these tools:
32167
32168 @itemize @bullet
32169
32170 @item
32171 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
32172 subsystems.
32173
32174 @item
32175 You can use any Dynamically Linked Library (DLL) in your Ada code (both
32176 relocatable and non-relocatable DLLs are supported).
32177
32178 @item
32179 You can build Ada DLLs for use in other applications. These applications
32180 can be written in a language other than Ada (e.g., C, C++, etc). Again both
32181 relocatable and non-relocatable Ada DLLs are supported.
32182
32183 @item
32184 You can include Windows resources in your Ada application.
32185
32186 @item
32187 You can use or create COM/DCOM objects.
32188 @end itemize
32189
32190 @noindent
32191 Immediately below are listed all known general GNAT-for-Windows restrictions.
32192 Other restrictions about specific features like Windows Resources and DLLs
32193 are listed in separate sections below.
32194
32195 @itemize @bullet
32196
32197 @item
32198 It is not possible to use @code{GetLastError} and @code{SetLastError}
32199 when tasking, protected records, or exceptions are used. In these
32200 cases, in order to implement Ada semantics, the GNAT run-time system
32201 calls certain Win32 routines that set the last error variable to 0 upon
32202 success. It should be possible to use @code{GetLastError} and
32203 @code{SetLastError} when tasking, protected record, and exception
32204 features are not used, but it is not guaranteed to work.
32205
32206 @item
32207 It is not possible to link against Microsoft libraries except for
32208 import libraries. The library must be built to be compatible with
32209 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
32210 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
32211 not be compatible with the GNAT runtime. Even if the library is
32212 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
32213
32214 @item
32215 When the compilation environment is located on FAT32 drives, users may
32216 experience recompilations of the source files that have not changed if
32217 Daylight Saving Time (DST) state has changed since the last time files
32218 were compiled. NTFS drives do not have this problem.
32219
32220 @item
32221 No components of the GNAT toolset use any entries in the Windows
32222 registry. The only entries that can be created are file associations and
32223 PATH settings, provided the user has chosen to create them at installation
32224 time, as well as some minimal book-keeping information needed to correctly
32225 uninstall or integrate different GNAT products.
32226 @end itemize
32227
32228 @node Using a network installation of GNAT
32229 @section Using a network installation of GNAT
32230
32231 @noindent
32232 Make sure the system on which GNAT is installed is accessible from the
32233 current machine, i.e., the install location is shared over the network.
32234 Shared resources are accessed on Windows by means of UNC paths, which
32235 have the format @code{\\server\sharename\path}
32236
32237 In order to use such a network installation, simply add the UNC path of the
32238 @file{bin} directory of your GNAT installation in front of your PATH. For
32239 example, if GNAT is installed in @file{\GNAT} directory of a share location
32240 called @file{c-drive} on a machine @file{LOKI}, the following command will
32241 make it available:
32242
32243 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
32244
32245 Be aware that every compilation using the network installation results in the
32246 transfer of large amounts of data across the network and will likely cause
32247 serious performance penalty.
32248
32249 @node CONSOLE and WINDOWS subsystems
32250 @section CONSOLE and WINDOWS subsystems
32251 @cindex CONSOLE Subsystem
32252 @cindex WINDOWS Subsystem
32253 @cindex -mwindows
32254
32255 @noindent
32256 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
32257 (which is the default subsystem) will always create a console when
32258 launching the application. This is not something desirable when the
32259 application has a Windows GUI. To get rid of this console the
32260 application must be using the @code{WINDOWS} subsystem. To do so
32261 the @option{-mwindows} linker option must be specified.
32262
32263 @smallexample
32264 $ gnatmake winprog -largs -mwindows
32265 @end smallexample
32266
32267 @node Temporary Files
32268 @section Temporary Files
32269 @cindex Temporary files
32270
32271 @noindent
32272 It is possible to control where temporary files gets created by setting
32273 the @env{TMP} environment variable. The file will be created:
32274
32275 @itemize
32276 @item Under the directory pointed to by the @env{TMP} environment variable if
32277 this directory exists.
32278
32279 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
32280 set (or not pointing to a directory) and if this directory exists.
32281
32282 @item Under the current working directory otherwise.
32283 @end itemize
32284
32285 @noindent
32286 This allows you to determine exactly where the temporary
32287 file will be created. This is particularly useful in networked
32288 environments where you may not have write access to some
32289 directories.
32290
32291 @node Mixed-Language Programming on Windows
32292 @section Mixed-Language Programming on Windows
32293
32294 @noindent
32295 Developing pure Ada applications on Windows is no different than on
32296 other GNAT-supported platforms. However, when developing or porting an
32297 application that contains a mix of Ada and C/C++, the choice of your
32298 Windows C/C++ development environment conditions your overall
32299 interoperability strategy.
32300
32301 If you use @command{gcc} to compile the non-Ada part of your application,
32302 there are no Windows-specific restrictions that affect the overall
32303 interoperability with your Ada code. If you plan to use
32304 Microsoft tools (e.g.@: Microsoft Visual C/C++), you should be aware of
32305 the following limitations:
32306
32307 @itemize @bullet
32308 @item
32309 You cannot link your Ada code with an object or library generated with
32310 Microsoft tools if these use the @code{.tls} section (Thread Local
32311 Storage section) since the GNAT linker does not yet support this section.
32312
32313 @item
32314 You cannot link your Ada code with an object or library generated with
32315 Microsoft tools if these use I/O routines other than those provided in
32316 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
32317 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
32318 libraries can cause a conflict with @code{msvcrt.dll} services. For
32319 instance Visual C++ I/O stream routines conflict with those in
32320 @code{msvcrt.dll}.
32321 @end itemize
32322
32323 @noindent
32324 If you do want to use the Microsoft tools for your non-Ada code and hit one
32325 of the above limitations, you have two choices:
32326
32327 @enumerate
32328 @item
32329 Encapsulate your non-Ada code in a DLL to be linked with your Ada
32330 application. In this case, use the Microsoft or whatever environment to
32331 build the DLL and use GNAT to build your executable
32332 (@pxref{Using DLLs with GNAT}).
32333
32334 @item
32335 Or you can encapsulate your Ada code in a DLL to be linked with the
32336 other part of your application. In this case, use GNAT to build the DLL
32337 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
32338 environment to build your executable.
32339 @end enumerate
32340
32341 @node Windows Calling Conventions
32342 @section Windows Calling Conventions
32343 @findex Stdcall
32344 @findex APIENTRY
32345
32346 @menu
32347 * C Calling Convention::
32348 * Stdcall Calling Convention::
32349 * Win32 Calling Convention::
32350 * DLL Calling Convention::
32351 @end menu
32352
32353 @noindent
32354 When a subprogram @code{F} (caller) calls a subprogram @code{G}
32355 (callee), there are several ways to push @code{G}'s parameters on the
32356 stack and there are several possible scenarios to clean up the stack
32357 upon @code{G}'s return. A calling convention is an agreed upon software
32358 protocol whereby the responsibilities between the caller (@code{F}) and
32359 the callee (@code{G}) are clearly defined. Several calling conventions
32360 are available for Windows:
32361
32362 @itemize @bullet
32363 @item
32364 @code{C} (Microsoft defined)
32365
32366 @item
32367 @code{Stdcall} (Microsoft defined)
32368
32369 @item
32370 @code{Win32} (GNAT specific)
32371
32372 @item
32373 @code{DLL} (GNAT specific)
32374 @end itemize
32375
32376 @node C Calling Convention
32377 @subsection @code{C} Calling Convention
32378
32379 @noindent
32380 This is the default calling convention used when interfacing to C/C++
32381 routines compiled with either @command{gcc} or Microsoft Visual C++.
32382
32383 In the @code{C} calling convention subprogram parameters are pushed on the
32384 stack by the caller from right to left. The caller itself is in charge of
32385 cleaning up the stack after the call. In addition, the name of a routine
32386 with @code{C} calling convention is mangled by adding a leading underscore.
32387
32388 The name to use on the Ada side when importing (or exporting) a routine
32389 with @code{C} calling convention is the name of the routine. For
32390 instance the C function:
32391
32392 @smallexample
32393 int get_val (long);
32394 @end smallexample
32395
32396 @noindent
32397 should be imported from Ada as follows:
32398
32399 @smallexample @c ada
32400 @group
32401 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32402 pragma Import (C, Get_Val, External_Name => "get_val");
32403 @end group
32404 @end smallexample
32405
32406 @noindent
32407 Note that in this particular case the @code{External_Name} parameter could
32408 have been omitted since, when missing, this parameter is taken to be the
32409 name of the Ada entity in lower case. When the @code{Link_Name} parameter
32410 is missing, as in the above example, this parameter is set to be the
32411 @code{External_Name} with a leading underscore.
32412
32413 When importing a variable defined in C, you should always use the @code{C}
32414 calling convention unless the object containing the variable is part of a
32415 DLL (in which case you should use the @code{Stdcall} calling
32416 convention, @pxref{Stdcall Calling Convention}).
32417
32418 @node Stdcall Calling Convention
32419 @subsection @code{Stdcall} Calling Convention
32420
32421 @noindent
32422 This convention, which was the calling convention used for Pascal
32423 programs, is used by Microsoft for all the routines in the Win32 API for
32424 efficiency reasons. It must be used to import any routine for which this
32425 convention was specified.
32426
32427 In the @code{Stdcall} calling convention subprogram parameters are pushed
32428 on the stack by the caller from right to left. The callee (and not the
32429 caller) is in charge of cleaning the stack on routine exit. In addition,
32430 the name of a routine with @code{Stdcall} calling convention is mangled by
32431 adding a leading underscore (as for the @code{C} calling convention) and a
32432 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
32433 bytes) of the parameters passed to the routine.
32434
32435 The name to use on the Ada side when importing a C routine with a
32436 @code{Stdcall} calling convention is the name of the C routine. The leading
32437 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
32438 the compiler. For instance the Win32 function:
32439
32440 @smallexample
32441 @b{APIENTRY} int get_val (long);
32442 @end smallexample
32443
32444 @noindent
32445 should be imported from Ada as follows:
32446
32447 @smallexample @c ada
32448 @group
32449 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32450 pragma Import (Stdcall, Get_Val);
32451 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
32452 @end group
32453 @end smallexample
32454
32455 @noindent
32456 As for the @code{C} calling convention, when the @code{External_Name}
32457 parameter is missing, it is taken to be the name of the Ada entity in lower
32458 case. If instead of writing the above import pragma you write:
32459
32460 @smallexample @c ada
32461 @group
32462 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32463 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
32464 @end group
32465 @end smallexample
32466
32467 @noindent
32468 then the imported routine is @code{_retrieve_val@@4}. However, if instead
32469 of specifying the @code{External_Name} parameter you specify the
32470 @code{Link_Name} as in the following example:
32471
32472 @smallexample @c ada
32473 @group
32474 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32475 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
32476 @end group
32477 @end smallexample
32478
32479 @noindent
32480 then the imported routine is @code{retrieve_val}, that is, there is no
32481 decoration at all. No leading underscore and no Stdcall suffix
32482 @code{@@}@code{@var{nn}}.
32483
32484 @noindent
32485 This is especially important as in some special cases a DLL's entry
32486 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
32487 name generated for a call has it.
32488
32489 @noindent
32490 It is also possible to import variables defined in a DLL by using an
32491 import pragma for a variable. As an example, if a DLL contains a
32492 variable defined as:
32493
32494 @smallexample
32495 int my_var;
32496 @end smallexample
32497
32498 @noindent
32499 then, to access this variable from Ada you should write:
32500
32501 @smallexample @c ada
32502 @group
32503 My_Var : Interfaces.C.int;
32504 pragma Import (Stdcall, My_Var);
32505 @end group
32506 @end smallexample
32507
32508 @noindent
32509 Note that to ease building cross-platform bindings this convention
32510 will be handled as a @code{C} calling convention on non-Windows platforms.
32511
32512 @node Win32 Calling Convention
32513 @subsection @code{Win32} Calling Convention
32514
32515 @noindent
32516 This convention, which is GNAT-specific is fully equivalent to the
32517 @code{Stdcall} calling convention described above.
32518
32519 @node DLL Calling Convention
32520 @subsection @code{DLL} Calling Convention
32521
32522 @noindent
32523 This convention, which is GNAT-specific is fully equivalent to the
32524 @code{Stdcall} calling convention described above.
32525
32526 @node Introduction to Dynamic Link Libraries (DLLs)
32527 @section Introduction to Dynamic Link Libraries (DLLs)
32528 @findex DLL
32529
32530 @noindent
32531 A Dynamically Linked Library (DLL) is a library that can be shared by
32532 several applications running under Windows. A DLL can contain any number of
32533 routines and variables.
32534
32535 One advantage of DLLs is that you can change and enhance them without
32536 forcing all the applications that depend on them to be relinked or
32537 recompiled. However, you should be aware than all calls to DLL routines are
32538 slower since, as you will understand below, such calls are indirect.
32539
32540 To illustrate the remainder of this section, suppose that an application
32541 wants to use the services of a DLL @file{API.dll}. To use the services
32542 provided by @file{API.dll} you must statically link against the DLL or
32543 an import library which contains a jump table with an entry for each
32544 routine and variable exported by the DLL. In the Microsoft world this
32545 import library is called @file{API.lib}. When using GNAT this import
32546 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
32547 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
32548
32549 After you have linked your application with the DLL or the import library
32550 and you run your application, here is what happens:
32551
32552 @enumerate
32553 @item
32554 Your application is loaded into memory.
32555
32556 @item
32557 The DLL @file{API.dll} is mapped into the address space of your
32558 application. This means that:
32559
32560 @itemize @bullet
32561 @item
32562 The DLL will use the stack of the calling thread.
32563
32564 @item
32565 The DLL will use the virtual address space of the calling process.
32566
32567 @item
32568 The DLL will allocate memory from the virtual address space of the calling
32569 process.
32570
32571 @item
32572 Handles (pointers) can be safely exchanged between routines in the DLL
32573 routines and routines in the application using the DLL.
32574 @end itemize
32575
32576 @item
32577 The entries in the jump table (from the import library @file{libAPI.dll.a}
32578 or @file{API.lib} or automatically created when linking against a DLL)
32579 which is part of your application are initialized with the addresses
32580 of the routines and variables in @file{API.dll}.
32581
32582 @item
32583 If present in @file{API.dll}, routines @code{DllMain} or
32584 @code{DllMainCRTStartup} are invoked. These routines typically contain
32585 the initialization code needed for the well-being of the routines and
32586 variables exported by the DLL.
32587 @end enumerate
32588
32589 @noindent
32590 There is an additional point which is worth mentioning. In the Windows
32591 world there are two kind of DLLs: relocatable and non-relocatable
32592 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
32593 in the target application address space. If the addresses of two
32594 non-relocatable DLLs overlap and these happen to be used by the same
32595 application, a conflict will occur and the application will run
32596 incorrectly. Hence, when possible, it is always preferable to use and
32597 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
32598 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
32599 User's Guide) removes the debugging symbols from the DLL but the DLL can
32600 still be relocated.
32601
32602 As a side note, an interesting difference between Microsoft DLLs and
32603 Unix shared libraries, is the fact that on most Unix systems all public
32604 routines are exported by default in a Unix shared library, while under
32605 Windows it is possible (but not required) to list exported routines in
32606 a definition file (@pxref{The Definition File}).
32607
32608 @node Using DLLs with GNAT
32609 @section Using DLLs with GNAT
32610
32611 @menu
32612 * Creating an Ada Spec for the DLL Services::
32613 * Creating an Import Library::
32614 @end menu
32615
32616 @noindent
32617 To use the services of a DLL, say @file{API.dll}, in your Ada application
32618 you must have:
32619
32620 @enumerate
32621 @item
32622 The Ada spec for the routines and/or variables you want to access in
32623 @file{API.dll}. If not available this Ada spec must be built from the C/C++
32624 header files provided with the DLL.
32625
32626 @item
32627 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
32628 mentioned an import library is a statically linked library containing the
32629 import table which will be filled at load time to point to the actual
32630 @file{API.dll} routines. Sometimes you don't have an import library for the
32631 DLL you want to use. The following sections will explain how to build
32632 one. Note that this is optional.
32633
32634 @item
32635 The actual DLL, @file{API.dll}.
32636 @end enumerate
32637
32638 @noindent
32639 Once you have all the above, to compile an Ada application that uses the
32640 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
32641 you simply issue the command
32642
32643 @smallexample
32644 $ gnatmake my_ada_app -largs -lAPI
32645 @end smallexample
32646
32647 @noindent
32648 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
32649 tells the GNAT linker to look first for a library named @file{API.lib}
32650 (Microsoft-style name) and if not found for a libraries named
32651 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
32652 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
32653 contains the following pragma
32654
32655 @smallexample @c ada
32656 pragma Linker_Options ("-lAPI");
32657 @end smallexample
32658
32659 @noindent
32660 you do not have to add @option{-largs -lAPI} at the end of the
32661 @command{gnatmake} command.
32662
32663 If any one of the items above is missing you will have to create it
32664 yourself. The following sections explain how to do so using as an
32665 example a fictitious DLL called @file{API.dll}.
32666
32667 @node Creating an Ada Spec for the DLL Services
32668 @subsection Creating an Ada Spec for the DLL Services
32669
32670 @noindent
32671 A DLL typically comes with a C/C++ header file which provides the
32672 definitions of the routines and variables exported by the DLL. The Ada
32673 equivalent of this header file is a package spec that contains definitions
32674 for the imported entities. If the DLL you intend to use does not come with
32675 an Ada spec you have to generate one such spec yourself. For example if
32676 the header file of @file{API.dll} is a file @file{api.h} containing the
32677 following two definitions:
32678
32679 @smallexample
32680 @group
32681 @cartouche
32682 int some_var;
32683 int get (char *);
32684 @end cartouche
32685 @end group
32686 @end smallexample
32687
32688 @noindent
32689 then the equivalent Ada spec could be:
32690
32691 @smallexample @c ada
32692 @group
32693 @cartouche
32694 with Interfaces.C.Strings;
32695 package API is
32696    use Interfaces;
32697
32698    Some_Var : C.int;
32699    function Get (Str : C.Strings.Chars_Ptr) return C.int;
32700
32701 private
32702    pragma Import (C, Get);
32703    pragma Import (DLL, Some_Var);
32704 end API;
32705 @end cartouche
32706 @end group
32707 @end smallexample
32708
32709 @noindent
32710 Note that a variable is
32711 @strong{always imported with a Stdcall convention}. A function
32712 can have @code{C} or @code{Stdcall} convention.
32713 (@pxref{Windows Calling Conventions}).
32714
32715 @node Creating an Import Library
32716 @subsection Creating an Import Library
32717 @cindex Import library
32718
32719 @menu
32720 * The Definition File::
32721 * GNAT-Style Import Library::
32722 * Microsoft-Style Import Library::
32723 @end menu
32724
32725 @noindent
32726 If a Microsoft-style import library @file{API.lib} or a GNAT-style
32727 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
32728 with @file{API.dll} you can skip this section. You can also skip this
32729 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
32730 as in this case it is possible to link directly against the
32731 DLL. Otherwise read on.
32732
32733 @node The Definition File
32734 @subsubsection The Definition File
32735 @cindex Definition file
32736 @findex .def
32737
32738 @noindent
32739 As previously mentioned, and unlike Unix systems, the list of symbols
32740 that are exported from a DLL must be provided explicitly in Windows.
32741 The main goal of a definition file is precisely that: list the symbols
32742 exported by a DLL. A definition file (usually a file with a @code{.def}
32743 suffix) has the following structure:
32744
32745 @smallexample
32746 @group
32747 @cartouche
32748 @r{[}LIBRARY @var{name}@r{]}
32749 @r{[}DESCRIPTION @var{string}@r{]}
32750 EXPORTS
32751    @var{symbol1}
32752    @var{symbol2}
32753    @dots{}
32754 @end cartouche
32755 @end group
32756 @end smallexample
32757
32758 @table @code
32759 @item LIBRARY @var{name}
32760 This section, which is optional, gives the name of the DLL.
32761
32762 @item DESCRIPTION @var{string}
32763 This section, which is optional, gives a description string that will be
32764 embedded in the import library.
32765
32766 @item EXPORTS
32767 This section gives the list of exported symbols (procedures, functions or
32768 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
32769 section of @file{API.def} looks like:
32770
32771 @smallexample
32772 @group
32773 @cartouche
32774 EXPORTS
32775    some_var
32776    get
32777 @end cartouche
32778 @end group
32779 @end smallexample
32780 @end table
32781
32782 @noindent
32783 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
32784 (@pxref{Windows Calling Conventions}) for a Stdcall
32785 calling convention function in the exported symbols list.
32786
32787 @noindent
32788 There can actually be other sections in a definition file, but these
32789 sections are not relevant to the discussion at hand.
32790
32791 @node GNAT-Style Import Library
32792 @subsubsection GNAT-Style Import Library
32793
32794 @noindent
32795 To create a static import library from @file{API.dll} with the GNAT tools
32796 you should proceed as follows:
32797
32798 @enumerate
32799 @item
32800 Create the definition file @file{API.def} (@pxref{The Definition File}).
32801 For that use the @code{dll2def} tool as follows:
32802
32803 @smallexample
32804 $ dll2def API.dll > API.def
32805 @end smallexample
32806
32807 @noindent
32808 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
32809 to standard output the list of entry points in the DLL. Note that if
32810 some routines in the DLL have the @code{Stdcall} convention
32811 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
32812 suffix then you'll have to edit @file{api.def} to add it, and specify
32813 @option{-k} to @command{gnatdll} when creating the import library.
32814
32815 @noindent
32816 Here are some hints to find the right @code{@@}@var{nn} suffix.
32817
32818 @enumerate
32819 @item
32820 If you have the Microsoft import library (.lib), it is possible to get
32821 the right symbols by using Microsoft @code{dumpbin} tool (see the
32822 corresponding Microsoft documentation for further details).
32823
32824 @smallexample
32825 $ dumpbin /exports api.lib
32826 @end smallexample
32827
32828 @item
32829 If you have a message about a missing symbol at link time the compiler
32830 tells you what symbol is expected. You just have to go back to the
32831 definition file and add the right suffix.
32832 @end enumerate
32833
32834 @item
32835 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
32836 (@pxref{Using gnatdll}) as follows:
32837
32838 @smallexample
32839 $ gnatdll -e API.def -d API.dll
32840 @end smallexample
32841
32842 @noindent
32843 @code{gnatdll} takes as input a definition file @file{API.def} and the
32844 name of the DLL containing the services listed in the definition file
32845 @file{API.dll}. The name of the static import library generated is
32846 computed from the name of the definition file as follows: if the
32847 definition file name is @var{xyz}@code{.def}, the import library name will
32848 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
32849 @option{-e} could have been removed because the name of the definition
32850 file (before the ``@code{.def}'' suffix) is the same as the name of the
32851 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
32852 @end enumerate
32853
32854 @node Microsoft-Style Import Library
32855 @subsubsection Microsoft-Style Import Library
32856
32857 @noindent
32858 With GNAT you can either use a GNAT-style or Microsoft-style import
32859 library. A Microsoft import library is needed only if you plan to make an
32860 Ada DLL available to applications developed with Microsoft
32861 tools (@pxref{Mixed-Language Programming on Windows}).
32862
32863 To create a Microsoft-style import library for @file{API.dll} you
32864 should proceed as follows:
32865
32866 @enumerate
32867 @item
32868 Create the definition file @file{API.def} from the DLL. For this use either
32869 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
32870 tool (see the corresponding Microsoft documentation for further details).
32871
32872 @item
32873 Build the actual import library using Microsoft's @code{lib} utility:
32874
32875 @smallexample
32876 $ lib -machine:IX86 -def:API.def -out:API.lib
32877 @end smallexample
32878
32879 @noindent
32880 If you use the above command the definition file @file{API.def} must
32881 contain a line giving the name of the DLL:
32882
32883 @smallexample
32884 LIBRARY      "API"
32885 @end smallexample
32886
32887 @noindent
32888 See the Microsoft documentation for further details about the usage of
32889 @code{lib}.
32890 @end enumerate
32891
32892 @node Building DLLs with GNAT
32893 @section Building DLLs with GNAT
32894 @cindex DLLs, building
32895
32896 @noindent
32897 This section explain how to build DLLs using the GNAT built-in DLL
32898 support. With the following procedure it is straight forward to build
32899 and use DLLs with GNAT.
32900
32901 @enumerate
32902
32903 @item building object files
32904
32905 The first step is to build all objects files that are to be included
32906 into the DLL. This is done by using the standard @command{gnatmake} tool.
32907
32908 @item building the DLL
32909
32910 To build the DLL you must use @command{gcc}'s @option{-shared}
32911 option. It is quite simple to use this method:
32912
32913 @smallexample
32914 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
32915 @end smallexample
32916
32917 It is important to note that in this case all symbols found in the
32918 object files are automatically exported. It is possible to restrict
32919 the set of symbols to export by passing to @command{gcc} a definition
32920 file, @pxref{The Definition File}. For example:
32921
32922 @smallexample
32923 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
32924 @end smallexample
32925
32926 If you use a definition file you must export the elaboration procedures
32927 for every package that required one. Elaboration procedures are named
32928 using the package name followed by "_E".
32929
32930 @item preparing DLL to be used
32931
32932 For the DLL to be used by client programs the bodies must be hidden
32933 from it and the .ali set with read-only attribute. This is very important
32934 otherwise GNAT will recompile all packages and will not actually use
32935 the code in the DLL. For example:
32936
32937 @smallexample
32938 $ mkdir apilib
32939 $ copy *.ads *.ali api.dll apilib
32940 $ attrib +R apilib\*.ali
32941 @end smallexample
32942
32943 @end enumerate
32944
32945 At this point it is possible to use the DLL by directly linking
32946 against it. Note that you must use the GNAT shared runtime when using
32947 GNAT shared libraries. This is achieved by using @option{-shared} binder's
32948 option.
32949
32950 @smallexample
32951 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
32952 @end smallexample
32953
32954 @node Building DLLs with GNAT Project files
32955 @section Building DLLs with GNAT Project files
32956 @cindex DLLs, building
32957
32958 @noindent
32959 There is nothing specific to Windows in the build process.
32960 @pxref{Library Projects}.
32961
32962 @noindent
32963 Due to a system limitation, it is not possible under Windows to create threads
32964 when inside the @code{DllMain} routine which is used for auto-initialization
32965 of shared libraries, so it is not possible to have library level tasks in SALs.
32966
32967 @node Building DLLs with gnatdll
32968 @section Building DLLs with gnatdll
32969 @cindex DLLs, building
32970
32971 @menu
32972 * Limitations When Using Ada DLLs from Ada::
32973 * Exporting Ada Entities::
32974 * Ada DLLs and Elaboration::
32975 * Ada DLLs and Finalization::
32976 * Creating a Spec for Ada DLLs::
32977 * Creating the Definition File::
32978 * Using gnatdll::
32979 @end menu
32980
32981 @noindent
32982 Note that it is preferred to use the built-in GNAT DLL support
32983 (@pxref{Building DLLs with GNAT}) or GNAT Project files
32984 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
32985
32986 This section explains how to build DLLs containing Ada code using
32987 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
32988 remainder of this section.
32989
32990 The steps required to build an Ada DLL that is to be used by Ada as well as
32991 non-Ada applications are as follows:
32992
32993 @enumerate
32994 @item
32995 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
32996 @code{Stdcall} calling convention to avoid any Ada name mangling for the
32997 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
32998 skip this step if you plan to use the Ada DLL only from Ada applications.
32999
33000 @item
33001 Your Ada code must export an initialization routine which calls the routine
33002 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
33003 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
33004 routine exported by the Ada DLL must be invoked by the clients of the DLL
33005 to initialize the DLL.
33006
33007 @item
33008 When useful, the DLL should also export a finalization routine which calls
33009 routine @code{adafinal} generated by @command{gnatbind} to perform the
33010 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
33011 The finalization routine exported by the Ada DLL must be invoked by the
33012 clients of the DLL when the DLL services are no further needed.
33013
33014 @item
33015 You must provide a spec for the services exported by the Ada DLL in each
33016 of the programming languages to which you plan to make the DLL available.
33017
33018 @item
33019 You must provide a definition file listing the exported entities
33020 (@pxref{The Definition File}).
33021
33022 @item
33023 Finally you must use @code{gnatdll} to produce the DLL and the import
33024 library (@pxref{Using gnatdll}).
33025 @end enumerate
33026
33027 @noindent
33028 Note that a relocatable DLL stripped using the @code{strip}
33029 binutils tool will not be relocatable anymore. To build a DLL without
33030 debug information pass @code{-largs -s} to @code{gnatdll}. This
33031 restriction does not apply to a DLL built using a Library Project.
33032 @pxref{Library Projects}.
33033
33034 @node Limitations When Using Ada DLLs from Ada
33035 @subsection Limitations When Using Ada DLLs from Ada
33036
33037 @noindent
33038 When using Ada DLLs from Ada applications there is a limitation users
33039 should be aware of. Because on Windows the GNAT run time is not in a DLL of
33040 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
33041 each Ada DLL includes the services of the GNAT run time that are necessary
33042 to the Ada code inside the DLL. As a result, when an Ada program uses an
33043 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
33044 one in the main program.
33045
33046 It is therefore not possible to exchange GNAT run-time objects between the
33047 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
33048 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
33049 types, etc.
33050
33051 It is completely safe to exchange plain elementary, array or record types,
33052 Windows object handles, etc.
33053
33054 @node Exporting Ada Entities
33055 @subsection Exporting Ada Entities
33056 @cindex Export table
33057
33058 @noindent
33059 Building a DLL is a way to encapsulate a set of services usable from any
33060 application. As a result, the Ada entities exported by a DLL should be
33061 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
33062 any Ada name mangling. As an example here is an Ada package
33063 @code{API}, spec and body, exporting two procedures, a function, and a
33064 variable:
33065
33066 @smallexample @c ada
33067 @group
33068 @cartouche
33069 with Interfaces.C; use Interfaces;
33070 package API is
33071    Count : C.int := 0;
33072    function Factorial (Val : C.int) return C.int;
33073
33074    procedure Initialize_API;
33075    procedure Finalize_API;
33076    --  Initialization & Finalization routines. More in the next section.
33077 private
33078    pragma Export (C, Initialize_API);
33079    pragma Export (C, Finalize_API);
33080    pragma Export (C, Count);
33081    pragma Export (C, Factorial);
33082 end API;
33083 @end cartouche
33084 @end group
33085 @end smallexample
33086
33087 @smallexample @c ada
33088 @group
33089 @cartouche
33090 package body API is
33091    function Factorial (Val : C.int) return C.int is
33092       Fact : C.int := 1;
33093    begin
33094       Count := Count + 1;
33095       for K in 1 .. Val loop
33096          Fact := Fact * K;
33097       end loop;
33098       return Fact;
33099    end Factorial;
33100
33101    procedure Initialize_API is
33102       procedure Adainit;
33103       pragma Import (C, Adainit);
33104    begin
33105       Adainit;
33106    end Initialize_API;
33107
33108    procedure Finalize_API is
33109       procedure Adafinal;
33110       pragma Import (C, Adafinal);
33111    begin
33112       Adafinal;
33113    end Finalize_API;
33114 end API;
33115 @end cartouche
33116 @end group
33117 @end smallexample
33118
33119 @noindent
33120 If the Ada DLL you are building will only be used by Ada applications
33121 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
33122 convention. As an example, the previous package could be written as
33123 follows:
33124
33125 @smallexample @c ada
33126 @group
33127 @cartouche
33128 package API is
33129    Count : Integer := 0;
33130    function Factorial (Val : Integer) return Integer;
33131
33132    procedure Initialize_API;
33133    procedure Finalize_API;
33134    --  Initialization and Finalization routines.
33135 end API;
33136 @end cartouche
33137 @end group
33138 @end smallexample
33139
33140 @smallexample @c ada
33141 @group
33142 @cartouche
33143 package body API is
33144    function Factorial (Val : Integer) return Integer is
33145       Fact : Integer := 1;
33146    begin
33147       Count := Count + 1;
33148       for K in 1 .. Val loop
33149          Fact := Fact * K;
33150       end loop;
33151       return Fact;
33152    end Factorial;
33153
33154    @dots{}
33155    --  The remainder of this package body is unchanged.
33156 end API;
33157 @end cartouche
33158 @end group
33159 @end smallexample
33160
33161 @noindent
33162 Note that if you do not export the Ada entities with a @code{C} or
33163 @code{Stdcall} convention you will have to provide the mangled Ada names
33164 in the definition file of the Ada DLL
33165 (@pxref{Creating the Definition File}).
33166
33167 @node Ada DLLs and Elaboration
33168 @subsection Ada DLLs and Elaboration
33169 @cindex DLLs and elaboration
33170
33171 @noindent
33172 The DLL that you are building contains your Ada code as well as all the
33173 routines in the Ada library that are needed by it. The first thing a
33174 user of your DLL must do is elaborate the Ada code
33175 (@pxref{Elaboration Order Handling in GNAT}).
33176
33177 To achieve this you must export an initialization routine
33178 (@code{Initialize_API} in the previous example), which must be invoked
33179 before using any of the DLL services. This elaboration routine must call
33180 the Ada elaboration routine @code{adainit} generated by the GNAT binder
33181 (@pxref{Binding with Non-Ada Main Programs}). See the body of
33182 @code{Initialize_Api} for an example. Note that the GNAT binder is
33183 automatically invoked during the DLL build process by the @code{gnatdll}
33184 tool (@pxref{Using gnatdll}).
33185
33186 When a DLL is loaded, Windows systematically invokes a routine called
33187 @code{DllMain}. It would therefore be possible to call @code{adainit}
33188 directly from @code{DllMain} without having to provide an explicit
33189 initialization routine. Unfortunately, it is not possible to call
33190 @code{adainit} from the @code{DllMain} if your program has library level
33191 tasks because access to the @code{DllMain} entry point is serialized by
33192 the system (that is, only a single thread can execute ``through'' it at a
33193 time), which means that the GNAT run time will deadlock waiting for the
33194 newly created task to complete its initialization.
33195
33196 @node Ada DLLs and Finalization
33197 @subsection Ada DLLs and Finalization
33198 @cindex DLLs and finalization
33199
33200 @noindent
33201 When the services of an Ada DLL are no longer needed, the client code should
33202 invoke the DLL finalization routine, if available. The DLL finalization
33203 routine is in charge of releasing all resources acquired by the DLL. In the
33204 case of the Ada code contained in the DLL, this is achieved by calling
33205 routine @code{adafinal} generated by the GNAT binder
33206 (@pxref{Binding with Non-Ada Main Programs}).
33207 See the body of @code{Finalize_Api} for an
33208 example. As already pointed out the GNAT binder is automatically invoked
33209 during the DLL build process by the @code{gnatdll} tool
33210 (@pxref{Using gnatdll}).
33211
33212 @node Creating a Spec for Ada DLLs
33213 @subsection Creating a Spec for Ada DLLs
33214
33215 @noindent
33216 To use the services exported by the Ada DLL from another programming
33217 language (e.g.@: C), you have to translate the specs of the exported Ada
33218 entities in that language. For instance in the case of @code{API.dll},
33219 the corresponding C header file could look like:
33220
33221 @smallexample
33222 @group
33223 @cartouche
33224 extern int *_imp__count;
33225 #define count (*_imp__count)
33226 int factorial (int);
33227 @end cartouche
33228 @end group
33229 @end smallexample
33230
33231 @noindent
33232 It is important to understand that when building an Ada DLL to be used by
33233 other Ada applications, you need two different specs for the packages
33234 contained in the DLL: one for building the DLL and the other for using
33235 the DLL. This is because the @code{DLL} calling convention is needed to
33236 use a variable defined in a DLL, but when building the DLL, the variable
33237 must have either the @code{Ada} or @code{C} calling convention. As an
33238 example consider a DLL comprising the following package @code{API}:
33239
33240 @smallexample @c ada
33241 @group
33242 @cartouche
33243 package API is
33244    Count : Integer := 0;
33245    @dots{}
33246    --  Remainder of the package omitted.
33247 end API;
33248 @end cartouche
33249 @end group
33250 @end smallexample
33251
33252 @noindent
33253 After producing a DLL containing package @code{API}, the spec that
33254 must be used to import @code{API.Count} from Ada code outside of the
33255 DLL is:
33256
33257 @smallexample @c ada
33258 @group
33259 @cartouche
33260 package API is
33261    Count : Integer;
33262    pragma Import (DLL, Count);
33263 end API;
33264 @end cartouche
33265 @end group
33266 @end smallexample
33267
33268 @node Creating the Definition File
33269 @subsection Creating the Definition File
33270
33271 @noindent
33272 The definition file is the last file needed to build the DLL. It lists
33273 the exported symbols. As an example, the definition file for a DLL
33274 containing only package @code{API} (where all the entities are exported
33275 with a @code{C} calling convention) is:
33276
33277 @smallexample
33278 @group
33279 @cartouche
33280 EXPORTS
33281     count
33282     factorial
33283     finalize_api
33284     initialize_api
33285 @end cartouche
33286 @end group
33287 @end smallexample
33288
33289 @noindent
33290 If the @code{C} calling convention is missing from package @code{API},
33291 then the definition file contains the mangled Ada names of the above
33292 entities, which in this case are:
33293
33294 @smallexample
33295 @group
33296 @cartouche
33297 EXPORTS
33298     api__count
33299     api__factorial
33300     api__finalize_api
33301     api__initialize_api
33302 @end cartouche
33303 @end group
33304 @end smallexample
33305
33306 @node Using gnatdll
33307 @subsection Using @code{gnatdll}
33308 @findex gnatdll
33309
33310 @menu
33311 * gnatdll Example::
33312 * gnatdll behind the Scenes::
33313 * Using dlltool::
33314 @end menu
33315
33316 @noindent
33317 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
33318 and non-Ada sources that make up your DLL have been compiled.
33319 @code{gnatdll} is actually in charge of two distinct tasks: build the
33320 static import library for the DLL and the actual DLL. The form of the
33321 @code{gnatdll} command is
33322
33323 @smallexample
33324 @cartouche
33325 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
33326 @c Expanding @ovar macro inline (explanation in macro def comments)
33327 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
33328 @end cartouche
33329 @end smallexample
33330
33331 @noindent
33332 where @var{list-of-files} is a list of ALI and object files. The object
33333 file list must be the exact list of objects corresponding to the non-Ada
33334 sources whose services are to be included in the DLL. The ALI file list
33335 must be the exact list of ALI files for the corresponding Ada sources
33336 whose services are to be included in the DLL. If @var{list-of-files} is
33337 missing, only the static import library is generated.
33338
33339 @noindent
33340 You may specify any of the following switches to @code{gnatdll}:
33341
33342 @table @code
33343 @c @item -a@ovar{address}
33344 @c Expanding @ovar macro inline (explanation in macro def comments)
33345 @item -a@r{[}@var{address}@r{]}
33346 @cindex @option{-a} (@code{gnatdll})
33347 Build a non-relocatable DLL at @var{address}. If @var{address} is not
33348 specified the default address @var{0x11000000} will be used. By default,
33349 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
33350 advise the reader to build relocatable DLL.
33351
33352 @item -b @var{address}
33353 @cindex @option{-b} (@code{gnatdll})
33354 Set the relocatable DLL base address. By default the address is
33355 @code{0x11000000}.
33356
33357 @item -bargs @var{opts}
33358 @cindex @option{-bargs} (@code{gnatdll})
33359 Binder options. Pass @var{opts} to the binder.
33360
33361 @item -d @var{dllfile}
33362 @cindex @option{-d} (@code{gnatdll})
33363 @var{dllfile} is the name of the DLL. This switch must be present for
33364 @code{gnatdll} to do anything. The name of the generated import library is
33365 obtained algorithmically from @var{dllfile} as shown in the following
33366 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
33367 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
33368 by option @option{-e}) is obtained algorithmically from @var{dllfile}
33369 as shown in the following example:
33370 if @var{dllfile} is @code{xyz.dll}, the definition
33371 file used is @code{xyz.def}.
33372
33373 @item -e @var{deffile}
33374 @cindex @option{-e} (@code{gnatdll})
33375 @var{deffile} is the name of the definition file.
33376
33377 @item -g
33378 @cindex @option{-g} (@code{gnatdll})
33379 Generate debugging information. This information is stored in the object
33380 file and copied from there to the final DLL file by the linker,
33381 where it can be read by the debugger. You must use the
33382 @option{-g} switch if you plan on using the debugger or the symbolic
33383 stack traceback.
33384
33385 @item -h
33386 @cindex @option{-h} (@code{gnatdll})
33387 Help mode. Displays @code{gnatdll} switch usage information.
33388
33389 @item -Idir
33390 @cindex @option{-I} (@code{gnatdll})
33391 Direct @code{gnatdll} to search the @var{dir} directory for source and
33392 object files needed to build the DLL.
33393 (@pxref{Search Paths and the Run-Time Library (RTL)}).
33394
33395 @item -k
33396 @cindex @option{-k} (@code{gnatdll})
33397 Removes the @code{@@}@var{nn} suffix from the import library's exported
33398 names, but keeps them for the link names. You must specify this
33399 option if you want to use a @code{Stdcall} function in a DLL for which
33400 the @code{@@}@var{nn} suffix has been removed. This is the case for most
33401 of the Windows NT DLL for example. This option has no effect when
33402 @option{-n} option is specified.
33403
33404 @item -l @var{file}
33405 @cindex @option{-l} (@code{gnatdll})
33406 The list of ALI and object files used to build the DLL are listed in
33407 @var{file}, instead of being given in the command line. Each line in
33408 @var{file} contains the name of an ALI or object file.
33409
33410 @item -n
33411 @cindex @option{-n} (@code{gnatdll})
33412 No Import. Do not create the import library.
33413
33414 @item -q
33415 @cindex @option{-q} (@code{gnatdll})
33416 Quiet mode. Do not display unnecessary messages.
33417
33418 @item -v
33419 @cindex @option{-v} (@code{gnatdll})
33420 Verbose mode. Display extra information.
33421
33422 @item -largs @var{opts}
33423 @cindex @option{-largs} (@code{gnatdll})
33424 Linker options. Pass @var{opts} to the linker.
33425 @end table
33426
33427 @node gnatdll Example
33428 @subsubsection @code{gnatdll} Example
33429
33430 @noindent
33431 As an example the command to build a relocatable DLL from @file{api.adb}
33432 once @file{api.adb} has been compiled and @file{api.def} created is
33433
33434 @smallexample
33435 $ gnatdll -d api.dll api.ali
33436 @end smallexample
33437
33438 @noindent
33439 The above command creates two files: @file{libapi.dll.a} (the import
33440 library) and @file{api.dll} (the actual DLL). If you want to create
33441 only the DLL, just type:
33442
33443 @smallexample
33444 $ gnatdll -d api.dll -n api.ali
33445 @end smallexample
33446
33447 @noindent
33448 Alternatively if you want to create just the import library, type:
33449
33450 @smallexample
33451 $ gnatdll -d api.dll
33452 @end smallexample
33453
33454 @node gnatdll behind the Scenes
33455 @subsubsection @code{gnatdll} behind the Scenes
33456
33457 @noindent
33458 This section details the steps involved in creating a DLL. @code{gnatdll}
33459 does these steps for you. Unless you are interested in understanding what
33460 goes on behind the scenes, you should skip this section.
33461
33462 We use the previous example of a DLL containing the Ada package @code{API},
33463 to illustrate the steps necessary to build a DLL. The starting point is a
33464 set of objects that will make up the DLL and the corresponding ALI
33465 files. In the case of this example this means that @file{api.o} and
33466 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
33467 the following:
33468
33469 @enumerate
33470 @item
33471 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
33472 the information necessary to generate relocation information for the
33473 DLL.
33474
33475 @smallexample
33476 @group
33477 $ gnatbind -n api
33478 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
33479 @end group
33480 @end smallexample
33481
33482 @noindent
33483 In addition to the base file, the @command{gnatlink} command generates an
33484 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
33485 asks @command{gnatlink} to generate the routines @code{DllMain} and
33486 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
33487 is loaded into memory.
33488
33489 @item
33490 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
33491 export table (@file{api.exp}). The export table contains the relocation
33492 information in a form which can be used during the final link to ensure
33493 that the Windows loader is able to place the DLL anywhere in memory.
33494
33495 @smallexample
33496 @group
33497 $ dlltool --dllname api.dll --def api.def --base-file api.base \
33498           --output-exp api.exp
33499 @end group
33500 @end smallexample
33501
33502 @item
33503 @code{gnatdll} builds the base file using the new export table. Note that
33504 @command{gnatbind} must be called once again since the binder generated file
33505 has been deleted during the previous call to @command{gnatlink}.
33506
33507 @smallexample
33508 @group
33509 $ gnatbind -n api
33510 $ gnatlink api -o api.jnk api.exp -mdll
33511       -Wl,--base-file,api.base
33512 @end group
33513 @end smallexample
33514
33515 @item
33516 @code{gnatdll} builds the new export table using the new base file and
33517 generates the DLL import library @file{libAPI.dll.a}.
33518
33519 @smallexample
33520 @group
33521 $ dlltool --dllname api.dll --def api.def --base-file api.base \
33522           --output-exp api.exp --output-lib libAPI.a
33523 @end group
33524 @end smallexample
33525
33526 @item
33527 Finally @code{gnatdll} builds the relocatable DLL using the final export
33528 table.
33529
33530 @smallexample
33531 @group
33532 $ gnatbind -n api
33533 $ gnatlink api api.exp -o api.dll -mdll
33534 @end group
33535 @end smallexample
33536 @end enumerate
33537
33538 @node Using dlltool
33539 @subsubsection Using @code{dlltool}
33540
33541 @noindent
33542 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
33543 DLLs and static import libraries. This section summarizes the most
33544 common @code{dlltool} switches. The form of the @code{dlltool} command
33545 is
33546
33547 @smallexample
33548 @c $ dlltool @ovar{switches}
33549 @c Expanding @ovar macro inline (explanation in macro def comments)
33550 $ dlltool @r{[}@var{switches}@r{]}
33551 @end smallexample
33552
33553 @noindent
33554 @code{dlltool} switches include:
33555
33556 @table @option
33557 @item --base-file @var{basefile}
33558 @cindex @option{--base-file} (@command{dlltool})
33559 Read the base file @var{basefile} generated by the linker. This switch
33560 is used to create a relocatable DLL.
33561
33562 @item --def @var{deffile}
33563 @cindex @option{--def} (@command{dlltool})
33564 Read the definition file.
33565
33566 @item --dllname @var{name}
33567 @cindex @option{--dllname} (@command{dlltool})
33568 Gives the name of the DLL. This switch is used to embed the name of the
33569 DLL in the static import library generated by @code{dlltool} with switch
33570 @option{--output-lib}.
33571
33572 @item -k
33573 @cindex @option{-k} (@command{dlltool})
33574 Kill @code{@@}@var{nn} from exported names
33575 (@pxref{Windows Calling Conventions}
33576 for a discussion about @code{Stdcall}-style symbols.
33577
33578 @item --help
33579 @cindex @option{--help} (@command{dlltool})
33580 Prints the @code{dlltool} switches with a concise description.
33581
33582 @item --output-exp @var{exportfile}
33583 @cindex @option{--output-exp} (@command{dlltool})
33584 Generate an export file @var{exportfile}. The export file contains the
33585 export table (list of symbols in the DLL) and is used to create the DLL.
33586
33587 @item --output-lib @var{libfile}
33588 @cindex @option{--output-lib} (@command{dlltool})
33589 Generate a static import library @var{libfile}.
33590
33591 @item -v
33592 @cindex @option{-v} (@command{dlltool})
33593 Verbose mode.
33594
33595 @item --as @var{assembler-name}
33596 @cindex @option{--as} (@command{dlltool})
33597 Use @var{assembler-name} as the assembler. The default is @code{as}.
33598 @end table
33599
33600 @node GNAT and Windows Resources
33601 @section GNAT and Windows Resources
33602 @cindex Resources, windows
33603
33604 @menu
33605 * Building Resources::
33606 * Compiling Resources::
33607 * Using Resources::
33608 @end menu
33609
33610 @noindent
33611 Resources are an easy way to add Windows specific objects to your
33612 application. The objects that can be added as resources include:
33613
33614 @itemize @bullet
33615 @item
33616 menus
33617
33618 @item
33619 accelerators
33620
33621 @item
33622 dialog boxes
33623
33624 @item
33625 string tables
33626
33627 @item
33628 bitmaps
33629
33630 @item
33631 cursors
33632
33633 @item
33634 icons
33635
33636 @item
33637 fonts
33638 @end itemize
33639
33640 @noindent
33641 This section explains how to build, compile and use resources.
33642
33643 @node Building Resources
33644 @subsection Building Resources
33645 @cindex Resources, building
33646
33647 @noindent
33648 A resource file is an ASCII file. By convention resource files have an
33649 @file{.rc} extension.
33650 The easiest way to build a resource file is to use Microsoft tools
33651 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
33652 @code{dlgedit.exe} to build dialogs.
33653 It is always possible to build an @file{.rc} file yourself by writing a
33654 resource script.
33655
33656 It is not our objective to explain how to write a resource file. A
33657 complete description of the resource script language can be found in the
33658 Microsoft documentation.
33659
33660 @node Compiling Resources
33661 @subsection Compiling Resources
33662 @findex rc
33663 @findex windres
33664 @cindex Resources, compiling
33665
33666 @noindent
33667 This section describes how to build a GNAT-compatible (COFF) object file
33668 containing the resources. This is done using the Resource Compiler
33669 @code{windres} as follows:
33670
33671 @smallexample
33672 $ windres -i myres.rc -o myres.o
33673 @end smallexample
33674
33675 @noindent
33676 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
33677 file. You can specify an alternate preprocessor (usually named
33678 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
33679 parameter. A list of all possible options may be obtained by entering
33680 the command @code{windres} @option{--help}.
33681
33682 It is also possible to use the Microsoft resource compiler @code{rc.exe}
33683 to produce a @file{.res} file (binary resource file). See the
33684 corresponding Microsoft documentation for further details. In this case
33685 you need to use @code{windres} to translate the @file{.res} file to a
33686 GNAT-compatible object file as follows:
33687
33688 @smallexample
33689 $ windres -i myres.res -o myres.o
33690 @end smallexample
33691
33692 @node Using Resources
33693 @subsection Using Resources
33694 @cindex Resources, using
33695
33696 @noindent
33697 To include the resource file in your program just add the
33698 GNAT-compatible object file for the resource(s) to the linker
33699 arguments. With @command{gnatmake} this is done by using the @option{-largs}
33700 option:
33701
33702 @smallexample
33703 $ gnatmake myprog -largs myres.o
33704 @end smallexample
33705
33706 @node Debugging a DLL
33707 @section Debugging a DLL
33708 @cindex DLL debugging
33709
33710 @menu
33711 * Program and DLL Both Built with GCC/GNAT::
33712 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
33713 @end menu
33714
33715 @noindent
33716 Debugging a DLL is similar to debugging a standard program. But
33717 we have to deal with two different executable parts: the DLL and the
33718 program that uses it. We have the following four possibilities:
33719
33720 @enumerate 1
33721 @item
33722 The program and the DLL are built with @code{GCC/GNAT}.
33723 @item
33724 The program is built with foreign tools and the DLL is built with
33725 @code{GCC/GNAT}.
33726 @item
33727 The program is built with @code{GCC/GNAT} and the DLL is built with
33728 foreign tools.
33729 @item
33730 @end enumerate
33731
33732 @noindent
33733 In this section we address only cases one and two above.
33734 There is no point in trying to debug
33735 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
33736 information in it. To do so you must use a debugger compatible with the
33737 tools suite used to build the DLL.
33738
33739 @node Program and DLL Both Built with GCC/GNAT
33740 @subsection Program and DLL Both Built with GCC/GNAT
33741
33742 @noindent
33743 This is the simplest case. Both the DLL and the program have @code{GDB}
33744 compatible debugging information. It is then possible to break anywhere in
33745 the process. Let's suppose here that the main procedure is named
33746 @code{ada_main} and that in the DLL there is an entry point named
33747 @code{ada_dll}.
33748
33749 @noindent
33750 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
33751 program must have been built with the debugging information (see GNAT -g
33752 switch). Here are the step-by-step instructions for debugging it:
33753
33754 @enumerate 1
33755 @item Launch @code{GDB} on the main program.
33756
33757 @smallexample
33758 $ gdb -nw ada_main
33759 @end smallexample
33760
33761 @item Start the program and stop at the beginning of the main procedure
33762
33763 @smallexample
33764 (gdb) start
33765 @end smallexample
33766
33767 @noindent
33768 This step is required to be able to set a breakpoint inside the DLL. As long
33769 as the program is not run, the DLL is not loaded. This has the
33770 consequence that the DLL debugging information is also not loaded, so it is not
33771 possible to set a breakpoint in the DLL.
33772
33773 @item Set a breakpoint inside the DLL
33774
33775 @smallexample
33776 (gdb) break ada_dll
33777 (gdb) cont
33778 @end smallexample
33779
33780 @end enumerate
33781
33782 @noindent
33783 At this stage a breakpoint is set inside the DLL. From there on
33784 you can use the standard approach to debug the whole program
33785 (@pxref{Running and Debugging Ada Programs}).
33786
33787 @ignore
33788 @c This used to work, probably because the DLLs were non-relocatable
33789 @c keep this section around until the problem is sorted out.
33790
33791 To break on the @code{DllMain} routine it is not possible to follow
33792 the procedure above. At the time the program stop on @code{ada_main}
33793 the @code{DllMain} routine as already been called. Either you can use
33794 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
33795
33796 @enumerate 1
33797 @item Launch @code{GDB} on the main program.
33798
33799 @smallexample
33800 $ gdb ada_main
33801 @end smallexample
33802
33803 @item Load DLL symbols
33804
33805 @smallexample
33806 (gdb) add-sym api.dll
33807 @end smallexample
33808
33809 @item Set a breakpoint inside the DLL
33810
33811 @smallexample
33812 (gdb) break ada_dll.adb:45
33813 @end smallexample
33814
33815 Note that at this point it is not possible to break using the routine symbol
33816 directly as the program is not yet running. The solution is to break
33817 on the proper line (break in @file{ada_dll.adb} line 45).
33818
33819 @item Start the program
33820
33821 @smallexample
33822 (gdb) run
33823 @end smallexample
33824
33825 @end enumerate
33826 @end ignore
33827
33828 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
33829 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
33830
33831 @menu
33832 * Debugging the DLL Directly::
33833 * Attaching to a Running Process::
33834 @end menu
33835
33836 @noindent
33837 In this case things are slightly more complex because it is not possible to
33838 start the main program and then break at the beginning to load the DLL and the
33839 associated DLL debugging information. It is not possible to break at the
33840 beginning of the program because there is no @code{GDB} debugging information,
33841 and therefore there is no direct way of getting initial control. This
33842 section addresses this issue by describing some methods that can be used
33843 to break somewhere in the DLL to debug it.
33844
33845 @noindent
33846 First suppose that the main procedure is named @code{main} (this is for
33847 example some C code built with Microsoft Visual C) and that there is a
33848 DLL named @code{test.dll} containing an Ada entry point named
33849 @code{ada_dll}.
33850
33851 @noindent
33852 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
33853 been built with debugging information (see GNAT -g option).
33854
33855 @node Debugging the DLL Directly
33856 @subsubsection Debugging the DLL Directly
33857
33858 @enumerate 1
33859 @item
33860 Find out the executable starting address
33861
33862 @smallexample
33863 $ objdump --file-header main.exe
33864 @end smallexample
33865
33866 The starting address is reported on the last line. For example:
33867
33868 @smallexample
33869 main.exe:     file format pei-i386
33870 architecture: i386, flags 0x0000010a:
33871 EXEC_P, HAS_DEBUG, D_PAGED
33872 start address 0x00401010
33873 @end smallexample
33874
33875 @item
33876 Launch the debugger on the executable.
33877
33878 @smallexample
33879 $ gdb main.exe
33880 @end smallexample
33881
33882 @item
33883 Set a breakpoint at the starting address, and launch the program.
33884
33885 @smallexample
33886 $ (gdb) break *0x00401010
33887 $ (gdb) run
33888 @end smallexample
33889
33890 The program will stop at the given address.
33891
33892 @item
33893 Set a breakpoint on a DLL subroutine.
33894
33895 @smallexample
33896 (gdb) break ada_dll.adb:45
33897 @end smallexample
33898
33899 Or if you want to break using a symbol on the DLL, you need first to
33900 select the Ada language (language used by the DLL).
33901
33902 @smallexample
33903 (gdb) set language ada
33904 (gdb) break ada_dll
33905 @end smallexample
33906
33907 @item
33908 Continue the program.
33909
33910 @smallexample
33911 (gdb) cont
33912 @end smallexample
33913
33914 @noindent
33915 This will run the program until it reaches the breakpoint that has been
33916 set. From that point you can use the standard way to debug a program
33917 as described in (@pxref{Running and Debugging Ada Programs}).
33918
33919 @end enumerate
33920
33921 @noindent
33922 It is also possible to debug the DLL by attaching to a running process.
33923
33924 @node Attaching to a Running Process
33925 @subsubsection Attaching to a Running Process
33926 @cindex DLL debugging, attach to process
33927
33928 @noindent
33929 With @code{GDB} it is always possible to debug a running process by
33930 attaching to it. It is possible to debug a DLL this way. The limitation
33931 of this approach is that the DLL must run long enough to perform the
33932 attach operation. It may be useful for instance to insert a time wasting
33933 loop in the code of the DLL to meet this criterion.
33934
33935 @enumerate 1
33936
33937 @item Launch the main program @file{main.exe}.
33938
33939 @smallexample
33940 $ main
33941 @end smallexample
33942
33943 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
33944 that the process PID for @file{main.exe} is 208.
33945
33946 @item Launch gdb.
33947
33948 @smallexample
33949 $ gdb
33950 @end smallexample
33951
33952 @item Attach to the running process to be debugged.
33953
33954 @smallexample
33955 (gdb) attach 208
33956 @end smallexample
33957
33958 @item Load the process debugging information.
33959
33960 @smallexample
33961 (gdb) symbol-file main.exe
33962 @end smallexample
33963
33964 @item Break somewhere in the DLL.
33965
33966 @smallexample
33967 (gdb) break ada_dll
33968 @end smallexample
33969
33970 @item Continue process execution.
33971
33972 @smallexample
33973 (gdb) cont
33974 @end smallexample
33975
33976 @end enumerate
33977
33978 @noindent
33979 This last step will resume the process execution, and stop at
33980 the breakpoint we have set. From there you can use the standard
33981 approach to debug a program as described in
33982 (@pxref{Running and Debugging Ada Programs}).
33983
33984 @node Setting Stack Size from gnatlink
33985 @section Setting Stack Size from @command{gnatlink}
33986
33987 @noindent
33988 It is possible to specify the program stack size at link time. On modern
33989 versions of Windows, starting with XP, this is mostly useful to set the size of
33990 the main stack (environment task). The other task stacks are set with pragma
33991 Storage_Size or with the @command{gnatbind -d} command.
33992
33993 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
33994 reserve size of individual tasks, the link-time stack size applies to all
33995 tasks, and pragma Storage_Size has no effect.
33996 In particular, Stack Overflow checks are made against this
33997 link-time specified size.
33998
33999 This setting can be done with
34000 @command{gnatlink} using either:
34001
34002 @itemize @bullet
34003
34004 @item using @option{-Xlinker} linker option
34005
34006 @smallexample
34007 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
34008 @end smallexample
34009
34010 This sets the stack reserve size to 0x10000 bytes and the stack commit
34011 size to 0x1000 bytes.
34012
34013 @item using @option{-Wl} linker option
34014
34015 @smallexample
34016 $ gnatlink hello -Wl,--stack=0x1000000
34017 @end smallexample
34018
34019 This sets the stack reserve size to 0x1000000 bytes. Note that with
34020 @option{-Wl} option it is not possible to set the stack commit size
34021 because the coma is a separator for this option.
34022
34023 @end itemize
34024
34025 @node Setting Heap Size from gnatlink
34026 @section Setting Heap Size from @command{gnatlink}
34027
34028 @noindent
34029 Under Windows systems, it is possible to specify the program heap size from
34030 @command{gnatlink} using either:
34031
34032 @itemize @bullet
34033
34034 @item using @option{-Xlinker} linker option
34035
34036 @smallexample
34037 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
34038 @end smallexample
34039
34040 This sets the heap reserve size to 0x10000 bytes and the heap commit
34041 size to 0x1000 bytes.
34042
34043 @item using @option{-Wl} linker option
34044
34045 @smallexample
34046 $ gnatlink hello -Wl,--heap=0x1000000
34047 @end smallexample
34048
34049 This sets the heap reserve size to 0x1000000 bytes. Note that with
34050 @option{-Wl} option it is not possible to set the heap commit size
34051 because the coma is a separator for this option.
34052
34053 @end itemize
34054
34055 @end ifset
34056
34057 @c **********************************
34058 @c * GNU Free Documentation License *
34059 @c **********************************
34060 @include fdl.texi
34061 @c GNU Free Documentation License
34062
34063 @node Index,,GNU Free Documentation License, Top
34064 @unnumbered Index
34065
34066 @printindex cp
34067
34068 @contents
34069 @c Put table of contents at end, otherwise it precedes the "title page" in
34070 @c the .txt version
34071 @c Edit the pdf file to move the contents to the beginning, after the title
34072 @c page
34073
34074 @bye