OSDN Git Service

2010-06-17 Ed Schonberg <schonberg@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, and this directory must be writable,
14052 different from the project's object directory and from any source directory
14053 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}. The directory specified by @code{Library_ALI_Dir}
14077 must be writable and different from the project's object directory and from
14078 any source directory in the project tree.
14079
14080 The @code{Library_Version} attribute has a string value whose interpretation
14081 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
14082 used only for dynamic/relocatable libraries as the internal name of the
14083 library (the @code{"soname"}). If the library file name (built from the
14084 @code{Library_Name}) is different from the @code{Library_Version}, then the
14085 library file will be a symbolic link to the actual file whose name will be
14086 @code{Library_Version}.
14087
14088 Example (on Unix):
14089
14090 @smallexample @c projectfile
14091 @group
14092 project Plib is
14093
14094    Version := "1";
14095
14096    for Library_Dir use "lib_dir";
14097    for Library_Name use "dummy";
14098    for Library_Kind use "relocatable";
14099    for Library_Version use "libdummy.so." & Version;
14100
14101 end Plib;
14102 @end group
14103 @end smallexample
14104
14105 @noindent
14106 Directory @file{lib_dir} will contain the internal library file whose name
14107 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
14108 @file{libdummy.so.1}.
14109
14110 When @command{gnatmake} detects that a project file
14111 is a library project file, it will check all immediate sources of the project
14112 and rebuild the library if any of the sources have been recompiled.
14113
14114 Standard project files can import library project files. In such cases,
14115 the libraries will only be rebuilt if some of its sources are recompiled
14116 because they are in the closure of some other source in an importing project.
14117 Sources of the library project files that are not in such a closure will
14118 not be checked, unless the full library is checked, because one of its sources
14119 needs to be recompiled.
14120
14121 For instance, assume the project file @code{A} imports the library project file
14122 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
14123 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
14124 @file{l2.ads}, @file{l2.adb}.
14125
14126 If @file{l1.adb} has been modified, then the library associated with @code{L}
14127 will be rebuilt when compiling all the immediate sources of @code{A} only
14128 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
14129 @code{"with L1;"}.
14130
14131 To be sure that all the sources in the library associated with @code{L} are
14132 up to date, and that all the sources of project @code{A} are also up to date,
14133 the following two commands needs to be used:
14134
14135 @smallexample
14136 gnatmake -Pl.gpr
14137 gnatmake -Pa.gpr
14138 @end smallexample
14139
14140 When a library is built or rebuilt, an attempt is made first to delete all
14141 files in the library directory.
14142 All @file{ALI} files will also be copied from the object directory to the
14143 library directory. To build executables, @command{gnatmake} will use the
14144 library rather than the individual object files.
14145
14146 @ifclear vms
14147 It is also possible to create library project files for third-party libraries
14148 that are precompiled and cannot be compiled locally thanks to the
14149 @code{externally_built} attribute. (See @ref{Installing a library}).
14150 @end ifclear
14151
14152 @c *******************************
14153 @c * Stand-alone Library Projects *
14154 @c *******************************
14155
14156 @node Stand-alone Library Projects
14157 @section Stand-alone Library Projects
14158
14159 @noindent
14160 A Stand-alone Library is a library that contains the necessary code to
14161 elaborate the Ada units that are included in the library. A Stand-alone
14162 Library is suitable to be used in an executable when the main is not
14163 in Ada. However, Stand-alone Libraries may also be used with an Ada main
14164 subprogram.
14165
14166 A Stand-alone Library Project is a Library Project where the library is
14167 a Stand-alone Library.
14168
14169 To be a Stand-alone Library Project, in addition to the two attributes
14170 that make a project a Library Project (@code{Library_Name} and
14171 @code{Library_Dir}, see @ref{Library Projects}), the attribute
14172 @code{Library_Interface} must be defined.
14173
14174 @smallexample @c projectfile
14175 @group
14176    for Library_Dir use "lib_dir";
14177    for Library_Name use "dummy";
14178    for Library_Interface use ("int1", "int1.child");
14179 @end group
14180 @end smallexample
14181
14182 Attribute @code{Library_Interface} has a nonempty string list value,
14183 each string in the list designating a unit contained in an immediate source
14184 of the project file.
14185
14186 When a Stand-alone Library is built, first the binder is invoked to build
14187 a package whose name depends on the library name
14188 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
14189 This binder-generated package includes initialization and
14190 finalization procedures whose
14191 names depend on the library name (dummyinit and dummyfinal in the example
14192 above). The object corresponding to this package is included in the library.
14193
14194 A dynamic or relocatable Stand-alone Library is automatically initialized
14195 if automatic initialization of Stand-alone Libraries is supported on the
14196 platform and if attribute @code{Library_Auto_Init} is not specified or
14197 is specified with the value "true". A static Stand-alone Library is never
14198 automatically initialized.
14199
14200 Single string attribute @code{Library_Auto_Init} may be specified with only
14201 two possible values: "false" or "true" (case-insensitive). Specifying
14202 "false" for attribute @code{Library_Auto_Init} will prevent automatic
14203 initialization of dynamic or relocatable libraries.
14204
14205 When a non-automatically initialized Stand-alone Library is used
14206 in an executable, its initialization procedure must be called before
14207 any service of the library is used.
14208 When the main subprogram is in Ada, it may mean that the initialization
14209 procedure has to be called during elaboration of another package.
14210
14211 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
14212 (those that are listed in attribute @code{Library_Interface}) are copied to
14213 the Library Directory. As a consequence, only the Interface Units may be
14214 imported from Ada units outside of the library. If other units are imported,
14215 the binding phase will fail.
14216
14217 When a Stand-Alone Library is bound, the switches that are specified in
14218 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
14219 used in the call to @command{gnatbind}.
14220
14221 The string list attribute @code{Library_Options} may be used to specified
14222 additional switches to the call to @command{gcc} to link the library.
14223
14224 The attribute @code{Library_Src_Dir}, may be specified for a
14225 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
14226 single string value. Its value must be the path (absolute or relative to the
14227 project directory) of an existing directory. This directory cannot be the
14228 object directory or one of the source directories, but it can be the same as
14229 the library directory. The sources of the Interface
14230 Units of the library, necessary to an Ada client of the library, will be
14231 copied to the designated directory, called Interface Copy directory.
14232 These sources includes the specs of the Interface Units, but they may also
14233 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
14234 are used, or when there is a generic units in the spec. Before the sources
14235 are copied to the Interface Copy directory, an attempt is made to delete all
14236 files in the Interface Copy directory.
14237
14238 @c *************************************
14239 @c * Switches Related to Project Files *
14240 @c *************************************
14241 @node Switches Related to Project Files
14242 @section Switches Related to Project Files
14243
14244 @noindent
14245 The following switches are used by GNAT tools that support project files:
14246
14247 @table @option
14248
14249 @item ^-P^/PROJECT_FILE=^@var{project}
14250 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
14251 Indicates the name of a project file. This project file will be parsed with
14252 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
14253 if any, and using the external references indicated
14254 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
14255 @ifclear vms
14256 There may zero, one or more spaces between @option{-P} and @var{project}.
14257 @end ifclear
14258
14259 @noindent
14260 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
14261
14262 @noindent
14263 Since the Project Manager parses the project file only after all the switches
14264 on the command line are checked, the order of the switches
14265 @option{^-P^/PROJECT_FILE^},
14266 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
14267 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
14268
14269 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
14270 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
14271 Indicates that external variable @var{name} has the value @var{value}.
14272 The Project Manager will use this value for occurrences of
14273 @code{external(name)} when parsing the project file.
14274
14275 @ifclear vms
14276 @noindent
14277 If @var{name} or @var{value} includes a space, then @var{name=value} should be
14278 put between quotes.
14279 @smallexample
14280   -XOS=NT
14281   -X"user=John Doe"
14282 @end smallexample
14283 @end ifclear
14284
14285 @noindent
14286 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
14287 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
14288 @var{name}, only the last one is used.
14289
14290 @noindent
14291 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
14292 takes precedence over the value of the same name in the environment.
14293
14294 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
14295 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
14296 Indicates the verbosity of the parsing of GNAT project files.
14297
14298 @ifclear vms
14299 @option{-vP0} means Default;
14300 @option{-vP1} means Medium;
14301 @option{-vP2} means High.
14302 @end ifclear
14303
14304 @ifset vms
14305 There are three possible options for this qualifier: DEFAULT, MEDIUM and
14306 HIGH.
14307 @end ifset
14308
14309 @noindent
14310 The default is ^Default^DEFAULT^: no output for syntactically correct
14311 project files.
14312 @noindent
14313 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
14314 only the last one is used.
14315
14316 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
14317 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
14318 Add directory <dir> at the beginning of the project search path, in order,
14319 after the current working directory.
14320
14321 @ifclear vms
14322 @item -eL
14323 @cindex @option{-eL} (any project-aware tool)
14324 Follow all symbolic links when processing project files.
14325 @end ifclear
14326
14327 @item ^--subdirs^/SUBDIRS^=<subdir>
14328 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
14329 This switch is recognized by gnatmake and gnatclean. It indicate that the real
14330 directories (except the source directories) are the subdirectories <subdir>
14331 of the directories specified in the project files. This applies in particular
14332 to object directories, library directories and exec directories. If the
14333 subdirectories do not exist, they are created automatically.
14334
14335 @end table
14336
14337 @c **********************************
14338 @c * Tools Supporting Project Files *
14339 @c **********************************
14340
14341 @node  Tools Supporting Project Files
14342 @section Tools Supporting Project Files
14343
14344 @menu
14345 * gnatmake and Project Files::
14346 * The GNAT Driver and Project Files::
14347 @end menu
14348
14349 @node gnatmake and Project Files
14350 @subsection gnatmake and Project Files
14351
14352 @noindent
14353 This section covers several topics related to @command{gnatmake} and
14354 project files: defining ^switches^switches^ for @command{gnatmake}
14355 and for the tools that it invokes; specifying configuration pragmas;
14356 the use of the @code{Main} attribute; building and rebuilding library project
14357 files.
14358
14359 @menu
14360 * ^Switches^Switches^ and Project Files::
14361 * Specifying Configuration Pragmas::
14362 * Project Files and Main Subprograms::
14363 * Library Project Files::
14364 @end menu
14365
14366 @node ^Switches^Switches^ and Project Files
14367 @subsubsection ^Switches^Switches^ and Project Files
14368
14369 @ifset vms
14370 It is not currently possible to specify VMS style qualifiers in the project
14371 files; only Unix style ^switches^switches^ may be specified.
14372 @end ifset
14373
14374 @noindent
14375 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
14376 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
14377 attribute, a @code{^Switches^Switches^} attribute, or both;
14378 as their names imply, these ^switch^switch^-related
14379 attributes affect the ^switches^switches^ that are used for each of these GNAT
14380 components when
14381 @command{gnatmake} is invoked.  As will be explained below, these
14382 component-specific ^switches^switches^ precede
14383 the ^switches^switches^ provided on the @command{gnatmake} command line.
14384
14385 The @code{^Default_Switches^Default_Switches^} attribute is an associative
14386 array indexed by language name (case insensitive) whose value is a string list.
14387 For example:
14388
14389 @smallexample @c projectfile
14390 @group
14391 package Compiler is
14392   for ^Default_Switches^Default_Switches^ ("Ada")
14393       use ("^-gnaty^-gnaty^",
14394            "^-v^-v^");
14395 end Compiler;
14396 @end group
14397 @end smallexample
14398
14399 @noindent
14400 The @code{^Switches^Switches^} attribute is also an associative array,
14401 indexed by a file name (which may or may not be case sensitive, depending
14402 on the operating system) whose value is a string list.  For example:
14403
14404 @smallexample @c projectfile
14405 @group
14406 package Builder is
14407    for ^Switches^Switches^ ("main1.adb")
14408        use ("^-O2^-O2^");
14409    for ^Switches^Switches^ ("main2.adb")
14410        use ("^-g^-g^");
14411 end Builder;
14412 @end group
14413 @end smallexample
14414
14415 @noindent
14416 For the @code{Builder} package, the file names must designate source files
14417 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
14418 file names must designate @file{ALI} or source files for main subprograms.
14419 In each case just the file name without an explicit extension is acceptable.
14420
14421 For each tool used in a program build (@command{gnatmake}, the compiler, the
14422 binder, and the linker), the corresponding package @dfn{contributes} a set of
14423 ^switches^switches^ for each file on which the tool is invoked, based on the
14424 ^switch^switch^-related attributes defined in the package.
14425 In particular, the ^switches^switches^
14426 that each of these packages contributes for a given file @var{f} comprise:
14427
14428 @itemize @bullet
14429 @item
14430 the value of attribute @code{^Switches^Switches^ (@var{f})},
14431 if it is specified in the package for the given file,
14432 @item
14433 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
14434 if it is specified in the package.
14435 @end itemize
14436
14437 @noindent
14438 If neither of these attributes is defined in the package, then the package does
14439 not contribute any ^switches^switches^ for the given file.
14440
14441 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
14442 two sets, in the following order: those contributed for the file
14443 by the @code{Builder} package;
14444 and the switches passed on the command line.
14445
14446 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
14447 the ^switches^switches^ passed to the tool comprise three sets,
14448 in the following order:
14449
14450 @enumerate
14451 @item
14452 the applicable ^switches^switches^ contributed for the file
14453 by the @code{Builder} package in the project file supplied on the command line;
14454
14455 @item
14456 those contributed for the file by the package (in the relevant project file --
14457 see below) corresponding to the tool; and
14458
14459 @item
14460 the applicable switches passed on the command line.
14461 @end enumerate
14462
14463 @noindent
14464 The term @emph{applicable ^switches^switches^} reflects the fact that
14465 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
14466 tools, depending on the individual ^switch^switch^.
14467
14468 @command{gnatmake} may invoke the compiler on source files from different
14469 projects. The Project Manager will use the appropriate project file to
14470 determine the @code{Compiler} package for each source file being compiled.
14471 Likewise for the @code{Binder} and @code{Linker} packages.
14472
14473 As an example, consider the following package in a project file:
14474
14475 @smallexample @c projectfile
14476 @group
14477 project Proj1 is
14478    package Compiler is
14479       for ^Default_Switches^Default_Switches^ ("Ada")
14480           use ("^-g^-g^");
14481       for ^Switches^Switches^ ("a.adb")
14482           use ("^-O1^-O1^");
14483       for ^Switches^Switches^ ("b.adb")
14484           use ("^-O2^-O2^",
14485                "^-gnaty^-gnaty^");
14486    end Compiler;
14487 end Proj1;
14488 @end group
14489 @end smallexample
14490
14491 @noindent
14492 If @command{gnatmake} is invoked with this project file, and it needs to
14493 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
14494 @file{a.adb} will be compiled with the ^switch^switch^
14495 @option{^-O1^-O1^},
14496 @file{b.adb} with ^switches^switches^
14497 @option{^-O2^-O2^}
14498 and @option{^-gnaty^-gnaty^},
14499 and @file{c.adb} with @option{^-g^-g^}.
14500
14501 The following example illustrates the ordering of the ^switches^switches^
14502 contributed by different packages:
14503
14504 @smallexample @c projectfile
14505 @group
14506 project Proj2 is
14507    package Builder is
14508       for ^Switches^Switches^ ("main.adb")
14509           use ("^-g^-g^",
14510                "^-O1^-)1^",
14511                "^-f^-f^");
14512    end Builder;
14513 @end group
14514
14515 @group
14516    package Compiler is
14517       for ^Switches^Switches^ ("main.adb")
14518           use ("^-O2^-O2^");
14519    end Compiler;
14520 end Proj2;
14521 @end group
14522 @end smallexample
14523
14524 @noindent
14525 If you issue the command:
14526
14527 @smallexample
14528     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
14529 @end smallexample
14530
14531 @noindent
14532 then the compiler will be invoked on @file{main.adb} with the following
14533 sequence of ^switches^switches^
14534
14535 @smallexample
14536    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
14537 @end smallexample
14538
14539 with the last @option{^-O^-O^}
14540 ^switch^switch^ having precedence over the earlier ones;
14541 several other ^switches^switches^
14542 (such as @option{^-c^-c^}) are added implicitly.
14543
14544 The ^switches^switches^
14545 @option{^-g^-g^}
14546 and @option{^-O1^-O1^} are contributed by package
14547 @code{Builder},  @option{^-O2^-O2^} is contributed
14548 by the package @code{Compiler}
14549 and @option{^-O0^-O0^} comes from the command line.
14550
14551 The @option{^-g^-g^}
14552 ^switch^switch^ will also be passed in the invocation of
14553 @command{Gnatlink.}
14554
14555 A final example illustrates switch contributions from packages in different
14556 project files:
14557
14558 @smallexample @c projectfile
14559 @group
14560 project Proj3 is
14561    for Source_Files use ("pack.ads", "pack.adb");
14562    package Compiler is
14563       for ^Default_Switches^Default_Switches^ ("Ada")
14564           use ("^-gnata^-gnata^");
14565    end Compiler;
14566 end Proj3;
14567 @end group
14568
14569 @group
14570 with "Proj3";
14571 project Proj4 is
14572    for Source_Files use ("foo_main.adb", "bar_main.adb");
14573    package Builder is
14574       for ^Switches^Switches^ ("foo_main.adb")
14575           use ("^-s^-s^",
14576                "^-g^-g^");
14577    end Builder;
14578 end Proj4;
14579 @end group
14580
14581 @group
14582 -- Ada source file:
14583 with Pack;
14584 procedure Foo_Main is
14585    @dots{}
14586 end Foo_Main;
14587 @end group
14588 @end smallexample
14589
14590 If the command is
14591 @smallexample
14592 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
14593 @end smallexample
14594
14595 @noindent
14596 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
14597 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
14598 @option{^-gnato^-gnato^} (passed on the command line).
14599 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
14600 are @option{^-g^-g^} from @code{Proj4.Builder},
14601 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
14602 and @option{^-gnato^-gnato^} from the command line.
14603
14604 @noindent
14605 When using @command{gnatmake} with project files, some ^switches^switches^ or
14606 arguments may be expressed as relative paths. As the working directory where
14607 compilation occurs may change, these relative paths are converted to absolute
14608 paths. For the ^switches^switches^ found in a project file, the relative paths
14609 are relative to the project file directory, for the switches on the command
14610 line, they are relative to the directory where @command{gnatmake} is invoked.
14611 The ^switches^switches^ for which this occurs are:
14612 ^-I^-I^,
14613 ^-A^-A^,
14614 ^-L^-L^,
14615 ^-aO^-aO^,
14616 ^-aL^-aL^,
14617 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
14618 ^switch^switch^
14619 ^-o^-o^, object files specified in package @code{Linker} or after
14620 -largs on the command line). The exception to this rule is the ^switch^switch^
14621 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
14622
14623 @node Specifying Configuration Pragmas
14624 @subsubsection Specifying Configuration Pragmas
14625
14626 When using @command{gnatmake} with project files, if there exists a file
14627 @file{gnat.adc} that contains configuration pragmas, this file will be
14628 ignored.
14629
14630 Configuration pragmas can be defined by means of the following attributes in
14631 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
14632 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
14633
14634 Both these attributes are single string attributes. Their values is the path
14635 name of a file containing configuration pragmas. If a path name is relative,
14636 then it is relative to the project directory of the project file where the
14637 attribute is defined.
14638
14639 When compiling a source, the configuration pragmas used are, in order,
14640 those listed in the file designated by attribute
14641 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
14642 project file, if it is specified, and those listed in the file designated by
14643 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
14644 the project file of the source, if it exists.
14645
14646 @node Project Files and Main Subprograms
14647 @subsubsection Project Files and Main Subprograms
14648
14649 @noindent
14650 When using a project file, you can invoke @command{gnatmake}
14651 with one or several main subprograms, by specifying their source files on the
14652 command line.
14653
14654 @smallexample
14655     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
14656 @end smallexample
14657
14658 @noindent
14659 Each of these needs to be a source file of the same project, except
14660 when the switch ^-u^/UNIQUE^ is used.
14661
14662 @noindent
14663 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
14664 same project, one of the project in the tree rooted at the project specified
14665 on the command line. The package @code{Builder} of this common project, the
14666 "main project" is the one that is considered by @command{gnatmake}.
14667
14668 @noindent
14669 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
14670 imported directly or indirectly by the project specified on the command line.
14671 Note that if such a source file is not part of the project specified on the
14672 command line, the ^switches^switches^ found in package @code{Builder} of the
14673 project specified on the command line, if any, that are transmitted
14674 to the compiler will still be used, not those found in the project file of
14675 the source file.
14676
14677 @noindent
14678 When using a project file, you can also invoke @command{gnatmake} without
14679 explicitly specifying any main, and the effect depends on whether you have
14680 defined the @code{Main} attribute.  This attribute has a string list value,
14681 where each element in the list is the name of a source file (the file
14682 extension is optional) that contains a unit that can be a main subprogram.
14683
14684 If the @code{Main} attribute is defined in a project file as a non-empty
14685 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
14686 line, then invoking @command{gnatmake} with this project file but without any
14687 main on the command line is equivalent to invoking @command{gnatmake} with all
14688 the file names in the @code{Main} attribute on the command line.
14689
14690 Example:
14691 @smallexample @c projectfile
14692 @group
14693    project Prj is
14694       for Main use ("main1", "main2", "main3");
14695    end Prj;
14696 @end group
14697 @end smallexample
14698
14699 @noindent
14700 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
14701 is equivalent to
14702 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
14703
14704 When the project attribute @code{Main} is not specified, or is specified
14705 as an empty string list, or when the switch @option{-u} is used on the command
14706 line, then invoking @command{gnatmake} with no main on the command line will
14707 result in all immediate sources of the project file being checked, and
14708 potentially recompiled. Depending on the presence of the switch @option{-u},
14709 sources from other project files on which the immediate sources of the main
14710 project file depend are also checked and potentially recompiled. In other
14711 words, the @option{-u} switch is applied to all of the immediate sources of the
14712 main project file.
14713
14714 When no main is specified on the command line and attribute @code{Main} exists
14715 and includes several mains, or when several mains are specified on the
14716 command line, the default ^switches^switches^ in package @code{Builder} will
14717 be used for all mains, even if there are specific ^switches^switches^
14718 specified for one or several mains.
14719
14720 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
14721 the specific ^switches^switches^ for each main, if they are specified.
14722
14723 @node Library Project Files
14724 @subsubsection Library Project Files
14725
14726 @noindent
14727 When @command{gnatmake} is invoked with a main project file that is a library
14728 project file, it is not allowed to specify one or more mains on the command
14729 line.
14730
14731 @noindent
14732 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
14733 ^-l^/ACTION=LINK^ have special meanings.
14734
14735 @itemize @bullet
14736 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
14737 to @command{gnatmake} that @command{gnatbind} should be invoked for the
14738 library.
14739
14740 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
14741 to @command{gnatmake} that the binder generated file should be compiled
14742 (in the case of a stand-alone library) and that the library should be built.
14743
14744 @end itemize
14745
14746 @node The GNAT Driver and Project Files
14747 @subsection The GNAT Driver and Project Files
14748
14749 @noindent
14750 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
14751 can benefit from project files:
14752 (@command{^gnatbind^gnatbind^},
14753 @command{^gnatcheck^gnatcheck^},
14754 @command{^gnatclean^gnatclean^},
14755 @command{^gnatelim^gnatelim^},
14756 @command{^gnatfind^gnatfind^},
14757 @command{^gnatlink^gnatlink^},
14758 @command{^gnatls^gnatls^},
14759 @command{^gnatmetric^gnatmetric^},
14760 @command{^gnatpp^gnatpp^},
14761 @command{^gnatstub^gnatstub^},
14762 and @command{^gnatxref^gnatxref^}). However, none of these tools can be invoked
14763 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
14764 They must be invoked through the @command{gnat} driver.
14765
14766 The @command{gnat} driver is a wrapper that accepts a number of commands and
14767 calls the corresponding tool. It was designed initially for VMS platforms (to
14768 convert VMS qualifiers to Unix-style switches), but it is now available on all
14769 GNAT platforms.
14770
14771 On non-VMS platforms, the @command{gnat} driver accepts the following commands
14772 (case insensitive):
14773
14774 @itemize @bullet
14775 @item
14776 BIND to invoke @command{^gnatbind^gnatbind^}
14777 @item
14778 CHOP to invoke @command{^gnatchop^gnatchop^}
14779 @item
14780 CLEAN to invoke @command{^gnatclean^gnatclean^}
14781 @item
14782 COMP or COMPILE to invoke the compiler
14783 @item
14784 ELIM to invoke @command{^gnatelim^gnatelim^}
14785 @item
14786 FIND to invoke @command{^gnatfind^gnatfind^}
14787 @item
14788 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
14789 @item
14790 LINK to invoke @command{^gnatlink^gnatlink^}
14791 @item
14792 LS or LIST to invoke @command{^gnatls^gnatls^}
14793 @item
14794 MAKE to invoke @command{^gnatmake^gnatmake^}
14795 @item
14796 NAME to invoke @command{^gnatname^gnatname^}
14797 @item
14798 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
14799 @item
14800 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
14801 @item
14802 METRIC to invoke @command{^gnatmetric^gnatmetric^}
14803 @item
14804 STUB to invoke @command{^gnatstub^gnatstub^}
14805 @item
14806 XREF to invoke @command{^gnatxref^gnatxref^}
14807 @end itemize
14808
14809 @noindent
14810 (note that the compiler is invoked using the command
14811 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
14812
14813 @noindent
14814 On non-VMS platforms, between @command{gnat} and the command, two
14815 special switches may be used:
14816
14817 @itemize @bullet
14818 @item
14819 @command{-v} to display the invocation of the tool.
14820 @item
14821 @command{-dn} to prevent the @command{gnat} driver from removing
14822 the temporary files it has created. These temporary files are
14823 configuration files and temporary file list files.
14824 @end itemize
14825
14826 @noindent
14827 The command may be followed by switches and arguments for the invoked
14828 tool.
14829
14830 @smallexample
14831   gnat bind -C main.ali
14832   gnat ls -a main
14833   gnat chop foo.txt
14834 @end smallexample
14835
14836 @noindent
14837 Switches may also be put in text files, one switch per line, and the text
14838 files may be specified with their path name preceded by '@@'.
14839
14840 @smallexample
14841    gnat bind @@args.txt main.ali
14842 @end smallexample
14843
14844 @noindent
14845 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
14846 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
14847 (@option{^-P^/PROJECT_FILE^},
14848 @option{^-X^/EXTERNAL_REFERENCE^} and
14849 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
14850 the switches of the invoking tool.
14851
14852 @noindent
14853 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
14854 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
14855 the immediate sources of the specified project file.
14856
14857 @noindent
14858 When GNAT METRIC is used with a project file, but with no source
14859 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
14860 with all the immediate sources of the specified project file and with
14861 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
14862 of the project.
14863
14864 @noindent
14865 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
14866 a project file, no source is specified on the command line and
14867 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
14868 the underlying tool (^gnatpp^gnatpp^ or
14869 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
14870 not only for the immediate sources of the main project.
14871 @ifclear vms
14872 (-U stands for Universal or Union of the project files of the project tree)
14873 @end ifclear
14874
14875 @noindent
14876 For each of the following commands, there is optionally a corresponding
14877 package in the main project.
14878
14879 @itemize @bullet
14880 @item
14881 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
14882
14883 @item
14884 package @code{Check} for command CHECK (invoking
14885 @code{^gnatcheck^gnatcheck^})
14886
14887 @item
14888 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
14889
14890 @item
14891 package @code{Cross_Reference} for command XREF (invoking
14892 @code{^gnatxref^gnatxref^})
14893
14894 @item
14895 package @code{Eliminate} for command ELIM (invoking
14896 @code{^gnatelim^gnatelim^})
14897
14898 @item
14899 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
14900
14901 @item
14902 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
14903
14904 @item
14905 package @code{Gnatstub} for command STUB
14906 (invoking @code{^gnatstub^gnatstub^})
14907
14908 @item
14909 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
14910
14911 @item
14912 package @code{Check} for command CHECK
14913 (invoking @code{^gnatcheck^gnatcheck^})
14914
14915 @item
14916 package @code{Metrics} for command METRIC
14917 (invoking @code{^gnatmetric^gnatmetric^})
14918
14919 @item
14920 package @code{Pretty_Printer} for command PP or PRETTY
14921 (invoking @code{^gnatpp^gnatpp^})
14922
14923 @end itemize
14924
14925 @noindent
14926 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
14927 a simple variable with a string list value. It contains ^switches^switches^
14928 for the invocation of @code{^gnatls^gnatls^}.
14929
14930 @smallexample @c projectfile
14931 @group
14932 project Proj1 is
14933    package gnatls is
14934       for ^Switches^Switches^
14935           use ("^-a^-a^",
14936                "^-v^-v^");
14937    end gnatls;
14938 end Proj1;
14939 @end group
14940 @end smallexample
14941
14942 @noindent
14943 All other packages have two attribute @code{^Switches^Switches^} and
14944 @code{^Default_Switches^Default_Switches^}.
14945
14946 @noindent
14947 @code{^Switches^Switches^} is an associative array attribute, indexed by the
14948 source file name, that has a string list value: the ^switches^switches^ to be
14949 used when the tool corresponding to the package is invoked for the specific
14950 source file.
14951
14952 @noindent
14953 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
14954 indexed by  the programming language that has a string list value.
14955 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
14956 ^switches^switches^ for the invocation of the tool corresponding
14957 to the package, except if a specific @code{^Switches^Switches^} attribute
14958 is specified for the source file.
14959
14960 @smallexample @c projectfile
14961 @group
14962 project Proj is
14963
14964    for Source_Dirs use ("./**");
14965
14966    package gnatls is
14967       for ^Switches^Switches^ use
14968           ("^-a^-a^",
14969            "^-v^-v^");
14970    end gnatls;
14971 @end group
14972 @group
14973
14974    package Compiler is
14975       for ^Default_Switches^Default_Switches^ ("Ada")
14976           use ("^-gnatv^-gnatv^",
14977                "^-gnatwa^-gnatwa^");
14978    end Binder;
14979 @end group
14980 @group
14981
14982    package Binder is
14983       for ^Default_Switches^Default_Switches^ ("Ada")
14984           use ("^-C^-C^",
14985                "^-e^-e^");
14986    end Binder;
14987 @end group
14988 @group
14989
14990    package Linker is
14991       for ^Default_Switches^Default_Switches^ ("Ada")
14992           use ("^-C^-C^");
14993       for ^Switches^Switches^ ("main.adb")
14994           use ("^-C^-C^",
14995                "^-v^-v^",
14996                "^-v^-v^");
14997    end Linker;
14998 @end group
14999 @group
15000
15001    package Finder is
15002       for ^Default_Switches^Default_Switches^ ("Ada")
15003            use ("^-a^-a^",
15004                 "^-f^-f^");
15005    end Finder;
15006 @end group
15007 @group
15008
15009    package Cross_Reference is
15010       for ^Default_Switches^Default_Switches^ ("Ada")
15011           use ("^-a^-a^",
15012                "^-f^-f^",
15013                "^-d^-d^",
15014                "^-u^-u^");
15015    end Cross_Reference;
15016 end Proj;
15017 @end group
15018 @end smallexample
15019
15020 @noindent
15021 With the above project file, commands such as
15022
15023 @smallexample
15024    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
15025    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
15026    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
15027    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
15028    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
15029 @end smallexample
15030
15031 @noindent
15032 will set up the environment properly and invoke the tool with the switches
15033 found in the package corresponding to the tool:
15034 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
15035 except @code{^Switches^Switches^ ("main.adb")}
15036 for @code{^gnatlink^gnatlink^}.
15037 It is also possible to invoke some of the tools,
15038 (@code{^gnatcheck^gnatcheck^},
15039 @code{^gnatmetric^gnatmetric^},
15040 and @code{^gnatpp^gnatpp^})
15041 on a set of project units thanks to the combination of the switches
15042 @option{-P}, @option{-U} and possibly the main unit when one is interested
15043 in its closure. For instance,
15044 @smallexample
15045 gnat metric -Pproj
15046 @end smallexample
15047 will compute the metrics for all the immediate units of project
15048 @code{proj}.
15049 @smallexample
15050 gnat metric -Pproj -U
15051 @end smallexample
15052 will compute the metrics for all the units of the closure of projects
15053 rooted at @code{proj}.
15054 @smallexample
15055 gnat metric -Pproj -U main_unit
15056 @end smallexample
15057 will compute the metrics for the closure of units rooted at
15058 @code{main_unit}. This last possibility relies implicitly
15059 on @command{gnatbind}'s option @option{-R}. But if the argument files for the
15060 tool invoked by the the @command{gnat} driver are explicitly  specified
15061 either directly or through the tool @option{-files} option, then the tool
15062 is called only for these explicitly specified files.
15063
15064 @c **********************
15065 @node An Extended Example
15066 @section An Extended Example
15067
15068 @noindent
15069 Suppose that we have two programs, @var{prog1} and @var{prog2},
15070 whose sources are in corresponding directories. We would like
15071 to build them with a single @command{gnatmake} command, and we want to place
15072 their object files into @file{build} subdirectories of the source directories.
15073 Furthermore, we want to have to have two separate subdirectories
15074 in @file{build}  -- @file{release} and @file{debug} -- which will contain
15075 the object files compiled with different set of compilation flags.
15076
15077 In other words, we have the following structure:
15078
15079 @smallexample
15080 @group
15081    main
15082      |- prog1
15083      |    |- build
15084      |         | debug
15085      |         | release
15086      |- prog2
15087           |- build
15088                | debug
15089                | release
15090 @end group
15091 @end smallexample
15092
15093 @noindent
15094 Here are the project files that we must place in a directory @file{main}
15095 to maintain this structure:
15096
15097 @enumerate
15098
15099 @item We create a @code{Common} project with a package @code{Compiler} that
15100 specifies the compilation ^switches^switches^:
15101
15102 @smallexample
15103 File "common.gpr":
15104 @group
15105 @b{project} Common @b{is}
15106
15107    @b{for} Source_Dirs @b{use} (); -- No source files
15108 @end group
15109
15110 @group
15111    @b{type} Build_Type @b{is} ("release", "debug");
15112    Build : Build_Type := External ("BUILD", "debug");
15113 @end group
15114 @group
15115    @b{package} Compiler @b{is}
15116       @b{case} Build @b{is}
15117          @b{when} "release" =>
15118            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15119                    @b{use} ("^-O2^-O2^");
15120          @b{when} "debug"   =>
15121            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
15122                    @b{use} ("^-g^-g^");
15123       @b{end case};
15124    @b{end} Compiler;
15125
15126 @b{end} Common;
15127 @end group
15128 @end smallexample
15129
15130 @item We create separate projects for the two programs:
15131
15132 @smallexample
15133 @group
15134 File "prog1.gpr":
15135
15136 @b{with} "common";
15137 @b{project} Prog1 @b{is}
15138
15139     @b{for} Source_Dirs @b{use} ("prog1");
15140     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
15141
15142     @b{package} Compiler @b{renames} Common.Compiler;
15143
15144 @b{end} Prog1;
15145 @end group
15146 @end smallexample
15147
15148 @smallexample
15149 @group
15150 File "prog2.gpr":
15151
15152 @b{with} "common";
15153 @b{project} Prog2 @b{is}
15154
15155     @b{for} Source_Dirs @b{use} ("prog2");
15156     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
15157
15158     @b{package} Compiler @b{renames} Common.Compiler;
15159
15160 @end group
15161 @b{end} Prog2;
15162 @end smallexample
15163
15164 @item We create a wrapping project @code{Main}:
15165
15166 @smallexample
15167 @group
15168 File "main.gpr":
15169
15170 @b{with} "common";
15171 @b{with} "prog1";
15172 @b{with} "prog2";
15173 @b{project} Main @b{is}
15174
15175    @b{package} Compiler @b{renames} Common.Compiler;
15176
15177 @b{end} Main;
15178 @end group
15179 @end smallexample
15180
15181 @item Finally we need to create a dummy procedure that @code{with}s (either
15182 explicitly or implicitly) all the sources of our two programs.
15183
15184 @end enumerate
15185
15186 @noindent
15187 Now we can build the programs using the command
15188
15189 @smallexample
15190    gnatmake ^-P^/PROJECT_FILE=^main dummy
15191 @end smallexample
15192
15193 @noindent
15194 for the Debug mode, or
15195
15196 @ifclear vms
15197 @smallexample
15198    gnatmake -Pmain -XBUILD=release
15199 @end smallexample
15200 @end ifclear
15201
15202 @ifset vms
15203 @smallexample
15204    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
15205 @end smallexample
15206 @end ifset
15207
15208 @noindent
15209 for the Release mode.
15210
15211 @c ********************************
15212 @c * Project File Complete Syntax *
15213 @c ********************************
15214
15215 @node Project File Complete Syntax
15216 @section Project File Complete Syntax
15217
15218 @smallexample
15219 project ::=
15220   context_clause project_declaration
15221
15222 context_clause ::=
15223   @{with_clause@}
15224
15225 with_clause ::=
15226   @b{with} path_name @{ , path_name @} ;
15227
15228 path_name ::=
15229    string_literal
15230
15231 project_declaration ::=
15232   simple_project_declaration | project_extension
15233
15234 simple_project_declaration ::=
15235   @b{project} <project_>simple_name @b{is}
15236     @{declarative_item@}
15237   @b{end} <project_>simple_name;
15238
15239 project_extension ::=
15240   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
15241     @{declarative_item@}
15242   @b{end} <project_>simple_name;
15243
15244 declarative_item ::=
15245   package_declaration |
15246   typed_string_declaration |
15247   other_declarative_item
15248
15249 package_declaration ::=
15250   package_spec | package_renaming
15251
15252 package_spec ::=
15253   @b{package} package_identifier @b{is}
15254     @{simple_declarative_item@}
15255   @b{end} package_identifier ;
15256
15257 package_identifier ::=
15258   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
15259   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
15260   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
15261
15262 package_renaming ::==
15263   @b{package} package_identifier @b{renames}
15264        <project_>simple_name.package_identifier ;
15265
15266 typed_string_declaration ::=
15267   @b{type} <typed_string_>_simple_name @b{is}
15268    ( string_literal @{, string_literal@} );
15269
15270 other_declarative_item ::=
15271   attribute_declaration |
15272   typed_variable_declaration |
15273   variable_declaration |
15274   case_construction
15275
15276 attribute_declaration ::=
15277   full_associative_array_declaration |
15278   @b{for} attribute_designator @b{use} expression ;
15279
15280 full_associative_array_declaration ::=
15281   @b{for} <associative_array_attribute_>simple_name @b{use}
15282   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
15283
15284 attribute_designator ::=
15285   <simple_attribute_>simple_name |
15286   <associative_array_attribute_>simple_name ( string_literal )
15287
15288 typed_variable_declaration ::=
15289   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
15290
15291 variable_declaration ::=
15292   <variable_>simple_name := expression;
15293
15294 expression ::=
15295   term @{& term@}
15296
15297 term ::=
15298   literal_string |
15299   string_list |
15300   <variable_>name |
15301   external_value |
15302   attribute_reference
15303
15304 string_literal ::=
15305   (same as Ada)
15306
15307 string_list ::=
15308   ( <string_>expression @{ , <string_>expression @} )
15309
15310 external_value ::=
15311   @b{external} ( string_literal [, string_literal] )
15312
15313 attribute_reference ::=
15314   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
15315
15316 attribute_prefix ::=
15317   @b{project} |
15318   <project_>simple_name | package_identifier |
15319   <project_>simple_name . package_identifier
15320
15321 case_construction ::=
15322   @b{case} <typed_variable_>name @b{is}
15323     @{case_item@}
15324   @b{end case} ;
15325
15326 case_item ::=
15327   @b{when} discrete_choice_list =>
15328       @{case_construction | attribute_declaration@}
15329
15330 discrete_choice_list ::=
15331   string_literal @{| string_literal@} |
15332   @b{others}
15333
15334 name ::=
15335   simple_name @{. simple_name@}
15336
15337 simple_name ::=
15338   identifier (same as Ada)
15339
15340 @end smallexample
15341
15342 @node The Cross-Referencing Tools gnatxref and gnatfind
15343 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
15344 @findex gnatxref
15345 @findex gnatfind
15346
15347 @noindent
15348 The compiler generates cross-referencing information (unless
15349 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
15350 This information indicates where in the source each entity is declared and
15351 referenced. Note that entities in package Standard are not included, but
15352 entities in all other predefined units are included in the output.
15353
15354 Before using any of these two tools, you need to compile successfully your
15355 application, so that GNAT gets a chance to generate the cross-referencing
15356 information.
15357
15358 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
15359 information to provide the user with the capability to easily locate the
15360 declaration and references to an entity. These tools are quite similar,
15361 the difference being that @code{gnatfind} is intended for locating
15362 definitions and/or references to a specified entity or entities, whereas
15363 @code{gnatxref} is oriented to generating a full report of all
15364 cross-references.
15365
15366 To use these tools, you must not compile your application using the
15367 @option{-gnatx} switch on the @command{gnatmake} command line
15368 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
15369 information will not be generated.
15370
15371 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
15372 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
15373
15374 @menu
15375 * Switches for gnatxref::
15376 * Switches for gnatfind::
15377 * Project Files for gnatxref and gnatfind::
15378 * Regular Expressions in gnatfind and gnatxref::
15379 * Examples of gnatxref Usage::
15380 * Examples of gnatfind Usage::
15381 @end menu
15382
15383 @node Switches for gnatxref
15384 @section @code{gnatxref} Switches
15385
15386 @noindent
15387 The command invocation for @code{gnatxref} is:
15388 @smallexample
15389 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
15390 @c Expanding @ovar macro inline (explanation in macro def comments)
15391 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
15392 @end smallexample
15393
15394 @noindent
15395 where
15396
15397 @table @var
15398 @item sourcefile1
15399 @itemx sourcefile2
15400 identifies the source files for which a report is to be generated. The
15401 ``with''ed units will be processed too. You must provide at least one file.
15402
15403 These file names are considered to be regular expressions, so for instance
15404 specifying @file{source*.adb} is the same as giving every file in the current
15405 directory whose name starts with @file{source} and whose extension is
15406 @file{adb}.
15407
15408 You shouldn't specify any directory name, just base names. @command{gnatxref}
15409 and @command{gnatfind} will be able to locate these files by themselves using
15410 the source path. If you specify directories, no result is produced.
15411
15412 @end table
15413
15414 @noindent
15415 The switches can be:
15416 @table @option
15417 @c !sort!
15418 @item --version
15419 @cindex @option{--version} @command{gnatxref}
15420 Display Copyright and version, then exit disregarding all other options.
15421
15422 @item --help
15423 @cindex @option{--help} @command{gnatxref}
15424 If @option{--version} was not used, display usage, then exit disregarding
15425 all other options.
15426
15427 @item ^-a^/ALL_FILES^
15428 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
15429 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15430 the read-only files found in the library search path. Otherwise, these files
15431 will be ignored. This option can be used to protect Gnat sources or your own
15432 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15433 much faster, and their output much smaller. Read-only here refers to access
15434 or permissions status in the file system for the current user.
15435
15436 @item -aIDIR
15437 @cindex @option{-aIDIR} (@command{gnatxref})
15438 When looking for source files also look in directory DIR. The order in which
15439 source file search is undertaken is the same as for @command{gnatmake}.
15440
15441 @item -aODIR
15442 @cindex @option{-aODIR} (@command{gnatxref})
15443 When searching for library and object files, look in directory
15444 DIR. The order in which library files are searched is the same as for
15445 @command{gnatmake}.
15446
15447 @item -nostdinc
15448 @cindex @option{-nostdinc} (@command{gnatxref})
15449 Do not look for sources in the system default directory.
15450
15451 @item -nostdlib
15452 @cindex @option{-nostdlib} (@command{gnatxref})
15453 Do not look for library files in the system default directory.
15454
15455 @item --RTS=@var{rts-path}
15456 @cindex @option{--RTS} (@command{gnatxref})
15457 Specifies the default location of the runtime library. Same meaning as the
15458 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15459
15460 @item ^-d^/DERIVED_TYPES^
15461 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
15462 If this switch is set @code{gnatxref} will output the parent type
15463 reference for each matching derived types.
15464
15465 @item ^-f^/FULL_PATHNAME^
15466 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
15467 If this switch is set, the output file names will be preceded by their
15468 directory (if the file was found in the search path). If this switch is
15469 not set, the directory will not be printed.
15470
15471 @item ^-g^/IGNORE_LOCALS^
15472 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
15473 If this switch is set, information is output only for library-level
15474 entities, ignoring local entities. The use of this switch may accelerate
15475 @code{gnatfind} and @code{gnatxref}.
15476
15477 @item -IDIR
15478 @cindex @option{-IDIR} (@command{gnatxref})
15479 Equivalent to @samp{-aODIR -aIDIR}.
15480
15481 @item -pFILE
15482 @cindex @option{-pFILE} (@command{gnatxref})
15483 Specify a project file to use @xref{Project Files}.
15484 If you need to use the @file{.gpr}
15485 project files, you should use gnatxref through the GNAT driver
15486 (@command{gnat xref -Pproject}).
15487
15488 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15489 project file in the current directory.
15490
15491 If a project file is either specified or found by the tools, then the content
15492 of the source directory and object directory lines are added as if they
15493 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
15494 and @samp{^-aO^OBJECT_SEARCH^}.
15495 @item ^-u^/UNUSED^
15496 Output only unused symbols. This may be really useful if you give your
15497 main compilation unit on the command line, as @code{gnatxref} will then
15498 display every unused entity and 'with'ed package.
15499
15500 @ifclear vms
15501 @item -v
15502 Instead of producing the default output, @code{gnatxref} will generate a
15503 @file{tags} file that can be used by vi. For examples how to use this
15504 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
15505 to the standard output, thus you will have to redirect it to a file.
15506 @end ifclear
15507
15508 @end table
15509
15510 @noindent
15511 All these switches may be in any order on the command line, and may even
15512 appear after the file names. They need not be separated by spaces, thus
15513 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15514 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15515
15516 @node Switches for gnatfind
15517 @section @code{gnatfind} Switches
15518
15519 @noindent
15520 The command line for @code{gnatfind} is:
15521
15522 @smallexample
15523 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
15524 @c       @r{[}@var{file1} @var{file2} @dots{}]
15525 @c Expanding @ovar macro inline (explanation in macro def comments)
15526 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
15527       @r{[}@var{file1} @var{file2} @dots{}@r{]}
15528 @end smallexample
15529
15530 @noindent
15531 where
15532
15533 @table @var
15534 @item pattern
15535 An entity will be output only if it matches the regular expression found
15536 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
15537
15538 Omitting the pattern is equivalent to specifying @samp{*}, which
15539 will match any entity. Note that if you do not provide a pattern, you
15540 have to provide both a sourcefile and a line.
15541
15542 Entity names are given in Latin-1, with uppercase/lowercase equivalence
15543 for matching purposes. At the current time there is no support for
15544 8-bit codes other than Latin-1, or for wide characters in identifiers.
15545
15546 @item sourcefile
15547 @code{gnatfind} will look for references, bodies or declarations
15548 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
15549 and column @var{column}. See @ref{Examples of gnatfind Usage}
15550 for syntax examples.
15551
15552 @item line
15553 is a decimal integer identifying the line number containing
15554 the reference to the entity (or entities) to be located.
15555
15556 @item column
15557 is a decimal integer identifying the exact location on the
15558 line of the first character of the identifier for the
15559 entity reference. Columns are numbered from 1.
15560
15561 @item file1 file2 @dots{}
15562 The search will be restricted to these source files. If none are given, then
15563 the search will be done for every library file in the search path.
15564 These file must appear only after the pattern or sourcefile.
15565
15566 These file names are considered to be regular expressions, so for instance
15567 specifying @file{source*.adb} is the same as giving every file in the current
15568 directory whose name starts with @file{source} and whose extension is
15569 @file{adb}.
15570
15571 The location of the spec of the entity will always be displayed, even if it
15572 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
15573 occurrences of the entity in the separate units of the ones given on the
15574 command line will also be displayed.
15575
15576 Note that if you specify at least one file in this part, @code{gnatfind} may
15577 sometimes not be able to find the body of the subprograms.
15578
15579 @end table
15580
15581 @noindent
15582 At least one of 'sourcefile' or 'pattern' has to be present on
15583 the command line.
15584
15585 The following switches are available:
15586 @table @option
15587 @c !sort!
15588
15589 @cindex @option{--version} @command{gnatfind}
15590 Display Copyright and version, then exit disregarding all other options.
15591
15592 @item --help
15593 @cindex @option{--help} @command{gnatfind}
15594 If @option{--version} was not used, display usage, then exit disregarding
15595 all other options.
15596
15597 @item ^-a^/ALL_FILES^
15598 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
15599 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
15600 the read-only files found in the library search path. Otherwise, these files
15601 will be ignored. This option can be used to protect Gnat sources or your own
15602 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
15603 much faster, and their output much smaller. Read-only here refers to access
15604 or permission status in the file system for the current user.
15605
15606 @item -aIDIR
15607 @cindex @option{-aIDIR} (@command{gnatfind})
15608 When looking for source files also look in directory DIR. The order in which
15609 source file search is undertaken is the same as for @command{gnatmake}.
15610
15611 @item -aODIR
15612 @cindex @option{-aODIR} (@command{gnatfind})
15613 When searching for library and object files, look in directory
15614 DIR. The order in which library files are searched is the same as for
15615 @command{gnatmake}.
15616
15617 @item -nostdinc
15618 @cindex @option{-nostdinc} (@command{gnatfind})
15619 Do not look for sources in the system default directory.
15620
15621 @item -nostdlib
15622 @cindex @option{-nostdlib} (@command{gnatfind})
15623 Do not look for library files in the system default directory.
15624
15625 @item --ext=@var{extension}
15626 @cindex @option{--ext} (@command{gnatfind})
15627 Specify an alternate ali file extension. The default is @code{ali} and other
15628 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
15629 switch. Note that if this switch overrides the default, which means that only
15630 the new extension will be considered.
15631
15632 @item --RTS=@var{rts-path}
15633 @cindex @option{--RTS} (@command{gnatfind})
15634 Specifies the default location of the runtime library. Same meaning as the
15635 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
15636
15637 @item ^-d^/DERIVED_TYPE_INFORMATION^
15638 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
15639 If this switch is set, then @code{gnatfind} will output the parent type
15640 reference for each matching derived types.
15641
15642 @item ^-e^/EXPRESSIONS^
15643 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
15644 By default, @code{gnatfind} accept the simple regular expression set for
15645 @samp{pattern}. If this switch is set, then the pattern will be
15646 considered as full Unix-style regular expression.
15647
15648 @item ^-f^/FULL_PATHNAME^
15649 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
15650 If this switch is set, the output file names will be preceded by their
15651 directory (if the file was found in the search path). If this switch is
15652 not set, the directory will not be printed.
15653
15654 @item ^-g^/IGNORE_LOCALS^
15655 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
15656 If this switch is set, information is output only for library-level
15657 entities, ignoring local entities. The use of this switch may accelerate
15658 @code{gnatfind} and @code{gnatxref}.
15659
15660 @item -IDIR
15661 @cindex @option{-IDIR} (@command{gnatfind})
15662 Equivalent to @samp{-aODIR -aIDIR}.
15663
15664 @item -pFILE
15665 @cindex @option{-pFILE} (@command{gnatfind})
15666 Specify a project file (@pxref{Project Files}) to use.
15667 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
15668 project file in the current directory.
15669
15670 If a project file is either specified or found by the tools, then the content
15671 of the source directory and object directory lines are added as if they
15672 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
15673 @samp{^-aO^/OBJECT_SEARCH^}.
15674
15675 @item ^-r^/REFERENCES^
15676 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
15677 By default, @code{gnatfind} will output only the information about the
15678 declaration, body or type completion of the entities. If this switch is
15679 set, the @code{gnatfind} will locate every reference to the entities in
15680 the files specified on the command line (or in every file in the search
15681 path if no file is given on the command line).
15682
15683 @item ^-s^/PRINT_LINES^
15684 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
15685 If this switch is set, then @code{gnatfind} will output the content
15686 of the Ada source file lines were the entity was found.
15687
15688 @item ^-t^/TYPE_HIERARCHY^
15689 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
15690 If this switch is set, then @code{gnatfind} will output the type hierarchy for
15691 the specified type. It act like -d option but recursively from parent
15692 type to parent type. When this switch is set it is not possible to
15693 specify more than one file.
15694
15695 @end table
15696
15697 @noindent
15698 All these switches may be in any order on the command line, and may even
15699 appear after the file names. They need not be separated by spaces, thus
15700 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
15701 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
15702
15703 As stated previously, gnatfind will search in every directory in the
15704 search path. You can force it to look only in the current directory if
15705 you specify @code{*} at the end of the command line.
15706
15707 @node Project Files for gnatxref and gnatfind
15708 @section Project Files for @command{gnatxref} and @command{gnatfind}
15709
15710 @noindent
15711 Project files allow a programmer to specify how to compile its
15712 application, where to find sources, etc.  These files are used
15713 @ifclear vms
15714 primarily by GPS, but they can also be used
15715 @end ifclear
15716 by the two tools
15717 @code{gnatxref} and @code{gnatfind}.
15718
15719 A project file name must end with @file{.gpr}. If a single one is
15720 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
15721 extract the information from it. If multiple project files are found, none of
15722 them is read, and you have to use the @samp{-p} switch to specify the one
15723 you want to use.
15724
15725 The following lines can be included, even though most of them have default
15726 values which can be used in most cases.
15727 The lines can be entered in any order in the file.
15728 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
15729 each line. If you have multiple instances, only the last one is taken into
15730 account.
15731
15732 @table @code
15733 @item src_dir=DIR
15734 [default: @code{"^./^[]^"}]
15735 specifies a directory where to look for source files. Multiple @code{src_dir}
15736 lines can be specified and they will be searched in the order they
15737 are specified.
15738
15739 @item obj_dir=DIR
15740 [default: @code{"^./^[]^"}]
15741 specifies a directory where to look for object and library files. Multiple
15742 @code{obj_dir} lines can be specified, and they will be searched in the order
15743 they are specified
15744
15745 @item comp_opt=SWITCHES
15746 [default: @code{""}]
15747 creates a variable which can be referred to subsequently by using
15748 the @code{$@{comp_opt@}} notation. This is intended to store the default
15749 switches given to @command{gnatmake} and @command{gcc}.
15750
15751 @item bind_opt=SWITCHES
15752 [default: @code{""}]
15753 creates a variable which can be referred to subsequently by using
15754 the @samp{$@{bind_opt@}} notation. This is intended to store the default
15755 switches given to @command{gnatbind}.
15756
15757 @item link_opt=SWITCHES
15758 [default: @code{""}]
15759 creates a variable which can be referred to subsequently by using
15760 the @samp{$@{link_opt@}} notation. This is intended to store the default
15761 switches given to @command{gnatlink}.
15762
15763 @item main=EXECUTABLE
15764 [default: @code{""}]
15765 specifies the name of the executable for the application. This variable can
15766 be referred to in the following lines by using the @samp{$@{main@}} notation.
15767
15768 @ifset vms
15769 @item comp_cmd=COMMAND
15770 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
15771 @end ifset
15772 @ifclear vms
15773 @item comp_cmd=COMMAND
15774 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
15775 @end ifclear
15776 specifies the command used to compile a single file in the application.
15777
15778 @ifset vms
15779 @item make_cmd=COMMAND
15780 [default: @code{"GNAT MAKE $@{main@}
15781 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
15782 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
15783 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
15784 @end ifset
15785 @ifclear vms
15786 @item make_cmd=COMMAND
15787 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
15788 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
15789 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
15790 @end ifclear
15791 specifies the command used to recompile the whole application.
15792
15793 @item run_cmd=COMMAND
15794 [default: @code{"$@{main@}"}]
15795 specifies the command used to run the application.
15796
15797 @item debug_cmd=COMMAND
15798 [default: @code{"gdb $@{main@}"}]
15799 specifies the command used to debug the application
15800
15801 @end table
15802
15803 @noindent
15804 @command{gnatxref} and @command{gnatfind} only take into account the
15805 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
15806
15807 @node Regular Expressions in gnatfind and gnatxref
15808 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
15809
15810 @noindent
15811 As specified in the section about @command{gnatfind}, the pattern can be a
15812 regular expression. Actually, there are to set of regular expressions
15813 which are recognized by the program:
15814
15815 @table @code
15816 @item globbing patterns
15817 These are the most usual regular expression. They are the same that you
15818 generally used in a Unix shell command line, or in a DOS session.
15819
15820 Here is a more formal grammar:
15821 @smallexample
15822 @group
15823 @iftex
15824 @leftskip=.5cm
15825 @end iftex
15826 regexp ::= term
15827 term   ::= elmt            -- matches elmt
15828 term   ::= elmt elmt       -- concatenation (elmt then elmt)
15829 term   ::= *               -- any string of 0 or more characters
15830 term   ::= ?               -- matches any character
15831 term   ::= [char @{char@}]   -- matches any character listed
15832 term   ::= [char - char]   -- matches any character in range
15833 @end group
15834 @end smallexample
15835
15836 @item full regular expression
15837 The second set of regular expressions is much more powerful. This is the
15838 type of regular expressions recognized by utilities such a @file{grep}.
15839
15840 The following is the form of a regular expression, expressed in Ada
15841 reference manual style BNF is as follows
15842
15843 @smallexample
15844 @iftex
15845 @leftskip=.5cm
15846 @end iftex
15847 @group
15848 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
15849
15850 term ::= item @{item@}       -- concatenation (item then item)
15851
15852 item ::= elmt              -- match elmt
15853 item ::= elmt *            -- zero or more elmt's
15854 item ::= elmt +            -- one or more elmt's
15855 item ::= elmt ?            -- matches elmt or nothing
15856 @end group
15857 @group
15858 elmt ::= nschar            -- matches given character
15859 elmt ::= [nschar @{nschar@}]   -- matches any character listed
15860 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
15861 elmt ::= [char - char]     -- matches chars in given range
15862 elmt ::= \ char            -- matches given character
15863 elmt ::= .                 -- matches any single character
15864 elmt ::= ( regexp )        -- parens used for grouping
15865
15866 char ::= any character, including special characters
15867 nschar ::= any character except ()[].*+?^^^
15868 @end group
15869 @end smallexample
15870
15871 Following are a few examples:
15872
15873 @table @samp
15874 @item abcde|fghi
15875 will match any of the two strings @samp{abcde} and @samp{fghi},
15876
15877 @item abc*d
15878 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
15879 @samp{abcccd}, and so on,
15880
15881 @item [a-z]+
15882 will match any string which has only lowercase characters in it (and at
15883 least one character.
15884
15885 @end table
15886 @end table
15887
15888 @node Examples of gnatxref Usage
15889 @section Examples of @code{gnatxref} Usage
15890
15891 @subsection General Usage
15892
15893 @noindent
15894 For the following examples, we will consider the following units:
15895
15896 @smallexample @c ada
15897 @group
15898 @cartouche
15899 main.ads:
15900 1: with Bar;
15901 2: package Main is
15902 3:     procedure Foo (B : in Integer);
15903 4:     C : Integer;
15904 5: private
15905 6:     D : Integer;
15906 7: end Main;
15907
15908 main.adb:
15909 1: package body Main is
15910 2:     procedure Foo (B : in Integer) is
15911 3:     begin
15912 4:        C := B;
15913 5:        D := B;
15914 6:        Bar.Print (B);
15915 7:        Bar.Print (C);
15916 8:     end Foo;
15917 9: end Main;
15918
15919 bar.ads:
15920 1: package Bar is
15921 2:     procedure Print (B : Integer);
15922 3: end bar;
15923 @end cartouche
15924 @end group
15925 @end smallexample
15926
15927 @table @code
15928
15929 @noindent
15930 The first thing to do is to recompile your application (for instance, in
15931 that case just by doing a @samp{gnatmake main}, so that GNAT generates
15932 the cross-referencing information.
15933 You can then issue any of the following commands:
15934
15935 @item gnatxref main.adb
15936 @code{gnatxref} generates cross-reference information for main.adb
15937 and every unit 'with'ed by main.adb.
15938
15939 The output would be:
15940 @smallexample
15941 @iftex
15942 @leftskip=0cm
15943 @end iftex
15944 B                                                      Type: Integer
15945   Decl: bar.ads           2:22
15946 B                                                      Type: Integer
15947   Decl: main.ads          3:20
15948   Body: main.adb          2:20
15949   Ref:  main.adb          4:13     5:13     6:19
15950 Bar                                                    Type: Unit
15951   Decl: bar.ads           1:9
15952   Ref:  main.adb          6:8      7:8
15953        main.ads           1:6
15954 C                                                      Type: Integer
15955   Decl: main.ads          4:5
15956   Modi: main.adb          4:8
15957   Ref:  main.adb          7:19
15958 D                                                      Type: Integer
15959   Decl: main.ads          6:5
15960   Modi: main.adb          5:8
15961 Foo                                                    Type: Unit
15962   Decl: main.ads          3:15
15963   Body: main.adb          2:15
15964 Main                                                    Type: Unit
15965   Decl: main.ads          2:9
15966   Body: main.adb          1:14
15967 Print                                                   Type: Unit
15968   Decl: bar.ads           2:15
15969   Ref:  main.adb          6:12     7:12
15970 @end smallexample
15971
15972 @noindent
15973 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
15974 its body is in main.adb, line 1, column 14 and is not referenced any where.
15975
15976 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
15977 it referenced in main.adb, line 6 column 12 and line 7 column 12.
15978
15979 @item gnatxref package1.adb package2.ads
15980 @code{gnatxref} will generates cross-reference information for
15981 package1.adb, package2.ads and any other package 'with'ed by any
15982 of these.
15983
15984 @end table
15985
15986 @ifclear vms
15987 @subsection Using gnatxref with vi
15988
15989 @code{gnatxref} can generate a tags file output, which can be used
15990 directly from @command{vi}. Note that the standard version of @command{vi}
15991 will not work properly with overloaded symbols. Consider using another
15992 free implementation of @command{vi}, such as @command{vim}.
15993
15994 @smallexample
15995 $ gnatxref -v gnatfind.adb > tags
15996 @end smallexample
15997
15998 @noindent
15999 will generate the tags file for @code{gnatfind} itself (if the sources
16000 are in the search path!).
16001
16002 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
16003 (replacing @var{entity} by whatever you are looking for), and vi will
16004 display a new file with the corresponding declaration of entity.
16005 @end ifclear
16006
16007 @node Examples of gnatfind Usage
16008 @section Examples of @code{gnatfind} Usage
16009
16010 @table @code
16011
16012 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
16013 Find declarations for all entities xyz referenced at least once in
16014 main.adb. The references are search in every library file in the search
16015 path.
16016
16017 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
16018 switch is set)
16019
16020 The output will look like:
16021 @smallexample
16022 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
16023 ^directory/^[directory]^main.adb:24:10: xyz <= body
16024 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
16025 @end smallexample
16026
16027 @noindent
16028 that is to say, one of the entities xyz found in main.adb is declared at
16029 line 12 of main.ads (and its body is in main.adb), and another one is
16030 declared at line 45 of foo.ads
16031
16032 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
16033 This is the same command as the previous one, instead @code{gnatfind} will
16034 display the content of the Ada source file lines.
16035
16036 The output will look like:
16037
16038 @smallexample
16039 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
16040    procedure xyz;
16041 ^directory/^[directory]^main.adb:24:10: xyz <= body
16042    procedure xyz is
16043 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
16044    xyz : Integer;
16045 @end smallexample
16046
16047 @noindent
16048 This can make it easier to find exactly the location your are looking
16049 for.
16050
16051 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
16052 Find references to all entities containing an x that are
16053 referenced on line 123 of main.ads.
16054 The references will be searched only in main.ads and foo.adb.
16055
16056 @item gnatfind main.ads:123
16057 Find declarations and bodies for all entities that are referenced on
16058 line 123 of main.ads.
16059
16060 This is the same as @code{gnatfind "*":main.adb:123}.
16061
16062 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
16063 Find the declaration for the entity referenced at column 45 in
16064 line 123 of file main.adb in directory mydir. Note that it
16065 is usual to omit the identifier name when the column is given,
16066 since the column position identifies a unique reference.
16067
16068 The column has to be the beginning of the identifier, and should not
16069 point to any character in the middle of the identifier.
16070
16071 @end table
16072
16073 @c *********************************
16074 @node The GNAT Pretty-Printer gnatpp
16075 @chapter The GNAT Pretty-Printer @command{gnatpp}
16076 @findex gnatpp
16077 @cindex Pretty-Printer
16078
16079 @noindent
16080 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
16081 for source reformatting / pretty-printing.
16082 It takes an Ada source file as input and generates a reformatted
16083 version as output.
16084 You can specify various style directives via switches; e.g.,
16085 identifier case conventions, rules of indentation, and comment layout.
16086
16087 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
16088 tree for the input source and thus requires the input to be syntactically and
16089 semantically legal.
16090 If this condition is not met, @command{gnatpp} will terminate with an
16091 error message; no output file will be generated.
16092
16093 If the source files presented to @command{gnatpp} contain
16094 preprocessing directives, then the output file will
16095 correspond to the generated source after all
16096 preprocessing is carried out. There is no way
16097 using @command{gnatpp} to obtain pretty printed files that
16098 include the preprocessing directives.
16099
16100 If the compilation unit
16101 contained in the input source depends semantically upon units located
16102 outside the current directory, you have to provide the source search path
16103 when invoking @command{gnatpp}, if these units are contained in files with
16104 names that do not follow the GNAT file naming rules, you have to provide
16105 the configuration file describing the corresponding naming scheme;
16106 see the description of the @command{gnatpp}
16107 switches below. Another possibility is to use a project file and to
16108 call @command{gnatpp} through the @command{gnat} driver
16109
16110 The @command{gnatpp} command has the form
16111
16112 @smallexample
16113 @c $ gnatpp @ovar{switches} @var{filename}
16114 @c Expanding @ovar macro inline (explanation in macro def comments)
16115 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
16116 @end smallexample
16117
16118 @noindent
16119 where
16120 @itemize @bullet
16121 @item
16122 @var{switches} is an optional sequence of switches defining such properties as
16123 the formatting rules, the source search path, and the destination for the
16124 output source file
16125
16126 @item
16127 @var{filename} is the name (including the extension) of the source file to
16128 reformat; ``wildcards'' or several file names on the same gnatpp command are
16129 allowed.  The file name may contain path information; it does not have to
16130 follow the GNAT file naming rules
16131
16132 @item
16133 @samp{@var{gcc_switches}} is a list of switches for
16134 @command{gcc}. They will be passed on to all compiler invocations made by
16135 @command{gnatelim} to generate the ASIS trees. Here you can provide
16136 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
16137 use the @option{-gnatec} switch to set the configuration file etc.
16138 @end itemize
16139
16140 @menu
16141 * Switches for gnatpp::
16142 * Formatting Rules::
16143 @end menu
16144
16145 @node Switches for gnatpp
16146 @section Switches for @command{gnatpp}
16147
16148 @noindent
16149 The following subsections describe the various switches accepted by
16150 @command{gnatpp}, organized by category.
16151
16152 @ifclear vms
16153 You specify a switch by supplying a name and generally also a value.
16154 In many cases the values for a switch with a given name are incompatible with
16155 each other
16156 (for example the switch that controls the casing of a reserved word may have
16157 exactly one value: upper case, lower case, or
16158 mixed case) and thus exactly one such switch can be in effect for an
16159 invocation of @command{gnatpp}.
16160 If more than one is supplied, the last one is used.
16161 However, some values for the same switch are mutually compatible.
16162 You may supply several such switches to @command{gnatpp}, but then
16163 each must be specified in full, with both the name and the value.
16164 Abbreviated forms (the name appearing once, followed by each value) are
16165 not permitted.
16166 For example, to set
16167 the alignment of the assignment delimiter both in declarations and in
16168 assignment statements, you must write @option{-A2A3}
16169 (or @option{-A2 -A3}), but not @option{-A23}.
16170 @end ifclear
16171
16172 @ifset vms
16173 In many cases the set of options for a given qualifier are incompatible with
16174 each other (for example the qualifier that controls the casing of a reserved
16175 word may have exactly one option, which specifies either upper case, lower
16176 case, or mixed case), and thus exactly one such option can be in effect for
16177 an invocation of @command{gnatpp}.
16178 If more than one is supplied, the last one is used.
16179 However, some qualifiers have options that are mutually compatible,
16180 and then you may then supply several such options when invoking
16181 @command{gnatpp}.
16182 @end ifset
16183
16184 In most cases, it is obvious whether or not the
16185 ^values for a switch with a given name^options for a given qualifier^
16186 are compatible with each other.
16187 When the semantics might not be evident, the summaries below explicitly
16188 indicate the effect.
16189
16190 @menu
16191 * Alignment Control::
16192 * Casing Control::
16193 * Construct Layout Control::
16194 * General Text Layout Control::
16195 * Other Formatting Options::
16196 * Setting the Source Search Path::
16197 * Output File Control::
16198 * Other gnatpp Switches::
16199 @end menu
16200
16201 @node Alignment Control
16202 @subsection Alignment Control
16203 @cindex Alignment control in @command{gnatpp}
16204
16205 @noindent
16206 Programs can be easier to read if certain constructs are vertically aligned.
16207 By default all alignments are set ON.
16208 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
16209 OFF, and then use one or more of the other
16210 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
16211 to activate alignment for specific constructs.
16212
16213 @table @option
16214 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
16215
16216 @ifset vms
16217 @item /ALIGN=ON
16218 Set all alignments to ON
16219 @end ifset
16220
16221 @item ^-A0^/ALIGN=OFF^
16222 Set all alignments to OFF
16223
16224 @item ^-A1^/ALIGN=COLONS^
16225 Align @code{:} in declarations
16226
16227 @item ^-A2^/ALIGN=DECLARATIONS^
16228 Align @code{:=} in initializations in declarations
16229
16230 @item ^-A3^/ALIGN=STATEMENTS^
16231 Align @code{:=} in assignment statements
16232
16233 @item ^-A4^/ALIGN=ARROWS^
16234 Align @code{=>} in associations
16235
16236 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
16237 Align @code{at} keywords in the component clauses in record
16238 representation clauses
16239 @end table
16240
16241 @noindent
16242 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
16243 is allowed.
16244
16245 @node Casing Control
16246 @subsection Casing Control
16247 @cindex Casing control in @command{gnatpp}
16248
16249 @noindent
16250 @command{gnatpp} allows you to specify the casing for reserved words,
16251 pragma names, attribute designators and identifiers.
16252 For identifiers you may define a
16253 general rule for name casing but also override this rule
16254 via a set of dictionary files.
16255
16256 Three types of casing are supported: lower case, upper case, and mixed case.
16257 Lower and upper case are self-explanatory (but since some letters in
16258 Latin1 and other GNAT-supported character sets
16259 exist only in lower-case form, an upper case conversion will have no
16260 effect on them.)
16261 ``Mixed case'' means that the first letter, and also each letter immediately
16262 following an underscore, are converted to their uppercase forms;
16263 all the other letters are converted to their lowercase forms.
16264
16265 @table @option
16266 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
16267 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
16268 Attribute designators are lower case
16269
16270 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
16271 Attribute designators are upper case
16272
16273 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
16274 Attribute designators are mixed case (this is the default)
16275
16276 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
16277 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
16278 Keywords (technically, these are known in Ada as @emph{reserved words}) are
16279 lower case (this is the default)
16280
16281 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
16282 Keywords are upper case
16283
16284 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
16285 @item ^-nD^/NAME_CASING=AS_DECLARED^
16286 Name casing for defining occurrences are as they appear in the source file
16287 (this is the default)
16288
16289 @item ^-nU^/NAME_CASING=UPPER_CASE^
16290 Names are in upper case
16291
16292 @item ^-nL^/NAME_CASING=LOWER_CASE^
16293 Names are in lower case
16294
16295 @item ^-nM^/NAME_CASING=MIXED_CASE^
16296 Names are in mixed case
16297
16298 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
16299 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
16300 Pragma names are lower case
16301
16302 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
16303 Pragma names are upper case
16304
16305 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
16306 Pragma names are mixed case (this is the default)
16307
16308 @item ^-D@var{file}^/DICTIONARY=@var{file}^
16309 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
16310 Use @var{file} as a @emph{dictionary file} that defines
16311 the casing for a set of specified names,
16312 thereby overriding the effect on these names by
16313 any explicit or implicit
16314 ^-n^/NAME_CASING^ switch.
16315 To supply more than one dictionary file,
16316 use ^several @option{-D} switches^a list of files as options^.
16317
16318 @noindent
16319 @option{gnatpp} implicitly uses a @emph{default dictionary file}
16320 to define the casing for the Ada predefined names and
16321 the names declared in the GNAT libraries.
16322
16323 @item ^-D-^/SPECIFIC_CASING^
16324 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
16325 Do not use the default dictionary file;
16326 instead, use the casing
16327 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
16328 dictionary file(s)
16329 @end table
16330
16331 @noindent
16332 The structure of a dictionary file, and details on the conventions
16333 used in the default dictionary file, are defined in @ref{Name Casing}.
16334
16335 The @option{^-D-^/SPECIFIC_CASING^} and
16336 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
16337 compatible.
16338
16339 @node Construct Layout Control
16340 @subsection Construct Layout Control
16341 @cindex Layout control in @command{gnatpp}
16342
16343 @noindent
16344 This group of @command{gnatpp} switches controls the layout of comments and
16345 complex syntactic constructs.  See @ref{Formatting Comments} for details
16346 on their effect.
16347
16348 @table @option
16349 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
16350 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
16351 All the comments remain unchanged
16352
16353 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
16354 GNAT-style comment line indentation (this is the default).
16355
16356 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
16357 Reference-manual comment line indentation.
16358
16359 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
16360 GNAT-style comment beginning
16361
16362 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
16363 Reformat comment blocks
16364
16365 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
16366 Keep unchanged special form comments
16367
16368 Reformat comment blocks
16369
16370 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
16371 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
16372 GNAT-style layout (this is the default)
16373
16374 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
16375 Compact layout
16376
16377 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
16378 Uncompact layout
16379
16380 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
16381 @item ^-N^/NOTABS^
16382 All the VT characters are removed from the comment text. All the HT characters
16383 are expanded with the sequences of space characters to get to the next tab
16384 stops.
16385
16386 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
16387 @item ^--no-separate-is^/NO_SEPARATE_IS^
16388 Do not place the keyword @code{is} on a separate line in a subprogram body in
16389 case if the spec occupies more then one line.
16390
16391 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
16392 @item ^--separate-label^/SEPARATE_LABEL^
16393 Place statement label(s) on a separate line, with the following statement
16394 on the next line.
16395
16396 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
16397 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
16398 Place the keyword @code{loop} in FOR and WHILE loop statements and the
16399 keyword @code{then} in IF statements on a separate line.
16400
16401 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
16402 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
16403 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
16404 keyword @code{then} in IF statements on a separate line. This option is
16405 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
16406
16407 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
16408 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
16409 Start each USE clause in a context clause from a separate line.
16410
16411 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
16412 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
16413 Use a separate line for a loop or block statement name, but do not use an extra
16414 indentation level for the statement itself.
16415
16416 @end table
16417
16418 @ifclear vms
16419 @noindent
16420 The @option{-c1} and @option{-c2} switches are incompatible.
16421 The @option{-c3} and @option{-c4} switches are compatible with each other and
16422 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
16423 the other comment formatting switches.
16424
16425 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
16426 @end ifclear
16427
16428 @ifset vms
16429 @noindent
16430 For the @option{/COMMENTS_LAYOUT} qualifier:
16431 @itemize @bullet
16432 @item
16433 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
16434 @item
16435 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
16436 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
16437 @end itemize
16438
16439 @noindent
16440 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
16441 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
16442 @end ifset
16443
16444 @node General Text Layout Control
16445 @subsection General Text Layout Control
16446
16447 @noindent
16448 These switches allow control over line length and indentation.
16449
16450 @table @option
16451 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
16452 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
16453 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
16454
16455 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
16456 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
16457 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
16458
16459 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
16460 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
16461 Indentation level for continuation lines (relative to the line being
16462 continued), @var{nnn} from 1@dots{}9.
16463 The default
16464 value is one less then the (normal) indentation level, unless the
16465 indentation is set to 1 (in which case the default value for continuation
16466 line indentation is also 1)
16467 @end table
16468
16469 @node Other Formatting Options
16470 @subsection Other Formatting Options
16471
16472 @noindent
16473 These switches control the inclusion of missing end/exit labels, and
16474 the indentation level in @b{case} statements.
16475
16476 @table @option
16477 @item ^-e^/NO_MISSED_LABELS^
16478 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
16479 Do not insert missing end/exit labels. An end label is the name of
16480 a construct that may optionally be repeated at the end of the
16481 construct's declaration;
16482 e.g., the names of packages, subprograms, and tasks.
16483 An exit label is the name of a loop that may appear as target
16484 of an exit statement within the loop.
16485 By default, @command{gnatpp} inserts these end/exit labels when
16486 they are absent from the original source. This option suppresses such
16487 insertion, so that the formatted source reflects the original.
16488
16489 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
16490 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
16491 Insert a Form Feed character after a pragma Page.
16492
16493 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
16494 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
16495 Do not use an additional indentation level for @b{case} alternatives
16496 and variants if there are @var{nnn} or more (the default
16497 value is 10).
16498 If @var{nnn} is 0, an additional indentation level is
16499 used for @b{case} alternatives and variants regardless of their number.
16500 @end table
16501
16502 @node Setting the Source Search Path
16503 @subsection Setting the Source Search Path
16504
16505 @noindent
16506 To define the search path for the input source file, @command{gnatpp}
16507 uses the same switches as the GNAT compiler, with the same effects.
16508
16509 @table @option
16510 @item ^-I^/SEARCH=^@var{dir}
16511 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
16512 The same as the corresponding gcc switch
16513
16514 @item ^-I-^/NOCURRENT_DIRECTORY^
16515 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
16516 The same as the corresponding gcc switch
16517
16518 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
16519 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
16520 The same as the corresponding gcc switch
16521
16522 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
16523 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
16524 The same as the corresponding gcc switch
16525
16526 @end table
16527
16528 @node Output File Control
16529 @subsection Output File Control
16530
16531 @noindent
16532 By default the output is sent to the file whose name is obtained by appending
16533 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
16534 (if the file with this name already exists, it is unconditionally overwritten).
16535 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
16536 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
16537 as output file.
16538 The output may be redirected by the following switches:
16539
16540 @table @option
16541 @item ^-pipe^/STANDARD_OUTPUT^
16542 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
16543 Send the output to @code{Standard_Output}
16544
16545 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
16546 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
16547 Write the output into @var{output_file}.
16548 If @var{output_file} already exists, @command{gnatpp} terminates without
16549 reading or processing the input file.
16550
16551 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
16552 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
16553 Write the output into @var{output_file}, overwriting the existing file
16554 (if one is present).
16555
16556 @item ^-r^/REPLACE^
16557 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
16558 Replace the input source file with the reformatted output, and copy the
16559 original input source into the file whose name is obtained by appending the
16560 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
16561 If a file with this name already exists, @command{gnatpp} terminates without
16562 reading or processing the input file.
16563
16564 @item ^-rf^/OVERRIDING_REPLACE^
16565 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
16566 Like @option{^-r^/REPLACE^} except that if the file with the specified name
16567 already exists, it is overwritten.
16568
16569 @item ^-rnb^/REPLACE_NO_BACKUP^
16570 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
16571 Replace the input source file with the reformatted output without
16572 creating any backup copy of the input source.
16573
16574 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
16575 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
16576 Specifies the format of the reformatted output file. The @var{xxx}
16577 ^string specified with the switch^option^ may be either
16578 @itemize @bullet
16579 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
16580 @item ``@option{^crlf^CRLF^}''
16581 the same as @option{^crlf^CRLF^}
16582 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
16583 @item ``@option{^lf^LF^}''
16584 the same as @option{^unix^UNIX^}
16585 @end itemize
16586
16587 @item ^-W^/RESULT_ENCODING=^@var{e}
16588 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
16589 Specify the wide character encoding method used to write the code in the
16590 result file
16591 @var{e} is one of the following:
16592
16593 @itemize @bullet
16594
16595 @item ^h^HEX^
16596 Hex encoding
16597
16598 @item ^u^UPPER^
16599 Upper half encoding
16600
16601 @item ^s^SHIFT_JIS^
16602 Shift/JIS encoding
16603
16604 @item ^e^EUC^
16605 EUC encoding
16606
16607 @item ^8^UTF8^
16608 UTF-8 encoding
16609
16610 @item ^b^BRACKETS^
16611 Brackets encoding (default value)
16612 @end itemize
16613
16614 @end table
16615
16616 @noindent
16617 Options @option{^-pipe^/STANDARD_OUTPUT^},
16618 @option{^-o^/OUTPUT^} and
16619 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
16620 contains only one file to reformat.
16621 Option
16622 @option{^--eol^/END_OF_LINE^}
16623 and
16624 @option{^-W^/RESULT_ENCODING^}
16625 cannot be used together
16626 with @option{^-pipe^/STANDARD_OUTPUT^} option.
16627
16628 @node Other gnatpp Switches
16629 @subsection Other @code{gnatpp} Switches
16630
16631 @noindent
16632 The additional @command{gnatpp} switches are defined in this subsection.
16633
16634 @table @option
16635 @item ^-files @var{filename}^/FILES=@var{filename}^
16636 @cindex @option{^-files^/FILES^} (@code{gnatpp})
16637 Take the argument source files from the specified file. This file should be an
16638 ordinary text file containing file names separated by spaces or
16639 line breaks. You can use this switch more than once in the same call to
16640 @command{gnatpp}. You also can combine this switch with an explicit list of
16641 files.
16642
16643 @item ^-v^/VERBOSE^
16644 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
16645 Verbose mode;
16646 @command{gnatpp} generates version information and then
16647 a trace of the actions it takes to produce or obtain the ASIS tree.
16648
16649 @item ^-w^/WARNINGS^
16650 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
16651 Warning mode;
16652 @command{gnatpp} generates a warning whenever it cannot provide
16653 a required layout in the result source.
16654 @end table
16655
16656 @node Formatting Rules
16657 @section Formatting Rules
16658
16659 @noindent
16660 The following subsections show how @command{gnatpp} treats ``white space'',
16661 comments, program layout, and name casing.
16662 They provide the detailed descriptions of the switches shown above.
16663
16664 @menu
16665 * White Space and Empty Lines::
16666 * Formatting Comments::
16667 * Construct Layout::
16668 * Name Casing::
16669 @end menu
16670
16671 @node White Space and Empty Lines
16672 @subsection White Space and Empty Lines
16673
16674 @noindent
16675 @command{gnatpp} does not have an option to control space characters.
16676 It will add or remove spaces according to the style illustrated by the
16677 examples in the @cite{Ada Reference Manual}.
16678
16679 The only format effectors
16680 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
16681 that will appear in the output file are platform-specific line breaks,
16682 and also format effectors within (but not at the end of) comments.
16683 In particular, each horizontal tab character that is not inside
16684 a comment will be treated as a space and thus will appear in the
16685 output file as zero or more spaces depending on
16686 the reformatting of the line in which it appears.
16687 The only exception is a Form Feed character, which is inserted after a
16688 pragma @code{Page} when @option{-ff} is set.
16689
16690 The output file will contain no lines with trailing ``white space'' (spaces,
16691 format effectors).
16692
16693 Empty lines in the original source are preserved
16694 only if they separate declarations or statements.
16695 In such contexts, a
16696 sequence of two or more empty lines is replaced by exactly one empty line.
16697 Note that a blank line will be removed if it separates two ``comment blocks''
16698 (a comment block is a sequence of whole-line comments).
16699 In order to preserve a visual separation between comment blocks, use an
16700 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
16701 Likewise, if for some reason you wish to have a sequence of empty lines,
16702 use a sequence of empty comments instead.
16703
16704 @node Formatting Comments
16705 @subsection Formatting Comments
16706
16707 @noindent
16708 Comments in Ada code are of two kinds:
16709 @itemize @bullet
16710 @item
16711 a @emph{whole-line comment}, which appears by itself (possibly preceded by
16712 ``white space'') on a line
16713
16714 @item
16715 an @emph{end-of-line comment}, which follows some other Ada lexical element
16716 on the same line.
16717 @end itemize
16718
16719 @noindent
16720 The indentation of a whole-line comment is that of either
16721 the preceding or following line in
16722 the formatted source, depending on switch settings as will be described below.
16723
16724 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
16725 between the end of the preceding Ada lexical element and the beginning
16726 of the comment as appear in the original source,
16727 unless either the comment has to be split to
16728 satisfy the line length limitation, or else the next line contains a
16729 whole line comment that is considered a continuation of this end-of-line
16730 comment (because it starts at the same position).
16731 In the latter two
16732 cases, the start of the end-of-line comment is moved right to the nearest
16733 multiple of the indentation level.
16734 This may result in a ``line overflow'' (the right-shifted comment extending
16735 beyond the maximum line length), in which case the comment is split as
16736 described below.
16737
16738 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
16739 (GNAT-style comment line indentation)
16740 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
16741 (reference-manual comment line indentation).
16742 With reference-manual style, a whole-line comment is indented as if it
16743 were a declaration or statement at the same place
16744 (i.e., according to the indentation of the preceding line(s)).
16745 With GNAT style, a whole-line comment that is immediately followed by an
16746 @b{if} or @b{case} statement alternative, a record variant, or the reserved
16747 word @b{begin}, is indented based on the construct that follows it.
16748
16749 For example:
16750 @smallexample @c ada
16751 @cartouche
16752 if A then
16753     null;
16754        -- some comment
16755 else
16756    null;
16757 end if;
16758 @end cartouche
16759 @end smallexample
16760
16761 @noindent
16762 Reference-manual indentation produces:
16763
16764 @smallexample @c ada
16765 @cartouche
16766 if A then
16767    null;
16768    --  some comment
16769 else
16770    null;
16771 end if;
16772 @end cartouche
16773 @end smallexample
16774
16775 @noindent
16776 while GNAT-style indentation produces:
16777
16778 @smallexample @c ada
16779 @cartouche
16780 if A then
16781    null;
16782 --  some comment
16783 else
16784    null;
16785 end if;
16786 @end cartouche
16787 @end smallexample
16788
16789 @noindent
16790 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
16791 (GNAT style comment beginning) has the following
16792 effect:
16793
16794 @itemize @bullet
16795 @item
16796 For each whole-line comment that does not end with two hyphens,
16797 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
16798 to ensure that there are at least two spaces between these hyphens and the
16799 first non-blank character of the comment.
16800 @end itemize
16801
16802 @noindent
16803 For an end-of-line comment, if in the original source the next line is a
16804 whole-line comment that starts at the same position
16805 as the end-of-line comment,
16806 then the whole-line comment (and all whole-line comments
16807 that follow it and that start at the same position)
16808 will start at this position in the output file.
16809
16810 @noindent
16811 That is, if in the original source we have:
16812
16813 @smallexample @c ada
16814 @cartouche
16815 begin
16816 A := B + C;            --  B must be in the range Low1..High1
16817                        --  C must be in the range Low2..High2
16818              --B+C will be in the range Low1+Low2..High1+High2
16819 X := X + 1;
16820 @end cartouche
16821 @end smallexample
16822
16823 @noindent
16824 Then in the formatted source we get
16825
16826 @smallexample @c ada
16827 @cartouche
16828 begin
16829    A := B + C;            --  B must be in the range Low1..High1
16830                           --  C must be in the range Low2..High2
16831    --  B+C will be in the range Low1+Low2..High1+High2
16832    X := X + 1;
16833 @end cartouche
16834 @end smallexample
16835
16836 @noindent
16837 A comment that exceeds the line length limit will be split.
16838 Unless switch
16839 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
16840 the line belongs to a reformattable block, splitting the line generates a
16841 @command{gnatpp} warning.
16842 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
16843 comments may be reformatted in typical
16844 word processor style (that is, moving words between lines and putting as
16845 many words in a line as possible).
16846
16847 @noindent
16848 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
16849 that has a special format (that is, a character that is neither a letter nor digit
16850 not white space nor line break immediately following the leading @code{--} of
16851 the comment) should be without any change moved from the argument source
16852 into reformatted source. This switch allows to preserve comments that are used
16853 as a special marks in the code (e.g.@: SPARK annotation).
16854
16855 @node Construct Layout
16856 @subsection Construct Layout
16857
16858 @noindent
16859 In several cases the suggested layout in the Ada Reference Manual includes
16860 an extra level of indentation that many programmers prefer to avoid. The
16861 affected cases include:
16862
16863 @itemize @bullet
16864
16865 @item Record type declaration (RM 3.8)
16866
16867 @item Record representation clause (RM 13.5.1)
16868
16869 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
16870
16871 @item Block statement in case if a block has a statement identifier (RM 5.6)
16872 @end itemize
16873
16874 @noindent
16875 In compact mode (when GNAT style layout or compact layout is set),
16876 the pretty printer uses one level of indentation instead
16877 of two. This is achieved in the record definition and record representation
16878 clause cases by putting the @code{record} keyword on the same line as the
16879 start of the declaration or representation clause, and in the block and loop
16880 case by putting the block or loop header on the same line as the statement
16881 identifier.
16882
16883 @noindent
16884 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
16885 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
16886 layout on the one hand, and uncompact layout
16887 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
16888 can be illustrated by the following examples:
16889
16890 @iftex
16891 @cartouche
16892 @multitable @columnfractions .5 .5
16893 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
16894
16895 @item
16896 @smallexample @c ada
16897 type q is record
16898    a : integer;
16899    b : integer;
16900 end record;
16901 @end smallexample
16902 @tab
16903 @smallexample @c ada
16904 type q is
16905    record
16906       a : integer;
16907       b : integer;
16908    end record;
16909 @end smallexample
16910
16911 @item
16912 @smallexample @c ada
16913 for q use record
16914    a at 0 range  0 .. 31;
16915    b at 4 range  0 .. 31;
16916 end record;
16917 @end smallexample
16918 @tab
16919 @smallexample @c ada
16920 for q use
16921    record
16922       a at 0 range  0 .. 31;
16923       b at 4 range  0 .. 31;
16924    end record;
16925 @end smallexample
16926
16927 @item
16928 @smallexample @c ada
16929 Block : declare
16930    A : Integer := 3;
16931 begin
16932    Proc (A, A);
16933 end Block;
16934 @end smallexample
16935 @tab
16936 @smallexample @c ada
16937 Block :
16938    declare
16939       A : Integer := 3;
16940    begin
16941       Proc (A, A);
16942    end Block;
16943 @end smallexample
16944
16945 @item
16946 @smallexample @c ada
16947 Clear : for J in 1 .. 10 loop
16948    A (J) := 0;
16949 end loop Clear;
16950 @end smallexample
16951 @tab
16952 @smallexample @c ada
16953 Clear :
16954    for J in 1 .. 10 loop
16955       A (J) := 0;
16956    end loop Clear;
16957 @end smallexample
16958 @end multitable
16959 @end cartouche
16960 @end iftex
16961
16962 @ifnottex
16963 @smallexample
16964 @cartouche
16965 GNAT style, compact layout              Uncompact layout
16966
16967 type q is record                        type q is
16968    a : integer;                            record
16969    b : integer;                               a : integer;
16970 end record;                                   b : integer;
16971                                            end record;
16972
16973 for q use record                        for q use
16974    a at 0 range  0 .. 31;                  record
16975    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
16976 end record;                                   b at 4 range  0 .. 31;
16977                                            end record;
16978
16979 Block : declare                         Block :
16980    A : Integer := 3;                       declare
16981 begin                                         A : Integer := 3;
16982    Proc (A, A);                            begin
16983 end Block;                                    Proc (A, A);
16984                                            end Block;
16985
16986 Clear : for J in 1 .. 10 loop           Clear :
16987    A (J) := 0;                             for J in 1 .. 10 loop
16988 end loop Clear;                               A (J) := 0;
16989                                            end loop Clear;
16990 @end cartouche
16991 @end smallexample
16992 @end ifnottex
16993
16994 @noindent
16995 A further difference between GNAT style layout and compact layout is that
16996 GNAT style layout inserts empty lines as separation for
16997 compound statements, return statements and bodies.
16998
16999 Note that the layout specified by
17000 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
17001 for named block and loop statements overrides the layout defined by these
17002 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
17003 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
17004 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
17005
17006 @node Name Casing
17007 @subsection Name Casing
17008
17009 @noindent
17010 @command{gnatpp} always converts the usage occurrence of a (simple) name to
17011 the same casing as the corresponding defining identifier.
17012
17013 You control the casing for defining occurrences via the
17014 @option{^-n^/NAME_CASING^} switch.
17015 @ifclear vms
17016 With @option{-nD} (``as declared'', which is the default),
17017 @end ifclear
17018 @ifset vms
17019 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
17020 @end ifset
17021 defining occurrences appear exactly as in the source file
17022 where they are declared.
17023 The other ^values for this switch^options for this qualifier^ ---
17024 @option{^-nU^UPPER_CASE^},
17025 @option{^-nL^LOWER_CASE^},
17026 @option{^-nM^MIXED_CASE^} ---
17027 result in
17028 ^upper, lower, or mixed case, respectively^the corresponding casing^.
17029 If @command{gnatpp} changes the casing of a defining
17030 occurrence, it analogously changes the casing of all the
17031 usage occurrences of this name.
17032
17033 If the defining occurrence of a name is not in the source compilation unit
17034 currently being processed by @command{gnatpp}, the casing of each reference to
17035 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
17036 switch (subject to the dictionary file mechanism described below).
17037 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
17038 had affected the
17039 casing for the defining occurrence of the name.
17040
17041 Some names may need to be spelled with casing conventions that are not
17042 covered by the upper-, lower-, and mixed-case transformations.
17043 You can arrange correct casing by placing such names in a
17044 @emph{dictionary file},
17045 and then supplying a @option{^-D^/DICTIONARY^} switch.
17046 The casing of names from dictionary files overrides
17047 any @option{^-n^/NAME_CASING^} switch.
17048
17049 To handle the casing of Ada predefined names and the names from GNAT libraries,
17050 @command{gnatpp} assumes a default dictionary file.
17051 The name of each predefined entity is spelled with the same casing as is used
17052 for the entity in the @cite{Ada Reference Manual}.
17053 The name of each entity in the GNAT libraries is spelled with the same casing
17054 as is used in the declaration of that entity.
17055
17056 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
17057 default dictionary file.
17058 Instead, the casing for predefined and GNAT-defined names will be established
17059 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
17060 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
17061 will appear as just shown,
17062 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
17063 To ensure that even such names are rendered in uppercase,
17064 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
17065 (or else, less conveniently, place these names in upper case in a dictionary
17066 file).
17067
17068 A dictionary file is
17069 a plain text file; each line in this file can be either a blank line
17070 (containing only space characters and ASCII.HT characters), an Ada comment
17071 line, or the specification of exactly one @emph{casing schema}.
17072
17073 A casing schema is a string that has the following syntax:
17074
17075 @smallexample
17076 @cartouche
17077   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
17078
17079   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
17080 @end cartouche
17081 @end smallexample
17082
17083 @noindent
17084 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
17085 @var{identifier} lexical element and the @var{letter_or_digit} category.)
17086
17087 The casing schema string can be followed by white space and/or an Ada-style
17088 comment; any amount of white space is allowed before the string.
17089
17090 If a dictionary file is passed as
17091 @ifclear vms
17092 the value of a @option{-D@var{file}} switch
17093 @end ifclear
17094 @ifset vms
17095 an option to the @option{/DICTIONARY} qualifier
17096 @end ifset
17097 then for every
17098 simple name and every identifier, @command{gnatpp} checks if the dictionary
17099 defines the casing for the name or for some of its parts (the term ``subword''
17100 is used below to denote the part of a name which is delimited by ``_'' or by
17101 the beginning or end of the word and which does not contain any ``_'' inside):
17102
17103 @itemize @bullet
17104 @item
17105 if the whole name is in the dictionary, @command{gnatpp} uses for this name
17106 the casing defined by the dictionary; no subwords are checked for this word
17107
17108 @item
17109 for every subword @command{gnatpp} checks if the dictionary contains the
17110 corresponding string of the form @code{*@var{simple_identifier}*},
17111 and if it does, the casing of this @var{simple_identifier} is used
17112 for this subword
17113
17114 @item
17115 if the whole name does not contain any ``_'' inside, and if for this name
17116 the dictionary contains two entries - one of the form @var{identifier},
17117 and another - of the form *@var{simple_identifier}*, then the first one
17118 is applied to define the casing of this name
17119
17120 @item
17121 if more than one dictionary file is passed as @command{gnatpp} switches, each
17122 dictionary adds new casing exceptions and overrides all the existing casing
17123 exceptions set by the previous dictionaries
17124
17125 @item
17126 when @command{gnatpp} checks if the word or subword is in the dictionary,
17127 this check is not case sensitive
17128 @end itemize
17129
17130 @noindent
17131 For example, suppose we have the following source to reformat:
17132
17133 @smallexample @c ada
17134 @cartouche
17135 procedure test is
17136    name1 : integer := 1;
17137    name4_name3_name2 : integer := 2;
17138    name2_name3_name4 : Boolean;
17139    name1_var : Float;
17140 begin
17141    name2_name3_name4 := name4_name3_name2 > name1;
17142 end;
17143 @end cartouche
17144 @end smallexample
17145
17146 @noindent
17147 And suppose we have two dictionaries:
17148
17149 @smallexample
17150 @cartouche
17151 @i{dict1:}
17152    NAME1
17153    *NaMe3*
17154    *Name1*
17155 @end cartouche
17156
17157 @cartouche
17158 @i{dict2:}
17159   *NAME3*
17160 @end cartouche
17161 @end smallexample
17162
17163 @noindent
17164 If @command{gnatpp} is called with the following switches:
17165
17166 @smallexample
17167 @ifclear vms
17168 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
17169 @end ifclear
17170 @ifset vms
17171 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
17172 @end ifset
17173 @end smallexample
17174
17175 @noindent
17176 then we will get the following name casing in the @command{gnatpp} output:
17177
17178 @smallexample @c ada
17179 @cartouche
17180 procedure Test is
17181    NAME1             : Integer := 1;
17182    Name4_NAME3_Name2 : Integer := 2;
17183    Name2_NAME3_Name4 : Boolean;
17184    Name1_Var         : Float;
17185 begin
17186    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
17187 end Test;
17188 @end cartouche
17189 @end smallexample
17190
17191 @c *********************************
17192 @node The GNAT Metric Tool gnatmetric
17193 @chapter The GNAT Metric Tool @command{gnatmetric}
17194 @findex gnatmetric
17195 @cindex Metric tool
17196
17197 @noindent
17198 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
17199 for computing various program metrics.
17200 It takes an Ada source file as input and generates a file containing the
17201 metrics data as output. Various switches control which
17202 metrics are computed and output.
17203
17204 @command{gnatmetric} generates and uses the ASIS
17205 tree for the input source and thus requires the input to be syntactically and
17206 semantically legal.
17207 If this condition is not met, @command{gnatmetric} will generate
17208 an error message; no metric information for this file will be
17209 computed and reported.
17210
17211 If the compilation unit contained in the input source depends semantically
17212 upon units in files located outside the current directory, you have to provide
17213 the source search path when invoking @command{gnatmetric}.
17214 If it depends semantically upon units that are contained
17215 in files with names that do not follow the GNAT file naming rules, you have to
17216 provide the configuration file describing the corresponding naming scheme (see
17217 the description of the @command{gnatmetric} switches below.)
17218 Alternatively, you may use a project file and invoke @command{gnatmetric}
17219 through the @command{gnat} driver.
17220
17221 The @command{gnatmetric} command has the form
17222
17223 @smallexample
17224 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
17225 @c Expanding @ovar macro inline (explanation in macro def comments)
17226 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
17227 @end smallexample
17228
17229 @noindent
17230 where
17231 @itemize @bullet
17232 @item
17233 @var{switches} specify the metrics to compute and define the destination for
17234 the output
17235
17236 @item
17237 Each @var{filename} is the name (including the extension) of a source
17238 file to process. ``Wildcards'' are allowed, and
17239 the file name may contain path information.
17240 If no @var{filename} is supplied, then the @var{switches} list must contain
17241 at least one
17242 @option{-files} switch (@pxref{Other gnatmetric Switches}).
17243 Including both a @option{-files} switch and one or more
17244 @var{filename} arguments is permitted.
17245
17246 @item
17247 @samp{@var{gcc_switches}} is a list of switches for
17248 @command{gcc}. They will be passed on to all compiler invocations made by
17249 @command{gnatmetric} to generate the ASIS trees. Here you can provide
17250 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
17251 and use the @option{-gnatec} switch to set the configuration file.
17252 @end itemize
17253
17254 @menu
17255 * Switches for gnatmetric::
17256 @end menu
17257
17258 @node Switches for gnatmetric
17259 @section Switches for @command{gnatmetric}
17260
17261 @noindent
17262 The following subsections describe the various switches accepted by
17263 @command{gnatmetric}, organized by category.
17264
17265 @menu
17266 * Output Files Control::
17267 * Disable Metrics For Local Units::
17268 * Specifying a set of metrics to compute::
17269 * Other gnatmetric Switches::
17270 * Generate project-wide metrics::
17271 @end menu
17272
17273 @node Output Files Control
17274 @subsection Output File Control
17275 @cindex Output file control in @command{gnatmetric}
17276
17277 @noindent
17278 @command{gnatmetric} has two output formats. It can generate a
17279 textual (human-readable) form, and also XML. By default only textual
17280 output is generated.
17281
17282 When generating the output in textual form, @command{gnatmetric} creates
17283 for each Ada source file a corresponding text file
17284 containing the computed metrics, except for the case when the set of metrics
17285 specified by gnatmetric parameters consists only of metrics that are computed
17286 for the whole set of analyzed sources, but not for each Ada source.
17287 By default, this file is placed in the same directory as where the source
17288 file is located, and its name is obtained
17289 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
17290 input file.
17291
17292 All the output information generated in XML format is placed in a single
17293 file. By default this file is placed in the current directory and has the
17294 name ^@file{metrix.xml}^@file{METRIX$XML}^.
17295
17296 Some of the computed metrics are summed over the units passed to
17297 @command{gnatmetric}; for example, the total number of lines of code.
17298 By default this information is sent to @file{stdout}, but a file
17299 can be specified with the @option{-og} switch.
17300
17301 The following switches control the @command{gnatmetric} output:
17302
17303 @table @option
17304 @cindex @option{^-x^/XML^} (@command{gnatmetric})
17305 @item ^-x^/XML^
17306 Generate the XML output
17307
17308 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
17309 @item ^-xs^/XSD^
17310 Generate the XML output and the XML schema file that describes the structure
17311 of the XML metric report, this schema is assigned to the XML file. The schema
17312 file has the same name as the XML output file with @file{.xml} suffix replaced
17313 with @file{.xsd}
17314
17315 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
17316 @item ^-nt^/NO_TEXT^
17317 Do not generate the output in text form (implies @option{^-x^/XML^})
17318
17319 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
17320 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
17321 Put text files with detailed metrics into @var{output_dir}
17322
17323 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
17324 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
17325 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
17326 in the name of the output file.
17327
17328 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
17329 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
17330 Put global metrics into @var{file_name}
17331
17332 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
17333 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
17334 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
17335
17336 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
17337 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
17338 Use ``short'' source file names in the output.  (The @command{gnatmetric}
17339 output includes the name(s) of the Ada source file(s) from which the metrics
17340 are computed.  By default each name includes the absolute path. The
17341 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
17342 to exclude all directory information from the file names that are output.)
17343
17344 @end table
17345
17346 @node Disable Metrics For Local Units
17347 @subsection Disable Metrics For Local Units
17348 @cindex Disable Metrics For Local Units in @command{gnatmetric}
17349
17350 @noindent
17351 @command{gnatmetric} relies on the GNAT compilation model @minus{}
17352 one compilation
17353 unit per one source file. It computes line metrics for the whole source
17354 file, and it also computes syntax
17355 and complexity metrics for the file's outermost unit.
17356
17357 By default, @command{gnatmetric} will also compute all metrics for certain
17358 kinds of locally declared program units:
17359
17360 @itemize @bullet
17361 @item
17362 subprogram (and generic subprogram) bodies;
17363
17364 @item
17365 package (and generic package) specs and bodies;
17366
17367 @item
17368 task object and type specifications and bodies;
17369
17370 @item
17371 protected object and type specifications and bodies.
17372 @end itemize
17373
17374 @noindent
17375 These kinds of entities will be referred to as
17376 @emph{eligible local program units}, or simply @emph{eligible local units},
17377 @cindex Eligible local unit (for @command{gnatmetric})
17378 in the discussion below.
17379
17380 Note that a subprogram declaration, generic instantiation,
17381 or renaming declaration only receives metrics
17382 computation when it appear as the outermost entity
17383 in a source file.
17384
17385 Suppression of metrics computation for eligible local units can be
17386 obtained via the following switch:
17387
17388 @table @option
17389 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
17390 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
17391 Do not compute detailed metrics for eligible local program units
17392
17393 @end table
17394
17395 @node Specifying a set of metrics to compute
17396 @subsection Specifying a set of metrics to compute
17397
17398 @noindent
17399 By default all the metrics are computed and reported. The switches
17400 described in this subsection allow you to control, on an individual
17401 basis, whether metrics are computed and
17402 reported. If at least one positive metric
17403 switch is specified (that is, a switch that defines that a given
17404 metric or set of metrics is to be computed), then only
17405 explicitly specified metrics are reported.
17406
17407 @menu
17408 * Line Metrics Control::
17409 * Syntax Metrics Control::
17410 * Complexity Metrics Control::
17411 * Object-Oriented Metrics Control::
17412 @end menu
17413
17414 @node Line Metrics Control
17415 @subsubsection Line Metrics Control
17416 @cindex Line metrics control in @command{gnatmetric}
17417
17418 @noindent
17419 For any (legal) source file, and for each of its
17420 eligible local program units, @command{gnatmetric} computes the following
17421 metrics:
17422
17423 @itemize @bullet
17424 @item
17425 the total number of lines;
17426
17427 @item
17428 the total number of code lines (i.e., non-blank lines that are not comments)
17429
17430 @item
17431 the number of comment lines
17432
17433 @item
17434 the number of code lines containing end-of-line comments;
17435
17436 @item
17437 the comment percentage: the ratio between the number of lines that contain
17438 comments and the number of all non-blank lines, expressed as a percentage;
17439
17440 @item
17441 the number of empty lines and lines containing only space characters and/or
17442 format effectors (blank lines)
17443
17444 @item
17445 the average number of code lines in subprogram bodies, task bodies, entry
17446 bodies and statement sequences in package bodies (this metric is only computed
17447 across the whole set of the analyzed units)
17448
17449 @end itemize
17450
17451 @noindent
17452 @command{gnatmetric} sums the values of the line metrics for all the
17453 files being processed and then generates the cumulative results. The tool
17454 also computes for all the files being processed the average number of code
17455 lines in bodies.
17456
17457 You can use the following switches to select the specific line metrics
17458 to be computed and reported.
17459
17460 @table @option
17461 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
17462
17463 @ifclear vms
17464 @cindex @option{--no-lines@var{x}}
17465 @end ifclear
17466
17467 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
17468 Report all the line metrics
17469
17470 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
17471 Do not report any of line metrics
17472
17473 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
17474 Report the number of all lines
17475
17476 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
17477 Do not report the number of all lines
17478
17479 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
17480 Report the number of code lines
17481
17482 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
17483 Do not report the number of code lines
17484
17485 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
17486 Report the number of comment lines
17487
17488 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
17489 Do not report the number of comment lines
17490
17491 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
17492 Report the number of code lines containing
17493 end-of-line comments
17494
17495 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
17496 Do not report the number of code lines containing
17497 end-of-line comments
17498
17499 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
17500 Report the comment percentage in the program text
17501
17502 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
17503 Do not report the comment percentage in the program text
17504
17505 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
17506 Report the number of blank lines
17507
17508 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
17509 Do not report the number of blank lines
17510
17511 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
17512 Report the average number of code lines in subprogram bodies, task bodies,
17513 entry bodies and statement sequences in package bodies. The metric is computed
17514 and reported for the whole set of processed Ada sources only.
17515
17516 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
17517 Do not report the average number of code lines in subprogram bodies,
17518 task bodies, entry bodies and statement sequences in package bodies.
17519
17520 @end table
17521
17522 @node Syntax Metrics Control
17523 @subsubsection Syntax Metrics Control
17524 @cindex Syntax metrics control in @command{gnatmetric}
17525
17526 @noindent
17527 @command{gnatmetric} computes various syntactic metrics for the
17528 outermost unit and for each eligible local unit:
17529
17530 @table @emph
17531 @item LSLOC (``Logical Source Lines Of Code'')
17532 The total number of declarations and the total number of statements
17533
17534 @item Maximal static nesting level of inner program units
17535 According to
17536 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
17537 package, a task unit, a protected unit, a
17538 protected entry, a generic unit, or an explicitly declared subprogram other
17539 than an enumeration literal.''
17540
17541 @item Maximal nesting level of composite syntactic constructs
17542 This corresponds to the notion of the
17543 maximum nesting level in the GNAT built-in style checks
17544 (@pxref{Style Checking})
17545 @end table
17546
17547 @noindent
17548 For the outermost unit in the file, @command{gnatmetric} additionally computes
17549 the following metrics:
17550
17551 @table @emph
17552 @item Public subprograms
17553 This metric is computed for package specs. It is the
17554 number of subprograms and generic subprograms declared in the visible
17555 part (including the visible part of nested packages, protected objects, and
17556 protected types).
17557
17558 @item All subprograms
17559 This metric is computed for bodies and subunits. The
17560 metric is equal to a total number of subprogram bodies in the compilation
17561 unit.
17562 Neither generic instantiations nor renamings-as-a-body nor body stubs
17563 are counted. Any subprogram body is counted, independently of its nesting
17564 level and enclosing constructs. Generic bodies and bodies of protected
17565 subprograms are counted in the same way as ``usual'' subprogram bodies.
17566
17567 @item Public types
17568 This metric is computed for package specs and
17569 generic package declarations. It is the total number of types
17570 that can be referenced from outside this compilation unit, plus the
17571 number of types from all the visible parts of all the visible generic
17572 packages. Generic formal types are not counted.  Only types, not subtypes,
17573 are included.
17574
17575 @noindent
17576 Along with the total number of public types, the following
17577 types are counted and reported separately:
17578
17579 @itemize @bullet
17580 @item
17581 Abstract types
17582
17583 @item
17584 Root tagged types (abstract, non-abstract, private, non-private). Type
17585 extensions are @emph{not} counted
17586
17587 @item
17588 Private types (including private extensions)
17589
17590 @item
17591 Task types
17592
17593 @item
17594 Protected types
17595
17596 @end itemize
17597
17598 @item All types
17599 This metric is computed for any compilation unit. It is equal to the total
17600 number of the declarations of different types given in the compilation unit.
17601 The private and the corresponding full type declaration are counted as one
17602 type declaration. Incomplete type declarations and generic formal types
17603 are not counted.
17604 No distinction is made among different kinds of types (abstract,
17605 private etc.); the total number of types is computed and reported.
17606
17607 @end table
17608
17609 @noindent
17610 By default, all the syntax metrics are computed and reported. You can use the
17611 following switches to select specific syntax metrics.
17612
17613 @table @option
17614
17615 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
17616
17617 @ifclear vms
17618 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
17619 @end ifclear
17620
17621 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
17622 Report all the syntax metrics
17623
17624 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
17625 Do not report any of syntax metrics
17626
17627 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
17628 Report the total number of declarations
17629
17630 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
17631 Do not report the total number of declarations
17632
17633 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
17634 Report the total number of statements
17635
17636 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
17637 Do not report the total number of statements
17638
17639 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
17640 Report the number of public subprograms in a compilation unit
17641
17642 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
17643 Do not report the number of public subprograms in a compilation unit
17644
17645 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
17646 Report the number of all the subprograms in a compilation unit
17647
17648 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
17649 Do not report the number of all the subprograms in a compilation unit
17650
17651 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
17652 Report the number of public types in a compilation unit
17653
17654 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
17655 Do not report the number of public types in a compilation unit
17656
17657 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
17658 Report the number of all the types in a compilation unit
17659
17660 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
17661 Do not report the number of all the types in a compilation unit
17662
17663 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
17664 Report the maximal program unit nesting level
17665
17666 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
17667 Do not report the maximal program unit nesting level
17668
17669 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
17670 Report the maximal construct nesting level
17671
17672 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
17673 Do not report the maximal construct nesting level
17674
17675 @end table
17676
17677 @node Complexity Metrics Control
17678 @subsubsection Complexity Metrics Control
17679 @cindex Complexity metrics control in @command{gnatmetric}
17680
17681 @noindent
17682 For a program unit that is an executable body (a subprogram body (including
17683 generic bodies), task body, entry body or a package body containing
17684 its own statement sequence) @command{gnatmetric} computes the following
17685 complexity metrics:
17686
17687 @itemize @bullet
17688 @item
17689 McCabe cyclomatic complexity;
17690
17691 @item
17692 McCabe essential complexity;
17693
17694 @item
17695 maximal loop nesting level
17696
17697 @end itemize
17698
17699 @noindent
17700 The McCabe complexity metrics are defined
17701 in @url{http://www.mccabe.com/pdf/nist235r.pdf}
17702
17703 According to McCabe, both control statements and short-circuit control forms
17704 should be taken into account when computing cyclomatic complexity. For each
17705 body, we compute three metric values:
17706
17707 @itemize @bullet
17708 @item
17709 the complexity introduced by control
17710 statements only, without taking into account short-circuit forms,
17711
17712 @item
17713 the complexity introduced by short-circuit control forms only, and
17714
17715 @item
17716 the total
17717 cyclomatic complexity, which is the sum of these two values.
17718 @end itemize
17719
17720 @noindent
17721 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
17722 the code in the exception handlers and in all the nested program units.
17723
17724 By default, all the complexity metrics are computed and reported.
17725 For more fine-grained control you can use
17726 the following switches:
17727
17728 @table @option
17729 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
17730
17731 @ifclear vms
17732 @cindex @option{--no-complexity@var{x}}
17733 @end ifclear
17734
17735 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
17736 Report all the complexity metrics
17737
17738 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
17739 Do not report any of complexity metrics
17740
17741 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
17742 Report the McCabe Cyclomatic Complexity
17743
17744 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
17745 Do not report the McCabe Cyclomatic Complexity
17746
17747 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
17748 Report the Essential Complexity
17749
17750 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
17751 Do not report the Essential Complexity
17752
17753 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
17754 Report maximal loop nesting level
17755
17756 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
17757 Do not report maximal loop nesting level
17758
17759 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
17760 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
17761 task bodies, entry bodies and statement sequences in package bodies.
17762 The metric is computed and reported for whole set of processed Ada sources
17763 only.
17764
17765 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
17766 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
17767 bodies, task bodies, entry bodies and statement sequences in package bodies
17768
17769 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
17770 @item ^-ne^/NO_EXITS_AS_GOTOS^
17771 Do not consider @code{exit} statements as @code{goto}s when
17772 computing Essential Complexity
17773
17774 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
17775 Report the extra exit points for subprogram bodies. As an exit point, this
17776 metric counts @code{return} statements and raise statements in case when the
17777 raised exception is not handled in the same body. In case of a function this
17778 metric subtracts 1 from the number of exit points, because a function body
17779 must contain at least one @code{return} statement.
17780
17781 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
17782 Do not report the extra exit points for subprogram bodies
17783 @end table
17784
17785
17786 @node Object-Oriented Metrics Control
17787 @subsubsection Object-Oriented Metrics Control
17788 @cindex Object-Oriented metrics control in @command{gnatmetric}
17789
17790 @noindent
17791 @cindex Coupling metrics (in in @command{gnatmetric})
17792 Coupling metrics are object-oriented metrics that measure the
17793 dependencies between a given class (or a group of classes) and the
17794 ``external world'' (that is, the other classes in the program). In this
17795 subsection the term ``class'' is used in its
17796 traditional object-oriented programming sense
17797 (an instantiable module that contains data and/or method members).
17798 A @emph{category} (of classes)
17799 is a group of closely related classes that are reused and/or
17800 modified together.
17801
17802 A class @code{K}'s @emph{efferent coupling} is the number of classes
17803 that @code{K} depends upon.
17804 A category's efferent coupling is the number of classes outside the
17805 category that the classes inside the category depend upon.
17806
17807 A class @code{K}'s @emph{afferent coupling} is the number of classes
17808 that depend upon @code{K}.
17809 A category's afferent coupling is the number of classes outside the
17810 category that depend on classes belonging to the category.
17811
17812 Ada's implementation of the object-oriented paradigm does not use the
17813 traditional class notion, so the definition of the coupling
17814 metrics for Ada maps the class and class category notions
17815 onto Ada constructs.
17816
17817 For the coupling metrics, several kinds of modules -- a library package,
17818 a library generic package, and a library generic package instantiation --
17819 that define a tagged type or an interface type are
17820 considered to be a class. A category consists of a library package (or
17821 a library generic package) that defines a tagged or an interface type,
17822 together with all its descendant (generic) packages that define tagged
17823 or interface types. For any package counted as a class,
17824 its body and subunits (if any) are considered
17825 together with its spec when counting the dependencies, and coupling
17826 metrics are reported for spec units only. For dependencies
17827 between classes, the Ada semantic dependencies are considered.
17828 For coupling metrics, only dependencies on units that are considered as
17829 classes, are considered.
17830
17831 When computing coupling metrics, @command{gnatmetric} counts only
17832 dependencies between units that are arguments of the gnatmetric call.
17833 Coupling metrics are program-wide (or project-wide) metrics, so to
17834 get a valid result, you should call @command{gnatmetric} for
17835 the whole set of sources that make up your program. It can be done
17836 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
17837 option (see See @ref{The GNAT Driver and Project Files} for details.
17838
17839 By default, all the coupling metrics are disabled. You can use the following
17840 switches to specify the coupling metrics to be computed and reported:
17841
17842 @table @option
17843
17844 @ifclear vms
17845 @cindex @option{--package@var{x}} (@command{gnatmetric})
17846 @cindex @option{--no-package@var{x}} (@command{gnatmetric})
17847 @cindex @option{--category@var{x}} (@command{gnatmetric})
17848 @cindex @option{--no-category@var{x}} (@command{gnatmetric})
17849 @end ifclear
17850
17851 @ifset vms
17852 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
17853 @end ifset
17854
17855 @item ^--coupling-all^/COUPLING_METRICS=ALL^
17856 Report all the coupling metrics
17857
17858 @item ^--no-coupling-all^/COUPLING_METRICS=NONE^
17859 Do not report any of  metrics
17860
17861 @item ^--package-efferent-coupling^/COUPLING_METRICS=PACKAGE_EFFERENT^
17862 Report package efferent coupling
17863
17864 @item ^--no-package-efferent-coupling^/COUPLING_METRICS=NOPACKAGE_EFFERENT^
17865 Do not report package efferent coupling
17866
17867 @item ^--package-afferent-coupling^/COUPLING_METRICS=PACKAGE_AFFERENT^
17868 Report package afferent coupling
17869
17870 @item ^--no-package-afferent-coupling^/COUPLING_METRICS=NOPACKAGE_AFFERENT^
17871 Do not report package afferent coupling
17872
17873 @item ^--category-efferent-coupling^/COUPLING_METRICS=CATEGORY_EFFERENT^
17874 Report category efferent coupling
17875
17876 @item ^--no-category-efferent-coupling^/COUPLING_METRICS=NOCATEGORY_EFFERENT^
17877 Do not report category efferent coupling
17878
17879 @item ^--category-afferent-coupling^/COUPLING_METRICS=CATEGORY_AFFERENT^
17880 Report category afferent coupling
17881
17882 @item ^--no-category-afferent-coupling^/COUPLING_METRICS=NOCATEGORY_AFFERENT^
17883 Do not report category afferent coupling
17884
17885 @end table
17886
17887 @node Other gnatmetric Switches
17888 @subsection Other @code{gnatmetric} Switches
17889
17890 @noindent
17891 Additional @command{gnatmetric} switches are as follows:
17892
17893 @table @option
17894 @item ^-files @var{filename}^/FILES=@var{filename}^
17895 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
17896 Take the argument source files from the specified file. This file should be an
17897 ordinary text file containing file names separated by spaces or
17898 line breaks. You can use this switch more than once in the same call to
17899 @command{gnatmetric}. You also can combine this switch with
17900 an explicit list of files.
17901
17902 @item ^-v^/VERBOSE^
17903 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
17904 Verbose mode;
17905 @command{gnatmetric} generates version information and then
17906 a trace of sources being processed.
17907
17908 @item ^-dv^/DEBUG_OUTPUT^
17909 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
17910 Debug mode;
17911 @command{gnatmetric} generates various messages useful to understand what
17912 happens during the metrics computation
17913
17914 @item ^-q^/QUIET^
17915 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
17916 Quiet mode.
17917 @end table
17918
17919 @node Generate project-wide metrics
17920 @subsection Generate project-wide metrics
17921
17922 In order to compute metrics on all units of a given project, you can use
17923 the @command{gnat} driver along with the @option{-P} option:
17924 @smallexample
17925    gnat metric -Pproj
17926 @end smallexample
17927
17928 @noindent
17929 If the project @code{proj} depends upon other projects, you can compute
17930 the metrics on the project closure using the @option{-U} option:
17931 @smallexample
17932    gnat metric -Pproj -U
17933 @end smallexample
17934
17935 @noindent
17936 Finally, if not all the units are relevant to a particular main
17937 program in the project closure, you can generate metrics for the set
17938 of units needed to create a given main program (unit closure) using
17939 the @option{-U} option followed by the name of the main unit:
17940 @smallexample
17941    gnat metric -Pproj -U main
17942 @end smallexample
17943
17944
17945 @c ***********************************
17946 @node File Name Krunching Using gnatkr
17947 @chapter File Name Krunching Using @code{gnatkr}
17948 @findex gnatkr
17949
17950 @noindent
17951 This chapter discusses the method used by the compiler to shorten
17952 the default file names chosen for Ada units so that they do not
17953 exceed the maximum length permitted. It also describes the
17954 @code{gnatkr} utility that can be used to determine the result of
17955 applying this shortening.
17956 @menu
17957 * About gnatkr::
17958 * Using gnatkr::
17959 * Krunching Method::
17960 * Examples of gnatkr Usage::
17961 @end menu
17962
17963 @node About gnatkr
17964 @section About @code{gnatkr}
17965
17966 @noindent
17967 The default file naming rule in GNAT
17968 is that the file name must be derived from
17969 the unit name. The exact default rule is as follows:
17970 @itemize @bullet
17971 @item
17972 Take the unit name and replace all dots by hyphens.
17973 @item
17974 If such a replacement occurs in the
17975 second character position of a name, and the first character is
17976 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
17977 then replace the dot by the character
17978 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
17979 instead of a minus.
17980 @end itemize
17981 The reason for this exception is to avoid clashes
17982 with the standard names for children of System, Ada, Interfaces,
17983 and GNAT, which use the prefixes
17984 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
17985 respectively.
17986
17987 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
17988 switch of the compiler activates a ``krunching''
17989 circuit that limits file names to nn characters (where nn is a decimal
17990 integer). For example, using OpenVMS,
17991 where the maximum file name length is
17992 39, the value of nn is usually set to 39, but if you want to generate
17993 a set of files that would be usable if ported to a system with some
17994 different maximum file length, then a different value can be specified.
17995 The default value of 39 for OpenVMS need not be specified.
17996
17997 The @code{gnatkr} utility can be used to determine the krunched name for
17998 a given file, when krunched to a specified maximum length.
17999
18000 @node Using gnatkr
18001 @section Using @code{gnatkr}
18002
18003 @noindent
18004 The @code{gnatkr} command has the form
18005
18006 @ifclear vms
18007 @smallexample
18008 @c $ gnatkr @var{name} @ovar{length}
18009 @c Expanding @ovar macro inline (explanation in macro def comments)
18010 $ gnatkr @var{name} @r{[}@var{length}@r{]}
18011 @end smallexample
18012 @end ifclear
18013
18014 @ifset vms
18015 @smallexample
18016 $ gnatkr @var{name} /COUNT=nn
18017 @end smallexample
18018 @end ifset
18019
18020 @noindent
18021 @var{name} is the uncrunched file name, derived from the name of the unit
18022 in the standard manner described in the previous section (i.e., in particular
18023 all dots are replaced by hyphens). The file name may or may not have an
18024 extension (defined as a suffix of the form period followed by arbitrary
18025 characters other than period). If an extension is present then it will
18026 be preserved in the output. For example, when krunching @file{hellofile.ads}
18027 to eight characters, the result will be hellofil.ads.
18028
18029 Note: for compatibility with previous versions of @code{gnatkr} dots may
18030 appear in the name instead of hyphens, but the last dot will always be
18031 taken as the start of an extension. So if @code{gnatkr} is given an argument
18032 such as @file{Hello.World.adb} it will be treated exactly as if the first
18033 period had been a hyphen, and for example krunching to eight characters
18034 gives the result @file{hellworl.adb}.
18035
18036 Note that the result is always all lower case (except on OpenVMS where it is
18037 all upper case). Characters of the other case are folded as required.
18038
18039 @var{length} represents the length of the krunched name. The default
18040 when no argument is given is ^8^39^ characters. A length of zero stands for
18041 unlimited, in other words do not chop except for system files where the
18042 implied crunching length is always eight characters.
18043
18044 @noindent
18045 The output is the krunched name. The output has an extension only if the
18046 original argument was a file name with an extension.
18047
18048 @node Krunching Method
18049 @section Krunching Method
18050
18051 @noindent
18052 The initial file name is determined by the name of the unit that the file
18053 contains. The name is formed by taking the full expanded name of the
18054 unit and replacing the separating dots with hyphens and
18055 using ^lowercase^uppercase^
18056 for all letters, except that a hyphen in the second character position is
18057 replaced by a ^tilde^dollar sign^ if the first character is
18058 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
18059 The extension is @code{.ads} for a
18060 spec and @code{.adb} for a body.
18061 Krunching does not affect the extension, but the file name is shortened to
18062 the specified length by following these rules:
18063
18064 @itemize @bullet
18065 @item
18066 The name is divided into segments separated by hyphens, tildes or
18067 underscores and all hyphens, tildes, and underscores are
18068 eliminated. If this leaves the name short enough, we are done.
18069
18070 @item
18071 If the name is too long, the longest segment is located (left-most
18072 if there are two of equal length), and shortened by dropping
18073 its last character. This is repeated until the name is short enough.
18074
18075 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
18076 to fit the name into 8 characters as required by some operating systems.
18077
18078 @smallexample
18079 our-strings-wide_fixed 22
18080 our strings wide fixed 19
18081 our string  wide fixed 18
18082 our strin   wide fixed 17
18083 our stri    wide fixed 16
18084 our stri    wide fixe  15
18085 our str     wide fixe  14
18086 our str     wid  fixe  13
18087 our str     wid  fix   12
18088 ou  str     wid  fix   11
18089 ou  st      wid  fix   10
18090 ou  st      wi   fix   9
18091 ou  st      wi   fi    8
18092 Final file name: oustwifi.adb
18093 @end smallexample
18094
18095 @item
18096 The file names for all predefined units are always krunched to eight
18097 characters. The krunching of these predefined units uses the following
18098 special prefix replacements:
18099
18100 @table @file
18101 @item ada-
18102 replaced by @file{^a^A^-}
18103
18104 @item gnat-
18105 replaced by @file{^g^G^-}
18106
18107 @item interfaces-
18108 replaced by @file{^i^I^-}
18109
18110 @item system-
18111 replaced by @file{^s^S^-}
18112 @end table
18113
18114 These system files have a hyphen in the second character position. That
18115 is why normal user files replace such a character with a
18116 ^tilde^dollar sign^, to
18117 avoid confusion with system file names.
18118
18119 As an example of this special rule, consider
18120 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
18121
18122 @smallexample
18123 ada-strings-wide_fixed 22
18124 a-  strings wide fixed 18
18125 a-  string  wide fixed 17
18126 a-  strin   wide fixed 16
18127 a-  stri    wide fixed 15
18128 a-  stri    wide fixe  14
18129 a-  str     wide fixe  13
18130 a-  str     wid  fixe  12
18131 a-  str     wid  fix   11
18132 a-  st      wid  fix   10
18133 a-  st      wi   fix   9
18134 a-  st      wi   fi    8
18135 Final file name: a-stwifi.adb
18136 @end smallexample
18137 @end itemize
18138
18139 Of course no file shortening algorithm can guarantee uniqueness over all
18140 possible unit names, and if file name krunching is used then it is your
18141 responsibility to ensure that no name clashes occur. The utility
18142 program @code{gnatkr} is supplied for conveniently determining the
18143 krunched name of a file.
18144
18145 @node Examples of gnatkr Usage
18146 @section Examples of @code{gnatkr} Usage
18147
18148 @smallexample
18149 @iftex
18150 @leftskip=0cm
18151 @end iftex
18152 @ifclear vms
18153 $ gnatkr very_long_unit_name.ads      --> velounna.ads
18154 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
18155 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
18156 $ gnatkr grandparent-parent-child     --> grparchi
18157 @end ifclear
18158 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
18159 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
18160 @end smallexample
18161
18162 @node Preprocessing Using gnatprep
18163 @chapter Preprocessing Using @code{gnatprep}
18164 @findex gnatprep
18165
18166 @noindent
18167 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
18168 preprocessing.
18169 Although designed for use with GNAT, @code{gnatprep} does not depend on any
18170 special GNAT features.
18171 For further discussion of conditional compilation in general, see
18172 @ref{Conditional Compilation}.
18173
18174 @menu
18175 * Preprocessing Symbols::
18176 * Using gnatprep::
18177 * Switches for gnatprep::
18178 * Form of Definitions File::
18179 * Form of Input Text for gnatprep::
18180 @end menu
18181
18182 @node Preprocessing Symbols
18183 @section Preprocessing Symbols
18184
18185 @noindent
18186 Preprocessing symbols are defined in definition files and referred to in
18187 sources to be preprocessed. A Preprocessing symbol is an identifier, following
18188 normal Ada (case-insensitive) rules for its syntax, with the restriction that
18189 all characters need to be in the ASCII set (no accented letters).
18190
18191 @node Using gnatprep
18192 @section Using @code{gnatprep}
18193
18194 @noindent
18195 To call @code{gnatprep} use
18196
18197 @smallexample
18198 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
18199 @c Expanding @ovar macro inline (explanation in macro def comments)
18200 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
18201 @end smallexample
18202
18203 @noindent
18204 where
18205 @table @var
18206 @item switches
18207 is an optional sequence of switches as described in the next section.
18208
18209 @item infile
18210 is the full name of the input file, which is an Ada source
18211 file containing preprocessor directives.
18212
18213 @item outfile
18214 is the full name of the output file, which is an Ada source
18215 in standard Ada form. When used with GNAT, this file name will
18216 normally have an ads or adb suffix.
18217
18218 @item deffile
18219 is the full name of a text file containing definitions of
18220 preprocessing symbols to be referenced by the preprocessor. This argument is
18221 optional, and can be replaced by the use of the @option{-D} switch.
18222
18223 @end table
18224
18225 @node Switches for gnatprep
18226 @section Switches for @code{gnatprep}
18227
18228 @table @option
18229 @c !sort!
18230
18231 @item ^-b^/BLANK_LINES^
18232 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
18233 Causes both preprocessor lines and the lines deleted by
18234 preprocessing to be replaced by blank lines in the output source file,
18235 preserving line numbers in the output file.
18236
18237 @item ^-c^/COMMENTS^
18238 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
18239 Causes both preprocessor lines and the lines deleted
18240 by preprocessing to be retained in the output source as comments marked
18241 with the special string @code{"--! "}. This option will result in line numbers
18242 being preserved in the output file.
18243
18244 @item ^-C^/REPLACE_IN_COMMENTS^
18245 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
18246 Causes comments to be scanned. Normally comments are ignored by gnatprep.
18247 If this option is specified, then comments are scanned and any $symbol
18248 substitutions performed as in program text. This is particularly useful
18249 when structured comments are used (e.g., when writing programs in the
18250 SPARK dialect of Ada). Note that this switch is not available when
18251 doing integrated preprocessing (it would be useless in this context
18252 since comments are ignored by the compiler in any case).
18253
18254 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
18255 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
18256 Defines a new preprocessing symbol, associated with value. If no value is given
18257 on the command line, then symbol is considered to be @code{True}. This switch
18258 can be used in place of a definition file.
18259
18260 @ifset vms
18261 @item /REMOVE
18262 @cindex @option{/REMOVE} (@command{gnatprep})
18263 This is the default setting which causes lines deleted by preprocessing
18264 to be entirely removed from the output file.
18265 @end ifset
18266
18267 @item ^-r^/REFERENCE^
18268 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
18269 Causes a @code{Source_Reference} pragma to be generated that
18270 references the original input file, so that error messages will use
18271 the file name of this original file. The use of this switch implies
18272 that preprocessor lines are not to be removed from the file, so its
18273 use will force @option{^-b^/BLANK_LINES^} mode if
18274 @option{^-c^/COMMENTS^}
18275 has not been specified explicitly.
18276
18277 Note that if the file to be preprocessed contains multiple units, then
18278 it will be necessary to @code{gnatchop} the output file from
18279 @code{gnatprep}. If a @code{Source_Reference} pragma is present
18280 in the preprocessed file, it will be respected by
18281 @code{gnatchop ^-r^/REFERENCE^}
18282 so that the final chopped files will correctly refer to the original
18283 input source file for @code{gnatprep}.
18284
18285 @item ^-s^/SYMBOLS^
18286 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
18287 Causes a sorted list of symbol names and values to be
18288 listed on the standard output file.
18289
18290 @item ^-u^/UNDEFINED^
18291 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
18292 Causes undefined symbols to be treated as having the value FALSE in the context
18293 of a preprocessor test. In the absence of this option, an undefined symbol in
18294 a @code{#if} or @code{#elsif} test will be treated as an error.
18295
18296 @end table
18297
18298 @ifclear vms
18299 @noindent
18300 Note: if neither @option{-b} nor @option{-c} is present,
18301 then preprocessor lines and
18302 deleted lines are completely removed from the output, unless -r is
18303 specified, in which case -b is assumed.
18304 @end ifclear
18305
18306 @node Form of Definitions File
18307 @section Form of Definitions File
18308
18309 @noindent
18310 The definitions file contains lines of the form
18311
18312 @smallexample
18313 symbol := value
18314 @end smallexample
18315
18316 @noindent
18317 where symbol is a preprocessing symbol, and value is one of the following:
18318
18319 @itemize @bullet
18320 @item
18321 Empty, corresponding to a null substitution
18322 @item
18323 A string literal using normal Ada syntax
18324 @item
18325 Any sequence of characters from the set
18326 (letters, digits, period, underline).
18327 @end itemize
18328
18329 @noindent
18330 Comment lines may also appear in the definitions file, starting with
18331 the usual @code{--},
18332 and comments may be added to the definitions lines.
18333
18334 @node Form of Input Text for gnatprep
18335 @section Form of Input Text for @code{gnatprep}
18336
18337 @noindent
18338 The input text may contain preprocessor conditional inclusion lines,
18339 as well as general symbol substitution sequences.
18340
18341 The preprocessor conditional inclusion commands have the form
18342
18343 @smallexample
18344 @group
18345 @cartouche
18346 #if @i{expression} @r{[}then@r{]}
18347    lines
18348 #elsif @i{expression} @r{[}then@r{]}
18349    lines
18350 #elsif @i{expression} @r{[}then@r{]}
18351    lines
18352 @dots{}
18353 #else
18354    lines
18355 #end if;
18356 @end cartouche
18357 @end group
18358 @end smallexample
18359
18360 @noindent
18361 In this example, @i{expression} is defined by the following grammar:
18362 @smallexample
18363 @i{expression} ::=  <symbol>
18364 @i{expression} ::=  <symbol> = "<value>"
18365 @i{expression} ::=  <symbol> = <symbol>
18366 @i{expression} ::=  <symbol> 'Defined
18367 @i{expression} ::=  not @i{expression}
18368 @i{expression} ::=  @i{expression} and @i{expression}
18369 @i{expression} ::=  @i{expression} or @i{expression}
18370 @i{expression} ::=  @i{expression} and then @i{expression}
18371 @i{expression} ::=  @i{expression} or else @i{expression}
18372 @i{expression} ::=  ( @i{expression} )
18373 @end smallexample
18374
18375 The following restriction exists: it is not allowed to have "and" or "or"
18376 following "not" in the same expression without parentheses. For example, this
18377 is not allowed:
18378
18379 @smallexample
18380    not X or Y
18381 @end smallexample
18382
18383 This should be one of the following:
18384
18385 @smallexample
18386    (not X) or Y
18387    not (X or Y)
18388 @end smallexample
18389
18390 @noindent
18391 For the first test (@i{expression} ::= <symbol>) the symbol must have
18392 either the value true or false, that is to say the right-hand of the
18393 symbol definition must be one of the (case-insensitive) literals
18394 @code{True} or @code{False}. If the value is true, then the
18395 corresponding lines are included, and if the value is false, they are
18396 excluded.
18397
18398 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
18399 the symbol has been defined in the definition file or by a @option{-D}
18400 switch on the command line. Otherwise, the test is false.
18401
18402 The equality tests are case insensitive, as are all the preprocessor lines.
18403
18404 If the symbol referenced is not defined in the symbol definitions file,
18405 then the effect depends on whether or not switch @option{-u}
18406 is specified. If so, then the symbol is treated as if it had the value
18407 false and the test fails. If this switch is not specified, then
18408 it is an error to reference an undefined symbol. It is also an error to
18409 reference a symbol that is defined with a value other than @code{True}
18410 or @code{False}.
18411
18412 The use of the @code{not} operator inverts the sense of this logical test.
18413 The @code{not} operator cannot be combined with the @code{or} or @code{and}
18414 operators, without parentheses. For example, "if not X or Y then" is not
18415 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
18416
18417 The @code{then} keyword is optional as shown
18418
18419 The @code{#} must be the first non-blank character on a line, but
18420 otherwise the format is free form. Spaces or tabs may appear between
18421 the @code{#} and the keyword. The keywords and the symbols are case
18422 insensitive as in normal Ada code. Comments may be used on a
18423 preprocessor line, but other than that, no other tokens may appear on a
18424 preprocessor line. Any number of @code{elsif} clauses can be present,
18425 including none at all. The @code{else} is optional, as in Ada.
18426
18427 The @code{#} marking the start of a preprocessor line must be the first
18428 non-blank character on the line, i.e., it must be preceded only by
18429 spaces or horizontal tabs.
18430
18431 Symbol substitution outside of preprocessor lines is obtained by using
18432 the sequence
18433
18434 @smallexample
18435 $symbol
18436 @end smallexample
18437
18438 @noindent
18439 anywhere within a source line, except in a comment or within a
18440 string literal. The identifier
18441 following the @code{$} must match one of the symbols defined in the symbol
18442 definition file, and the result is to substitute the value of the
18443 symbol in place of @code{$symbol} in the output file.
18444
18445 Note that although the substitution of strings within a string literal
18446 is not possible, it is possible to have a symbol whose defined value is
18447 a string literal. So instead of setting XYZ to @code{hello} and writing:
18448
18449 @smallexample
18450 Header : String := "$XYZ";
18451 @end smallexample
18452
18453 @noindent
18454 you should set XYZ to @code{"hello"} and write:
18455
18456 @smallexample
18457 Header : String := $XYZ;
18458 @end smallexample
18459
18460 @noindent
18461 and then the substitution will occur as desired.
18462
18463 @ifset vms
18464 @node The GNAT Run-Time Library Builder gnatlbr
18465 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
18466 @findex gnatlbr
18467 @cindex Library builder
18468
18469 @noindent
18470 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
18471 supplied configuration pragmas.
18472
18473 @menu
18474 * Running gnatlbr::
18475 * Switches for gnatlbr::
18476 * Examples of gnatlbr Usage::
18477 @end menu
18478
18479 @node Running gnatlbr
18480 @section Running @code{gnatlbr}
18481
18482 @noindent
18483 The @code{gnatlbr} command has the form
18484
18485 @smallexample
18486 $ GNAT LIBRARY /@r{[}CREATE@r{|}SET@r{|}DELETE@r{]}=directory @r{[}/CONFIG=file@r{]}
18487 @end smallexample
18488
18489 @node Switches for gnatlbr
18490 @section Switches for @code{gnatlbr}
18491
18492 @noindent
18493 @code{gnatlbr} recognizes the following switches:
18494
18495 @table @option
18496 @c !sort!
18497 @item /CREATE=directory
18498 @cindex @code{/CREATE} (@code{gnatlbr})
18499 Create the new run-time library in the specified directory.
18500
18501 @item /SET=directory
18502 @cindex @code{/SET} (@code{gnatlbr})
18503 Make the library in the specified directory the current run-time library.
18504
18505 @item /DELETE=directory
18506 @cindex @code{/DELETE} (@code{gnatlbr})
18507 Delete the run-time library in the specified directory.
18508
18509 @item /CONFIG=file
18510 @cindex @code{/CONFIG} (@code{gnatlbr})
18511 With /CREATE: Use the configuration pragmas in the specified file when
18512 building the library.
18513
18514 With /SET: Use the configuration pragmas in the specified file when
18515 compiling.
18516
18517 @end table
18518
18519 @node Examples of gnatlbr Usage
18520 @section Example of @code{gnatlbr} Usage
18521
18522 @smallexample
18523 Contents of VAXFLOAT.ADC:
18524 pragma Float_Representation (VAX_Float);
18525
18526 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
18527
18528 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
18529
18530 @end smallexample
18531 @end ifset
18532
18533 @node The GNAT Library Browser gnatls
18534 @chapter The GNAT Library Browser @code{gnatls}
18535 @findex gnatls
18536 @cindex Library browser
18537
18538 @noindent
18539 @code{gnatls} is a tool that outputs information about compiled
18540 units. It gives the relationship between objects, unit names and source
18541 files. It can also be used to check the source dependencies of a unit
18542 as well as various characteristics.
18543
18544 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
18545 driver (see @ref{The GNAT Driver and Project Files}).
18546
18547 @menu
18548 * Running gnatls::
18549 * Switches for gnatls::
18550 * Examples of gnatls Usage::
18551 @end menu
18552
18553 @node Running gnatls
18554 @section Running @code{gnatls}
18555
18556 @noindent
18557 The @code{gnatls} command has the form
18558
18559 @smallexample
18560 $ gnatls switches @var{object_or_ali_file}
18561 @end smallexample
18562
18563 @noindent
18564 The main argument is the list of object or @file{ali} files
18565 (@pxref{The Ada Library Information Files})
18566 for which information is requested.
18567
18568 In normal mode, without additional option, @code{gnatls} produces a
18569 four-column listing. Each line represents information for a specific
18570 object. The first column gives the full path of the object, the second
18571 column gives the name of the principal unit in this object, the third
18572 column gives the status of the source and the fourth column gives the
18573 full path of the source representing this unit.
18574 Here is a simple example of use:
18575
18576 @smallexample
18577 $ gnatls *.o
18578 ^./^[]^demo1.o            demo1            DIF demo1.adb
18579 ^./^[]^demo2.o            demo2             OK demo2.adb
18580 ^./^[]^hello.o            h1                OK hello.adb
18581 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
18582 ^./^[]^instr.o            instr             OK instr.adb
18583 ^./^[]^tef.o              tef              DIF tef.adb
18584 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
18585 ^./^[]^tgef.o             tgef             DIF tgef.adb
18586 @end smallexample
18587
18588 @noindent
18589 The first line can be interpreted as follows: the main unit which is
18590 contained in
18591 object file @file{demo1.o} is demo1, whose main source is in
18592 @file{demo1.adb}. Furthermore, the version of the source used for the
18593 compilation of demo1 has been modified (DIF). Each source file has a status
18594 qualifier which can be:
18595
18596 @table @code
18597 @item OK (unchanged)
18598 The version of the source file used for the compilation of the
18599 specified unit corresponds exactly to the actual source file.
18600
18601 @item MOK (slightly modified)
18602 The version of the source file used for the compilation of the
18603 specified unit differs from the actual source file but not enough to
18604 require recompilation. If you use gnatmake with the qualifier
18605 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
18606 MOK will not be recompiled.
18607
18608 @item DIF (modified)
18609 No version of the source found on the path corresponds to the source
18610 used to build this object.
18611
18612 @item ??? (file not found)
18613 No source file was found for this unit.
18614
18615 @item HID (hidden,  unchanged version not first on PATH)
18616 The version of the source that corresponds exactly to the source used
18617 for compilation has been found on the path but it is hidden by another
18618 version of the same source that has been modified.
18619
18620 @end table
18621
18622 @node Switches for gnatls
18623 @section Switches for @code{gnatls}
18624
18625 @noindent
18626 @code{gnatls} recognizes the following switches:
18627
18628 @table @option
18629 @c !sort!
18630 @cindex @option{--version} @command{gnatls}
18631 Display Copyright and version, then exit disregarding all other options.
18632
18633 @item --help
18634 @cindex @option{--help} @command{gnatls}
18635 If @option{--version} was not used, display usage, then exit disregarding
18636 all other options.
18637
18638 @item ^-a^/ALL_UNITS^
18639 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
18640 Consider all units, including those of the predefined Ada library.
18641 Especially useful with @option{^-d^/DEPENDENCIES^}.
18642
18643 @item ^-d^/DEPENDENCIES^
18644 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
18645 List sources from which specified units depend on.
18646
18647 @item ^-h^/OUTPUT=OPTIONS^
18648 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
18649 Output the list of options.
18650
18651 @item ^-o^/OUTPUT=OBJECTS^
18652 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
18653 Only output information about object files.
18654
18655 @item ^-s^/OUTPUT=SOURCES^
18656 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
18657 Only output information about source files.
18658
18659 @item ^-u^/OUTPUT=UNITS^
18660 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
18661 Only output information about compilation units.
18662
18663 @item ^-files^/FILES^=@var{file}
18664 @cindex @option{^-files^/FILES^} (@code{gnatls})
18665 Take as arguments the files listed in text file @var{file}.
18666 Text file @var{file} may contain empty lines that are ignored.
18667 Each nonempty line should contain the name of an existing file.
18668 Several such switches may be specified simultaneously.
18669
18670 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18671 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
18672 @itemx ^-I^/SEARCH=^@var{dir}
18673 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
18674 @itemx -nostdinc
18675 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
18676 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
18677 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
18678 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
18679 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
18680 flags (@pxref{Switches for gnatmake}).
18681
18682 @item --RTS=@var{rts-path}
18683 @cindex @option{--RTS} (@code{gnatls})
18684 Specifies the default location of the runtime library. Same meaning as the
18685 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
18686
18687 @item ^-v^/OUTPUT=VERBOSE^
18688 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
18689 Verbose mode. Output the complete source, object and project paths. Do not use
18690 the default column layout but instead use long format giving as much as
18691 information possible on each requested units, including special
18692 characteristics such as:
18693
18694 @table @code
18695 @item  Preelaborable
18696 The unit is preelaborable in the Ada sense.
18697
18698 @item No_Elab_Code
18699 No elaboration code has been produced by the compiler for this unit.
18700
18701 @item Pure
18702 The unit is pure in the Ada sense.
18703
18704 @item Elaborate_Body
18705 The unit contains a pragma Elaborate_Body.
18706
18707 @item Remote_Types
18708 The unit contains a pragma Remote_Types.
18709
18710 @item Shared_Passive
18711 The unit contains a pragma Shared_Passive.
18712
18713 @item Predefined
18714 This unit is part of the predefined environment and cannot be modified
18715 by the user.
18716
18717 @item Remote_Call_Interface
18718 The unit contains a pragma Remote_Call_Interface.
18719
18720 @end table
18721
18722 @end table
18723
18724 @node Examples of gnatls Usage
18725 @section Example of @code{gnatls} Usage
18726 @ifclear vms
18727
18728 @noindent
18729 Example of using the verbose switch. Note how the source and
18730 object paths are affected by the -I switch.
18731
18732 @smallexample
18733 $ gnatls -v -I.. demo1.o
18734
18735 GNATLS 5.03w (20041123-34)
18736 Copyright 1997-2004 Free Software Foundation, Inc.
18737
18738 Source Search Path:
18739    <Current_Directory>
18740    ../
18741    /home/comar/local/adainclude/
18742
18743 Object Search Path:
18744    <Current_Directory>
18745    ../
18746    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18747
18748 Project Search Path:
18749    <Current_Directory>
18750    /home/comar/local/lib/gnat/
18751
18752 ./demo1.o
18753    Unit =>
18754      Name   => demo1
18755      Kind   => subprogram body
18756      Flags  => No_Elab_Code
18757      Source => demo1.adb    modified
18758 @end smallexample
18759
18760 @noindent
18761 The following is an example of use of the dependency list.
18762 Note the use of the -s switch
18763 which gives a straight list of source files. This can be useful for
18764 building specialized scripts.
18765
18766 @smallexample
18767 $ gnatls -d demo2.o
18768 ./demo2.o   demo2        OK demo2.adb
18769                          OK gen_list.ads
18770                          OK gen_list.adb
18771                          OK instr.ads
18772                          OK instr-child.ads
18773
18774 $ gnatls -d -s -a demo1.o
18775 demo1.adb
18776 /home/comar/local/adainclude/ada.ads
18777 /home/comar/local/adainclude/a-finali.ads
18778 /home/comar/local/adainclude/a-filico.ads
18779 /home/comar/local/adainclude/a-stream.ads
18780 /home/comar/local/adainclude/a-tags.ads
18781 gen_list.ads
18782 gen_list.adb
18783 /home/comar/local/adainclude/gnat.ads
18784 /home/comar/local/adainclude/g-io.ads
18785 instr.ads
18786 /home/comar/local/adainclude/system.ads
18787 /home/comar/local/adainclude/s-exctab.ads
18788 /home/comar/local/adainclude/s-finimp.ads
18789 /home/comar/local/adainclude/s-finroo.ads
18790 /home/comar/local/adainclude/s-secsta.ads
18791 /home/comar/local/adainclude/s-stalib.ads
18792 /home/comar/local/adainclude/s-stoele.ads
18793 /home/comar/local/adainclude/s-stratt.ads
18794 /home/comar/local/adainclude/s-tasoli.ads
18795 /home/comar/local/adainclude/s-unstyp.ads
18796 /home/comar/local/adainclude/unchconv.ads
18797 @end smallexample
18798 @end ifclear
18799
18800 @ifset vms
18801 @smallexample
18802 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
18803
18804 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
18805 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
18806 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
18807 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
18808 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
18809 demo1.adb
18810 gen_list.ads
18811 gen_list.adb
18812 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
18813 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
18814 instr.ads
18815 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
18816 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
18817 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
18818 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
18819 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
18820 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
18821 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
18822 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
18823 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
18824 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
18825 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
18826 @end smallexample
18827 @end ifset
18828
18829 @node Cleaning Up Using gnatclean
18830 @chapter Cleaning Up Using @code{gnatclean}
18831 @findex gnatclean
18832 @cindex Cleaning tool
18833
18834 @noindent
18835 @code{gnatclean} is a tool that allows the deletion of files produced by the
18836 compiler, binder and linker, including ALI files, object files, tree files,
18837 expanded source files, library files, interface copy source files, binder
18838 generated files and executable files.
18839
18840 @menu
18841 * Running gnatclean::
18842 * Switches for gnatclean::
18843 @c * Examples of gnatclean Usage::
18844 @end menu
18845
18846 @node Running gnatclean
18847 @section Running @code{gnatclean}
18848
18849 @noindent
18850 The @code{gnatclean} command has the form:
18851
18852 @smallexample
18853 $ gnatclean switches @var{names}
18854 @end smallexample
18855
18856 @noindent
18857 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
18858 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
18859 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
18860
18861 @noindent
18862 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
18863 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
18864 the linker. In informative-only mode, specified by switch
18865 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
18866 normal mode is listed, but no file is actually deleted.
18867
18868 @node Switches for gnatclean
18869 @section Switches for @code{gnatclean}
18870
18871 @noindent
18872 @code{gnatclean} recognizes the following switches:
18873
18874 @table @option
18875 @c !sort!
18876 @cindex @option{--version} @command{gnatclean}
18877 Display Copyright and version, then exit disregarding all other options.
18878
18879 @item --help
18880 @cindex @option{--help} @command{gnatclean}
18881 If @option{--version} was not used, display usage, then exit disregarding
18882 all other options.
18883
18884 @item ^-c^/COMPILER_FILES_ONLY^
18885 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
18886 Only attempt to delete the files produced by the compiler, not those produced
18887 by the binder or the linker. The files that are not to be deleted are library
18888 files, interface copy files, binder generated files and executable files.
18889
18890 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
18891 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
18892 Indicate that ALI and object files should normally be found in directory
18893 @var{dir}.
18894
18895 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
18896 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
18897 When using project files, if some errors or warnings are detected during
18898 parsing and verbose mode is not in effect (no use of switch
18899 ^-v^/VERBOSE^), then error lines start with the full path name of the project
18900 file, rather than its simple file name.
18901
18902 @item ^-h^/HELP^
18903 @cindex @option{^-h^/HELP^} (@code{gnatclean})
18904 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
18905
18906 @item ^-n^/NODELETE^
18907 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
18908 Informative-only mode. Do not delete any files. Output the list of the files
18909 that would have been deleted if this switch was not specified.
18910
18911 @item ^-P^/PROJECT_FILE=^@var{project}
18912 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
18913 Use project file @var{project}. Only one such switch can be used.
18914 When cleaning a project file, the files produced by the compilation of the
18915 immediate sources or inherited sources of the project files are to be
18916 deleted. This is not depending on the presence or not of executable names
18917 on the command line.
18918
18919 @item ^-q^/QUIET^
18920 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
18921 Quiet output. If there are no errors, do not output anything, except in
18922 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
18923 (switch ^-n^/NODELETE^).
18924
18925 @item ^-r^/RECURSIVE^
18926 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
18927 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
18928 clean all imported and extended project files, recursively. If this switch
18929 is not specified, only the files related to the main project file are to be
18930 deleted. This switch has no effect if no project file is specified.
18931
18932 @item ^-v^/VERBOSE^
18933 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
18934 Verbose mode.
18935
18936 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
18937 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
18938 Indicates the verbosity of the parsing of GNAT project files.
18939 @xref{Switches Related to Project Files}.
18940
18941 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
18942 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
18943 Indicates that external variable @var{name} has the value @var{value}.
18944 The Project Manager will use this value for occurrences of
18945 @code{external(name)} when parsing the project file.
18946 @xref{Switches Related to Project Files}.
18947
18948 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
18949 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
18950 When searching for ALI and object files, look in directory
18951 @var{dir}.
18952
18953 @item ^-I^/SEARCH=^@var{dir}
18954 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
18955 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
18956
18957 @item ^-I-^/NOCURRENT_DIRECTORY^
18958 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
18959 @cindex Source files, suppressing search
18960 Do not look for ALI or object files in the directory
18961 where @code{gnatclean} was invoked.
18962
18963 @end table
18964
18965 @c @node Examples of gnatclean Usage
18966 @c @section Examples of @code{gnatclean} Usage
18967
18968 @ifclear vms
18969 @node GNAT and Libraries
18970 @chapter GNAT and Libraries
18971 @cindex Library, building, installing, using
18972
18973 @noindent
18974 This chapter describes how to build and use libraries with GNAT, and also shows
18975 how to recompile the GNAT run-time library. You should be familiar with the
18976 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
18977 chapter.
18978
18979 @menu
18980 * Introduction to Libraries in GNAT::
18981 * General Ada Libraries::
18982 * Stand-alone Ada Libraries::
18983 * Rebuilding the GNAT Run-Time Library::
18984 @end menu
18985
18986 @node Introduction to Libraries in GNAT
18987 @section Introduction to Libraries in GNAT
18988
18989 @noindent
18990 A library is, conceptually, a collection of objects which does not have its
18991 own main thread of execution, but rather provides certain services to the
18992 applications that use it. A library can be either statically linked with the
18993 application, in which case its code is directly included in the application,
18994 or, on platforms that support it, be dynamically linked, in which case
18995 its code is shared by all applications making use of this library.
18996
18997 GNAT supports both types of libraries.
18998 In the static case, the compiled code can be provided in different ways. The
18999 simplest approach is to provide directly the set of objects resulting from
19000 compilation of the library source files. Alternatively, you can group the
19001 objects into an archive using whatever commands are provided by the operating
19002 system. For the latter case, the objects are grouped into a shared library.
19003
19004 In the GNAT environment, a library has three types of components:
19005 @itemize @bullet
19006 @item
19007 Source files.
19008 @item
19009 @file{ALI} files.
19010 @xref{The Ada Library Information Files}.
19011 @item
19012 Object files, an archive or a shared library.
19013 @end itemize
19014
19015 @noindent
19016 A GNAT library may expose all its source files, which is useful for
19017 documentation purposes. Alternatively, it may expose only the units needed by
19018 an external user to make use of the library. That is to say, the specs
19019 reflecting the library services along with all the units needed to compile
19020 those specs, which can include generic bodies or any body implementing an
19021 inlined routine. In the case of @emph{stand-alone libraries} those exposed
19022 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
19023
19024 All compilation units comprising an application, including those in a library,
19025 need to be elaborated in an order partially defined by Ada's semantics. GNAT
19026 computes the elaboration order from the @file{ALI} files and this is why they
19027 constitute a mandatory part of GNAT libraries.
19028 @emph{Stand-alone libraries} are the exception to this rule because a specific
19029 library elaboration routine is produced independently of the application(s)
19030 using the library.
19031
19032 @node General Ada Libraries
19033 @section General Ada Libraries
19034
19035 @menu
19036 * Building a library::
19037 * Installing a library::
19038 * Using a library::
19039 @end menu
19040
19041 @node Building a library
19042 @subsection Building a library
19043
19044 @noindent
19045 The easiest way to build a library is to use the Project Manager,
19046 which supports a special type of project called a @emph{Library Project}
19047 (@pxref{Library Projects}).
19048
19049 A project is considered a library project, when two project-level attributes
19050 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
19051 control different aspects of library configuration, additional optional
19052 project-level attributes can be specified:
19053 @table @code
19054 @item Library_Kind
19055 This attribute controls whether the library is to be static or dynamic
19056
19057 @item Library_Version
19058 This attribute specifies the library version; this value is used
19059 during dynamic linking of shared libraries to determine if the currently
19060 installed versions of the binaries are compatible.
19061
19062 @item Library_Options
19063 @item Library_GCC
19064 These attributes specify additional low-level options to be used during
19065 library generation, and redefine the actual application used to generate
19066 library.
19067 @end table
19068
19069 @noindent
19070 The GNAT Project Manager takes full care of the library maintenance task,
19071 including recompilation of the source files for which objects do not exist
19072 or are not up to date, assembly of the library archive, and installation of
19073 the library (i.e., copying associated source, object and @file{ALI} files
19074 to the specified location).
19075
19076 Here is a simple library project file:
19077 @smallexample @c ada
19078 project My_Lib is
19079    for Source_Dirs use ("src1", "src2");
19080    for Object_Dir use "obj";
19081    for Library_Name use "mylib";
19082    for Library_Dir use "lib";
19083    for Library_Kind use "dynamic";
19084 end My_lib;
19085 @end smallexample
19086
19087 @noindent
19088 and the compilation command to build and install the library:
19089
19090 @smallexample @c ada
19091   $ gnatmake -Pmy_lib
19092 @end smallexample
19093
19094 @noindent
19095 It is not entirely trivial to perform manually all the steps required to
19096 produce a library. We recommend that you use the GNAT Project Manager
19097 for this task. In special cases where this is not desired, the necessary
19098 steps are discussed below.
19099
19100 There are various possibilities for compiling the units that make up the
19101 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
19102 with a conventional script. For simple libraries, it is also possible to create
19103 a dummy main program which depends upon all the packages that comprise the
19104 interface of the library. This dummy main program can then be given to
19105 @command{gnatmake}, which will ensure that all necessary objects are built.
19106
19107 After this task is accomplished, you should follow the standard procedure
19108 of the underlying operating system to produce the static or shared library.
19109
19110 Here is an example of such a dummy program:
19111 @smallexample @c ada
19112 @group
19113 with My_Lib.Service1;
19114 with My_Lib.Service2;
19115 with My_Lib.Service3;
19116 procedure My_Lib_Dummy is
19117 begin
19118    null;
19119 end;
19120 @end group
19121 @end smallexample
19122
19123 @noindent
19124 Here are the generic commands that will build an archive or a shared library.
19125
19126 @smallexample
19127 # compiling the library
19128 $ gnatmake -c my_lib_dummy.adb
19129
19130 # we don't need the dummy object itself
19131 $ rm my_lib_dummy.o my_lib_dummy.ali
19132
19133 # create an archive with the remaining objects
19134 $ ar rc libmy_lib.a *.o
19135 # some systems may require "ranlib" to be run as well
19136
19137 # or create a shared library
19138 $ gcc -shared -o libmy_lib.so *.o
19139 # some systems may require the code to have been compiled with -fPIC
19140
19141 # remove the object files that are now in the library
19142 $ rm *.o
19143
19144 # Make the ALI files read-only so that gnatmake will not try to
19145 # regenerate the objects that are in the library
19146 $ chmod -w *.ali
19147 @end smallexample
19148
19149 @noindent
19150 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
19151 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
19152 be accessed by the directive @option{-l@var{xxx}} at link time.
19153
19154 @node Installing a library
19155 @subsection Installing a library
19156 @cindex @code{ADA_PROJECT_PATH}
19157 @cindex @code{GPR_PROJECT_PATH}
19158
19159 @noindent
19160 If you use project files, library installation is part of the library build
19161 process. Thus no further action is needed in order to make use of the
19162 libraries that are built as part of the general application build. A usable
19163 version of the library is installed in the directory specified by the
19164 @code{Library_Dir} attribute of the library project file.
19165
19166 You may want to install a library in a context different from where the library
19167 is built. This situation arises with third party suppliers, who may want
19168 to distribute a library in binary form where the user is not expected to be
19169 able to recompile the library. The simplest option in this case is to provide
19170 a project file slightly different from the one used to build the library, by
19171 using the @code{externally_built} attribute. For instance, the project
19172 file used to build the library in the previous section can be changed into the
19173 following one when the library is installed:
19174
19175 @smallexample @c projectfile
19176 project My_Lib is
19177    for Source_Dirs use ("src1", "src2");
19178    for Library_Name use "mylib";
19179    for Library_Dir use "lib";
19180    for Library_Kind use "dynamic";
19181    for Externally_Built use "true";
19182 end My_lib;
19183 @end smallexample
19184
19185 @noindent
19186 This project file assumes that the directories @file{src1},
19187 @file{src2}, and @file{lib} exist in
19188 the directory containing the project file. The @code{externally_built}
19189 attribute makes it clear to the GNAT builder that it should not attempt to
19190 recompile any of the units from this library. It allows the library provider to
19191 restrict the source set to the minimum necessary for clients to make use of the
19192 library as described in the first section of this chapter. It is the
19193 responsibility of the library provider to install the necessary sources, ALI
19194 files and libraries in the directories mentioned in the project file. For
19195 convenience, the user's library project file should be installed in a location
19196 that will be searched automatically by the GNAT
19197 builder. These are the directories referenced in the @env{GPR_PROJECT_PATH}
19198 environment variable (@pxref{Importing Projects}), and also the default GNAT
19199 library location that can be queried with @command{gnatls -v} and is usually of
19200 the form $gnat_install_root/lib/gnat.
19201
19202 When project files are not an option, it is also possible, but not recommended,
19203 to install the library so that the sources needed to use the library are on the
19204 Ada source path and the ALI files & libraries be on the Ada Object path (see
19205 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
19206 administrator can place general-purpose libraries in the default compiler
19207 paths, by specifying the libraries' location in the configuration files
19208 @file{ada_source_path} and @file{ada_object_path}. These configuration files
19209 must be located in the GNAT installation tree at the same place as the gcc spec
19210 file. The location of the gcc spec file can be determined as follows:
19211 @smallexample
19212 $ gcc -v
19213 @end smallexample
19214
19215 @noindent
19216 The configuration files mentioned above have a simple format: each line
19217 must contain one unique directory name.
19218 Those names are added to the corresponding path
19219 in their order of appearance in the file. The names can be either absolute
19220 or relative; in the latter case, they are relative to where theses files
19221 are located.
19222
19223 The files @file{ada_source_path} and @file{ada_object_path} might not be
19224 present in a
19225 GNAT installation, in which case, GNAT will look for its run-time library in
19226 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
19227 objects and @file{ALI} files). When the files exist, the compiler does not
19228 look in @file{adainclude} and @file{adalib}, and thus the
19229 @file{ada_source_path} file
19230 must contain the location for the GNAT run-time sources (which can simply
19231 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
19232 contain the location for the GNAT run-time objects (which can simply
19233 be @file{adalib}).
19234
19235 You can also specify a new default path to the run-time library at compilation
19236 time with the switch @option{--RTS=rts-path}. You can thus choose / change
19237 the run-time library you want your program to be compiled with. This switch is
19238 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
19239 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
19240
19241 It is possible to install a library before or after the standard GNAT
19242 library, by reordering the lines in the configuration files. In general, a
19243 library must be installed before the GNAT library if it redefines
19244 any part of it.
19245
19246 @node Using a library
19247 @subsection Using a library
19248
19249 @noindent Once again, the project facility greatly simplifies the use of
19250 libraries. In this context, using a library is just a matter of adding a
19251 @code{with} clause in the user project. For instance, to make use of the
19252 library @code{My_Lib} shown in examples in earlier sections, you can
19253 write:
19254
19255 @smallexample @c projectfile
19256 with "my_lib";
19257 project My_Proj is
19258   @dots{}
19259 end My_Proj;
19260 @end smallexample
19261
19262 Even if you have a third-party, non-Ada library, you can still use GNAT's
19263 Project Manager facility to provide a wrapper for it. For example, the
19264 following project, when @code{with}ed by your main project, will link with the
19265 third-party library @file{liba.a}:
19266
19267 @smallexample @c projectfile
19268 @group
19269 project Liba is
19270    for Externally_Built use "true";
19271    for Source_Files use ();
19272    for Library_Dir use "lib";
19273    for Library_Name use "a";
19274    for Library_Kind use "static";
19275 end Liba;
19276 @end group
19277 @end smallexample
19278 This is an alternative to the use of @code{pragma Linker_Options}. It is
19279 especially interesting in the context of systems with several interdependent
19280 static libraries where finding a proper linker order is not easy and best be
19281 left to the tools having visibility over project dependence information.
19282
19283 @noindent
19284 In order to use an Ada library manually, you need to make sure that this
19285 library is on both your source and object path
19286 (see @ref{Search Paths and the Run-Time Library (RTL)}
19287 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
19288 in an archive or a shared library, you need to specify the desired
19289 library at link time.
19290
19291 For example, you can use the library @file{mylib} installed in
19292 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
19293
19294 @smallexample
19295 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
19296   -largs -lmy_lib
19297 @end smallexample
19298
19299 @noindent
19300 This can be expressed more simply:
19301 @smallexample
19302 $ gnatmake my_appl
19303 @end smallexample
19304 @noindent
19305 when the following conditions are met:
19306 @itemize @bullet
19307 @item
19308 @file{/dir/my_lib_src} has been added by the user to the environment
19309 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
19310 @file{ada_source_path}
19311 @item
19312 @file{/dir/my_lib_obj} has been added by the user to the environment
19313 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
19314 @file{ada_object_path}
19315 @item
19316 a pragma @code{Linker_Options} has been added to one of the sources.
19317 For example:
19318
19319 @smallexample @c ada
19320 pragma Linker_Options ("-lmy_lib");
19321 @end smallexample
19322 @end itemize
19323
19324 @node Stand-alone Ada Libraries
19325 @section Stand-alone Ada Libraries
19326 @cindex Stand-alone library, building, using
19327
19328 @menu
19329 * Introduction to Stand-alone Libraries::
19330 * Building a Stand-alone Library::
19331 * Creating a Stand-alone Library to be used in a non-Ada context::
19332 * Restrictions in Stand-alone Libraries::
19333 @end menu
19334
19335 @node Introduction to Stand-alone Libraries
19336 @subsection Introduction to Stand-alone Libraries
19337
19338 @noindent
19339 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
19340 necessary code to
19341 elaborate the Ada units that are included in the library. In contrast with
19342 an ordinary library, which consists of all sources, objects and @file{ALI}
19343 files of the
19344 library, a SAL may specify a restricted subset of compilation units
19345 to serve as a library interface. In this case, the fully
19346 self-sufficient set of files will normally consist of an objects
19347 archive, the sources of interface units' specs, and the @file{ALI}
19348 files of interface units.
19349 If an interface spec contains a generic unit or an inlined subprogram,
19350 the body's
19351 source must also be provided; if the units that must be provided in the source
19352 form depend on other units, the source and @file{ALI} files of those must
19353 also be provided.
19354
19355 The main purpose of a SAL is to minimize the recompilation overhead of client
19356 applications when a new version of the library is installed. Specifically,
19357 if the interface sources have not changed, client applications do not need to
19358 be recompiled. If, furthermore, a SAL is provided in the shared form and its
19359 version, controlled by @code{Library_Version} attribute, is not changed,
19360 then the clients do not need to be relinked.
19361
19362 SALs also allow the library providers to minimize the amount of library source
19363 text exposed to the clients.  Such ``information hiding'' might be useful or
19364 necessary for various reasons.
19365
19366 Stand-alone libraries are also well suited to be used in an executable whose
19367 main routine is not written in Ada.
19368
19369 @node Building a Stand-alone Library
19370 @subsection Building a Stand-alone Library
19371
19372 @noindent
19373 GNAT's Project facility provides a simple way of building and installing
19374 stand-alone libraries; see @ref{Stand-alone Library Projects}.
19375 To be a Stand-alone Library Project, in addition to the two attributes
19376 that make a project a Library Project (@code{Library_Name} and
19377 @code{Library_Dir}; see @ref{Library Projects}), the attribute
19378 @code{Library_Interface} must be defined.  For example:
19379
19380 @smallexample @c projectfile
19381 @group
19382    for Library_Dir use "lib_dir";
19383    for Library_Name use "dummy";
19384    for Library_Interface use ("int1", "int1.child");
19385 @end group
19386 @end smallexample
19387
19388 @noindent
19389 Attribute @code{Library_Interface} has a non-empty string list value,
19390 each string in the list designating a unit contained in an immediate source
19391 of the project file.
19392
19393 When a Stand-alone Library is built, first the binder is invoked to build
19394 a package whose name depends on the library name
19395 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
19396 This binder-generated package includes initialization and
19397 finalization procedures whose
19398 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
19399 in the example
19400 above). The object corresponding to this package is included in the library.
19401
19402 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
19403 calling of these procedures if a static SAL is built, or if a shared SAL
19404 is built
19405 with the project-level attribute @code{Library_Auto_Init} set to
19406 @code{"false"}.
19407
19408 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
19409 (those that are listed in attribute @code{Library_Interface}) are copied to
19410 the Library Directory. As a consequence, only the Interface Units may be
19411 imported from Ada units outside of the library. If other units are imported,
19412 the binding phase will fail.
19413
19414 The attribute @code{Library_Src_Dir} may be specified for a
19415 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
19416 single string value. Its value must be the path (absolute or relative to the
19417 project directory) of an existing directory. This directory cannot be the
19418 object directory or one of the source directories, but it can be the same as
19419 the library directory. The sources of the Interface
19420 Units of the library that are needed by an Ada client of the library will be
19421 copied to the designated directory, called the Interface Copy directory.
19422 These sources include the specs of the Interface Units, but they may also
19423 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
19424 are used, or when there is a generic unit in the spec. Before the sources
19425 are copied to the Interface Copy directory, an attempt is made to delete all
19426 files in the Interface Copy directory.
19427
19428 Building stand-alone libraries by hand is somewhat tedious, but for those
19429 occasions when it is necessary here are the steps that you need to perform:
19430 @itemize @bullet
19431 @item
19432 Compile all library sources.
19433
19434 @item
19435 Invoke the binder with the switch @option{-n} (No Ada main program),
19436 with all the @file{ALI} files of the interfaces, and
19437 with the switch @option{-L} to give specific names to the @code{init}
19438 and @code{final} procedures.  For example:
19439 @smallexample
19440   gnatbind -n int1.ali int2.ali -Lsal1
19441 @end smallexample
19442
19443 @item
19444 Compile the binder generated file:
19445 @smallexample
19446   gcc -c b~int2.adb
19447 @end smallexample
19448
19449 @item
19450 Link the dynamic library with all the necessary object files,
19451 indicating to the linker the names of the @code{init} (and possibly
19452 @code{final}) procedures for automatic initialization (and finalization).
19453 The built library should be placed in a directory different from
19454 the object directory.
19455
19456 @item
19457 Copy the @code{ALI} files of the interface to the library directory,
19458 add in this copy an indication that it is an interface to a SAL
19459 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
19460 with letter ``P'') and make the modified copy of the @file{ALI} file
19461 read-only.
19462 @end itemize
19463
19464 @noindent
19465 Using SALs is not different from using other libraries
19466 (see @ref{Using a library}).
19467
19468 @node Creating a Stand-alone Library to be used in a non-Ada context
19469 @subsection Creating a Stand-alone Library to be used in a non-Ada context
19470
19471 @noindent
19472 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
19473 a non-Ada context.
19474
19475 The only extra step required is to ensure that library interface subprograms
19476 are compatible with the main program, by means of @code{pragma Export}
19477 or @code{pragma Convention}.
19478
19479 Here is an example of simple library interface for use with C main program:
19480
19481 @smallexample @c ada
19482 package My_Package is
19483
19484    procedure Do_Something;
19485    pragma Export (C, Do_Something, "do_something");
19486
19487    procedure Do_Something_Else;
19488    pragma Export (C, Do_Something_Else, "do_something_else");
19489
19490 end My_Package;
19491 @end smallexample
19492
19493 @noindent
19494 On the foreign language side, you must provide a ``foreign'' view of the
19495 library interface; remember that it should contain elaboration routines in
19496 addition to interface subprograms.
19497
19498 The example below shows the content of @code{mylib_interface.h} (note
19499 that there is no rule for the naming of this file, any name can be used)
19500 @smallexample
19501 /* the library elaboration procedure */
19502 extern void mylibinit (void);
19503
19504 /* the library finalization procedure */
19505 extern void mylibfinal (void);
19506
19507 /* the interface exported by the library */
19508 extern void do_something (void);
19509 extern void do_something_else (void);
19510 @end smallexample
19511
19512 @noindent
19513 Libraries built as explained above can be used from any program, provided
19514 that the elaboration procedures (named @code{mylibinit} in the previous
19515 example) are called before the library services are used. Any number of
19516 libraries can be used simultaneously, as long as the elaboration
19517 procedure of each library is called.
19518
19519 Below is an example of a C program that uses the @code{mylib} library.
19520
19521 @smallexample
19522 #include "mylib_interface.h"
19523
19524 int
19525 main (void)
19526 @{
19527    /* First, elaborate the library before using it */
19528    mylibinit ();
19529
19530    /* Main program, using the library exported entities */
19531    do_something ();
19532    do_something_else ();
19533
19534    /* Library finalization at the end of the program */
19535    mylibfinal ();
19536    return 0;
19537 @}
19538 @end smallexample
19539
19540 @noindent
19541 Note that invoking any library finalization procedure generated by
19542 @code{gnatbind} shuts down the Ada run-time environment.
19543 Consequently, the
19544 finalization of all Ada libraries must be performed at the end of the program.
19545 No call to these libraries or to the Ada run-time library should be made
19546 after the finalization phase.
19547
19548 @node Restrictions in Stand-alone Libraries
19549 @subsection Restrictions in Stand-alone Libraries
19550
19551 @noindent
19552 The pragmas listed below should be used with caution inside libraries,
19553 as they can create incompatibilities with other Ada libraries:
19554 @itemize @bullet
19555 @item pragma @code{Locking_Policy}
19556 @item pragma @code{Queuing_Policy}
19557 @item pragma @code{Task_Dispatching_Policy}
19558 @item pragma @code{Unreserve_All_Interrupts}
19559 @end itemize
19560
19561 @noindent
19562 When using a library that contains such pragmas, the user must make sure
19563 that all libraries use the same pragmas with the same values. Otherwise,
19564 @code{Program_Error} will
19565 be raised during the elaboration of the conflicting
19566 libraries. The usage of these pragmas and its consequences for the user
19567 should therefore be well documented.
19568
19569 Similarly, the traceback in the exception occurrence mechanism should be
19570 enabled or disabled in a consistent manner across all libraries.
19571 Otherwise, Program_Error will be raised during the elaboration of the
19572 conflicting libraries.
19573
19574 If the @code{Version} or @code{Body_Version}
19575 attributes are used inside a library, then you need to
19576 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
19577 libraries, so that version identifiers can be properly computed.
19578 In practice these attributes are rarely used, so this is unlikely
19579 to be a consideration.
19580
19581 @node  Rebuilding the GNAT Run-Time Library
19582 @section Rebuilding the GNAT Run-Time Library
19583 @cindex GNAT Run-Time Library, rebuilding
19584 @cindex Building the GNAT Run-Time Library
19585 @cindex Rebuilding the GNAT Run-Time Library
19586 @cindex Run-Time Library, rebuilding
19587
19588 @noindent
19589 It may be useful to recompile the GNAT library in various contexts, the
19590 most important one being the use of partition-wide configuration pragmas
19591 such as @code{Normalize_Scalars}. A special Makefile called
19592 @code{Makefile.adalib} is provided to that effect and can be found in
19593 the directory containing the GNAT library. The location of this
19594 directory depends on the way the GNAT environment has been installed and can
19595 be determined by means of the command:
19596
19597 @smallexample
19598 $ gnatls -v
19599 @end smallexample
19600
19601 @noindent
19602 The last entry in the object search path usually contains the
19603 gnat library. This Makefile contains its own documentation and in
19604 particular the set of instructions needed to rebuild a new library and
19605 to use it.
19606
19607 @node Using the GNU make Utility
19608 @chapter Using the GNU @code{make} Utility
19609 @findex make
19610
19611 @noindent
19612 This chapter offers some examples of makefiles that solve specific
19613 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
19614 make, make, GNU @code{make}}), nor does it try to replace the
19615 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
19616
19617 All the examples in this section are specific to the GNU version of
19618 make. Although @command{make} is a standard utility, and the basic language
19619 is the same, these examples use some advanced features found only in
19620 @code{GNU make}.
19621
19622 @menu
19623 * Using gnatmake in a Makefile::
19624 * Automatically Creating a List of Directories::
19625 * Generating the Command Line Switches::
19626 * Overcoming Command Line Length Limits::
19627 @end menu
19628
19629 @node Using gnatmake in a Makefile
19630 @section Using gnatmake in a Makefile
19631 @findex makefile
19632 @cindex GNU make
19633
19634 @noindent
19635 Complex project organizations can be handled in a very powerful way by
19636 using GNU make combined with gnatmake. For instance, here is a Makefile
19637 which allows you to build each subsystem of a big project into a separate
19638 shared library. Such a makefile allows you to significantly reduce the link
19639 time of very big applications while maintaining full coherence at
19640 each step of the build process.
19641
19642 The list of dependencies are handled automatically by
19643 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
19644 the appropriate directories.
19645
19646 Note that you should also read the example on how to automatically
19647 create the list of directories
19648 (@pxref{Automatically Creating a List of Directories})
19649 which might help you in case your project has a lot of subdirectories.
19650
19651 @smallexample
19652 @iftex
19653 @leftskip=0cm
19654 @font@heightrm=cmr8
19655 @heightrm
19656 @end iftex
19657 ## This Makefile is intended to be used with the following directory
19658 ## configuration:
19659 ##  - The sources are split into a series of csc (computer software components)
19660 ##    Each of these csc is put in its own directory.
19661 ##    Their name are referenced by the directory names.
19662 ##    They will be compiled into shared library (although this would also work
19663 ##    with static libraries
19664 ##  - The main program (and possibly other packages that do not belong to any
19665 ##    csc is put in the top level directory (where the Makefile is).
19666 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
19667 ##                    \_ second_csc (sources) __ lib (will contain the library)
19668 ##                    \_ @dots{}
19669 ## Although this Makefile is build for shared library, it is easy to modify
19670 ## to build partial link objects instead (modify the lines with -shared and
19671 ## gnatlink below)
19672 ##
19673 ## With this makefile, you can change any file in the system or add any new
19674 ## file, and everything will be recompiled correctly (only the relevant shared
19675 ## objects will be recompiled, and the main program will be re-linked).
19676
19677 # The list of computer software component for your project. This might be
19678 # generated automatically.
19679 CSC_LIST=aa bb cc
19680
19681 # Name of the main program (no extension)
19682 MAIN=main
19683
19684 # If we need to build objects with -fPIC, uncomment the following line
19685 #NEED_FPIC=-fPIC
19686
19687 # The following variable should give the directory containing libgnat.so
19688 # You can get this directory through 'gnatls -v'. This is usually the last
19689 # directory in the Object_Path.
19690 GLIB=@dots{}
19691
19692 # The directories for the libraries
19693 # (This macro expands the list of CSC to the list of shared libraries, you
19694 # could simply use the expanded form:
19695 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
19696 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
19697
19698 $@{MAIN@}: objects $@{LIB_DIR@}
19699     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
19700     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
19701
19702 objects::
19703     # recompile the sources
19704     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
19705
19706 # Note: In a future version of GNAT, the following commands will be simplified
19707 # by a new tool, gnatmlib
19708 $@{LIB_DIR@}:
19709     mkdir -p $@{dir $@@ @}
19710     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
19711     cd $@{dir $@@ @} && cp -f ../*.ali .
19712
19713 # The dependencies for the modules
19714 # Note that we have to force the expansion of *.o, since in some cases
19715 # make won't be able to do it itself.
19716 aa/lib/libaa.so: $@{wildcard aa/*.o@}
19717 bb/lib/libbb.so: $@{wildcard bb/*.o@}
19718 cc/lib/libcc.so: $@{wildcard cc/*.o@}
19719
19720 # Make sure all of the shared libraries are in the path before starting the
19721 # program
19722 run::
19723     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
19724
19725 clean::
19726     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
19727     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
19728     $@{RM@} $@{CSC_LIST:%=%/*.o@}
19729     $@{RM@} *.o *.ali $@{MAIN@}
19730 @end smallexample
19731
19732 @node Automatically Creating a List of Directories
19733 @section Automatically Creating a List of Directories
19734
19735 @noindent
19736 In most makefiles, you will have to specify a list of directories, and
19737 store it in a variable. For small projects, it is often easier to
19738 specify each of them by hand, since you then have full control over what
19739 is the proper order for these directories, which ones should be
19740 included.
19741
19742 However, in larger projects, which might involve hundreds of
19743 subdirectories, it might be more convenient to generate this list
19744 automatically.
19745
19746 The example below presents two methods. The first one, although less
19747 general, gives you more control over the list. It involves wildcard
19748 characters, that are automatically expanded by @command{make}. Its
19749 shortcoming is that you need to explicitly specify some of the
19750 organization of your project, such as for instance the directory tree
19751 depth, whether some directories are found in a separate tree, @enddots{}
19752
19753 The second method is the most general one. It requires an external
19754 program, called @command{find}, which is standard on all Unix systems. All
19755 the directories found under a given root directory will be added to the
19756 list.
19757
19758 @smallexample
19759 @iftex
19760 @leftskip=0cm
19761 @font@heightrm=cmr8
19762 @heightrm
19763 @end iftex
19764 # The examples below are based on the following directory hierarchy:
19765 # All the directories can contain any number of files
19766 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
19767 #                       ->  ab
19768 #                       ->  ac
19769 #                ->  b  ->  ba  ->  baa
19770 #                       ->  bb
19771 #                       ->  bc
19772 # This Makefile creates a variable called DIRS, that can be reused any time
19773 # you need this list (see the other examples in this section)
19774
19775 # The root of your project's directory hierarchy
19776 ROOT_DIRECTORY=.
19777
19778 ####
19779 # First method: specify explicitly the list of directories
19780 # This allows you to specify any subset of all the directories you need.
19781 ####
19782
19783 DIRS := a/aa/ a/ab/ b/ba/
19784
19785 ####
19786 # Second method: use wildcards
19787 # Note that the argument(s) to wildcard below should end with a '/'.
19788 # Since wildcards also return file names, we have to filter them out
19789 # to avoid duplicate directory names.
19790 # We thus use make's @code{dir} and @code{sort} functions.
19791 # It sets DIRs to the following value (note that the directories aaa and baa
19792 # are not given, unless you change the arguments to wildcard).
19793 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
19794 ####
19795
19796 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
19797                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
19798
19799 ####
19800 # Third method: use an external program
19801 # This command is much faster if run on local disks, avoiding NFS slowdowns.
19802 # This is the most complete command: it sets DIRs to the following value:
19803 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
19804 ####
19805
19806 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
19807
19808 @end smallexample
19809
19810 @node Generating the Command Line Switches
19811 @section Generating the Command Line Switches
19812
19813 @noindent
19814 Once you have created the list of directories as explained in the
19815 previous section (@pxref{Automatically Creating a List of Directories}),
19816 you can easily generate the command line arguments to pass to gnatmake.
19817
19818 For the sake of completeness, this example assumes that the source path
19819 is not the same as the object path, and that you have two separate lists
19820 of directories.
19821
19822 @smallexample
19823 # see "Automatically creating a list of directories" to create
19824 # these variables
19825 SOURCE_DIRS=
19826 OBJECT_DIRS=
19827
19828 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
19829 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
19830
19831 all:
19832         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
19833 @end smallexample
19834
19835 @node Overcoming Command Line Length Limits
19836 @section Overcoming Command Line Length Limits
19837
19838 @noindent
19839 One problem that might be encountered on big projects is that many
19840 operating systems limit the length of the command line. It is thus hard to give
19841 gnatmake the list of source and object directories.
19842
19843 This example shows how you can set up environment variables, which will
19844 make @command{gnatmake} behave exactly as if the directories had been
19845 specified on the command line, but have a much higher length limit (or
19846 even none on most systems).
19847
19848 It assumes that you have created a list of directories in your Makefile,
19849 using one of the methods presented in
19850 @ref{Automatically Creating a List of Directories}.
19851 For the sake of completeness, we assume that the object
19852 path (where the ALI files are found) is different from the sources patch.
19853
19854 Note a small trick in the Makefile below: for efficiency reasons, we
19855 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
19856 expanded immediately by @code{make}. This way we overcome the standard
19857 make behavior which is to expand the variables only when they are
19858 actually used.
19859
19860 On Windows, if you are using the standard Windows command shell, you must
19861 replace colons with semicolons in the assignments to these variables.
19862
19863 @smallexample
19864 @iftex
19865 @leftskip=0cm
19866 @font@heightrm=cmr8
19867 @heightrm
19868 @end iftex
19869 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
19870 # This is the same thing as putting the -I arguments on the command line.
19871 # (the equivalent of using -aI on the command line would be to define
19872 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
19873 # You can of course have different values for these variables.
19874 #
19875 # Note also that we need to keep the previous values of these variables, since
19876 # they might have been set before running 'make' to specify where the GNAT
19877 # library is installed.
19878
19879 # see "Automatically creating a list of directories" to create these
19880 # variables
19881 SOURCE_DIRS=
19882 OBJECT_DIRS=
19883
19884 empty:=
19885 space:=$@{empty@} $@{empty@}
19886 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
19887 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
19888 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
19889 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
19890 export ADA_INCLUDE_PATH
19891 export ADA_OBJECT_PATH
19892
19893 all:
19894         gnatmake main_unit
19895 @end smallexample
19896 @end ifclear
19897
19898 @node Memory Management Issues
19899 @chapter Memory Management Issues
19900
19901 @noindent
19902 This chapter describes some useful memory pools provided in the GNAT library
19903 and in particular the GNAT Debug Pool facility, which can be used to detect
19904 incorrect uses of access values (including ``dangling references'').
19905 @ifclear vms
19906 It also describes the @command{gnatmem} tool, which can be used to track down
19907 ``memory leaks''.
19908 @end ifclear
19909
19910 @menu
19911 * Some Useful Memory Pools::
19912 * The GNAT Debug Pool Facility::
19913 @ifclear vms
19914 * The gnatmem Tool::
19915 @end ifclear
19916 @end menu
19917
19918 @node Some Useful Memory Pools
19919 @section Some Useful Memory Pools
19920 @findex Memory Pool
19921 @cindex storage, pool
19922
19923 @noindent
19924 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
19925 storage pool. Allocations use the standard system call @code{malloc} while
19926 deallocations use the standard system call @code{free}. No reclamation is
19927 performed when the pool goes out of scope. For performance reasons, the
19928 standard default Ada allocators/deallocators do not use any explicit storage
19929 pools but if they did, they could use this storage pool without any change in
19930 behavior. That is why this storage pool is used  when the user
19931 manages to make the default implicit allocator explicit as in this example:
19932 @smallexample @c ada
19933    type T1 is access Something;
19934     -- no Storage pool is defined for T2
19935    type T2 is access Something_Else;
19936    for T2'Storage_Pool use T1'Storage_Pool;
19937    -- the above is equivalent to
19938    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
19939 @end smallexample
19940
19941 @noindent
19942 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
19943 pool. The allocation strategy is similar to @code{Pool_Local}'s
19944 except that the all
19945 storage allocated with this pool is reclaimed when the pool object goes out of
19946 scope. This pool provides a explicit mechanism similar to the implicit one
19947 provided by several Ada 83 compilers for allocations performed through a local
19948 access type and whose purpose was to reclaim memory when exiting the
19949 scope of a given local access. As an example, the following program does not
19950 leak memory even though it does not perform explicit deallocation:
19951
19952 @smallexample @c ada
19953 with System.Pool_Local;
19954 procedure Pooloc1 is
19955    procedure Internal is
19956       type A is access Integer;
19957       X : System.Pool_Local.Unbounded_Reclaim_Pool;
19958       for A'Storage_Pool use X;
19959       v : A;
19960    begin
19961       for I in  1 .. 50 loop
19962          v := new Integer;
19963       end loop;
19964    end Internal;
19965 begin
19966    for I in  1 .. 100 loop
19967       Internal;
19968    end loop;
19969 end Pooloc1;
19970 @end smallexample
19971
19972 @noindent
19973 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
19974 @code{Storage_Size} is specified for an access type.
19975 The whole storage for the pool is
19976 allocated at once, usually on the stack at the point where the access type is
19977 elaborated. It is automatically reclaimed when exiting the scope where the
19978 access type is defined. This package is not intended to be used directly by the
19979 user and it is implicitly used for each such declaration:
19980
19981 @smallexample @c ada
19982    type T1 is access Something;
19983    for T1'Storage_Size use 10_000;
19984 @end smallexample
19985
19986 @node The GNAT Debug Pool Facility
19987 @section The GNAT Debug Pool Facility
19988 @findex Debug Pool
19989 @cindex storage, pool, memory corruption
19990
19991 @noindent
19992 The use of unchecked deallocation and unchecked conversion can easily
19993 lead to incorrect memory references. The problems generated by such
19994 references are usually difficult to tackle because the symptoms can be
19995 very remote from the origin of the problem. In such cases, it is
19996 very helpful to detect the problem as early as possible. This is the
19997 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
19998
19999 In order to use the GNAT specific debugging pool, the user must
20000 associate a debug pool object with each of the access types that may be
20001 related to suspected memory problems. See Ada Reference Manual 13.11.
20002 @smallexample @c ada
20003 type Ptr is access Some_Type;
20004 Pool : GNAT.Debug_Pools.Debug_Pool;
20005 for Ptr'Storage_Pool use Pool;
20006 @end smallexample
20007
20008 @noindent
20009 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
20010 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
20011 allow the user to redefine allocation and deallocation strategies. They
20012 also provide a checkpoint for each dereference, through the use of
20013 the primitive operation @code{Dereference} which is implicitly called at
20014 each dereference of an access value.
20015
20016 Once an access type has been associated with a debug pool, operations on
20017 values of the type may raise four distinct exceptions,
20018 which correspond to four potential kinds of memory corruption:
20019 @itemize @bullet
20020 @item
20021 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
20022 @item
20023 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
20024 @item
20025 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
20026 @item
20027 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
20028 @end itemize
20029
20030 @noindent
20031 For types associated with a Debug_Pool, dynamic allocation is performed using
20032 the standard GNAT allocation routine. References to all allocated chunks of
20033 memory are kept in an internal dictionary. Several deallocation strategies are
20034 provided, whereupon the user can choose to release the memory to the system,
20035 keep it allocated for further invalid access checks, or fill it with an easily
20036 recognizable pattern for debug sessions. The memory pattern is the old IBM
20037 hexadecimal convention: @code{16#DEADBEEF#}.
20038
20039 See the documentation in the file g-debpoo.ads for more information on the
20040 various strategies.
20041
20042 Upon each dereference, a check is made that the access value denotes a
20043 properly allocated memory location. Here is a complete example of use of
20044 @code{Debug_Pools}, that includes typical instances of  memory corruption:
20045 @smallexample @c ada
20046 @iftex
20047 @leftskip=0cm
20048 @end iftex
20049 with Gnat.Io; use Gnat.Io;
20050 with Unchecked_Deallocation;
20051 with Unchecked_Conversion;
20052 with GNAT.Debug_Pools;
20053 with System.Storage_Elements;
20054 with Ada.Exceptions; use Ada.Exceptions;
20055 procedure Debug_Pool_Test is
20056
20057    type T is access Integer;
20058    type U is access all T;
20059
20060    P : GNAT.Debug_Pools.Debug_Pool;
20061    for T'Storage_Pool use P;
20062
20063    procedure Free is new Unchecked_Deallocation (Integer, T);
20064    function UC is new Unchecked_Conversion (U, T);
20065    A, B : aliased T;
20066
20067    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
20068
20069 begin
20070    Info (P);
20071    A := new Integer;
20072    B := new Integer;
20073    B := A;
20074    Info (P);
20075    Free (A);
20076    begin
20077       Put_Line (Integer'Image(B.all));
20078    exception
20079       when E : others => Put_Line ("raised: " & Exception_Name (E));
20080    end;
20081    begin
20082       Free (B);
20083    exception
20084       when E : others => Put_Line ("raised: " & Exception_Name (E));
20085    end;
20086    B := UC(A'Access);
20087    begin
20088       Put_Line (Integer'Image(B.all));
20089    exception
20090       when E : others => Put_Line ("raised: " & Exception_Name (E));
20091    end;
20092    begin
20093       Free (B);
20094    exception
20095       when E : others => Put_Line ("raised: " & Exception_Name (E));
20096    end;
20097    Info (P);
20098 end Debug_Pool_Test;
20099 @end smallexample
20100
20101 @noindent
20102 The debug pool mechanism provides the following precise diagnostics on the
20103 execution of this erroneous program:
20104 @smallexample
20105 Debug Pool info:
20106   Total allocated bytes :  0
20107   Total deallocated bytes :  0
20108   Current Water Mark:  0
20109   High Water Mark:  0
20110
20111 Debug Pool info:
20112   Total allocated bytes :  8
20113   Total deallocated bytes :  0
20114   Current Water Mark:  8
20115   High Water Mark:  8
20116
20117 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
20118 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
20119 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
20120 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
20121 Debug Pool info:
20122   Total allocated bytes :  8
20123   Total deallocated bytes :  4
20124   Current Water Mark:  4
20125   High Water Mark:  8
20126 @end smallexample
20127
20128 @ifclear vms
20129 @node The gnatmem Tool
20130 @section The @command{gnatmem} Tool
20131 @findex gnatmem
20132
20133 @noindent
20134 The @code{gnatmem} utility monitors dynamic allocation and
20135 deallocation activity in a program, and displays information about
20136 incorrect deallocations and possible sources of memory leaks.
20137 It is designed to work in association with a static runtime library
20138 only and in this context provides three types of information:
20139 @itemize @bullet
20140 @item
20141 General information concerning memory management, such as the total
20142 number of allocations and deallocations, the amount of allocated
20143 memory and the high water mark, i.e.@: the largest amount of allocated
20144 memory in the course of program execution.
20145
20146 @item
20147 Backtraces for all incorrect deallocations, that is to say deallocations
20148 which do not correspond to a valid allocation.
20149
20150 @item
20151 Information on each allocation that is potentially the origin of a memory
20152 leak.
20153 @end itemize
20154
20155 @menu
20156 * Running gnatmem::
20157 * Switches for gnatmem::
20158 * Example of gnatmem Usage::
20159 @end menu
20160
20161 @node Running gnatmem
20162 @subsection Running @code{gnatmem}
20163
20164 @noindent
20165 @code{gnatmem} makes use of the output created by the special version of
20166 allocation and deallocation routines that record call information. This
20167 allows to obtain accurate dynamic memory usage history at a minimal cost to
20168 the execution speed. Note however, that @code{gnatmem} is not supported on
20169 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
20170 Solaris and Windows NT/2000/XP (x86).
20171
20172 @noindent
20173 The @code{gnatmem} command has the form
20174
20175 @smallexample
20176 @c    $ gnatmem @ovar{switches} user_program
20177 @c Expanding @ovar macro inline (explanation in macro def comments)
20178       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
20179 @end smallexample
20180
20181 @noindent
20182 The program must have been linked with the instrumented version of the
20183 allocation and deallocation routines. This is done by linking with the
20184 @file{libgmem.a} library. For correct symbolic backtrace information,
20185 the user program should be compiled with debugging options
20186 (see @ref{Switches for gcc}). For example to build @file{my_program}:
20187
20188 @smallexample
20189 $ gnatmake -g my_program -largs -lgmem
20190 @end smallexample
20191
20192 @noindent
20193 As library @file{libgmem.a} contains an alternate body for package
20194 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
20195 when an executable is linked with library @file{libgmem.a}. It is then not
20196 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
20197
20198 @noindent
20199 When @file{my_program} is executed, the file @file{gmem.out} is produced.
20200 This file contains information about all allocations and deallocations
20201 performed by the program. It is produced by the instrumented allocations and
20202 deallocations routines and will be used by @code{gnatmem}.
20203
20204 In order to produce symbolic backtrace information for allocations and
20205 deallocations performed by the GNAT run-time library, you need to use a
20206 version of that library that has been compiled with the @option{-g} switch
20207 (see @ref{Rebuilding the GNAT Run-Time Library}).
20208
20209 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
20210 examine. If the location of @file{gmem.out} file was not explicitly supplied by
20211 @option{-i} switch, gnatmem will assume that this file can be found in the
20212 current directory. For example, after you have executed @file{my_program},
20213 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
20214
20215 @smallexample
20216 $ gnatmem my_program
20217 @end smallexample
20218
20219 @noindent
20220 This will produce the output with the following format:
20221
20222 *************** debut cc
20223 @smallexample
20224 $ gnatmem my_program
20225
20226 Global information
20227 ------------------
20228    Total number of allocations        :  45
20229    Total number of deallocations      :   6
20230    Final Water Mark (non freed mem)   :  11.29 Kilobytes
20231    High Water Mark                    :  11.40 Kilobytes
20232
20233 .
20234 .
20235 .
20236 Allocation Root # 2
20237 -------------------
20238  Number of non freed allocations    :  11
20239  Final Water Mark (non freed mem)   :   1.16 Kilobytes
20240  High Water Mark                    :   1.27 Kilobytes
20241  Backtrace                          :
20242    my_program.adb:23 my_program.alloc
20243 .
20244 .
20245 .
20246 @end smallexample
20247
20248 The first block of output gives general information. In this case, the
20249 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
20250 Unchecked_Deallocation routine occurred.
20251
20252 @noindent
20253 Subsequent paragraphs display  information on all allocation roots.
20254 An allocation root is a specific point in the execution of the program
20255 that generates some dynamic allocation, such as a ``@code{@b{new}}''
20256 construct. This root is represented by an execution backtrace (or subprogram
20257 call stack). By default the backtrace depth for allocations roots is 1, so
20258 that a root corresponds exactly to a source location. The backtrace can
20259 be made deeper, to make the root more specific.
20260
20261 @node Switches for gnatmem
20262 @subsection Switches for @code{gnatmem}
20263
20264 @noindent
20265 @code{gnatmem} recognizes the following switches:
20266
20267 @table @option
20268
20269 @item -q
20270 @cindex @option{-q} (@code{gnatmem})
20271 Quiet. Gives the minimum output needed to identify the origin of the
20272 memory leaks. Omits statistical information.
20273
20274 @item @var{N}
20275 @cindex @var{N} (@code{gnatmem})
20276 N is an integer literal (usually between 1 and 10) which controls the
20277 depth of the backtraces defining allocation root. The default value for
20278 N is 1. The deeper the backtrace, the more precise the localization of
20279 the root. Note that the total number of roots can depend on this
20280 parameter. This parameter must be specified @emph{before} the name of the
20281 executable to be analyzed, to avoid ambiguity.
20282
20283 @item -b n
20284 @cindex @option{-b} (@code{gnatmem})
20285 This switch has the same effect as just depth parameter.
20286
20287 @item -i @var{file}
20288 @cindex @option{-i} (@code{gnatmem})
20289 Do the @code{gnatmem} processing starting from @file{file}, rather than
20290 @file{gmem.out} in the current directory.
20291
20292 @item -m n
20293 @cindex @option{-m} (@code{gnatmem})
20294 This switch causes @code{gnatmem} to mask the allocation roots that have less
20295 than n leaks. The default value is 1. Specifying the value of 0 will allow to
20296 examine even the roots that didn't result in leaks.
20297
20298 @item -s order
20299 @cindex @option{-s} (@code{gnatmem})
20300 This switch causes @code{gnatmem} to sort the allocation roots according to the
20301 specified order of sort criteria, each identified by a single letter. The
20302 currently supported criteria are @code{n, h, w} standing respectively for
20303 number of unfreed allocations, high watermark, and final watermark
20304 corresponding to a specific root. The default order is @code{nwh}.
20305
20306 @end table
20307
20308 @node Example of gnatmem Usage
20309 @subsection Example of @code{gnatmem} Usage
20310
20311 @noindent
20312 The following example shows the use of @code{gnatmem}
20313 on a simple memory-leaking program.
20314 Suppose that we have the following Ada program:
20315
20316 @smallexample @c ada
20317 @group
20318 @cartouche
20319 with Unchecked_Deallocation;
20320 procedure Test_Gm is
20321
20322    type T is array (1..1000) of Integer;
20323    type Ptr is access T;
20324    procedure Free is new Unchecked_Deallocation (T, Ptr);
20325    A : Ptr;
20326
20327    procedure My_Alloc is
20328    begin
20329       A := new T;
20330    end My_Alloc;
20331
20332    procedure My_DeAlloc is
20333       B : Ptr := A;
20334    begin
20335       Free (B);
20336    end My_DeAlloc;
20337
20338 begin
20339    My_Alloc;
20340    for I in 1 .. 5 loop
20341       for J in I .. 5 loop
20342          My_Alloc;
20343       end loop;
20344       My_Dealloc;
20345    end loop;
20346 end;
20347 @end cartouche
20348 @end group
20349 @end smallexample
20350
20351 @noindent
20352 The program needs to be compiled with debugging option and linked with
20353 @code{gmem} library:
20354
20355 @smallexample
20356 $ gnatmake -g test_gm -largs -lgmem
20357 @end smallexample
20358
20359 @noindent
20360 Then we execute the program as usual:
20361
20362 @smallexample
20363 $ test_gm
20364 @end smallexample
20365
20366 @noindent
20367 Then @code{gnatmem} is invoked simply with
20368 @smallexample
20369 $ gnatmem test_gm
20370 @end smallexample
20371
20372 @noindent
20373 which produces the following output (result may vary on different platforms):
20374
20375 @smallexample
20376 Global information
20377 ------------------
20378    Total number of allocations        :  18
20379    Total number of deallocations      :   5
20380    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20381    High Water Mark                    :  56.90 Kilobytes
20382
20383 Allocation Root # 1
20384 -------------------
20385  Number of non freed allocations    :  11
20386  Final Water Mark (non freed mem)   :  42.97 Kilobytes
20387  High Water Mark                    :  46.88 Kilobytes
20388  Backtrace                          :
20389    test_gm.adb:11 test_gm.my_alloc
20390
20391 Allocation Root # 2
20392 -------------------
20393  Number of non freed allocations    :   1
20394  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20395  High Water Mark                    :  10.02 Kilobytes
20396  Backtrace                          :
20397    s-secsta.adb:81 system.secondary_stack.ss_init
20398
20399 Allocation Root # 3
20400 -------------------
20401  Number of non freed allocations    :   1
20402  Final Water Mark (non freed mem)   :  12 Bytes
20403  High Water Mark                    :  12 Bytes
20404  Backtrace                          :
20405    s-secsta.adb:181 system.secondary_stack.ss_init
20406 @end smallexample
20407
20408 @noindent
20409 Note that the GNAT run time contains itself a certain number of
20410 allocations that have no  corresponding deallocation,
20411 as shown here for root #2 and root
20412 #3. This is a normal behavior when the number of non-freed allocations
20413 is one, it allocates dynamic data structures that the run time needs for
20414 the complete lifetime of the program. Note also that there is only one
20415 allocation root in the user program with a single line back trace:
20416 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
20417 program shows that 'My_Alloc' is called at 2 different points in the
20418 source (line 21 and line 24). If those two allocation roots need to be
20419 distinguished, the backtrace depth parameter can be used:
20420
20421 @smallexample
20422 $ gnatmem 3 test_gm
20423 @end smallexample
20424
20425 @noindent
20426 which will give the following output:
20427
20428 @smallexample
20429 Global information
20430 ------------------
20431    Total number of allocations        :  18
20432    Total number of deallocations      :   5
20433    Final Water Mark (non freed mem)   :  53.00 Kilobytes
20434    High Water Mark                    :  56.90 Kilobytes
20435
20436 Allocation Root # 1
20437 -------------------
20438  Number of non freed allocations    :  10
20439  Final Water Mark (non freed mem)   :  39.06 Kilobytes
20440  High Water Mark                    :  42.97 Kilobytes
20441  Backtrace                          :
20442    test_gm.adb:11 test_gm.my_alloc
20443    test_gm.adb:24 test_gm
20444    b_test_gm.c:52 main
20445
20446 Allocation Root # 2
20447 -------------------
20448  Number of non freed allocations    :   1
20449  Final Water Mark (non freed mem)   :  10.02 Kilobytes
20450  High Water Mark                    :  10.02 Kilobytes
20451  Backtrace                          :
20452    s-secsta.adb:81  system.secondary_stack.ss_init
20453    s-secsta.adb:283 <system__secondary_stack___elabb>
20454    b_test_gm.c:33   adainit
20455
20456 Allocation Root # 3
20457 -------------------
20458  Number of non freed allocations    :   1
20459  Final Water Mark (non freed mem)   :   3.91 Kilobytes
20460  High Water Mark                    :   3.91 Kilobytes
20461  Backtrace                          :
20462    test_gm.adb:11 test_gm.my_alloc
20463    test_gm.adb:21 test_gm
20464    b_test_gm.c:52 main
20465
20466 Allocation Root # 4
20467 -------------------
20468  Number of non freed allocations    :   1
20469  Final Water Mark (non freed mem)   :  12 Bytes
20470  High Water Mark                    :  12 Bytes
20471  Backtrace                          :
20472    s-secsta.adb:181 system.secondary_stack.ss_init
20473    s-secsta.adb:283 <system__secondary_stack___elabb>
20474    b_test_gm.c:33   adainit
20475 @end smallexample
20476
20477 @noindent
20478 The allocation root #1 of the first example has been split in 2 roots #1
20479 and #3 thanks to the more precise associated backtrace.
20480
20481 @end ifclear
20482
20483 @node Stack Related Facilities
20484 @chapter Stack Related Facilities
20485
20486 @noindent
20487 This chapter describes some useful tools associated with stack
20488 checking and analysis. In
20489 particular, it deals with dynamic and static stack usage measurements.
20490
20491 @menu
20492 * Stack Overflow Checking::
20493 * Static Stack Usage Analysis::
20494 * Dynamic Stack Usage Analysis::
20495 @end menu
20496
20497 @node Stack Overflow Checking
20498 @section Stack Overflow Checking
20499 @cindex Stack Overflow Checking
20500 @cindex -fstack-check
20501
20502 @noindent
20503 For most operating systems, @command{gcc} does not perform stack overflow
20504 checking by default. This means that if the main environment task or
20505 some other task exceeds the available stack space, then unpredictable
20506 behavior will occur. Most native systems offer some level of protection by
20507 adding a guard page at the end of each task stack. This mechanism is usually
20508 not enough for dealing properly with stack overflow situations because
20509 a large local variable could ``jump'' above the guard page.
20510 Furthermore, when the
20511 guard page is hit, there may not be any space left on the stack for executing
20512 the exception propagation code. Enabling stack checking avoids
20513 such situations.
20514
20515 To activate stack checking, compile all units with the gcc option
20516 @option{-fstack-check}. For example:
20517
20518 @smallexample
20519 gcc -c -fstack-check package1.adb
20520 @end smallexample
20521
20522 @noindent
20523 Units compiled with this option will generate extra instructions to check
20524 that any use of the stack (for procedure calls or for declaring local
20525 variables in declare blocks) does not exceed the available stack space.
20526 If the space is exceeded, then a @code{Storage_Error} exception is raised.
20527
20528 For declared tasks, the stack size is controlled by the size
20529 given in an applicable @code{Storage_Size} pragma or by the value specified
20530 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
20531 the default size as defined in the GNAT runtime otherwise.
20532
20533 For the environment task, the stack size depends on
20534 system defaults and is unknown to the compiler. Stack checking
20535 may still work correctly if a fixed
20536 size stack is allocated, but this cannot be guaranteed.
20537 @ifclear vms
20538 To ensure that a clean exception is signalled for stack
20539 overflow, set the environment variable
20540 @env{GNAT_STACK_LIMIT} to indicate the maximum
20541 stack area that can be used, as in:
20542 @cindex GNAT_STACK_LIMIT
20543
20544 @smallexample
20545 SET GNAT_STACK_LIMIT 1600
20546 @end smallexample
20547
20548 @noindent
20549 The limit is given in kilobytes, so the above declaration would
20550 set the stack limit of the environment task to 1.6 megabytes.
20551 Note that the only purpose of this usage is to limit the amount
20552 of stack used by the environment task. If it is necessary to
20553 increase the amount of stack for the environment task, then this
20554 is an operating systems issue, and must be addressed with the
20555 appropriate operating systems commands.
20556 @end ifclear
20557 @ifset vms
20558 To have a fixed size stack in the environment task, the stack must be put
20559 in the P0 address space and its size specified.  Use these switches to
20560 create a p0 image:
20561
20562 @smallexample
20563 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
20564 @end smallexample
20565
20566 @noindent
20567 The quotes are required to keep case.  The number after @samp{STACK=} is the
20568 size of the environmental task stack in pagelets (512 bytes).  In this example
20569 the stack size is about 2 megabytes.
20570
20571 @noindent
20572 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
20573 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
20574 more details about the @option{/p0image} qualifier and the @option{stack}
20575 option.
20576 @end ifset
20577
20578 @node Static Stack Usage Analysis
20579 @section Static Stack Usage Analysis
20580 @cindex Static Stack Usage Analysis
20581 @cindex -fstack-usage
20582
20583 @noindent
20584 A unit compiled with @option{-fstack-usage} will generate an extra file
20585 that specifies
20586 the maximum amount of stack used, on a per-function basis.
20587 The file has the same
20588 basename as the target object file with a @file{.su} extension.
20589 Each line of this file is made up of three fields:
20590
20591 @itemize
20592 @item
20593 The name of the function.
20594 @item
20595 A number of bytes.
20596 @item
20597 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
20598 @end itemize
20599
20600 The second field corresponds to the size of the known part of the function
20601 frame.
20602
20603 The qualifier @code{static} means that the function frame size
20604 is purely static.
20605 It usually means that all local variables have a static size.
20606 In this case, the second field is a reliable measure of the function stack
20607 utilization.
20608
20609 The qualifier @code{dynamic} means that the function frame size is not static.
20610 It happens mainly when some local variables have a dynamic size. When this
20611 qualifier appears alone, the second field is not a reliable measure
20612 of the function stack analysis. When it is qualified with  @code{bounded}, it
20613 means that the second field is a reliable maximum of the function stack
20614 utilization.
20615
20616 @node Dynamic Stack Usage Analysis
20617 @section Dynamic Stack Usage Analysis
20618
20619 @noindent
20620 It is possible to measure the maximum amount of stack used by a task, by
20621 adding a switch to @command{gnatbind}, as:
20622
20623 @smallexample
20624 $ gnatbind -u0 file
20625 @end smallexample
20626
20627 @noindent
20628 With this option, at each task termination, its stack usage is  output on
20629 @file{stderr}.
20630 It is not always convenient to output the stack usage when the program
20631 is still running. Hence, it is possible to delay this output until program
20632 termination. for a given number of tasks specified as the argument of the
20633 @option{-u} option. For instance:
20634
20635 @smallexample
20636 $ gnatbind -u100 file
20637 @end smallexample
20638
20639 @noindent
20640 will buffer the stack usage information of the first 100 tasks to terminate and
20641 output this info at program termination. Results are displayed in four
20642 columns:
20643
20644 @noindent
20645 Index | Task Name | Stack Size | Stack Usage [Value +/- Variation]
20646
20647 @noindent
20648 where:
20649
20650 @table @emph
20651 @item Index
20652 is a number associated with each task.
20653
20654 @item Task Name
20655 is the name of the task analyzed.
20656
20657 @item Stack Size
20658 is the maximum size for the stack.
20659
20660 @item Stack Usage
20661 is the measure done by the stack analyzer. In order to prevent overflow, the stack
20662 is not entirely analyzed, and it's not possible to know exactly how
20663 much has actually been used. The report thus contains the theoretical stack usage
20664 (Value) and the possible variation (Variation) around this value.
20665
20666 @end table
20667
20668 @noindent
20669 The environment task stack, e.g., the stack that contains the main unit, is
20670 only processed when the environment variable GNAT_STACK_LIMIT is set.
20671
20672
20673 @c *********************************
20674 @c *            GNATCHECK          *
20675 @c *********************************
20676 @node Verifying Properties Using gnatcheck
20677 @chapter Verifying Properties Using @command{gnatcheck}
20678 @findex gnatcheck
20679 @cindex @command{gnatcheck}
20680
20681 @noindent
20682 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
20683 of Ada source files according to a given set of semantic rules.
20684 @cindex ASIS
20685
20686 In order to check compliance with a given rule, @command{gnatcheck} has to
20687 semantically analyze the Ada sources.
20688 Therefore, checks can only be performed on
20689 legal Ada units. Moreover, when a unit depends semantically upon units located
20690 outside the current directory, the source search path has to be provided when
20691 calling @command{gnatcheck}, either through a specified project file or
20692 through @command{gnatcheck} switches as described below.
20693
20694 A number of rules are predefined in @command{gnatcheck} and are described
20695 later in this chapter.
20696 You can also add new rules, by modifying the @command{gnatcheck} code and
20697 rebuilding the tool. In order to add a simple rule making some local checks,
20698 a small amount of straightforward ASIS-based programming is usually needed.
20699
20700 Project support for @command{gnatcheck} is provided by the GNAT
20701 driver (see @ref{The GNAT Driver and Project Files}).
20702
20703 Invoking @command{gnatcheck} on the command line has the form:
20704
20705 @smallexample
20706 @c $ gnatcheck @ovar{switches}  @{@var{filename}@}
20707 @c       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
20708 @c       @r{[}-cargs @var{gcc_switches}@r{]} -rules @var{rule_options}
20709 @c Expanding @ovar macro inline (explanation in macro def comments)
20710 $ gnatcheck @r{[}@var{switches}@r{]}  @{@var{filename}@}
20711       @r{[}^-files^/FILES^=@{@var{arg_list_filename}@}@r{]}
20712       @r{[}-cargs @var{gcc_switches}@r{]} -rules @var{rule_options}
20713 @end smallexample
20714
20715 @noindent
20716 where
20717 @itemize @bullet
20718 @item
20719 @var{switches} specify the general tool options
20720
20721 @item
20722 Each @var{filename} is the name (including the extension) of a source
20723 file to process. ``Wildcards'' are allowed, and
20724 the file name may contain path information.
20725
20726 @item
20727 Each @var{arg_list_filename} is the name (including the extension) of a text
20728 file containing the names of the source files to process, separated by spaces
20729 or line breaks.
20730
20731 @item
20732 @var{gcc_switches} is a list of switches for
20733 @command{gcc}. They will be passed on to all compiler invocations made by
20734 @command{gnatcheck} to generate the ASIS trees. Here you can provide
20735 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
20736 and use the @option{-gnatec} switch to set the configuration file.
20737
20738 @item
20739 @var{rule_options} is a list of options for controlling a set of
20740 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options}).
20741 @end itemize
20742
20743 @noindent
20744 Either a @file{@var{filename}} or an @file{@var{arg_list_filename}} must be
20745 supplied.
20746
20747 @menu
20748 * Format of the Report File::
20749 * General gnatcheck Switches::
20750 * gnatcheck Rule Options::
20751 * Adding the Results of Compiler Checks to gnatcheck Output::
20752 * Project-Wide Checks::
20753 * Rule exemption::
20754 * Predefined Rules::
20755 * Example of gnatcheck Usage::
20756 @end menu
20757
20758 @node Format of the Report File
20759 @section Format of the Report File
20760 @cindex Report file (for @code{gnatcheck})
20761
20762 @noindent
20763 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
20764 rule violations.
20765 It also creates a text file  that
20766 contains the complete report of the last gnatcheck run. By default this file
20767 is named named @file{^gnatcheck.out^GNATCHECK.OUT^} and it is located in the
20768 current directory; the @option{^-o^/OUTPUT^} option can be used to change the
20769 name and/or location of the report file. This report contains:
20770 @itemize @bullet
20771 @item date and time of @command{gnatcheck} run, the version of
20772 the tool that has generated this report and the full parameters
20773 of the  @command{gnatcheck} invocation;
20774 @item list of enabled rules;
20775 @item total number of detected violations;
20776 @item list of source files where rule violations have been detected;
20777 @item list of source files where no violations have been detected.
20778 @end itemize
20779
20780 @node General gnatcheck Switches
20781 @section General @command{gnatcheck} Switches
20782
20783 @noindent
20784 The following switches control the general @command{gnatcheck} behavior
20785
20786 @table @option
20787 @c !sort!
20788 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
20789 @item ^-a^/ALL^
20790 Process all units including those with read-only ALI files such as
20791 those from the GNAT Run-Time library.
20792
20793 @ifclear vms
20794 @ignore
20795 @cindex @option{-d} (@command{gnatcheck})
20796 @item -d
20797 Debug mode
20798 @end ignore
20799
20800 @cindex @option{-dd} (@command{gnatcheck})
20801 @item -dd
20802 Progress indicator mode (for use in GPS).
20803 @end ifclear
20804
20805 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
20806 @item ^-h^/HELP^
20807 List the predefined and user-defined rules. For more details see
20808 @ref{Predefined Rules}.
20809
20810 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
20811 @item ^-l^/LOCS^
20812 Use full source locations references in the report file. For a construct from
20813 a generic instantiation a full source location is a chain from the location
20814 of this construct in the generic unit to the place where this unit is
20815 instantiated.
20816
20817 @cindex @option{^-log^/LOG^} (@command{gnatcheck})
20818 @item ^-log^/LOG^
20819 Duplicate all the output sent to @file{stderr} into a log file. The log file
20820 is named @file{gnatcheck.log} and is located in the current directory.
20821
20822 @cindex @option{^-m^/DIAGNOSTIC_LIMIT^} (@command{gnatcheck})
20823 @item ^-m@i{nnnn}^/DIAGNOSTIC_LIMIT=@i{nnnn}^
20824 Maximum number of diagnostics to be sent to @file{stdout}, where @i{nnnn} is in
20825 the range 0@dots{}1000;
20826 the default value is 500. Zero means that there is no limitation on
20827 the number of diagnostic messages to be output.
20828
20829 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
20830 @item ^-q^/QUIET^
20831 Quiet mode. All the diagnostics about rule violations are placed in the
20832 @command{gnatcheck} report file only, without duplication on @file{stdout}.
20833
20834 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
20835 @item ^-s^/SHORT^
20836 Short format of the report file (no version information, no list of applied
20837 rules, no list of checked sources is included)
20838
20839 @cindex @option{^--include-file=@var{file}^/INCLUDE_FILE=@var{file}^} (@command{gnatcheck})
20840 @item ^--include-file^/INCLUDE_FILE^
20841 Append the content of the specified text file to the report file
20842
20843 @cindex @option{^-t^/TIME^} (@command{gnatcheck})
20844 @item ^-t^/TIME^
20845 Print out execution time.
20846
20847 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
20848 @item ^-v^/VERBOSE^
20849 Verbose mode; @command{gnatcheck} generates version information and then
20850 a trace of sources being processed.
20851
20852 @cindex @option{^-o ^/OUTPUT^} (@command{gnatcheck})
20853 @item ^-o ^/OUTPUT=^@var{report_file}
20854 Set name of report file file to @var{report_file} .
20855
20856 @end table
20857
20858 @node gnatcheck Rule Options
20859 @section @command{gnatcheck} Rule Options
20860
20861 @noindent
20862 The following options control the processing performed by
20863 @command{gnatcheck}.
20864
20865 @table @option
20866 @cindex @option{+ALL} (@command{gnatcheck})
20867 @item +ALL
20868 Turn all the rule checks ON.
20869
20870 @cindex @option{-ALL} (@command{gnatcheck})
20871 @item -ALL
20872 Turn all the rule checks OFF.
20873
20874 @cindex @option{+R} (@command{gnatcheck})
20875 @item +R@var{rule_id}@r{[}:@var{param}@r{]}
20876 Turn on the check for a specified rule with the specified parameter, if any.
20877 @var{rule_id} must be the identifier of one of the currently implemented rules
20878 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
20879 are not case-sensitive. The @var{param} item must
20880 be a string representing a valid parameter(s) for the specified rule.
20881 If it contains any space characters then this string must be enclosed in
20882 quotation marks.
20883
20884 @cindex @option{-R} (@command{gnatcheck})
20885 @item -R@var{rule_id}@r{[}:@var{param}@r{]}
20886 Turn off the check for a specified rule with the specified parameter, if any.
20887
20888 @cindex @option{-from} (@command{gnatcheck})
20889 @item -from=@var{rule_option_filename}
20890 Read the rule options from the text file @var{rule_option_filename}, referred
20891 to as a ``coding standard file'' below.
20892
20893 @end table
20894
20895 @noindent
20896 The default behavior is that all the rule checks are disabled.
20897
20898 A coding standard file is a text file that contains a set of rule options
20899 described above.
20900 @cindex Coding standard file (for @code{gnatcheck})
20901 The file may contain empty lines and Ada-style comments (comment
20902 lines and end-of-line comments). There can be several rule options on a
20903 single line (separated by a space).
20904
20905 A coding standard file may reference other coding standard files by including
20906 more @option{-from=@var{rule_option_filename}}
20907 options, each such option being replaced with the content of the
20908 corresponding coding standard file during processing. In case a
20909 cycle is detected (that is, @file{@var{rule_file_1}} reads rule options
20910 from @file{@var{rule_file_2}}, and @file{@var{rule_file_2}} reads
20911 (directly or indirectly) rule options from @file{@var{rule_file_1}}),
20912 processing fails with an error message.
20913
20914
20915 @node Adding the Results of Compiler Checks to gnatcheck Output
20916 @section Adding the Results of Compiler Checks to @command{gnatcheck} Output
20917
20918 @noindent
20919 The @command{gnatcheck} tool can include in the generated diagnostic messages
20920 and in
20921 the report file the results of the checks performed by the compiler. Though
20922 disabled by default, this effect may be obtained by using @option{+R} with
20923 the following rule identifiers and parameters:
20924
20925 @table @option
20926 @item Restrictions
20927 To record restrictions violations (which are performed by the compiler if the
20928 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
20929 use the @code{Restrictions} rule
20930 with the same parameters as pragma
20931 @code{Restrictions} or @code{Restriction_Warnings}.
20932
20933 @item Style_Checks
20934 To record compiler style checks (@pxref{Style Checking}), use the
20935 @code{Style_Checks} rule.
20936 This rule takes a parameter in one of the following forms:
20937 @itemize
20938 @item
20939 @code{All_Checks},
20940 which enables the standard style checks corresponding to the @option{-gnatyy}
20941 GNAT style check option, or
20942
20943 @item
20944 a string with the same
20945 structure and semantics as the @code{string_LITERAL} parameter of the
20946 GNAT pragma @code{Style_Checks}
20947 (for further information about this pragma,
20948 @pxref{Pragma Style_Checks,,, gnat_rm, GNAT Reference Manual}).
20949 @end itemize
20950
20951 @noindent
20952 For example, the
20953 @code{+RStyle_Checks:O} rule option activates
20954 the compiler style check that corresponds to
20955 @code{-gnatyO} style check option.
20956
20957 @item Warnings
20958 To record compiler warnings (@pxref{Warning Message Control}), use the
20959 @code{Warnings} rule with a parameter that is a valid
20960 @i{static_string_expression} argument of the GNAT pragma @code{Warnings}
20961 (for further information about this pragma,
20962 @pxref{Pragma Warnings,,,gnat_rm, GNAT Reference Manual}).
20963 Note that in case of gnatcheck
20964 's' parameter, that corresponds to the GNAT @option{-gnatws} option, disables
20965 all the specific warnings, but not suppresses the warning mode,
20966 and 'e' parameter, corresponding to @option{-gnatwe} that means
20967 "treat warnings as errors", does not have any effect.
20968
20969 @end table
20970
20971 To disable a specific restriction check, use @code{-RStyle_Checks} gnatcheck
20972 option with the corresponding restriction name as a parameter. @code{-R} is
20973 not available for @code{Style_Checks} and @code{Warnings} options, to disable
20974 warnings and style checks, use the corresponding warning and style options.
20975
20976 @node Project-Wide Checks
20977 @section Project-Wide Checks
20978 @cindex Project-wide checks (for @command{gnatcheck})
20979
20980 @noindent
20981 In order to perform checks on all units of a given project, you can use
20982 the GNAT driver along with the @option{-P} option:
20983 @smallexample
20984    gnat check -Pproj -rules -from=my_rules
20985 @end smallexample
20986
20987 @noindent
20988 If the project @code{proj} depends upon other projects, you can perform
20989 checks on the project closure using the @option{-U} option:
20990 @smallexample
20991    gnat check -Pproj -U -rules -from=my_rules
20992 @end smallexample
20993
20994 @noindent
20995 Finally, if not all the units are relevant to a particular main
20996 program in the project closure, you can perform checks for the set
20997 of units needed to create a given main program (unit closure) using
20998 the @option{-U} option followed by the name of the main unit:
20999 @smallexample
21000    gnat check -Pproj -U main -rules -from=my_rules
21001 @end smallexample
21002
21003
21004 @node Rule exemption
21005 @section Rule exemption
21006 @cindex Rule exemption (for @command{gnatcheck})
21007
21008 @noindent
21009 One of the most useful applications of @command{gnatcheck} is to
21010 automate the enforcement of project-specific coding standards,
21011 for example in safety-critical systems where particular features
21012 must be restricted in order to simplify the certification effort.
21013 However, it may sometimes be appropriate to violate a coding standard rule,
21014 and in such cases the rationale for the violation should be provided
21015 in the source program itself so that the individuals
21016 reviewing or maintaining the program can immediately understand the intent.
21017
21018 The @command{gnatcheck} tool supports this practice with the notion of
21019 a ``rule exemption'' covering a specific source code section. Normally
21020 rule violation messages are issued both on @file{stderr}
21021 and in a report file. In contrast, exempted violations are not listed on
21022 @file{stderr}; thus users invoking @command{gnatcheck} interactively
21023 (e.g. in its GPS interface) do not need to pay attention to known and
21024 justified violations. However, exempted violations along with their
21025 justification are documented in a special section of the report file that
21026 @command{gnatcheck} generates.
21027
21028 @menu
21029 * Using pragma Annotate to Control Rule Exemption::
21030 * gnatcheck Annotations Rules::
21031 @end menu
21032
21033 @node Using pragma Annotate to Control Rule Exemption
21034 @subsection Using pragma @code{Annotate} to Control Rule Exemption
21035 @cindex Using pragma Annotate to control rule exemption
21036
21037 @noindent
21038 Rule exemption is controlled by pragma @code{Annotate} when its first
21039 argument is ``gnatcheck''. The syntax of @command{gnatcheck}'s
21040 exemption control annotations is as follows:
21041
21042 @smallexample @c ada
21043 @group
21044 pragma Annotate (gnatcheck, @i{exemption_control}, @i{Rule_Name}, [@i{justification}]);
21045
21046 @i{exemption_control} ::= Exempt_On | Exempt_Off
21047
21048 @i{Rule_Name}         ::= string_literal
21049
21050 @i{justification}     ::= string_literal
21051 @end group
21052 @end smallexample
21053
21054 @noindent
21055 When a @command{gnatcheck} annotation has more then four arguments,
21056 @command{gnatcheck} issues a warning and ignores the additional arguments.
21057 If the additional arguments do not follow the syntax above,
21058 @command{gnatcheck} emits a warning and ignores the annotation.
21059
21060 The @i{@code{Rule_Name}} argument should be the name of some existing
21061 @command{gnatcheck} rule.
21062 Otherwise a warning message is generated and the pragma is
21063 ignored. If @code{Rule_Name} denotes a rule that is not activated by the given
21064 @command{gnatcheck} call, the pragma is ignored and no warning is issued.
21065
21066 A source code section where an exemption is active for a given rule is
21067 delimited by an @code{exempt_on} and @code{exempt_off} annotation pair:
21068
21069 @smallexample @c ada
21070 pragma Annotate (gnatcheck, Exempt_On, Rule_Name, "justification");
21071 -- source code section
21072 pragma Annotate (gnatcheck, Exempt_Off, Rule_Name);
21073 @end smallexample
21074
21075
21076 @node gnatcheck Annotations Rules
21077 @subsection @command{gnatcheck} Annotations Rules
21078 @cindex @command{gnatcheck} annotations rules
21079
21080 @itemize @bullet
21081
21082 @item
21083 An ``Exempt_Off'' annotation can only appear after a corresponding
21084 ``Exempt_On'' annotation.
21085
21086 @item
21087 Exempted source code sections are only based on the source location of the
21088 annotations. Any source construct between the two
21089 annotations is part of the exempted source code section.
21090
21091 @item
21092 Exempted source code sections for different rules are independent. They can
21093 be nested or intersect with one another without limitation.
21094 Creating nested or intersecting source code sections for the same rule is
21095 not allowed.
21096
21097 @item
21098 Malformed exempted source code sections are reported by a warning, and
21099 the corresponding rule exemptions are ignored.
21100
21101 @item
21102 When an exempted source code section does not contain at least one violation
21103 of the exempted rule, a warning is emitted on @file{stderr}.
21104
21105 @item
21106 If an ``Exempt_On'' annotation pragma does not have a matching
21107 ``Exempt_Off'' annotation pragma in the same compilation unit, then the
21108 exemption for the given rule is ignored and a warning is issued.
21109 @end itemize
21110
21111
21112 @node Predefined Rules
21113 @section Predefined Rules
21114 @cindex Predefined rules (for @command{gnatcheck})
21115
21116 @ignore
21117 @c (Jan 2007) Since the global rules are still under development and are not
21118 @c documented, there is no point in explaining the difference between
21119 @c global and local rules
21120 @noindent
21121 A rule in @command{gnatcheck} is either local or global.
21122 A @emph{local rule} is a rule that applies to a well-defined section
21123 of a program and that can be checked by analyzing only this section.
21124 A @emph{global rule} requires analysis of some global properties of the
21125 whole program (mostly related to the program call graph).
21126 As of @value{NOW}, the implementation of global rules should be
21127 considered to be at a preliminary stage. You can use the
21128 @option{+GLOBAL} option to enable all the global rules, and the
21129 @option{-GLOBAL} rule option to disable all the global rules.
21130
21131 All the global rules in the list below are
21132 so indicated by marking them ``GLOBAL''.
21133 This +GLOBAL and -GLOBAL options are not
21134 included in the list of gnatcheck options above, because at the moment they
21135 are considered as a temporary debug options.
21136
21137 @command{gnatcheck} performs rule checks for generic
21138 instances only for global rules.  This limitation may be relaxed in a later
21139 release.
21140 @end ignore
21141
21142 @noindent
21143 The following subsections document the rules implemented in
21144 @command{gnatcheck}.
21145 The subsection title is the same as the rule identifier, which may be
21146 used as a parameter of the @option{+R} or @option{-R} options.
21147
21148
21149 @menu
21150 * Abstract_Type_Declarations::
21151 * Anonymous_Arrays::
21152 * Anonymous_Subtypes::
21153 * Blocks::
21154 * Boolean_Relational_Operators::
21155 @ignore
21156 * Ceiling_Violations::
21157 @end ignore
21158 * Complex_Inlined_Subprograms::
21159 * Controlled_Type_Declarations::
21160 * Declarations_In_Blocks::
21161 * Deep_Inheritance_Hierarchies::
21162 * Deeply_Nested_Generics::
21163 * Deeply_Nested_Inlining::
21164 @ignore
21165 * Deeply_Nested_Local_Inlining::
21166 @end ignore
21167 * Default_Parameters::
21168 * Direct_Calls_To_Primitives::
21169 * Discriminated_Records::
21170 * Enumeration_Ranges_In_CASE_Statements::
21171 * Exceptions_As_Control_Flow::
21172 * Exits_From_Conditional_Loops::
21173 * EXIT_Statements_With_No_Loop_Name::
21174 * Expanded_Loop_Exit_Names::
21175 * Explicit_Full_Discrete_Ranges::
21176 * Float_Equality_Checks::
21177 * Forbidden_Attributes::
21178 * Forbidden_Pragmas::
21179 * Function_Style_Procedures::
21180 * Generics_In_Subprograms::
21181 * GOTO_Statements::
21182 * Implicit_IN_Mode_Parameters::
21183 * Implicit_SMALL_For_Fixed_Point_Types::
21184 * Improperly_Located_Instantiations::
21185 * Improper_Returns::
21186 * Library_Level_Subprograms::
21187 * Local_Packages::
21188 @ignore
21189 * Improperly_Called_Protected_Entries::
21190 @end ignore
21191 * Metrics::
21192 * Misnamed_Controlling_Parameters::
21193 * Misnamed_Identifiers::
21194 * Multiple_Entries_In_Protected_Definitions::
21195 * Name_Clashes::
21196 * Non_Qualified_Aggregates::
21197 * Non_Short_Circuit_Operators::
21198 * Non_SPARK_Attributes::
21199 * Non_Tagged_Derived_Types::
21200 * Non_Visible_Exceptions::
21201 * Numeric_Literals::
21202 * OTHERS_In_Aggregates::
21203 * OTHERS_In_CASE_Statements::
21204 * OTHERS_In_Exception_Handlers::
21205 * Outer_Loop_Exits::
21206 * Overloaded_Operators::
21207 * Overly_Nested_Control_Structures::
21208 * Parameters_Out_Of_Order::
21209 * Positional_Actuals_For_Defaulted_Generic_Parameters::
21210 * Positional_Actuals_For_Defaulted_Parameters::
21211 * Positional_Components::
21212 * Positional_Generic_Parameters::
21213 * Positional_Parameters::
21214 * Predefined_Numeric_Types::
21215 * Raising_External_Exceptions::
21216 * Raising_Predefined_Exceptions::
21217 * Separate_Numeric_Error_Handlers::
21218 @ignore
21219 * Recursion::
21220 * Side_Effect_Functions::
21221 @end ignore
21222 * Slices::
21223 * Too_Many_Parents::
21224 * Unassigned_OUT_Parameters::
21225 * Uncommented_BEGIN_In_Package_Bodies::
21226 * Unconditional_Exits::
21227 * Unconstrained_Array_Returns::
21228 * Universal_Ranges::
21229 * Unnamed_Blocks_And_Loops::
21230 @ignore
21231 * Unused_Subprograms::
21232 @end ignore
21233 * USE_PACKAGE_Clauses::
21234 * Visible_Components::
21235 * Volatile_Objects_Without_Address_Clauses::
21236 @end menu
21237
21238
21239 @node Abstract_Type_Declarations
21240 @subsection @code{Abstract_Type_Declarations}
21241 @cindex @code{Abstract_Type_Declarations} rule (for @command{gnatcheck})
21242
21243 @noindent
21244 Flag all declarations of abstract types. For an abstract private
21245 type, both the private and full type declarations are flagged.
21246
21247 This rule has no parameters.
21248
21249
21250 @node Anonymous_Arrays
21251 @subsection @code{Anonymous_Arrays}
21252 @cindex @code{Anonymous_Arrays} rule (for @command{gnatcheck})
21253
21254 @noindent
21255 Flag all anonymous array type definitions (by Ada semantics these can only
21256 occur in object declarations).
21257
21258 This rule has no parameters.
21259
21260 @node Anonymous_Subtypes
21261 @subsection @code{Anonymous_Subtypes}
21262 @cindex @code{Anonymous_Subtypes} rule (for @command{gnatcheck})
21263
21264 @noindent
21265 Flag all uses of anonymous subtypes (except cases when subtype indication
21266 is a part of a record component definition, and this subtype indication
21267 depends on a discriminant). A use of an anonymous subtype is
21268 any instance of a subtype indication with a constraint, other than one
21269 that occurs immediately within a subtype declaration. Any use of a range
21270 other than as a constraint used immediately within a subtype declaration
21271 is considered as an anonymous subtype.
21272
21273 An effect of this rule is that @code{for} loops such as the following are
21274 flagged (since @code{1..N} is formally a ``range''):
21275
21276 @smallexample @c ada
21277 for I in 1 .. N loop
21278    @dots{}
21279 end loop;
21280 @end smallexample
21281
21282 @noindent
21283 Declaring an explicit subtype solves the problem:
21284
21285 @smallexample @c ada
21286 subtype S is Integer range 1..N;
21287 @dots{}
21288 for I in S loop
21289    @dots{}
21290 end loop;
21291 @end smallexample
21292
21293 @noindent
21294 This rule has no parameters.
21295
21296 @node Blocks
21297 @subsection @code{Blocks}
21298 @cindex @code{Blocks} rule (for @command{gnatcheck})
21299
21300 @noindent
21301 Flag each block statement.
21302
21303 This rule has no parameters.
21304
21305 @node Boolean_Relational_Operators
21306 @subsection @code{Boolean_Relational_Operators}
21307 @cindex @code{Boolean_Relational_Operators} rule (for @command{gnatcheck})
21308
21309 @noindent
21310 Flag each call to a predefined relational operator (``<'', ``>'', ``<='',
21311 ``>='', ``='' and ``/='') for the predefined Boolean type.
21312 (This rule is useful in enforcing the SPARK language restrictions.)
21313
21314 Calls to predefined relational operators of any type derived from
21315 @code{Standard.Boolean} are not detected.  Calls to user-defined functions
21316 with these designators, and uses of operators that are renamings
21317 of the predefined relational operators for @code{Standard.Boolean},
21318 are likewise not detected.
21319
21320 This rule has no parameters.
21321
21322 @ignore
21323 @node Ceiling_Violations
21324 @subsection @code{Ceiling5_Violations} (under construction, GLOBAL)
21325 @cindex @code{Ceiling_Violations} rule (for @command{gnatcheck})
21326
21327 @noindent
21328 Flag invocations of a protected operation by a task whose priority exceeds
21329 the protected object's ceiling.
21330
21331 As of @value{NOW}, this rule has the following limitations:
21332
21333 @itemize @bullet
21334
21335 @item
21336  We consider only pragmas Priority and Interrupt_Priority as means to define
21337   a task/protected operation priority. We do not consider the effect of using
21338   Ada.Dynamic_Priorities.Set_Priority procedure;
21339
21340 @item
21341  We consider only base task priorities, and no priority inheritance. That is,
21342   we do not make a difference between calls issued during task activation and
21343   execution of the sequence of statements from task body;
21344
21345 @item
21346  Any situation when the priority of protected operation caller is set by a
21347   dynamic expression (that is, the corresponding Priority or
21348   Interrupt_Priority pragma has a non-static expression as an argument) we
21349   treat as a priority inconsistency (and, therefore, detect this situation).
21350 @end itemize
21351
21352 @noindent
21353 At the moment the notion of the main subprogram is not implemented in
21354 gnatcheck, so any pragma Priority in a library level subprogram body (in case
21355 if this subprogram can be a main subprogram of a partition) changes the
21356 priority of an environment task. So if we have more then one such pragma in
21357 the set of processed sources, the pragma that is processed last, defines the
21358 priority of an environment task.
21359
21360 This rule has no parameters.
21361 @end ignore
21362
21363 @node Controlled_Type_Declarations
21364 @subsection @code{Controlled_Type_Declarations}
21365 @cindex @code{Controlled_Type_Declarations} rule (for @command{gnatcheck})
21366
21367 @noindent
21368 Flag all declarations of controlled types. A declaration of a private type
21369 is flagged if its full declaration declares a controlled type. A declaration
21370 of a derived type is flagged if its ancestor type is controlled. Subtype
21371 declarations are not checked. A declaration of a type that itself is not a
21372 descendant of a type declared in @code{Ada.Finalization} but has a controlled
21373 component is not checked.
21374
21375 This rule has no parameters.
21376
21377
21378 @node Complex_Inlined_Subprograms
21379 @subsection @code{Complex_Inlined_Subprograms}
21380 @cindex @code{Complex_Inlined_Subprograms} rule (for @command{gnatcheck})
21381
21382 @noindent
21383 Flags a subprogram (or generic subprogram) if
21384 pragma Inline is applied to the subprogram and at least one of the following
21385 conditions is met:
21386
21387 @itemize @bullet
21388 @item
21389 it contains at least one complex declaration such as a subprogram body,
21390 package, task, protected declaration, or a generic instantiation
21391 (except instantiation of @code{Ada.Unchecked_Conversion});
21392
21393 @item
21394 it contains at least one complex statement such as a loop, a case
21395 or a if statement, or a short circuit control form;
21396
21397 @item
21398 the number of statements exceeds
21399 a value specified by the @option{N} rule parameter;
21400 @end itemize
21401
21402 @noindent
21403 This rule has the following (mandatory) parameter for the @option{+R} option:
21404
21405 @table @emph
21406 @item N
21407 Positive integer specifying the maximum allowed total number of statements
21408 in the subprogram body.
21409 @end table
21410
21411
21412 @node Declarations_In_Blocks
21413 @subsection @code{Declarations_In_Blocks}
21414 @cindex @code{Declarations_In_Blocks} rule (for @command{gnatcheck})
21415
21416 @noindent
21417 Flag all block statements containing local declarations. A @code{declare}
21418 block with an empty @i{declarative_part} or with a @i{declarative part}
21419 containing only pragmas and/or @code{use} clauses is not flagged.
21420
21421 This rule has no parameters.
21422
21423
21424 @node Deep_Inheritance_Hierarchies
21425 @subsection @code{Deep_Inheritance_Hierarchies}
21426 @cindex @code{Deep_Inheritance_Hierarchies} rule (for @command{gnatcheck})
21427
21428 @noindent
21429 Flags a tagged derived type declaration or an interface type declaration if
21430 its depth (in its inheritance
21431 hierarchy) exceeds the value specified by the @option{N} rule parameter.
21432
21433 The inheritance depth of a tagged type or interface type is defined as 0 for
21434 a type  with no parent and no progenitor, and otherwise as 1 + max of the
21435 depths of the immediate parent and immediate progenitors.
21436
21437 This rule does not flag private extension
21438 declarations. In the case of a private extension, the corresponding full
21439 declaration is checked.
21440
21441 This rule has the following (mandatory) parameter for the @option{+R} option:
21442
21443 @table @emph
21444 @item N
21445 Integer not less than -1 specifying the maximal allowed depth of any inheritance
21446 hierarchy. If the rule parameter is set to -1, the rule flags all the declarations
21447 of tagged and interface types.
21448 @end table
21449
21450
21451 @node Deeply_Nested_Generics
21452 @subsection @code{Deeply_Nested_Generics}
21453 @cindex @code{Deeply_Nested_Generics} rule (for @command{gnatcheck})
21454
21455 @noindent
21456 Flags a generic declaration nested in another generic declaration if
21457 the nesting level of the inner generic exceeds
21458 a value specified by the @option{N} rule parameter.
21459 The nesting level is the number of generic declaratons that enclose the given
21460 (generic) declaration. Formal packages are not flagged by this rule.
21461
21462 This rule has the following (mandatory) parameters for the @option{+R} option:
21463
21464 @table @emph
21465 @item N
21466 Positive integer specifying the maximal allowed nesting level
21467 for a generic declaration.
21468 @end table
21469
21470 @node Deeply_Nested_Inlining
21471 @subsection @code{Deeply_Nested_Inlining}
21472 @cindex @code{Deeply_Nested_Inlining} rule (for @command{gnatcheck})
21473
21474 @noindent
21475 Flags a subprogram (or generic subprogram) if
21476 pragma Inline has been applied to the subprogram but the subprogram
21477 calls to another inlined subprogram that results in nested inlining
21478 with nesting depth exceeding the value specified by the
21479 @option{N} rule parameter.
21480
21481 This rule requires the global analysis of all the compilation units that
21482 are @command{gnatcheck} arguments; such analysis may affect the tool's
21483 performance.
21484
21485 This rule has the following (mandatory) parameter for the @option{+R} option:
21486
21487 @table @emph
21488 @item N
21489 Positive integer specifying the maximal allowed level of nested inlining.
21490 @end table
21491
21492
21493 @ignore
21494 @node Deeply_Nested_Local_Inlining
21495 @subsection @code{Deeply_Nested_Local_Inlining}
21496 @cindex @code{Deeply_Nested_Local_Inlining} rule (for @command{gnatcheck})
21497
21498 @noindent
21499 Flags a subprogram body if a pragma @code{Inline} is applied to the
21500 corresponding subprogram (or generic subprogram) and the body contains a call
21501 to another inlined subprogram that results in nested inlining with nesting
21502 depth more then a value specified by the @option{N} rule parameter.
21503 This rule is similar to @code{Deeply_Nested_Inlining} rule, but it
21504 assumes that calls to subprograms in
21505 with'ed units are not inlided, so all the analysis of the depth of inlining is
21506 limited by the compilation unit where the subprogram body is located and the
21507 units it depends semantically upon. Such analysis may be usefull for the case
21508 when neiter @option{-gnatn} nor @option{-gnatN} option is used when building
21509 the executable.
21510
21511 This rule has the following (mandatory) parameters for the @option{+R} option:
21512
21513 @table @emph
21514 @item N
21515 Positive integer specifying the maximal allowed level of nested inlining.
21516 @end table
21517
21518 @end ignore
21519
21520 @node Default_Parameters
21521 @subsection @code{Default_Parameters}
21522 @cindex @code{Default_Parameters} rule (for @command{gnatcheck})
21523
21524 @noindent
21525 Flag all default expressions for subprogram parameters. Parameter
21526 declarations of formal and generic subprograms are also checked.
21527
21528 This rule has no parameters.
21529
21530
21531 @node Direct_Calls_To_Primitives
21532 @subsection @code{Direct_Calls_To_Primitives}
21533 @cindex @code{Direct_Calls_To_Primitives} rule (for @command{gnatcheck})
21534
21535 @noindent
21536 Flags any non-dispatching call to a dispatching primitive operation, except
21537 for the common idiom where a primitive subprogram for a tagged type
21538 directly calls the same primitive subprogram of the type's immediate ancestor.
21539
21540 This rule has no parameters.
21541
21542
21543 @node Discriminated_Records
21544 @subsection @code{Discriminated_Records}
21545 @cindex @code{Discriminated_Records} rule (for @command{gnatcheck})
21546
21547 @noindent
21548 Flag all declarations of record types with discriminants. Only the
21549 declarations of record and record extension types are checked. Incomplete,
21550 formal, private, derived and private extension type declarations are not
21551 checked. Task and protected type declarations also are not checked.
21552
21553 This rule has no parameters.
21554
21555
21556 @node Enumeration_Ranges_In_CASE_Statements
21557 @subsection @code{Enumeration_Ranges_In_CASE_Statements}
21558 @cindex @code{Enumeration_Ranges_In_CASE_Statements} (for @command{gnatcheck})
21559
21560 @noindent
21561 Flag each use of a range of enumeration literals as a choice in a
21562 @code{case} statement.
21563 All forms for specifying a range (explicit ranges
21564 such as @code{A .. B}, subtype marks and @code{'Range} attributes) are flagged.
21565 An enumeration range is
21566 flagged even if contains exactly one enumeration value or no values at all. A
21567 type derived from an enumeration type is considered as an enumeration type.
21568
21569 This rule helps prevent maintenance problems arising from adding an
21570 enumeration value to a type and having it implicitly handled by an existing
21571 @code{case} statement with an enumeration range that includes the new literal.
21572
21573 This rule has no parameters.
21574
21575
21576 @node Exceptions_As_Control_Flow
21577 @subsection @code{Exceptions_As_Control_Flow}
21578 @cindex @code{Exceptions_As_Control_Flow} (for @command{gnatcheck})
21579
21580 @noindent
21581 Flag each place where an exception is explicitly raised and handled in the
21582 same subprogram body. A @code{raise} statement in an exception handler,
21583 package body, task body or entry body is not flagged.
21584
21585 The rule has no parameters.
21586
21587 @node Exits_From_Conditional_Loops
21588 @subsection @code{Exits_From_Conditional_Loops}
21589 @cindex @code{Exits_From_Conditional_Loops} (for @command{gnatcheck})
21590
21591 @noindent
21592 Flag any exit statement if it transfers the control out of a @code{for} loop
21593 or a @code{while} loop. This includes cases when the @code{exit} statement
21594 applies to a @code{FOR} or @code{while} loop, and cases when it is enclosed
21595 in some @code{for} or @code{while} loop, but transfers the control from some
21596 outer (inconditional) @code{loop} statement.
21597
21598 The rule has no parameters.
21599
21600
21601 @node EXIT_Statements_With_No_Loop_Name
21602 @subsection @code{EXIT_Statements_With_No_Loop_Name}
21603 @cindex @code{EXIT_Statements_With_No_Loop_Name} (for @command{gnatcheck})
21604
21605 @noindent
21606 Flag each @code{exit} statement that does not specify the name of the loop
21607 being exited.
21608
21609 The rule has no parameters.
21610
21611
21612 @node Expanded_Loop_Exit_Names
21613 @subsection @code{Expanded_Loop_Exit_Names}
21614 @cindex @code{Expanded_Loop_Exit_Names} rule (for @command{gnatcheck})
21615
21616 @noindent
21617 Flag all expanded loop names in @code{exit} statements.
21618
21619 This rule has no parameters.
21620
21621 @node Explicit_Full_Discrete_Ranges
21622 @subsection @code{Explicit_Full_Discrete_Ranges}
21623 @cindex @code{Explicit_Full_Discrete_Ranges} rule (for @command{gnatcheck})
21624
21625 @noindent
21626 Flag each discrete range that has the form @code{A'First .. A'Last}.
21627
21628 This rule has no parameters.
21629
21630 @node Float_Equality_Checks
21631 @subsection @code{Float_Equality_Checks}
21632 @cindex @code{Float_Equality_Checks} rule (for @command{gnatcheck})
21633
21634 @noindent
21635 Flag all calls to the predefined equality operations for floating-point types.
21636 Both ``@code{=}'' and ``@code{/=}'' operations are checked.
21637 User-defined equality operations are not flagged, nor are ``@code{=}''
21638 and ``@code{/=}'' operations for fixed-point types.
21639
21640 This rule has no parameters.
21641
21642
21643 @node Forbidden_Attributes
21644 @subsection @code{Forbidden_Attributes}
21645 @cindex @code{Forbidden_Attributes} rule (for @command{gnatcheck})
21646
21647 @noindent
21648 Flag each use of the specified attributes. The attributes to be detected are
21649 named in the rule's parameters.
21650
21651 This rule has the following parameters:
21652
21653 @itemize @bullet
21654 @item For the @option{+R} option
21655
21656 @table @asis
21657 @item @emph{Attribute_Designator}
21658 Adds the specified attribute to the set of attributes to be detected and sets
21659 the detection checks for all the specified attributes ON.
21660 If @emph{Attribute_Designator}
21661 does not denote any attribute defined in the Ada standard
21662 or in
21663 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
21664 Manual}, it is treated as the name of unknown attribute.
21665
21666 @item @code{GNAT}
21667 All the GNAT-specific attributes are detected; this sets
21668 the detection checks for all the specified attributes ON.
21669
21670 @item @code{ALL}
21671 All attributes are detected; this sets the rule ON.
21672 @end table
21673
21674 @item For the @option{-R} option
21675 @table @asis
21676 @item @emph{Attribute_Designator}
21677 Removes the specified attribute from the set of attributes to be
21678 detected without affecting detection checks for
21679 other attributes. If @emph{Attribute_Designator} does not correspond to any
21680 attribute defined in the Ada standard or in
21681 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference Manual},
21682 this option is treated as turning OFF detection of all unknown attributes.
21683
21684 @item GNAT
21685 Turn OFF detection of all GNAT-specific attributes
21686
21687 @item ALL
21688 Clear the list of the attributes to be detected and
21689 turn the rule OFF.
21690 @end table
21691 @end itemize
21692
21693 @noindent
21694 Parameters are not case sensitive. If @emph{Attribute_Designator} does not
21695 have the syntax of an Ada identifier and therefore can not be considered as a
21696 (part of an) attribute designator, a diagnostic message is generated and the
21697 corresponding parameter is ignored. (If an attribute allows a static
21698 expression to be a part of the attribute designator, this expression is
21699 ignored by this rule.)
21700
21701 When more then one parameter is given in the same rule option, the parameters
21702 must be separated by commas.
21703
21704 If more then one option for this rule is specified for the gnatcheck call, a
21705 new option overrides the previous one(s).
21706
21707 The @option{+R} option with no parameters turns the rule ON, with the set of
21708 attributes to be detected defined by the previous rule options.
21709 (By default this set is empty, so if the only option specified for the rule is
21710 @option{+RForbidden_Attributes} (with
21711 no parameter), then the rule is enabled, but it does not detect anything).
21712 The @option{-R} option with no parameter turns the rule OFF, but it does not
21713 affect the set of attributes to be detected.
21714
21715
21716 @node Forbidden_Pragmas
21717 @subsection @code{Forbidden_Pragmas}
21718 @cindex @code{Forbidden_Pragmas} rule (for @command{gnatcheck})
21719
21720 @noindent
21721 Flag each use of the specified pragmas.  The pragmas to be detected
21722 are named in the rule's  parameters.
21723
21724 This rule has the following parameters:
21725
21726 @itemize @bullet
21727 @item For the @option{+R} option
21728
21729 @table @asis
21730 @item @emph{Pragma_Name}
21731 Adds the specified pragma to the set of pragmas to be
21732 checked and sets the checks for all the specified pragmas
21733 ON. @emph{Pragma_Name} is treated as a name of a pragma. If it
21734 does not correspond to any pragma name defined in the Ada
21735 standard or to the name of a GNAT-specific pragma defined
21736 in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
21737 Manual}, it is treated as the name of unknown pragma.
21738
21739 @item @code{GNAT}
21740 All the GNAT-specific pragmas are detected; this sets
21741 the checks for all the specified pragmas ON.
21742
21743 @item @code{ALL}
21744 All pragmas are detected; this sets the rule ON.
21745 @end table
21746
21747 @item For the @option{-R} option
21748 @table @asis
21749 @item @emph{Pragma_Name}
21750 Removes the specified pragma from the set of pragmas to be
21751 checked without affecting checks for
21752 other pragmas. @emph{Pragma_Name} is treated as a name
21753 of a pragma. If it does not correspond to any pragma
21754 defined in the Ada standard or to any name defined in
21755 @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
21756 this option is treated as turning OFF detection of all unknown pragmas.
21757
21758 @item GNAT
21759 Turn OFF detection of all GNAT-specific pragmas
21760
21761 @item ALL
21762 Clear the list of the pragmas to be detected and
21763 turn the rule OFF.
21764 @end table
21765 @end itemize
21766
21767 @noindent
21768 Parameters are not case sensitive. If @emph{Pragma_Name} does not have
21769 the syntax of an Ada identifier and therefore can not be considered
21770 as a pragma name, a diagnostic message is generated and the corresponding
21771 parameter is ignored.
21772
21773 When more then one parameter is given in the same rule option, the parameters
21774 must be separated by a comma.
21775
21776 If more then one option for this rule is specified for the @command{gnatcheck}
21777 call, a new option overrides the previous one(s).
21778
21779 The @option{+R} option with no parameters turns the rule ON with the set of
21780 pragmas to be detected defined by the previous rule options.
21781 (By default this set is empty, so if the only option specified for the rule is
21782 @option{+RForbidden_Pragmas} (with
21783 no parameter), then the rule is enabled, but it does not detect anything).
21784 The @option{-R} option with no parameter turns the rule OFF, but it does not
21785 affect the set of pragmas to be detected.
21786
21787
21788
21789
21790 @node Function_Style_Procedures
21791 @subsection @code{Function_Style_Procedures}
21792 @cindex @code{Function_Style_Procedures} rule (for @command{gnatcheck})
21793
21794 @noindent
21795 Flag each procedure that can be rewritten as a function. A procedure can be
21796 converted into a function if it has exactly one parameter of mode @code{out}
21797 and no parameters of mode @code{in out}. Procedure declarations,
21798 formal procedure declarations, and generic procedure declarations are always
21799 checked. Procedure
21800 bodies and body stubs are flagged only if they do not have corresponding
21801 separate declarations. Procedure renamings and procedure instantiations are
21802 not flagged.
21803
21804 If a procedure can be rewritten as a function, but its @code{out} parameter is
21805 of a limited type, it is not flagged.
21806
21807 Protected procedures are not flagged. Null procedures also are not flagged.
21808
21809 This rule has no parameters.
21810
21811
21812 @node Generics_In_Subprograms
21813 @subsection @code{Generics_In_Subprograms}
21814 @cindex @code{Generics_In_Subprograms} rule (for @command{gnatcheck})
21815
21816 @noindent
21817 Flag each declaration of a generic unit in a subprogram. Generic
21818 declarations in the bodies of generic subprograms are also flagged.
21819 A generic unit nested in another generic unit is not flagged.
21820 If a generic unit is
21821 declared in a local package that is declared in a subprogram body, the
21822 generic unit is flagged.
21823
21824 This rule has no parameters.
21825
21826
21827 @node GOTO_Statements
21828 @subsection @code{GOTO_Statements}
21829 @cindex @code{GOTO_Statements} rule (for @command{gnatcheck})
21830
21831 @noindent
21832 Flag each occurrence of a @code{goto} statement.
21833
21834 This rule has no parameters.
21835
21836
21837 @node Implicit_IN_Mode_Parameters
21838 @subsection @code{Implicit_IN_Mode_Parameters}
21839 @cindex @code{Implicit_IN_Mode_Parameters} rule (for @command{gnatcheck})
21840
21841 @noindent
21842 Flag each occurrence of a formal parameter with an implicit @code{in} mode.
21843 Note that @code{access} parameters, although they technically behave
21844 like @code{in} parameters, are not flagged.
21845
21846 This rule has no parameters.
21847
21848
21849 @node Implicit_SMALL_For_Fixed_Point_Types
21850 @subsection @code{Implicit_SMALL_For_Fixed_Point_Types}
21851 @cindex @code{Implicit_SMALL_For_Fixed_Point_Types} rule (for @command{gnatcheck})
21852
21853 @noindent
21854 Flag each fixed point type declaration that lacks an explicit
21855 representation  clause to define its @code{'Small} value.
21856 Since @code{'Small} can be  defined only for ordinary fixed point types,
21857 decimal fixed point type declarations are not checked.
21858
21859 This rule has no parameters.
21860
21861
21862 @node Improperly_Located_Instantiations
21863 @subsection @code{Improperly_Located_Instantiations}
21864 @cindex @code{Improperly_Located_Instantiations} rule (for @command{gnatcheck})
21865
21866 @noindent
21867 Flag all generic instantiations in library-level package specs
21868 (including library generic packages) and in all subprogram bodies.
21869
21870 Instantiations in task and entry bodies are not flagged. Instantiations in the
21871 bodies of protected subprograms are flagged.
21872
21873 This rule has no parameters.
21874
21875
21876
21877 @node Improper_Returns
21878 @subsection @code{Improper_Returns}
21879 @cindex @code{Improper_Returns} rule (for @command{gnatcheck})
21880
21881 @noindent
21882 Flag each explicit @code{return} statement in procedures, and
21883 multiple @code{return} statements in functions.
21884 Diagnostic messages are generated for all @code{return} statements
21885 in a procedure (thus each procedure must be written so that it
21886 returns implicitly at the end of its statement part),
21887 and for all @code{return} statements in a function after the first one.
21888 This rule supports the stylistic convention that each subprogram
21889 should have no more than one point of normal return.
21890
21891 This rule has no parameters.
21892
21893
21894 @node Library_Level_Subprograms
21895 @subsection @code{Library_Level_Subprograms}
21896 @cindex @code{Library_Level_Subprograms} rule (for @command{gnatcheck})
21897
21898 @noindent
21899 Flag all library-level subprograms (including generic subprogram instantiations).
21900
21901 This rule has no parameters.
21902
21903
21904 @node Local_Packages
21905 @subsection @code{Local_Packages}
21906 @cindex @code{Local_Packages} rule (for @command{gnatcheck})
21907
21908 @noindent
21909 Flag all local packages declared in package and generic package
21910 specs.
21911 Local packages in bodies are not flagged.
21912
21913 This rule has no parameters.
21914
21915 @ignore
21916 @node Improperly_Called_Protected_Entries
21917 @subsection @code{Improperly_Called_Protected_Entries} (under construction, GLOBAL)
21918 @cindex @code{Improperly_Called_Protected_Entries} rule (for @command{gnatcheck})
21919
21920 @noindent
21921 Flag each protected entry that can be called from more than one task.
21922
21923 This rule has no parameters.
21924 @end ignore
21925
21926 @node Metrics
21927 @subsection @code{Metrics}
21928 @cindex @code{Metrics} rule (for @command{gnatcheck})
21929
21930 @noindent
21931 There is a set of checks based on computing a metric value and comparing the
21932 result with the specified upper (or lower, depending on a specific metric)
21933 value specified for a given metric. A construct is flagged if a given metric
21934 is applicable (can be computed) for it and the computed value is greater
21935 then (lover then) the specified upper (lower) bound.
21936
21937 The name of any metric-based rule consists of the prefix @code{Metrics_}
21938 followed by the name of the corresponding metric (see the table below).
21939 For @option{+R} option, each metric-based rule has a numeric parameter
21940 specifying the bound (integer or real, depending on a metric), @option{-R}
21941 option for metric rules does not have a parameter.
21942
21943 The following table shows the metric names for that the corresponding
21944 metrics-based checks are supported by gnatcheck, including the
21945 constraint that must be satisfied by the bound that is specified for the check
21946 and what bound - upper (U) or lower (L) - should be specified.
21947
21948 @multitable {@code{Cyclomatic_Complexity}}{Cyclomatic complexity}{Positive integer}
21949 @ifnothtml
21950 @headitem Check Name @tab Description @tab Bounds Value
21951 @end ifnothtml
21952 @ifhtml
21953 @item @b{Check Name} @tab @b{Description} @tab @b{Bounds Value}
21954 @end ifhtml
21955 @c Above conditional code is workaround to bug in texi2html (Feb 2008)
21956 @item @code{Essential_Complexity} @tab Essential complexity @tab Positive integer (U)
21957 @item @code{Cyclomatic_Complexity} @tab Cyclomatic complexity @tab Positive integer (U)
21958 @item @code{LSLOC} @tab Logical Source Lines of Code @tab Positive integer (U)
21959 @end multitable
21960
21961 @noindent
21962 The meaning and the computed values for all these metrics are exactly
21963 the same as for the corresponding metrics in @command{gnatmetric}.
21964
21965 @emph{Example:} the rule
21966 @smallexample
21967 +RMetrics_Cyclomatic_Complexity : 7
21968 @end smallexample
21969 @noindent
21970 means that all bodies with cyclomatic complexity exceeding 7 will be flagged.
21971
21972 To turn OFF the check for cyclomatic complexity metric, use the following option:
21973 @smallexample
21974 -RMetrics_Cyclomatic_Complexity
21975 @end smallexample
21976
21977
21978 @node Misnamed_Controlling_Parameters
21979 @subsection @code{Misnamed_Controlling_Parameters}
21980 @cindex @code{Misnamed_Controlling_Parameters} rule (for @command{gnatcheck})
21981
21982 @noindent
21983 Flags a declaration of a dispatching operation, if the first parameter is
21984 not a controlling one and its name is not @code{This} (the check for
21985 parameter name is not case-sensitive). Declarations of dispatching functions
21986 with controlling result and no controlling parameter are never flagged.
21987
21988 A subprogram body declaration, subprogram renaming declaration or subprogram
21989 body stub is flagged only if it is not a completion of a prior subprogram
21990 declaration.
21991
21992 This rule has no parameters.
21993
21994
21995
21996 @node Misnamed_Identifiers
21997 @subsection @code{Misnamed_Identifiers}
21998 @cindex @code{Misnamed_Identifiers} rule (for @command{gnatcheck})
21999
22000 @noindent
22001 Flag the declaration of each identifier that does not have a suffix
22002 corresponding to the kind of entity being declared.
22003 The following declarations are checked:
22004
22005 @itemize @bullet
22006 @item
22007 type declarations
22008
22009 @item
22010 subtype declarations
22011
22012 @item
22013 constant declarations (but not number declarations)
22014
22015 @item
22016 package renaming declarations (but not generic package renaming
22017 declarations)
22018 @end itemize
22019
22020 @noindent
22021 This rule may have parameters. When used without parameters, the rule enforces
22022 the following checks:
22023
22024 @itemize @bullet
22025 @item
22026 type-defining names end with @code{_T}, unless the type is an access type,
22027 in which case the suffix must be @code{_A}
22028 @item
22029 constant names end with @code{_C}
22030 @item
22031 names defining package renamings end with @code{_R}
22032 @end itemize
22033
22034 @noindent
22035 Defining identifiers from incomplete type declarations are never flagged.
22036
22037 For a private type declaration (including private extensions), the defining
22038 identifier from the private type declaration is checked against the type
22039 suffix (even if the corresponding full declaration is an access type
22040 declaration), and the defining identifier from the corresponding full type
22041 declaration is not checked.
22042
22043 @noindent
22044 For a deferred constant, the defining name in the corresponding full constant
22045 declaration is not checked.
22046
22047 Defining names of formal types are not checked.
22048
22049 The rule may have the following parameters:
22050
22051 @itemize @bullet
22052 @item
22053 For the @option{+R} option:
22054 @table @code
22055 @item Default
22056 Sets the default listed above for all the names to be checked.
22057
22058 @item Type_Suffix=@emph{string}
22059 Specifies the suffix for a type name.
22060
22061 @item Access_Suffix=@emph{string}
22062 Specifies the suffix for an access type name. If
22063 this parameter is set, it overrides for access
22064 types the suffix set by the @code{Type_Suffix} parameter.
22065 For access types, @emph{string} may have the following format:
22066 @emph{suffix1(suffix2)}. That means that an access type name
22067 should have the @emph{suffix1} suffix except for the case when
22068 the designated type is also an access type, in this case the
22069 type name should have the @emph{suffix1 & suffix2} suffix.
22070
22071 @item Class_Access_Suffix=@emph{string}
22072 Specifies the suffix for the name of an access type that points to some class-wide
22073 type. If this parameter is set, it overrides for such access
22074 types the suffix set by the @code{Type_Suffix} or @code{Access_Suffix}
22075 parameter.
22076
22077 @item Class_Subtype_Suffix=@emph{string}
22078 Specifies the suffix for the name of a subtype that denotes a class-wide type.
22079
22080 @item Constant_Suffix=@emph{string}
22081 Specifies the suffix for a constant name.
22082
22083 @item Renaming_Suffix=@emph{string}
22084 Specifies the suffix for a package renaming name.
22085 @end table
22086
22087 @item
22088 For the @option{-R} option:
22089 @table @code
22090 @item All_Suffixes
22091 Remove all the suffixes specified for the
22092 identifier suffix checks, whether by default or
22093 as specified by other rule parameters. All the
22094 checks for this rule are disabled as a result.
22095
22096 @item Type_Suffix
22097 Removes the suffix specified for types. This
22098 disables checks for types but does not disable
22099 any other checks for this rule (including the
22100 check for access type names if @code{Access_Suffix} is
22101 set).
22102
22103 @item Access_Suffix
22104 Removes the suffix specified for access types.
22105 This disables checks for access type names but
22106 does not disable any other checks for this rule.
22107 If @code{Type_Suffix} is set, access type names are
22108 checked as ordinary type names.
22109
22110 @item Class_Access_Suffix
22111 Removes the suffix specified for access types pointing to class-wide
22112 type. This disables specific checks for names of access types pointing to
22113 class-wide types but does not disable any other checks for this rule.
22114 If @code{Type_Suffix} is set, access type names are
22115 checked as ordinary type names. If @code{Access_Suffix} is set, these
22116 access types are checked as any other access type name.
22117
22118 @item Class_Subtype_Suffix=@emph{string}
22119 Removes the suffix specified for subtype names.
22120 This disables checks for subtype names but
22121 does not disable any other checks for this rule.
22122
22123 @item Constant_Suffix
22124 Removes the suffix specified for constants. This
22125 disables checks for constant names but does not
22126 disable any other checks for this rule.
22127
22128 @item Renaming_Suffix
22129 Removes the suffix specified for package
22130 renamings. This disables checks for package
22131 renamings but does not disable any other checks
22132 for this rule.
22133 @end table
22134 @end itemize
22135
22136 @noindent
22137 If more than one parameter is used, parameters must be separated by commas.
22138
22139 If more than one  option is specified for the @command{gnatcheck} invocation,
22140 a new option overrides the previous one(s).
22141
22142 The @option{+RMisnamed_Identifiers} option (with no parameter) enables
22143 checks for all the
22144 name suffixes specified by previous options used for this rule.
22145
22146 The @option{-RMisnamed_Identifiers} option (with no parameter) disables
22147 all the checks but keeps
22148 all the suffixes specified by previous options used for this rule.
22149
22150 The @emph{string} value must be a valid suffix for an Ada identifier (after
22151 trimming all the leading and trailing space characters, if any).
22152 Parameters are not case sensitive, except the @emph{string} part.
22153
22154 If any error is detected in a rule parameter, the parameter is ignored.
22155 In such a case the options that are set for the rule are not
22156 specified.
22157
22158
22159
22160 @node Multiple_Entries_In_Protected_Definitions
22161 @subsection @code{Multiple_Entries_In_Protected_Definitions}
22162 @cindex @code{Multiple_Entries_In_Protected_Definitions} rule (for @command{gnatcheck})
22163
22164 @noindent
22165 Flag each protected definition (i.e., each protected object/type declaration)
22166 that defines more than one entry.
22167 Diagnostic messages are generated for all the entry declarations
22168 except the first one. An entry family is counted as one entry. Entries from
22169 the private part of the protected definition are also checked.
22170
22171 This rule has no parameters.
22172
22173 @node Name_Clashes
22174 @subsection @code{Name_Clashes}
22175 @cindex @code{Name_Clashes} rule (for @command{gnatcheck})
22176
22177 @noindent
22178 Check that certain names are not used as defining identifiers. To activate
22179 this rule, you need to supply a reference to the dictionary file(s) as a rule
22180 parameter(s) (more then one dictionary file can be specified). If no
22181 dictionary file is set, this rule will not cause anything to be flagged.
22182 Only defining occurrences, not references, are checked.
22183 The check is not case-sensitive.
22184
22185 This rule is enabled by default, but without setting any corresponding
22186 dictionary file(s); thus the default effect is to do no checks.
22187
22188 A dictionary file is a plain text file. The maximum line length for this file
22189 is 1024 characters.  If the line is longer then this limit, extra characters
22190 are ignored.
22191
22192 Each line can be either an empty line, a comment line, or a line containing
22193 a list of identifiers separated by space or HT characters.
22194 A comment is an Ada-style comment (from @code{--} to end-of-line).
22195 Identifiers must follow the Ada syntax for identifiers.
22196 A line containing one or more identifiers may end with a comment.
22197
22198 @node Non_Qualified_Aggregates
22199 @subsection @code{Non_Qualified_Aggregates}
22200 @cindex @code{Non_Qualified_Aggregates} rule (for @command{gnatcheck})
22201
22202 @noindent
22203 Flag each non-qualified aggregate.
22204 A non-qualified aggregate is an
22205 aggregate that is not the expression of a qualified expression. A
22206 string literal is not considered an aggregate, but an array
22207 aggregate of a string type is considered as a normal aggregate.
22208 Aggregates of anonymous array types are not flagged.
22209
22210 This rule has no parameters.
22211
22212
22213 @node Non_Short_Circuit_Operators
22214 @subsection @code{Non_Short_Circuit_Operators}
22215 @cindex @code{Non_Short_Circuit_Operators} rule (for @command{gnatcheck})
22216
22217 @noindent
22218 Flag all calls to predefined @code{and} and @code{or} operators for
22219 any boolean type. Calls to
22220 user-defined @code{and} and @code{or} and to operators defined by renaming
22221 declarations are not flagged. Calls to predefined @code{and} and @code{or}
22222 operators for modular types or boolean array types are not flagged.
22223
22224 This rule has no parameters.
22225
22226
22227
22228 @node Non_SPARK_Attributes
22229 @subsection @code{Non_SPARK_Attributes}
22230 @cindex @code{Non_SPARK_Attributes} rule (for @command{gnatcheck})
22231
22232 @noindent
22233 The SPARK language defines the following subset of Ada 95 attribute
22234 designators as those that can be used in SPARK programs. The use of
22235 any other attribute is flagged.
22236
22237 @itemize @bullet
22238 @item @code{'Adjacent}
22239 @item @code{'Aft}
22240 @item @code{'Base}
22241 @item @code{'Ceiling}
22242 @item @code{'Component_Size}
22243 @item @code{'Compose}
22244 @item @code{'Copy_Sign}
22245 @item @code{'Delta}
22246 @item @code{'Denorm}
22247 @item @code{'Digits}
22248 @item @code{'Exponent}
22249 @item @code{'First}
22250 @item @code{'Floor}
22251 @item @code{'Fore}
22252 @item @code{'Fraction}
22253 @item @code{'Last}
22254 @item @code{'Leading_Part}
22255 @item @code{'Length}
22256 @item @code{'Machine}
22257 @item @code{'Machine_Emax}
22258 @item @code{'Machine_Emin}
22259 @item @code{'Machine_Mantissa}
22260 @item @code{'Machine_Overflows}
22261 @item @code{'Machine_Radix}
22262 @item @code{'Machine_Rounds}
22263 @item @code{'Max}
22264 @item @code{'Min}
22265 @item @code{'Model}
22266 @item @code{'Model_Emin}
22267 @item @code{'Model_Epsilon}
22268 @item @code{'Model_Mantissa}
22269 @item @code{'Model_Small}
22270 @item @code{'Modulus}
22271 @item @code{'Pos}
22272 @item @code{'Pred}
22273 @item @code{'Range}
22274 @item @code{'Remainder}
22275 @item @code{'Rounding}
22276 @item @code{'Safe_First}
22277 @item @code{'Safe_Last}
22278 @item @code{'Scaling}
22279 @item @code{'Signed_Zeros}
22280 @item @code{'Size}
22281 @item @code{'Small}
22282 @item @code{'Succ}
22283 @item @code{'Truncation}
22284 @item @code{'Unbiased_Rounding}
22285 @item @code{'Val}
22286 @item @code{'Valid}
22287 @end itemize
22288
22289 @noindent
22290 This rule has no parameters.
22291
22292
22293 @node Non_Tagged_Derived_Types
22294 @subsection @code{Non_Tagged_Derived_Types}
22295 @cindex @code{Non_Tagged_Derived_Types} rule (for @command{gnatcheck})
22296
22297 @noindent
22298 Flag all derived type declarations that do not have a record extension part.
22299
22300 This rule has no parameters.
22301
22302
22303
22304 @node Non_Visible_Exceptions
22305 @subsection @code{Non_Visible_Exceptions}
22306 @cindex @code{Non_Visible_Exceptions} rule (for @command{gnatcheck})
22307
22308 @noindent
22309 Flag constructs leading to the possibility of propagating an exception
22310 out of the scope in which the exception is declared.
22311 Two cases are detected:
22312
22313 @itemize @bullet
22314 @item
22315 An exception declaration in a subprogram body, task body or block
22316 statement is flagged if the body or statement does not contain a handler for
22317 that exception or a handler with an @code{others} choice.
22318
22319 @item
22320 A @code{raise} statement in an exception handler of a subprogram body,
22321 task body or block statement is flagged if it (re)raises a locally
22322 declared exception.  This may occur under the following circumstances:
22323 @itemize @minus
22324 @item
22325 it explicitly raises a locally declared exception, or
22326 @item
22327 it does not specify an exception name (i.e., it is simply @code{raise;})
22328 and the enclosing handler contains a locally declared exception in its
22329 exception choices.
22330 @end itemize
22331 @end itemize
22332
22333 @noindent
22334 Renamings of local exceptions are not flagged.
22335
22336 This rule has no parameters.
22337
22338
22339 @node Numeric_Literals
22340 @subsection @code{Numeric_Literals}
22341 @cindex @code{Numeric_Literals} rule (for @command{gnatcheck})
22342
22343 @noindent
22344 Flag each use of a numeric literal in an index expression, and in any
22345 circumstance except for the following:
22346
22347 @itemize @bullet
22348 @item
22349 a literal occurring in the initialization expression for a constant
22350 declaration or a named number declaration, or
22351
22352 @item
22353 an integer literal that is less than or equal to a value
22354 specified by the @option{N} rule parameter.
22355 @end itemize
22356
22357 @noindent
22358 This rule may have the following parameters for the @option{+R} option:
22359
22360 @table @asis
22361 @item @emph{N}
22362 @emph{N} is an integer literal used as the maximal value that is not flagged
22363 (i.e., integer literals not exceeding this value are allowed)
22364
22365 @item @code{ALL}
22366 All integer literals are flagged
22367 @end table
22368
22369 @noindent
22370 If no parameters are set, the maximum unflagged value is 1.
22371
22372 The last specified check limit (or the fact that there is no limit at
22373 all) is used when multiple @option{+R} options appear.
22374
22375 The @option{-R} option for this rule has no parameters.
22376 It disables the rule but retains the last specified maximum unflagged value.
22377 If the @option{+R} option subsequently appears, this value is used as the
22378 threshold for the check.
22379
22380
22381 @node OTHERS_In_Aggregates
22382 @subsection @code{OTHERS_In_Aggregates}
22383 @cindex @code{OTHERS_In_Aggregates} rule (for @command{gnatcheck})
22384
22385 @noindent
22386 Flag each use of an @code{others} choice in extension aggregates.
22387 In record and array aggregates, an @code{others} choice is flagged unless
22388 it is used to refer to all components, or to all but one component.
22389
22390 If, in case of a named array aggregate, there are two associations, one
22391 with an @code{others} choice and another with a discrete range, the
22392 @code{others} choice is flagged even if the discrete range specifies
22393 exactly one component; for example, @code{(1..1 => 0, others => 1)}.
22394
22395 This rule has no parameters.
22396
22397 @node OTHERS_In_CASE_Statements
22398 @subsection @code{OTHERS_In_CASE_Statements}
22399 @cindex @code{OTHERS_In_CASE_Statements} rule (for @command{gnatcheck})
22400
22401 @noindent
22402 Flag any use of an @code{others} choice in a @code{case} statement.
22403
22404 This rule has no parameters.
22405
22406 @node OTHERS_In_Exception_Handlers
22407 @subsection @code{OTHERS_In_Exception_Handlers}
22408 @cindex @code{OTHERS_In_Exception_Handlers} rule (for @command{gnatcheck})
22409
22410 @noindent
22411 Flag any use of an @code{others} choice in an exception handler.
22412
22413 This rule has no parameters.
22414
22415
22416 @node Outer_Loop_Exits
22417 @subsection @code{Outer_Loop_Exits}
22418 @cindex @code{Outer_Loop_Exits} rule (for @command{gnatcheck})
22419
22420 @noindent
22421 Flag each @code{exit} statement containing a loop name that is not the name
22422 of the immediately enclosing @code{loop} statement.
22423
22424 This rule has no parameters.
22425
22426
22427 @node Overloaded_Operators
22428 @subsection @code{Overloaded_Operators}
22429 @cindex @code{Overloaded_Operators} rule (for @command{gnatcheck})
22430
22431 @noindent
22432 Flag each function declaration that overloads an operator symbol.
22433 A function body is checked only if the body does not have a
22434 separate spec. Formal functions are also checked. For a
22435 renaming declaration, only renaming-as-declaration is checked
22436
22437 This rule has no parameters.
22438
22439
22440 @node Overly_Nested_Control_Structures
22441 @subsection @code{Overly_Nested_Control_Structures}
22442 @cindex @code{Overly_Nested_Control_Structures} rule (for @command{gnatcheck})
22443
22444 @noindent
22445 Flag each control structure whose nesting level exceeds the value provided
22446 in the rule parameter.
22447
22448 The control structures checked are the following:
22449
22450 @itemize @bullet
22451 @item    @code{if} statement
22452 @item    @code{case} statement
22453 @item    @code{loop} statement
22454 @item    Selective accept statement
22455 @item    Timed entry call statement
22456 @item    Conditional entry call
22457 @item    Asynchronous select statement
22458 @end itemize
22459
22460 @noindent
22461 The rule has the following parameter for the @option{+R} option:
22462
22463 @table @emph
22464 @item N
22465 Positive integer specifying the maximal control structure nesting
22466 level that is not flagged
22467 @end table
22468
22469 @noindent
22470 If the parameter for the @option{+R} option is not specified or
22471 if it is not a positive integer, @option{+R} option is ignored.
22472
22473 If more then one  option is specified for the gnatcheck call, the later option and
22474 new parameter override the previous one(s).
22475
22476
22477 @node Parameters_Out_Of_Order
22478 @subsection @code{Parameters_Out_Of_Order}
22479 @cindex @code{Parameters_Out_Of_Order} rule (for @command{gnatcheck})
22480
22481 @noindent
22482 Flag each subprogram and entry declaration whose formal parameters are not
22483 ordered according to the following scheme:
22484
22485 @itemize @bullet
22486
22487 @item @code{in} and @code{access} parameters first,
22488 then @code{in out} parameters,
22489 and then @code{out} parameters;
22490
22491 @item for @code{in} mode, parameters with default initialization expressions
22492 occur last
22493 @end itemize
22494
22495 @noindent
22496 Only the first violation of the described order is flagged.
22497
22498 The following constructs are checked:
22499
22500 @itemize @bullet
22501 @item   subprogram declarations (including null procedures);
22502 @item   generic subprogram declarations;
22503 @item   formal subprogram declarations;
22504 @item   entry declarations;
22505 @item   subprogram bodies and subprogram body stubs that do not
22506 have separate specifications
22507 @end itemize
22508
22509 @noindent
22510 Subprogram renamings are not checked.
22511
22512 This rule has no parameters.
22513
22514
22515 @node Positional_Actuals_For_Defaulted_Generic_Parameters
22516 @subsection @code{Positional_Actuals_For_Defaulted_Generic_Parameters}
22517 @cindex @code{Positional_Actuals_For_Defaulted_Generic_Parameters} rule (for @command{gnatcheck})
22518
22519 @noindent
22520 Flag each generic actual parameter corresponding to a generic formal
22521 parameter with a default initialization, if positional notation is used.
22522
22523 This rule has no parameters.
22524
22525 @node Positional_Actuals_For_Defaulted_Parameters
22526 @subsection @code{Positional_Actuals_For_Defaulted_Parameters}
22527 @cindex @code{Positional_Actuals_For_Defaulted_Parameters} rule (for @command{gnatcheck})
22528
22529 @noindent
22530 Flag each actual parameter to a subprogram or entry call where the
22531 corresponding formal parameter has a default expression, if positional
22532 notation is used.
22533
22534 This rule has no parameters.
22535
22536 @node Positional_Components
22537 @subsection @code{Positional_Components}
22538 @cindex @code{Positional_Components} rule (for @command{gnatcheck})
22539
22540 @noindent
22541 Flag each array, record and extension aggregate that includes positional
22542 notation.
22543
22544 This rule has no parameters.
22545
22546
22547 @node Positional_Generic_Parameters
22548 @subsection @code{Positional_Generic_Parameters}
22549 @cindex @code{Positional_Generic_Parameters} rule (for @command{gnatcheck})
22550
22551 @noindent
22552 Flag each positional actual generic parameter except for the case when
22553 the generic unit being iinstantiated has exactly one generic formal
22554 parameter.
22555
22556 This rule has no parameters.
22557
22558
22559 @node Positional_Parameters
22560 @subsection @code{Positional_Parameters}
22561 @cindex @code{Positional_Parameters} rule (for @command{gnatcheck})
22562
22563 @noindent
22564 Flag each positional parameter notation in a subprogram or entry call,
22565 except for the following:
22566
22567 @itemize @bullet
22568 @item
22569 Parameters of calls to of prefix or infix operators are not flagged
22570 @item
22571 If the called subprogram or entry has only one formal parameter,
22572 the parameter of the call is not flagged;
22573 @item
22574 If a subprogram call uses the @emph{Object.Operation} notation, then
22575 @itemize @minus
22576 @item
22577 the first parameter (that is, @emph{Object}) is not flagged;
22578 @item
22579 if the called subprogram has only two parameters, the second parameter
22580 of the call is not flagged;
22581 @end itemize
22582 @end itemize
22583
22584 @noindent
22585 This rule has no parameters.
22586
22587
22588
22589
22590 @node Predefined_Numeric_Types
22591 @subsection @code{Predefined_Numeric_Types}
22592 @cindex @code{Predefined_Numeric_Types} rule (for @command{gnatcheck})
22593
22594 @noindent
22595 Flag each explicit use of the name of any numeric type or subtype defined
22596 in package @code{Standard}.
22597
22598 The rationale for this rule is to detect when the
22599 program may depend on platform-specific characteristics of the implementation
22600 of the predefined numeric types. Note that this rule is over-pessimistic;
22601 for example, a program that uses @code{String} indexing
22602 likely needs a variable of type @code{Integer}.
22603 Another example is the flagging of predefined numeric types with explicit
22604 constraints:
22605
22606 @smallexample @c ada
22607     subtype My_Integer is Integer range Left .. Right;
22608     Vy_Var : My_Integer;
22609 @end smallexample
22610
22611 @noindent
22612 This rule detects only numeric types and subtypes defined in
22613 @code{Standard}. The use of numeric types and subtypes defined in other
22614 predefined packages (such as @code{System.Any_Priority} or
22615 @code{Ada.Text_IO.Count}) is not flagged
22616
22617 This rule has no parameters.
22618
22619
22620
22621 @node Raising_External_Exceptions
22622 @subsection @code{Raising_External_Exceptions}
22623 @cindex @code{Raising_External_Exceptions} rule (for @command{gnatcheck})
22624
22625 @noindent
22626 Flag any @code{raise} statement, in a program unit declared in a library
22627 package or in a generic library package, for an exception that is
22628 neither a predefined exception nor an exception that is also declared (or
22629 renamed) in the visible part of the package.
22630
22631 This rule has no parameters.
22632
22633
22634
22635 @node Raising_Predefined_Exceptions
22636 @subsection @code{Raising_Predefined_Exceptions}
22637 @cindex @code{Raising_Predefined_Exceptions} rule (for @command{gnatcheck})
22638
22639 @noindent
22640 Flag each @code{raise} statement that raises a predefined exception
22641 (i.e., one of the exceptions @code{Constraint_Error}, @code{Numeric_Error},
22642 @code{Program_Error}, @code{Storage_Error}, or @code{Tasking_Error}).
22643
22644 This rule has no parameters.
22645
22646 @node Separate_Numeric_Error_Handlers
22647 @subsection @code{Separate_Numeric_Error_Handlers}
22648 @cindex @code{Separate_Numeric_Error_Handlers} rule (for @command{gnatcheck})
22649
22650 @noindent
22651 Flags each exception handler that contains a choice for
22652 the predefined @code{Constraint_Error} exception, but does not contain
22653 the choice for the predefined @code{Numeric_Error} exception, or
22654 that contains the choice for @code{Numeric_Error}, but does not contain the
22655 choice for @code{Constraint_Error}.
22656
22657 This rule has no parameters.
22658
22659 @ignore
22660 @node Recursion
22661 @subsection @code{Recursion} (under construction, GLOBAL)
22662 @cindex @code{Recursion} rule (for @command{gnatcheck})
22663
22664 @noindent
22665 Flag recursive subprograms (cycles in the call graph). Declarations, and not
22666 calls, of recursive subprograms are detected.
22667
22668 This rule has no parameters.
22669 @end ignore
22670
22671 @ignore
22672 @node Side_Effect_Functions
22673 @subsection @code{Side_Effect_Functions} (under construction, GLOBAL)
22674 @cindex @code{Side_Effect_Functions} rule (for @command{gnatcheck})
22675
22676 @noindent
22677 Flag functions with side effects.
22678
22679 We define a side effect as changing any data object that is not local for the
22680 body of this function.
22681
22682 At the moment, we do NOT consider a side effect any input-output operations
22683 (changing a state or a content of any file).
22684
22685 We do not consider protected functions for this rule (???)
22686
22687 There are the following sources of side effect:
22688
22689 @enumerate
22690 @item Explicit (or direct) side-effect:
22691
22692 @itemize @bullet
22693 @item
22694 direct assignment to a non-local variable;
22695
22696 @item
22697 direct call to an entity that is known to change some data object that is
22698      not local for the body of this function (Note, that if F1 calls F2 and F2
22699      does have a side effect, this does not automatically mean that F1 also
22700      have a side effect, because it may be the case that F2 is declared in
22701      F1's body and it changes some data object that is global for F2, but
22702      local for F1);
22703 @end itemize
22704
22705 @item Indirect side-effect:
22706 @itemize @bullet
22707 @item
22708 Subprogram calls implicitly issued by:
22709 @itemize @bullet
22710 @item
22711 computing initialization expressions from type declarations as a part
22712          of object elaboration or allocator evaluation;
22713 @item
22714 computing implicit parameters of subprogram or entry calls or generic
22715          instantiations;
22716 @end itemize
22717
22718 @item
22719 activation of a task that change some non-local data object (directly or
22720      indirectly);
22721
22722 @item
22723 elaboration code of a package that is a result of a package instantiation;
22724
22725 @item
22726 controlled objects;
22727 @end itemize
22728
22729 @item Situations when we can suspect a side-effect, but the full static check
22730 is either impossible or too hard:
22731 @itemize @bullet
22732 @item
22733 assignment to access variables or to the objects pointed by access
22734      variables;
22735
22736 @item
22737 call to a subprogram pointed by access-to-subprogram value
22738
22739 @item
22740 dispatching calls;
22741 @end itemize
22742 @end enumerate
22743
22744 @noindent
22745 This rule has no parameters.
22746 @end ignore
22747
22748 @node Slices
22749 @subsection @code{Slices}
22750 @cindex @code{Slices} rule (for @command{gnatcheck})
22751
22752 @noindent
22753 Flag all uses of array slicing
22754
22755 This rule has no parameters.
22756
22757
22758 @node Too_Many_Parents
22759 @subsection @code{Too_Many_Parents}
22760 @cindex @code{Too_Many_Parents} rule (for @command{gnatcheck})
22761
22762 @noindent
22763 Flags any type declaration, single task declaration or single protected
22764 declaration that has more then  @option{N} parents,  @option{N} is a parameter
22765 of the rule.
22766 A parent here is either a (sub)type denoted by the subtype mark from the
22767 parent_subtype_indication (in case of a derived type declaration), or
22768 any of the progenitors from the interface list, if any.
22769
22770 This rule has the following (mandatory) parameters for the @option{+R} option:
22771
22772 @table @emph
22773 @item N
22774 Positive integer specifying the maximal allowed number of parents.
22775 @end table
22776
22777
22778 @node Unassigned_OUT_Parameters
22779 @subsection @code{Unassigned_OUT_Parameters}
22780 @cindex @code{Unassigned_OUT_Parameters} rule (for @command{gnatcheck})
22781
22782 @noindent
22783 Flags procedures' @code{out} parameters that are not assigned, and
22784 identifies the contexts in which the assignments are missing.
22785
22786 An @code{out} parameter is flagged in the statements in the procedure
22787 body's handled sequence of statements (before the procedure body's
22788 @code{exception} part, if any) if this sequence of statements contains
22789 no assignments to the parameter.
22790
22791 An @code{out} parameter is flagged in an exception handler in the exception
22792 part of the procedure body's handled sequence of statements if the handler
22793 contains no assignment to the parameter.
22794
22795 Bodies of generic procedures are also considered.
22796
22797 The following are treated as assignments to an @code{out} parameter:
22798
22799 @itemize @bullet
22800 @item
22801 an assignment statement, with the parameter or some component as the target;
22802
22803 @item
22804 passing the parameter (or one of its components) as an @code{out} or
22805 @code{in out} parameter.
22806 @end itemize
22807
22808 @noindent
22809 This rule does not have any parameters.
22810
22811
22812
22813 @node Uncommented_BEGIN_In_Package_Bodies
22814 @subsection @code{Uncommented_BEGIN_In_Package_Bodies}
22815 @cindex @code{Uncommented_BEGIN_In_Package_Bodies} rule (for @command{gnatcheck})
22816
22817 @noindent
22818 Flags each package body with declarations and a statement part that does not
22819 include a trailing comment on the line containing the @code{begin} keyword;
22820 this trailing comment needs to specify the package name and nothing else.
22821 The @code{begin} is not flagged if the package body does not
22822 contain any declarations.
22823
22824 If the @code{begin} keyword is placed on the
22825 same line as the last declaration or the first statement, it is flagged
22826 independently of whether the line contains a trailing comment. The
22827 diagnostic message is attached to the line containing the first statement.
22828
22829 This rule has no parameters.
22830
22831 @node Unconditional_Exits
22832 @subsection @code{Unconditional_Exits}
22833 @cindex @code{Unconditional_Exits} rule (for @command{gnatcheck})
22834
22835 @noindent
22836 Flag unconditional @code{exit} statements.
22837
22838 This rule has no parameters.
22839
22840 @node Unconstrained_Array_Returns
22841 @subsection @code{Unconstrained_Array_Returns}
22842 @cindex @code{Unconstrained_Array_Returns} rule (for @command{gnatcheck})
22843
22844 @noindent
22845 Flag each function returning an unconstrained array. Function declarations,
22846 function bodies (and body stubs) having no separate specifications,
22847 and generic function instantiations are checked.
22848 Function calls and function renamings are
22849 not checked.
22850
22851 Generic function declarations, and function declarations in generic
22852 packages are not checked, instead this rule checks the results of
22853 generic instantiations (that is, expanded specification and expanded
22854 body corresponding to an instantiation).
22855
22856 This rule has no parameters.
22857
22858 @node Universal_Ranges
22859 @subsection @code{Universal_Ranges}
22860 @cindex @code{Universal_Ranges} rule (for @command{gnatcheck})
22861
22862 @noindent
22863 Flag discrete ranges that are a part of an index constraint, constrained
22864 array definition, or @code{for}-loop parameter specification, and whose bounds
22865 are both of type @i{universal_integer}. Ranges that have at least one
22866 bound of a specific type (such as @code{1 .. N}, where @code{N} is a variable
22867 or an expression of non-universal type) are not flagged.
22868
22869 This rule has no parameters.
22870
22871
22872 @node Unnamed_Blocks_And_Loops
22873 @subsection @code{Unnamed_Blocks_And_Loops}
22874 @cindex @code{Unnamed_Blocks_And_Loops} rule (for @command{gnatcheck})
22875
22876 @noindent
22877 Flag each unnamed block statement and loop statement.
22878
22879 The rule has no parameters.
22880
22881
22882
22883 @ignore
22884 @node Unused_Subprograms
22885 @subsection @code{Unused_Subprograms} (under construction, GLOBAL)
22886 @cindex @code{Unused_Subprograms} rule (for @command{gnatcheck})
22887
22888 @noindent
22889 Flag all unused subprograms.
22890
22891 This rule has no parameters.
22892 @end ignore
22893
22894
22895
22896
22897 @node USE_PACKAGE_Clauses
22898 @subsection @code{USE_PACKAGE_Clauses}
22899 @cindex @code{USE_PACKAGE_Clauses} rule (for @command{gnatcheck})
22900
22901 @noindent
22902 Flag all @code{use} clauses for packages; @code{use type} clauses are
22903 not flagged.
22904
22905 This rule has no parameters.
22906
22907
22908 @node Visible_Components
22909 @subsection @code{Visible_Components}
22910 @cindex @code{Visible_Components} rule (for @command{gnatcheck})
22911
22912 @noindent
22913 Flags all the type declarations located in the visible part of a library
22914 package or a library generic package that can declare a visible component. A
22915 type is considered as declaring a visible component if it contains a record
22916 definition by its own or as a part of a record extension. Type declaration is
22917 flagged even if it contains a record definition that defines no components.
22918
22919 Declarations located in private parts of local (generic) packages are not
22920 flagged. Declarations in private packages are not flagged.
22921
22922 This rule has no parameters.
22923
22924
22925 @node Volatile_Objects_Without_Address_Clauses
22926 @subsection @code{Volatile_Objects_Without_Address_Clauses}
22927 @cindex @code{Volatile_Objects_Without_Address_Clauses} rule (for @command{gnatcheck})
22928
22929 @noindent
22930 Flag each volatile object that does not have an address clause.
22931
22932 The following check is made: if the pragma @code{Volatile} is applied to a
22933 data object or to its type, then an address clause must
22934 be supplied for this object.
22935
22936 This rule does not check the components of data objects,
22937 array components that are volatile as a result of the pragma
22938 @code{Volatile_Components}, or objects that are volatile because
22939 they are atomic as a result of pragmas @code{Atomic} or
22940 @code{Atomic_Components}.
22941
22942 Only variable declarations, and not constant declarations, are checked.
22943
22944 This rule has no parameters.
22945
22946 @node Example of gnatcheck Usage
22947 @section Example of @command{gnatcheck} Usage
22948
22949 @noindent
22950 Here is a simple example. Suppose that in the current directory we have a
22951 project file named @file{gnatcheck_example.gpr} with the following content:
22952
22953 @smallexample @c projectfile
22954 project Gnatcheck_Example is
22955
22956    for Source_Dirs use ("src");
22957    for Object_Dir use "obj";
22958    for Main use ("main.adb");
22959
22960    package Check is
22961       for Default_Switches ("ada") use ("-rules", "-from=coding_standard");
22962    end Check;
22963
22964 end Gnatcheck_Example;
22965 @end smallexample
22966
22967 @noindent
22968 And the file named @file{coding_standard} is also located in the current
22969 directory and has the following content:
22970
22971 @smallexample
22972 -----------------------------------------------------
22973 -- This is a sample gnatcheck coding standard file --
22974 -----------------------------------------------------
22975
22976 --  First, turning on rules, that are directly implemented in gnatcheck
22977 +RAbstract_Type_Declarations
22978 +RAnonymous_Arrays
22979 +RLocal_Packages
22980 +RFloat_Equality_Checks
22981 +REXIT_Statements_With_No_Loop_Name
22982
22983 --  Then, activating compiler checks of interest:
22984 +RStyle_Checks:e
22985 --  This style check checks if a unit name is present on END keyword that
22986 --  is the end of the unit declaration
22987 @end smallexample
22988
22989 @noindent
22990 And the subdirectory @file{src} contains the following Ada sources:
22991
22992 @file{pack.ads}:
22993
22994 @smallexample @c ada
22995 package Pack is
22996    type T is abstract tagged private;
22997    procedure P (X : T) is abstract;
22998
22999    package Inner is
23000       type My_Float is digits 8;
23001       function Is_Equal (L, R : My_Float) return Boolean;
23002    end Inner;
23003 private
23004    type T is abstract tagged null record;
23005 end;
23006 @end smallexample
23007
23008 @noindent
23009 @file{pack.adb}:
23010
23011 @smallexample @c ada
23012 package body Pack is
23013    package body Inner is
23014       function Is_Equal (L, R : My_Float) return Boolean is
23015       begin
23016          return L = R;
23017       end;
23018    end Inner;
23019 end Pack;
23020 @end smallexample
23021
23022 @noindent
23023 and @file{main.adb}
23024
23025 @smallexample @c ada
23026 with Pack; use Pack;
23027 procedure Main is
23028
23029    pragma Annotate
23030      (gnatcheck, Exempt_On, "Anonymous_Arrays", "this one is fine");
23031    Float_Array : array (1 .. 10) of Inner.My_Float;
23032    pragma Annotate (gnatcheck, Exempt_Off, "Anonymous_Arrays");
23033
23034    Another_Float_Array : array (1 .. 10) of Inner.My_Float;
23035
23036    use Inner;
23037
23038    B : Boolean := False;
23039
23040 begin
23041    for J in Float_Array'Range loop
23042       if Is_Equal (Float_Array (J), Another_Float_Array (J)) then
23043          B := True;
23044          exit;
23045       end if;
23046    end loop;
23047 end Main;
23048 @end smallexample
23049
23050 @noindent
23051 And suppose we call @command{gnatcheck} from the current directory using
23052 the @command{gnat} driver:
23053
23054 @smallexample
23055    gnat check -Pgnatcheck_example.gpr
23056 @end smallexample
23057
23058 @noindent
23059 As a result, @command{gnatcheck} is called to check all the files from the
23060 project @file{gnatcheck_example.gpr} using the coding standard defined by
23061 the file @file{coding_standard}. As the result, the @command{gnatcheck}
23062 report file named @file{gnatcheck.out} will be created in the current
23063 directory, and it will have the following content:
23064
23065 @smallexample
23066 RULE CHECKING REPORT
23067
23068 1. OVERVIEW
23069
23070 Date and time of execution: 2009.10.28 14:17
23071 Tool version: GNATCHECK (built with ASIS 2.0.R for GNAT Pro 6.3.0w (20091016))
23072 Command line:
23073
23074 gnatcheck -files=.../GNAT-TEMP-000004.TMP -cargs -gnatec=.../GNAT-TEMP-000003.TMP -rules -from=coding_standard
23075
23076 Coding standard (applied rules):
23077    Abstract_Type_Declarations
23078    Anonymous_Arrays
23079    EXIT_Statements_With_No_Loop_Name
23080    Float_Equality_Checks
23081    Local_Packages
23082
23083    Compiler style checks: -gnatye
23084
23085 Number of coding standard violations: 6
23086 Number of exempted coding standard violations: 1
23087
23088 2. DETECTED RULE VIOLATIONS
23089
23090 2.1. NON-EXEMPTED VIOLATIONS
23091
23092 Source files with non-exempted violations
23093    pack.ads
23094    pack.adb
23095    main.adb
23096
23097 List of violations grouped by files, and ordered by increasing source location:
23098
23099 pack.ads:2:4: declaration of abstract type
23100 pack.ads:5:4: declaration of local package
23101 pack.ads:10:30: declaration of abstract type
23102 pack.ads:11:1: (style) "end Pack" required
23103 pack.adb:5:19: use of equality operation for float values
23104 pack.adb:6:7: (style) "end Is_Equal" required
23105 main.adb:9:26: anonymous array type
23106 main.adb:19:10: exit statement with no loop name
23107
23108 2.2. EXEMPTED VIOLATIONS
23109
23110 Source files with exempted violations
23111    main.adb
23112
23113 List of violations grouped by files, and ordered by increasing source location:
23114
23115 main.adb:6:18: anonymous array type
23116    (this one is fine)
23117
23118 2.3. SOURCE FILES WITH NO VIOLATION
23119
23120    No files without violations
23121
23122 END OF REPORT
23123 @end smallexample
23124
23125
23126 @c *********************************
23127 @node Creating Sample Bodies Using gnatstub
23128 @chapter Creating Sample Bodies Using @command{gnatstub}
23129 @findex gnatstub
23130
23131 @noindent
23132 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
23133 for library unit declarations.
23134
23135 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
23136 driver (see @ref{The GNAT Driver and Project Files}).
23137
23138 To create a body stub, @command{gnatstub} has to compile the library
23139 unit declaration. Therefore, bodies can be created only for legal
23140 library units. Moreover, if a library unit depends semantically upon
23141 units located outside the current directory, you have to provide
23142 the source search path when calling @command{gnatstub}, see the description
23143 of @command{gnatstub} switches below.
23144
23145 By default, all the program unit body stubs generated by @code{gnatstub}
23146 raise the predefined @code{Program_Error} exception, which will catch
23147 accidental calls of generated stubs. This behavior can be changed with
23148 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
23149
23150 @menu
23151 * Running gnatstub::
23152 * Switches for gnatstub::
23153 @end menu
23154
23155 @node Running gnatstub
23156 @section Running @command{gnatstub}
23157
23158 @noindent
23159 @command{gnatstub} has the command-line interface of the form
23160
23161 @smallexample
23162 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
23163 @c Expanding @ovar macro inline (explanation in macro def comments)
23164 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
23165 @end smallexample
23166
23167 @noindent
23168 where
23169 @table @var
23170 @item filename
23171 is the name of the source file that contains a library unit declaration
23172 for which a body must be created. The file name may contain the path
23173 information.
23174 The file name does not have to follow the GNAT file name conventions. If the
23175 name
23176 does not follow GNAT file naming conventions, the name of the body file must
23177 be provided
23178 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
23179 If the file name follows the GNAT file naming
23180 conventions and the name of the body file is not provided,
23181 @command{gnatstub}
23182 creates the name
23183 of the body file from the argument file name by replacing the @file{.ads}
23184 suffix
23185 with the @file{.adb} suffix.
23186
23187 @item directory
23188 indicates the directory in which the body stub is to be placed (the default
23189 is the
23190 current directory)
23191
23192 @item @samp{@var{gcc_switches}} is a list of switches for
23193 @command{gcc}. They will be passed on to all compiler invocations made by
23194 @command{gnatelim} to generate the ASIS trees. Here you can provide
23195 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
23196 use the @option{-gnatec} switch to set the configuration file etc.
23197
23198 @item switches
23199 is an optional sequence of switches as described in the next section
23200 @end table
23201
23202 @node Switches for gnatstub
23203 @section Switches for @command{gnatstub}
23204
23205 @table @option
23206 @c !sort!
23207
23208 @item ^-f^/FULL^
23209 @cindex @option{^-f^/FULL^} (@command{gnatstub})
23210 If the destination directory already contains a file with the name of the
23211 body file
23212 for the argument spec file, replace it with the generated body stub.
23213
23214 @item ^-hs^/HEADER=SPEC^
23215 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
23216 Put the comment header (i.e., all the comments preceding the
23217 compilation unit) from the source of the library unit declaration
23218 into the body stub.
23219
23220 @item ^-hg^/HEADER=GENERAL^
23221 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
23222 Put a sample comment header into the body stub.
23223
23224 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
23225 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
23226 Use the content of the file as the comment header for a generated body stub.
23227
23228 @ifclear vms
23229 @item -IDIR
23230 @cindex @option{-IDIR} (@command{gnatstub})
23231 @itemx -I-
23232 @cindex @option{-I-} (@command{gnatstub})
23233 @end ifclear
23234 @ifset vms
23235 @item /NOCURRENT_DIRECTORY
23236 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
23237 @end ifset
23238 ^These switches have ^This switch has^ the same meaning as in calls to
23239 @command{gcc}.
23240 ^They define ^It defines ^ the source search path in the call to
23241 @command{gcc} issued
23242 by @command{gnatstub} to compile an argument source file.
23243
23244 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
23245 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
23246 This switch has the same meaning as in calls to @command{gcc}.
23247 It defines the additional configuration file to be passed to the call to
23248 @command{gcc} issued
23249 by @command{gnatstub} to compile an argument source file.
23250
23251 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
23252 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
23253 (@var{n} is a non-negative integer). Set the maximum line length in the
23254 body stub to @var{n}; the default is 79. The maximum value that can be
23255 specified is 32767. Note that in the special case of configuration
23256 pragma files, the maximum is always 32767 regardless of whether or
23257 not this switch appears.
23258
23259 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
23260 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
23261 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
23262 the generated body sample to @var{n}.
23263 The default indentation is 3.
23264
23265 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
23266 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
23267 Order local bodies alphabetically. (By default local bodies are ordered
23268 in the same way as the corresponding local specs in the argument spec file.)
23269
23270 @item ^-i^/INDENTATION=^@var{n}
23271 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
23272 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
23273
23274 @item ^-k^/TREE_FILE=SAVE^
23275 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
23276 Do not remove the tree file (i.e., the snapshot of the compiler internal
23277 structures used by @command{gnatstub}) after creating the body stub.
23278
23279 @item ^-l^/LINE_LENGTH=^@var{n}
23280 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
23281 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
23282
23283 @item ^--no-exception^/NO_EXCEPTION^
23284 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
23285 Avoind raising PROGRAM_ERROR in the generated bodies of program unit stubs.
23286 This is not always possible for function stubs.
23287
23288 @item ^--no-local-header^/NO_LOCAL_HEADER^
23289 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
23290 Do not place local comment header with unit name before body stub for a
23291 unit.
23292
23293 @item ^-o ^/BODY=^@var{body-name}
23294 @cindex @option{^-o^/BODY^} (@command{gnatstub})
23295 Body file name.  This should be set if the argument file name does not
23296 follow
23297 the GNAT file naming
23298 conventions. If this switch is omitted the default name for the body will be
23299 obtained
23300 from the argument file name according to the GNAT file naming conventions.
23301
23302 @item ^-q^/QUIET^
23303 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
23304 Quiet mode: do not generate a confirmation when a body is
23305 successfully created, and do not generate a message when a body is not
23306 required for an
23307 argument unit.
23308
23309 @item ^-r^/TREE_FILE=REUSE^
23310 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
23311 Reuse the tree file (if it exists) instead of creating it.  Instead of
23312 creating the tree file for the library unit declaration, @command{gnatstub}
23313 tries to find it in the current directory and use it for creating
23314 a body. If the tree file is not found, no body is created. This option
23315 also implies @option{^-k^/SAVE^}, whether or not
23316 the latter is set explicitly.
23317
23318 @item ^-t^/TREE_FILE=OVERWRITE^
23319 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
23320 Overwrite the existing tree file.  If the current directory already
23321 contains the file which, according to the GNAT file naming rules should
23322 be considered as a tree file for the argument source file,
23323 @command{gnatstub}
23324 will refuse to create the tree file needed to create a sample body
23325 unless this option is set.
23326
23327 @item ^-v^/VERBOSE^
23328 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
23329 Verbose mode: generate version information.
23330
23331 @end table
23332
23333 @c *********************************
23334 @node Generating Ada Bindings for C and C++ headers
23335 @chapter Generating Ada Bindings for C and C++ headers
23336 @findex binding
23337
23338 @noindent
23339 GNAT now comes with a binding generator for C and C++ headers which is
23340 intended to do 95% of the tedious work of generating Ada specs from C
23341 or C++ header files.
23342
23343 Note that this capability is not intended to generate 100% correct Ada specs,
23344 and will is some cases require manual adjustments, although it can often
23345 be used out of the box in practice.
23346
23347 Some of the known limitations include:
23348
23349 @itemize @bullet
23350 @item only very simple character constant macros are translated into Ada
23351 constants. Function macros (macros with arguments) are partially translated
23352 as comments, to be completed manually if needed.
23353 @item some extensions (e.g. vector types) are not supported
23354 @item pointers to pointers or complex structures are mapped to System.Address
23355 @end itemize
23356
23357 The code generated is using the Ada 2005 syntax, which makes it
23358 easier to interface with other languages than previous versions of Ada.
23359
23360 @menu
23361 * Running the binding generator::
23362 * Generating bindings for C++ headers::
23363 * Switches::
23364 @end menu
23365
23366 @node Running the binding generator
23367 @section Running the binding generator
23368
23369 @noindent
23370 The binding generator is part of the @command{gcc} compiler and can be
23371 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
23372 spec files for the header files specified on the command line, and all
23373 header files needed by these files transitivitely. For example:
23374
23375 @smallexample
23376 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
23377 $ gcc -c -gnat05 *.ads
23378 @end smallexample
23379
23380 will generate, under GNU/Linux, the following files: @file{time_h.ads},
23381 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
23382 correspond to the files @file{/usr/include/time.h},
23383 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
23384 mode these Ada specs.
23385
23386 The @code{-C} switch tells @command{gcc} to extract comments from headers,
23387 and will attempt to generate corresponding Ada comments.
23388
23389 If you want to generate a single Ada file and not the transitive closure, you
23390 can use instead the @option{-fdump-ada-spec-slim} switch.
23391
23392 Note that we recommend when possible to use the @command{g++} driver to
23393 generate bindings, even for most C headers, since this will in general
23394 generate better Ada specs. For generating bindings for C++ headers, it is
23395 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
23396 is equivalent in this case. If @command{g++} cannot work on your C headers
23397 because of incompatibilities between C and C++, then you can fallback to
23398 @command{gcc} instead.
23399
23400 For an example of better bindings generated from the C++ front-end,
23401 the name of the parameters (when available) are actually ignored by the C
23402 front-end. Consider the following C header:
23403
23404 @smallexample
23405 extern void foo (int variable);
23406 @end smallexample
23407
23408 with the C front-end, @code{variable} is ignored, and the above is handled as:
23409
23410 @smallexample
23411 extern void foo (int);
23412 @end smallexample
23413
23414 generating a generic:
23415
23416 @smallexample
23417 procedure foo (param1 : int);
23418 @end smallexample
23419
23420 with the C++ front-end, the name is available, and we generate:
23421
23422 @smallexample
23423 procedure foo (variable : int);
23424 @end smallexample
23425
23426 In some cases, the generated bindings will be more complete or more meaningful
23427 when defining some macros, which you can do via the @option{-D} switch. This
23428 is for example the case with @file{Xlib.h} under GNU/Linux:
23429
23430 @smallexample
23431 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
23432 @end smallexample
23433
23434 The above will generate more complete bindings than a straight call without
23435 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
23436
23437 In other cases, it is not possible to parse a header file in a stand alone
23438 manner, because other include files need to be included first. In this
23439 case, the solution is to create a small header file including the needed
23440 @code{#include} and possible @code{#define} directives. For example, to
23441 generate Ada bindings for @file{readline/readline.h}, you need to first
23442 include @file{stdio.h}, so you can create a file with the following two
23443 lines in e.g. @file{readline1.h}:
23444
23445 @smallexample
23446 #include <stdio.h>
23447 #include <readline/readline.h>
23448 @end smallexample
23449
23450 and then generate Ada bindings from this file:
23451
23452 @smallexample
23453 $ g++ -c -fdump-ada-spec readline1.h
23454 @end smallexample
23455
23456 @node Generating bindings for C++ headers
23457 @section Generating bindings for C++ headers
23458
23459 @noindent
23460 Generating bindings for C++ headers is done using the same options, always
23461 with the @command{g++} compiler.
23462
23463 In this mode, C++ classes will be mapped to Ada tagged types, constructors
23464 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
23465 multiple inheritance of abstract classes will be mapped to Ada interfaces
23466 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
23467 information on interfacing to C++).
23468
23469 For example, given the following C++ header file:
23470
23471 @smallexample
23472 @group
23473 @cartouche
23474 class Carnivore @{
23475 public:
23476    virtual int Number_Of_Teeth () = 0;
23477 @};
23478
23479 class Domestic @{
23480 public:
23481    virtual void Set_Owner (char* Name) = 0;
23482 @};
23483
23484 class Animal @{
23485 public:
23486   int Age_Count;
23487   virtual void Set_Age (int New_Age);
23488 @};
23489
23490 class Dog : Animal, Carnivore, Domestic @{
23491  public:
23492   int  Tooth_Count;
23493   char *Owner;
23494
23495   virtual int  Number_Of_Teeth ();
23496   virtual void Set_Owner (char* Name);
23497
23498   Dog();
23499 @};
23500 @end cartouche
23501 @end group
23502 @end smallexample
23503
23504 The corresponding Ada code is generated:
23505
23506 @smallexample @c ada
23507 @group
23508 @cartouche
23509   package Class_Carnivore is
23510     type Carnivore is limited interface;
23511     pragma Import (CPP, Carnivore);
23512
23513     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
23514   end;
23515   use Class_Carnivore;
23516
23517   package Class_Domestic is
23518     type Domestic is limited interface;
23519     pragma Import (CPP, Domestic);
23520
23521     procedure Set_Owner
23522       (this : access Domestic;
23523        Name : Interfaces.C.Strings.chars_ptr) is abstract;
23524   end;
23525   use Class_Domestic;
23526
23527   package Class_Animal is
23528     type Animal is tagged limited record
23529       Age_Count : aliased int;
23530     end record;
23531     pragma Import (CPP, Animal);
23532
23533     procedure Set_Age (this : access Animal; New_Age : int);
23534     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
23535   end;
23536   use Class_Animal;
23537
23538   package Class_Dog is
23539     type Dog is new Animal and Carnivore and Domestic with record
23540       Tooth_Count : aliased int;
23541       Owner : Interfaces.C.Strings.chars_ptr;
23542     end record;
23543     pragma Import (CPP, Dog);
23544
23545     function Number_Of_Teeth (this : access Dog) return int;
23546     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
23547
23548     procedure Set_Owner
23549       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
23550     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
23551
23552     function New_Dog return Dog;
23553     pragma CPP_Constructor (New_Dog);
23554     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
23555   end;
23556   use Class_Dog;
23557 @end cartouche
23558 @end group
23559 @end smallexample
23560
23561 @node Switches
23562 @section Switches
23563
23564 @table @option
23565 @item -fdump-ada-spec
23566 @cindex @option{-fdump-ada-spec} (@command{gcc})
23567 Generate Ada spec files for the given header files transitively (including
23568 all header files that these headers depend upon).
23569
23570 @item -fdump-ada-spec-slim
23571 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
23572 Generate Ada spec files for the header files specified on the command line
23573 only.
23574
23575 @item -C
23576 @cindex @option{-C} (@command{gcc})
23577 Extract comments from headers and generate Ada comments in the Ada spec files.
23578 @end table
23579
23580 @node Other Utility Programs
23581 @chapter Other Utility Programs
23582
23583 @noindent
23584 This chapter discusses some other utility programs available in the Ada
23585 environment.
23586
23587 @menu
23588 * Using Other Utility Programs with GNAT::
23589 * The External Symbol Naming Scheme of GNAT::
23590 * Converting Ada Files to html with gnathtml::
23591 * Installing gnathtml::
23592 @ifset vms
23593 * LSE::
23594 * Profiling::
23595 @end ifset
23596 @end menu
23597
23598 @node Using Other Utility Programs with GNAT
23599 @section Using Other Utility Programs with GNAT
23600
23601 @noindent
23602 The object files generated by GNAT are in standard system format and in
23603 particular the debugging information uses this format. This means
23604 programs generated by GNAT can be used with existing utilities that
23605 depend on these formats.
23606
23607 @ifclear vms
23608 In general, any utility program that works with C will also often work with
23609 Ada programs generated by GNAT. This includes software utilities such as
23610 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
23611 as Purify.
23612 @end ifclear
23613
23614 @node The External Symbol Naming Scheme of GNAT
23615 @section The External Symbol Naming Scheme of GNAT
23616
23617 @noindent
23618 In order to interpret the output from GNAT, when using tools that are
23619 originally intended for use with other languages, it is useful to
23620 understand the conventions used to generate link names from the Ada
23621 entity names.
23622
23623 All link names are in all lowercase letters. With the exception of library
23624 procedure names, the mechanism used is simply to use the full expanded
23625 Ada name with dots replaced by double underscores. For example, suppose
23626 we have the following package spec:
23627
23628 @smallexample @c ada
23629 @group
23630 @cartouche
23631 package QRS is
23632    MN : Integer;
23633 end QRS;
23634 @end cartouche
23635 @end group
23636 @end smallexample
23637
23638 @noindent
23639 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
23640 the corresponding link name is @code{qrs__mn}.
23641 @findex Export
23642 Of course if a @code{pragma Export} is used this may be overridden:
23643
23644 @smallexample @c ada
23645 @group
23646 @cartouche
23647 package Exports is
23648    Var1 : Integer;
23649    pragma Export (Var1, C, External_Name => "var1_name");
23650    Var2 : Integer;
23651    pragma Export (Var2, C, Link_Name => "var2_link_name");
23652 end Exports;
23653 @end cartouche
23654 @end group
23655 @end smallexample
23656
23657 @noindent
23658 In this case, the link name for @var{Var1} is whatever link name the
23659 C compiler would assign for the C function @var{var1_name}. This typically
23660 would be either @var{var1_name} or @var{_var1_name}, depending on operating
23661 system conventions, but other possibilities exist. The link name for
23662 @var{Var2} is @var{var2_link_name}, and this is not operating system
23663 dependent.
23664
23665 @findex _main
23666 One exception occurs for library level procedures. A potential ambiguity
23667 arises between the required name @code{_main} for the C main program,
23668 and the name we would otherwise assign to an Ada library level procedure
23669 called @code{Main} (which might well not be the main program).
23670
23671 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
23672 names. So if we have a library level procedure such as
23673
23674 @smallexample @c ada
23675 @group
23676 @cartouche
23677 procedure Hello (S : String);
23678 @end cartouche
23679 @end group
23680 @end smallexample
23681
23682 @noindent
23683 the external name of this procedure will be @var{_ada_hello}.
23684
23685
23686 @node Converting Ada Files to html with gnathtml
23687 @section Converting Ada Files to HTML with @code{gnathtml}
23688
23689 @noindent
23690 This @code{Perl} script allows Ada source files to be browsed using
23691 standard Web browsers. For installation procedure, see the section
23692 @xref{Installing gnathtml}.
23693
23694 Ada reserved keywords are highlighted in a bold font and Ada comments in
23695 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
23696 switch to suppress the generation of cross-referencing information, user
23697 defined variables and types will appear in a different color; you will
23698 be able to click on any identifier and go to its declaration.
23699
23700 The command line is as follow:
23701 @smallexample
23702 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
23703 @c Expanding @ovar macro inline (explanation in macro def comments)
23704 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
23705 @end smallexample
23706
23707 @noindent
23708 You can pass it as many Ada files as you want. @code{gnathtml} will generate
23709 an html file for every ada file, and a global file called @file{index.htm}.
23710 This file is an index of every identifier defined in the files.
23711
23712 The available ^switches^options^ are the following ones:
23713
23714 @table @option
23715 @item -83
23716 @cindex @option{-83} (@code{gnathtml})
23717 Only the Ada 83 subset of keywords will be highlighted.
23718
23719 @item -cc @var{color}
23720 @cindex @option{-cc} (@code{gnathtml})
23721 This option allows you to change the color used for comments. The default
23722 value is green. The color argument can be any name accepted by html.
23723
23724 @item -d
23725 @cindex @option{-d} (@code{gnathtml})
23726 If the Ada files depend on some other files (for instance through
23727 @code{with} clauses, the latter files will also be converted to html.
23728 Only the files in the user project will be converted to html, not the files
23729 in the run-time library itself.
23730
23731 @item -D
23732 @cindex @option{-D} (@code{gnathtml})
23733 This command is the same as @option{-d} above, but @command{gnathtml} will
23734 also look for files in the run-time library, and generate html files for them.
23735
23736 @item -ext @var{extension}
23737 @cindex @option{-ext} (@code{gnathtml})
23738 This option allows you to change the extension of the generated HTML files.
23739 If you do not specify an extension, it will default to @file{htm}.
23740
23741 @item -f
23742 @cindex @option{-f} (@code{gnathtml})
23743 By default, gnathtml will generate html links only for global entities
23744 ('with'ed units, global variables and types,@dots{}).  If you specify
23745 @option{-f} on the command line, then links will be generated for local
23746 entities too.
23747
23748 @item -l @var{number}
23749 @cindex @option{-l} (@code{gnathtml})
23750 If this ^switch^option^ is provided and @var{number} is not 0, then
23751 @code{gnathtml} will number the html files every @var{number} line.
23752
23753 @item -I @var{dir}
23754 @cindex @option{-I} (@code{gnathtml})
23755 Specify a directory to search for library files (@file{.ALI} files) and
23756 source files. You can provide several -I switches on the command line,
23757 and the directories will be parsed in the order of the command line.
23758
23759 @item -o @var{dir}
23760 @cindex @option{-o} (@code{gnathtml})
23761 Specify the output directory for html files. By default, gnathtml will
23762 saved the generated html files in a subdirectory named @file{html/}.
23763
23764 @item -p @var{file}
23765 @cindex @option{-p} (@code{gnathtml})
23766 If you are using Emacs and the most recent Emacs Ada mode, which provides
23767 a full Integrated Development Environment for compiling, checking,
23768 running and debugging applications, you may use @file{.gpr} files
23769 to give the directories where Emacs can find sources and object files.
23770
23771 Using this ^switch^option^, you can tell gnathtml to use these files.
23772 This allows you to get an html version of your application, even if it
23773 is spread over multiple directories.
23774
23775 @item -sc @var{color}
23776 @cindex @option{-sc} (@code{gnathtml})
23777 This ^switch^option^ allows you to change the color used for symbol
23778 definitions.
23779 The default value is red. The color argument can be any name accepted by html.
23780
23781 @item -t @var{file}
23782 @cindex @option{-t} (@code{gnathtml})
23783 This ^switch^option^ provides the name of a file. This file contains a list of
23784 file names to be converted, and the effect is exactly as though they had
23785 appeared explicitly on the command line. This
23786 is the recommended way to work around the command line length limit on some
23787 systems.
23788
23789 @end table
23790
23791 @node Installing gnathtml
23792 @section Installing @code{gnathtml}
23793
23794 @noindent
23795 @code{Perl} needs to be installed on your machine to run this script.
23796 @code{Perl} is freely available for almost every architecture and
23797 Operating System via the Internet.
23798
23799 On Unix systems, you  may want to modify  the  first line of  the script
23800 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
23801 is. The syntax of this line is:
23802 @smallexample
23803 #!full_path_name_to_perl
23804 @end smallexample
23805
23806 @noindent
23807 Alternatively, you may run the script using the following command line:
23808
23809 @smallexample
23810 @c $ perl gnathtml.pl @ovar{switches} @var{files}
23811 @c Expanding @ovar macro inline (explanation in macro def comments)
23812 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
23813 @end smallexample
23814
23815 @ifset vms
23816 @node LSE
23817 @section LSE
23818 @findex LSE
23819
23820 @noindent
23821 The GNAT distribution provides an Ada 95 template for the HP Language
23822 Sensitive Editor (LSE), a component of DECset. In order to
23823 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
23824
23825 @node Profiling
23826 @section Profiling
23827 @findex PCA
23828
23829 @noindent
23830 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
23831 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
23832 the collection phase with the /DEBUG qualifier.
23833
23834 @smallexample
23835 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
23836 $ DEFINE LIB$DEBUG PCA$COLLECTOR
23837 $ RUN/DEBUG <PROGRAM_NAME>
23838 @end smallexample
23839 @noindent
23840 @end ifset
23841
23842 @ifclear vms
23843 @c ******************************
23844 @node Code Coverage and Profiling
23845 @chapter Code Coverage and Profiling
23846 @cindex Code Coverage
23847 @cindex Profiling
23848
23849 @noindent
23850 This chapter describes how to use @code{gcov} - coverage testing tool - and
23851 @code{gprof} - profiler tool - on your Ada programs.
23852
23853 @menu
23854 * Code Coverage of Ada Programs using gcov::
23855 * Profiling an Ada Program using gprof::
23856 @end menu
23857
23858 @node Code Coverage of Ada Programs using gcov
23859 @section Code Coverage of Ada Programs using gcov
23860 @cindex gcov
23861 @cindex -fprofile-arcs
23862 @cindex -ftest-coverage
23863 @cindex -coverage
23864 @cindex Code Coverage
23865
23866 @noindent
23867 @code{gcov} is a test coverage program: it analyzes the execution of a given
23868 program on selected tests, to help you determine the portions of the program
23869 that are still untested.
23870
23871 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
23872 User's Guide. You can refer to this documentation for a more complete
23873 description.
23874
23875 This chapter provides a quick startup guide, and
23876 details some Gnat-specific features.
23877
23878 @menu
23879 * Quick startup guide::
23880 * Gnat specifics::
23881 @end menu
23882
23883 @node Quick startup guide
23884 @subsection Quick startup guide
23885
23886 In order to perform coverage analysis of a program using @code{gcov}, 3
23887 steps are needed:
23888
23889 @itemize @bullet
23890 @item
23891 Code instrumentation during the compilation process
23892 @item
23893 Execution of the instrumented program
23894 @item
23895 Execution of the @code{gcov} tool to generate the result.
23896 @end itemize
23897
23898 The code instrumentation needed by gcov is created at the object level:
23899 The source code is not modified in any way, because the instrumentation code is
23900 inserted by gcc during the compilation process. To compile your code with code
23901 coverage activated, you need to recompile your whole project using the
23902 switches
23903 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
23904 @code{-fprofile-arcs}.
23905
23906 @smallexample
23907 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
23908    -largs -fprofile-arcs
23909 @end smallexample
23910
23911 This compilation process will create @file{.gcno} files together with
23912 the usual object files.
23913
23914 Once the program is compiled with coverage instrumentation, you can
23915 run it as many times as needed - on portions of a test suite for
23916 example. The first execution will produce @file{.gcda} files at the
23917 same location as the @file{.gcno} files.  The following executions
23918 will update those files, so that a cumulative result of the covered
23919 portions of the program is generated.
23920
23921 Finally, you need to call the @code{gcov} tool. The different options of
23922 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
23923
23924 This will create annotated source files with a @file{.gcov} extension:
23925 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
23926
23927 @node Gnat specifics
23928 @subsection Gnat specifics
23929
23930 Because Ada semantics, portions of the source code may be shared among
23931 several object files. This is the case for example when generics are
23932 involved, when inlining is active  or when declarations generate  initialisation
23933 calls. In order to take
23934 into account this shared code, you need to call @code{gcov} on all
23935 source files of the tested program at once.
23936
23937 The list of source files might exceed the system's maximum command line
23938 length. In order to bypass this limitation, a new mechanism has been
23939 implemented in @code{gcov}: you can now list all your project's files into a
23940 text file, and provide this file to gcov as a parameter,  preceded by a @@
23941 (e.g. @samp{gcov @@mysrclist.txt}).
23942
23943 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
23944 not supported as there can be unresolved symbols during the final link.
23945
23946 @node Profiling an Ada Program using gprof
23947 @section Profiling an Ada Program using gprof
23948 @cindex gprof
23949 @cindex -pg
23950 @cindex Profiling
23951
23952 @noindent
23953 This section is not meant to be an exhaustive documentation of @code{gprof}.
23954 Full documentation for it can be found in the GNU Profiler User's Guide
23955 documentation that is part of this GNAT distribution.
23956
23957 Profiling a program helps determine the parts of a program that are executed
23958 most often, and are therefore the most time-consuming.
23959
23960 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
23961 better handle Ada programs and multitasking.
23962 It is currently supported on the following platforms
23963 @itemize @bullet
23964 @item
23965 linux x86/x86_64
23966 @item
23967 solaris sparc/sparc64/x86
23968 @item
23969 windows x86
23970 @end itemize
23971
23972 @noindent
23973 In order to profile a program using @code{gprof}, 3 steps are needed:
23974
23975 @itemize @bullet
23976 @item
23977 Code instrumentation, requiring a full recompilation of the project with the
23978 proper switches.
23979 @item
23980 Execution of the program under the analysis conditions, i.e. with the desired
23981 input.
23982 @item
23983 Analysis of the results using the @code{gprof} tool.
23984 @end itemize
23985
23986 @noindent
23987 The following sections detail the different steps, and indicate how
23988 to interpret the results:
23989 @menu
23990 * Compilation for profiling::
23991 * Program execution::
23992 * Running gprof::
23993 * Interpretation of profiling results::
23994 @end menu
23995
23996 @node Compilation for profiling
23997 @subsection Compilation for profiling
23998 @cindex -pg
23999 @cindex Profiling
24000
24001 In order to profile a program the first step is to tell the compiler
24002 to generate the necessary profiling information. The compiler switch to be used
24003 is @code{-pg}, which must be added to other compilation switches. This
24004 switch needs to be specified both during compilation and link stages, and can
24005 be specified once when using gnatmake:
24006
24007 @smallexample
24008 gnatmake -f -pg -P my_project
24009 @end smallexample
24010
24011 @noindent
24012 Note that only the objects that were compiled with the @samp{-pg} switch will be
24013 profiled; if you need to profile your whole project, use the
24014 @samp{-f} gnatmake switch to force full recompilation.
24015
24016 @node Program execution
24017 @subsection Program execution
24018
24019 @noindent
24020 Once the program has been compiled for profiling, you can run it as usual.
24021
24022 The only constraint imposed by profiling is that the program must terminate
24023 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
24024 properly analyzed.
24025
24026 Once the program completes execution, a data file called @file{gmon.out} is
24027 generated in the directory where the program was launched from. If this file
24028 already exists, it will be overwritten.
24029
24030 @node Running gprof
24031 @subsection Running gprof
24032
24033 @noindent
24034 The @code{gprof} tool is called as follow:
24035
24036 @smallexample
24037 gprof my_prog gmon.out
24038 @end smallexample
24039
24040 @noindent
24041 or simpler:
24042
24043 @smallexample
24044 gprof my_prog
24045 @end smallexample
24046
24047 @noindent
24048 The complete form of the gprof command line is the following:
24049
24050 @smallexample
24051 gprof [^switches^options^] [executable [data-file]]
24052 @end smallexample
24053
24054 @noindent
24055 @code{gprof} supports numerous ^switch^options^. The order of these
24056 ^switch^options^ does not matter. The full list of options can be found in
24057 the GNU Profiler User's Guide documentation that comes with this documentation.
24058
24059 The following is the subset of those switches that is most relevant:
24060
24061 @table @option
24062
24063 @item --demangle[=@var{style}]
24064 @itemx --no-demangle
24065 @cindex @option{--demangle} (@code{gprof})
24066 These options control whether symbol names should be demangled when
24067 printing output.  The default is to demangle C++ symbols.  The
24068 @code{--no-demangle} option may be used to turn off demangling. Different
24069 compilers have different mangling styles.  The optional demangling style
24070 argument can be used to choose an appropriate demangling style for your
24071 compiler, in particular Ada symbols generated by GNAT can be demangled using
24072 @code{--demangle=gnat}.
24073
24074 @item -e @var{function_name}
24075 @cindex @option{-e} (@code{gprof})
24076 The @samp{-e @var{function}} option tells @code{gprof} not to print
24077 information about the function @var{function_name} (and its
24078 children@dots{}) in the call graph.  The function will still be listed
24079 as a child of any functions that call it, but its index number will be
24080 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
24081 given; only one @var{function_name} may be indicated with each @samp{-e}
24082 option.
24083
24084 @item -E @var{function_name}
24085 @cindex @option{-E} (@code{gprof})
24086 The @code{-E @var{function}} option works like the @code{-e} option, but
24087 execution time spent in the function (and children who were not called from
24088 anywhere else), will not be used to compute the percentages-of-time for
24089 the call graph.  More than one @samp{-E} option may be given; only one
24090 @var{function_name} may be indicated with each @samp{-E} option.
24091
24092 @item -f @var{function_name}
24093 @cindex @option{-f} (@code{gprof})
24094 The @samp{-f @var{function}} option causes @code{gprof} to limit the
24095 call graph to the function @var{function_name} and its children (and
24096 their children@dots{}).  More than one @samp{-f} option may be given;
24097 only one @var{function_name} may be indicated with each @samp{-f}
24098 option.
24099
24100 @item -F @var{function_name}
24101 @cindex @option{-F} (@code{gprof})
24102 The @samp{-F @var{function}} option works like the @code{-f} option, but
24103 only time spent in the function and its children (and their
24104 children@dots{}) will be used to determine total-time and
24105 percentages-of-time for the call graph.  More than one @samp{-F} option
24106 may be given; only one @var{function_name} may be indicated with each
24107 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
24108
24109 @end table
24110
24111 @node Interpretation of profiling results
24112 @subsection Interpretation of profiling results
24113
24114 @noindent
24115
24116 The results of the profiling analysis are represented by two arrays: the
24117 'flat profile' and the 'call graph'. Full documentation of those outputs
24118 can be found in the GNU Profiler User's Guide.
24119
24120 The flat profile shows the time spent in each function of the program, and how
24121 many time it has been called. This allows you to locate easily the most
24122 time-consuming functions.
24123
24124 The call graph shows, for each subprogram, the subprograms that call it,
24125 and the subprograms that it calls. It also provides an estimate of the time
24126 spent in each of those callers/called subprograms.
24127 @end ifclear
24128
24129 @c ******************************
24130 @node Running and Debugging Ada Programs
24131 @chapter Running and Debugging Ada Programs
24132 @cindex Debugging
24133
24134 @noindent
24135 This chapter discusses how to debug Ada programs.
24136 @ifset vms
24137 It applies to GNAT on the Alpha OpenVMS platform;
24138 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
24139 since HP has implemented Ada support in the OpenVMS debugger on I64.
24140 @end ifset
24141
24142 An incorrect Ada program may be handled in three ways by the GNAT compiler:
24143
24144 @enumerate
24145 @item
24146 The illegality may be a violation of the static semantics of Ada. In
24147 that case GNAT diagnoses the constructs in the program that are illegal.
24148 It is then a straightforward matter for the user to modify those parts of
24149 the program.
24150
24151 @item
24152 The illegality may be a violation of the dynamic semantics of Ada. In
24153 that case the program compiles and executes, but may generate incorrect
24154 results, or may terminate abnormally with some exception.
24155
24156 @item
24157 When presented with a program that contains convoluted errors, GNAT
24158 itself may terminate abnormally without providing full diagnostics on
24159 the incorrect user program.
24160 @end enumerate
24161
24162 @menu
24163 * The GNAT Debugger GDB::
24164 * Running GDB::
24165 * Introduction to GDB Commands::
24166 * Using Ada Expressions::
24167 * Calling User-Defined Subprograms::
24168 * Using the Next Command in a Function::
24169 * Ada Exceptions::
24170 * Ada Tasks::
24171 * Debugging Generic Units::
24172 * GNAT Abnormal Termination or Failure to Terminate::
24173 * Naming Conventions for GNAT Source Files::
24174 * Getting Internal Debugging Information::
24175 * Stack Traceback::
24176 @end menu
24177
24178 @cindex Debugger
24179 @findex gdb
24180
24181 @node The GNAT Debugger GDB
24182 @section The GNAT Debugger GDB
24183
24184 @noindent
24185 @code{GDB} is a general purpose, platform-independent debugger that
24186 can be used to debug mixed-language programs compiled with @command{gcc},
24187 and in particular is capable of debugging Ada programs compiled with
24188 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
24189 complex Ada data structures.
24190
24191 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
24192 @ifset vms
24193 located in the GNU:[DOCS] directory,
24194 @end ifset
24195 for full details on the usage of @code{GDB}, including a section on
24196 its usage on programs. This manual should be consulted for full
24197 details. The section that follows is a brief introduction to the
24198 philosophy and use of @code{GDB}.
24199
24200 When GNAT programs are compiled, the compiler optionally writes debugging
24201 information into the generated object file, including information on
24202 line numbers, and on declared types and variables. This information is
24203 separate from the generated code. It makes the object files considerably
24204 larger, but it does not add to the size of the actual executable that
24205 will be loaded into memory, and has no impact on run-time performance. The
24206 generation of debug information is triggered by the use of the
24207 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
24208 used to carry out the compilations. It is important to emphasize that
24209 the use of these options does not change the generated code.
24210
24211 The debugging information is written in standard system formats that
24212 are used by many tools, including debuggers and profilers. The format
24213 of the information is typically designed to describe C types and
24214 semantics, but GNAT implements a translation scheme which allows full
24215 details about Ada types and variables to be encoded into these
24216 standard C formats. Details of this encoding scheme may be found in
24217 the file exp_dbug.ads in the GNAT source distribution. However, the
24218 details of this encoding are, in general, of no interest to a user,
24219 since @code{GDB} automatically performs the necessary decoding.
24220
24221 When a program is bound and linked, the debugging information is
24222 collected from the object files, and stored in the executable image of
24223 the program. Again, this process significantly increases the size of
24224 the generated executable file, but it does not increase the size of
24225 the executable program itself. Furthermore, if this program is run in
24226 the normal manner, it runs exactly as if the debug information were
24227 not present, and takes no more actual memory.
24228
24229 However, if the program is run under control of @code{GDB}, the
24230 debugger is activated.  The image of the program is loaded, at which
24231 point it is ready to run.  If a run command is given, then the program
24232 will run exactly as it would have if @code{GDB} were not present. This
24233 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
24234 entirely non-intrusive until a breakpoint is encountered.  If no
24235 breakpoint is ever hit, the program will run exactly as it would if no
24236 debugger were present. When a breakpoint is hit, @code{GDB} accesses
24237 the debugging information and can respond to user commands to inspect
24238 variables, and more generally to report on the state of execution.
24239
24240 @c **************
24241 @node Running GDB
24242 @section Running GDB
24243
24244 @noindent
24245 This section describes how to initiate the debugger.
24246 @c The above sentence is really just filler, but it was otherwise
24247 @c clumsy to get the first paragraph nonindented given the conditional
24248 @c nature of the description
24249
24250 @ifclear vms
24251 The debugger can be launched from a @code{GPS} menu or
24252 directly from the command line. The description below covers the latter use.
24253 All the commands shown can be used in the @code{GPS} debug console window,
24254 but there are usually more GUI-based ways to achieve the same effect.
24255 @end ifclear
24256
24257 The command to run @code{GDB} is
24258
24259 @smallexample
24260 $ ^gdb program^GDB PROGRAM^
24261 @end smallexample
24262
24263 @noindent
24264 where @code{^program^PROGRAM^} is the name of the executable file. This
24265 activates the debugger and results in a prompt for debugger commands.
24266 The simplest command is simply @code{run}, which causes the program to run
24267 exactly as if the debugger were not present. The following section
24268 describes some of the additional commands that can be given to @code{GDB}.
24269
24270 @c *******************************
24271 @node Introduction to GDB Commands
24272 @section Introduction to GDB Commands
24273
24274 @noindent
24275 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
24276 Debugging with GDB, gdb, Debugging with GDB},
24277 @ifset vms
24278 located in the GNU:[DOCS] directory,
24279 @end ifset
24280 for extensive documentation on the use
24281 of these commands, together with examples of their use. Furthermore,
24282 the command @command{help} invoked from within GDB activates a simple help
24283 facility which summarizes the available commands and their options.
24284 In this section we summarize a few of the most commonly
24285 used commands to give an idea of what @code{GDB} is about. You should create
24286 a simple program with debugging information and experiment with the use of
24287 these @code{GDB} commands on the program as you read through the
24288 following section.
24289
24290 @table @code
24291 @item set args @var{arguments}
24292 The @var{arguments} list above is a list of arguments to be passed to
24293 the program on a subsequent run command, just as though the arguments
24294 had been entered on a normal invocation of the program. The @code{set args}
24295 command is not needed if the program does not require arguments.
24296
24297 @item run
24298 The @code{run} command causes execution of the program to start from
24299 the beginning. If the program is already running, that is to say if
24300 you are currently positioned at a breakpoint, then a prompt will ask
24301 for confirmation that you want to abandon the current execution and
24302 restart.
24303
24304 @item breakpoint @var{location}
24305 The breakpoint command sets a breakpoint, that is to say a point at which
24306 execution will halt and @code{GDB} will await further
24307 commands. @var{location} is
24308 either a line number within a file, given in the format @code{file:linenumber},
24309 or it is the name of a subprogram. If you request that a breakpoint be set on
24310 a subprogram that is overloaded, a prompt will ask you to specify on which of
24311 those subprograms you want to breakpoint. You can also
24312 specify that all of them should be breakpointed. If the program is run
24313 and execution encounters the breakpoint, then the program
24314 stops and @code{GDB} signals that the breakpoint was encountered by
24315 printing the line of code before which the program is halted.
24316
24317 @item breakpoint exception @var{name}
24318 A special form of the breakpoint command which breakpoints whenever
24319 exception @var{name} is raised.
24320 If @var{name} is omitted,
24321 then a breakpoint will occur when any exception is raised.
24322
24323 @item print @var{expression}
24324 This will print the value of the given expression. Most simple
24325 Ada expression formats are properly handled by @code{GDB}, so the expression
24326 can contain function calls, variables, operators, and attribute references.
24327
24328 @item continue
24329 Continues execution following a breakpoint, until the next breakpoint or the
24330 termination of the program.
24331
24332 @item step
24333 Executes a single line after a breakpoint. If the next statement
24334 is a subprogram call, execution continues into (the first statement of)
24335 the called subprogram.
24336
24337 @item next
24338 Executes a single line. If this line is a subprogram call, executes and
24339 returns from the call.
24340
24341 @item list
24342 Lists a few lines around the current source location. In practice, it
24343 is usually more convenient to have a separate edit window open with the
24344 relevant source file displayed. Successive applications of this command
24345 print subsequent lines. The command can be given an argument which is a
24346 line number, in which case it displays a few lines around the specified one.
24347
24348 @item backtrace
24349 Displays a backtrace of the call chain. This command is typically
24350 used after a breakpoint has occurred, to examine the sequence of calls that
24351 leads to the current breakpoint. The display includes one line for each
24352 activation record (frame) corresponding to an active subprogram.
24353
24354 @item up
24355 At a breakpoint, @code{GDB} can display the values of variables local
24356 to the current frame. The command @code{up} can be used to
24357 examine the contents of other active frames, by moving the focus up
24358 the stack, that is to say from callee to caller, one frame at a time.
24359
24360 @item down
24361 Moves the focus of @code{GDB} down from the frame currently being
24362 examined to the frame of its callee (the reverse of the previous command),
24363
24364 @item frame @var{n}
24365 Inspect the frame with the given number. The value 0 denotes the frame
24366 of the current breakpoint, that is to say the top of the call stack.
24367
24368 @end table
24369
24370 @noindent
24371 The above list is a very short introduction to the commands that
24372 @code{GDB} provides. Important additional capabilities, including conditional
24373 breakpoints, the ability to execute command sequences on a breakpoint,
24374 the ability to debug at the machine instruction level and many other
24375 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
24376 Debugging with GDB}.  Note that most commands can be abbreviated
24377 (for example, c for continue, bt for backtrace).
24378
24379 @node Using Ada Expressions
24380 @section Using Ada Expressions
24381 @cindex Ada expressions
24382
24383 @noindent
24384 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
24385 extensions. The philosophy behind the design of this subset is
24386
24387 @itemize @bullet
24388 @item
24389 That @code{GDB} should provide basic literals and access to operations for
24390 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
24391 leaving more sophisticated computations to subprograms written into the
24392 program (which therefore may be called from @code{GDB}).
24393
24394 @item
24395 That type safety and strict adherence to Ada language restrictions
24396 are not particularly important to the @code{GDB} user.
24397
24398 @item
24399 That brevity is important to the @code{GDB} user.
24400 @end itemize
24401
24402 @noindent
24403 Thus, for brevity, the debugger acts as if there were
24404 implicit @code{with} and @code{use} clauses in effect for all user-written
24405 packages, thus making it unnecessary to fully qualify most names with
24406 their packages, regardless of context. Where this causes ambiguity,
24407 @code{GDB} asks the user's intent.
24408
24409 For details on the supported Ada syntax, see @ref{Top,, Debugging with
24410 GDB, gdb, Debugging with GDB}.
24411
24412 @node Calling User-Defined Subprograms
24413 @section Calling User-Defined Subprograms
24414
24415 @noindent
24416 An important capability of @code{GDB} is the ability to call user-defined
24417 subprograms while debugging. This is achieved simply by entering
24418 a subprogram call statement in the form:
24419
24420 @smallexample
24421 call subprogram-name (parameters)
24422 @end smallexample
24423
24424 @noindent
24425 The keyword @code{call} can be omitted in the normal case where the
24426 @code{subprogram-name} does not coincide with any of the predefined
24427 @code{GDB} commands.
24428
24429 The effect is to invoke the given subprogram, passing it the
24430 list of parameters that is supplied. The parameters can be expressions and
24431 can include variables from the program being debugged. The
24432 subprogram must be defined
24433 at the library level within your program, and @code{GDB} will call the
24434 subprogram within the environment of your program execution (which
24435 means that the subprogram is free to access or even modify variables
24436 within your program).
24437
24438 The most important use of this facility is in allowing the inclusion of
24439 debugging routines that are tailored to particular data structures
24440 in your program. Such debugging routines can be written to provide a suitably
24441 high-level description of an abstract type, rather than a low-level dump
24442 of its physical layout. After all, the standard
24443 @code{GDB print} command only knows the physical layout of your
24444 types, not their abstract meaning. Debugging routines can provide information
24445 at the desired semantic level and are thus enormously useful.
24446
24447 For example, when debugging GNAT itself, it is crucial to have access to
24448 the contents of the tree nodes used to represent the program internally.
24449 But tree nodes are represented simply by an integer value (which in turn
24450 is an index into a table of nodes).
24451 Using the @code{print} command on a tree node would simply print this integer
24452 value, which is not very useful. But the PN routine (defined in file
24453 treepr.adb in the GNAT sources) takes a tree node as input, and displays
24454 a useful high level representation of the tree node, which includes the
24455 syntactic category of the node, its position in the source, the integers
24456 that denote descendant nodes and parent node, as well as varied
24457 semantic information. To study this example in more detail, you might want to
24458 look at the body of the PN procedure in the stated file.
24459
24460 @node Using the Next Command in a Function
24461 @section Using the Next Command in a Function
24462
24463 @noindent
24464 When you use the @code{next} command in a function, the current source
24465 location will advance to the next statement as usual. A special case
24466 arises in the case of a @code{return} statement.
24467
24468 Part of the code for a return statement is the ``epilog'' of the function.
24469 This is the code that returns to the caller. There is only one copy of
24470 this epilog code, and it is typically associated with the last return
24471 statement in the function if there is more than one return. In some
24472 implementations, this epilog is associated with the first statement
24473 of the function.
24474
24475 The result is that if you use the @code{next} command from a return
24476 statement that is not the last return statement of the function you
24477 may see a strange apparent jump to the last return statement or to
24478 the start of the function. You should simply ignore this odd jump.
24479 The value returned is always that from the first return statement
24480 that was stepped through.
24481
24482 @node Ada Exceptions
24483 @section Breaking on Ada Exceptions
24484 @cindex Exceptions
24485
24486 @noindent
24487 You can set breakpoints that trip when your program raises
24488 selected exceptions.
24489
24490 @table @code
24491 @item break exception
24492 Set a breakpoint that trips whenever (any task in the) program raises
24493 any exception.
24494
24495 @item break exception @var{name}
24496 Set a breakpoint that trips whenever (any task in the) program raises
24497 the exception @var{name}.
24498
24499 @item break exception unhandled
24500 Set a breakpoint that trips whenever (any task in the) program raises an
24501 exception for which there is no handler.
24502
24503 @item info exceptions
24504 @itemx info exceptions @var{regexp}
24505 The @code{info exceptions} command permits the user to examine all defined
24506 exceptions within Ada programs. With a regular expression, @var{regexp}, as
24507 argument, prints out only those exceptions whose name matches @var{regexp}.
24508 @end table
24509
24510 @node Ada Tasks
24511 @section Ada Tasks
24512 @cindex Tasks
24513
24514 @noindent
24515 @code{GDB} allows the following task-related commands:
24516
24517 @table @code
24518 @item info tasks
24519 This command shows a list of current Ada tasks, as in the following example:
24520
24521 @smallexample
24522 @iftex
24523 @leftskip=0cm
24524 @end iftex
24525 (gdb) info tasks
24526   ID       TID P-ID   Thread Pri State                 Name
24527    1   8088000   0   807e000  15 Child Activation Wait main_task
24528    2   80a4000   1   80ae000  15 Accept/Select Wait    b
24529    3   809a800   1   80a4800  15 Child Activation Wait a
24530 *  4   80ae800   3   80b8000  15 Running               c
24531 @end smallexample
24532
24533 @noindent
24534 In this listing, the asterisk before the first task indicates it to be the
24535 currently running task. The first column lists the task ID that is used
24536 to refer to tasks in the following commands.
24537
24538 @item break @var{linespec} task @var{taskid}
24539 @itemx break @var{linespec} task @var{taskid} if @dots{}
24540 @cindex Breakpoints and tasks
24541 These commands are like the @code{break @dots{} thread @dots{}}.
24542 @var{linespec} specifies source lines.
24543
24544 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
24545 to specify that you only want @code{GDB} to stop the program when a
24546 particular Ada task reaches this breakpoint. @var{taskid} is one of the
24547 numeric task identifiers assigned by @code{GDB}, shown in the first
24548 column of the @samp{info tasks} display.
24549
24550 If you do not specify @samp{task @var{taskid}} when you set a
24551 breakpoint, the breakpoint applies to @emph{all} tasks of your
24552 program.
24553
24554 You can use the @code{task} qualifier on conditional breakpoints as
24555 well; in this case, place @samp{task @var{taskid}} before the
24556 breakpoint condition (before the @code{if}).
24557
24558 @item task @var{taskno}
24559 @cindex Task switching
24560
24561 This command allows to switch to the task referred by @var{taskno}. In
24562 particular, This allows to browse the backtrace of the specified
24563 task. It is advised to switch back to the original task before
24564 continuing execution otherwise the scheduling of the program may be
24565 perturbed.
24566 @end table
24567
24568 @noindent
24569 For more detailed information on the tasking support,
24570 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
24571
24572 @node Debugging Generic Units
24573 @section Debugging Generic Units
24574 @cindex Debugging Generic Units
24575 @cindex Generics
24576
24577 @noindent
24578 GNAT always uses code expansion for generic instantiation. This means that
24579 each time an instantiation occurs, a complete copy of the original code is
24580 made, with appropriate substitutions of formals by actuals.
24581
24582 It is not possible to refer to the original generic entities in
24583 @code{GDB}, but it is always possible to debug a particular instance of
24584 a generic, by using the appropriate expanded names. For example, if we have
24585
24586 @smallexample @c ada
24587 @group
24588 @cartouche
24589 procedure g is
24590
24591    generic package k is
24592       procedure kp (v1 : in out integer);
24593    end k;
24594
24595    package body k is
24596       procedure kp (v1 : in out integer) is
24597       begin
24598          v1 := v1 + 1;
24599       end kp;
24600    end k;
24601
24602    package k1 is new k;
24603    package k2 is new k;
24604
24605    var : integer := 1;
24606
24607 begin
24608    k1.kp (var);
24609    k2.kp (var);
24610    k1.kp (var);
24611    k2.kp (var);
24612 end;
24613 @end cartouche
24614 @end group
24615 @end smallexample
24616
24617 @noindent
24618 Then to break on a call to procedure kp in the k2 instance, simply
24619 use the command:
24620
24621 @smallexample
24622 (gdb) break g.k2.kp
24623 @end smallexample
24624
24625 @noindent
24626 When the breakpoint occurs, you can step through the code of the
24627 instance in the normal manner and examine the values of local variables, as for
24628 other units.
24629
24630 @node GNAT Abnormal Termination or Failure to Terminate
24631 @section GNAT Abnormal Termination or Failure to Terminate
24632 @cindex GNAT Abnormal Termination or Failure to Terminate
24633
24634 @noindent
24635 When presented with programs that contain serious errors in syntax
24636 or semantics,
24637 GNAT may on rare occasions  experience problems in operation, such
24638 as aborting with a
24639 segmentation fault or illegal memory access, raising an internal
24640 exception, terminating abnormally, or failing to terminate at all.
24641 In such cases, you can activate
24642 various features of GNAT that can help you pinpoint the construct in your
24643 program that is the likely source of the problem.
24644
24645 The following strategies are presented in increasing order of
24646 difficulty, corresponding to your experience in using GNAT and your
24647 familiarity with compiler internals.
24648
24649 @enumerate
24650 @item
24651 Run @command{gcc} with the @option{-gnatf}. This first
24652 switch causes all errors on a given line to be reported. In its absence,
24653 only the first error on a line is displayed.
24654
24655 The @option{-gnatdO} switch causes errors to be displayed as soon as they
24656 are encountered, rather than after compilation is terminated. If GNAT
24657 terminates prematurely or goes into an infinite loop, the last error
24658 message displayed may help to pinpoint the culprit.
24659
24660 @item
24661 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
24662 mode, @command{gcc} produces ongoing information about the progress of the
24663 compilation and provides the name of each procedure as code is
24664 generated. This switch allows you to find which Ada procedure was being
24665 compiled when it encountered a code generation problem.
24666
24667 @item
24668 @cindex @option{-gnatdc} switch
24669 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
24670 switch that does for the front-end what @option{^-v^VERBOSE^} does
24671 for the back end. The system prints the name of each unit,
24672 either a compilation unit or nested unit, as it is being analyzed.
24673 @item
24674 Finally, you can start
24675 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
24676 front-end of GNAT, and can be run independently (normally it is just
24677 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
24678 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
24679 @code{where} command is the first line of attack; the variable
24680 @code{lineno} (seen by @code{print lineno}), used by the second phase of
24681 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
24682 which the execution stopped, and @code{input_file name} indicates the name of
24683 the source file.
24684 @end enumerate
24685
24686 @node Naming Conventions for GNAT Source Files
24687 @section Naming Conventions for GNAT Source Files
24688
24689 @noindent
24690 In order to examine the workings of the GNAT system, the following
24691 brief description of its organization may be helpful:
24692
24693 @itemize @bullet
24694 @item
24695 Files with prefix @file{^sc^SC^} contain the lexical scanner.
24696
24697 @item
24698 All files prefixed with @file{^par^PAR^} are components of the parser. The
24699 numbers correspond to chapters of the Ada Reference Manual. For example,
24700 parsing of select statements can be found in @file{par-ch9.adb}.
24701
24702 @item
24703 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
24704 numbers correspond to chapters of the Ada standard. For example, all
24705 issues involving context clauses can be found in @file{sem_ch10.adb}. In
24706 addition, some features of the language require sufficient special processing
24707 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
24708 dynamic dispatching, etc.
24709
24710 @item
24711 All files prefixed with @file{^exp^EXP^} perform normalization and
24712 expansion of the intermediate representation (abstract syntax tree, or AST).
24713 these files use the same numbering scheme as the parser and semantics files.
24714 For example, the construction of record initialization procedures is done in
24715 @file{exp_ch3.adb}.
24716
24717 @item
24718 The files prefixed with @file{^bind^BIND^} implement the binder, which
24719 verifies the consistency of the compilation, determines an order of
24720 elaboration, and generates the bind file.
24721
24722 @item
24723 The files @file{atree.ads} and @file{atree.adb} detail the low-level
24724 data structures used by the front-end.
24725
24726 @item
24727 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
24728 the abstract syntax tree as produced by the parser.
24729
24730 @item
24731 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
24732 all entities, computed during semantic analysis.
24733
24734 @item
24735 Library management issues are dealt with in files with prefix
24736 @file{^lib^LIB^}.
24737
24738 @item
24739 @findex Ada
24740 @cindex Annex A
24741 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
24742 defined in Annex A.
24743
24744 @item
24745 @findex Interfaces
24746 @cindex Annex B
24747 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
24748 defined in Annex B.
24749
24750 @item
24751 @findex System
24752 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
24753 both language-defined children and GNAT run-time routines.
24754
24755 @item
24756 @findex GNAT
24757 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
24758 general-purpose packages, fully documented in their specs. All
24759 the other @file{.c} files are modifications of common @command{gcc} files.
24760 @end itemize
24761
24762 @node Getting Internal Debugging Information
24763 @section Getting Internal Debugging Information
24764
24765 @noindent
24766 Most compilers have internal debugging switches and modes. GNAT
24767 does also, except GNAT internal debugging switches and modes are not
24768 secret. A summary and full description of all the compiler and binder
24769 debug flags are in the file @file{debug.adb}. You must obtain the
24770 sources of the compiler to see the full detailed effects of these flags.
24771
24772 The switches that print the source of the program (reconstructed from
24773 the internal tree) are of general interest for user programs, as are the
24774 options to print
24775 the full internal tree, and the entity table (the symbol table
24776 information). The reconstructed source provides a readable version of the
24777 program after the front-end has completed analysis and  expansion,
24778 and is useful when studying the performance of specific constructs.
24779 For example, constraint checks are indicated, complex aggregates
24780 are replaced with loops and assignments, and tasking primitives
24781 are replaced with run-time calls.
24782
24783 @node Stack Traceback
24784 @section Stack Traceback
24785 @cindex traceback
24786 @cindex stack traceback
24787 @cindex stack unwinding
24788
24789 @noindent
24790 Traceback is a mechanism to display the sequence of subprogram calls that
24791 leads to a specified execution point in a program. Often (but not always)
24792 the execution point is an instruction at which an exception has been raised.
24793 This mechanism is also known as @i{stack unwinding} because it obtains
24794 its information by scanning the run-time stack and recovering the activation
24795 records of all active subprograms. Stack unwinding is one of the most
24796 important tools for program debugging.
24797
24798 The first entry stored in traceback corresponds to the deepest calling level,
24799 that is to say the subprogram currently executing the instruction
24800 from which we want to obtain the traceback.
24801
24802 Note that there is no runtime performance penalty when stack traceback
24803 is enabled, and no exception is raised during program execution.
24804
24805 @menu
24806 * Non-Symbolic Traceback::
24807 * Symbolic Traceback::
24808 @end menu
24809
24810 @node Non-Symbolic Traceback
24811 @subsection Non-Symbolic Traceback
24812 @cindex traceback, non-symbolic
24813
24814 @noindent
24815 Note: this feature is not supported on all platforms. See
24816 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
24817 platforms.
24818
24819 @menu
24820 * Tracebacks From an Unhandled Exception::
24821 * Tracebacks From Exception Occurrences (non-symbolic)::
24822 * Tracebacks From Anywhere in a Program (non-symbolic)::
24823 @end menu
24824
24825 @node Tracebacks From an Unhandled Exception
24826 @subsubsection Tracebacks From an Unhandled Exception
24827
24828 @noindent
24829 A runtime non-symbolic traceback is a list of addresses of call instructions.
24830 To enable this feature you must use the @option{-E}
24831 @code{gnatbind}'s option. With this option a stack traceback is stored as part
24832 of exception information. You can retrieve this information using the
24833 @code{addr2line} tool.
24834
24835 Here is a simple example:
24836
24837 @smallexample @c ada
24838 @cartouche
24839 procedure STB is
24840
24841    procedure P1 is
24842    begin
24843       raise Constraint_Error;
24844    end P1;
24845
24846    procedure P2 is
24847    begin
24848       P1;
24849    end P2;
24850
24851 begin
24852    P2;
24853 end STB;
24854 @end cartouche
24855 @end smallexample
24856
24857 @smallexample
24858 $ gnatmake stb -bargs -E
24859 $ stb
24860
24861 Execution terminated by unhandled exception
24862 Exception name: CONSTRAINT_ERROR
24863 Message: stb.adb:5
24864 Call stack traceback locations:
24865 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24866 @end smallexample
24867
24868 @noindent
24869 As we see the traceback lists a sequence of addresses for the unhandled
24870 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
24871 guess that this exception come from procedure P1. To translate these
24872 addresses into the source lines where the calls appear, the
24873 @code{addr2line} tool, described below, is invaluable. The use of this tool
24874 requires the program to be compiled with debug information.
24875
24876 @smallexample
24877 $ gnatmake -g stb -bargs -E
24878 $ stb
24879
24880 Execution terminated by unhandled exception
24881 Exception name: CONSTRAINT_ERROR
24882 Message: stb.adb:5
24883 Call stack traceback locations:
24884 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
24885
24886 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
24887    0x4011f1 0x77e892a4
24888
24889 00401373 at d:/stb/stb.adb:5
24890 0040138B at d:/stb/stb.adb:10
24891 0040139C at d:/stb/stb.adb:14
24892 00401335 at d:/stb/b~stb.adb:104
24893 004011C4 at /build/@dots{}/crt1.c:200
24894 004011F1 at /build/@dots{}/crt1.c:222
24895 77E892A4 in ?? at ??:0
24896 @end smallexample
24897
24898 @noindent
24899 The @code{addr2line} tool has several other useful options:
24900
24901 @table @code
24902 @item --functions
24903 to get the function name corresponding to any location
24904
24905 @item --demangle=gnat
24906 to use the gnat decoding mode for the function names. Note that
24907 for binutils version 2.9.x the option is simply @option{--demangle}.
24908 @end table
24909
24910 @smallexample
24911 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
24912    0x40139c 0x401335 0x4011c4 0x4011f1
24913
24914 00401373 in stb.p1 at d:/stb/stb.adb:5
24915 0040138B in stb.p2 at d:/stb/stb.adb:10
24916 0040139C in stb at d:/stb/stb.adb:14
24917 00401335 in main at d:/stb/b~stb.adb:104
24918 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
24919 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
24920 @end smallexample
24921
24922 @noindent
24923 From this traceback we can see that the exception was raised in
24924 @file{stb.adb} at line 5, which was reached from a procedure call in
24925 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
24926 which contains the call to the main program.
24927 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
24928 and the output will vary from platform to platform.
24929
24930 It is also possible to use @code{GDB} with these traceback addresses to debug
24931 the program. For example, we can break at a given code location, as reported
24932 in the stack traceback:
24933
24934 @smallexample
24935 $ gdb -nw stb
24936 @ifclear vms
24937 @noindent
24938 Furthermore, this feature is not implemented inside Windows DLL. Only
24939 the non-symbolic traceback is reported in this case.
24940 @end ifclear
24941
24942 (gdb) break *0x401373
24943 Breakpoint 1 at 0x401373: file stb.adb, line 5.
24944 @end smallexample
24945
24946 @noindent
24947 It is important to note that the stack traceback addresses
24948 do not change when debug information is included. This is particularly useful
24949 because it makes it possible to release software without debug information (to
24950 minimize object size), get a field report that includes a stack traceback
24951 whenever an internal bug occurs, and then be able to retrieve the sequence
24952 of calls with the same program compiled with debug information.
24953
24954 @node Tracebacks From Exception Occurrences (non-symbolic)
24955 @subsubsection Tracebacks From Exception Occurrences
24956
24957 @noindent
24958 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
24959 The stack traceback is attached to the exception information string, and can
24960 be retrieved in an exception handler within the Ada program, by means of the
24961 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
24962
24963 @smallexample @c ada
24964 with Ada.Text_IO;
24965 with Ada.Exceptions;
24966
24967 procedure STB is
24968
24969    use Ada;
24970    use Ada.Exceptions;
24971
24972    procedure P1 is
24973       K : Positive := 1;
24974    begin
24975       K := K - 1;
24976    exception
24977       when E : others =>
24978          Text_IO.Put_Line (Exception_Information (E));
24979    end P1;
24980
24981    procedure P2 is
24982    begin
24983       P1;
24984    end P2;
24985
24986 begin
24987    P2;
24988 end STB;
24989 @end smallexample
24990
24991 @noindent
24992 This program will output:
24993
24994 @smallexample
24995 $ stb
24996
24997 Exception name: CONSTRAINT_ERROR
24998 Message: stb.adb:12
24999 Call stack traceback locations:
25000 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
25001 @end smallexample
25002
25003 @node Tracebacks From Anywhere in a Program (non-symbolic)
25004 @subsubsection Tracebacks From Anywhere in a Program
25005
25006 @noindent
25007 It is also possible to retrieve a stack traceback from anywhere in a
25008 program. For this you need to
25009 use the @code{GNAT.Traceback} API. This package includes a procedure called
25010 @code{Call_Chain} that computes a complete stack traceback, as well as useful
25011 display procedures described below. It is not necessary to use the
25012 @option{-E gnatbind} option in this case, because the stack traceback mechanism
25013 is invoked explicitly.
25014
25015 @noindent
25016 In the following example we compute a traceback at a specific location in
25017 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
25018 convert addresses to strings:
25019
25020 @smallexample @c ada
25021 with Ada.Text_IO;
25022 with GNAT.Traceback;
25023 with GNAT.Debug_Utilities;
25024
25025 procedure STB is
25026
25027    use Ada;
25028    use GNAT;
25029    use GNAT.Traceback;
25030
25031    procedure P1 is
25032       TB  : Tracebacks_Array (1 .. 10);
25033       --  We are asking for a maximum of 10 stack frames.
25034       Len : Natural;
25035       --  Len will receive the actual number of stack frames returned.
25036    begin
25037       Call_Chain (TB, Len);
25038
25039       Text_IO.Put ("In STB.P1 : ");
25040
25041       for K in 1 .. Len loop
25042          Text_IO.Put (Debug_Utilities.Image (TB (K)));
25043          Text_IO.Put (' ');
25044       end loop;
25045
25046       Text_IO.New_Line;
25047    end P1;
25048
25049    procedure P2 is
25050    begin
25051       P1;
25052    end P2;
25053
25054 begin
25055    P2;
25056 end STB;
25057 @end smallexample
25058
25059 @smallexample
25060 $ gnatmake -g stb
25061 $ stb
25062
25063 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
25064 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
25065 @end smallexample
25066
25067 @noindent
25068 You can then get further information by invoking the @code{addr2line}
25069 tool as described earlier (note that the hexadecimal addresses
25070 need to be specified in C format, with a leading ``0x'').
25071
25072 @node Symbolic Traceback
25073 @subsection Symbolic Traceback
25074 @cindex traceback, symbolic
25075
25076 @noindent
25077 A symbolic traceback is a stack traceback in which procedure names are
25078 associated with each code location.
25079
25080 @noindent
25081 Note that this feature is not supported on all platforms. See
25082 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
25083 list of currently supported platforms.
25084
25085 @noindent
25086 Note that the symbolic traceback requires that the program be compiled
25087 with debug information. If it is not compiled with debug information
25088 only the non-symbolic information will be valid.
25089
25090 @menu
25091 * Tracebacks From Exception Occurrences (symbolic)::
25092 * Tracebacks From Anywhere in a Program (symbolic)::
25093 @end menu
25094
25095 @node Tracebacks From Exception Occurrences (symbolic)
25096 @subsubsection Tracebacks From Exception Occurrences
25097
25098 @smallexample @c ada
25099 with Ada.Text_IO;
25100 with GNAT.Traceback.Symbolic;
25101
25102 procedure STB is
25103
25104    procedure P1 is
25105    begin
25106       raise Constraint_Error;
25107    end P1;
25108
25109    procedure P2 is
25110    begin
25111       P1;
25112    end P2;
25113
25114    procedure P3 is
25115    begin
25116       P2;
25117    end P3;
25118
25119 begin
25120    P3;
25121 exception
25122    when E : others =>
25123       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
25124 end STB;
25125 @end smallexample
25126
25127 @smallexample
25128 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
25129 $ stb
25130
25131 0040149F in stb.p1 at stb.adb:8
25132 004014B7 in stb.p2 at stb.adb:13
25133 004014CF in stb.p3 at stb.adb:18
25134 004015DD in ada.stb at stb.adb:22
25135 00401461 in main at b~stb.adb:168
25136 004011C4 in __mingw_CRTStartup at crt1.c:200
25137 004011F1 in mainCRTStartup at crt1.c:222
25138 77E892A4 in ?? at ??:0
25139 @end smallexample
25140
25141 @noindent
25142 In the above example the ``.\'' syntax in the @command{gnatmake} command
25143 is currently required by @command{addr2line} for files that are in
25144 the current working directory.
25145 Moreover, the exact sequence of linker options may vary from platform
25146 to platform.
25147 The above @option{-largs} section is for Windows platforms. By contrast,
25148 under Unix there is no need for the @option{-largs} section.
25149 Differences across platforms are due to details of linker implementation.
25150
25151 @node Tracebacks From Anywhere in a Program (symbolic)
25152 @subsubsection Tracebacks From Anywhere in a Program
25153
25154 @noindent
25155 It is possible to get a symbolic stack traceback
25156 from anywhere in a program, just as for non-symbolic tracebacks.
25157 The first step is to obtain a non-symbolic
25158 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
25159 information. Here is an example:
25160
25161 @smallexample @c ada
25162 with Ada.Text_IO;
25163 with GNAT.Traceback;
25164 with GNAT.Traceback.Symbolic;
25165
25166 procedure STB is
25167
25168    use Ada;
25169    use GNAT.Traceback;
25170    use GNAT.Traceback.Symbolic;
25171
25172    procedure P1 is
25173       TB  : Tracebacks_Array (1 .. 10);
25174       --  We are asking for a maximum of 10 stack frames.
25175       Len : Natural;
25176       --  Len will receive the actual number of stack frames returned.
25177    begin
25178       Call_Chain (TB, Len);
25179       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
25180    end P1;
25181
25182    procedure P2 is
25183    begin
25184       P1;
25185    end P2;
25186
25187 begin
25188    P2;
25189 end STB;
25190 @end smallexample
25191
25192 @c ******************************
25193 @ifset vms
25194 @node Compatibility with HP Ada
25195 @chapter Compatibility with HP Ada
25196 @cindex Compatibility
25197
25198 @noindent
25199 @cindex DEC Ada
25200 @cindex HP Ada
25201 @cindex Compatibility between GNAT and HP Ada
25202 This chapter compares HP Ada (formerly known as ``DEC Ada'')
25203 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
25204 GNAT is highly compatible
25205 with HP Ada, and it should generally be straightforward to port code
25206 from the HP Ada environment to GNAT. However, there are a few language
25207 and implementation differences of which the user must be aware. These
25208 differences are discussed in this chapter. In
25209 addition, the operating environment and command structure for the
25210 compiler are different, and these differences are also discussed.
25211
25212 For further details on these and other compatibility issues,
25213 see Appendix E of the HP publication
25214 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
25215
25216 Except where otherwise indicated, the description of GNAT for OpenVMS
25217 applies to both the Alpha and I64 platforms.
25218
25219 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
25220 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
25221
25222 The discussion in this chapter addresses specifically the implementation
25223 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
25224 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
25225 GNAT always follows the Alpha implementation.
25226
25227 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
25228 attributes are recognized, although only a subset of them can sensibly
25229 be implemented.  The description of pragmas in
25230 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
25231 indicates whether or not they are applicable to non-VMS systems.
25232
25233 @menu
25234 * Ada Language Compatibility::
25235 * Differences in the Definition of Package System::
25236 * Language-Related Features::
25237 * The Package STANDARD::
25238 * The Package SYSTEM::
25239 * Tasking and Task-Related Features::
25240 * Pragmas and Pragma-Related Features::
25241 * Library of Predefined Units::
25242 * Bindings::
25243 * Main Program Definition::
25244 * Implementation-Defined Attributes::
25245 * Compiler and Run-Time Interfacing::
25246 * Program Compilation and Library Management::
25247 * Input-Output::
25248 * Implementation Limits::
25249 * Tools and Utilities::
25250 @end menu
25251
25252 @node Ada Language Compatibility
25253 @section Ada Language Compatibility
25254
25255 @noindent
25256 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
25257 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
25258 with Ada 83, and therefore Ada 83 programs will compile
25259 and run under GNAT with
25260 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
25261 provides details on specific incompatibilities.
25262
25263 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
25264 as well as the pragma @code{ADA_83}, to force the compiler to
25265 operate in Ada 83 mode. This mode does not guarantee complete
25266 conformance to Ada 83, but in practice is sufficient to
25267 eliminate most sources of incompatibilities.
25268 In particular, it eliminates the recognition of the
25269 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
25270 in Ada 83 programs is legal, and handles the cases of packages
25271 with optional bodies, and generics that instantiate unconstrained
25272 types without the use of @code{(<>)}.
25273
25274 @node Differences in the Definition of Package System
25275 @section Differences in the Definition of Package @code{System}
25276
25277 @noindent
25278 An Ada compiler is allowed to add
25279 implementation-dependent declarations to package @code{System}.
25280 In normal mode,
25281 GNAT does not take advantage of this permission, and the version of
25282 @code{System} provided by GNAT exactly matches that defined in the Ada
25283 Reference Manual.
25284
25285 However, HP Ada adds an extensive set of declarations to package
25286 @code{System},
25287 as fully documented in the HP Ada manuals. To minimize changes required
25288 for programs that make use of these extensions, GNAT provides the pragma
25289 @code{Extend_System} for extending the definition of package System. By using:
25290 @cindex pragma @code{Extend_System}
25291 @cindex @code{Extend_System} pragma
25292
25293 @smallexample @c ada
25294 @group
25295 @cartouche
25296 pragma Extend_System (Aux_DEC);
25297 @end cartouche
25298 @end group
25299 @end smallexample
25300
25301 @noindent
25302 the set of definitions in @code{System} is extended to include those in
25303 package @code{System.Aux_DEC}.
25304 @cindex @code{System.Aux_DEC} package
25305 @cindex @code{Aux_DEC} package (child of @code{System})
25306 These definitions are incorporated directly into package @code{System},
25307 as though they had been declared there. For a
25308 list of the declarations added, see the spec of this package,
25309 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
25310 @cindex @file{s-auxdec.ads} file
25311 The pragma @code{Extend_System} is a configuration pragma, which means that
25312 it can be placed in the file @file{gnat.adc}, so that it will automatically
25313 apply to all subsequent compilations. See @ref{Configuration Pragmas},
25314 for further details.
25315
25316 An alternative approach that avoids the use of the non-standard
25317 @code{Extend_System} pragma is to add a context clause to the unit that
25318 references these facilities:
25319
25320 @smallexample @c ada
25321 @cartouche
25322 with System.Aux_DEC;
25323 use  System.Aux_DEC;
25324 @end cartouche
25325 @end smallexample
25326
25327 @noindent
25328 The effect is not quite semantically identical to incorporating
25329 the declarations directly into package @code{System},
25330 but most programs will not notice a difference
25331 unless they use prefix notation (e.g.@: @code{System.Integer_8})
25332 to reference the entities directly in package @code{System}.
25333 For units containing such references,
25334 the prefixes must either be removed, or the pragma @code{Extend_System}
25335 must be used.
25336
25337 @node Language-Related Features
25338 @section Language-Related Features
25339
25340 @noindent
25341 The following sections highlight differences in types,
25342 representations of types, operations, alignment, and
25343 related topics.
25344
25345 @menu
25346 * Integer Types and Representations::
25347 * Floating-Point Types and Representations::
25348 * Pragmas Float_Representation and Long_Float::
25349 * Fixed-Point Types and Representations::
25350 * Record and Array Component Alignment::
25351 * Address Clauses::
25352 * Other Representation Clauses::
25353 @end menu
25354
25355 @node Integer Types and Representations
25356 @subsection Integer Types and Representations
25357
25358 @noindent
25359 The set of predefined integer types is identical in HP Ada and GNAT.
25360 Furthermore the representation of these integer types is also identical,
25361 including the capability of size clauses forcing biased representation.
25362
25363 In addition,
25364 HP Ada for OpenVMS Alpha systems has defined the
25365 following additional integer types in package @code{System}:
25366
25367 @itemize @bullet
25368
25369 @item
25370 @code{INTEGER_8}
25371
25372 @item
25373 @code{INTEGER_16}
25374
25375 @item
25376 @code{INTEGER_32}
25377
25378 @item
25379 @code{INTEGER_64}
25380
25381 @item
25382 @code{LARGEST_INTEGER}
25383 @end itemize
25384
25385 @noindent
25386 In GNAT, the first four of these types may be obtained from the
25387 standard Ada package @code{Interfaces}.
25388 Alternatively, by use of the pragma @code{Extend_System}, identical
25389 declarations can be referenced directly in package @code{System}.
25390 On both GNAT and HP Ada, the maximum integer size is 64 bits.
25391
25392 @node Floating-Point Types and Representations
25393 @subsection Floating-Point Types and Representations
25394 @cindex Floating-Point types
25395
25396 @noindent
25397 The set of predefined floating-point types is identical in HP Ada and GNAT.
25398 Furthermore the representation of these floating-point
25399 types is also identical. One important difference is that the default
25400 representation for HP Ada is @code{VAX_Float}, but the default representation
25401 for GNAT is IEEE.
25402
25403 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
25404 pragma @code{Float_Representation} as described in the HP Ada
25405 documentation.
25406 For example, the declarations:
25407
25408 @smallexample @c ada
25409 @cartouche
25410 type F_Float is digits 6;
25411 pragma Float_Representation (VAX_Float, F_Float);
25412 @end cartouche
25413 @end smallexample
25414
25415 @noindent
25416 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
25417 format.
25418 This set of declarations actually appears in @code{System.Aux_DEC},
25419 which contains
25420 the full set of additional floating-point declarations provided in
25421 the HP Ada version of package @code{System}.
25422 This and similar declarations may be accessed in a user program
25423 by using pragma @code{Extend_System}. The use of this
25424 pragma, and the related pragma @code{Long_Float} is described in further
25425 detail in the following section.
25426
25427 @node Pragmas Float_Representation and Long_Float
25428 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
25429
25430 @noindent
25431 HP Ada provides the pragma @code{Float_Representation}, which
25432 acts as a program library switch to allow control over
25433 the internal representation chosen for the predefined
25434 floating-point types declared in the package @code{Standard}.
25435 The format of this pragma is as follows:
25436
25437 @smallexample @c ada
25438 @cartouche
25439 pragma Float_Representation(VAX_Float | IEEE_Float);
25440 @end cartouche
25441 @end smallexample
25442
25443 @noindent
25444 This pragma controls the representation of floating-point
25445 types as follows:
25446
25447 @itemize @bullet
25448 @item
25449 @code{VAX_Float} specifies that floating-point
25450 types are represented by default with the VAX system hardware types
25451 @code{F-floating}, @code{D-floating}, @code{G-floating}.
25452 Note that the @code{H-floating}
25453 type was available only on VAX systems, and is not available
25454 in either HP Ada or GNAT.
25455
25456 @item
25457 @code{IEEE_Float} specifies that floating-point
25458 types are represented by default with the IEEE single and
25459 double floating-point types.
25460 @end itemize
25461
25462 @noindent
25463 GNAT provides an identical implementation of the pragma
25464 @code{Float_Representation}, except that it functions as a
25465 configuration pragma. Note that the
25466 notion of configuration pragma corresponds closely to the
25467 HP Ada notion of a program library switch.
25468
25469 When no pragma is used in GNAT, the default is @code{IEEE_Float},
25470 which is different
25471 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
25472 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
25473 advisable to change the format of numbers passed to standard library
25474 routines, and if necessary explicit type conversions may be needed.
25475
25476 The use of @code{IEEE_Float} is recommended in GNAT since it is more
25477 efficient, and (given that it conforms to an international standard)
25478 potentially more portable.
25479 The situation in which @code{VAX_Float} may be useful is in interfacing
25480 to existing code and data that expect the use of @code{VAX_Float}.
25481 In such a situation use the predefined @code{VAX_Float}
25482 types in package @code{System}, as extended by
25483 @code{Extend_System}. For example, use @code{System.F_Float}
25484 to specify the 32-bit @code{F-Float} format.
25485
25486 @noindent
25487 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
25488 to allow control over the internal representation chosen
25489 for the predefined type @code{Long_Float} and for floating-point
25490 type declarations with digits specified in the range 7 .. 15.
25491 The format of this pragma is as follows:
25492
25493 @smallexample @c ada
25494 @cartouche
25495 pragma Long_Float (D_FLOAT | G_FLOAT);
25496 @end cartouche
25497 @end smallexample
25498
25499 @node Fixed-Point Types and Representations
25500 @subsection Fixed-Point Types and Representations
25501
25502 @noindent
25503 On HP Ada for OpenVMS Alpha systems, rounding is
25504 away from zero for both positive and negative numbers.
25505 Therefore, @code{+0.5} rounds to @code{1},
25506 and @code{-0.5} rounds to @code{-1}.
25507
25508 On GNAT the results of operations
25509 on fixed-point types are in accordance with the Ada
25510 rules. In particular, results of operations on decimal
25511 fixed-point types are truncated.
25512
25513 @node Record and Array Component Alignment
25514 @subsection Record and Array Component Alignment
25515
25516 @noindent
25517 On HP Ada for OpenVMS Alpha, all non-composite components
25518 are aligned on natural boundaries. For example, 1-byte
25519 components are aligned on byte boundaries, 2-byte
25520 components on 2-byte boundaries, 4-byte components on 4-byte
25521 byte boundaries, and so on. The OpenVMS Alpha hardware
25522 runs more efficiently with naturally aligned data.
25523
25524 On GNAT, alignment rules are compatible
25525 with HP Ada for OpenVMS Alpha.
25526
25527 @node Address Clauses
25528 @subsection Address Clauses
25529
25530 @noindent
25531 In HP Ada and GNAT, address clauses are supported for
25532 objects and imported subprograms.
25533 The predefined type @code{System.Address} is a private type
25534 in both compilers on Alpha OpenVMS, with the same representation
25535 (it is simply a machine pointer). Addition, subtraction, and comparison
25536 operations are available in the standard Ada package
25537 @code{System.Storage_Elements}, or in package @code{System}
25538 if it is extended to include @code{System.Aux_DEC} using a
25539 pragma @code{Extend_System} as previously described.
25540
25541 Note that code that @code{with}'s both this extended package @code{System}
25542 and the package @code{System.Storage_Elements} should not @code{use}
25543 both packages, or ambiguities will result. In general it is better
25544 not to mix these two sets of facilities. The Ada package was
25545 designed specifically to provide the kind of features that HP Ada
25546 adds directly to package @code{System}.
25547
25548 The type @code{System.Address} is a 64-bit integer type in GNAT for
25549 I64 OpenVMS.  For more information,
25550 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
25551
25552 GNAT is compatible with HP Ada in its handling of address
25553 clauses, except for some limitations in
25554 the form of address clauses for composite objects with
25555 initialization. Such address clauses are easily replaced
25556 by the use of an explicitly-defined constant as described
25557 in the Ada Reference Manual (13.1(22)). For example, the sequence
25558 of declarations:
25559
25560 @smallexample @c ada
25561 @cartouche
25562 X, Y : Integer := Init_Func;
25563 Q : String (X .. Y) := "abc";
25564 @dots{}
25565 for Q'Address use Compute_Address;
25566 @end cartouche
25567 @end smallexample
25568
25569 @noindent
25570 will be rejected by GNAT, since the address cannot be computed at the time
25571 that @code{Q} is declared. To achieve the intended effect, write instead:
25572
25573 @smallexample @c ada
25574 @group
25575 @cartouche
25576 X, Y : Integer := Init_Func;
25577 Q_Address : constant Address := Compute_Address;
25578 Q : String (X .. Y) := "abc";
25579 @dots{}
25580 for Q'Address use Q_Address;
25581 @end cartouche
25582 @end group
25583 @end smallexample
25584
25585 @noindent
25586 which will be accepted by GNAT (and other Ada compilers), and is also
25587 compatible with Ada 83. A fuller description of the restrictions
25588 on address specifications is found in @ref{Top, GNAT Reference Manual,
25589 About This Guide, gnat_rm, GNAT Reference Manual}.
25590
25591 @node Other Representation Clauses
25592 @subsection Other Representation Clauses
25593
25594 @noindent
25595 GNAT implements in a compatible manner all the representation
25596 clauses supported by HP Ada. In addition, GNAT
25597 implements the representation clause forms that were introduced in Ada 95,
25598 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
25599
25600 @node The Package STANDARD
25601 @section The Package @code{STANDARD}
25602
25603 @noindent
25604 The package @code{STANDARD}, as implemented by HP Ada, is fully
25605 described in the @cite{Ada Reference Manual} and in the
25606 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
25607 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
25608
25609 In addition, HP Ada supports the Latin-1 character set in
25610 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
25611 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
25612 the type @code{WIDE_CHARACTER}.
25613
25614 The floating-point types supported by GNAT are those
25615 supported by HP Ada, but the defaults are different, and are controlled by
25616 pragmas. See @ref{Floating-Point Types and Representations}, for details.
25617
25618 @node The Package SYSTEM
25619 @section The Package @code{SYSTEM}
25620
25621 @noindent
25622 HP Ada provides a specific version of the package
25623 @code{SYSTEM} for each platform on which the language is implemented.
25624 For the complete spec of the package @code{SYSTEM}, see
25625 Appendix F of the @cite{HP Ada Language Reference Manual}.
25626
25627 On HP Ada, the package @code{SYSTEM} includes the following conversion
25628 functions:
25629 @itemize @bullet
25630 @item @code{TO_ADDRESS(INTEGER)}
25631
25632 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
25633
25634 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
25635
25636 @item @code{TO_INTEGER(ADDRESS)}
25637
25638 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
25639
25640 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
25641 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
25642 @end itemize
25643
25644 @noindent
25645 By default, GNAT supplies a version of @code{SYSTEM} that matches
25646 the definition given in the @cite{Ada Reference Manual}.
25647 This
25648 is a subset of the HP system definitions, which is as
25649 close as possible to the original definitions. The only difference
25650 is that the definition of @code{SYSTEM_NAME} is different:
25651
25652 @smallexample @c ada
25653 @cartouche
25654 type Name is (SYSTEM_NAME_GNAT);
25655 System_Name : constant Name := SYSTEM_NAME_GNAT;
25656 @end cartouche
25657 @end smallexample
25658
25659 @noindent
25660 Also, GNAT adds the Ada declarations for
25661 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
25662
25663 However, the use of the following pragma causes GNAT
25664 to extend the definition of package @code{SYSTEM} so that it
25665 encompasses the full set of HP-specific extensions,
25666 including the functions listed above:
25667
25668 @smallexample @c ada
25669 @cartouche
25670 pragma Extend_System (Aux_DEC);
25671 @end cartouche
25672 @end smallexample
25673
25674 @noindent
25675 The pragma @code{Extend_System} is a configuration pragma that
25676 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
25677 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
25678
25679 HP Ada does not allow the recompilation of the package
25680 @code{SYSTEM}. Instead HP Ada provides several pragmas
25681 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
25682 to modify values in the package @code{SYSTEM}.
25683 On OpenVMS Alpha systems, the pragma
25684 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
25685 its single argument.
25686
25687 GNAT does permit the recompilation of package @code{SYSTEM} using
25688 the special switch @option{-gnatg}, and this switch can be used if
25689 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
25690 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
25691 or @code{MEMORY_SIZE} by any other means.
25692
25693 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
25694 enumeration literal @code{SYSTEM_NAME_GNAT}.
25695
25696 The definitions provided by the use of
25697
25698 @smallexample @c ada
25699 pragma Extend_System (AUX_Dec);
25700 @end smallexample
25701
25702 @noindent
25703 are virtually identical to those provided by the HP Ada 83 package
25704 @code{SYSTEM}. One important difference is that the name of the
25705 @code{TO_ADDRESS}
25706 function for type @code{UNSIGNED_LONGWORD} is changed to
25707 @code{TO_ADDRESS_LONG}.
25708 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
25709 discussion of why this change was necessary.
25710
25711 @noindent
25712 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
25713 is in fact
25714 an extension to Ada 83 not strictly compatible with the reference manual.
25715 GNAT, in order to be exactly compatible with the standard,
25716 does not provide this capability. In HP Ada 83, the
25717 point of this definition is to deal with a call like:
25718
25719 @smallexample @c ada
25720 TO_ADDRESS (16#12777#);
25721 @end smallexample
25722
25723 @noindent
25724 Normally, according to Ada 83 semantics, one would expect this to be
25725 ambiguous, since it matches both the @code{INTEGER} and
25726 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
25727 However, in HP Ada 83, there is no ambiguity, since the
25728 definition using @i{universal_integer} takes precedence.
25729
25730 In GNAT, since the version with @i{universal_integer} cannot be supplied,
25731 it is
25732 not possible to be 100% compatible. Since there are many programs using
25733 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
25734 GNAT was
25735 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
25736 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
25737
25738 @smallexample @c ada
25739 function To_Address (X : Integer) return Address;
25740 pragma Pure_Function (To_Address);
25741
25742 function To_Address_Long (X : Unsigned_Longword) return Address;
25743 pragma Pure_Function (To_Address_Long);
25744 @end smallexample
25745
25746 @noindent
25747 This means that programs using @code{TO_ADDRESS} for
25748 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
25749
25750 @node Tasking and Task-Related Features
25751 @section Tasking and Task-Related Features
25752
25753 @noindent
25754 This section compares the treatment of tasking in GNAT
25755 and in HP Ada for OpenVMS Alpha.
25756 The GNAT description applies to both Alpha and I64 OpenVMS.
25757 For detailed information on tasking in
25758 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
25759 relevant run-time reference manual.
25760
25761 @menu
25762 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
25763 * Assigning Task IDs::
25764 * Task IDs and Delays::
25765 * Task-Related Pragmas::
25766 * Scheduling and Task Priority::
25767 * The Task Stack::
25768 * External Interrupts::
25769 @end menu
25770
25771 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25772 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
25773
25774 @noindent
25775 On OpenVMS Alpha systems, each Ada task (except a passive
25776 task) is implemented as a single stream of execution
25777 that is created and managed by the kernel. On these
25778 systems, HP Ada tasking support is based on DECthreads,
25779 an implementation of the POSIX standard for threads.
25780
25781 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
25782 code that calls DECthreads routines can be used together.
25783 The interaction between Ada tasks and DECthreads routines
25784 can have some benefits. For example when on OpenVMS Alpha,
25785 HP Ada can call C code that is already threaded.
25786
25787 GNAT uses the facilities of DECthreads,
25788 and Ada tasks are mapped to threads.
25789
25790 @node Assigning Task IDs
25791 @subsection Assigning Task IDs
25792
25793 @noindent
25794 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
25795 the environment task that executes the main program. On
25796 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
25797 that have been created but are not yet activated.
25798
25799 On OpenVMS Alpha systems, task IDs are assigned at
25800 activation. On GNAT systems, task IDs are also assigned at
25801 task creation but do not have the same form or values as
25802 task ID values in HP Ada. There is no null task, and the
25803 environment task does not have a specific task ID value.
25804
25805 @node Task IDs and Delays
25806 @subsection Task IDs and Delays
25807
25808 @noindent
25809 On OpenVMS Alpha systems, tasking delays are implemented
25810 using Timer System Services. The Task ID is used for the
25811 identification of the timer request (the @code{REQIDT} parameter).
25812 If Timers are used in the application take care not to use
25813 @code{0} for the identification, because cancelling such a timer
25814 will cancel all timers and may lead to unpredictable results.
25815
25816 @node Task-Related Pragmas
25817 @subsection Task-Related Pragmas
25818
25819 @noindent
25820 Ada supplies the pragma @code{TASK_STORAGE}, which allows
25821 specification of the size of the guard area for a task
25822 stack. (The guard area forms an area of memory that has no
25823 read or write access and thus helps in the detection of
25824 stack overflow.) On OpenVMS Alpha systems, if the pragma
25825 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
25826 area is created. In the absence of a pragma @code{TASK_STORAGE},
25827 a default guard area is created.
25828
25829 GNAT supplies the following task-related pragmas:
25830
25831 @itemize @bullet
25832 @item  @code{TASK_INFO}
25833
25834 This pragma appears within a task definition and
25835 applies to the task in which it appears. The argument
25836 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
25837
25838 @item  @code{TASK_STORAGE}
25839
25840 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
25841 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
25842 @code{SUPPRESS}, and @code{VOLATILE}.
25843 @end itemize
25844 @node Scheduling and Task Priority
25845 @subsection Scheduling and Task Priority
25846
25847 @noindent
25848 HP Ada implements the Ada language requirement that
25849 when two tasks are eligible for execution and they have
25850 different priorities, the lower priority task does not
25851 execute while the higher priority task is waiting. The HP
25852 Ada Run-Time Library keeps a task running until either the
25853 task is suspended or a higher priority task becomes ready.
25854
25855 On OpenVMS Alpha systems, the default strategy is round-
25856 robin with preemption. Tasks of equal priority take turns
25857 at the processor. A task is run for a certain period of
25858 time and then placed at the tail of the ready queue for
25859 its priority level.
25860
25861 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
25862 which can be used to enable or disable round-robin
25863 scheduling of tasks with the same priority.
25864 See the relevant HP Ada run-time reference manual for
25865 information on using the pragmas to control HP Ada task
25866 scheduling.
25867
25868 GNAT follows the scheduling rules of Annex D (Real-Time
25869 Annex) of the @cite{Ada Reference Manual}. In general, this
25870 scheduling strategy is fully compatible with HP Ada
25871 although it provides some additional constraints (as
25872 fully documented in Annex D).
25873 GNAT implements time slicing control in a manner compatible with
25874 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
25875 are identical to the HP Ada 83 pragma of the same name.
25876 Note that it is not possible to mix GNAT tasking and
25877 HP Ada 83 tasking in the same program, since the two run-time
25878 libraries are not compatible.
25879
25880 @node The Task Stack
25881 @subsection The Task Stack
25882
25883 @noindent
25884 In HP Ada, a task stack is allocated each time a
25885 non-passive task is activated. As soon as the task is
25886 terminated, the storage for the task stack is deallocated.
25887 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
25888 a default stack size is used. Also, regardless of the size
25889 specified, some additional space is allocated for task
25890 management purposes. On OpenVMS Alpha systems, at least
25891 one page is allocated.
25892
25893 GNAT handles task stacks in a similar manner. In accordance with
25894 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
25895 an alternative method for controlling the task stack size.
25896 The specification of the attribute @code{T'STORAGE_SIZE} is also
25897 supported in a manner compatible with HP Ada.
25898
25899 @node External Interrupts
25900 @subsection External Interrupts
25901
25902 @noindent
25903 On HP Ada, external interrupts can be associated with task entries.
25904 GNAT is compatible with HP Ada in its handling of external interrupts.
25905
25906 @node Pragmas and Pragma-Related Features
25907 @section Pragmas and Pragma-Related Features
25908
25909 @noindent
25910 Both HP Ada and GNAT supply all language-defined pragmas
25911 as specified by the Ada 83 standard. GNAT also supplies all
25912 language-defined pragmas introduced by Ada 95 and Ada 2005.
25913 In addition, GNAT implements the implementation-defined pragmas
25914 from HP Ada 83.
25915
25916 @itemize @bullet
25917 @item  @code{AST_ENTRY}
25918
25919 @item  @code{COMMON_OBJECT}
25920
25921 @item  @code{COMPONENT_ALIGNMENT}
25922
25923 @item  @code{EXPORT_EXCEPTION}
25924
25925 @item  @code{EXPORT_FUNCTION}
25926
25927 @item  @code{EXPORT_OBJECT}
25928
25929 @item  @code{EXPORT_PROCEDURE}
25930
25931 @item  @code{EXPORT_VALUED_PROCEDURE}
25932
25933 @item  @code{FLOAT_REPRESENTATION}
25934
25935 @item  @code{IDENT}
25936
25937 @item  @code{IMPORT_EXCEPTION}
25938
25939 @item  @code{IMPORT_FUNCTION}
25940
25941 @item  @code{IMPORT_OBJECT}
25942
25943 @item  @code{IMPORT_PROCEDURE}
25944
25945 @item  @code{IMPORT_VALUED_PROCEDURE}
25946
25947 @item  @code{INLINE_GENERIC}
25948
25949 @item  @code{INTERFACE_NAME}
25950
25951 @item  @code{LONG_FLOAT}
25952
25953 @item  @code{MAIN_STORAGE}
25954
25955 @item  @code{PASSIVE}
25956
25957 @item  @code{PSECT_OBJECT}
25958
25959 @item  @code{SHARE_GENERIC}
25960
25961 @item  @code{SUPPRESS_ALL}
25962
25963 @item  @code{TASK_STORAGE}
25964
25965 @item  @code{TIME_SLICE}
25966
25967 @item  @code{TITLE}
25968 @end itemize
25969
25970 @noindent
25971 These pragmas are all fully implemented, with the exception of @code{TITLE},
25972 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
25973 recognized, but which have no
25974 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
25975 use of Ada protected objects. In GNAT, all generics are inlined.
25976
25977 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
25978 a separate subprogram specification which must appear before the
25979 subprogram body.
25980
25981 GNAT also supplies a number of implementation-defined pragmas as follows:
25982 @itemize @bullet
25983 @item  @code{ABORT_DEFER}
25984
25985 @item  @code{ADA_83}
25986
25987 @item  @code{ADA_95}
25988
25989 @item  @code{ADA_05}
25990
25991 @item  @code{ANNOTATE}
25992
25993 @item  @code{ASSERT}
25994
25995 @item  @code{C_PASS_BY_COPY}
25996
25997 @item  @code{CPP_CLASS}
25998
25999 @item  @code{CPP_CONSTRUCTOR}
26000
26001 @item  @code{CPP_DESTRUCTOR}
26002
26003 @item  @code{DEBUG}
26004
26005 @item  @code{EXTEND_SYSTEM}
26006
26007 @item  @code{LINKER_ALIAS}
26008
26009 @item  @code{LINKER_SECTION}
26010
26011 @item  @code{MACHINE_ATTRIBUTE}
26012
26013 @item  @code{NO_RETURN}
26014
26015 @item  @code{PURE_FUNCTION}
26016
26017 @item  @code{SOURCE_FILE_NAME}
26018
26019 @item  @code{SOURCE_REFERENCE}
26020
26021 @item  @code{TASK_INFO}
26022
26023 @item  @code{UNCHECKED_UNION}
26024
26025 @item  @code{UNIMPLEMENTED_UNIT}
26026
26027 @item  @code{UNIVERSAL_DATA}
26028
26029 @item  @code{UNSUPPRESS}
26030
26031 @item  @code{WARNINGS}
26032
26033 @item  @code{WEAK_EXTERNAL}
26034 @end itemize
26035
26036 @noindent
26037 For full details on these GNAT implementation-defined pragmas,
26038 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
26039 Manual}.
26040
26041 @menu
26042 * Restrictions on the Pragma INLINE::
26043 * Restrictions on the Pragma INTERFACE::
26044 * Restrictions on the Pragma SYSTEM_NAME::
26045 @end menu
26046
26047 @node Restrictions on the Pragma INLINE
26048 @subsection Restrictions on Pragma @code{INLINE}
26049
26050 @noindent
26051 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
26052 @itemize @bullet
26053 @item  Parameters cannot have a task type.
26054
26055 @item  Function results cannot be task types, unconstrained
26056 array types, or unconstrained types with discriminants.
26057
26058 @item  Bodies cannot declare the following:
26059 @itemize @bullet
26060 @item  Subprogram body or stub (imported subprogram is allowed)
26061
26062 @item  Tasks
26063
26064 @item  Generic declarations
26065
26066 @item  Instantiations
26067
26068 @item  Exceptions
26069
26070 @item  Access types (types derived from access types allowed)
26071
26072 @item  Array or record types
26073
26074 @item  Dependent tasks
26075
26076 @item  Direct recursive calls of subprogram or containing
26077 subprogram, directly or via a renaming
26078
26079 @end itemize
26080 @end itemize
26081
26082 @noindent
26083 In GNAT, the only restriction on pragma @code{INLINE} is that the
26084 body must occur before the call if both are in the same
26085 unit, and the size must be appropriately small. There are
26086 no other specific restrictions which cause subprograms to
26087 be incapable of being inlined.
26088
26089 @node  Restrictions on the Pragma INTERFACE
26090 @subsection  Restrictions on Pragma @code{INTERFACE}
26091
26092 @noindent
26093 The following restrictions on pragma @code{INTERFACE}
26094 are enforced by both HP Ada and GNAT:
26095 @itemize @bullet
26096 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
26097 Default is the default on OpenVMS Alpha systems.
26098
26099 @item  Parameter passing: Language specifies default
26100 mechanisms but can be overridden with an @code{EXPORT} pragma.
26101
26102 @itemize @bullet
26103 @item  Ada: Use internal Ada rules.
26104
26105 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
26106 record or task type. Result cannot be a string, an
26107 array, or a record.
26108
26109 @item  Fortran: Parameters cannot have a task type. Result cannot
26110 be a string, an array, or a record.
26111 @end itemize
26112 @end itemize
26113
26114 @noindent
26115 GNAT is entirely upwards compatible with HP Ada, and in addition allows
26116 record parameters for all languages.
26117
26118 @node  Restrictions on the Pragma SYSTEM_NAME
26119 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
26120
26121 @noindent
26122 For HP Ada for OpenVMS Alpha, the enumeration literal
26123 for the type @code{NAME} is @code{OPENVMS_AXP}.
26124 In GNAT, the enumeration
26125 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
26126
26127 @node  Library of Predefined Units
26128 @section  Library of Predefined Units
26129
26130 @noindent
26131 A library of predefined units is provided as part of the
26132 HP Ada and GNAT implementations. HP Ada does not provide
26133 the package @code{MACHINE_CODE} but instead recommends importing
26134 assembler code.
26135
26136 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
26137 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
26138 version.
26139 The HP Ada Predefined Library units are modified to remove post-Ada 83
26140 incompatibilities and to make them interoperable with GNAT
26141 (@pxref{Changes to DECLIB}, for details).
26142 The units are located in the @file{DECLIB} directory.
26143
26144 The GNAT RTL is contained in
26145 the @file{ADALIB} directory, and
26146 the default search path is set up to find @code{DECLIB} units in preference
26147 to @code{ADALIB} units with the same name (@code{TEXT_IO},
26148 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
26149
26150 @menu
26151 * Changes to DECLIB::
26152 @end menu
26153
26154 @node Changes to DECLIB
26155 @subsection Changes to @code{DECLIB}
26156
26157 @noindent
26158 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
26159 compatibility are minor and include the following:
26160
26161 @itemize @bullet
26162 @item  Adjusting the location of pragmas and record representation
26163 clauses to obey Ada 95 (and thus Ada 2005) rules
26164
26165 @item  Adding the proper notation to generic formal parameters
26166 that take unconstrained types in instantiation
26167
26168 @item  Adding pragma @code{ELABORATE_BODY} to package specs
26169 that have package bodies not otherwise allowed
26170
26171 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
26172 ``@code{PROTECTD}''.
26173 Currently these are found only in the @code{STARLET} package spec.
26174
26175 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
26176 where the address size is constrained to 32 bits.
26177 @end itemize
26178
26179 @noindent
26180 None of the above changes is visible to users.
26181
26182 @node Bindings
26183 @section Bindings
26184
26185 @noindent
26186 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
26187 @itemize @bullet
26188
26189 @item  Command Language Interpreter (CLI interface)
26190
26191 @item  DECtalk Run-Time Library (DTK interface)
26192
26193 @item  Librarian utility routines (LBR interface)
26194
26195 @item  General Purpose Run-Time Library (LIB interface)
26196
26197 @item  Math Run-Time Library (MTH interface)
26198
26199 @item  National Character Set Run-Time Library (NCS interface)
26200
26201 @item  Compiled Code Support Run-Time Library (OTS interface)
26202
26203 @item  Parallel Processing Run-Time Library (PPL interface)
26204
26205 @item  Screen Management Run-Time Library (SMG interface)
26206
26207 @item  Sort Run-Time Library (SOR interface)
26208
26209 @item  String Run-Time Library (STR interface)
26210
26211 @item STARLET System Library
26212 @findex Starlet
26213
26214 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
26215
26216 @item  X Windows Toolkit (XT interface)
26217
26218 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
26219 @end itemize
26220
26221 @noindent
26222 GNAT provides implementations of these HP bindings in the @code{DECLIB}
26223 directory, on both the Alpha and I64 OpenVMS platforms.
26224
26225 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
26226 in the
26227 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
26228 A pragma @code{Linker_Options} has been added to packages @code{Xm},
26229 @code{Xt}, and @code{X_Lib}
26230 causing the default X/Motif sharable image libraries to be linked in. This
26231 is done via options files named @file{xm.opt}, @file{xt.opt}, and
26232 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
26233
26234 It may be necessary to edit these options files to update or correct the
26235 library names if, for example, the newer X/Motif bindings from
26236 @file{ADA$EXAMPLES}
26237 had been (previous to installing GNAT) copied and renamed to supersede the
26238 default @file{ADA$PREDEFINED} versions.
26239
26240 @menu
26241 * Shared Libraries and Options Files::
26242 * Interfaces to C::
26243 @end menu
26244
26245 @node Shared Libraries and Options Files
26246 @subsection Shared Libraries and Options Files
26247
26248 @noindent
26249 When using the HP Ada
26250 predefined X and Motif bindings, the linking with their sharable images is
26251 done automatically by @command{GNAT LINK}.
26252 When using other X and Motif bindings, you need
26253 to add the corresponding sharable images to the command line for
26254 @code{GNAT LINK}. When linking with shared libraries, or with
26255 @file{.OPT} files, you must
26256 also add them to the command line for @command{GNAT LINK}.
26257
26258 A shared library to be used with GNAT is built in the same way as other
26259 libraries under VMS. The VMS Link command can be used in standard fashion.
26260
26261 @node Interfaces to C
26262 @subsection Interfaces to C
26263
26264 @noindent
26265 HP Ada
26266 provides the following Ada types and operations:
26267
26268 @itemize @bullet
26269 @item C types package (@code{C_TYPES})
26270
26271 @item C strings (@code{C_TYPES.NULL_TERMINATED})
26272
26273 @item Other_types (@code{SHORT_INT})
26274 @end itemize
26275
26276 @noindent
26277 Interfacing to C with GNAT, you can use the above approach
26278 described for HP Ada or the facilities of Annex B of
26279 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
26280 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
26281 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
26282
26283 The @option{-gnatF} qualifier forces default and explicit
26284 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
26285 to be uppercased for compatibility with the default behavior
26286 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
26287
26288 @node Main Program Definition
26289 @section Main Program Definition
26290
26291 @noindent
26292 The following section discusses differences in the
26293 definition of main programs on HP Ada and GNAT.
26294 On HP Ada, main programs are defined to meet the
26295 following conditions:
26296 @itemize @bullet
26297 @item  Procedure with no formal parameters (returns @code{0} upon
26298 normal completion)
26299
26300 @item  Procedure with no formal parameters (returns @code{42} when
26301 an unhandled exception is raised)
26302
26303 @item  Function with no formal parameters whose returned value
26304 is of a discrete type
26305
26306 @item  Procedure with one @code{out} formal of a discrete type for
26307 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
26308
26309 @end itemize
26310
26311 @noindent
26312 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
26313 a main function or main procedure returns a discrete
26314 value whose size is less than 64 bits (32 on VAX systems),
26315 the value is zero- or sign-extended as appropriate.
26316 On GNAT, main programs are defined as follows:
26317 @itemize @bullet
26318 @item  Must be a non-generic, parameterless subprogram that
26319 is either a procedure or function returning an Ada
26320 @code{STANDARD.INTEGER} (the predefined type)
26321
26322 @item  Cannot be a generic subprogram or an instantiation of a
26323 generic subprogram
26324 @end itemize
26325
26326 @node Implementation-Defined Attributes
26327 @section Implementation-Defined Attributes
26328
26329 @noindent
26330 GNAT provides all HP Ada implementation-defined
26331 attributes.
26332
26333 @node Compiler and Run-Time Interfacing
26334 @section Compiler and Run-Time Interfacing
26335
26336 @noindent
26337 HP Ada provides the following qualifiers to pass options to the linker
26338 (ACS LINK):
26339 @itemize @bullet
26340 @item  @option{/WAIT} and @option{/SUBMIT}
26341
26342 @item  @option{/COMMAND}
26343
26344 @item  @option{/@r{[}NO@r{]}MAP}
26345
26346 @item  @option{/OUTPUT=@var{file-spec}}
26347
26348 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
26349 @end itemize
26350
26351 @noindent
26352 To pass options to the linker, GNAT provides the following
26353 switches:
26354
26355 @itemize @bullet
26356 @item   @option{/EXECUTABLE=@var{exec-name}}
26357
26358 @item   @option{/VERBOSE}
26359
26360 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
26361 @end itemize
26362
26363 @noindent
26364 For more information on these switches, see
26365 @ref{Switches for gnatlink}.
26366 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
26367 to control optimization. HP Ada also supplies the
26368 following pragmas:
26369 @itemize @bullet
26370 @item  @code{OPTIMIZE}
26371
26372 @item  @code{INLINE}
26373
26374 @item  @code{INLINE_GENERIC}
26375
26376 @item  @code{SUPPRESS_ALL}
26377
26378 @item  @code{PASSIVE}
26379 @end itemize
26380
26381 @noindent
26382 In GNAT, optimization is controlled strictly by command
26383 line parameters, as described in the corresponding section of this guide.
26384 The HP pragmas for control of optimization are
26385 recognized but ignored.
26386
26387 Note that in GNAT, the default is optimization off, whereas in HP Ada
26388 the default is that optimization is turned on.
26389
26390 @node Program Compilation and Library Management
26391 @section Program Compilation and Library Management
26392
26393 @noindent
26394 HP Ada and GNAT provide a comparable set of commands to
26395 build programs. HP Ada also provides a program library,
26396 which is a concept that does not exist on GNAT. Instead,
26397 GNAT provides directories of sources that are compiled as
26398 needed.
26399
26400 The following table summarizes
26401 the HP Ada commands and provides
26402 equivalent GNAT commands. In this table, some GNAT
26403 equivalents reflect the fact that GNAT does not use the
26404 concept of a program library. Instead, it uses a model
26405 in which collections of source and object files are used
26406 in a manner consistent with other languages like C and
26407 Fortran. Therefore, standard system file commands are used
26408 to manipulate these elements. Those GNAT commands are marked with
26409 an asterisk.
26410 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
26411
26412 @need 1500
26413 @multitable @columnfractions .35 .65
26414
26415 @item @emph{HP Ada Command}
26416 @tab @emph{GNAT Equivalent / Description}
26417
26418 @item @command{ADA}
26419 @tab @command{GNAT COMPILE}@*
26420 Invokes the compiler to compile one or more Ada source files.
26421
26422 @item @command{ACS ATTACH}@*
26423 @tab [No equivalent]@*
26424 Switches control of terminal from current process running the program
26425 library manager.
26426
26427 @item @command{ACS CHECK}
26428 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
26429 Forms the execution closure of one
26430 or more compiled units and checks completeness and currency.
26431
26432 @item @command{ACS COMPILE}
26433 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
26434 Forms the execution closure of one or
26435 more specified units, checks completeness and currency,
26436 identifies units that have revised source files, compiles same,
26437 and recompiles units that are or will become obsolete.
26438 Also completes incomplete generic instantiations.
26439
26440 @item @command{ACS COPY FOREIGN}
26441 @tab Copy (*)@*
26442 Copies a foreign object file into the program library as a
26443 library unit body.
26444
26445 @item @command{ACS COPY UNIT}
26446 @tab Copy (*)@*
26447 Copies a compiled unit from one program library to another.
26448
26449 @item @command{ACS CREATE LIBRARY}
26450 @tab Create /directory (*)@*
26451 Creates a program library.
26452
26453 @item @command{ACS CREATE SUBLIBRARY}
26454 @tab Create /directory (*)@*
26455 Creates a program sublibrary.
26456
26457 @item @command{ACS DELETE LIBRARY}
26458 @tab @*
26459 Deletes a program library and its contents.
26460
26461 @item @command{ACS DELETE SUBLIBRARY}
26462 @tab @*
26463 Deletes a program sublibrary and its contents.
26464
26465 @item @command{ACS DELETE UNIT}
26466 @tab Delete file (*)@*
26467 On OpenVMS systems, deletes one or more compiled units from
26468 the current program library.
26469
26470 @item @command{ACS DIRECTORY}
26471 @tab Directory (*)@*
26472 On OpenVMS systems, lists units contained in the current
26473 program library.
26474
26475 @item @command{ACS ENTER FOREIGN}
26476 @tab Copy (*)@*
26477 Allows the import of a foreign body as an Ada library
26478 spec and enters a reference to a pointer.
26479
26480 @item @command{ACS ENTER UNIT}
26481 @tab Copy (*)@*
26482 Enters a reference (pointer) from the current program library to
26483 a unit compiled into another program library.
26484
26485 @item @command{ACS EXIT}
26486 @tab [No equivalent]@*
26487 Exits from the program library manager.
26488
26489 @item @command{ACS EXPORT}
26490 @tab Copy (*)@*
26491 Creates an object file that contains system-specific object code
26492 for one or more units. With GNAT, object files can simply be copied
26493 into the desired directory.
26494
26495 @item @command{ACS EXTRACT SOURCE}
26496 @tab Copy (*)@*
26497 Allows access to the copied source file for each Ada compilation unit
26498
26499 @item @command{ACS HELP}
26500 @tab @command{HELP GNAT}@*
26501 Provides online help.
26502
26503 @item @command{ACS LINK}
26504 @tab @command{GNAT LINK}@*
26505 Links an object file containing Ada units into an executable file.
26506
26507 @item @command{ACS LOAD}
26508 @tab Copy (*)@*
26509 Loads (partially compiles) Ada units into the program library.
26510 Allows loading a program from a collection of files into a library
26511 without knowing the relationship among units.
26512
26513 @item @command{ACS MERGE}
26514 @tab Copy (*)@*
26515 Merges into the current program library, one or more units from
26516 another library where they were modified.
26517
26518 @item @command{ACS RECOMPILE}
26519 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
26520 Recompiles from   external or copied source files any obsolete
26521 unit in the closure. Also, completes any incomplete generic
26522 instantiations.
26523
26524 @item @command{ACS REENTER}
26525 @tab @command{GNAT MAKE}@*
26526 Reenters current references to units compiled after last entered
26527 with the @command{ACS ENTER UNIT} command.
26528
26529 @item @command{ACS SET LIBRARY}
26530 @tab Set default (*)@*
26531 Defines a program library to be the compilation context as well
26532 as the target library for compiler output and commands in general.
26533
26534 @item @command{ACS SET PRAGMA}
26535 @tab Edit @file{gnat.adc} (*)@*
26536 Redefines specified  values of the library characteristics
26537 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
26538 and @code{Float_Representation}.
26539
26540 @item @command{ACS SET SOURCE}
26541 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
26542 Defines the source file search list for the @command{ACS COMPILE} command.
26543
26544 @item @command{ACS SHOW LIBRARY}
26545 @tab Directory (*)@*
26546 Lists information about one or more program libraries.
26547
26548 @item @command{ACS SHOW PROGRAM}
26549 @tab [No equivalent]@*
26550 Lists information about the execution closure of one or
26551 more units in the program library.
26552
26553 @item @command{ACS SHOW SOURCE}
26554 @tab Show logical @code{ADA_INCLUDE_PATH}@*
26555 Shows the source file search used when compiling units.
26556
26557 @item @command{ACS SHOW VERSION}
26558 @tab Compile with @option{VERBOSE} option
26559 Displays the version number of the compiler and program library
26560 manager used.
26561
26562 @item @command{ACS SPAWN}
26563 @tab [No equivalent]@*
26564 Creates a subprocess of the current process (same as @command{DCL SPAWN}
26565 command).
26566
26567 @item @command{ACS VERIFY}
26568 @tab [No equivalent]@*
26569 Performs a series of consistency checks on a program library to
26570 determine whether the library structure and library files are in
26571 valid form.
26572 @end multitable
26573
26574 @noindent
26575
26576 @node Input-Output
26577 @section Input-Output
26578
26579 @noindent
26580 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
26581 Management Services (RMS) to perform operations on
26582 external files.
26583
26584 @noindent
26585 HP Ada and GNAT predefine an identical set of input-
26586 output packages. To make the use of the
26587 generic @code{TEXT_IO} operations more convenient, HP Ada
26588 provides predefined library packages that instantiate the
26589 integer and floating-point operations for the predefined
26590 integer and floating-point types as shown in the following table.
26591
26592 @multitable @columnfractions .45 .55
26593 @item @emph{Package Name} @tab Instantiation
26594
26595 @item @code{INTEGER_TEXT_IO}
26596 @tab @code{INTEGER_IO(INTEGER)}
26597
26598 @item @code{SHORT_INTEGER_TEXT_IO}
26599 @tab @code{INTEGER_IO(SHORT_INTEGER)}
26600
26601 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
26602 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
26603
26604 @item @code{FLOAT_TEXT_IO}
26605 @tab @code{FLOAT_IO(FLOAT)}
26606
26607 @item @code{LONG_FLOAT_TEXT_IO}
26608 @tab @code{FLOAT_IO(LONG_FLOAT)}
26609 @end multitable
26610
26611 @noindent
26612 The HP Ada predefined packages and their operations
26613 are implemented using OpenVMS Alpha files and input-output
26614 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
26615 Familiarity with the following is recommended:
26616 @itemize @bullet
26617 @item  RMS file organizations and access methods
26618
26619 @item  OpenVMS file specifications and directories
26620
26621 @item  OpenVMS File Definition Language (FDL)
26622 @end itemize
26623
26624 @noindent
26625 GNAT provides I/O facilities that are completely
26626 compatible with HP Ada. The distribution includes the
26627 standard HP Ada versions of all I/O packages, operating
26628 in a manner compatible with HP Ada. In particular, the
26629 following packages are by default the HP Ada (Ada 83)
26630 versions of these packages rather than the renamings
26631 suggested in Annex J of the Ada Reference Manual:
26632 @itemize @bullet
26633 @item  @code{TEXT_IO}
26634
26635 @item  @code{SEQUENTIAL_IO}
26636
26637 @item  @code{DIRECT_IO}
26638 @end itemize
26639
26640 @noindent
26641 The use of the standard child package syntax (for
26642 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
26643 packages.
26644 GNAT provides HP-compatible predefined instantiations
26645 of the @code{TEXT_IO} packages, and also
26646 provides the standard predefined instantiations required
26647 by the @cite{Ada Reference Manual}.
26648
26649 For further information on how GNAT interfaces to the file
26650 system or how I/O is implemented in programs written in
26651 mixed languages, see @ref{Implementation of the Standard I/O,,,
26652 gnat_rm, GNAT Reference Manual}.
26653 This chapter covers the following:
26654 @itemize @bullet
26655 @item  Standard I/O packages
26656
26657 @item  @code{FORM} strings
26658
26659 @item  @code{ADA.DIRECT_IO}
26660
26661 @item  @code{ADA.SEQUENTIAL_IO}
26662
26663 @item  @code{ADA.TEXT_IO}
26664
26665 @item  Stream pointer positioning
26666
26667 @item  Reading and writing non-regular files
26668
26669 @item  @code{GET_IMMEDIATE}
26670
26671 @item  Treating @code{TEXT_IO} files as streams
26672
26673 @item  Shared files
26674
26675 @item  Open modes
26676 @end itemize
26677
26678 @node Implementation Limits
26679 @section Implementation Limits
26680
26681 @noindent
26682 The following table lists implementation limits for HP Ada
26683 and GNAT systems.
26684 @multitable @columnfractions .60 .20 .20
26685 @sp 1
26686 @item  @emph{Compilation Parameter}
26687 @tab   @emph{HP Ada}
26688 @tab   @emph{GNAT}
26689 @sp 1
26690
26691 @item  In a subprogram or entry  declaration, maximum number of
26692 formal parameters that are of an unconstrained record type
26693 @tab   32
26694 @tab   No set limit
26695 @sp 1
26696
26697 @item  Maximum identifier length (number of characters)
26698 @tab   255
26699 @tab   32766
26700 @sp 1
26701
26702 @item  Maximum number of characters in a source line
26703 @tab   255
26704 @tab   32766
26705 @sp 1
26706
26707 @item  Maximum collection size   (number of bytes)
26708 @tab   2**31-1
26709 @tab   2**31-1
26710 @sp 1
26711
26712 @item  Maximum number of discriminants for a record type
26713 @tab   245
26714 @tab   No set limit
26715 @sp 1
26716
26717 @item  Maximum number of formal parameters in an entry or
26718 subprogram declaration
26719 @tab   246
26720 @tab    No set limit
26721 @sp 1
26722
26723 @item  Maximum number of dimensions in an array type
26724 @tab   255
26725 @tab   No set limit
26726 @sp 1
26727
26728 @item  Maximum number of library  units and subunits in a compilation.
26729 @tab   4095
26730 @tab   No set limit
26731 @sp 1
26732
26733 @item  Maximum number of library units and subunits in an execution.
26734 @tab   16383
26735 @tab   No set limit
26736 @sp 1
26737
26738 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
26739 or @code{PSECT_OBJECT}
26740 @tab   32757
26741 @tab   No set limit
26742 @sp 1
26743
26744 @item  Maximum number of enumeration literals in an enumeration type
26745 definition
26746 @tab   65535
26747 @tab   No set limit
26748 @sp 1
26749
26750 @item  Maximum number of lines in a source file
26751 @tab   65534
26752 @tab   No set limit
26753 @sp 1
26754
26755 @item  Maximum number of bits in any object
26756 @tab   2**31-1
26757 @tab   2**31-1
26758 @sp 1
26759
26760 @item  Maximum size of the static portion of a stack frame (approximate)
26761 @tab   2**31-1
26762 @tab   2**31-1
26763 @end multitable
26764
26765 @node Tools and Utilities
26766 @section Tools and Utilities
26767
26768 @noindent
26769 The following table lists some of the OpenVMS development tools
26770 available for HP Ada, and the corresponding tools for
26771 use with @value{EDITION} on Alpha and I64 platforms.
26772 Aside from the debugger, all the OpenVMS tools identified are part
26773 of the DECset package.
26774
26775 @iftex
26776 @c Specify table in TeX since Texinfo does a poor job
26777 @tex
26778 \smallskip
26779 \smallskip
26780 \settabs\+Language-Sensitive Editor\quad
26781    &Product with HP Ada\quad
26782    &\cr
26783 \+\it Tool
26784    &\it Product with HP Ada
26785    & \it Product with GNAT Pro\cr
26786 \smallskip
26787 \+Code Management System
26788    &HP CMS
26789    & HP CMS\cr
26790 \smallskip
26791 \+Language-Sensitive Editor
26792    &HP LSE
26793    & emacs or HP LSE (Alpha)\cr
26794 \+
26795    &
26796    & HP LSE (I64)\cr
26797 \smallskip
26798 \+Debugger
26799    &OpenVMS Debug
26800    & gdb (Alpha),\cr
26801 \+
26802    &
26803    & OpenVMS Debug (I64)\cr
26804 \smallskip
26805 \+Source Code Analyzer /
26806    &HP SCA
26807    & GNAT XREF\cr
26808 \+Cross Referencer
26809    &
26810    &\cr
26811 \smallskip
26812 \+Test Manager
26813    &HP Digital Test
26814    & HP DTM\cr
26815 \+
26816    &Manager (DTM)
26817    &\cr
26818 \smallskip
26819 \+Performance and
26820    & HP PCA
26821    & HP PCA\cr
26822 \+Coverage Analyzer
26823    &
26824    &\cr
26825 \smallskip
26826 \+Module Management
26827    & HP MMS
26828    & Not applicable\cr
26829 \+ System
26830    &
26831    &\cr
26832 \smallskip
26833 \smallskip
26834 @end tex
26835 @end iftex
26836
26837 @ifnottex
26838 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
26839 @c the TeX version above for the printed version
26840 @flushleft
26841 @c @multitable @columnfractions .3 .4 .4
26842 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with GNAT Pro}
26843 @item @i{Tool}
26844 @tab @i{Tool with HP Ada}
26845 @tab @i{Tool with @value{EDITION}}
26846 @item Code Management@*System
26847 @tab HP CMS
26848 @tab HP CMS
26849 @item Language-Sensitive@*Editor
26850 @tab HP LSE
26851 @tab emacs or HP LSE (Alpha)
26852 @item
26853 @tab
26854 @tab HP LSE (I64)
26855 @item Debugger
26856 @tab OpenVMS Debug
26857 @tab gdb (Alpha),
26858 @item
26859 @tab
26860 @tab OpenVMS Debug (I64)
26861 @item Source Code Analyzer /@*Cross Referencer
26862 @tab HP SCA
26863 @tab GNAT XREF
26864 @item Test Manager
26865 @tab HP Digital Test@*Manager (DTM)
26866 @tab HP DTM
26867 @item Performance and@*Coverage Analyzer
26868 @tab HP PCA
26869 @tab HP PCA
26870 @item Module Management@*System
26871 @tab HP MMS
26872 @tab Not applicable
26873 @end multitable
26874 @end flushleft
26875 @end ifnottex
26876
26877 @end ifset
26878
26879 @c **************************************
26880 @node Platform-Specific Information for the Run-Time Libraries
26881 @appendix Platform-Specific Information for the Run-Time Libraries
26882 @cindex Tasking and threads libraries
26883 @cindex Threads libraries and tasking
26884 @cindex Run-time libraries (platform-specific information)
26885
26886 @noindent
26887 The GNAT run-time implementation may vary with respect to both the
26888 underlying threads library and the exception handling scheme.
26889 For threads support, one or more of the following are supplied:
26890 @itemize @bullet
26891 @item @b{native threads library}, a binding to the thread package from
26892 the underlying operating system
26893
26894 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
26895 POSIX thread package
26896 @end itemize
26897
26898 @noindent
26899 For exception handling, either or both of two models are supplied:
26900 @itemize @bullet
26901 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
26902 Most programs should experience a substantial speed improvement by
26903 being compiled with a ZCX run-time.
26904 This is especially true for
26905 tasking applications or applications with many exception handlers.}
26906 @cindex Zero-Cost Exceptions
26907 @cindex ZCX (Zero-Cost Exceptions)
26908 which uses binder-generated tables that
26909 are interrogated at run time to locate a handler
26910
26911 @item @b{setjmp / longjmp} (``SJLJ''),
26912 @cindex setjmp/longjmp Exception Model
26913 @cindex SJLJ (setjmp/longjmp Exception Model)
26914 which uses dynamically-set data to establish
26915 the set of handlers
26916 @end itemize
26917
26918 @noindent
26919 This appendix summarizes which combinations of threads and exception support
26920 are supplied on various GNAT platforms.
26921 It then shows how to select a particular library either
26922 permanently or temporarily,
26923 explains the properties of (and tradeoffs among) the various threads
26924 libraries, and provides some additional
26925 information about several specific platforms.
26926
26927 @menu
26928 * Summary of Run-Time Configurations::
26929 * Specifying a Run-Time Library::
26930 * Choosing the Scheduling Policy::
26931 * Solaris-Specific Considerations::
26932 * Linux-Specific Considerations::
26933 * AIX-Specific Considerations::
26934 * Irix-Specific Considerations::
26935 * RTX-Specific Considerations::
26936 * HP-UX-Specific Considerations::
26937 @end menu
26938
26939 @node Summary of Run-Time Configurations
26940 @section Summary of Run-Time Configurations
26941
26942 @multitable @columnfractions .30 .70
26943 @item @b{alpha-openvms}
26944 @item @code{@ @ }@i{rts-native (default)}
26945 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26946 @item @code{@ @ @ @ }Exceptions @tab ZCX
26947 @*
26948 @item @b{alpha-tru64}
26949 @item @code{@ @ }@i{rts-native (default)}
26950 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26951 @item @code{@ @ @ @ }Exceptions @tab ZCX
26952 @*
26953 @item @code{@ @ }@i{rts-sjlj}
26954 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
26955 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26956 @*
26957 @item @b{ia64-hp_linux}
26958 @item @code{@ @ }@i{rts-native (default)}
26959 @item @code{@ @ @ @ }Tasking    @tab pthread library
26960 @item @code{@ @ @ @ }Exceptions @tab ZCX
26961 @*
26962 @item @b{ia64-hpux}
26963 @item @code{@ @ }@i{rts-native (default)}
26964 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26965 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26966 @*
26967 @item @b{ia64-openvms}
26968 @item @code{@ @ }@i{rts-native (default)}
26969 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
26970 @item @code{@ @ @ @ }Exceptions @tab ZCX
26971 @*
26972 @item @b{ia64-sgi_linux}
26973 @item @code{@ @ }@i{rts-native (default)}
26974 @item @code{@ @ @ @ }Tasking    @tab pthread library
26975 @item @code{@ @ @ @ }Exceptions @tab ZCX
26976 @*
26977 @item @b{mips-irix}
26978 @item @code{@ @ }@i{rts-native (default)}
26979 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
26980 @item @code{@ @ @ @ }Exceptions @tab ZCX
26981 @*
26982 @item @b{pa-hpux}
26983 @item @code{@ @ }@i{rts-native (default)}
26984 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26985 @item @code{@ @ @ @ }Exceptions @tab ZCX
26986 @*
26987 @item @code{@ @ }@i{rts-sjlj}
26988 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
26989 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26990 @*
26991 @item @b{ppc-aix}
26992 @item @code{@ @ }@i{rts-native (default)}
26993 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
26994 @item @code{@ @ @ @ }Exceptions @tab SJLJ
26995 @*
26996 @item @b{ppc-darwin}
26997 @item @code{@ @ }@i{rts-native (default)}
26998 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
26999 @item @code{@ @ @ @ }Exceptions @tab ZCX
27000 @*
27001 @item @b{sparc-solaris}  @tab
27002 @item @code{@ @ }@i{rts-native (default)}
27003 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
27004 @item @code{@ @ @ @ }Exceptions @tab ZCX
27005 @*
27006 @item @code{@ @ }@i{rts-pthread}
27007 @item @code{@ @ @ @ }Tasking    @tab pthread library
27008 @item @code{@ @ @ @ }Exceptions @tab ZCX
27009 @*
27010 @item @code{@ @ }@i{rts-sjlj}
27011 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
27012 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27013 @*
27014 @item @b{sparc64-solaris}  @tab
27015 @item @code{@ @ }@i{rts-native (default)}
27016 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
27017 @item @code{@ @ @ @ }Exceptions @tab ZCX
27018 @*
27019 @item @b{x86-linux}
27020 @item @code{@ @ }@i{rts-native (default)}
27021 @item @code{@ @ @ @ }Tasking    @tab pthread library
27022 @item @code{@ @ @ @ }Exceptions @tab ZCX
27023 @*
27024 @item @code{@ @ }@i{rts-sjlj}
27025 @item @code{@ @ @ @ }Tasking    @tab pthread library
27026 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27027 @*
27028 @item @b{x86-lynx}
27029 @item @code{@ @ }@i{rts-native (default)}
27030 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
27031 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27032 @*
27033 @item @b{x86-solaris}
27034 @item @code{@ @ }@i{rts-native (default)}
27035 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
27036 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27037 @*
27038 @item @b{x86-windows}
27039 @item @code{@ @ }@i{rts-native (default)}
27040 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
27041 @item @code{@ @ @ @ }Exceptions @tab ZCX
27042 @*
27043 @item @code{@ @ }@i{rts-sjlj (default)}
27044 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
27045 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27046 @*
27047 @item @b{x86-windows-rtx}
27048 @item @code{@ @ }@i{rts-rtx-rtss (default)}
27049 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
27050 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27051 @*
27052 @item @code{@ @ }@i{rts-rtx-w32}
27053 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
27054 @item @code{@ @ @ @ }Exceptions @tab ZCX
27055 @*
27056 @item @b{x86_64-linux}
27057 @item @code{@ @ }@i{rts-native (default)}
27058 @item @code{@ @ @ @ }Tasking    @tab pthread library
27059 @item @code{@ @ @ @ }Exceptions @tab ZCX
27060 @*
27061 @item @code{@ @ }@i{rts-sjlj}
27062 @item @code{@ @ @ @ }Tasking    @tab pthread library
27063 @item @code{@ @ @ @ }Exceptions @tab SJLJ
27064 @*
27065 @end multitable
27066
27067 @node Specifying a Run-Time Library
27068 @section Specifying a Run-Time Library
27069
27070 @noindent
27071 The @file{adainclude} subdirectory containing the sources of the GNAT
27072 run-time library, and the @file{adalib} subdirectory containing the
27073 @file{ALI} files and the static and/or shared GNAT library, are located
27074 in the gcc target-dependent area:
27075
27076 @smallexample
27077 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
27078 @end smallexample
27079
27080 @noindent
27081 As indicated above, on some platforms several run-time libraries are supplied.
27082 These libraries are installed in the target dependent area and
27083 contain a complete source and binary subdirectory. The detailed description
27084 below explains the differences between the different libraries in terms of
27085 their thread support.
27086
27087 The default run-time library (when GNAT is installed) is @emph{rts-native}.
27088 This default run time is selected by the means of soft links.
27089 For example on x86-linux:
27090
27091 @smallexample
27092 @group
27093  $(target-dir)
27094      |
27095      +--- adainclude----------+
27096      |                        |
27097      +--- adalib-----------+  |
27098      |                     |  |
27099      +--- rts-native       |  |
27100      |    |                |  |
27101      |    +--- adainclude <---+
27102      |    |                |
27103      |    +--- adalib <----+
27104      |
27105      +--- rts-sjlj
27106           |
27107           +--- adainclude
27108           |
27109           +--- adalib
27110 @end group
27111 @end smallexample
27112
27113 @noindent
27114 If the @i{rts-sjlj} library is to be selected on a permanent basis,
27115 these soft links can be modified with the following commands:
27116
27117 @smallexample
27118 $ cd $target
27119 $ rm -f adainclude adalib
27120 $ ln -s rts-sjlj/adainclude adainclude
27121 $ ln -s rts-sjlj/adalib adalib
27122 @end smallexample
27123
27124 @noindent
27125 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
27126 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
27127 @file{$target/ada_object_path}.
27128
27129 Selecting another run-time library temporarily can be
27130 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
27131 @cindex @option{--RTS} option
27132
27133 @node Choosing the Scheduling Policy
27134 @section Choosing the Scheduling Policy
27135
27136 @noindent
27137 When using a POSIX threads implementation, you have a choice of several
27138 scheduling policies: @code{SCHED_FIFO},
27139 @cindex @code{SCHED_FIFO} scheduling policy
27140 @code{SCHED_RR}
27141 @cindex @code{SCHED_RR} scheduling policy
27142 and @code{SCHED_OTHER}.
27143 @cindex @code{SCHED_OTHER} scheduling policy
27144 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
27145 or @code{SCHED_RR} requires special (e.g., root) privileges.
27146
27147 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
27148 @code{SCHED_FIFO},
27149 @cindex @code{SCHED_FIFO} scheduling policy
27150 you can use one of the following:
27151
27152 @itemize @bullet
27153 @item
27154 @code{pragma Time_Slice (0.0)}
27155 @cindex pragma Time_Slice
27156 @item
27157 the corresponding binder option @option{-T0}
27158 @cindex @option{-T0} option
27159 @item
27160 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
27161 @cindex pragma Task_Dispatching_Policy
27162 @end itemize
27163
27164 @noindent
27165 To specify @code{SCHED_RR},
27166 @cindex @code{SCHED_RR} scheduling policy
27167 you should use @code{pragma Time_Slice} with a
27168 value greater than @code{0.0}, or else use the corresponding @option{-T}
27169 binder option.
27170
27171 @node Solaris-Specific Considerations
27172 @section Solaris-Specific Considerations
27173 @cindex Solaris Sparc threads libraries
27174
27175 @noindent
27176 This section addresses some topics related to the various threads libraries
27177 on Sparc Solaris.
27178
27179 @menu
27180 * Solaris Threads Issues::
27181 @end menu
27182
27183 @node Solaris Threads Issues
27184 @subsection Solaris Threads Issues
27185
27186 @noindent
27187 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
27188 library based on POSIX threads --- @emph{rts-pthread}.
27189 @cindex rts-pthread threads library
27190 This run-time library has the advantage of being mostly shared across all
27191 POSIX-compliant thread implementations, and it also provides under
27192 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
27193 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
27194 and @code{PTHREAD_PRIO_PROTECT}
27195 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
27196 semantics that can be selected using the predefined pragma
27197 @code{Locking_Policy}
27198 @cindex pragma Locking_Policy (under rts-pthread)
27199 with respectively
27200 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
27201 @cindex @code{Inheritance_Locking} (under rts-pthread)
27202 @cindex @code{Ceiling_Locking} (under rts-pthread)
27203
27204 As explained above, the native run-time library is based on the Solaris thread
27205 library (@code{libthread}) and is the default library.
27206
27207 When the Solaris threads library is used (this is the default), programs
27208 compiled with GNAT can automatically take advantage of
27209 and can thus execute on multiple processors.
27210 The user can alternatively specify a processor on which the program should run
27211 to emulate a single-processor system. The multiprocessor / uniprocessor choice
27212 is made by
27213 setting the environment variable @env{GNAT_PROCESSOR}
27214 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
27215 to one of the following:
27216
27217 @table @code
27218 @item -2
27219 Use the default configuration (run the program on all
27220 available processors) - this is the same as having @code{GNAT_PROCESSOR}
27221 unset
27222
27223 @item -1
27224 Let the run-time implementation choose one processor and run the program on
27225 that processor
27226
27227 @item 0 .. Last_Proc
27228 Run the program on the specified processor.
27229 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
27230 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
27231 @end table
27232
27233 @node Linux-Specific Considerations
27234 @section Linux-Specific Considerations
27235 @cindex Linux threads libraries
27236
27237 @noindent
27238 On GNU/Linux without NPTL support (usually system with GNU C Library
27239 older than 2.3), the signal model is not POSIX compliant, which means
27240 that to send a signal to the process, you need to send the signal to all
27241 threads, e.g.@: by using @code{killpg()}.
27242
27243 @node AIX-Specific Considerations
27244 @section AIX-Specific Considerations
27245 @cindex AIX resolver library
27246
27247 @noindent
27248 On AIX, the resolver library initializes some internal structure on
27249 the first call to @code{get*by*} functions, which are used to implement
27250 @code{GNAT.Sockets.Get_Host_By_Name} and
27251 @code{GNAT.Sockets.Get_Host_By_Address}.
27252 If such initialization occurs within an Ada task, and the stack size for
27253 the task is the default size, a stack overflow may occur.
27254
27255 To avoid this overflow, the user should either ensure that the first call
27256 to @code{GNAT.Sockets.Get_Host_By_Name} or
27257 @code{GNAT.Sockets.Get_Host_By_Addrss}
27258 occurs in the environment task, or use @code{pragma Storage_Size} to
27259 specify a sufficiently large size for the stack of the task that contains
27260 this call.
27261
27262 @node Irix-Specific Considerations
27263 @section Irix-Specific Considerations
27264 @cindex Irix libraries
27265
27266 @noindent
27267 The GCC support libraries coming with the Irix compiler have moved to
27268 their canonical place with respect to the general Irix ABI related
27269 conventions. Running applications built with the default shared GNAT
27270 run-time now requires the LD_LIBRARY_PATH environment variable to
27271 include this location. A possible way to achieve this is to issue the
27272 following command line on a bash prompt:
27273
27274 @smallexample
27275 @group
27276 $  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`dirname \`gcc --print-file-name=libgcc_s.so\``
27277 @end group
27278 @end smallexample
27279
27280 @node RTX-Specific Considerations
27281 @section RTX-Specific Considerations
27282 @cindex RTX libraries
27283
27284 @noindent
27285 The Real-time Extension (RTX) to Windows is based on the Windows Win32
27286 API. Applications can be built to work in two different modes:
27287
27288 @itemize @bullet
27289 @item
27290 Windows executables that run in Ring 3 to utilize memory protection
27291 (@emph{rts-rtx-w32}).
27292
27293 @item
27294 Real-time subsystem (RTSS) executables that run in Ring 0, where
27295 performance can be optimized with RTSS applications taking precedent
27296 over all Windows applications (@emph{rts-rtx-rtss}).
27297
27298 @end itemize
27299
27300 @node HP-UX-Specific Considerations
27301 @section HP-UX-Specific Considerations
27302 @cindex HP-UX Scheduling
27303
27304 @noindent
27305 On HP-UX, appropriate privileges are required to change the scheduling
27306 parameters of a task. The calling process must have appropriate
27307 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
27308 successfully change the scheduling parameters.
27309
27310 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
27311 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
27312 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
27313
27314 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
27315 one of the following:
27316
27317 @itemize @bullet
27318 @item
27319 @code{pragma Time_Slice (0.0)}
27320 @cindex pragma Time_Slice
27321 @item
27322 the corresponding binder option @option{-T0}
27323 @cindex @option{-T0} option
27324 @item
27325 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
27326 @cindex pragma Task_Dispatching_Policy
27327 @end itemize
27328
27329 @noindent
27330 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
27331 you should use @code{pragma Time_Slice} with a
27332 value greater than @code{0.0}, or use the corresponding @option{-T}
27333 binder option, or set the @code{pragma Task_Dispatching_Policy
27334 (Round_Robin_Within_Priorities)}.
27335
27336 @c *******************************
27337 @node Example of Binder Output File
27338 @appendix Example of Binder Output File
27339
27340 @noindent
27341 This Appendix displays the source code for @command{gnatbind}'s output
27342 file generated for a simple ``Hello World'' program.
27343 Comments have been added for clarification purposes.
27344
27345 @smallexample @c adanocomment
27346 @iftex
27347 @leftskip=0cm
27348 @end iftex
27349 --  The package is called Ada_Main unless this name is actually used
27350 --  as a unit name in the partition, in which case some other unique
27351 --  name is used.
27352
27353 with System;
27354 package ada_main is
27355
27356    Elab_Final_Code : Integer;
27357    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
27358
27359    --  The main program saves the parameters (argument count,
27360    --  argument values, environment pointer) in global variables
27361    --  for later access by other units including
27362    --  Ada.Command_Line.
27363
27364    gnat_argc : Integer;
27365    gnat_argv : System.Address;
27366    gnat_envp : System.Address;
27367
27368    --  The actual variables are stored in a library routine. This
27369    --  is useful for some shared library situations, where there
27370    --  are problems if variables are not in the library.
27371
27372    pragma Import (C, gnat_argc);
27373    pragma Import (C, gnat_argv);
27374    pragma Import (C, gnat_envp);
27375
27376    --  The exit status is similarly an external location
27377
27378    gnat_exit_status : Integer;
27379    pragma Import (C, gnat_exit_status);
27380
27381    GNAT_Version : constant String :=
27382                     "GNAT Version: 6.0.0w (20061115)";
27383    pragma Export (C, GNAT_Version, "__gnat_version");
27384
27385    --  This is the generated adafinal routine that performs
27386    --  finalization at the end of execution. In the case where
27387    --  Ada is the main program, this main program makes a call
27388    --  to adafinal at program termination.
27389
27390    procedure adafinal;
27391    pragma Export (C, adafinal, "adafinal");
27392
27393    --  This is the generated adainit routine that performs
27394    --  initialization at the start of execution. In the case
27395    --  where Ada is the main program, this main program makes
27396    --  a call to adainit at program startup.
27397
27398    procedure adainit;
27399    pragma Export (C, adainit, "adainit");
27400
27401    --  This routine is called at the start of execution. It is
27402    --  a dummy routine that is used by the debugger to breakpoint
27403    --  at the start of execution.
27404
27405    procedure Break_Start;
27406    pragma Import (C, Break_Start, "__gnat_break_start");
27407
27408    --  This is the actual generated main program (it would be
27409    --  suppressed if the no main program switch were used). As
27410    --  required by standard system conventions, this program has
27411    --  the external name main.
27412
27413    function main
27414      (argc : Integer;
27415       argv : System.Address;
27416       envp : System.Address)
27417       return Integer;
27418    pragma Export (C, main, "main");
27419
27420    --  The following set of constants give the version
27421    --  identification values for every unit in the bound
27422    --  partition. This identification is computed from all
27423    --  dependent semantic units, and corresponds to the
27424    --  string that would be returned by use of the
27425    --  Body_Version or Version attributes.
27426
27427    type Version_32 is mod 2 ** 32;
27428    u00001 : constant Version_32 := 16#7880BEB3#;
27429    u00002 : constant Version_32 := 16#0D24CBD0#;
27430    u00003 : constant Version_32 := 16#3283DBEB#;
27431    u00004 : constant Version_32 := 16#2359F9ED#;
27432    u00005 : constant Version_32 := 16#664FB847#;
27433    u00006 : constant Version_32 := 16#68E803DF#;
27434    u00007 : constant Version_32 := 16#5572E604#;
27435    u00008 : constant Version_32 := 16#46B173D8#;
27436    u00009 : constant Version_32 := 16#156A40CF#;
27437    u00010 : constant Version_32 := 16#033DABE0#;
27438    u00011 : constant Version_32 := 16#6AB38FEA#;
27439    u00012 : constant Version_32 := 16#22B6217D#;
27440    u00013 : constant Version_32 := 16#68A22947#;
27441    u00014 : constant Version_32 := 16#18CC4A56#;
27442    u00015 : constant Version_32 := 16#08258E1B#;
27443    u00016 : constant Version_32 := 16#367D5222#;
27444    u00017 : constant Version_32 := 16#20C9ECA4#;
27445    u00018 : constant Version_32 := 16#50D32CB6#;
27446    u00019 : constant Version_32 := 16#39A8BB77#;
27447    u00020 : constant Version_32 := 16#5CF8FA2B#;
27448    u00021 : constant Version_32 := 16#2F1EB794#;
27449    u00022 : constant Version_32 := 16#31AB6444#;
27450    u00023 : constant Version_32 := 16#1574B6E9#;
27451    u00024 : constant Version_32 := 16#5109C189#;
27452    u00025 : constant Version_32 := 16#56D770CD#;
27453    u00026 : constant Version_32 := 16#02F9DE3D#;
27454    u00027 : constant Version_32 := 16#08AB6B2C#;
27455    u00028 : constant Version_32 := 16#3FA37670#;
27456    u00029 : constant Version_32 := 16#476457A0#;
27457    u00030 : constant Version_32 := 16#731E1B6E#;
27458    u00031 : constant Version_32 := 16#23C2E789#;
27459    u00032 : constant Version_32 := 16#0F1BD6A1#;
27460    u00033 : constant Version_32 := 16#7C25DE96#;
27461    u00034 : constant Version_32 := 16#39ADFFA2#;
27462    u00035 : constant Version_32 := 16#571DE3E7#;
27463    u00036 : constant Version_32 := 16#5EB646AB#;
27464    u00037 : constant Version_32 := 16#4249379B#;
27465    u00038 : constant Version_32 := 16#0357E00A#;
27466    u00039 : constant Version_32 := 16#3784FB72#;
27467    u00040 : constant Version_32 := 16#2E723019#;
27468    u00041 : constant Version_32 := 16#623358EA#;
27469    u00042 : constant Version_32 := 16#107F9465#;
27470    u00043 : constant Version_32 := 16#6843F68A#;
27471    u00044 : constant Version_32 := 16#63305874#;
27472    u00045 : constant Version_32 := 16#31E56CE1#;
27473    u00046 : constant Version_32 := 16#02917970#;
27474    u00047 : constant Version_32 := 16#6CCBA70E#;
27475    u00048 : constant Version_32 := 16#41CD4204#;
27476    u00049 : constant Version_32 := 16#572E3F58#;
27477    u00050 : constant Version_32 := 16#20729FF5#;
27478    u00051 : constant Version_32 := 16#1D4F93E8#;
27479    u00052 : constant Version_32 := 16#30B2EC3D#;
27480    u00053 : constant Version_32 := 16#34054F96#;
27481    u00054 : constant Version_32 := 16#5A199860#;
27482    u00055 : constant Version_32 := 16#0E7F912B#;
27483    u00056 : constant Version_32 := 16#5760634A#;
27484    u00057 : constant Version_32 := 16#5D851835#;
27485
27486    --  The following Export pragmas export the version numbers
27487    --  with symbolic names ending in B (for body) or S
27488    --  (for spec) so that they can be located in a link. The
27489    --  information provided here is sufficient to track down
27490    --  the exact versions of units used in a given build.
27491
27492    pragma Export (C, u00001, "helloB");
27493    pragma Export (C, u00002, "system__standard_libraryB");
27494    pragma Export (C, u00003, "system__standard_libraryS");
27495    pragma Export (C, u00004, "adaS");
27496    pragma Export (C, u00005, "ada__text_ioB");
27497    pragma Export (C, u00006, "ada__text_ioS");
27498    pragma Export (C, u00007, "ada__exceptionsB");
27499    pragma Export (C, u00008, "ada__exceptionsS");
27500    pragma Export (C, u00009, "gnatS");
27501    pragma Export (C, u00010, "gnat__heap_sort_aB");
27502    pragma Export (C, u00011, "gnat__heap_sort_aS");
27503    pragma Export (C, u00012, "systemS");
27504    pragma Export (C, u00013, "system__exception_tableB");
27505    pragma Export (C, u00014, "system__exception_tableS");
27506    pragma Export (C, u00015, "gnat__htableB");
27507    pragma Export (C, u00016, "gnat__htableS");
27508    pragma Export (C, u00017, "system__exceptionsS");
27509    pragma Export (C, u00018, "system__machine_state_operationsB");
27510    pragma Export (C, u00019, "system__machine_state_operationsS");
27511    pragma Export (C, u00020, "system__machine_codeS");
27512    pragma Export (C, u00021, "system__storage_elementsB");
27513    pragma Export (C, u00022, "system__storage_elementsS");
27514    pragma Export (C, u00023, "system__secondary_stackB");
27515    pragma Export (C, u00024, "system__secondary_stackS");
27516    pragma Export (C, u00025, "system__parametersB");
27517    pragma Export (C, u00026, "system__parametersS");
27518    pragma Export (C, u00027, "system__soft_linksB");
27519    pragma Export (C, u00028, "system__soft_linksS");
27520    pragma Export (C, u00029, "system__stack_checkingB");
27521    pragma Export (C, u00030, "system__stack_checkingS");
27522    pragma Export (C, u00031, "system__tracebackB");
27523    pragma Export (C, u00032, "system__tracebackS");
27524    pragma Export (C, u00033, "ada__streamsS");
27525    pragma Export (C, u00034, "ada__tagsB");
27526    pragma Export (C, u00035, "ada__tagsS");
27527    pragma Export (C, u00036, "system__string_opsB");
27528    pragma Export (C, u00037, "system__string_opsS");
27529    pragma Export (C, u00038, "interfacesS");
27530    pragma Export (C, u00039, "interfaces__c_streamsB");
27531    pragma Export (C, u00040, "interfaces__c_streamsS");
27532    pragma Export (C, u00041, "system__file_ioB");
27533    pragma Export (C, u00042, "system__file_ioS");
27534    pragma Export (C, u00043, "ada__finalizationB");
27535    pragma Export (C, u00044, "ada__finalizationS");
27536    pragma Export (C, u00045, "system__finalization_rootB");
27537    pragma Export (C, u00046, "system__finalization_rootS");
27538    pragma Export (C, u00047, "system__finalization_implementationB");
27539    pragma Export (C, u00048, "system__finalization_implementationS");
27540    pragma Export (C, u00049, "system__string_ops_concat_3B");
27541    pragma Export (C, u00050, "system__string_ops_concat_3S");
27542    pragma Export (C, u00051, "system__stream_attributesB");
27543    pragma Export (C, u00052, "system__stream_attributesS");
27544    pragma Export (C, u00053, "ada__io_exceptionsS");
27545    pragma Export (C, u00054, "system__unsigned_typesS");
27546    pragma Export (C, u00055, "system__file_control_blockS");
27547    pragma Export (C, u00056, "ada__finalization__list_controllerB");
27548    pragma Export (C, u00057, "ada__finalization__list_controllerS");
27549
27550    -- BEGIN ELABORATION ORDER
27551    -- ada (spec)
27552    -- gnat (spec)
27553    -- gnat.heap_sort_a (spec)
27554    -- gnat.heap_sort_a (body)
27555    -- gnat.htable (spec)
27556    -- gnat.htable (body)
27557    -- interfaces (spec)
27558    -- system (spec)
27559    -- system.machine_code (spec)
27560    -- system.parameters (spec)
27561    -- system.parameters (body)
27562    -- interfaces.c_streams (spec)
27563    -- interfaces.c_streams (body)
27564    -- system.standard_library (spec)
27565    -- ada.exceptions (spec)
27566    -- system.exception_table (spec)
27567    -- system.exception_table (body)
27568    -- ada.io_exceptions (spec)
27569    -- system.exceptions (spec)
27570    -- system.storage_elements (spec)
27571    -- system.storage_elements (body)
27572    -- system.machine_state_operations (spec)
27573    -- system.machine_state_operations (body)
27574    -- system.secondary_stack (spec)
27575    -- system.stack_checking (spec)
27576    -- system.soft_links (spec)
27577    -- system.soft_links (body)
27578    -- system.stack_checking (body)
27579    -- system.secondary_stack (body)
27580    -- system.standard_library (body)
27581    -- system.string_ops (spec)
27582    -- system.string_ops (body)
27583    -- ada.tags (spec)
27584    -- ada.tags (body)
27585    -- ada.streams (spec)
27586    -- system.finalization_root (spec)
27587    -- system.finalization_root (body)
27588    -- system.string_ops_concat_3 (spec)
27589    -- system.string_ops_concat_3 (body)
27590    -- system.traceback (spec)
27591    -- system.traceback (body)
27592    -- ada.exceptions (body)
27593    -- system.unsigned_types (spec)
27594    -- system.stream_attributes (spec)
27595    -- system.stream_attributes (body)
27596    -- system.finalization_implementation (spec)
27597    -- system.finalization_implementation (body)
27598    -- ada.finalization (spec)
27599    -- ada.finalization (body)
27600    -- ada.finalization.list_controller (spec)
27601    -- ada.finalization.list_controller (body)
27602    -- system.file_control_block (spec)
27603    -- system.file_io (spec)
27604    -- system.file_io (body)
27605    -- ada.text_io (spec)
27606    -- ada.text_io (body)
27607    -- hello (body)
27608    -- END ELABORATION ORDER
27609
27610 end ada_main;
27611
27612 --  The following source file name pragmas allow the generated file
27613 --  names to be unique for different main programs. They are needed
27614 --  since the package name will always be Ada_Main.
27615
27616 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
27617 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
27618
27619 --  Generated package body for Ada_Main starts here
27620
27621 package body ada_main is
27622
27623    --  The actual finalization is performed by calling the
27624    --  library routine in System.Standard_Library.Adafinal
27625
27626    procedure Do_Finalize;
27627    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
27628
27629    -------------
27630    -- adainit --
27631    -------------
27632
27633 @findex adainit
27634    procedure adainit is
27635
27636       --  These booleans are set to True once the associated unit has
27637       --  been elaborated. It is also used to avoid elaborating the
27638       --  same unit twice.
27639
27640       E040 : Boolean;
27641       pragma Import (Ada, E040, "interfaces__c_streams_E");
27642
27643       E008 : Boolean;
27644       pragma Import (Ada, E008, "ada__exceptions_E");
27645
27646       E014 : Boolean;
27647       pragma Import (Ada, E014, "system__exception_table_E");
27648
27649       E053 : Boolean;
27650       pragma Import (Ada, E053, "ada__io_exceptions_E");
27651
27652       E017 : Boolean;
27653       pragma Import (Ada, E017, "system__exceptions_E");
27654
27655       E024 : Boolean;
27656       pragma Import (Ada, E024, "system__secondary_stack_E");
27657
27658       E030 : Boolean;
27659       pragma Import (Ada, E030, "system__stack_checking_E");
27660
27661       E028 : Boolean;
27662       pragma Import (Ada, E028, "system__soft_links_E");
27663
27664       E035 : Boolean;
27665       pragma Import (Ada, E035, "ada__tags_E");
27666
27667       E033 : Boolean;
27668       pragma Import (Ada, E033, "ada__streams_E");
27669
27670       E046 : Boolean;
27671       pragma Import (Ada, E046, "system__finalization_root_E");
27672
27673       E048 : Boolean;
27674       pragma Import (Ada, E048, "system__finalization_implementation_E");
27675
27676       E044 : Boolean;
27677       pragma Import (Ada, E044, "ada__finalization_E");
27678
27679       E057 : Boolean;
27680       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
27681
27682       E055 : Boolean;
27683       pragma Import (Ada, E055, "system__file_control_block_E");
27684
27685       E042 : Boolean;
27686       pragma Import (Ada, E042, "system__file_io_E");
27687
27688       E006 : Boolean;
27689       pragma Import (Ada, E006, "ada__text_io_E");
27690
27691       --  Set_Globals is a library routine that stores away the
27692       --  value of the indicated set of global values in global
27693       --  variables within the library.
27694
27695       procedure Set_Globals
27696         (Main_Priority            : Integer;
27697          Time_Slice_Value         : Integer;
27698          WC_Encoding              : Character;
27699          Locking_Policy           : Character;
27700          Queuing_Policy           : Character;
27701          Task_Dispatching_Policy  : Character;
27702          Adafinal                 : System.Address;
27703          Unreserve_All_Interrupts : Integer;
27704          Exception_Tracebacks     : Integer);
27705 @findex __gnat_set_globals
27706       pragma Import (C, Set_Globals, "__gnat_set_globals");
27707
27708       --  SDP_Table_Build is a library routine used to build the
27709       --  exception tables. See unit Ada.Exceptions in files
27710       --  a-except.ads/adb for full details of how zero cost
27711       --  exception handling works. This procedure, the call to
27712       --  it, and the two following tables are all omitted if the
27713       --  build is in longjmp/setjmp exception mode.
27714
27715 @findex SDP_Table_Build
27716 @findex Zero Cost Exceptions
27717       procedure SDP_Table_Build
27718         (SDP_Addresses   : System.Address;
27719          SDP_Count       : Natural;
27720          Elab_Addresses  : System.Address;
27721          Elab_Addr_Count : Natural);
27722       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
27723
27724       --  Table of Unit_Exception_Table addresses. Used for zero
27725       --  cost exception handling to build the top level table.
27726
27727       ST : aliased constant array (1 .. 23) of System.Address := (
27728         Hello'UET_Address,
27729         Ada.Text_Io'UET_Address,
27730         Ada.Exceptions'UET_Address,
27731         Gnat.Heap_Sort_A'UET_Address,
27732         System.Exception_Table'UET_Address,
27733         System.Machine_State_Operations'UET_Address,
27734         System.Secondary_Stack'UET_Address,
27735         System.Parameters'UET_Address,
27736         System.Soft_Links'UET_Address,
27737         System.Stack_Checking'UET_Address,
27738         System.Traceback'UET_Address,
27739         Ada.Streams'UET_Address,
27740         Ada.Tags'UET_Address,
27741         System.String_Ops'UET_Address,
27742         Interfaces.C_Streams'UET_Address,
27743         System.File_Io'UET_Address,
27744         Ada.Finalization'UET_Address,
27745         System.Finalization_Root'UET_Address,
27746         System.Finalization_Implementation'UET_Address,
27747         System.String_Ops_Concat_3'UET_Address,
27748         System.Stream_Attributes'UET_Address,
27749         System.File_Control_Block'UET_Address,
27750         Ada.Finalization.List_Controller'UET_Address);
27751
27752       --  Table of addresses of elaboration routines. Used for
27753       --  zero cost exception handling to make sure these
27754       --  addresses are included in the top level procedure
27755       --  address table.
27756
27757       EA : aliased constant array (1 .. 23) of System.Address := (
27758         adainit'Code_Address,
27759         Do_Finalize'Code_Address,
27760         Ada.Exceptions'Elab_Spec'Address,
27761         System.Exceptions'Elab_Spec'Address,
27762         Interfaces.C_Streams'Elab_Spec'Address,
27763         System.Exception_Table'Elab_Body'Address,
27764         Ada.Io_Exceptions'Elab_Spec'Address,
27765         System.Stack_Checking'Elab_Spec'Address,
27766         System.Soft_Links'Elab_Body'Address,
27767         System.Secondary_Stack'Elab_Body'Address,
27768         Ada.Tags'Elab_Spec'Address,
27769         Ada.Tags'Elab_Body'Address,
27770         Ada.Streams'Elab_Spec'Address,
27771         System.Finalization_Root'Elab_Spec'Address,
27772         Ada.Exceptions'Elab_Body'Address,
27773         System.Finalization_Implementation'Elab_Spec'Address,
27774         System.Finalization_Implementation'Elab_Body'Address,
27775         Ada.Finalization'Elab_Spec'Address,
27776         Ada.Finalization.List_Controller'Elab_Spec'Address,
27777         System.File_Control_Block'Elab_Spec'Address,
27778         System.File_Io'Elab_Body'Address,
27779         Ada.Text_Io'Elab_Spec'Address,
27780         Ada.Text_Io'Elab_Body'Address);
27781
27782    --  Start of processing for adainit
27783
27784    begin
27785
27786       --  Call SDP_Table_Build to build the top level procedure
27787       --  table for zero cost exception handling (omitted in
27788       --  longjmp/setjmp mode).
27789
27790       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
27791
27792       --  Call Set_Globals to record various information for
27793       --  this partition.  The values are derived by the binder
27794       --  from information stored in the ali files by the compiler.
27795
27796 @findex __gnat_set_globals
27797       Set_Globals
27798         (Main_Priority            => -1,
27799          --  Priority of main program, -1 if no pragma Priority used
27800
27801          Time_Slice_Value         => -1,
27802          --  Time slice from Time_Slice pragma, -1 if none used
27803
27804          WC_Encoding              => 'b',
27805          --  Wide_Character encoding used, default is brackets
27806
27807          Locking_Policy           => ' ',
27808          --  Locking_Policy used, default of space means not
27809          --  specified, otherwise it is the first character of
27810          --  the policy name.
27811
27812          Queuing_Policy           => ' ',
27813          --  Queuing_Policy used, default of space means not
27814          --  specified, otherwise it is the first character of
27815          --  the policy name.
27816
27817          Task_Dispatching_Policy  => ' ',
27818          --  Task_Dispatching_Policy used, default of space means
27819          --  not specified, otherwise first character of the
27820          --  policy name.
27821
27822          Adafinal                 => System.Null_Address,
27823          --  Address of Adafinal routine, not used anymore
27824
27825          Unreserve_All_Interrupts => 0,
27826          --  Set true if pragma Unreserve_All_Interrupts was used
27827
27828          Exception_Tracebacks     => 0);
27829          --  Indicates if exception tracebacks are enabled
27830
27831       Elab_Final_Code := 1;
27832
27833       --  Now we have the elaboration calls for all units in the partition.
27834       --  The Elab_Spec and Elab_Body attributes generate references to the
27835       --  implicit elaboration procedures generated by the compiler for
27836       --  each unit that requires elaboration.
27837
27838       if not E040 then
27839          Interfaces.C_Streams'Elab_Spec;
27840       end if;
27841       E040 := True;
27842       if not E008 then
27843          Ada.Exceptions'Elab_Spec;
27844       end if;
27845       if not E014 then
27846          System.Exception_Table'Elab_Body;
27847          E014 := True;
27848       end if;
27849       if not E053 then
27850          Ada.Io_Exceptions'Elab_Spec;
27851          E053 := True;
27852       end if;
27853       if not E017 then
27854          System.Exceptions'Elab_Spec;
27855          E017 := True;
27856       end if;
27857       if not E030 then
27858          System.Stack_Checking'Elab_Spec;
27859       end if;
27860       if not E028 then
27861          System.Soft_Links'Elab_Body;
27862          E028 := True;
27863       end if;
27864       E030 := True;
27865       if not E024 then
27866          System.Secondary_Stack'Elab_Body;
27867          E024 := True;
27868       end if;
27869       if not E035 then
27870          Ada.Tags'Elab_Spec;
27871       end if;
27872       if not E035 then
27873          Ada.Tags'Elab_Body;
27874          E035 := True;
27875       end if;
27876       if not E033 then
27877          Ada.Streams'Elab_Spec;
27878          E033 := True;
27879       end if;
27880       if not E046 then
27881          System.Finalization_Root'Elab_Spec;
27882       end if;
27883       E046 := True;
27884       if not E008 then
27885          Ada.Exceptions'Elab_Body;
27886          E008 := True;
27887       end if;
27888       if not E048 then
27889          System.Finalization_Implementation'Elab_Spec;
27890       end if;
27891       if not E048 then
27892          System.Finalization_Implementation'Elab_Body;
27893          E048 := True;
27894       end if;
27895       if not E044 then
27896          Ada.Finalization'Elab_Spec;
27897       end if;
27898       E044 := True;
27899       if not E057 then
27900          Ada.Finalization.List_Controller'Elab_Spec;
27901       end if;
27902       E057 := True;
27903       if not E055 then
27904          System.File_Control_Block'Elab_Spec;
27905          E055 := True;
27906       end if;
27907       if not E042 then
27908          System.File_Io'Elab_Body;
27909          E042 := True;
27910       end if;
27911       if not E006 then
27912          Ada.Text_Io'Elab_Spec;
27913       end if;
27914       if not E006 then
27915          Ada.Text_Io'Elab_Body;
27916          E006 := True;
27917       end if;
27918
27919       Elab_Final_Code := 0;
27920    end adainit;
27921
27922    --------------
27923    -- adafinal --
27924    --------------
27925
27926 @findex adafinal
27927    procedure adafinal is
27928    begin
27929       Do_Finalize;
27930    end adafinal;
27931
27932    ----------
27933    -- main --
27934    ----------
27935
27936    --  main is actually a function, as in the ANSI C standard,
27937    --  defined to return the exit status. The three parameters
27938    --  are the argument count, argument values and environment
27939    --  pointer.
27940
27941 @findex Main Program
27942    function main
27943      (argc : Integer;
27944       argv : System.Address;
27945       envp : System.Address)
27946       return Integer
27947    is
27948       --  The initialize routine performs low level system
27949       --  initialization using a standard library routine which
27950       --  sets up signal handling and performs any other
27951       --  required setup. The routine can be found in file
27952       --  a-init.c.
27953
27954 @findex __gnat_initialize
27955       procedure initialize;
27956       pragma Import (C, initialize, "__gnat_initialize");
27957
27958       --  The finalize routine performs low level system
27959       --  finalization using a standard library routine. The
27960       --  routine is found in file a-final.c and in the standard
27961       --  distribution is a dummy routine that does nothing, so
27962       --  really this is a hook for special user finalization.
27963
27964 @findex __gnat_finalize
27965       procedure finalize;
27966       pragma Import (C, finalize, "__gnat_finalize");
27967
27968       --  We get to the main program of the partition by using
27969       --  pragma Import because if we try to with the unit and
27970       --  call it Ada style, then not only do we waste time
27971       --  recompiling it, but also, we don't really know the right
27972       --  switches (e.g.@: identifier character set) to be used
27973       --  to compile it.
27974
27975       procedure Ada_Main_Program;
27976       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
27977
27978    --  Start of processing for main
27979
27980    begin
27981       --  Save global variables
27982
27983       gnat_argc := argc;
27984       gnat_argv := argv;
27985       gnat_envp := envp;
27986
27987       --  Call low level system initialization
27988
27989       Initialize;
27990
27991       --  Call our generated Ada initialization routine
27992
27993       adainit;
27994
27995       --  This is the point at which we want the debugger to get
27996       --  control
27997
27998       Break_Start;
27999
28000       --  Now we call the main program of the partition
28001
28002       Ada_Main_Program;
28003
28004       --  Perform Ada finalization
28005
28006       adafinal;
28007
28008       --  Perform low level system finalization
28009
28010       Finalize;
28011
28012       --  Return the proper exit status
28013       return (gnat_exit_status);
28014    end;
28015
28016 --  This section is entirely comments, so it has no effect on the
28017 --  compilation of the Ada_Main package. It provides the list of
28018 --  object files and linker options, as well as some standard
28019 --  libraries needed for the link. The gnatlink utility parses
28020 --  this b~hello.adb file to read these comment lines to generate
28021 --  the appropriate command line arguments for the call to the
28022 --  system linker. The BEGIN/END lines are used for sentinels for
28023 --  this parsing operation.
28024
28025 --  The exact file names will of course depend on the environment,
28026 --  host/target and location of files on the host system.
28027
28028 @findex Object file list
28029 -- BEGIN Object file/option list
28030    --   ./hello.o
28031    --   -L./
28032    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
28033    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
28034 -- END Object file/option list
28035
28036 end ada_main;
28037 @end smallexample
28038
28039 @noindent
28040 The Ada code in the above example is exactly what is generated by the
28041 binder. We have added comments to more clearly indicate the function
28042 of each part of the generated @code{Ada_Main} package.
28043
28044 The code is standard Ada in all respects, and can be processed by any
28045 tools that handle Ada. In particular, it is possible to use the debugger
28046 in Ada mode to debug the generated @code{Ada_Main} package. For example,
28047 suppose that for reasons that you do not understand, your program is crashing
28048 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
28049 you can place a breakpoint on the call:
28050
28051 @smallexample @c ada
28052 Ada.Text_Io'Elab_Body;
28053 @end smallexample
28054
28055 @noindent
28056 and trace the elaboration routine for this package to find out where
28057 the problem might be (more usually of course you would be debugging
28058 elaboration code in your own application).
28059
28060 @node Elaboration Order Handling in GNAT
28061 @appendix Elaboration Order Handling in GNAT
28062 @cindex Order of elaboration
28063 @cindex Elaboration control
28064
28065 @menu
28066 * Elaboration Code::
28067 * Checking the Elaboration Order::
28068 * Controlling the Elaboration Order::
28069 * Controlling Elaboration in GNAT - Internal Calls::
28070 * Controlling Elaboration in GNAT - External Calls::
28071 * Default Behavior in GNAT - Ensuring Safety::
28072 * Treatment of Pragma Elaborate::
28073 * Elaboration Issues for Library Tasks::
28074 * Mixing Elaboration Models::
28075 * What to Do If the Default Elaboration Behavior Fails::
28076 * Elaboration for Access-to-Subprogram Values::
28077 * Summary of Procedures for Elaboration Control::
28078 * Other Elaboration Order Considerations::
28079 @end menu
28080
28081 @noindent
28082 This chapter describes the handling of elaboration code in Ada and
28083 in GNAT, and discusses how the order of elaboration of program units can
28084 be controlled in GNAT, either automatically or with explicit programming
28085 features.
28086
28087 @node Elaboration Code
28088 @section Elaboration Code
28089
28090 @noindent
28091 Ada provides rather general mechanisms for executing code at elaboration
28092 time, that is to say before the main program starts executing. Such code arises
28093 in three contexts:
28094
28095 @table @asis
28096 @item Initializers for variables.
28097 Variables declared at the library level, in package specs or bodies, can
28098 require initialization that is performed at elaboration time, as in:
28099 @smallexample @c ada
28100 @cartouche
28101 Sqrt_Half : Float := Sqrt (0.5);
28102 @end cartouche
28103 @end smallexample
28104
28105 @item Package initialization code
28106 Code in a @code{BEGIN-END} section at the outer level of a package body is
28107 executed as part of the package body elaboration code.
28108
28109 @item Library level task allocators
28110 Tasks that are declared using task allocators at the library level
28111 start executing immediately and hence can execute at elaboration time.
28112 @end table
28113
28114 @noindent
28115 Subprogram calls are possible in any of these contexts, which means that
28116 any arbitrary part of the program may be executed as part of the elaboration
28117 code. It is even possible to write a program which does all its work at
28118 elaboration time, with a null main program, although stylistically this
28119 would usually be considered an inappropriate way to structure
28120 a program.
28121
28122 An important concern arises in the context of elaboration code:
28123 we have to be sure that it is executed in an appropriate order. What we
28124 have is a series of elaboration code sections, potentially one section
28125 for each unit in the program. It is important that these execute
28126 in the correct order. Correctness here means that, taking the above
28127 example of the declaration of @code{Sqrt_Half},
28128 if some other piece of
28129 elaboration code references @code{Sqrt_Half},
28130 then it must run after the
28131 section of elaboration code that contains the declaration of
28132 @code{Sqrt_Half}.
28133
28134 There would never be any order of elaboration problem if we made a rule
28135 that whenever you @code{with} a unit, you must elaborate both the spec and body
28136 of that unit before elaborating the unit doing the @code{with}'ing:
28137
28138 @smallexample @c ada
28139 @group
28140 @cartouche
28141 with Unit_1;
28142 package Unit_2 is @dots{}
28143 @end cartouche
28144 @end group
28145 @end smallexample
28146
28147 @noindent
28148 would require that both the body and spec of @code{Unit_1} be elaborated
28149 before the spec of @code{Unit_2}. However, a rule like that would be far too
28150 restrictive. In particular, it would make it impossible to have routines
28151 in separate packages that were mutually recursive.
28152
28153 You might think that a clever enough compiler could look at the actual
28154 elaboration code and determine an appropriate correct order of elaboration,
28155 but in the general case, this is not possible. Consider the following
28156 example.
28157
28158 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
28159 that references
28160 the variable @code{Sqrt_1}, which is declared in the elaboration code
28161 of the body of @code{Unit_1}:
28162
28163 @smallexample @c ada
28164 @cartouche
28165 Sqrt_1 : Float := Sqrt (0.1);
28166 @end cartouche
28167 @end smallexample
28168
28169 @noindent
28170 The elaboration code of the body of @code{Unit_1} also contains:
28171
28172 @smallexample @c ada
28173 @group
28174 @cartouche
28175 if expression_1 = 1 then
28176    Q := Unit_2.Func_2;
28177 end if;
28178 @end cartouche
28179 @end group
28180 @end smallexample
28181
28182 @noindent
28183 @code{Unit_2} is exactly parallel,
28184 it has a procedure @code{Func_2} that references
28185 the variable @code{Sqrt_2}, which is declared in the elaboration code of
28186 the body @code{Unit_2}:
28187
28188 @smallexample @c ada
28189 @cartouche
28190 Sqrt_2 : Float := Sqrt (0.1);
28191 @end cartouche
28192 @end smallexample
28193
28194 @noindent
28195 The elaboration code of the body of @code{Unit_2} also contains:
28196
28197 @smallexample @c ada
28198 @group
28199 @cartouche
28200 if expression_2 = 2 then
28201    Q := Unit_1.Func_1;
28202 end if;
28203 @end cartouche
28204 @end group
28205 @end smallexample
28206
28207 @noindent
28208 Now the question is, which of the following orders of elaboration is
28209 acceptable:
28210
28211 @smallexample
28212 @group
28213 Spec of Unit_1
28214 Spec of Unit_2
28215 Body of Unit_1
28216 Body of Unit_2
28217 @end group
28218 @end smallexample
28219
28220 @noindent
28221 or
28222
28223 @smallexample
28224 @group
28225 Spec of Unit_2
28226 Spec of Unit_1
28227 Body of Unit_2
28228 Body of Unit_1
28229 @end group
28230 @end smallexample
28231
28232 @noindent
28233 If you carefully analyze the flow here, you will see that you cannot tell
28234 at compile time the answer to this question.
28235 If @code{expression_1} is not equal to 1,
28236 and @code{expression_2} is not equal to 2,
28237 then either order is acceptable, because neither of the function calls is
28238 executed. If both tests evaluate to true, then neither order is acceptable
28239 and in fact there is no correct order.
28240
28241 If one of the two expressions is true, and the other is false, then one
28242 of the above orders is correct, and the other is incorrect. For example,
28243 if @code{expression_1} /= 1 and @code{expression_2} = 2,
28244 then the call to @code{Func_1}
28245 will occur, but not the call to @code{Func_2.}
28246 This means that it is essential
28247 to elaborate the body of @code{Unit_1} before
28248 the body of @code{Unit_2}, so the first
28249 order of elaboration is correct and the second is wrong.
28250
28251 By making @code{expression_1} and @code{expression_2}
28252 depend on input data, or perhaps
28253 the time of day, we can make it impossible for the compiler or binder
28254 to figure out which of these expressions will be true, and hence it
28255 is impossible to guarantee a safe order of elaboration at run time.
28256
28257 @node Checking the Elaboration Order
28258 @section Checking the Elaboration Order
28259
28260 @noindent
28261 In some languages that involve the same kind of elaboration problems,
28262 e.g.@: Java and C++, the programmer is expected to worry about these
28263 ordering problems himself, and it is common to
28264 write a program in which an incorrect elaboration order  gives
28265 surprising results, because it references variables before they
28266 are initialized.
28267 Ada is designed to be a safe language, and a programmer-beware approach is
28268 clearly not sufficient. Consequently, the language provides three lines
28269 of defense:
28270
28271 @table @asis
28272 @item Standard rules
28273 Some standard rules restrict the possible choice of elaboration
28274 order. In particular, if you @code{with} a unit, then its spec is always
28275 elaborated before the unit doing the @code{with}. Similarly, a parent
28276 spec is always elaborated before the child spec, and finally
28277 a spec is always elaborated before its corresponding body.
28278
28279 @item Dynamic elaboration checks
28280 @cindex Elaboration checks
28281 @cindex Checks, elaboration
28282 Dynamic checks are made at run time, so that if some entity is accessed
28283 before it is elaborated (typically  by means of a subprogram call)
28284 then the exception (@code{Program_Error}) is raised.
28285
28286 @item Elaboration control
28287 Facilities are provided for the programmer to specify the desired order
28288 of elaboration.
28289 @end table
28290
28291 Let's look at these facilities in more detail. First, the rules for
28292 dynamic checking. One possible rule would be simply to say that the
28293 exception is raised if you access a variable which has not yet been
28294 elaborated. The trouble with this approach is that it could require
28295 expensive checks on every variable reference. Instead Ada has two
28296 rules which are a little more restrictive, but easier to check, and
28297 easier to state:
28298
28299 @table @asis
28300 @item Restrictions on calls
28301 A subprogram can only be called at elaboration time if its body
28302 has been elaborated. The rules for elaboration given above guarantee
28303 that the spec of the subprogram has been elaborated before the
28304 call, but not the body. If this rule is violated, then the
28305 exception @code{Program_Error} is raised.
28306
28307 @item Restrictions on instantiations
28308 A generic unit can only be instantiated if the body of the generic
28309 unit has been elaborated. Again, the rules for elaboration given above
28310 guarantee that the spec of the generic unit has been elaborated
28311 before the instantiation, but not the body. If this rule is
28312 violated, then the exception @code{Program_Error} is raised.
28313 @end table
28314
28315 @noindent
28316 The idea is that if the body has been elaborated, then any variables
28317 it references must have been elaborated; by checking for the body being
28318 elaborated we guarantee that none of its references causes any
28319 trouble. As we noted above, this is a little too restrictive, because a
28320 subprogram that has no non-local references in its body may in fact be safe
28321 to call. However, it really would be unsafe to rely on this, because
28322 it would mean that the caller was aware of details of the implementation
28323 in the body. This goes against the basic tenets of Ada.
28324
28325 A plausible implementation can be described as follows.
28326 A Boolean variable is associated with each subprogram
28327 and each generic unit. This variable is initialized to False, and is set to
28328 True at the point body is elaborated. Every call or instantiation checks the
28329 variable, and raises @code{Program_Error} if the variable is False.
28330
28331 Note that one might think that it would be good enough to have one Boolean
28332 variable for each package, but that would not deal with cases of trying
28333 to call a body in the same package as the call
28334 that has not been elaborated yet.
28335 Of course a compiler may be able to do enough analysis to optimize away
28336 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
28337 does such optimizations, but still the easiest conceptual model is to
28338 think of there being one variable per subprogram.
28339
28340 @node Controlling the Elaboration Order
28341 @section Controlling the Elaboration Order
28342
28343 @noindent
28344 In the previous section we discussed the rules in Ada which ensure
28345 that @code{Program_Error} is raised if an incorrect elaboration order is
28346 chosen. This prevents erroneous executions, but we need mechanisms to
28347 specify a correct execution and avoid the exception altogether.
28348 To achieve this, Ada provides a number of features for controlling
28349 the order of elaboration. We discuss these features in this section.
28350
28351 First, there are several ways of indicating to the compiler that a given
28352 unit has no elaboration problems:
28353
28354 @table @asis
28355 @item packages that do not require a body
28356 A library package that does not require a body does not permit
28357 a body (this rule was introduced in Ada 95).
28358 Thus if we have a such a package, as in:
28359
28360 @smallexample @c ada
28361 @group
28362 @cartouche
28363 package Definitions is
28364    generic
28365       type m is new integer;
28366    package Subp is
28367       type a is array (1 .. 10) of m;
28368       type b is array (1 .. 20) of m;
28369    end Subp;
28370 end Definitions;
28371 @end cartouche
28372 @end group
28373 @end smallexample
28374
28375 @noindent
28376 A package that @code{with}'s @code{Definitions} may safely instantiate
28377 @code{Definitions.Subp} because the compiler can determine that there
28378 definitely is no package body to worry about in this case
28379
28380 @item pragma Pure
28381 @cindex pragma Pure
28382 @findex Pure
28383 Places sufficient restrictions on a unit to guarantee that
28384 no call to any subprogram in the unit can result in an
28385 elaboration problem. This means that the compiler does not need
28386 to worry about the point of elaboration of such units, and in
28387 particular, does not need to check any calls to any subprograms
28388 in this unit.
28389
28390 @item pragma Preelaborate
28391 @findex Preelaborate
28392 @cindex pragma Preelaborate
28393 This pragma places slightly less stringent restrictions on a unit than
28394 does pragma Pure,
28395 but these restrictions are still sufficient to ensure that there
28396 are no elaboration problems with any calls to the unit.
28397
28398 @item pragma Elaborate_Body
28399 @findex Elaborate_Body
28400 @cindex pragma Elaborate_Body
28401 This pragma requires that the body of a unit be elaborated immediately
28402 after its spec. Suppose a unit @code{A} has such a pragma,
28403 and unit @code{B} does
28404 a @code{with} of unit @code{A}. Recall that the standard rules require
28405 the spec of unit @code{A}
28406 to be elaborated before the @code{with}'ing unit; given the pragma in
28407 @code{A}, we also know that the body of @code{A}
28408 will be elaborated before @code{B}, so
28409 that calls to @code{A} are safe and do not need a check.
28410 @end table
28411
28412 @noindent
28413 Note that,
28414 unlike pragma @code{Pure} and pragma @code{Preelaborate},
28415 the use of
28416 @code{Elaborate_Body} does not guarantee that the program is
28417 free of elaboration problems, because it may not be possible
28418 to satisfy the requested elaboration order.
28419 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
28420 If a programmer
28421 marks @code{Unit_1} as @code{Elaborate_Body},
28422 and not @code{Unit_2,} then the order of
28423 elaboration will be:
28424
28425 @smallexample
28426 @group
28427 Spec of Unit_2
28428 Spec of Unit_1
28429 Body of Unit_1
28430 Body of Unit_2
28431 @end group
28432 @end smallexample
28433
28434 @noindent
28435 Now that means that the call to @code{Func_1} in @code{Unit_2}
28436 need not be checked,
28437 it must be safe. But the call to @code{Func_2} in
28438 @code{Unit_1} may still fail if
28439 @code{Expression_1} is equal to 1,
28440 and the programmer must still take
28441 responsibility for this not being the case.
28442
28443 If all units carry a pragma @code{Elaborate_Body}, then all problems are
28444 eliminated, except for calls entirely within a body, which are
28445 in any case fully under programmer control. However, using the pragma
28446 everywhere is not always possible.
28447 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
28448 we marked both of them as having pragma @code{Elaborate_Body}, then
28449 clearly there would be no possible elaboration order.
28450
28451 The above pragmas allow a server to guarantee safe use by clients, and
28452 clearly this is the preferable approach. Consequently a good rule
28453 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
28454 and if this is not possible,
28455 mark them as @code{Elaborate_Body} if possible.
28456 As we have seen, there are situations where neither of these
28457 three pragmas can be used.
28458 So we also provide methods for clients to control the
28459 order of elaboration of the servers on which they depend:
28460
28461 @table @asis
28462 @item pragma Elaborate (unit)
28463 @findex Elaborate
28464 @cindex pragma Elaborate
28465 This pragma is placed in the context clause, after a @code{with} clause,
28466 and it requires that the body of the named unit be elaborated before
28467 the unit in which the pragma occurs. The idea is to use this pragma
28468 if the current unit calls at elaboration time, directly or indirectly,
28469 some subprogram in the named unit.
28470
28471 @item pragma Elaborate_All (unit)
28472 @findex Elaborate_All
28473 @cindex pragma Elaborate_All
28474 This is a stronger version of the Elaborate pragma. Consider the
28475 following example:
28476
28477 @smallexample
28478 Unit A @code{with}'s unit B and calls B.Func in elab code
28479 Unit B @code{with}'s unit C, and B.Func calls C.Func
28480 @end smallexample
28481
28482 @noindent
28483 Now if we put a pragma @code{Elaborate (B)}
28484 in unit @code{A}, this ensures that the
28485 body of @code{B} is elaborated before the call, but not the
28486 body of @code{C}, so
28487 the call to @code{C.Func} could still cause @code{Program_Error} to
28488 be raised.
28489
28490 The effect of a pragma @code{Elaborate_All} is stronger, it requires
28491 not only that the body of the named unit be elaborated before the
28492 unit doing the @code{with}, but also the bodies of all units that the
28493 named unit uses, following @code{with} links transitively. For example,
28494 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
28495 then it requires
28496 not only that the body of @code{B} be elaborated before @code{A},
28497 but also the
28498 body of @code{C}, because @code{B} @code{with}'s @code{C}.
28499 @end table
28500
28501 @noindent
28502 We are now in a position to give a usage rule in Ada for avoiding
28503 elaboration problems, at least if dynamic dispatching and access to
28504 subprogram values are not used. We will handle these cases separately
28505 later.
28506
28507 The rule is simple. If a unit has elaboration code that can directly or
28508 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
28509 a generic package in a @code{with}'ed unit,
28510 then if the @code{with}'ed unit does not have
28511 pragma @code{Pure} or @code{Preelaborate}, then the client should have
28512 a pragma @code{Elaborate_All}
28513 for the @code{with}'ed unit. By following this rule a client is
28514 assured that calls can be made without risk of an exception.
28515
28516 For generic subprogram instantiations, the rule can be relaxed to
28517 require only a pragma @code{Elaborate} since elaborating the body
28518 of a subprogram cannot cause any transitive elaboration (we are
28519 not calling the subprogram in this case, just elaborating its
28520 declaration).
28521
28522 If this rule is not followed, then a program may be in one of four
28523 states:
28524
28525 @table @asis
28526 @item No order exists
28527 No order of elaboration exists which follows the rules, taking into
28528 account any @code{Elaborate}, @code{Elaborate_All},
28529 or @code{Elaborate_Body} pragmas. In
28530 this case, an Ada compiler must diagnose the situation at bind
28531 time, and refuse to build an executable program.
28532
28533 @item One or more orders exist, all incorrect
28534 One or more acceptable elaboration orders exist, and all of them
28535 generate an elaboration order problem. In this case, the binder
28536 can build an executable program, but @code{Program_Error} will be raised
28537 when the program is run.
28538
28539 @item Several orders exist, some right, some incorrect
28540 One or more acceptable elaboration orders exists, and some of them
28541 work, and some do not. The programmer has not controlled
28542 the order of elaboration, so the binder may or may not pick one of
28543 the correct orders, and the program may or may not raise an
28544 exception when it is run. This is the worst case, because it means
28545 that the program may fail when moved to another compiler, or even
28546 another version of the same compiler.
28547
28548 @item One or more orders exists, all correct
28549 One ore more acceptable elaboration orders exist, and all of them
28550 work. In this case the program runs successfully. This state of
28551 affairs can be guaranteed by following the rule we gave above, but
28552 may be true even if the rule is not followed.
28553 @end table
28554
28555 @noindent
28556 Note that one additional advantage of following our rules on the use
28557 of @code{Elaborate} and @code{Elaborate_All}
28558 is that the program continues to stay in the ideal (all orders OK) state
28559 even if maintenance
28560 changes some bodies of some units. Conversely, if a program that does
28561 not follow this rule happens to be safe at some point, this state of affairs
28562 may deteriorate silently as a result of maintenance changes.
28563
28564 You may have noticed that the above discussion did not mention
28565 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
28566 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
28567 code in the body makes calls to some other unit, so it is still necessary
28568 to use @code{Elaborate_All} on such units.
28569
28570 @node Controlling Elaboration in GNAT - Internal Calls
28571 @section Controlling Elaboration in GNAT - Internal Calls
28572
28573 @noindent
28574 In the case of internal calls, i.e., calls within a single package, the
28575 programmer has full control over the order of elaboration, and it is up
28576 to the programmer to elaborate declarations in an appropriate order. For
28577 example writing:
28578
28579 @smallexample @c ada
28580 @group
28581 @cartouche
28582 function One return Float;
28583
28584 Q : Float := One;
28585
28586 function One return Float is
28587 begin
28588      return 1.0;
28589 end One;
28590 @end cartouche
28591 @end group
28592 @end smallexample
28593
28594 @noindent
28595 will obviously raise @code{Program_Error} at run time, because function
28596 One will be called before its body is elaborated. In this case GNAT will
28597 generate a warning that the call will raise @code{Program_Error}:
28598
28599 @smallexample
28600 @group
28601 @cartouche
28602  1. procedure y is
28603  2.    function One return Float;
28604  3.
28605  4.    Q : Float := One;
28606                     |
28607     >>> warning: cannot call "One" before body is elaborated
28608     >>> warning: Program_Error will be raised at run time
28609
28610  5.
28611  6.    function One return Float is
28612  7.    begin
28613  8.         return 1.0;
28614  9.    end One;
28615 10.
28616 11. begin
28617 12.    null;
28618 13. end;
28619 @end cartouche
28620 @end group
28621 @end smallexample
28622
28623 @noindent
28624 Note that in this particular case, it is likely that the call is safe, because
28625 the function @code{One} does not access any global variables.
28626 Nevertheless in Ada, we do not want the validity of the check to depend on
28627 the contents of the body (think about the separate compilation case), so this
28628 is still wrong, as we discussed in the previous sections.
28629
28630 The error is easily corrected by rearranging the declarations so that the
28631 body of @code{One} appears before the declaration containing the call
28632 (note that in Ada 95 and Ada 2005,
28633 declarations can appear in any order, so there is no restriction that
28634 would prevent this reordering, and if we write:
28635
28636 @smallexample @c ada
28637 @group
28638 @cartouche
28639 function One return Float;
28640
28641 function One return Float is
28642 begin
28643      return 1.0;
28644 end One;
28645
28646 Q : Float := One;
28647 @end cartouche
28648 @end group
28649 @end smallexample
28650
28651 @noindent
28652 then all is well, no warning is generated, and no
28653 @code{Program_Error} exception
28654 will be raised.
28655 Things are more complicated when a chain of subprograms is executed:
28656
28657 @smallexample @c ada
28658 @group
28659 @cartouche
28660 function A return Integer;
28661 function B return Integer;
28662 function C return Integer;
28663
28664 function B return Integer is begin return A; end;
28665 function C return Integer is begin return B; end;
28666
28667 X : Integer := C;
28668
28669 function A return Integer is begin return 1; end;
28670 @end cartouche
28671 @end group
28672 @end smallexample
28673
28674 @noindent
28675 Now the call to @code{C}
28676 at elaboration time in the declaration of @code{X} is correct, because
28677 the body of @code{C} is already elaborated,
28678 and the call to @code{B} within the body of
28679 @code{C} is correct, but the call
28680 to @code{A} within the body of @code{B} is incorrect, because the body
28681 of @code{A} has not been elaborated, so @code{Program_Error}
28682 will be raised on the call to @code{A}.
28683 In this case GNAT will generate a
28684 warning that @code{Program_Error} may be
28685 raised at the point of the call. Let's look at the warning:
28686
28687 @smallexample
28688 @group
28689 @cartouche
28690  1. procedure x is
28691  2.    function A return Integer;
28692  3.    function B return Integer;
28693  4.    function C return Integer;
28694  5.
28695  6.    function B return Integer is begin return A; end;
28696                                                     |
28697     >>> warning: call to "A" before body is elaborated may
28698                  raise Program_Error
28699     >>> warning: "B" called at line 7
28700     >>> warning: "C" called at line 9
28701
28702  7.    function C return Integer is begin return B; end;
28703  8.
28704  9.    X : Integer := C;
28705 10.
28706 11.    function A return Integer is begin return 1; end;
28707 12.
28708 13. begin
28709 14.    null;
28710 15. end;
28711 @end cartouche
28712 @end group
28713 @end smallexample
28714
28715 @noindent
28716 Note that the message here says ``may raise'', instead of the direct case,
28717 where the message says ``will be raised''. That's because whether
28718 @code{A} is
28719 actually called depends in general on run-time flow of control.
28720 For example, if the body of @code{B} said
28721
28722 @smallexample @c ada
28723 @group
28724 @cartouche
28725 function B return Integer is
28726 begin
28727    if some-condition-depending-on-input-data then
28728       return A;
28729    else
28730       return 1;
28731    end if;
28732 end B;
28733 @end cartouche
28734 @end group
28735 @end smallexample
28736
28737 @noindent
28738 then we could not know until run time whether the incorrect call to A would
28739 actually occur, so @code{Program_Error} might
28740 or might not be raised. It is possible for a compiler to
28741 do a better job of analyzing bodies, to
28742 determine whether or not @code{Program_Error}
28743 might be raised, but it certainly
28744 couldn't do a perfect job (that would require solving the halting problem
28745 and is provably impossible), and because this is a warning anyway, it does
28746 not seem worth the effort to do the analysis. Cases in which it
28747 would be relevant are rare.
28748
28749 In practice, warnings of either of the forms given
28750 above will usually correspond to
28751 real errors, and should be examined carefully and eliminated.
28752 In the rare case where a warning is bogus, it can be suppressed by any of
28753 the following methods:
28754
28755 @itemize @bullet
28756 @item
28757 Compile with the @option{-gnatws} switch set
28758
28759 @item
28760 Suppress @code{Elaboration_Check} for the called subprogram
28761
28762 @item
28763 Use pragma @code{Warnings_Off} to turn warnings off for the call
28764 @end itemize
28765
28766 @noindent
28767 For the internal elaboration check case,
28768 GNAT by default generates the
28769 necessary run-time checks to ensure
28770 that @code{Program_Error} is raised if any
28771 call fails an elaboration check. Of course this can only happen if a
28772 warning has been issued as described above. The use of pragma
28773 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
28774 some of these checks, meaning that it may be possible (but is not
28775 guaranteed) for a program to be able to call a subprogram whose body
28776 is not yet elaborated, without raising a @code{Program_Error} exception.
28777
28778 @node Controlling Elaboration in GNAT - External Calls
28779 @section Controlling Elaboration in GNAT - External Calls
28780
28781 @noindent
28782 The previous section discussed the case in which the execution of a
28783 particular thread of elaboration code occurred entirely within a
28784 single unit. This is the easy case to handle, because a programmer
28785 has direct and total control over the order of elaboration, and
28786 furthermore, checks need only be generated in cases which are rare
28787 and which the compiler can easily detect.
28788 The situation is more complex when separate compilation is taken into account.
28789 Consider the following:
28790
28791 @smallexample @c ada
28792 @cartouche
28793 @group
28794 package Math is
28795    function Sqrt (Arg : Float) return Float;
28796 end Math;
28797
28798 package body Math is
28799    function Sqrt (Arg : Float) return Float is
28800    begin
28801          @dots{}
28802    end Sqrt;
28803 end Math;
28804 @end group
28805 @group
28806 with Math;
28807 package Stuff is
28808    X : Float := Math.Sqrt (0.5);
28809 end Stuff;
28810
28811 with Stuff;
28812 procedure Main is
28813 begin
28814    @dots{}
28815 end Main;
28816 @end group
28817 @end cartouche
28818 @end smallexample
28819
28820 @noindent
28821 where @code{Main} is the main program. When this program is executed, the
28822 elaboration code must first be executed, and one of the jobs of the
28823 binder is to determine the order in which the units of a program are
28824 to be elaborated. In this case we have four units: the spec and body
28825 of @code{Math},
28826 the spec of @code{Stuff} and the body of @code{Main}).
28827 In what order should the four separate sections of elaboration code
28828 be executed?
28829
28830 There are some restrictions in the order of elaboration that the binder
28831 can choose. In particular, if unit U has a @code{with}
28832 for a package @code{X}, then you
28833 are assured that the spec of @code{X}
28834 is elaborated before U , but you are
28835 not assured that the body of @code{X}
28836 is elaborated before U.
28837 This means that in the above case, the binder is allowed to choose the
28838 order:
28839
28840 @smallexample
28841 spec of Math
28842 spec of Stuff
28843 body of Math
28844 body of Main
28845 @end smallexample
28846
28847 @noindent
28848 but that's not good, because now the call to @code{Math.Sqrt}
28849 that happens during
28850 the elaboration of the @code{Stuff}
28851 spec happens before the body of @code{Math.Sqrt} is
28852 elaborated, and hence causes @code{Program_Error} exception to be raised.
28853 At first glance, one might say that the binder is misbehaving, because
28854 obviously you want to elaborate the body of something you @code{with}
28855 first, but
28856 that is not a general rule that can be followed in all cases. Consider
28857
28858 @smallexample @c ada
28859 @group
28860 @cartouche
28861 package X is @dots{}
28862
28863 package Y is @dots{}
28864
28865 with X;
28866 package body Y is @dots{}
28867
28868 with Y;
28869 package body X is @dots{}
28870 @end cartouche
28871 @end group
28872 @end smallexample
28873
28874 @noindent
28875 This is a common arrangement, and, apart from the order of elaboration
28876 problems that might arise in connection with elaboration code, this works fine.
28877 A rule that says that you must first elaborate the body of anything you
28878 @code{with} cannot work in this case:
28879 the body of @code{X} @code{with}'s @code{Y},
28880 which means you would have to
28881 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
28882 which means
28883 you have to elaborate the body of @code{X} first, but @dots{} and we have a
28884 loop that cannot be broken.
28885
28886 It is true that the binder can in many cases guess an order of elaboration
28887 that is unlikely to cause a @code{Program_Error}
28888 exception to be raised, and it tries to do so (in the
28889 above example of @code{Math/Stuff/Spec}, the GNAT binder will
28890 by default
28891 elaborate the body of @code{Math} right after its spec, so all will be well).
28892
28893 However, a program that blindly relies on the binder to be helpful can
28894 get into trouble, as we discussed in the previous sections, so
28895 GNAT
28896 provides a number of facilities for assisting the programmer in
28897 developing programs that are robust with respect to elaboration order.
28898
28899 @node Default Behavior in GNAT - Ensuring Safety
28900 @section Default Behavior in GNAT - Ensuring Safety
28901
28902 @noindent
28903 The default behavior in GNAT ensures elaboration safety. In its
28904 default mode GNAT implements the
28905 rule we previously described as the right approach. Let's restate it:
28906
28907 @itemize
28908 @item
28909 @emph{If a unit has elaboration code that can directly or indirectly make a
28910 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
28911 package in a @code{with}'ed unit, then if the @code{with}'ed unit
28912 does not have pragma @code{Pure} or
28913 @code{Preelaborate}, then the client should have an
28914 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
28915
28916 @emph{In the case of instantiating a generic subprogram, it is always
28917 sufficient to have only an @code{Elaborate} pragma for the
28918 @code{with}'ed unit.}
28919 @end itemize
28920
28921 @noindent
28922 By following this rule a client is assured that calls and instantiations
28923 can be made without risk of an exception.
28924
28925 In this mode GNAT traces all calls that are potentially made from
28926 elaboration code, and puts in any missing implicit @code{Elaborate}
28927 and @code{Elaborate_All} pragmas.
28928 The advantage of this approach is that no elaboration problems
28929 are possible if the binder can find an elaboration order that is
28930 consistent with these implicit @code{Elaborate} and
28931 @code{Elaborate_All} pragmas. The
28932 disadvantage of this approach is that no such order may exist.
28933
28934 If the binder does not generate any diagnostics, then it means that it has
28935 found an elaboration order that is guaranteed to be safe. However, the binder
28936 may still be relying on implicitly generated @code{Elaborate} and
28937 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
28938 guaranteed.
28939
28940 If it is important to guarantee portability, then the compilations should
28941 use the
28942 @option{-gnatwl}
28943 (warn on elaboration problems) switch. This will cause warning messages
28944 to be generated indicating the missing @code{Elaborate} and
28945 @code{Elaborate_All} pragmas.
28946 Consider the following source program:
28947
28948 @smallexample @c ada
28949 @group
28950 @cartouche
28951 with k;
28952 package j is
28953   m : integer := k.r;
28954 end;
28955 @end cartouche
28956 @end group
28957 @end smallexample
28958
28959 @noindent
28960 where it is clear that there
28961 should be a pragma @code{Elaborate_All}
28962 for unit @code{k}. An implicit pragma will be generated, and it is
28963 likely that the binder will be able to honor it. However, if you want
28964 to port this program to some other Ada compiler than GNAT.
28965 it is safer to include the pragma explicitly in the source. If this
28966 unit is compiled with the
28967 @option{-gnatwl}
28968 switch, then the compiler outputs a warning:
28969
28970 @smallexample
28971 @group
28972 @cartouche
28973 1. with k;
28974 2. package j is
28975 3.   m : integer := k.r;
28976                      |
28977    >>> warning: call to "r" may raise Program_Error
28978    >>> warning: missing pragma Elaborate_All for "k"
28979
28980 4. end;
28981 @end cartouche
28982 @end group
28983 @end smallexample
28984
28985 @noindent
28986 and these warnings can be used as a guide for supplying manually
28987 the missing pragmas. It is usually a bad idea to use this warning
28988 option during development. That's because it will warn you when
28989 you need to put in a pragma, but cannot warn you when it is time
28990 to take it out. So the use of pragma @code{Elaborate_All} may lead to
28991 unnecessary dependencies and even false circularities.
28992
28993 This default mode is more restrictive than the Ada Reference
28994 Manual, and it is possible to construct programs which will compile
28995 using the dynamic model described there, but will run into a
28996 circularity using the safer static model we have described.
28997
28998 Of course any Ada compiler must be able to operate in a mode
28999 consistent with the requirements of the Ada Reference Manual,
29000 and in particular must have the capability of implementing the
29001 standard dynamic model of elaboration with run-time checks.
29002
29003 In GNAT, this standard mode can be achieved either by the use of
29004 the @option{-gnatE} switch on the compiler (@command{gcc} or
29005 @command{gnatmake}) command, or by the use of the configuration pragma:
29006
29007 @smallexample @c ada
29008 pragma Elaboration_Checks (DYNAMIC);
29009 @end smallexample
29010
29011 @noindent
29012 Either approach will cause the unit affected to be compiled using the
29013 standard dynamic run-time elaboration checks described in the Ada
29014 Reference Manual. The static model is generally preferable, since it
29015 is clearly safer to rely on compile and link time checks rather than
29016 run-time checks. However, in the case of legacy code, it may be
29017 difficult to meet the requirements of the static model. This
29018 issue is further discussed in
29019 @ref{What to Do If the Default Elaboration Behavior Fails}.
29020
29021 Note that the static model provides a strict subset of the allowed
29022 behavior and programs of the Ada Reference Manual, so if you do
29023 adhere to the static model and no circularities exist,
29024 then you are assured that your program will
29025 work using the dynamic model, providing that you remove any
29026 pragma Elaborate statements from the source.
29027
29028 @node Treatment of Pragma Elaborate
29029 @section Treatment of Pragma Elaborate
29030 @cindex Pragma Elaborate
29031
29032 @noindent
29033 The use of @code{pragma Elaborate}
29034 should generally be avoided in Ada 95 and Ada 2005 programs,
29035 since there is no guarantee that transitive calls
29036 will be properly handled. Indeed at one point, this pragma was placed
29037 in Annex J (Obsolescent Features), on the grounds that it is never useful.
29038
29039 Now that's a bit restrictive. In practice, the case in which
29040 @code{pragma Elaborate} is useful is when the caller knows that there
29041 are no transitive calls, or that the called unit contains all necessary
29042 transitive @code{pragma Elaborate} statements, and legacy code often
29043 contains such uses.
29044
29045 Strictly speaking the static mode in GNAT should ignore such pragmas,
29046 since there is no assurance at compile time that the necessary safety
29047 conditions are met. In practice, this would cause GNAT to be incompatible
29048 with correctly written Ada 83 code that had all necessary
29049 @code{pragma Elaborate} statements in place. Consequently, we made the
29050 decision that GNAT in its default mode will believe that if it encounters
29051 a @code{pragma Elaborate} then the programmer knows what they are doing,
29052 and it will trust that no elaboration errors can occur.
29053
29054 The result of this decision is two-fold. First to be safe using the
29055 static mode, you should remove all @code{pragma Elaborate} statements.
29056 Second, when fixing circularities in existing code, you can selectively
29057 use @code{pragma Elaborate} statements to convince the static mode of
29058 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
29059 statement.
29060
29061 When using the static mode with @option{-gnatwl}, any use of
29062 @code{pragma Elaborate} will generate a warning about possible
29063 problems.
29064
29065 @node Elaboration Issues for Library Tasks
29066 @section Elaboration Issues for Library Tasks
29067 @cindex Library tasks, elaboration issues
29068 @cindex Elaboration of library tasks
29069
29070 @noindent
29071 In this section we examine special elaboration issues that arise for
29072 programs that declare library level tasks.
29073
29074 Generally the model of execution of an Ada program is that all units are
29075 elaborated, and then execution of the program starts. However, the
29076 declaration of library tasks definitely does not fit this model. The
29077 reason for this is that library tasks start as soon as they are declared
29078 (more precisely, as soon as the statement part of the enclosing package
29079 body is reached), that is to say before elaboration
29080 of the program is complete. This means that if such a task calls a
29081 subprogram, or an entry in another task, the callee may or may not be
29082 elaborated yet, and in the standard
29083 Reference Manual model of dynamic elaboration checks, you can even
29084 get timing dependent Program_Error exceptions, since there can be
29085 a race between the elaboration code and the task code.
29086
29087 The static model of elaboration in GNAT seeks to avoid all such
29088 dynamic behavior, by being conservative, and the conservative
29089 approach in this particular case is to assume that all the code
29090 in a task body is potentially executed at elaboration time if
29091 a task is declared at the library level.
29092
29093 This can definitely result in unexpected circularities. Consider
29094 the following example
29095
29096 @smallexample @c ada
29097 package Decls is
29098   task Lib_Task is
29099      entry Start;
29100   end Lib_Task;
29101
29102   type My_Int is new Integer;
29103
29104   function Ident (M : My_Int) return My_Int;
29105 end Decls;
29106
29107 with Utils;
29108 package body Decls is
29109   task body Lib_Task is
29110   begin
29111      accept Start;
29112      Utils.Put_Val (2);
29113   end Lib_Task;
29114
29115   function Ident (M : My_Int) return My_Int is
29116   begin
29117      return M;
29118   end Ident;
29119 end Decls;
29120
29121 with Decls;
29122 package Utils is
29123   procedure Put_Val (Arg : Decls.My_Int);
29124 end Utils;
29125
29126 with Text_IO;
29127 package body Utils is
29128   procedure Put_Val (Arg : Decls.My_Int) is
29129   begin
29130      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
29131   end Put_Val;
29132 end Utils;
29133
29134 with Decls;
29135 procedure Main is
29136 begin
29137    Decls.Lib_Task.Start;
29138 end;
29139 @end smallexample
29140
29141 @noindent
29142 If the above example is compiled in the default static elaboration
29143 mode, then a circularity occurs. The circularity comes from the call
29144 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
29145 this call occurs in elaboration code, we need an implicit pragma
29146 @code{Elaborate_All} for @code{Utils}. This means that not only must
29147 the spec and body of @code{Utils} be elaborated before the body
29148 of @code{Decls}, but also the spec and body of any unit that is
29149 @code{with'ed} by the body of @code{Utils} must also be elaborated before
29150 the body of @code{Decls}. This is the transitive implication of
29151 pragma @code{Elaborate_All} and it makes sense, because in general
29152 the body of @code{Put_Val} might have a call to something in a
29153 @code{with'ed} unit.
29154
29155 In this case, the body of Utils (actually its spec) @code{with's}
29156 @code{Decls}. Unfortunately this means that the body of @code{Decls}
29157 must be elaborated before itself, in case there is a call from the
29158 body of @code{Utils}.
29159
29160 Here is the exact chain of events we are worrying about:
29161
29162 @enumerate
29163 @item
29164 In the body of @code{Decls} a call is made from within the body of a library
29165 task to a subprogram in the package @code{Utils}. Since this call may
29166 occur at elaboration time (given that the task is activated at elaboration
29167 time), we have to assume the worst, i.e., that the
29168 call does happen at elaboration time.
29169
29170 @item
29171 This means that the body and spec of @code{Util} must be elaborated before
29172 the body of @code{Decls} so that this call does not cause an access before
29173 elaboration.
29174
29175 @item
29176 Within the body of @code{Util}, specifically within the body of
29177 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
29178 by this package.
29179
29180 @item
29181 One such @code{with}'ed package is package @code{Decls}, so there
29182 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
29183 In fact there is such a call in this example, but we would have to
29184 assume that there was such a call even if it were not there, since
29185 we are not supposed to write the body of @code{Decls} knowing what
29186 is in the body of @code{Utils}; certainly in the case of the
29187 static elaboration model, the compiler does not know what is in
29188 other bodies and must assume the worst.
29189
29190 @item
29191 This means that the spec and body of @code{Decls} must also be
29192 elaborated before we elaborate the unit containing the call, but
29193 that unit is @code{Decls}! This means that the body of @code{Decls}
29194 must be elaborated before itself, and that's a circularity.
29195 @end enumerate
29196
29197 @noindent
29198 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
29199 the body of @code{Decls} you will get a true Ada Reference Manual
29200 circularity that makes the program illegal.
29201
29202 In practice, we have found that problems with the static model of
29203 elaboration in existing code often arise from library tasks, so
29204 we must address this particular situation.
29205
29206 Note that if we compile and run the program above, using the dynamic model of
29207 elaboration (that is to say use the @option{-gnatE} switch),
29208 then it compiles, binds,
29209 links, and runs, printing the expected result of 2. Therefore in some sense
29210 the circularity here is only apparent, and we need to capture
29211 the properties of this program that  distinguish it from other library-level
29212 tasks that have real elaboration problems.
29213
29214 We have four possible answers to this question:
29215
29216 @itemize @bullet
29217
29218 @item
29219 Use the dynamic model of elaboration.
29220
29221 If we use the @option{-gnatE} switch, then as noted above, the program works.
29222 Why is this? If we examine the task body, it is apparent that the task cannot
29223 proceed past the
29224 @code{accept} statement until after elaboration has been completed, because
29225 the corresponding entry call comes from the main program, not earlier.
29226 This is why the dynamic model works here. But that's really giving
29227 up on a precise analysis, and we prefer to take this approach only if we cannot
29228 solve the
29229 problem in any other manner. So let us examine two ways to reorganize
29230 the program to avoid the potential elaboration problem.
29231
29232 @item
29233 Split library tasks into separate packages.
29234
29235 Write separate packages, so that library tasks are isolated from
29236 other declarations as much as possible. Let us look at a variation on
29237 the above program.
29238
29239 @smallexample @c ada
29240 package Decls1 is
29241   task Lib_Task is
29242      entry Start;
29243   end Lib_Task;
29244 end Decls1;
29245
29246 with Utils;
29247 package body Decls1 is
29248   task body Lib_Task is
29249   begin
29250      accept Start;
29251      Utils.Put_Val (2);
29252   end Lib_Task;
29253 end Decls1;
29254
29255 package Decls2 is
29256   type My_Int is new Integer;
29257   function Ident (M : My_Int) return My_Int;
29258 end Decls2;
29259
29260 with Utils;
29261 package body Decls2 is
29262   function Ident (M : My_Int) return My_Int is
29263   begin
29264      return M;
29265   end Ident;
29266 end Decls2;
29267
29268 with Decls2;
29269 package Utils is
29270   procedure Put_Val (Arg : Decls2.My_Int);
29271 end Utils;
29272
29273 with Text_IO;
29274 package body Utils is
29275   procedure Put_Val (Arg : Decls2.My_Int) is
29276   begin
29277      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
29278   end Put_Val;
29279 end Utils;
29280
29281 with Decls1;
29282 procedure Main is
29283 begin
29284    Decls1.Lib_Task.Start;
29285 end;
29286 @end smallexample
29287
29288 @noindent
29289 All we have done is to split @code{Decls} into two packages, one
29290 containing the library task, and one containing everything else. Now
29291 there is no cycle, and the program compiles, binds, links and executes
29292 using the default static model of elaboration.
29293
29294 @item
29295 Declare separate task types.
29296
29297 A significant part of the problem arises because of the use of the
29298 single task declaration form. This means that the elaboration of
29299 the task type, and the elaboration of the task itself (i.e.@: the
29300 creation of the task) happen at the same time. A good rule
29301 of style in Ada is to always create explicit task types. By
29302 following the additional step of placing task objects in separate
29303 packages from the task type declaration, many elaboration problems
29304 are avoided. Here is another modified example of the example program:
29305
29306 @smallexample @c ada
29307 package Decls is
29308   task type Lib_Task_Type is
29309      entry Start;
29310   end Lib_Task_Type;
29311
29312   type My_Int is new Integer;
29313
29314   function Ident (M : My_Int) return My_Int;
29315 end Decls;
29316
29317 with Utils;
29318 package body Decls is
29319   task body Lib_Task_Type is
29320   begin
29321      accept Start;
29322      Utils.Put_Val (2);
29323   end Lib_Task_Type;
29324
29325   function Ident (M : My_Int) return My_Int is
29326   begin
29327      return M;
29328   end Ident;
29329 end Decls;
29330
29331 with Decls;
29332 package Utils is
29333   procedure Put_Val (Arg : Decls.My_Int);
29334 end Utils;
29335
29336 with Text_IO;
29337 package body Utils is
29338   procedure Put_Val (Arg : Decls.My_Int) is
29339   begin
29340      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
29341   end Put_Val;
29342 end Utils;
29343
29344 with Decls;
29345 package Declst is
29346    Lib_Task : Decls.Lib_Task_Type;
29347 end Declst;
29348
29349 with Declst;
29350 procedure Main is
29351 begin
29352    Declst.Lib_Task.Start;
29353 end;
29354 @end smallexample
29355
29356 @noindent
29357 What we have done here is to replace the @code{task} declaration in
29358 package @code{Decls} with a @code{task type} declaration. Then we
29359 introduce a separate package @code{Declst} to contain the actual
29360 task object. This separates the elaboration issues for
29361 the @code{task type}
29362 declaration, which causes no trouble, from the elaboration issues
29363 of the task object, which is also unproblematic, since it is now independent
29364 of the elaboration of  @code{Utils}.
29365 This separation of concerns also corresponds to
29366 a generally sound engineering principle of separating declarations
29367 from instances. This version of the program also compiles, binds, links,
29368 and executes, generating the expected output.
29369
29370 @item
29371 Use No_Entry_Calls_In_Elaboration_Code restriction.
29372 @cindex No_Entry_Calls_In_Elaboration_Code
29373
29374 The previous two approaches described how a program can be restructured
29375 to avoid the special problems caused by library task bodies. in practice,
29376 however, such restructuring may be difficult to apply to existing legacy code,
29377 so we must consider solutions that do not require massive rewriting.
29378
29379 Let us consider more carefully why our original sample program works
29380 under the dynamic model of elaboration. The reason is that the code
29381 in the task body blocks immediately on the @code{accept}
29382 statement. Now of course there is nothing to prohibit elaboration
29383 code from making entry calls (for example from another library level task),
29384 so we cannot tell in isolation that
29385 the task will not execute the accept statement  during elaboration.
29386
29387 However, in practice it is very unusual to see elaboration code
29388 make any entry calls, and the pattern of tasks starting
29389 at elaboration time and then immediately blocking on @code{accept} or
29390 @code{select} statements is very common. What this means is that
29391 the compiler is being too pessimistic when it analyzes the
29392 whole package body as though it might be executed at elaboration
29393 time.
29394
29395 If we know that the elaboration code contains no entry calls, (a very safe
29396 assumption most of the time, that could almost be made the default
29397 behavior), then we can compile all units of the program under control
29398 of the following configuration pragma:
29399
29400 @smallexample
29401 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
29402 @end smallexample
29403
29404 @noindent
29405 This pragma can be placed in the @file{gnat.adc} file in the usual
29406 manner. If we take our original unmodified program and compile it
29407 in the presence of a @file{gnat.adc} containing the above pragma,
29408 then once again, we can compile, bind, link, and execute, obtaining
29409 the expected result. In the presence of this pragma, the compiler does
29410 not trace calls in a task body, that appear after the first @code{accept}
29411 or @code{select} statement, and therefore does not report a potential
29412 circularity in the original program.
29413
29414 The compiler will check to the extent it can that the above
29415 restriction is not violated, but it is not always possible to do a
29416 complete check at compile time, so it is important to use this
29417 pragma only if the stated restriction is in fact met, that is to say
29418 no task receives an entry call before elaboration of all units is completed.
29419
29420 @end itemize
29421
29422 @node Mixing Elaboration Models
29423 @section Mixing Elaboration Models
29424 @noindent
29425 So far, we have assumed that the entire program is either compiled
29426 using the dynamic model or static model, ensuring consistency. It
29427 is possible to mix the two models, but rules have to be followed
29428 if this mixing is done to ensure that elaboration checks are not
29429 omitted.
29430
29431 The basic rule is that @emph{a unit compiled with the static model cannot
29432 be @code{with'ed} by a unit compiled with the dynamic model}. The
29433 reason for this is that in the static model, a unit assumes that
29434 its clients guarantee to use (the equivalent of) pragma
29435 @code{Elaborate_All} so that no elaboration checks are required
29436 in inner subprograms, and this assumption is violated if the
29437 client is compiled with dynamic checks.
29438
29439 The precise rule is as follows. A unit that is compiled with dynamic
29440 checks can only @code{with} a unit that meets at least one of the
29441 following criteria:
29442
29443 @itemize @bullet
29444
29445 @item
29446 The @code{with'ed} unit is itself compiled with dynamic elaboration
29447 checks (that is with the @option{-gnatE} switch.
29448
29449 @item
29450 The @code{with'ed} unit is an internal GNAT implementation unit from
29451 the System, Interfaces, Ada, or GNAT hierarchies.
29452
29453 @item
29454 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
29455
29456 @item
29457 The @code{with'ing} unit (that is the client) has an explicit pragma
29458 @code{Elaborate_All} for the @code{with'ed} unit.
29459
29460 @end itemize
29461
29462 @noindent
29463 If this rule is violated, that is if a unit with dynamic elaboration
29464 checks @code{with's} a unit that does not meet one of the above four
29465 criteria, then the binder (@code{gnatbind}) will issue a warning
29466 similar to that in the following example:
29467
29468 @smallexample
29469 warning: "x.ads" has dynamic elaboration checks and with's
29470 warning:   "y.ads" which has static elaboration checks
29471 @end smallexample
29472
29473 @noindent
29474 These warnings indicate that the rule has been violated, and that as a result
29475 elaboration checks may be missed in the resulting executable file.
29476 This warning may be suppressed using the @option{-ws} binder switch
29477 in the usual manner.
29478
29479 One useful application of this mixing rule is in the case of a subsystem
29480 which does not itself @code{with} units from the remainder of the
29481 application. In this case, the entire subsystem can be compiled with
29482 dynamic checks to resolve a circularity in the subsystem, while
29483 allowing the main application that uses this subsystem to be compiled
29484 using the more reliable default static model.
29485
29486 @node What to Do If the Default Elaboration Behavior Fails
29487 @section What to Do If the Default Elaboration Behavior Fails
29488
29489 @noindent
29490 If the binder cannot find an acceptable order, it outputs detailed
29491 diagnostics. For example:
29492 @smallexample
29493 @group
29494 @iftex
29495 @leftskip=0cm
29496 @end iftex
29497 error: elaboration circularity detected
29498 info:   "proc (body)" must be elaborated before "pack (body)"
29499 info:     reason: Elaborate_All probably needed in unit "pack (body)"
29500 info:     recompile "pack (body)" with -gnatwl
29501 info:                             for full details
29502 info:       "proc (body)"
29503 info:         is needed by its spec:
29504 info:       "proc (spec)"
29505 info:         which is withed by:
29506 info:       "pack (body)"
29507 info:  "pack (body)" must be elaborated before "proc (body)"
29508 info:     reason: pragma Elaborate in unit "proc (body)"
29509 @end group
29510
29511 @end smallexample
29512
29513 @noindent
29514 In this case we have a cycle that the binder cannot break. On the one
29515 hand, there is an explicit pragma Elaborate in @code{proc} for
29516 @code{pack}. This means that the body of @code{pack} must be elaborated
29517 before the body of @code{proc}. On the other hand, there is elaboration
29518 code in @code{pack} that calls a subprogram in @code{proc}. This means
29519 that for maximum safety, there should really be a pragma
29520 Elaborate_All in @code{pack} for @code{proc} which would require that
29521 the body of @code{proc} be elaborated before the body of
29522 @code{pack}. Clearly both requirements cannot be satisfied.
29523 Faced with a circularity of this kind, you have three different options.
29524
29525 @table @asis
29526 @item Fix the program
29527 The most desirable option from the point of view of long-term maintenance
29528 is to rearrange the program so that the elaboration problems are avoided.
29529 One useful technique is to place the elaboration code into separate
29530 child packages. Another is to move some of the initialization code to
29531 explicitly called subprograms, where the program controls the order
29532 of initialization explicitly. Although this is the most desirable option,
29533 it may be impractical and involve too much modification, especially in
29534 the case of complex legacy code.
29535
29536 @item Perform dynamic checks
29537 If the compilations are done using the
29538 @option{-gnatE}
29539 (dynamic elaboration check) switch, then GNAT behaves in a quite different
29540 manner. Dynamic checks are generated for all calls that could possibly result
29541 in raising an exception. With this switch, the compiler does not generate
29542 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
29543 exactly as specified in the @cite{Ada Reference Manual}.
29544 The binder will generate
29545 an executable program that may or may not raise @code{Program_Error}, and then
29546 it is the programmer's job to ensure that it does not raise an exception. Note
29547 that it is important to compile all units with the switch, it cannot be used
29548 selectively.
29549
29550 @item Suppress checks
29551 The drawback of dynamic checks is that they generate a
29552 significant overhead at run time, both in space and time. If you
29553 are absolutely sure that your program cannot raise any elaboration
29554 exceptions, and you still want to use the dynamic elaboration model,
29555 then you can use the configuration pragma
29556 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
29557 example this pragma could be placed in the @file{gnat.adc} file.
29558
29559 @item Suppress checks selectively
29560 When you know that certain calls or instantiations in elaboration code cannot
29561 possibly lead to an elaboration error, and the binder nevertheless complains
29562 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
29563 elaboration circularities, it is possible to remove those warnings locally and
29564 obtain a program that will bind. Clearly this can be unsafe, and it is the
29565 responsibility of the programmer to make sure that the resulting program has no
29566 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
29567 used with different granularity to suppress warnings and break elaboration
29568 circularities:
29569
29570 @itemize @bullet
29571 @item
29572 Place the pragma that names the called subprogram in the declarative part
29573 that contains the call.
29574
29575 @item
29576 Place the pragma in the declarative part, without naming an entity. This
29577 disables warnings on all calls in the corresponding  declarative region.
29578
29579 @item
29580 Place the pragma in the package spec that declares the called subprogram,
29581 and name the subprogram. This disables warnings on all elaboration calls to
29582 that subprogram.
29583
29584 @item
29585 Place the pragma in the package spec that declares the called subprogram,
29586 without naming any entity. This disables warnings on all elaboration calls to
29587 all subprograms declared in this spec.
29588
29589 @item Use Pragma Elaborate
29590 As previously described in section @xref{Treatment of Pragma Elaborate},
29591 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
29592 that no elaboration checks are required on calls to the designated unit.
29593 There may be cases in which the caller knows that no transitive calls
29594 can occur, so that a @code{pragma Elaborate} will be sufficient in a
29595 case where @code{pragma Elaborate_All} would cause a circularity.
29596 @end itemize
29597
29598 @noindent
29599 These five cases are listed in order of decreasing safety, and therefore
29600 require increasing programmer care in their application. Consider the
29601 following program:
29602
29603 @smallexample @c adanocomment
29604 package Pack1 is
29605   function F1 return Integer;
29606   X1 : Integer;
29607 end Pack1;
29608
29609 package Pack2 is
29610   function F2 return Integer;
29611   function Pure (x : integer) return integer;
29612   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
29613   --  pragma Suppress (Elaboration_Check);              -- (4)
29614 end Pack2;
29615
29616 with Pack2;
29617 package body Pack1 is
29618   function F1 return Integer is
29619   begin
29620     return 100;
29621   end F1;
29622   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
29623 begin
29624   declare
29625     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
29626     --  pragma Suppress(Elaboration_Check);             -- (2)
29627   begin
29628     X1 := Pack2.F2 + 1;                --  Elab. call (2)
29629   end;
29630 end Pack1;
29631
29632 with Pack1;
29633 package body Pack2 is
29634   function F2 return Integer is
29635   begin
29636      return Pack1.F1;
29637   end F2;
29638   function Pure (x : integer) return integer is
29639   begin
29640      return x ** 3 - 3 * x;
29641   end;
29642 end Pack2;
29643
29644 with Pack1, Ada.Text_IO;
29645 procedure Proc3 is
29646 begin
29647   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
29648 end Proc3;
29649 @end smallexample
29650 In the absence of any pragmas, an attempt to bind this program produces
29651 the following diagnostics:
29652 @smallexample
29653 @group
29654 @iftex
29655 @leftskip=.5cm
29656 @end iftex
29657 error: elaboration circularity detected
29658 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
29659 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
29660 info:       recompile "pack1 (body)" with -gnatwl for full details
29661 info:          "pack1 (body)"
29662 info:             must be elaborated along with its spec:
29663 info:          "pack1 (spec)"
29664 info:             which is withed by:
29665 info:          "pack2 (body)"
29666 info:             which must be elaborated along with its spec:
29667 info:          "pack2 (spec)"
29668 info:             which is withed by:
29669 info:          "pack1 (body)"
29670 @end group
29671 @end smallexample
29672 The sources of the circularity are the two calls to @code{Pack2.Pure} and
29673 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
29674 F2 is safe, even though F2 calls F1, because the call appears after the
29675 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
29676 remove the warning on the call. It is also possible to use pragma (2)
29677 because there are no other potentially unsafe calls in the block.
29678
29679 @noindent
29680 The call to @code{Pure} is safe because this function does not depend on the
29681 state of @code{Pack2}. Therefore any call to this function is safe, and it
29682 is correct to place pragma (3) in the corresponding package spec.
29683
29684 @noindent
29685 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
29686 warnings on all calls to functions declared therein. Note that this is not
29687 necessarily safe, and requires more detailed examination of the subprogram
29688 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
29689 be already elaborated.
29690 @end table
29691
29692 @noindent
29693 It is hard to generalize on which of these four approaches should be
29694 taken. Obviously if it is possible to fix the program so that the default
29695 treatment works, this is preferable, but this may not always be practical.
29696 It is certainly simple enough to use
29697 @option{-gnatE}
29698 but the danger in this case is that, even if the GNAT binder
29699 finds a correct elaboration order, it may not always do so,
29700 and certainly a binder from another Ada compiler might not. A
29701 combination of testing and analysis (for which the warnings generated
29702 with the
29703 @option{-gnatwl}
29704 switch can be useful) must be used to ensure that the program is free
29705 of errors. One switch that is useful in this testing is the
29706 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
29707 switch for
29708 @code{gnatbind}.
29709 Normally the binder tries to find an order that has the best chance
29710 of avoiding elaboration problems. However, if this switch is used, the binder
29711 plays a devil's advocate role, and tries to choose the order that
29712 has the best chance of failing. If your program works even with this
29713 switch, then it has a better chance of being error free, but this is still
29714 not a guarantee.
29715
29716 For an example of this approach in action, consider the C-tests (executable
29717 tests) from the ACVC suite. If these are compiled and run with the default
29718 treatment, then all but one of them succeed without generating any error
29719 diagnostics from the binder. However, there is one test that fails, and
29720 this is not surprising, because the whole point of this test is to ensure
29721 that the compiler can handle cases where it is impossible to determine
29722 a correct order statically, and it checks that an exception is indeed
29723 raised at run time.
29724
29725 This one test must be compiled and run using the
29726 @option{-gnatE}
29727 switch, and then it passes. Alternatively, the entire suite can
29728 be run using this switch. It is never wrong to run with the dynamic
29729 elaboration switch if your code is correct, and we assume that the
29730 C-tests are indeed correct (it is less efficient, but efficiency is
29731 not a factor in running the ACVC tests.)
29732
29733 @node Elaboration for Access-to-Subprogram Values
29734 @section Elaboration for Access-to-Subprogram Values
29735 @cindex Access-to-subprogram
29736
29737 @noindent
29738 Access-to-subprogram types (introduced in Ada 95) complicate
29739 the handling of elaboration. The trouble is that it becomes
29740 impossible to tell at compile time which procedure
29741 is being called. This means that it is not possible for the binder
29742 to analyze the elaboration requirements in this case.
29743
29744 If at the point at which the access value is created
29745 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
29746 the body of the subprogram is
29747 known to have been elaborated, then the access value is safe, and its use
29748 does not require a check. This may be achieved by appropriate arrangement
29749 of the order of declarations if the subprogram is in the current unit,
29750 or, if the subprogram is in another unit, by using pragma
29751 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
29752 on the referenced unit.
29753
29754 If the referenced body is not known to have been elaborated at the point
29755 the access value is created, then any use of the access value must do a
29756 dynamic check, and this dynamic check will fail and raise a
29757 @code{Program_Error} exception if the body has not been elaborated yet.
29758 GNAT will generate the necessary checks, and in addition, if the
29759 @option{-gnatwl}
29760 switch is set, will generate warnings that such checks are required.
29761
29762 The use of dynamic dispatching for tagged types similarly generates
29763 a requirement for dynamic checks, and premature calls to any primitive
29764 operation of a tagged type before the body of the operation has been
29765 elaborated, will result in the raising of @code{Program_Error}.
29766
29767 @node Summary of Procedures for Elaboration Control
29768 @section Summary of Procedures for Elaboration Control
29769 @cindex Elaboration control
29770
29771 @noindent
29772 First, compile your program with the default options, using none of
29773 the special elaboration control switches. If the binder successfully
29774 binds your program, then you can be confident that, apart from issues
29775 raised by the use of access-to-subprogram types and dynamic dispatching,
29776 the program is free of elaboration errors. If it is important that the
29777 program be portable, then use the
29778 @option{-gnatwl}
29779 switch to generate warnings about missing @code{Elaborate} or
29780 @code{Elaborate_All} pragmas, and supply the missing pragmas.
29781
29782 If the program fails to bind using the default static elaboration
29783 handling, then you can fix the program to eliminate the binder
29784 message, or recompile the entire program with the
29785 @option{-gnatE} switch to generate dynamic elaboration checks,
29786 and, if you are sure there really are no elaboration problems,
29787 use a global pragma @code{Suppress (Elaboration_Check)}.
29788
29789 @node Other Elaboration Order Considerations
29790 @section Other Elaboration Order Considerations
29791 @noindent
29792 This section has been entirely concerned with the issue of finding a valid
29793 elaboration order, as defined by the Ada Reference Manual. In a case
29794 where several elaboration orders are valid, the task is to find one
29795 of the possible valid elaboration orders (and the static model in GNAT
29796 will ensure that this is achieved).
29797
29798 The purpose of the elaboration rules in the Ada Reference Manual is to
29799 make sure that no entity is accessed before it has been elaborated. For
29800 a subprogram, this means that the spec and body must have been elaborated
29801 before the subprogram is called. For an object, this means that the object
29802 must have been elaborated before its value is read or written. A violation
29803 of either of these two requirements is an access before elaboration order,
29804 and this section has been all about avoiding such errors.
29805
29806 In the case where more than one order of elaboration is possible, in the
29807 sense that access before elaboration errors are avoided, then any one of
29808 the orders is ``correct'' in the sense that it meets the requirements of
29809 the Ada Reference Manual, and no such error occurs.
29810
29811 However, it may be the case for a given program, that there are
29812 constraints on the order of elaboration that come not from consideration
29813 of avoiding elaboration errors, but rather from extra-lingual logic
29814 requirements. Consider this example:
29815
29816 @smallexample @c ada
29817 with Init_Constants;
29818 package Constants is
29819    X : Integer := 0;
29820    Y : Integer := 0;
29821 end Constants;
29822
29823 package Init_Constants is
29824    procedure P; -- require a body
29825 end Init_Constants;
29826
29827 with Constants;
29828 package body Init_Constants is
29829    procedure P is begin null; end;
29830 begin
29831    Constants.X := 3;
29832    Constants.Y := 4;
29833 end Init_Constants;
29834
29835 with Constants;
29836 package Calc is
29837    Z : Integer := Constants.X + Constants.Y;
29838 end Calc;
29839
29840 with Calc;
29841 with Text_IO; use Text_IO;
29842 procedure Main is
29843 begin
29844    Put_Line (Calc.Z'Img);
29845 end Main;
29846 @end smallexample
29847
29848 @noindent
29849 In this example, there is more than one valid order of elaboration. For
29850 example both the following are correct orders:
29851
29852 @smallexample
29853 Init_Constants spec
29854 Constants spec
29855 Calc spec
29856 Init_Constants body
29857 Main body
29858
29859   and
29860
29861 Init_Constants spec
29862 Init_Constants body
29863 Constants spec
29864 Calc spec
29865 Main body
29866 @end smallexample
29867
29868 @noindent
29869 There is no language rule to prefer one or the other, both are correct
29870 from an order of elaboration point of view. But the programmatic effects
29871 of the two orders are very different. In the first, the elaboration routine
29872 of @code{Calc} initializes @code{Z} to zero, and then the main program
29873 runs with this value of zero. But in the second order, the elaboration
29874 routine of @code{Calc} runs after the body of Init_Constants has set
29875 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
29876 runs.
29877
29878 One could perhaps by applying pretty clever non-artificial intelligence
29879 to the situation guess that it is more likely that the second order of
29880 elaboration is the one desired, but there is no formal linguistic reason
29881 to prefer one over the other. In fact in this particular case, GNAT will
29882 prefer the second order, because of the rule that bodies are elaborated
29883 as soon as possible, but it's just luck that this is what was wanted
29884 (if indeed the second order was preferred).
29885
29886 If the program cares about the order of elaboration routines in a case like
29887 this, it is important to specify the order required. In this particular
29888 case, that could have been achieved by adding to the spec of Calc:
29889
29890 @smallexample @c ada
29891 pragma Elaborate_All (Constants);
29892 @end smallexample
29893
29894 @noindent
29895 which requires that the body (if any) and spec of @code{Constants},
29896 as well as the body and spec of any unit @code{with}'ed by
29897 @code{Constants} be elaborated before @code{Calc} is elaborated.
29898
29899 Clearly no automatic method can always guess which alternative you require,
29900 and if you are working with legacy code that had constraints of this kind
29901 which were not properly specified by adding @code{Elaborate} or
29902 @code{Elaborate_All} pragmas, then indeed it is possible that two different
29903 compilers can choose different orders.
29904
29905 However, GNAT does attempt to diagnose the common situation where there
29906 are uninitialized variables in the visible part of a package spec, and the
29907 corresponding package body has an elaboration block that directly or
29908 indirectly initialized one or more of these variables. This is the situation
29909 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
29910 a warning that suggests this addition if it detects this situation.
29911
29912 The @code{gnatbind}
29913 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
29914 out problems. This switch causes bodies to be elaborated as late as possible
29915 instead of as early as possible. In the example above, it would have forced
29916 the choice of the first elaboration order. If you get different results
29917 when using this switch, and particularly if one set of results is right,
29918 and one is wrong as far as you are concerned, it shows that you have some
29919 missing @code{Elaborate} pragmas. For the example above, we have the
29920 following output:
29921
29922 @smallexample
29923 gnatmake -f -q main
29924 main
29925  7
29926 gnatmake -f -q main -bargs -p
29927 main
29928  0
29929 @end smallexample
29930
29931 @noindent
29932 It is of course quite unlikely that both these results are correct, so
29933 it is up to you in a case like this to investigate the source of the
29934 difference, by looking at the two elaboration orders that are chosen,
29935 and figuring out which is correct, and then adding the necessary
29936 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
29937
29938
29939
29940 @c *******************************
29941 @node Conditional Compilation
29942 @appendix Conditional Compilation
29943 @c *******************************
29944 @cindex Conditional compilation
29945
29946 @noindent
29947 It is often necessary to arrange for a single source program
29948 to serve multiple purposes, where it is compiled in different
29949 ways to achieve these different goals. Some examples of the
29950 need for this feature are
29951
29952 @itemize @bullet
29953 @item  Adapting a program to a different hardware environment
29954 @item  Adapting a program to a different target architecture
29955 @item  Turning debugging features on and off
29956 @item  Arranging for a program to compile with different compilers
29957 @end itemize
29958
29959 @noindent
29960 In C, or C++, the typical approach would be to use the preprocessor
29961 that is defined as part of the language. The Ada language does not
29962 contain such a feature. This is not an oversight, but rather a very
29963 deliberate design decision, based on the experience that overuse of
29964 the preprocessing features in C and C++ can result in programs that
29965 are extremely difficult to maintain. For example, if we have ten
29966 switches that can be on or off, this means that there are a thousand
29967 separate programs, any one of which might not even be syntactically
29968 correct, and even if syntactically correct, the resulting program
29969 might not work correctly. Testing all combinations can quickly become
29970 impossible.
29971
29972 Nevertheless, the need to tailor programs certainly exists, and in
29973 this Appendix we will discuss how this can
29974 be achieved using Ada in general, and GNAT in particular.
29975
29976 @menu
29977 * Use of Boolean Constants::
29978 * Debugging - A Special Case::
29979 * Conditionalizing Declarations::
29980 * Use of Alternative Implementations::
29981 * Preprocessing::
29982 @end menu
29983
29984 @node Use of Boolean Constants
29985 @section Use of Boolean Constants
29986
29987 @noindent
29988 In the case where the difference is simply which code
29989 sequence is executed, the cleanest solution is to use Boolean
29990 constants to control which code is executed.
29991
29992 @smallexample @c ada
29993 @group
29994 FP_Initialize_Required : constant Boolean := True;
29995 @dots{}
29996 if FP_Initialize_Required then
29997 @dots{}
29998 end if;
29999 @end group
30000 @end smallexample
30001
30002 @noindent
30003 Not only will the code inside the @code{if} statement not be executed if
30004 the constant Boolean is @code{False}, but it will also be completely
30005 deleted from the program.
30006 However, the code is only deleted after the @code{if} statement
30007 has been checked for syntactic and semantic correctness.
30008 (In contrast, with preprocessors the code is deleted before the
30009 compiler ever gets to see it, so it is not checked until the switch
30010 is turned on.)
30011 @cindex Preprocessors (contrasted with conditional compilation)
30012
30013 Typically the Boolean constants will be in a separate package,
30014 something like:
30015
30016 @smallexample @c ada
30017 @group
30018 package Config is
30019    FP_Initialize_Required : constant Boolean := True;
30020    Reset_Available        : constant Boolean := False;
30021    @dots{}
30022 end Config;
30023 @end group
30024 @end smallexample
30025
30026 @noindent
30027 The @code{Config} package exists in multiple forms for the various targets,
30028 with an appropriate script selecting the version of @code{Config} needed.
30029 Then any other unit requiring conditional compilation can do a @code{with}
30030 of @code{Config} to make the constants visible.
30031
30032
30033 @node Debugging - A Special Case
30034 @section Debugging - A Special Case
30035
30036 @noindent
30037 A common use of conditional code is to execute statements (for example
30038 dynamic checks, or output of intermediate results) under control of a
30039 debug switch, so that the debugging behavior can be turned on and off.
30040 This can be done using a Boolean constant to control whether the code
30041 is active:
30042
30043 @smallexample @c ada
30044 @group
30045 if Debugging then
30046    Put_Line ("got to the first stage!");
30047 end if;
30048 @end group
30049 @end smallexample
30050
30051 @noindent
30052 or
30053
30054 @smallexample @c ada
30055 @group
30056 if Debugging and then Temperature > 999.0 then
30057    raise Temperature_Crazy;
30058 end if;
30059 @end group
30060 @end smallexample
30061
30062 @noindent
30063 Since this is a common case, there are special features to deal with
30064 this in a convenient manner. For the case of tests, Ada 2005 has added
30065 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
30066 @cindex pragma @code{Assert}
30067 on the @code{Assert} pragma that has always been available in GNAT, so this
30068 feature may be used with GNAT even if you are not using Ada 2005 features.
30069 The use of pragma @code{Assert} is described in
30070 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
30071 example, the last test could be written:
30072
30073 @smallexample @c ada
30074 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
30075 @end smallexample
30076
30077 @noindent
30078 or simply
30079
30080 @smallexample @c ada
30081 pragma Assert (Temperature <= 999.0);
30082 @end smallexample
30083
30084 @noindent
30085 In both cases, if assertions are active and the temperature is excessive,
30086 the exception @code{Assert_Failure} will be raised, with the given string in
30087 the first case or a string indicating the location of the pragma in the second
30088 case used as the exception message.
30089
30090 You can turn assertions on and off by using the @code{Assertion_Policy}
30091 pragma.
30092 @cindex pragma @code{Assertion_Policy}
30093 This is an Ada 2005 pragma which is implemented in all modes by
30094 GNAT, but only in the latest versions of GNAT which include Ada 2005
30095 capability. Alternatively, you can use the @option{-gnata} switch
30096 @cindex @option{-gnata} switch
30097 to enable assertions from the command line (this is recognized by all versions
30098 of GNAT).
30099
30100 For the example above with the @code{Put_Line}, the GNAT-specific pragma
30101 @code{Debug} can be used:
30102 @cindex pragma @code{Debug}
30103
30104 @smallexample @c ada
30105 pragma Debug (Put_Line ("got to the first stage!"));
30106 @end smallexample
30107
30108 @noindent
30109 If debug pragmas are enabled, the argument, which must be of the form of
30110 a procedure call, is executed (in this case, @code{Put_Line} will be called).
30111 Only one call can be present, but of course a special debugging procedure
30112 containing any code you like can be included in the program and then
30113 called in a pragma @code{Debug} argument as needed.
30114
30115 One advantage of pragma @code{Debug} over the @code{if Debugging then}
30116 construct is that pragma @code{Debug} can appear in declarative contexts,
30117 such as at the very beginning of a procedure, before local declarations have
30118 been elaborated.
30119
30120 Debug pragmas are enabled using either the @option{-gnata} switch that also
30121 controls assertions, or with a separate Debug_Policy pragma.
30122 @cindex pragma @code{Debug_Policy}
30123 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
30124 in Ada 95 and Ada 83 programs as well), and is analogous to
30125 pragma @code{Assertion_Policy} to control assertions.
30126
30127 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
30128 and thus they can appear in @file{gnat.adc} if you are not using a
30129 project file, or in the file designated to contain configuration pragmas
30130 in a project file.
30131 They then apply to all subsequent compilations. In practice the use of
30132 the @option{-gnata} switch is often the most convenient method of controlling
30133 the status of these pragmas.
30134
30135 Note that a pragma is not a statement, so in contexts where a statement
30136 sequence is required, you can't just write a pragma on its own. You have
30137 to add a @code{null} statement.
30138
30139 @smallexample @c ada
30140 @group
30141 if @dots{} then
30142    @dots{} -- some statements
30143 else
30144    pragma Assert (Num_Cases < 10);
30145    null;
30146 end if;
30147 @end group
30148 @end smallexample
30149
30150
30151 @node Conditionalizing Declarations
30152 @section Conditionalizing Declarations
30153
30154 @noindent
30155 In some cases, it may be necessary to conditionalize declarations to meet
30156 different requirements. For example we might want a bit string whose length
30157 is set to meet some hardware message requirement.
30158
30159 In some cases, it may be possible to do this using declare blocks controlled
30160 by conditional constants:
30161
30162 @smallexample @c ada
30163 @group
30164 if Small_Machine then
30165    declare
30166       X : Bit_String (1 .. 10);
30167    begin
30168       @dots{}
30169    end;
30170 else
30171    declare
30172       X : Large_Bit_String (1 .. 1000);
30173    begin
30174       @dots{}
30175    end;
30176 end if;
30177 @end group
30178 @end smallexample
30179
30180 @noindent
30181 Note that in this approach, both declarations are analyzed by the
30182 compiler so this can only be used where both declarations are legal,
30183 even though one of them will not be used.
30184
30185 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, or
30186 Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
30187 that are parameterized by these constants. For example
30188
30189 @smallexample @c ada
30190 @group
30191 for Rec use
30192   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
30193 end record;
30194 @end group
30195 @end smallexample
30196
30197 @noindent
30198 If @code{Bits_Per_Word} is set to 32, this generates either
30199
30200 @smallexample @c ada
30201 @group
30202 for Rec use
30203   Field1 at 0 range 0 .. 32;
30204 end record;
30205 @end group
30206 @end smallexample
30207
30208 @noindent
30209 for the big endian case, or
30210
30211 @smallexample @c ada
30212 @group
30213 for Rec use record
30214   Field1 at 0 range 10 .. 32;
30215 end record;
30216 @end group
30217 @end smallexample
30218
30219 @noindent
30220 for the little endian case. Since a powerful subset of Ada expression
30221 notation is usable for creating static constants, clever use of this
30222 feature can often solve quite difficult problems in conditionalizing
30223 compilation (note incidentally that in Ada 95, the little endian
30224 constant was introduced as @code{System.Default_Bit_Order}, so you do not
30225 need to define this one yourself).
30226
30227
30228 @node Use of Alternative Implementations
30229 @section Use of Alternative Implementations
30230
30231 @noindent
30232 In some cases, none of the approaches described above are adequate. This
30233 can occur for example if the set of declarations required is radically
30234 different for two different configurations.
30235
30236 In this situation, the official Ada way of dealing with conditionalizing
30237 such code is to write separate units for the different cases. As long as
30238 this does not result in excessive duplication of code, this can be done
30239 without creating maintenance problems. The approach is to share common
30240 code as far as possible, and then isolate the code and declarations
30241 that are different. Subunits are often a convenient method for breaking
30242 out a piece of a unit that is to be conditionalized, with separate files
30243 for different versions of the subunit for different targets, where the
30244 build script selects the right one to give to the compiler.
30245 @cindex Subunits (and conditional compilation)
30246
30247 As an example, consider a situation where a new feature in Ada 2005
30248 allows something to be done in a really nice way. But your code must be able
30249 to compile with an Ada 95 compiler. Conceptually you want to say:
30250
30251 @smallexample @c ada
30252 @group
30253 if Ada_2005 then
30254    @dots{} neat Ada 2005 code
30255 else
30256    @dots{} not quite as neat Ada 95 code
30257 end if;
30258 @end group
30259 @end smallexample
30260
30261 @noindent
30262 where @code{Ada_2005} is a Boolean constant.
30263
30264 But this won't work when @code{Ada_2005} is set to @code{False},
30265 since the @code{then} clause will be illegal for an Ada 95 compiler.
30266 (Recall that although such unreachable code would eventually be deleted
30267 by the compiler, it still needs to be legal.  If it uses features
30268 introduced in Ada 2005, it will be illegal in Ada 95.)
30269
30270 So instead we write
30271
30272 @smallexample @c ada
30273 procedure Insert is separate;
30274 @end smallexample
30275
30276 @noindent
30277 Then we have two files for the subunit @code{Insert}, with the two sets of
30278 code.
30279 If the package containing this is called @code{File_Queries}, then we might
30280 have two files
30281
30282 @itemize @bullet
30283 @item    @file{file_queries-insert-2005.adb}
30284 @item    @file{file_queries-insert-95.adb}
30285 @end itemize
30286
30287 @noindent
30288 and the build script renames the appropriate file to
30289
30290 @smallexample
30291 file_queries-insert.adb
30292 @end smallexample
30293
30294 @noindent
30295 and then carries out the compilation.
30296
30297 This can also be done with project files' naming schemes. For example:
30298
30299 @smallexample @c project
30300 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
30301 @end smallexample
30302
30303 @noindent
30304 Note also that with project files it is desirable to use a different extension
30305 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
30306 conflict may arise through another commonly used feature: to declare as part
30307 of the project a set of directories containing all the sources obeying the
30308 default naming scheme.
30309
30310 The use of alternative units is certainly feasible in all situations,
30311 and for example the Ada part of the GNAT run-time is conditionalized
30312 based on the target architecture using this approach. As a specific example,
30313 consider the implementation of the AST feature in VMS. There is one
30314 spec:
30315
30316 @smallexample
30317 s-asthan.ads
30318 @end smallexample
30319
30320 @noindent
30321 which is the same for all architectures, and three bodies:
30322
30323 @table @file
30324 @item    s-asthan.adb
30325 used for all non-VMS operating systems
30326 @item    s-asthan-vms-alpha.adb
30327 used for VMS on the Alpha
30328 @item    s-asthan-vms-ia64.adb
30329 used for VMS on the ia64
30330 @end table
30331
30332 @noindent
30333 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
30334 this operating system feature is not available, and the two remaining
30335 versions interface with the corresponding versions of VMS to provide
30336 VMS-compatible AST handling. The GNAT build script knows the architecture
30337 and operating system, and automatically selects the right version,
30338 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
30339
30340 Another style for arranging alternative implementations is through Ada's
30341 access-to-subprogram facility.
30342 In case some functionality is to be conditionally included,
30343 you can declare an access-to-procedure variable @code{Ref} that is initialized
30344 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
30345 when appropriate.
30346 In some library package, set @code{Ref} to @code{Proc'Access} for some
30347 procedure @code{Proc} that performs the relevant processing.
30348 The initialization only occurs if the library package is included in the
30349 program.
30350 The same idea can also be implemented using tagged types and dispatching
30351 calls.
30352
30353
30354 @node Preprocessing
30355 @section Preprocessing
30356 @cindex Preprocessing
30357
30358 @noindent
30359 Although it is quite possible to conditionalize code without the use of
30360 C-style preprocessing, as described earlier in this section, it is
30361 nevertheless convenient in some cases to use the C approach. Moreover,
30362 older Ada compilers have often provided some preprocessing capability,
30363 so legacy code may depend on this approach, even though it is not
30364 standard.
30365
30366 To accommodate such use, GNAT provides a preprocessor (modeled to a large
30367 extent on the various preprocessors that have been used
30368 with legacy code on other compilers, to enable easier transition).
30369
30370 The preprocessor may be used in two separate modes. It can be used quite
30371 separately from the compiler, to generate a separate output source file
30372 that is then fed to the compiler as a separate step. This is the
30373 @code{gnatprep} utility, whose use is fully described in
30374 @ref{Preprocessing Using gnatprep}.
30375 @cindex @code{gnatprep}
30376
30377 The preprocessing language allows such constructs as
30378
30379 @smallexample
30380 @group
30381 #if DEBUG or PRIORITY > 4 then
30382    bunch of declarations
30383 #else
30384    completely different bunch of declarations
30385 #end if;
30386 @end group
30387 @end smallexample
30388
30389 @noindent
30390 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
30391 defined either on the command line or in a separate file.
30392
30393 The other way of running the preprocessor is even closer to the C style and
30394 often more convenient. In this approach the preprocessing is integrated into
30395 the compilation process. The compiler is fed the preprocessor input which
30396 includes @code{#if} lines etc, and then the compiler carries out the
30397 preprocessing internally and processes the resulting output.
30398 For more details on this approach, see @ref{Integrated Preprocessing}.
30399
30400
30401 @c *******************************
30402 @node Inline Assembler
30403 @appendix Inline Assembler
30404 @c *******************************
30405
30406 @noindent
30407 If you need to write low-level software that interacts directly
30408 with the hardware, Ada provides two ways to incorporate assembly
30409 language code into your program.  First, you can import and invoke
30410 external routines written in assembly language, an Ada feature fully
30411 supported by GNAT@.  However, for small sections of code it may be simpler
30412 or more efficient to include assembly language statements directly
30413 in your Ada source program, using the facilities of the implementation-defined
30414 package @code{System.Machine_Code}, which incorporates the gcc
30415 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
30416 including the following:
30417
30418 @itemize @bullet
30419 @item No need to use non-Ada tools
30420 @item Consistent interface over different targets
30421 @item Automatic usage of the proper calling conventions
30422 @item Access to Ada constants and variables
30423 @item Definition of intrinsic routines
30424 @item Possibility of inlining a subprogram comprising assembler code
30425 @item Code optimizer can take Inline Assembler code into account
30426 @end itemize
30427
30428 This chapter presents a series of examples to show you how to use
30429 the Inline Assembler.  Although it focuses on the Intel x86,
30430 the general approach applies also to other processors.
30431 It is assumed that you are familiar with Ada
30432 and with assembly language programming.
30433
30434 @menu
30435 * Basic Assembler Syntax::
30436 * A Simple Example of Inline Assembler::
30437 * Output Variables in Inline Assembler::
30438 * Input Variables in Inline Assembler::
30439 * Inlining Inline Assembler Code::
30440 * Other Asm Functionality::
30441 @end menu
30442
30443 @c ---------------------------------------------------------------------------
30444 @node Basic Assembler Syntax
30445 @section Basic Assembler Syntax
30446
30447 @noindent
30448 The assembler used by GNAT and gcc is based not on the Intel assembly
30449 language, but rather on a language that descends from the AT&T Unix
30450 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
30451 The following table summarizes the main features of @emph{as} syntax
30452 and points out the differences from the Intel conventions.
30453 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
30454 pre-processor) documentation for further information.
30455
30456 @table @asis
30457 @item Register names
30458 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
30459 @*
30460 Intel: No extra punctuation; for example @code{eax}
30461
30462 @item Immediate operand
30463 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
30464 @*
30465 Intel: No extra punctuation; for example @code{4}
30466
30467 @item Address
30468 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
30469 @*
30470 Intel: No extra punctuation; for example @code{loc}
30471
30472 @item Memory contents
30473 gcc / @emph{as}: No extra punctuation; for example @code{loc}
30474 @*
30475 Intel: Square brackets; for example @code{[loc]}
30476
30477 @item Register contents
30478 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
30479 @*
30480 Intel: Square brackets; for example @code{[eax]}
30481
30482 @item Hexadecimal numbers
30483 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
30484 @*
30485 Intel: Trailing ``h''; for example @code{A0h}
30486
30487 @item Operand size
30488 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
30489 a 16-bit word
30490 @*
30491 Intel: Implicit, deduced by assembler; for example @code{mov}
30492
30493 @item Instruction repetition
30494 gcc / @emph{as}: Split into two lines; for example
30495 @*
30496 @code{rep}
30497 @*
30498 @code{stosl}
30499 @*
30500 Intel: Keep on one line; for example @code{rep stosl}
30501
30502 @item Order of operands
30503 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
30504 @*
30505 Intel: Destination first; for example @code{mov eax, 4}
30506 @end table
30507
30508 @c ---------------------------------------------------------------------------
30509 @node A Simple Example of Inline Assembler
30510 @section A Simple Example of Inline Assembler
30511
30512 @noindent
30513 The following example will generate a single assembly language statement,
30514 @code{nop}, which does nothing.  Despite its lack of run-time effect,
30515 the example will be useful in illustrating the basics of
30516 the Inline Assembler facility.
30517
30518 @smallexample @c ada
30519 @group
30520 with System.Machine_Code; use System.Machine_Code;
30521 procedure Nothing is
30522 begin
30523    Asm ("nop");
30524 end Nothing;
30525 @end group
30526 @end smallexample
30527
30528 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
30529 here it takes one parameter, a @emph{template string} that must be a static
30530 expression and that will form the generated instruction.
30531 @code{Asm} may be regarded as a compile-time procedure that parses
30532 the template string and additional parameters (none here),
30533 from which it generates a sequence of assembly language instructions.
30534
30535 The examples in this chapter will illustrate several of the forms
30536 for invoking @code{Asm}; a complete specification of the syntax
30537 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
30538 Manual}.
30539
30540 Under the standard GNAT conventions, the @code{Nothing} procedure
30541 should be in a file named @file{nothing.adb}.
30542 You can build the executable in the usual way:
30543 @smallexample
30544 gnatmake nothing
30545 @end smallexample
30546 However, the interesting aspect of this example is not its run-time behavior
30547 but rather the generated assembly code.
30548 To see this output, invoke the compiler as follows:
30549 @smallexample
30550    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
30551 @end smallexample
30552 where the options are:
30553
30554 @table @code
30555 @item -c
30556 compile only (no bind or link)
30557 @item -S
30558 generate assembler listing
30559 @item -fomit-frame-pointer
30560 do not set up separate stack frames
30561 @item -gnatp
30562 do not add runtime checks
30563 @end table
30564
30565 This gives a human-readable assembler version of the code. The resulting
30566 file will have the same name as the Ada source file, but with a @code{.s}
30567 extension. In our example, the file @file{nothing.s} has the following
30568 contents:
30569
30570 @smallexample
30571 @group
30572 .file "nothing.adb"
30573 gcc2_compiled.:
30574 ___gnu_compiled_ada:
30575 .text
30576    .align 4
30577 .globl __ada_nothing
30578 __ada_nothing:
30579 #APP
30580    nop
30581 #NO_APP
30582    jmp L1
30583    .align 2,0x90
30584 L1:
30585    ret
30586 @end group
30587 @end smallexample
30588
30589 The assembly code you included is clearly indicated by
30590 the compiler, between the @code{#APP} and @code{#NO_APP}
30591 delimiters. The character before the 'APP' and 'NOAPP'
30592 can differ on different targets. For example, GNU/Linux uses '#APP' while
30593 on NT you will see '/APP'.
30594
30595 If you make a mistake in your assembler code (such as using the
30596 wrong size modifier, or using a wrong operand for the instruction) GNAT
30597 will report this error in a temporary file, which will be deleted when
30598 the compilation is finished.  Generating an assembler file will help
30599 in such cases, since you can assemble this file separately using the
30600 @emph{as} assembler that comes with gcc.
30601
30602 Assembling the file using the command
30603
30604 @smallexample
30605 as @file{nothing.s}
30606 @end smallexample
30607 @noindent
30608 will give you error messages whose lines correspond to the assembler
30609 input file, so you can easily find and correct any mistakes you made.
30610 If there are no errors, @emph{as} will generate an object file
30611 @file{nothing.out}.
30612
30613 @c ---------------------------------------------------------------------------
30614 @node Output Variables in Inline Assembler
30615 @section Output Variables in Inline Assembler
30616
30617 @noindent
30618 The examples in this section, showing how to access the processor flags,
30619 illustrate how to specify the destination operands for assembly language
30620 statements.
30621
30622 @smallexample @c ada
30623 @group
30624 with Interfaces; use Interfaces;
30625 with Ada.Text_IO; use Ada.Text_IO;
30626 with System.Machine_Code; use System.Machine_Code;
30627 procedure Get_Flags is
30628    Flags : Unsigned_32;
30629    use ASCII;
30630 begin
30631    Asm ("pushfl"          & LF & HT & -- push flags on stack
30632         "popl %%eax"      & LF & HT & -- load eax with flags
30633         "movl %%eax, %0",             -- store flags in variable
30634         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30635    Put_Line ("Flags register:" & Flags'Img);
30636 end Get_Flags;
30637 @end group
30638 @end smallexample
30639
30640 In order to have a nicely aligned assembly listing, we have separated
30641 multiple assembler statements in the Asm template string with linefeed
30642 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
30643 The resulting section of the assembly output file is:
30644
30645 @smallexample
30646 @group
30647 #APP
30648    pushfl
30649    popl %eax
30650    movl %eax, -40(%ebp)
30651 #NO_APP
30652 @end group
30653 @end smallexample
30654
30655 It would have been legal to write the Asm invocation as:
30656
30657 @smallexample
30658 Asm ("pushfl popl %%eax movl %%eax, %0")
30659 @end smallexample
30660
30661 but in the generated assembler file, this would come out as:
30662
30663 @smallexample
30664 #APP
30665    pushfl popl %eax movl %eax, -40(%ebp)
30666 #NO_APP
30667 @end smallexample
30668
30669 which is not so convenient for the human reader.
30670
30671 We use Ada comments
30672 at the end of each line to explain what the assembler instructions
30673 actually do.  This is a useful convention.
30674
30675 When writing Inline Assembler instructions, you need to precede each register
30676 and variable name with a percent sign.  Since the assembler already requires
30677 a percent sign at the beginning of a register name, you need two consecutive
30678 percent signs for such names in the Asm template string, thus @code{%%eax}.
30679 In the generated assembly code, one of the percent signs will be stripped off.
30680
30681 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
30682 variables: operands you later define using @code{Input} or @code{Output}
30683 parameters to @code{Asm}.
30684 An output variable is illustrated in
30685 the third statement in the Asm template string:
30686 @smallexample
30687 movl %%eax, %0
30688 @end smallexample
30689 The intent is to store the contents of the eax register in a variable that can
30690 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
30691 necessarily work, since the compiler might optimize by using a register
30692 to hold Flags, and the expansion of the @code{movl} instruction would not be
30693 aware of this optimization.  The solution is not to store the result directly
30694 but rather to advise the compiler to choose the correct operand form;
30695 that is the purpose of the @code{%0} output variable.
30696
30697 Information about the output variable is supplied in the @code{Outputs}
30698 parameter to @code{Asm}:
30699 @smallexample
30700 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30701 @end smallexample
30702
30703 The output is defined by the @code{Asm_Output} attribute of the target type;
30704 the general format is
30705 @smallexample
30706 Type'Asm_Output (constraint_string, variable_name)
30707 @end smallexample
30708
30709 The constraint string directs the compiler how
30710 to store/access the associated variable.  In the example
30711 @smallexample
30712 Unsigned_32'Asm_Output ("=m", Flags);
30713 @end smallexample
30714 the @code{"m"} (memory) constraint tells the compiler that the variable
30715 @code{Flags} should be stored in a memory variable, thus preventing
30716 the optimizer from keeping it in a register.  In contrast,
30717 @smallexample
30718 Unsigned_32'Asm_Output ("=r", Flags);
30719 @end smallexample
30720 uses the @code{"r"} (register) constraint, telling the compiler to
30721 store the variable in a register.
30722
30723 If the constraint is preceded by the equal character (@strong{=}), it tells
30724 the compiler that the variable will be used to store data into it.
30725
30726 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
30727 allowing the optimizer to choose whatever it deems best.
30728
30729 There are a fairly large number of constraints, but the ones that are
30730 most useful (for the Intel x86 processor) are the following:
30731
30732 @table @code
30733 @item =
30734 output constraint
30735 @item g
30736 global (i.e.@: can be stored anywhere)
30737 @item m
30738 in memory
30739 @item I
30740 a constant
30741 @item a
30742 use eax
30743 @item b
30744 use ebx
30745 @item c
30746 use ecx
30747 @item d
30748 use edx
30749 @item S
30750 use esi
30751 @item D
30752 use edi
30753 @item r
30754 use one of eax, ebx, ecx or edx
30755 @item q
30756 use one of eax, ebx, ecx, edx, esi or edi
30757 @end table
30758
30759 The full set of constraints is described in the gcc and @emph{as}
30760 documentation; note that it is possible to combine certain constraints
30761 in one constraint string.
30762
30763 You specify the association of an output variable with an assembler operand
30764 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
30765 integer.  Thus in
30766 @smallexample @c ada
30767 @group
30768 Asm ("pushfl"          & LF & HT & -- push flags on stack
30769      "popl %%eax"      & LF & HT & -- load eax with flags
30770      "movl %%eax, %0",             -- store flags in variable
30771      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30772 @end group
30773 @end smallexample
30774 @noindent
30775 @code{%0} will be replaced in the expanded code by the appropriate operand,
30776 whatever
30777 the compiler decided for the @code{Flags} variable.
30778
30779 In general, you may have any number of output variables:
30780 @itemize @bullet
30781 @item
30782 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
30783 @item
30784 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
30785 of @code{Asm_Output} attributes
30786 @end itemize
30787
30788 For example:
30789 @smallexample @c ada
30790 @group
30791 Asm ("movl %%eax, %0" & LF & HT &
30792      "movl %%ebx, %1" & LF & HT &
30793      "movl %%ecx, %2",
30794      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
30795                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
30796                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
30797 @end group
30798 @end smallexample
30799 @noindent
30800 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
30801 in the Ada program.
30802
30803 As a variation on the @code{Get_Flags} example, we can use the constraints
30804 string to direct the compiler to store the eax register into the @code{Flags}
30805 variable, instead of including the store instruction explicitly in the
30806 @code{Asm} template string:
30807
30808 @smallexample @c ada
30809 @group
30810 with Interfaces; use Interfaces;
30811 with Ada.Text_IO; use Ada.Text_IO;
30812 with System.Machine_Code; use System.Machine_Code;
30813 procedure Get_Flags_2 is
30814    Flags : Unsigned_32;
30815    use ASCII;
30816 begin
30817    Asm ("pushfl"      & LF & HT & -- push flags on stack
30818         "popl %%eax",             -- save flags in eax
30819         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
30820    Put_Line ("Flags register:" & Flags'Img);
30821 end Get_Flags_2;
30822 @end group
30823 @end smallexample
30824
30825 @noindent
30826 The @code{"a"} constraint tells the compiler that the @code{Flags}
30827 variable will come from the eax register. Here is the resulting code:
30828
30829 @smallexample
30830 @group
30831 #APP
30832    pushfl
30833    popl %eax
30834 #NO_APP
30835    movl %eax,-40(%ebp)
30836 @end group
30837 @end smallexample
30838
30839 @noindent
30840 The compiler generated the store of eax into Flags after
30841 expanding the assembler code.
30842
30843 Actually, there was no need to pop the flags into the eax register;
30844 more simply, we could just pop the flags directly into the program variable:
30845
30846 @smallexample @c ada
30847 @group
30848 with Interfaces; use Interfaces;
30849 with Ada.Text_IO; use Ada.Text_IO;
30850 with System.Machine_Code; use System.Machine_Code;
30851 procedure Get_Flags_3 is
30852    Flags : Unsigned_32;
30853    use ASCII;
30854 begin
30855    Asm ("pushfl"  & LF & HT & -- push flags on stack
30856         "pop %0",             -- save flags in Flags
30857         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
30858    Put_Line ("Flags register:" & Flags'Img);
30859 end Get_Flags_3;
30860 @end group
30861 @end smallexample
30862
30863 @c ---------------------------------------------------------------------------
30864 @node Input Variables in Inline Assembler
30865 @section Input Variables in Inline Assembler
30866
30867 @noindent
30868 The example in this section illustrates how to specify the source operands
30869 for assembly language statements.
30870 The program simply increments its input value by 1:
30871
30872 @smallexample @c ada
30873 @group
30874 with Interfaces; use Interfaces;
30875 with Ada.Text_IO; use Ada.Text_IO;
30876 with System.Machine_Code; use System.Machine_Code;
30877 procedure Increment is
30878
30879    function Incr (Value : Unsigned_32) return Unsigned_32 is
30880       Result : Unsigned_32;
30881    begin
30882       Asm ("incl %0",
30883            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30884            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30885       return Result;
30886    end Incr;
30887
30888    Value : Unsigned_32;
30889
30890 begin
30891    Value := 5;
30892    Put_Line ("Value before is" & Value'Img);
30893    Value := Incr (Value);
30894    Put_Line ("Value after is" & Value'Img);
30895 end Increment;
30896 @end group
30897 @end smallexample
30898
30899 The @code{Outputs} parameter to @code{Asm} specifies
30900 that the result will be in the eax register and that it is to be stored
30901 in the @code{Result} variable.
30902
30903 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
30904 but with an @code{Asm_Input} attribute.
30905 The @code{"="} constraint, indicating an output value, is not present.
30906
30907 You can have multiple input variables, in the same way that you can have more
30908 than one output variable.
30909
30910 The parameter count (%0, %1) etc, now starts at the first input
30911 statement, and continues with the output statements.
30912 When both parameters use the same variable, the
30913 compiler will treat them as the same %n operand, which is the case here.
30914
30915 Just as the @code{Outputs} parameter causes the register to be stored into the
30916 target variable after execution of the assembler statements, so does the
30917 @code{Inputs} parameter cause its variable to be loaded into the register
30918 before execution of the assembler statements.
30919
30920 Thus the effect of the @code{Asm} invocation is:
30921 @enumerate
30922 @item load the 32-bit value of @code{Value} into eax
30923 @item execute the @code{incl %eax} instruction
30924 @item store the contents of eax into the @code{Result} variable
30925 @end enumerate
30926
30927 The resulting assembler file (with @option{-O2} optimization) contains:
30928 @smallexample
30929 @group
30930 _increment__incr.1:
30931    subl $4,%esp
30932    movl 8(%esp),%eax
30933 #APP
30934    incl %eax
30935 #NO_APP
30936    movl %eax,%edx
30937    movl %ecx,(%esp)
30938    addl $4,%esp
30939    ret
30940 @end group
30941 @end smallexample
30942
30943 @c ---------------------------------------------------------------------------
30944 @node Inlining Inline Assembler Code
30945 @section Inlining Inline Assembler Code
30946
30947 @noindent
30948 For a short subprogram such as the @code{Incr} function in the previous
30949 section, the overhead of the call and return (creating / deleting the stack
30950 frame) can be significant, compared to the amount of code in the subprogram
30951 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
30952 which directs the compiler to expand invocations of the subprogram at the
30953 point(s) of call, instead of setting up a stack frame for out-of-line calls.
30954 Here is the resulting program:
30955
30956 @smallexample @c ada
30957 @group
30958 with Interfaces; use Interfaces;
30959 with Ada.Text_IO; use Ada.Text_IO;
30960 with System.Machine_Code; use System.Machine_Code;
30961 procedure Increment_2 is
30962
30963    function Incr (Value : Unsigned_32) return Unsigned_32 is
30964       Result : Unsigned_32;
30965    begin
30966       Asm ("incl %0",
30967            Inputs  => Unsigned_32'Asm_Input ("a", Value),
30968            Outputs => Unsigned_32'Asm_Output ("=a", Result));
30969       return Result;
30970    end Incr;
30971    pragma Inline (Increment);
30972
30973    Value : Unsigned_32;
30974
30975 begin
30976    Value := 5;
30977    Put_Line ("Value before is" & Value'Img);
30978    Value := Increment (Value);
30979    Put_Line ("Value after is" & Value'Img);
30980 end Increment_2;
30981 @end group
30982 @end smallexample
30983
30984 Compile the program with both optimization (@option{-O2}) and inlining
30985 (@option{-gnatn}) enabled.
30986
30987 The @code{Incr} function is still compiled as usual, but at the
30988 point in @code{Increment} where our function used to be called:
30989
30990 @smallexample
30991 @group
30992 pushl %edi
30993 call _increment__incr.1
30994 @end group
30995 @end smallexample
30996
30997 @noindent
30998 the code for the function body directly appears:
30999
31000 @smallexample
31001 @group
31002 movl %esi,%eax
31003 #APP
31004    incl %eax
31005 #NO_APP
31006    movl %eax,%edx
31007 @end group
31008 @end smallexample
31009
31010 @noindent
31011 thus saving the overhead of stack frame setup and an out-of-line call.
31012
31013 @c ---------------------------------------------------------------------------
31014 @node Other Asm Functionality
31015 @section Other @code{Asm} Functionality
31016
31017 @noindent
31018 This section describes two important parameters to the @code{Asm}
31019 procedure: @code{Clobber}, which identifies register usage;
31020 and @code{Volatile}, which inhibits unwanted optimizations.
31021
31022 @menu
31023 * The Clobber Parameter::
31024 * The Volatile Parameter::
31025 @end menu
31026
31027 @c ---------------------------------------------------------------------------
31028 @node The Clobber Parameter
31029 @subsection The @code{Clobber} Parameter
31030
31031 @noindent
31032 One of the dangers of intermixing assembly language and a compiled language
31033 such as Ada is that the compiler needs to be aware of which registers are
31034 being used by the assembly code.  In some cases, such as the earlier examples,
31035 the constraint string is sufficient to indicate register usage (e.g.,
31036 @code{"a"} for
31037 the eax register).  But more generally, the compiler needs an explicit
31038 identification of the registers that are used by the Inline Assembly
31039 statements.
31040
31041 Using a register that the compiler doesn't know about
31042 could be a side effect of an instruction (like @code{mull}
31043 storing its result in both eax and edx).
31044 It can also arise from explicit register usage in your
31045 assembly code; for example:
31046 @smallexample
31047 @group
31048 Asm ("movl %0, %%ebx" & LF & HT &
31049      "movl %%ebx, %1",
31050      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
31051      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
31052 @end group
31053 @end smallexample
31054 @noindent
31055 where the compiler (since it does not analyze the @code{Asm} template string)
31056 does not know you are using the ebx register.
31057
31058 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
31059 to identify the registers that will be used by your assembly code:
31060
31061 @smallexample
31062 @group
31063 Asm ("movl %0, %%ebx" & LF & HT &
31064      "movl %%ebx, %1",
31065      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
31066      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
31067      Clobber => "ebx");
31068 @end group
31069 @end smallexample
31070
31071 The Clobber parameter is a static string expression specifying the
31072 register(s) you are using.  Note that register names are @emph{not} prefixed
31073 by a percent sign. Also, if more than one register is used then their names
31074 are separated by commas; e.g., @code{"eax, ebx"}
31075
31076 The @code{Clobber} parameter has several additional uses:
31077 @enumerate
31078 @item Use ``register'' name @code{cc} to indicate that flags might have changed
31079 @item Use ``register'' name @code{memory} if you changed a memory location
31080 @end enumerate
31081
31082 @c ---------------------------------------------------------------------------
31083 @node The Volatile Parameter
31084 @subsection The @code{Volatile} Parameter
31085 @cindex Volatile parameter
31086
31087 @noindent
31088 Compiler optimizations in the presence of Inline Assembler may sometimes have
31089 unwanted effects.  For example, when an @code{Asm} invocation with an input
31090 variable is inside a loop, the compiler might move the loading of the input
31091 variable outside the loop, regarding it as a one-time initialization.
31092
31093 If this effect is not desired, you can disable such optimizations by setting
31094 the @code{Volatile} parameter to @code{True}; for example:
31095
31096 @smallexample @c ada
31097 @group
31098 Asm ("movl %0, %%ebx" & LF & HT &
31099      "movl %%ebx, %1",
31100      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
31101      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
31102      Clobber  => "ebx",
31103      Volatile => True);
31104 @end group
31105 @end smallexample
31106
31107 By default, @code{Volatile} is set to @code{False} unless there is no
31108 @code{Outputs} parameter.
31109
31110 Although setting @code{Volatile} to @code{True} prevents unwanted
31111 optimizations, it will also disable other optimizations that might be
31112 important for efficiency. In general, you should set @code{Volatile}
31113 to @code{True} only if the compiler's optimizations have created
31114 problems.
31115 @c END OF INLINE ASSEMBLER CHAPTER
31116 @c ===============================
31117
31118 @c ***********************************
31119 @c * Compatibility and Porting Guide *
31120 @c ***********************************
31121 @node Compatibility and Porting Guide
31122 @appendix Compatibility and Porting Guide
31123
31124 @noindent
31125 This chapter describes the compatibility issues that may arise between
31126 GNAT and other Ada compilation systems (including those for Ada 83),
31127 and shows how GNAT can expedite porting
31128 applications developed in other Ada environments.
31129
31130 @menu
31131 * Compatibility with Ada 83::
31132 * Compatibility between Ada 95 and Ada 2005::
31133 * Implementation-dependent characteristics::
31134 * Compatibility with Other Ada Systems::
31135 * Representation Clauses::
31136 @ifclear vms
31137 @c Brief section is only in non-VMS version
31138 @c Full chapter is in VMS version
31139 * Compatibility with HP Ada 83::
31140 @end ifclear
31141 @ifset vms
31142 * Transitioning to 64-Bit GNAT for OpenVMS::
31143 @end ifset
31144 @end menu
31145
31146 @node Compatibility with Ada 83
31147 @section Compatibility with Ada 83
31148 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
31149
31150 @noindent
31151 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
31152 particular, the design intention was that the difficulties associated
31153 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
31154 that occur when moving from one Ada 83 system to another.
31155
31156 However, there are a number of points at which there are minor
31157 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
31158 full details of these issues,
31159 and should be consulted for a complete treatment.
31160 In practice the
31161 following subsections treat the most likely issues to be encountered.
31162
31163 @menu
31164 * Legal Ada 83 programs that are illegal in Ada 95::
31165 * More deterministic semantics::
31166 * Changed semantics::
31167 * Other language compatibility issues::
31168 @end menu
31169
31170 @node Legal Ada 83 programs that are illegal in Ada 95
31171 @subsection Legal Ada 83 programs that are illegal in Ada 95
31172
31173 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
31174 Ada 95 and thus also in Ada 2005:
31175
31176 @table @emph
31177 @item Character literals
31178 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
31179 @code{Wide_Character} as a new predefined character type, some uses of
31180 character literals that were legal in Ada 83 are illegal in Ada 95.
31181 For example:
31182 @smallexample @c ada
31183    for Char in 'A' .. 'Z' loop @dots{} end loop;
31184 @end smallexample
31185
31186 @noindent
31187 The problem is that @code{'A'} and @code{'Z'} could be from either
31188 @code{Character} or @code{Wide_Character}.  The simplest correction
31189 is to make the type explicit; e.g.:
31190 @smallexample @c ada
31191    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
31192 @end smallexample
31193
31194 @item New reserved words
31195 The identifiers @code{abstract}, @code{aliased}, @code{protected},
31196 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
31197 Existing Ada 83 code using any of these identifiers must be edited to
31198 use some alternative name.
31199
31200 @item Freezing rules
31201 The rules in Ada 95 are slightly different with regard to the point at
31202 which entities are frozen, and representation pragmas and clauses are
31203 not permitted past the freeze point.  This shows up most typically in
31204 the form of an error message complaining that a representation item
31205 appears too late, and the appropriate corrective action is to move
31206 the item nearer to the declaration of the entity to which it refers.
31207
31208 A particular case is that representation pragmas
31209 @ifset vms
31210 (including the
31211 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
31212 @end ifset
31213 cannot be applied to a subprogram body.  If necessary, a separate subprogram
31214 declaration must be introduced to which the pragma can be applied.
31215
31216 @item Optional bodies for library packages
31217 In Ada 83, a package that did not require a package body was nevertheless
31218 allowed to have one.  This lead to certain surprises in compiling large
31219 systems (situations in which the body could be unexpectedly ignored by the
31220 binder).  In Ada 95, if a package does not require a body then it is not
31221 permitted to have a body.  To fix this problem, simply remove a redundant
31222 body if it is empty, or, if it is non-empty, introduce a dummy declaration
31223 into the spec that makes the body required.  One approach is to add a private
31224 part to the package declaration (if necessary), and define a parameterless
31225 procedure called @code{Requires_Body}, which must then be given a dummy
31226 procedure body in the package body, which then becomes required.
31227 Another approach (assuming that this does not introduce elaboration
31228 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
31229 since one effect of this pragma is to require the presence of a package body.
31230
31231 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
31232 In Ada 95, the exception @code{Numeric_Error} is a renaming of
31233 @code{Constraint_Error}.
31234 This means that it is illegal to have separate exception handlers for
31235 the two exceptions.  The fix is simply to remove the handler for the
31236 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
31237 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
31238
31239 @item Indefinite subtypes in generics
31240 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
31241 as the actual for a generic formal private type, but then the instantiation
31242 would be illegal if there were any instances of declarations of variables
31243 of this type in the generic body.  In Ada 95, to avoid this clear violation
31244 of the methodological principle known as the ``contract model'',
31245 the generic declaration explicitly indicates whether
31246 or not such instantiations are permitted.  If a generic formal parameter
31247 has explicit unknown discriminants, indicated by using @code{(<>)} after the
31248 type name, then it can be instantiated with indefinite types, but no
31249 stand-alone variables can be declared of this type.  Any attempt to declare
31250 such a variable will result in an illegality at the time the generic is
31251 declared.  If the @code{(<>)} notation is not used, then it is illegal
31252 to instantiate the generic with an indefinite type.
31253 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
31254 It will show up as a compile time error, and
31255 the fix is usually simply to add the @code{(<>)} to the generic declaration.
31256 @end table
31257
31258 @node More deterministic semantics
31259 @subsection More deterministic semantics
31260
31261 @table @emph
31262 @item Conversions
31263 Conversions from real types to integer types round away from 0.  In Ada 83
31264 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
31265 implementation freedom was intended to support unbiased rounding in
31266 statistical applications, but in practice it interfered with portability.
31267 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
31268 is required.  Numeric code may be affected by this change in semantics.
31269 Note, though, that this issue is no worse than already existed in Ada 83
31270 when porting code from one vendor to another.
31271
31272 @item Tasking
31273 The Real-Time Annex introduces a set of policies that define the behavior of
31274 features that were implementation dependent in Ada 83, such as the order in
31275 which open select branches are executed.
31276 @end table
31277
31278 @node Changed semantics
31279 @subsection Changed semantics
31280
31281 @noindent
31282 The worst kind of incompatibility is one where a program that is legal in
31283 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
31284 possible in Ada 83.  Fortunately this is extremely rare, but the one
31285 situation that you should be alert to is the change in the predefined type
31286 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
31287
31288 @table @emph
31289 @item Range of type @code{Character}
31290 The range of @code{Standard.Character} is now the full 256 characters
31291 of Latin-1, whereas in most Ada 83 implementations it was restricted
31292 to 128 characters. Although some of the effects of
31293 this change will be manifest in compile-time rejection of legal
31294 Ada 83 programs it is possible for a working Ada 83 program to have
31295 a different effect in Ada 95, one that was not permitted in Ada 83.
31296 As an example, the expression
31297 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
31298 delivers @code{255} as its value.
31299 In general, you should look at the logic of any
31300 character-processing Ada 83 program and see whether it needs to be adapted
31301 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
31302 character handling package that may be relevant if code needs to be adapted
31303 to account for the additional Latin-1 elements.
31304 The desirable fix is to
31305 modify the program to accommodate the full character set, but in some cases
31306 it may be convenient to define a subtype or derived type of Character that
31307 covers only the restricted range.
31308 @cindex Latin-1
31309 @end table
31310
31311 @node Other language compatibility issues
31312 @subsection Other language compatibility issues
31313
31314 @table @emph
31315 @item @option{-gnat83} switch
31316 All implementations of GNAT provide a switch that causes GNAT to operate
31317 in Ada 83 mode.  In this mode, some but not all compatibility problems
31318 of the type described above are handled automatically.  For example, the
31319 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
31320 as identifiers as in Ada 83.
31321 However,
31322 in practice, it is usually advisable to make the necessary modifications
31323 to the program to remove the need for using this switch.
31324 See @ref{Compiling Different Versions of Ada}.
31325
31326 @item Support for removed Ada 83 pragmas and attributes
31327 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
31328 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
31329 compilers are allowed, but not required, to implement these missing
31330 elements.  In contrast with some other compilers, GNAT implements all
31331 such pragmas and attributes, eliminating this compatibility concern.  These
31332 include @code{pragma Interface} and the floating point type attributes
31333 (@code{Emax}, @code{Mantissa}, etc.), among other items.
31334 @end table
31335
31336
31337 @node Compatibility between Ada 95 and Ada 2005
31338 @section Compatibility between Ada 95 and Ada 2005
31339 @cindex Compatibility between Ada 95 and Ada 2005
31340
31341 @noindent
31342 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
31343 a number of incompatibilities. Several are enumerated below;
31344 for a complete description please see the
31345 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
31346 @cite{Rationale for Ada 2005}.
31347
31348 @table @emph
31349 @item New reserved words.
31350 The words @code{interface}, @code{overriding} and @code{synchronized} are
31351 reserved in Ada 2005.
31352 A pre-Ada 2005 program that uses any of these as an identifier will be
31353 illegal.
31354
31355 @item New declarations in predefined packages.
31356 A number of packages in the predefined environment contain new declarations:
31357 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
31358 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
31359 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
31360 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
31361 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
31362 If an Ada 95 program does a @code{with} and @code{use} of any of these
31363 packages, the new declarations may cause name clashes.
31364
31365 @item Access parameters.
31366 A nondispatching subprogram with an access parameter cannot be renamed
31367 as a dispatching operation.  This was permitted in Ada 95.
31368
31369 @item Access types, discriminants, and constraints.
31370 Rule changes in this area have led to some incompatibilities; for example,
31371 constrained subtypes of some access types are not permitted in Ada 2005.
31372
31373 @item Aggregates for limited types.
31374 The allowance of aggregates for limited types in Ada 2005 raises the
31375 possibility of ambiguities in legal Ada 95 programs, since additional types
31376 now need to be considered in expression resolution.
31377
31378 @item Fixed-point multiplication and division.
31379 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
31380 were legal in Ada 95 and invoked the predefined versions of these operations,
31381 are now ambiguous.
31382 The ambiguity may be resolved either by applying a type conversion to the
31383 expression, or by explicitly invoking the operation from package
31384 @code{Standard}.
31385
31386 @item Return-by-reference types.
31387 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
31388 can declare a function returning a value from an anonymous access type.
31389 @end table
31390
31391
31392 @node Implementation-dependent characteristics
31393 @section Implementation-dependent characteristics
31394 @noindent
31395 Although the Ada language defines the semantics of each construct as
31396 precisely as practical, in some situations (for example for reasons of
31397 efficiency, or where the effect is heavily dependent on the host or target
31398 platform) the implementation is allowed some freedom.  In porting Ada 83
31399 code to GNAT, you need to be aware of whether / how the existing code
31400 exercised such implementation dependencies.  Such characteristics fall into
31401 several categories, and GNAT offers specific support in assisting the
31402 transition from certain Ada 83 compilers.
31403
31404 @menu
31405 * Implementation-defined pragmas::
31406 * Implementation-defined attributes::
31407 * Libraries::
31408 * Elaboration order::
31409 * Target-specific aspects::
31410 @end menu
31411
31412 @node Implementation-defined pragmas
31413 @subsection Implementation-defined pragmas
31414
31415 @noindent
31416 Ada compilers are allowed to supplement the language-defined pragmas, and
31417 these are a potential source of non-portability.  All GNAT-defined pragmas
31418 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
31419 Reference Manual}, and these include several that are specifically
31420 intended to correspond to other vendors' Ada 83 pragmas.
31421 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
31422 For compatibility with HP Ada 83, GNAT supplies the pragmas
31423 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
31424 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
31425 and @code{Volatile}.
31426 Other relevant pragmas include @code{External} and @code{Link_With}.
31427 Some vendor-specific
31428 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
31429 recognized, thus
31430 avoiding compiler rejection of units that contain such pragmas; they are not
31431 relevant in a GNAT context and hence are not otherwise implemented.
31432
31433 @node Implementation-defined attributes
31434 @subsection Implementation-defined attributes
31435
31436 Analogous to pragmas, the set of attributes may be extended by an
31437 implementation.  All GNAT-defined attributes are described in
31438 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
31439 Manual}, and these include several that are specifically intended
31440 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
31441 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
31442 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
31443 @code{Type_Class}.
31444
31445 @node Libraries
31446 @subsection Libraries
31447 @noindent
31448 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
31449 code uses vendor-specific libraries then there are several ways to manage
31450 this in Ada 95 or Ada 2005:
31451 @enumerate
31452 @item
31453 If the source code for the libraries (specs and bodies) are
31454 available, then the libraries can be migrated in the same way as the
31455 application.
31456 @item
31457 If the source code for the specs but not the bodies are
31458 available, then you can reimplement the bodies.
31459 @item
31460 Some features introduced by Ada 95 obviate the need for library support.  For
31461 example most Ada 83 vendors supplied a package for unsigned integers.  The
31462 Ada 95 modular type feature is the preferred way to handle this need, so
31463 instead of migrating or reimplementing the unsigned integer package it may
31464 be preferable to retrofit the application using modular types.
31465 @end enumerate
31466
31467 @node Elaboration order
31468 @subsection Elaboration order
31469 @noindent
31470 The implementation can choose any elaboration order consistent with the unit
31471 dependency relationship.  This freedom means that some orders can result in
31472 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
31473 to invoke a subprogram its body has been elaborated, or to instantiate a
31474 generic before the generic body has been elaborated.  By default GNAT
31475 attempts to choose a safe order (one that will not encounter access before
31476 elaboration problems) by implicitly inserting @code{Elaborate} or
31477 @code{Elaborate_All} pragmas where
31478 needed.  However, this can lead to the creation of elaboration circularities
31479 and a resulting rejection of the program by gnatbind.  This issue is
31480 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
31481 In brief, there are several
31482 ways to deal with this situation:
31483
31484 @itemize @bullet
31485 @item
31486 Modify the program to eliminate the circularities, e.g.@: by moving
31487 elaboration-time code into explicitly-invoked procedures
31488 @item
31489 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
31490 @code{Elaborate} pragmas, and then inhibit the generation of implicit
31491 @code{Elaborate_All}
31492 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
31493 (by selectively suppressing elaboration checks via pragma
31494 @code{Suppress(Elaboration_Check)} when it is safe to do so).
31495 @end itemize
31496
31497 @node Target-specific aspects
31498 @subsection Target-specific aspects
31499 @noindent
31500 Low-level applications need to deal with machine addresses, data
31501 representations, interfacing with assembler code, and similar issues.  If
31502 such an Ada 83 application is being ported to different target hardware (for
31503 example where the byte endianness has changed) then you will need to
31504 carefully examine the program logic; the porting effort will heavily depend
31505 on the robustness of the original design.  Moreover, Ada 95 (and thus
31506 Ada 2005) are sometimes
31507 incompatible with typical Ada 83 compiler practices regarding implicit
31508 packing, the meaning of the Size attribute, and the size of access values.
31509 GNAT's approach to these issues is described in @ref{Representation Clauses}.
31510
31511 @node Compatibility with Other Ada Systems
31512 @section Compatibility with Other Ada Systems
31513
31514 @noindent
31515 If programs avoid the use of implementation dependent and
31516 implementation defined features, as documented in the @cite{Ada
31517 Reference Manual}, there should be a high degree of portability between
31518 GNAT and other Ada systems.  The following are specific items which
31519 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
31520 compilers, but do not affect porting code to GNAT@.
31521 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
31522 the following issues may or may not arise for Ada 2005 programs
31523 when other compilers appear.)
31524
31525 @table @emph
31526 @item Ada 83 Pragmas and Attributes
31527 Ada 95 compilers are allowed, but not required, to implement the missing
31528 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
31529 GNAT implements all such pragmas and attributes, eliminating this as
31530 a compatibility concern, but some other Ada 95 compilers reject these
31531 pragmas and attributes.
31532
31533 @item Specialized Needs Annexes
31534 GNAT implements the full set of special needs annexes.  At the
31535 current time, it is the only Ada 95 compiler to do so.  This means that
31536 programs making use of these features may not be portable to other Ada
31537 95 compilation systems.
31538
31539 @item Representation Clauses
31540 Some other Ada 95 compilers implement only the minimal set of
31541 representation clauses required by the Ada 95 reference manual.  GNAT goes
31542 far beyond this minimal set, as described in the next section.
31543 @end table
31544
31545 @node Representation Clauses
31546 @section Representation Clauses
31547
31548 @noindent
31549 The Ada 83 reference manual was quite vague in describing both the minimal
31550 required implementation of representation clauses, and also their precise
31551 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
31552 minimal set of capabilities required is still quite limited.
31553
31554 GNAT implements the full required set of capabilities in
31555 Ada 95 and Ada 2005, but also goes much further, and in particular
31556 an effort has been made to be compatible with existing Ada 83 usage to the
31557 greatest extent possible.
31558
31559 A few cases exist in which Ada 83 compiler behavior is incompatible with
31560 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
31561 intentional or accidental dependence on specific implementation dependent
31562 characteristics of these Ada 83 compilers.  The following is a list of
31563 the cases most likely to arise in existing Ada 83 code.
31564
31565 @table @emph
31566 @item Implicit Packing
31567 Some Ada 83 compilers allowed a Size specification to cause implicit
31568 packing of an array or record.  This could cause expensive implicit
31569 conversions for change of representation in the presence of derived
31570 types, and the Ada design intends to avoid this possibility.
31571 Subsequent AI's were issued to make it clear that such implicit
31572 change of representation in response to a Size clause is inadvisable,
31573 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
31574 Reference Manuals as implementation advice that is followed by GNAT@.
31575 The problem will show up as an error
31576 message rejecting the size clause.  The fix is simply to provide
31577 the explicit pragma @code{Pack}, or for more fine tuned control, provide
31578 a Component_Size clause.
31579
31580 @item Meaning of Size Attribute
31581 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
31582 the minimal number of bits required to hold values of the type.  For example,
31583 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
31584 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
31585 some 32 in this situation.  This problem will usually show up as a compile
31586 time error, but not always.  It is a good idea to check all uses of the
31587 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
31588 Object_Size can provide a useful way of duplicating the behavior of
31589 some Ada 83 compiler systems.
31590
31591 @item Size of Access Types
31592 A common assumption in Ada 83 code is that an access type is in fact a pointer,
31593 and that therefore it will be the same size as a System.Address value.  This
31594 assumption is true for GNAT in most cases with one exception.  For the case of
31595 a pointer to an unconstrained array type (where the bounds may vary from one
31596 value of the access type to another), the default is to use a ``fat pointer'',
31597 which is represented as two separate pointers, one to the bounds, and one to
31598 the array.  This representation has a number of advantages, including improved
31599 efficiency.  However, it may cause some difficulties in porting existing Ada 83
31600 code which makes the assumption that, for example, pointers fit in 32 bits on
31601 a machine with 32-bit addressing.
31602
31603 To get around this problem, GNAT also permits the use of ``thin pointers'' for
31604 access types in this case (where the designated type is an unconstrained array
31605 type).  These thin pointers are indeed the same size as a System.Address value.
31606 To specify a thin pointer, use a size clause for the type, for example:
31607
31608 @smallexample @c ada
31609 type X is access all String;
31610 for X'Size use Standard'Address_Size;
31611 @end smallexample
31612
31613 @noindent
31614 which will cause the type X to be represented using a single pointer.
31615 When using this representation, the bounds are right behind the array.
31616 This representation is slightly less efficient, and does not allow quite
31617 such flexibility in the use of foreign pointers or in using the
31618 Unrestricted_Access attribute to create pointers to non-aliased objects.
31619 But for any standard portable use of the access type it will work in
31620 a functionally correct manner and allow porting of existing code.
31621 Note that another way of forcing a thin pointer representation
31622 is to use a component size clause for the element size in an array,
31623 or a record representation clause for an access field in a record.
31624 @end table
31625
31626 @ifclear vms
31627 @c This brief section is only in the non-VMS version
31628 @c The complete chapter on HP Ada is in the VMS version
31629 @node Compatibility with HP Ada 83
31630 @section Compatibility with HP Ada 83
31631
31632 @noindent
31633 The VMS version of GNAT fully implements all the pragmas and attributes
31634 provided by HP Ada 83, as well as providing the standard HP Ada 83
31635 libraries, including Starlet.  In addition, data layouts and parameter
31636 passing conventions are highly compatible.  This means that porting
31637 existing HP Ada 83 code to GNAT in VMS systems should be easier than
31638 most other porting efforts.  The following are some of the most
31639 significant differences between GNAT and HP Ada 83.
31640
31641 @table @emph
31642 @item Default floating-point representation
31643 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
31644 it is VMS format.  GNAT does implement the necessary pragmas
31645 (Long_Float, Float_Representation) for changing this default.
31646
31647 @item System
31648 The package System in GNAT exactly corresponds to the definition in the
31649 Ada 95 reference manual, which means that it excludes many of the
31650 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
31651 that contains the additional definitions, and a special pragma,
31652 Extend_System allows this package to be treated transparently as an
31653 extension of package System.
31654
31655 @item To_Address
31656 The definitions provided by Aux_DEC are exactly compatible with those
31657 in the HP Ada 83 version of System, with one exception.
31658 HP Ada provides the following declarations:
31659
31660 @smallexample @c ada
31661 TO_ADDRESS (INTEGER)
31662 TO_ADDRESS (UNSIGNED_LONGWORD)
31663 TO_ADDRESS (@i{universal_integer})
31664 @end smallexample
31665
31666 @noindent
31667 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
31668 an extension to Ada 83 not strictly compatible with the reference manual.
31669 In GNAT, we are constrained to be exactly compatible with the standard,
31670 and this means we cannot provide this capability.  In HP Ada 83, the
31671 point of this definition is to deal with a call like:
31672
31673 @smallexample @c ada
31674 TO_ADDRESS (16#12777#);
31675 @end smallexample
31676
31677 @noindent
31678 Normally, according to the Ada 83 standard, one would expect this to be
31679 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
31680 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
31681 definition using @i{universal_integer} takes precedence.
31682
31683 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
31684 is not possible to be 100% compatible.  Since there are many programs using
31685 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
31686 to change the name of the function in the UNSIGNED_LONGWORD case, so the
31687 declarations provided in the GNAT version of AUX_Dec are:
31688
31689 @smallexample @c ada
31690 function To_Address (X : Integer) return Address;
31691 pragma Pure_Function (To_Address);
31692
31693 function To_Address_Long (X : Unsigned_Longword)
31694  return Address;
31695 pragma Pure_Function (To_Address_Long);
31696 @end smallexample
31697
31698 @noindent
31699 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
31700 change the name to TO_ADDRESS_LONG@.
31701
31702 @item Task_Id values
31703 The Task_Id values assigned will be different in the two systems, and GNAT
31704 does not provide a specified value for the Task_Id of the environment task,
31705 which in GNAT is treated like any other declared task.
31706 @end table
31707
31708 @noindent
31709 For full details on these and other less significant compatibility issues,
31710 see appendix E of the HP publication entitled @cite{HP Ada, Technical
31711 Overview and Comparison on HP Platforms}.
31712
31713 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
31714 attributes are recognized, although only a subset of them can sensibly
31715 be implemented.  The description of pragmas in @ref{Implementation
31716 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
31717 indicates whether or not they are applicable to non-VMS systems.
31718 @end ifclear
31719
31720 @ifset vms
31721 @node Transitioning to 64-Bit GNAT for OpenVMS
31722 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
31723
31724 @noindent
31725 This section is meant to assist users of pre-2006 @value{EDITION}
31726 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
31727 the version of the GNAT technology supplied in 2006 and later for
31728 OpenVMS on both Alpha and I64.
31729
31730 @menu
31731 * Introduction to transitioning::
31732 * Migration of 32 bit code::
31733 * Taking advantage of 64 bit addressing::
31734 * Technical details::
31735 @end menu
31736
31737 @node Introduction to transitioning
31738 @subsection Introduction
31739
31740 @noindent
31741 64-bit @value{EDITION} for Open VMS has been designed to meet
31742 three main goals:
31743
31744 @enumerate
31745 @item
31746 Providing a full conforming implementation of Ada 95 and Ada 2005
31747
31748 @item
31749 Allowing maximum backward compatibility, thus easing migration of existing
31750 Ada source code
31751
31752 @item
31753 Supplying a path for exploiting the full 64-bit address range
31754 @end enumerate
31755
31756 @noindent
31757 Ada's strong typing semantics has made it
31758 impractical to have different 32-bit and 64-bit modes. As soon as
31759 one object could possibly be outside the 32-bit address space, this
31760 would make it necessary for the @code{System.Address} type to be 64 bits.
31761 In particular, this would cause inconsistencies if 32-bit code is
31762 called from 64-bit code that raises an exception.
31763
31764 This issue has been resolved by always using 64-bit addressing
31765 at the system level, but allowing for automatic conversions between
31766 32-bit and 64-bit addresses where required. Thus users who
31767 do not currently require 64-bit addressing capabilities, can
31768 recompile their code with only minimal changes (and indeed
31769 if the code is written in portable Ada, with no assumptions about
31770 the size of the @code{Address} type, then no changes at all are necessary).
31771 At the same time,
31772 this approach provides a simple, gradual upgrade path to future
31773 use of larger memories than available for 32-bit systems.
31774 Also, newly written applications or libraries will by default
31775 be fully compatible with future systems exploiting 64-bit
31776 addressing capabilities.
31777
31778 @ref{Migration of 32 bit code}, will focus on porting applications
31779 that do not require more than 2 GB of
31780 addressable memory. This code will be referred to as
31781 @emph{32-bit code}.
31782 For applications intending to exploit the full 64-bit address space,
31783 @ref{Taking advantage of 64 bit addressing},
31784 will consider further changes that may be required.
31785 Such code will be referred to below as @emph{64-bit code}.
31786
31787 @node Migration of 32 bit code
31788 @subsection Migration of 32-bit code
31789
31790 @menu
31791 * Address types::
31792 * Access types::
31793 * Unchecked conversions::
31794 * Predefined constants::
31795 * Interfacing with C::
31796 * Experience with source compatibility::
31797 @end menu
31798
31799 @node Address types
31800 @subsubsection Address types
31801
31802 @noindent
31803 To solve the problem of mixing 64-bit and 32-bit addressing,
31804 while maintaining maximum backward compatibility, the following
31805 approach has been taken:
31806
31807 @itemize @bullet
31808 @item
31809 @code{System.Address} always has a size of 64 bits
31810
31811 @item
31812 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
31813 @end itemize
31814
31815 @noindent
31816 Since @code{System.Short_Address} is a subtype of @code{System.Address},
31817 a @code{Short_Address}
31818 may be used where an @code{Address} is required, and vice versa, without
31819 needing explicit type conversions.
31820 By virtue of the Open VMS parameter passing conventions,
31821 even imported
31822 and exported subprograms that have 32-bit address parameters are
31823 compatible with those that have 64-bit address parameters.
31824 (See @ref{Making code 64 bit clean} for details.)
31825
31826 The areas that may need attention are those where record types have
31827 been defined that contain components of the type @code{System.Address}, and
31828 where objects of this type are passed to code expecting a record layout with
31829 32-bit addresses.
31830
31831 Different compilers on different platforms cannot be
31832 expected to represent the same type in the same way,
31833 since alignment constraints
31834 and other system-dependent properties affect the compiler's decision.
31835 For that reason, Ada code
31836 generally uses representation clauses to specify the expected
31837 layout where required.
31838
31839 If such a representation clause uses 32 bits for a component having
31840 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
31841 will detect that error and produce a specific diagnostic message.
31842 The developer should then determine whether the representation
31843 should be 64 bits or not and make either of two changes:
31844 change the size to 64 bits and leave the type as @code{System.Address}, or
31845 leave the size as 32 bits and change the type to @code{System.Short_Address}.
31846 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
31847 required in any code setting or accessing the field; the compiler will
31848 automatically perform any needed conversions between address
31849 formats.
31850
31851 @node Access types
31852 @subsubsection Access types
31853
31854 @noindent
31855 By default, objects designated by access values are always
31856 allocated in the 32-bit
31857 address space. Thus legacy code will never contain
31858 any objects that are not addressable with 32-bit addresses, and
31859 the compiler will never raise exceptions as result of mixing
31860 32-bit and 64-bit addresses.
31861
31862 However, the access values themselves are represented in 64 bits, for optimum
31863 performance and future compatibility with 64-bit code. As was
31864 the case with @code{System.Address}, the compiler will give an error message
31865 if an object or record component has a representation clause that
31866 requires the access value to fit in 32 bits. In such a situation,
31867 an explicit size clause for the access type, specifying 32 bits,
31868 will have the desired effect.
31869
31870 General access types (declared with @code{access all}) can never be
31871 32 bits, as values of such types must be able to refer to any object
31872 of the  designated type,
31873 including objects residing outside the 32-bit address range.
31874 Existing Ada 83 code will not contain such type definitions,
31875 however, since general access types were introduced in Ada 95.
31876
31877 @node Unchecked conversions
31878 @subsubsection Unchecked conversions
31879
31880 @noindent
31881 In the case of an @code{Unchecked_Conversion} where the source type is a
31882 64-bit access type or the type @code{System.Address}, and the target
31883 type is a 32-bit type, the compiler will generate a warning.
31884 Even though the generated code will still perform the required
31885 conversions, it is highly recommended in these cases to use
31886 respectively a 32-bit access type or @code{System.Short_Address}
31887 as the source type.
31888
31889 @node Predefined constants
31890 @subsubsection Predefined constants
31891
31892 @noindent
31893 The following table shows the correspondence between pre-2006 versions of
31894 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
31895 (``New''):
31896
31897 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
31898 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
31899 @item   @code{System.Word_Size}          @tab 32      @tab 64
31900 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
31901 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
31902 @item   @code{System.Address_Size}       @tab 32      @tab 64
31903 @end multitable
31904
31905 @noindent
31906 If you need to refer to the specific
31907 memory size of a 32-bit implementation, instead of the
31908 actual memory size, use @code{System.Short_Memory_Size}
31909 rather than @code{System.Memory_Size}.
31910 Similarly, references to @code{System.Address_Size} may need
31911 to be replaced by @code{System.Short_Address'Size}.
31912 The program @command{gnatfind} may be useful for locating
31913 references to the above constants, so that you can verify that they
31914 are still correct.
31915
31916 @node Interfacing with C
31917 @subsubsection Interfacing with C
31918
31919 @noindent
31920 In order to minimize the impact of the transition to 64-bit addresses on
31921 legacy programs, some fundamental types in the @code{Interfaces.C}
31922 package hierarchy continue to be represented in 32 bits.
31923 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
31924 This eases integration with the default HP C layout choices, for example
31925 as found in the system routines in @code{DECC$SHR.EXE}.
31926 Because of this implementation choice, the type fully compatible with
31927 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
31928 Depending on the context the compiler will issue a
31929 warning or an error when type @code{Address} is used, alerting the user to a
31930 potential problem. Otherwise 32-bit programs that use
31931 @code{Interfaces.C} should normally not require code modifications
31932
31933 The other issue arising with C interfacing concerns pragma @code{Convention}.
31934 For VMS 64-bit systems, there is an issue of the appropriate default size
31935 of C convention pointers in the absence of an explicit size clause. The HP
31936 C compiler can choose either 32 or 64 bits depending on compiler options.
31937 GNAT chooses 32-bits rather than 64-bits in the default case where no size
31938 clause is given. This proves a better choice for porting 32-bit legacy
31939 applications. In order to have a 64-bit representation, it is necessary to
31940 specify a size representation clause. For example:
31941
31942 @smallexample @c ada
31943 type int_star is access Interfaces.C.int;
31944 pragma Convention(C, int_star);
31945 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
31946 @end smallexample
31947
31948 @node Experience with source compatibility
31949 @subsubsection Experience with source compatibility
31950
31951 @noindent
31952 The Security Server and STARLET on I64 provide an interesting ``test case''
31953 for source compatibility issues, since it is in such system code
31954 where assumptions about @code{Address} size might be expected to occur.
31955 Indeed, there were a small number of occasions in the Security Server
31956 file @file{jibdef.ads}
31957 where a representation clause for a record type specified
31958 32 bits for a component of type @code{Address}.
31959 All of these errors were detected by the compiler.
31960 The repair was obvious and immediate; to simply replace @code{Address} by
31961 @code{Short_Address}.
31962
31963 In the case of STARLET, there were several record types that should
31964 have had representation clauses but did not.  In these record types
31965 there was an implicit assumption that an @code{Address} value occupied
31966 32 bits.
31967 These compiled without error, but their usage resulted in run-time error
31968 returns from STARLET system calls.
31969 Future GNAT technology enhancements may include a tool that detects and flags
31970 these sorts of potential source code porting problems.
31971
31972 @c ****************************************
31973 @node Taking advantage of 64 bit addressing
31974 @subsection Taking advantage of 64-bit addressing
31975
31976 @menu
31977 * Making code 64 bit clean::
31978 * Allocating memory from the 64 bit storage pool::
31979 * Restrictions on use of 64 bit objects::
31980 * Using 64 bit storage pools by default::
31981 * General access types::
31982 * STARLET and other predefined libraries::
31983 @end menu
31984
31985 @node Making code 64 bit clean
31986 @subsubsection Making code 64-bit clean
31987
31988 @noindent
31989 In order to prevent problems that may occur when (parts of) a
31990 system start using memory outside the 32-bit address range,
31991 we recommend some additional guidelines:
31992
31993 @itemize @bullet
31994 @item
31995 For imported subprograms that take parameters of the
31996 type @code{System.Address}, ensure that these subprograms can
31997 indeed handle 64-bit addresses. If not, or when in doubt,
31998 change the subprogram declaration to specify
31999 @code{System.Short_Address} instead.
32000
32001 @item
32002 Resolve all warnings related to size mismatches in
32003 unchecked conversions. Failing to do so causes
32004 erroneous execution if the source object is outside
32005 the 32-bit address space.
32006
32007 @item
32008 (optional) Explicitly use the 32-bit storage pool
32009 for access types used in a 32-bit context, or use
32010 generic access types where possible
32011 (@pxref{Restrictions on use of 64 bit objects}).
32012 @end itemize
32013
32014 @noindent
32015 If these rules are followed, the compiler will automatically insert
32016 any necessary checks to ensure that no addresses or access values
32017 passed to 32-bit code ever refer to objects outside the 32-bit
32018 address range.
32019 Any attempt to do this will raise @code{Constraint_Error}.
32020
32021 @node Allocating memory from the 64 bit storage pool
32022 @subsubsection Allocating memory from the 64-bit storage pool
32023
32024 @noindent
32025 For any access type @code{T} that potentially requires memory allocations
32026 beyond the 32-bit address space,
32027 use the following representation clause:
32028
32029 @smallexample @c ada
32030    for T'Storage_Pool use System.Pool_64;
32031 @end smallexample
32032
32033 @node Restrictions on use of 64 bit objects
32034 @subsubsection Restrictions on use of 64-bit objects
32035
32036 @noindent
32037 Taking the address of an object allocated from a 64-bit storage pool,
32038 and then passing this address to a subprogram expecting
32039 @code{System.Short_Address},
32040 or assigning it to a variable of type @code{Short_Address}, will cause
32041 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
32042 (@pxref{Making code 64 bit clean}), or checks are suppressed,
32043 no exception is raised and execution
32044 will become erroneous.
32045
32046 @node Using 64 bit storage pools by default
32047 @subsubsection Using 64-bit storage pools by default
32048
32049 @noindent
32050 In some cases it may be desirable to have the compiler allocate
32051 from 64-bit storage pools by default. This may be the case for
32052 libraries that are 64-bit clean, but may be used in both 32-bit
32053 and 64-bit contexts. For these cases the following configuration
32054 pragma may be specified:
32055
32056 @smallexample @c ada
32057   pragma Pool_64_Default;
32058 @end smallexample
32059
32060 @noindent
32061 Any code compiled in the context of this pragma will by default
32062 use the @code{System.Pool_64} storage pool. This default may be overridden
32063 for a specific access type @code{T} by the representation clause:
32064
32065 @smallexample @c ada
32066    for T'Storage_Pool use System.Pool_32;
32067 @end smallexample
32068
32069 @noindent
32070 Any object whose address may be passed to a subprogram with a
32071 @code{Short_Address} argument, or assigned to a variable of type
32072 @code{Short_Address}, needs to be allocated from this pool.
32073
32074 @node General access types
32075 @subsubsection General access types
32076
32077 @noindent
32078 Objects designated by access values from a
32079 general access type (declared with @code{access all}) are never allocated
32080 from a 64-bit storage pool. Code that uses general access types will
32081 accept objects allocated in either 32-bit or 64-bit address spaces,
32082 but never allocate objects outside the 32-bit address space.
32083 Using general access types ensures maximum compatibility with both
32084 32-bit and 64-bit code.
32085
32086 @node STARLET and other predefined libraries
32087 @subsubsection STARLET and other predefined libraries
32088
32089 @noindent
32090 All code that comes as part of GNAT is 64-bit clean, but the
32091 restrictions given in @ref{Restrictions on use of 64 bit objects},
32092 still apply. Look at the package
32093 specs to see in which contexts objects allocated
32094 in 64-bit address space are acceptable.
32095
32096 @node Technical details
32097 @subsection Technical details
32098
32099 @noindent
32100 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
32101 Ada standard with respect to the type of @code{System.Address}. Previous
32102 versions of GNAT Pro have defined this type as private and implemented it as a
32103 modular type.
32104
32105 In order to allow defining @code{System.Short_Address} as a proper subtype,
32106 and to match the implicit sign extension in parameter passing,
32107 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
32108 visible (i.e., non-private) integer type.
32109 Standard operations on the type, such as the binary operators ``+'', ``-'',
32110 etc., that take @code{Address} operands and return an @code{Address} result,
32111 have been hidden by declaring these
32112 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
32113 ambiguities that would otherwise result from overloading.
32114 (Note that, although @code{Address} is a visible integer type,
32115 good programming practice dictates against exploiting the type's
32116 integer properties such as literals, since this will compromise
32117 code portability.)
32118
32119 Defining @code{Address} as a visible integer type helps achieve
32120 maximum compatibility for existing Ada code,
32121 without sacrificing the capabilities of the 64-bit architecture.
32122 @end ifset
32123
32124 @c ************************************************
32125 @ifset unw
32126 @node Microsoft Windows Topics
32127 @appendix Microsoft Windows Topics
32128 @cindex Windows NT
32129 @cindex Windows 95
32130 @cindex Windows 98
32131
32132 @noindent
32133 This chapter describes topics that are specific to the Microsoft Windows
32134 platforms (NT, 2000, and XP Professional).
32135
32136 @menu
32137 * Using GNAT on Windows::
32138 * Using a network installation of GNAT::
32139 * CONSOLE and WINDOWS subsystems::
32140 * Temporary Files::
32141 * Mixed-Language Programming on Windows::
32142 * Windows Calling Conventions::
32143 * Introduction to Dynamic Link Libraries (DLLs)::
32144 * Using DLLs with GNAT::
32145 * Building DLLs with GNAT::
32146 * Building DLLs with GNAT Project files::
32147 * Building DLLs with gnatdll::
32148 * GNAT and Windows Resources::
32149 * Debugging a DLL::
32150 * Setting Stack Size from gnatlink::
32151 * Setting Heap Size from gnatlink::
32152 @end menu
32153
32154 @node Using GNAT on Windows
32155 @section Using GNAT on Windows
32156
32157 @noindent
32158 One of the strengths of the GNAT technology is that its tool set
32159 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
32160 @code{gdb} debugger, etc.) is used in the same way regardless of the
32161 platform.
32162
32163 On Windows this tool set is complemented by a number of Microsoft-specific
32164 tools that have been provided to facilitate interoperability with Windows
32165 when this is required. With these tools:
32166
32167 @itemize @bullet
32168
32169 @item
32170 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
32171 subsystems.
32172
32173 @item
32174 You can use any Dynamically Linked Library (DLL) in your Ada code (both
32175 relocatable and non-relocatable DLLs are supported).
32176
32177 @item
32178 You can build Ada DLLs for use in other applications. These applications
32179 can be written in a language other than Ada (e.g., C, C++, etc). Again both
32180 relocatable and non-relocatable Ada DLLs are supported.
32181
32182 @item
32183 You can include Windows resources in your Ada application.
32184
32185 @item
32186 You can use or create COM/DCOM objects.
32187 @end itemize
32188
32189 @noindent
32190 Immediately below are listed all known general GNAT-for-Windows restrictions.
32191 Other restrictions about specific features like Windows Resources and DLLs
32192 are listed in separate sections below.
32193
32194 @itemize @bullet
32195
32196 @item
32197 It is not possible to use @code{GetLastError} and @code{SetLastError}
32198 when tasking, protected records, or exceptions are used. In these
32199 cases, in order to implement Ada semantics, the GNAT run-time system
32200 calls certain Win32 routines that set the last error variable to 0 upon
32201 success. It should be possible to use @code{GetLastError} and
32202 @code{SetLastError} when tasking, protected record, and exception
32203 features are not used, but it is not guaranteed to work.
32204
32205 @item
32206 It is not possible to link against Microsoft libraries except for
32207 import libraries. The library must be built to be compatible with
32208 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
32209 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
32210 not be compatible with the GNAT runtime. Even if the library is
32211 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
32212
32213 @item
32214 When the compilation environment is located on FAT32 drives, users may
32215 experience recompilations of the source files that have not changed if
32216 Daylight Saving Time (DST) state has changed since the last time files
32217 were compiled. NTFS drives do not have this problem.
32218
32219 @item
32220 No components of the GNAT toolset use any entries in the Windows
32221 registry. The only entries that can be created are file associations and
32222 PATH settings, provided the user has chosen to create them at installation
32223 time, as well as some minimal book-keeping information needed to correctly
32224 uninstall or integrate different GNAT products.
32225 @end itemize
32226
32227 @node Using a network installation of GNAT
32228 @section Using a network installation of GNAT
32229
32230 @noindent
32231 Make sure the system on which GNAT is installed is accessible from the
32232 current machine, i.e., the install location is shared over the network.
32233 Shared resources are accessed on Windows by means of UNC paths, which
32234 have the format @code{\\server\sharename\path}
32235
32236 In order to use such a network installation, simply add the UNC path of the
32237 @file{bin} directory of your GNAT installation in front of your PATH. For
32238 example, if GNAT is installed in @file{\GNAT} directory of a share location
32239 called @file{c-drive} on a machine @file{LOKI}, the following command will
32240 make it available:
32241
32242 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
32243
32244 Be aware that every compilation using the network installation results in the
32245 transfer of large amounts of data across the network and will likely cause
32246 serious performance penalty.
32247
32248 @node CONSOLE and WINDOWS subsystems
32249 @section CONSOLE and WINDOWS subsystems
32250 @cindex CONSOLE Subsystem
32251 @cindex WINDOWS Subsystem
32252 @cindex -mwindows
32253
32254 @noindent
32255 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
32256 (which is the default subsystem) will always create a console when
32257 launching the application. This is not something desirable when the
32258 application has a Windows GUI. To get rid of this console the
32259 application must be using the @code{WINDOWS} subsystem. To do so
32260 the @option{-mwindows} linker option must be specified.
32261
32262 @smallexample
32263 $ gnatmake winprog -largs -mwindows
32264 @end smallexample
32265
32266 @node Temporary Files
32267 @section Temporary Files
32268 @cindex Temporary files
32269
32270 @noindent
32271 It is possible to control where temporary files gets created by setting
32272 the @env{TMP} environment variable. The file will be created:
32273
32274 @itemize
32275 @item Under the directory pointed to by the @env{TMP} environment variable if
32276 this directory exists.
32277
32278 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
32279 set (or not pointing to a directory) and if this directory exists.
32280
32281 @item Under the current working directory otherwise.
32282 @end itemize
32283
32284 @noindent
32285 This allows you to determine exactly where the temporary
32286 file will be created. This is particularly useful in networked
32287 environments where you may not have write access to some
32288 directories.
32289
32290 @node Mixed-Language Programming on Windows
32291 @section Mixed-Language Programming on Windows
32292
32293 @noindent
32294 Developing pure Ada applications on Windows is no different than on
32295 other GNAT-supported platforms. However, when developing or porting an
32296 application that contains a mix of Ada and C/C++, the choice of your
32297 Windows C/C++ development environment conditions your overall
32298 interoperability strategy.
32299
32300 If you use @command{gcc} to compile the non-Ada part of your application,
32301 there are no Windows-specific restrictions that affect the overall
32302 interoperability with your Ada code. If you plan to use
32303 Microsoft tools (e.g.@: Microsoft Visual C/C++), you should be aware of
32304 the following limitations:
32305
32306 @itemize @bullet
32307 @item
32308 You cannot link your Ada code with an object or library generated with
32309 Microsoft tools if these use the @code{.tls} section (Thread Local
32310 Storage section) since the GNAT linker does not yet support this section.
32311
32312 @item
32313 You cannot link your Ada code with an object or library generated with
32314 Microsoft tools if these use I/O routines other than those provided in
32315 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
32316 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
32317 libraries can cause a conflict with @code{msvcrt.dll} services. For
32318 instance Visual C++ I/O stream routines conflict with those in
32319 @code{msvcrt.dll}.
32320 @end itemize
32321
32322 @noindent
32323 If you do want to use the Microsoft tools for your non-Ada code and hit one
32324 of the above limitations, you have two choices:
32325
32326 @enumerate
32327 @item
32328 Encapsulate your non-Ada code in a DLL to be linked with your Ada
32329 application. In this case, use the Microsoft or whatever environment to
32330 build the DLL and use GNAT to build your executable
32331 (@pxref{Using DLLs with GNAT}).
32332
32333 @item
32334 Or you can encapsulate your Ada code in a DLL to be linked with the
32335 other part of your application. In this case, use GNAT to build the DLL
32336 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
32337 environment to build your executable.
32338 @end enumerate
32339
32340 @node Windows Calling Conventions
32341 @section Windows Calling Conventions
32342 @findex Stdcall
32343 @findex APIENTRY
32344
32345 @menu
32346 * C Calling Convention::
32347 * Stdcall Calling Convention::
32348 * Win32 Calling Convention::
32349 * DLL Calling Convention::
32350 @end menu
32351
32352 @noindent
32353 When a subprogram @code{F} (caller) calls a subprogram @code{G}
32354 (callee), there are several ways to push @code{G}'s parameters on the
32355 stack and there are several possible scenarios to clean up the stack
32356 upon @code{G}'s return. A calling convention is an agreed upon software
32357 protocol whereby the responsibilities between the caller (@code{F}) and
32358 the callee (@code{G}) are clearly defined. Several calling conventions
32359 are available for Windows:
32360
32361 @itemize @bullet
32362 @item
32363 @code{C} (Microsoft defined)
32364
32365 @item
32366 @code{Stdcall} (Microsoft defined)
32367
32368 @item
32369 @code{Win32} (GNAT specific)
32370
32371 @item
32372 @code{DLL} (GNAT specific)
32373 @end itemize
32374
32375 @node C Calling Convention
32376 @subsection @code{C} Calling Convention
32377
32378 @noindent
32379 This is the default calling convention used when interfacing to C/C++
32380 routines compiled with either @command{gcc} or Microsoft Visual C++.
32381
32382 In the @code{C} calling convention subprogram parameters are pushed on the
32383 stack by the caller from right to left. The caller itself is in charge of
32384 cleaning up the stack after the call. In addition, the name of a routine
32385 with @code{C} calling convention is mangled by adding a leading underscore.
32386
32387 The name to use on the Ada side when importing (or exporting) a routine
32388 with @code{C} calling convention is the name of the routine. For
32389 instance the C function:
32390
32391 @smallexample
32392 int get_val (long);
32393 @end smallexample
32394
32395 @noindent
32396 should be imported from Ada as follows:
32397
32398 @smallexample @c ada
32399 @group
32400 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32401 pragma Import (C, Get_Val, External_Name => "get_val");
32402 @end group
32403 @end smallexample
32404
32405 @noindent
32406 Note that in this particular case the @code{External_Name} parameter could
32407 have been omitted since, when missing, this parameter is taken to be the
32408 name of the Ada entity in lower case. When the @code{Link_Name} parameter
32409 is missing, as in the above example, this parameter is set to be the
32410 @code{External_Name} with a leading underscore.
32411
32412 When importing a variable defined in C, you should always use the @code{C}
32413 calling convention unless the object containing the variable is part of a
32414 DLL (in which case you should use the @code{Stdcall} calling
32415 convention, @pxref{Stdcall Calling Convention}).
32416
32417 @node Stdcall Calling Convention
32418 @subsection @code{Stdcall} Calling Convention
32419
32420 @noindent
32421 This convention, which was the calling convention used for Pascal
32422 programs, is used by Microsoft for all the routines in the Win32 API for
32423 efficiency reasons. It must be used to import any routine for which this
32424 convention was specified.
32425
32426 In the @code{Stdcall} calling convention subprogram parameters are pushed
32427 on the stack by the caller from right to left. The callee (and not the
32428 caller) is in charge of cleaning the stack on routine exit. In addition,
32429 the name of a routine with @code{Stdcall} calling convention is mangled by
32430 adding a leading underscore (as for the @code{C} calling convention) and a
32431 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
32432 bytes) of the parameters passed to the routine.
32433
32434 The name to use on the Ada side when importing a C routine with a
32435 @code{Stdcall} calling convention is the name of the C routine. The leading
32436 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
32437 the compiler. For instance the Win32 function:
32438
32439 @smallexample
32440 @b{APIENTRY} int get_val (long);
32441 @end smallexample
32442
32443 @noindent
32444 should be imported from Ada as follows:
32445
32446 @smallexample @c ada
32447 @group
32448 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32449 pragma Import (Stdcall, Get_Val);
32450 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
32451 @end group
32452 @end smallexample
32453
32454 @noindent
32455 As for the @code{C} calling convention, when the @code{External_Name}
32456 parameter is missing, it is taken to be the name of the Ada entity in lower
32457 case. If instead of writing the above import pragma you write:
32458
32459 @smallexample @c ada
32460 @group
32461 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32462 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
32463 @end group
32464 @end smallexample
32465
32466 @noindent
32467 then the imported routine is @code{_retrieve_val@@4}. However, if instead
32468 of specifying the @code{External_Name} parameter you specify the
32469 @code{Link_Name} as in the following example:
32470
32471 @smallexample @c ada
32472 @group
32473 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
32474 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
32475 @end group
32476 @end smallexample
32477
32478 @noindent
32479 then the imported routine is @code{retrieve_val}, that is, there is no
32480 decoration at all. No leading underscore and no Stdcall suffix
32481 @code{@@}@code{@var{nn}}.
32482
32483 @noindent
32484 This is especially important as in some special cases a DLL's entry
32485 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
32486 name generated for a call has it.
32487
32488 @noindent
32489 It is also possible to import variables defined in a DLL by using an
32490 import pragma for a variable. As an example, if a DLL contains a
32491 variable defined as:
32492
32493 @smallexample
32494 int my_var;
32495 @end smallexample
32496
32497 @noindent
32498 then, to access this variable from Ada you should write:
32499
32500 @smallexample @c ada
32501 @group
32502 My_Var : Interfaces.C.int;
32503 pragma Import (Stdcall, My_Var);
32504 @end group
32505 @end smallexample
32506
32507 @noindent
32508 Note that to ease building cross-platform bindings this convention
32509 will be handled as a @code{C} calling convention on non-Windows platforms.
32510
32511 @node Win32 Calling Convention
32512 @subsection @code{Win32} Calling Convention
32513
32514 @noindent
32515 This convention, which is GNAT-specific is fully equivalent to the
32516 @code{Stdcall} calling convention described above.
32517
32518 @node DLL Calling Convention
32519 @subsection @code{DLL} Calling Convention
32520
32521 @noindent
32522 This convention, which is GNAT-specific is fully equivalent to the
32523 @code{Stdcall} calling convention described above.
32524
32525 @node Introduction to Dynamic Link Libraries (DLLs)
32526 @section Introduction to Dynamic Link Libraries (DLLs)
32527 @findex DLL
32528
32529 @noindent
32530 A Dynamically Linked Library (DLL) is a library that can be shared by
32531 several applications running under Windows. A DLL can contain any number of
32532 routines and variables.
32533
32534 One advantage of DLLs is that you can change and enhance them without
32535 forcing all the applications that depend on them to be relinked or
32536 recompiled. However, you should be aware than all calls to DLL routines are
32537 slower since, as you will understand below, such calls are indirect.
32538
32539 To illustrate the remainder of this section, suppose that an application
32540 wants to use the services of a DLL @file{API.dll}. To use the services
32541 provided by @file{API.dll} you must statically link against the DLL or
32542 an import library which contains a jump table with an entry for each
32543 routine and variable exported by the DLL. In the Microsoft world this
32544 import library is called @file{API.lib}. When using GNAT this import
32545 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
32546 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
32547
32548 After you have linked your application with the DLL or the import library
32549 and you run your application, here is what happens:
32550
32551 @enumerate
32552 @item
32553 Your application is loaded into memory.
32554
32555 @item
32556 The DLL @file{API.dll} is mapped into the address space of your
32557 application. This means that:
32558
32559 @itemize @bullet
32560 @item
32561 The DLL will use the stack of the calling thread.
32562
32563 @item
32564 The DLL will use the virtual address space of the calling process.
32565
32566 @item
32567 The DLL will allocate memory from the virtual address space of the calling
32568 process.
32569
32570 @item
32571 Handles (pointers) can be safely exchanged between routines in the DLL
32572 routines and routines in the application using the DLL.
32573 @end itemize
32574
32575 @item
32576 The entries in the jump table (from the import library @file{libAPI.dll.a}
32577 or @file{API.lib} or automatically created when linking against a DLL)
32578 which is part of your application are initialized with the addresses
32579 of the routines and variables in @file{API.dll}.
32580
32581 @item
32582 If present in @file{API.dll}, routines @code{DllMain} or
32583 @code{DllMainCRTStartup} are invoked. These routines typically contain
32584 the initialization code needed for the well-being of the routines and
32585 variables exported by the DLL.
32586 @end enumerate
32587
32588 @noindent
32589 There is an additional point which is worth mentioning. In the Windows
32590 world there are two kind of DLLs: relocatable and non-relocatable
32591 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
32592 in the target application address space. If the addresses of two
32593 non-relocatable DLLs overlap and these happen to be used by the same
32594 application, a conflict will occur and the application will run
32595 incorrectly. Hence, when possible, it is always preferable to use and
32596 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
32597 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
32598 User's Guide) removes the debugging symbols from the DLL but the DLL can
32599 still be relocated.
32600
32601 As a side note, an interesting difference between Microsoft DLLs and
32602 Unix shared libraries, is the fact that on most Unix systems all public
32603 routines are exported by default in a Unix shared library, while under
32604 Windows it is possible (but not required) to list exported routines in
32605 a definition file (@pxref{The Definition File}).
32606
32607 @node Using DLLs with GNAT
32608 @section Using DLLs with GNAT
32609
32610 @menu
32611 * Creating an Ada Spec for the DLL Services::
32612 * Creating an Import Library::
32613 @end menu
32614
32615 @noindent
32616 To use the services of a DLL, say @file{API.dll}, in your Ada application
32617 you must have:
32618
32619 @enumerate
32620 @item
32621 The Ada spec for the routines and/or variables you want to access in
32622 @file{API.dll}. If not available this Ada spec must be built from the C/C++
32623 header files provided with the DLL.
32624
32625 @item
32626 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
32627 mentioned an import library is a statically linked library containing the
32628 import table which will be filled at load time to point to the actual
32629 @file{API.dll} routines. Sometimes you don't have an import library for the
32630 DLL you want to use. The following sections will explain how to build
32631 one. Note that this is optional.
32632
32633 @item
32634 The actual DLL, @file{API.dll}.
32635 @end enumerate
32636
32637 @noindent
32638 Once you have all the above, to compile an Ada application that uses the
32639 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
32640 you simply issue the command
32641
32642 @smallexample
32643 $ gnatmake my_ada_app -largs -lAPI
32644 @end smallexample
32645
32646 @noindent
32647 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
32648 tells the GNAT linker to look first for a library named @file{API.lib}
32649 (Microsoft-style name) and if not found for a libraries named
32650 @file{libAPI.dll.a}, @file{API.dll.a} or @file{libAPI.a}.
32651 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
32652 contains the following pragma
32653
32654 @smallexample @c ada
32655 pragma Linker_Options ("-lAPI");
32656 @end smallexample
32657
32658 @noindent
32659 you do not have to add @option{-largs -lAPI} at the end of the
32660 @command{gnatmake} command.
32661
32662 If any one of the items above is missing you will have to create it
32663 yourself. The following sections explain how to do so using as an
32664 example a fictitious DLL called @file{API.dll}.
32665
32666 @node Creating an Ada Spec for the DLL Services
32667 @subsection Creating an Ada Spec for the DLL Services
32668
32669 @noindent
32670 A DLL typically comes with a C/C++ header file which provides the
32671 definitions of the routines and variables exported by the DLL. The Ada
32672 equivalent of this header file is a package spec that contains definitions
32673 for the imported entities. If the DLL you intend to use does not come with
32674 an Ada spec you have to generate one such spec yourself. For example if
32675 the header file of @file{API.dll} is a file @file{api.h} containing the
32676 following two definitions:
32677
32678 @smallexample
32679 @group
32680 @cartouche
32681 int some_var;
32682 int get (char *);
32683 @end cartouche
32684 @end group
32685 @end smallexample
32686
32687 @noindent
32688 then the equivalent Ada spec could be:
32689
32690 @smallexample @c ada
32691 @group
32692 @cartouche
32693 with Interfaces.C.Strings;
32694 package API is
32695    use Interfaces;
32696
32697    Some_Var : C.int;
32698    function Get (Str : C.Strings.Chars_Ptr) return C.int;
32699
32700 private
32701    pragma Import (C, Get);
32702    pragma Import (DLL, Some_Var);
32703 end API;
32704 @end cartouche
32705 @end group
32706 @end smallexample
32707
32708 @noindent
32709 Note that a variable is
32710 @strong{always imported with a Stdcall convention}. A function
32711 can have @code{C} or @code{Stdcall} convention.
32712 (@pxref{Windows Calling Conventions}).
32713
32714 @node Creating an Import Library
32715 @subsection Creating an Import Library
32716 @cindex Import library
32717
32718 @menu
32719 * The Definition File::
32720 * GNAT-Style Import Library::
32721 * Microsoft-Style Import Library::
32722 @end menu
32723
32724 @noindent
32725 If a Microsoft-style import library @file{API.lib} or a GNAT-style
32726 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
32727 with @file{API.dll} you can skip this section. You can also skip this
32728 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
32729 as in this case it is possible to link directly against the
32730 DLL. Otherwise read on.
32731
32732 @node The Definition File
32733 @subsubsection The Definition File
32734 @cindex Definition file
32735 @findex .def
32736
32737 @noindent
32738 As previously mentioned, and unlike Unix systems, the list of symbols
32739 that are exported from a DLL must be provided explicitly in Windows.
32740 The main goal of a definition file is precisely that: list the symbols
32741 exported by a DLL. A definition file (usually a file with a @code{.def}
32742 suffix) has the following structure:
32743
32744 @smallexample
32745 @group
32746 @cartouche
32747 @r{[}LIBRARY @var{name}@r{]}
32748 @r{[}DESCRIPTION @var{string}@r{]}
32749 EXPORTS
32750    @var{symbol1}
32751    @var{symbol2}
32752    @dots{}
32753 @end cartouche
32754 @end group
32755 @end smallexample
32756
32757 @table @code
32758 @item LIBRARY @var{name}
32759 This section, which is optional, gives the name of the DLL.
32760
32761 @item DESCRIPTION @var{string}
32762 This section, which is optional, gives a description string that will be
32763 embedded in the import library.
32764
32765 @item EXPORTS
32766 This section gives the list of exported symbols (procedures, functions or
32767 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
32768 section of @file{API.def} looks like:
32769
32770 @smallexample
32771 @group
32772 @cartouche
32773 EXPORTS
32774    some_var
32775    get
32776 @end cartouche
32777 @end group
32778 @end smallexample
32779 @end table
32780
32781 @noindent
32782 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
32783 (@pxref{Windows Calling Conventions}) for a Stdcall
32784 calling convention function in the exported symbols list.
32785
32786 @noindent
32787 There can actually be other sections in a definition file, but these
32788 sections are not relevant to the discussion at hand.
32789
32790 @node GNAT-Style Import Library
32791 @subsubsection GNAT-Style Import Library
32792
32793 @noindent
32794 To create a static import library from @file{API.dll} with the GNAT tools
32795 you should proceed as follows:
32796
32797 @enumerate
32798 @item
32799 Create the definition file @file{API.def} (@pxref{The Definition File}).
32800 For that use the @code{dll2def} tool as follows:
32801
32802 @smallexample
32803 $ dll2def API.dll > API.def
32804 @end smallexample
32805
32806 @noindent
32807 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
32808 to standard output the list of entry points in the DLL. Note that if
32809 some routines in the DLL have the @code{Stdcall} convention
32810 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
32811 suffix then you'll have to edit @file{api.def} to add it, and specify
32812 @option{-k} to @command{gnatdll} when creating the import library.
32813
32814 @noindent
32815 Here are some hints to find the right @code{@@}@var{nn} suffix.
32816
32817 @enumerate
32818 @item
32819 If you have the Microsoft import library (.lib), it is possible to get
32820 the right symbols by using Microsoft @code{dumpbin} tool (see the
32821 corresponding Microsoft documentation for further details).
32822
32823 @smallexample
32824 $ dumpbin /exports api.lib
32825 @end smallexample
32826
32827 @item
32828 If you have a message about a missing symbol at link time the compiler
32829 tells you what symbol is expected. You just have to go back to the
32830 definition file and add the right suffix.
32831 @end enumerate
32832
32833 @item
32834 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
32835 (@pxref{Using gnatdll}) as follows:
32836
32837 @smallexample
32838 $ gnatdll -e API.def -d API.dll
32839 @end smallexample
32840
32841 @noindent
32842 @code{gnatdll} takes as input a definition file @file{API.def} and the
32843 name of the DLL containing the services listed in the definition file
32844 @file{API.dll}. The name of the static import library generated is
32845 computed from the name of the definition file as follows: if the
32846 definition file name is @var{xyz}@code{.def}, the import library name will
32847 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
32848 @option{-e} could have been removed because the name of the definition
32849 file (before the ``@code{.def}'' suffix) is the same as the name of the
32850 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
32851 @end enumerate
32852
32853 @node Microsoft-Style Import Library
32854 @subsubsection Microsoft-Style Import Library
32855
32856 @noindent
32857 With GNAT you can either use a GNAT-style or Microsoft-style import
32858 library. A Microsoft import library is needed only if you plan to make an
32859 Ada DLL available to applications developed with Microsoft
32860 tools (@pxref{Mixed-Language Programming on Windows}).
32861
32862 To create a Microsoft-style import library for @file{API.dll} you
32863 should proceed as follows:
32864
32865 @enumerate
32866 @item
32867 Create the definition file @file{API.def} from the DLL. For this use either
32868 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
32869 tool (see the corresponding Microsoft documentation for further details).
32870
32871 @item
32872 Build the actual import library using Microsoft's @code{lib} utility:
32873
32874 @smallexample
32875 $ lib -machine:IX86 -def:API.def -out:API.lib
32876 @end smallexample
32877
32878 @noindent
32879 If you use the above command the definition file @file{API.def} must
32880 contain a line giving the name of the DLL:
32881
32882 @smallexample
32883 LIBRARY      "API"
32884 @end smallexample
32885
32886 @noindent
32887 See the Microsoft documentation for further details about the usage of
32888 @code{lib}.
32889 @end enumerate
32890
32891 @node Building DLLs with GNAT
32892 @section Building DLLs with GNAT
32893 @cindex DLLs, building
32894
32895 @noindent
32896 This section explain how to build DLLs using the GNAT built-in DLL
32897 support. With the following procedure it is straight forward to build
32898 and use DLLs with GNAT.
32899
32900 @enumerate
32901
32902 @item building object files
32903
32904 The first step is to build all objects files that are to be included
32905 into the DLL. This is done by using the standard @command{gnatmake} tool.
32906
32907 @item building the DLL
32908
32909 To build the DLL you must use @command{gcc}'s @option{-shared}
32910 option. It is quite simple to use this method:
32911
32912 @smallexample
32913 $ gcc -shared -o api.dll obj1.o obj2.o @dots{}
32914 @end smallexample
32915
32916 It is important to note that in this case all symbols found in the
32917 object files are automatically exported. It is possible to restrict
32918 the set of symbols to export by passing to @command{gcc} a definition
32919 file, @pxref{The Definition File}. For example:
32920
32921 @smallexample
32922 $ gcc -shared -o api.dll api.def obj1.o obj2.o @dots{}
32923 @end smallexample
32924
32925 If you use a definition file you must export the elaboration procedures
32926 for every package that required one. Elaboration procedures are named
32927 using the package name followed by "_E".
32928
32929 @item preparing DLL to be used
32930
32931 For the DLL to be used by client programs the bodies must be hidden
32932 from it and the .ali set with read-only attribute. This is very important
32933 otherwise GNAT will recompile all packages and will not actually use
32934 the code in the DLL. For example:
32935
32936 @smallexample
32937 $ mkdir apilib
32938 $ copy *.ads *.ali api.dll apilib
32939 $ attrib +R apilib\*.ali
32940 @end smallexample
32941
32942 @end enumerate
32943
32944 At this point it is possible to use the DLL by directly linking
32945 against it. Note that you must use the GNAT shared runtime when using
32946 GNAT shared libraries. This is achieved by using @option{-shared} binder's
32947 option.
32948
32949 @smallexample
32950 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
32951 @end smallexample
32952
32953 @node Building DLLs with GNAT Project files
32954 @section Building DLLs with GNAT Project files
32955 @cindex DLLs, building
32956
32957 @noindent
32958 There is nothing specific to Windows in the build process.
32959 @pxref{Library Projects}.
32960
32961 @noindent
32962 Due to a system limitation, it is not possible under Windows to create threads
32963 when inside the @code{DllMain} routine which is used for auto-initialization
32964 of shared libraries, so it is not possible to have library level tasks in SALs.
32965
32966 @node Building DLLs with gnatdll
32967 @section Building DLLs with gnatdll
32968 @cindex DLLs, building
32969
32970 @menu
32971 * Limitations When Using Ada DLLs from Ada::
32972 * Exporting Ada Entities::
32973 * Ada DLLs and Elaboration::
32974 * Ada DLLs and Finalization::
32975 * Creating a Spec for Ada DLLs::
32976 * Creating the Definition File::
32977 * Using gnatdll::
32978 @end menu
32979
32980 @noindent
32981 Note that it is preferred to use the built-in GNAT DLL support
32982 (@pxref{Building DLLs with GNAT}) or GNAT Project files
32983 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
32984
32985 This section explains how to build DLLs containing Ada code using
32986 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
32987 remainder of this section.
32988
32989 The steps required to build an Ada DLL that is to be used by Ada as well as
32990 non-Ada applications are as follows:
32991
32992 @enumerate
32993 @item
32994 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
32995 @code{Stdcall} calling convention to avoid any Ada name mangling for the
32996 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
32997 skip this step if you plan to use the Ada DLL only from Ada applications.
32998
32999 @item
33000 Your Ada code must export an initialization routine which calls the routine
33001 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
33002 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
33003 routine exported by the Ada DLL must be invoked by the clients of the DLL
33004 to initialize the DLL.
33005
33006 @item
33007 When useful, the DLL should also export a finalization routine which calls
33008 routine @code{adafinal} generated by @command{gnatbind} to perform the
33009 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
33010 The finalization routine exported by the Ada DLL must be invoked by the
33011 clients of the DLL when the DLL services are no further needed.
33012
33013 @item
33014 You must provide a spec for the services exported by the Ada DLL in each
33015 of the programming languages to which you plan to make the DLL available.
33016
33017 @item
33018 You must provide a definition file listing the exported entities
33019 (@pxref{The Definition File}).
33020
33021 @item
33022 Finally you must use @code{gnatdll} to produce the DLL and the import
33023 library (@pxref{Using gnatdll}).
33024 @end enumerate
33025
33026 @noindent
33027 Note that a relocatable DLL stripped using the @code{strip}
33028 binutils tool will not be relocatable anymore. To build a DLL without
33029 debug information pass @code{-largs -s} to @code{gnatdll}. This
33030 restriction does not apply to a DLL built using a Library Project.
33031 @pxref{Library Projects}.
33032
33033 @node Limitations When Using Ada DLLs from Ada
33034 @subsection Limitations When Using Ada DLLs from Ada
33035
33036 @noindent
33037 When using Ada DLLs from Ada applications there is a limitation users
33038 should be aware of. Because on Windows the GNAT run time is not in a DLL of
33039 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
33040 each Ada DLL includes the services of the GNAT run time that are necessary
33041 to the Ada code inside the DLL. As a result, when an Ada program uses an
33042 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
33043 one in the main program.
33044
33045 It is therefore not possible to exchange GNAT run-time objects between the
33046 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
33047 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
33048 types, etc.
33049
33050 It is completely safe to exchange plain elementary, array or record types,
33051 Windows object handles, etc.
33052
33053 @node Exporting Ada Entities
33054 @subsection Exporting Ada Entities
33055 @cindex Export table
33056
33057 @noindent
33058 Building a DLL is a way to encapsulate a set of services usable from any
33059 application. As a result, the Ada entities exported by a DLL should be
33060 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
33061 any Ada name mangling. As an example here is an Ada package
33062 @code{API}, spec and body, exporting two procedures, a function, and a
33063 variable:
33064
33065 @smallexample @c ada
33066 @group
33067 @cartouche
33068 with Interfaces.C; use Interfaces;
33069 package API is
33070    Count : C.int := 0;
33071    function Factorial (Val : C.int) return C.int;
33072
33073    procedure Initialize_API;
33074    procedure Finalize_API;
33075    --  Initialization & Finalization routines. More in the next section.
33076 private
33077    pragma Export (C, Initialize_API);
33078    pragma Export (C, Finalize_API);
33079    pragma Export (C, Count);
33080    pragma Export (C, Factorial);
33081 end API;
33082 @end cartouche
33083 @end group
33084 @end smallexample
33085
33086 @smallexample @c ada
33087 @group
33088 @cartouche
33089 package body API is
33090    function Factorial (Val : C.int) return C.int is
33091       Fact : C.int := 1;
33092    begin
33093       Count := Count + 1;
33094       for K in 1 .. Val loop
33095          Fact := Fact * K;
33096       end loop;
33097       return Fact;
33098    end Factorial;
33099
33100    procedure Initialize_API is
33101       procedure Adainit;
33102       pragma Import (C, Adainit);
33103    begin
33104       Adainit;
33105    end Initialize_API;
33106
33107    procedure Finalize_API is
33108       procedure Adafinal;
33109       pragma Import (C, Adafinal);
33110    begin
33111       Adafinal;
33112    end Finalize_API;
33113 end API;
33114 @end cartouche
33115 @end group
33116 @end smallexample
33117
33118 @noindent
33119 If the Ada DLL you are building will only be used by Ada applications
33120 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
33121 convention. As an example, the previous package could be written as
33122 follows:
33123
33124 @smallexample @c ada
33125 @group
33126 @cartouche
33127 package API is
33128    Count : Integer := 0;
33129    function Factorial (Val : Integer) return Integer;
33130
33131    procedure Initialize_API;
33132    procedure Finalize_API;
33133    --  Initialization and Finalization routines.
33134 end API;
33135 @end cartouche
33136 @end group
33137 @end smallexample
33138
33139 @smallexample @c ada
33140 @group
33141 @cartouche
33142 package body API is
33143    function Factorial (Val : Integer) return Integer is
33144       Fact : Integer := 1;
33145    begin
33146       Count := Count + 1;
33147       for K in 1 .. Val loop
33148          Fact := Fact * K;
33149       end loop;
33150       return Fact;
33151    end Factorial;
33152
33153    @dots{}
33154    --  The remainder of this package body is unchanged.
33155 end API;
33156 @end cartouche
33157 @end group
33158 @end smallexample
33159
33160 @noindent
33161 Note that if you do not export the Ada entities with a @code{C} or
33162 @code{Stdcall} convention you will have to provide the mangled Ada names
33163 in the definition file of the Ada DLL
33164 (@pxref{Creating the Definition File}).
33165
33166 @node Ada DLLs and Elaboration
33167 @subsection Ada DLLs and Elaboration
33168 @cindex DLLs and elaboration
33169
33170 @noindent
33171 The DLL that you are building contains your Ada code as well as all the
33172 routines in the Ada library that are needed by it. The first thing a
33173 user of your DLL must do is elaborate the Ada code
33174 (@pxref{Elaboration Order Handling in GNAT}).
33175
33176 To achieve this you must export an initialization routine
33177 (@code{Initialize_API} in the previous example), which must be invoked
33178 before using any of the DLL services. This elaboration routine must call
33179 the Ada elaboration routine @code{adainit} generated by the GNAT binder
33180 (@pxref{Binding with Non-Ada Main Programs}). See the body of
33181 @code{Initialize_Api} for an example. Note that the GNAT binder is
33182 automatically invoked during the DLL build process by the @code{gnatdll}
33183 tool (@pxref{Using gnatdll}).
33184
33185 When a DLL is loaded, Windows systematically invokes a routine called
33186 @code{DllMain}. It would therefore be possible to call @code{adainit}
33187 directly from @code{DllMain} without having to provide an explicit
33188 initialization routine. Unfortunately, it is not possible to call
33189 @code{adainit} from the @code{DllMain} if your program has library level
33190 tasks because access to the @code{DllMain} entry point is serialized by
33191 the system (that is, only a single thread can execute ``through'' it at a
33192 time), which means that the GNAT run time will deadlock waiting for the
33193 newly created task to complete its initialization.
33194
33195 @node Ada DLLs and Finalization
33196 @subsection Ada DLLs and Finalization
33197 @cindex DLLs and finalization
33198
33199 @noindent
33200 When the services of an Ada DLL are no longer needed, the client code should
33201 invoke the DLL finalization routine, if available. The DLL finalization
33202 routine is in charge of releasing all resources acquired by the DLL. In the
33203 case of the Ada code contained in the DLL, this is achieved by calling
33204 routine @code{adafinal} generated by the GNAT binder
33205 (@pxref{Binding with Non-Ada Main Programs}).
33206 See the body of @code{Finalize_Api} for an
33207 example. As already pointed out the GNAT binder is automatically invoked
33208 during the DLL build process by the @code{gnatdll} tool
33209 (@pxref{Using gnatdll}).
33210
33211 @node Creating a Spec for Ada DLLs
33212 @subsection Creating a Spec for Ada DLLs
33213
33214 @noindent
33215 To use the services exported by the Ada DLL from another programming
33216 language (e.g.@: C), you have to translate the specs of the exported Ada
33217 entities in that language. For instance in the case of @code{API.dll},
33218 the corresponding C header file could look like:
33219
33220 @smallexample
33221 @group
33222 @cartouche
33223 extern int *_imp__count;
33224 #define count (*_imp__count)
33225 int factorial (int);
33226 @end cartouche
33227 @end group
33228 @end smallexample
33229
33230 @noindent
33231 It is important to understand that when building an Ada DLL to be used by
33232 other Ada applications, you need two different specs for the packages
33233 contained in the DLL: one for building the DLL and the other for using
33234 the DLL. This is because the @code{DLL} calling convention is needed to
33235 use a variable defined in a DLL, but when building the DLL, the variable
33236 must have either the @code{Ada} or @code{C} calling convention. As an
33237 example consider a DLL comprising the following package @code{API}:
33238
33239 @smallexample @c ada
33240 @group
33241 @cartouche
33242 package API is
33243    Count : Integer := 0;
33244    @dots{}
33245    --  Remainder of the package omitted.
33246 end API;
33247 @end cartouche
33248 @end group
33249 @end smallexample
33250
33251 @noindent
33252 After producing a DLL containing package @code{API}, the spec that
33253 must be used to import @code{API.Count} from Ada code outside of the
33254 DLL is:
33255
33256 @smallexample @c ada
33257 @group
33258 @cartouche
33259 package API is
33260    Count : Integer;
33261    pragma Import (DLL, Count);
33262 end API;
33263 @end cartouche
33264 @end group
33265 @end smallexample
33266
33267 @node Creating the Definition File
33268 @subsection Creating the Definition File
33269
33270 @noindent
33271 The definition file is the last file needed to build the DLL. It lists
33272 the exported symbols. As an example, the definition file for a DLL
33273 containing only package @code{API} (where all the entities are exported
33274 with a @code{C} calling convention) is:
33275
33276 @smallexample
33277 @group
33278 @cartouche
33279 EXPORTS
33280     count
33281     factorial
33282     finalize_api
33283     initialize_api
33284 @end cartouche
33285 @end group
33286 @end smallexample
33287
33288 @noindent
33289 If the @code{C} calling convention is missing from package @code{API},
33290 then the definition file contains the mangled Ada names of the above
33291 entities, which in this case are:
33292
33293 @smallexample
33294 @group
33295 @cartouche
33296 EXPORTS
33297     api__count
33298     api__factorial
33299     api__finalize_api
33300     api__initialize_api
33301 @end cartouche
33302 @end group
33303 @end smallexample
33304
33305 @node Using gnatdll
33306 @subsection Using @code{gnatdll}
33307 @findex gnatdll
33308
33309 @menu
33310 * gnatdll Example::
33311 * gnatdll behind the Scenes::
33312 * Using dlltool::
33313 @end menu
33314
33315 @noindent
33316 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
33317 and non-Ada sources that make up your DLL have been compiled.
33318 @code{gnatdll} is actually in charge of two distinct tasks: build the
33319 static import library for the DLL and the actual DLL. The form of the
33320 @code{gnatdll} command is
33321
33322 @smallexample
33323 @cartouche
33324 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
33325 @c Expanding @ovar macro inline (explanation in macro def comments)
33326 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
33327 @end cartouche
33328 @end smallexample
33329
33330 @noindent
33331 where @var{list-of-files} is a list of ALI and object files. The object
33332 file list must be the exact list of objects corresponding to the non-Ada
33333 sources whose services are to be included in the DLL. The ALI file list
33334 must be the exact list of ALI files for the corresponding Ada sources
33335 whose services are to be included in the DLL. If @var{list-of-files} is
33336 missing, only the static import library is generated.
33337
33338 @noindent
33339 You may specify any of the following switches to @code{gnatdll}:
33340
33341 @table @code
33342 @c @item -a@ovar{address}
33343 @c Expanding @ovar macro inline (explanation in macro def comments)
33344 @item -a@r{[}@var{address}@r{]}
33345 @cindex @option{-a} (@code{gnatdll})
33346 Build a non-relocatable DLL at @var{address}. If @var{address} is not
33347 specified the default address @var{0x11000000} will be used. By default,
33348 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
33349 advise the reader to build relocatable DLL.
33350
33351 @item -b @var{address}
33352 @cindex @option{-b} (@code{gnatdll})
33353 Set the relocatable DLL base address. By default the address is
33354 @code{0x11000000}.
33355
33356 @item -bargs @var{opts}
33357 @cindex @option{-bargs} (@code{gnatdll})
33358 Binder options. Pass @var{opts} to the binder.
33359
33360 @item -d @var{dllfile}
33361 @cindex @option{-d} (@code{gnatdll})
33362 @var{dllfile} is the name of the DLL. This switch must be present for
33363 @code{gnatdll} to do anything. The name of the generated import library is
33364 obtained algorithmically from @var{dllfile} as shown in the following
33365 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
33366 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
33367 by option @option{-e}) is obtained algorithmically from @var{dllfile}
33368 as shown in the following example:
33369 if @var{dllfile} is @code{xyz.dll}, the definition
33370 file used is @code{xyz.def}.
33371
33372 @item -e @var{deffile}
33373 @cindex @option{-e} (@code{gnatdll})
33374 @var{deffile} is the name of the definition file.
33375
33376 @item -g
33377 @cindex @option{-g} (@code{gnatdll})
33378 Generate debugging information. This information is stored in the object
33379 file and copied from there to the final DLL file by the linker,
33380 where it can be read by the debugger. You must use the
33381 @option{-g} switch if you plan on using the debugger or the symbolic
33382 stack traceback.
33383
33384 @item -h
33385 @cindex @option{-h} (@code{gnatdll})
33386 Help mode. Displays @code{gnatdll} switch usage information.
33387
33388 @item -Idir
33389 @cindex @option{-I} (@code{gnatdll})
33390 Direct @code{gnatdll} to search the @var{dir} directory for source and
33391 object files needed to build the DLL.
33392 (@pxref{Search Paths and the Run-Time Library (RTL)}).
33393
33394 @item -k
33395 @cindex @option{-k} (@code{gnatdll})
33396 Removes the @code{@@}@var{nn} suffix from the import library's exported
33397 names, but keeps them for the link names. You must specify this
33398 option if you want to use a @code{Stdcall} function in a DLL for which
33399 the @code{@@}@var{nn} suffix has been removed. This is the case for most
33400 of the Windows NT DLL for example. This option has no effect when
33401 @option{-n} option is specified.
33402
33403 @item -l @var{file}
33404 @cindex @option{-l} (@code{gnatdll})
33405 The list of ALI and object files used to build the DLL are listed in
33406 @var{file}, instead of being given in the command line. Each line in
33407 @var{file} contains the name of an ALI or object file.
33408
33409 @item -n
33410 @cindex @option{-n} (@code{gnatdll})
33411 No Import. Do not create the import library.
33412
33413 @item -q
33414 @cindex @option{-q} (@code{gnatdll})
33415 Quiet mode. Do not display unnecessary messages.
33416
33417 @item -v
33418 @cindex @option{-v} (@code{gnatdll})
33419 Verbose mode. Display extra information.
33420
33421 @item -largs @var{opts}
33422 @cindex @option{-largs} (@code{gnatdll})
33423 Linker options. Pass @var{opts} to the linker.
33424 @end table
33425
33426 @node gnatdll Example
33427 @subsubsection @code{gnatdll} Example
33428
33429 @noindent
33430 As an example the command to build a relocatable DLL from @file{api.adb}
33431 once @file{api.adb} has been compiled and @file{api.def} created is
33432
33433 @smallexample
33434 $ gnatdll -d api.dll api.ali
33435 @end smallexample
33436
33437 @noindent
33438 The above command creates two files: @file{libapi.dll.a} (the import
33439 library) and @file{api.dll} (the actual DLL). If you want to create
33440 only the DLL, just type:
33441
33442 @smallexample
33443 $ gnatdll -d api.dll -n api.ali
33444 @end smallexample
33445
33446 @noindent
33447 Alternatively if you want to create just the import library, type:
33448
33449 @smallexample
33450 $ gnatdll -d api.dll
33451 @end smallexample
33452
33453 @node gnatdll behind the Scenes
33454 @subsubsection @code{gnatdll} behind the Scenes
33455
33456 @noindent
33457 This section details the steps involved in creating a DLL. @code{gnatdll}
33458 does these steps for you. Unless you are interested in understanding what
33459 goes on behind the scenes, you should skip this section.
33460
33461 We use the previous example of a DLL containing the Ada package @code{API},
33462 to illustrate the steps necessary to build a DLL. The starting point is a
33463 set of objects that will make up the DLL and the corresponding ALI
33464 files. In the case of this example this means that @file{api.o} and
33465 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
33466 the following:
33467
33468 @enumerate
33469 @item
33470 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
33471 the information necessary to generate relocation information for the
33472 DLL.
33473
33474 @smallexample
33475 @group
33476 $ gnatbind -n api
33477 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
33478 @end group
33479 @end smallexample
33480
33481 @noindent
33482 In addition to the base file, the @command{gnatlink} command generates an
33483 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
33484 asks @command{gnatlink} to generate the routines @code{DllMain} and
33485 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
33486 is loaded into memory.
33487
33488 @item
33489 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
33490 export table (@file{api.exp}). The export table contains the relocation
33491 information in a form which can be used during the final link to ensure
33492 that the Windows loader is able to place the DLL anywhere in memory.
33493
33494 @smallexample
33495 @group
33496 $ dlltool --dllname api.dll --def api.def --base-file api.base \
33497           --output-exp api.exp
33498 @end group
33499 @end smallexample
33500
33501 @item
33502 @code{gnatdll} builds the base file using the new export table. Note that
33503 @command{gnatbind} must be called once again since the binder generated file
33504 has been deleted during the previous call to @command{gnatlink}.
33505
33506 @smallexample
33507 @group
33508 $ gnatbind -n api
33509 $ gnatlink api -o api.jnk api.exp -mdll
33510       -Wl,--base-file,api.base
33511 @end group
33512 @end smallexample
33513
33514 @item
33515 @code{gnatdll} builds the new export table using the new base file and
33516 generates the DLL import library @file{libAPI.dll.a}.
33517
33518 @smallexample
33519 @group
33520 $ dlltool --dllname api.dll --def api.def --base-file api.base \
33521           --output-exp api.exp --output-lib libAPI.a
33522 @end group
33523 @end smallexample
33524
33525 @item
33526 Finally @code{gnatdll} builds the relocatable DLL using the final export
33527 table.
33528
33529 @smallexample
33530 @group
33531 $ gnatbind -n api
33532 $ gnatlink api api.exp -o api.dll -mdll
33533 @end group
33534 @end smallexample
33535 @end enumerate
33536
33537 @node Using dlltool
33538 @subsubsection Using @code{dlltool}
33539
33540 @noindent
33541 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
33542 DLLs and static import libraries. This section summarizes the most
33543 common @code{dlltool} switches. The form of the @code{dlltool} command
33544 is
33545
33546 @smallexample
33547 @c $ dlltool @ovar{switches}
33548 @c Expanding @ovar macro inline (explanation in macro def comments)
33549 $ dlltool @r{[}@var{switches}@r{]}
33550 @end smallexample
33551
33552 @noindent
33553 @code{dlltool} switches include:
33554
33555 @table @option
33556 @item --base-file @var{basefile}
33557 @cindex @option{--base-file} (@command{dlltool})
33558 Read the base file @var{basefile} generated by the linker. This switch
33559 is used to create a relocatable DLL.
33560
33561 @item --def @var{deffile}
33562 @cindex @option{--def} (@command{dlltool})
33563 Read the definition file.
33564
33565 @item --dllname @var{name}
33566 @cindex @option{--dllname} (@command{dlltool})
33567 Gives the name of the DLL. This switch is used to embed the name of the
33568 DLL in the static import library generated by @code{dlltool} with switch
33569 @option{--output-lib}.
33570
33571 @item -k
33572 @cindex @option{-k} (@command{dlltool})
33573 Kill @code{@@}@var{nn} from exported names
33574 (@pxref{Windows Calling Conventions}
33575 for a discussion about @code{Stdcall}-style symbols.
33576
33577 @item --help
33578 @cindex @option{--help} (@command{dlltool})
33579 Prints the @code{dlltool} switches with a concise description.
33580
33581 @item --output-exp @var{exportfile}
33582 @cindex @option{--output-exp} (@command{dlltool})
33583 Generate an export file @var{exportfile}. The export file contains the
33584 export table (list of symbols in the DLL) and is used to create the DLL.
33585
33586 @item --output-lib @var{libfile}
33587 @cindex @option{--output-lib} (@command{dlltool})
33588 Generate a static import library @var{libfile}.
33589
33590 @item -v
33591 @cindex @option{-v} (@command{dlltool})
33592 Verbose mode.
33593
33594 @item --as @var{assembler-name}
33595 @cindex @option{--as} (@command{dlltool})
33596 Use @var{assembler-name} as the assembler. The default is @code{as}.
33597 @end table
33598
33599 @node GNAT and Windows Resources
33600 @section GNAT and Windows Resources
33601 @cindex Resources, windows
33602
33603 @menu
33604 * Building Resources::
33605 * Compiling Resources::
33606 * Using Resources::
33607 @end menu
33608
33609 @noindent
33610 Resources are an easy way to add Windows specific objects to your
33611 application. The objects that can be added as resources include:
33612
33613 @itemize @bullet
33614 @item
33615 menus
33616
33617 @item
33618 accelerators
33619
33620 @item
33621 dialog boxes
33622
33623 @item
33624 string tables
33625
33626 @item
33627 bitmaps
33628
33629 @item
33630 cursors
33631
33632 @item
33633 icons
33634
33635 @item
33636 fonts
33637 @end itemize
33638
33639 @noindent
33640 This section explains how to build, compile and use resources.
33641
33642 @node Building Resources
33643 @subsection Building Resources
33644 @cindex Resources, building
33645
33646 @noindent
33647 A resource file is an ASCII file. By convention resource files have an
33648 @file{.rc} extension.
33649 The easiest way to build a resource file is to use Microsoft tools
33650 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
33651 @code{dlgedit.exe} to build dialogs.
33652 It is always possible to build an @file{.rc} file yourself by writing a
33653 resource script.
33654
33655 It is not our objective to explain how to write a resource file. A
33656 complete description of the resource script language can be found in the
33657 Microsoft documentation.
33658
33659 @node Compiling Resources
33660 @subsection Compiling Resources
33661 @findex rc
33662 @findex windres
33663 @cindex Resources, compiling
33664
33665 @noindent
33666 This section describes how to build a GNAT-compatible (COFF) object file
33667 containing the resources. This is done using the Resource Compiler
33668 @code{windres} as follows:
33669
33670 @smallexample
33671 $ windres -i myres.rc -o myres.o
33672 @end smallexample
33673
33674 @noindent
33675 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
33676 file. You can specify an alternate preprocessor (usually named
33677 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
33678 parameter. A list of all possible options may be obtained by entering
33679 the command @code{windres} @option{--help}.
33680
33681 It is also possible to use the Microsoft resource compiler @code{rc.exe}
33682 to produce a @file{.res} file (binary resource file). See the
33683 corresponding Microsoft documentation for further details. In this case
33684 you need to use @code{windres} to translate the @file{.res} file to a
33685 GNAT-compatible object file as follows:
33686
33687 @smallexample
33688 $ windres -i myres.res -o myres.o
33689 @end smallexample
33690
33691 @node Using Resources
33692 @subsection Using Resources
33693 @cindex Resources, using
33694
33695 @noindent
33696 To include the resource file in your program just add the
33697 GNAT-compatible object file for the resource(s) to the linker
33698 arguments. With @command{gnatmake} this is done by using the @option{-largs}
33699 option:
33700
33701 @smallexample
33702 $ gnatmake myprog -largs myres.o
33703 @end smallexample
33704
33705 @node Debugging a DLL
33706 @section Debugging a DLL
33707 @cindex DLL debugging
33708
33709 @menu
33710 * Program and DLL Both Built with GCC/GNAT::
33711 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
33712 @end menu
33713
33714 @noindent
33715 Debugging a DLL is similar to debugging a standard program. But
33716 we have to deal with two different executable parts: the DLL and the
33717 program that uses it. We have the following four possibilities:
33718
33719 @enumerate 1
33720 @item
33721 The program and the DLL are built with @code{GCC/GNAT}.
33722 @item
33723 The program is built with foreign tools and the DLL is built with
33724 @code{GCC/GNAT}.
33725 @item
33726 The program is built with @code{GCC/GNAT} and the DLL is built with
33727 foreign tools.
33728 @item
33729 @end enumerate
33730
33731 @noindent
33732 In this section we address only cases one and two above.
33733 There is no point in trying to debug
33734 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
33735 information in it. To do so you must use a debugger compatible with the
33736 tools suite used to build the DLL.
33737
33738 @node Program and DLL Both Built with GCC/GNAT
33739 @subsection Program and DLL Both Built with GCC/GNAT
33740
33741 @noindent
33742 This is the simplest case. Both the DLL and the program have @code{GDB}
33743 compatible debugging information. It is then possible to break anywhere in
33744 the process. Let's suppose here that the main procedure is named
33745 @code{ada_main} and that in the DLL there is an entry point named
33746 @code{ada_dll}.
33747
33748 @noindent
33749 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
33750 program must have been built with the debugging information (see GNAT -g
33751 switch). Here are the step-by-step instructions for debugging it:
33752
33753 @enumerate 1
33754 @item Launch @code{GDB} on the main program.
33755
33756 @smallexample
33757 $ gdb -nw ada_main
33758 @end smallexample
33759
33760 @item Start the program and stop at the beginning of the main procedure
33761
33762 @smallexample
33763 (gdb) start
33764 @end smallexample
33765
33766 @noindent
33767 This step is required to be able to set a breakpoint inside the DLL. As long
33768 as the program is not run, the DLL is not loaded. This has the
33769 consequence that the DLL debugging information is also not loaded, so it is not
33770 possible to set a breakpoint in the DLL.
33771
33772 @item Set a breakpoint inside the DLL
33773
33774 @smallexample
33775 (gdb) break ada_dll
33776 (gdb) cont
33777 @end smallexample
33778
33779 @end enumerate
33780
33781 @noindent
33782 At this stage a breakpoint is set inside the DLL. From there on
33783 you can use the standard approach to debug the whole program
33784 (@pxref{Running and Debugging Ada Programs}).
33785
33786 @ignore
33787 @c This used to work, probably because the DLLs were non-relocatable
33788 @c keep this section around until the problem is sorted out.
33789
33790 To break on the @code{DllMain} routine it is not possible to follow
33791 the procedure above. At the time the program stop on @code{ada_main}
33792 the @code{DllMain} routine as already been called. Either you can use
33793 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
33794
33795 @enumerate 1
33796 @item Launch @code{GDB} on the main program.
33797
33798 @smallexample
33799 $ gdb ada_main
33800 @end smallexample
33801
33802 @item Load DLL symbols
33803
33804 @smallexample
33805 (gdb) add-sym api.dll
33806 @end smallexample
33807
33808 @item Set a breakpoint inside the DLL
33809
33810 @smallexample
33811 (gdb) break ada_dll.adb:45
33812 @end smallexample
33813
33814 Note that at this point it is not possible to break using the routine symbol
33815 directly as the program is not yet running. The solution is to break
33816 on the proper line (break in @file{ada_dll.adb} line 45).
33817
33818 @item Start the program
33819
33820 @smallexample
33821 (gdb) run
33822 @end smallexample
33823
33824 @end enumerate
33825 @end ignore
33826
33827 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
33828 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
33829
33830 @menu
33831 * Debugging the DLL Directly::
33832 * Attaching to a Running Process::
33833 @end menu
33834
33835 @noindent
33836 In this case things are slightly more complex because it is not possible to
33837 start the main program and then break at the beginning to load the DLL and the
33838 associated DLL debugging information. It is not possible to break at the
33839 beginning of the program because there is no @code{GDB} debugging information,
33840 and therefore there is no direct way of getting initial control. This
33841 section addresses this issue by describing some methods that can be used
33842 to break somewhere in the DLL to debug it.
33843
33844 @noindent
33845 First suppose that the main procedure is named @code{main} (this is for
33846 example some C code built with Microsoft Visual C) and that there is a
33847 DLL named @code{test.dll} containing an Ada entry point named
33848 @code{ada_dll}.
33849
33850 @noindent
33851 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
33852 been built with debugging information (see GNAT -g option).
33853
33854 @node Debugging the DLL Directly
33855 @subsubsection Debugging the DLL Directly
33856
33857 @enumerate 1
33858 @item
33859 Find out the executable starting address
33860
33861 @smallexample
33862 $ objdump --file-header main.exe
33863 @end smallexample
33864
33865 The starting address is reported on the last line. For example:
33866
33867 @smallexample
33868 main.exe:     file format pei-i386
33869 architecture: i386, flags 0x0000010a:
33870 EXEC_P, HAS_DEBUG, D_PAGED
33871 start address 0x00401010
33872 @end smallexample
33873
33874 @item
33875 Launch the debugger on the executable.
33876
33877 @smallexample
33878 $ gdb main.exe
33879 @end smallexample
33880
33881 @item
33882 Set a breakpoint at the starting address, and launch the program.
33883
33884 @smallexample
33885 $ (gdb) break *0x00401010
33886 $ (gdb) run
33887 @end smallexample
33888
33889 The program will stop at the given address.
33890
33891 @item
33892 Set a breakpoint on a DLL subroutine.
33893
33894 @smallexample
33895 (gdb) break ada_dll.adb:45
33896 @end smallexample
33897
33898 Or if you want to break using a symbol on the DLL, you need first to
33899 select the Ada language (language used by the DLL).
33900
33901 @smallexample
33902 (gdb) set language ada
33903 (gdb) break ada_dll
33904 @end smallexample
33905
33906 @item
33907 Continue the program.
33908
33909 @smallexample
33910 (gdb) cont
33911 @end smallexample
33912
33913 @noindent
33914 This will run the program until it reaches the breakpoint that has been
33915 set. From that point you can use the standard way to debug a program
33916 as described in (@pxref{Running and Debugging Ada Programs}).
33917
33918 @end enumerate
33919
33920 @noindent
33921 It is also possible to debug the DLL by attaching to a running process.
33922
33923 @node Attaching to a Running Process
33924 @subsubsection Attaching to a Running Process
33925 @cindex DLL debugging, attach to process
33926
33927 @noindent
33928 With @code{GDB} it is always possible to debug a running process by
33929 attaching to it. It is possible to debug a DLL this way. The limitation
33930 of this approach is that the DLL must run long enough to perform the
33931 attach operation. It may be useful for instance to insert a time wasting
33932 loop in the code of the DLL to meet this criterion.
33933
33934 @enumerate 1
33935
33936 @item Launch the main program @file{main.exe}.
33937
33938 @smallexample
33939 $ main
33940 @end smallexample
33941
33942 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
33943 that the process PID for @file{main.exe} is 208.
33944
33945 @item Launch gdb.
33946
33947 @smallexample
33948 $ gdb
33949 @end smallexample
33950
33951 @item Attach to the running process to be debugged.
33952
33953 @smallexample
33954 (gdb) attach 208
33955 @end smallexample
33956
33957 @item Load the process debugging information.
33958
33959 @smallexample
33960 (gdb) symbol-file main.exe
33961 @end smallexample
33962
33963 @item Break somewhere in the DLL.
33964
33965 @smallexample
33966 (gdb) break ada_dll
33967 @end smallexample
33968
33969 @item Continue process execution.
33970
33971 @smallexample
33972 (gdb) cont
33973 @end smallexample
33974
33975 @end enumerate
33976
33977 @noindent
33978 This last step will resume the process execution, and stop at
33979 the breakpoint we have set. From there you can use the standard
33980 approach to debug a program as described in
33981 (@pxref{Running and Debugging Ada Programs}).
33982
33983 @node Setting Stack Size from gnatlink
33984 @section Setting Stack Size from @command{gnatlink}
33985
33986 @noindent
33987 It is possible to specify the program stack size at link time. On modern
33988 versions of Windows, starting with XP, this is mostly useful to set the size of
33989 the main stack (environment task). The other task stacks are set with pragma
33990 Storage_Size or with the @command{gnatbind -d} command.
33991
33992 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
33993 reserve size of individual tasks, the link-time stack size applies to all
33994 tasks, and pragma Storage_Size has no effect.
33995 In particular, Stack Overflow checks are made against this
33996 link-time specified size.
33997
33998 This setting can be done with
33999 @command{gnatlink} using either:
34000
34001 @itemize @bullet
34002
34003 @item using @option{-Xlinker} linker option
34004
34005 @smallexample
34006 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
34007 @end smallexample
34008
34009 This sets the stack reserve size to 0x10000 bytes and the stack commit
34010 size to 0x1000 bytes.
34011
34012 @item using @option{-Wl} linker option
34013
34014 @smallexample
34015 $ gnatlink hello -Wl,--stack=0x1000000
34016 @end smallexample
34017
34018 This sets the stack reserve size to 0x1000000 bytes. Note that with
34019 @option{-Wl} option it is not possible to set the stack commit size
34020 because the coma is a separator for this option.
34021
34022 @end itemize
34023
34024 @node Setting Heap Size from gnatlink
34025 @section Setting Heap Size from @command{gnatlink}
34026
34027 @noindent
34028 Under Windows systems, it is possible to specify the program heap size from
34029 @command{gnatlink} using either:
34030
34031 @itemize @bullet
34032
34033 @item using @option{-Xlinker} linker option
34034
34035 @smallexample
34036 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
34037 @end smallexample
34038
34039 This sets the heap reserve size to 0x10000 bytes and the heap commit
34040 size to 0x1000 bytes.
34041
34042 @item using @option{-Wl} linker option
34043
34044 @smallexample
34045 $ gnatlink hello -Wl,--heap=0x1000000
34046 @end smallexample
34047
34048 This sets the heap reserve size to 0x1000000 bytes. Note that with
34049 @option{-Wl} option it is not possible to set the heap commit size
34050 because the coma is a separator for this option.
34051
34052 @end itemize
34053
34054 @end ifset
34055
34056 @c **********************************
34057 @c * GNU Free Documentation License *
34058 @c **********************************
34059 @include fdl.texi
34060 @c GNU Free Documentation License
34061
34062 @node Index,,GNU Free Documentation License, Top
34063 @unnumbered Index
34064
34065 @printindex cp
34066
34067 @contents
34068 @c Put table of contents at end, otherwise it precedes the "title page" in
34069 @c the .txt version
34070 @c Edit the pdf file to move the contents to the beginning, after the title
34071 @c page
34072
34073 @bye